sc_cli/params/
network_params.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19use crate::{
20	arg_enums::{NetworkBackendType, SyncMode},
21	params::node_key_params::NodeKeyParams,
22};
23use clap::Args;
24use sc_network::{
25	config::{
26		NetworkConfiguration, NodeKeyConfig, NonReservedPeerMode, SetConfig, TransportConfig,
27	},
28	multiaddr::Protocol,
29};
30use sc_service::{
31	config::{Multiaddr, MultiaddrWithPeerId},
32	ChainSpec, ChainType,
33};
34use std::{borrow::Cow, num::NonZeroUsize, path::PathBuf};
35
36/// Parameters used to create the network configuration.
37#[derive(Debug, Clone, Args)]
38pub struct NetworkParams {
39	/// Specify a list of bootnodes.
40	#[arg(long, value_name = "ADDR", num_args = 1..)]
41	pub bootnodes: Vec<MultiaddrWithPeerId>,
42
43	/// Specify a list of reserved node addresses.
44	#[arg(long, value_name = "ADDR", num_args = 1..)]
45	pub reserved_nodes: Vec<MultiaddrWithPeerId>,
46
47	/// Whether to only synchronize the chain with reserved nodes.
48	///
49	/// Also disables automatic peer discovery.
50	/// TCP connections might still be established with non-reserved nodes.
51	/// In particular, if you are a validator your node might still connect to other
52	/// validator nodes and collator nodes regardless of whether they are defined as
53	/// reserved nodes.
54	#[arg(long)]
55	pub reserved_only: bool,
56
57	/// Public address that other nodes will use to connect to this node.
58	///
59	/// This can be used if there's a proxy in front of this node.
60	#[arg(long, value_name = "PUBLIC_ADDR", num_args = 1..)]
61	pub public_addr: Vec<Multiaddr>,
62
63	/// Listen on this multiaddress.
64	///
65	/// By default:
66	/// If `--validator` is passed: `/ip4/0.0.0.0/tcp/<port>` and `/ip6/[::]/tcp/<port>`.
67	/// Otherwise: `/ip4/0.0.0.0/tcp/<port>/ws` and `/ip6/[::]/tcp/<port>/ws`.
68	#[arg(long, value_name = "LISTEN_ADDR", num_args = 1..)]
69	pub listen_addr: Vec<Multiaddr>,
70
71	/// Specify p2p protocol TCP port.
72	#[arg(long, value_name = "PORT", conflicts_with_all = &[ "listen_addr" ])]
73	pub port: Option<u16>,
74
75	/// Always forbid connecting to private IPv4/IPv6 addresses.
76	///
77	/// The option doesn't apply to addresses passed with `--reserved-nodes` or
78	/// `--bootnodes`. Enabled by default for chains marked as "live" in their chain
79	/// specifications.
80	///
81	/// Address allocation for private networks is specified by
82	/// [RFC1918](https://tools.ietf.org/html/rfc1918)).
83	#[arg(long, alias = "no-private-ipv4", conflicts_with_all = &["allow_private_ip"])]
84	pub no_private_ip: bool,
85
86	/// Always accept connecting to private IPv4/IPv6 addresses.
87	///
88	/// Enabled by default for chains marked as "local" in their chain specifications,
89	/// or when `--dev` is passed.
90	///
91	/// Address allocation for private networks is specified by
92	/// [RFC1918](https://tools.ietf.org/html/rfc1918)).
93	#[arg(long, alias = "allow-private-ipv4", conflicts_with_all = &["no_private_ip"])]
94	pub allow_private_ip: bool,
95
96	/// Number of outgoing connections we're trying to maintain.
97	#[arg(long, value_name = "COUNT", default_value_t = 8)]
98	pub out_peers: u32,
99
100	/// Maximum number of inbound full nodes peers.
101	#[arg(long, value_name = "COUNT", default_value_t = 32)]
102	pub in_peers: u32,
103
104	/// Maximum number of inbound light nodes peers.
105	#[arg(long, value_name = "COUNT", default_value_t = 100)]
106	pub in_peers_light: u32,
107
108	/// Disable mDNS discovery (default: true).
109	///
110	/// By default, the network will use mDNS to discover other nodes on the
111	/// local network. This disables it. Automatically implied when using --dev.
112	#[arg(long)]
113	pub no_mdns: bool,
114
115	/// Maximum number of peers from which to ask for the same blocks in parallel.
116	///
117	/// This allows downloading announced blocks from multiple peers.
118	/// Decrease to save traffic and risk increased latency.
119	#[arg(long, value_name = "COUNT", default_value_t = 5)]
120	pub max_parallel_downloads: u32,
121
122	#[allow(missing_docs)]
123	#[clap(flatten)]
124	pub node_key_params: NodeKeyParams,
125
126	/// Enable peer discovery on local networks.
127	///
128	/// By default this option is `true` for `--dev` or when the chain type is
129	/// `Local`/`Development` and false otherwise.
130	#[arg(long)]
131	pub discover_local: bool,
132
133	/// Require iterative Kademlia DHT queries to use disjoint paths.
134	///
135	/// Disjoint paths increase resiliency in the presence of potentially adversarial nodes.
136	///
137	/// See the S/Kademlia paper for more information on the high level design as well as its
138	/// security improvements.
139	#[arg(long)]
140	pub kademlia_disjoint_query_paths: bool,
141
142	/// Kademlia replication factor.
143	///
144	/// Determines to how many closest peers a record is replicated to.
145	///
146	/// Discovery mechanism requires successful replication to all
147	/// `kademlia_replication_factor` peers to consider record successfully put.
148	#[arg(long, default_value = "20")]
149	pub kademlia_replication_factor: NonZeroUsize,
150
151	/// Join the IPFS network and serve transactions over bitswap protocol.
152	#[arg(long)]
153	pub ipfs_server: bool,
154
155	/// Blockchain syncing mode.
156	#[arg(
157		long,
158		value_enum,
159		value_name = "SYNC_MODE",
160		default_value_t = SyncMode::Full,
161		ignore_case = true,
162		verbatim_doc_comment
163	)]
164	pub sync: SyncMode,
165
166	/// Maximum number of blocks per request.
167	///
168	/// Try reducing this number from the default value if you have a slow network connection
169	/// and observe block requests timing out.
170	#[arg(long, value_name = "COUNT", default_value_t = 64)]
171	pub max_blocks_per_request: u32,
172
173	/// Network backend used for P2P networking.
174	///
175	/// litep2p network backend is considered experimental and isn't as stable as the libp2p
176	/// network backend.
177	#[arg(
178		long,
179		value_enum,
180		value_name = "NETWORK_BACKEND",
181		default_value_t = NetworkBackendType::Libp2p,
182		ignore_case = true,
183		verbatim_doc_comment
184	)]
185	pub network_backend: NetworkBackendType,
186}
187
188impl NetworkParams {
189	/// Fill the given `NetworkConfiguration` by looking at the cli parameters.
190	pub fn network_config(
191		&self,
192		chain_spec: &Box<dyn ChainSpec>,
193		is_dev: bool,
194		is_validator: bool,
195		net_config_path: Option<PathBuf>,
196		client_id: &str,
197		node_name: &str,
198		node_key: NodeKeyConfig,
199		default_listen_port: u16,
200	) -> NetworkConfiguration {
201		let port = self.port.unwrap_or(default_listen_port);
202
203		let listen_addresses = if self.listen_addr.is_empty() {
204			if is_validator || is_dev {
205				vec![
206					Multiaddr::empty()
207						.with(Protocol::Ip6([0, 0, 0, 0, 0, 0, 0, 0].into()))
208						.with(Protocol::Tcp(port)),
209					Multiaddr::empty()
210						.with(Protocol::Ip4([0, 0, 0, 0].into()))
211						.with(Protocol::Tcp(port)),
212				]
213			} else {
214				vec![
215					Multiaddr::empty()
216						.with(Protocol::Ip6([0, 0, 0, 0, 0, 0, 0, 0].into()))
217						.with(Protocol::Tcp(port))
218						.with(Protocol::Ws(Cow::Borrowed("/"))),
219					Multiaddr::empty()
220						.with(Protocol::Ip4([0, 0, 0, 0].into()))
221						.with(Protocol::Tcp(port))
222						.with(Protocol::Ws(Cow::Borrowed("/"))),
223				]
224			}
225		} else {
226			self.listen_addr.clone()
227		};
228
229		let public_addresses = self.public_addr.clone();
230
231		let mut boot_nodes = chain_spec.boot_nodes().to_vec();
232		boot_nodes.extend(self.bootnodes.clone());
233
234		let chain_type = chain_spec.chain_type();
235		// Activate if the user explicitly requested local discovery, `--dev` is given or the
236		// chain type is `Local`/`Development`
237		let allow_non_globals_in_dht =
238			self.discover_local ||
239				is_dev || matches!(chain_type, ChainType::Local | ChainType::Development);
240
241		let allow_private_ip = match (self.allow_private_ip, self.no_private_ip) {
242			(true, true) => unreachable!("`*_private_ip` flags are mutually exclusive; qed"),
243			(true, false) => true,
244			(false, true) => false,
245			(false, false) =>
246				is_dev || matches!(chain_type, ChainType::Local | ChainType::Development),
247		};
248
249		NetworkConfiguration {
250			boot_nodes,
251			net_config_path,
252			default_peers_set: SetConfig {
253				in_peers: self.in_peers + self.in_peers_light,
254				out_peers: self.out_peers,
255				reserved_nodes: self.reserved_nodes.clone(),
256				non_reserved_mode: if self.reserved_only {
257					NonReservedPeerMode::Deny
258				} else {
259					NonReservedPeerMode::Accept
260				},
261			},
262			default_peers_set_num_full: self.in_peers + self.out_peers,
263			listen_addresses,
264			public_addresses,
265			node_key,
266			node_name: node_name.to_string(),
267			client_version: client_id.to_string(),
268			transport: TransportConfig::Normal {
269				enable_mdns: !is_dev && !self.no_mdns,
270				allow_private_ip,
271			},
272			max_parallel_downloads: self.max_parallel_downloads,
273			max_blocks_per_request: self.max_blocks_per_request,
274			enable_dht_random_walk: !self.reserved_only,
275			allow_non_globals_in_dht,
276			kademlia_disjoint_query_paths: self.kademlia_disjoint_query_paths,
277			kademlia_replication_factor: self.kademlia_replication_factor,
278			yamux_window_size: None,
279			ipfs_server: self.ipfs_server,
280			sync_mode: self.sync.into(),
281			network_backend: self.network_backend.into(),
282		}
283	}
284}
285
286#[cfg(test)]
287mod tests {
288	use super::*;
289	use clap::Parser;
290
291	#[derive(Parser)]
292	struct Cli {
293		#[clap(flatten)]
294		network_params: NetworkParams,
295	}
296
297	#[test]
298	fn reserved_nodes_multiple_values_and_occurrences() {
299		let params = Cli::try_parse_from([
300			"",
301			"--reserved-nodes",
302			"/ip4/0.0.0.0/tcp/501/p2p/12D3KooWEBo1HUPQJwiBmM5kSeg4XgiVxEArArQdDarYEsGxMfbS",
303			"/ip4/0.0.0.0/tcp/502/p2p/12D3KooWEBo1HUPQJwiBmM5kSeg4XgiVxEArArQdDarYEsGxMfbS",
304			"--reserved-nodes",
305			"/ip4/0.0.0.0/tcp/503/p2p/12D3KooWEBo1HUPQJwiBmM5kSeg4XgiVxEArArQdDarYEsGxMfbS",
306		])
307		.expect("Parses network params");
308
309		let expected = vec![
310			MultiaddrWithPeerId::try_from(
311				"/ip4/0.0.0.0/tcp/501/p2p/12D3KooWEBo1HUPQJwiBmM5kSeg4XgiVxEArArQdDarYEsGxMfbS"
312					.to_string(),
313			)
314			.unwrap(),
315			MultiaddrWithPeerId::try_from(
316				"/ip4/0.0.0.0/tcp/502/p2p/12D3KooWEBo1HUPQJwiBmM5kSeg4XgiVxEArArQdDarYEsGxMfbS"
317					.to_string(),
318			)
319			.unwrap(),
320			MultiaddrWithPeerId::try_from(
321				"/ip4/0.0.0.0/tcp/503/p2p/12D3KooWEBo1HUPQJwiBmM5kSeg4XgiVxEArArQdDarYEsGxMfbS"
322					.to_string(),
323			)
324			.unwrap(),
325		];
326
327		assert_eq!(expected, params.network_params.reserved_nodes);
328	}
329
330	#[test]
331	fn sync_ignores_case() {
332		let params = Cli::try_parse_from(["", "--sync", "wArP"]).expect("Parses network params");
333
334		assert_eq!(SyncMode::Warp, params.network_params.sync);
335	}
336}