Skip to main content

reth_node_core/args/
network.rs

1//! clap [`Args`] for network related arguments.
2
3use alloy_eips::BlockNumHash;
4use alloy_primitives::B256;
5use std::{
6    net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6},
7    num::NonZeroUsize,
8    ops::Not,
9    path::PathBuf,
10    sync::OnceLock,
11};
12
13use crate::version::version_metadata;
14use clap::{
15    builder::{OsStr, Resettable},
16    Args,
17};
18use reth_chainspec::EthChainSpec;
19use reth_cli_util::{get_secret_key, load_secret_key::SecretKeyError};
20use reth_config::Config;
21use reth_discv4::{NodeRecord, DEFAULT_DISCOVERY_ADDR, DEFAULT_DISCOVERY_PORT};
22use reth_discv5::{
23    discv5::ListenConfig, DEFAULT_COUNT_BOOTSTRAP_LOOKUPS, DEFAULT_DISCOVERY_V5_PORT,
24    DEFAULT_SECONDS_BOOTSTRAP_LOOKUP_INTERVAL, DEFAULT_SECONDS_LOOKUP_INTERVAL,
25};
26use reth_net_banlist::IpFilter;
27use reth_net_nat::{NatResolver, DEFAULT_NET_IF_NAME};
28use reth_network::{
29    transactions::{
30        config::{TransactionIngressPolicy, TransactionPropagationKind},
31        constants::{
32            tx_fetcher::{
33                DEFAULT_MAX_CAPACITY_CACHE_PENDING_FETCH, DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS,
34                DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS_PER_PEER,
35            },
36            tx_manager::{
37                DEFAULT_MAX_BYTE_SIZE_PENDING_POOL_IMPORTS, DEFAULT_MAX_COUNT_PENDING_POOL_IMPORTS,
38                DEFAULT_MAX_COUNT_TRANSACTIONS_SEEN_BY_PEER,
39                DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES, MIN_BLOB_FETCH_PROBABILITY,
40            },
41        },
42        TransactionFetcherConfig, TransactionPropagationMode, TransactionsManagerConfig,
43        DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESP_ON_PACK_GET_POOLED_TRANSACTIONS_REQ,
44        SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE,
45    },
46    HelloMessageWithProtocols, NetworkConfigBuilder, NetworkPrimitives,
47};
48use reth_network_peers::{mainnet_nodes, TrustedPeer};
49use reth_tasks::Runtime;
50use secp256k1::SecretKey;
51use std::str::FromStr;
52use tracing::error;
53
54/// Global static network defaults
55static NETWORK_DEFAULTS: OnceLock<DefaultNetworkArgs> = OnceLock::new();
56
57/// Default values for network CLI arguments that can be customized.
58///
59/// Global defaults can be set via [`DefaultNetworkArgs::try_init`].
60#[derive(Debug, Clone)]
61pub struct DefaultNetworkArgs {
62    /// Default DNS retries.
63    pub dns_retries: usize,
64    /// Default NAT resolver.
65    pub nat: NatResolver,
66    /// Default network listening address.
67    pub addr: IpAddr,
68    /// Default network listening port.
69    pub port: u16,
70    /// Default max concurrent `GetPooledTransactions` requests.
71    pub max_concurrent_tx_requests: u32,
72    /// Default max concurrent `GetPooledTransactions` requests per peer.
73    pub max_concurrent_tx_requests_per_peer: u8,
74    /// Default max number of seen transactions to remember per peer.
75    pub max_seen_tx_history: u32,
76    /// Default max number of transactions to import concurrently.
77    pub max_pending_pool_imports: usize,
78    /// Default max accumulated byte size of transactions to pack in one response.
79    pub soft_limit_byte_size_pooled_transactions_response: usize,
80    /// Default max accumulated byte size of transactions to request in one request.
81    pub soft_limit_byte_size_pooled_transactions_response_on_pack_request: usize,
82    /// Default max capacity of cache of hashes for transactions pending fetch.
83    pub max_capacity_cache_txns_pending_fetch: u32,
84    /// Default memory limit (in bytes) for the network manager → transactions manager channel.
85    pub tx_channel_memory_limit_bytes: usize,
86    /// Default probability, in percent, of fetching an eth/72 blob transaction in full.
87    pub blob_fetch_probability: u8,
88    /// Default transaction propagation policy.
89    pub tx_propagation_policy: TransactionPropagationKind,
90    /// Default transaction ingress policy.
91    pub tx_ingress_policy: TransactionIngressPolicy,
92    /// Default transaction propagation mode.
93    pub propagation_mode: TransactionPropagationMode,
94    /// Default enforce ENR fork ID setting.
95    pub enforce_enr_fork_id: bool,
96}
97
98impl DefaultNetworkArgs {
99    /// Initialize the global network defaults with this configuration.
100    pub fn try_init(self) -> Result<(), Self> {
101        NETWORK_DEFAULTS.set(self)
102    }
103
104    /// Get a reference to the global network defaults.
105    pub fn get_global() -> &'static Self {
106        NETWORK_DEFAULTS.get_or_init(Self::default)
107    }
108
109    /// Set the default DNS retries.
110    pub const fn with_dns_retries(mut self, v: usize) -> Self {
111        self.dns_retries = v;
112        self
113    }
114
115    /// Set the default NAT resolver.
116    pub fn with_nat(mut self, v: NatResolver) -> Self {
117        self.nat = v;
118        self
119    }
120
121    /// Set the default network listening address.
122    pub const fn with_addr(mut self, v: IpAddr) -> Self {
123        self.addr = v;
124        self
125    }
126
127    /// Set the default network listening port.
128    pub const fn with_port(mut self, v: u16) -> Self {
129        self.port = v;
130        self
131    }
132
133    /// Set the default max concurrent `GetPooledTransactions` requests.
134    pub const fn with_max_concurrent_tx_requests(mut self, v: u32) -> Self {
135        self.max_concurrent_tx_requests = v;
136        self
137    }
138
139    /// Set the default max concurrent `GetPooledTransactions` requests per peer.
140    pub const fn with_max_concurrent_tx_requests_per_peer(mut self, v: u8) -> Self {
141        self.max_concurrent_tx_requests_per_peer = v;
142        self
143    }
144
145    /// Set the default max number of seen transactions to remember per peer.
146    pub const fn with_max_seen_tx_history(mut self, v: u32) -> Self {
147        self.max_seen_tx_history = v;
148        self
149    }
150
151    /// Set the default max number of transactions to import concurrently.
152    pub const fn with_max_pending_pool_imports(mut self, v: usize) -> Self {
153        self.max_pending_pool_imports = v;
154        self
155    }
156
157    /// Set the default max accumulated byte size of transactions to pack in one response.
158    pub const fn with_soft_limit_byte_size_pooled_transactions_response(
159        mut self,
160        v: usize,
161    ) -> Self {
162        self.soft_limit_byte_size_pooled_transactions_response = v;
163        self
164    }
165
166    /// Set the default max accumulated byte size of transactions to request in one request.
167    pub const fn with_soft_limit_byte_size_pooled_transactions_response_on_pack_request(
168        mut self,
169        v: usize,
170    ) -> Self {
171        self.soft_limit_byte_size_pooled_transactions_response_on_pack_request = v;
172        self
173    }
174
175    /// Set the default max capacity of cache of hashes for transactions pending fetch.
176    pub const fn with_max_capacity_cache_txns_pending_fetch(mut self, v: u32) -> Self {
177        self.max_capacity_cache_txns_pending_fetch = v;
178        self
179    }
180
181    /// Set the default memory limit (in bytes) for the network manager → transactions
182    /// manager channel.
183    pub const fn with_tx_channel_memory_limit_bytes(mut self, v: usize) -> Self {
184        self.tx_channel_memory_limit_bytes = v;
185        self
186    }
187
188    /// Set the default probability, in percent, of fetching an eth/72 blob transaction in full.
189    pub const fn with_blob_fetch_probability(mut self, v: u8) -> Self {
190        self.blob_fetch_probability = v;
191        self
192    }
193
194    /// Set the default transaction propagation policy.
195    pub const fn with_tx_propagation_policy(mut self, v: TransactionPropagationKind) -> Self {
196        self.tx_propagation_policy = v;
197        self
198    }
199
200    /// Set the default transaction ingress policy.
201    pub const fn with_tx_ingress_policy(mut self, v: TransactionIngressPolicy) -> Self {
202        self.tx_ingress_policy = v;
203        self
204    }
205
206    /// Set the default transaction propagation mode.
207    pub const fn with_propagation_mode(mut self, v: TransactionPropagationMode) -> Self {
208        self.propagation_mode = v;
209        self
210    }
211
212    /// Set the default enforce ENR fork ID setting.
213    pub const fn with_enforce_enr_fork_id(mut self, v: bool) -> Self {
214        self.enforce_enr_fork_id = v;
215        self
216    }
217}
218
219impl Default for DefaultNetworkArgs {
220    fn default() -> Self {
221        Self {
222            dns_retries: 0,
223            nat: NatResolver::Any,
224            addr: DEFAULT_DISCOVERY_ADDR,
225            port: DEFAULT_DISCOVERY_PORT,
226            max_concurrent_tx_requests: DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS,
227            max_concurrent_tx_requests_per_peer: DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS_PER_PEER,
228            max_seen_tx_history: DEFAULT_MAX_COUNT_TRANSACTIONS_SEEN_BY_PEER,
229            max_pending_pool_imports: DEFAULT_MAX_COUNT_PENDING_POOL_IMPORTS,
230            soft_limit_byte_size_pooled_transactions_response:
231                SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE,
232            soft_limit_byte_size_pooled_transactions_response_on_pack_request:
233                DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESP_ON_PACK_GET_POOLED_TRANSACTIONS_REQ,
234            max_capacity_cache_txns_pending_fetch: DEFAULT_MAX_CAPACITY_CACHE_PENDING_FETCH,
235            tx_channel_memory_limit_bytes: DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,
236            blob_fetch_probability: MIN_BLOB_FETCH_PROBABILITY,
237            tx_propagation_policy: TransactionPropagationKind::default(),
238            tx_ingress_policy: TransactionIngressPolicy::default(),
239            propagation_mode: TransactionPropagationMode::Sqrt,
240            enforce_enr_fork_id: false,
241        }
242    }
243}
244
245/// Parameters for configuring the network more granularity via CLI
246#[derive(Debug, Clone, Args, PartialEq, Eq)]
247#[command(next_help_heading = "Networking")]
248pub struct NetworkArgs {
249    /// Arguments to setup discovery service.
250    #[command(flatten)]
251    pub discovery: DiscoveryArgs,
252
253    /// Advertise and serve experimental snap/2. `reth node` also bootstraps a fresh database with
254    /// it, and uses the staged pipeline while the chain head predates block access lists.
255    #[arg(long = "snap.v2")]
256    pub snap_v2: bool,
257
258    #[expect(clippy::doc_markdown)]
259    /// Comma separated enode URLs or ENRs of trusted peers for P2P connections.
260    ///
261    /// --trusted-peers enode://abcd@192.168.0.1:30303
262    #[arg(long, value_delimiter = ',')]
263    pub trusted_peers: Vec<TrustedPeer>,
264
265    /// Connect to or accept from trusted peers only
266    #[arg(long)]
267    pub trusted_only: bool,
268
269    /// Comma separated enode URLs or ENRs for P2P discovery bootstrap.
270    ///
271    /// Will fall back to a network-specific default if not specified.
272    #[arg(long, value_delimiter = ',')]
273    pub bootnodes: Option<Vec<TrustedPeer>>,
274
275    /// Amount of DNS resolution requests retries to perform when peering.
276    #[arg(long, default_value_t = DefaultNetworkArgs::get_global().dns_retries)]
277    pub dns_retries: usize,
278
279    /// The path to the known peers file. Connected peers are dumped to this file on nodes
280    /// shutdown, and read on startup. Cannot be used with `--no-persist-peers`.
281    #[arg(long, value_name = "FILE", verbatim_doc_comment, conflicts_with = "no_persist_peers")]
282    pub peers_file: Option<PathBuf>,
283
284    /// Custom node identity
285    #[arg(long, value_name = "IDENTITY", default_value = version_metadata().p2p_client_version.as_ref())]
286    pub identity: String,
287
288    /// Secret key to use for this node.
289    ///
290    /// This will also deterministically set the peer ID. If not specified, it will be set in the
291    /// data dir for the chain being used.
292    #[arg(long, value_name = "PATH", conflicts_with = "p2p_secret_key_hex")]
293    pub p2p_secret_key: Option<PathBuf>,
294
295    /// Hex encoded secret key to use for this node.
296    ///
297    /// This will also deterministically set the peer ID. Cannot be used together with
298    /// `--p2p-secret-key`.
299    #[arg(long, value_name = "HEX", conflicts_with = "p2p_secret_key")]
300    pub p2p_secret_key_hex: Option<B256>,
301
302    /// Do not persist peers.
303    #[arg(long, verbatim_doc_comment)]
304    pub no_persist_peers: bool,
305
306    /// NAT resolution method (any|none|upnp|publicip|extip:\<IP\>)
307    #[arg(long, default_value_t = DefaultNetworkArgs::get_global().nat.clone())]
308    pub nat: NatResolver,
309
310    /// Network listening address
311    #[arg(long = "addr", value_name = "ADDR", default_value_t = DefaultNetworkArgs::get_global().addr)]
312    pub addr: IpAddr,
313
314    /// Network listening port
315    #[arg(long = "port", value_name = "PORT", default_value_t = DefaultNetworkArgs::get_global().port)]
316    pub port: u16,
317
318    /// Maximum number of outbound peers. default: 100
319    #[arg(long)]
320    pub max_outbound_peers: Option<usize>,
321
322    /// Maximum number of inbound peers. default: 30
323    #[arg(long)]
324    pub max_inbound_peers: Option<usize>,
325
326    /// Maximum number of total peers (inbound + outbound).
327    ///
328    /// Splits peers using approximately 2:1 inbound:outbound ratio. Cannot be used together with
329    /// `--max-outbound-peers` or `--max-inbound-peers`.
330    #[arg(
331        long,
332        value_name = "COUNT",
333        conflicts_with = "max_outbound_peers",
334        conflicts_with = "max_inbound_peers"
335    )]
336    pub max_peers: Option<usize>,
337
338    /// Max concurrent `GetPooledTransactions` requests.
339    #[arg(long = "max-tx-reqs", value_name = "COUNT", default_value_t = DefaultNetworkArgs::get_global().max_concurrent_tx_requests, verbatim_doc_comment)]
340    pub max_concurrent_tx_requests: u32,
341
342    /// Max concurrent `GetPooledTransactions` requests per peer.
343    #[arg(long = "max-tx-reqs-peer", value_name = "COUNT", default_value_t = DefaultNetworkArgs::get_global().max_concurrent_tx_requests_per_peer, verbatim_doc_comment)]
344    pub max_concurrent_tx_requests_per_peer: u8,
345
346    /// Max number of seen transactions to remember per peer.
347    ///
348    /// Default is 320 transaction hashes.
349    #[arg(long = "max-seen-tx-history", value_name = "COUNT", default_value_t = DefaultNetworkArgs::get_global().max_seen_tx_history, verbatim_doc_comment)]
350    pub max_seen_tx_history: u32,
351
352    #[arg(long = "max-pending-imports", value_name = "COUNT", default_value_t = DefaultNetworkArgs::get_global().max_pending_pool_imports, verbatim_doc_comment)]
353    /// Max number of transactions to import concurrently.
354    pub max_pending_pool_imports: usize,
355
356    /// Experimental, for usage in research. Sets the max accumulated byte size of transactions
357    /// to pack in one response.
358    /// Spec'd at 2MiB.
359    #[arg(long = "pooled-tx-response-soft-limit", value_name = "BYTES", default_value_t = DefaultNetworkArgs::get_global().soft_limit_byte_size_pooled_transactions_response, verbatim_doc_comment)]
360    pub soft_limit_byte_size_pooled_transactions_response: usize,
361
362    /// Experimental, for usage in research. Sets the max accumulated byte size of transactions to
363    /// request in one request.
364    ///
365    /// Since `RLPx` protocol version 68, the byte size of a transaction is shared as metadata in a
366    /// transaction announcement (see `RLPx` specs). This allows a node to request a specific size
367    /// response.
368    ///
369    /// By default, nodes request only 128 KiB worth of transactions, but should a peer request
370    /// more, up to 2 MiB, a node will answer with more than 128 KiB.
371    ///
372    /// Default is 128 KiB.
373    #[arg(long = "pooled-tx-pack-soft-limit", value_name = "BYTES", default_value_t = DefaultNetworkArgs::get_global().soft_limit_byte_size_pooled_transactions_response_on_pack_request, verbatim_doc_comment)]
374    pub soft_limit_byte_size_pooled_transactions_response_on_pack_request: usize,
375
376    /// Maximum number of announced transaction hashes to track, including inflight requests.
377    #[arg(long = "max-tx-pending-fetch", value_name = "COUNT", default_value_t = DefaultNetworkArgs::get_global().max_capacity_cache_txns_pending_fetch, verbatim_doc_comment)]
378    pub max_capacity_cache_txns_pending_fetch: u32,
379
380    /// Memory limit (in bytes) for the channel that buffers transaction events flowing
381    /// from the network manager to the transactions manager.
382    ///
383    /// When the budget is exhausted, new events are dropped (see metric
384    /// `total_dropped_tx_events_at_full_capacity`). Acts as a backstop against unbounded
385    /// memory growth under sustained P2P transaction flooding.
386    #[arg(long = "tx-channel-memory-limit", value_name = "BYTES", default_value_t = DefaultNetworkArgs::get_global().tx_channel_memory_limit_bytes, verbatim_doc_comment)]
387    pub tx_channel_memory_limit_bytes: usize,
388
389    /// Probability, in percent, of fetching an eth/72 blob transaction in full instead of sampling
390    /// the consensus client's custody columns, at least EIP-8070's minimum of 15.
391    ///
392    /// A sampled transaction can't be included in a locally built block, so block builders should
393    /// set this to 100.
394    #[arg(
395        long = "tx-blob-fetch-probability",
396        value_name = "PERCENT",
397        default_value_t = DefaultNetworkArgs::get_global().blob_fetch_probability,
398        value_parser = clap::value_parser!(u8).range(i64::from(MIN_BLOB_FETCH_PROBABILITY)..=100)
399    )]
400    pub blob_fetch_probability: u8,
401
402    /// Name of network interface used to communicate with peers.
403    ///
404    /// If flag is set, but no value is passed, the default interface for docker `eth0` is tried.
405    /// If `--discovery.addr` is left at its default, discv4 will also bind to the resolved
406    /// interface address.
407    #[arg(long = "net-if.experimental", conflicts_with = "addr", value_name = "IF_NAME")]
408    pub net_if: Option<String>,
409
410    /// Transaction Propagation Policy
411    ///
412    /// The policy determines which peers transactions are gossiped to.
413    #[arg(long = "tx-propagation-policy", default_value_t = DefaultNetworkArgs::get_global().tx_propagation_policy)]
414    pub tx_propagation_policy: TransactionPropagationKind,
415
416    /// Transaction ingress policy
417    ///
418    /// Determines which peers' transactions are accepted over P2P.
419    #[arg(long = "tx-ingress-policy", default_value_t = DefaultNetworkArgs::get_global().tx_ingress_policy)]
420    pub tx_ingress_policy: TransactionIngressPolicy,
421
422    /// Disable transaction pool gossip
423    ///
424    /// Disables gossiping of transactions in the mempool to peers. This can be omitted for
425    /// personal nodes, though providers should always opt to enable this flag.
426    #[arg(long = "disable-tx-gossip")]
427    pub disable_tx_gossip: bool,
428
429    /// Sets the transaction propagation mode by determining how new pending transactions are
430    /// propagated to other peers in full.
431    ///
432    /// Examples: sqrt, all, max:10
433    #[arg(
434        long = "tx-propagation-mode",
435        default_value_t = DefaultNetworkArgs::get_global().propagation_mode,
436        help = "Transaction propagation mode (sqrt, all, max:<number>)"
437    )]
438    pub propagation_mode: TransactionPropagationMode,
439
440    /// Comma separated list of required block hashes or block number=hash pairs.
441    /// Peers that don't have these blocks will be filtered out.
442    /// Format: hash or `block_number=hash` (e.g., 23115201=0x1234...)
443    #[arg(long = "required-block-hashes", value_delimiter = ',', value_parser = parse_block_num_hash)]
444    pub required_block_hashes: Vec<BlockNumHash>,
445
446    /// Optional network ID to override the chain specification's network ID for P2P connections
447    #[arg(long)]
448    pub network_id: Option<u64>,
449
450    /// Maximum allowed ETH message size in bytes. Default is 10 MiB.
451    #[arg(long = "eth-max-message-size", value_name = "BYTES")]
452    pub eth_max_message_size: Option<NonZeroUsize>,
453
454    /// Restrict network communication to the given IP networks (CIDR masks).
455    ///
456    /// Comma separated list of CIDR network specifications.
457    /// Only peers with IP addresses within these ranges will be allowed to connect.
458    ///
459    /// Example: --netrestrict "192.168.0.0/16,10.0.0.0/8"
460    #[arg(long, value_name = "NETRESTRICT", value_parser = IpFilter::from_cidr_string)]
461    pub netrestrict: Option<IpFilter>,
462
463    /// Enforce EIP-868 ENR fork ID validation for discovered peers.
464    ///
465    /// When enabled, peers discovered without a confirmed fork ID are not added to the peer set
466    /// until their fork ID is verified via EIP-868 ENR request. This filters out peers from other
467    /// networks that pollute the discovery table.
468    #[arg(long, default_value_t = DefaultNetworkArgs::get_global().enforce_enr_fork_id)]
469    pub enforce_enr_fork_id: bool,
470}
471
472impl NetworkArgs {
473    /// Returns the IP address used for the `RLPx` TCP listener.
474    ///
475    /// If `--net-if.experimental` is set, this resolves the interface name to a concrete local IP
476    /// address. That concrete address is also passed to discv5 as the default address to advertise
477    /// in the local ENR.
478    ///
479    /// If no interface is configured, this returns the configured `--addr` value.
480    pub fn resolved_addr(&self) -> IpAddr {
481        if let Some(ref if_name) = self.net_if {
482            let if_name = if if_name.is_empty() { DEFAULT_NET_IF_NAME } else { if_name };
483            return match reth_net_nat::net_if::resolve_net_if_ip(if_name) {
484                Ok(addr) => addr,
485                Err(err) => {
486                    error!(target: "reth::cli",
487                        if_name,
488                        %err,
489                        "Failed to read network interface IP"
490                    );
491
492                    DEFAULT_DISCOVERY_ADDR
493                }
494            };
495        }
496
497        self.addr
498    }
499
500    /// Returns the IP address used for the discovery v4 UDP bind socket.
501    ///
502    /// By default this is `--discovery.addr`. When `--net-if.experimental` is set and
503    /// `--discovery.addr` is still the wildcard default, discovery v4 follows the resolved `RLPx`
504    /// listener address. That keeps discv4 and discv5 on the same concrete UDP address when they
505    /// share a port; otherwise discv4 would bind wildcard while discv5 binds the resolved
506    /// interface address, which prevents socket sharing.
507    fn resolved_discovery_addr(&self, listener_addr: IpAddr) -> IpAddr {
508        if self.net_if.is_some() && self.discovery.addr == DEFAULT_DISCOVERY_ADDR {
509            return listener_addr;
510        }
511
512        self.discovery.addr
513    }
514
515    /// Returns the resolved bootnodes if any are provided.
516    pub fn resolved_bootnodes(&self) -> Option<Vec<NodeRecord>> {
517        self.bootnodes.as_deref().map(|bootnodes| {
518            bootnodes.iter().filter_map(|node| node.resolve_blocking().ok()).collect()
519        })
520    }
521
522    /// Returns the max inbound peers (2:1 ratio).
523    pub fn resolved_max_inbound_peers(&self) -> Option<usize> {
524        if let Some(max_peers) = self.max_peers {
525            if max_peers == 0 {
526                Some(0)
527            } else {
528                let outbound = (max_peers / 3).max(1);
529                Some(max_peers.saturating_sub(outbound))
530            }
531        } else {
532            self.max_inbound_peers
533        }
534    }
535
536    /// Returns the max outbound peers (1:2 ratio).
537    pub fn resolved_max_outbound_peers(&self) -> Option<usize> {
538        if let Some(max_peers) = self.max_peers {
539            if max_peers == 0 {
540                Some(0)
541            } else {
542                Some((max_peers / 3).max(1))
543            }
544        } else {
545            self.max_outbound_peers
546        }
547    }
548
549    /// Configures and returns a `TransactionsManagerConfig` based on the current settings.
550    pub const fn transactions_manager_config(&self) -> TransactionsManagerConfig {
551        TransactionsManagerConfig {
552            transaction_fetcher_config: TransactionFetcherConfig::new(
553                self.max_concurrent_tx_requests,
554                self.max_concurrent_tx_requests_per_peer,
555                self.soft_limit_byte_size_pooled_transactions_response,
556                self.soft_limit_byte_size_pooled_transactions_response_on_pack_request,
557                self.max_capacity_cache_txns_pending_fetch,
558            ),
559            max_transactions_seen_by_peer_history: self.max_seen_tx_history,
560            max_pending_pool_imports: self.max_pending_pool_imports,
561            max_pending_pool_imports_bytes: DEFAULT_MAX_BYTE_SIZE_PENDING_POOL_IMPORTS,
562            propagation_mode: self.propagation_mode,
563            ingress_policy: self.tx_ingress_policy,
564            tx_channel_memory_limit_bytes: self.tx_channel_memory_limit_bytes,
565            blob_fetch_probability: self.blob_fetch_probability,
566        }
567    }
568
569    /// Build a [`NetworkConfigBuilder`] from a [`Config`] and a [`EthChainSpec`], in addition to
570    /// the values in this option struct.
571    ///
572    /// The `default_peers_file` will be used as the default location to store the persistent peers
573    /// file if `no_persist_peers` is false, and there is no provided `peers_file`.
574    ///
575    /// Configured Bootnodes are prioritized, if unset, the chain spec bootnodes are used
576    /// Priority order for bootnodes configuration:
577    /// 1. --bootnodes flag
578    /// 2. `bootnodes` in the config file
579    /// 3. Network preset flags (e.g. --holesky)
580    /// 4. default to mainnet nodes
581    pub fn network_config<N: NetworkPrimitives>(
582        &self,
583        config: &Config,
584        chain_spec: impl EthChainSpec,
585        secret_key: SecretKey,
586        default_peers_file: PathBuf,
587        executor: Runtime,
588    ) -> NetworkConfigBuilder<N> {
589        // `listener_addr` is the concrete RLPx TCP bind address. With `--net-if.experimental`,
590        // this is the resolved interface IP and is also used as discv5's default address.
591        let listener_addr = self.resolved_addr();
592        // Discovery v4 has its own CLI bind address. If left at the wildcard default while
593        // `--net-if.experimental` is active, make it follow the listener address so discv4 and
594        // discv5 can share the same UDP socket.
595        let discovery_addr = self.resolved_discovery_addr(listener_addr);
596        let chain_bootnodes = self
597            .resolved_bootnodes()
598            .or_else(|| {
599                (!config.bootnodes.is_empty()).then(|| {
600                    config
601                        .bootnodes
602                        .iter()
603                        .filter_map(|node| node.resolve_blocking().ok())
604                        .collect()
605                })
606            })
607            .unwrap_or_else(|| chain_spec.bootnodes().unwrap_or_else(mainnet_nodes));
608        let peers_file = self.peers_file.clone().unwrap_or(default_peers_file);
609
610        // Configure peer connections
611        let ip_filter = self.ip_filter();
612        let peers_config = config
613            .peers_config_with_basic_nodes_from_file(
614                self.persistent_peers_file(peers_file).as_deref(),
615            )
616            .with_max_inbound_opt(self.resolved_max_inbound_peers())
617            .with_max_outbound_opt(self.resolved_max_outbound_peers())
618            .with_ip_filter(ip_filter)
619            // The flag can only enable enforcement, so the reth.toml value applies when it is not
620            // passed.
621            .with_enforce_enr_fork_id(self.enforce_enr_fork_id || config.peers.enforce_enr_fork_id);
622
623        // Configure basic network stack
624        NetworkConfigBuilder::<N>::new(secret_key, executor)
625            .with_snap(self.snap_v2)
626            .external_ip_resolver(self.nat.clone())
627            .sessions_config(
628                config.sessions.clone().with_upscaled_event_buffer(peers_config.max_peers()),
629            )
630            .peer_config(peers_config)
631            .boot_nodes(chain_bootnodes.clone())
632            .transactions_manager_config(self.transactions_manager_config())
633            // Configure node identity
634            .apply(|builder| {
635                let peer_id = builder.get_peer_id();
636                builder.hello_message(
637                    HelloMessageWithProtocols::builder(peer_id)
638                        .client_version(&self.identity)
639                        .build(),
640                )
641            })
642            // apply discovery settings
643            .apply(|builder| {
644                let rlpx_socket = (listener_addr, self.port).into();
645                self.discovery.apply_to_builder(builder, rlpx_socket, chain_bootnodes)
646            })
647            .listener_addr(SocketAddr::new(listener_addr, self.port))
648            .discovery_addr(SocketAddr::new(discovery_addr, self.discovery.port))
649            .disable_tx_gossip(self.disable_tx_gossip)
650            .required_block_hashes(self.required_block_hashes.clone())
651            .eth_max_message_size_opt(self.eth_max_message_size.map(NonZeroUsize::get))
652            .network_id(self.network_id)
653    }
654
655    /// If `no_persist_peers` is false then this returns the path to the persistent peers file path.
656    pub fn persistent_peers_file(&self, peers_file: PathBuf) -> Option<PathBuf> {
657        self.no_persist_peers.not().then_some(peers_file)
658    }
659
660    /// Configures the [`DiscoveryArgs`].
661    pub const fn with_discovery(mut self, discovery: DiscoveryArgs) -> Self {
662        self.discovery = discovery;
663        self
664    }
665
666    /// Sets the p2p port to zero, to allow the OS to assign a random unused port when
667    /// the network components bind to a socket.
668    pub const fn with_unused_p2p_port(mut self) -> Self {
669        self.port = 0;
670        self
671    }
672
673    /// Sets the p2p and discovery ports to zero, allowing the OD to assign a random unused port
674    /// when network components bind to sockets.
675    pub const fn with_unused_ports(mut self) -> Self {
676        self = self.with_unused_p2p_port();
677        self.discovery = self.discovery.with_unused_discovery_port();
678        self
679    }
680
681    /// Configures the [`NatResolver`]
682    pub fn with_nat_resolver(mut self, nat: NatResolver) -> Self {
683        self.nat = nat;
684        self
685    }
686
687    /// Change networking port numbers based on the instance number, if provided.
688    /// Ports are updated to `previous_value + instance - 1`
689    ///
690    /// # Panics
691    /// Warning: if `instance` is zero in debug mode, this will panic.
692    pub fn adjust_instance_ports(&mut self, instance: Option<u16>) {
693        if let Some(instance) = instance {
694            debug_assert_ne!(instance, 0, "instance must be non-zero");
695            self.port += instance - 1;
696            self.discovery.adjust_instance_ports(instance);
697        }
698    }
699
700    /// Resolve all trusted peers at once
701    pub async fn resolve_trusted_peers(&self) -> Result<Vec<NodeRecord>, std::io::Error> {
702        futures::future::try_join_all(
703            self.trusted_peers.iter().map(|peer| async move { peer.resolve().await }),
704        )
705        .await
706    }
707
708    /// Load the p2p secret key from the provided options.
709    ///
710    /// If `p2p_secret_key_hex` is provided, it will be used directly.
711    /// If `p2p_secret_key` is provided, it will be loaded from the file.
712    /// If neither is provided, the `default_secret_key_path` will be used.
713    pub fn secret_key(
714        &self,
715        default_secret_key_path: PathBuf,
716    ) -> Result<SecretKey, SecretKeyError> {
717        if let Some(b256) = &self.p2p_secret_key_hex {
718            // Use the B256 value directly (already validated as 32 bytes)
719            SecretKey::from_secret_bytes(b256.0).map_err(SecretKeyError::SecretKeyDecodeError)
720        } else {
721            // Load from file (either provided path or default)
722            let secret_key_path = self.p2p_secret_key.clone().unwrap_or(default_secret_key_path);
723            get_secret_key(&secret_key_path)
724        }
725    }
726
727    /// Returns the IP filter from the netrestrict argument, allowing all IPs if it is not set.
728    pub fn ip_filter(&self) -> IpFilter {
729        self.netrestrict.clone().unwrap_or_default()
730    }
731}
732
733impl Default for NetworkArgs {
734    fn default() -> Self {
735        let DefaultNetworkArgs {
736            dns_retries,
737            nat,
738            addr,
739            port,
740            max_concurrent_tx_requests,
741            max_concurrent_tx_requests_per_peer,
742            max_seen_tx_history,
743            max_pending_pool_imports,
744            soft_limit_byte_size_pooled_transactions_response,
745            soft_limit_byte_size_pooled_transactions_response_on_pack_request,
746            max_capacity_cache_txns_pending_fetch,
747            tx_channel_memory_limit_bytes,
748            blob_fetch_probability,
749            tx_propagation_policy,
750            tx_ingress_policy,
751            propagation_mode,
752            enforce_enr_fork_id,
753        } = DefaultNetworkArgs::get_global().clone();
754        Self {
755            discovery: DiscoveryArgs::default(),
756            snap_v2: false,
757            trusted_peers: vec![],
758            trusted_only: false,
759            bootnodes: None,
760            dns_retries,
761            peers_file: None,
762            identity: version_metadata().p2p_client_version.to_string(),
763            p2p_secret_key: None,
764            p2p_secret_key_hex: None,
765            no_persist_peers: false,
766            nat,
767            addr,
768            port,
769            max_outbound_peers: None,
770            max_inbound_peers: None,
771            max_peers: None,
772            max_concurrent_tx_requests,
773            max_concurrent_tx_requests_per_peer,
774            soft_limit_byte_size_pooled_transactions_response,
775            soft_limit_byte_size_pooled_transactions_response_on_pack_request,
776            max_pending_pool_imports,
777            max_seen_tx_history,
778            max_capacity_cache_txns_pending_fetch,
779            tx_channel_memory_limit_bytes,
780            blob_fetch_probability,
781            net_if: None,
782            tx_propagation_policy,
783            tx_ingress_policy,
784            disable_tx_gossip: false,
785            propagation_mode,
786            required_block_hashes: vec![],
787            network_id: None,
788            eth_max_message_size: None,
789            netrestrict: None,
790            enforce_enr_fork_id,
791        }
792    }
793}
794
795/// Global static discovery defaults
796static DISCOVERY_DEFAULTS: OnceLock<DefaultDiscoveryArgs> = OnceLock::new();
797
798/// Default values for discovery CLI arguments that can be customized.
799#[derive(Debug, Clone, Copy)]
800pub struct DefaultDiscoveryArgs {
801    /// Default for `--disable-discovery`.
802    pub disable_discovery: bool,
803    /// Default for `--disable-dns-discovery`.
804    pub disable_dns_discovery: bool,
805    /// Default for `--disable-discv4-discovery`.
806    pub disable_discv4_discovery: bool,
807    /// Default for `--disable-discv5-discovery`.
808    pub disable_discv5_discovery: bool,
809    /// Default for `--disable-nat`.
810    pub disable_nat: bool,
811    /// Default UDP address for devp2p discovery v4.
812    pub addr: IpAddr,
813    /// Default UDP port for devp2p discovery v4.
814    pub port: u16,
815    /// Default UDP IPv4 address for devp2p discovery v5.
816    pub discv5_addr: Option<Ipv4Addr>,
817    /// Default UDP IPv6 address for devp2p discovery v5.
818    pub discv5_addr_ipv6: Option<Ipv6Addr>,
819    /// Default UDP IPv4 port for devp2p discovery v5.
820    pub discv5_port: Option<u16>,
821    /// Default UDP IPv6 port for devp2p discovery v5.
822    pub discv5_port_ipv6: Option<u16>,
823    /// Default discv5 periodic lookup interval (seconds).
824    pub discv5_lookup_interval: u64,
825    /// Default discv5 bootstrap lookup interval (seconds).
826    pub discv5_bootstrap_lookup_interval: u64,
827    /// Default discv5 bootstrap lookup countdown.
828    pub discv5_bootstrap_lookup_countdown: u64,
829}
830
831impl DefaultDiscoveryArgs {
832    /// Initialize the global discovery defaults with this configuration.
833    pub fn try_init(self) -> Result<(), Self> {
834        DISCOVERY_DEFAULTS.set(self)
835    }
836
837    /// Get a reference to the global discovery defaults.
838    pub fn get_global() -> &'static Self {
839        DISCOVERY_DEFAULTS.get_or_init(Self::default)
840    }
841
842    /// Set the default for `--disable-discovery`.
843    pub const fn with_disable_discovery(mut self, disable: bool) -> Self {
844        self.disable_discovery = disable;
845        self
846    }
847
848    /// Set the default for `--disable-dns-discovery`.
849    pub const fn with_disable_dns_discovery(mut self, disable: bool) -> Self {
850        self.disable_dns_discovery = disable;
851        self
852    }
853
854    /// Set the default for `--disable-discv4-discovery`.
855    pub const fn with_disable_discv4_discovery(mut self, disable: bool) -> Self {
856        self.disable_discv4_discovery = disable;
857        self
858    }
859
860    /// Set the default for `--disable-discv5-discovery`.
861    pub const fn with_disable_discv5_discovery(mut self, disable: bool) -> Self {
862        self.disable_discv5_discovery = disable;
863        self
864    }
865
866    /// Set the default for `--disable-nat`.
867    pub const fn with_disable_nat(mut self, disable: bool) -> Self {
868        self.disable_nat = disable;
869        self
870    }
871
872    /// Set the default discovery v4 address.
873    pub const fn with_addr(mut self, addr: IpAddr) -> Self {
874        self.addr = addr;
875        self
876    }
877
878    /// Set the default discovery v4 port.
879    pub const fn with_port(mut self, port: u16) -> Self {
880        self.port = port;
881        self
882    }
883
884    /// Set the default discovery v5 IPv4 address.
885    pub fn with_discv5_addr(mut self, addr: impl Into<Option<Ipv4Addr>>) -> Self {
886        self.discv5_addr = addr.into();
887        self
888    }
889
890    /// Set the default discovery v5 IPv6 address.
891    pub fn with_discv5_addr_ipv6(mut self, addr: impl Into<Option<Ipv6Addr>>) -> Self {
892        self.discv5_addr_ipv6 = addr.into();
893        self
894    }
895
896    /// Set the default discovery V5 port.
897    pub fn with_discv5_port(mut self, port: impl Into<Option<u16>>) -> Self {
898        self.discv5_port = port.into();
899        self
900    }
901
902    /// Set the default discovery v5 IPv6 port.
903    pub fn with_discv5_port_ipv6(mut self, port: impl Into<Option<u16>>) -> Self {
904        self.discv5_port_ipv6 = port.into();
905        self
906    }
907
908    /// Set the default discv5 periodic lookup interval (seconds).
909    pub const fn with_discv5_lookup_interval(mut self, interval: u64) -> Self {
910        self.discv5_lookup_interval = interval;
911        self
912    }
913
914    /// Set the default discv5 bootstrap lookup interval (seconds).
915    pub const fn with_discv5_bootstrap_lookup_interval(mut self, interval: u64) -> Self {
916        self.discv5_bootstrap_lookup_interval = interval;
917        self
918    }
919
920    /// Set the default discv5 bootstrap lookup countdown.
921    pub const fn with_discv5_bootstrap_lookup_countdown(mut self, countdown: u64) -> Self {
922        self.discv5_bootstrap_lookup_countdown = countdown;
923        self
924    }
925}
926
927impl Default for DefaultDiscoveryArgs {
928    fn default() -> Self {
929        Self {
930            disable_discovery: false,
931            disable_dns_discovery: false,
932            disable_discv4_discovery: false,
933            disable_discv5_discovery: false,
934            disable_nat: false,
935            addr: DEFAULT_DISCOVERY_ADDR,
936            port: DEFAULT_DISCOVERY_PORT,
937            discv5_addr: None,
938            discv5_addr_ipv6: None,
939            discv5_port: Some(DEFAULT_DISCOVERY_V5_PORT),
940            discv5_port_ipv6: Some(DEFAULT_DISCOVERY_V5_PORT),
941            discv5_lookup_interval: DEFAULT_SECONDS_LOOKUP_INTERVAL,
942            discv5_bootstrap_lookup_interval: DEFAULT_SECONDS_BOOTSTRAP_LOOKUP_INTERVAL,
943            discv5_bootstrap_lookup_countdown: DEFAULT_COUNT_BOOTSTRAP_LOOKUPS,
944        }
945    }
946}
947
948/// Arguments to setup discovery
949#[derive(Debug, Clone, Args, PartialEq, Eq)]
950pub struct DiscoveryArgs {
951    /// Disable the discovery service.
952    #[arg(short, long, default_value_if("dev", "true", "true"), default_value_t = DefaultDiscoveryArgs::get_global().disable_discovery)]
953    pub disable_discovery: bool,
954
955    /// Disable the DNS discovery.
956    #[arg(long, conflicts_with = "disable_discovery", default_value_t = DefaultDiscoveryArgs::get_global().disable_dns_discovery)]
957    pub disable_dns_discovery: bool,
958
959    /// Disable Discv4 discovery.
960    #[arg(long, conflicts_with = "disable_discovery", default_value_t = DefaultDiscoveryArgs::get_global().disable_discv4_discovery)]
961    pub disable_discv4_discovery: bool,
962
963    /// Enable Discv5 discovery.
964    ///
965    /// Discv5 is now enabled by default, so this flag is a no-op and will be removed in a future
966    /// release.
967    #[arg(long, conflicts_with = "disable_discovery", hide = true)]
968    pub enable_discv5_discovery: bool,
969
970    /// Disable Discv5 discovery.
971    #[arg(long, conflicts_with = "disable_discovery", default_value_t = DefaultDiscoveryArgs::get_global().disable_discv5_discovery)]
972    pub disable_discv5_discovery: bool,
973
974    /// Disable Nat discovery.
975    #[arg(long, conflicts_with = "disable_discovery", default_value_t = DefaultDiscoveryArgs::get_global().disable_nat)]
976    pub disable_nat: bool,
977
978    /// The UDP address to use for devp2p peer discovery version 4.
979    ///
980    /// If unset and `--net-if.experimental` is used, discv4 binds to the resolved interface
981    /// address.
982    #[arg(id = "discovery.addr", long = "discovery.addr", value_name = "DISCOVERY_ADDR", default_value_t = DefaultDiscoveryArgs::get_global().addr)]
983    pub addr: IpAddr,
984
985    /// The UDP port to use for devp2p peer discovery version 4.
986    #[arg(id = "discovery.port", long = "discovery.port", value_name = "DISCOVERY_PORT", default_value_t = DefaultDiscoveryArgs::get_global().port)]
987    pub port: u16,
988
989    /// The UDP IPv4 address to use for devp2p peer discovery version 5. Overwritten by `RLPx`
990    /// address, if it's also IPv4.
991    #[arg(id = "discovery.v5.addr", long = "discovery.v5.addr", value_name = "DISCOVERY_V5_ADDR", default_value = Resettable::from(DefaultDiscoveryArgs::get_global().discv5_addr.map(|a| OsStr::from(a.to_string()))))]
992    pub discv5_addr: Option<Ipv4Addr>,
993
994    /// The UDP IPv6 address to use for devp2p peer discovery version 5. Overwritten by `RLPx`
995    /// address, if it's also IPv6.
996    #[arg(id = "discovery.v5.addr.ipv6", long = "discovery.v5.addr.ipv6", value_name = "DISCOVERY_V5_ADDR_IPV6", default_value = Resettable::from(DefaultDiscoveryArgs::get_global().discv5_addr_ipv6.map(|a| OsStr::from(a.to_string()))))]
997    pub discv5_addr_ipv6: Option<Ipv6Addr>,
998
999    /// The UDP IPv4 port to use for devp2p peer discovery version 5. Not used unless `--addr` is
1000    /// IPv4, or `--discovery.v5.addr` is set.
1001    #[arg(id = "discovery.v5.port", long = "discovery.v5.port", value_name = "DISCOVERY_V5_PORT", default_value = Resettable::from(DefaultDiscoveryArgs::get_global().discv5_port.map(|p| OsStr::from(p.to_string()))))]
1002    pub discv5_port: Option<u16>,
1003
1004    /// The UDP IPv6 port to use for devp2p peer discovery version 5. Not used unless `--addr` is
1005    /// IPv6, or `--discovery.addr.ipv6` is set.
1006    ///
1007    /// If not provided, discovery V5 defaults to same port as discovery V4 (--discovery.port).
1008    #[arg(id = "discovery.v5.port.ipv6", long = "discovery.v5.port.ipv6", value_name = "DISCOVERY_V5_PORT_IPV6", default_value = Resettable::from(DefaultDiscoveryArgs::get_global().discv5_port_ipv6.map(|p| OsStr::from(p.to_string()))))]
1009    pub discv5_port_ipv6: Option<u16>,
1010
1011    /// The interval in seconds at which to carry out periodic lookup queries, for the whole
1012    /// run of the program.
1013    #[arg(id = "discovery.v5.lookup-interval", long = "discovery.v5.lookup-interval", value_name = "DISCOVERY_V5_LOOKUP_INTERVAL", default_value_t = DefaultDiscoveryArgs::get_global().discv5_lookup_interval)]
1014    pub discv5_lookup_interval: u64,
1015
1016    /// The interval in seconds at which to carry out boost lookup queries, for a fixed number of
1017    /// times, at bootstrap.
1018    #[arg(id = "discovery.v5.bootstrap.lookup-interval", long = "discovery.v5.bootstrap.lookup-interval", value_name = "DISCOVERY_V5_BOOTSTRAP_LOOKUP_INTERVAL",
1019        default_value_t = DefaultDiscoveryArgs::get_global().discv5_bootstrap_lookup_interval)]
1020    pub discv5_bootstrap_lookup_interval: u64,
1021
1022    /// The number of times to carry out boost lookup queries at bootstrap.
1023    #[arg(id = "discovery.v5.bootstrap.lookup-countdown", long = "discovery.v5.bootstrap.lookup-countdown", value_name = "DISCOVERY_V5_BOOTSTRAP_LOOKUP_COUNTDOWN",
1024        default_value_t = DefaultDiscoveryArgs::get_global().discv5_bootstrap_lookup_countdown)]
1025    pub discv5_bootstrap_lookup_countdown: u64,
1026}
1027
1028impl DiscoveryArgs {
1029    /// Apply the discovery settings to the given [`NetworkConfigBuilder`]
1030    pub fn apply_to_builder<N>(
1031        &self,
1032        mut network_config_builder: NetworkConfigBuilder<N>,
1033        rlpx_tcp_socket: SocketAddr,
1034        boot_nodes: impl IntoIterator<Item = NodeRecord>,
1035    ) -> NetworkConfigBuilder<N>
1036    where
1037        N: NetworkPrimitives,
1038    {
1039        if self.disable_discovery || self.disable_dns_discovery {
1040            network_config_builder = network_config_builder.disable_dns_discovery();
1041        }
1042
1043        if self.disable_discovery || self.disable_discv4_discovery {
1044            network_config_builder = network_config_builder.disable_discv4_discovery();
1045        }
1046
1047        if self.disable_nat {
1048            // we only check for `disable-nat` here and not for disable discovery because nat:extip can be used without discovery: <https://github.com/paradigmxyz/reth/issues/14878>
1049            network_config_builder = network_config_builder.disable_nat();
1050        }
1051
1052        if self.should_enable_discv5() {
1053            network_config_builder = network_config_builder
1054                .discovery_v5(self.discovery_v5_builder(rlpx_tcp_socket, boot_nodes));
1055        }
1056
1057        network_config_builder
1058    }
1059
1060    /// Creates a [`reth_discv5::ConfigBuilder`] filling it with the values from this struct.
1061    pub fn discovery_v5_builder(
1062        &self,
1063        rlpx_tcp_socket: SocketAddr,
1064        boot_nodes: impl IntoIterator<Item = NodeRecord>,
1065    ) -> reth_discv5::ConfigBuilder {
1066        let Self {
1067            discv5_addr,
1068            discv5_addr_ipv6,
1069            discv5_port,
1070            discv5_port_ipv6,
1071            discv5_lookup_interval,
1072            discv5_bootstrap_lookup_interval,
1073            discv5_bootstrap_lookup_countdown,
1074            port,
1075            ..
1076        } = self;
1077
1078        let has_discv5_addr_args = discv5_addr.is_some() || discv5_addr_ipv6.is_some();
1079
1080        // Use rlpx address if none given
1081        let discv5_addr_ipv4 = discv5_addr.or(match rlpx_tcp_socket {
1082            SocketAddr::V4(addr) => Some(*addr.ip()),
1083            SocketAddr::V6(_) => None,
1084        });
1085        let discv5_addr_ipv6 = discv5_addr_ipv6.or(match rlpx_tcp_socket {
1086            SocketAddr::V4(_) => None,
1087            SocketAddr::V6(addr) => Some(*addr.ip()),
1088        });
1089
1090        let mut discv5_config_builder =
1091            reth_discv5::discv5::ConfigBuilder::new(ListenConfig::from_two_sockets(
1092                discv5_addr_ipv4.map(|addr| SocketAddrV4::new(addr, discv5_port.unwrap_or(*port))),
1093                discv5_addr_ipv6
1094                    .map(|addr| SocketAddrV6::new(addr, discv5_port_ipv6.unwrap_or(*port), 0, 0)),
1095            ));
1096
1097        if has_discv5_addr_args || self.disable_nat {
1098            // disable native enr update if addresses manually set or nat disabled
1099            discv5_config_builder.disable_enr_update();
1100        }
1101        reth_discv5::Config::builder(rlpx_tcp_socket)
1102            .discv5_config(discv5_config_builder.build())
1103            .add_unsigned_boot_nodes(boot_nodes)
1104            .lookup_interval(*discv5_lookup_interval)
1105            .bootstrap_lookup_interval(*discv5_bootstrap_lookup_interval)
1106            .bootstrap_lookup_countdown(*discv5_bootstrap_lookup_countdown)
1107    }
1108
1109    /// Returns true if discv5 discovery should be configured.
1110    ///
1111    /// Discv5 is enabled by default and can be disabled with `--disable-discv5-discovery`.
1112    const fn should_enable_discv5(&self) -> bool {
1113        !(self.disable_discovery || self.disable_discv5_discovery)
1114    }
1115
1116    /// Set the discovery ports to zero, to allow the OS to assign random unused ports when
1117    /// discovery binds to the sockets.
1118    pub const fn with_unused_discovery_port(mut self) -> Self {
1119        self.port = 0;
1120        self.discv5_port = Some(0);
1121        self.discv5_port_ipv6 = Some(0);
1122        self
1123    }
1124
1125    /// Set the discovery V5 port
1126    pub fn with_discv5_port(mut self, port: impl Into<Option<u16>>) -> Self {
1127        self.discv5_port = port.into();
1128        self
1129    }
1130
1131    /// Change networking port numbers based on the instance number.
1132    /// Ports are updated to `previous_value + instance - 1`
1133    ///
1134    /// # Panics
1135    /// Warning: if `instance` is zero in debug mode, this will panic.
1136    pub fn adjust_instance_ports(&mut self, instance: u16) {
1137        debug_assert_ne!(instance, 0, "instance must be non-zero");
1138        self.port += instance - 1;
1139        self.discv5_port = self.discv5_port.map(|port| port + instance - 1);
1140        self.discv5_port_ipv6 = self.discv5_port_ipv6.map(|port| port + instance - 1);
1141    }
1142}
1143
1144impl Default for DiscoveryArgs {
1145    fn default() -> Self {
1146        let DefaultDiscoveryArgs {
1147            disable_discovery,
1148            disable_dns_discovery,
1149            disable_discv4_discovery,
1150            disable_discv5_discovery,
1151            disable_nat,
1152            addr,
1153            port,
1154            discv5_addr,
1155            discv5_addr_ipv6,
1156            discv5_port,
1157            discv5_port_ipv6,
1158            discv5_lookup_interval,
1159            discv5_bootstrap_lookup_interval,
1160            discv5_bootstrap_lookup_countdown,
1161        } = *DefaultDiscoveryArgs::get_global();
1162        Self {
1163            disable_discovery,
1164            disable_dns_discovery,
1165            disable_discv4_discovery,
1166            enable_discv5_discovery: false,
1167            disable_discv5_discovery,
1168            disable_nat,
1169            addr,
1170            port,
1171            discv5_addr,
1172            discv5_addr_ipv6,
1173            discv5_port,
1174            discv5_port_ipv6,
1175            discv5_lookup_interval,
1176            discv5_bootstrap_lookup_interval,
1177            discv5_bootstrap_lookup_countdown,
1178        }
1179    }
1180}
1181
1182/// Parse a block number=hash pair or just a hash into `BlockNumHash`
1183fn parse_block_num_hash(s: &str) -> Result<BlockNumHash, String> {
1184    if let Some((num_str, hash_str)) = s.split_once('=') {
1185        let number = num_str.parse().map_err(|_| format!("Invalid block number: {}", num_str))?;
1186        let hash = B256::from_str(hash_str).map_err(|_| format!("Invalid hash: {}", hash_str))?;
1187        Ok(BlockNumHash::new(number, hash))
1188    } else {
1189        // For backward compatibility, treat as hash-only with number 0
1190        let hash = B256::from_str(s).map_err(|_| format!("Invalid hash: {}", s))?;
1191        Ok(BlockNumHash::new(0, hash))
1192    }
1193}
1194
1195#[cfg(test)]
1196mod tests {
1197    use super::*;
1198    use clap::Parser;
1199    use reth_chainspec::MAINNET;
1200    use reth_config::Config;
1201    use reth_network::EthNetworkPrimitives;
1202    use reth_network_peers::NodeRecord;
1203    use secp256k1::SecretKey;
1204    use std::{
1205        fs,
1206        time::{SystemTime, UNIX_EPOCH},
1207    };
1208
1209    /// A helper type to parse Args more easily
1210    #[derive(Parser)]
1211    struct CommandParser<T: Args> {
1212        #[command(flatten)]
1213        args: T,
1214    }
1215
1216    #[test]
1217    fn parse_nat_args() {
1218        let args = CommandParser::<NetworkArgs>::parse_from(["reth", "--nat", "none"]).args;
1219        assert_eq!(args.nat, NatResolver::None);
1220
1221        let args =
1222            CommandParser::<NetworkArgs>::parse_from(["reth", "--nat", "extip:0.0.0.0"]).args;
1223        assert_eq!(args.nat, NatResolver::ExternalIp("0.0.0.0".parse().unwrap()));
1224    }
1225
1226    #[test]
1227    fn parse_peer_args() {
1228        let args =
1229            CommandParser::<NetworkArgs>::parse_from(["reth", "--max-outbound-peers", "50"]).args;
1230        assert_eq!(args.max_outbound_peers, Some(50));
1231        assert_eq!(args.max_inbound_peers, None);
1232
1233        let args = CommandParser::<NetworkArgs>::parse_from([
1234            "reth",
1235            "--max-outbound-peers",
1236            "75",
1237            "--max-inbound-peers",
1238            "15",
1239        ])
1240        .args;
1241        assert_eq!(args.max_outbound_peers, Some(75));
1242        assert_eq!(args.max_inbound_peers, Some(15));
1243    }
1244
1245    #[test]
1246    fn parse_trusted_peer_args() {
1247        let args =
1248            CommandParser::<NetworkArgs>::parse_from([
1249            "reth",
1250            "--trusted-peers",
1251            "enode://d860a01f9722d78051619d1e2351aba3f43f943f6f00718d1b9baa4101932a1f5011f16bb2b1bb35db20d6fe28fa0bf09636d26a87d31de9ec6203eeedb1f666@18.138.108.67:30303,enode://22a8232c3abc76a16ae9d6c3b164f98775fe226f0917b0ca871128a74a8e9630b458460865bab457221f1d448dd9791d24c4e5d88786180ac185df813a68d4de@3.209.45.79:30303"
1252        ])
1253        .args;
1254
1255        assert_eq!(
1256            args.trusted_peers,
1257            vec![
1258            "enode://d860a01f9722d78051619d1e2351aba3f43f943f6f00718d1b9baa4101932a1f5011f16bb2b1bb35db20d6fe28fa0bf09636d26a87d31de9ec6203eeedb1f666@18.138.108.67:30303".parse().unwrap(),
1259            "enode://22a8232c3abc76a16ae9d6c3b164f98775fe226f0917b0ca871128a74a8e9630b458460865bab457221f1d448dd9791d24c4e5d88786180ac185df813a68d4de@3.209.45.79:30303".parse().unwrap()
1260            ]
1261        );
1262    }
1263
1264    #[test]
1265    fn parse_retry_strategy_args() {
1266        let tests = vec![0, 10];
1267
1268        for retries in tests {
1269            let retries_str = retries.to_string();
1270            let args = CommandParser::<NetworkArgs>::parse_from([
1271                "reth",
1272                "--dns-retries",
1273                retries_str.as_str(),
1274            ])
1275            .args;
1276
1277            assert_eq!(args.dns_retries, retries);
1278        }
1279    }
1280
1281    #[test]
1282    fn transactions_manager_config_uses_max_pending_imports() {
1283        let args = NetworkArgs { max_pending_pool_imports: 50_000, ..Default::default() };
1284
1285        let config = args.transactions_manager_config();
1286
1287        assert_eq!(config.max_pending_pool_imports, 50_000);
1288    }
1289
1290    #[test]
1291    fn parse_blob_fetch_probability() {
1292        let args = CommandParser::<NetworkArgs>::parse_from(["reth"]).args;
1293        assert_eq!(args.transactions_manager_config().blob_fetch_probability, 15);
1294        let args =
1295            CommandParser::<NetworkArgs>::parse_from(["reth", "--tx-blob-fetch-probability", "40"])
1296                .args;
1297        assert_eq!(args.transactions_manager_config().blob_fetch_probability, 40);
1298        // EIP-8070 sets the minimum.
1299        for percent in ["14", "101"] {
1300            assert!(CommandParser::<NetworkArgs>::try_parse_from([
1301                "reth",
1302                "--tx-blob-fetch-probability",
1303                percent
1304            ])
1305            .is_err());
1306        }
1307    }
1308
1309    #[test]
1310    fn parse_disable_tx_gossip_args() {
1311        let args = CommandParser::<NetworkArgs>::parse_from(["reth", "--disable-tx-gossip"]).args;
1312        assert!(args.disable_tx_gossip);
1313    }
1314
1315    #[test]
1316    fn parse_max_peers_flag() {
1317        let args = CommandParser::<NetworkArgs>::parse_from(["reth", "--max-peers", "90"]).args;
1318
1319        assert_eq!(args.max_peers, Some(90));
1320        assert_eq!(args.max_outbound_peers, None);
1321        assert_eq!(args.max_inbound_peers, None);
1322        assert_eq!(args.resolved_max_outbound_peers(), Some(30));
1323        assert_eq!(args.resolved_max_inbound_peers(), Some(60));
1324    }
1325
1326    #[test]
1327    fn max_peers_conflicts_with_outbound() {
1328        let result = CommandParser::<NetworkArgs>::try_parse_from([
1329            "reth",
1330            "--max-peers",
1331            "90",
1332            "--max-outbound-peers",
1333            "50",
1334        ]);
1335        assert!(
1336            result.is_err(),
1337            "Should fail when both --max-peers and --max-outbound-peers are used"
1338        );
1339    }
1340
1341    #[test]
1342    fn max_peers_conflicts_with_inbound() {
1343        let result = CommandParser::<NetworkArgs>::try_parse_from([
1344            "reth",
1345            "--max-peers",
1346            "90",
1347            "--max-inbound-peers",
1348            "30",
1349        ]);
1350        assert!(
1351            result.is_err(),
1352            "Should fail when both --max-peers and --max-inbound-peers are used"
1353        );
1354    }
1355
1356    #[test]
1357    fn max_peers_split_calculation() {
1358        let args = CommandParser::<NetworkArgs>::parse_from(["reth", "--max-peers", "90"]).args;
1359
1360        assert_eq!(args.max_peers, Some(90));
1361        assert_eq!(args.resolved_max_outbound_peers(), Some(30));
1362        assert_eq!(args.resolved_max_inbound_peers(), Some(60));
1363    }
1364
1365    #[test]
1366    fn max_peers_small_values() {
1367        let args1 = CommandParser::<NetworkArgs>::parse_from(["reth", "--max-peers", "1"]).args;
1368        assert_eq!(args1.resolved_max_outbound_peers(), Some(1));
1369        assert_eq!(args1.resolved_max_inbound_peers(), Some(0));
1370
1371        let args2 = CommandParser::<NetworkArgs>::parse_from(["reth", "--max-peers", "2"]).args;
1372        assert_eq!(args2.resolved_max_outbound_peers(), Some(1));
1373        assert_eq!(args2.resolved_max_inbound_peers(), Some(1));
1374
1375        let args3 = CommandParser::<NetworkArgs>::parse_from(["reth", "--max-peers", "3"]).args;
1376        assert_eq!(args3.resolved_max_outbound_peers(), Some(1));
1377        assert_eq!(args3.resolved_max_inbound_peers(), Some(2));
1378    }
1379
1380    #[test]
1381    fn resolved_peers_without_max_peers() {
1382        let args = CommandParser::<NetworkArgs>::parse_from([
1383            "reth",
1384            "--max-outbound-peers",
1385            "75",
1386            "--max-inbound-peers",
1387            "15",
1388        ])
1389        .args;
1390
1391        assert_eq!(args.max_peers, None);
1392        assert_eq!(args.resolved_max_outbound_peers(), Some(75));
1393        assert_eq!(args.resolved_max_inbound_peers(), Some(15));
1394    }
1395
1396    #[test]
1397    fn resolved_peers_with_defaults() {
1398        let args = CommandParser::<NetworkArgs>::parse_from(["reth"]).args;
1399
1400        assert_eq!(args.max_peers, None);
1401        assert_eq!(args.resolved_max_outbound_peers(), None);
1402        assert_eq!(args.resolved_max_inbound_peers(), None);
1403    }
1404
1405    #[test]
1406    fn network_args_default_sanity_test() {
1407        let default_args = NetworkArgs::default();
1408        let args = CommandParser::<NetworkArgs>::parse_from(["reth"]).args;
1409
1410        assert_eq!(args, default_args);
1411    }
1412
1413    #[test]
1414    fn net_if_uses_resolved_addr_for_default_discovery_addr() {
1415        let args =
1416            CommandParser::<NetworkArgs>::parse_from(["reth", "--net-if.experimental", "en0"]).args;
1417        let listener_addr = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1));
1418
1419        assert_eq!(args.resolved_discovery_addr(listener_addr), listener_addr);
1420    }
1421
1422    #[test]
1423    fn net_if_preserves_custom_discovery_addr() {
1424        let custom_discovery_addr = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 2));
1425        let args = CommandParser::<NetworkArgs>::parse_from([
1426            "reth",
1427            "--net-if.experimental",
1428            "en0",
1429            "--discovery.addr",
1430            "192.0.2.2",
1431        ])
1432        .args;
1433        let listener_addr = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1));
1434
1435        assert_eq!(args.resolved_discovery_addr(listener_addr), custom_discovery_addr);
1436    }
1437
1438    #[test]
1439    fn default_discovery_addr_is_preserved_without_net_if() {
1440        let args = CommandParser::<NetworkArgs>::parse_from(["reth"]).args;
1441        let listener_addr = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1));
1442
1443        assert_eq!(args.resolved_discovery_addr(listener_addr), DEFAULT_DISCOVERY_ADDR);
1444    }
1445
1446    #[test]
1447    fn parse_eth_max_message_size() {
1448        let args = CommandParser::<NetworkArgs>::parse_from([
1449            "reth",
1450            "--eth-max-message-size",
1451            "15728640",
1452        ])
1453        .args;
1454
1455        assert_eq!(args.eth_max_message_size, Some(NonZeroUsize::new(15 * 1024 * 1024).unwrap()));
1456    }
1457
1458    #[test]
1459    fn parse_eth_max_message_size_zero_rejected() {
1460        let result =
1461            CommandParser::<NetworkArgs>::try_parse_from(["reth", "--eth-max-message-size", "0"]);
1462        assert!(result.is_err());
1463    }
1464
1465    #[test]
1466    fn parse_eth_max_message_size_above_rlpx_cap() {
1467        let result = CommandParser::<NetworkArgs>::try_parse_from([
1468            "reth",
1469            "--eth-max-message-size",
1470            "16777216",
1471        ]);
1472        assert!(result.is_ok());
1473        let args = result.unwrap().args;
1474        assert_eq!(args.eth_max_message_size, Some(NonZeroUsize::new(16 * 1024 * 1024).unwrap()));
1475    }
1476
1477    #[test]
1478    fn parse_required_block_hashes() {
1479        let args = CommandParser::<NetworkArgs>::parse_from([
1480            "reth",
1481            "--required-block-hashes",
1482            "0x1111111111111111111111111111111111111111111111111111111111111111,23115201=0x2222222222222222222222222222222222222222222222222222222222222222",
1483        ])
1484        .args;
1485
1486        assert_eq!(args.required_block_hashes.len(), 2);
1487        // First hash without block number (should default to 0)
1488        assert_eq!(args.required_block_hashes[0].number, 0);
1489        assert_eq!(
1490            args.required_block_hashes[0].hash.to_string(),
1491            "0x1111111111111111111111111111111111111111111111111111111111111111"
1492        );
1493        // Second with block number=hash format
1494        assert_eq!(args.required_block_hashes[1].number, 23115201);
1495        assert_eq!(
1496            args.required_block_hashes[1].hash.to_string(),
1497            "0x2222222222222222222222222222222222222222222222222222222222222222"
1498        );
1499    }
1500
1501    #[test]
1502    fn parse_empty_required_block_hashes() {
1503        let args = CommandParser::<NetworkArgs>::parse_from(["reth"]).args;
1504        assert!(args.required_block_hashes.is_empty());
1505    }
1506
1507    #[test]
1508    fn test_parse_block_num_hash() {
1509        // Test hash only format
1510        let result = parse_block_num_hash(
1511            "0x1111111111111111111111111111111111111111111111111111111111111111",
1512        );
1513        assert!(result.is_ok());
1514        assert_eq!(result.unwrap().number, 0);
1515
1516        // Test block_number=hash format
1517        let result = parse_block_num_hash(
1518            "23115201=0x2222222222222222222222222222222222222222222222222222222222222222",
1519        );
1520        assert!(result.is_ok());
1521        assert_eq!(result.unwrap().number, 23115201);
1522
1523        // Test invalid formats
1524        assert!(parse_block_num_hash("invalid").is_err());
1525        assert!(parse_block_num_hash(
1526            "abc=0x1111111111111111111111111111111111111111111111111111111111111111"
1527        )
1528        .is_err());
1529    }
1530
1531    #[test]
1532    fn parse_p2p_secret_key_hex() {
1533        let hex = "4c0883a69102937d6231471b5dbb6204fe512961708279f8c5c58b3b9c4e8b8f";
1534        let args =
1535            CommandParser::<NetworkArgs>::parse_from(["reth", "--p2p-secret-key-hex", hex]).args;
1536
1537        let expected: B256 = hex.parse().unwrap();
1538        assert_eq!(args.p2p_secret_key_hex, Some(expected));
1539        assert_eq!(args.p2p_secret_key, None);
1540    }
1541
1542    #[test]
1543    fn parse_p2p_secret_key_hex_with_0x_prefix() {
1544        let hex = "0x4c0883a69102937d6231471b5dbb6204fe512961708279f8c5c58b3b9c4e8b8f";
1545        let args =
1546            CommandParser::<NetworkArgs>::parse_from(["reth", "--p2p-secret-key-hex", hex]).args;
1547
1548        let expected: B256 = hex.parse().unwrap();
1549        assert_eq!(args.p2p_secret_key_hex, Some(expected));
1550        assert_eq!(args.p2p_secret_key, None);
1551    }
1552
1553    #[test]
1554    fn test_p2p_secret_key_and_hex_are_mutually_exclusive() {
1555        let result = CommandParser::<NetworkArgs>::try_parse_from([
1556            "reth",
1557            "--p2p-secret-key",
1558            "/path/to/key",
1559            "--p2p-secret-key-hex",
1560            "4c0883a69102937d6231471b5dbb6204fe512961708279f8c5c58b3b9c4e8b8f",
1561        ]);
1562
1563        assert!(result.is_err());
1564    }
1565
1566    #[test]
1567    fn test_secret_key_method_with_hex() {
1568        let hex = "4c0883a69102937d6231471b5dbb6204fe512961708279f8c5c58b3b9c4e8b8f";
1569        let args =
1570            CommandParser::<NetworkArgs>::parse_from(["reth", "--p2p-secret-key-hex", hex]).args;
1571
1572        let temp_dir = std::env::temp_dir();
1573        let default_path = temp_dir.join("default_key");
1574        let secret_key = args.secret_key(default_path).unwrap();
1575
1576        // Verify the secret key matches the hex input
1577        assert_eq!(alloy_primitives::hex::encode(secret_key.to_secret_bytes()), hex);
1578    }
1579
1580    #[test]
1581    fn parse_netrestrict_single_network() {
1582        let args =
1583            CommandParser::<NetworkArgs>::parse_from(["reth", "--netrestrict", "192.168.0.0/16"])
1584                .args;
1585
1586        assert_eq!(args.netrestrict, Some(IpFilter::from_cidr_string("192.168.0.0/16").unwrap()));
1587
1588        let ip_filter = args.ip_filter();
1589        assert!(ip_filter.has_restrictions());
1590        assert!(ip_filter.is_allowed(&"192.168.1.1".parse().unwrap()));
1591        assert!(!ip_filter.is_allowed(&"10.0.0.1".parse().unwrap()));
1592    }
1593
1594    #[test]
1595    fn parse_netrestrict_multiple_networks() {
1596        let args = CommandParser::<NetworkArgs>::parse_from([
1597            "reth",
1598            "--netrestrict",
1599            "192.168.0.0/16,10.0.0.0/8",
1600        ])
1601        .args;
1602
1603        assert_eq!(
1604            args.netrestrict,
1605            Some(IpFilter::from_cidr_string("192.168.0.0/16,10.0.0.0/8").unwrap())
1606        );
1607
1608        let ip_filter = args.ip_filter();
1609        assert!(ip_filter.has_restrictions());
1610        assert!(ip_filter.is_allowed(&"192.168.1.1".parse().unwrap()));
1611        assert!(ip_filter.is_allowed(&"10.5.10.20".parse().unwrap()));
1612        assert!(!ip_filter.is_allowed(&"172.16.0.1".parse().unwrap()));
1613    }
1614
1615    #[test]
1616    fn parse_netrestrict_ipv6() {
1617        let args =
1618            CommandParser::<NetworkArgs>::parse_from(["reth", "--netrestrict", "2001:db8::/32"])
1619                .args;
1620
1621        let ip_filter = args.ip_filter();
1622        assert!(ip_filter.has_restrictions());
1623        assert!(ip_filter.is_allowed(&"2001:db8::1".parse().unwrap()));
1624        assert!(!ip_filter.is_allowed(&"2001:db9::1".parse().unwrap()));
1625    }
1626
1627    #[test]
1628    fn netrestrict_not_set() {
1629        let args = CommandParser::<NetworkArgs>::parse_from(["reth"]).args;
1630        assert_eq!(args.netrestrict, None);
1631
1632        let ip_filter = args.ip_filter();
1633        assert!(!ip_filter.has_restrictions());
1634        assert!(ip_filter.is_allowed(&"192.168.1.1".parse().unwrap()));
1635        assert!(ip_filter.is_allowed(&"10.0.0.1".parse().unwrap()));
1636    }
1637
1638    #[test]
1639    fn netrestrict_invalid_cidr() {
1640        for cidr in ["invalid-cidr", "10.0.0.0/33", "192.168.0.0/16,10.0.0.0/33"] {
1641            let Err(err) =
1642                CommandParser::<NetworkArgs>::try_parse_from(["reth", "--netrestrict", cidr])
1643            else {
1644                panic!("{cidr} should be rejected")
1645            };
1646            assert_eq!(err.kind(), clap::error::ErrorKind::ValueValidation, "{cidr}");
1647        }
1648    }
1649
1650    #[test]
1651    fn snap_v2_flag_controls_advertisement() {
1652        for (cli, enabled) in [(vec!["reth"], false), (vec!["reth", "--snap.v2"], true)] {
1653            let args = CommandParser::<NetworkArgs>::parse_from(cli).args;
1654            assert_eq!(args.snap_v2, enabled);
1655            let config = args
1656                .network_config::<EthNetworkPrimitives>(
1657                    &Config::default(),
1658                    MAINNET.clone(),
1659                    SecretKey::from_secret_bytes([1u8; 32]).unwrap(),
1660                    PathBuf::new(),
1661                    Runtime::test(),
1662                )
1663                .build_with_noop_provider(MAINNET.clone());
1664            let versions = config
1665                .hello_message
1666                .protocols
1667                .iter()
1668                .filter(|protocol| protocol.cap.name == "snap")
1669                .map(|protocol| protocol.cap.version)
1670                .collect::<Vec<_>>();
1671            assert_eq!(versions, if enabled { vec![2] } else { vec![] });
1672        }
1673    }
1674
1675    #[test]
1676    fn network_config_preserves_basic_nodes_from_peers_file() {
1677        let enode = "enode://6f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@10.3.58.6:30303?discport=30301";
1678        let unique = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos();
1679
1680        let peers_file = std::env::temp_dir().join(format!("reth_peers_test_{}.json", unique));
1681        fs::write(&peers_file, format!("[\"{}\"]", enode)).expect("write peers file");
1682
1683        // Build NetworkArgs with peers_file set and no_persist_peers=false
1684        let args = NetworkArgs {
1685            peers_file: Some(peers_file.clone()),
1686            no_persist_peers: false,
1687            ..Default::default()
1688        };
1689
1690        // Build the network config using a deterministic secret key
1691        let secret_key = SecretKey::from_secret_bytes([1u8; 32]).unwrap();
1692        let builder = args.network_config::<EthNetworkPrimitives>(
1693            &Config::default(),
1694            MAINNET.clone(),
1695            secret_key,
1696            peers_file.clone(),
1697            Runtime::test(),
1698        );
1699
1700        let net_cfg = builder.build_with_noop_provider(MAINNET.clone());
1701
1702        // Assert persisted_peers contains our node (legacy format is auto-converted)
1703        let node: NodeRecord = enode.parse().unwrap();
1704        assert!(net_cfg.peers_config.persisted_peers.iter().any(|p| p.record == node));
1705
1706        // Cleanup
1707        let _ = fs::remove_file(&peers_file);
1708    }
1709
1710    #[test]
1711    fn network_config_prefers_cli_bootnodes_over_config_file() {
1712        let enr = "enr:-IS4QHCYrYZbAKWCBRlAy5zzaDZXJBGkcnh4MHcBFZntXNFrdvJjX04jRzjzCBOonrkTfj499SZuOh8R33Ls8RRcy5wBgmlkgnY0gmlwhH8AAAGJc2VjcDI1NmsxoQPKY0yuDUmstAHYpMa2_oxVtw0RW_QAdpzBQA8yWM0xOIN1ZHCCdl8";
1713        let enode = "enode://6f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@10.3.58.6:30303";
1714        let config = Config { bootnodes: vec![enr.parse().unwrap()], ..Default::default() };
1715        let secret_key = SecretKey::from_secret_bytes([1u8; 32]).unwrap();
1716
1717        let boot_nodes = |args: &NetworkArgs| {
1718            args.network_config::<EthNetworkPrimitives>(
1719                &config,
1720                MAINNET.clone(),
1721                secret_key,
1722                PathBuf::from("peers.json"),
1723                Runtime::test(),
1724            )
1725            .boot_nodes_iter()
1726            .cloned()
1727            .collect::<Vec<_>>()
1728        };
1729
1730        let args = NetworkArgs { no_persist_peers: true, ..Default::default() };
1731        assert_eq!(boot_nodes(&args), vec![enr.parse::<TrustedPeer>().unwrap()]);
1732
1733        let args = NetworkArgs { bootnodes: Some(vec![enode.parse().unwrap()]), ..args };
1734        assert_eq!(boot_nodes(&args), vec![enode.parse::<TrustedPeer>().unwrap()]);
1735    }
1736
1737    #[test]
1738    fn network_config_enforce_enr_fork_id_from_config_or_cli() {
1739        let secret_key = SecretKey::from_secret_bytes([1u8; 32]).unwrap();
1740
1741        let enforced = |args: &NetworkArgs, config: &Config| {
1742            args.network_config::<EthNetworkPrimitives>(
1743                config,
1744                MAINNET.clone(),
1745                secret_key,
1746                PathBuf::from("peers.json"),
1747                Runtime::test(),
1748            )
1749            .build_with_noop_provider(MAINNET.clone())
1750            .peers_config
1751            .enforce_enr_fork_id
1752        };
1753
1754        let args = NetworkArgs { no_persist_peers: true, ..Default::default() };
1755        let mut config = Config::default();
1756        assert!(!enforced(&args, &config));
1757
1758        config.peers.enforce_enr_fork_id = true;
1759        assert!(enforced(&args, &config));
1760
1761        config.peers.enforce_enr_fork_id = false;
1762        let args = NetworkArgs { enforce_enr_fork_id: true, ..args };
1763        assert!(enforced(&args, &config));
1764    }
1765}