reth_node_core/args/
network.rs

1//! clap [Args](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    ops::Not,
8    path::PathBuf,
9};
10
11use crate::version::version_metadata;
12use clap::Args;
13use reth_chainspec::EthChainSpec;
14use reth_cli_util::{get_secret_key, load_secret_key::SecretKeyError};
15use reth_config::Config;
16use reth_discv4::{NodeRecord, DEFAULT_DISCOVERY_ADDR, DEFAULT_DISCOVERY_PORT};
17use reth_discv5::{
18    discv5::ListenConfig, DEFAULT_COUNT_BOOTSTRAP_LOOKUPS, DEFAULT_DISCOVERY_V5_PORT,
19    DEFAULT_SECONDS_BOOTSTRAP_LOOKUP_INTERVAL, DEFAULT_SECONDS_LOOKUP_INTERVAL,
20};
21use reth_net_banlist::IpFilter;
22use reth_net_nat::{NatResolver, DEFAULT_NET_IF_NAME};
23use reth_network::{
24    transactions::{
25        config::{TransactionIngressPolicy, TransactionPropagationKind},
26        constants::{
27            tx_fetcher::{
28                DEFAULT_MAX_CAPACITY_CACHE_PENDING_FETCH, DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS,
29                DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS_PER_PEER,
30            },
31            tx_manager::{
32                DEFAULT_MAX_COUNT_PENDING_POOL_IMPORTS, DEFAULT_MAX_COUNT_TRANSACTIONS_SEEN_BY_PEER,
33            },
34        },
35        TransactionFetcherConfig, TransactionPropagationMode, TransactionsManagerConfig,
36        DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESP_ON_PACK_GET_POOLED_TRANSACTIONS_REQ,
37        SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE,
38    },
39    HelloMessageWithProtocols, NetworkConfigBuilder, NetworkPrimitives, SessionsConfig,
40};
41use reth_network_peers::{mainnet_nodes, TrustedPeer};
42use secp256k1::SecretKey;
43use std::str::FromStr;
44use tracing::error;
45
46/// Parameters for configuring the network more granularity via CLI
47#[derive(Debug, Clone, Args, PartialEq, Eq)]
48#[command(next_help_heading = "Networking")]
49pub struct NetworkArgs {
50    /// Arguments to setup discovery service.
51    #[command(flatten)]
52    pub discovery: DiscoveryArgs,
53
54    #[expect(clippy::doc_markdown)]
55    /// Comma separated enode URLs of trusted peers for P2P connections.
56    ///
57    /// --trusted-peers enode://abcd@192.168.0.1:30303
58    #[arg(long, value_delimiter = ',')]
59    pub trusted_peers: Vec<TrustedPeer>,
60
61    /// Connect to or accept from trusted peers only
62    #[arg(long)]
63    pub trusted_only: bool,
64
65    /// Comma separated enode URLs for P2P discovery bootstrap.
66    ///
67    /// Will fall back to a network-specific default if not specified.
68    #[arg(long, value_delimiter = ',')]
69    pub bootnodes: Option<Vec<TrustedPeer>>,
70
71    /// Amount of DNS resolution requests retries to perform when peering.
72    #[arg(long, default_value_t = 0)]
73    pub dns_retries: usize,
74
75    /// The path to the known peers file. Connected peers are dumped to this file on nodes
76    /// shutdown, and read on startup. Cannot be used with `--no-persist-peers`.
77    #[arg(long, value_name = "FILE", verbatim_doc_comment, conflicts_with = "no_persist_peers")]
78    pub peers_file: Option<PathBuf>,
79
80    /// Custom node identity
81    #[arg(long, value_name = "IDENTITY", default_value = version_metadata().p2p_client_version.as_ref())]
82    pub identity: String,
83
84    /// Secret key to use for this node.
85    ///
86    /// This will also deterministically set the peer ID. If not specified, it will be set in the
87    /// data dir for the chain being used.
88    #[arg(long, value_name = "PATH", conflicts_with = "p2p_secret_key_hex")]
89    pub p2p_secret_key: Option<PathBuf>,
90
91    /// Hex encoded secret key to use for this node.
92    ///
93    /// This will also deterministically set the peer ID. Cannot be used together with
94    /// `--p2p-secret-key`.
95    #[arg(long, value_name = "HEX", conflicts_with = "p2p_secret_key")]
96    pub p2p_secret_key_hex: Option<B256>,
97
98    /// Do not persist peers.
99    #[arg(long, verbatim_doc_comment)]
100    pub no_persist_peers: bool,
101
102    /// NAT resolution method (any|none|upnp|publicip|extip:\<IP\>)
103    #[arg(long, default_value = "any")]
104    pub nat: NatResolver,
105
106    /// Network listening address
107    #[arg(long = "addr", value_name = "ADDR", default_value_t = DEFAULT_DISCOVERY_ADDR)]
108    pub addr: IpAddr,
109
110    /// Network listening port
111    #[arg(long = "port", value_name = "PORT", default_value_t = DEFAULT_DISCOVERY_PORT)]
112    pub port: u16,
113
114    /// Maximum number of outbound peers. default: 100
115    #[arg(long)]
116    pub max_outbound_peers: Option<usize>,
117
118    /// Maximum number of inbound peers. default: 30
119    #[arg(long)]
120    pub max_inbound_peers: Option<usize>,
121
122    /// Maximum number of total peers (inbound + outbound).
123    ///
124    /// Splits peers using approximately 2:1 inbound:outbound ratio. Cannot be used together with
125    /// `--max-outbound-peers` or `--max-inbound-peers`.
126    #[arg(
127        long,
128        value_name = "COUNT",
129        conflicts_with = "max_outbound_peers",
130        conflicts_with = "max_inbound_peers"
131    )]
132    pub max_peers: Option<usize>,
133
134    /// Max concurrent `GetPooledTransactions` requests.
135    #[arg(long = "max-tx-reqs", value_name = "COUNT", default_value_t = DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS, verbatim_doc_comment)]
136    pub max_concurrent_tx_requests: u32,
137
138    /// Max concurrent `GetPooledTransactions` requests per peer.
139    #[arg(long = "max-tx-reqs-peer", value_name = "COUNT", default_value_t = DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS_PER_PEER, verbatim_doc_comment)]
140    pub max_concurrent_tx_requests_per_peer: u8,
141
142    /// Max number of seen transactions to remember per peer.
143    ///
144    /// Default is 320 transaction hashes.
145    #[arg(long = "max-seen-tx-history", value_name = "COUNT", default_value_t = DEFAULT_MAX_COUNT_TRANSACTIONS_SEEN_BY_PEER, verbatim_doc_comment)]
146    pub max_seen_tx_history: u32,
147
148    #[arg(long = "max-pending-imports", value_name = "COUNT", default_value_t = DEFAULT_MAX_COUNT_PENDING_POOL_IMPORTS, verbatim_doc_comment)]
149    /// Max number of transactions to import concurrently.
150    pub max_pending_pool_imports: usize,
151
152    /// Experimental, for usage in research. Sets the max accumulated byte size of transactions
153    /// to pack in one response.
154    /// Spec'd at 2MiB.
155    #[arg(long = "pooled-tx-response-soft-limit", value_name = "BYTES", default_value_t = SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE, verbatim_doc_comment)]
156    pub soft_limit_byte_size_pooled_transactions_response: usize,
157
158    /// Experimental, for usage in research. Sets the max accumulated byte size of transactions to
159    /// request in one request.
160    ///
161    /// Since `RLPx` protocol version 68, the byte size of a transaction is shared as metadata in a
162    /// transaction announcement (see `RLPx` specs). This allows a node to request a specific size
163    /// response.
164    ///
165    /// By default, nodes request only 128 KiB worth of transactions, but should a peer request
166    /// more, up to 2 MiB, a node will answer with more than 128 KiB.
167    ///
168    /// Default is 128 KiB.
169    #[arg(long = "pooled-tx-pack-soft-limit", value_name = "BYTES", default_value_t = DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESP_ON_PACK_GET_POOLED_TRANSACTIONS_REQ, verbatim_doc_comment)]
170    pub soft_limit_byte_size_pooled_transactions_response_on_pack_request: usize,
171
172    /// Max capacity of cache of hashes for transactions pending fetch.
173    #[arg(long = "max-tx-pending-fetch", value_name = "COUNT", default_value_t = DEFAULT_MAX_CAPACITY_CACHE_PENDING_FETCH, verbatim_doc_comment)]
174    pub max_capacity_cache_txns_pending_fetch: u32,
175
176    /// Name of network interface used to communicate with peers.
177    ///
178    /// If flag is set, but no value is passed, the default interface for docker `eth0` is tried.
179    #[arg(long = "net-if.experimental", conflicts_with = "addr", value_name = "IF_NAME")]
180    pub net_if: Option<String>,
181
182    /// Transaction Propagation Policy
183    ///
184    /// The policy determines which peers transactions are gossiped to.
185    #[arg(long = "tx-propagation-policy", default_value_t = TransactionPropagationKind::All)]
186    pub tx_propagation_policy: TransactionPropagationKind,
187
188    /// Transaction ingress policy
189    ///
190    /// Determines which peers' transactions are accepted over P2P.
191    #[arg(long = "tx-ingress-policy", default_value_t = TransactionIngressPolicy::All)]
192    pub tx_ingress_policy: TransactionIngressPolicy,
193
194    /// Disable transaction pool gossip
195    ///
196    /// Disables gossiping of transactions in the mempool to peers. This can be omitted for
197    /// personal nodes, though providers should always opt to enable this flag.
198    #[arg(long = "disable-tx-gossip")]
199    pub disable_tx_gossip: bool,
200
201    /// Sets the transaction propagation mode by determining how new pending transactions are
202    /// propagated to other peers in full.
203    ///
204    /// Examples: sqrt, all, max:10
205    #[arg(
206        long = "tx-propagation-mode",
207        default_value = "sqrt",
208        help = "Transaction propagation mode (sqrt, all, max:<number>)"
209    )]
210    pub propagation_mode: TransactionPropagationMode,
211
212    /// Comma separated list of required block hashes or block number=hash pairs.
213    /// Peers that don't have these blocks will be filtered out.
214    /// Format: hash or `block_number=hash` (e.g., 23115201=0x1234...)
215    #[arg(long = "required-block-hashes", value_delimiter = ',', value_parser = parse_block_num_hash)]
216    pub required_block_hashes: Vec<BlockNumHash>,
217
218    /// Optional network ID to override the chain specification's network ID for P2P connections
219    #[arg(long)]
220    pub network_id: Option<u64>,
221
222    /// Restrict network communication to the given IP networks (CIDR masks).
223    ///
224    /// Comma separated list of CIDR network specifications.
225    /// Only peers with IP addresses within these ranges will be allowed to connect.
226    ///
227    /// Example: --netrestrict "192.168.0.0/16,10.0.0.0/8"
228    #[arg(long, value_name = "NETRESTRICT")]
229    pub netrestrict: Option<String>,
230}
231
232impl NetworkArgs {
233    /// Returns the resolved IP address.
234    pub fn resolved_addr(&self) -> IpAddr {
235        if let Some(ref if_name) = self.net_if {
236            let if_name = if if_name.is_empty() { DEFAULT_NET_IF_NAME } else { if_name };
237            return match reth_net_nat::net_if::resolve_net_if_ip(if_name) {
238                Ok(addr) => addr,
239                Err(err) => {
240                    error!(target: "reth::cli",
241                        if_name,
242                        %err,
243                        "Failed to read network interface IP"
244                    );
245
246                    DEFAULT_DISCOVERY_ADDR
247                }
248            };
249        }
250
251        self.addr
252    }
253
254    /// Returns the resolved bootnodes if any are provided.
255    pub fn resolved_bootnodes(&self) -> Option<Vec<NodeRecord>> {
256        self.bootnodes.clone().map(|bootnodes| {
257            bootnodes.into_iter().filter_map(|node| node.resolve_blocking().ok()).collect()
258        })
259    }
260
261    /// Returns the max inbound peers (2:1 ratio).
262    pub fn resolved_max_inbound_peers(&self) -> Option<usize> {
263        if let Some(max_peers) = self.max_peers {
264            if max_peers == 0 {
265                Some(0)
266            } else {
267                let outbound = (max_peers / 3).max(1);
268                Some(max_peers.saturating_sub(outbound))
269            }
270        } else {
271            self.max_inbound_peers
272        }
273    }
274
275    /// Returns the max outbound peers (1:2 ratio).
276    pub fn resolved_max_outbound_peers(&self) -> Option<usize> {
277        if let Some(max_peers) = self.max_peers {
278            if max_peers == 0 {
279                Some(0)
280            } else {
281                Some((max_peers / 3).max(1))
282            }
283        } else {
284            self.max_outbound_peers
285        }
286    }
287
288    /// Configures and returns a `TransactionsManagerConfig` based on the current settings.
289    pub const fn transactions_manager_config(&self) -> TransactionsManagerConfig {
290        TransactionsManagerConfig {
291            transaction_fetcher_config: TransactionFetcherConfig::new(
292                self.max_concurrent_tx_requests,
293                self.max_concurrent_tx_requests_per_peer,
294                self.soft_limit_byte_size_pooled_transactions_response,
295                self.soft_limit_byte_size_pooled_transactions_response_on_pack_request,
296                self.max_capacity_cache_txns_pending_fetch,
297            ),
298            max_transactions_seen_by_peer_history: self.max_seen_tx_history,
299            propagation_mode: self.propagation_mode,
300            ingress_policy: self.tx_ingress_policy,
301        }
302    }
303
304    /// Build a [`NetworkConfigBuilder`] from a [`Config`] and a [`EthChainSpec`], in addition to
305    /// the values in this option struct.
306    ///
307    /// The `default_peers_file` will be used as the default location to store the persistent peers
308    /// file if `no_persist_peers` is false, and there is no provided `peers_file`.
309    ///
310    /// Configured Bootnodes are prioritized, if unset, the chain spec bootnodes are used
311    /// Priority order for bootnodes configuration:
312    /// 1. --bootnodes flag
313    /// 2. Network preset flags (e.g. --holesky)
314    /// 3. default to mainnet nodes
315    pub fn network_config<N: NetworkPrimitives>(
316        &self,
317        config: &Config,
318        chain_spec: impl EthChainSpec,
319        secret_key: SecretKey,
320        default_peers_file: PathBuf,
321    ) -> NetworkConfigBuilder<N> {
322        let addr = self.resolved_addr();
323        let chain_bootnodes = self
324            .resolved_bootnodes()
325            .unwrap_or_else(|| chain_spec.bootnodes().unwrap_or_else(mainnet_nodes));
326        let peers_file = self.peers_file.clone().unwrap_or(default_peers_file);
327
328        // Configure peer connections
329        let ip_filter = self.ip_filter().unwrap_or_default();
330        let peers_config = config
331            .peers_config_with_basic_nodes_from_file(
332                self.persistent_peers_file(peers_file).as_deref(),
333            )
334            .with_max_inbound_opt(self.resolved_max_inbound_peers())
335            .with_max_outbound_opt(self.resolved_max_outbound_peers())
336            .with_ip_filter(ip_filter);
337
338        // Configure basic network stack
339        NetworkConfigBuilder::<N>::new(secret_key)
340            .external_ip_resolver(self.nat)
341            .sessions_config(
342                SessionsConfig::default().with_upscaled_event_buffer(peers_config.max_peers()),
343            )
344            .peer_config(peers_config)
345            .boot_nodes(chain_bootnodes.clone())
346            .transactions_manager_config(self.transactions_manager_config())
347            // Configure node identity
348            .apply(|builder| {
349                let peer_id = builder.get_peer_id();
350                builder.hello_message(
351                    HelloMessageWithProtocols::builder(peer_id)
352                        .client_version(&self.identity)
353                        .build(),
354                )
355            })
356            // apply discovery settings
357            .apply(|builder| {
358                let rlpx_socket = (addr, self.port).into();
359                self.discovery.apply_to_builder(builder, rlpx_socket, chain_bootnodes)
360            })
361            .listener_addr(SocketAddr::new(
362                addr, // set discovery port based on instance number
363                self.port,
364            ))
365            .discovery_addr(SocketAddr::new(
366                self.discovery.addr,
367                // set discovery port based on instance number
368                self.discovery.port,
369            ))
370            .disable_tx_gossip(self.disable_tx_gossip)
371            .required_block_hashes(self.required_block_hashes.clone())
372            .network_id(self.network_id)
373    }
374
375    /// If `no_persist_peers` is false then this returns the path to the persistent peers file path.
376    pub fn persistent_peers_file(&self, peers_file: PathBuf) -> Option<PathBuf> {
377        self.no_persist_peers.not().then_some(peers_file)
378    }
379
380    /// Configures the [`DiscoveryArgs`].
381    pub const fn with_discovery(mut self, discovery: DiscoveryArgs) -> Self {
382        self.discovery = discovery;
383        self
384    }
385
386    /// Sets the p2p port to zero, to allow the OS to assign a random unused port when
387    /// the network components bind to a socket.
388    pub const fn with_unused_p2p_port(mut self) -> Self {
389        self.port = 0;
390        self
391    }
392
393    /// Sets the p2p and discovery ports to zero, allowing the OD to assign a random unused port
394    /// when network components bind to sockets.
395    pub const fn with_unused_ports(mut self) -> Self {
396        self = self.with_unused_p2p_port();
397        self.discovery = self.discovery.with_unused_discovery_port();
398        self
399    }
400
401    /// Configures the [`NatResolver`]
402    pub const fn with_nat_resolver(mut self, nat: NatResolver) -> Self {
403        self.nat = nat;
404        self
405    }
406
407    /// Change networking port numbers based on the instance number, if provided.
408    /// Ports are updated to `previous_value + instance - 1`
409    ///
410    /// # Panics
411    /// Warning: if `instance` is zero in debug mode, this will panic.
412    pub fn adjust_instance_ports(&mut self, instance: Option<u16>) {
413        if let Some(instance) = instance {
414            debug_assert_ne!(instance, 0, "instance must be non-zero");
415            self.port += instance - 1;
416            self.discovery.adjust_instance_ports(instance);
417        }
418    }
419
420    /// Resolve all trusted peers at once
421    pub async fn resolve_trusted_peers(&self) -> Result<Vec<NodeRecord>, std::io::Error> {
422        futures::future::try_join_all(
423            self.trusted_peers.iter().map(|peer| async move { peer.resolve().await }),
424        )
425        .await
426    }
427
428    /// Load the p2p secret key from the provided options.
429    ///
430    /// If `p2p_secret_key_hex` is provided, it will be used directly.
431    /// If `p2p_secret_key` is provided, it will be loaded from the file.
432    /// If neither is provided, the `default_secret_key_path` will be used.
433    pub fn secret_key(
434        &self,
435        default_secret_key_path: PathBuf,
436    ) -> Result<SecretKey, SecretKeyError> {
437        if let Some(b256) = &self.p2p_secret_key_hex {
438            // Use the B256 value directly (already validated as 32 bytes)
439            SecretKey::from_slice(b256.as_slice()).map_err(SecretKeyError::SecretKeyDecodeError)
440        } else {
441            // Load from file (either provided path or default)
442            let secret_key_path = self.p2p_secret_key.clone().unwrap_or(default_secret_key_path);
443            get_secret_key(&secret_key_path)
444        }
445    }
446
447    /// Creates an IP filter from the netrestrict argument.
448    ///
449    /// Returns an error if the CIDR format is invalid.
450    pub fn ip_filter(&self) -> Result<IpFilter, ipnet::AddrParseError> {
451        if let Some(netrestrict) = &self.netrestrict {
452            IpFilter::from_cidr_string(netrestrict)
453        } else {
454            Ok(IpFilter::allow_all())
455        }
456    }
457}
458
459impl Default for NetworkArgs {
460    fn default() -> Self {
461        Self {
462            discovery: DiscoveryArgs::default(),
463            trusted_peers: vec![],
464            trusted_only: false,
465            bootnodes: None,
466            dns_retries: 0,
467            peers_file: None,
468            identity: version_metadata().p2p_client_version.to_string(),
469            p2p_secret_key: None,
470            p2p_secret_key_hex: None,
471            no_persist_peers: false,
472            nat: NatResolver::Any,
473            addr: DEFAULT_DISCOVERY_ADDR,
474            port: DEFAULT_DISCOVERY_PORT,
475            max_outbound_peers: None,
476            max_inbound_peers: None,
477            max_peers: None,
478            max_concurrent_tx_requests: DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS,
479            max_concurrent_tx_requests_per_peer: DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS_PER_PEER,
480            soft_limit_byte_size_pooled_transactions_response:
481                SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE,
482            soft_limit_byte_size_pooled_transactions_response_on_pack_request: DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESP_ON_PACK_GET_POOLED_TRANSACTIONS_REQ,
483            max_pending_pool_imports: DEFAULT_MAX_COUNT_PENDING_POOL_IMPORTS,
484            max_seen_tx_history: DEFAULT_MAX_COUNT_TRANSACTIONS_SEEN_BY_PEER,
485            max_capacity_cache_txns_pending_fetch: DEFAULT_MAX_CAPACITY_CACHE_PENDING_FETCH,
486            net_if: None,
487            tx_propagation_policy: TransactionPropagationKind::default(),
488            tx_ingress_policy: TransactionIngressPolicy::default(),
489            disable_tx_gossip: false,
490            propagation_mode: TransactionPropagationMode::Sqrt,
491            required_block_hashes: vec![],
492            network_id: None,
493            netrestrict: None,
494        }
495    }
496}
497
498/// Arguments to setup discovery
499#[derive(Debug, Clone, Args, PartialEq, Eq)]
500pub struct DiscoveryArgs {
501    /// Disable the discovery service.
502    #[arg(short, long, default_value_if("dev", "true", "true"))]
503    pub disable_discovery: bool,
504
505    /// Disable the DNS discovery.
506    #[arg(long, conflicts_with = "disable_discovery")]
507    pub disable_dns_discovery: bool,
508
509    /// Disable Discv4 discovery.
510    #[arg(long, conflicts_with = "disable_discovery")]
511    pub disable_discv4_discovery: bool,
512
513    /// Enable Discv5 discovery.
514    #[arg(long, conflicts_with = "disable_discovery")]
515    pub enable_discv5_discovery: bool,
516
517    /// Disable Nat discovery.
518    #[arg(long, conflicts_with = "disable_discovery")]
519    pub disable_nat: bool,
520
521    /// The UDP address to use for devp2p peer discovery version 4.
522    #[arg(id = "discovery.addr", long = "discovery.addr", value_name = "DISCOVERY_ADDR", default_value_t = DEFAULT_DISCOVERY_ADDR)]
523    pub addr: IpAddr,
524
525    /// The UDP port to use for devp2p peer discovery version 4.
526    #[arg(id = "discovery.port", long = "discovery.port", value_name = "DISCOVERY_PORT", default_value_t = DEFAULT_DISCOVERY_PORT)]
527    pub port: u16,
528
529    /// The UDP IPv4 address to use for devp2p peer discovery version 5. Overwritten by `RLPx`
530    /// address, if it's also IPv4.
531    #[arg(id = "discovery.v5.addr", long = "discovery.v5.addr", value_name = "DISCOVERY_V5_ADDR", default_value = None)]
532    pub discv5_addr: Option<Ipv4Addr>,
533
534    /// The UDP IPv6 address to use for devp2p peer discovery version 5. Overwritten by `RLPx`
535    /// address, if it's also IPv6.
536    #[arg(id = "discovery.v5.addr.ipv6", long = "discovery.v5.addr.ipv6", value_name = "DISCOVERY_V5_ADDR_IPV6", default_value = None)]
537    pub discv5_addr_ipv6: Option<Ipv6Addr>,
538
539    /// The UDP IPv4 port to use for devp2p peer discovery version 5. Not used unless `--addr` is
540    /// IPv4, or `--discovery.v5.addr` is set.
541    #[arg(id = "discovery.v5.port", long = "discovery.v5.port", value_name = "DISCOVERY_V5_PORT",
542    default_value_t = DEFAULT_DISCOVERY_V5_PORT)]
543    pub discv5_port: u16,
544
545    /// The UDP IPv6 port to use for devp2p peer discovery version 5. Not used unless `--addr` is
546    /// IPv6, or `--discovery.addr.ipv6` is set.
547    #[arg(id = "discovery.v5.port.ipv6", long = "discovery.v5.port.ipv6", value_name = "DISCOVERY_V5_PORT_IPV6",
548    default_value = None, default_value_t = DEFAULT_DISCOVERY_V5_PORT)]
549    pub discv5_port_ipv6: u16,
550
551    /// The interval in seconds at which to carry out periodic lookup queries, for the whole
552    /// run of the program.
553    #[arg(id = "discovery.v5.lookup-interval", long = "discovery.v5.lookup-interval", value_name = "DISCOVERY_V5_LOOKUP_INTERVAL", default_value_t = DEFAULT_SECONDS_LOOKUP_INTERVAL)]
554    pub discv5_lookup_interval: u64,
555
556    /// The interval in seconds at which to carry out boost lookup queries, for a fixed number of
557    /// times, at bootstrap.
558    #[arg(id = "discovery.v5.bootstrap.lookup-interval", long = "discovery.v5.bootstrap.lookup-interval", value_name = "DISCOVERY_V5_BOOTSTRAP_LOOKUP_INTERVAL",
559        default_value_t = DEFAULT_SECONDS_BOOTSTRAP_LOOKUP_INTERVAL)]
560    pub discv5_bootstrap_lookup_interval: u64,
561
562    /// The number of times to carry out boost lookup queries at bootstrap.
563    #[arg(id = "discovery.v5.bootstrap.lookup-countdown", long = "discovery.v5.bootstrap.lookup-countdown", value_name = "DISCOVERY_V5_BOOTSTRAP_LOOKUP_COUNTDOWN",
564        default_value_t = DEFAULT_COUNT_BOOTSTRAP_LOOKUPS)]
565    pub discv5_bootstrap_lookup_countdown: u64,
566}
567
568impl DiscoveryArgs {
569    /// Apply the discovery settings to the given [`NetworkConfigBuilder`]
570    pub fn apply_to_builder<N>(
571        &self,
572        mut network_config_builder: NetworkConfigBuilder<N>,
573        rlpx_tcp_socket: SocketAddr,
574        boot_nodes: impl IntoIterator<Item = NodeRecord>,
575    ) -> NetworkConfigBuilder<N>
576    where
577        N: NetworkPrimitives,
578    {
579        if self.disable_discovery || self.disable_dns_discovery {
580            network_config_builder = network_config_builder.disable_dns_discovery();
581        }
582
583        if self.disable_discovery || self.disable_discv4_discovery {
584            network_config_builder = network_config_builder.disable_discv4_discovery();
585        }
586
587        if self.disable_nat {
588            // 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>
589            network_config_builder = network_config_builder.disable_nat();
590        }
591
592        if self.should_enable_discv5() {
593            network_config_builder = network_config_builder
594                .discovery_v5(self.discovery_v5_builder(rlpx_tcp_socket, boot_nodes));
595        }
596
597        network_config_builder
598    }
599
600    /// Creates a [`reth_discv5::ConfigBuilder`] filling it with the values from this struct.
601    pub fn discovery_v5_builder(
602        &self,
603        rlpx_tcp_socket: SocketAddr,
604        boot_nodes: impl IntoIterator<Item = NodeRecord>,
605    ) -> reth_discv5::ConfigBuilder {
606        let Self {
607            discv5_addr,
608            discv5_addr_ipv6,
609            discv5_port,
610            discv5_port_ipv6,
611            discv5_lookup_interval,
612            discv5_bootstrap_lookup_interval,
613            discv5_bootstrap_lookup_countdown,
614            ..
615        } = self;
616
617        // Use rlpx address if none given
618        let discv5_addr_ipv4 = discv5_addr.or(match rlpx_tcp_socket {
619            SocketAddr::V4(addr) => Some(*addr.ip()),
620            SocketAddr::V6(_) => None,
621        });
622        let discv5_addr_ipv6 = discv5_addr_ipv6.or(match rlpx_tcp_socket {
623            SocketAddr::V4(_) => None,
624            SocketAddr::V6(addr) => Some(*addr.ip()),
625        });
626
627        reth_discv5::Config::builder(rlpx_tcp_socket)
628            .discv5_config(
629                reth_discv5::discv5::ConfigBuilder::new(ListenConfig::from_two_sockets(
630                    discv5_addr_ipv4.map(|addr| SocketAddrV4::new(addr, *discv5_port)),
631                    discv5_addr_ipv6.map(|addr| SocketAddrV6::new(addr, *discv5_port_ipv6, 0, 0)),
632                ))
633                .build(),
634            )
635            .add_unsigned_boot_nodes(boot_nodes)
636            .lookup_interval(*discv5_lookup_interval)
637            .bootstrap_lookup_interval(*discv5_bootstrap_lookup_interval)
638            .bootstrap_lookup_countdown(*discv5_bootstrap_lookup_countdown)
639    }
640
641    /// Returns true if discv5 discovery should be configured
642    const fn should_enable_discv5(&self) -> bool {
643        if self.disable_discovery {
644            return false;
645        }
646
647        self.enable_discv5_discovery ||
648            self.discv5_addr.is_some() ||
649            self.discv5_addr_ipv6.is_some()
650    }
651
652    /// Set the discovery port to zero, to allow the OS to assign a random unused port when
653    /// discovery binds to the socket.
654    pub const fn with_unused_discovery_port(mut self) -> Self {
655        self.port = 0;
656        self
657    }
658
659    /// Set the discovery V5 port
660    pub const fn with_discv5_port(mut self, port: u16) -> Self {
661        self.discv5_port = port;
662        self
663    }
664
665    /// Change networking port numbers based on the instance number.
666    /// Ports are updated to `previous_value + instance - 1`
667    ///
668    /// # Panics
669    /// Warning: if `instance` is zero in debug mode, this will panic.
670    pub fn adjust_instance_ports(&mut self, instance: u16) {
671        debug_assert_ne!(instance, 0, "instance must be non-zero");
672        self.port += instance - 1;
673        self.discv5_port += instance - 1;
674        self.discv5_port_ipv6 += instance - 1;
675    }
676}
677
678impl Default for DiscoveryArgs {
679    fn default() -> Self {
680        Self {
681            disable_discovery: false,
682            disable_dns_discovery: false,
683            disable_discv4_discovery: false,
684            enable_discv5_discovery: false,
685            disable_nat: false,
686            addr: DEFAULT_DISCOVERY_ADDR,
687            port: DEFAULT_DISCOVERY_PORT,
688            discv5_addr: None,
689            discv5_addr_ipv6: None,
690            discv5_port: DEFAULT_DISCOVERY_V5_PORT,
691            discv5_port_ipv6: DEFAULT_DISCOVERY_V5_PORT,
692            discv5_lookup_interval: DEFAULT_SECONDS_LOOKUP_INTERVAL,
693            discv5_bootstrap_lookup_interval: DEFAULT_SECONDS_BOOTSTRAP_LOOKUP_INTERVAL,
694            discv5_bootstrap_lookup_countdown: DEFAULT_COUNT_BOOTSTRAP_LOOKUPS,
695        }
696    }
697}
698
699/// Parse a block number=hash pair or just a hash into `BlockNumHash`
700fn parse_block_num_hash(s: &str) -> Result<BlockNumHash, String> {
701    if let Some((num_str, hash_str)) = s.split_once('=') {
702        let number = num_str.parse().map_err(|_| format!("Invalid block number: {}", num_str))?;
703        let hash = B256::from_str(hash_str).map_err(|_| format!("Invalid hash: {}", hash_str))?;
704        Ok(BlockNumHash::new(number, hash))
705    } else {
706        // For backward compatibility, treat as hash-only with number 0
707        let hash = B256::from_str(s).map_err(|_| format!("Invalid hash: {}", s))?;
708        Ok(BlockNumHash::new(0, hash))
709    }
710}
711
712#[cfg(test)]
713mod tests {
714    use super::*;
715    use clap::Parser;
716    use reth_chainspec::MAINNET;
717    use reth_config::Config;
718    use reth_network_peers::NodeRecord;
719    use secp256k1::SecretKey;
720    use std::{
721        fs,
722        time::{SystemTime, UNIX_EPOCH},
723    };
724
725    /// A helper type to parse Args more easily
726    #[derive(Parser)]
727    struct CommandParser<T: Args> {
728        #[command(flatten)]
729        args: T,
730    }
731
732    #[test]
733    fn parse_nat_args() {
734        let args = CommandParser::<NetworkArgs>::parse_from(["reth", "--nat", "none"]).args;
735        assert_eq!(args.nat, NatResolver::None);
736
737        let args =
738            CommandParser::<NetworkArgs>::parse_from(["reth", "--nat", "extip:0.0.0.0"]).args;
739        assert_eq!(args.nat, NatResolver::ExternalIp("0.0.0.0".parse().unwrap()));
740    }
741
742    #[test]
743    fn parse_peer_args() {
744        let args =
745            CommandParser::<NetworkArgs>::parse_from(["reth", "--max-outbound-peers", "50"]).args;
746        assert_eq!(args.max_outbound_peers, Some(50));
747        assert_eq!(args.max_inbound_peers, None);
748
749        let args = CommandParser::<NetworkArgs>::parse_from([
750            "reth",
751            "--max-outbound-peers",
752            "75",
753            "--max-inbound-peers",
754            "15",
755        ])
756        .args;
757        assert_eq!(args.max_outbound_peers, Some(75));
758        assert_eq!(args.max_inbound_peers, Some(15));
759    }
760
761    #[test]
762    fn parse_trusted_peer_args() {
763        let args =
764            CommandParser::<NetworkArgs>::parse_from([
765            "reth",
766            "--trusted-peers",
767            "enode://d860a01f9722d78051619d1e2351aba3f43f943f6f00718d1b9baa4101932a1f5011f16bb2b1bb35db20d6fe28fa0bf09636d26a87d31de9ec6203eeedb1f666@18.138.108.67:30303,enode://22a8232c3abc76a16ae9d6c3b164f98775fe226f0917b0ca871128a74a8e9630b458460865bab457221f1d448dd9791d24c4e5d88786180ac185df813a68d4de@3.209.45.79:30303"
768        ])
769        .args;
770
771        assert_eq!(
772            args.trusted_peers,
773            vec![
774            "enode://d860a01f9722d78051619d1e2351aba3f43f943f6f00718d1b9baa4101932a1f5011f16bb2b1bb35db20d6fe28fa0bf09636d26a87d31de9ec6203eeedb1f666@18.138.108.67:30303".parse().unwrap(),
775            "enode://22a8232c3abc76a16ae9d6c3b164f98775fe226f0917b0ca871128a74a8e9630b458460865bab457221f1d448dd9791d24c4e5d88786180ac185df813a68d4de@3.209.45.79:30303".parse().unwrap()
776            ]
777        );
778    }
779
780    #[test]
781    fn parse_retry_strategy_args() {
782        let tests = vec![0, 10];
783
784        for retries in tests {
785            let args = CommandParser::<NetworkArgs>::parse_from([
786                "reth",
787                "--dns-retries",
788                retries.to_string().as_str(),
789            ])
790            .args;
791
792            assert_eq!(args.dns_retries, retries);
793        }
794    }
795
796    #[test]
797    fn parse_disable_tx_gossip_args() {
798        let args = CommandParser::<NetworkArgs>::parse_from(["reth", "--disable-tx-gossip"]).args;
799        assert!(args.disable_tx_gossip);
800    }
801
802    #[test]
803    fn parse_max_peers_flag() {
804        let args = CommandParser::<NetworkArgs>::parse_from(["reth", "--max-peers", "90"]).args;
805
806        assert_eq!(args.max_peers, Some(90));
807        assert_eq!(args.max_outbound_peers, None);
808        assert_eq!(args.max_inbound_peers, None);
809        assert_eq!(args.resolved_max_outbound_peers(), Some(30));
810        assert_eq!(args.resolved_max_inbound_peers(), Some(60));
811    }
812
813    #[test]
814    fn max_peers_conflicts_with_outbound() {
815        let result = CommandParser::<NetworkArgs>::try_parse_from([
816            "reth",
817            "--max-peers",
818            "90",
819            "--max-outbound-peers",
820            "50",
821        ]);
822        assert!(
823            result.is_err(),
824            "Should fail when both --max-peers and --max-outbound-peers are used"
825        );
826    }
827
828    #[test]
829    fn max_peers_conflicts_with_inbound() {
830        let result = CommandParser::<NetworkArgs>::try_parse_from([
831            "reth",
832            "--max-peers",
833            "90",
834            "--max-inbound-peers",
835            "30",
836        ]);
837        assert!(
838            result.is_err(),
839            "Should fail when both --max-peers and --max-inbound-peers are used"
840        );
841    }
842
843    #[test]
844    fn max_peers_split_calculation() {
845        let args = CommandParser::<NetworkArgs>::parse_from(["reth", "--max-peers", "90"]).args;
846
847        assert_eq!(args.max_peers, Some(90));
848        assert_eq!(args.resolved_max_outbound_peers(), Some(30));
849        assert_eq!(args.resolved_max_inbound_peers(), Some(60));
850    }
851
852    #[test]
853    fn max_peers_small_values() {
854        let args1 = CommandParser::<NetworkArgs>::parse_from(["reth", "--max-peers", "1"]).args;
855        assert_eq!(args1.resolved_max_outbound_peers(), Some(1));
856        assert_eq!(args1.resolved_max_inbound_peers(), Some(0));
857
858        let args2 = CommandParser::<NetworkArgs>::parse_from(["reth", "--max-peers", "2"]).args;
859        assert_eq!(args2.resolved_max_outbound_peers(), Some(1));
860        assert_eq!(args2.resolved_max_inbound_peers(), Some(1));
861
862        let args3 = CommandParser::<NetworkArgs>::parse_from(["reth", "--max-peers", "3"]).args;
863        assert_eq!(args3.resolved_max_outbound_peers(), Some(1));
864        assert_eq!(args3.resolved_max_inbound_peers(), Some(2));
865    }
866
867    #[test]
868    fn resolved_peers_without_max_peers() {
869        let args = CommandParser::<NetworkArgs>::parse_from([
870            "reth",
871            "--max-outbound-peers",
872            "75",
873            "--max-inbound-peers",
874            "15",
875        ])
876        .args;
877
878        assert_eq!(args.max_peers, None);
879        assert_eq!(args.resolved_max_outbound_peers(), Some(75));
880        assert_eq!(args.resolved_max_inbound_peers(), Some(15));
881    }
882
883    #[test]
884    fn resolved_peers_with_defaults() {
885        let args = CommandParser::<NetworkArgs>::parse_from(["reth"]).args;
886
887        assert_eq!(args.max_peers, None);
888        assert_eq!(args.resolved_max_outbound_peers(), None);
889        assert_eq!(args.resolved_max_inbound_peers(), None);
890    }
891
892    #[test]
893    fn network_args_default_sanity_test() {
894        let default_args = NetworkArgs::default();
895        let args = CommandParser::<NetworkArgs>::parse_from(["reth"]).args;
896
897        assert_eq!(args, default_args);
898    }
899
900    #[test]
901    fn parse_required_block_hashes() {
902        let args = CommandParser::<NetworkArgs>::parse_from([
903            "reth",
904            "--required-block-hashes",
905            "0x1111111111111111111111111111111111111111111111111111111111111111,23115201=0x2222222222222222222222222222222222222222222222222222222222222222",
906        ])
907        .args;
908
909        assert_eq!(args.required_block_hashes.len(), 2);
910        // First hash without block number (should default to 0)
911        assert_eq!(args.required_block_hashes[0].number, 0);
912        assert_eq!(
913            args.required_block_hashes[0].hash.to_string(),
914            "0x1111111111111111111111111111111111111111111111111111111111111111"
915        );
916        // Second with block number=hash format
917        assert_eq!(args.required_block_hashes[1].number, 23115201);
918        assert_eq!(
919            args.required_block_hashes[1].hash.to_string(),
920            "0x2222222222222222222222222222222222222222222222222222222222222222"
921        );
922    }
923
924    #[test]
925    fn parse_empty_required_block_hashes() {
926        let args = CommandParser::<NetworkArgs>::parse_from(["reth"]).args;
927        assert!(args.required_block_hashes.is_empty());
928    }
929
930    #[test]
931    fn test_parse_block_num_hash() {
932        // Test hash only format
933        let result = parse_block_num_hash(
934            "0x1111111111111111111111111111111111111111111111111111111111111111",
935        );
936        assert!(result.is_ok());
937        assert_eq!(result.unwrap().number, 0);
938
939        // Test block_number=hash format
940        let result = parse_block_num_hash(
941            "23115201=0x2222222222222222222222222222222222222222222222222222222222222222",
942        );
943        assert!(result.is_ok());
944        assert_eq!(result.unwrap().number, 23115201);
945
946        // Test invalid formats
947        assert!(parse_block_num_hash("invalid").is_err());
948        assert!(parse_block_num_hash(
949            "abc=0x1111111111111111111111111111111111111111111111111111111111111111"
950        )
951        .is_err());
952    }
953
954    #[test]
955    fn parse_p2p_secret_key_hex() {
956        let hex = "4c0883a69102937d6231471b5dbb6204fe512961708279f8c5c58b3b9c4e8b8f";
957        let args =
958            CommandParser::<NetworkArgs>::parse_from(["reth", "--p2p-secret-key-hex", hex]).args;
959
960        let expected: B256 = hex.parse().unwrap();
961        assert_eq!(args.p2p_secret_key_hex, Some(expected));
962        assert_eq!(args.p2p_secret_key, None);
963    }
964
965    #[test]
966    fn parse_p2p_secret_key_hex_with_0x_prefix() {
967        let hex = "0x4c0883a69102937d6231471b5dbb6204fe512961708279f8c5c58b3b9c4e8b8f";
968        let args =
969            CommandParser::<NetworkArgs>::parse_from(["reth", "--p2p-secret-key-hex", hex]).args;
970
971        let expected: B256 = hex.parse().unwrap();
972        assert_eq!(args.p2p_secret_key_hex, Some(expected));
973        assert_eq!(args.p2p_secret_key, None);
974    }
975
976    #[test]
977    fn test_p2p_secret_key_and_hex_are_mutually_exclusive() {
978        let result = CommandParser::<NetworkArgs>::try_parse_from([
979            "reth",
980            "--p2p-secret-key",
981            "/path/to/key",
982            "--p2p-secret-key-hex",
983            "4c0883a69102937d6231471b5dbb6204fe512961708279f8c5c58b3b9c4e8b8f",
984        ]);
985
986        assert!(result.is_err());
987    }
988
989    #[test]
990    fn test_secret_key_method_with_hex() {
991        let hex = "4c0883a69102937d6231471b5dbb6204fe512961708279f8c5c58b3b9c4e8b8f";
992        let args =
993            CommandParser::<NetworkArgs>::parse_from(["reth", "--p2p-secret-key-hex", hex]).args;
994
995        let temp_dir = std::env::temp_dir();
996        let default_path = temp_dir.join("default_key");
997        let secret_key = args.secret_key(default_path).unwrap();
998
999        // Verify the secret key matches the hex input
1000        assert_eq!(alloy_primitives::hex::encode(secret_key.secret_bytes()), hex);
1001    }
1002
1003    #[test]
1004    fn parse_netrestrict_single_network() {
1005        let args =
1006            CommandParser::<NetworkArgs>::parse_from(["reth", "--netrestrict", "192.168.0.0/16"])
1007                .args;
1008
1009        assert_eq!(args.netrestrict, Some("192.168.0.0/16".to_string()));
1010
1011        let ip_filter = args.ip_filter().unwrap();
1012        assert!(ip_filter.has_restrictions());
1013        assert!(ip_filter.is_allowed(&"192.168.1.1".parse().unwrap()));
1014        assert!(!ip_filter.is_allowed(&"10.0.0.1".parse().unwrap()));
1015    }
1016
1017    #[test]
1018    fn parse_netrestrict_multiple_networks() {
1019        let args = CommandParser::<NetworkArgs>::parse_from([
1020            "reth",
1021            "--netrestrict",
1022            "192.168.0.0/16,10.0.0.0/8",
1023        ])
1024        .args;
1025
1026        assert_eq!(args.netrestrict, Some("192.168.0.0/16,10.0.0.0/8".to_string()));
1027
1028        let ip_filter = args.ip_filter().unwrap();
1029        assert!(ip_filter.has_restrictions());
1030        assert!(ip_filter.is_allowed(&"192.168.1.1".parse().unwrap()));
1031        assert!(ip_filter.is_allowed(&"10.5.10.20".parse().unwrap()));
1032        assert!(!ip_filter.is_allowed(&"172.16.0.1".parse().unwrap()));
1033    }
1034
1035    #[test]
1036    fn parse_netrestrict_ipv6() {
1037        let args =
1038            CommandParser::<NetworkArgs>::parse_from(["reth", "--netrestrict", "2001:db8::/32"])
1039                .args;
1040
1041        let ip_filter = args.ip_filter().unwrap();
1042        assert!(ip_filter.has_restrictions());
1043        assert!(ip_filter.is_allowed(&"2001:db8::1".parse().unwrap()));
1044        assert!(!ip_filter.is_allowed(&"2001:db9::1".parse().unwrap()));
1045    }
1046
1047    #[test]
1048    fn netrestrict_not_set() {
1049        let args = CommandParser::<NetworkArgs>::parse_from(["reth"]).args;
1050        assert_eq!(args.netrestrict, None);
1051
1052        let ip_filter = args.ip_filter().unwrap();
1053        assert!(!ip_filter.has_restrictions());
1054        assert!(ip_filter.is_allowed(&"192.168.1.1".parse().unwrap()));
1055        assert!(ip_filter.is_allowed(&"10.0.0.1".parse().unwrap()));
1056    }
1057
1058    #[test]
1059    fn netrestrict_invalid_cidr() {
1060        let args =
1061            CommandParser::<NetworkArgs>::parse_from(["reth", "--netrestrict", "invalid-cidr"])
1062                .args;
1063
1064        assert!(args.ip_filter().is_err());
1065    }
1066
1067    #[test]
1068    fn network_config_preserves_basic_nodes_from_peers_file() {
1069        let enode = "enode://6f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@10.3.58.6:30303?discport=30301";
1070        let unique = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos();
1071
1072        let peers_file = std::env::temp_dir().join(format!("reth_peers_test_{}.json", unique));
1073        fs::write(&peers_file, format!("[\"{}\"]", enode)).expect("write peers file");
1074
1075        // Build NetworkArgs with peers_file set and no_persist_peers=false
1076        let args = NetworkArgs {
1077            peers_file: Some(peers_file.clone()),
1078            no_persist_peers: false,
1079            ..Default::default()
1080        };
1081
1082        // Build the network config using a deterministic secret key
1083        let secret_key = SecretKey::from_byte_array(&[1u8; 32]).unwrap();
1084        let builder = args.network_config::<reth_network::EthNetworkPrimitives>(
1085            &Config::default(),
1086            MAINNET.clone(),
1087            secret_key,
1088            peers_file.clone(),
1089        );
1090
1091        let net_cfg = builder.build_with_noop_provider(MAINNET.clone());
1092
1093        // Assert basic_nodes contains our node
1094        let node: NodeRecord = enode.parse().unwrap();
1095        assert!(net_cfg.peers_config.basic_nodes.contains(&node));
1096
1097        // Cleanup
1098        let _ = fs::remove_file(&peers_file);
1099    }
1100}