referrerpolicy=no-referrer-when-downgrade

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