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