cumulus_primitives_core/lib.rs
1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Cumulus.
3// SPDX-License-Identifier: Apache-2.0
4
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17//! Cumulus related core primitive types and traits.
18
19#![cfg_attr(not(feature = "std"), no_std)]
20
21extern crate alloc;
22
23use alloc::vec::Vec;
24use codec::{Compact, Decode, DecodeAll, DecodeWithMemTracking, Encode, MaxEncodedLen};
25use polkadot_parachain_primitives::primitives::HeadData;
26use scale_info::TypeInfo;
27use Debug;
28
29/// The ref time per core in seconds.
30///
31/// This is the execution time each PoV gets on a core on the relay chain.
32pub const REF_TIME_PER_CORE_IN_SECS: u64 = 2;
33
34pub mod parachain_block_data;
35pub mod scheduling;
36
37pub use parachain_block_data::ParachainBlockData;
38pub use polkadot_core_primitives::InboundDownwardMessage;
39pub use polkadot_parachain_primitives::primitives::{
40 DmpMessageHandler, Id as ParaId, IsSystem, UpwardMessage, ValidationParams, XcmpMessageFormat,
41 XcmpMessageHandler,
42};
43pub use polkadot_primitives::{
44 AbridgedHostConfiguration, AbridgedHrmpChannel, ClaimQueueOffset, CoreSelector,
45 PersistedValidationData,
46};
47pub use scheduling::{
48 SchedulingInfoPayload, SchedulingProof, SignedSchedulingInfo, VerifySchedulingSignature,
49};
50pub use sp_runtime::{
51 generic::{Digest, DigestItem},
52 traits::Block as BlockT,
53 ConsensusEngineId,
54};
55pub use xcm::latest::prelude::*;
56
57/// A module that re-exports relevant relay chain definitions.
58pub mod relay_chain {
59 pub use polkadot_core_primitives::*;
60 pub use polkadot_primitives::*;
61}
62
63/// An inbound HRMP message.
64pub type InboundHrmpMessage = polkadot_primitives::InboundHrmpMessage<relay_chain::BlockNumber>;
65
66/// And outbound HRMP message
67pub type OutboundHrmpMessage = polkadot_primitives::OutboundHrmpMessage<ParaId>;
68
69/// Error description of a message send failure.
70#[derive(Eq, PartialEq, Copy, Clone, Debug, Encode, Decode)]
71pub enum MessageSendError {
72 /// The dispatch queue is full.
73 QueueFull,
74 /// There does not exist a channel for sending the message.
75 NoChannel,
76 /// The message is too big to ever fit in a channel.
77 TooBig,
78 /// Some other error.
79 Other,
80 /// There are too many channels open at once.
81 TooManyChannels,
82}
83
84impl From<MessageSendError> for &'static str {
85 fn from(e: MessageSendError) -> Self {
86 use MessageSendError::*;
87 match e {
88 QueueFull => "QueueFull",
89 NoChannel => "NoChannel",
90 TooBig => "TooBig",
91 Other => "Other",
92 TooManyChannels => "TooManyChannels",
93 }
94 }
95}
96
97/// The origin of an inbound message.
98#[derive(
99 Encode, Decode, DecodeWithMemTracking, MaxEncodedLen, Clone, Eq, PartialEq, TypeInfo, Debug,
100)]
101pub enum AggregateMessageOrigin {
102 /// The message came from the para-chain itself.
103 Here,
104 /// The message came from the relay-chain.
105 ///
106 /// This is used by the DMP queue.
107 Parent,
108 /// The message came from a sibling para-chain.
109 ///
110 /// This is used by the HRMP queue.
111 Sibling(ParaId),
112}
113
114impl From<AggregateMessageOrigin> for Location {
115 fn from(origin: AggregateMessageOrigin) -> Self {
116 match origin {
117 AggregateMessageOrigin::Here => Location::here(),
118 AggregateMessageOrigin::Parent => Location::parent(),
119 AggregateMessageOrigin::Sibling(id) => Location::new(1, Junction::Parachain(id.into())),
120 }
121 }
122}
123
124#[cfg(feature = "runtime-benchmarks")]
125impl From<u32> for AggregateMessageOrigin {
126 fn from(x: u32) -> Self {
127 match x {
128 0 => Self::Here,
129 1 => Self::Parent,
130 p => Self::Sibling(ParaId::from(p)),
131 }
132 }
133}
134
135/// Information about an XCMP channel.
136pub struct ChannelInfo {
137 /// The maximum number of messages that can be pending in the channel at once.
138 pub max_capacity: u32,
139 /// The maximum total size of the messages that can be pending in the channel at once.
140 pub max_total_size: u32,
141 /// The maximum message size that could be put into the channel.
142 pub max_message_size: u32,
143 /// The current number of messages pending in the channel.
144 /// Invariant: should be less or equal to `max_capacity`.s`.
145 pub msg_count: u32,
146 /// The total size in bytes of all message payloads in the channel.
147 /// Invariant: should be less or equal to `max_total_size`.
148 pub total_size: u32,
149}
150
151pub trait GetChannelInfo {
152 fn get_channel_status(id: ParaId) -> ChannelStatus;
153 fn get_channel_info(id: ParaId) -> Option<ChannelInfo>;
154}
155
156/// List all open outgoing channels.
157pub trait ListChannelInfos {
158 fn outgoing_channels() -> Vec<ParaId>;
159}
160
161/// Something that should be called when sending an upward message.
162pub trait UpwardMessageSender {
163 /// Send the given UMP message; return the expected number of blocks before the message will
164 /// be dispatched or an error if the message cannot be sent.
165 /// return the hash of the message sent
166 fn send_upward_message(message: UpwardMessage) -> Result<(u32, XcmHash), MessageSendError>;
167
168 /// Pre-check the given UMP message.
169 fn can_send_upward_message(message: &UpwardMessage) -> Result<(), MessageSendError>;
170
171 /// Ensure `[Self::send_upward_message]` is successful when called in benchmarks/tests.
172 #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
173 fn ensure_successful_delivery() {}
174}
175
176impl UpwardMessageSender for () {
177 fn send_upward_message(_message: UpwardMessage) -> Result<(u32, XcmHash), MessageSendError> {
178 Err(MessageSendError::NoChannel)
179 }
180
181 fn can_send_upward_message(_message: &UpwardMessage) -> Result<(), MessageSendError> {
182 Err(MessageSendError::Other)
183 }
184}
185
186/// The status of a channel.
187pub enum ChannelStatus {
188 /// Channel doesn't exist/has been closed.
189 Closed,
190 /// Channel is completely full right now.
191 Full,
192 /// Channel is ready for sending; the two parameters are the maximum size a valid message may
193 /// have right now, and the maximum size a message may ever have (this will generally have been
194 /// available during message construction, but it's possible the channel parameters changed in
195 /// the meantime).
196 Ready(usize, usize),
197}
198
199/// A means of figuring out what outbound XCMP messages should be being sent.
200pub trait XcmpMessageSource {
201 /// Take outbound XCMP messages from the queue.
202 ///
203 /// `excluded_recipients` contains para IDs that must be skipped.
204 fn take_outbound_messages(
205 maximum_channels: usize,
206 excluded_recipients: &[ParaId],
207 ) -> Vec<(ParaId, Vec<u8>)>;
208}
209
210impl XcmpMessageSource for () {
211 fn take_outbound_messages(
212 _maximum_channels: usize,
213 _excluded_recipients: &[ParaId],
214 ) -> Vec<(ParaId, Vec<u8>)> {
215 Vec::new()
216 }
217}
218
219/// The "quality of service" considerations for message sending.
220#[derive(Eq, PartialEq, Clone, Copy, Encode, Decode, Debug)]
221pub enum ServiceQuality {
222 /// Ensure that this message is dispatched in the same relative order as any other messages
223 /// that were also sent with `Ordered`. This only guarantees message ordering on the dispatch
224 /// side, and not necessarily on the execution side.
225 Ordered,
226 /// Ensure that the message is dispatched as soon as possible, which could result in it being
227 /// dispatched before other messages which are larger and/or rely on relative ordering.
228 Fast,
229}
230
231/// A consensus engine ID indicating that this is a Cumulus Parachain.
232pub const CUMULUS_CONSENSUS_ID: ConsensusEngineId = *b"CMLS";
233
234/// Information about the core on the relay chain this block will be validated on.
235#[derive(Clone, Debug, Decode, Encode, PartialEq, Eq)]
236pub struct CoreInfo {
237 /// The selector that determines the actual core at `claim_queue_offset`.
238 pub selector: CoreSelector,
239 /// The claim queue offset that determines how far "into the future" the core is selected.
240 pub claim_queue_offset: ClaimQueueOffset,
241 /// The number of cores assigned to the parachain at `claim_queue_offset`.
242 pub number_of_cores: Compact<u16>,
243}
244
245impl core::hash::Hash for CoreInfo {
246 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
247 state.write_u8(self.selector.0);
248 state.write_u8(self.claim_queue_offset.0);
249 state.write_u16(self.number_of_cores.0);
250 }
251}
252
253impl CoreInfo {
254 /// Puts this into a [`CumulusDigestItem::CoreInfo`] and then encodes it as a Substrate
255 /// [`DigestItem`].
256 pub fn to_digest_item(&self) -> DigestItem {
257 CumulusDigestItem::CoreInfo(self.clone()).to_digest_item()
258 }
259}
260
261/// Information about a block that is part of a PoV bundle.
262#[derive(Clone, Debug, Decode, Encode, PartialEq)]
263pub struct BlockBundleInfo {
264 /// The index of the block in the bundle.
265 pub index: u8,
266 /// Is this the last block in the bundle from the point of view of the node?
267 ///
268 /// It is possible that the runtime outputs the
269 /// [`CumulusDigestItem::UseFullCore`] to inform the node to use an entire for one block
270 /// only.
271 pub is_last: bool,
272}
273
274impl BlockBundleInfo {
275 /// Puts this into a [`CumulusDigestItem::BlockBundleInfo`] and then encodes it as a Substrate
276 /// [`DigestItem`].
277 pub fn to_digest_item(&self) -> DigestItem {
278 CumulusDigestItem::BlockBundleInfo(self.clone()).to_digest_item()
279 }
280}
281
282/// Return value of [`CumulusDigestItem::core_info_exists_at_max_once`]
283#[derive(Debug, Clone, PartialEq, Eq)]
284pub enum CoreInfoExistsAtMaxOnce {
285 /// Exists exactly once.
286 Once(CoreInfo),
287 /// Not found.
288 NotFound,
289 /// Found more than once.
290 MoreThanOnce,
291}
292
293/// Identifier for a relay chain block used by [`CumulusDigestItem`].
294#[derive(Clone, Debug, PartialEq, Hash, Eq)]
295pub enum RelayBlockIdentifier {
296 /// The block is identified using its block hash.
297 ByHash(relay_chain::Hash),
298 /// The block is identified using its storage root and block number.
299 ByStorageRoot { storage_root: relay_chain::Hash, block_number: relay_chain::BlockNumber },
300}
301
302/// Consensus header digests for Cumulus parachains.
303#[derive(Clone, Debug, Decode, Encode, PartialEq)]
304pub enum CumulusDigestItem {
305 /// A digest item indicating the relay-parent a parachain block was built against.
306 #[codec(index = 0)]
307 RelayParent(relay_chain::Hash),
308 /// A digest item providing information about the core selected on the relay chain for this
309 /// block.
310 #[codec(index = 1)]
311 CoreInfo(CoreInfo),
312 /// A digest item providing information about the position of the block in the bundle.
313 #[codec(index = 2)]
314 BlockBundleInfo(BlockBundleInfo),
315 /// A digest item informing the node that this block should be put alone onto a core.
316 ///
317 /// In other words, the core should not be shared with other blocks.
318 ///
319 /// Under certain conditions (mainly runtime misconfigurations) the digest is still set when
320 /// there are muliple blocks per core. This is done to communicate to the collator that block
321 /// production for this core should be stopped.
322 #[codec(index = 3)]
323 UseFullCore,
324}
325
326impl CumulusDigestItem {
327 /// Encode this as a Substrate [`DigestItem`].
328 pub fn to_digest_item(&self) -> DigestItem {
329 let encoded = self.encode();
330
331 match self {
332 Self::RelayParent(_) | Self::UseFullCore => {
333 DigestItem::Consensus(CUMULUS_CONSENSUS_ID, encoded)
334 },
335 _ => DigestItem::PreRuntime(CUMULUS_CONSENSUS_ID, encoded),
336 }
337 }
338
339 /// Find [`CumulusDigestItem::CoreInfo`] in the given `digest`.
340 ///
341 /// If there are multiple valid digests, this returns the value of the first one.
342 pub fn find_core_info(digest: &Digest) -> Option<CoreInfo> {
343 digest.convert_first(|d| match d {
344 DigestItem::PreRuntime(id, val) if id == &CUMULUS_CONSENSUS_ID => {
345 let Ok(CumulusDigestItem::CoreInfo(core_info)) =
346 CumulusDigestItem::decode_all(&mut &val[..])
347 else {
348 return None;
349 };
350
351 Some(core_info)
352 },
353 _ => None,
354 })
355 }
356
357 /// Returns the found [`CoreInfo`] and iff [`Self::CoreInfo`] exists at max once in the given
358 /// `digest`.
359 pub fn core_info_exists_at_max_once(digest: &Digest) -> CoreInfoExistsAtMaxOnce {
360 let mut core_info = None;
361 if digest
362 .logs()
363 .iter()
364 .filter(|l| match l {
365 DigestItem::PreRuntime(CUMULUS_CONSENSUS_ID, d) => {
366 if let Ok(Self::CoreInfo(ci)) = Self::decode_all(&mut &d[..]) {
367 core_info = Some(ci);
368 true
369 } else {
370 false
371 }
372 },
373 _ => false,
374 })
375 .count() <= 1
376 {
377 core_info
378 .map(CoreInfoExistsAtMaxOnce::Once)
379 .unwrap_or(CoreInfoExistsAtMaxOnce::NotFound)
380 } else {
381 CoreInfoExistsAtMaxOnce::MoreThanOnce
382 }
383 }
384
385 /// Returns the [`RelayBlockIdentifier`] from the given `digest`.
386 ///
387 /// The identifier corresponds to the relay parent used to build the parachain block.
388 pub fn find_relay_block_identifier(digest: &Digest) -> Option<RelayBlockIdentifier> {
389 digest.convert_first(|d| match d {
390 DigestItem::Consensus(id, val) if id == &CUMULUS_CONSENSUS_ID => {
391 let Ok(CumulusDigestItem::RelayParent(hash)) =
392 CumulusDigestItem::decode_all(&mut &val[..])
393 else {
394 return None;
395 };
396
397 Some(RelayBlockIdentifier::ByHash(hash))
398 },
399 DigestItem::Consensus(id, val) if id == &rpsr_digest::RPSR_CONSENSUS_ID => {
400 let Ok((storage_root, block_number)) =
401 rpsr_digest::RpsrType::decode_all(&mut &val[..])
402 else {
403 return None;
404 };
405
406 Some(RelayBlockIdentifier::ByStorageRoot {
407 storage_root,
408 block_number: block_number.into(),
409 })
410 },
411 _ => None,
412 })
413 }
414
415 /// Returns the [`BlockBundleInfo`] from the given `digest`.
416 pub fn find_block_bundle_info(digest: &Digest) -> Option<BlockBundleInfo> {
417 digest.convert_first(|d| match d {
418 DigestItem::PreRuntime(id, val) if id == &CUMULUS_CONSENSUS_ID => {
419 let Ok(CumulusDigestItem::BlockBundleInfo(bundle_info)) =
420 CumulusDigestItem::decode_all(&mut &val[..])
421 else {
422 return None;
423 };
424
425 Some(bundle_info)
426 },
427 _ => None,
428 })
429 }
430
431 /// Returns `true` if the given `digest` contains the [`Self::UseFullCore`] item.
432 pub fn contains_use_full_core(digest: &Digest) -> bool {
433 digest
434 .convert_first(|d| match d {
435 DigestItem::Consensus(id, val) if id == &CUMULUS_CONSENSUS_ID => {
436 let Ok(CumulusDigestItem::UseFullCore) =
437 CumulusDigestItem::decode_all(&mut &val[..])
438 else {
439 return None;
440 };
441
442 Some(true)
443 },
444 _ => None,
445 })
446 .unwrap_or_default()
447 }
448
449 /// Returns `true` if the given `digest` is from a block that is the last block in a core.
450 ///
451 /// Checks the following conditions:
452 ///
453 /// - Is [`BlockBundleInfo::is_last`] set to true?
454 /// - Or is [`Self::UseFullCore`] digest present?
455 /// - Or is [`DigestItem::RuntimeEnvironmentUpdated`] digest present?
456 ///
457 /// If any of these conditions is `true`, this function will return `true`.
458 ///
459 /// Returns `None` if the `BlockBundleInfo` digest is not present, which is interpreted as the
460 /// associated block is not using block bundling.
461 pub fn is_last_block_in_core(digest: &Digest) -> Option<bool> {
462 let bundle_info = Self::find_block_bundle_info(digest)?;
463
464 Some(
465 bundle_info.is_last ||
466 Self::contains_use_full_core(digest) ||
467 digest.logs.iter().any(|l| matches!(l, DigestItem::RuntimeEnvironmentUpdated)),
468 )
469 }
470}
471
472/// If there are multiple valid digests, this returns the value of the first one, although
473/// well-behaving runtimes should not produce headers with more than one.
474pub fn extract_relay_parent(digest: &Digest) -> Option<relay_chain::Hash> {
475 digest.convert_first(|d| match d {
476 DigestItem::Consensus(id, val) if id == &CUMULUS_CONSENSUS_ID => {
477 match CumulusDigestItem::decode(&mut &val[..]) {
478 Ok(CumulusDigestItem::RelayParent(hash)) => Some(hash),
479 _ => None,
480 }
481 },
482 _ => None,
483 })
484}
485
486/// Utilities for handling the relay-parent storage root as a digest item.
487///
488/// This is not intended to be part of the public API, as it is a workaround for
489/// <https://github.com/paritytech/cumulus/issues/303> via
490/// <https://github.com/paritytech/polkadot/issues/7191>.
491///
492/// Runtimes using the parachain-system pallet are expected to produce this digest item,
493/// but will stop as soon as they are able to provide the relay-parent hash directly.
494///
495/// The relay-chain storage root is, in practice, a unique identifier of a block
496/// in the absence of equivocations (which are slashable). This assumes that the relay chain
497/// uses BABE or SASSAFRAS, because the slot and the author's VRF randomness are both included
498/// in the relay-chain storage root in both cases.
499///
500/// Therefore, the relay-parent storage root is a suitable identifier of unique relay chain
501/// blocks in low-value scenarios such as performance optimizations.
502#[doc(hidden)]
503pub mod rpsr_digest {
504 use super::{relay_chain, ConsensusEngineId, DecodeAll, Digest, DigestItem, Encode};
505 use codec::Compact;
506
507 /// The type used to store the relay-parent storage root and number.
508 pub type RpsrType = (relay_chain::Hash, Compact<relay_chain::BlockNumber>);
509
510 /// A consensus engine ID for relay-parent storage root digests.
511 pub const RPSR_CONSENSUS_ID: ConsensusEngineId = *b"RPSR";
512
513 /// Construct a digest item for relay-parent storage roots.
514 pub fn relay_parent_storage_root_item(
515 storage_root: relay_chain::Hash,
516 number: impl Into<Compact<relay_chain::BlockNumber>>,
517 ) -> DigestItem {
518 DigestItem::Consensus(
519 RPSR_CONSENSUS_ID,
520 RpsrType::from((storage_root, number.into())).encode(),
521 )
522 }
523
524 /// Extract the relay-parent storage root and number from the provided header digest. Returns
525 /// `None` if none were found.
526 pub fn extract_relay_parent_storage_root(
527 digest: &Digest,
528 ) -> Option<(relay_chain::Hash, relay_chain::BlockNumber)> {
529 digest.convert_first(|d| match d {
530 DigestItem::Consensus(id, val) if id == &RPSR_CONSENSUS_ID => {
531 let (h, n) = RpsrType::decode_all(&mut &val[..]).ok()?;
532
533 Some((h, n.0))
534 },
535 _ => None,
536 })
537 }
538}
539
540/// Information about a collation.
541///
542/// This was used in version 1 of the [`CollectCollationInfo`] runtime api.
543#[derive(Clone, Debug, codec::Decode, codec::Encode, PartialEq)]
544pub struct CollationInfoV1 {
545 /// Messages destined to be interpreted by the Relay chain itself.
546 pub upward_messages: Vec<UpwardMessage>,
547 /// The horizontal messages sent by the parachain.
548 pub horizontal_messages: Vec<OutboundHrmpMessage>,
549 /// New validation code.
550 pub new_validation_code: Option<relay_chain::ValidationCode>,
551 /// The number of messages processed from the DMQ.
552 pub processed_downward_messages: u32,
553 /// The mark which specifies the block number up to which all inbound HRMP messages are
554 /// processed.
555 pub hrmp_watermark: relay_chain::BlockNumber,
556}
557
558impl CollationInfoV1 {
559 /// Convert into the latest version of the [`CollationInfo`] struct.
560 pub fn into_latest(self, head_data: HeadData) -> CollationInfo {
561 CollationInfo {
562 upward_messages: self.upward_messages,
563 horizontal_messages: self.horizontal_messages,
564 new_validation_code: self.new_validation_code,
565 processed_downward_messages: self.processed_downward_messages,
566 hrmp_watermark: self.hrmp_watermark,
567 head_data,
568 }
569 }
570}
571
572/// Information about a collation.
573#[derive(Clone, Debug, codec::Decode, codec::Encode, PartialEq, TypeInfo)]
574pub struct CollationInfo {
575 /// Messages destined to be interpreted by the Relay chain itself.
576 pub upward_messages: Vec<UpwardMessage>,
577 /// The horizontal messages sent by the parachain.
578 pub horizontal_messages: Vec<OutboundHrmpMessage>,
579 /// New validation code.
580 pub new_validation_code: Option<relay_chain::ValidationCode>,
581 /// The number of messages processed from the DMQ.
582 pub processed_downward_messages: u32,
583 /// The mark which specifies the block number up to which all inbound HRMP messages are
584 /// processed.
585 pub hrmp_watermark: relay_chain::BlockNumber,
586 /// The head data, aka encoded header, of the block that corresponds to the collation.
587 pub head_data: HeadData,
588}
589
590/// A relay chain storage key to be included in the storage proof.
591#[derive(Clone, Debug, Encode, Decode, TypeInfo, PartialEq, Eq)]
592pub enum RelayStorageKey {
593 /// Top-level relay chain storage key.
594 Top(Vec<u8>),
595 /// Child trie storage key.
596 Child {
597 /// Unprefixed storage key identifying the child trie root location.
598 /// Prefix `:child_storage:default:` is added when accessing storage.
599 /// Used to derive `ChildInfo` for reading child trie data.
600 /// Usage: let child_info = ChildInfo::new_default(&storage_key);
601 storage_key: Vec<u8>,
602 /// Key within the child trie.
603 key: Vec<u8>,
604 },
605}
606
607/// Request for proving relay chain storage data.
608///
609/// Contains a list of storage keys (either top-level or child trie keys)
610/// to be included in the relay chain state proof.
611#[derive(Clone, Debug, Encode, Decode, TypeInfo, PartialEq, Eq, Default)]
612pub struct RelayProofRequest {
613 /// Storage keys to include in the relay chain state proof.
614 pub keys: Vec<RelayStorageKey>,
615}
616
617sp_api::decl_runtime_apis! {
618 /// Runtime api to collect information about a collation.
619 ///
620 /// Version history:
621 /// - Version 2: Changed [`Self::collect_collation_info`] signature
622 /// - Version 3: Signals to the node to use version 1 of [`ParachainBlockData`].
623 #[api_version(3)]
624 pub trait CollectCollationInfo {
625 /// Collect information about a collation.
626 #[changed_in(2)]
627 fn collect_collation_info() -> CollationInfoV1;
628 /// Collect information about a collation.
629 ///
630 /// The given `header` is the header of the built block for that
631 /// we are collecting the collation info for.
632 fn collect_collation_info(header: &Block::Header) -> CollationInfo;
633 }
634
635 /// Runtime api used to access general info about a parachain runtime.
636 pub trait GetParachainInfo {
637 /// Retrieve the parachain id used for runtime.
638 fn parachain_id() -> ParaId;
639 }
640
641 /// API to tell the node side how the relay parent should be chosen and how claim queue
642 /// offsets are determined.
643 ///
644 /// A larger relay parent offset indicates that the relay parent should not be the tip of
645 /// the relay chain, but `N` blocks behind the tip. This offset is then enforced by the
646 /// runtime.
647 ///
648 /// The max claim queue offset determines how far "into the future" collators target when
649 /// selecting cores from the claim queue. This provides async backing flexibility while
650 /// preventing collators from skipping slots.
651 /// See: <https://github.com/paritytech/polkadot-sdk/issues/8893>
652 ///
653 /// Version history:
654 /// - Version 1: Initial version with `relay_parent_offset` only
655 /// - Version 2: Added `max_claim_queue_offset` method
656 #[api_version(2)]
657 pub trait RelayParentOffsetApi {
658 /// Fetch the relay parent offset that is expected from the relay chain.
659 ///
660 /// This determines how many blocks behind the relay chain tip the relay parent should be.
661 fn relay_parent_offset() -> u32;
662
663 /// Maximum claim queue offset for async backing flexibility.
664 ///
665 /// Bounds how far "into the future" a candidate may look in the claim queue when
666 /// selecting a core. The effective claim queue depth depends on the candidate version:
667 ///
668 /// - **V1/V2 candidates**: the claim queue is looked up at the candidate's `relay_parent`,
669 /// which is `relay_parent_offset` blocks behind the relay-chain tip. The effective
670 /// depth is `relay_parent_offset + max_claim_queue_offset`.
671 ///
672 /// - **V3 candidates**: the claim queue is looked up at the candidate's
673 /// `scheduling_parent` โ the relay-chain block of the *last finished* slot, decoupled
674 /// from the execution-context `relay_parent`. The effective depth is just
675 /// `max_claim_queue_offset`.
676 ///
677 /// Collators select a core via an offset in `[0, max_claim_queue_offset]`.
678 ///
679 /// - **V2 candidates**: `max_claim_queue_offset = 1` is sufficient. The claim queue is
680 /// looked up at `relay_parent`, which sits behind the tip. Offset 0 covers synchronous
681 /// backing in the next relay block; offset 1 covers asynchronous backing in the relay
682 /// block after that.
683 ///
684 /// - **V3 candidates**: offset 0 is not reachable โ the `scheduling_parent`
685 /// is usually the leaf when picked, but its child is already being built, so there is
686 /// no opportunity to land in the next relay block. Offset 1 is reachable under
687 /// synchronous-backing semantics. For elastic scaling the last block in the bundle is
688 /// built near the end of the current slot, which makes offset 1 too tight โ
689 /// `max_claim_queue_offset = 2` is the minimum cap that keeps elastic scaling viable.
690 ///
691 /// Note: this method was added in `api_version = 2`. Collators calling on runtimes that
692 /// only implement `api_version = 1` of [`RelayParentOffsetApi`] will receive an error
693 /// and should fall back to a sensible default (current collator defaults: `1` on the
694 /// V3 path, `0` on the V1/V2 path).
695 ///
696 /// See: <https://github.com/paritytech/polkadot-sdk/issues/8893>
697 #[api_version(2)]
698 fn max_claim_queue_offset() -> u8;
699 }
700
701 /// API to tell the node side whether V3 scheduling is enabled.
702 ///
703 /// When enabled, collators must produce V3 candidates with:
704 /// - ParachainBlockData::V2 containing the scheduling proof
705 /// - CandidateDescriptorV3 with scheduling_parent
706 ///
707 /// This is mutually exclusive with relay parent offset (building on older
708 /// relay parents). A parachain enables V3 when it wants low-latency block
709 /// production with the dual-parent model.
710 pub trait SchedulingV3EnabledApi {
711 /// Returns true if V3 scheduling is enabled for this parachain.
712 fn scheduling_v3_enabled() -> bool;
713 }
714
715 /// API for parachain target block rate.
716 ///
717 /// This runtime API allows the parachain runtime to communicate the target block rate
718 /// to the node side. The target block rate is always valid for the next relay chain slot.
719 ///
720 /// The runtime can not enforce this target block rate. It only acts as a maximum, but not more.
721 /// In the end it depends on the collator how many blocks will be produced. If there are no cores
722 /// available or the collator is offline, no blocks at all will be produced.
723 pub trait TargetBlockRate {
724 /// Get the target block rate for this parachain.
725 ///
726 /// Returns the target number of blocks per relay chain slot.
727 fn target_block_rate() -> u32;
728 }
729
730 /// API for specifying which relay chain storage data to include in storage proofs.
731 ///
732 /// This API allows parachains to request both top-level relay chain storage keys
733 /// and child trie storage keys to be included in the relay chain state proof.
734 pub trait KeyToIncludeInRelayProof {
735 /// Returns relay chain storage proof requests.
736 ///
737 /// The collator will include them in the relay chain proof that is passed alongside the parachain inherent into the runtime.
738 fn keys_to_prove() -> RelayProofRequest;
739 }
740}