referrerpolicy=no-referrer-when-downgrade

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