referrerpolicy=no-referrer-when-downgrade

sc_network_sync/strategy/
chain_sync.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//! Contains the state of the chain synchronization process
20//!
21//! At any given point in time, a running node tries as much as possible to be at the head of the
22//! chain. This module handles the logic of which blocks to request from remotes, and processing
23//! responses. It yields blocks to check and potentially move to the database.
24//!
25//! # Usage
26//!
27//! The `ChainSync` struct maintains the state of the block requests. Whenever something happens on
28//! the network, or whenever a block has been successfully verified, call the appropriate method in
29//! order to update it.
30
31use crate::{
32	block_relay_protocol::{BlockDownloader, BlockResponseError},
33	blocks::{BlockCollection, Metrics as BlockCollectionMetrics},
34	justification_requests::ExtraRequests,
35	schema::v1::{StateRequest, StateResponse},
36	service::network::NetworkServiceHandle,
37	strategy::{
38		disconnected_peers::DisconnectedPeers,
39		state_sync::{ImportResult, StateSync, StateSyncProvider},
40		warp::{WarpSyncPhase, WarpSyncProgress},
41		StrategyKey, SyncingAction, SyncingStrategy,
42	},
43	types::{BadPeer, SyncState, SyncStatus},
44	LOG_TARGET,
45};
46
47use codec::Encode;
48use futures::{channel::oneshot, FutureExt};
49use log::{debug, error, info, trace, warn};
50use prometheus_endpoint::{register, Counter, Gauge, PrometheusError, Registry, U64};
51use prost::Message;
52use sc_client_api::{blockchain::BlockGap, BlockBackend, ProofProvider};
53use sc_consensus::{BlockImportError, BlockImportStatus, IncomingBlock};
54use sc_network::{IfDisconnected, ProtocolName};
55use sc_network_common::sync::message::{
56	BlockAnnounce, BlockAttributes, BlockData, BlockRequest, BlockResponse, Direction, FromBlock,
57};
58use sc_network_types::PeerId;
59use sp_arithmetic::traits::Saturating;
60use sp_blockchain::{Error as ClientError, HeaderBackend, HeaderMetadata};
61use sp_consensus::{BlockOrigin, BlockStatus};
62use sp_runtime::{
63	traits::{
64		Block as BlockT, CheckedSub, Header as HeaderT, NumberFor, One, SaturatedConversion, Zero,
65	},
66	EncodedJustification, Justifications,
67};
68
69use std::{
70	any::Any,
71	collections::{HashMap, HashSet},
72	fmt,
73	ops::{AddAssign, Range},
74	sync::Arc,
75};
76
77#[cfg(test)]
78mod test;
79
80/// Maximum blocks to store in the import queue.
81const MAX_IMPORTING_BLOCKS: usize = 2048;
82
83/// Maximum blocks to download ahead of any gap.
84const MAX_DOWNLOAD_AHEAD: u32 = 2048;
85
86/// Maximum blocks to look backwards. The gap is the difference between the highest block and the
87/// common block of a node.
88const MAX_BLOCKS_TO_LOOK_BACKWARDS: u32 = MAX_DOWNLOAD_AHEAD / 2;
89
90/// Pick the state to sync as the latest finalized number minus this.
91const STATE_SYNC_FINALITY_THRESHOLD: u32 = 8;
92
93/// We use a heuristic that with a high likelihood, by the time
94/// `MAJOR_SYNC_BLOCKS` have been imported we'll be on the same
95/// chain as (or at least closer to) the peer so we want to delay
96/// the ancestor search to not waste time doing that when we are
97/// so far behind.
98const MAJOR_SYNC_BLOCKS: u8 = 5;
99
100mod rep {
101	use sc_network::ReputationChange as Rep;
102	/// Reputation change when a peer sent us a message that led to a
103	/// database read error.
104	pub const BLOCKCHAIN_READ_ERROR: Rep = Rep::new(-(1 << 16), "DB Error");
105
106	/// Reputation change when a peer sent us a status message with a different
107	/// genesis than us.
108	pub const GENESIS_MISMATCH: Rep = Rep::new(i32::MIN, "Genesis mismatch");
109
110	/// Reputation change for peers which send us a block with an incomplete header.
111	pub const INCOMPLETE_HEADER: Rep = Rep::new(-(1 << 20), "Incomplete header");
112
113	/// Reputation change for peers which send us a block which we fail to verify.
114	pub const VERIFICATION_FAIL: Rep = Rep::new(-(1 << 29), "Block verification failed");
115
116	/// Reputation change for peers which send us a known bad block.
117	pub const BAD_BLOCK: Rep = Rep::new(-(1 << 29), "Bad block");
118
119	/// Peer did not provide us with advertised block data.
120	pub const NO_BLOCK: Rep = Rep::new(-(1 << 29), "No requested block data");
121
122	/// Reputation change for peers which send us non-requested block data.
123	pub const NOT_REQUESTED: Rep = Rep::new(-(1 << 29), "Not requested block data");
124
125	/// Peer could not serve any body of a gap sync request that required them.
126	/// Mild, since the peer may still be backfilling its own block history.
127	pub const NO_GAP_BODIES: Rep = Rep::new(-(1 << 26), "No gap sync bodies");
128
129	/// Peer returned an empty response for a range of blocks we requested from it.
130	/// Mild, since the peer's announced best number is not a claim to hold the whole
131	/// history below it: bodies are pruned oldest-first, and a warp-synced node may
132	/// still be backfilling its gap.
133	pub const NO_BLOCKS_IN_RANGE: Rep = Rep::new(-(1 << 26), "No blocks in requested range");
134
135	/// Reputation change for peers which send us a block with bad justifications.
136	pub const BAD_JUSTIFICATION: Rep = Rep::new(-(1 << 16), "Bad justification");
137
138	/// Reputation change when a peer sent us invalid ancestry result.
139	pub const UNKNOWN_ANCESTOR: Rep = Rep::new(-(1 << 16), "DB Error");
140
141	/// Peer response data does not have requested bits.
142	pub const BAD_RESPONSE: Rep = Rep::new(-(1 << 12), "Incomplete response");
143
144	/// We received a message that failed to decode.
145	pub const BAD_MESSAGE: Rep = Rep::new(-(1 << 12), "Bad message");
146}
147
148struct Metrics {
149	queued_blocks: Gauge<U64>,
150	fork_targets: Gauge<U64>,
151	block_collection: BlockCollectionMetrics,
152	empty_block_responses: Counter<U64>,
153	gap_body_empty_responses: Counter<U64>,
154	gap_header_only_downgrades: Counter<U64>,
155	gap_oldest_required_body: Gauge<U64>,
156}
157
158impl Metrics {
159	fn register(r: &Registry) -> Result<Self, PrometheusError> {
160		Ok(Self {
161			queued_blocks: {
162				let g =
163					Gauge::new("substrate_sync_queued_blocks", "Number of blocks in import queue")?;
164				register(g, r)?
165			},
166			fork_targets: {
167				let g = Gauge::new("substrate_sync_fork_targets", "Number of fork sync targets")?;
168				register(g, r)?
169			},
170			block_collection: BlockCollectionMetrics::register(r)?,
171			empty_block_responses: {
172				let c = Counter::new(
173					"substrate_sync_empty_block_responses_total",
174					"Number of empty responses to block requests, i.e. peers that did \
175					 not have the requested range; each drops the responding peer",
176				)?;
177				register(c, r)?
178			},
179			gap_body_empty_responses: {
180				let c = Counter::new(
181					"substrate_sync_gap_body_empty_responses_total",
182					"Number of empty responses to gap sync requests that required bodies; \
183					 each drops the responding peer",
184				)?;
185				register(c, r)?
186			},
187			gap_header_only_downgrades: {
188				let c = Counter::new(
189					"substrate_sync_gap_header_only_downgrades_total",
190					"Number of gap sync requests issued header-only because the moving body \
191					 cutoff passed the range",
192				)?;
193				register(c, r)?
194			},
195			gap_oldest_required_body: {
196				let g = Gauge::new(
197					"substrate_sync_gap_oldest_required_body",
198					"Oldest block number for which gap sync still requires a body; \
199					 0 when gap sync is inactive or bodies are not required",
200				)?;
201				register(g, r)?
202			},
203		})
204	}
205}
206
207#[derive(Debug, Clone)]
208enum AllowedRequests {
209	Some(HashSet<PeerId>),
210	All,
211}
212
213impl AllowedRequests {
214	fn add(&mut self, id: &PeerId) {
215		if let Self::Some(ref mut set) = self {
216			set.insert(*id);
217		}
218	}
219
220	fn take(&mut self) -> Self {
221		std::mem::take(self)
222	}
223
224	fn set_all(&mut self) {
225		*self = Self::All;
226	}
227
228	fn contains(&self, id: &PeerId) -> bool {
229		match self {
230			Self::Some(set) => set.contains(id),
231			Self::All => true,
232		}
233	}
234
235	fn is_empty(&self) -> bool {
236		match self {
237			Self::Some(set) => set.is_empty(),
238			Self::All => false,
239		}
240	}
241
242	fn clear(&mut self) {
243		std::mem::take(self);
244	}
245}
246
247impl Default for AllowedRequests {
248	fn default() -> Self {
249		Self::Some(HashSet::default())
250	}
251}
252
253/// Statistics for gap sync operations.
254#[derive(Debug, Default, Clone)]
255struct GapSyncStats {
256	/// Size of headers downloaded during gap sync
257	header_bytes: usize,
258	/// Size of bodies downloaded during gap sync
259	body_bytes: usize,
260	/// Size of justifications downloaded during gap sync
261	justification_bytes: usize,
262}
263
264impl GapSyncStats {
265	fn new() -> Self {
266		Self::default()
267	}
268
269	fn total_bytes(&self) -> usize {
270		self.header_bytes + self.body_bytes + self.justification_bytes
271	}
272
273	fn bytes_to_mib(bytes: usize) -> f64 {
274		bytes as f64 / (1024.0 * 1024.0)
275	}
276}
277
278impl fmt::Display for GapSyncStats {
279	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280		let total = self.total_bytes();
281		write!(
282			f,
283			"hdr: {} B ({:.2} MiB), body: {} B ({:.2} MiB), just: {} B ({:.2} MiB) | total: {} B ({:.2} MiB)",
284			self.header_bytes,
285			Self::bytes_to_mib(self.header_bytes),
286			self.body_bytes,
287			Self::bytes_to_mib(self.body_bytes),
288			self.justification_bytes,
289			Self::bytes_to_mib(self.justification_bytes),
290			total,
291			Self::bytes_to_mib(total),
292		)
293	}
294}
295
296impl AddAssign for GapSyncStats {
297	fn add_assign(&mut self, other: Self) {
298		self.header_bytes += other.header_bytes;
299		self.body_bytes += other.body_bytes;
300		self.justification_bytes += other.justification_bytes;
301	}
302}
303
304struct GapSync<B: BlockT> {
305	blocks: BlockCollection<B>,
306	best_queued_number: NumberFor<B>,
307	target: NumberFor<B>,
308	stats: GapSyncStats,
309}
310
311/// Sync operation mode.
312#[derive(Copy, Clone, Debug, Eq, PartialEq)]
313pub enum ChainSyncMode {
314	/// Full block download and verification.
315	Full,
316	/// Download blocks and the latest state.
317	LightState {
318		/// Skip state proof download and verification.
319		skip_proofs: bool,
320	},
321}
322
323/// Returns the base block attributes required for chain sync.
324fn required_block_attributes() -> BlockAttributes {
325	BlockAttributes::HEADER | BlockAttributes::JUSTIFICATION | BlockAttributes::BODY
326}
327
328/// Which block bodies gap sync downloads while backfilling the block history below a
329/// warp-synced block.
330#[derive(Copy, Clone, Debug, Eq, PartialEq)]
331pub enum GapSyncBodyPolicy {
332	/// Backfill gap headers and justifications without bodies.
333	HeadersOnly,
334	/// Require bodies for the complete gap.
335	All,
336	/// Require bodies for blocks within the given window below the finalized block.
337	/// The window is expected to be pre-shrunk by the node with a safety margin, so
338	/// that peers whose finality runs ahead of ours still retain every requested body.
339	///
340	/// While the node is major syncing, local finality can lag the network beyond the
341	/// safety margin, so gap ranges above the cutoff are deferred until it has caught up.
342	BodiesWithinWindow(u32),
343}
344
345/// Resolves the [`GapSyncBodyPolicy`] lazily, when a `ChainSync` instance is created.
346///
347/// On a warp-syncing node this happens right after state sync completes, so the
348/// provider can query runtime state at the warp target. Errors fail `ChainSync`
349/// creation instead of silently degrading the policy.
350pub type GapSyncBodyPolicyProvider =
351	Arc<dyn Fn() -> Result<GapSyncBodyPolicy, ClientError> + Send + Sync>;
352
353/// All the data we have about a Peer that we are trying to sync with
354#[derive(Debug, Clone)]
355pub(crate) struct PeerSync<B: BlockT> {
356	/// Peer id of this peer.
357	pub peer_id: PeerId,
358	/// The common number is the block number that is a common point of
359	/// ancestry for both our chains (as far as we know).
360	pub common_number: NumberFor<B>,
361	/// The hash of the best block that we've seen for this peer.
362	pub best_hash: B::Hash,
363	/// The number of the best block that we've seen for this peer.
364	pub best_number: NumberFor<B>,
365	/// The state of syncing this peer is in for us, generally categories
366	/// into `Available` or "busy" with something as defined by `PeerSyncState`.
367	pub state: PeerSyncState<B>,
368}
369
370impl<B: BlockT> PeerSync<B> {
371	/// Update the `common_number` iff `new_common > common_number`.
372	fn update_common_number(&mut self, new_common: NumberFor<B>) {
373		if self.common_number < new_common {
374			trace!(
375				target: LOG_TARGET,
376				"Updating peer {} common number from={} => to={}.",
377				self.peer_id,
378				self.common_number,
379				new_common,
380			);
381			self.common_number = new_common;
382		}
383	}
384}
385
386struct ForkTarget<B: BlockT> {
387	number: NumberFor<B>,
388	parent_hash: Option<B::Hash>,
389	peers: HashSet<PeerId>,
390}
391
392/// The state of syncing between a Peer and ourselves.
393///
394/// Generally two categories, "busy" or `Available`. If busy, the enum
395/// defines what we are busy with.
396#[derive(Copy, Clone, Eq, PartialEq, Debug)]
397pub(crate) enum PeerSyncState<B: BlockT> {
398	/// Available for sync requests.
399	Available,
400	/// Searching for ancestors the Peer has in common with us.
401	AncestorSearch {
402		/// The best queued number when starting the ancestor search.
403		start: NumberFor<B>,
404		/// The current block that is being downloaded.
405		current: NumberFor<B>,
406		/// The state of the search.
407		state: AncestorSearchState<B>,
408	},
409	/// Actively downloading new blocks, starting from the given Number.
410	DownloadingNew(NumberFor<B>),
411	/// Downloading a stale block with given Hash. Stale means that it is a
412	/// block with a number that is lower than our best number. It might be
413	/// from a fork and not necessarily already imported.
414	DownloadingStale(B::Hash),
415	/// Downloading justification for given block hash.
416	DownloadingJustification(B::Hash),
417	/// Downloading state.
418	DownloadingState,
419	/// Actively downloading block history after warp sync.
420	DownloadingGap(NumberFor<B>),
421}
422
423impl<B: BlockT> PeerSyncState<B> {
424	pub fn is_available(&self) -> bool {
425		matches!(self, Self::Available)
426	}
427}
428
429/// The main data structure which contains all the state for a chains
430/// active syncing strategy.
431pub struct ChainSync<B: BlockT, Client> {
432	/// Chain client.
433	client: Arc<Client>,
434	/// The active peers that we are using to sync and their PeerSync status
435	peers: HashMap<PeerId, PeerSync<B>>,
436	disconnected_peers: DisconnectedPeers,
437	/// A `BlockCollection` of blocks that are being downloaded from peers
438	blocks: BlockCollection<B>,
439	/// The best block number in our queue of blocks to import
440	best_queued_number: NumberFor<B>,
441	/// The best block hash in our queue of blocks to import
442	best_queued_hash: B::Hash,
443	/// Current mode (full/light)
444	mode: ChainSyncMode,
445	/// Any extra justification requests.
446	extra_justifications: ExtraRequests<B>,
447	/// A set of hashes of blocks that are being downloaded or have been
448	/// downloaded and are queued for import.
449	queue_blocks: HashSet<B::Hash>,
450	/// A pending attempt to start the state sync.
451	///
452	/// The initiation of state sync may be deferred in cases where other conditions
453	/// are not yet met when the finalized block notification is received, such as
454	/// when `queue_blocks` is not empty or there are no peers. This field holds the
455	/// necessary information to attempt the state sync at a later point when
456	/// conditions are satisfied.
457	pending_state_sync_attempt: Option<(B::Hash, NumberFor<B>, bool)>,
458	/// Fork sync targets.
459	fork_targets: HashMap<B::Hash, ForkTarget<B>>,
460	/// A set of peers for which there might be potential block requests
461	allowed_requests: AllowedRequests,
462	/// Maximum number of peers to ask the same blocks in parallel.
463	max_parallel_downloads: u32,
464	/// Maximum blocks per request.
465	max_blocks_per_request: u32,
466	/// Protocol name used to send out state requests
467	state_request_protocol_name: ProtocolName,
468	/// Total number of downloaded blocks.
469	downloaded_blocks: usize,
470	/// State sync in progress, if any.
471	state_sync: Option<StateSync<B, Client>>,
472	/// Enable importing existing blocks. This is used after the state download to
473	/// catch up to the latest state while re-importing blocks.
474	import_existing: bool,
475	/// Block downloader
476	block_downloader: Arc<dyn BlockDownloader<B>>,
477	/// Which block bodies gap sync downloads.
478	gap_sync_body_policy: GapSyncBodyPolicy,
479	/// Gap download process.
480	gap_sync: Option<GapSync<B>>,
481	/// Pending actions.
482	actions: Vec<SyncingAction<B>>,
483	/// Prometheus metrics.
484	metrics: Option<Metrics>,
485}
486
487impl<B, Client> SyncingStrategy<B> for ChainSync<B, Client>
488where
489	B: BlockT,
490	Client: HeaderBackend<B>
491		+ BlockBackend<B>
492		+ HeaderMetadata<B, Error = sp_blockchain::Error>
493		+ ProofProvider<B>
494		+ Send
495		+ Sync
496		+ 'static,
497{
498	fn add_peer(&mut self, peer_id: PeerId, best_hash: B::Hash, best_number: NumberFor<B>) {
499		match self.add_peer_inner(peer_id, best_hash, best_number) {
500			Ok(Some(request)) => {
501				let action = self.create_block_request_action(peer_id, request);
502				self.actions.push(action);
503			},
504			Ok(None) => {},
505			Err(bad_peer) => self.actions.push(SyncingAction::DropPeer(bad_peer)),
506		}
507	}
508
509	fn remove_peer(&mut self, peer_id: &PeerId) {
510		self.blocks.clear_peer_download(peer_id);
511		if let Some(gap_sync) = &mut self.gap_sync {
512			gap_sync.blocks.clear_peer_download(peer_id)
513		}
514
515		if let Some(state) = self.peers.remove(peer_id) {
516			if !state.state.is_available() {
517				if let Some(bad_peer) =
518					self.disconnected_peers.on_disconnect_during_request(*peer_id)
519				{
520					self.actions.push(SyncingAction::DropPeer(bad_peer));
521				}
522			}
523		}
524
525		self.extra_justifications.cancel_request(peer_id);
526		self.allowed_requests.set_all();
527		self.fork_targets.retain(|_, target| {
528			target.peers.remove(peer_id);
529			!target.peers.is_empty()
530		});
531		if let Some(metrics) = &self.metrics {
532			metrics.fork_targets.set(self.fork_targets.len().try_into().unwrap_or(u64::MAX));
533		}
534
535		let blocks = self.ready_blocks();
536
537		if !blocks.is_empty() {
538			self.validate_and_queue_blocks(blocks, false);
539		}
540	}
541
542	fn on_validated_block_announce(
543		&mut self,
544		is_best: bool,
545		peer_id: PeerId,
546		announce: &BlockAnnounce<B::Header>,
547	) -> Option<(B::Hash, NumberFor<B>)> {
548		let number = *announce.header.number();
549		let hash = announce.header.hash();
550		let parent_status =
551			self.block_status(announce.header.parent_hash()).unwrap_or(BlockStatus::Unknown);
552		let known_parent = parent_status != BlockStatus::Unknown;
553		let ancient_parent = parent_status == BlockStatus::InChainPruned;
554
555		let known = self.is_known(&hash);
556		let is_major_syncing = self.is_major_syncing();
557		let peer = if let Some(peer) = self.peers.get_mut(&peer_id) {
558			peer
559		} else {
560			error!(target: LOG_TARGET, "๐Ÿ’” Called `on_validated_block_announce` with a bad peer ID {peer_id}");
561			return Some((hash, number));
562		};
563
564		if let PeerSyncState::AncestorSearch { .. } = peer.state {
565			trace!(target: LOG_TARGET, "Peer {} is in the ancestor search state.", peer_id);
566			return None;
567		}
568
569		// The node is continuing a known fork if either the block itself is known, the
570		// parent is known or the block references the previously announced `best_hash`.
571		let continues_known_fork =
572			known || known_parent || announce.header.parent_hash() == &peer.best_hash;
573
574		let peer_info = is_best.then(|| {
575			// update their best block
576			peer.best_number = number;
577			peer.best_hash = hash;
578
579			(hash, number)
580		});
581
582		// If the announced block is the best they have and is not ahead of us, our common number
583		// is either one further ahead or it's the one they just announced, if we know about it.
584		if is_best {
585			let best_queued_number = self.best_queued_number;
586
587			if known && best_queued_number >= number {
588				peer.update_common_number(number);
589			} else if announce.header.parent_hash() == &self.best_queued_hash ||
590				known_parent && best_queued_number >= number
591			{
592				peer.update_common_number(number.saturating_sub(One::one()));
593			}
594
595			// If this announced block isn't following any known fork, we have to start an
596			// ancestor search to find out our real common block. However, we skip this during
597			// major sync to avoid pulling peers out of the download pool.
598			if !continues_known_fork && !is_major_syncing {
599				let current = number.min(best_queued_number);
600				peer.common_number = peer.common_number.min(self.client.info().finalized_number);
601				let old_state = std::mem::replace(
602					&mut peer.state,
603					PeerSyncState::AncestorSearch {
604						current,
605						start: best_queued_number,
606						state: AncestorSearchState::ExponentialBackoff(One::one()),
607					},
608				);
609				self.cancel_peer_request(peer_id, old_state);
610
611				let request = ancestry_request::<B>(current);
612				let action = self.create_block_request_action(peer_id, request);
613				self.actions.push(action);
614
615				return peer_info;
616			}
617		}
618		self.allowed_requests.add(&peer_id);
619
620		// known block case
621		if known || self.is_already_downloading(&hash) {
622			trace!(target: LOG_TARGET, "Known block announce from {}: {}", peer_id, hash);
623			if let Some(target) = self.fork_targets.get_mut(&hash) {
624				target.peers.insert(peer_id);
625			}
626			return peer_info;
627		}
628
629		if ancient_parent {
630			trace!(
631				target: LOG_TARGET,
632				"Ignored ancient block announced from {}: {} {:?}",
633				peer_id,
634				hash,
635				announce.header,
636			);
637			return peer_info;
638		}
639
640		if self.status().state == SyncState::Idle {
641			trace!(
642				target: LOG_TARGET,
643				"Added sync target for block announced from {}: {} {:?}",
644				peer_id,
645				hash,
646				announce.summary(),
647			);
648			self.fork_targets
649				.entry(hash)
650				.or_insert_with(|| {
651					if let Some(metrics) = &self.metrics {
652						metrics.fork_targets.inc();
653					}
654
655					ForkTarget {
656						number,
657						parent_hash: Some(*announce.header.parent_hash()),
658						peers: Default::default(),
659					}
660				})
661				.peers
662				.insert(peer_id);
663		}
664
665		peer_info
666	}
667
668	// The implementation is similar to `on_validated_block_announce` with unknown parent hash.
669	fn set_sync_fork_request(
670		&mut self,
671		mut peers: Vec<PeerId>,
672		hash: &B::Hash,
673		number: NumberFor<B>,
674	) {
675		if peers.is_empty() {
676			peers = self
677				.peers
678				.iter()
679				// Only request blocks from peers who are ahead or on a par.
680				.filter(|(_, peer)| peer.best_number >= number)
681				.map(|(id, _)| *id)
682				.collect();
683
684			debug!(
685				target: LOG_TARGET,
686				"Explicit sync request for block {hash:?} with no peers specified. \
687				Syncing from these peers {peers:?} instead.",
688			);
689		} else {
690			debug!(
691				target: LOG_TARGET,
692				"Explicit sync request for block {hash:?} with {peers:?}",
693			);
694		}
695
696		if self.is_known(hash) {
697			debug!(target: LOG_TARGET, "Refusing to sync known hash {hash:?}");
698			return;
699		}
700
701		trace!(target: LOG_TARGET, "Downloading requested old fork {hash:?}");
702		for peer_id in &peers {
703			if let Some(peer) = self.peers.get_mut(peer_id) {
704				if let PeerSyncState::AncestorSearch { .. } = peer.state {
705					continue;
706				}
707
708				if number > peer.best_number {
709					peer.best_number = number;
710					peer.best_hash = *hash;
711				}
712				self.allowed_requests.add(peer_id);
713			}
714		}
715
716		self.fork_targets
717			.entry(*hash)
718			.or_insert_with(|| {
719				if let Some(metrics) = &self.metrics {
720					metrics.fork_targets.inc();
721				}
722
723				ForkTarget { number, peers: Default::default(), parent_hash: None }
724			})
725			.peers
726			.extend(peers);
727	}
728
729	fn request_justification(&mut self, hash: &B::Hash, number: NumberFor<B>) {
730		let client = &self.client;
731		self.extra_justifications
732			.schedule((*hash, number), |base, block| is_descendent_of(&**client, base, block))
733	}
734
735	fn clear_justification_requests(&mut self) {
736		self.extra_justifications.reset();
737	}
738
739	fn on_justification_import(&mut self, hash: B::Hash, number: NumberFor<B>, success: bool) {
740		let finalization_result = if success { Ok((hash, number)) } else { Err(()) };
741		self.extra_justifications
742			.try_finalize_root((hash, number), finalization_result, true);
743		self.allowed_requests.set_all();
744	}
745
746	fn on_generic_response(
747		&mut self,
748		peer_id: &PeerId,
749		key: StrategyKey,
750		protocol_name: ProtocolName,
751		response: Box<dyn Any + Send>,
752	) {
753		if Self::STRATEGY_KEY != key {
754			warn!(
755				target: LOG_TARGET,
756				"Unexpected generic response strategy key {key:?}, protocol {protocol_name}",
757			);
758			debug_assert!(false);
759			return;
760		}
761
762		if protocol_name == self.state_request_protocol_name {
763			let Ok(response) = response.downcast::<Vec<u8>>() else {
764				warn!(target: LOG_TARGET, "Failed to downcast state response");
765				debug_assert!(false);
766				return;
767			};
768
769			if let Err(bad_peer) = self.on_state_data(&peer_id, &response) {
770				self.actions.push(SyncingAction::DropPeer(bad_peer));
771			}
772		} else if &protocol_name == self.block_downloader.protocol_name() {
773			let Ok(response) = response
774				.downcast::<(BlockRequest<B>, Result<Vec<BlockData<B>>, BlockResponseError>)>()
775			else {
776				warn!(target: LOG_TARGET, "Failed to downcast block response");
777				debug_assert!(false);
778				return;
779			};
780
781			let (request, response) = *response;
782			let blocks = match response {
783				Ok(blocks) => blocks,
784				Err(BlockResponseError::DecodeFailed(e)) => {
785					debug!(
786						target: LOG_TARGET,
787						"Failed to decode block response from peer {:?}: {:?}.",
788						peer_id,
789						e
790					);
791					self.actions.push(SyncingAction::DropPeer(BadPeer(*peer_id, rep::BAD_MESSAGE)));
792					return;
793				},
794				Err(BlockResponseError::ExtractionFailed(e)) => {
795					debug!(
796						target: LOG_TARGET,
797						"Failed to extract blocks from peer response {:?}: {:?}.",
798						peer_id,
799						e
800					);
801					self.actions.push(SyncingAction::DropPeer(BadPeer(*peer_id, rep::BAD_MESSAGE)));
802					return;
803				},
804			};
805
806			if let Err(bad_peer) = self.on_block_response(peer_id, key, request, blocks) {
807				self.actions.push(SyncingAction::DropPeer(bad_peer));
808			}
809		} else {
810			warn!(
811				target: LOG_TARGET,
812				"Unexpected generic response protocol {protocol_name}, strategy key \
813				{key:?}",
814			);
815			debug_assert!(false);
816		}
817	}
818
819	fn on_blocks_processed(
820		&mut self,
821		imported: usize,
822		count: usize,
823		results: Vec<(Result<BlockImportStatus<NumberFor<B>>, BlockImportError>, B::Hash)>,
824	) {
825		trace!(target: LOG_TARGET, "Imported {imported} of {count}");
826
827		let mut has_error = false;
828		for (_, hash) in &results {
829			if self.queue_blocks.remove(hash) {
830				if let Some(metrics) = &self.metrics {
831					metrics.queued_blocks.dec();
832				}
833			}
834			self.blocks.clear_queued(hash);
835			if let Some(gap_sync) = &mut self.gap_sync {
836				gap_sync.blocks.clear_queued(hash);
837			}
838		}
839		for (result, hash) in results {
840			if has_error {
841				break;
842			}
843
844			has_error |= result.is_err();
845
846			match result {
847				Ok(BlockImportStatus::ImportedKnown(number, peer_id)) => {
848					if let Some(peer) = peer_id {
849						self.update_peer_common_number(&peer, number);
850					}
851					self.complete_gap_if_target(number);
852				},
853				Ok(BlockImportStatus::ImportedUnknown(number, aux, peer_id)) => {
854					if aux.clear_justification_requests {
855						trace!(
856							target: LOG_TARGET,
857							"Block imported clears all pending justification requests {number}: {hash:?}",
858						);
859						self.clear_justification_requests();
860					}
861
862					if aux.needs_justification {
863						trace!(
864							target: LOG_TARGET,
865							"Block imported but requires justification {number}: {hash:?}",
866						);
867						self.request_justification(&hash, number);
868					}
869
870					if aux.bad_justification {
871						if let Some(ref peer) = peer_id {
872							warn!("๐Ÿ’” Sent block with bad justification to import");
873							self.actions.push(SyncingAction::DropPeer(BadPeer(
874								*peer,
875								rep::BAD_JUSTIFICATION,
876							)));
877						}
878					}
879
880					if let Some(peer) = peer_id {
881						self.update_peer_common_number(&peer, number);
882					}
883					let state_sync_complete =
884						self.state_sync.as_ref().map_or(false, |s| s.target_hash() == hash);
885					if state_sync_complete {
886						info!(
887							target: LOG_TARGET,
888							"State sync is complete ({} MiB), restarting block sync.",
889							self.state_sync.as_ref().map_or(0, |s| s.progress().size / (1024 * 1024)),
890						);
891						self.state_sync = None;
892						self.mode = ChainSyncMode::Full;
893						self.restart();
894					}
895
896					self.complete_gap_if_target(number);
897				},
898				Err(BlockImportError::IncompleteHeader(peer_id)) => {
899					if let Some(peer) = peer_id {
900						warn!(
901							target: LOG_TARGET,
902							"๐Ÿ’” Peer sent block with incomplete header to import",
903						);
904						self.actions
905							.push(SyncingAction::DropPeer(BadPeer(peer, rep::INCOMPLETE_HEADER)));
906						self.restart();
907					}
908				},
909				Err(BlockImportError::VerificationFailed(peer_id, e)) => {
910					let extra_message = peer_id
911						.map_or_else(|| "".into(), |peer| format!(" received from ({peer})"));
912
913					warn!(
914						target: LOG_TARGET,
915						"๐Ÿ’” Verification failed for block {hash:?}{extra_message}: {e:?}",
916					);
917
918					if let Some(peer) = peer_id {
919						self.actions
920							.push(SyncingAction::DropPeer(BadPeer(peer, rep::VERIFICATION_FAIL)));
921					}
922
923					self.restart();
924				},
925				Err(BlockImportError::BadBlock(peer_id)) => {
926					if let Some(peer) = peer_id {
927						warn!(
928							target: LOG_TARGET,
929							"๐Ÿ’” Block {hash:?} received from peer {peer} has been blacklisted",
930						);
931						self.actions.push(SyncingAction::DropPeer(BadPeer(peer, rep::BAD_BLOCK)));
932					}
933				},
934				Err(BlockImportError::MissingState) => {
935					// This may happen if the chain we were requesting upon has been discarded
936					// in the meantime because other chain has been finalized.
937					// Don't mark it as bad as it still may be synced if explicitly requested.
938					trace!(target: LOG_TARGET, "Obsolete block {hash:?}");
939				},
940				e @ Err(BlockImportError::UnknownParent) | e @ Err(BlockImportError::Other(_)) => {
941					warn!(target: LOG_TARGET, "๐Ÿ’” Error importing block {hash:?}: {}", e.unwrap_err());
942					self.state_sync = None;
943					self.restart();
944				},
945				Err(BlockImportError::Cancelled) => {},
946			};
947		}
948
949		self.allowed_requests.set_all();
950	}
951
952	fn on_block_finalized(&mut self, hash: &B::Hash, number: NumberFor<B>) {
953		let client = &self.client;
954		let r = self.extra_justifications.on_block_finalized(hash, number, |base, block| {
955			is_descendent_of(&**client, base, block)
956		});
957
958		if let ChainSyncMode::LightState { skip_proofs, .. } = &self.mode {
959			if self.state_sync.is_none() {
960				if !self.peers.is_empty() && self.queue_blocks.is_empty() {
961					self.attempt_state_sync(*hash, number, *skip_proofs);
962				} else {
963					self.pending_state_sync_attempt.replace((*hash, number, *skip_proofs));
964				}
965			}
966		}
967
968		if let Err(err) = r {
969			warn!(
970				target: LOG_TARGET,
971				"๐Ÿ’” Error cleaning up pending extra justification data requests: {err}",
972			);
973		}
974	}
975
976	fn update_chain_info(&mut self, best_hash: &B::Hash, best_number: NumberFor<B>) {
977		self.on_block_queued(best_hash, best_number);
978	}
979
980	fn is_major_syncing(&self) -> bool {
981		self.status().state.is_major_syncing()
982	}
983
984	fn num_peers(&self) -> usize {
985		self.peers.len()
986	}
987
988	fn status(&self) -> SyncStatus<B> {
989		let median_seen = self.median_seen();
990		let best_seen_block =
991			median_seen.and_then(|median| (median > self.best_queued_number).then_some(median));
992		let sync_state = if let Some(target) = median_seen {
993			// A chain is classified as downloading if the provided best block is
994			// more than `MAJOR_SYNC_BLOCKS` behind the best block or as importing
995			// if the same can be said about queued blocks.
996			let best_block = self.client.info().best_number;
997			if target > best_block && target - best_block > MAJOR_SYNC_BLOCKS.into() {
998				// If target is not queued, we're downloading, otherwise importing.
999				if target > self.best_queued_number {
1000					SyncState::Downloading { target }
1001				} else {
1002					SyncState::Importing { target }
1003				}
1004			} else {
1005				SyncState::Idle
1006			}
1007		} else {
1008			SyncState::Idle
1009		};
1010
1011		let warp_sync_progress = self.gap_sync.as_ref().map(|gap_sync| WarpSyncProgress {
1012			phase: WarpSyncPhase::DownloadingBlocks(gap_sync.best_queued_number),
1013			total_bytes: 0,
1014			status: None,
1015		});
1016
1017		SyncStatus {
1018			state: sync_state,
1019			best_seen_block,
1020			num_peers: self.peers.len() as u32,
1021			queued_blocks: self.queue_blocks.len() as u32,
1022			state_sync: self.state_sync.as_ref().map(|s| s.progress()),
1023			warp_sync: warp_sync_progress,
1024		}
1025	}
1026
1027	fn num_downloaded_blocks(&self) -> usize {
1028		self.downloaded_blocks
1029	}
1030
1031	fn num_sync_requests(&self) -> usize {
1032		self.fork_targets
1033			.values()
1034			.filter(|f| f.number <= self.best_queued_number)
1035			.count()
1036	}
1037
1038	fn actions(
1039		&mut self,
1040		network_service: &NetworkServiceHandle,
1041	) -> Result<Vec<SyncingAction<B>>, ClientError> {
1042		if !self.peers.is_empty() && self.queue_blocks.is_empty() {
1043			if let Some((hash, number, skip_proofs)) = self.pending_state_sync_attempt.take() {
1044				self.attempt_state_sync(hash, number, skip_proofs);
1045			}
1046		}
1047
1048		let block_requests = self
1049			.block_requests()
1050			.into_iter()
1051			.map(|(peer_id, request)| self.create_block_request_action(peer_id, request))
1052			.collect::<Vec<_>>();
1053		self.actions.extend(block_requests);
1054
1055		let justification_requests = self
1056			.justification_requests()
1057			.into_iter()
1058			.map(|(peer_id, request)| self.create_block_request_action(peer_id, request))
1059			.collect::<Vec<_>>();
1060		self.actions.extend(justification_requests);
1061
1062		let state_request = self.state_request().into_iter().map(|(peer_id, request)| {
1063			trace!(
1064				target: LOG_TARGET,
1065				"Created `StateRequest` to {peer_id}.",
1066			);
1067
1068			let (tx, rx) = oneshot::channel();
1069
1070			network_service.start_request(
1071				peer_id,
1072				self.state_request_protocol_name.clone(),
1073				request.encode_to_vec(),
1074				tx,
1075				IfDisconnected::ImmediateError,
1076			);
1077
1078			SyncingAction::StartRequest {
1079				peer_id,
1080				key: Self::STRATEGY_KEY,
1081				request: async move {
1082					Ok(rx.await?.and_then(|(response, protocol_name)| {
1083						Ok((Box::new(response) as Box<dyn Any + Send>, protocol_name))
1084					}))
1085				}
1086				.boxed(),
1087			}
1088		});
1089		self.actions.extend(state_request);
1090
1091		Ok(std::mem::take(&mut self.actions))
1092	}
1093}
1094
1095impl<B, Client> ChainSync<B, Client>
1096where
1097	B: BlockT,
1098	Client: HeaderBackend<B>
1099		+ BlockBackend<B>
1100		+ HeaderMetadata<B, Error = sp_blockchain::Error>
1101		+ ProofProvider<B>
1102		+ Send
1103		+ Sync
1104		+ 'static,
1105{
1106	/// Strategy key used by chain sync.
1107	pub const STRATEGY_KEY: StrategyKey = StrategyKey::new("ChainSync");
1108
1109	/// Create a new instance.
1110	pub fn new(
1111		mode: ChainSyncMode,
1112		client: Arc<Client>,
1113		max_parallel_downloads: u32,
1114		max_blocks_per_request: u32,
1115		state_request_protocol_name: ProtocolName,
1116		block_downloader: Arc<dyn BlockDownloader<B>>,
1117		gap_sync_body_policy: GapSyncBodyPolicy,
1118		metrics_registry: Option<&Registry>,
1119		initial_peers: impl Iterator<Item = (PeerId, B::Hash, NumberFor<B>)>,
1120	) -> Result<Self, ClientError> {
1121		info!(target: LOG_TARGET, "Gap sync body policy: {gap_sync_body_policy:?}");
1122		let metrics = metrics_registry.and_then(|r| match Metrics::register(r) {
1123			Ok(metrics) => Some(metrics),
1124			Err(err) => {
1125				log::error!(target: LOG_TARGET, "Failed to register `ChainSync` metrics {err:?}");
1126				None
1127			},
1128		});
1129		let mut sync = Self {
1130			client,
1131			peers: HashMap::new(),
1132			disconnected_peers: DisconnectedPeers::new(),
1133			blocks: BlockCollection::with_metrics(
1134				metrics.as_ref().map(|m| m.block_collection.clone()),
1135			),
1136			best_queued_hash: Default::default(),
1137			best_queued_number: Zero::zero(),
1138			extra_justifications: ExtraRequests::new("justification", metrics_registry),
1139			mode,
1140			queue_blocks: Default::default(),
1141			pending_state_sync_attempt: None,
1142			fork_targets: Default::default(),
1143			allowed_requests: Default::default(),
1144			max_parallel_downloads,
1145			max_blocks_per_request,
1146			state_request_protocol_name,
1147			downloaded_blocks: 0,
1148			state_sync: None,
1149			import_existing: false,
1150			block_downloader,
1151			gap_sync_body_policy,
1152			gap_sync: None,
1153			actions: Vec::new(),
1154			metrics,
1155		};
1156
1157		sync.reset_sync_start_point()?;
1158		initial_peers.for_each(|(peer_id, best_hash, best_number)| {
1159			sync.add_peer(peer_id, best_hash, best_number);
1160		});
1161
1162		Ok(sync)
1163	}
1164
1165	/// Complete the gap sync if the target number is reached and there is a gap.
1166	fn complete_gap_if_target(&mut self, number: NumberFor<B>) {
1167		let Some(gap_sync) = &self.gap_sync else { return };
1168
1169		if gap_sync.target != number {
1170			return;
1171		}
1172
1173		info!(
1174			target: LOG_TARGET,
1175			"Block history download is complete. Downloaded {}.",
1176			gap_sync.stats,
1177		);
1178		self.gap_sync = None;
1179		if let Some(metrics) = &self.metrics {
1180			metrics.gap_oldest_required_body.set(0);
1181		}
1182	}
1183
1184	#[must_use]
1185	fn add_peer_inner(
1186		&mut self,
1187		peer_id: PeerId,
1188		best_hash: B::Hash,
1189		best_number: NumberFor<B>,
1190	) -> Result<Option<BlockRequest<B>>, BadPeer> {
1191		// There is nothing sync can get from the node that has no blockchain data.
1192		match self.block_status(&best_hash) {
1193			Err(e) => {
1194				debug!(target: LOG_TARGET, "Error reading blockchain: {e}");
1195				Err(BadPeer(peer_id, rep::BLOCKCHAIN_READ_ERROR))
1196			},
1197			Ok(BlockStatus::KnownBad) => {
1198				info!(
1199					"๐Ÿ’” New peer {peer_id} with known bad best block {best_hash} ({best_number})."
1200				);
1201				Err(BadPeer(peer_id, rep::BAD_BLOCK))
1202			},
1203			Ok(BlockStatus::Unknown) => {
1204				if best_number.is_zero() {
1205					info!(
1206						"๐Ÿ’” New peer {} with unknown genesis hash {} ({}).",
1207						peer_id, best_hash, best_number,
1208					);
1209					return Err(BadPeer(peer_id, rep::GENESIS_MISMATCH));
1210				}
1211
1212				// If there are more than `MAJOR_SYNC_BLOCKS` in the import queue then we have
1213				// enough to do in the import queue that it's not worth kicking off
1214				// an ancestor search, which is what we do in the next match case below.
1215				if self.queue_blocks.len() > MAJOR_SYNC_BLOCKS as usize {
1216					debug!(
1217						target: LOG_TARGET,
1218						"New peer {} with unknown best hash {} ({}), assuming common block.",
1219						peer_id,
1220						self.best_queued_hash,
1221						self.best_queued_number
1222					);
1223					self.peers.insert(
1224						peer_id,
1225						PeerSync {
1226							peer_id,
1227							common_number: self.best_queued_number,
1228							best_hash,
1229							best_number,
1230							state: PeerSyncState::Available,
1231						},
1232					);
1233					return Ok(None);
1234				}
1235
1236				// If we are at genesis, just start downloading.
1237				let (state, req) = if self.best_queued_number.is_zero() {
1238					debug!(
1239						target: LOG_TARGET,
1240						"New peer {peer_id} with best hash {best_hash} ({best_number}).",
1241					);
1242
1243					(PeerSyncState::Available, None)
1244				} else {
1245					let common_best = std::cmp::min(self.best_queued_number, best_number);
1246
1247					debug!(
1248						target: LOG_TARGET,
1249						"New peer {} with unknown best hash {} ({}), searching for common ancestor.",
1250						peer_id,
1251						best_hash,
1252						best_number
1253					);
1254
1255					(
1256						PeerSyncState::AncestorSearch {
1257							current: common_best,
1258							start: self.best_queued_number,
1259							state: AncestorSearchState::ExponentialBackoff(One::one()),
1260						},
1261						Some(ancestry_request::<B>(common_best)),
1262					)
1263				};
1264
1265				self.allowed_requests.add(&peer_id);
1266				self.peers.insert(
1267					peer_id,
1268					PeerSync {
1269						peer_id,
1270						common_number: Zero::zero(),
1271						best_hash,
1272						best_number,
1273						state,
1274					},
1275				);
1276
1277				Ok(req)
1278			},
1279			Ok(BlockStatus::Queued) |
1280			Ok(BlockStatus::InChainWithState) |
1281			Ok(BlockStatus::InChainPruned) => {
1282				debug!(
1283					target: LOG_TARGET,
1284					"New peer {peer_id} with known best hash {best_hash} ({best_number}).",
1285				);
1286				self.peers.insert(
1287					peer_id,
1288					PeerSync {
1289						peer_id,
1290						common_number: std::cmp::min(self.best_queued_number, best_number),
1291						best_hash,
1292						best_number,
1293						state: PeerSyncState::Available,
1294					},
1295				);
1296				self.allowed_requests.add(&peer_id);
1297				Ok(None)
1298			},
1299		}
1300	}
1301
1302	/// Release bookkeeping for a peer's old request and queue its cancellation.
1303	///
1304	/// The caller handles the peer's state transition and must call this before scheduling
1305	/// replacement work. The engine only drops the old response future.
1306	fn cancel_peer_request(&mut self, peer_id: PeerId, old_state: PeerSyncState<B>) {
1307		match old_state {
1308			PeerSyncState::Available => return,
1309			PeerSyncState::DownloadingNew(_) => self.blocks.clear_peer_download(&peer_id),
1310			PeerSyncState::DownloadingGap(_) => {
1311				if let Some(gap_sync) = &mut self.gap_sync {
1312					gap_sync.blocks.clear_peer_download(&peer_id);
1313				}
1314			},
1315			PeerSyncState::DownloadingJustification(_) => {
1316				self.extra_justifications.cancel_request(&peer_id);
1317			},
1318			// State requests are regenerated from the last imported cursor; fork targets
1319			// remain pending. Neither has a separate in-flight range reservation.
1320			PeerSyncState::DownloadingState |
1321			PeerSyncState::DownloadingStale(_) |
1322			PeerSyncState::AncestorSearch { .. } => {},
1323		}
1324		self.actions
1325			.push(SyncingAction::CancelRequest { peer_id, key: Self::STRATEGY_KEY });
1326		// Let any available peer pick up the released work, e.g. while this peer does
1327		// ancestry search.
1328		self.allowed_requests.set_all();
1329	}
1330
1331	fn create_block_request_action(
1332		&mut self,
1333		peer_id: PeerId,
1334		request: BlockRequest<B>,
1335	) -> SyncingAction<B> {
1336		let downloader = self.block_downloader.clone();
1337
1338		SyncingAction::StartRequest {
1339			peer_id,
1340			key: Self::STRATEGY_KEY,
1341			request: async move {
1342				Ok(downloader.download_blocks(peer_id, request.clone()).await?.and_then(
1343					|(response, protocol_name)| {
1344						let decoded_response =
1345							downloader.block_response_into_blocks(&request, response);
1346						let result = Box::new((request, decoded_response)) as Box<dyn Any + Send>;
1347						Ok((result, protocol_name))
1348					},
1349				))
1350			}
1351			.boxed(),
1352		}
1353	}
1354
1355	/// Submit a block response for processing.
1356	#[must_use]
1357	fn on_block_data(
1358		&mut self,
1359		peer_id: &PeerId,
1360		request: Option<BlockRequest<B>>,
1361		response: BlockResponse<B>,
1362	) -> Result<(), BadPeer> {
1363		self.downloaded_blocks += response.blocks.len();
1364		let mut gap = false;
1365		let new_blocks: Vec<IncomingBlock<B>> = if let Some(peer) = self.peers.get_mut(peer_id) {
1366			let mut blocks = response.blocks;
1367			if request.as_ref().map_or(false, |r| r.direction == Direction::Descending) {
1368				trace!(target: LOG_TARGET, "Reversing incoming block list");
1369				blocks.reverse()
1370			}
1371			self.allowed_requests.add(peer_id);
1372			if let Some(request) = request {
1373				match &mut peer.state {
1374					PeerSyncState::DownloadingNew(_) => {
1375						self.blocks.clear_peer_download(peer_id);
1376						peer.state = PeerSyncState::Available;
1377						if blocks.is_empty() {
1378							// The peer holds no block of the range. The range is inferred
1379							// from the peer's announced best number, which is not a claim to
1380							// hold the history below it (bodies are pruned oldest-first, and
1381							// a warp-synced node may still be backfilling), so this is not
1382							// misbehavior. Disconnect it anyway to hand the range - already
1383							// freed above - to a peer that has it; the mild penalty lets it
1384							// come back. Checked on `blocks` rather than the parsed header so
1385							// that a malformed non-empty response still gets the harsh
1386							// `NOT_REQUESTED` verdict from `validate_blocks` below.
1387							debug!(
1388								target: LOG_TARGET,
1389								"Peer {peer_id} sent an empty response for block request \
1390								 {request:?}; disconnecting it",
1391							);
1392							if let Some(metrics) = &self.metrics {
1393								metrics.empty_block_responses.inc();
1394							}
1395							return Err(BadPeer(*peer_id, rep::NO_BLOCKS_IN_RANGE));
1396						}
1397						if let Some(start_block) =
1398							validate_blocks::<B>(&blocks, peer_id, Some(request))?
1399						{
1400							self.blocks.insert(start_block, blocks, *peer_id);
1401						}
1402						self.ready_blocks()
1403					},
1404					PeerSyncState::DownloadingGap(_) => {
1405						peer.state = PeerSyncState::Available;
1406						if blocks.is_empty() && request.fields.contains(BlockAttributes::BODY) {
1407							// An empty response means the peer holds no body of the entire
1408							// range (bodies are pruned oldest-first). Disconnect it to free
1409							// the slot for a peer that does; the mild penalty lets it retry
1410							// later.
1411							debug!(
1412								target: LOG_TARGET,
1413								"Peer {peer_id} sent an empty response for gap block request \
1414								 {request:?} that required bodies; disconnecting it",
1415							);
1416							if let Some(metrics) = &self.metrics {
1417								metrics.gap_body_empty_responses.inc();
1418							}
1419							if let Some(gap_sync) = &mut self.gap_sync {
1420								gap_sync.blocks.clear_peer_download(peer_id);
1421							}
1422							return Err(BadPeer(*peer_id, rep::NO_GAP_BODIES));
1423						} else if blocks.is_empty() {
1424							// Header-only gap request, so the body check above does not
1425							// apply: the peer holds no header of the range either. Same
1426							// honest cause (its own history below the warp target may be
1427							// pruned or not yet backfilled), same treatment.
1428							debug!(
1429								target: LOG_TARGET,
1430								"Peer {peer_id} sent an empty response for header-only gap \
1431								 block request {request:?}; disconnecting it",
1432							);
1433							if let Some(metrics) = &self.metrics {
1434								metrics.empty_block_responses.inc();
1435							}
1436							if let Some(gap_sync) = &mut self.gap_sync {
1437								gap_sync.blocks.clear_peer_download(peer_id);
1438							}
1439							return Err(BadPeer(*peer_id, rep::NO_BLOCKS_IN_RANGE));
1440						}
1441						if let Some(gap_sync) = &mut self.gap_sync {
1442							gap_sync.blocks.clear_peer_download(peer_id);
1443							if let Some(start_block) =
1444								validate_blocks::<B>(&blocks, peer_id, Some(request))?
1445							{
1446								gap_sync.blocks.insert(start_block, blocks, *peer_id);
1447							}
1448							gap = true;
1449							let mut batch_gap_sync_stats = GapSyncStats::new();
1450							let blocks: Vec<_> = gap_sync
1451								.blocks
1452								.ready_blocks(gap_sync.best_queued_number + One::one())
1453								.into_iter()
1454								.map(|block_data| {
1455									let justifications =
1456										block_data.block.justifications.or_else(|| {
1457											legacy_justification_mapping(
1458												block_data.block.justification,
1459											)
1460										});
1461									let gap_sync_stats = GapSyncStats {
1462										header_bytes: block_data
1463											.block
1464											.header
1465											.as_ref()
1466											.map(|h| h.encoded_size())
1467											.unwrap_or(0),
1468										body_bytes: block_data
1469											.block
1470											.body
1471											.as_ref()
1472											.map(|b| b.encoded_size())
1473											.unwrap_or(0),
1474										justification_bytes: justifications
1475											.as_ref()
1476											.map(|j| j.encoded_size())
1477											.unwrap_or(0),
1478									};
1479									batch_gap_sync_stats += gap_sync_stats;
1480
1481									IncomingBlock {
1482										hash: block_data.block.hash,
1483										header: block_data.block.header,
1484										body: block_data.block.body,
1485										justifications,
1486										origin: block_data.origin,
1487										allow_missing_state: true,
1488										// Warp-synced blocks are header-only. Allow re-import to
1489										// store bodies if gap sync requested them.
1490										import_existing: true,
1491										skip_execution: true,
1492										state: None,
1493									}
1494								})
1495								.collect();
1496
1497							debug!(
1498								target: LOG_TARGET,
1499								"Drained {} gap blocks from {}",
1500								blocks.len(),
1501								gap_sync.best_queued_number,
1502							);
1503
1504							gap_sync.stats += batch_gap_sync_stats;
1505
1506							if blocks.len() > 0 {
1507								trace!(
1508									target: LOG_TARGET,
1509									"Gap sync cumulative stats: {}",
1510									gap_sync.stats
1511								);
1512							}
1513							blocks
1514						} else {
1515							debug!(target: LOG_TARGET, "Unexpected gap block response from {peer_id}");
1516							return Err(BadPeer(*peer_id, rep::NO_BLOCK));
1517						}
1518					},
1519					PeerSyncState::DownloadingStale(_) => {
1520						peer.state = PeerSyncState::Available;
1521						if blocks.is_empty() {
1522							debug!(target: LOG_TARGET, "Empty block response from {peer_id}");
1523							return Err(BadPeer(*peer_id, rep::NO_BLOCK));
1524						}
1525						validate_blocks::<B>(&blocks, peer_id, Some(request))?;
1526						blocks
1527							.into_iter()
1528							.map(|b| {
1529								let justifications = b
1530									.justifications
1531									.or_else(|| legacy_justification_mapping(b.justification));
1532								IncomingBlock {
1533									hash: b.hash,
1534									header: b.header,
1535									body: b.body,
1536									justifications,
1537									origin: Some(*peer_id),
1538									allow_missing_state: true,
1539									import_existing: self.import_existing,
1540									skip_execution: self.skip_execution(),
1541									state: None,
1542								}
1543							})
1544							.collect()
1545					},
1546					PeerSyncState::AncestorSearch { current, start, state } => {
1547						let matching_hash = match (blocks.get(0), self.client.hash(*current)) {
1548							(Some(block), Ok(maybe_our_block_hash)) => {
1549								trace!(
1550									target: LOG_TARGET,
1551									"Got ancestry block #{} ({}) from peer {}",
1552									current,
1553									block.hash,
1554									peer_id,
1555								);
1556								maybe_our_block_hash.filter(|x| x == &block.hash)
1557							},
1558							(None, _) => {
1559								debug!(
1560									target: LOG_TARGET,
1561									"Invalid response when searching for ancestor from {peer_id}",
1562								);
1563								return Err(BadPeer(*peer_id, rep::UNKNOWN_ANCESTOR));
1564							},
1565							(_, Err(e)) => {
1566								info!(
1567									target: LOG_TARGET,
1568									"โŒ Error answering legitimate blockchain query: {e}",
1569								);
1570								return Err(BadPeer(*peer_id, rep::BLOCKCHAIN_READ_ERROR));
1571							},
1572						};
1573						if matching_hash.is_some() {
1574							if *start < self.best_queued_number &&
1575								self.best_queued_number <= peer.best_number
1576							{
1577								// We've made progress on this chain since the search was started.
1578								// Opportunistically set common number to updated number
1579								// instead of the one that started the search.
1580								trace!(
1581									target: LOG_TARGET,
1582									"Ancestry search: opportunistically updating peer {} common number from={} => to={}.",
1583									*peer_id,
1584									peer.common_number,
1585									self.best_queued_number,
1586								);
1587								peer.common_number = self.best_queued_number;
1588							} else if peer.common_number < *current {
1589								trace!(
1590									target: LOG_TARGET,
1591									"Ancestry search: updating peer {} common number from={} => to={}.",
1592									*peer_id,
1593									peer.common_number,
1594									*current,
1595								);
1596								peer.common_number = *current;
1597							}
1598						}
1599						if matching_hash.is_none() && current.is_zero() {
1600							trace!(
1601								target: LOG_TARGET,
1602								"Ancestry search: genesis mismatch for peer {peer_id}",
1603							);
1604							return Err(BadPeer(*peer_id, rep::GENESIS_MISMATCH));
1605						}
1606						if let Some((next_state, next_num)) =
1607							handle_ancestor_search_state(state, *current, matching_hash.is_some())
1608						{
1609							peer.state = PeerSyncState::AncestorSearch {
1610								current: next_num,
1611								start: *start,
1612								state: next_state,
1613							};
1614							let request = ancestry_request::<B>(next_num);
1615							let action = self.create_block_request_action(*peer_id, request);
1616							self.actions.push(action);
1617							return Ok(());
1618						} else {
1619							// Ancestry search is complete. Check if peer is on a stale fork unknown
1620							// to us and add it to sync targets if necessary.
1621							trace!(
1622								target: LOG_TARGET,
1623								"Ancestry search complete. Ours={} ({}), Theirs={} ({}), Common={:?} ({})",
1624								self.best_queued_hash,
1625								self.best_queued_number,
1626								peer.best_hash,
1627								peer.best_number,
1628								matching_hash,
1629								peer.common_number,
1630							);
1631							if peer.common_number < peer.best_number &&
1632								peer.best_number < self.best_queued_number
1633							{
1634								trace!(
1635									target: LOG_TARGET,
1636									"Added fork target {} for {}",
1637									peer.best_hash,
1638									peer_id,
1639								);
1640								self.fork_targets
1641									.entry(peer.best_hash)
1642									.or_insert_with(|| {
1643										if let Some(metrics) = &self.metrics {
1644											metrics.fork_targets.inc();
1645										}
1646
1647										ForkTarget {
1648											number: peer.best_number,
1649											parent_hash: None,
1650											peers: Default::default(),
1651										}
1652									})
1653									.peers
1654									.insert(*peer_id);
1655							}
1656							peer.state = PeerSyncState::Available;
1657							return Ok(());
1658						}
1659					},
1660					PeerSyncState::Available |
1661					PeerSyncState::DownloadingJustification(..) |
1662					PeerSyncState::DownloadingState => Vec::new(),
1663				}
1664			} else {
1665				// When request.is_none() this is a block announcement. Just accept blocks.
1666				validate_blocks::<B>(&blocks, peer_id, None)?;
1667				blocks
1668					.into_iter()
1669					.map(|b| {
1670						let justifications = b
1671							.justifications
1672							.or_else(|| legacy_justification_mapping(b.justification));
1673						IncomingBlock {
1674							hash: b.hash,
1675							header: b.header,
1676							body: b.body,
1677							justifications,
1678							origin: Some(*peer_id),
1679							allow_missing_state: true,
1680							import_existing: false,
1681							skip_execution: true,
1682							state: None,
1683						}
1684					})
1685					.collect()
1686			}
1687		} else {
1688			// We don't know of this peer, so we also did not request anything from it.
1689			return Err(BadPeer(*peer_id, rep::NOT_REQUESTED));
1690		};
1691
1692		self.validate_and_queue_blocks(new_blocks, gap);
1693
1694		Ok(())
1695	}
1696
1697	fn on_block_response(
1698		&mut self,
1699		peer_id: &PeerId,
1700		key: StrategyKey,
1701		request: BlockRequest<B>,
1702		blocks: Vec<BlockData<B>>,
1703	) -> Result<(), BadPeer> {
1704		if key != Self::STRATEGY_KEY {
1705			error!(
1706				target: LOG_TARGET,
1707				"`on_block_response()` called with unexpected key {key:?} for chain sync",
1708			);
1709			debug_assert!(false);
1710		}
1711		let block_response = BlockResponse::<B> { id: request.id, blocks };
1712
1713		let blocks_range = || match (
1714			block_response
1715				.blocks
1716				.first()
1717				.and_then(|b| b.header.as_ref().map(|h| h.number())),
1718			block_response.blocks.last().and_then(|b| b.header.as_ref().map(|h| h.number())),
1719		) {
1720			(Some(first), Some(last)) if first != last => format!(" ({}..{})", first, last),
1721			(Some(first), Some(_)) => format!(" ({})", first),
1722			_ => Default::default(),
1723		};
1724
1725		trace!(
1726			target: LOG_TARGET,
1727			"BlockResponse {} from {} with {} blocks {}",
1728			block_response.id,
1729			peer_id,
1730			block_response.blocks.len(),
1731			blocks_range(),
1732		);
1733
1734		if request.fields == BlockAttributes::JUSTIFICATION {
1735			self.on_block_justification(*peer_id, block_response)
1736		} else {
1737			self.on_block_data(peer_id, Some(request), block_response)
1738		}
1739	}
1740
1741	/// Submit a justification response for processing.
1742	#[must_use]
1743	fn on_block_justification(
1744		&mut self,
1745		peer_id: PeerId,
1746		response: BlockResponse<B>,
1747	) -> Result<(), BadPeer> {
1748		let peer = if let Some(peer) = self.peers.get_mut(&peer_id) {
1749			peer
1750		} else {
1751			error!(
1752				target: LOG_TARGET,
1753				"๐Ÿ’” Called on_block_justification with a peer ID of an unknown peer",
1754			);
1755			return Ok(());
1756		};
1757
1758		self.allowed_requests.add(&peer_id);
1759		if let PeerSyncState::DownloadingJustification(hash) = peer.state {
1760			peer.state = PeerSyncState::Available;
1761
1762			// We only request one justification at a time
1763			let justification = if let Some(block) = response.blocks.into_iter().next() {
1764				if hash != block.hash {
1765					warn!(
1766						target: LOG_TARGET,
1767						"๐Ÿ’” Invalid block justification provided by {}: requested: {:?} got: {:?}",
1768						peer_id,
1769						hash,
1770						block.hash,
1771					);
1772					return Err(BadPeer(peer_id, rep::BAD_JUSTIFICATION));
1773				}
1774
1775				block
1776					.justifications
1777					.or_else(|| legacy_justification_mapping(block.justification))
1778			} else {
1779				// we might have asked the peer for a justification on a block that we assumed it
1780				// had but didn't (regardless of whether it had a justification for it or not).
1781				trace!(
1782					target: LOG_TARGET,
1783					"Peer {peer_id:?} provided empty response for justification request {hash:?}",
1784				);
1785
1786				None
1787			};
1788
1789			if let Some((peer_id, hash, number, justifications)) =
1790				self.extra_justifications.on_response(peer_id, justification)
1791			{
1792				self.actions.push(SyncingAction::ImportJustifications {
1793					peer_id,
1794					hash,
1795					number,
1796					justifications,
1797				});
1798				return Ok(());
1799			}
1800		}
1801
1802		Ok(())
1803	}
1804
1805	/// Returns the median seen block number.
1806	fn median_seen(&self) -> Option<NumberFor<B>> {
1807		let mut best_seens = self.peers.values().map(|p| p.best_number).collect::<Vec<_>>();
1808
1809		if best_seens.is_empty() {
1810			None
1811		} else {
1812			let middle = best_seens.len() / 2;
1813
1814			// Not the "perfect median" when we have an even number of peers.
1815			Some(*best_seens.select_nth_unstable(middle).1)
1816		}
1817	}
1818
1819	fn skip_execution(&self) -> bool {
1820		match self.mode {
1821			ChainSyncMode::Full => false,
1822			ChainSyncMode::LightState { .. } => true,
1823		}
1824	}
1825
1826	fn validate_and_queue_blocks(&mut self, mut new_blocks: Vec<IncomingBlock<B>>, gap: bool) {
1827		let orig_len = new_blocks.len();
1828		new_blocks.retain(|b| !self.queue_blocks.contains(&b.hash));
1829		if new_blocks.len() != orig_len {
1830			debug!(
1831				target: LOG_TARGET,
1832				"Ignoring {} blocks that are already queued",
1833				orig_len - new_blocks.len(),
1834			);
1835		}
1836
1837		let origin = if gap {
1838			// Gap sync: filling historical blocks after warp sync
1839			BlockOrigin::GapSync
1840		} else if !self.status().state.is_major_syncing() {
1841			// Normal operation: receiving new blocks
1842			BlockOrigin::NetworkBroadcast
1843		} else {
1844			// Initial sync: catching up with the chain
1845			BlockOrigin::NetworkInitialSync
1846		};
1847
1848		if let Some((h, n)) = new_blocks
1849			.last()
1850			.and_then(|b| b.header.as_ref().map(|h| (&b.hash, *h.number())))
1851		{
1852			trace!(
1853				target: LOG_TARGET,
1854				"Accepted {} blocks ({:?}) with origin {:?}",
1855				new_blocks.len(),
1856				h,
1857				origin,
1858			);
1859			self.on_block_queued(h, n)
1860		}
1861		self.queue_blocks.extend(new_blocks.iter().map(|b| b.hash));
1862		if let Some(metrics) = &self.metrics {
1863			metrics
1864				.queued_blocks
1865				.set(self.queue_blocks.len().try_into().unwrap_or(u64::MAX));
1866		}
1867
1868		self.actions.push(SyncingAction::ImportBlocks { origin, blocks: new_blocks })
1869	}
1870
1871	fn update_peer_common_number(&mut self, peer_id: &PeerId, new_common: NumberFor<B>) {
1872		if let Some(peer) = self.peers.get_mut(peer_id) {
1873			peer.update_common_number(new_common);
1874		}
1875	}
1876
1877	/// Called when a block has been queued for import.
1878	///
1879	/// Updates our internal state for best queued block and then goes
1880	/// through all peers to update our view of their state as well.
1881	fn on_block_queued(&mut self, hash: &B::Hash, number: NumberFor<B>) {
1882		if self.fork_targets.remove(hash).is_some() {
1883			if let Some(metrics) = &self.metrics {
1884				metrics.fork_targets.dec();
1885			}
1886			trace!(target: LOG_TARGET, "Completed fork sync {hash:?}");
1887		}
1888		if let Some(gap_sync) = &mut self.gap_sync {
1889			if number > gap_sync.best_queued_number && number <= gap_sync.target {
1890				gap_sync.best_queued_number = number;
1891			}
1892		}
1893		if number > self.best_queued_number {
1894			self.best_queued_number = number;
1895			self.best_queued_hash = *hash;
1896			// Update common blocks
1897			for (n, peer) in self.peers.iter_mut() {
1898				if let PeerSyncState::AncestorSearch { .. } = peer.state {
1899					// Wait for ancestry search to complete first.
1900					continue;
1901				}
1902				let new_common_number =
1903					if peer.best_number >= number { number } else { peer.best_number };
1904				trace!(
1905					target: LOG_TARGET,
1906					"Updating peer {} info, ours={}, common={}->{}, their best={}",
1907					n,
1908					number,
1909					peer.common_number,
1910					new_common_number,
1911					peer.best_number,
1912				);
1913				peer.common_number = new_common_number;
1914			}
1915		}
1916		self.allowed_requests.set_all();
1917	}
1918
1919	/// Restart the sync process. This will reset all pending block requests and return an iterator
1920	/// of new block requests to make to peers. Peers that were downloading finality data (i.e.
1921	/// their state was `DownloadingJustification`) are unaffected and will stay in the same state.
1922	fn restart(&mut self) {
1923		self.blocks.clear();
1924		if let Err(e) = self.reset_sync_start_point() {
1925			warn!(target: LOG_TARGET, "๐Ÿ’”  Unable to restart sync: {e}");
1926		}
1927		self.allowed_requests.set_all();
1928		debug!(
1929			target: LOG_TARGET,
1930			"Restarted with {} ({})",
1931			self.best_queued_number,
1932			self.best_queued_hash,
1933		);
1934		let old_peers = std::mem::take(&mut self.peers);
1935
1936		old_peers.into_iter().for_each(|(peer_id, mut peer_sync)| {
1937			match peer_sync.state {
1938				PeerSyncState::DownloadingJustification(_) => {
1939					// Peers that were downloading justifications
1940					// should be kept in that state.
1941					// We make sure our common number is at least something we have.
1942					trace!(
1943						target: LOG_TARGET,
1944						"Keeping peer {} after restart, updating common number from={} => to={} (our best).",
1945						peer_id,
1946						peer_sync.common_number,
1947						self.best_queued_number,
1948					);
1949					peer_sync.common_number = self.best_queued_number;
1950					self.peers.insert(peer_id, peer_sync);
1951				},
1952				_ => {
1953					self.cancel_peer_request(peer_id, peer_sync.state);
1954					self.add_peer(peer_id, peer_sync.best_hash, peer_sync.best_number);
1955				},
1956			}
1957		});
1958	}
1959
1960	/// Find a block to start sync from. If we sync with state, that's the latest block we have
1961	/// state for.
1962	fn reset_sync_start_point(&mut self) -> Result<(), ClientError> {
1963		let info = self.client.info();
1964		debug!(target: LOG_TARGET, "Restarting sync with client info {info:?}");
1965
1966		if matches!(self.mode, ChainSyncMode::LightState { .. }) && info.finalized_state.is_some() {
1967			warn!(
1968				target: LOG_TARGET,
1969				"Can't use fast sync mode with a partially synced database. Reverting to full sync mode."
1970			);
1971			self.mode = ChainSyncMode::Full;
1972		}
1973
1974		self.import_existing = false;
1975		self.best_queued_hash = info.best_hash;
1976		self.best_queued_number = info.best_number;
1977
1978		if self.mode == ChainSyncMode::Full &&
1979			self.client.block_status(info.best_hash)? != BlockStatus::InChainWithState
1980		{
1981			self.import_existing = true;
1982			// Latest state is missing, start with the last finalized state or genesis instead.
1983			if let Some((hash, number)) = info.finalized_state {
1984				debug!(target: LOG_TARGET, "Starting from finalized state #{number}");
1985				self.best_queued_hash = hash;
1986				self.best_queued_number = number;
1987			} else {
1988				debug!(target: LOG_TARGET, "Restarting from genesis");
1989				self.best_queued_hash = Default::default();
1990				self.best_queued_number = Zero::zero();
1991			}
1992		}
1993
1994		// The client is the source of truth for the gap. Rebuild the gap sync state from it, or
1995		// drop ours if the database has already closed the gap.
1996		let old_gap = self.gap_sync.take().map(|g| (g.best_queued_number, g.target));
1997		if let Some(BlockGap { start, end, .. }) = info.block_gap {
1998			debug!(target: LOG_TARGET, "Starting gap sync #{start} - #{end} (old gap best and target: {old_gap:?})");
1999			self.gap_sync = Some(GapSync {
2000				best_queued_number: start - One::one(),
2001				target: end,
2002				blocks: BlockCollection::with_metrics(
2003					self.metrics.as_ref().map(|m| m.block_collection.clone()),
2004				),
2005				stats: GapSyncStats::new(),
2006			});
2007		} else if let Some((best, target)) = old_gap {
2008			debug!(
2009				target: LOG_TARGET,
2010				"Block gap is closed in the database, dropping gap sync state (best: #{best}, target: #{target})",
2011			);
2012			if let Some(metrics) = &self.metrics {
2013				metrics.gap_oldest_required_body.set(0);
2014			}
2015		}
2016		trace!(
2017			target: LOG_TARGET,
2018			"Restarted sync at #{} ({:?})",
2019			self.best_queued_number,
2020			self.best_queued_hash,
2021		);
2022		Ok(())
2023	}
2024
2025	/// What is the status of the block corresponding to the given hash?
2026	fn block_status(&self, hash: &B::Hash) -> Result<BlockStatus, ClientError> {
2027		if self.queue_blocks.contains(hash) {
2028			return Ok(BlockStatus::Queued);
2029		}
2030		self.client.block_status(*hash)
2031	}
2032
2033	/// Is the block corresponding to the given hash known?
2034	fn is_known(&self, hash: &B::Hash) -> bool {
2035		self.block_status(hash).ok().map_or(false, |s| s != BlockStatus::Unknown)
2036	}
2037
2038	/// Is any peer downloading the given hash?
2039	fn is_already_downloading(&self, hash: &B::Hash) -> bool {
2040		self.peers
2041			.iter()
2042			.any(|(_, p)| p.state == PeerSyncState::DownloadingStale(*hash))
2043	}
2044
2045	/// Get the set of downloaded blocks that are ready to be queued for import.
2046	fn ready_blocks(&mut self) -> Vec<IncomingBlock<B>> {
2047		self.blocks
2048			.ready_blocks(self.best_queued_number + One::one())
2049			.into_iter()
2050			.map(|block_data| {
2051				let justifications = block_data
2052					.block
2053					.justifications
2054					.or_else(|| legacy_justification_mapping(block_data.block.justification));
2055				IncomingBlock {
2056					hash: block_data.block.hash,
2057					header: block_data.block.header,
2058					body: block_data.block.body,
2059					justifications,
2060					origin: block_data.origin,
2061					allow_missing_state: true,
2062					import_existing: self.import_existing,
2063					skip_execution: self.skip_execution(),
2064					state: None,
2065				}
2066			})
2067			.collect()
2068	}
2069
2070	/// Get justification requests scheduled by sync to be sent out.
2071	fn justification_requests(&mut self) -> Vec<(PeerId, BlockRequest<B>)> {
2072		let peers = &mut self.peers;
2073		let mut matcher = self.extra_justifications.matcher();
2074		std::iter::from_fn(move || {
2075			if let Some((peer, request)) = matcher.next(peers) {
2076				peers
2077					.get_mut(&peer)
2078					.expect(
2079						"`Matcher::next` guarantees the `PeerId` comes from the given peers; qed",
2080					)
2081					.state = PeerSyncState::DownloadingJustification(request.0);
2082				let req = BlockRequest::<B> {
2083					id: 0,
2084					fields: BlockAttributes::JUSTIFICATION,
2085					from: FromBlock::Hash(request.0),
2086					direction: Direction::Ascending,
2087					max: Some(1),
2088				};
2089				Some((peer, req))
2090			} else {
2091				None
2092			}
2093		})
2094		.collect()
2095	}
2096
2097	/// Block attributes for gap requests, plus the body cutoff: bodies are required for
2098	/// gap blocks above the cutoff and stripped from ranges entirely at or below it.
2099	/// Recomputed every scheduling pass so the cutoff follows finality.
2100	fn gap_request_attributes(
2101		&self,
2102		finalized_number: NumberFor<B>,
2103	) -> (BlockAttributes, Option<NumberFor<B>>) {
2104		let attrs = required_block_attributes();
2105		match self.gap_sync_body_policy {
2106			GapSyncBodyPolicy::HeadersOnly => (attrs & !BlockAttributes::BODY, None),
2107			GapSyncBodyPolicy::All => (attrs, None),
2108			GapSyncBodyPolicy::BodiesWithinWindow(window) => {
2109				// The gap is created by importing a finalized block right above it,
2110				// so `gap.target + 1` is a lower bound for the finalized number even
2111				// while the client's finality info still lags right after warp sync.
2112				let anchor = self.gap_sync.as_ref().map_or(finalized_number, |gap| {
2113					std::cmp::max(finalized_number, gap.target + One::one())
2114				});
2115				(attrs, Some(anchor.saturating_sub(window.into())))
2116			},
2117		}
2118	}
2119
2120	/// Get block requests scheduled by sync to be sent out.
2121	fn block_requests(&mut self) -> Vec<(PeerId, BlockRequest<B>)> {
2122		if self.allowed_requests.is_empty() || self.state_sync.is_some() {
2123			return Vec::new();
2124		}
2125
2126		if self.queue_blocks.len() > MAX_IMPORTING_BLOCKS {
2127			trace!(target: LOG_TARGET, "Too many blocks in the queue.");
2128			return Vec::new();
2129		}
2130		let is_major_syncing = self.status().state.is_major_syncing();
2131		let finalized_number = self.client.info().finalized_number;
2132		let (gap_attrs, gap_body_cutoff) = self.gap_request_attributes(finalized_number);
2133		if let (Some(metrics), Some(cutoff), Some(gap)) =
2134			(self.metrics.as_ref(), gap_body_cutoff, self.gap_sync.as_ref())
2135		{
2136			// The oldest gap block still requiring a body: the lowest not-yet-queued
2137			// block, clamped from below by the cutoff.
2138			let oldest_required = std::cmp::max(gap.best_queued_number, cutoff) + One::one();
2139			metrics.gap_oldest_required_body.set(if oldest_required <= gap.target {
2140				oldest_required.saturated_into::<u64>()
2141			} else {
2142				0
2143			});
2144		}
2145		let blocks = &mut self.blocks;
2146		let fork_targets = &mut self.fork_targets;
2147		let last_finalized = std::cmp::min(self.best_queued_number, finalized_number);
2148		let best_queued = self.best_queued_number;
2149		let client = &self.client;
2150		let queue_blocks = &self.queue_blocks;
2151		let allowed_requests = self.allowed_requests.clone();
2152		let max_parallel = if is_major_syncing { 1 } else { self.max_parallel_downloads };
2153		let max_blocks_per_request = self.max_blocks_per_request;
2154		let gap_sync = &mut self.gap_sync;
2155		let disconnected_peers = &mut self.disconnected_peers;
2156		let metrics = self.metrics.as_ref();
2157		let requests = self
2158			.peers
2159			.iter_mut()
2160			.filter_map(move |(&id, peer)| {
2161				if !peer.state.is_available() ||
2162					!allowed_requests.contains(&id) ||
2163					!disconnected_peers.is_peer_available(&id)
2164				{
2165					return None;
2166				}
2167
2168				// If our best queued is more than `MAX_BLOCKS_TO_LOOK_BACKWARDS` blocks away from
2169				// the common number, the peer best number is higher than our best queued and the
2170				// common number is smaller than the last finalized block number, we should do an
2171				// ancestor search to find a better common block. If the queue is full we wait till
2172				// all blocks are imported though.
2173				if best_queued.saturating_sub(peer.common_number) >
2174					MAX_BLOCKS_TO_LOOK_BACKWARDS.into() &&
2175					best_queued < peer.best_number &&
2176					peer.common_number < last_finalized &&
2177					queue_blocks.len() <= MAJOR_SYNC_BLOCKS as usize
2178				{
2179					trace!(
2180						target: LOG_TARGET,
2181						"Peer {:?} common block {} too far behind of our best {}. Starting ancestry search.",
2182						id,
2183						peer.common_number,
2184						best_queued,
2185					);
2186					let current = std::cmp::min(peer.best_number, best_queued);
2187					peer.state = PeerSyncState::AncestorSearch {
2188						current,
2189						start: best_queued,
2190						state: AncestorSearchState::ExponentialBackoff(One::one()),
2191					};
2192					Some((id, ancestry_request::<B>(current)))
2193				} else if let Some((range, req)) = peer_block_request(
2194					&id,
2195					peer,
2196					blocks,
2197					required_block_attributes(),
2198					max_parallel,
2199					max_blocks_per_request,
2200					last_finalized,
2201					best_queued,
2202				) {
2203					peer.state = PeerSyncState::DownloadingNew(range.start);
2204					trace!(
2205						target: LOG_TARGET,
2206						"New block request for {}, (best:{}, common:{}) {:?}",
2207						id,
2208						peer.best_number,
2209						peer.common_number,
2210						req,
2211					);
2212					Some((id, req))
2213				} else if let Some((hash, req)) = fork_sync_request(
2214					&id,
2215					fork_targets,
2216					best_queued,
2217					last_finalized,
2218					required_block_attributes(),
2219					|hash| {
2220						if queue_blocks.contains(hash) {
2221							BlockStatus::Queued
2222						} else {
2223							client.block_status(*hash).unwrap_or(BlockStatus::Unknown)
2224						}
2225					},
2226					max_blocks_per_request,
2227					metrics,
2228				) {
2229					trace!(target: LOG_TARGET, "Downloading fork {hash:?} from {id}");
2230					peer.state = PeerSyncState::DownloadingStale(hash);
2231					Some((id, req))
2232				} else if let Some((range, req)) = gap_sync.as_mut().and_then(|sync| {
2233					peer_gap_block_request(
2234						&id,
2235						peer,
2236						&mut sync.blocks,
2237						gap_attrs,
2238						gap_body_cutoff,
2239						is_major_syncing,
2240						sync.target,
2241						sync.best_queued_number,
2242						max_blocks_per_request,
2243						metrics,
2244					)
2245				}) {
2246					peer.state = PeerSyncState::DownloadingGap(range.start);
2247					trace!(
2248						target: LOG_TARGET,
2249						"New gap block request for {}, (best:{}, common:{}) {:?}",
2250						id,
2251						peer.best_number,
2252						peer.common_number,
2253						req,
2254					);
2255					Some((id, req))
2256				} else {
2257					None
2258				}
2259			})
2260			.collect::<Vec<_>>();
2261
2262		// Clear the allowed_requests state when sending new block requests
2263		// to prevent multiple inflight block requests from being issued.
2264		if !requests.is_empty() {
2265			self.allowed_requests.take();
2266		}
2267
2268		requests
2269	}
2270
2271	/// Get a state request scheduled by sync to be sent out (if any).
2272	fn state_request(&mut self) -> Option<(PeerId, StateRequest)> {
2273		if self.allowed_requests.is_empty() {
2274			return None;
2275		}
2276		if self.state_sync.is_some() &&
2277			self.peers.iter().any(|(_, peer)| peer.state == PeerSyncState::DownloadingState)
2278		{
2279			// Only one pending state request is allowed.
2280			return None;
2281		}
2282		if let Some(sync) = &self.state_sync {
2283			if sync.is_complete() {
2284				return None;
2285			}
2286
2287			for (id, peer) in self.peers.iter_mut() {
2288				if peer.state.is_available() &&
2289					peer.common_number >= sync.target_number() &&
2290					self.disconnected_peers.is_peer_available(&id)
2291				{
2292					peer.state = PeerSyncState::DownloadingState;
2293					let request = sync.next_request();
2294					trace!(target: LOG_TARGET, "New StateRequest for {}: {:?}", id, request);
2295					self.allowed_requests.clear();
2296					return Some((*id, request));
2297				}
2298			}
2299		}
2300		None
2301	}
2302
2303	#[must_use]
2304	fn on_state_data(&mut self, peer_id: &PeerId, response: &[u8]) -> Result<(), BadPeer> {
2305		let response = match StateResponse::decode(response) {
2306			Ok(response) => response,
2307			Err(error) => {
2308				debug!(
2309					target: LOG_TARGET,
2310					"Failed to decode state response from peer {peer_id:?}: {error:?}.",
2311				);
2312
2313				return Err(BadPeer(*peer_id, rep::BAD_RESPONSE));
2314			},
2315		};
2316
2317		if let Some(peer) = self.peers.get_mut(peer_id) {
2318			if let PeerSyncState::DownloadingState = peer.state {
2319				peer.state = PeerSyncState::Available;
2320				self.allowed_requests.set_all();
2321			}
2322		}
2323		let import_result = if let Some(sync) = &mut self.state_sync {
2324			debug!(
2325				target: LOG_TARGET,
2326				"Importing state data from {} with {} keys, {} proof nodes.",
2327				peer_id,
2328				response.entries.len(),
2329				response.proof.len(),
2330			);
2331			sync.import(response)
2332		} else {
2333			debug!(target: LOG_TARGET, "Ignored obsolete state response from {peer_id}");
2334			return Err(BadPeer(*peer_id, rep::NOT_REQUESTED));
2335		};
2336
2337		match import_result {
2338			ImportResult::Import(hash, header, state, body, justifications) => {
2339				let origin = BlockOrigin::NetworkInitialSync;
2340				let block = IncomingBlock {
2341					hash,
2342					header: Some(header),
2343					body,
2344					justifications,
2345					origin: None,
2346					allow_missing_state: true,
2347					import_existing: true,
2348					skip_execution: self.skip_execution(),
2349					state: Some(state),
2350				};
2351				debug!(target: LOG_TARGET, "State download is complete. Import is queued");
2352				self.actions.push(SyncingAction::ImportBlocks { origin, blocks: vec![block] });
2353				Ok(())
2354			},
2355			ImportResult::Continue => Ok(()),
2356			ImportResult::BadResponse => {
2357				debug!(target: LOG_TARGET, "Bad state data received from {peer_id}");
2358				Err(BadPeer(*peer_id, rep::BAD_BLOCK))
2359			},
2360		}
2361	}
2362
2363	fn attempt_state_sync(
2364		&mut self,
2365		finalized_hash: B::Hash,
2366		finalized_number: NumberFor<B>,
2367		skip_proofs: bool,
2368	) {
2369		let mut heads: Vec<_> = self.peers.values().map(|peer| peer.best_number).collect();
2370		heads.sort();
2371		let median = heads[heads.len() / 2];
2372		if finalized_number + STATE_SYNC_FINALITY_THRESHOLD.saturated_into() >= median {
2373			if let Ok(Some(header)) = self.client.header(finalized_hash) {
2374				log::debug!(
2375					target: LOG_TARGET,
2376					"Starting state sync for #{finalized_number} ({finalized_hash})",
2377				);
2378				self.state_sync =
2379					Some(StateSync::new(self.client.clone(), header, None, None, skip_proofs));
2380				self.allowed_requests.set_all();
2381			} else {
2382				log::error!(
2383					target: LOG_TARGET,
2384					"Failed to start state sync: header for finalized block \
2385					  #{finalized_number} ({finalized_hash}) is not available",
2386				);
2387				debug_assert!(false);
2388			}
2389		}
2390	}
2391
2392	/// A version of `actions()` that doesn't schedule extra requests. For testing only.
2393	#[cfg(test)]
2394	#[must_use]
2395	fn take_actions(&mut self) -> impl Iterator<Item = SyncingAction<B>> {
2396		std::mem::take(&mut self.actions).into_iter()
2397	}
2398}
2399
2400// This is purely during a backwards compatible transitionary period and should be removed
2401// once we can assume all nodes can send and receive multiple Justifications
2402// The ID tag is hardcoded here to avoid depending on the GRANDPA crate.
2403// See: https://github.com/paritytech/substrate/issues/8172
2404fn legacy_justification_mapping(
2405	justification: Option<EncodedJustification>,
2406) -> Option<Justifications> {
2407	justification.map(|just| (*b"FRNK", just).into())
2408}
2409
2410/// Request the ancestry for a block. Sends a request for header and justification for the given
2411/// block number. Used during ancestry search.
2412fn ancestry_request<B: BlockT>(block: NumberFor<B>) -> BlockRequest<B> {
2413	BlockRequest::<B> {
2414		id: 0,
2415		fields: BlockAttributes::HEADER | BlockAttributes::JUSTIFICATION,
2416		from: FromBlock::Number(block),
2417		direction: Direction::Ascending,
2418		max: Some(1),
2419	}
2420}
2421
2422/// The ancestor search state expresses which algorithm, and its stateful parameters, we are using
2423/// to try to find an ancestor block
2424#[derive(Copy, Clone, Eq, PartialEq, Debug)]
2425pub(crate) enum AncestorSearchState<B: BlockT> {
2426	/// Use exponential backoff to find an ancestor, then switch to binary search.
2427	/// We keep track of the exponent.
2428	ExponentialBackoff(NumberFor<B>),
2429	/// Using binary search to find the best ancestor.
2430	/// We keep track of left and right bounds.
2431	BinarySearch(NumberFor<B>, NumberFor<B>),
2432}
2433
2434/// This function handles the ancestor search strategy used. The goal is to find a common point
2435/// that both our chains agree on that is as close to the tip as possible.
2436/// The way this works is we first have an exponential backoff strategy, where we try to step
2437/// forward until we find a block hash mismatch. The size of the step doubles each step we take.
2438///
2439/// When we've found a block hash mismatch we then fall back to a binary search between the two
2440/// last known points to find the common block closest to the tip.
2441fn handle_ancestor_search_state<B: BlockT>(
2442	state: &AncestorSearchState<B>,
2443	curr_block_num: NumberFor<B>,
2444	block_hash_match: bool,
2445) -> Option<(AncestorSearchState<B>, NumberFor<B>)> {
2446	let two = <NumberFor<B>>::one() + <NumberFor<B>>::one();
2447	match state {
2448		AncestorSearchState::ExponentialBackoff(next_distance_to_tip) => {
2449			let next_distance_to_tip = *next_distance_to_tip;
2450			if block_hash_match && next_distance_to_tip == One::one() {
2451				// We found the ancestor in the first step so there is no need to execute binary
2452				// search.
2453				return None;
2454			}
2455			if block_hash_match {
2456				let left = curr_block_num;
2457				let right = left + next_distance_to_tip / two;
2458				let middle = left + (right - left) / two;
2459				Some((AncestorSearchState::BinarySearch(left, right), middle))
2460			} else {
2461				let next_block_num =
2462					curr_block_num.checked_sub(&next_distance_to_tip).unwrap_or_else(Zero::zero);
2463				let next_distance_to_tip = next_distance_to_tip * two;
2464				Some((
2465					AncestorSearchState::ExponentialBackoff(next_distance_to_tip),
2466					next_block_num,
2467				))
2468			}
2469		},
2470		AncestorSearchState::BinarySearch(mut left, mut right) => {
2471			if left >= curr_block_num {
2472				return None;
2473			}
2474			if block_hash_match {
2475				left = curr_block_num;
2476			} else {
2477				right = curr_block_num;
2478			}
2479			assert!(right >= left);
2480			let middle = left + (right - left) / two;
2481			if middle == curr_block_num {
2482				None
2483			} else {
2484				Some((AncestorSearchState::BinarySearch(left, right), middle))
2485			}
2486		},
2487	}
2488}
2489
2490/// Get a new block request for the peer if any.
2491fn peer_block_request<B: BlockT>(
2492	id: &PeerId,
2493	peer: &PeerSync<B>,
2494	blocks: &mut BlockCollection<B>,
2495	attrs: BlockAttributes,
2496	max_parallel_downloads: u32,
2497	max_blocks_per_request: u32,
2498	finalized: NumberFor<B>,
2499	best_num: NumberFor<B>,
2500) -> Option<(Range<NumberFor<B>>, BlockRequest<B>)> {
2501	if best_num >= peer.best_number {
2502		// Will be downloaded as alternative fork instead.
2503		return None;
2504	} else if peer.common_number < finalized {
2505		trace!(
2506			target: LOG_TARGET,
2507			"Requesting pre-finalized chain from {:?}, common={}, finalized={}, peer best={}, our best={}",
2508			id, peer.common_number, finalized, peer.best_number, best_num,
2509		);
2510	}
2511	let range = blocks.needed_blocks(
2512		*id,
2513		max_blocks_per_request,
2514		peer.best_number,
2515		peer.common_number,
2516		max_parallel_downloads,
2517		MAX_DOWNLOAD_AHEAD,
2518	)?;
2519
2520	// The end is not part of the range.
2521	let last = range.end.saturating_sub(One::one());
2522
2523	let from = if peer.best_number == last {
2524		FromBlock::Hash(peer.best_hash)
2525	} else {
2526		FromBlock::Number(last)
2527	};
2528
2529	let request = BlockRequest::<B> {
2530		id: 0,
2531		fields: attrs,
2532		from,
2533		direction: Direction::Descending,
2534		max: Some((range.end - range.start).saturated_into::<u32>()),
2535	};
2536
2537	Some((range, request))
2538}
2539
2540/// Get a new gap block request for the peer if any.
2541///
2542/// Bodies are stripped from the request if the whole range is at or below
2543/// `body_cutoff`. A range straddling the cutoff requests bodies for all its blocks
2544/// rather than being split.
2545///
2546/// While the node is major syncing, the cutoff is a stale lower bound of the true one
2547/// (peers may have pruned bodies right above it), so scheduling is clamped to the
2548/// header-only region at or below it until the node has caught up.
2549fn peer_gap_block_request<B: BlockT>(
2550	id: &PeerId,
2551	peer: &PeerSync<B>,
2552	blocks: &mut BlockCollection<B>,
2553	attrs: BlockAttributes,
2554	body_cutoff: Option<NumberFor<B>>,
2555	is_major_syncing: bool,
2556	target: NumberFor<B>,
2557	common_number: NumberFor<B>,
2558	max_blocks_per_request: u32,
2559	metrics: Option<&Metrics>,
2560) -> Option<(Range<NumberFor<B>>, BlockRequest<B>)> {
2561	let mut scheduling_bound = std::cmp::min(peer.best_number, target);
2562	if let Some(cutoff) = body_cutoff.filter(|_| is_major_syncing) {
2563		scheduling_bound = std::cmp::min(scheduling_bound, cutoff);
2564	}
2565	let range = blocks.needed_blocks(
2566		*id,
2567		max_blocks_per_request,
2568		scheduling_bound,
2569		common_number,
2570		1,
2571		MAX_DOWNLOAD_AHEAD,
2572	)?;
2573
2574	// The end is not part of the range.
2575	let last = range.end.saturating_sub(One::one());
2576	let from = FromBlock::Number(last);
2577
2578	let attrs = match body_cutoff {
2579		Some(cutoff) if last <= cutoff => {
2580			if let Some(metrics) = metrics {
2581				metrics.gap_header_only_downgrades.inc();
2582			}
2583			attrs & !BlockAttributes::BODY
2584		},
2585		_ => attrs,
2586	};
2587
2588	let request = BlockRequest::<B> {
2589		id: 0,
2590		fields: attrs,
2591		from,
2592		direction: Direction::Descending,
2593		max: Some((range.end - range.start).saturated_into::<u32>()),
2594	};
2595	Some((range, request))
2596}
2597
2598/// Get pending fork sync targets for a peer.
2599fn fork_sync_request<B: BlockT>(
2600	id: &PeerId,
2601	fork_targets: &mut HashMap<B::Hash, ForkTarget<B>>,
2602	best_num: NumberFor<B>,
2603	finalized: NumberFor<B>,
2604	attributes: BlockAttributes,
2605	check_block: impl Fn(&B::Hash) -> BlockStatus,
2606	max_blocks_per_request: u32,
2607	metrics: Option<&Metrics>,
2608) -> Option<(B::Hash, BlockRequest<B>)> {
2609	fork_targets.retain(|hash, r| {
2610		if r.number <= finalized {
2611			trace!(
2612				target: LOG_TARGET,
2613				"Removed expired fork sync request {:?} (#{})",
2614				hash,
2615				r.number,
2616			);
2617			return false;
2618		}
2619		if check_block(hash) != BlockStatus::Unknown {
2620			trace!(
2621				target: LOG_TARGET,
2622				"Removed obsolete fork sync request {:?} (#{})",
2623				hash,
2624				r.number,
2625			);
2626			return false;
2627		}
2628		true
2629	});
2630	if let Some(metrics) = metrics {
2631		metrics.fork_targets.set(fork_targets.len().try_into().unwrap_or(u64::MAX));
2632	}
2633	for (hash, r) in fork_targets {
2634		if !r.peers.contains(&id) {
2635			continue;
2636		}
2637		// Download the fork only if it is behind or not too far ahead our tip of the chain
2638		// Otherwise it should be downloaded in full sync mode.
2639		if r.number <= best_num ||
2640			(r.number - best_num).saturated_into::<u32>() < max_blocks_per_request as u32
2641		{
2642			let parent_status = r.parent_hash.as_ref().map_or(BlockStatus::Unknown, check_block);
2643			let count = if parent_status == BlockStatus::Unknown {
2644				(r.number - finalized).saturated_into::<u32>() // up to the last finalized block
2645			} else {
2646				// request only single block
2647				1
2648			};
2649			trace!(
2650				target: LOG_TARGET,
2651				"Downloading requested fork {hash:?} from {id}, {count} blocks",
2652			);
2653			return Some((
2654				*hash,
2655				BlockRequest::<B> {
2656					id: 0,
2657					fields: attributes,
2658					from: FromBlock::Hash(*hash),
2659					direction: Direction::Descending,
2660					max: Some(count),
2661				},
2662			));
2663		} else {
2664			trace!(target: LOG_TARGET, "Fork too far in the future: {:?} (#{})", hash, r.number);
2665		}
2666	}
2667	None
2668}
2669
2670/// Returns `true` if the given `block` is a descendent of `base`.
2671fn is_descendent_of<Block, T>(
2672	client: &T,
2673	base: &Block::Hash,
2674	block: &Block::Hash,
2675) -> sp_blockchain::Result<bool>
2676where
2677	Block: BlockT,
2678	T: HeaderMetadata<Block, Error = sp_blockchain::Error> + ?Sized,
2679{
2680	if base == block {
2681		return Ok(false);
2682	}
2683
2684	let ancestor = sp_blockchain::lowest_common_ancestor(client, *block, *base)?;
2685
2686	Ok(ancestor.hash == *base)
2687}
2688
2689/// Validate that the given `blocks` are correct.
2690/// Returns the number of the first block in the sequence.
2691///
2692/// It is expected that `blocks` are in ascending order.
2693pub fn validate_blocks<Block: BlockT>(
2694	blocks: &Vec<BlockData<Block>>,
2695	peer_id: &PeerId,
2696	request: Option<BlockRequest<Block>>,
2697) -> Result<Option<NumberFor<Block>>, BadPeer> {
2698	if let Some(request) = request {
2699		if Some(blocks.len() as _) > request.max {
2700			debug!(
2701				target: LOG_TARGET,
2702				"Received more blocks than requested from {}. Expected in maximum {:?}, got {}.",
2703				peer_id,
2704				request.max,
2705				blocks.len(),
2706			);
2707
2708			return Err(BadPeer(*peer_id, rep::NOT_REQUESTED));
2709		}
2710
2711		let block_header =
2712			if request.direction == Direction::Descending { blocks.last() } else { blocks.first() }
2713				.and_then(|b| b.header.as_ref());
2714
2715		let expected_block = block_header.as_ref().map_or(false, |h| match request.from {
2716			FromBlock::Hash(hash) => h.hash() == hash,
2717			FromBlock::Number(n) => h.number() == &n,
2718		});
2719
2720		if !expected_block {
2721			debug!(
2722				target: LOG_TARGET,
2723				"Received block that was not requested. Requested {:?}, got {:?}.",
2724				request.from,
2725				block_header,
2726			);
2727
2728			return Err(BadPeer(*peer_id, rep::NOT_REQUESTED));
2729		}
2730
2731		if request.fields.contains(BlockAttributes::HEADER) &&
2732			blocks.iter().any(|b| b.header.is_none())
2733		{
2734			trace!(
2735				target: LOG_TARGET,
2736				"Missing requested header for a block in response from {peer_id}.",
2737			);
2738
2739			return Err(BadPeer(*peer_id, rep::BAD_RESPONSE));
2740		}
2741
2742		if request.fields.contains(BlockAttributes::BODY) && blocks.iter().any(|b| b.body.is_none())
2743		{
2744			trace!(
2745				target: LOG_TARGET,
2746				"Missing requested body for a block in response from {peer_id}.",
2747			);
2748
2749			return Err(BadPeer(*peer_id, rep::BAD_RESPONSE));
2750		}
2751	}
2752
2753	for b in blocks {
2754		if let Some(header) = &b.header {
2755			let hash = header.hash();
2756			if hash != b.hash {
2757				debug!(
2758					target: LOG_TARGET,
2759					"Bad header received from {}. Expected hash {:?}, got {:?}",
2760					peer_id,
2761					b.hash,
2762					hash,
2763				);
2764				return Err(BadPeer(*peer_id, rep::BAD_BLOCK));
2765			}
2766		}
2767	}
2768
2769	Ok(blocks.first().and_then(|b| b.header.as_ref()).map(|h| *h.number()))
2770}