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