sc_network/
service.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//! Main entry point of the sc-network crate.
20//!
21//! There are two main structs in this module: [`NetworkWorker`] and [`NetworkService`].
22//! The [`NetworkWorker`] *is* the network. Network is driven by [`NetworkWorker::run`] future that
23//! terminates only when all instances of the control handles [`NetworkService`] were dropped.
24//! The [`NetworkService`] is merely a shared version of the [`NetworkWorker`]. You can obtain an
25//! `Arc<NetworkService>` by calling [`NetworkWorker::service`].
26//!
27//! The methods of the [`NetworkService`] are implemented by sending a message over a channel,
28//! which is then processed by [`NetworkWorker::next_action`].
29
30use crate::{
31	behaviour::{self, Behaviour, BehaviourOut},
32	bitswap::BitswapRequestHandler,
33	config::{
34		parse_addr, FullNetworkConfiguration, IncomingRequest, MultiaddrWithPeerId,
35		NonDefaultSetConfig, NotificationHandshake, Params, SetConfig, TransportConfig,
36	},
37	discovery::DiscoveryConfig,
38	error::Error,
39	event::{DhtEvent, Event},
40	network_state::{
41		NetworkState, NotConnectedPeer as NetworkStateNotConnectedPeer, Peer as NetworkStatePeer,
42	},
43	peer_store::{PeerStore, PeerStoreProvider},
44	protocol::{self, Protocol, Ready},
45	protocol_controller::{self, ProtoSetConfig, ProtocolController, SetId},
46	request_responses::{IfDisconnected, ProtocolConfig as RequestResponseConfig, RequestFailure},
47	service::{
48		signature::{Signature, SigningError},
49		traits::{
50			BandwidthSink, NetworkBackend, NetworkDHTProvider, NetworkEventStream, NetworkPeers,
51			NetworkRequest, NetworkService as NetworkServiceT, NetworkSigner, NetworkStateInfo,
52			NetworkStatus, NetworkStatusProvider, NotificationSender as NotificationSenderT,
53			NotificationSenderError, NotificationSenderReady as NotificationSenderReadyT,
54		},
55	},
56	transport,
57	types::ProtocolName,
58	NotificationService, ReputationChange,
59};
60
61use codec::DecodeAll;
62use futures::{channel::oneshot, prelude::*};
63use libp2p::{
64	connection_limits::{ConnectionLimits, Exceeded},
65	core::{upgrade, ConnectedPoint, Endpoint},
66	identify::Info as IdentifyInfo,
67	identity::ed25519,
68	multiaddr::{self, Multiaddr},
69	swarm::{
70		Config as SwarmConfig, ConnectionError, ConnectionId, DialError, Executor, ListenError,
71		NetworkBehaviour, Swarm, SwarmEvent,
72	},
73	PeerId,
74};
75use log::{debug, error, info, trace, warn};
76use metrics::{Histogram, MetricSources, Metrics};
77use parking_lot::Mutex;
78use prometheus_endpoint::Registry;
79use sc_network_types::kad::{Key as KademliaKey, Record};
80
81use sc_client_api::BlockBackend;
82use sc_network_common::{
83	role::{ObservedRole, Roles},
84	ExHashT,
85};
86use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedReceiver, TracingUnboundedSender};
87use sp_runtime::traits::Block as BlockT;
88
89pub use behaviour::{InboundFailure, OutboundFailure, ResponseFailure};
90pub use libp2p::identity::{DecodingError, Keypair, PublicKey};
91pub use metrics::NotificationMetrics;
92pub use protocol::NotificationsSink;
93use std::{
94	collections::{HashMap, HashSet},
95	fs, iter,
96	marker::PhantomData,
97	num::NonZeroUsize,
98	pin::Pin,
99	str,
100	sync::{
101		atomic::{AtomicUsize, Ordering},
102		Arc,
103	},
104	time::{Duration, Instant},
105};
106
107pub(crate) mod metrics;
108pub(crate) mod out_events;
109
110pub mod signature;
111pub mod traits;
112
113/// Logging target for the file.
114const LOG_TARGET: &str = "sub-libp2p";
115
116struct Libp2pBandwidthSink {
117	#[allow(deprecated)]
118	sink: Arc<transport::BandwidthSinks>,
119}
120
121impl BandwidthSink for Libp2pBandwidthSink {
122	fn total_inbound(&self) -> u64 {
123		self.sink.total_inbound()
124	}
125
126	fn total_outbound(&self) -> u64 {
127		self.sink.total_outbound()
128	}
129}
130
131/// Substrate network service. Handles network IO and manages connectivity.
132pub struct NetworkService<B: BlockT + 'static, H: ExHashT> {
133	/// Number of peers we're connected to.
134	num_connected: Arc<AtomicUsize>,
135	/// The local external addresses.
136	external_addresses: Arc<Mutex<HashSet<Multiaddr>>>,
137	/// Listen addresses. Do **NOT** include a trailing `/p2p/` with our `PeerId`.
138	listen_addresses: Arc<Mutex<HashSet<Multiaddr>>>,
139	/// Local copy of the `PeerId` of the local node.
140	local_peer_id: PeerId,
141	/// The `KeyPair` that defines the `PeerId` of the local node.
142	local_identity: Keypair,
143	/// Bandwidth logging system. Can be queried to know the average bandwidth consumed.
144	bandwidth: Arc<dyn BandwidthSink>,
145	/// Channel that sends messages to the actual worker.
146	to_worker: TracingUnboundedSender<ServiceToWorkerMsg>,
147	/// Protocol name -> `SetId` mapping for notification protocols. The map never changes after
148	/// initialization.
149	notification_protocol_ids: HashMap<ProtocolName, SetId>,
150	/// Handles to manage peer connections on notification protocols. The vector never changes
151	/// after initialization.
152	protocol_handles: Vec<protocol_controller::ProtocolHandle>,
153	/// Shortcut to sync protocol handle (`protocol_handles[0]`).
154	sync_protocol_handle: protocol_controller::ProtocolHandle,
155	/// Handle to `PeerStore`.
156	peer_store_handle: Arc<dyn PeerStoreProvider>,
157	/// Marker to pin the `H` generic. Serves no purpose except to not break backwards
158	/// compatibility.
159	_marker: PhantomData<H>,
160	/// Marker for block type
161	_block: PhantomData<B>,
162}
163
164#[async_trait::async_trait]
165impl<B, H> NetworkBackend<B, H> for NetworkWorker<B, H>
166where
167	B: BlockT + 'static,
168	H: ExHashT,
169{
170	type NotificationProtocolConfig = NonDefaultSetConfig;
171	type RequestResponseProtocolConfig = RequestResponseConfig;
172	type NetworkService<Block, Hash> = Arc<NetworkService<B, H>>;
173	type PeerStore = PeerStore;
174	type BitswapConfig = RequestResponseConfig;
175
176	fn new(params: Params<B, H, Self>) -> Result<Self, Error>
177	where
178		Self: Sized,
179	{
180		NetworkWorker::new(params)
181	}
182
183	/// Get handle to `NetworkService` of the `NetworkBackend`.
184	fn network_service(&self) -> Arc<dyn NetworkServiceT> {
185		self.service.clone()
186	}
187
188	/// Create `PeerStore`.
189	fn peer_store(
190		bootnodes: Vec<sc_network_types::PeerId>,
191		metrics_registry: Option<Registry>,
192	) -> Self::PeerStore {
193		PeerStore::new(bootnodes.into_iter().map(From::from).collect(), metrics_registry)
194	}
195
196	fn register_notification_metrics(registry: Option<&Registry>) -> NotificationMetrics {
197		NotificationMetrics::new(registry)
198	}
199
200	fn bitswap_server(
201		client: Arc<dyn BlockBackend<B> + Send + Sync>,
202	) -> (Pin<Box<dyn Future<Output = ()> + Send>>, Self::BitswapConfig) {
203		let (handler, protocol_config) = BitswapRequestHandler::new(client.clone());
204
205		(Box::pin(async move { handler.run().await }), protocol_config)
206	}
207
208	/// Create notification protocol configuration.
209	fn notification_config(
210		protocol_name: ProtocolName,
211		fallback_names: Vec<ProtocolName>,
212		max_notification_size: u64,
213		handshake: Option<NotificationHandshake>,
214		set_config: SetConfig,
215		_metrics: NotificationMetrics,
216		_peerstore_handle: Arc<dyn PeerStoreProvider>,
217	) -> (Self::NotificationProtocolConfig, Box<dyn NotificationService>) {
218		NonDefaultSetConfig::new(
219			protocol_name,
220			fallback_names,
221			max_notification_size,
222			handshake,
223			set_config,
224		)
225	}
226
227	/// Create request-response protocol configuration.
228	fn request_response_config(
229		protocol_name: ProtocolName,
230		fallback_names: Vec<ProtocolName>,
231		max_request_size: u64,
232		max_response_size: u64,
233		request_timeout: Duration,
234		inbound_queue: Option<async_channel::Sender<IncomingRequest>>,
235	) -> Self::RequestResponseProtocolConfig {
236		Self::RequestResponseProtocolConfig {
237			name: protocol_name,
238			fallback_names,
239			max_request_size,
240			max_response_size,
241			request_timeout,
242			inbound_queue,
243		}
244	}
245
246	/// Start [`NetworkBackend`] event loop.
247	async fn run(mut self) {
248		self.run().await
249	}
250}
251
252impl<B, H> NetworkWorker<B, H>
253where
254	B: BlockT + 'static,
255	H: ExHashT,
256{
257	/// Creates the network service.
258	///
259	/// Returns a `NetworkWorker` that implements `Future` and must be regularly polled in order
260	/// for the network processing to advance. From it, you can extract a `NetworkService` using
261	/// `worker.service()`. The `NetworkService` can be shared through the codebase.
262	pub fn new(params: Params<B, H, Self>) -> Result<Self, Error> {
263		let peer_store_handle = params.network_config.peer_store_handle();
264		let FullNetworkConfiguration {
265			notification_protocols,
266			request_response_protocols,
267			mut network_config,
268			..
269		} = params.network_config;
270
271		// Private and public keys configuration.
272		let local_identity = network_config.node_key.clone().into_keypair()?;
273		let local_public = local_identity.public();
274		let local_peer_id = local_public.to_peer_id();
275
276		// Convert to libp2p types.
277		let local_identity: ed25519::Keypair = local_identity.into();
278		let local_public: ed25519::PublicKey = local_public.into();
279		let local_peer_id: PeerId = local_peer_id.into();
280
281		network_config.boot_nodes = network_config
282			.boot_nodes
283			.into_iter()
284			.filter(|boot_node| boot_node.peer_id != local_peer_id.into())
285			.collect();
286		network_config.default_peers_set.reserved_nodes = network_config
287			.default_peers_set
288			.reserved_nodes
289			.into_iter()
290			.filter(|reserved_node| {
291				if reserved_node.peer_id == local_peer_id.into() {
292					warn!(
293						target: LOG_TARGET,
294						"Local peer ID used in reserved node, ignoring: {}",
295						reserved_node,
296					);
297					false
298				} else {
299					true
300				}
301			})
302			.collect();
303
304		// Ensure the listen addresses are consistent with the transport.
305		ensure_addresses_consistent_with_transport(
306			network_config.listen_addresses.iter(),
307			&network_config.transport,
308		)?;
309		ensure_addresses_consistent_with_transport(
310			network_config.boot_nodes.iter().map(|x| &x.multiaddr),
311			&network_config.transport,
312		)?;
313		ensure_addresses_consistent_with_transport(
314			network_config.default_peers_set.reserved_nodes.iter().map(|x| &x.multiaddr),
315			&network_config.transport,
316		)?;
317		for notification_protocol in &notification_protocols {
318			ensure_addresses_consistent_with_transport(
319				notification_protocol.set_config().reserved_nodes.iter().map(|x| &x.multiaddr),
320				&network_config.transport,
321			)?;
322		}
323		ensure_addresses_consistent_with_transport(
324			network_config.public_addresses.iter(),
325			&network_config.transport,
326		)?;
327
328		let (to_worker, from_service) = tracing_unbounded("mpsc_network_worker", 100_000);
329
330		if let Some(path) = &network_config.net_config_path {
331			fs::create_dir_all(path)?;
332		}
333
334		info!(
335			target: LOG_TARGET,
336			"🏷  Local node identity is: {}",
337			local_peer_id.to_base58(),
338		);
339		info!(target: LOG_TARGET, "Running libp2p network backend");
340
341		let (transport, bandwidth) = {
342			let config_mem = match network_config.transport {
343				TransportConfig::MemoryOnly => true,
344				TransportConfig::Normal { .. } => false,
345			};
346
347			transport::build_transport(local_identity.clone().into(), config_mem)
348		};
349
350		let (to_notifications, from_protocol_controllers) =
351			tracing_unbounded("mpsc_protocol_controllers_to_notifications", 10_000);
352
353		// We must prepend a hardcoded default peer set to notification protocols.
354		let all_peer_sets_iter = iter::once(&network_config.default_peers_set)
355			.chain(notification_protocols.iter().map(|protocol| protocol.set_config()));
356
357		let (protocol_handles, protocol_controllers): (Vec<_>, Vec<_>) = all_peer_sets_iter
358			.enumerate()
359			.map(|(set_id, set_config)| {
360				let proto_set_config = ProtoSetConfig {
361					in_peers: set_config.in_peers,
362					out_peers: set_config.out_peers,
363					reserved_nodes: set_config
364						.reserved_nodes
365						.iter()
366						.map(|node| node.peer_id.into())
367						.collect(),
368					reserved_only: set_config.non_reserved_mode.is_reserved_only(),
369				};
370
371				ProtocolController::new(
372					SetId::from(set_id),
373					proto_set_config,
374					to_notifications.clone(),
375					Arc::clone(&peer_store_handle),
376				)
377			})
378			.unzip();
379
380		// Shortcut to default (sync) peer set protocol handle.
381		let sync_protocol_handle = protocol_handles[0].clone();
382
383		// Spawn `ProtocolController` runners.
384		protocol_controllers
385			.into_iter()
386			.for_each(|controller| (params.executor)(controller.run().boxed()));
387
388		// Protocol name to protocol id mapping. The first protocol is always block announce (sync)
389		// protocol, aka default (hardcoded) peer set.
390		let notification_protocol_ids: HashMap<ProtocolName, SetId> =
391			iter::once(&params.block_announce_config)
392				.chain(notification_protocols.iter())
393				.enumerate()
394				.map(|(index, protocol)| (protocol.protocol_name().clone(), SetId::from(index)))
395				.collect();
396
397		let known_addresses = {
398			// Collect all reserved nodes and bootnodes addresses.
399			let mut addresses: Vec<_> = network_config
400				.default_peers_set
401				.reserved_nodes
402				.iter()
403				.map(|reserved| (reserved.peer_id, reserved.multiaddr.clone()))
404				.chain(notification_protocols.iter().flat_map(|protocol| {
405					protocol
406						.set_config()
407						.reserved_nodes
408						.iter()
409						.map(|reserved| (reserved.peer_id, reserved.multiaddr.clone()))
410				}))
411				.chain(
412					network_config
413						.boot_nodes
414						.iter()
415						.map(|bootnode| (bootnode.peer_id, bootnode.multiaddr.clone())),
416				)
417				.collect();
418
419			// Remove possible duplicates.
420			addresses.sort();
421			addresses.dedup();
422
423			addresses
424		};
425
426		// Check for duplicate bootnodes.
427		network_config.boot_nodes.iter().try_for_each(|bootnode| {
428			if let Some(other) = network_config
429				.boot_nodes
430				.iter()
431				.filter(|o| o.multiaddr == bootnode.multiaddr)
432				.find(|o| o.peer_id != bootnode.peer_id)
433			{
434				Err(Error::DuplicateBootnode {
435					address: bootnode.multiaddr.clone().into(),
436					first_id: bootnode.peer_id.into(),
437					second_id: other.peer_id.into(),
438				})
439			} else {
440				Ok(())
441			}
442		})?;
443
444		// List of bootnode multiaddresses.
445		let mut boot_node_ids = HashMap::<PeerId, Vec<Multiaddr>>::new();
446
447		for bootnode in network_config.boot_nodes.iter() {
448			boot_node_ids
449				.entry(bootnode.peer_id.into())
450				.or_default()
451				.push(bootnode.multiaddr.clone().into());
452		}
453
454		let boot_node_ids = Arc::new(boot_node_ids);
455
456		let num_connected = Arc::new(AtomicUsize::new(0));
457		let external_addresses = Arc::new(Mutex::new(HashSet::new()));
458
459		let (protocol, notif_protocol_handles) = Protocol::new(
460			From::from(&params.role),
461			params.notification_metrics,
462			notification_protocols,
463			params.block_announce_config,
464			Arc::clone(&peer_store_handle),
465			protocol_handles.clone(),
466			from_protocol_controllers,
467		)?;
468
469		// Build the swarm.
470		let (mut swarm, bandwidth): (Swarm<Behaviour<B>>, _) = {
471			let user_agent =
472				format!("{} ({})", network_config.client_version, network_config.node_name);
473
474			let discovery_config = {
475				let mut config = DiscoveryConfig::new(local_peer_id);
476				config.with_permanent_addresses(
477					known_addresses
478						.iter()
479						.map(|(peer, address)| (peer.into(), address.clone().into()))
480						.collect::<Vec<_>>(),
481				);
482				config.discovery_limit(u64::from(network_config.default_peers_set.out_peers) + 15);
483				config.with_kademlia(
484					params.genesis_hash,
485					params.fork_id.as_deref(),
486					&params.protocol_id,
487				);
488				config.with_dht_random_walk(network_config.enable_dht_random_walk);
489				config.allow_non_globals_in_dht(network_config.allow_non_globals_in_dht);
490				config.use_kademlia_disjoint_query_paths(
491					network_config.kademlia_disjoint_query_paths,
492				);
493				config.with_kademlia_replication_factor(network_config.kademlia_replication_factor);
494
495				match network_config.transport {
496					TransportConfig::MemoryOnly => {
497						config.with_mdns(false);
498						config.allow_private_ip(false);
499					},
500					TransportConfig::Normal {
501						enable_mdns,
502						allow_private_ip: allow_private_ipv4,
503						..
504					} => {
505						config.with_mdns(enable_mdns);
506						config.allow_private_ip(allow_private_ipv4);
507					},
508				}
509
510				config
511			};
512
513			let behaviour = {
514				let result = Behaviour::new(
515					protocol,
516					user_agent,
517					local_public.into(),
518					discovery_config,
519					request_response_protocols,
520					Arc::clone(&peer_store_handle),
521					external_addresses.clone(),
522					network_config.public_addresses.iter().cloned().map(Into::into).collect(),
523					ConnectionLimits::default()
524						.with_max_established_per_peer(Some(crate::MAX_CONNECTIONS_PER_PEER as u32))
525						.with_max_established_incoming(Some(
526							crate::MAX_CONNECTIONS_ESTABLISHED_INCOMING,
527						)),
528				);
529
530				match result {
531					Ok(b) => b,
532					Err(crate::request_responses::RegisterError::DuplicateProtocol(proto)) =>
533						return Err(Error::DuplicateRequestResponseProtocol { protocol: proto }),
534				}
535			};
536
537			let swarm = {
538				struct SpawnImpl<F>(F);
539				impl<F: Fn(Pin<Box<dyn Future<Output = ()> + Send>>)> Executor for SpawnImpl<F> {
540					fn exec(&self, f: Pin<Box<dyn Future<Output = ()> + Send>>) {
541						(self.0)(f)
542					}
543				}
544
545				let config = SwarmConfig::with_executor(SpawnImpl(params.executor))
546					.with_substream_upgrade_protocol_override(upgrade::Version::V1)
547					.with_notify_handler_buffer_size(NonZeroUsize::new(32).expect("32 != 0; qed"))
548					// NOTE: 24 is somewhat arbitrary and should be tuned in the future if
549					// necessary. See <https://github.com/paritytech/substrate/pull/6080>
550					.with_per_connection_event_buffer_size(24)
551					.with_max_negotiating_inbound_streams(2048)
552					.with_idle_connection_timeout(Duration::from_secs(10));
553
554				Swarm::new(transport, behaviour, local_peer_id, config)
555			};
556
557			(swarm, Arc::new(Libp2pBandwidthSink { sink: bandwidth }))
558		};
559
560		// Initialize the metrics.
561		let metrics = match &params.metrics_registry {
562			Some(registry) => Some(metrics::register(
563				registry,
564				MetricSources {
565					bandwidth: bandwidth.clone(),
566					connected_peers: num_connected.clone(),
567				},
568			)?),
569			None => None,
570		};
571
572		// Listen on multiaddresses.
573		for addr in &network_config.listen_addresses {
574			if let Err(err) = Swarm::<Behaviour<B>>::listen_on(&mut swarm, addr.clone().into()) {
575				warn!(target: LOG_TARGET, "Can't listen on {} because: {:?}", addr, err)
576			}
577		}
578
579		// Add external addresses.
580		for addr in &network_config.public_addresses {
581			Swarm::<Behaviour<B>>::add_external_address(&mut swarm, addr.clone().into());
582		}
583
584		let listen_addresses_set = Arc::new(Mutex::new(HashSet::new()));
585
586		let service = Arc::new(NetworkService {
587			bandwidth,
588			external_addresses,
589			listen_addresses: listen_addresses_set.clone(),
590			num_connected: num_connected.clone(),
591			local_peer_id,
592			local_identity: local_identity.into(),
593			to_worker,
594			notification_protocol_ids,
595			protocol_handles,
596			sync_protocol_handle,
597			peer_store_handle: Arc::clone(&peer_store_handle),
598			_marker: PhantomData,
599			_block: Default::default(),
600		});
601
602		Ok(NetworkWorker {
603			listen_addresses: listen_addresses_set,
604			num_connected,
605			network_service: swarm,
606			service,
607			from_service,
608			event_streams: out_events::OutChannels::new(params.metrics_registry.as_ref())?,
609			metrics,
610			boot_node_ids,
611			reported_invalid_boot_nodes: Default::default(),
612			peer_store_handle: Arc::clone(&peer_store_handle),
613			notif_protocol_handles,
614			_marker: Default::default(),
615			_block: Default::default(),
616		})
617	}
618
619	/// High-level network status information.
620	pub fn status(&self) -> NetworkStatus {
621		NetworkStatus {
622			num_connected_peers: self.num_connected_peers(),
623			total_bytes_inbound: self.total_bytes_inbound(),
624			total_bytes_outbound: self.total_bytes_outbound(),
625		}
626	}
627
628	/// Returns the total number of bytes received so far.
629	pub fn total_bytes_inbound(&self) -> u64 {
630		self.service.bandwidth.total_inbound()
631	}
632
633	/// Returns the total number of bytes sent so far.
634	pub fn total_bytes_outbound(&self) -> u64 {
635		self.service.bandwidth.total_outbound()
636	}
637
638	/// Returns the number of peers we're connected to.
639	pub fn num_connected_peers(&self) -> usize {
640		self.network_service.behaviour().user_protocol().num_sync_peers()
641	}
642
643	/// Adds an address for a node.
644	pub fn add_known_address(&mut self, peer_id: PeerId, addr: Multiaddr) {
645		self.network_service.behaviour_mut().add_known_address(peer_id, addr);
646	}
647
648	/// Return a `NetworkService` that can be shared through the code base and can be used to
649	/// manipulate the worker.
650	pub fn service(&self) -> &Arc<NetworkService<B, H>> {
651		&self.service
652	}
653
654	/// Returns the local `PeerId`.
655	pub fn local_peer_id(&self) -> &PeerId {
656		Swarm::<Behaviour<B>>::local_peer_id(&self.network_service)
657	}
658
659	/// Returns the list of addresses we are listening on.
660	///
661	/// Does **NOT** include a trailing `/p2p/` with our `PeerId`.
662	pub fn listen_addresses(&self) -> impl Iterator<Item = &Multiaddr> {
663		Swarm::<Behaviour<B>>::listeners(&self.network_service)
664	}
665
666	/// Get network state.
667	///
668	/// **Note**: Use this only for debugging. This API is unstable. There are warnings literally
669	/// everywhere about this. Please don't use this function to retrieve actual information.
670	pub fn network_state(&mut self) -> NetworkState {
671		let swarm = &mut self.network_service;
672		let open = swarm.behaviour_mut().user_protocol().open_peers().cloned().collect::<Vec<_>>();
673		let connected_peers = {
674			let swarm = &mut *swarm;
675			open.iter()
676				.filter_map(move |peer_id| {
677					let known_addresses = if let Ok(addrs) =
678						NetworkBehaviour::handle_pending_outbound_connection(
679							swarm.behaviour_mut(),
680							ConnectionId::new_unchecked(0), // dummy value
681							Some(*peer_id),
682							&vec![],
683							Endpoint::Listener,
684						) {
685						addrs.into_iter().collect()
686					} else {
687						error!(target: LOG_TARGET, "Was not able to get known addresses for {:?}", peer_id);
688						return None
689					};
690
691					let endpoint = if let Some(e) =
692						swarm.behaviour_mut().node(peer_id).and_then(|i| i.endpoint())
693					{
694						e.clone().into()
695					} else {
696						error!(target: LOG_TARGET, "Found state inconsistency between custom protocol \
697						and debug information about {:?}", peer_id);
698						return None
699					};
700
701					Some((
702						peer_id.to_base58(),
703						NetworkStatePeer {
704							endpoint,
705							version_string: swarm
706								.behaviour_mut()
707								.node(peer_id)
708								.and_then(|i| i.client_version().map(|s| s.to_owned())),
709							latest_ping_time: swarm
710								.behaviour_mut()
711								.node(peer_id)
712								.and_then(|i| i.latest_ping()),
713							known_addresses,
714						},
715					))
716				})
717				.collect()
718		};
719
720		let not_connected_peers = {
721			let swarm = &mut *swarm;
722			swarm
723				.behaviour_mut()
724				.known_peers()
725				.into_iter()
726				.filter(|p| open.iter().all(|n| n != p))
727				.map(move |peer_id| {
728					let known_addresses = if let Ok(addrs) =
729						NetworkBehaviour::handle_pending_outbound_connection(
730							swarm.behaviour_mut(),
731							ConnectionId::new_unchecked(0), // dummy value
732							Some(peer_id),
733							&vec![],
734							Endpoint::Listener,
735						) {
736						addrs.into_iter().collect()
737					} else {
738						error!(target: LOG_TARGET, "Was not able to get known addresses for {:?}", peer_id);
739						Default::default()
740					};
741
742					(
743						peer_id.to_base58(),
744						NetworkStateNotConnectedPeer {
745							version_string: swarm
746								.behaviour_mut()
747								.node(&peer_id)
748								.and_then(|i| i.client_version().map(|s| s.to_owned())),
749							latest_ping_time: swarm
750								.behaviour_mut()
751								.node(&peer_id)
752								.and_then(|i| i.latest_ping()),
753							known_addresses,
754						},
755					)
756				})
757				.collect()
758		};
759
760		let peer_id = Swarm::<Behaviour<B>>::local_peer_id(swarm).to_base58();
761		let listened_addresses = swarm.listeners().cloned().collect();
762		let external_addresses = swarm.external_addresses().cloned().collect();
763
764		NetworkState {
765			peer_id,
766			listened_addresses,
767			external_addresses,
768			connected_peers,
769			not_connected_peers,
770			// TODO: Check what info we can include here.
771			//       Issue reference: https://github.com/paritytech/substrate/issues/14160.
772			peerset: serde_json::json!(
773				"Unimplemented. See https://github.com/paritytech/substrate/issues/14160."
774			),
775		}
776	}
777
778	/// Removes a `PeerId` from the list of reserved peers.
779	pub fn remove_reserved_peer(&self, peer: PeerId) {
780		self.service.remove_reserved_peer(peer.into());
781	}
782
783	/// Adds a `PeerId` and its `Multiaddr` as reserved.
784	pub fn add_reserved_peer(&self, peer: MultiaddrWithPeerId) -> Result<(), String> {
785		self.service.add_reserved_peer(peer)
786	}
787}
788
789impl<B: BlockT + 'static, H: ExHashT> NetworkService<B, H> {
790	/// Get network state.
791	///
792	/// **Note**: Use this only for debugging. This API is unstable. There are warnings literally
793	/// everywhere about this. Please don't use this function to retrieve actual information.
794	///
795	/// Returns an error if the `NetworkWorker` is no longer running.
796	pub async fn network_state(&self) -> Result<NetworkState, ()> {
797		let (tx, rx) = oneshot::channel();
798
799		let _ = self
800			.to_worker
801			.unbounded_send(ServiceToWorkerMsg::NetworkState { pending_response: tx });
802
803		match rx.await {
804			Ok(v) => v.map_err(|_| ()),
805			// The channel can only be closed if the network worker no longer exists.
806			Err(_) => Err(()),
807		}
808	}
809
810	/// Utility function to extract `PeerId` from each `Multiaddr` for peer set updates.
811	///
812	/// Returns an `Err` if one of the given addresses is invalid or contains an
813	/// invalid peer ID (which includes the local peer ID).
814	fn split_multiaddr_and_peer_id(
815		&self,
816		peers: HashSet<Multiaddr>,
817	) -> Result<Vec<(PeerId, Multiaddr)>, String> {
818		peers
819			.into_iter()
820			.map(|mut addr| {
821				let peer = match addr.pop() {
822					Some(multiaddr::Protocol::P2p(peer_id)) => peer_id,
823					_ => return Err("Missing PeerId from address".to_string()),
824				};
825
826				// Make sure the local peer ID is never added to the PSM
827				// or added as a "known address", even if given.
828				if peer == self.local_peer_id {
829					Err("Local peer ID in peer set.".to_string())
830				} else {
831					Ok((peer, addr))
832				}
833			})
834			.collect::<Result<Vec<(PeerId, Multiaddr)>, String>>()
835	}
836}
837
838impl<B, H> NetworkStateInfo for NetworkService<B, H>
839where
840	B: sp_runtime::traits::Block,
841	H: ExHashT,
842{
843	/// Returns the local external addresses.
844	fn external_addresses(&self) -> Vec<sc_network_types::multiaddr::Multiaddr> {
845		self.external_addresses.lock().iter().cloned().map(Into::into).collect()
846	}
847
848	/// Returns the listener addresses (without trailing `/p2p/` with our `PeerId`).
849	fn listen_addresses(&self) -> Vec<sc_network_types::multiaddr::Multiaddr> {
850		self.listen_addresses.lock().iter().cloned().map(Into::into).collect()
851	}
852
853	/// Returns the local Peer ID.
854	fn local_peer_id(&self) -> sc_network_types::PeerId {
855		self.local_peer_id.into()
856	}
857}
858
859impl<B, H> NetworkSigner for NetworkService<B, H>
860where
861	B: sp_runtime::traits::Block,
862	H: ExHashT,
863{
864	fn sign_with_local_identity(&self, msg: Vec<u8>) -> Result<Signature, SigningError> {
865		let public_key = self.local_identity.public();
866		let bytes = self.local_identity.sign(msg.as_ref())?;
867
868		Ok(Signature {
869			public_key: crate::service::signature::PublicKey::Libp2p(public_key),
870			bytes,
871		})
872	}
873
874	fn verify(
875		&self,
876		peer_id: sc_network_types::PeerId,
877		public_key: &Vec<u8>,
878		signature: &Vec<u8>,
879		message: &Vec<u8>,
880	) -> Result<bool, String> {
881		let public_key =
882			PublicKey::try_decode_protobuf(&public_key).map_err(|error| error.to_string())?;
883		let peer_id: PeerId = peer_id.into();
884		let remote: libp2p::PeerId = public_key.to_peer_id();
885
886		Ok(peer_id == remote && public_key.verify(message, signature))
887	}
888}
889
890impl<B, H> NetworkDHTProvider for NetworkService<B, H>
891where
892	B: BlockT + 'static,
893	H: ExHashT,
894{
895	/// Start getting a value from the DHT.
896	///
897	/// This will generate either a `ValueFound` or a `ValueNotFound` event and pass it as an
898	/// item on the [`NetworkWorker`] stream.
899	fn get_value(&self, key: &KademliaKey) {
900		let _ = self.to_worker.unbounded_send(ServiceToWorkerMsg::GetValue(key.clone()));
901	}
902
903	/// Start putting a value in the DHT.
904	///
905	/// This will generate either a `ValuePut` or a `ValuePutFailed` event and pass it as an
906	/// item on the [`NetworkWorker`] stream.
907	fn put_value(&self, key: KademliaKey, value: Vec<u8>) {
908		let _ = self.to_worker.unbounded_send(ServiceToWorkerMsg::PutValue(key, value));
909	}
910
911	fn put_record_to(
912		&self,
913		record: Record,
914		peers: HashSet<sc_network_types::PeerId>,
915		update_local_storage: bool,
916	) {
917		let _ = self.to_worker.unbounded_send(ServiceToWorkerMsg::PutRecordTo {
918			record,
919			peers,
920			update_local_storage,
921		});
922	}
923
924	fn store_record(
925		&self,
926		key: KademliaKey,
927		value: Vec<u8>,
928		publisher: Option<sc_network_types::PeerId>,
929		expires: Option<Instant>,
930	) {
931		let _ = self.to_worker.unbounded_send(ServiceToWorkerMsg::StoreRecord(
932			key,
933			value,
934			publisher.map(Into::into),
935			expires,
936		));
937	}
938
939	fn start_providing(&self, key: KademliaKey) {
940		let _ = self.to_worker.unbounded_send(ServiceToWorkerMsg::StartProviding(key));
941	}
942
943	fn stop_providing(&self, key: KademliaKey) {
944		let _ = self.to_worker.unbounded_send(ServiceToWorkerMsg::StopProviding(key));
945	}
946
947	fn get_providers(&self, key: KademliaKey) {
948		let _ = self.to_worker.unbounded_send(ServiceToWorkerMsg::GetProviders(key));
949	}
950}
951
952#[async_trait::async_trait]
953impl<B, H> NetworkStatusProvider for NetworkService<B, H>
954where
955	B: BlockT + 'static,
956	H: ExHashT,
957{
958	async fn status(&self) -> Result<NetworkStatus, ()> {
959		let (tx, rx) = oneshot::channel();
960
961		let _ = self
962			.to_worker
963			.unbounded_send(ServiceToWorkerMsg::NetworkStatus { pending_response: tx });
964
965		match rx.await {
966			Ok(v) => v.map_err(|_| ()),
967			// The channel can only be closed if the network worker no longer exists.
968			Err(_) => Err(()),
969		}
970	}
971
972	async fn network_state(&self) -> Result<NetworkState, ()> {
973		let (tx, rx) = oneshot::channel();
974
975		let _ = self
976			.to_worker
977			.unbounded_send(ServiceToWorkerMsg::NetworkState { pending_response: tx });
978
979		match rx.await {
980			Ok(v) => v.map_err(|_| ()),
981			// The channel can only be closed if the network worker no longer exists.
982			Err(_) => Err(()),
983		}
984	}
985}
986
987#[async_trait::async_trait]
988impl<B, H> NetworkPeers for NetworkService<B, H>
989where
990	B: BlockT + 'static,
991	H: ExHashT,
992{
993	fn set_authorized_peers(&self, peers: HashSet<sc_network_types::PeerId>) {
994		self.sync_protocol_handle
995			.set_reserved_peers(peers.iter().map(|peer| (*peer).into()).collect());
996	}
997
998	fn set_authorized_only(&self, reserved_only: bool) {
999		self.sync_protocol_handle.set_reserved_only(reserved_only);
1000	}
1001
1002	fn add_known_address(
1003		&self,
1004		peer_id: sc_network_types::PeerId,
1005		addr: sc_network_types::multiaddr::Multiaddr,
1006	) {
1007		let _ = self
1008			.to_worker
1009			.unbounded_send(ServiceToWorkerMsg::AddKnownAddress(peer_id.into(), addr.into()));
1010	}
1011
1012	fn report_peer(&self, peer_id: sc_network_types::PeerId, cost_benefit: ReputationChange) {
1013		self.peer_store_handle.report_peer(peer_id, cost_benefit);
1014	}
1015
1016	fn peer_reputation(&self, peer_id: &sc_network_types::PeerId) -> i32 {
1017		self.peer_store_handle.peer_reputation(peer_id)
1018	}
1019
1020	fn disconnect_peer(&self, peer_id: sc_network_types::PeerId, protocol: ProtocolName) {
1021		let _ = self
1022			.to_worker
1023			.unbounded_send(ServiceToWorkerMsg::DisconnectPeer(peer_id.into(), protocol));
1024	}
1025
1026	fn accept_unreserved_peers(&self) {
1027		self.sync_protocol_handle.set_reserved_only(false);
1028	}
1029
1030	fn deny_unreserved_peers(&self) {
1031		self.sync_protocol_handle.set_reserved_only(true);
1032	}
1033
1034	fn add_reserved_peer(&self, peer: MultiaddrWithPeerId) -> Result<(), String> {
1035		// Make sure the local peer ID is never added as a reserved peer.
1036		if peer.peer_id == self.local_peer_id.into() {
1037			return Err("Local peer ID cannot be added as a reserved peer.".to_string())
1038		}
1039
1040		let _ = self.to_worker.unbounded_send(ServiceToWorkerMsg::AddKnownAddress(
1041			peer.peer_id.into(),
1042			peer.multiaddr.into(),
1043		));
1044		self.sync_protocol_handle.add_reserved_peer(peer.peer_id.into());
1045
1046		Ok(())
1047	}
1048
1049	fn remove_reserved_peer(&self, peer_id: sc_network_types::PeerId) {
1050		self.sync_protocol_handle.remove_reserved_peer(peer_id.into());
1051	}
1052
1053	fn set_reserved_peers(
1054		&self,
1055		protocol: ProtocolName,
1056		peers: HashSet<sc_network_types::multiaddr::Multiaddr>,
1057	) -> Result<(), String> {
1058		let Some(set_id) = self.notification_protocol_ids.get(&protocol) else {
1059			return Err(format!("Cannot set reserved peers for unknown protocol: {}", protocol))
1060		};
1061
1062		let peers: HashSet<Multiaddr> = peers.into_iter().map(Into::into).collect();
1063		let peers_addrs = self.split_multiaddr_and_peer_id(peers)?;
1064
1065		let mut peers: HashSet<PeerId> = HashSet::with_capacity(peers_addrs.len());
1066
1067		for (peer_id, addr) in peers_addrs.into_iter() {
1068			// Make sure the local peer ID is never added to the PSM.
1069			if peer_id == self.local_peer_id {
1070				return Err("Local peer ID cannot be added as a reserved peer.".to_string())
1071			}
1072
1073			peers.insert(peer_id.into());
1074
1075			if !addr.is_empty() {
1076				let _ = self
1077					.to_worker
1078					.unbounded_send(ServiceToWorkerMsg::AddKnownAddress(peer_id, addr));
1079			}
1080		}
1081
1082		self.protocol_handles[usize::from(*set_id)].set_reserved_peers(peers);
1083
1084		Ok(())
1085	}
1086
1087	fn add_peers_to_reserved_set(
1088		&self,
1089		protocol: ProtocolName,
1090		peers: HashSet<sc_network_types::multiaddr::Multiaddr>,
1091	) -> Result<(), String> {
1092		let Some(set_id) = self.notification_protocol_ids.get(&protocol) else {
1093			return Err(format!(
1094				"Cannot add peers to reserved set of unknown protocol: {}",
1095				protocol
1096			))
1097		};
1098
1099		let peers: HashSet<Multiaddr> = peers.into_iter().map(Into::into).collect();
1100		let peers = self.split_multiaddr_and_peer_id(peers)?;
1101
1102		for (peer_id, addr) in peers.into_iter() {
1103			// Make sure the local peer ID is never added to the PSM.
1104			if peer_id == self.local_peer_id {
1105				return Err("Local peer ID cannot be added as a reserved peer.".to_string())
1106			}
1107
1108			if !addr.is_empty() {
1109				let _ = self
1110					.to_worker
1111					.unbounded_send(ServiceToWorkerMsg::AddKnownAddress(peer_id, addr));
1112			}
1113
1114			self.protocol_handles[usize::from(*set_id)].add_reserved_peer(peer_id);
1115		}
1116
1117		Ok(())
1118	}
1119
1120	fn remove_peers_from_reserved_set(
1121		&self,
1122		protocol: ProtocolName,
1123		peers: Vec<sc_network_types::PeerId>,
1124	) -> Result<(), String> {
1125		let Some(set_id) = self.notification_protocol_ids.get(&protocol) else {
1126			return Err(format!(
1127				"Cannot remove peers from reserved set of unknown protocol: {}",
1128				protocol
1129			))
1130		};
1131
1132		for peer_id in peers.into_iter() {
1133			self.protocol_handles[usize::from(*set_id)].remove_reserved_peer(peer_id.into());
1134		}
1135
1136		Ok(())
1137	}
1138
1139	fn sync_num_connected(&self) -> usize {
1140		self.num_connected.load(Ordering::Relaxed)
1141	}
1142
1143	fn peer_role(
1144		&self,
1145		peer_id: sc_network_types::PeerId,
1146		handshake: Vec<u8>,
1147	) -> Option<ObservedRole> {
1148		match Roles::decode_all(&mut &handshake[..]) {
1149			Ok(role) => Some(role.into()),
1150			Err(_) => {
1151				log::debug!(target: LOG_TARGET, "handshake doesn't contain peer role: {handshake:?}");
1152				self.peer_store_handle.peer_role(&(peer_id.into()))
1153			},
1154		}
1155	}
1156
1157	/// Get the list of reserved peers.
1158	///
1159	/// Returns an error if the `NetworkWorker` is no longer running.
1160	async fn reserved_peers(&self) -> Result<Vec<sc_network_types::PeerId>, ()> {
1161		let (tx, rx) = oneshot::channel();
1162
1163		self.sync_protocol_handle.reserved_peers(tx);
1164
1165		// The channel can only be closed if `ProtocolController` no longer exists.
1166		rx.await
1167			.map(|peers| peers.into_iter().map(From::from).collect())
1168			.map_err(|_| ())
1169	}
1170}
1171
1172impl<B, H> NetworkEventStream for NetworkService<B, H>
1173where
1174	B: BlockT + 'static,
1175	H: ExHashT,
1176{
1177	fn event_stream(&self, name: &'static str) -> Pin<Box<dyn Stream<Item = Event> + Send>> {
1178		let (tx, rx) = out_events::channel(name, 100_000);
1179		let _ = self.to_worker.unbounded_send(ServiceToWorkerMsg::EventStream(tx));
1180		Box::pin(rx)
1181	}
1182}
1183
1184#[async_trait::async_trait]
1185impl<B, H> NetworkRequest for NetworkService<B, H>
1186where
1187	B: BlockT + 'static,
1188	H: ExHashT,
1189{
1190	async fn request(
1191		&self,
1192		target: sc_network_types::PeerId,
1193		protocol: ProtocolName,
1194		request: Vec<u8>,
1195		fallback_request: Option<(Vec<u8>, ProtocolName)>,
1196		connect: IfDisconnected,
1197	) -> Result<(Vec<u8>, ProtocolName), RequestFailure> {
1198		let (tx, rx) = oneshot::channel();
1199
1200		self.start_request(target.into(), protocol, request, fallback_request, tx, connect);
1201
1202		match rx.await {
1203			Ok(v) => v,
1204			// The channel can only be closed if the network worker no longer exists. If the
1205			// network worker no longer exists, then all connections to `target` are necessarily
1206			// closed, and we legitimately report this situation as a "ConnectionClosed".
1207			Err(_) => Err(RequestFailure::Network(OutboundFailure::ConnectionClosed)),
1208		}
1209	}
1210
1211	fn start_request(
1212		&self,
1213		target: sc_network_types::PeerId,
1214		protocol: ProtocolName,
1215		request: Vec<u8>,
1216		fallback_request: Option<(Vec<u8>, ProtocolName)>,
1217		tx: oneshot::Sender<Result<(Vec<u8>, ProtocolName), RequestFailure>>,
1218		connect: IfDisconnected,
1219	) {
1220		let _ = self.to_worker.unbounded_send(ServiceToWorkerMsg::Request {
1221			target: target.into(),
1222			protocol: protocol.into(),
1223			request,
1224			fallback_request,
1225			pending_response: tx,
1226			connect,
1227		});
1228	}
1229}
1230
1231/// A `NotificationSender` allows for sending notifications to a peer with a chosen protocol.
1232#[must_use]
1233pub struct NotificationSender {
1234	sink: NotificationsSink,
1235
1236	/// Name of the protocol on the wire.
1237	protocol_name: ProtocolName,
1238
1239	/// Field extracted from the [`Metrics`] struct and necessary to report the
1240	/// notifications-related metrics.
1241	notification_size_metric: Option<Histogram>,
1242}
1243
1244#[async_trait::async_trait]
1245impl NotificationSenderT for NotificationSender {
1246	async fn ready(
1247		&self,
1248	) -> Result<Box<dyn NotificationSenderReadyT + '_>, NotificationSenderError> {
1249		Ok(Box::new(NotificationSenderReady {
1250			ready: match self.sink.reserve_notification().await {
1251				Ok(r) => Some(r),
1252				Err(()) => return Err(NotificationSenderError::Closed),
1253			},
1254			peer_id: self.sink.peer_id(),
1255			protocol_name: &self.protocol_name,
1256			notification_size_metric: self.notification_size_metric.clone(),
1257		}))
1258	}
1259}
1260
1261/// Reserved slot in the notifications buffer, ready to accept data.
1262#[must_use]
1263pub struct NotificationSenderReady<'a> {
1264	ready: Option<Ready<'a>>,
1265
1266	/// Target of the notification.
1267	peer_id: &'a PeerId,
1268
1269	/// Name of the protocol on the wire.
1270	protocol_name: &'a ProtocolName,
1271
1272	/// Field extracted from the [`Metrics`] struct and necessary to report the
1273	/// notifications-related metrics.
1274	notification_size_metric: Option<Histogram>,
1275}
1276
1277impl<'a> NotificationSenderReadyT for NotificationSenderReady<'a> {
1278	fn send(&mut self, notification: Vec<u8>) -> Result<(), NotificationSenderError> {
1279		if let Some(notification_size_metric) = &self.notification_size_metric {
1280			notification_size_metric.observe(notification.len() as f64);
1281		}
1282
1283		trace!(
1284			target: LOG_TARGET,
1285			"External API => Notification({:?}, {}, {} bytes)",
1286			self.peer_id, self.protocol_name, notification.len(),
1287		);
1288		trace!(target: LOG_TARGET, "Handler({:?}) <= Async notification", self.peer_id);
1289
1290		self.ready
1291			.take()
1292			.ok_or(NotificationSenderError::Closed)?
1293			.send(notification)
1294			.map_err(|()| NotificationSenderError::Closed)
1295	}
1296}
1297
1298/// Messages sent from the `NetworkService` to the `NetworkWorker`.
1299///
1300/// Each entry corresponds to a method of `NetworkService`.
1301enum ServiceToWorkerMsg {
1302	GetValue(KademliaKey),
1303	PutValue(KademliaKey, Vec<u8>),
1304	PutRecordTo {
1305		record: Record,
1306		peers: HashSet<sc_network_types::PeerId>,
1307		update_local_storage: bool,
1308	},
1309	StoreRecord(KademliaKey, Vec<u8>, Option<PeerId>, Option<Instant>),
1310	StartProviding(KademliaKey),
1311	StopProviding(KademliaKey),
1312	GetProviders(KademliaKey),
1313	AddKnownAddress(PeerId, Multiaddr),
1314	EventStream(out_events::Sender),
1315	Request {
1316		target: PeerId,
1317		protocol: ProtocolName,
1318		request: Vec<u8>,
1319		fallback_request: Option<(Vec<u8>, ProtocolName)>,
1320		pending_response: oneshot::Sender<Result<(Vec<u8>, ProtocolName), RequestFailure>>,
1321		connect: IfDisconnected,
1322	},
1323	NetworkStatus {
1324		pending_response: oneshot::Sender<Result<NetworkStatus, RequestFailure>>,
1325	},
1326	NetworkState {
1327		pending_response: oneshot::Sender<Result<NetworkState, RequestFailure>>,
1328	},
1329	DisconnectPeer(PeerId, ProtocolName),
1330}
1331
1332/// Main network worker. Must be polled in order for the network to advance.
1333///
1334/// You are encouraged to poll this in a separate background thread or task.
1335#[must_use = "The NetworkWorker must be polled in order for the network to advance"]
1336pub struct NetworkWorker<B, H>
1337where
1338	B: BlockT + 'static,
1339	H: ExHashT,
1340{
1341	/// Updated by the `NetworkWorker` and loaded by the `NetworkService`.
1342	listen_addresses: Arc<Mutex<HashSet<Multiaddr>>>,
1343	/// Updated by the `NetworkWorker` and loaded by the `NetworkService`.
1344	num_connected: Arc<AtomicUsize>,
1345	/// The network service that can be extracted and shared through the codebase.
1346	service: Arc<NetworkService<B, H>>,
1347	/// The *actual* network.
1348	network_service: Swarm<Behaviour<B>>,
1349	/// Messages from the [`NetworkService`] that must be processed.
1350	from_service: TracingUnboundedReceiver<ServiceToWorkerMsg>,
1351	/// Senders for events that happen on the network.
1352	event_streams: out_events::OutChannels,
1353	/// Prometheus network metrics.
1354	metrics: Option<Metrics>,
1355	/// The `PeerId`'s of all boot nodes mapped to the registered addresses.
1356	boot_node_ids: Arc<HashMap<PeerId, Vec<Multiaddr>>>,
1357	/// Boot nodes that we already have reported as invalid.
1358	reported_invalid_boot_nodes: HashSet<PeerId>,
1359	/// Peer reputation store handle.
1360	peer_store_handle: Arc<dyn PeerStoreProvider>,
1361	/// Notification protocol handles.
1362	notif_protocol_handles: Vec<protocol::ProtocolHandle>,
1363	/// Marker to pin the `H` generic. Serves no purpose except to not break backwards
1364	/// compatibility.
1365	_marker: PhantomData<H>,
1366	/// Marker for block type
1367	_block: PhantomData<B>,
1368}
1369
1370impl<B, H> NetworkWorker<B, H>
1371where
1372	B: BlockT + 'static,
1373	H: ExHashT,
1374{
1375	/// Run the network.
1376	pub async fn run(mut self) {
1377		while self.next_action().await {}
1378	}
1379
1380	/// Perform one action on the network.
1381	///
1382	/// Returns `false` when the worker should be shutdown.
1383	/// Use in tests only.
1384	pub async fn next_action(&mut self) -> bool {
1385		futures::select! {
1386			// Next message from the service.
1387			msg = self.from_service.next() => {
1388				if let Some(msg) = msg {
1389					self.handle_worker_message(msg);
1390				} else {
1391					return false
1392				}
1393			},
1394			// Next event from `Swarm` (the stream guaranteed to never terminate).
1395			event = self.network_service.select_next_some() => {
1396				self.handle_swarm_event(event);
1397			},
1398		};
1399
1400		// Update the `num_connected` count shared with the `NetworkService`.
1401		let num_connected_peers = self.network_service.behaviour().user_protocol().num_sync_peers();
1402		self.num_connected.store(num_connected_peers, Ordering::Relaxed);
1403
1404		if let Some(metrics) = self.metrics.as_ref() {
1405			if let Some(buckets) = self.network_service.behaviour_mut().num_entries_per_kbucket() {
1406				for (lower_ilog2_bucket_bound, num_entries) in buckets {
1407					metrics
1408						.kbuckets_num_nodes
1409						.with_label_values(&[&lower_ilog2_bucket_bound.to_string()])
1410						.set(num_entries as u64);
1411				}
1412			}
1413			if let Some(num_entries) = self.network_service.behaviour_mut().num_kademlia_records() {
1414				metrics.kademlia_records_count.set(num_entries as u64);
1415			}
1416			if let Some(num_entries) =
1417				self.network_service.behaviour_mut().kademlia_records_total_size()
1418			{
1419				metrics.kademlia_records_sizes_total.set(num_entries as u64);
1420			}
1421
1422			metrics.pending_connections.set(
1423				Swarm::network_info(&self.network_service).connection_counters().num_pending()
1424					as u64,
1425			);
1426		}
1427
1428		true
1429	}
1430
1431	/// Process the next message coming from the `NetworkService`.
1432	fn handle_worker_message(&mut self, msg: ServiceToWorkerMsg) {
1433		match msg {
1434			ServiceToWorkerMsg::GetValue(key) =>
1435				self.network_service.behaviour_mut().get_value(key.into()),
1436			ServiceToWorkerMsg::PutValue(key, value) =>
1437				self.network_service.behaviour_mut().put_value(key.into(), value),
1438			ServiceToWorkerMsg::PutRecordTo { record, peers, update_local_storage } => self
1439				.network_service
1440				.behaviour_mut()
1441				.put_record_to(record.into(), peers, update_local_storage),
1442			ServiceToWorkerMsg::StoreRecord(key, value, publisher, expires) => self
1443				.network_service
1444				.behaviour_mut()
1445				.store_record(key.into(), value, publisher, expires),
1446			ServiceToWorkerMsg::StartProviding(key) =>
1447				self.network_service.behaviour_mut().start_providing(key.into()),
1448			ServiceToWorkerMsg::StopProviding(key) =>
1449				self.network_service.behaviour_mut().stop_providing(&key.into()),
1450			ServiceToWorkerMsg::GetProviders(key) =>
1451				self.network_service.behaviour_mut().get_providers(key.into()),
1452			ServiceToWorkerMsg::AddKnownAddress(peer_id, addr) =>
1453				self.network_service.behaviour_mut().add_known_address(peer_id, addr),
1454			ServiceToWorkerMsg::EventStream(sender) => self.event_streams.push(sender),
1455			ServiceToWorkerMsg::Request {
1456				target,
1457				protocol,
1458				request,
1459				fallback_request,
1460				pending_response,
1461				connect,
1462			} => {
1463				self.network_service.behaviour_mut().send_request(
1464					&target,
1465					protocol,
1466					request,
1467					fallback_request,
1468					pending_response,
1469					connect,
1470				);
1471			},
1472			ServiceToWorkerMsg::NetworkStatus { pending_response } => {
1473				let _ = pending_response.send(Ok(self.status()));
1474			},
1475			ServiceToWorkerMsg::NetworkState { pending_response } => {
1476				let _ = pending_response.send(Ok(self.network_state()));
1477			},
1478			ServiceToWorkerMsg::DisconnectPeer(who, protocol_name) => self
1479				.network_service
1480				.behaviour_mut()
1481				.user_protocol_mut()
1482				.disconnect_peer(&who, protocol_name),
1483		}
1484	}
1485
1486	/// Process the next event coming from `Swarm`.
1487	fn handle_swarm_event(&mut self, event: SwarmEvent<BehaviourOut>) {
1488		match event {
1489			SwarmEvent::Behaviour(BehaviourOut::InboundRequest { protocol, result, .. }) => {
1490				if let Some(metrics) = self.metrics.as_ref() {
1491					match result {
1492						Ok(serve_time) => {
1493							metrics
1494								.requests_in_success_total
1495								.with_label_values(&[&protocol])
1496								.observe(serve_time.as_secs_f64());
1497						},
1498						Err(err) => {
1499							let reason = match err {
1500								ResponseFailure::Network(InboundFailure::Timeout) =>
1501									Some("timeout"),
1502								ResponseFailure::Network(InboundFailure::UnsupportedProtocols) =>
1503								// `UnsupportedProtocols` is reported for every single
1504								// inbound request whenever a request with an unsupported
1505								// protocol is received. This is not reported in order to
1506								// avoid confusions.
1507									None,
1508								ResponseFailure::Network(InboundFailure::ResponseOmission) =>
1509									Some("busy-omitted"),
1510								ResponseFailure::Network(InboundFailure::ConnectionClosed) =>
1511									Some("connection-closed"),
1512								ResponseFailure::Network(InboundFailure::Io(_)) => Some("io"),
1513							};
1514
1515							if let Some(reason) = reason {
1516								metrics
1517									.requests_in_failure_total
1518									.with_label_values(&[&protocol, reason])
1519									.inc();
1520							}
1521						},
1522					}
1523				}
1524			},
1525			SwarmEvent::Behaviour(BehaviourOut::RequestFinished {
1526				protocol,
1527				duration,
1528				result,
1529				..
1530			}) =>
1531				if let Some(metrics) = self.metrics.as_ref() {
1532					match result {
1533						Ok(_) => {
1534							metrics
1535								.requests_out_success_total
1536								.with_label_values(&[&protocol])
1537								.observe(duration.as_secs_f64());
1538						},
1539						Err(err) => {
1540							let reason = match err {
1541								RequestFailure::NotConnected => "not-connected",
1542								RequestFailure::UnknownProtocol => "unknown-protocol",
1543								RequestFailure::Refused => "refused",
1544								RequestFailure::Obsolete => "obsolete",
1545								RequestFailure::Network(OutboundFailure::DialFailure) =>
1546									"dial-failure",
1547								RequestFailure::Network(OutboundFailure::Timeout) => "timeout",
1548								RequestFailure::Network(OutboundFailure::ConnectionClosed) =>
1549									"connection-closed",
1550								RequestFailure::Network(OutboundFailure::UnsupportedProtocols) =>
1551									"unsupported",
1552								RequestFailure::Network(OutboundFailure::Io(_)) => "io",
1553							};
1554
1555							metrics
1556								.requests_out_failure_total
1557								.with_label_values(&[&protocol, reason])
1558								.inc();
1559						},
1560					}
1561				},
1562			SwarmEvent::Behaviour(BehaviourOut::ReputationChanges { peer, changes }) => {
1563				for change in changes {
1564					self.peer_store_handle.report_peer(peer.into(), change);
1565				}
1566			},
1567			SwarmEvent::Behaviour(BehaviourOut::PeerIdentify {
1568				peer_id,
1569				info:
1570					IdentifyInfo {
1571						protocol_version, agent_version, mut listen_addrs, protocols, ..
1572					},
1573			}) => {
1574				if listen_addrs.len() > 30 {
1575					debug!(
1576						target: LOG_TARGET,
1577						"Node {:?} has reported more than 30 addresses; it is identified by {:?} and {:?}",
1578						peer_id, protocol_version, agent_version
1579					);
1580					listen_addrs.truncate(30);
1581				}
1582				for addr in listen_addrs {
1583					self.network_service.behaviour_mut().add_self_reported_address_to_dht(
1584						&peer_id,
1585						&protocols,
1586						addr.clone(),
1587					);
1588				}
1589				self.peer_store_handle.add_known_peer(peer_id.into());
1590			},
1591			SwarmEvent::Behaviour(BehaviourOut::Discovered(peer_id)) => {
1592				self.peer_store_handle.add_known_peer(peer_id.into());
1593			},
1594			SwarmEvent::Behaviour(BehaviourOut::RandomKademliaStarted) => {
1595				if let Some(metrics) = self.metrics.as_ref() {
1596					metrics.kademlia_random_queries_total.inc();
1597				}
1598			},
1599			SwarmEvent::Behaviour(BehaviourOut::NotificationStreamOpened {
1600				remote,
1601				set_id,
1602				direction,
1603				negotiated_fallback,
1604				notifications_sink,
1605				received_handshake,
1606			}) => {
1607				let _ = self.notif_protocol_handles[usize::from(set_id)].report_substream_opened(
1608					remote,
1609					direction,
1610					received_handshake,
1611					negotiated_fallback,
1612					notifications_sink,
1613				);
1614			},
1615			SwarmEvent::Behaviour(BehaviourOut::NotificationStreamReplaced {
1616				remote,
1617				set_id,
1618				notifications_sink,
1619			}) => {
1620				let _ = self.notif_protocol_handles[usize::from(set_id)]
1621					.report_notification_sink_replaced(remote, notifications_sink);
1622
1623				// TODO: Notifications might have been lost as a result of the previous
1624				// connection being dropped, and as a result it would be preferable to notify
1625				// the users of this fact by simulating the substream being closed then
1626				// reopened.
1627				// The code below doesn't compile because `role` is unknown. Propagating the
1628				// handshake of the secondary connections is quite an invasive change and
1629				// would conflict with https://github.com/paritytech/substrate/issues/6403.
1630				// Considering that dropping notifications is generally regarded as
1631				// acceptable, this bug is at the moment intentionally left there and is
1632				// intended to be fixed at the same time as
1633				// https://github.com/paritytech/substrate/issues/6403.
1634				// self.event_streams.send(Event::NotificationStreamClosed {
1635				// remote,
1636				// protocol,
1637				// });
1638				// self.event_streams.send(Event::NotificationStreamOpened {
1639				// remote,
1640				// protocol,
1641				// role,
1642				// });
1643			},
1644			SwarmEvent::Behaviour(BehaviourOut::NotificationStreamClosed { remote, set_id }) => {
1645				let _ = self.notif_protocol_handles[usize::from(set_id)]
1646					.report_substream_closed(remote);
1647			},
1648			SwarmEvent::Behaviour(BehaviourOut::NotificationsReceived {
1649				remote,
1650				set_id,
1651				notification,
1652			}) => {
1653				let _ = self.notif_protocol_handles[usize::from(set_id)]
1654					.report_notification_received(remote, notification);
1655			},
1656			SwarmEvent::Behaviour(BehaviourOut::Dht(event, duration)) => {
1657				match (self.metrics.as_ref(), duration) {
1658					(Some(metrics), Some(duration)) => {
1659						let query_type = match event {
1660							DhtEvent::ValueFound(_) => "value-found",
1661							DhtEvent::ValueNotFound(_) => "value-not-found",
1662							DhtEvent::ValuePut(_) => "value-put",
1663							DhtEvent::ValuePutFailed(_) => "value-put-failed",
1664							DhtEvent::PutRecordRequest(_, _, _, _) => "put-record-request",
1665							DhtEvent::StartProvidingFailed(_) => "start-providing-failed",
1666							DhtEvent::ProvidersFound(_, _) => "providers-found",
1667							DhtEvent::ProvidersNotFound(_) => "providers-not-found",
1668						};
1669						metrics
1670							.kademlia_query_duration
1671							.with_label_values(&[query_type])
1672							.observe(duration.as_secs_f64());
1673					},
1674					_ => {},
1675				}
1676
1677				self.event_streams.send(Event::Dht(event));
1678			},
1679			SwarmEvent::Behaviour(BehaviourOut::None) => {
1680				// Ignored event from lower layers.
1681			},
1682			SwarmEvent::ConnectionEstablished {
1683				peer_id,
1684				endpoint,
1685				num_established,
1686				concurrent_dial_errors,
1687				..
1688			} => {
1689				if let Some(errors) = concurrent_dial_errors {
1690					debug!(target: LOG_TARGET, "Libp2p => Connected({:?}) with errors: {:?}", peer_id, errors);
1691				} else {
1692					debug!(target: LOG_TARGET, "Libp2p => Connected({:?})", peer_id);
1693				}
1694
1695				if let Some(metrics) = self.metrics.as_ref() {
1696					let direction = match endpoint {
1697						ConnectedPoint::Dialer { .. } => "out",
1698						ConnectedPoint::Listener { .. } => "in",
1699					};
1700					metrics.connections_opened_total.with_label_values(&[direction]).inc();
1701
1702					if num_established.get() == 1 {
1703						metrics.distinct_peers_connections_opened_total.inc();
1704					}
1705				}
1706			},
1707			SwarmEvent::ConnectionClosed {
1708				connection_id,
1709				peer_id,
1710				cause,
1711				endpoint,
1712				num_established,
1713			} => {
1714				debug!(target: LOG_TARGET, "Libp2p => Disconnected({peer_id:?} via {connection_id:?}, {cause:?})");
1715				if let Some(metrics) = self.metrics.as_ref() {
1716					let direction = match endpoint {
1717						ConnectedPoint::Dialer { .. } => "out",
1718						ConnectedPoint::Listener { .. } => "in",
1719					};
1720					let reason = match cause {
1721						Some(ConnectionError::IO(_)) => "transport-error",
1722						Some(ConnectionError::KeepAliveTimeout) => "keep-alive-timeout",
1723						None => "actively-closed",
1724					};
1725					metrics.connections_closed_total.with_label_values(&[direction, reason]).inc();
1726
1727					// `num_established` represents the number of *remaining* connections.
1728					if num_established == 0 {
1729						metrics.distinct_peers_connections_closed_total.inc();
1730					}
1731				}
1732			},
1733			SwarmEvent::NewListenAddr { address, .. } => {
1734				trace!(target: LOG_TARGET, "Libp2p => NewListenAddr({})", address);
1735				if let Some(metrics) = self.metrics.as_ref() {
1736					metrics.listeners_local_addresses.inc();
1737				}
1738				self.listen_addresses.lock().insert(address.clone());
1739			},
1740			SwarmEvent::ExpiredListenAddr { address, .. } => {
1741				info!(target: LOG_TARGET, "📪 No longer listening on {}", address);
1742				if let Some(metrics) = self.metrics.as_ref() {
1743					metrics.listeners_local_addresses.dec();
1744				}
1745				self.listen_addresses.lock().remove(&address);
1746			},
1747			SwarmEvent::OutgoingConnectionError { connection_id, peer_id, error } => {
1748				if let Some(peer_id) = peer_id {
1749					trace!(
1750						target: LOG_TARGET,
1751						"Libp2p => Failed to reach {peer_id:?} via {connection_id:?}: {error}",
1752					);
1753
1754					let not_reported = !self.reported_invalid_boot_nodes.contains(&peer_id);
1755
1756					if let Some(addresses) =
1757						not_reported.then(|| self.boot_node_ids.get(&peer_id)).flatten()
1758					{
1759						if let DialError::WrongPeerId { obtained, endpoint } = &error {
1760							if let ConnectedPoint::Dialer {
1761								address,
1762								role_override: _,
1763								port_use: _,
1764							} = endpoint
1765							{
1766								let address_without_peer_id = parse_addr(address.clone().into())
1767									.map_or_else(|_| address.clone(), |r| r.1.into());
1768
1769								// Only report for address of boot node that was added at startup of
1770								// the node and not for any address that the node learned of the
1771								// boot node.
1772								if addresses.iter().any(|a| address_without_peer_id == *a) {
1773									warn!(
1774										"💔 The bootnode you want to connect to at `{address}` provided a \
1775										 different peer ID `{obtained}` than the one you expect `{peer_id}`.",
1776									);
1777
1778									self.reported_invalid_boot_nodes.insert(peer_id);
1779								}
1780							}
1781						}
1782					}
1783				}
1784
1785				if let Some(metrics) = self.metrics.as_ref() {
1786					let reason = match error {
1787						DialError::Denied { cause } =>
1788							if cause.downcast::<Exceeded>().is_ok() {
1789								Some("limit-reached")
1790							} else {
1791								None
1792							},
1793						DialError::LocalPeerId { .. } => Some("local-peer-id"),
1794						DialError::WrongPeerId { .. } => Some("invalid-peer-id"),
1795						DialError::Transport(_) => Some("transport-error"),
1796						DialError::NoAddresses |
1797						DialError::DialPeerConditionFalse(_) |
1798						DialError::Aborted => None, // ignore them
1799					};
1800					if let Some(reason) = reason {
1801						metrics.pending_connections_errors_total.with_label_values(&[reason]).inc();
1802					}
1803				}
1804			},
1805			SwarmEvent::Dialing { connection_id, peer_id } => {
1806				trace!(target: LOG_TARGET, "Libp2p => Dialing({peer_id:?}) via {connection_id:?}")
1807			},
1808			SwarmEvent::IncomingConnection { connection_id, local_addr, send_back_addr } => {
1809				trace!(target: LOG_TARGET, "Libp2p => IncomingConnection({local_addr},{send_back_addr} via {connection_id:?}))");
1810				if let Some(metrics) = self.metrics.as_ref() {
1811					metrics.incoming_connections_total.inc();
1812				}
1813			},
1814			SwarmEvent::IncomingConnectionError {
1815				connection_id,
1816				local_addr,
1817				send_back_addr,
1818				error,
1819			} => {
1820				debug!(
1821					target: LOG_TARGET,
1822					"Libp2p => IncomingConnectionError({local_addr},{send_back_addr} via {connection_id:?}): {error}"
1823				);
1824				if let Some(metrics) = self.metrics.as_ref() {
1825					let reason = match error {
1826						ListenError::Denied { cause } =>
1827							if cause.downcast::<Exceeded>().is_ok() {
1828								Some("limit-reached")
1829							} else {
1830								None
1831							},
1832						ListenError::WrongPeerId { .. } | ListenError::LocalPeerId { .. } =>
1833							Some("invalid-peer-id"),
1834						ListenError::Transport(_) => Some("transport-error"),
1835						ListenError::Aborted => None, // ignore it
1836					};
1837
1838					if let Some(reason) = reason {
1839						metrics
1840							.incoming_connections_errors_total
1841							.with_label_values(&[reason])
1842							.inc();
1843					}
1844				}
1845			},
1846			SwarmEvent::ListenerClosed { reason, addresses, .. } => {
1847				if let Some(metrics) = self.metrics.as_ref() {
1848					metrics.listeners_local_addresses.sub(addresses.len() as u64);
1849				}
1850				let mut listen_addresses = self.listen_addresses.lock();
1851				for addr in &addresses {
1852					listen_addresses.remove(addr);
1853				}
1854				drop(listen_addresses);
1855
1856				let addrs =
1857					addresses.into_iter().map(|a| a.to_string()).collect::<Vec<_>>().join(", ");
1858				match reason {
1859					Ok(()) => error!(
1860						target: LOG_TARGET,
1861						"📪 Libp2p listener ({}) closed gracefully",
1862						addrs
1863					),
1864					Err(e) => error!(
1865						target: LOG_TARGET,
1866						"📪 Libp2p listener ({}) closed: {}",
1867						addrs, e
1868					),
1869				}
1870			},
1871			SwarmEvent::ListenerError { error, .. } => {
1872				debug!(target: LOG_TARGET, "Libp2p => ListenerError: {}", error);
1873				if let Some(metrics) = self.metrics.as_ref() {
1874					metrics.listeners_errors_total.inc();
1875				}
1876			},
1877			SwarmEvent::NewExternalAddrCandidate { address } => {
1878				trace!(target: LOG_TARGET, "Libp2p => NewExternalAddrCandidate: {address:?}");
1879			},
1880			SwarmEvent::ExternalAddrConfirmed { address } => {
1881				trace!(target: LOG_TARGET, "Libp2p => ExternalAddrConfirmed: {address:?}");
1882			},
1883			SwarmEvent::ExternalAddrExpired { address } => {
1884				trace!(target: LOG_TARGET, "Libp2p => ExternalAddrExpired: {address:?}");
1885			},
1886			SwarmEvent::NewExternalAddrOfPeer { peer_id, address } => {
1887				trace!(target: LOG_TARGET, "Libp2p => NewExternalAddrOfPeer({peer_id:?}): {address:?}")
1888			},
1889			event => {
1890				warn!(target: LOG_TARGET, "New unknown SwarmEvent libp2p event: {event:?}");
1891			},
1892		}
1893	}
1894}
1895
1896impl<B, H> Unpin for NetworkWorker<B, H>
1897where
1898	B: BlockT + 'static,
1899	H: ExHashT,
1900{
1901}
1902
1903pub(crate) fn ensure_addresses_consistent_with_transport<'a>(
1904	addresses: impl Iterator<Item = &'a sc_network_types::multiaddr::Multiaddr>,
1905	transport: &TransportConfig,
1906) -> Result<(), Error> {
1907	use sc_network_types::multiaddr::Protocol;
1908
1909	if matches!(transport, TransportConfig::MemoryOnly) {
1910		let addresses: Vec<_> = addresses
1911			.filter(|x| x.iter().any(|y| !matches!(y, Protocol::Memory(_))))
1912			.cloned()
1913			.collect();
1914
1915		if !addresses.is_empty() {
1916			return Err(Error::AddressesForAnotherTransport {
1917				transport: transport.clone(),
1918				addresses,
1919			})
1920		}
1921	} else {
1922		let addresses: Vec<_> = addresses
1923			.filter(|x| x.iter().any(|y| matches!(y, Protocol::Memory(_))))
1924			.cloned()
1925			.collect();
1926
1927		if !addresses.is_empty() {
1928			return Err(Error::AddressesForAnotherTransport {
1929				transport: transport.clone(),
1930				addresses,
1931			})
1932		}
1933	}
1934
1935	Ok(())
1936}