referrerpolicy=no-referrer-when-downgrade

cumulus_client_consensus_aura/collators/
mod.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Cumulus.
3// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
4
5// Cumulus is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9
10// Cumulus is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14
15// You should have received a copy of the GNU General Public License
16// along with Cumulus. If not, see <https://www.gnu.org/licenses/>.
17
18//! Stock, pure Aura collators.
19//!
20//! This includes the [`lookahead`] collator, which prospectively builds on parachain blocks which
21//! have not yet been included in the relay chain, and also the [`slot_based`] collator.
22
23use crate::collator::SlotClaim;
24use codec::Codec;
25use cumulus_client_consensus_common::{self as consensus_common, ParentSearchParams};
26use cumulus_primitives_aura::{AuraUnincludedSegmentApi, Slot};
27use cumulus_primitives_core::{
28	relay_chain::Header as RelayHeader, BlockT, KeyToIncludeInRelayProof, RelayProofRequest,
29};
30use cumulus_relay_chain_interface::{OverseerHandle, RelayChainInterface};
31use polkadot_node_subsystem::messages::CollatorProtocolMessage;
32use polkadot_node_subsystem_util::runtime::ClaimQueueSnapshot;
33use polkadot_primitives::{
34	Hash as RelayHash, Id as ParaId, OccupiedCoreAssumption, ValidationCodeHash,
35};
36use sc_consensus_aura::{standalone as aura_internal, AuraApi};
37use sp_api::{ApiExt, ProvideRuntimeApi};
38use sp_core::Pair;
39use sp_keystore::KeystorePtr;
40use sp_timestamp::Timestamp;
41
42pub mod lookahead;
43pub mod slot_based;
44
45// Helper to pre-connect to the backing group we got assigned to and keep the connection
46// open until backing group changes or own slot ends.
47struct BackingGroupConnectionHelper {
48	keystore: sp_keystore::KeystorePtr,
49	overseer_handle: OverseerHandle,
50	our_slot: Option<Slot>,
51}
52
53impl BackingGroupConnectionHelper {
54	pub fn new(keystore: sp_keystore::KeystorePtr, overseer_handle: OverseerHandle) -> Self {
55		Self { keystore, overseer_handle, our_slot: None }
56	}
57
58	async fn send_subsystem_message(&mut self, message: CollatorProtocolMessage) {
59		self.overseer_handle.send_msg(message, "BackingGroupConnectionHelper").await;
60	}
61
62	/// Update the current slot and initiate connections to backing groups if needed.
63	pub async fn update<P>(&mut self, current_slot: Slot, authorities: &[P::Public])
64	where
65		P: sp_core::Pair + Send + Sync,
66		P::Public: Codec,
67	{
68		if Some(current_slot) <= self.our_slot {
69			// Current slot or next slot is ours.
70			// We already sent pre-connect message, no need to proceed further.
71			return;
72		}
73
74		let next_slot = current_slot + 1;
75		let next_slot_is_ours =
76			aura_internal::claim_slot::<P>(next_slot, authorities, &self.keystore)
77				.await
78				.is_some();
79
80		if next_slot_is_ours {
81			// Only send message if we were not connected. This avoids sending duplicate messages
82			// when running with a single collator.
83			if self.our_slot.is_none() {
84				// Next slot is ours, send connect message.
85				tracing::debug!(target: crate::LOG_TARGET, "Our slot {} is next, connecting to backing groups", next_slot);
86				self.send_subsystem_message(CollatorProtocolMessage::ConnectToBackingGroups)
87					.await;
88			}
89			self.our_slot = Some(next_slot);
90		} else if self.our_slot.take().is_some() {
91			// Next slot is not ours, send disconnect only if we had a slot before.
92			tracing::debug!(target: crate::LOG_TARGET, "Current slot = {}, disconnecting from backing groups", current_slot);
93			self.send_subsystem_message(CollatorProtocolMessage::DisconnectFromBackingGroups)
94				.await;
95		}
96	}
97}
98
99/// Check the `local_validation_code_hash` against the validation code hash in the relay chain
100/// state.
101///
102/// If the code hashes do not match, it prints a warning.
103async fn check_validation_code_or_log(
104	local_validation_code_hash: &ValidationCodeHash,
105	para_id: ParaId,
106	relay_client: &impl RelayChainInterface,
107	relay_parent: RelayHash,
108) {
109	let state_validation_code_hash = match relay_client
110		.validation_code_hash(relay_parent, para_id, OccupiedCoreAssumption::Included)
111		.await
112	{
113		Ok(hash) => hash,
114		Err(error) => {
115			tracing::debug!(
116				target: super::LOG_TARGET,
117				%error,
118				?relay_parent,
119				%para_id,
120				"Failed to fetch validation code hash",
121			);
122			return;
123		},
124	};
125
126	match state_validation_code_hash {
127		Some(state) => {
128			if state != *local_validation_code_hash {
129				tracing::warn!(
130					target: super::LOG_TARGET,
131					%para_id,
132					?relay_parent,
133					?local_validation_code_hash,
134					relay_validation_code_hash = ?state,
135					"Parachain code doesn't match validation code stored in the relay chain state.",
136				);
137			}
138		},
139		None => {
140			tracing::warn!(
141				target: super::LOG_TARGET,
142				%para_id,
143				?relay_parent,
144				"Could not find validation code for parachain in the relay chain state.",
145			);
146		},
147	}
148}
149
150// Returns the claim queue at the given relay parent.
151async fn claim_queue_at(
152	relay_parent: RelayHash,
153	relay_client: &impl RelayChainInterface,
154) -> ClaimQueueSnapshot {
155	// Get `ClaimQueue` from runtime
156	match relay_client.claim_queue(relay_parent).await {
157		Ok(claim_queue) => claim_queue.into(),
158		Err(error) => {
159			tracing::error!(
160				target: crate::LOG_TARGET,
161				?error,
162				?relay_parent,
163				"Failed to query claim queue runtime API",
164			);
165			Default::default()
166		},
167	}
168}
169
170// Checks if we own the slot at the given block.
171async fn claim_slot<Block: BlockT, Client, P>(
172	para_slot: Slot,
173	timestamp: Timestamp,
174	parent_hash: Block::Hash,
175	client: &Client,
176	keystore: &KeystorePtr,
177) -> Option<SlotClaim<P::Public>>
178where
179	Client: ProvideRuntimeApi<Block>,
180	Client::Api: AuraApi<Block, P::Public> + ApiExt<Block>,
181	P: Pair,
182	P::Public: Codec,
183	P::Signature: Codec,
184{
185	let mut runtime_api = client.runtime_api();
186	runtime_api.set_call_context(sp_core::traits::CallContext::Onchain { import: false });
187	let authorities = runtime_api.authorities(parent_hash).ok()?;
188	let author_pub = aura_internal::claim_slot::<P>(para_slot, &authorities, keystore).await?;
189	Some(SlotClaim::unchecked::<P>(author_pub, para_slot, timestamp))
190}
191
192// Checks if there is space in the unincluded segment.
193async fn can_build_upon<Block: BlockT, Client>(
194	parent_hash: Block::Hash,
195	included_block: Block::Hash,
196	relay_slot: Slot,
197	para_slot: Slot,
198	client: &Client,
199) -> bool
200where
201	Client: ProvideRuntimeApi<Block>,
202	Client::Api: AuraUnincludedSegmentApi<Block> + ApiExt<Block>,
203{
204	// This function is typically called when we want to build block N. At that point, the
205	// unincluded segment in the runtime is unaware of the hash of block N-1. If the unincluded
206	// segment in the runtime is full, but block N-1 is the included block, the unincluded segment
207	// should have length 0 and we can build. Since the hash is not available to the runtime
208	// however, we need this extra check here.
209	if parent_hash == included_block {
210		return true;
211	}
212
213	let runtime_api = client.runtime_api();
214	let Some(api_version) = runtime_api
215		.api_version::<dyn AuraUnincludedSegmentApi<Block>>(parent_hash)
216		.ok()
217		.flatten()
218	else {
219		return false;
220	};
221
222	let slot = if api_version > 1 { relay_slot } else { para_slot };
223
224	runtime_api
225		.can_build_upon(parent_hash, included_block, slot)
226		.ok()
227		.unwrap_or(false)
228}
229
230/// Use [`cumulus_client_consensus_common::find_parent_for_building`] to find the best parachain
231/// block to build on.
232///
233/// If the best parent does not pass `filter_parent`, walks backwards through ancestors
234/// until finding one that does, or reaching the included block.
235async fn find_parent<Block>(
236	relay_client: &impl RelayChainInterface,
237	para_backend: &impl sc_client_api::Backend<Block>,
238	para_id: ParaId,
239	params: ParentSearchParams,
240	v3_enabled_at: impl Fn(Block::Hash) -> bool,
241	filter_parent: impl Fn(&Block::Header) -> bool,
242) -> Option<consensus_common::ParentSearchResult<Block>>
243where
244	Block: BlockT,
245{
246	// The best parent may be a middle block in a bundle; `find_parent_for_building` trims it (and
247	// the resubmittable segment) back to the first block passing the filter, so the segment ends on
248	// a bundle-ender.
249	let result = match cumulus_client_consensus_common::find_parent_for_building::<Block>(
250		relay_client,
251		para_backend,
252		para_id,
253		params.clone(),
254		v3_enabled_at,
255		filter_parent,
256	)
257	.await
258	{
259		Ok(Some(result)) => result,
260		Ok(None) => {
261			tracing::warn!(
262				target: crate::LOG_TARGET,
263				?params,
264				"Could not find parent to build upon.",
265			);
266			return None;
267		},
268		Err(e) => {
269			tracing::error!(
270				target: crate::LOG_TARGET,
271				?params,
272				err = ?e,
273				"Could not find parent to build upon"
274			);
275			return None;
276		},
277	};
278
279	Some(result)
280}
281
282#[cfg(test)]
283mod tests {
284	use super::*;
285	use crate::collators::BackingGroupConnectionHelper;
286	use codec::Encode;
287	use cumulus_primitives_aura::Slot;
288	use cumulus_primitives_core::BlockT;
289	use cumulus_relay_chain_interface::PHash;
290	use cumulus_test_client::{
291		runtime::{Block, Hash},
292		BuildBlockBuilder, Client, DefaultTestClientBuilderExt, TestClientBuilder,
293		TestClientBuilderExt,
294	};
295	use cumulus_test_relay_sproof_builder::RelayStateSproofBuilder;
296	use futures::StreamExt;
297	use polkadot_overseer::{Event, Handle};
298	use polkadot_primitives::HeadData;
299	use sc_consensus::{BlockImport, BlockImportParams, ForkChoiceStrategy};
300	use sp_consensus::BlockOrigin;
301	use sp_keystore::{Keystore, KeystorePtr};
302	use std::sync::{Arc, Mutex};
303
304	async fn import_block<I: BlockImport<Block>>(
305		importer: &I,
306		block: Block,
307		origin: BlockOrigin,
308		import_as_best: bool,
309	) {
310		let (header, body) = block.deconstruct();
311
312		let mut block_import_params = BlockImportParams::new(origin, header);
313		block_import_params.fork_choice = Some(ForkChoiceStrategy::Custom(import_as_best));
314		block_import_params.body = Some(body);
315		importer.import_block(block_import_params).await.unwrap();
316	}
317
318	fn sproof_with_parent_by_hash(client: &Client, hash: PHash) -> RelayStateSproofBuilder {
319		let header = client.header(hash).ok().flatten().expect("No header for parent block");
320		let included = HeadData(header.encode());
321		let mut builder = RelayStateSproofBuilder::default();
322		builder.para_id = cumulus_test_client::runtime::PARACHAIN_ID.into();
323		builder.included_para_head = Some(included);
324
325		builder
326	}
327	async fn build_and_import_block(client: &Client, included: Hash) -> Block {
328		let sproof = sproof_with_parent_by_hash(client, included);
329
330		let block_builder = client
331			.init_block_builder_builder()
332			.with_relay_sproof_builder(sproof)
333			.build()
334			.block_builder;
335
336		let block = block_builder.build().unwrap().block;
337
338		let origin = BlockOrigin::NetworkInitialSync;
339		import_block(client, block.clone(), origin, true).await;
340		block
341	}
342
343	fn set_up_components(num_authorities: usize) -> (Arc<Client>, KeystorePtr) {
344		let keystore = Arc::new(sp_keystore::testing::MemoryKeystore::new()) as Arc<_>;
345		for key in sp_keyring::Sr25519Keyring::iter().take(num_authorities) {
346			Keystore::sr25519_generate_new(
347				&*keystore,
348				sp_application_crypto::key_types::AURA,
349				Some(&key.to_seed()),
350			)
351			.expect("Can insert key into MemoryKeyStore");
352		}
353		(Arc::new(TestClientBuilder::new().build()), keystore)
354	}
355
356	/// This tests a special scenario where the unincluded segment in the runtime
357	/// is full. We are calling `can_build_upon`, passing the last built block as the
358	/// included one. In the runtime we will not find the hash of the included block in the
359	/// unincluded segment. The `can_build_upon` runtime API would therefore return `false`, but
360	/// we are ensuring on the node side that we are are always able to build on the included block.
361	#[tokio::test]
362	async fn test_can_build_upon() {
363		sp_tracing::try_init_simple();
364
365		let (client, _keystore) = set_up_components(6);
366
367		let genesis_hash = client.chain_info().genesis_hash;
368		let mut last_hash = genesis_hash;
369
370		// Fill up the unincluded segment tracker in the runtime.
371		while can_build_upon::<_, _>(
372			last_hash,
373			genesis_hash,
374			Slot::from(u64::MAX),
375			Slot::from(u64::MAX),
376			&*client,
377		)
378		.await
379		{
380			let block = build_and_import_block(&client, genesis_hash).await;
381			last_hash = block.header().hash();
382		}
383
384		// Blocks were built with the genesis hash set as included block.
385		// We call `can_build_upon` with the last built block as the included block.
386		let result = can_build_upon::<_, _>(
387			last_hash,
388			last_hash,
389			Slot::from(u64::MAX),
390			Slot::from(u64::MAX),
391			&*client,
392		)
393		.await;
394		assert!(result);
395	}
396
397	/// Helper to create a mock overseer handle and message recorder
398	fn create_overseer_handle() -> (OverseerHandle, Arc<Mutex<Vec<CollatorProtocolMessage>>>) {
399		let messages = Arc::new(Mutex::new(Vec::new()));
400		let messages_clone = messages.clone();
401
402		let (tx, mut rx) = polkadot_node_subsystem_util::metered::channel(100);
403
404		// Spawn a task to receive and record overseer messages
405		tokio::spawn(async move {
406			while let Some(event) = rx.next().await {
407				if let Event::MsgToSubsystem { msg, .. } = event {
408					if let polkadot_node_subsystem::AllMessages::CollatorProtocol(cp_msg) = msg {
409						messages_clone.lock().unwrap().push(cp_msg);
410					}
411				}
412			}
413		});
414
415		(Handle::new(tx), messages)
416	}
417
418	#[tokio::test]
419	async fn preconnect_when_next_slot_is_ours() {
420		let (client, keystore) = set_up_components(1);
421		let genesis_hash = client.chain_info().genesis_hash;
422		let (overseer_handle, messages_recorder) = create_overseer_handle();
423
424		let mut helper = BackingGroupConnectionHelper::new(keystore, overseer_handle);
425
426		// Fetch authorities for the update call
427		let authorities = client.runtime_api().authorities(genesis_hash).unwrap();
428
429		// Update with slot 5, next slot (6) should be ours
430		helper
431			.update::<sp_consensus_aura::sr25519::AuthorityPair>(Slot::from(5), &authorities)
432			.await;
433
434		// Give time for message to be processed
435		tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
436
437		let messages = messages_recorder.lock().unwrap();
438		assert_eq!(messages.len(), 1);
439		assert!(matches!(messages[0], CollatorProtocolMessage::ConnectToBackingGroups));
440		assert_eq!(helper.our_slot, Some(Slot::from(6)));
441	}
442
443	#[tokio::test]
444	async fn preconnect_no_duplicate_connect_message() {
445		let (client, keystore) = set_up_components(1);
446		let genesis_hash = client.chain_info().genesis_hash;
447		let (overseer_handle, messages_recorder) = create_overseer_handle();
448
449		let mut helper = BackingGroupConnectionHelper::new(keystore, overseer_handle);
450
451		// Fetch authorities for the update calls
452		let authorities = client.runtime_api().authorities(genesis_hash).unwrap();
453
454		// Update with slot 5, next slot (6) is ours
455		helper
456			.update::<sp_consensus_aura::sr25519::AuthorityPair>(Slot::from(5), &authorities)
457			.await;
458
459		// Give time for message to be processed
460		tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
461		assert_eq!(messages_recorder.lock().unwrap().len(), 1);
462		messages_recorder.lock().unwrap().clear();
463
464		// Update with slot 5 again - should not send another message
465		helper
466			.update::<sp_consensus_aura::sr25519::AuthorityPair>(Slot::from(5), &authorities)
467			.await;
468		tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
469		assert_eq!(messages_recorder.lock().unwrap().len(), 0);
470
471		// Update with slot 1 (our slot) - should not send another message
472		helper
473			.update::<sp_consensus_aura::sr25519::AuthorityPair>(Slot::from(6), &authorities)
474			.await;
475		tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
476		assert_eq!(messages_recorder.lock().unwrap().len(), 0);
477	}
478
479	#[tokio::test]
480	async fn preconnect_disconnect_when_slot_passes() {
481		let (client, keystore) = set_up_components(1);
482		let genesis_hash = client.chain_info().genesis_hash;
483		let (overseer_handle, messages_recorder) = create_overseer_handle();
484
485		let mut helper = BackingGroupConnectionHelper::new(keystore, overseer_handle);
486
487		// Fetch authorities for the update calls
488		let authorities = client.runtime_api().authorities(genesis_hash).unwrap();
489
490		// Slot 0 -> Alice, Slot 1 -> Bob, Slot 2 -> Charlie, Slot 3 -> Dave, Slot 4 -> Eve,
491		// Slot 5 -> Ferdie, Slot 6 -> Alice
492
493		// Update with slot 5, next slot (6) is ours -> should connect
494		helper
495			.update::<sp_consensus_aura::sr25519::AuthorityPair>(Slot::from(5), &authorities)
496			.await;
497		tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
498		assert_eq!(helper.our_slot, Some(Slot::from(6)));
499		messages_recorder.lock().unwrap().clear();
500
501		// Update with slot 8, next slot (9) is Charlie's -> should disconnect
502		helper
503			.update::<sp_consensus_aura::sr25519::AuthorityPair>(Slot::from(8), &authorities)
504			.await;
505		tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
506
507		{
508			let messages = messages_recorder.lock().unwrap();
509			assert_eq!(messages.len(), 1, "Expected exactly one disconnect message");
510			assert!(matches!(messages[0], CollatorProtocolMessage::DisconnectFromBackingGroups));
511			assert_eq!(helper.our_slot, None);
512		}
513
514		messages_recorder.lock().unwrap().clear();
515
516		// Update again with slot 8, next slot (9) is Charlie's -> should not send another
517		// disconnect message
518		helper
519			.update::<sp_consensus_aura::sr25519::AuthorityPair>(Slot::from(8), &authorities)
520			.await;
521		tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
522
523		let messages = messages_recorder.lock().unwrap();
524		assert_eq!(messages.len(), 0, "Expected no messages");
525		assert_eq!(helper.our_slot, None);
526	}
527
528	#[tokio::test]
529	async fn preconnect_no_disconnect_without_previous_connection() {
530		let (client, keystore) = set_up_components(1);
531		let genesis_hash = client.chain_info().genesis_hash;
532		let (overseer_handle, messages_recorder) = create_overseer_handle();
533
534		let mut helper = BackingGroupConnectionHelper::new(keystore, overseer_handle);
535
536		// Fetch authorities for the update call
537		let authorities = client.runtime_api().authorities(genesis_hash).unwrap();
538
539		// Slot 0 -> Alice, Slot 1 -> Bob, Slot 2 -> Charlie, Slot 3 -> Dave, Slot 4 -> Eve,
540		// Slot 5 -> Ferdie
541
542		// Update with slot 1 (Bob's slot), next slot (2) is Charlie's
543		// Since we never connected before (our_slot is None), we should not send disconnect
544		helper
545			.update::<sp_consensus_aura::sr25519::AuthorityPair>(Slot::from(1), &authorities)
546			.await;
547
548		tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
549		// Should not send any message since we never connected
550		assert_eq!(messages_recorder.lock().unwrap().len(), 0);
551		assert_eq!(helper.our_slot, None);
552	}
553
554	#[tokio::test]
555	async fn preconnect_multiple_cycles() {
556		let (client, keystore) = set_up_components(1);
557		let genesis_hash = client.chain_info().genesis_hash;
558		let (overseer_handle, messages_recorder) = create_overseer_handle();
559
560		let mut helper = BackingGroupConnectionHelper::new(keystore, overseer_handle);
561
562		// Fetch authorities for the update calls
563		let authorities = client.runtime_api().authorities(genesis_hash).unwrap();
564
565		// Slot 0 -> Alice, Slot 1 -> Bob, Slot 2 -> Charlie, Slot 3 -> Dave, Slot 4 -> Eve,
566		// Slot 5 -> Ferdie, Slot 6 -> Alice, Slot 7 -> Bob, ...
567
568		// Cycle 1: Connect at slot 5, next slot (6) is ours
569		helper
570			.update::<sp_consensus_aura::sr25519::AuthorityPair>(Slot::from(5), &authorities)
571			.await;
572		tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
573		{
574			let messages = messages_recorder.lock().unwrap();
575			assert_eq!(messages.len(), 1);
576			assert!(matches!(messages[0], CollatorProtocolMessage::ConnectToBackingGroups));
577		}
578		assert_eq!(helper.our_slot, Some(Slot::from(6)));
579		messages_recorder.lock().unwrap().clear();
580
581		// Cycle 1: Disconnect at slot 7, next slot (8) is Charlie's
582		helper
583			.update::<sp_consensus_aura::sr25519::AuthorityPair>(Slot::from(7), &authorities)
584			.await;
585		tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
586		{
587			let messages = messages_recorder.lock().unwrap();
588			assert_eq!(messages.len(), 1);
589			assert!(matches!(messages[0], CollatorProtocolMessage::DisconnectFromBackingGroups));
590		}
591		assert_eq!(helper.our_slot, None);
592		messages_recorder.lock().unwrap().clear();
593
594		// Cycle 2: Connect again at slot 11, next slot (12) is ours
595		helper
596			.update::<sp_consensus_aura::sr25519::AuthorityPair>(Slot::from(11), &authorities)
597			.await;
598		tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
599		{
600			let messages = messages_recorder.lock().unwrap();
601			assert_eq!(messages.len(), 1);
602			assert!(matches!(messages[0], CollatorProtocolMessage::ConnectToBackingGroups));
603		}
604		assert_eq!(helper.our_slot, Some(Slot::from(12)));
605	}
606
607	#[tokio::test]
608	async fn preconnect_handles_empty_authorities() {
609		let keystore = Arc::new(sp_keystore::testing::MemoryKeystore::new()) as Arc<_>;
610		let (overseer_handle, messages_recorder) = create_overseer_handle();
611
612		let mut helper = BackingGroupConnectionHelper::new(keystore, overseer_handle);
613
614		// Pass empty authorities list
615		let authorities = vec![];
616		helper
617			.update::<sp_consensus_aura::sr25519::AuthorityPair>(Slot::from(0), &authorities)
618			.await;
619
620		tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
621		// Should not send any message if authorities list is empty
622		assert_eq!(messages_recorder.lock().unwrap().len(), 0);
623	}
624}
625
626/// Fetches relay chain storage proof requests from the parachain runtime.
627///
628/// Queries the runtime API to determine which relay chain storage keys
629/// (both top-level and child trie keys) should be included in the relay chain state proof.
630///
631/// Falls back to an empty request if the runtime API call fails or is not implemented.
632pub(crate) fn get_relay_proof_request<Block, Client>(
633	client: &Client,
634	parent_hash: Block::Hash,
635) -> RelayProofRequest
636where
637	Block: BlockT,
638	Client: ProvideRuntimeApi<Block>,
639	Client::Api: KeyToIncludeInRelayProof<Block>,
640{
641	client.runtime_api().keys_to_prove(parent_hash).unwrap_or_else(|e| {
642		tracing::debug!(
643			target: crate::LOG_TARGET,
644			error = ?e,
645			"Failed to fetch relay proof requests from runtime, using empty request"
646		);
647		Default::default()
648	})
649}
650
651/// Holds a relay parent and its descendants.
652#[derive(Clone)]
653pub struct RelayParentData {
654	/// The relay parent block header
655	relay_parent: RelayHeader,
656	/// Ordered collection of descendant block headers, from oldest to newest
657	descendants: Vec<RelayHeader>,
658}
659
660impl RelayParentData {
661	/// Creates a new instance with the given relay parent and no descendants.
662	pub fn new(relay_parent: RelayHeader) -> Self {
663		Self { relay_parent, descendants: Default::default() }
664	}
665
666	/// Creates a new instance with the given relay parent and descendants.
667	pub fn new_with_descendants(relay_parent: RelayHeader, descendants: Vec<RelayHeader>) -> Self {
668		Self { relay_parent, descendants }
669	}
670
671	/// Returns a reference to the relay parent header.
672	pub fn relay_parent(&self) -> &RelayHeader {
673		&self.relay_parent
674	}
675
676	/// Takes the descendants list.
677	///
678	/// List is ordered from oldest to newest.
679	pub fn take_descendants(&mut self) -> Vec<RelayHeader> {
680		std::mem::take(&mut self.descendants)
681	}
682
683	/// Returns the number of descendants.
684	#[cfg(test)]
685	pub fn descendants_len(&self) -> usize {
686		self.descendants.len()
687	}
688
689	/// Consumes the structure and returns a vector containing the relay parent followed by its
690	/// descendants in chronological order. The resulting list should be provided to the parachain
691	/// inherent data.
692	pub fn into_inherent_descendant_list(self) -> Vec<RelayHeader> {
693		let Self { relay_parent, mut descendants } = self;
694
695		if descendants.is_empty() {
696			return Default::default();
697		}
698
699		let mut result = vec![relay_parent];
700		result.append(&mut descendants);
701		result
702	}
703}