1use 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
45struct 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 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 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 if self.our_slot.is_none() {
84 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 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
99async 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
150async fn claim_queue_at(
152 relay_parent: RelayHash,
153 relay_client: &impl RelayChainInterface,
154) -> ClaimQueueSnapshot {
155 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
170async 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
192async 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 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
230async 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 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 #[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 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 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 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 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 let authorities = client.runtime_api().authorities(genesis_hash).unwrap();
428
429 helper
431 .update::<sp_consensus_aura::sr25519::AuthorityPair>(Slot::from(5), &authorities)
432 .await;
433
434 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 let authorities = client.runtime_api().authorities(genesis_hash).unwrap();
453
454 helper
456 .update::<sp_consensus_aura::sr25519::AuthorityPair>(Slot::from(5), &authorities)
457 .await;
458
459 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 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 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 let authorities = client.runtime_api().authorities(genesis_hash).unwrap();
489
490 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 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 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 let authorities = client.runtime_api().authorities(genesis_hash).unwrap();
538
539 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 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 let authorities = client.runtime_api().authorities(genesis_hash).unwrap();
564
565 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 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 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 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 assert_eq!(messages_recorder.lock().unwrap().len(), 0);
623 }
624}
625
626pub(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#[derive(Clone)]
653pub struct RelayParentData {
654 relay_parent: RelayHeader,
656 descendants: Vec<RelayHeader>,
658}
659
660impl RelayParentData {
661 pub fn new(relay_parent: RelayHeader) -> Self {
663 Self { relay_parent, descendants: Default::default() }
664 }
665
666 pub fn new_with_descendants(relay_parent: RelayHeader, descendants: Vec<RelayHeader>) -> Self {
668 Self { relay_parent, descendants }
669 }
670
671 pub fn relay_parent(&self) -> &RelayHeader {
673 &self.relay_parent
674 }
675
676 pub fn take_descendants(&mut self) -> Vec<RelayHeader> {
680 std::mem::take(&mut self.descendants)
681 }
682
683 #[cfg(test)]
685 pub fn descendants_len(&self) -> usize {
686 self.descendants.len()
687 }
688
689 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}