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::{Decode, DecodeAll, DecodeWithMemTracking, Encode, MaxEncodedLen};
25use polkadot_parachain_primitives::primitives::HeadData;
26use scale_info::TypeInfo;
27use sp_runtime::RuntimeDebug;
28
29pub mod parachain_block_data;
30
31pub use parachain_block_data::ParachainBlockData;
32pub use polkadot_core_primitives::InboundDownwardMessage;
33pub use polkadot_parachain_primitives::primitives::{
34	DmpMessageHandler, Id as ParaId, IsSystem, UpwardMessage, ValidationParams, XcmpMessageFormat,
35	XcmpMessageHandler,
36};
37pub use polkadot_primitives::{
38	vstaging::{ClaimQueueOffset, CoreSelector},
39	AbridgedHostConfiguration, AbridgedHrmpChannel, PersistedValidationData,
40};
41pub use sp_runtime::{
42	generic::{Digest, DigestItem},
43	traits::Block as BlockT,
44	ConsensusEngineId,
45};
46pub use xcm::latest::prelude::*;
47
48/// A module that re-exports relevant relay chain definitions.
49pub mod relay_chain {
50	pub use polkadot_core_primitives::*;
51	pub use polkadot_primitives::*;
52}
53
54/// An inbound HRMP message.
55pub type InboundHrmpMessage = polkadot_primitives::InboundHrmpMessage<relay_chain::BlockNumber>;
56
57/// And outbound HRMP message
58pub type OutboundHrmpMessage = polkadot_primitives::OutboundHrmpMessage<ParaId>;
59
60/// Error description of a message send failure.
61#[derive(Eq, PartialEq, Copy, Clone, RuntimeDebug, Encode, Decode)]
62pub enum MessageSendError {
63	/// The dispatch queue is full.
64	QueueFull,
65	/// There does not exist a channel for sending the message.
66	NoChannel,
67	/// The message is too big to ever fit in a channel.
68	TooBig,
69	/// Some other error.
70	Other,
71	/// There are too many channels open at once.
72	TooManyChannels,
73}
74
75impl From<MessageSendError> for &'static str {
76	fn from(e: MessageSendError) -> Self {
77		use MessageSendError::*;
78		match e {
79			QueueFull => "QueueFull",
80			NoChannel => "NoChannel",
81			TooBig => "TooBig",
82			Other => "Other",
83			TooManyChannels => "TooManyChannels",
84		}
85	}
86}
87
88/// The origin of an inbound message.
89#[derive(
90	Encode, Decode, DecodeWithMemTracking, MaxEncodedLen, Clone, Eq, PartialEq, TypeInfo, Debug,
91)]
92pub enum AggregateMessageOrigin {
93	/// The message came from the para-chain itself.
94	Here,
95	/// The message came from the relay-chain.
96	///
97	/// This is used by the DMP queue.
98	Parent,
99	/// The message came from a sibling para-chain.
100	///
101	/// This is used by the HRMP queue.
102	Sibling(ParaId),
103}
104
105impl From<AggregateMessageOrigin> for Location {
106	fn from(origin: AggregateMessageOrigin) -> Self {
107		match origin {
108			AggregateMessageOrigin::Here => Location::here(),
109			AggregateMessageOrigin::Parent => Location::parent(),
110			AggregateMessageOrigin::Sibling(id) => Location::new(1, Junction::Parachain(id.into())),
111		}
112	}
113}
114
115#[cfg(feature = "runtime-benchmarks")]
116impl From<u32> for AggregateMessageOrigin {
117	fn from(x: u32) -> Self {
118		match x {
119			0 => Self::Here,
120			1 => Self::Parent,
121			p => Self::Sibling(ParaId::from(p)),
122		}
123	}
124}
125
126/// Information about an XCMP channel.
127pub struct ChannelInfo {
128	/// The maximum number of messages that can be pending in the channel at once.
129	pub max_capacity: u32,
130	/// The maximum total size of the messages that can be pending in the channel at once.
131	pub max_total_size: u32,
132	/// The maximum message size that could be put into the channel.
133	pub max_message_size: u32,
134	/// The current number of messages pending in the channel.
135	/// Invariant: should be less or equal to `max_capacity`.s`.
136	pub msg_count: u32,
137	/// The total size in bytes of all message payloads in the channel.
138	/// Invariant: should be less or equal to `max_total_size`.
139	pub total_size: u32,
140}
141
142pub trait GetChannelInfo {
143	fn get_channel_status(id: ParaId) -> ChannelStatus;
144	fn get_channel_info(id: ParaId) -> Option<ChannelInfo>;
145}
146
147/// List all open outgoing channels.
148pub trait ListChannelInfos {
149	fn outgoing_channels() -> Vec<ParaId>;
150}
151
152/// Something that should be called when sending an upward message.
153pub trait UpwardMessageSender {
154	/// Send the given UMP message; return the expected number of blocks before the message will
155	/// be dispatched or an error if the message cannot be sent.
156	/// return the hash of the message sent
157	fn send_upward_message(message: UpwardMessage) -> Result<(u32, XcmHash), MessageSendError>;
158
159	/// Pre-check the given UMP message.
160	fn can_send_upward_message(message: &UpwardMessage) -> Result<(), MessageSendError>;
161
162	/// Ensure `[Self::send_upward_message]` is successful when called in benchmarks/tests.
163	#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
164	fn ensure_successful_delivery() {}
165}
166
167impl UpwardMessageSender for () {
168	fn send_upward_message(_message: UpwardMessage) -> Result<(u32, XcmHash), MessageSendError> {
169		Err(MessageSendError::NoChannel)
170	}
171
172	fn can_send_upward_message(_message: &UpwardMessage) -> Result<(), MessageSendError> {
173		Err(MessageSendError::Other)
174	}
175}
176
177/// The status of a channel.
178pub enum ChannelStatus {
179	/// Channel doesn't exist/has been closed.
180	Closed,
181	/// Channel is completely full right now.
182	Full,
183	/// Channel is ready for sending; the two parameters are the maximum size a valid message may
184	/// have right now, and the maximum size a message may ever have (this will generally have been
185	/// available during message construction, but it's possible the channel parameters changed in
186	/// the meantime).
187	Ready(usize, usize),
188}
189
190/// A means of figuring out what outbound XCMP messages should be being sent.
191pub trait XcmpMessageSource {
192	/// Take a single XCMP message from the queue for the given `dest`, if one exists.
193	fn take_outbound_messages(maximum_channels: usize) -> Vec<(ParaId, Vec<u8>)>;
194}
195
196impl XcmpMessageSource for () {
197	fn take_outbound_messages(_maximum_channels: usize) -> Vec<(ParaId, Vec<u8>)> {
198		Vec::new()
199	}
200}
201
202/// The "quality of service" considerations for message sending.
203#[derive(Eq, PartialEq, Clone, Copy, Encode, Decode, RuntimeDebug)]
204pub enum ServiceQuality {
205	/// Ensure that this message is dispatched in the same relative order as any other messages
206	/// that were also sent with `Ordered`. This only guarantees message ordering on the dispatch
207	/// side, and not necessarily on the execution side.
208	Ordered,
209	/// Ensure that the message is dispatched as soon as possible, which could result in it being
210	/// dispatched before other messages which are larger and/or rely on relative ordering.
211	Fast,
212}
213
214/// A consensus engine ID indicating that this is a Cumulus Parachain.
215pub const CUMULUS_CONSENSUS_ID: ConsensusEngineId = *b"CMLS";
216
217/// Consensus header digests for Cumulus parachains.
218#[derive(Clone, RuntimeDebug, Decode, Encode, PartialEq)]
219pub enum CumulusDigestItem {
220	/// A digest item indicating the relay-parent a parachain block was built against.
221	#[codec(index = 0)]
222	RelayParent(relay_chain::Hash),
223	/// A digest item indicating which core to select on the relay chain for this block.
224	#[codec(index = 1)]
225	SelectCore {
226		/// The selector that determines the actual core.
227		selector: CoreSelector,
228		/// The claim queue offset that determines how far "into the future" the core is selected.
229		claim_queue_offset: ClaimQueueOffset,
230	},
231}
232
233impl CumulusDigestItem {
234	/// Encode this as a Substrate [`DigestItem`].
235	pub fn to_digest_item(&self) -> DigestItem {
236		DigestItem::Consensus(CUMULUS_CONSENSUS_ID, self.encode())
237	}
238
239	/// Find [`CumulusDigestItem::SelectCore`] in the given `digest`.
240	///
241	/// If there are multiple valid digests, this returns the value of the first one, although
242	/// well-behaving runtimes should not produce headers with more than one.
243	pub fn find_select_core(digest: &Digest) -> Option<(CoreSelector, ClaimQueueOffset)> {
244		digest.convert_first(|d| match d {
245			DigestItem::Consensus(id, val) if id == &CUMULUS_CONSENSUS_ID => {
246				let Ok(CumulusDigestItem::SelectCore { selector, claim_queue_offset }) =
247					CumulusDigestItem::decode_all(&mut &val[..])
248				else {
249					return None
250				};
251
252				Some((selector, claim_queue_offset))
253			},
254			_ => None,
255		})
256	}
257}
258
259/// Extract the relay-parent from the provided header digest. Returns `None` if none were found.
260///
261/// If there are multiple valid digests, this returns the value of the first one, although
262/// well-behaving runtimes should not produce headers with more than one.
263pub fn extract_relay_parent(digest: &Digest) -> Option<relay_chain::Hash> {
264	digest.convert_first(|d| match d {
265		DigestItem::Consensus(id, val) if id == &CUMULUS_CONSENSUS_ID =>
266			match CumulusDigestItem::decode(&mut &val[..]) {
267				Ok(CumulusDigestItem::RelayParent(hash)) => Some(hash),
268				_ => None,
269			},
270		_ => None,
271	})
272}
273
274/// Utilities for handling the relay-parent storage root as a digest item.
275///
276/// This is not intended to be part of the public API, as it is a workaround for
277/// <https://github.com/paritytech/cumulus/issues/303> via
278/// <https://github.com/paritytech/polkadot/issues/7191>.
279///
280/// Runtimes using the parachain-system pallet are expected to produce this digest item,
281/// but will stop as soon as they are able to provide the relay-parent hash directly.
282///
283/// The relay-chain storage root is, in practice, a unique identifier of a block
284/// in the absence of equivocations (which are slashable). This assumes that the relay chain
285/// uses BABE or SASSAFRAS, because the slot and the author's VRF randomness are both included
286/// in the relay-chain storage root in both cases.
287///
288/// Therefore, the relay-parent storage root is a suitable identifier of unique relay chain
289/// blocks in low-value scenarios such as performance optimizations.
290#[doc(hidden)]
291pub mod rpsr_digest {
292	use super::{relay_chain, ConsensusEngineId, Decode, Digest, DigestItem, Encode};
293	use codec::Compact;
294
295	/// A consensus engine ID for relay-parent storage root digests.
296	pub const RPSR_CONSENSUS_ID: ConsensusEngineId = *b"RPSR";
297
298	/// Construct a digest item for relay-parent storage roots.
299	pub fn relay_parent_storage_root_item(
300		storage_root: relay_chain::Hash,
301		number: impl Into<Compact<relay_chain::BlockNumber>>,
302	) -> DigestItem {
303		DigestItem::Consensus(RPSR_CONSENSUS_ID, (storage_root, number.into()).encode())
304	}
305
306	/// Extract the relay-parent storage root and number from the provided header digest. Returns
307	/// `None` if none were found.
308	pub fn extract_relay_parent_storage_root(
309		digest: &Digest,
310	) -> Option<(relay_chain::Hash, relay_chain::BlockNumber)> {
311		digest.convert_first(|d| match d {
312			DigestItem::Consensus(id, val) if id == &RPSR_CONSENSUS_ID => {
313				let (h, n): (relay_chain::Hash, Compact<relay_chain::BlockNumber>) =
314					Decode::decode(&mut &val[..]).ok()?;
315
316				Some((h, n.0))
317			},
318			_ => None,
319		})
320	}
321}
322
323/// Information about a collation.
324///
325/// This was used in version 1 of the [`CollectCollationInfo`] runtime api.
326#[derive(Clone, Debug, codec::Decode, codec::Encode, PartialEq)]
327pub struct CollationInfoV1 {
328	/// Messages destined to be interpreted by the Relay chain itself.
329	pub upward_messages: Vec<UpwardMessage>,
330	/// The horizontal messages sent by the parachain.
331	pub horizontal_messages: Vec<OutboundHrmpMessage>,
332	/// New validation code.
333	pub new_validation_code: Option<relay_chain::ValidationCode>,
334	/// The number of messages processed from the DMQ.
335	pub processed_downward_messages: u32,
336	/// The mark which specifies the block number up to which all inbound HRMP messages are
337	/// processed.
338	pub hrmp_watermark: relay_chain::BlockNumber,
339}
340
341impl CollationInfoV1 {
342	/// Convert into the latest version of the [`CollationInfo`] struct.
343	pub fn into_latest(self, head_data: HeadData) -> CollationInfo {
344		CollationInfo {
345			upward_messages: self.upward_messages,
346			horizontal_messages: self.horizontal_messages,
347			new_validation_code: self.new_validation_code,
348			processed_downward_messages: self.processed_downward_messages,
349			hrmp_watermark: self.hrmp_watermark,
350			head_data,
351		}
352	}
353}
354
355/// Information about a collation.
356#[derive(Clone, Debug, codec::Decode, codec::Encode, PartialEq, TypeInfo)]
357pub struct CollationInfo {
358	/// Messages destined to be interpreted by the Relay chain itself.
359	pub upward_messages: Vec<UpwardMessage>,
360	/// The horizontal messages sent by the parachain.
361	pub horizontal_messages: Vec<OutboundHrmpMessage>,
362	/// New validation code.
363	pub new_validation_code: Option<relay_chain::ValidationCode>,
364	/// The number of messages processed from the DMQ.
365	pub processed_downward_messages: u32,
366	/// The mark which specifies the block number up to which all inbound HRMP messages are
367	/// processed.
368	pub hrmp_watermark: relay_chain::BlockNumber,
369	/// The head data, aka encoded header, of the block that corresponds to the collation.
370	pub head_data: HeadData,
371}
372
373sp_api::decl_runtime_apis! {
374	/// Runtime api to collect information about a collation.
375	///
376	/// Version history:
377	/// - Version 2: Changed [`Self::collect_collation_info`] signature
378	/// - Version 3: Signals to the node to use version 1 of [`ParachainBlockData`].
379	#[api_version(3)]
380	pub trait CollectCollationInfo {
381		/// Collect information about a collation.
382		#[changed_in(2)]
383		fn collect_collation_info() -> CollationInfoV1;
384		/// Collect information about a collation.
385		///
386		/// The given `header` is the header of the built block for that
387		/// we are collecting the collation info for.
388		fn collect_collation_info(header: &Block::Header) -> CollationInfo;
389	}
390
391	/// Runtime api used to select the core for which the next block will be built.
392	pub trait GetCoreSelectorApi {
393		/// Retrieve core selector and claim queue offset for the next block.
394		fn core_selector() -> (CoreSelector, ClaimQueueOffset);
395	}
396	/// API to tell the node side how the relay parent should be chosen.
397	///
398	/// A larger offset indicates that the relay parent should not be the tip of the relay chain,
399	/// but `N` blocks behind the tip. This offset is then enforced by the runtime.
400	pub trait RelayParentOffsetApi {
401		/// Fetch the slot offset that is expected from the relay chain.
402		fn relay_parent_offset() -> u32;
403	}
404}