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