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 sp_runtime::RuntimeDebug;
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, RuntimeDebug, 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 a single XCMP message from the queue for the given `dest`, if one exists.
198	fn take_outbound_messages(maximum_channels: usize) -> Vec<(ParaId, Vec<u8>)>;
199}
200
201impl XcmpMessageSource for () {
202	fn take_outbound_messages(_maximum_channels: usize) -> Vec<(ParaId, Vec<u8>)> {
203		Vec::new()
204	}
205}
206
207/// The "quality of service" considerations for message sending.
208#[derive(Eq, PartialEq, Clone, Copy, Encode, Decode, RuntimeDebug)]
209pub enum ServiceQuality {
210	/// Ensure that this message is dispatched in the same relative order as any other messages
211	/// that were also sent with `Ordered`. This only guarantees message ordering on the dispatch
212	/// side, and not necessarily on the execution side.
213	Ordered,
214	/// Ensure that the message is dispatched as soon as possible, which could result in it being
215	/// dispatched before other messages which are larger and/or rely on relative ordering.
216	Fast,
217}
218
219/// A consensus engine ID indicating that this is a Cumulus Parachain.
220pub const CUMULUS_CONSENSUS_ID: ConsensusEngineId = *b"CMLS";
221
222/// Information about the core on the relay chain this block will be validated on.
223#[derive(Clone, Debug, Decode, Encode, PartialEq, Eq)]
224pub struct CoreInfo {
225	/// The selector that determines the actual core at `claim_queue_offset`.
226	pub selector: CoreSelector,
227	/// The claim queue offset that determines how far "into the future" the core is selected.
228	pub claim_queue_offset: ClaimQueueOffset,
229	/// The number of cores assigned to the parachain at `claim_queue_offset`.
230	pub number_of_cores: Compact<u16>,
231}
232
233/// Return value of [`CumulusDigestItem::core_info_exists_at_max_once`]
234#[derive(Debug, Clone, PartialEq, Eq)]
235pub enum CoreInfoExistsAtMaxOnce {
236	/// Exists exactly once.
237	Once(CoreInfo),
238	/// Not found.
239	NotFound,
240	/// Found more than once.
241	MoreThanOnce,
242}
243
244/// Identifier for a relay chain block used by [`CumulusDigestItem`].
245#[derive(Clone, Debug, PartialEq, Hash, Eq)]
246pub enum RelayBlockIdentifier {
247	/// The block is identified using its block hash.
248	ByHash(relay_chain::Hash),
249	/// The block is identified using its storage root and block number.
250	ByStorageRoot { storage_root: relay_chain::Hash, block_number: relay_chain::BlockNumber },
251}
252
253/// Consensus header digests for Cumulus parachains.
254#[derive(Clone, Debug, Decode, Encode, PartialEq)]
255pub enum CumulusDigestItem {
256	/// A digest item indicating the relay-parent a parachain block was built against.
257	#[codec(index = 0)]
258	RelayParent(relay_chain::Hash),
259	/// A digest item providing information about the core selected on the relay chain for this
260	/// block.
261	#[codec(index = 1)]
262	CoreInfo(CoreInfo),
263}
264
265impl CumulusDigestItem {
266	/// Encode this as a Substrate [`DigestItem`].
267	pub fn to_digest_item(&self) -> DigestItem {
268		match self {
269			Self::RelayParent(_) => DigestItem::Consensus(CUMULUS_CONSENSUS_ID, self.encode()),
270			Self::CoreInfo(_) => DigestItem::PreRuntime(CUMULUS_CONSENSUS_ID, self.encode()),
271		}
272	}
273
274	/// Find [`CumulusDigestItem::CoreInfo`] in the given `digest`.
275	///
276	/// If there are multiple valid digests, this returns the value of the first one.
277	pub fn find_core_info(digest: &Digest) -> Option<CoreInfo> {
278		digest.convert_first(|d| match d {
279			DigestItem::PreRuntime(id, val) if id == &CUMULUS_CONSENSUS_ID => {
280				let Ok(CumulusDigestItem::CoreInfo(core_info)) =
281					CumulusDigestItem::decode_all(&mut &val[..])
282				else {
283					return None
284				};
285
286				Some(core_info)
287			},
288			_ => None,
289		})
290	}
291
292	/// Returns the found [`CoreInfo`] and iff [`Self::CoreInfo`] exists at max once in the given
293	/// `digest`.
294	pub fn core_info_exists_at_max_once(digest: &Digest) -> CoreInfoExistsAtMaxOnce {
295		let mut core_info = None;
296		if digest
297			.logs()
298			.iter()
299			.filter(|l| match l {
300				DigestItem::PreRuntime(CUMULUS_CONSENSUS_ID, d) => {
301					if let Ok(Self::CoreInfo(ci)) = Self::decode_all(&mut &d[..]) {
302						core_info = Some(ci);
303						true
304					} else {
305						false
306					}
307				},
308				_ => false,
309			})
310			.count() <= 1
311		{
312			core_info
313				.map(CoreInfoExistsAtMaxOnce::Once)
314				.unwrap_or(CoreInfoExistsAtMaxOnce::NotFound)
315		} else {
316			CoreInfoExistsAtMaxOnce::MoreThanOnce
317		}
318	}
319
320	/// Returns the [`RelayBlockIdentifier`] from the given `digest`.
321	///
322	/// The identifier corresponds to the relay parent used to build the parachain block.
323	pub fn find_relay_block_identifier(digest: &Digest) -> Option<RelayBlockIdentifier> {
324		digest.convert_first(|d| match d {
325			DigestItem::Consensus(id, val) if id == &CUMULUS_CONSENSUS_ID => {
326				let Ok(CumulusDigestItem::RelayParent(hash)) =
327					CumulusDigestItem::decode_all(&mut &val[..])
328				else {
329					return None
330				};
331
332				Some(RelayBlockIdentifier::ByHash(hash))
333			},
334			DigestItem::Consensus(id, val) if id == &rpsr_digest::RPSR_CONSENSUS_ID => {
335				let Ok((storage_root, block_number)) =
336					rpsr_digest::RpsrType::decode_all(&mut &val[..])
337				else {
338					return None
339				};
340
341				Some(RelayBlockIdentifier::ByStorageRoot {
342					storage_root,
343					block_number: block_number.into(),
344				})
345			},
346			_ => None,
347		})
348	}
349}
350
351///
352/// If there are multiple valid digests, this returns the value of the first one, although
353/// well-behaving runtimes should not produce headers with more than one.
354pub fn extract_relay_parent(digest: &Digest) -> Option<relay_chain::Hash> {
355	digest.convert_first(|d| match d {
356		DigestItem::Consensus(id, val) if id == &CUMULUS_CONSENSUS_ID =>
357			match CumulusDigestItem::decode(&mut &val[..]) {
358				Ok(CumulusDigestItem::RelayParent(hash)) => Some(hash),
359				_ => None,
360			},
361		_ => None,
362	})
363}
364
365/// Utilities for handling the relay-parent storage root as a digest item.
366///
367/// This is not intended to be part of the public API, as it is a workaround for
368/// <https://github.com/paritytech/cumulus/issues/303> via
369/// <https://github.com/paritytech/polkadot/issues/7191>.
370///
371/// Runtimes using the parachain-system pallet are expected to produce this digest item,
372/// but will stop as soon as they are able to provide the relay-parent hash directly.
373///
374/// The relay-chain storage root is, in practice, a unique identifier of a block
375/// in the absence of equivocations (which are slashable). This assumes that the relay chain
376/// uses BABE or SASSAFRAS, because the slot and the author's VRF randomness are both included
377/// in the relay-chain storage root in both cases.
378///
379/// Therefore, the relay-parent storage root is a suitable identifier of unique relay chain
380/// blocks in low-value scenarios such as performance optimizations.
381#[doc(hidden)]
382pub mod rpsr_digest {
383	use super::{relay_chain, ConsensusEngineId, DecodeAll, Digest, DigestItem, Encode};
384	use codec::Compact;
385
386	/// The type used to store the relay-parent storage root and number.
387	pub type RpsrType = (relay_chain::Hash, Compact<relay_chain::BlockNumber>);
388
389	/// A consensus engine ID for relay-parent storage root digests.
390	pub const RPSR_CONSENSUS_ID: ConsensusEngineId = *b"RPSR";
391
392	/// Construct a digest item for relay-parent storage roots.
393	pub fn relay_parent_storage_root_item(
394		storage_root: relay_chain::Hash,
395		number: impl Into<Compact<relay_chain::BlockNumber>>,
396	) -> DigestItem {
397		DigestItem::Consensus(
398			RPSR_CONSENSUS_ID,
399			RpsrType::from((storage_root, number.into())).encode(),
400		)
401	}
402
403	/// Extract the relay-parent storage root and number from the provided header digest. Returns
404	/// `None` if none were found.
405	pub fn extract_relay_parent_storage_root(
406		digest: &Digest,
407	) -> Option<(relay_chain::Hash, relay_chain::BlockNumber)> {
408		digest.convert_first(|d| match d {
409			DigestItem::Consensus(id, val) if id == &RPSR_CONSENSUS_ID => {
410				let (h, n) = RpsrType::decode_all(&mut &val[..]).ok()?;
411
412				Some((h, n.0))
413			},
414			_ => None,
415		})
416	}
417}
418
419/// Information about a collation.
420///
421/// This was used in version 1 of the [`CollectCollationInfo`] runtime api.
422#[derive(Clone, Debug, codec::Decode, codec::Encode, PartialEq)]
423pub struct CollationInfoV1 {
424	/// Messages destined to be interpreted by the Relay chain itself.
425	pub upward_messages: Vec<UpwardMessage>,
426	/// The horizontal messages sent by the parachain.
427	pub horizontal_messages: Vec<OutboundHrmpMessage>,
428	/// New validation code.
429	pub new_validation_code: Option<relay_chain::ValidationCode>,
430	/// The number of messages processed from the DMQ.
431	pub processed_downward_messages: u32,
432	/// The mark which specifies the block number up to which all inbound HRMP messages are
433	/// processed.
434	pub hrmp_watermark: relay_chain::BlockNumber,
435}
436
437impl CollationInfoV1 {
438	/// Convert into the latest version of the [`CollationInfo`] struct.
439	pub fn into_latest(self, head_data: HeadData) -> CollationInfo {
440		CollationInfo {
441			upward_messages: self.upward_messages,
442			horizontal_messages: self.horizontal_messages,
443			new_validation_code: self.new_validation_code,
444			processed_downward_messages: self.processed_downward_messages,
445			hrmp_watermark: self.hrmp_watermark,
446			head_data,
447		}
448	}
449}
450
451/// Information about a collation.
452#[derive(Clone, Debug, codec::Decode, codec::Encode, PartialEq, TypeInfo)]
453pub struct CollationInfo {
454	/// Messages destined to be interpreted by the Relay chain itself.
455	pub upward_messages: Vec<UpwardMessage>,
456	/// The horizontal messages sent by the parachain.
457	pub horizontal_messages: Vec<OutboundHrmpMessage>,
458	/// New validation code.
459	pub new_validation_code: Option<relay_chain::ValidationCode>,
460	/// The number of messages processed from the DMQ.
461	pub processed_downward_messages: u32,
462	/// The mark which specifies the block number up to which all inbound HRMP messages are
463	/// processed.
464	pub hrmp_watermark: relay_chain::BlockNumber,
465	/// The head data, aka encoded header, of the block that corresponds to the collation.
466	pub head_data: HeadData,
467}
468
469sp_api::decl_runtime_apis! {
470	/// Runtime api to collect information about a collation.
471	///
472	/// Version history:
473	/// - Version 2: Changed [`Self::collect_collation_info`] signature
474	/// - Version 3: Signals to the node to use version 1 of [`ParachainBlockData`].
475	#[api_version(3)]
476	pub trait CollectCollationInfo {
477		/// Collect information about a collation.
478		#[changed_in(2)]
479		fn collect_collation_info() -> CollationInfoV1;
480		/// Collect information about a collation.
481		///
482		/// The given `header` is the header of the built block for that
483		/// we are collecting the collation info for.
484		fn collect_collation_info(header: &Block::Header) -> CollationInfo;
485	}
486
487	/// Runtime api used to access general info about a parachain runtime.
488	pub trait GetParachainInfo {
489		/// Retrieve the parachain id used for runtime.
490		fn parachain_id() -> ParaId;
491  }
492
493	/// API to tell the node side how the relay parent should be chosen.
494	///
495	/// A larger offset indicates that the relay parent should not be the tip of the relay chain,
496	/// but `N` blocks behind the tip. This offset is then enforced by the runtime.
497	pub trait RelayParentOffsetApi {
498		/// Fetch the slot offset that is expected from the relay chain.
499		fn relay_parent_offset() -> u32;
500	}
501
502	/// API for parachain target block rate.
503	///
504	/// This runtime API allows the parachain runtime to communicate the target block rate
505	/// to the node side. The target block rate is always valid for the next relay chain slot.
506	///
507	/// The runtime can not enforce this target block rate. It only acts as a maximum, but not more.
508	/// In the end it depends on the collator how many blocks will be produced. If there are no cores
509	/// available or the collator is offline, no blocks at all will be produced.
510	pub trait TargetBlockRate {
511		/// Get the target block rate for this parachain.
512		///
513		/// Returns the target number of blocks per relay chain slot.
514		fn target_block_rate() -> u32;
515	}
516}