Skip to main content

pezkuwi_node_subsystem_util/
backing_implicit_view.rs

1// Copyright (C) Parity Technologies (UK) Ltd. and Dijital Kurdistan Tech Institute
2// This file is part of Pezkuwi.
3
4// Pezkuwi is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Pezkuwi is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Pezkuwi.  If not, see <http://www.gnu.org/licenses/>.
16
17use futures::channel::oneshot;
18use pezkuwi_node_subsystem::{
19	errors::ChainApiError,
20	messages::{ChainApiMessage, ProspectiveTeyrchainsMessage, RuntimeApiMessage},
21	SubsystemSender,
22};
23use pezkuwi_primitives::{BlockNumber, Hash, Id as ParaId};
24
25use std::collections::{HashMap, HashSet};
26
27use crate::{
28	inclusion_emulator::RelayChainBlockInfo,
29	request_session_index_for_child,
30	runtime::{self, fetch_scheduling_lookahead, recv_runtime},
31	LOG_TARGET,
32};
33
34// Always aim to retain 1 block before the active leaves.
35const MINIMUM_RETAIN_LENGTH: BlockNumber = 2;
36
37/// Handles the implicit view of the relay chain derived from the immediate view, which
38/// is composed of active leaves, and the minimum relay-parents allowed for
39/// candidates of various teyrchains at those leaves.
40#[derive(Clone)]
41pub struct View {
42	leaves: HashMap<Hash, ActiveLeafPruningInfo>,
43	block_info_storage: HashMap<Hash, BlockInfo>,
44	collating_for: Option<ParaId>,
45}
46
47impl View {
48	/// Create a new empty view.
49	/// If `collating_for` is `Some`, the node is a collator and is only interested in the allowed
50	/// relay parents of a single paraid. When this is true, prospective-teyrchains is no longer
51	/// queried.
52	pub fn new(collating_for: Option<ParaId>) -> Self {
53		Self { leaves: Default::default(), block_info_storage: Default::default(), collating_for }
54	}
55}
56
57impl Default for View {
58	fn default() -> Self {
59		Self::new(None)
60	}
61}
62
63// Minimum relay parents implicitly relative to a particular block.
64#[derive(Debug, Clone)]
65struct AllowedRelayParents {
66	// minimum relay parents can only be fetched for active leaves,
67	// so this will be empty for all blocks that haven't ever been
68	// witnessed as active leaves.
69	minimum_relay_parents: HashMap<ParaId, BlockNumber>,
70	// Ancestry, in descending order, starting from the block hash itself down
71	// to and including the minimum of `minimum_relay_parents`.
72	allowed_relay_parents_contiguous: Vec<Hash>,
73}
74
75impl AllowedRelayParents {
76	fn allowed_relay_parents_for(
77		&self,
78		para_id: Option<ParaId>,
79		base_number: BlockNumber,
80	) -> &[Hash] {
81		let para_id = match para_id {
82			None => return &self.allowed_relay_parents_contiguous[..],
83			Some(p) => p,
84		};
85
86		let para_min = match self.minimum_relay_parents.get(&para_id) {
87			Some(p) => *p,
88			None => return &[],
89		};
90
91		if base_number < para_min {
92			return &[];
93		}
94
95		let diff = base_number - para_min;
96
97		// difference of 0 should lead to slice len of 1
98		let slice_len = ((diff + 1) as usize).min(self.allowed_relay_parents_contiguous.len());
99		&self.allowed_relay_parents_contiguous[..slice_len]
100	}
101}
102
103#[derive(Debug, Clone)]
104struct ActiveLeafPruningInfo {
105	// The minimum block in the same branch of the relay-chain that should be
106	// preserved.
107	retain_minimum: BlockNumber,
108}
109
110#[derive(Debug, Clone)]
111struct BlockInfo {
112	block_number: BlockNumber,
113	// If this was previously an active leaf, this will be `Some`
114	// and is useful for understanding the views of peers in the network
115	// which may not be in perfect synchrony with our own view.
116	//
117	// If they are ahead of us in getting a new leaf, there's nothing we
118	// can do as it's an unrecognized block hash. But if they're behind us,
119	// it's useful for us to retain some information about previous leaves'
120	// implicit views so we can continue to send relevant messages to them
121	// until they catch up.
122	maybe_allowed_relay_parents: Option<AllowedRelayParents>,
123	parent_hash: Hash,
124}
125
126/// Information about a relay-chain block, to be used when calling this module from prospective
127/// teyrchains.
128#[derive(Debug, Clone, PartialEq)]
129pub struct BlockInfoProspectiveTeyrchains {
130	/// The hash of the relay-chain block.
131	pub hash: Hash,
132	/// The hash of the parent relay-chain block.
133	pub parent_hash: Hash,
134	/// The number of the relay-chain block.
135	pub number: BlockNumber,
136	/// The storage-root of the relay-chain block.
137	pub storage_root: Hash,
138}
139
140impl From<BlockInfoProspectiveTeyrchains> for RelayChainBlockInfo {
141	fn from(value: BlockInfoProspectiveTeyrchains) -> Self {
142		Self { hash: value.hash, number: value.number, storage_root: value.storage_root }
143	}
144}
145
146impl View {
147	/// Get an iterator over active leaves in the view.
148	pub fn leaves(&self) -> impl Iterator<Item = &Hash> {
149		self.leaves.keys()
150	}
151
152	/// Check if the given block hash is an active leaf of the current view.
153	pub fn contains_leaf(&self, leaf_hash: &Hash) -> bool {
154		self.leaves.contains_key(leaf_hash)
155	}
156
157	/// Get the block number of a leaf in the current view.
158	/// Returns `None` if leaf is not in the view.
159	pub fn block_number(&self, leaf_hash: &Hash) -> Option<BlockNumber> {
160		self.block_info_storage.get(leaf_hash).map(|block_info| block_info.block_number)
161	}
162
163	/// Activate a leaf in the view.
164	/// This will request the minimum relay parents the leaf and will load headers in the
165	/// ancestry of the leaf as needed. These are the 'implicit ancestors' of the leaf.
166	///
167	/// To maximize reuse of outdated leaves, it's best to activate new leaves before
168	/// deactivating old ones.
169	///
170	/// The allowed relay parents for the relevant paras under this leaf can be
171	/// queried with [`View::known_allowed_relay_parents_under`].
172	///
173	/// No-op for known leaves.
174	pub async fn activate_leaf<Sender>(
175		&mut self,
176		sender: &mut Sender,
177		leaf_hash: Hash,
178	) -> Result<(), FetchError>
179	where
180		Sender: SubsystemSender<ChainApiMessage>
181			+ SubsystemSender<ProspectiveTeyrchainsMessage>
182			+ SubsystemSender<RuntimeApiMessage>,
183	{
184		if self.leaves.contains_key(&leaf_hash) {
185			return Err(FetchError::AlreadyKnown);
186		}
187
188		let res = self.fetch_fresh_leaf_and_insert_ancestry(leaf_hash, &mut *sender).await;
189
190		match res {
191			Ok(fetched) => {
192				// Retain at least `MINIMUM_RETAIN_LENGTH` blocks in storage.
193				// This helps to avoid Chain API calls when activating leaves in the
194				// same chain.
195				let retain_minimum = std::cmp::min(
196					fetched.minimum_ancestor_number,
197					fetched.leaf_number.saturating_sub(MINIMUM_RETAIN_LENGTH),
198				);
199
200				self.leaves.insert(leaf_hash, ActiveLeafPruningInfo { retain_minimum });
201
202				Ok(())
203			},
204			Err(e) => Err(e),
205		}
206	}
207
208	/// Activate a leaf in the view. To be used by the prospective teyrchains subsystem.
209	///
210	/// This will not request any additional data, as prospective teyrchains already provides all
211	/// the required info.
212	/// NOTE: using `activate_leaf` instead of this function will result in a
213	/// deadlock, as it calls prospective-teyrchains under the hood.
214	///
215	/// No-op for known leaves.
216	pub fn activate_leaf_from_prospective_teyrchains(
217		&mut self,
218		leaf: BlockInfoProspectiveTeyrchains,
219		ancestors: &[BlockInfoProspectiveTeyrchains],
220	) {
221		if self.leaves.contains_key(&leaf.hash) {
222			return;
223		}
224
225		// Retain at least `MINIMUM_RETAIN_LENGTH` blocks in storage.
226		// This helps to avoid Chain API calls when activating leaves in the
227		// same chain.
228		let retain_minimum = std::cmp::min(
229			ancestors.last().map(|a| a.number).unwrap_or(0),
230			leaf.number.saturating_sub(MINIMUM_RETAIN_LENGTH),
231		);
232
233		self.leaves.insert(leaf.hash, ActiveLeafPruningInfo { retain_minimum });
234		let mut allowed_relay_parents = AllowedRelayParents {
235			allowed_relay_parents_contiguous: Vec::with_capacity(ancestors.len()),
236			// In this case, initialise this to an empty map, as prospective teyrchains already has
237			// this data and it won't query the implicit view for it.
238			minimum_relay_parents: HashMap::new(),
239		};
240
241		for ancestor in ancestors {
242			self.block_info_storage.insert(
243				ancestor.hash,
244				BlockInfo {
245					block_number: ancestor.number,
246					maybe_allowed_relay_parents: None,
247					parent_hash: ancestor.parent_hash,
248				},
249			);
250			allowed_relay_parents.allowed_relay_parents_contiguous.push(ancestor.hash);
251		}
252
253		self.block_info_storage.insert(
254			leaf.hash,
255			BlockInfo {
256				block_number: leaf.number,
257				maybe_allowed_relay_parents: Some(allowed_relay_parents),
258				parent_hash: leaf.parent_hash,
259			},
260		);
261	}
262
263	/// Deactivate a leaf in the view. This prunes any outdated implicit ancestors as well.
264	///
265	/// Returns hashes of blocks pruned from storage.
266	pub fn deactivate_leaf(&mut self, leaf_hash: Hash) -> Vec<Hash> {
267		let mut removed = Vec::new();
268
269		if self.leaves.remove(&leaf_hash).is_none() {
270			return removed;
271		}
272
273		// Prune everything before the minimum out of all leaves,
274		// pruning absolutely everything if there are no leaves (empty view)
275		//
276		// Pruning by block number does leave behind orphaned forks slightly longer
277		// but the memory overhead is negligible.
278		{
279			let minimum = self.leaves.values().map(|l| l.retain_minimum).min();
280
281			self.block_info_storage.retain(|hash, i| {
282				let keep = minimum.map_or(false, |m| i.block_number >= m);
283				if !keep {
284					removed.push(*hash);
285				}
286				keep
287			});
288
289			removed
290		}
291	}
292
293	/// Get an iterator over all allowed relay-parents in the view with no particular order.
294	///
295	/// **Important**: not all blocks are guaranteed to be allowed for some leaves, it may
296	/// happen that a block info is only kept in the view storage because of a retaining rule.
297	///
298	/// For getting relay-parents that are valid for teyrchain candidates use
299	/// [`View::known_allowed_relay_parents_under`].
300	pub fn all_allowed_relay_parents(&self) -> impl Iterator<Item = &Hash> {
301		self.block_info_storage.keys()
302	}
303
304	/// Get the known, allowed relay-parents that are valid for teyrchain candidates
305	/// which could be backed in a child of a given block for a given para ID.
306	///
307	/// This is expressed as a contiguous slice of relay-chain block hashes which may
308	/// include the provided block hash itself.
309	///
310	/// If `para_id` is `None`, this returns all valid relay-parents across all paras
311	/// for the leaf.
312	///
313	/// `None` indicates that the block hash isn't part of the implicit view or that
314	/// there are no known allowed relay parents.
315	///
316	/// This always returns `Some` for active leaves or for blocks that previously
317	/// were active leaves.
318	///
319	/// This can return the empty slice, which indicates that no relay-parents are allowed
320	/// for the para, e.g. if the para is not scheduled at the given block hash.
321	pub fn known_allowed_relay_parents_under(
322		&self,
323		block_hash: &Hash,
324		para_id: Option<ParaId>,
325	) -> Option<&[Hash]> {
326		let block_info = self.block_info_storage.get(block_hash)?;
327		block_info
328			.maybe_allowed_relay_parents
329			.as_ref()
330			.map(|mins| mins.allowed_relay_parents_for(para_id, block_info.block_number))
331	}
332
333	/// Returns all paths from each leaf to the last block in state containing `relay_parent`. If no
334	/// paths exist the function will return an empty `Vec`.
335	pub fn paths_via_relay_parent(&self, relay_parent: &Hash) -> Vec<Vec<Hash>> {
336		gum::trace!(
337			target: LOG_TARGET,
338			?relay_parent,
339			leaves=?self.leaves,
340			block_info_storage=?self.block_info_storage,
341			"Finding paths via relay parent"
342		);
343
344		if self.leaves.is_empty() {
345			// No leaves so the view should be empty. Don't return any paths.
346			return vec![];
347		};
348
349		if !self.block_info_storage.contains_key(relay_parent) {
350			// `relay_parent` is not in the view - don't return any paths
351			return vec![];
352		}
353
354		// Find all paths from each leaf to `relay_parent`.
355		let mut paths = Vec::new();
356		for (leaf, _) in &self.leaves {
357			let mut path = Vec::new();
358			let mut current_leaf = *leaf;
359			let mut visited = HashSet::new();
360			let mut path_contains_target = false;
361
362			// Start from the leaf and traverse all known blocks
363			loop {
364				if visited.contains(&current_leaf) {
365					// There is a cycle - abandon this path
366					break;
367				}
368
369				current_leaf = match self.block_info_storage.get(&current_leaf) {
370					Some(info) => {
371						// `current_leaf` is a known block - add it to the path and mark it as
372						// visited
373						path.push(current_leaf);
374						visited.insert(current_leaf);
375
376						// `current_leaf` is the target `relay_parent`. Mark the path so that it's
377						// included in the result
378						if current_leaf == *relay_parent {
379							path_contains_target = true;
380						}
381
382						// update `current_leaf` with the parent
383						info.parent_hash
384					},
385					None => {
386						// path is complete
387						if path_contains_target {
388							// we want the path ordered from oldest to newest so reverse it
389							paths.push(path.into_iter().rev().collect());
390						}
391						break;
392					},
393				};
394			}
395		}
396
397		paths
398	}
399
400	async fn fetch_fresh_leaf_and_insert_ancestry<Sender>(
401		&mut self,
402		leaf_hash: Hash,
403		sender: &mut Sender,
404	) -> Result<FetchSummary, FetchError>
405	where
406		Sender: SubsystemSender<ChainApiMessage>
407			+ SubsystemSender<ProspectiveTeyrchainsMessage>
408			+ SubsystemSender<RuntimeApiMessage>,
409	{
410		let leaf_header = {
411			let (tx, rx) = oneshot::channel();
412			sender.send_message(ChainApiMessage::BlockHeader(leaf_hash, tx)).await;
413
414			match rx.await {
415				Ok(Ok(Some(header))) => header,
416				Ok(Ok(None)) => {
417					return Err(FetchError::BlockHeaderUnavailable(
418						leaf_hash,
419						BlockHeaderUnavailableReason::Unknown,
420					))
421				},
422				Ok(Err(e)) => {
423					return Err(FetchError::BlockHeaderUnavailable(
424						leaf_hash,
425						BlockHeaderUnavailableReason::Internal(e),
426					))
427				},
428				Err(_) => {
429					return Err(FetchError::BlockHeaderUnavailable(
430						leaf_hash,
431						BlockHeaderUnavailableReason::SubsystemUnavailable,
432					))
433				},
434			}
435		};
436
437		// If the node is a collator, bypass prospective-teyrchains. We're only interested in the
438		// one paraid and the subsystem is not present.
439		let min_relay_parents = if let Some(para_id) = self.collating_for {
440			fetch_min_relay_parents_for_collator(leaf_hash, leaf_header.number, sender)
441				.await?
442				.map(|x| vec![(para_id, x)])
443				.unwrap_or_default()
444		} else {
445			fetch_min_relay_parents_from_prospective_teyrchains(leaf_hash, sender).await?
446		};
447
448		let min_min = min_relay_parents.iter().map(|x| x.1).min().unwrap_or(leaf_header.number);
449		let expected_ancestry_len = (leaf_header.number.saturating_sub(min_min) as usize) + 1;
450
451		let ancestry = if leaf_header.number > 0 {
452			let mut next_ancestor_number = leaf_header.number - 1;
453			let mut next_ancestor_hash = leaf_header.parent_hash;
454
455			let mut ancestry = Vec::with_capacity(expected_ancestry_len);
456			ancestry.push(leaf_hash);
457
458			// Ensure all ancestors up to and including `min_min` are in the
459			// block storage. When views advance incrementally, everything
460			// should already be present.
461			while next_ancestor_number >= min_min {
462				let parent_hash = if let Some(info) =
463					self.block_info_storage.get(&next_ancestor_hash)
464				{
465					info.parent_hash
466				} else {
467					// load the header and insert into block storage.
468					let (tx, rx) = oneshot::channel();
469					sender.send_message(ChainApiMessage::BlockHeader(next_ancestor_hash, tx)).await;
470
471					let header = match rx.await {
472						Ok(Ok(Some(header))) => header,
473						Ok(Ok(None)) => {
474							return Err(FetchError::BlockHeaderUnavailable(
475								next_ancestor_hash,
476								BlockHeaderUnavailableReason::Unknown,
477							))
478						},
479						Ok(Err(e)) => {
480							return Err(FetchError::BlockHeaderUnavailable(
481								next_ancestor_hash,
482								BlockHeaderUnavailableReason::Internal(e),
483							))
484						},
485						Err(_) => {
486							return Err(FetchError::BlockHeaderUnavailable(
487								next_ancestor_hash,
488								BlockHeaderUnavailableReason::SubsystemUnavailable,
489							))
490						},
491					};
492
493					self.block_info_storage.insert(
494						next_ancestor_hash,
495						BlockInfo {
496							block_number: next_ancestor_number,
497							parent_hash: header.parent_hash,
498							maybe_allowed_relay_parents: None,
499						},
500					);
501
502					header.parent_hash
503				};
504
505				ancestry.push(next_ancestor_hash);
506				if next_ancestor_number == 0 {
507					break;
508				}
509
510				next_ancestor_number -= 1;
511				next_ancestor_hash = parent_hash;
512			}
513
514			ancestry
515		} else {
516			vec![leaf_hash]
517		};
518
519		let fetched_ancestry =
520			FetchSummary { minimum_ancestor_number: min_min, leaf_number: leaf_header.number };
521
522		let allowed_relay_parents = AllowedRelayParents {
523			minimum_relay_parents: min_relay_parents.into_iter().collect(),
524			allowed_relay_parents_contiguous: ancestry,
525		};
526
527		let leaf_block_info = BlockInfo {
528			parent_hash: leaf_header.parent_hash,
529			block_number: leaf_header.number,
530			maybe_allowed_relay_parents: Some(allowed_relay_parents),
531		};
532
533		self.block_info_storage.insert(leaf_hash, leaf_block_info);
534
535		Ok(fetched_ancestry)
536	}
537}
538
539/// Errors when fetching a leaf and associated ancestry.
540#[fatality::fatality]
541pub enum FetchError {
542	/// Activated leaf is already present in view.
543	#[error("Leaf was already known")]
544	AlreadyKnown,
545
546	/// Request to the prospective teyrchains subsystem failed.
547	#[error("The prospective teyrchains subsystem was unavailable")]
548	ProspectiveTeyrchainsUnavailable,
549
550	/// Failed to fetch the block header.
551	#[error("A block header was unavailable")]
552	BlockHeaderUnavailable(Hash, BlockHeaderUnavailableReason),
553
554	/// A block header was unavailable due to a chain API error.
555	#[error("A block header was unavailable due to a chain API error")]
556	ChainApiError(Hash, ChainApiError),
557
558	/// Request to the Chain API subsystem failed.
559	#[error("The chain API subsystem was unavailable")]
560	ChainApiUnavailable,
561
562	/// Request to the runtime API failed.
563	#[error("Runtime API error: {0}")]
564	RuntimeApi(#[from] runtime::Error),
565}
566
567/// Reasons a block header might have been unavailable.
568#[derive(Debug)]
569pub enum BlockHeaderUnavailableReason {
570	/// Block header simply unknown.
571	Unknown,
572	/// Internal Chain API error.
573	Internal(ChainApiError),
574	/// The subsystem was unavailable.
575	SubsystemUnavailable,
576}
577
578struct FetchSummary {
579	minimum_ancestor_number: BlockNumber,
580	leaf_number: BlockNumber,
581}
582
583// Request the min relay parents from prospective-teyrchains.
584async fn fetch_min_relay_parents_from_prospective_teyrchains<
585	Sender: SubsystemSender<ProspectiveTeyrchainsMessage>,
586>(
587	leaf_hash: Hash,
588	sender: &mut Sender,
589) -> Result<Vec<(ParaId, BlockNumber)>, FetchError> {
590	let (tx, rx) = oneshot::channel();
591	sender
592		.send_message(ProspectiveTeyrchainsMessage::GetMinimumRelayParents(leaf_hash, tx))
593		.await;
594
595	rx.await.map_err(|_| FetchError::ProspectiveTeyrchainsUnavailable)
596}
597
598// Request the min relay parent for the purposes of a collator, directly using ChainApi (where
599// prospective-teyrchains is not available).
600async fn fetch_min_relay_parents_for_collator<Sender>(
601	leaf_hash: Hash,
602	leaf_number: BlockNumber,
603	sender: &mut Sender,
604) -> Result<Option<BlockNumber>, FetchError>
605where
606	Sender: SubsystemSender<ProspectiveTeyrchainsMessage>
607		+ SubsystemSender<RuntimeApiMessage>
608		+ SubsystemSender<ChainApiMessage>,
609{
610	// Fetch the session of the leaf. We must make sure that we stop at the ancestor which has a
611	// different session index.
612	let required_session =
613		recv_runtime(request_session_index_for_child(leaf_hash, sender).await).await?;
614
615	let scheduling_lookahead =
616		fetch_scheduling_lookahead(leaf_hash, required_session, sender).await?;
617
618	let mut min = leaf_number;
619
620	// Fetch the ancestors, up to (scheduling_lookahead - 1).
621	let (tx, rx) = oneshot::channel();
622	sender
623		.send_message(ChainApiMessage::Ancestors {
624			hash: leaf_hash,
625			k: scheduling_lookahead.saturating_sub(1) as usize,
626			response_channel: tx,
627		})
628		.await;
629	let hashes = rx
630		.await
631		.map_err(|_| FetchError::ChainApiUnavailable)?
632		.map_err(|err| FetchError::ChainApiError(leaf_hash, err))?;
633
634	for hash in hashes {
635		// The relay chain cannot accept blocks backed from previous sessions, with
636		// potentially previous validators. This is a technical limitation we need to
637		// respect here.
638		let session = recv_runtime(request_session_index_for_child(hash, sender).await).await?;
639
640		if session == required_session {
641			// We should never underflow here, the ChainAPI stops at genesis block.
642			min = min.saturating_sub(1);
643		} else {
644			break;
645		}
646	}
647
648	Ok(Some(min))
649}
650
651#[cfg(test)]
652mod tests {
653	use super::*;
654	use crate::TimeoutExt;
655	use assert_matches::assert_matches;
656	use futures::future::{join, FutureExt};
657	use pezkuwi_node_subsystem::{messages::RuntimeApiRequest, AllMessages};
658	use pezkuwi_node_subsystem_test_helpers::{make_subsystem_context, TestSubsystemContextHandle};
659	use pezkuwi_overseer::SubsystemContext;
660	use pezkuwi_primitives::Header;
661	use pezsp_core::testing::TaskExecutor;
662	use std::time::Duration;
663
664	const PARA_A: ParaId = ParaId::new(0);
665	const PARA_B: ParaId = ParaId::new(1);
666	const PARA_C: ParaId = ParaId::new(2);
667
668	const GENESIS_HASH: Hash = Hash::repeat_byte(0xFF);
669	const GENESIS_NUMBER: BlockNumber = 0;
670
671	// Chains A and B are forks of genesis.
672
673	const CHAIN_A: &[Hash] =
674		&[Hash::repeat_byte(0x01), Hash::repeat_byte(0x02), Hash::repeat_byte(0x03)];
675
676	const CHAIN_B: &[Hash] = &[
677		Hash::repeat_byte(0x04),
678		Hash::repeat_byte(0x05),
679		Hash::repeat_byte(0x06),
680		Hash::repeat_byte(0x07),
681		Hash::repeat_byte(0x08),
682		Hash::repeat_byte(0x09),
683	];
684
685	type VirtualOverseer = TestSubsystemContextHandle<AllMessages>;
686
687	const TIMEOUT: Duration = Duration::from_secs(2);
688
689	async fn overseer_recv(virtual_overseer: &mut VirtualOverseer) -> AllMessages {
690		virtual_overseer
691			.recv()
692			.timeout(TIMEOUT)
693			.await
694			.expect("overseer `recv` timed out")
695	}
696
697	fn default_header() -> Header {
698		Header {
699			parent_hash: Hash::zero(),
700			number: 0,
701			state_root: Hash::zero(),
702			extrinsics_root: Hash::zero(),
703			digest: Default::default(),
704		}
705	}
706
707	fn get_block_header(chain: &[Hash], hash: &Hash) -> Option<Header> {
708		let idx = chain.iter().position(|h| h == hash)?;
709		let parent_hash = idx.checked_sub(1).map(|i| chain[i]).unwrap_or(GENESIS_HASH);
710		let number =
711			if *hash == GENESIS_HASH { GENESIS_NUMBER } else { GENESIS_NUMBER + idx as u32 + 1 };
712		Some(Header { parent_hash, number, ..default_header() })
713	}
714
715	async fn assert_block_header_requests(
716		virtual_overseer: &mut VirtualOverseer,
717		chain: &[Hash],
718		blocks: &[Hash],
719	) {
720		for block in blocks.iter().rev() {
721			assert_matches!(
722				overseer_recv(virtual_overseer).await,
723				AllMessages::ChainApi(
724					ChainApiMessage::BlockHeader(hash, tx)
725				) => {
726					assert_eq!(*block, hash, "unexpected block header request");
727					let header = if block == &GENESIS_HASH {
728						Header {
729							number: GENESIS_NUMBER,
730							..default_header()
731						}
732					} else {
733						get_block_header(chain, block).expect("unknown block")
734					};
735
736					tx.send(Ok(Some(header))).unwrap();
737				}
738			);
739		}
740	}
741
742	async fn assert_min_relay_parents_request(
743		virtual_overseer: &mut VirtualOverseer,
744		leaf: &Hash,
745		response: Vec<(ParaId, u32)>,
746	) {
747		assert_matches!(
748			overseer_recv(virtual_overseer).await,
749			AllMessages::ProspectiveTeyrchains(
750				ProspectiveTeyrchainsMessage::GetMinimumRelayParents(
751					leaf_hash,
752					tx
753				)
754			) => {
755				assert_eq!(*leaf, leaf_hash, "received unexpected leaf hash");
756				tx.send(response).unwrap();
757			}
758		);
759	}
760
761	async fn assert_scheduling_lookahead_request(
762		virtual_overseer: &mut VirtualOverseer,
763		leaf: Hash,
764		lookahead: u32,
765	) {
766		assert_matches!(
767			overseer_recv(virtual_overseer).await,
768			AllMessages::RuntimeApi(
769				RuntimeApiMessage::Request(
770					leaf_hash,
771					RuntimeApiRequest::SchedulingLookahead(
772						_,
773						tx
774					)
775				)
776			) => {
777				assert_eq!(leaf, leaf_hash, "received unexpected leaf hash");
778				tx.send(Ok(lookahead)).unwrap();
779			}
780		);
781	}
782
783	async fn assert_session_index_request(
784		virtual_overseer: &mut VirtualOverseer,
785		leaf: Hash,
786		session: u32,
787	) {
788		assert_matches!(
789			overseer_recv(virtual_overseer).await,
790			AllMessages::RuntimeApi(
791				RuntimeApiMessage::Request(
792					leaf_hash,
793					RuntimeApiRequest::SessionIndexForChild(
794						tx
795					)
796				)
797			) => {
798				assert_eq!(leaf, leaf_hash, "received unexpected leaf hash");
799				tx.send(Ok(session)).unwrap();
800			}
801		);
802	}
803
804	async fn assert_ancestors_request(
805		virtual_overseer: &mut VirtualOverseer,
806		leaf: Hash,
807		expected_ancestor_len: u32,
808		response: Vec<Hash>,
809	) {
810		assert_matches!(
811			overseer_recv(virtual_overseer).await,
812			AllMessages::ChainApi(
813				ChainApiMessage::Ancestors {
814					hash: leaf_hash,
815					k,
816					response_channel: tx
817				}
818			) => {
819				assert_eq!(leaf, leaf_hash, "received unexpected leaf hash");
820				assert_eq!(k, expected_ancestor_len as usize);
821
822				tx.send(Ok(response)).unwrap();
823			}
824		);
825	}
826
827	#[test]
828	fn construct_fresh_view() {
829		let pool = TaskExecutor::new();
830		let (mut ctx, mut ctx_handle) = make_subsystem_context::<AllMessages, _>(pool);
831
832		let mut view = View::default();
833
834		assert_eq!(view.collating_for, None);
835
836		// Chain B.
837		const PARA_A_MIN_PARENT: u32 = 4;
838		const PARA_B_MIN_PARENT: u32 = 3;
839
840		let prospective_response = vec![(PARA_A, PARA_A_MIN_PARENT), (PARA_B, PARA_B_MIN_PARENT)];
841
842		let leaf = CHAIN_B.last().unwrap();
843		let leaf_idx = CHAIN_B.len() - 1;
844		let min_min_idx = (PARA_B_MIN_PARENT - GENESIS_NUMBER - 1) as usize;
845
846		let fut = view.activate_leaf(ctx.sender(), *leaf).timeout(TIMEOUT).map(|res| {
847			res.expect("`activate_leaf` timed out").unwrap();
848		});
849		let overseer_fut = async {
850			assert_block_header_requests(&mut ctx_handle, CHAIN_B, &CHAIN_B[leaf_idx..]).await;
851			assert_min_relay_parents_request(&mut ctx_handle, leaf, prospective_response).await;
852			assert_block_header_requests(&mut ctx_handle, CHAIN_B, &CHAIN_B[min_min_idx..leaf_idx])
853				.await;
854		};
855		futures::executor::block_on(join(fut, overseer_fut));
856
857		for i in min_min_idx..(CHAIN_B.len() - 1) {
858			// No allowed relay parents constructed for ancestry.
859			assert!(view.known_allowed_relay_parents_under(&CHAIN_B[i], None).is_none());
860		}
861
862		let leaf_info =
863			view.block_info_storage.get(leaf).expect("block must be present in storage");
864		assert_matches!(
865			leaf_info.maybe_allowed_relay_parents,
866			Some(ref allowed_relay_parents) => {
867				assert_eq!(allowed_relay_parents.minimum_relay_parents[&PARA_A], PARA_A_MIN_PARENT);
868				assert_eq!(allowed_relay_parents.minimum_relay_parents[&PARA_B], PARA_B_MIN_PARENT);
869				let expected_ancestry: Vec<Hash> =
870					CHAIN_B[min_min_idx..].iter().rev().copied().collect();
871				assert_eq!(
872					allowed_relay_parents.allowed_relay_parents_contiguous,
873					expected_ancestry
874				);
875
876				assert_eq!(view.known_allowed_relay_parents_under(&leaf, None), Some(&expected_ancestry[..]));
877				assert_eq!(view.known_allowed_relay_parents_under(&leaf, Some(PARA_A)), Some(&expected_ancestry[..(PARA_A_MIN_PARENT - 1) as usize]));
878				assert_eq!(view.known_allowed_relay_parents_under(&leaf, Some(PARA_B)), Some(&expected_ancestry[..]));
879				assert!(view.known_allowed_relay_parents_under(&leaf, Some(PARA_C)).unwrap().is_empty());
880
881				assert_eq!(view.leaves.len(), 1);
882				assert!(view.leaves.contains_key(leaf));
883				assert!(view.paths_via_relay_parent(&CHAIN_B[0]).is_empty());
884				assert!(view.paths_via_relay_parent(&CHAIN_A[0]).is_empty());
885				assert_eq!(
886					view.paths_via_relay_parent(&CHAIN_B[min_min_idx]),
887					vec![CHAIN_B[min_min_idx..].to_vec()]
888				);
889				assert_eq!(
890					view.paths_via_relay_parent(&CHAIN_B[min_min_idx + 1]),
891					vec![CHAIN_B[min_min_idx..].to_vec()]
892				);
893				assert_eq!(
894					view.paths_via_relay_parent(&leaf),
895					vec![CHAIN_B[min_min_idx..].to_vec()]
896				);
897			}
898		);
899
900		// Suppose the whole test chain A is allowed up to genesis for para C.
901		const PARA_C_MIN_PARENT: u32 = 0;
902		let prospective_response = vec![(PARA_C, PARA_C_MIN_PARENT)];
903		let leaf = CHAIN_A.last().unwrap();
904		let blocks = [&[GENESIS_HASH], CHAIN_A].concat();
905		let leaf_idx = blocks.len() - 1;
906
907		let fut = view.activate_leaf(ctx.sender(), *leaf).timeout(TIMEOUT).map(|res| {
908			res.expect("`activate_leaf` timed out").unwrap();
909		});
910		let overseer_fut = async {
911			assert_block_header_requests(&mut ctx_handle, CHAIN_A, &blocks[leaf_idx..]).await;
912			assert_min_relay_parents_request(&mut ctx_handle, leaf, prospective_response).await;
913			assert_block_header_requests(&mut ctx_handle, CHAIN_A, &blocks[..leaf_idx]).await;
914		};
915		futures::executor::block_on(join(fut, overseer_fut));
916
917		assert_eq!(view.leaves.len(), 2);
918
919		let leaf_info =
920			view.block_info_storage.get(leaf).expect("block must be present in storage");
921		assert_matches!(
922			leaf_info.maybe_allowed_relay_parents,
923			Some(ref allowed_relay_parents) => {
924				assert_eq!(allowed_relay_parents.minimum_relay_parents[&PARA_C], GENESIS_NUMBER);
925				let expected_ancestry: Vec<Hash> =
926					blocks[..].iter().rev().copied().collect();
927				assert_eq!(
928					allowed_relay_parents.allowed_relay_parents_contiguous,
929					expected_ancestry
930				);
931
932				assert_eq!(view.known_allowed_relay_parents_under(&leaf, None), Some(&expected_ancestry[..]));
933				assert_eq!(view.known_allowed_relay_parents_under(&leaf, Some(PARA_C)), Some(&expected_ancestry[..]));
934
935				assert!(view.known_allowed_relay_parents_under(&leaf, Some(PARA_A)).unwrap().is_empty());
936				assert!(view.known_allowed_relay_parents_under(&leaf, Some(PARA_B)).unwrap().is_empty());
937			}
938		);
939	}
940
941	#[test]
942	fn construct_fresh_view_single_para() {
943		let pool = TaskExecutor::new();
944		let (mut ctx, mut ctx_handle) = make_subsystem_context::<AllMessages, _>(pool);
945
946		let mut view = View::new(Some(PARA_A));
947
948		assert_eq!(view.collating_for, Some(PARA_A));
949
950		// Chain B.
951		const PARA_A_MIN_PARENT: u32 = 4;
952
953		let current_session = 2;
954
955		let leaf = CHAIN_B.last().unwrap();
956		let leaf_idx = CHAIN_B.len() - 1;
957		let min_min_idx = (PARA_A_MIN_PARENT - GENESIS_NUMBER - 1) as usize;
958
959		let fut = view.activate_leaf(ctx.sender(), *leaf).timeout(TIMEOUT).map(|res| {
960			res.expect("`activate_leaf` timed out").unwrap();
961		});
962		let overseer_fut = async {
963			assert_block_header_requests(&mut ctx_handle, CHAIN_B, &CHAIN_B[leaf_idx..]).await;
964
965			assert_session_index_request(&mut ctx_handle, *leaf, current_session).await;
966
967			assert_scheduling_lookahead_request(&mut ctx_handle, *leaf, PARA_A_MIN_PARENT + 1)
968				.await;
969
970			assert_ancestors_request(
971				&mut ctx_handle,
972				*leaf,
973				PARA_A_MIN_PARENT,
974				CHAIN_B[min_min_idx..leaf_idx].iter().copied().rev().collect(),
975			)
976			.await;
977
978			for hash in CHAIN_B[min_min_idx..leaf_idx].into_iter().rev() {
979				assert_session_index_request(&mut ctx_handle, *hash, current_session).await;
980			}
981
982			assert_block_header_requests(&mut ctx_handle, CHAIN_B, &CHAIN_B[min_min_idx..leaf_idx])
983				.await;
984		};
985		futures::executor::block_on(join(fut, overseer_fut));
986
987		for i in min_min_idx..(CHAIN_B.len() - 1) {
988			// No allowed relay parents constructed for ancestry.
989			assert!(view.known_allowed_relay_parents_under(&CHAIN_B[i], None).is_none());
990		}
991
992		let leaf_info =
993			view.block_info_storage.get(leaf).expect("block must be present in storage");
994		assert_matches!(
995			leaf_info.maybe_allowed_relay_parents,
996			Some(ref allowed_relay_parents) => {
997				assert_eq!(allowed_relay_parents.minimum_relay_parents[&PARA_A], PARA_A_MIN_PARENT);
998				let expected_ancestry: Vec<Hash> =
999					CHAIN_B[min_min_idx..].iter().rev().copied().collect();
1000				assert_eq!(
1001					allowed_relay_parents.allowed_relay_parents_contiguous,
1002					expected_ancestry
1003				);
1004
1005				assert_eq!(view.known_allowed_relay_parents_under(&leaf, None), Some(&expected_ancestry[..]));
1006				assert_eq!(view.known_allowed_relay_parents_under(&leaf, Some(PARA_A)), Some(&expected_ancestry[..]));
1007
1008				assert!(view.known_allowed_relay_parents_under(&leaf, Some(PARA_B)).unwrap().is_empty());
1009				assert!(view.known_allowed_relay_parents_under(&leaf, Some(PARA_C)).unwrap().is_empty());
1010
1011				assert!(view.paths_via_relay_parent(&CHAIN_A[0]).is_empty());
1012				assert_eq!(
1013					view.paths_via_relay_parent(&CHAIN_B[min_min_idx]),
1014					vec![CHAIN_B[min_min_idx..].to_vec()]
1015				);
1016			}
1017		);
1018
1019		// Suppose the whole test chain A is allowed up to genesis for para A, but the genesis block
1020		// is in a different session.
1021		let leaf = CHAIN_A.last().unwrap();
1022		let blocks = [&[GENESIS_HASH], CHAIN_A].concat();
1023		let leaf_idx = blocks.len() - 1;
1024
1025		let fut = view.activate_leaf(ctx.sender(), *leaf).timeout(TIMEOUT).map(|res| {
1026			res.expect("`activate_leaf` timed out").unwrap();
1027		});
1028
1029		let overseer_fut = async {
1030			assert_block_header_requests(&mut ctx_handle, CHAIN_A, &blocks[leaf_idx..]).await;
1031
1032			assert_session_index_request(&mut ctx_handle, *leaf, current_session).await;
1033
1034			assert_scheduling_lookahead_request(&mut ctx_handle, *leaf, blocks.len() as u32 + 1)
1035				.await;
1036
1037			assert_ancestors_request(
1038				&mut ctx_handle,
1039				*leaf,
1040				blocks.len() as u32,
1041				blocks[..leaf_idx].iter().rev().copied().collect(),
1042			)
1043			.await;
1044
1045			for hash in blocks[1..leaf_idx].into_iter().rev() {
1046				assert_session_index_request(&mut ctx_handle, *hash, current_session).await;
1047			}
1048
1049			assert_session_index_request(&mut ctx_handle, GENESIS_HASH, 0).await;
1050
1051			// We won't request for the genesis block
1052			assert_block_header_requests(&mut ctx_handle, CHAIN_A, &blocks[1..leaf_idx]).await;
1053		};
1054
1055		futures::executor::block_on(join(fut, overseer_fut));
1056
1057		assert_eq!(view.leaves.len(), 2);
1058
1059		let leaf_info =
1060			view.block_info_storage.get(leaf).expect("block must be present in storage");
1061		assert_matches!(
1062			leaf_info.maybe_allowed_relay_parents,
1063			Some(ref allowed_relay_parents) => {
1064				assert_eq!(allowed_relay_parents.minimum_relay_parents[&PARA_A], 1);
1065				let expected_ancestry: Vec<Hash> =
1066					CHAIN_A[..].iter().rev().copied().collect();
1067				assert_eq!(
1068					allowed_relay_parents.allowed_relay_parents_contiguous,
1069					expected_ancestry
1070				);
1071
1072				assert_eq!(view.known_allowed_relay_parents_under(&leaf, None), Some(&expected_ancestry[..]));
1073				assert_eq!(view.known_allowed_relay_parents_under(&leaf, Some(PARA_A)), Some(&expected_ancestry[..]));
1074
1075				assert!(view.known_allowed_relay_parents_under(&leaf, Some(PARA_B)).unwrap().is_empty());
1076				assert!(view.known_allowed_relay_parents_under(&leaf, Some(PARA_C)).unwrap().is_empty());
1077
1078				assert!(view.paths_via_relay_parent(&GENESIS_HASH).is_empty());
1079				assert_eq!(
1080					view.paths_via_relay_parent(&CHAIN_A[0]),
1081					vec![CHAIN_A.to_vec()]
1082				);
1083			}
1084		);
1085	}
1086
1087	#[test]
1088	fn reuse_block_info_storage() {
1089		let pool = TaskExecutor::new();
1090		let (mut ctx, mut ctx_handle) = make_subsystem_context::<AllMessages, _>(pool);
1091
1092		let mut view = View::default();
1093
1094		const PARA_A_MIN_PARENT: u32 = 1;
1095		let leaf_a_number = 3;
1096		let leaf_a = CHAIN_B[leaf_a_number - 1];
1097		let min_min_idx = (PARA_A_MIN_PARENT - GENESIS_NUMBER - 1) as usize;
1098
1099		let prospective_response = vec![(PARA_A, PARA_A_MIN_PARENT)];
1100
1101		let fut = view.activate_leaf(ctx.sender(), leaf_a).timeout(TIMEOUT).map(|res| {
1102			res.expect("`activate_leaf` timed out").unwrap();
1103		});
1104		let overseer_fut = async {
1105			assert_block_header_requests(
1106				&mut ctx_handle,
1107				CHAIN_B,
1108				&CHAIN_B[(leaf_a_number - 1)..leaf_a_number],
1109			)
1110			.await;
1111			assert_min_relay_parents_request(&mut ctx_handle, &leaf_a, prospective_response).await;
1112			assert_block_header_requests(
1113				&mut ctx_handle,
1114				CHAIN_B,
1115				&CHAIN_B[min_min_idx..(leaf_a_number - 1)],
1116			)
1117			.await;
1118		};
1119		futures::executor::block_on(join(fut, overseer_fut));
1120
1121		// Blocks up to the 3rd are present in storage.
1122		const PARA_B_MIN_PARENT: u32 = 2;
1123		let leaf_b_number = 5;
1124		let leaf_b = CHAIN_B[leaf_b_number - 1];
1125
1126		let prospective_response = vec![(PARA_B, PARA_B_MIN_PARENT)];
1127
1128		let fut = view.activate_leaf(ctx.sender(), leaf_b).timeout(TIMEOUT).map(|res| {
1129			res.expect("`activate_leaf` timed out").unwrap();
1130		});
1131		let overseer_fut = async {
1132			assert_block_header_requests(
1133				&mut ctx_handle,
1134				CHAIN_B,
1135				&CHAIN_B[(leaf_b_number - 1)..leaf_b_number],
1136			)
1137			.await;
1138			assert_min_relay_parents_request(&mut ctx_handle, &leaf_b, prospective_response).await;
1139			assert_block_header_requests(
1140				&mut ctx_handle,
1141				CHAIN_B,
1142				&CHAIN_B[leaf_a_number..(leaf_b_number - 1)], // Note the expected range.
1143			)
1144			.await;
1145		};
1146		futures::executor::block_on(join(fut, overseer_fut));
1147
1148		// Allowed relay parents for leaf A are preserved.
1149		let leaf_a_info =
1150			view.block_info_storage.get(&leaf_a).expect("block must be present in storage");
1151		assert_matches!(
1152			leaf_a_info.maybe_allowed_relay_parents,
1153			Some(ref allowed_relay_parents) => {
1154				assert_eq!(allowed_relay_parents.minimum_relay_parents[&PARA_A], PARA_A_MIN_PARENT);
1155				let expected_ancestry: Vec<Hash> =
1156					CHAIN_B[min_min_idx..leaf_a_number].iter().rev().copied().collect();
1157				let ancestry = view.known_allowed_relay_parents_under(&leaf_a, Some(PARA_A)).unwrap().to_vec();
1158				assert_eq!(ancestry, expected_ancestry);
1159			}
1160		);
1161	}
1162
1163	#[test]
1164	fn pruning() {
1165		let pool = TaskExecutor::new();
1166		let (mut ctx, mut ctx_handle) = make_subsystem_context::<AllMessages, _>(pool);
1167
1168		let mut view = View::default();
1169
1170		const PARA_A_MIN_PARENT: u32 = 3;
1171		let leaf_a = CHAIN_B.iter().rev().nth(1).unwrap();
1172		let leaf_a_idx = CHAIN_B.len() - 2;
1173		let min_a_idx = (PARA_A_MIN_PARENT - GENESIS_NUMBER - 1) as usize;
1174
1175		let prospective_response = vec![(PARA_A, PARA_A_MIN_PARENT)];
1176
1177		let fut = view
1178			.activate_leaf(ctx.sender(), *leaf_a)
1179			.timeout(TIMEOUT)
1180			.map(|res| res.unwrap().unwrap());
1181		let overseer_fut = async {
1182			assert_block_header_requests(
1183				&mut ctx_handle,
1184				CHAIN_B,
1185				&CHAIN_B[leaf_a_idx..(leaf_a_idx + 1)],
1186			)
1187			.await;
1188			assert_min_relay_parents_request(&mut ctx_handle, &leaf_a, prospective_response).await;
1189			assert_block_header_requests(&mut ctx_handle, CHAIN_B, &CHAIN_B[min_a_idx..leaf_a_idx])
1190				.await;
1191		};
1192		futures::executor::block_on(join(fut, overseer_fut));
1193
1194		// Also activate a leaf with a lesser minimum relay parent.
1195		const PARA_B_MIN_PARENT: u32 = 2;
1196		let leaf_b = CHAIN_B.last().unwrap();
1197		let min_b_idx = (PARA_B_MIN_PARENT - GENESIS_NUMBER - 1) as usize;
1198
1199		let prospective_response = vec![(PARA_B, PARA_B_MIN_PARENT)];
1200		// Headers will be requested for the minimum block and the leaf.
1201		let blocks = &[CHAIN_B[min_b_idx], *leaf_b];
1202
1203		let fut = view
1204			.activate_leaf(ctx.sender(), *leaf_b)
1205			.timeout(TIMEOUT)
1206			.map(|res| res.expect("`activate_leaf` timed out").unwrap());
1207		let overseer_fut = async {
1208			assert_block_header_requests(&mut ctx_handle, CHAIN_B, &blocks[(blocks.len() - 1)..])
1209				.await;
1210			assert_min_relay_parents_request(&mut ctx_handle, &leaf_b, prospective_response).await;
1211			assert_block_header_requests(&mut ctx_handle, CHAIN_B, &blocks[..(blocks.len() - 1)])
1212				.await;
1213		};
1214		futures::executor::block_on(join(fut, overseer_fut));
1215
1216		// Prune implicit ancestor (no-op).
1217		let block_info_len = view.block_info_storage.len();
1218		view.deactivate_leaf(CHAIN_B[leaf_a_idx - 1]);
1219		assert_eq!(block_info_len, view.block_info_storage.len());
1220
1221		// Prune a leaf with a greater minimum relay parent.
1222		view.deactivate_leaf(*leaf_b);
1223		for hash in CHAIN_B.iter().take(PARA_B_MIN_PARENT as usize) {
1224			assert!(!view.block_info_storage.contains_key(hash));
1225		}
1226
1227		// Prune the last leaf.
1228		view.deactivate_leaf(*leaf_a);
1229		assert!(view.block_info_storage.is_empty());
1230	}
1231
1232	#[test]
1233	fn genesis_ancestry() {
1234		let pool = TaskExecutor::new();
1235		let (mut ctx, mut ctx_handle) = make_subsystem_context::<AllMessages, _>(pool);
1236
1237		let mut view = View::default();
1238
1239		const PARA_A_MIN_PARENT: u32 = 0;
1240
1241		let prospective_response = vec![(PARA_A, PARA_A_MIN_PARENT)];
1242		let fut = view.activate_leaf(ctx.sender(), GENESIS_HASH).timeout(TIMEOUT).map(|res| {
1243			res.expect("`activate_leaf` timed out").unwrap();
1244		});
1245		let overseer_fut = async {
1246			assert_block_header_requests(&mut ctx_handle, &[GENESIS_HASH], &[GENESIS_HASH]).await;
1247			assert_min_relay_parents_request(&mut ctx_handle, &GENESIS_HASH, prospective_response)
1248				.await;
1249		};
1250		futures::executor::block_on(join(fut, overseer_fut));
1251
1252		assert_matches!(
1253			view.known_allowed_relay_parents_under(&GENESIS_HASH, None),
1254			Some(hashes) if hashes == &[GENESIS_HASH]
1255		);
1256	}
1257
1258	#[test]
1259	fn path_with_fork() {
1260		let pool = TaskExecutor::new();
1261		let (mut ctx, mut ctx_handle) = make_subsystem_context::<AllMessages, _>(pool);
1262
1263		let mut view = View::default();
1264
1265		assert_eq!(view.collating_for, None);
1266
1267		// Chain A
1268		let prospective_response = vec![(PARA_A, 0)]; // was PARA_A_MIN_PARENT
1269		let leaf = CHAIN_A.last().unwrap();
1270		let blocks = [&[GENESIS_HASH], CHAIN_A].concat();
1271		let leaf_idx = blocks.len() - 1;
1272
1273		let fut = view.activate_leaf(ctx.sender(), *leaf).timeout(TIMEOUT).map(|res| {
1274			res.expect("`activate_leaf` timed out").unwrap();
1275		});
1276		let overseer_fut = async {
1277			assert_block_header_requests(&mut ctx_handle, CHAIN_A, &blocks[leaf_idx..]).await;
1278			assert_min_relay_parents_request(&mut ctx_handle, leaf, prospective_response).await;
1279			assert_block_header_requests(&mut ctx_handle, CHAIN_A, &blocks[..leaf_idx]).await;
1280		};
1281		futures::executor::block_on(join(fut, overseer_fut));
1282
1283		// Chain B
1284		let prospective_response = vec![(PARA_A, 1)];
1285
1286		let leaf = CHAIN_B.last().unwrap();
1287		let leaf_idx = CHAIN_B.len() - 1;
1288
1289		let fut = view.activate_leaf(ctx.sender(), *leaf).timeout(TIMEOUT).map(|res| {
1290			res.expect("`activate_leaf` timed out").unwrap();
1291		});
1292		let overseer_fut = async {
1293			assert_block_header_requests(&mut ctx_handle, CHAIN_B, &CHAIN_B[leaf_idx..]).await;
1294			assert_min_relay_parents_request(&mut ctx_handle, leaf, prospective_response).await;
1295			assert_block_header_requests(&mut ctx_handle, CHAIN_B, &CHAIN_B[0..leaf_idx]).await;
1296		};
1297		futures::executor::block_on(join(fut, overseer_fut));
1298
1299		assert_eq!(view.leaves.len(), 2);
1300
1301		let mut paths_to_genesis = view.paths_via_relay_parent(&GENESIS_HASH);
1302		paths_to_genesis.sort();
1303		let mut expected_paths_to_genesis = vec![
1304			[GENESIS_HASH].iter().chain(CHAIN_A.iter()).copied().collect::<Vec<_>>(),
1305			[GENESIS_HASH].iter().chain(CHAIN_B.iter()).copied().collect::<Vec<_>>(),
1306		];
1307		expected_paths_to_genesis.sort();
1308		assert_eq!(paths_to_genesis, expected_paths_to_genesis);
1309
1310		let path_to_leaf_in_a = view.paths_via_relay_parent(&CHAIN_A[1]);
1311		let expected_path_to_leaf_in_a =
1312			vec![[GENESIS_HASH].iter().chain(CHAIN_A.iter()).copied().collect::<Vec<_>>()];
1313		assert_eq!(path_to_leaf_in_a, expected_path_to_leaf_in_a);
1314
1315		let path_to_leaf_in_b = view.paths_via_relay_parent(&CHAIN_B[4]);
1316		let expected_path_to_leaf_in_b =
1317			vec![[GENESIS_HASH].iter().chain(CHAIN_B.iter()).copied().collect::<Vec<_>>()];
1318		assert_eq!(path_to_leaf_in_b, expected_path_to_leaf_in_b);
1319
1320		assert_eq!(view.paths_via_relay_parent(&Hash::repeat_byte(0x0A)), Vec::<Vec<Hash>>::new());
1321	}
1322}