Skip to main content

sc_network_sync/
engine.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//! `SyncingEngine` is the actor responsible for syncing Substrate chain
20//! to tip and keep the blockchain up to date with network updates.
21
22use crate::{
23	block_announce_validator::{
24		BlockAnnounceValidationResult, BlockAnnounceValidator as BlockAnnounceValidatorStream,
25	},
26	pending_responses::{PendingResponses, ResponseEvent},
27	service::{
28		self,
29		syncing_service::{SyncingService, ToServiceCommand},
30	},
31	strategy::{SyncingAction, SyncingStrategy},
32	types::{BadPeer, ExtendedPeerInfo, SyncEvent},
33	LOG_TARGET,
34};
35
36use codec::{Decode, DecodeAll, Encode};
37use futures::{channel::oneshot, StreamExt};
38use log::{debug, error, trace};
39use prometheus_endpoint::{
40	register, Counter, Gauge, MetricSource, Opts, PrometheusError, Registry, SourcedGauge, U64,
41};
42use schnellru::{ByLength, LruMap};
43use tokio::time::{Interval, MissedTickBehavior};
44
45use sc_client_api::{BlockBackend, HeaderBackend, ProofProvider};
46use sc_consensus::{import_queue::ImportQueueService, IncomingBlock};
47use sc_network::{
48	config::{FullNetworkConfiguration, NotificationHandshake, ProtocolId, SetConfig},
49	peer_store::PeerStoreProvider,
50	request_responses::{OutboundFailure, RequestFailure},
51	service::{
52		traits::{Direction, NotificationConfig, NotificationEvent, ValidationResult},
53		NotificationMetrics,
54	},
55	types::ProtocolName,
56	utils::LruHashSet,
57	NetworkBackend, NotificationService, ReputationChange,
58};
59use sc_network_common::{
60	role::Roles,
61	sync::message::{BlockAnnounce, BlockAnnouncesHandshake, BlockState},
62};
63use sc_network_types::PeerId;
64use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedReceiver, TracingUnboundedSender};
65use sp_blockchain::{Error as ClientError, HeaderMetadata};
66use sp_consensus::{block_validation::BlockAnnounceValidator, BlockOrigin};
67use sp_runtime::{
68	traits::{Block as BlockT, Header, NumberFor, Zero},
69	Justifications,
70};
71
72use std::{
73	collections::{HashMap, HashSet},
74	iter,
75	num::NonZeroUsize,
76	sync::{
77		atomic::{AtomicBool, AtomicUsize, Ordering},
78		Arc,
79	},
80};
81
82/// Interval at which we perform time based maintenance
83const TICK_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(1100);
84
85/// Maximum number of known block hashes to keep for a peer.
86const MAX_KNOWN_BLOCKS: usize = 1024; // ~32kb per peer + LruHashSet overhead
87
88/// Maximum allowed size for a block announce.
89const MAX_BLOCK_ANNOUNCE_SIZE: u64 = 1024 * 1024;
90
91/// Generate the block announces protocol name from the genesis hash and fork id.
92pub fn block_announces_protocol_name<Hash: AsRef<[u8]>>(
93	genesis_hash: Hash,
94	fork_id: Option<&str>,
95) -> String {
96	let genesis_hash = genesis_hash.as_ref();
97	if let Some(fork_id) = fork_id {
98		format!("/{}/{}/block-announces/1", array_bytes::bytes2hex("", genesis_hash), fork_id)
99	} else {
100		format!("/{}/block-announces/1", array_bytes::bytes2hex("", genesis_hash))
101	}
102}
103
104/// Generate the legacy block announces protocol name from chain specific protocol identifier.
105pub fn block_announces_legacy_protocol_name(protocol_id: &ProtocolId) -> String {
106	format!("/{}/block-announces/1", protocol_id.as_ref())
107}
108
109mod rep {
110	use sc_network::ReputationChange as Rep;
111	/// Peer has different genesis.
112	pub const GENESIS_MISMATCH: Rep = Rep::new_fatal("Genesis mismatch");
113	/// Peer send us a block announcement that failed at validation.
114	pub const BAD_BLOCK_ANNOUNCEMENT: Rep = Rep::new(-(1 << 12), "Bad block announcement");
115	/// Peer is on unsupported protocol version.
116	pub const BAD_PROTOCOL: Rep = Rep::new_fatal("Unsupported protocol");
117	/// Reputation change when a peer refuses a request.
118	pub const REFUSED: Rep = Rep::new(-(1 << 10), "Request refused");
119	/// Reputation change when a peer doesn't respond in time to our messages.
120	pub const TIMEOUT: Rep = Rep::new(-(1 << 10), "Request timeout");
121	/// Reputation change when a peer connection failed with IO error.
122	pub const IO: Rep = Rep::new(-(1 << 10), "IO error during request");
123}
124
125struct Metrics {
126	peers: Gauge<U64>,
127	import_queue_blocks_submitted: Counter<U64>,
128	import_queue_justifications_submitted: Counter<U64>,
129}
130
131impl Metrics {
132	fn register(r: &Registry, major_syncing: Arc<AtomicBool>) -> Result<Self, PrometheusError> {
133		MajorSyncingGauge::register(r, major_syncing)?;
134		Ok(Self {
135			peers: {
136				let g = Gauge::new("substrate_sync_peers", "Number of peers we sync with")?;
137				register(g, r)?
138			},
139			import_queue_blocks_submitted: {
140				let c = Counter::new(
141					"substrate_sync_import_queue_blocks_submitted",
142					"Number of blocks submitted to the import queue.",
143				)?;
144				register(c, r)?
145			},
146			import_queue_justifications_submitted: {
147				let c = Counter::new(
148					"substrate_sync_import_queue_justifications_submitted",
149					"Number of justifications submitted to the import queue.",
150				)?;
151				register(c, r)?
152			},
153		})
154	}
155}
156
157/// The "major syncing" metric.
158#[derive(Clone)]
159pub struct MajorSyncingGauge(Arc<AtomicBool>);
160
161impl MajorSyncingGauge {
162	/// Registers the [`MajorSyncGauge`] metric whose value is
163	/// obtained from the given `AtomicBool`.
164	fn register(registry: &Registry, value: Arc<AtomicBool>) -> Result<(), PrometheusError> {
165		prometheus_endpoint::register(
166			SourcedGauge::new(
167				&Opts::new(
168					"substrate_sub_libp2p_is_major_syncing",
169					"Whether the node is performing a major sync or not.",
170				),
171				MajorSyncingGauge(value),
172			)?,
173			registry,
174		)?;
175
176		Ok(())
177	}
178}
179
180impl MetricSource for MajorSyncingGauge {
181	type N = u64;
182
183	fn collect(&self, mut set: impl FnMut(&[&str], Self::N)) {
184		set(&[], self.0.load(Ordering::Relaxed) as u64);
185	}
186}
187
188/// Peer information
189#[derive(Debug)]
190pub struct Peer<B: BlockT> {
191	pub info: ExtendedPeerInfo<B>,
192	/// Holds a set of blocks known to this peer.
193	pub known_blocks: LruHashSet<B::Hash>,
194	/// Is the peer inbound.
195	inbound: bool,
196}
197
198pub struct SyncingEngine<B: BlockT, Client> {
199	/// Syncing strategy.
200	strategy: Box<dyn SyncingStrategy<B>>,
201
202	/// Blockchain client.
203	client: Arc<Client>,
204
205	/// Number of peers we're connected to.
206	num_connected: Arc<AtomicUsize>,
207
208	/// Are we actively catching up with the chain?
209	is_major_syncing: Arc<AtomicBool>,
210
211	/// Network service.
212	network_service: service::network::NetworkServiceHandle,
213
214	/// Channel for receiving service commands
215	service_rx: TracingUnboundedReceiver<ToServiceCommand<B>>,
216
217	/// Assigned roles.
218	roles: Roles,
219
220	/// Genesis hash.
221	genesis_hash: B::Hash,
222
223	/// Set of channels for other protocols that have subscribed to syncing events.
224	event_streams: Vec<TracingUnboundedSender<SyncEvent>>,
225
226	/// Interval at which we call `tick`.
227	tick_timeout: Interval,
228
229	/// All connected peers. Contains both full and light node peers.
230	peers: HashMap<PeerId, Peer<B>>,
231
232	/// List of nodes for which we perform additional logging because they are important for the
233	/// user.
234	important_peers: HashSet<PeerId>,
235
236	/// Actual list of connected no-slot nodes.
237	default_peers_set_no_slot_connected_peers: HashSet<PeerId>,
238
239	/// List of nodes that should never occupy peer slots.
240	default_peers_set_no_slot_peers: HashSet<PeerId>,
241
242	/// Value that was passed as part of the configuration. Used to cap the number of full
243	/// nodes.
244	default_peers_set_num_full: usize,
245
246	/// Number of slots to allocate to light nodes.
247	default_peers_set_num_light: usize,
248
249	/// Maximum number of inbound peers.
250	max_in_peers: usize,
251
252	/// Number of inbound peers accepted so far.
253	num_in_peers: usize,
254
255	/// Dynamic updatable no-slot peer set (see [`SyncingService::set_no_slot_peers`]).
256	/// Treated identically to `default_peers_set_no_slot_peers` for inbound slot accounting.
257	dynamic_no_slot_peers: HashSet<PeerId>,
258
259	/// Async processor of block announce validations.
260	block_announce_validator: BlockAnnounceValidatorStream<B>,
261
262	/// A cache for the data that was associated to a block announcement.
263	block_announce_data_cache: LruMap<B::Hash, Vec<u8>>,
264
265	/// The `PeerId`'s of all boot nodes.
266	boot_node_ids: HashSet<PeerId>,
267
268	/// Protocol name used for block announcements
269	block_announce_protocol_name: ProtocolName,
270
271	/// Prometheus metrics.
272	metrics: Option<Metrics>,
273
274	/// Handle that is used to communicate with `sc_network::Notifications`.
275	notification_service: Box<dyn NotificationService>,
276
277	/// Handle to `PeerStore`.
278	peer_store_handle: Arc<dyn PeerStoreProvider>,
279
280	/// Pending responses
281	pending_responses: PendingResponses,
282
283	/// Handle to import queue.
284	import_queue: Box<dyn ImportQueueService<B>>,
285}
286
287impl<B: BlockT, Client> SyncingEngine<B, Client>
288where
289	B: BlockT,
290	Client: HeaderBackend<B>
291		+ BlockBackend<B>
292		+ HeaderMetadata<B, Error = sp_blockchain::Error>
293		+ ProofProvider<B>
294		+ Send
295		+ Sync
296		+ 'static,
297{
298	pub fn new<N>(
299		roles: Roles,
300		client: Arc<Client>,
301		metrics_registry: Option<&Registry>,
302		network_metrics: NotificationMetrics,
303		net_config: &FullNetworkConfiguration<B, <B as BlockT>::Hash, N>,
304		protocol_id: ProtocolId,
305		fork_id: Option<&str>,
306		block_announce_validator: Box<dyn BlockAnnounceValidator<B> + Send>,
307		syncing_strategy: Box<dyn SyncingStrategy<B>>,
308		network_service: service::network::NetworkServiceHandle,
309		import_queue: Box<dyn ImportQueueService<B>>,
310		peer_store_handle: Arc<dyn PeerStoreProvider>,
311	) -> Result<(Self, SyncingService<B>, N::NotificationProtocolConfig), ClientError>
312	where
313		N: NetworkBackend<B, <B as BlockT>::Hash>,
314	{
315		let cache_capacity = (net_config.network_config.default_peers_set.in_peers +
316			net_config.network_config.default_peers_set.out_peers)
317			.max(1);
318		let important_peers = {
319			let mut imp_p = HashSet::new();
320			for reserved in &net_config.network_config.default_peers_set.reserved_nodes {
321				imp_p.insert(reserved.peer_id);
322			}
323			for config in net_config.notification_protocols() {
324				let peer_ids = config.set_config().reserved_nodes.iter().map(|info| info.peer_id);
325				imp_p.extend(peer_ids);
326			}
327
328			imp_p.shrink_to_fit();
329			imp_p
330		};
331		let boot_node_ids = {
332			let mut list = HashSet::new();
333			for node in &net_config.network_config.boot_nodes {
334				list.insert(node.peer_id);
335			}
336			list.shrink_to_fit();
337			list
338		};
339		let default_peers_set_no_slot_peers = {
340			let mut no_slot_p: HashSet<PeerId> = net_config
341				.network_config
342				.default_peers_set
343				.reserved_nodes
344				.iter()
345				.map(|reserved| reserved.peer_id)
346				.collect();
347			no_slot_p.shrink_to_fit();
348			no_slot_p
349		};
350		let default_peers_set_num_full =
351			net_config.network_config.default_peers_set_num_full as usize;
352		let default_peers_set_num_light = {
353			let total = net_config.network_config.default_peers_set.out_peers +
354				net_config.network_config.default_peers_set.in_peers;
355			total.saturating_sub(net_config.network_config.default_peers_set_num_full) as usize
356		};
357
358		let info = client.info();
359
360		let (block_announce_config, notification_service) =
361			Self::get_block_announce_proto_config::<N>(
362				protocol_id,
363				fork_id,
364				roles,
365				info.best_number,
366				info.best_hash,
367				info.genesis_hash,
368				&net_config.network_config.default_peers_set,
369				network_metrics,
370				Arc::clone(&peer_store_handle),
371			);
372
373		let block_announce_protocol_name = block_announce_config.protocol_name().clone();
374		let (tx, service_rx) = tracing_unbounded("mpsc_chain_sync", 100_000);
375		let num_connected = Arc::new(AtomicUsize::new(0));
376		let is_major_syncing = Arc::new(AtomicBool::new(false));
377
378		// `default_peers_set.in_peers` contains an unspecified amount of light peers so the number
379		// of full inbound peers must be calculated from the total full peer count
380		let max_full_peers = net_config.network_config.default_peers_set_num_full;
381		let max_out_peers = net_config.network_config.default_peers_set.out_peers;
382		let max_in_peers = (max_full_peers - max_out_peers) as usize;
383
384		let tick_timeout = {
385			let mut interval = tokio::time::interval(TICK_TIMEOUT);
386			interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
387			interval
388		};
389
390		Ok((
391			Self {
392				roles,
393				client,
394				strategy: syncing_strategy,
395				network_service,
396				peers: HashMap::new(),
397				block_announce_data_cache: LruMap::new(ByLength::new(cache_capacity)),
398				block_announce_protocol_name,
399				block_announce_validator: BlockAnnounceValidatorStream::new(
400					block_announce_validator,
401				),
402				num_connected: num_connected.clone(),
403				is_major_syncing: is_major_syncing.clone(),
404				service_rx,
405				genesis_hash: info.genesis_hash,
406				important_peers,
407				default_peers_set_no_slot_connected_peers: HashSet::new(),
408				boot_node_ids,
409				default_peers_set_no_slot_peers,
410				default_peers_set_num_full,
411				default_peers_set_num_light,
412				num_in_peers: 0usize,
413				max_in_peers,
414				dynamic_no_slot_peers: HashSet::new(),
415				event_streams: Vec::new(),
416				notification_service,
417				tick_timeout,
418				peer_store_handle,
419				metrics: if let Some(r) = metrics_registry {
420					match Metrics::register(r, is_major_syncing.clone()) {
421						Ok(metrics) => Some(metrics),
422						Err(err) => {
423							log::error!(target: LOG_TARGET, "Failed to register metrics {err:?}");
424							None
425						},
426					}
427				} else {
428					None
429				},
430				pending_responses: PendingResponses::new(),
431				import_queue,
432			},
433			SyncingService::new(tx, num_connected, is_major_syncing),
434			block_announce_config,
435		))
436	}
437
438	fn update_peer_info(
439		&mut self,
440		peer_id: &PeerId,
441		best_hash: B::Hash,
442		best_number: NumberFor<B>,
443	) {
444		if let Some(ref mut peer) = self.peers.get_mut(peer_id) {
445			peer.info.best_hash = best_hash;
446			peer.info.best_number = best_number;
447		}
448	}
449
450	/// Process the result of the block announce validation.
451	fn process_block_announce_validation_result(
452		&mut self,
453		validation_result: BlockAnnounceValidationResult<B::Header>,
454	) {
455		match validation_result {
456			BlockAnnounceValidationResult::Skip { peer_id: _ } => {},
457			BlockAnnounceValidationResult::Process { is_new_best, peer_id, announce } => {
458				if let Some((best_hash, best_number)) =
459					self.strategy.on_validated_block_announce(is_new_best, peer_id, &announce)
460				{
461					self.update_peer_info(&peer_id, best_hash, best_number);
462				}
463
464				if let Some(data) = announce.data {
465					if !data.is_empty() {
466						self.block_announce_data_cache.insert(announce.header.hash(), data);
467					}
468				}
469			},
470			BlockAnnounceValidationResult::Failure { peer_id, disconnect } => {
471				if disconnect {
472					log::debug!(
473						target: LOG_TARGET,
474						"Disconnecting peer {peer_id} due to block announce validation failure",
475					);
476					self.network_service
477						.disconnect_peer(peer_id, self.block_announce_protocol_name.clone());
478				}
479
480				self.network_service.report_peer(peer_id, rep::BAD_BLOCK_ANNOUNCEMENT);
481			},
482		}
483	}
484
485	/// Push a block announce validation.
486	pub fn push_block_announce_validation(
487		&mut self,
488		peer_id: PeerId,
489		announce: BlockAnnounce<B::Header>,
490	) {
491		let hash = announce.header.hash();
492
493		let peer = match self.peers.get_mut(&peer_id) {
494			Some(p) => p,
495			None => {
496				log::error!(
497					target: LOG_TARGET,
498					"Received block announce from disconnected peer {peer_id}",
499				);
500				debug_assert!(false);
501				return;
502			},
503		};
504		peer.known_blocks.insert(hash);
505
506		if peer.info.roles.is_full() {
507			let is_best = match announce.state.unwrap_or(BlockState::Best) {
508				BlockState::Best => true,
509				BlockState::Normal => false,
510			};
511
512			self.block_announce_validator
513				.push_block_announce_validation(peer_id, hash, announce, is_best);
514		}
515	}
516
517	/// Make sure an important block is propagated to peers.
518	///
519	/// In chain-based consensus, we often need to make sure non-best forks are
520	/// at least temporarily synced.
521	pub fn announce_block(&mut self, hash: B::Hash, data: Option<Vec<u8>>) {
522		let header = match self.client.header(hash) {
523			Ok(Some(header)) => header,
524			Ok(None) => {
525				log::warn!(target: LOG_TARGET, "Trying to announce unknown block: {hash}");
526				return;
527			},
528			Err(e) => {
529				log::warn!(target: LOG_TARGET, "Error reading block header {hash}: {e}");
530				return;
531			},
532		};
533
534		// don't announce genesis block since it will be ignored
535		if header.number().is_zero() {
536			return;
537		}
538
539		let is_best = self.client.info().best_hash == hash;
540		log::debug!(target: LOG_TARGET, "Reannouncing block {hash:?} is_best: {is_best}");
541
542		let data = data
543			.or_else(|| self.block_announce_data_cache.get(&hash).cloned())
544			.unwrap_or_default();
545
546		for (peer_id, ref mut peer) in self.peers.iter_mut() {
547			let inserted = peer.known_blocks.insert(hash);
548			if inserted {
549				log::trace!(target: LOG_TARGET, "Announcing block {hash:?} to {peer_id}");
550				let message = BlockAnnounce {
551					header: header.clone(),
552					state: if is_best { Some(BlockState::Best) } else { Some(BlockState::Normal) },
553					data: Some(data.clone()),
554				};
555
556				let _ = self.notification_service.send_sync_notification(peer_id, message.encode());
557			}
558		}
559	}
560
561	pub async fn run(mut self) {
562		loop {
563			tokio::select! {
564				_ = self.tick_timeout.tick() => {
565					// TODO: This tick should not be necessary, but
566					//  `self.process_strategy_actions()` is not called in some cases otherwise and
567					//  some tests fail because of this
568				},
569				command = self.service_rx.select_next_some() =>
570					self.process_service_command(command),
571				notification_event = self.notification_service.next_event() => match notification_event {
572					Some(event) => self.process_notification_event(event),
573					None => {
574						error!(
575							target: LOG_TARGET,
576							"Terminating `SyncingEngine` because `NotificationService` has terminated.",
577						);
578
579						return;
580					}
581				},
582				response_event = self.pending_responses.select_next_some() =>
583					self.process_response_event(response_event),
584				validation_result = self.block_announce_validator.select_next_some() =>
585					self.process_block_announce_validation_result(validation_result),
586			}
587
588			// Update atomic variables
589			self.is_major_syncing.store(self.strategy.is_major_syncing(), Ordering::Relaxed);
590
591			// Process actions requested by a syncing strategy.
592			if let Err(e) = self.process_strategy_actions() {
593				error!(
594					target: LOG_TARGET,
595					"Terminating `SyncingEngine` due to fatal error: {e:?}.",
596				);
597				return;
598			}
599		}
600	}
601
602	fn process_strategy_actions(&mut self) -> Result<(), ClientError> {
603		for action in self.strategy.actions(&self.network_service)? {
604			match action {
605				SyncingAction::StartRequest { peer_id, key, request } => {
606					if !self.peers.contains_key(&peer_id) {
607						trace!(
608							target: LOG_TARGET,
609							"Cannot start request with strategy key {key:?} to unknown peer \
610							{peer_id}",
611						);
612						debug_assert!(false);
613						continue;
614					}
615
616					self.pending_responses.insert(peer_id, key, request);
617				},
618				SyncingAction::CancelRequest { peer_id, key } => {
619					let removed = self.pending_responses.remove(peer_id, key);
620
621					trace!(
622						target: LOG_TARGET,
623						"Processed `SyncingAction::CancelRequest`, response removed: {removed}.",
624					);
625				},
626				SyncingAction::DropPeer(BadPeer(peer_id, rep)) => {
627					self.pending_responses.remove_all(&peer_id);
628					self.network_service
629						.disconnect_peer(peer_id, self.block_announce_protocol_name.clone());
630					self.network_service.report_peer(peer_id, rep);
631
632					trace!(target: LOG_TARGET, "{peer_id:?} dropped: {rep:?}.");
633				},
634				SyncingAction::ImportBlocks { origin, blocks } => {
635					let count = blocks.len();
636					self.import_blocks(origin, blocks);
637
638					trace!(
639						target: LOG_TARGET,
640						"Processed `ChainSyncAction::ImportBlocks` with {count} blocks.",
641					);
642				},
643				SyncingAction::ImportJustifications { peer_id, hash, number, justifications } => {
644					self.import_justifications(peer_id, hash, number, justifications);
645
646					trace!(
647						target: LOG_TARGET,
648						"Processed `ChainSyncAction::ImportJustifications` from peer {} for block {} ({}).",
649						peer_id,
650						hash,
651						number,
652					)
653				},
654				// Nothing to do, this is handled internally by `PolkadotSyncingStrategy`.
655				SyncingAction::Finished => {},
656			}
657		}
658
659		Ok(())
660	}
661
662	/// Reconcile per-peer slot tracking against `new_dynamic_no_slot`. See
663	/// [`apply_no_slot_set_inner`] for details.
664	fn apply_no_slot_set(&mut self, new_dynamic_no_slot: HashSet<PeerId>) {
665		let connected_peers = &self.peers;
666		apply_no_slot_set_inner(
667			|peer_id| {
668				connected_peers
669					.get(peer_id)
670					.map(|peer| peer.inbound && peer.info.roles.is_full())
671			},
672			&self.default_peers_set_no_slot_peers,
673			&self.dynamic_no_slot_peers,
674			&new_dynamic_no_slot,
675			&mut self.default_peers_set_no_slot_connected_peers,
676			&mut self.num_in_peers,
677			self.max_in_peers,
678			&self.network_service,
679			&self.block_announce_protocol_name,
680		);
681		self.dynamic_no_slot_peers = new_dynamic_no_slot;
682	}
683
684	fn process_service_command(&mut self, command: ToServiceCommand<B>) {
685		match command {
686			ToServiceCommand::SetSyncForkRequest(peers, hash, number) => {
687				self.strategy.set_sync_fork_request(peers, &hash, number);
688			},
689			ToServiceCommand::EventStream(tx) => {
690				// Let a new subscriber know about already connected peers.
691				for (peer_id, peer) in self.peers.iter() {
692					let _ = tx.unbounded_send(SyncEvent::PeerConnected {
693						peer_id: *peer_id,
694						roles: peer.info.roles,
695					});
696				}
697				self.event_streams.push(tx);
698			},
699			ToServiceCommand::RequestJustification(hash, number) => {
700				self.strategy.request_justification(&hash, number)
701			},
702			ToServiceCommand::ClearJustificationRequests => {
703				self.strategy.clear_justification_requests()
704			},
705			ToServiceCommand::BlocksProcessed(imported, count, results) => {
706				self.strategy.on_blocks_processed(imported, count, results);
707			},
708			ToServiceCommand::JustificationImported(peer_id, hash, number, import_result) => {
709				let success =
710					matches!(import_result, sc_consensus::JustificationImportResult::Success);
711				self.strategy.on_justification_import(hash, number, success);
712
713				match import_result {
714					sc_consensus::JustificationImportResult::OutdatedJustification => {
715						log::info!(
716							target: LOG_TARGET,
717							"💔 Outdated justification provided by {peer_id} for #{hash}",
718						);
719					},
720					sc_consensus::JustificationImportResult::Failure => {
721						log::info!(
722							target: LOG_TARGET,
723							"💔 Invalid justification provided by {peer_id} for #{hash}",
724						);
725						self.network_service
726							.disconnect_peer(peer_id, self.block_announce_protocol_name.clone());
727						self.network_service.report_peer(
728							peer_id,
729							ReputationChange::new_fatal("Invalid justification"),
730						);
731					},
732					sc_consensus::JustificationImportResult::Success => {
733						log::debug!(
734							target: LOG_TARGET,
735							"Justification for block #{hash} ({number}) imported from {peer_id} successfully",
736						);
737					},
738				}
739			},
740			ToServiceCommand::AnnounceBlock(hash, data) => self.announce_block(hash, data),
741			ToServiceCommand::NewBestBlockImported(hash, number) => {
742				log::debug!(target: LOG_TARGET, "New best block imported {:?}/#{}", hash, number);
743
744				self.strategy.update_chain_info(&hash, number);
745				let _ = self.notification_service.try_set_handshake(
746					BlockAnnouncesHandshake::<B>::build(
747						self.roles,
748						number,
749						hash,
750						self.genesis_hash,
751					)
752					.encode(),
753				);
754			},
755			ToServiceCommand::Status(tx) => {
756				let _ = tx.send(self.strategy.status());
757			},
758			ToServiceCommand::NumActivePeers(tx) => {
759				let _ = tx.send(self.num_active_peers());
760			},
761			ToServiceCommand::NumDownloadedBlocks(tx) => {
762				let _ = tx.send(self.strategy.num_downloaded_blocks());
763			},
764			ToServiceCommand::NumSyncRequests(tx) => {
765				let _ = tx.send(self.strategy.num_sync_requests());
766			},
767			ToServiceCommand::PeersInfo(tx) => {
768				let peers_info =
769					self.peers.iter().map(|(peer_id, peer)| (*peer_id, peer.info)).collect();
770				let _ = tx.send(peers_info);
771			},
772			ToServiceCommand::SetNoSlotPeers(peers) => self.apply_no_slot_set(peers),
773			ToServiceCommand::OnBlockFinalized(hash, header) => {
774				self.strategy.on_block_finalized(&hash, *header.number())
775			},
776		}
777	}
778
779	fn process_notification_event(&mut self, event: NotificationEvent) {
780		match event {
781			NotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx } => {
782				let validation_result = self
783					.validate_connection(&peer, handshake, Direction::Inbound)
784					.map_or(ValidationResult::Reject, |_| ValidationResult::Accept);
785
786				let _ = result_tx.send(validation_result);
787			},
788			NotificationEvent::NotificationStreamOpened { peer, handshake, direction, .. } => {
789				log::debug!(
790					target: LOG_TARGET,
791					"Substream opened for {peer}, handshake {handshake:?}"
792				);
793
794				match self.validate_connection(&peer, handshake, direction) {
795					Ok(handshake) => {
796						if self.on_sync_peer_connected(peer, &handshake, direction).is_err() {
797							log::debug!(target: LOG_TARGET, "Failed to register peer {peer}");
798							self.network_service
799								.disconnect_peer(peer, self.block_announce_protocol_name.clone());
800						}
801					},
802					Err(wrong_genesis) => {
803						log::debug!(target: LOG_TARGET, "`SyncingEngine` rejected {peer}");
804
805						if wrong_genesis {
806							self.peer_store_handle.report_peer(peer, rep::GENESIS_MISMATCH);
807						}
808
809						self.network_service
810							.disconnect_peer(peer, self.block_announce_protocol_name.clone());
811					},
812				}
813			},
814			NotificationEvent::NotificationStreamClosed { peer } => {
815				self.on_sync_peer_disconnected(peer);
816			},
817			NotificationEvent::NotificationReceived { peer, notification } => {
818				if !self.peers.contains_key(&peer) {
819					log::error!(
820						target: LOG_TARGET,
821						"received notification from {peer} who had been earlier refused by `SyncingEngine`",
822					);
823					return;
824				}
825
826				let Ok(announce) = BlockAnnounce::decode(&mut notification.as_ref()) else {
827					log::warn!(target: LOG_TARGET, "failed to decode block announce");
828					return;
829				};
830
831				self.push_block_announce_validation(peer, announce);
832			},
833		}
834	}
835
836	fn is_no_slot_peer(&self, peer_id: &PeerId) -> bool {
837		self.default_peers_set_no_slot_peers.contains(peer_id) ||
838			self.dynamic_no_slot_peers.contains(peer_id)
839	}
840
841	/// Called by peer when it is disconnecting.
842	///
843	/// Returns a result if the handshake of this peer was indeed accepted.
844	fn on_sync_peer_disconnected(&mut self, peer_id: PeerId) {
845		let Some(info) = self.peers.remove(&peer_id) else {
846			log::debug!(target: LOG_TARGET, "{peer_id} does not exist in `SyncingEngine`");
847			return;
848		};
849		if let Some(metrics) = &self.metrics {
850			metrics.peers.dec();
851		}
852		self.num_connected.fetch_sub(1, Ordering::AcqRel);
853
854		if self.important_peers.contains(&peer_id) {
855			log::warn!(target: LOG_TARGET, "Reserved peer {peer_id} disconnected");
856		} else {
857			log::debug!(target: LOG_TARGET, "{peer_id} disconnected");
858		}
859
860		if !self.default_peers_set_no_slot_connected_peers.remove(&peer_id) &&
861			info.inbound &&
862			info.info.roles.is_full()
863		{
864			match self.num_in_peers.checked_sub(1) {
865				Some(value) => {
866					self.num_in_peers = value;
867				},
868				None => {
869					log::error!(
870						target: LOG_TARGET,
871						"trying to disconnect an inbound node which is not counted as inbound"
872					);
873					debug_assert!(false);
874				},
875			}
876		}
877
878		self.strategy.remove_peer(&peer_id);
879		self.pending_responses.remove_all(&peer_id);
880		self.event_streams
881			.retain(|stream| stream.unbounded_send(SyncEvent::PeerDisconnected(peer_id)).is_ok());
882	}
883
884	/// Validate received handshake.
885	fn validate_handshake(
886		&mut self,
887		peer_id: &PeerId,
888		handshake: Vec<u8>,
889	) -> Result<BlockAnnouncesHandshake<B>, bool> {
890		log::trace!(target: LOG_TARGET, "Validate handshake for {peer_id}");
891
892		let handshake = <BlockAnnouncesHandshake<B> as DecodeAll>::decode_all(&mut &handshake[..])
893			.map_err(|error| {
894				log::debug!(target: LOG_TARGET, "Failed to decode handshake for {peer_id}: {error:?}");
895				false
896			})?;
897
898		if handshake.genesis_hash != self.genesis_hash {
899			if self.important_peers.contains(&peer_id) {
900				log::error!(
901					target: LOG_TARGET,
902					"Reserved peer id `{peer_id}` is on a different chain (our genesis: {} theirs: {})",
903					self.genesis_hash,
904					handshake.genesis_hash,
905				);
906			} else if self.boot_node_ids.contains(&peer_id) {
907				log::error!(
908					target: LOG_TARGET,
909					"Bootnode with peer id `{peer_id}` is on a different chain (our genesis: {} theirs: {})",
910					self.genesis_hash,
911					handshake.genesis_hash,
912				);
913			} else {
914				log::debug!(
915					target: LOG_TARGET,
916					"Peer is on different chain (our genesis: {} theirs: {})",
917					self.genesis_hash,
918					handshake.genesis_hash
919				);
920			}
921
922			return Err(true);
923		}
924
925		Ok(handshake)
926	}
927
928	/// Validate connection.
929	// NOTE Returning `Err(bool)` is a really ugly hack to work around the issue
930	// that `ProtocolController` thinks the peer is connected when in fact it can
931	// still be under validation. If the peer has different genesis than the
932	// local node the validation fails but the peer cannot be reported in
933	// `validate_connection()` as that is also called by
934	// `ValidateInboundSubstream` which means that the peer is still being
935	// validated and banning the peer when handling that event would
936	// result in peer getting dropped twice.
937	//
938	// The proper way to fix this is to integrate `ProtocolController` more
939	// tightly with `NotificationService` or add an additional API call for
940	// banning pre-accepted peers (which is not desirable)
941	fn validate_connection(
942		&mut self,
943		peer_id: &PeerId,
944		handshake: Vec<u8>,
945		direction: Direction,
946	) -> Result<BlockAnnouncesHandshake<B>, bool> {
947		log::trace!(target: LOG_TARGET, "New peer {peer_id} {handshake:?}");
948
949		let handshake = self.validate_handshake(peer_id, handshake)?;
950
951		if self.peers.contains_key(&peer_id) {
952			log::error!(
953				target: LOG_TARGET,
954				"Called `validate_connection()` with already connected peer {peer_id}",
955			);
956			debug_assert!(false);
957			return Err(false);
958		}
959
960		let no_slot_peer = self.is_no_slot_peer(&peer_id);
961		let this_peer_reserved_slot: usize = if no_slot_peer { 1 } else { 0 };
962
963		if handshake.roles.is_full() &&
964			self.strategy.num_peers() >=
965				self.default_peers_set_num_full +
966					self.default_peers_set_no_slot_connected_peers.len() +
967					this_peer_reserved_slot
968		{
969			log::debug!(
970				target: LOG_TARGET,
971				"Too many full nodes, rejecting {peer_id} (no_slot_peer={no_slot_peer}, num_peers={}, full_cap={}, no_slot_connected={}, this_reserved={})",
972				self.strategy.num_peers(),
973				self.default_peers_set_num_full,
974				self.default_peers_set_no_slot_connected_peers.len(),
975				this_peer_reserved_slot,
976			);
977			return Err(false);
978		}
979
980		// make sure to accept no more than `--in-peers` many full nodes
981		if !no_slot_peer &&
982			handshake.roles.is_full() &&
983			direction.is_inbound() &&
984			self.num_in_peers >= self.max_in_peers
985		{
986			if self.num_in_peers > self.max_in_peers {
987				log::warn!(
988					target: LOG_TARGET,
989					"num_in_peers ({}) exceeds max_in_peers ({}), this is a slot accounting bug ",
990					self.num_in_peers,
991					self.max_in_peers,
992				);
993				debug_assert!(false);
994			}
995			log::debug!(
996				target: LOG_TARGET,
997				"All inbound slots have been consumed, rejecting {peer_id} (no_slot_peer={no_slot_peer}, num_in_peers={}, max_in_peers={})",
998				self.num_in_peers,
999				self.max_in_peers,
1000			);
1001			return Err(false);
1002		}
1003
1004		// make sure that all slots are not occupied by light peers
1005		//
1006		// `ChainSync` only accepts full peers whereas `SyncingEngine` accepts both full and light
1007		// peers. Verify that there is a slot in `SyncingEngine` for the inbound light peer
1008		if handshake.roles.is_light() &&
1009			(self.peers.len() - self.strategy.num_peers()) >= self.default_peers_set_num_light
1010		{
1011			log::debug!(target: LOG_TARGET, "Too many light nodes, rejecting {peer_id}");
1012			return Err(false);
1013		}
1014
1015		Ok(handshake)
1016	}
1017
1018	/// Called on the first connection between two peers on the default set, after their exchange
1019	/// of handshake.
1020	///
1021	/// Returns `Ok` if the handshake is accepted and the peer added to the list of peers we sync
1022	/// from.
1023	fn on_sync_peer_connected(
1024		&mut self,
1025		peer_id: PeerId,
1026		status: &BlockAnnouncesHandshake<B>,
1027		direction: Direction,
1028	) -> Result<(), ()> {
1029		log::trace!(target: LOG_TARGET, "New peer {peer_id} {status:?}");
1030
1031		let peer = Peer {
1032			info: ExtendedPeerInfo {
1033				roles: status.roles,
1034				best_hash: status.best_hash,
1035				best_number: status.best_number,
1036			},
1037			known_blocks: LruHashSet::new(
1038				NonZeroUsize::new(MAX_KNOWN_BLOCKS).expect("Constant is nonzero"),
1039			),
1040			inbound: direction.is_inbound(),
1041		};
1042
1043		// Only forward full peers to syncing strategy.
1044		if status.roles.is_full() {
1045			self.strategy.add_peer(peer_id, peer.info.best_hash, peer.info.best_number);
1046		}
1047
1048		log::debug!(target: LOG_TARGET, "Connected {peer_id}");
1049
1050		if self.peers.insert(peer_id, peer).is_none() {
1051			if let Some(metrics) = &self.metrics {
1052				metrics.peers.inc();
1053			}
1054			self.num_connected.fetch_add(1, Ordering::AcqRel);
1055		}
1056		self.peer_store_handle.set_peer_role(&peer_id, status.roles.into());
1057
1058		if self.is_no_slot_peer(&peer_id) {
1059			self.default_peers_set_no_slot_connected_peers.insert(peer_id);
1060		} else if direction.is_inbound() && status.roles.is_full() {
1061			self.num_in_peers += 1;
1062		}
1063
1064		self.event_streams.retain(|stream| {
1065			stream
1066				.unbounded_send(SyncEvent::PeerConnected { peer_id, roles: status.roles })
1067				.is_ok()
1068		});
1069
1070		Ok(())
1071	}
1072
1073	fn process_response_event(&mut self, response_event: ResponseEvent) {
1074		let ResponseEvent { peer_id, key, response: response_result } = response_event;
1075
1076		match response_result {
1077			Ok(Ok((response, protocol_name))) => {
1078				self.strategy.on_generic_response(&peer_id, key, protocol_name, response);
1079			},
1080			Ok(Err(e)) => {
1081				debug!(target: LOG_TARGET, "Request to peer {peer_id:?} failed: {e:?}.");
1082
1083				match e {
1084					RequestFailure::Network(OutboundFailure::Timeout) => {
1085						self.network_service.report_peer(peer_id, rep::TIMEOUT);
1086						self.network_service
1087							.disconnect_peer(peer_id, self.block_announce_protocol_name.clone());
1088					},
1089					RequestFailure::Network(OutboundFailure::UnsupportedProtocols) => {
1090						self.network_service.report_peer(peer_id, rep::BAD_PROTOCOL);
1091						self.network_service
1092							.disconnect_peer(peer_id, self.block_announce_protocol_name.clone());
1093					},
1094					RequestFailure::Network(OutboundFailure::DialFailure) => {
1095						self.network_service
1096							.disconnect_peer(peer_id, self.block_announce_protocol_name.clone());
1097					},
1098					RequestFailure::Refused => {
1099						self.network_service.report_peer(peer_id, rep::REFUSED);
1100						self.network_service
1101							.disconnect_peer(peer_id, self.block_announce_protocol_name.clone());
1102					},
1103					RequestFailure::Network(OutboundFailure::ConnectionClosed) |
1104					RequestFailure::NotConnected => {
1105						self.network_service
1106							.disconnect_peer(peer_id, self.block_announce_protocol_name.clone());
1107					},
1108					RequestFailure::UnknownProtocol => {
1109						debug_assert!(false, "Block request protocol should always be known.");
1110					},
1111					RequestFailure::InvalidRequest => {
1112						debug_assert!(false, "Block request payload should always be valid.");
1113					},
1114					RequestFailure::Obsolete => {
1115						debug_assert!(
1116							false,
1117							"Can not receive `RequestFailure::Obsolete` after dropping the \
1118							response receiver.",
1119						);
1120					},
1121					RequestFailure::Network(OutboundFailure::Io(_)) => {
1122						self.network_service.report_peer(peer_id, rep::IO);
1123						self.network_service
1124							.disconnect_peer(peer_id, self.block_announce_protocol_name.clone());
1125					},
1126				}
1127			},
1128			Err(oneshot::Canceled) => {
1129				trace!(
1130					target: LOG_TARGET,
1131					"Request to peer {peer_id:?} failed due to oneshot being canceled.",
1132				);
1133				self.network_service
1134					.disconnect_peer(peer_id, self.block_announce_protocol_name.clone());
1135			},
1136		}
1137	}
1138
1139	/// Returns the number of peers we're connected to and that are being queried.
1140	fn num_active_peers(&self) -> usize {
1141		self.pending_responses.len()
1142	}
1143
1144	/// Get config for the block announcement protocol
1145	fn get_block_announce_proto_config<N: NetworkBackend<B, <B as BlockT>::Hash>>(
1146		protocol_id: ProtocolId,
1147		fork_id: Option<&str>,
1148		roles: Roles,
1149		best_number: NumberFor<B>,
1150		best_hash: B::Hash,
1151		genesis_hash: B::Hash,
1152		set_config: &SetConfig,
1153		metrics: NotificationMetrics,
1154		peer_store_handle: Arc<dyn PeerStoreProvider>,
1155	) -> (N::NotificationProtocolConfig, Box<dyn NotificationService>) {
1156		let block_announces_protocol = block_announces_protocol_name(genesis_hash, fork_id);
1157
1158		N::notification_config(
1159			block_announces_protocol.into(),
1160			iter::once(block_announces_legacy_protocol_name(&protocol_id).into()).collect(),
1161			MAX_BLOCK_ANNOUNCE_SIZE,
1162			Some(NotificationHandshake::new(BlockAnnouncesHandshake::<B>::build(
1163				roles,
1164				best_number,
1165				best_hash,
1166				genesis_hash,
1167			))),
1168			set_config.clone(),
1169			metrics,
1170			peer_store_handle,
1171		)
1172	}
1173
1174	/// Import blocks.
1175	fn import_blocks(&mut self, origin: BlockOrigin, blocks: Vec<IncomingBlock<B>>) {
1176		if let Some(metrics) = &self.metrics {
1177			metrics.import_queue_blocks_submitted.inc();
1178		}
1179
1180		self.import_queue.import_blocks(origin, blocks);
1181	}
1182
1183	/// Import justifications.
1184	fn import_justifications(
1185		&mut self,
1186		peer_id: PeerId,
1187		hash: B::Hash,
1188		number: NumberFor<B>,
1189		justifications: Justifications,
1190	) {
1191		if let Some(metrics) = &self.metrics {
1192			metrics.import_queue_justifications_submitted.inc();
1193		}
1194
1195		self.import_queue.import_justifications(peer_id, hash, number, justifications);
1196	}
1197}
1198
1199/// Update per-peer slot tracking for changes in the dynamic no-slot set.
1200/// Promotes newly added peers, demotes removed ones, ignoring static no-slot peers.
1201///
1202/// `peer_inbound_full(peer_id)` returns `true` if `peer_id` is inbound and full.
1203///  Returns `None` if the peer is not connected.
1204///
1205/// If removing a peer from no-slot would make `num_in_peers` exceed `max_in_peers`,
1206/// disconnect the peer instead and keep it in `connected_no_slot` until the async disconnect
1207/// handler will update `num_in_peers`..
1208/// Caller needs to update `dynamic_no_slot_peers` after calling this function.
1209fn apply_no_slot_set_inner(
1210	peer_inbound_full: impl Fn(&PeerId) -> Option<bool>,
1211	static_no_slot: &HashSet<PeerId>,
1212	old_dynamic_no_slot: &HashSet<PeerId>,
1213	new_dynamic_no_slot: &HashSet<PeerId>,
1214	connected_no_slot: &mut HashSet<PeerId>,
1215	num_in_peers: &mut usize,
1216	max_in_peers: usize,
1217	network_service: &service::network::NetworkServiceHandle,
1218	protocol: &ProtocolName,
1219) {
1220	// Skip static-set and disconnected peers and return the slot-affecting flag for the rest.
1221	let slot_impact = |peer_id: &PeerId| -> Option<bool> {
1222		if static_no_slot.contains(peer_id) {
1223			return None;
1224		}
1225		peer_inbound_full(peer_id)
1226	};
1227
1228	let mut promoted = 0;
1229	let mut demoted = 0;
1230	let mut disconnected = 0;
1231
1232	for peer_id in new_dynamic_no_slot.difference(old_dynamic_no_slot) {
1233		let Some(affects_slots) = slot_impact(peer_id) else { continue };
1234		// Defensive check, should never happen as we filter above.
1235		if !connected_no_slot.insert(*peer_id) {
1236			log::error!(
1237				target: LOG_TARGET,
1238				"{peer_id} promoted to no-slot but was already in connected_no_slot",
1239			);
1240			debug_assert!(false);
1241			continue;
1242		}
1243		if affects_slots {
1244			if let Some(n) = num_in_peers.checked_sub(1) {
1245				*num_in_peers = n;
1246			} else {
1247				log::error!(
1248					target: LOG_TARGET,
1249					"num_in_peers underflow promoting {peer_id} to no-slot",
1250				);
1251				debug_assert!(false);
1252			}
1253			promoted += 1;
1254		}
1255	}
1256
1257	for peer_id in old_dynamic_no_slot.difference(new_dynamic_no_slot) {
1258		let Some(affects_slots) = slot_impact(peer_id) else { continue };
1259		if !connected_no_slot.contains(peer_id) {
1260			continue;
1261		}
1262		if affects_slots && *num_in_peers >= max_in_peers {
1263			log::debug!(
1264				target: LOG_TARGET,
1265				"Demoting {peer_id} would exceed max_in_peers ({max_in_peers}); disconnecting",
1266			);
1267			network_service.disconnect_peer(*peer_id, protocol.clone());
1268			disconnected += 1;
1269			continue;
1270		}
1271		connected_no_slot.remove(peer_id);
1272		if affects_slots {
1273			*num_in_peers += 1;
1274			demoted += 1;
1275		}
1276	}
1277
1278	log::debug!(
1279		target: LOG_TARGET,
1280		"Dynamic no-slot peer set updated: {} peers: +{} in, -{} out, {} disconnected",
1281		new_dynamic_no_slot.len(),
1282		promoted,
1283		demoted,
1284		disconnected,
1285	);
1286}
1287
1288#[cfg(test)]
1289mod tests {
1290	use super::*;
1291
1292	fn fresh_peers<const N: usize>() -> [PeerId; N] {
1293		std::array::from_fn(|_| PeerId::random())
1294	}
1295
1296	fn set_of<const N: usize>(peers: [PeerId; N]) -> HashSet<PeerId> {
1297		peers.into_iter().collect()
1298	}
1299
1300	/// Run [`apply_no_slot_set`] with the given initial state. Uses `usize::MAX` for
1301	/// `max_in_peers` so demotion never trips the disconnect path. Returns the final
1302	/// `connected_no_slot` set and `num_in_peers`.
1303	#[track_caller]
1304	fn run_apply(
1305		connected: Vec<(PeerId, bool)>,
1306		static_no_slot: HashSet<PeerId>,
1307		old_dynamic: HashSet<PeerId>,
1308		new_dynamic: HashSet<PeerId>,
1309		initial_connected_no_slot: HashSet<PeerId>,
1310		initial_num_in_peers: usize,
1311	) -> (HashSet<PeerId>, usize) {
1312		let (connected_no_slot, num_in, disconnects) = run_apply_with_cap(
1313			connected,
1314			static_no_slot,
1315			old_dynamic,
1316			new_dynamic,
1317			initial_connected_no_slot,
1318			initial_num_in_peers,
1319			usize::MAX,
1320		);
1321		assert!(disconnects.is_empty(), "unexpected disconnects: {disconnects:?}");
1322		(connected_no_slot, num_in)
1323	}
1324
1325	/// Variant of [`run_apply`] that exposes `max_in_peers` and the list of peers the
1326	/// function asked the network to disconnect (drained from the `NetworkServiceHandle`'s
1327	/// command channel).
1328	#[track_caller]
1329	fn run_apply_with_cap(
1330		connected: Vec<(PeerId, bool)>,
1331		static_no_slot: HashSet<PeerId>,
1332		old_dynamic: HashSet<PeerId>,
1333		new_dynamic: HashSet<PeerId>,
1334		initial_connected_no_slot: HashSet<PeerId>,
1335		initial_num_in_peers: usize,
1336		max_in_peers: usize,
1337	) -> (HashSet<PeerId>, usize, Vec<PeerId>) {
1338		use crate::service::network::{NetworkServiceHandle, ToServiceCommand as NetCmd};
1339
1340		let peer_inbound_full: HashMap<PeerId, bool> = connected.into_iter().collect();
1341		let (tx, mut rx) = tracing_unbounded::<NetCmd>("test_apply_no_slot_set_disconnects", 100);
1342		let network_service = NetworkServiceHandle::new(tx);
1343		let protocol: ProtocolName = "/test/block-announces/1".into();
1344		let mut connected_no_slot = initial_connected_no_slot;
1345		let mut num_in_peers = initial_num_in_peers;
1346		apply_no_slot_set_inner(
1347			|peer_id| peer_inbound_full.get(peer_id).copied(),
1348			&static_no_slot,
1349			&old_dynamic,
1350			&new_dynamic,
1351			&mut connected_no_slot,
1352			&mut num_in_peers,
1353			max_in_peers,
1354			&network_service,
1355			&protocol,
1356		);
1357		drop(network_service);
1358
1359		let mut disconnects = Vec::new();
1360		while let Ok(cmd) = rx.try_recv() {
1361			if let NetCmd::DisconnectPeer(peer, _) = cmd {
1362				disconnects.push(peer);
1363			}
1364		}
1365		(connected_no_slot, num_in_peers, disconnects)
1366	}
1367
1368	#[test]
1369	fn apply_promotes_multiple_inbound_full_peers() {
1370		// `already` is in both old and new dynamic — it must stay in `connected_no_slot`
1371		// without releasing another slot.
1372		let [a, b, c, already] = fresh_peers();
1373		let (connected_no_slot, num_in) = run_apply(
1374			vec![(a, true), (b, true), (c, true), (already, true)],
1375			HashSet::new(),
1376			set_of([already]),
1377			set_of([a, b, c, already]),
1378			set_of([already]),
1379			10,
1380		);
1381		assert_eq!(connected_no_slot, set_of([a, b, c, already]));
1382		assert_eq!(num_in, 7);
1383	}
1384
1385	#[test]
1386	fn apply_demotes_multiple_inbound_full_peers() {
1387		let [a, b, c, stays] = fresh_peers();
1388		let (connected_no_slot, num_in) = run_apply(
1389			vec![(a, true), (b, true), (c, true), (stays, true)],
1390			HashSet::new(),
1391			set_of([a, b, c, stays]),
1392			set_of([stays]),
1393			set_of([a, b, c, stays]),
1394			2,
1395		);
1396		assert_eq!(connected_no_slot, set_of([stays]));
1397		assert_eq!(num_in, 5);
1398	}
1399
1400	#[test]
1401	fn apply_ignores_non_slot_consuming_peers() {
1402		// Outbound peers and inbound light peers both yield `affects_slots = false`. Either
1403		// kind transitioning must update `connected_no_slot` but not move `num_in_peers`.
1404		let [outbound, light] = fresh_peers();
1405		let (connected_no_slot, num_in) = run_apply(
1406			vec![(outbound, false), (light, false)],
1407			HashSet::new(),
1408			HashSet::new(),
1409			set_of([outbound, light]),
1410			HashSet::new(),
1411			5,
1412		);
1413		assert_eq!(connected_no_slot, set_of([outbound, light]));
1414		assert_eq!(num_in, 5);
1415	}
1416
1417	#[test]
1418	fn apply_static_peers_stay_no_slot_when_removed_from_dynamic() {
1419		// `control` (dynamic-only) IS demoted, proving the wiring is live — the static peers
1420		// must NOT be demoted because the static set takes precedence over the dynamic one.
1421		let [s1, s2, control] = fresh_peers();
1422		let (connected_no_slot, num_in) = run_apply(
1423			vec![(s1, true), (s2, true), (control, true)],
1424			set_of([s1, s2]),
1425			set_of([s1, s2, control]),
1426			HashSet::new(),
1427			set_of([s1, s2, control]),
1428			2,
1429		);
1430		assert_eq!(connected_no_slot, set_of([s1, s2]));
1431		assert_eq!(num_in, 3);
1432	}
1433
1434	#[test]
1435	fn apply_static_peers_added_to_dynamic_are_unchanged() {
1436		let [s1, s2] = fresh_peers();
1437		let (connected_no_slot, num_in) = run_apply(
1438			vec![(s1, true), (s2, true)],
1439			set_of([s1, s2]),
1440			HashSet::new(),
1441			set_of([s1, s2]),
1442			set_of([s1, s2]),
1443			4,
1444		);
1445		assert_eq!(connected_no_slot, set_of([s1, s2]));
1446		assert_eq!(num_in, 4);
1447	}
1448
1449	#[test]
1450	fn apply_unconnected_peers_in_new_set_are_ignored() {
1451		// Unconnected peers go into `dynamic_no_slot_peers` (caller-installed) and take effect
1452		// on connect; they must not appear in `connected_no_slot` here.
1453		let [connected_a, connected_b] = fresh_peers();
1454		let [unconnected_a, unconnected_b] = fresh_peers();
1455		let (connected_no_slot, num_in) = run_apply(
1456			vec![(connected_a, true), (connected_b, true)],
1457			HashSet::new(),
1458			HashSet::new(),
1459			set_of([unconnected_a, unconnected_b]),
1460			HashSet::new(),
1461			3,
1462		);
1463		assert!(connected_no_slot.is_empty());
1464		assert_eq!(num_in, 3);
1465	}
1466
1467	#[test]
1468	fn apply_idempotent_same_set() {
1469		let [in_full, out_full, light] = fresh_peers();
1470		let target = set_of([in_full, out_full, light]);
1471		let (connected_no_slot, num_in) = run_apply(
1472			vec![(in_full, true), (out_full, false), (light, false)],
1473			HashSet::new(),
1474			target.clone(),
1475			target.clone(),
1476			target.clone(),
1477			2,
1478		);
1479		assert_eq!(connected_no_slot, target);
1480		assert_eq!(num_in, 2);
1481	}
1482
1483	#[test]
1484	fn apply_empty_set_clears_dynamic_only_peers() {
1485		let [in1, in2, out, light] = fresh_peers();
1486		let [static_peer] = fresh_peers();
1487		let old = set_of([in1, in2, out, light, static_peer]);
1488		let (connected_no_slot, num_in) = run_apply(
1489			vec![(in1, true), (in2, true), (out, false), (light, false), (static_peer, true)],
1490			set_of([static_peer]),
1491			old.clone(),
1492			HashSet::new(),
1493			old,
1494			0,
1495		);
1496		assert_eq!(connected_no_slot, set_of([static_peer]));
1497		assert_eq!(num_in, 2);
1498	}
1499
1500	#[test]
1501	fn apply_mixed_promote_and_demote() {
1502		let [p1, p2] = fresh_peers();
1503		let [d1, d2] = fresh_peers();
1504		let (connected_no_slot, num_in) = run_apply(
1505			vec![(p1, true), (p2, true), (d1, true), (d2, true)],
1506			HashSet::new(),
1507			set_of([d1, d2]),
1508			set_of([p1, p2]),
1509			set_of([d1, d2]),
1510			5,
1511		);
1512		assert_eq!(connected_no_slot, set_of([p1, p2]));
1513		assert_eq!(num_in, 5);
1514	}
1515
1516	#[test]
1517	fn apply_demote_at_capacity_disconnects_peer() {
1518		// Scenario: PeerX was promoted (freeing a slot), then a regular PeerY filled that slot,
1519		// bringing `num_in_peers` back to capacity. Now PeerX is demoted out of the dynamic set
1520		// — incrementing `num_in_peers` would push it strictly above `max_in_peers`. The peer
1521		// must be disconnected instead, and left in `connected_no_slot` so the async disconnect
1522		// handler is the sole updater of `num_in_peers`.
1523		let [px] = fresh_peers();
1524		let (connected_no_slot, num_in, disconnects) = run_apply_with_cap(
1525			vec![(px, true)],
1526			HashSet::new(),
1527			set_of([px]),
1528			HashSet::new(),
1529			set_of([px]),
1530			8,
1531			8,
1532		);
1533		assert_eq!(connected_no_slot, set_of([px]));
1534		assert_eq!(num_in, 8);
1535		assert_eq!(disconnects, vec![px]);
1536	}
1537
1538	#[test]
1539	fn apply_demote_below_capacity_increments_normally() {
1540		// Same shape as the over-capacity test but with `num_in_peers < max_in_peers`: the
1541		// peer is regularly demoted and `num_in_peers` is incremented.
1542		let [px] = fresh_peers();
1543		let (connected_no_slot, num_in, disconnects) = run_apply_with_cap(
1544			vec![(px, true)],
1545			HashSet::new(),
1546			set_of([px]),
1547			HashSet::new(),
1548			set_of([px]),
1549			7,
1550			8,
1551		);
1552		assert!(connected_no_slot.is_empty());
1553		assert_eq!(num_in, 8);
1554		assert!(disconnects.is_empty());
1555	}
1556}