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