Skip to main content

sc_network/
config.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
19//! Configuration of the networking layer.
20//!
21//! The [`Params`] struct is the struct that must be passed in order to initialize the networking.
22//! See the documentation of [`Params`].
23
24pub use crate::{
25	discovery::DEFAULT_KADEMLIA_REPLICATION_FACTOR,
26	peer_store::PeerStoreProvider,
27	protocol::{notification_service, NotificationsSink, ProtocolHandlePair},
28	request_responses::{
29		IncomingRequest, OutgoingResponse, ProtocolConfig as RequestResponseConfig,
30	},
31	service::{
32		metrics::NotificationMetrics,
33		traits::{NotificationConfig, NotificationService, PeerStore},
34	},
35	types::ProtocolName,
36};
37
38pub use sc_network_types::{build_multiaddr, ed25519};
39use sc_network_types::{
40	multiaddr::{self, Multiaddr},
41	PeerId,
42};
43
44use crate::{
45	service::{ensure_addresses_consistent_with_transport, traits::NetworkBackend},
46	webrtc,
47};
48use codec::Encode;
49use prometheus_endpoint::Registry;
50use zeroize::Zeroize;
51
52pub use sc_network_common::{
53	role::{Role, Roles},
54	sync::SyncMode,
55	ExHashT,
56};
57
58use sp_runtime::traits::Block as BlockT;
59
60use std::{
61	error::Error,
62	fmt, fs,
63	future::Future,
64	io::{self, Write},
65	iter,
66	net::Ipv4Addr,
67	num::NonZeroUsize,
68	path::{Path, PathBuf},
69	pin::Pin,
70	str::{self, FromStr},
71	sync::Arc,
72	time::Duration,
73};
74
75/// Default timeout for idle connections of 10 seconds is good enough for most networks.
76/// It doesn't make sense to expose it as a CLI parameter on individual nodes, but customizations
77/// are possible in custom nodes through [`NetworkConfiguration`].
78pub const DEFAULT_IDLE_CONNECTION_TIMEOUT: Duration = Duration::from_secs(10);
79
80/// Maximum number of locally kept Kademlia provider keys.
81///
82/// 10000 keys is enough for a testnet with fast runtime (1-minute epoch) and 13 parachains.
83pub const KADEMLIA_MAX_PROVIDER_KEYS: usize = 10000;
84
85/// Time to keep Kademlia content provider records.
86///
87/// 10 h is enough time to keep the parachain bootnode record for two 4-hour epochs.
88pub const KADEMLIA_PROVIDER_RECORD_TTL: Duration = Duration::from_secs(10 * 3600);
89
90/// Interval of republishing Kademlia provider records.
91///
92/// 3.5 h means we refresh next epoch provider record 30 minutes before next 4-hour epoch comes.
93pub const KADEMLIA_PROVIDER_REPUBLISH_INTERVAL: Duration = Duration::from_secs(12600);
94
95/// Protocol name prefix, transmitted on the wire for legacy protocol names.
96/// I.e., `dot` in `/dot/sync/2`. Should be unique for each chain. Always UTF-8.
97/// Deprecated in favour of genesis hash & fork ID based protocol names.
98#[derive(Clone, PartialEq, Eq, Hash)]
99pub struct ProtocolId(smallvec::SmallVec<[u8; 6]>);
100
101impl<'a> From<&'a str> for ProtocolId {
102	fn from(bytes: &'a str) -> ProtocolId {
103		Self(bytes.as_bytes().into())
104	}
105}
106
107impl AsRef<str> for ProtocolId {
108	fn as_ref(&self) -> &str {
109		str::from_utf8(&self.0[..])
110			.expect("the only way to build a ProtocolId is through a UTF-8 String; qed")
111	}
112}
113
114impl fmt::Debug for ProtocolId {
115	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
116		fmt::Debug::fmt(self.as_ref(), f)
117	}
118}
119
120/// Parses a string address and splits it into Multiaddress and PeerId, if
121/// valid.
122///
123/// # Example
124///
125/// ```
126/// # use sc_network_types::{multiaddr::Multiaddr, PeerId};
127/// use sc_network::config::parse_str_addr;
128/// let (peer_id, addr) = parse_str_addr(
129/// 	"/ip4/198.51.100.19/tcp/30333/p2p/QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV"
130/// ).unwrap();
131/// assert_eq!(peer_id, "QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV".parse::<PeerId>().unwrap().into());
132/// assert_eq!(addr, "/ip4/198.51.100.19/tcp/30333".parse::<Multiaddr>().unwrap());
133/// ```
134pub fn parse_str_addr(addr_str: &str) -> Result<(PeerId, Multiaddr), ParseErr> {
135	let addr: Multiaddr = addr_str.parse()?;
136	parse_addr(addr)
137}
138
139/// Splits a Multiaddress into a Multiaddress and PeerId.
140pub fn parse_addr(mut addr: Multiaddr) -> Result<(PeerId, Multiaddr), ParseErr> {
141	let multihash = match addr.pop() {
142		Some(multiaddr::Protocol::P2p(multihash)) => multihash,
143		_ => return Err(ParseErr::PeerIdMissing),
144	};
145	let peer_id = PeerId::from_multihash(multihash).map_err(|_| ParseErr::InvalidPeerId)?;
146
147	Ok((peer_id, addr))
148}
149
150/// Address of a node, including its identity.
151///
152/// This struct represents a decoded version of a multiaddress that ends with `/p2p/<peerid>`.
153///
154/// # Example
155///
156/// ```
157/// # use sc_network_types::{multiaddr::Multiaddr, PeerId};
158/// use sc_network::config::MultiaddrWithPeerId;
159/// let addr: MultiaddrWithPeerId =
160/// 	"/ip4/198.51.100.19/tcp/30333/p2p/QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV".parse().unwrap();
161/// assert_eq!(addr.peer_id.to_base58(), "QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV");
162/// assert_eq!(addr.multiaddr.to_string(), "/ip4/198.51.100.19/tcp/30333");
163/// ```
164#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
165#[serde(try_from = "String", into = "String")]
166pub struct MultiaddrWithPeerId {
167	/// Address of the node.
168	pub multiaddr: Multiaddr,
169	/// Its identity.
170	pub peer_id: PeerId,
171}
172
173impl MultiaddrWithPeerId {
174	/// Concatenates the multiaddress and peer ID into one multiaddress containing both.
175	pub fn concat(&self) -> Multiaddr {
176		let mut addr = self.multiaddr.clone();
177		// Ensure that the address not already contains the `p2p` protocol.
178		if matches!(addr.iter().last(), Some(multiaddr::Protocol::P2p(_))) {
179			addr.pop();
180		}
181		addr.with(multiaddr::Protocol::P2p(From::from(self.peer_id)))
182	}
183}
184
185impl fmt::Display for MultiaddrWithPeerId {
186	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
187		fmt::Display::fmt(&self.concat(), f)
188	}
189}
190
191impl FromStr for MultiaddrWithPeerId {
192	type Err = ParseErr;
193
194	fn from_str(s: &str) -> Result<Self, Self::Err> {
195		let (peer_id, multiaddr) = parse_str_addr(s)?;
196		Ok(Self { peer_id, multiaddr })
197	}
198}
199
200impl From<MultiaddrWithPeerId> for String {
201	fn from(ma: MultiaddrWithPeerId) -> String {
202		format!("{}", ma)
203	}
204}
205
206impl TryFrom<String> for MultiaddrWithPeerId {
207	type Error = ParseErr;
208	fn try_from(string: String) -> Result<Self, Self::Error> {
209		string.parse()
210	}
211}
212
213/// Error that can be generated by `parse_str_addr`.
214#[derive(Debug)]
215pub enum ParseErr {
216	/// Error while parsing the multiaddress.
217	MultiaddrParse(multiaddr::ParseError),
218	/// Multihash of the peer ID is invalid.
219	InvalidPeerId,
220	/// The peer ID is missing from the address.
221	PeerIdMissing,
222}
223
224impl fmt::Display for ParseErr {
225	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226		match self {
227			Self::MultiaddrParse(err) => write!(f, "{}", err),
228			Self::InvalidPeerId => write!(f, "Peer id at the end of the address is invalid"),
229			Self::PeerIdMissing => write!(f, "Peer id is missing from the address"),
230		}
231	}
232}
233
234impl std::error::Error for ParseErr {
235	fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
236		match self {
237			Self::MultiaddrParse(err) => Some(err),
238			Self::InvalidPeerId => None,
239			Self::PeerIdMissing => None,
240		}
241	}
242}
243
244impl From<multiaddr::ParseError> for ParseErr {
245	fn from(err: multiaddr::ParseError) -> ParseErr {
246		Self::MultiaddrParse(err)
247	}
248}
249
250/// Custom handshake for the notification protocol
251#[derive(Debug, Clone)]
252pub struct NotificationHandshake(Vec<u8>);
253
254impl NotificationHandshake {
255	/// Create new `NotificationHandshake` from an object that implements `Encode`
256	pub fn new<H: Encode>(handshake: H) -> Self {
257		Self(handshake.encode())
258	}
259
260	/// Create new `NotificationHandshake` from raw bytes
261	pub fn from_bytes(bytes: Vec<u8>) -> Self {
262		Self(bytes)
263	}
264}
265
266impl std::ops::Deref for NotificationHandshake {
267	type Target = Vec<u8>;
268
269	fn deref(&self) -> &Self::Target {
270		&self.0
271	}
272}
273
274/// Configuration for the transport layer.
275#[derive(Clone, Debug)]
276pub enum TransportConfig {
277	/// Normal transport mode.
278	Normal {
279		/// If true, the network will use mDNS to discover other libp2p nodes on the local network
280		/// and connect to them if they support the same chain.
281		enable_mdns: bool,
282
283		/// If true, allow connecting to private IPv4/IPv6 addresses (as defined in
284		/// [RFC1918](https://tools.ietf.org/html/rfc1918)). Irrelevant for addresses that have
285		/// been passed in `::sc_network::config::NetworkConfiguration::boot_nodes`.
286		allow_private_ip: bool,
287	},
288
289	/// Only allow connections within the same process.
290	/// Only addresses of the form `/memory/...` will be supported.
291	MemoryOnly,
292}
293
294/// The policy for connections to non-reserved peers.
295#[derive(Clone, Debug, PartialEq, Eq)]
296pub enum NonReservedPeerMode {
297	/// Accept them. This is the default.
298	Accept,
299	/// Deny them.
300	Deny,
301}
302
303impl NonReservedPeerMode {
304	/// Attempt to parse the peer mode from a string.
305	pub fn parse(s: &str) -> Option<Self> {
306		match s {
307			"accept" => Some(Self::Accept),
308			"deny" => Some(Self::Deny),
309			_ => None,
310		}
311	}
312
313	/// If we are in "reserved-only" peer mode.
314	pub fn is_reserved_only(&self) -> bool {
315		matches!(self, NonReservedPeerMode::Deny)
316	}
317}
318
319/// The configuration of a node's secret key, describing the type of key
320/// and how it is obtained. A node's identity keypair is the result of
321/// the evaluation of the node key configuration.
322#[derive(Clone, Debug)]
323pub enum NodeKeyConfig {
324	/// A Ed25519 secret key configuration.
325	Ed25519(Secret<ed25519::SecretKey>),
326}
327
328impl Default for NodeKeyConfig {
329	fn default() -> NodeKeyConfig {
330		Self::Ed25519(Secret::New)
331	}
332}
333
334/// The options for obtaining a Ed25519 secret key.
335pub type Ed25519Secret = Secret<ed25519::SecretKey>;
336
337/// The configuration options for obtaining a secret key `K`.
338#[derive(Clone)]
339pub enum Secret<K> {
340	/// Use the given secret key `K`.
341	Input(K),
342	/// Read the secret key from a file. If the file does not exist,
343	/// it is created with a newly generated secret key `K`. The format
344	/// of the file is determined by `K`:
345	///
346	///   * `ed25519::SecretKey`: An unencoded 32 bytes Ed25519 secret key.
347	File(PathBuf),
348	/// Always generate a new secret key `K`.
349	New,
350}
351
352impl<K> fmt::Debug for Secret<K> {
353	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
354		match self {
355			Self::Input(_) => f.debug_tuple("Secret::Input").finish(),
356			Self::File(path) => f.debug_tuple("Secret::File").field(path).finish(),
357			Self::New => f.debug_tuple("Secret::New").finish(),
358		}
359	}
360}
361
362impl NodeKeyConfig {
363	/// Evaluate a `NodeKeyConfig` to obtain an identity `Keypair`:
364	///
365	///  * If the secret is configured as input, the corresponding keypair is returned.
366	///
367	///  * If the secret is configured as a file, it is read from that file, if it exists. Otherwise
368	///    a new secret is generated and stored. In either case, the keypair obtained from the
369	///    secret is returned.
370	///
371	///  * If the secret is configured to be new, it is generated and the corresponding keypair is
372	///    returned.
373	pub fn into_keypair(self) -> io::Result<ed25519::Keypair> {
374		use NodeKeyConfig::*;
375		match self {
376			Ed25519(Secret::New) => Ok(ed25519::Keypair::generate()),
377
378			Ed25519(Secret::Input(k)) => Ok(ed25519::Keypair::from(k).into()),
379
380			Ed25519(Secret::File(f)) => get_secret(
381				f,
382				|mut b| match String::from_utf8(b.to_vec()).ok().and_then(|s| {
383					if s.len() == 64 {
384						array_bytes::hex2bytes(&s).ok()
385					} else {
386						None
387					}
388				}) {
389					Some(s) => ed25519::SecretKey::try_from_bytes(s),
390					_ => ed25519::SecretKey::try_from_bytes(&mut b),
391				},
392				ed25519::SecretKey::generate,
393				|b| b.as_ref().to_vec(),
394			)
395			.map(ed25519::Keypair::from),
396		}
397	}
398}
399
400/// Load a secret key from a file, if it exists, or generate a
401/// new secret key and write it to that file. In either case,
402/// the secret key is returned.
403fn get_secret<P, F, G, E, W, K>(file: P, parse: F, generate: G, serialize: W) -> io::Result<K>
404where
405	P: AsRef<Path>,
406	F: for<'r> FnOnce(&'r mut [u8]) -> Result<K, E>,
407	G: FnOnce() -> K,
408	E: Error + Send + Sync + 'static,
409	W: Fn(&K) -> Vec<u8>,
410{
411	std::fs::read(&file)
412		.and_then(|mut sk_bytes| {
413			parse(&mut sk_bytes).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
414		})
415		.or_else(|e| {
416			if e.kind() == io::ErrorKind::NotFound {
417				file.as_ref().parent().map_or(Ok(()), fs::create_dir_all)?;
418				let sk = generate();
419				let mut sk_vec = serialize(&sk);
420				write_secret_file(file, &sk_vec)?;
421				sk_vec.zeroize();
422				Ok(sk)
423			} else {
424				Err(e)
425			}
426		})
427}
428
429/// Write secret bytes to a file.
430pub(super) fn write_secret_file<P>(path: P, sk_bytes: &[u8]) -> io::Result<()>
431where
432	P: AsRef<Path>,
433{
434	let mut file = open_secret_file(&path)?;
435	file.write_all(sk_bytes)
436}
437
438/// Opens a file containing a secret key in write mode.
439#[cfg(unix)]
440fn open_secret_file<P>(path: P) -> io::Result<fs::File>
441where
442	P: AsRef<Path>,
443{
444	use std::os::unix::fs::OpenOptionsExt;
445	fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(path)
446}
447
448/// Opens a file containing a secret key in write mode.
449#[cfg(not(unix))]
450fn open_secret_file<P>(path: P) -> Result<fs::File, io::Error>
451where
452	P: AsRef<Path>,
453{
454	fs::OpenOptions::new().write(true).create_new(true).open(path)
455}
456
457/// Configuration for a set of nodes.
458#[derive(Clone, Debug)]
459pub struct SetConfig {
460	/// Maximum allowed number of incoming substreams related to this set.
461	pub in_peers: u32,
462
463	/// Number of outgoing substreams related to this set that we're trying to maintain.
464	pub out_peers: u32,
465
466	/// List of reserved node addresses.
467	pub reserved_nodes: Vec<MultiaddrWithPeerId>,
468
469	/// Whether nodes that aren't in [`SetConfig::reserved_nodes`] are accepted or automatically
470	/// refused.
471	pub non_reserved_mode: NonReservedPeerMode,
472}
473
474impl Default for SetConfig {
475	fn default() -> Self {
476		Self {
477			in_peers: 25,
478			out_peers: 75,
479			reserved_nodes: Vec::new(),
480			non_reserved_mode: NonReservedPeerMode::Accept,
481		}
482	}
483}
484
485/// Extension to [`SetConfig`] for sets that aren't the default set.
486///
487/// > **Note**: As new fields might be added in the future, please consider using the `new` method
488/// >			and modifiers instead of creating this struct manually.
489#[derive(Debug)]
490pub struct NonDefaultSetConfig {
491	/// Name of the notifications protocols of this set. A substream on this set will be
492	/// considered established once this protocol is open.
493	///
494	/// > **Note**: This field isn't present for the default set, as this is handled internally
495	/// > by the networking code.
496	protocol_name: ProtocolName,
497
498	/// If the remote reports that it doesn't support the protocol indicated in the
499	/// `notifications_protocol` field, then each of these fallback names will be tried one by
500	/// one.
501	///
502	/// If a fallback is used, it will be reported in
503	/// `sc_network::protocol::event::Event::NotificationStreamOpened::negotiated_fallback`
504	fallback_names: Vec<ProtocolName>,
505
506	/// Handshake of the protocol
507	///
508	/// NOTE: Currently custom handshakes are not fully supported. See issue #5685 for more
509	/// details. This field is temporarily used to allow moving the hardcoded block announcement
510	/// protocol out of `protocol.rs`.
511	handshake: Option<NotificationHandshake>,
512
513	/// Maximum allowed size of single notifications.
514	max_notification_size: u64,
515
516	/// Base configuration.
517	set_config: SetConfig,
518
519	/// Notification handle.
520	///
521	/// Notification handle is created during `NonDefaultSetConfig` creation and its other half,
522	/// `Box<dyn NotificationService>` is given to the protocol created the config and
523	/// `ProtocolHandle` is given to `Notifications` when it initializes itself. This handle allows
524	/// `Notifications ` to communicate with the protocol directly without relaying events through
525	/// `sc-network.`
526	protocol_handle_pair: ProtocolHandlePair,
527}
528
529impl NonDefaultSetConfig {
530	/// Creates a new [`NonDefaultSetConfig`]. Zero slots and accepts only reserved nodes.
531	/// Also returns an object which allows the protocol to communicate with `Notifications`.
532	pub fn new(
533		protocol_name: ProtocolName,
534		fallback_names: Vec<ProtocolName>,
535		max_notification_size: u64,
536		handshake: Option<NotificationHandshake>,
537		set_config: SetConfig,
538	) -> (Self, Box<dyn NotificationService>) {
539		let (protocol_handle_pair, notification_service) =
540			notification_service(protocol_name.clone());
541		(
542			Self {
543				protocol_name,
544				max_notification_size,
545				fallback_names,
546				handshake,
547				set_config,
548				protocol_handle_pair,
549			},
550			notification_service,
551		)
552	}
553
554	/// Get reference to protocol name.
555	pub fn protocol_name(&self) -> &ProtocolName {
556		&self.protocol_name
557	}
558
559	/// Get reference to fallback protocol names.
560	pub fn fallback_names(&self) -> impl Iterator<Item = &ProtocolName> {
561		self.fallback_names.iter()
562	}
563
564	/// Get reference to handshake.
565	pub fn handshake(&self) -> &Option<NotificationHandshake> {
566		&self.handshake
567	}
568
569	/// Get maximum notification size.
570	pub fn max_notification_size(&self) -> u64 {
571		self.max_notification_size
572	}
573
574	/// Get reference to `SetConfig`.
575	pub fn set_config(&self) -> &SetConfig {
576		&self.set_config
577	}
578
579	/// Take `ProtocolHandlePair` from `NonDefaultSetConfig`
580	pub fn take_protocol_handle(self) -> ProtocolHandlePair {
581		self.protocol_handle_pair
582	}
583
584	/// Modifies the configuration to allow non-reserved nodes.
585	pub fn allow_non_reserved(&mut self, in_peers: u32, out_peers: u32) {
586		self.set_config.in_peers = in_peers;
587		self.set_config.out_peers = out_peers;
588		self.set_config.non_reserved_mode = NonReservedPeerMode::Accept;
589	}
590
591	/// Add a node to the list of reserved nodes.
592	pub fn add_reserved(&mut self, peer: MultiaddrWithPeerId) {
593		self.set_config.reserved_nodes.push(peer);
594	}
595
596	/// Add a list of protocol names used for backward compatibility.
597	///
598	/// See the explanations in [`NonDefaultSetConfig::fallback_names`].
599	pub fn add_fallback_names(&mut self, fallback_names: Vec<ProtocolName>) {
600		self.fallback_names.extend(fallback_names);
601	}
602}
603
604impl NotificationConfig for NonDefaultSetConfig {
605	fn set_config(&self) -> &SetConfig {
606		&self.set_config
607	}
608
609	/// Get reference to protocol name.
610	fn protocol_name(&self) -> &ProtocolName {
611		&self.protocol_name
612	}
613}
614
615/// Network service configuration.
616#[derive(Clone, Debug)]
617pub struct NetworkConfiguration {
618	/// Directory path to store network-specific configuration. None means nothing will be saved.
619	pub net_config_path: Option<PathBuf>,
620
621	/// Multiaddresses to listen for incoming connections.
622	pub listen_addresses: Vec<Multiaddr>,
623
624	/// Multiaddresses to advertise. Detected automatically if empty.
625	pub public_addresses: Vec<Multiaddr>,
626
627	/// List of initial node addresses
628	pub boot_nodes: Vec<MultiaddrWithPeerId>,
629
630	/// The node key configuration, which determines the node's network identity keypair.
631	pub node_key: NodeKeyConfig,
632
633	/// Configuration for the default set of nodes used for block syncing and transactions.
634	pub default_peers_set: SetConfig,
635
636	/// Number of substreams to reserve for full nodes for block syncing and transactions.
637	/// Any other slot will be dedicated to light nodes.
638	///
639	/// This value is implicitly capped to `default_set.out_peers + default_set.in_peers`.
640	pub default_peers_set_num_full: u32,
641
642	/// Client identifier. Sent over the wire for debugging purposes.
643	pub client_version: String,
644
645	/// Name of the node. Sent over the wire for debugging purposes.
646	pub node_name: String,
647
648	/// Configuration for the transport layer.
649	pub transport: TransportConfig,
650
651	/// Idle connection timeout.
652	///
653	/// Set by default to [`DEFAULT_IDLE_CONNECTION_TIMEOUT`].
654	pub idle_connection_timeout: Duration,
655
656	/// Maximum number of peers to ask the same blocks in parallel.
657	pub max_parallel_downloads: u32,
658
659	/// Maximum number of blocks per request.
660	pub max_blocks_per_request: u32,
661
662	/// Number of peers that need to be connected before warp sync is started.
663	pub min_peers_to_start_warp_sync: Option<usize>,
664
665	/// Initial syncing mode.
666	pub sync_mode: SyncMode,
667
668	/// True if Kademlia random discovery should be enabled.
669	///
670	/// If true, the node will automatically randomly walk the DHT in order to find new peers.
671	pub enable_dht_random_walk: bool,
672
673	/// Should we insert non-global addresses into the DHT?
674	pub allow_non_globals_in_dht: bool,
675
676	/// Require iterative Kademlia DHT queries to use disjoint paths for increased resiliency in
677	/// the presence of potentially adversarial nodes.
678	pub kademlia_disjoint_query_paths: bool,
679
680	/// Kademlia replication factor determines to how many closest peers a record is replicated to.
681	///
682	/// Discovery mechanism requires successful replication to all
683	/// `kademlia_replication_factor` peers to consider record successfully put.
684	pub kademlia_replication_factor: NonZeroUsize,
685
686	/// Enable serving indexed transaction data using IPFS Bitswap protocol.
687	pub ipfs_server: bool,
688
689	/// List of IPFS bootstrap nodes to register in IPFS DHT as a provider of indexed transaction
690	/// data.
691	///
692	/// If IPFS bootstrap nodes are not provided, this node will only handle direct Bitswap
693	/// requests from peers that already know its address.
694	pub ipfs_bootnodes: Vec<MultiaddrWithPeerId>,
695
696	/// Networking backend used for P2P communication.
697	pub network_backend: NetworkBackendType,
698}
699
700impl NetworkConfiguration {
701	/// Create new default configuration
702	pub fn new<SN: Into<String>, SV: Into<String>>(
703		node_name: SN,
704		client_version: SV,
705		node_key: NodeKeyConfig,
706		net_config_path: Option<PathBuf>,
707	) -> Self {
708		let default_peers_set = SetConfig::default();
709		Self {
710			net_config_path,
711			listen_addresses: Vec::new(),
712			public_addresses: Vec::new(),
713			boot_nodes: Vec::new(),
714			node_key,
715			default_peers_set_num_full: default_peers_set.in_peers + default_peers_set.out_peers,
716			default_peers_set,
717			client_version: client_version.into(),
718			node_name: node_name.into(),
719			transport: TransportConfig::Normal { enable_mdns: false, allow_private_ip: true },
720			idle_connection_timeout: DEFAULT_IDLE_CONNECTION_TIMEOUT,
721			max_parallel_downloads: 5,
722			max_blocks_per_request: 64,
723			min_peers_to_start_warp_sync: None,
724			sync_mode: SyncMode::Full,
725			enable_dht_random_walk: true,
726			allow_non_globals_in_dht: false,
727			kademlia_disjoint_query_paths: false,
728			kademlia_replication_factor: NonZeroUsize::new(DEFAULT_KADEMLIA_REPLICATION_FACTOR)
729				.expect("value is a constant; constant is non-zero; qed."),
730			ipfs_server: false,
731			ipfs_bootnodes: Vec::new(),
732			network_backend: NetworkBackendType::Litep2p,
733		}
734	}
735
736	/// Create new default configuration for localhost-only connection with random port (useful for
737	/// testing)
738	pub fn new_local() -> NetworkConfiguration {
739		let mut config =
740			NetworkConfiguration::new("test-node", "test-client", Default::default(), None);
741
742		config.listen_addresses =
743			vec![iter::once(multiaddr::Protocol::Ip4(Ipv4Addr::new(127, 0, 0, 1)))
744				.chain(iter::once(multiaddr::Protocol::Tcp(0)))
745				.collect()];
746
747		config.allow_non_globals_in_dht = true;
748		config
749	}
750
751	/// Create new default configuration for localhost-only connection with random port (useful for
752	/// testing)
753	pub fn new_memory() -> NetworkConfiguration {
754		let mut config =
755			NetworkConfiguration::new("test-node", "test-client", Default::default(), None);
756
757		config.listen_addresses =
758			vec![iter::once(multiaddr::Protocol::Ip4(Ipv4Addr::new(127, 0, 0, 1)))
759				.chain(iter::once(multiaddr::Protocol::Tcp(0)))
760				.collect()];
761
762		config.allow_non_globals_in_dht = true;
763		config
764	}
765
766	/// Validate this node's `webrtc-direct` addresses and append its WebRTC `/certhash` to the
767	/// public ones.
768	///
769	/// Fails on a `webrtc-direct` address configured for the [`NetworkBackendType::Libp2p`]
770	/// backend, which cannot serve WebRTC, on a public one with no listener behind it, and on any
771	/// of them that is malformed.
772	pub fn validate_and_complete_webrtc_addresses(&mut self) -> Result<(), crate::error::Error> {
773		let has_webrtc_addr = |addrs: &[Multiaddr]| addrs.iter().any(webrtc::is_webrtc_address);
774
775		let listen_webrtc = has_webrtc_addr(&self.listen_addresses);
776		let public_webrtc = has_webrtc_addr(&self.public_addresses);
777
778		// WebRTC is a litep2p-only transport.
779		if matches!(self.network_backend, NetworkBackendType::Libp2p) {
780			if listen_webrtc || public_webrtc {
781				return Err(crate::error::Error::WebRtcNotSupportedByBackend);
782			}
783			return Ok(());
784		}
785
786		match (listen_webrtc, public_webrtc) {
787			// Nothing about this configuration is WebRTC.
788			(false, false) => Ok(()),
789			// An address peers would be told to dial with no listener behind it.
790			// Defaults addresses has already been appended so we are sure there is effectively
791			// no listener behind.
792			(false, true) => Err(crate::error::Error::WebRtcTransportNotConfigured),
793			// The node listens for WebRTC, so it presents a certificate which can be
794			// appended to public addresses.
795			(true, _) => {
796				let keypair = self.node_key.clone().into_keypair()?;
797				// Pin the resolved key, so that each following `into_keypair()` returns
798				// the same secret key.
799				self.node_key = NodeKeyConfig::Ed25519(Secret::Input(keypair.secret()));
800				let certificate = webrtc::derive_certificate(keypair.secret().into())
801					.map_err(crate::error::Error::Litep2p)?;
802				webrtc::validate_and_complete_addresses(
803					&self.listen_addresses,
804					&mut self.public_addresses,
805					certificate.certhash().into(),
806				)
807			},
808		}
809	}
810
811	/// Remove every `webrtc-direct` address of this node.
812	///
813	/// The relay chain side of a collator uses this to drop the WebRTC listeners appended by
814	/// default for a full node. The public WebRTC addresses go with the listeners serving them.
815	/// Dropping one is warned about, as it can only have been configured explicitly.
816	pub fn remove_webrtc_addresses(&mut self) {
817		self.listen_addresses.retain(|address| !webrtc::is_webrtc_address(address));
818		self.public_addresses.retain(|address| {
819			let keep = !webrtc::is_webrtc_address(address);
820			if !keep {
821				log::warn!(
822					target: crate::LOG_TARGET,
823					"removing public WebRTC address {address}: no WebRTC listener on this node",
824				);
825			}
826			keep
827		});
828	}
829}
830
831/// IPFS server configuration.
832pub struct IpfsConfig<Block: BlockT, H: ExHashT, N: NetworkBackend<Block, H>> {
833	/// Network-backend-specific Bitswap configuration.
834	pub bitswap_config: N::BitswapConfig,
835	/// Indexed transactions provider.
836	pub block_provider: Box<dyn crate::IpfsBlockProvider>,
837	/// IPFS bootstrap nodes.
838	pub bootnodes: Vec<MultiaddrWithPeerId>,
839}
840
841/// Network initialization parameters.
842pub struct Params<Block: BlockT, H: ExHashT, N: NetworkBackend<Block, H>> {
843	/// Assigned role for our node (full, light, ...).
844	pub role: Role,
845
846	/// How to spawn background tasks.
847	pub executor: Box<dyn Fn(Pin<Box<dyn Future<Output = ()> + Send>>) + Send + Sync>,
848
849	/// Network layer configuration.
850	pub network_config: FullNetworkConfiguration<Block, H, N>,
851
852	/// Legacy name of the protocol to use on the wire. Should be different for each chain.
853	pub protocol_id: ProtocolId,
854
855	/// Genesis hash of the chain
856	pub genesis_hash: Block::Hash,
857
858	/// Fork ID to distinguish protocols of different hard forks. Part of the standard protocol
859	/// name on the wire.
860	pub fork_id: Option<String>,
861
862	/// Registry for recording prometheus metrics to.
863	pub metrics_registry: Option<Registry>,
864
865	/// Block announce protocol configuration
866	pub block_announce_config: N::NotificationProtocolConfig,
867
868	/// Bitswap configuration, if the server has been enabled.
869	pub ipfs_config: Option<IpfsConfig<Block, H, N>>,
870
871	/// Notification metrics.
872	pub notification_metrics: NotificationMetrics,
873}
874
875/// Full network configuration.
876pub struct FullNetworkConfiguration<B: BlockT + 'static, H: ExHashT, N: NetworkBackend<B, H>> {
877	/// Installed notification protocols.
878	pub(crate) notification_protocols: Vec<N::NotificationProtocolConfig>,
879
880	/// List of request-response protocols that the node supports.
881	pub(crate) request_response_protocols: Vec<N::RequestResponseProtocolConfig>,
882
883	/// Network configuration.
884	pub network_config: NetworkConfiguration,
885
886	/// [`PeerStore`](crate::peer_store::PeerStore),
887	peer_store: Option<N::PeerStore>,
888
889	/// Handle to [`PeerStore`](crate::peer_store::PeerStore).
890	peer_store_handle: Arc<dyn PeerStoreProvider>,
891
892	/// Registry for recording prometheus metrics to.
893	pub metrics_registry: Option<Registry>,
894}
895
896impl<B: BlockT + 'static, H: ExHashT, N: NetworkBackend<B, H>> FullNetworkConfiguration<B, H, N> {
897	/// Create new [`FullNetworkConfiguration`].
898	pub fn new(network_config: &NetworkConfiguration, metrics_registry: Option<Registry>) -> Self {
899		let bootnodes = network_config.boot_nodes.iter().map(|bootnode| bootnode.peer_id).collect();
900		let peer_store = N::peer_store(bootnodes, metrics_registry.clone());
901		let peer_store_handle = peer_store.handle();
902
903		Self {
904			peer_store: Some(peer_store),
905			peer_store_handle,
906			notification_protocols: Vec::new(),
907			request_response_protocols: Vec::new(),
908			network_config: network_config.clone(),
909			metrics_registry,
910		}
911	}
912
913	/// Add a notification protocol.
914	pub fn add_notification_protocol(&mut self, config: N::NotificationProtocolConfig) {
915		self.notification_protocols.push(config);
916	}
917
918	/// Get reference to installed notification protocols.
919	pub fn notification_protocols(&self) -> &Vec<N::NotificationProtocolConfig> {
920		&self.notification_protocols
921	}
922
923	/// Add a request-response protocol.
924	pub fn add_request_response_protocol(&mut self, config: N::RequestResponseProtocolConfig) {
925		self.request_response_protocols.push(config);
926	}
927
928	/// Get handle to [`PeerStore`].
929	pub fn peer_store_handle(&self) -> Arc<dyn PeerStoreProvider> {
930		Arc::clone(&self.peer_store_handle)
931	}
932
933	/// Take [`PeerStore`].
934	///
935	/// `PeerStore` is created when `FullNetworkConfig` is initialized so that `PeerStoreHandle`s
936	/// can be passed onto notification protocols. `PeerStore` itself should be started only once
937	/// and since technically it's not a libp2p task, it should be started with `SpawnHandle` in
938	/// `builder.rs` instead of using the libp2p/litep2p executor in the networking backend. This
939	/// function consumes `PeerStore` and starts its event loop in the appropriate place.
940	pub fn take_peer_store(&mut self) -> N::PeerStore {
941		self.peer_store
942			.take()
943			.expect("`PeerStore` can only be taken once when it's started; qed")
944	}
945
946	/// Verify addresses are consistent with enabled transports.
947	pub fn sanity_check_addresses(&self) -> Result<(), crate::error::Error> {
948		ensure_addresses_consistent_with_transport(
949			self.network_config.listen_addresses.iter(),
950			&self.network_config.transport,
951		)?;
952		ensure_addresses_consistent_with_transport(
953			self.network_config.boot_nodes.iter().map(|x| &x.multiaddr),
954			&self.network_config.transport,
955		)?;
956		ensure_addresses_consistent_with_transport(
957			self.network_config
958				.default_peers_set
959				.reserved_nodes
960				.iter()
961				.map(|x| &x.multiaddr),
962			&self.network_config.transport,
963		)?;
964
965		for notification_protocol in &self.notification_protocols {
966			ensure_addresses_consistent_with_transport(
967				notification_protocol.set_config().reserved_nodes.iter().map(|x| &x.multiaddr),
968				&self.network_config.transport,
969			)?;
970		}
971		ensure_addresses_consistent_with_transport(
972			self.network_config.public_addresses.iter(),
973			&self.network_config.transport,
974		)?;
975
976		Ok(())
977	}
978
979	/// Check for duplicate bootnodes.
980	pub fn sanity_check_bootnodes(&self) -> Result<(), crate::error::Error> {
981		self.network_config.boot_nodes.iter().try_for_each(|bootnode| {
982			if let Some(other) = self
983				.network_config
984				.boot_nodes
985				.iter()
986				.filter(|o| o.multiaddr == bootnode.multiaddr)
987				.find(|o| o.peer_id != bootnode.peer_id)
988			{
989				Err(crate::error::Error::DuplicateBootnode {
990					address: bootnode.multiaddr.clone().into(),
991					first_id: bootnode.peer_id.into(),
992					second_id: other.peer_id.into(),
993				})
994			} else {
995				Ok(())
996			}
997		})
998	}
999
1000	/// Collect all reserved nodes and bootnodes addresses.
1001	pub fn known_addresses(&self) -> Vec<(PeerId, Multiaddr)> {
1002		let mut addresses: Vec<_> = self
1003			.network_config
1004			.default_peers_set
1005			.reserved_nodes
1006			.iter()
1007			.map(|reserved| (reserved.peer_id, reserved.multiaddr.clone()))
1008			.chain(self.notification_protocols.iter().flat_map(|protocol| {
1009				protocol
1010					.set_config()
1011					.reserved_nodes
1012					.iter()
1013					.map(|reserved| (reserved.peer_id, reserved.multiaddr.clone()))
1014			}))
1015			.chain(
1016				self.network_config
1017					.boot_nodes
1018					.iter()
1019					.map(|bootnode| (bootnode.peer_id, bootnode.multiaddr.clone())),
1020			)
1021			.collect();
1022
1023		// Remove possible duplicates.
1024		addresses.sort();
1025		addresses.dedup();
1026
1027		addresses
1028	}
1029}
1030
1031/// Network backend type.
1032#[derive(Debug, Clone, Default, Copy)]
1033pub enum NetworkBackendType {
1034	/// Use litep2p for P2P networking.
1035	///
1036	/// This is the preferred option for Substrate-based chains.
1037	#[default]
1038	Litep2p,
1039
1040	/// Use libp2p for P2P networking.
1041	///
1042	/// The libp2p is still used for compatibility reasons until the
1043	/// ecosystem switches entirely to litep2p. The backend will enter
1044	/// a "best-effort" maintenance mode, where only critical issues will
1045	/// get fixed. If you are unsure, please use `NetworkBackendType::Litep2p`.
1046	Libp2p,
1047}
1048
1049#[cfg(test)]
1050mod tests {
1051	use super::*;
1052	use tempfile::TempDir;
1053
1054	fn tempdir_with_prefix(prefix: &str) -> TempDir {
1055		tempfile::Builder::new().prefix(prefix).tempdir().unwrap()
1056	}
1057
1058	fn secret_bytes(kp: ed25519::Keypair) -> Vec<u8> {
1059		kp.secret().to_bytes().into()
1060	}
1061
1062	#[test]
1063	fn test_secret_file() {
1064		let tmp = tempdir_with_prefix("x");
1065		std::fs::remove_dir(tmp.path()).unwrap(); // should be recreated
1066		let file = tmp.path().join("x").to_path_buf();
1067		let kp1 = NodeKeyConfig::Ed25519(Secret::File(file.clone())).into_keypair().unwrap();
1068		let kp2 = NodeKeyConfig::Ed25519(Secret::File(file.clone())).into_keypair().unwrap();
1069		assert!(file.is_file() && secret_bytes(kp1) == secret_bytes(kp2))
1070	}
1071
1072	#[test]
1073	fn test_secret_input() {
1074		let sk = ed25519::SecretKey::generate();
1075		let kp1 = NodeKeyConfig::Ed25519(Secret::Input(sk.clone())).into_keypair().unwrap();
1076		let kp2 = NodeKeyConfig::Ed25519(Secret::Input(sk)).into_keypair().unwrap();
1077		assert!(secret_bytes(kp1) == secret_bytes(kp2));
1078	}
1079
1080	#[test]
1081	fn test_secret_new() {
1082		let kp1 = NodeKeyConfig::Ed25519(Secret::New).into_keypair().unwrap();
1083		let kp2 = NodeKeyConfig::Ed25519(Secret::New).into_keypair().unwrap();
1084		assert!(secret_bytes(kp1) != secret_bytes(kp2));
1085	}
1086}