Skip to main content

soil_network/
config.rs

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