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