referrerpolicy=no-referrer-when-downgrade

polkadot_primitives/v9/
mod.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Polkadot.
3
4// Polkadot is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Polkadot is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.
16
17//! `V9` Primitives.
18
19use alloc::{
20	collections::{BTreeMap, BTreeSet, VecDeque},
21	vec,
22	vec::{IntoIter, Vec},
23};
24
25use bitvec::{field::BitField, prelude::*, slice::BitSlice};
26
27use codec::{Decode, DecodeWithMemTracking, Encode};
28use scale_info::TypeInfo;
29
30use core::{
31	marker::PhantomData,
32	slice::{Iter, IterMut},
33};
34
35#[cfg(feature = "test")]
36use sp_application_crypto::ByteArray;
37use sp_application_crypto::KeyTypeId;
38use sp_arithmetic::{
39	traits::{BaseArithmetic, Saturating},
40	Perbill,
41};
42
43use bounded_collections::BoundedVec;
44use serde::{Deserialize, Serialize};
45use sp_core::ConstU32;
46use sp_inherents::InherentIdentifier;
47
48// ==========
49// PUBLIC RE-EXPORTS
50// ==========
51
52pub use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId;
53pub use sp_consensus_slots::Slot;
54pub use sp_runtime::traits::{AppVerify, BlakeTwo256, Hash as HashT, Header as HeaderT};
55pub use sp_staking::SessionIndex;
56
57// Export some core primitives.
58pub use polkadot_core_primitives::v2::{
59	AccountId, AccountIndex, AccountPublic, Balance, Block, BlockId, BlockNumber, CandidateHash,
60	ChainId, DownwardMessage, Hash, Header, InboundDownwardMessage, InboundHrmpMessage, Moment,
61	Nonce, OutboundHrmpMessage, Remark, Signature, UncheckedExtrinsic,
62};
63
64// Export some polkadot-parachain primitives
65pub use polkadot_parachain_primitives::primitives::{
66	HeadData, HorizontalMessages, HrmpChannelId, Id, Id as ParaId, UpwardMessage, UpwardMessages,
67	ValidationCode, ValidationCodeHash, LOWEST_PUBLIC_ID,
68};
69
70/// Signed data.
71mod signed;
72pub use signed::{EncodeAs, Signed, UncheckedSigned};
73
74pub mod async_backing;
75pub mod executor_params;
76pub mod slashing;
77pub mod speculative;
78pub use speculative::{CommitmentError, RequiresSet, StreamsRoot, MAX_COMMITMENT_ENTRIES};
79
80pub use async_backing::AsyncBackingParams;
81pub use executor_params::{
82	ExecutorHostFunction, ExecutorParam, ExecutorParamError, ExecutorParams, ExecutorParamsHash,
83	ExecutorParamsPrepHash,
84};
85
86mod metrics;
87pub use metrics::{
88	metric_definitions, RuntimeMetricLabel, RuntimeMetricLabelValue, RuntimeMetricLabelValues,
89	RuntimeMetricLabels, RuntimeMetricOp, RuntimeMetricUpdate,
90};
91
92/// The key type ID for a collator key.
93pub const COLLATOR_KEY_TYPE_ID: KeyTypeId = KeyTypeId(*b"coll");
94const LOG_TARGET: &str = "runtime::primitives";
95
96mod collator_app {
97	use sp_application_crypto::{app_crypto, sr25519};
98	app_crypto!(sr25519, super::COLLATOR_KEY_TYPE_ID);
99}
100
101/// Identity that collators use.
102pub type CollatorId = collator_app::Public;
103
104/// A Parachain collator keypair.
105#[cfg(feature = "std")]
106pub type CollatorPair = collator_app::Pair;
107
108/// Signature on candidate's block data by a collator.
109pub type CollatorSignature = collator_app::Signature;
110
111/// The key type ID for a parachain validator key.
112pub const PARACHAIN_KEY_TYPE_ID: KeyTypeId = KeyTypeId(*b"para");
113
114mod validator_app {
115	use sp_application_crypto::{app_crypto, sr25519};
116	app_crypto!(sr25519, super::PARACHAIN_KEY_TYPE_ID);
117}
118
119/// Identity that parachain validators use when signing validation messages.
120///
121/// For now we assert that parachain validator set is exactly equivalent to the authority set, and
122/// so we define it to be the same type as `SessionKey`. In the future it may have different crypto.
123pub type ValidatorId = validator_app::Public;
124
125/// Trait required for type specific indices e.g. `ValidatorIndex` and `GroupIndex`
126pub trait TypeIndex {
127	/// Returns the index associated to this value.
128	fn type_index(&self) -> usize;
129}
130
131/// Index of the validator is used as a lightweight replacement of the `ValidatorId` when
132/// appropriate.
133#[derive(
134	Eq,
135	Ord,
136	PartialEq,
137	PartialOrd,
138	Copy,
139	Clone,
140	Encode,
141	Decode,
142	DecodeWithMemTracking,
143	TypeInfo,
144	Debug,
145)]
146#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Hash))]
147pub struct ValidatorIndex(pub u32);
148
149/// Index of an availability chunk.
150///
151/// The underlying type is identical to `ValidatorIndex`, because
152/// the number of chunks will always be equal to the number of validators.
153/// However, the chunk index held by a validator may not always be equal to its `ValidatorIndex`, so
154/// we use a separate type to make code easier to read.
155#[derive(Eq, Ord, PartialEq, PartialOrd, Copy, Clone, Encode, Decode, TypeInfo, Debug)]
156#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Hash))]
157pub struct ChunkIndex(pub u32);
158
159impl From<ChunkIndex> for ValidatorIndex {
160	fn from(c_index: ChunkIndex) -> Self {
161		ValidatorIndex(c_index.0)
162	}
163}
164
165impl From<ValidatorIndex> for ChunkIndex {
166	fn from(v_index: ValidatorIndex) -> Self {
167		ChunkIndex(v_index.0)
168	}
169}
170
171impl From<u32> for ChunkIndex {
172	fn from(n: u32) -> Self {
173		ChunkIndex(n)
174	}
175}
176
177// We should really get https://github.com/paritytech/polkadot/issues/2403 going ..
178impl From<u32> for ValidatorIndex {
179	fn from(n: u32) -> Self {
180		ValidatorIndex(n)
181	}
182}
183
184impl TypeIndex for ValidatorIndex {
185	fn type_index(&self) -> usize {
186		self.0 as usize
187	}
188}
189
190sp_application_crypto::with_pair! {
191	/// A Parachain validator keypair.
192	pub type ValidatorPair = validator_app::Pair;
193}
194
195/// Signature with which parachain validators sign blocks.
196///
197/// For now we assert that parachain validator set is exactly equivalent to the authority set, and
198/// so we define it to be the same type as `SessionKey`. In the future it may have different crypto.
199pub type ValidatorSignature = validator_app::Signature;
200
201/// A declarations of storage keys where an external observer can find some interesting data.
202pub mod well_known_keys {
203	use super::{HrmpChannelId, Id, WellKnownKey};
204	use alloc::vec::Vec;
205	use codec::Encode as _;
206	use hex_literal::hex;
207	use sp_io::hashing::twox_64;
208
209	// A note on generating these magic values below:
210	//
211	// The `StorageValue`, such as `ACTIVE_CONFIG` was obtained by calling:
212	//
213	//     ActiveConfig::<T>::hashed_key()
214	//
215	// The `StorageMap` values require `prefix`, and for example for `hrmp_egress_channel_index`,
216	// it could be obtained like:
217	//
218	//     HrmpEgressChannelsIndex::<T>::prefix_hash();
219	//
220
221	/// The current epoch index.
222	///
223	/// The storage item should be access as a `u64` encoded value.
224	pub const EPOCH_INDEX: &[u8] =
225		&hex!["1cb6f36e027abb2091cfb5110ab5087f38316cbf8fa0da822a20ac1c55bf1be3"];
226
227	/// The current relay chain block randomness
228	///
229	/// The storage item should be accessed as a `schnorrkel::Randomness` encoded value.
230	pub const CURRENT_BLOCK_RANDOMNESS: &[u8] =
231		&hex!["1cb6f36e027abb2091cfb5110ab5087fd077dfdb8adb10f78f10a5df8742c545"];
232
233	/// The randomness for one epoch ago
234	///
235	/// The storage item should be accessed as a `schnorrkel::Randomness` encoded value.
236	pub const ONE_EPOCH_AGO_RANDOMNESS: &[u8] =
237		&hex!["1cb6f36e027abb2091cfb5110ab5087f7ce678799d3eff024253b90e84927cc6"];
238
239	/// The randomness for two epochs ago
240	///
241	/// The storage item should be accessed as a `schnorrkel::Randomness` encoded value.
242	pub const TWO_EPOCHS_AGO_RANDOMNESS: &[u8] =
243		&hex!["1cb6f36e027abb2091cfb5110ab5087f7a414cb008e0e61e46722aa60abdd672"];
244
245	/// The current slot number.
246	///
247	/// The storage entry should be accessed as a `Slot` encoded value.
248	pub const CURRENT_SLOT: &[u8] =
249		&hex!["1cb6f36e027abb2091cfb5110ab5087f06155b3cd9a8c9e5e9a23fd5dc13a5ed"];
250
251	/// The currently active host configuration.
252	///
253	/// The storage entry should be accessed as an `AbridgedHostConfiguration` encoded value.
254	pub const ACTIVE_CONFIG: &[u8] =
255		&hex!["06de3d8a54d27e44a9d5ce189618f22db4b49d95320d9021994c850f25b8e385"];
256
257	/// The authorities for the current epoch.
258	///
259	/// The storage entry should be accessed as an `Vec<(AuthorityId, BabeAuthorityWeight)>` encoded
260	/// value.
261	pub const AUTHORITIES: &[u8] =
262		&hex!["1cb6f36e027abb2091cfb5110ab5087f5e0621c4869aa60c02be9adcc98a0d1d"];
263
264	/// The authorities for the next epoch.
265	///
266	/// The storage entry should be accessed as an `Vec<(AuthorityId, BabeAuthorityWeight)>` encoded
267	/// value.
268	pub const NEXT_AUTHORITIES: &[u8] =
269		&hex!["1cb6f36e027abb2091cfb5110ab5087faacf00b9b41fda7a9268821c2a2b3e4c"];
270
271	/// Hash of the committed head data for a given registered para.
272	///
273	/// The storage entry stores wrapped `HeadData(Vec<u8>)`.
274	pub fn para_head(para_id: Id) -> Vec<u8> {
275		let prefix = hex!["cd710b30bd2eab0352ddcc26417aa1941b3c252fcb29d88eff4f3de5de4476c3"];
276
277		para_id.using_encoded(|para_id: &[u8]| {
278			prefix
279				.as_ref()
280				.iter()
281				.chain(twox_64(para_id).iter())
282				.chain(para_id.iter())
283				.cloned()
284				.collect()
285		})
286	}
287
288	/// The upward message dispatch queue for the given para id.
289	///
290	/// The storage entry stores a tuple of two values:
291	///
292	/// - `count: u32`, the number of messages currently in the queue for given para,
293	/// - `total_size: u32`, the total size of all messages in the queue.
294	#[deprecated = "Use `relay_dispatch_queue_remaining_capacity` instead"]
295	pub fn relay_dispatch_queue_size(para_id: Id) -> Vec<u8> {
296		let prefix = hex!["f5207f03cfdce586301014700e2c2593fad157e461d71fd4c1f936839a5f1f3e"];
297
298		para_id.using_encoded(|para_id: &[u8]| {
299			prefix
300				.as_ref()
301				.iter()
302				.chain(twox_64(para_id).iter())
303				.chain(para_id.iter())
304				.cloned()
305				.collect()
306		})
307	}
308
309	/// Type safe version of `relay_dispatch_queue_size`.
310	#[deprecated = "Use `relay_dispatch_queue_remaining_capacity` instead"]
311	pub fn relay_dispatch_queue_size_typed(para: Id) -> WellKnownKey<(u32, u32)> {
312		#[allow(deprecated)]
313		relay_dispatch_queue_size(para).into()
314	}
315
316	/// The upward message dispatch queue remaining capacity for the given para id.
317	///
318	/// The storage entry stores a tuple of two values:
319	///
320	/// - `count: u32`, the number of additional messages which may be enqueued for the given para,
321	/// - `total_size: u32`, the total size of additional messages which may be enqueued for the
322	/// given para.
323	pub fn relay_dispatch_queue_remaining_capacity(para_id: Id) -> WellKnownKey<(u32, u32)> {
324		(b":relay_dispatch_queue_remaining_capacity", para_id).encode().into()
325	}
326
327	/// The HRMP channel for the given identifier.
328	///
329	/// The storage entry should be accessed as an `AbridgedHrmpChannel` encoded value.
330	pub fn hrmp_channels(channel: HrmpChannelId) -> Vec<u8> {
331		let prefix = hex!["6a0da05ca59913bc38a8630590f2627cb6604cff828a6e3f579ca6c59ace013d"];
332
333		channel.using_encoded(|channel: &[u8]| {
334			prefix
335				.as_ref()
336				.iter()
337				.chain(twox_64(channel).iter())
338				.chain(channel.iter())
339				.cloned()
340				.collect()
341		})
342	}
343
344	/// The list of inbound channels for the given para.
345	///
346	/// The storage entry stores a `Vec<ParaId>`
347	pub fn hrmp_ingress_channel_index(para_id: Id) -> Vec<u8> {
348		let prefix = hex!["6a0da05ca59913bc38a8630590f2627c1d3719f5b0b12c7105c073c507445948"];
349
350		para_id.using_encoded(|para_id: &[u8]| {
351			prefix
352				.as_ref()
353				.iter()
354				.chain(twox_64(para_id).iter())
355				.chain(para_id.iter())
356				.cloned()
357				.collect()
358		})
359	}
360
361	/// The list of outbound channels for the given para.
362	///
363	/// The storage entry stores a `Vec<ParaId>`
364	pub fn hrmp_egress_channel_index(para_id: Id) -> Vec<u8> {
365		let prefix = hex!["6a0da05ca59913bc38a8630590f2627cf12b746dcf32e843354583c9702cc020"];
366
367		para_id.using_encoded(|para_id: &[u8]| {
368			prefix
369				.as_ref()
370				.iter()
371				.chain(twox_64(para_id).iter())
372				.chain(para_id.iter())
373				.cloned()
374				.collect()
375		})
376	}
377
378	/// The MQC head for the downward message queue of the given para. See more in the `Dmp` module.
379	///
380	/// The storage entry stores a `Hash`. This is polkadot hash which is at the moment
381	/// `blake2b-256`.
382	pub fn dmq_mqc_head(para_id: Id) -> Vec<u8> {
383		let prefix = hex!["63f78c98723ddc9073523ef3beefda0c4d7fefc408aac59dbfe80a72ac8e3ce5"];
384
385		para_id.using_encoded(|para_id: &[u8]| {
386			prefix
387				.as_ref()
388				.iter()
389				.chain(twox_64(para_id).iter())
390				.chain(para_id.iter())
391				.cloned()
392				.collect()
393		})
394	}
395
396	/// The signal that indicates whether the parachain should go-ahead with the proposed validation
397	/// code upgrade.
398	///
399	/// The storage entry stores a value of `UpgradeGoAhead` type.
400	pub fn upgrade_go_ahead_signal(para_id: Id) -> Vec<u8> {
401		let prefix = hex!["cd710b30bd2eab0352ddcc26417aa1949e94c040f5e73d9b7addd6cb603d15d3"];
402
403		para_id.using_encoded(|para_id: &[u8]| {
404			prefix
405				.as_ref()
406				.iter()
407				.chain(twox_64(para_id).iter())
408				.chain(para_id.iter())
409				.cloned()
410				.collect()
411		})
412	}
413
414	/// The signal that indicates whether the parachain is disallowed to signal an upgrade at this
415	/// relay-parent.
416	///
417	/// The storage entry stores a value of `UpgradeRestriction` type.
418	pub fn upgrade_restriction_signal(para_id: Id) -> Vec<u8> {
419		let prefix = hex!["cd710b30bd2eab0352ddcc26417aa194f27bbb460270642b5bcaf032ea04d56a"];
420
421		para_id.using_encoded(|para_id: &[u8]| {
422			prefix
423				.as_ref()
424				.iter()
425				.chain(twox_64(para_id).iter())
426				.chain(para_id.iter())
427				.cloned()
428				.collect()
429		})
430	}
431}
432
433/// Relay chain slot duration in milliseconds, which is the same
434/// value across all networks (e.g. Polkadot, Kusama, Westend, Rococo).
435pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u64 = 6000;
436
437/// Unique identifier for the Parachains Inherent
438pub const PARACHAINS_INHERENT_IDENTIFIER: InherentIdentifier = *b"parachn0";
439
440/// The key type ID for parachain assignment key.
441pub const ASSIGNMENT_KEY_TYPE_ID: KeyTypeId = KeyTypeId(*b"asgn");
442
443/// Compressed or not the wasm blob can never be less than 9 bytes.
444pub const MIN_CODE_SIZE: u32 = 9;
445
446/// Maximum compressed code size we support right now.
447/// At the moment we have runtime upgrade on chain, which restricts scalability severely. If we want
448/// to have bigger values, we should fix that first.
449///
450/// Used for:
451/// * initial genesis for the Parachains configuration
452/// * checking updates to this stored runtime configuration do not exceed this limit
453// NOTE: This value is used in the runtime so be careful when changing it.
454pub const MAX_CODE_SIZE: u32 = 5 * 1024 * 1024;
455
456/// Maximum head data size we support right now.
457///
458/// Used for:
459/// * initial genesis for the Parachains configuration
460/// * checking updates to this stored runtime configuration do not exceed this limit
461// NOTE: This value is used in the runtime so be careful when changing it.
462pub const MAX_HEAD_DATA_SIZE: u32 = 1 * 1024 * 1024;
463
464/// Maximum PoV size we support right now.
465///
466/// Used for:
467/// * initial genesis for the Parachains configuration
468/// * checking updates to this stored runtime configuration do not exceed this limit
469/// * when detecting a PoV decompression bomb in the client
470// NOTE: This value is used in the runtime so be careful when changing it.
471pub const MAX_POV_SIZE: u32 = 10 * 1024 * 1024;
472
473/// Default queue size we use for the on-demand order book.
474///
475/// Can be adjusted in configuration.
476pub const ON_DEMAND_DEFAULT_QUEUE_MAX_SIZE: u32 = 10_000;
477
478/// Maximum for maximum queue size.
479///
480/// We use this value for benchmarking.
481pub const ON_DEMAND_MAX_QUEUE_MAX_SIZE: u32 = 10_000;
482
483/// Backing votes threshold used from the host prior to runtime API version 6 and from the runtime
484/// prior to v9 configuration migration.
485pub const LEGACY_MIN_BACKING_VOTES: u32 = 2;
486
487/// Default value for `SchedulerParams.lookahead`
488pub const DEFAULT_SCHEDULING_LOOKAHEAD: u32 = 3;
489
490// The public key of a keypair used by a validator for determining assignments
491/// to approve included parachain candidates.
492mod assignment_app {
493	use sp_application_crypto::{app_crypto, sr25519};
494	app_crypto!(sr25519, super::ASSIGNMENT_KEY_TYPE_ID);
495}
496
497/// The public key of a keypair used by a validator for determining assignments
498/// to approve included parachain candidates.
499pub type AssignmentId = assignment_app::Public;
500
501sp_application_crypto::with_pair! {
502	/// The full keypair used by a validator for determining assignments to approve included
503	/// parachain candidates.
504	pub type AssignmentPair = assignment_app::Pair;
505}
506
507/// The index of the candidate in the list of candidates fully included as-of the block.
508pub type CandidateIndex = u32;
509
510/// The validation data provides information about how to create the inputs for validation of a
511/// candidate. This information is derived from the chain state and will vary from para to para,
512/// although some fields may be the same for every para.
513///
514/// Since this data is used to form inputs to the validation function, it needs to be persisted by
515/// the availability system to avoid dependence on availability of the relay-chain state.
516///
517/// Furthermore, the validation data acts as a way to authorize the additional data the collator
518/// needs to pass to the validation function. For example, the validation function can check whether
519/// the incoming messages (e.g. downward messages) were actually sent by using the data provided in
520/// the validation data using so called MQC heads.
521///
522/// Since the commitments of the validation function are checked by the relay-chain, secondary
523/// checkers can rely on the invariant that the relay-chain only includes para-blocks for which
524/// these checks have already been done. As such, there is no need for the validation data used to
525/// inform validators and collators about the checks the relay-chain will perform to be persisted by
526/// the availability system.
527///
528/// The `PersistedValidationData` should be relatively lightweight primarily because it is
529/// constructed during inclusion for each candidate and therefore lies on the critical path of
530/// inclusion.
531#[derive(PartialEq, Eq, Clone, Encode, Decode, DecodeWithMemTracking, TypeInfo, Debug)]
532#[cfg_attr(feature = "std", derive(Default))]
533pub struct PersistedValidationData<H = Hash, N = BlockNumber> {
534	/// The parent head-data.
535	pub parent_head: HeadData,
536	/// The relay-chain block number this is in the context of.
537	pub relay_parent_number: N,
538	/// The relay-chain block storage root this is in the context of.
539	pub relay_parent_storage_root: H,
540	/// The maximum legal size of a POV block, in bytes.
541	pub max_pov_size: u32,
542}
543
544impl<H: Encode, N: Encode> PersistedValidationData<H, N> {
545	/// Compute the blake2-256 hash of the persisted validation data.
546	pub fn hash(&self) -> Hash {
547		BlakeTwo256::hash_of(self)
548	}
549}
550
551/// Commitments made in a `CandidateReceipt`. Many of these are outputs of validation.
552#[derive(PartialEq, Eq, Clone, Encode, Decode, DecodeWithMemTracking, TypeInfo, Debug)]
553#[cfg_attr(feature = "std", derive(Default, Hash))]
554pub struct CandidateCommitments<N = BlockNumber> {
555	/// Messages destined to be interpreted by the Relay chain itself.
556	pub upward_messages: UpwardMessages,
557	/// Horizontal messages sent by the parachain.
558	pub horizontal_messages: HorizontalMessages,
559	/// New validation code.
560	pub new_validation_code: Option<ValidationCode>,
561	/// The head-data produced as a result of execution.
562	pub head_data: HeadData,
563	/// The number of messages processed from the DMQ.
564	pub processed_downward_messages: u32,
565	/// The mark which specifies the block number up to which all inbound HRMP messages are
566	/// processed.
567	pub hrmp_watermark: N,
568}
569
570impl CandidateCommitments {
571	/// Compute the blake2-256 hash of the commitments.
572	pub fn hash(&self) -> Hash {
573		BlakeTwo256::hash_of(self)
574	}
575}
576
577/// A bitfield concerning availability of backed candidates.
578///
579/// Every bit refers to an availability core index.
580#[derive(PartialEq, Eq, Clone, Encode, Decode, DecodeWithMemTracking, Debug, TypeInfo)]
581pub struct AvailabilityBitfield(pub BitVec<u8, bitvec::order::Lsb0>);
582
583impl From<BitVec<u8, bitvec::order::Lsb0>> for AvailabilityBitfield {
584	fn from(inner: BitVec<u8, bitvec::order::Lsb0>) -> Self {
585		AvailabilityBitfield(inner)
586	}
587}
588
589/// A signed compact statement, suitable to be sent to the chain.
590pub type SignedStatement = Signed<CompactStatement>;
591/// A signed compact statement, with signature not yet checked.
592pub type UncheckedSignedStatement = UncheckedSigned<CompactStatement>;
593
594/// A bitfield signed by a particular validator about the availability of pending candidates.
595pub type SignedAvailabilityBitfield = Signed<AvailabilityBitfield>;
596/// A signed bitfield with signature not yet checked.
597pub type UncheckedSignedAvailabilityBitfield = UncheckedSigned<AvailabilityBitfield>;
598
599/// A set of signed availability bitfields. Should be sorted by validator index, ascending.
600pub type SignedAvailabilityBitfields = Vec<SignedAvailabilityBitfield>;
601/// A set of unchecked signed availability bitfields. Should be sorted by validator index,
602/// ascending.
603pub type UncheckedSignedAvailabilityBitfields = Vec<UncheckedSignedAvailabilityBitfield>;
604
605/// Verify the backing of the given candidate.
606///
607/// Provide a lookup from the index of a validator within the group assigned to this para,
608/// as opposed to the index of the validator within the overall validator set, as well as
609/// the number of validators in the group.
610///
611/// Also provide the signing context.
612///
613/// Returns either an error, indicating that one of the signatures was invalid or that the index
614/// was out-of-bounds, or the number of signatures checked.
615pub fn check_candidate_backing<H: AsRef<[u8]> + Clone + Encode + core::fmt::Debug>(
616	candidate_hash: CandidateHash,
617	validity_votes: &[ValidityAttestation],
618	validator_indices: &BitSlice<u8, bitvec::order::Lsb0>,
619	signing_context: &SigningContext<H>,
620	group_len: usize,
621	validator_lookup: impl Fn(usize) -> Option<ValidatorId>,
622) -> Result<usize, ()> {
623	if validator_indices.len() != group_len {
624		log::debug!(
625			target: LOG_TARGET,
626			"Check candidate backing: indices mismatch: group_len = {} , indices_len = {}",
627			group_len,
628			validator_indices.len(),
629		);
630		return Err(());
631	}
632
633	if validity_votes.len() > group_len {
634		log::debug!(
635			target: LOG_TARGET,
636			"Check candidate backing: Too many votes, expected: {}, found: {}",
637			group_len,
638			validity_votes.len(),
639		);
640		return Err(());
641	}
642
643	let mut signed = 0;
644	for ((val_in_group_idx, _), attestation) in validator_indices
645		.iter()
646		.enumerate()
647		.filter(|(_, signed)| **signed)
648		.zip(validity_votes.iter())
649	{
650		let validator_id = validator_lookup(val_in_group_idx).ok_or(())?;
651		let payload = attestation.signed_payload(candidate_hash, signing_context);
652		let sig = attestation.signature();
653
654		if sig.verify(&payload[..], &validator_id) {
655			signed += 1;
656		} else {
657			log::debug!(
658				target: LOG_TARGET,
659				"Check candidate backing: Invalid signature. validator_id = {:?}, validator_index = {} ",
660				validator_id,
661				val_in_group_idx,
662			);
663			return Err(());
664		}
665	}
666
667	if signed != validity_votes.len() {
668		log::error!(
669			target: LOG_TARGET,
670			"Check candidate backing: Too many signatures, expected = {}, found = {}",
671			validity_votes.len(),
672			signed,
673		);
674		return Err(());
675	}
676
677	Ok(signed)
678}
679
680/// The unique (during session) index of a core.
681#[derive(
682	Encode,
683	Decode,
684	DecodeWithMemTracking,
685	Default,
686	PartialOrd,
687	Ord,
688	Eq,
689	PartialEq,
690	Clone,
691	Copy,
692	TypeInfo,
693	Debug,
694)]
695#[cfg_attr(feature = "std", derive(Hash))]
696pub struct CoreIndex(pub u32);
697
698impl From<u32> for CoreIndex {
699	fn from(i: u32) -> CoreIndex {
700		CoreIndex(i)
701	}
702}
703
704impl TypeIndex for CoreIndex {
705	fn type_index(&self) -> usize {
706		self.0 as usize
707	}
708}
709
710/// The unique (during session) index of a validator group.
711#[derive(
712	Encode,
713	Decode,
714	DecodeWithMemTracking,
715	Default,
716	Clone,
717	Copy,
718	Debug,
719	PartialEq,
720	Eq,
721	TypeInfo,
722	PartialOrd,
723	Ord,
724)]
725#[cfg_attr(feature = "std", derive(Hash))]
726pub struct GroupIndex(pub u32);
727
728impl From<u32> for GroupIndex {
729	fn from(i: u32) -> GroupIndex {
730		GroupIndex(i)
731	}
732}
733
734impl TypeIndex for GroupIndex {
735	fn type_index(&self) -> usize {
736		self.0 as usize
737	}
738}
739
740/// A claim on authoring the next block for a given parathread (on-demand parachain).
741#[derive(Clone, Encode, Decode, TypeInfo, PartialEq, Debug)]
742pub struct ParathreadClaim(pub Id, pub Option<CollatorId>);
743
744/// An entry tracking a claim to ensure it does not pass the maximum number of retries.
745#[derive(Clone, Encode, Decode, TypeInfo, PartialEq, Debug)]
746pub struct ParathreadEntry {
747	/// The claim.
748	pub claim: ParathreadClaim,
749	/// Number of retries
750	pub retries: u32,
751}
752
753/// A helper data-type for tracking validator-group rotations.
754#[derive(Clone, Encode, Decode, TypeInfo, Debug)]
755#[cfg_attr(feature = "std", derive(PartialEq))]
756pub struct GroupRotationInfo<N = BlockNumber> {
757	/// The block number where the session started.
758	pub session_start_block: N,
759	/// How often groups rotate. 0 means never.
760	pub group_rotation_frequency: N,
761	/// The current block number.
762	pub now: N,
763}
764
765impl GroupRotationInfo {
766	/// Returns the index of the group needed to validate the core at the given index, assuming
767	/// the given number of cores.
768	///
769	/// `core_index` should be less than `cores`, which is capped at `u32::max()`.
770	pub fn group_for_core(&self, core_index: CoreIndex, cores: usize) -> GroupIndex {
771		if self.group_rotation_frequency == 0 {
772			return GroupIndex(core_index.0);
773		}
774		if cores == 0 {
775			return GroupIndex(0);
776		}
777
778		let cores = core::cmp::min(cores, u32::MAX as usize);
779		let blocks_since_start = self.now.saturating_sub(self.session_start_block);
780		let rotations = blocks_since_start / self.group_rotation_frequency;
781
782		// g = c + r mod cores
783
784		let idx = (core_index.0 as usize + rotations as usize) % cores;
785		GroupIndex(idx as u32)
786	}
787
788	/// Returns the index of the group assigned to the given core. This does no checking or
789	/// whether the group index is in-bounds.
790	///
791	/// `core_index` should be less than `cores`, which is capped at `u32::max()`.
792	pub fn core_for_group(&self, group_index: GroupIndex, cores: usize) -> CoreIndex {
793		if self.group_rotation_frequency == 0 {
794			return CoreIndex(group_index.0);
795		}
796		if cores == 0 {
797			return CoreIndex(0);
798		}
799
800		let cores = core::cmp::min(cores, u32::MAX as usize);
801		let blocks_since_start = self.now.saturating_sub(self.session_start_block);
802		let rotations = blocks_since_start / self.group_rotation_frequency;
803		let rotations = rotations % cores as u32;
804
805		// g = c + r mod cores
806		// c = g - r mod cores
807		// x = x + cores mod cores
808		// c = (g + cores) - r mod cores
809
810		let idx = (group_index.0 as usize + cores - rotations as usize) % cores;
811		CoreIndex(idx as u32)
812	}
813
814	/// Create a new `GroupRotationInfo` with one further rotation applied.
815	pub fn bump_rotation(&self) -> Self {
816		GroupRotationInfo {
817			session_start_block: self.session_start_block,
818			group_rotation_frequency: self.group_rotation_frequency,
819			now: self.next_rotation_at(),
820		}
821	}
822}
823
824impl<N: Saturating + BaseArithmetic + Copy> GroupRotationInfo<N> {
825	/// Returns the block number of the next rotation after the current block. If the current block
826	/// is 10 and the rotation frequency is 5, this should return 15.
827	pub fn next_rotation_at(&self) -> N {
828		let cycle_once = self.now + self.group_rotation_frequency;
829		cycle_once -
830			(cycle_once.saturating_sub(self.session_start_block) % self.group_rotation_frequency)
831	}
832
833	/// Returns the block number of the last rotation before or including the current block. If the
834	/// current block is 10 and the rotation frequency is 5, this should return 10.
835	pub fn last_rotation_at(&self) -> N {
836		self.now -
837			(self.now.saturating_sub(self.session_start_block) % self.group_rotation_frequency)
838	}
839}
840
841/// Information about a core which is currently occupied.
842#[derive(Clone, Encode, Decode, TypeInfo, Debug)]
843#[cfg_attr(feature = "std", derive(PartialEq))]
844pub struct ScheduledCore {
845	/// The ID of a para scheduled.
846	pub para_id: Id,
847	/// DEPRECATED: see: <https://github.com/paritytech/polkadot/issues/7575>
848	///
849	/// Will be removed in a future version.
850	pub collator: Option<CollatorId>,
851}
852
853/// An assumption being made about the state of an occupied core.
854#[derive(Clone, Copy, Encode, Decode, TypeInfo, Debug)]
855#[cfg_attr(feature = "std", derive(PartialEq, Eq, Hash))]
856pub enum OccupiedCoreAssumption {
857	/// The candidate occupying the core was made available and included to free the core.
858	#[codec(index = 0)]
859	Included,
860	/// The candidate occupying the core timed out and freed the core without advancing the para.
861	#[codec(index = 1)]
862	TimedOut,
863	/// The core was not occupied to begin with.
864	#[codec(index = 2)]
865	Free,
866}
867
868/// A vote of approval on a candidate.
869#[derive(Clone, Debug)]
870pub struct ApprovalVote(pub CandidateHash);
871
872impl ApprovalVote {
873	/// Yields the signing payload for this approval vote.
874	pub fn signing_payload(&self, session_index: SessionIndex) -> Vec<u8> {
875		const MAGIC: [u8; 4] = *b"APPR";
876
877		(MAGIC, &self.0, session_index).encode()
878	}
879}
880
881/// A vote of approval for multiple candidates.
882#[derive(Clone, Debug)]
883pub struct ApprovalVoteMultipleCandidates<'a>(pub &'a [CandidateHash]);
884
885impl<'a> ApprovalVoteMultipleCandidates<'a> {
886	/// Yields the signing payload for this approval vote.
887	pub fn signing_payload(&self, session_index: SessionIndex) -> Vec<u8> {
888		const MAGIC: [u8; 4] = *b"APPR";
889		// Make this backwards compatible with `ApprovalVote` so if we have just on candidate the
890		// signature will look the same.
891		// This gives us the nice benefit that old nodes can still check signatures when len is 1
892		// and the new node can check the signature coming from old nodes.
893		if self.0.len() == 1 {
894			(MAGIC, self.0.first().expect("QED: we just checked"), session_index).encode()
895		} else {
896			(MAGIC, &self.0, session_index).encode()
897		}
898	}
899}
900
901/// Approval voting configuration parameters
902#[derive(
903	Debug,
904	Copy,
905	Clone,
906	PartialEq,
907	Encode,
908	Decode,
909	DecodeWithMemTracking,
910	TypeInfo,
911	serde::Serialize,
912	serde::Deserialize,
913)]
914pub struct ApprovalVotingParams {
915	/// The maximum number of candidates `approval-voting` can vote for with
916	/// a single signatures.
917	///
918	/// Setting it to 1, means we send the approval as soon as we have it available.
919	pub max_approval_coalesce_count: u32,
920}
921
922impl Default for ApprovalVotingParams {
923	fn default() -> Self {
924		Self { max_approval_coalesce_count: 1 }
925	}
926}
927
928/// Custom validity errors used in Polkadot while validating transactions.
929#[repr(u8)]
930pub enum ValidityError {
931	/// The Ethereum signature is invalid.
932	InvalidEthereumSignature = 0,
933	/// The signer has no claim.
934	SignerHasNoClaim = 1,
935	/// No permission to execute the call.
936	NoPermission = 2,
937	/// An invalid statement was made for a claim.
938	InvalidStatement = 3,
939}
940
941impl From<ValidityError> for u8 {
942	fn from(err: ValidityError) -> Self {
943		err as u8
944	}
945}
946
947/// Abridged version of `HostConfiguration` (from the `Configuration` parachains host runtime
948/// module) meant to be used by a parachain or PDK such as cumulus.
949#[derive(Clone, Encode, Decode, Debug, TypeInfo)]
950#[cfg_attr(feature = "std", derive(PartialEq))]
951pub struct AbridgedHostConfiguration {
952	/// The maximum validation code size, in bytes.
953	pub max_code_size: u32,
954	/// The maximum head-data size, in bytes.
955	pub max_head_data_size: u32,
956	/// Total number of individual messages allowed in the parachain -> relay-chain message queue.
957	pub max_upward_queue_count: u32,
958	/// Total size of messages allowed in the parachain -> relay-chain message queue before which
959	/// no further messages may be added to it. If it exceeds this then the queue may contain only
960	/// a single message.
961	pub max_upward_queue_size: u32,
962	/// The maximum size of an upward message that can be sent by a candidate.
963	///
964	/// This parameter affects the size upper bound of the `CandidateCommitments`.
965	pub max_upward_message_size: u32,
966	/// The maximum number of messages that a candidate can contain.
967	///
968	/// This parameter affects the size upper bound of the `CandidateCommitments`.
969	pub max_upward_message_num_per_candidate: u32,
970	/// The maximum number of outbound HRMP messages can be sent by a candidate.
971	///
972	/// This parameter affects the upper bound of size of `CandidateCommitments`.
973	pub hrmp_max_message_num_per_candidate: u32,
974	/// The minimum period, in blocks, between which parachains can update their validation code.
975	pub validation_upgrade_cooldown: BlockNumber,
976	/// The delay, in blocks, before a validation upgrade is applied.
977	pub validation_upgrade_delay: BlockNumber,
978	/// Asynchronous backing parameters.
979	pub async_backing_params: AsyncBackingParams,
980}
981
982/// Abridged version of `HrmpChannel` (from the `Hrmp` parachains host runtime module) meant to be
983/// used by a parachain or PDK such as cumulus.
984#[derive(Clone, Encode, Decode, Debug, TypeInfo)]
985#[cfg_attr(feature = "std", derive(Default, PartialEq))]
986pub struct AbridgedHrmpChannel {
987	/// The maximum number of messages that can be pending in the channel at once.
988	pub max_capacity: u32,
989	/// The maximum total size of the messages that can be pending in the channel at once.
990	pub max_total_size: u32,
991	/// The maximum message size that could be put into the channel.
992	pub max_message_size: u32,
993	/// The current number of messages pending in the channel.
994	/// Invariant: should be less or equal to `max_capacity`.s`.
995	pub msg_count: u32,
996	/// The total size in bytes of all message payloads in the channel.
997	/// Invariant: should be less or equal to `max_total_size`.
998	pub total_size: u32,
999	/// A head of the Message Queue Chain for this channel. Each link in this chain has a form:
1000	/// `(prev_head, B, H(M))`, where
1001	/// - `prev_head`: is the previous value of `mqc_head` or zero if none.
1002	/// - `B`: is the [relay-chain] block number in which a message was appended
1003	/// - `H(M)`: is the hash of the message being appended.
1004	/// This value is initialized to a special value that consists of all zeroes which indicates
1005	/// that no messages were previously added.
1006	pub mqc_head: Option<Hash>,
1007}
1008
1009/// A possible upgrade restriction that prevents a parachain from performing an upgrade.
1010#[derive(Copy, Clone, Encode, Decode, PartialEq, Debug, TypeInfo)]
1011pub enum UpgradeRestriction {
1012	/// There is an upgrade restriction and there are no details about its specifics nor how long
1013	/// it could last.
1014	#[codec(index = 0)]
1015	Present,
1016}
1017
1018/// A struct that the relay-chain communicates to a parachain indicating what course of action the
1019/// parachain should take in the coordinated parachain validation code upgrade process.
1020///
1021/// This data type appears in the last step of the upgrade process. After the parachain observes it
1022/// and reacts to it the upgrade process concludes.
1023#[derive(Copy, Clone, Encode, Decode, PartialEq, Debug, TypeInfo)]
1024pub enum UpgradeGoAhead {
1025	/// Abort the upgrade process. There is something wrong with the validation code previously
1026	/// submitted by the parachain. This variant can also be used to prevent upgrades by the
1027	/// governance should an emergency emerge.
1028	///
1029	/// The expected reaction on this variant is that the parachain will admit this message and
1030	/// remove all the data about the pending upgrade. Depending on the nature of the problem (to
1031	/// be examined offchain for now), it can try to send another validation code or just retry
1032	/// later.
1033	#[codec(index = 0)]
1034	Abort,
1035	/// Apply the pending code change. The parablock that is built on a relay-parent that is
1036	/// descendant of the relay-parent where the parachain observed this signal must use the
1037	/// upgraded validation code.
1038	#[codec(index = 1)]
1039	GoAhead,
1040}
1041
1042/// Consensus engine id for polkadot v1 consensus engine.
1043pub const POLKADOT_ENGINE_ID: sp_runtime::ConsensusEngineId = *b"POL1";
1044
1045/// A consensus log item for polkadot validation. To be used with [`POLKADOT_ENGINE_ID`].
1046#[derive(Decode, Encode, Clone, PartialEq, Eq)]
1047pub enum ConsensusLog {
1048	/// A parachain upgraded its code.
1049	#[codec(index = 1)]
1050	ParaUpgradeCode(Id, ValidationCodeHash),
1051	/// A parachain scheduled a code upgrade.
1052	#[codec(index = 2)]
1053	ParaScheduleUpgradeCode(Id, ValidationCodeHash, BlockNumber),
1054	/// Governance requests to auto-approve every candidate included up to the given block
1055	/// number in the current chain, inclusive.
1056	#[codec(index = 3)]
1057	ForceApprove(BlockNumber),
1058	/// A signal to revert the block number in the same chain as the
1059	/// header this digest is part of and all of its descendants.
1060	///
1061	/// It is a no-op for a block to contain a revert digest targeting
1062	/// its own number or a higher number.
1063	///
1064	/// In practice, these are issued when on-chain logic has detected an
1065	/// invalid parachain block within its own chain, due to a dispute.
1066	#[codec(index = 4)]
1067	Revert(BlockNumber),
1068}
1069
1070impl ConsensusLog {
1071	/// Attempt to convert a reference to a generic digest item into a consensus log.
1072	pub fn from_digest_item(
1073		digest_item: &sp_runtime::DigestItem,
1074	) -> Result<Option<Self>, codec::Error> {
1075		match digest_item {
1076			sp_runtime::DigestItem::Consensus(id, encoded) if id == &POLKADOT_ENGINE_ID => {
1077				Ok(Some(Self::decode(&mut &encoded[..])?))
1078			},
1079			_ => Ok(None),
1080		}
1081	}
1082}
1083
1084impl From<ConsensusLog> for sp_runtime::DigestItem {
1085	fn from(c: ConsensusLog) -> sp_runtime::DigestItem {
1086		Self::Consensus(POLKADOT_ENGINE_ID, c.encode())
1087	}
1088}
1089
1090/// A statement about a candidate, to be used within the dispute resolution process.
1091///
1092/// Statements are either in favor of the candidate's validity or against it.
1093#[derive(Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Debug, TypeInfo)]
1094pub enum DisputeStatement {
1095	/// A valid statement, of the given kind.
1096	#[codec(index = 0)]
1097	Valid(ValidDisputeStatementKind),
1098	/// An invalid statement, of the given kind.
1099	#[codec(index = 1)]
1100	Invalid(InvalidDisputeStatementKind),
1101}
1102
1103impl DisputeStatement {
1104	/// Get the payload data for this type of dispute statement.
1105	///
1106	/// Returns Error if the candidate_hash is not included in the list of signed
1107	/// candidate from ApprovalCheckingMultipleCandidate.
1108	pub fn payload_data(
1109		&self,
1110		candidate_hash: CandidateHash,
1111		session: SessionIndex,
1112	) -> Result<Vec<u8>, ()> {
1113		match self {
1114			DisputeStatement::Valid(ValidDisputeStatementKind::Explicit) => {
1115				Ok(ExplicitDisputeStatement { valid: true, candidate_hash, session }
1116					.signing_payload())
1117			},
1118			DisputeStatement::Valid(ValidDisputeStatementKind::BackingSeconded(
1119				inclusion_parent,
1120			)) => Ok(CompactStatement::Seconded(candidate_hash).signing_payload(&SigningContext {
1121				session_index: session,
1122				parent_hash: *inclusion_parent,
1123			})),
1124			DisputeStatement::Valid(ValidDisputeStatementKind::BackingValid(inclusion_parent)) => {
1125				Ok(CompactStatement::Valid(candidate_hash).signing_payload(&SigningContext {
1126					session_index: session,
1127					parent_hash: *inclusion_parent,
1128				}))
1129			},
1130			DisputeStatement::Valid(ValidDisputeStatementKind::ApprovalChecking) => {
1131				Ok(ApprovalVote(candidate_hash).signing_payload(session))
1132			},
1133			DisputeStatement::Valid(
1134				ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates(candidate_hashes),
1135			) => {
1136				if candidate_hashes.contains(&candidate_hash) {
1137					Ok(ApprovalVoteMultipleCandidates(candidate_hashes).signing_payload(session))
1138				} else {
1139					Err(())
1140				}
1141			},
1142			DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit) => {
1143				Ok(ExplicitDisputeStatement { valid: false, candidate_hash, session }
1144					.signing_payload())
1145			},
1146		}
1147	}
1148
1149	/// Check the signature on a dispute statement.
1150	pub fn check_signature(
1151		&self,
1152		validator_public: &ValidatorId,
1153		candidate_hash: CandidateHash,
1154		session: SessionIndex,
1155		validator_signature: &ValidatorSignature,
1156	) -> Result<(), ()> {
1157		let payload = self.payload_data(candidate_hash, session)?;
1158
1159		if validator_signature.verify(&payload[..], &validator_public) {
1160			Ok(())
1161		} else {
1162			Err(())
1163		}
1164	}
1165
1166	/// Whether the statement indicates validity.
1167	pub fn indicates_validity(&self) -> bool {
1168		match *self {
1169			DisputeStatement::Valid(_) => true,
1170			DisputeStatement::Invalid(_) => false,
1171		}
1172	}
1173
1174	/// Whether the statement indicates invalidity.
1175	pub fn indicates_invalidity(&self) -> bool {
1176		match *self {
1177			DisputeStatement::Valid(_) => false,
1178			DisputeStatement::Invalid(_) => true,
1179		}
1180	}
1181
1182	/// Statement is backing statement.
1183	pub fn is_backing(&self) -> bool {
1184		match self {
1185			Self::Valid(s) => s.is_backing(),
1186			Self::Invalid(_) => false,
1187		}
1188	}
1189}
1190
1191/// The maximum number of candidate approvals that can be coalesced into a single
1192/// [`ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates`] statement (and the
1193/// corresponding approval vote). It is a hard, type-level ceiling enforced at decode time, and the
1194/// maximum value the runtime accepts for `max_approval_coalesce_count`.
1195pub const MAX_COALESCE_APPROVALS: u32 = 16;
1196
1197/// The candidate hashes coalesced into a single approval vote, bounded at the type level to at most
1198/// [`MAX_COALESCE_APPROVALS`]. Used to carry coalesced approval signatures between subsystems while
1199/// preserving that bound.
1200pub type CoalescedApprovalCandidateHashes =
1201	BoundedVec<CandidateHash, ConstU32<{ MAX_COALESCE_APPROVALS }>>;
1202
1203/// Different kinds of statements of validity on  a candidate.
1204#[derive(Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Debug, TypeInfo)]
1205pub enum ValidDisputeStatementKind {
1206	/// An explicit statement issued as part of a dispute.
1207	#[codec(index = 0)]
1208	Explicit,
1209	/// A seconded statement on a candidate from the backing phase.
1210	#[codec(index = 1)]
1211	BackingSeconded(Hash),
1212	/// A valid statement on a candidate from the backing phase.
1213	#[codec(index = 2)]
1214	BackingValid(Hash),
1215	/// An approval vote from the approval checking phase.
1216	#[codec(index = 3)]
1217	ApprovalChecking,
1218	/// An approval vote from the new version.
1219	/// We can't create this version until all nodes
1220	/// have been updated to support it and max_approval_coalesce_count
1221	/// is set to more than 1.
1222	///
1223	/// The number of coalesced candidates is bounded at the type level to at most
1224	/// [`MAX_COALESCE_APPROVALS`]. This is a hard ceiling enforced at decode time; the effective
1225	/// per-session limit is `max_approval_coalesce_count`, enforced dynamically when the statement
1226	/// is validated.
1227	#[codec(index = 4)]
1228	ApprovalCheckingMultipleCandidates(
1229		BoundedVec<CandidateHash, ConstU32<{ MAX_COALESCE_APPROVALS }>>,
1230	),
1231}
1232
1233impl ValidDisputeStatementKind {
1234	/// Whether the statement is from the backing phase.
1235	pub fn is_backing(&self) -> bool {
1236		match self {
1237			ValidDisputeStatementKind::BackingSeconded(_) |
1238			ValidDisputeStatementKind::BackingValid(_) => true,
1239			ValidDisputeStatementKind::Explicit |
1240			ValidDisputeStatementKind::ApprovalChecking |
1241			ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates(_) => false,
1242		}
1243	}
1244}
1245
1246/// Different kinds of statements of invalidity on a candidate.
1247#[derive(Encode, Decode, DecodeWithMemTracking, Copy, Clone, PartialEq, Debug, TypeInfo)]
1248pub enum InvalidDisputeStatementKind {
1249	/// An explicit statement issued as part of a dispute.
1250	#[codec(index = 0)]
1251	Explicit,
1252}
1253
1254/// An explicit statement on a candidate issued as part of a dispute.
1255#[derive(Clone, PartialEq, Debug)]
1256pub struct ExplicitDisputeStatement {
1257	/// Whether the candidate is valid
1258	pub valid: bool,
1259	/// The candidate hash.
1260	pub candidate_hash: CandidateHash,
1261	/// The session index of the candidate.
1262	pub session: SessionIndex,
1263}
1264
1265impl ExplicitDisputeStatement {
1266	/// Produce the payload used for signing this type of statement.
1267	pub fn signing_payload(&self) -> Vec<u8> {
1268		const MAGIC: [u8; 4] = *b"DISP";
1269
1270		(MAGIC, self.valid, self.candidate_hash, self.session).encode()
1271	}
1272}
1273
1274/// A set of statements about a specific candidate.
1275#[derive(Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Debug, TypeInfo)]
1276pub struct DisputeStatementSet {
1277	/// The candidate referenced by this set.
1278	pub candidate_hash: CandidateHash,
1279	/// The session index of the candidate.
1280	pub session: SessionIndex,
1281	/// Statements about the candidate.
1282	pub statements: Vec<(DisputeStatement, ValidatorIndex, ValidatorSignature)>,
1283}
1284
1285impl From<CheckedDisputeStatementSet> for DisputeStatementSet {
1286	fn from(other: CheckedDisputeStatementSet) -> Self {
1287		other.0
1288	}
1289}
1290
1291impl AsRef<DisputeStatementSet> for DisputeStatementSet {
1292	fn as_ref(&self) -> &DisputeStatementSet {
1293		&self
1294	}
1295}
1296
1297/// A set of dispute statements.
1298pub type MultiDisputeStatementSet = Vec<DisputeStatementSet>;
1299
1300/// A _checked_ set of dispute statements.
1301#[derive(Clone, PartialEq, Debug, Encode)]
1302pub struct CheckedDisputeStatementSet(DisputeStatementSet);
1303
1304impl AsRef<DisputeStatementSet> for CheckedDisputeStatementSet {
1305	fn as_ref(&self) -> &DisputeStatementSet {
1306		&self.0
1307	}
1308}
1309
1310impl core::cmp::PartialEq<DisputeStatementSet> for CheckedDisputeStatementSet {
1311	fn eq(&self, other: &DisputeStatementSet) -> bool {
1312		self.0.eq(other)
1313	}
1314}
1315
1316impl CheckedDisputeStatementSet {
1317	/// Convert from an unchecked, the verification of correctness of the `unchecked` statement set
1318	/// _must_ be done before calling this function!
1319	pub fn unchecked_from_unchecked(unchecked: DisputeStatementSet) -> Self {
1320		Self(unchecked)
1321	}
1322}
1323
1324/// A set of _checked_ dispute statements.
1325pub type CheckedMultiDisputeStatementSet = Vec<CheckedDisputeStatementSet>;
1326
1327/// The entire state of a dispute.
1328#[derive(Encode, Decode, Clone, Debug, PartialEq, TypeInfo)]
1329pub struct DisputeState<N = BlockNumber> {
1330	/// A bitfield indicating all validators for the candidate.
1331	pub validators_for: BitVec<u8, bitvec::order::Lsb0>, // one bit per validator.
1332	/// A bitfield indicating all validators against the candidate.
1333	pub validators_against: BitVec<u8, bitvec::order::Lsb0>, // one bit per validator.
1334	/// The block number at which the dispute started on-chain.
1335	pub start: N,
1336	/// The block number at which the dispute concluded on-chain.
1337	pub concluded_at: Option<N>,
1338}
1339
1340/// An either implicit or explicit attestation to the validity of a parachain
1341/// candidate.
1342#[derive(Clone, Eq, PartialEq, Decode, DecodeWithMemTracking, Encode, Debug, TypeInfo)]
1343pub enum ValidityAttestation {
1344	/// Implicit validity attestation by issuing.
1345	/// This corresponds to issuance of a `Candidate` statement.
1346	#[codec(index = 1)]
1347	Implicit(ValidatorSignature),
1348	/// An explicit attestation. This corresponds to issuance of a
1349	/// `Valid` statement.
1350	#[codec(index = 2)]
1351	Explicit(ValidatorSignature),
1352}
1353
1354impl ValidityAttestation {
1355	/// Produce the underlying signed payload of the attestation, given the hash of the candidate,
1356	/// which should be known in context.
1357	pub fn to_compact_statement(&self, candidate_hash: CandidateHash) -> CompactStatement {
1358		// Explicit and implicit map directly from
1359		// `ValidityVote::Valid` and `ValidityVote::Issued`, and hence there is a
1360		// `1:1` relationship which enables the conversion.
1361		match *self {
1362			ValidityAttestation::Implicit(_) => CompactStatement::Seconded(candidate_hash),
1363			ValidityAttestation::Explicit(_) => CompactStatement::Valid(candidate_hash),
1364		}
1365	}
1366
1367	/// Get a reference to the signature.
1368	pub fn signature(&self) -> &ValidatorSignature {
1369		match *self {
1370			ValidityAttestation::Implicit(ref sig) => sig,
1371			ValidityAttestation::Explicit(ref sig) => sig,
1372		}
1373	}
1374
1375	/// Produce the underlying signed payload of the attestation, given the hash of the candidate,
1376	/// which should be known in context.
1377	pub fn signed_payload<H: Encode>(
1378		&self,
1379		candidate_hash: CandidateHash,
1380		signing_context: &SigningContext<H>,
1381	) -> Vec<u8> {
1382		match *self {
1383			ValidityAttestation::Implicit(_) => {
1384				(CompactStatement::Seconded(candidate_hash), signing_context).encode()
1385			},
1386			ValidityAttestation::Explicit(_) => {
1387				(CompactStatement::Valid(candidate_hash), signing_context).encode()
1388			},
1389		}
1390	}
1391}
1392
1393/// A type returned by runtime with current session index and a parent hash.
1394#[derive(Clone, Eq, PartialEq, Default, Decode, Encode, Debug)]
1395pub struct SigningContext<H = Hash> {
1396	/// Current session index.
1397	pub session_index: sp_staking::SessionIndex,
1398	/// Hash of the parent.
1399	pub parent_hash: H,
1400}
1401
1402const BACKING_STATEMENT_MAGIC: [u8; 4] = *b"BKNG";
1403
1404/// Statements that can be made about parachain candidates. These are the
1405/// actual values that are signed.
1406#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
1407#[cfg_attr(feature = "std", derive(Hash))]
1408pub enum CompactStatement {
1409	/// Proposal of a parachain candidate.
1410	Seconded(CandidateHash),
1411	/// State that a parachain candidate is valid.
1412	Valid(CandidateHash),
1413}
1414
1415impl CompactStatement {
1416	/// Yields the payload used for validator signatures on this kind
1417	/// of statement.
1418	pub fn signing_payload(&self, context: &SigningContext) -> Vec<u8> {
1419		(self, context).encode()
1420	}
1421
1422	/// Get the underlying candidate hash this references.
1423	pub fn candidate_hash(&self) -> &CandidateHash {
1424		match *self {
1425			CompactStatement::Seconded(ref h) | CompactStatement::Valid(ref h) => h,
1426		}
1427	}
1428}
1429
1430// Inner helper for codec on `CompactStatement`.
1431#[derive(Encode, Decode, TypeInfo)]
1432enum CompactStatementInner {
1433	#[codec(index = 1)]
1434	Seconded(CandidateHash),
1435	#[codec(index = 2)]
1436	Valid(CandidateHash),
1437}
1438
1439impl From<CompactStatement> for CompactStatementInner {
1440	fn from(s: CompactStatement) -> Self {
1441		match s {
1442			CompactStatement::Seconded(h) => CompactStatementInner::Seconded(h),
1443			CompactStatement::Valid(h) => CompactStatementInner::Valid(h),
1444		}
1445	}
1446}
1447
1448impl codec::Encode for CompactStatement {
1449	fn size_hint(&self) -> usize {
1450		// magic + discriminant + payload
1451		4 + 1 + 32
1452	}
1453
1454	fn encode_to<T: codec::Output + ?Sized>(&self, dest: &mut T) {
1455		dest.write(&BACKING_STATEMENT_MAGIC);
1456		CompactStatementInner::from(self.clone()).encode_to(dest)
1457	}
1458}
1459
1460impl codec::Decode for CompactStatement {
1461	fn decode<I: codec::Input>(input: &mut I) -> Result<Self, codec::Error> {
1462		let maybe_magic = <[u8; 4]>::decode(input)?;
1463		if maybe_magic != BACKING_STATEMENT_MAGIC {
1464			return Err(codec::Error::from("invalid magic string"));
1465		}
1466
1467		Ok(match CompactStatementInner::decode(input)? {
1468			CompactStatementInner::Seconded(h) => CompactStatement::Seconded(h),
1469			CompactStatementInner::Valid(h) => CompactStatement::Valid(h),
1470		})
1471	}
1472}
1473
1474/// `IndexedVec` struct indexed by type specific indices.
1475#[derive(Clone, Encode, Decode, Debug, TypeInfo)]
1476#[cfg_attr(feature = "std", derive(PartialEq))]
1477pub struct IndexedVec<K, V>(Vec<V>, PhantomData<fn(K) -> K>);
1478
1479impl<K, V> Default for IndexedVec<K, V> {
1480	fn default() -> Self {
1481		Self(vec![], PhantomData)
1482	}
1483}
1484
1485impl<K, V> From<Vec<V>> for IndexedVec<K, V> {
1486	fn from(validators: Vec<V>) -> Self {
1487		Self(validators, PhantomData)
1488	}
1489}
1490
1491impl<K, V> FromIterator<V> for IndexedVec<K, V> {
1492	fn from_iter<T: IntoIterator<Item = V>>(iter: T) -> Self {
1493		Self(Vec::from_iter(iter), PhantomData)
1494	}
1495}
1496
1497impl<K, V> IndexedVec<K, V>
1498where
1499	V: Clone,
1500{
1501	/// Returns a reference to an element indexed using `K`.
1502	pub fn get(&self, index: K) -> Option<&V>
1503	where
1504		K: TypeIndex,
1505	{
1506		self.0.get(index.type_index())
1507	}
1508
1509	/// Returns a mutable reference to an element indexed using `K`.
1510	pub fn get_mut(&mut self, index: K) -> Option<&mut V>
1511	where
1512		K: TypeIndex,
1513	{
1514		self.0.get_mut(index.type_index())
1515	}
1516
1517	/// Returns number of elements in vector.
1518	pub fn len(&self) -> usize {
1519		self.0.len()
1520	}
1521
1522	/// Returns contained vector.
1523	pub fn to_vec(&self) -> Vec<V> {
1524		self.0.clone()
1525	}
1526
1527	/// Returns an iterator over the underlying vector.
1528	pub fn iter(&self) -> Iter<'_, V> {
1529		self.0.iter()
1530	}
1531
1532	/// Returns a mutable iterator over the underlying vector.
1533	pub fn iter_mut(&mut self) -> IterMut<'_, V> {
1534		self.0.iter_mut()
1535	}
1536
1537	/// Creates a consuming iterator.
1538	pub fn into_iter(self) -> IntoIter<V> {
1539		self.0.into_iter()
1540	}
1541
1542	/// Returns true if the underlying container is empty.
1543	pub fn is_empty(&self) -> bool {
1544		self.0.is_empty()
1545	}
1546}
1547
1548/// The maximum number of validators `f` which may safely be faulty.
1549///
1550/// The total number of validators is `n = 3f + e` where `e in { 1, 2, 3 }`.
1551pub const fn byzantine_threshold(n: usize) -> usize {
1552	n.saturating_sub(1) / 3
1553}
1554
1555/// The supermajority threshold of validators which represents a subset
1556/// guaranteed to have at least f+1 honest validators.
1557pub const fn supermajority_threshold(n: usize) -> usize {
1558	n - byzantine_threshold(n)
1559}
1560
1561/// Adjust the configured needed backing votes with the size of the backing group.
1562pub fn effective_minimum_backing_votes(
1563	group_len: usize,
1564	configured_minimum_backing_votes: u32,
1565) -> usize {
1566	core::cmp::min(group_len, configured_minimum_backing_votes as usize)
1567}
1568
1569/// Information about validator sets of a session.
1570///
1571/// NOTE: `SessionInfo` is frozen. Do not include new fields, consider creating a separate runtime
1572/// API. Reasoning and further outlook [here](https://github.com/paritytech/polkadot/issues/6586).
1573#[derive(Clone, Encode, Decode, Debug, TypeInfo)]
1574#[cfg_attr(feature = "std", derive(PartialEq))]
1575pub struct SessionInfo {
1576	/// **** New in v2 ******
1577	/// All the validators actively participating in parachain consensus.
1578	/// Indices are into the broader validator set.
1579	pub active_validator_indices: Vec<ValidatorIndex>,
1580	/// A secure random seed for the session, gathered from BABE.
1581	pub random_seed: [u8; 32],
1582	/// The amount of sessions to keep for disputes.
1583	pub dispute_period: SessionIndex,
1584
1585	/// **** Old fields *****
1586	/// Validators in canonical ordering.
1587	///
1588	/// NOTE: There might be more authorities in the current session, than `validators`
1589	/// participating in parachain consensus. See
1590	/// [`max_validators`](https://github.com/paritytech/polkadot/blob/a52dca2be7840b23c19c153cf7e110b1e3e475f8/runtime/parachains/src/configuration.rs#L148).
1591	///
1592	/// `SessionInfo::validators` will be limited to `max_validators` when set.
1593	pub validators: IndexedVec<ValidatorIndex, ValidatorId>,
1594	/// Validators' authority discovery keys for the session in canonical ordering.
1595	///
1596	/// NOTE: The first `validators.len()` entries will match the corresponding validators in
1597	/// `validators`, afterwards any remaining authorities can be found. This is any authorities
1598	/// not participating in parachain consensus - see
1599	/// [`max_validators`](https://github.com/paritytech/polkadot/blob/a52dca2be7840b23c19c153cf7e110b1e3e475f8/runtime/parachains/src/configuration.rs#L148)
1600	pub discovery_keys: Vec<AuthorityDiscoveryId>,
1601	/// The assignment keys for validators.
1602	///
1603	/// NOTE: There might be more authorities in the current session, than validators participating
1604	/// in parachain consensus. See
1605	/// [`max_validators`](https://github.com/paritytech/polkadot/blob/a52dca2be7840b23c19c153cf7e110b1e3e475f8/runtime/parachains/src/configuration.rs#L148).
1606	///
1607	/// Therefore:
1608	/// ```ignore
1609	/// 	assignment_keys.len() == validators.len() && validators.len() <= discovery_keys.len()
1610	/// ```
1611	pub assignment_keys: Vec<AssignmentId>,
1612	/// Validators in shuffled ordering - these are the validator groups as produced
1613	/// by the `Scheduler` module for the session and are typically referred to by
1614	/// `GroupIndex`.
1615	pub validator_groups: IndexedVec<GroupIndex, Vec<ValidatorIndex>>,
1616	/// The number of availability cores used by the protocol during this session.
1617	pub n_cores: u32,
1618	/// The zeroth delay tranche width.
1619	pub zeroth_delay_tranche_width: u32,
1620	/// The number of samples we do of `relay_vrf_modulo`.
1621	pub relay_vrf_modulo_samples: u32,
1622	/// The number of delay tranches in total.
1623	pub n_delay_tranches: u32,
1624	/// How many slots (BABE / SASSAFRAS) must pass before an assignment is considered a
1625	/// no-show.
1626	pub no_show_slots: u32,
1627	/// The number of validators needed to approve a block.
1628	pub needed_approvals: u32,
1629}
1630
1631/// A statement from the specified validator whether the given validation code passes PVF
1632/// pre-checking or not anchored to the given session index.
1633#[derive(Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Debug, TypeInfo)]
1634pub struct PvfCheckStatement {
1635	/// `true` if the subject passed pre-checking and `false` otherwise.
1636	pub accept: bool,
1637	/// The validation code hash that was checked.
1638	pub subject: ValidationCodeHash,
1639	/// The index of a session during which this statement is considered valid.
1640	pub session_index: SessionIndex,
1641	/// The index of the validator from which this statement originates.
1642	pub validator_index: ValidatorIndex,
1643}
1644
1645impl PvfCheckStatement {
1646	/// Produce the payload used for signing this type of statement.
1647	///
1648	/// It is expected that it will be signed by the validator at `validator_index` in the
1649	/// `session_index`.
1650	pub fn signing_payload(&self) -> Vec<u8> {
1651		const MAGIC: [u8; 4] = *b"VCPC"; // for "validation code pre-checking"
1652		(MAGIC, self.accept, self.subject, self.session_index, self.validator_index).encode()
1653	}
1654}
1655
1656/// A well-known and typed storage key.
1657///
1658/// Allows for type-safe access to raw well-known storage keys.
1659pub struct WellKnownKey<T> {
1660	/// The raw storage key.
1661	pub key: Vec<u8>,
1662	_p: core::marker::PhantomData<T>,
1663}
1664
1665impl<T> From<Vec<u8>> for WellKnownKey<T> {
1666	fn from(key: Vec<u8>) -> Self {
1667		Self { key, _p: Default::default() }
1668	}
1669}
1670
1671impl<T> AsRef<[u8]> for WellKnownKey<T> {
1672	fn as_ref(&self) -> &[u8] {
1673		self.key.as_ref()
1674	}
1675}
1676
1677impl<T: Decode> WellKnownKey<T> {
1678	/// Gets the value or `None` if it does not exist or decoding failed.
1679	pub fn get(&self) -> Option<T> {
1680		sp_io::storage::get(&self.key)
1681			.and_then(|raw| codec::DecodeAll::decode_all(&mut raw.as_ref()).ok())
1682	}
1683}
1684
1685impl<T: Encode> WellKnownKey<T> {
1686	/// Sets the value.
1687	pub fn set(&self, value: T) {
1688		sp_io::storage::set(&self.key, &value.encode());
1689	}
1690}
1691
1692/// Type discriminator for PVF preparation.
1693#[derive(
1694	Encode,
1695	Decode,
1696	DecodeWithMemTracking,
1697	TypeInfo,
1698	Clone,
1699	Copy,
1700	Debug,
1701	PartialEq,
1702	Eq,
1703	Serialize,
1704	Deserialize,
1705)]
1706pub enum PvfPrepKind {
1707	/// For prechecking requests.
1708	Precheck,
1709
1710	/// For execution and heads-up requests.
1711	Prepare,
1712}
1713
1714/// Type discriminator for PVF execution.
1715#[derive(
1716	Encode,
1717	Decode,
1718	DecodeWithMemTracking,
1719	TypeInfo,
1720	Clone,
1721	Copy,
1722	Debug,
1723	PartialEq,
1724	Eq,
1725	Serialize,
1726	Deserialize,
1727)]
1728pub enum PvfExecKind {
1729	/// For backing requests.
1730	Backing,
1731	/// For approval and dispute request.
1732	Approval,
1733}
1734
1735/// Bit indices in the `HostConfiguration.node_features` that correspond to different node features.
1736pub type NodeFeatures = BitVec<u8, bitvec::order::Lsb0>;
1737
1738/// Module containing feature-specific bit indices into the `NodeFeatures` bitvec.
1739pub mod node_features {
1740	use crate::NodeFeatures;
1741
1742	/// A feature index used to identify a bit into the node_features array stored
1743	/// in the HostConfiguration.
1744	#[repr(u8)]
1745	#[derive(Clone, Copy)]
1746	pub enum FeatureIndex {
1747		/// Tells if tranch0 assignments could be sent in a single certificate.
1748		/// Reserved for: `<https://github.com/paritytech/polkadot-sdk/issues/628>`
1749		EnableAssignmentsV2 = 0,
1750		/// This feature enables the extension of `BackedCandidate::validator_indices` by 8 bits.
1751		/// The value stored there represents the assumed core index where the candidates
1752		/// are backed. This is needed for the elastic scaling MVP.
1753		ElasticScalingMVP = 1,
1754		/// Tells if the chunk mapping feature is enabled.
1755		/// Enables the implementation of
1756		/// [RFC-47](https://github.com/polkadot-fellows/RFCs/blob/main/text/0047-assignment-of-availability-chunks.md).
1757		/// Must not be enabled unless all validators and collators have stopped using `req_chunk`
1758		/// protocol version 1. If it is enabled, validators can start systematic chunk recovery.
1759		AvailabilityChunkMapping = 2,
1760		/// Enables node side support of `CoreIndex` committed candidate receipts.
1761		/// See [RFC-103](https://github.com/polkadot-fellows/RFCs/pull/103) for details.
1762		/// Only enable if at least 2/3 of nodes support the feature.
1763		CandidateReceiptV2 = 3,
1764		/// Enables support for scheduling information in the Candidate Descriptor.
1765		CandidateReceiptV3 = 4,
1766		/// First unassigned feature bit.
1767		/// Every time a new feature flag is assigned it should take this value.
1768		/// and this should be incremented.
1769		FirstUnassigned = 5,
1770	}
1771
1772	impl FeatureIndex {
1773		/// Check wheter the feature is enabled.
1774		pub fn is_set(self, node_features: &NodeFeatures) -> bool {
1775			node_features.get(self as usize).map(|v| *v).unwrap_or(false)
1776		}
1777	}
1778}
1779
1780/// Scheduler configuration parameters. All coretime/ondemand parameters are here.
1781#[derive(
1782	Debug,
1783	Copy,
1784	Clone,
1785	PartialEq,
1786	Encode,
1787	Decode,
1788	DecodeWithMemTracking,
1789	TypeInfo,
1790	serde::Serialize,
1791	serde::Deserialize,
1792)]
1793pub struct SchedulerParams<BlockNumber> {
1794	/// How often parachain groups should be rotated across parachains.
1795	///
1796	/// Must be non-zero.
1797	pub group_rotation_frequency: BlockNumber,
1798	/// Availability timeout for a block on a core, measured in blocks.
1799	///
1800	/// This is the maximum amount of blocks after a core became occupied that validators have time
1801	/// to make the block available.
1802	///
1803	/// This value only has effect on group rotations. If backers backed something at the end of
1804	/// their rotation, the occupied core affects the backing group that comes afterwards. We limit
1805	/// the effect one backing group can have on the next to `paras_availability_period` blocks.
1806	///
1807	/// Within a group rotation there is no timeout as backers are only affecting themselves.
1808	///
1809	/// Must be at least 1. With a value of 1, the previous group will not be able to negatively
1810	/// affect the following group at the expense of a tight availability timeline at group
1811	/// rotation boundaries.
1812	pub paras_availability_period: BlockNumber,
1813	/// The maximum number of validators to have per core.
1814	///
1815	/// `None` means no maximum.
1816	pub max_validators_per_core: Option<u32>,
1817	/// The amount of blocks ahead to schedule paras.
1818	pub lookahead: u32,
1819	/// How many cores are managed by the coretime chain.
1820	pub num_cores: u32,
1821	/// Deprecated and no longer used by the runtime.
1822	/// Removal is tracked by <https://github.com/paritytech/polkadot-sdk/issues/6067>.
1823	#[deprecated]
1824	pub max_availability_timeouts: u32,
1825	/// The maximum queue size of the pay as you go module.
1826	pub on_demand_queue_max_size: u32,
1827	/// The target utilization of the spot price queue in percentages.
1828	pub on_demand_target_queue_utilization: Perbill,
1829	/// How quickly the fee rises in reaction to increased utilization.
1830	/// The lower the number the slower the increase.
1831	pub on_demand_fee_variability: Perbill,
1832	/// The minimum amount needed to claim a slot in the spot pricing queue.
1833	pub on_demand_base_fee: Balance,
1834	/// Deprecated and no longer used by the runtime.
1835	/// Removal is tracked by <https://github.com/paritytech/polkadot-sdk/issues/6067>.
1836	#[deprecated]
1837	pub ttl: BlockNumber,
1838}
1839
1840impl<BlockNumber: Default + From<u32>> Default for SchedulerParams<BlockNumber> {
1841	#[allow(deprecated)]
1842	fn default() -> Self {
1843		Self {
1844			group_rotation_frequency: 1u32.into(),
1845			paras_availability_period: 1u32.into(),
1846			max_validators_per_core: Default::default(),
1847			lookahead: 1,
1848			num_cores: Default::default(),
1849			max_availability_timeouts: Default::default(),
1850			on_demand_queue_max_size: ON_DEMAND_DEFAULT_QUEUE_MAX_SIZE,
1851			on_demand_target_queue_utilization: Perbill::from_percent(25),
1852			on_demand_fee_variability: Perbill::from_percent(3),
1853			on_demand_base_fee: 10_000_000u128,
1854			ttl: 5u32.into(),
1855		}
1856	}
1857}
1858
1859/// A type representing the version of the candidate descriptor.
1860#[derive(PartialEq, Eq, Copy, Clone, Encode, Decode, TypeInfo, Debug, PartialOrd, Ord, Hash)]
1861pub enum CandidateDescriptorVersion {
1862	/// with deprecated collator id and collator signature.
1863	V1,
1864	/// First properly versioned candidate.
1865	///
1866	/// - Removes collator signature and collator id fields.
1867	/// - Introduces:
1868	/// -- A version field.
1869	/// -- session index field.
1870	/// -- core index field.
1871	V2,
1872	/// Candidate with scheduling info.
1873	V3,
1874	/// An unknown/not yet supported version.
1875	///
1876	/// Such a candidate must be dropped by the runtime and rejected by backers.
1877	Unknown(u8),
1878}
1879
1880/// Error returned by [`CandidateDescriptorV2::check_version_acceptance`].
1881#[derive(Debug, Copy, Clone, PartialEq, Eq)]
1882pub enum CandidateDescriptorVersionCheckError {
1883	/// Old-style and new-style version detection disagree, and this is not the
1884	/// expected V3 disagreement (old rules → V1, new rules → V3) with V3 enabled.
1885	Inconsistency,
1886	/// The descriptor is V3 but the V3 feature is not enabled.
1887	V3NotEnabled,
1888}
1889
1890// Manual Display impl required because this type is used in `no_std` runtime
1891// code (paras_inherent) where thiserror::Error is not available.
1892impl core::fmt::Display for CandidateDescriptorVersionCheckError {
1893	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1894		match self {
1895			Self::Inconsistency => {
1896				write!(f, "Descriptor version detection inconsistency (old vs new rules disagree)")
1897			},
1898			Self::V3NotEnabled => write!(f, "V3 candidate descriptor but V3 feature not enabled"),
1899		}
1900	}
1901}
1902
1903/// A unique descriptor of the candidate receipt.
1904#[derive(PartialEq, Eq, Clone, Encode, Decode, DecodeWithMemTracking, TypeInfo)]
1905pub struct CandidateDescriptorV2<H = Hash> {
1906	/// The ID of the para this is a candidate for.
1907	pub(super) para_id: ParaId,
1908	/// The hash of the relay-chain block this is executed in the context of.
1909	relay_parent: H,
1910	/// Version field. The raw value here is not exposed, instead it is used
1911	/// to determine the `CandidateDescriptorVersion`, see `fn version()`.
1912	/// For the current version this field is set to `0` and will be incremented
1913	/// by next versions.
1914	pub(super) version: u8,
1915	/// The core index where the candidate is backed.
1916	pub(super) core_index: u16,
1917	/// The session index of the candidate relay parent.
1918	session_index: SessionIndex,
1919	/// Offset from `session_index` to derive the scheduling session (introduced in v3).
1920	///
1921	/// Stored as a `u8` offset rather than a full `SessionIndex` to fit within the
1922	/// descriptor layout: `scheduling_session = session_index + scheduling_session_offset`.
1923	scheduling_session_offset: u8,
1924	/// Reserved bytes.
1925	reserved1: [u8; 24],
1926	/// The blake2-256 hash of the persisted validation data. This is extra data derived from
1927	/// relay-chain state which may vary based on bitfields included before the candidate.
1928	/// Thus it cannot be derived entirely from the relay-parent.
1929	persisted_validation_data_hash: Hash,
1930	/// The blake2-256 hash of the PoV.
1931	pov_hash: Hash,
1932	/// The root of a block's erasure encoding Merkle tree.
1933	erasure_root: Hash,
1934	/// The relay chain block determining scheduling.
1935	scheduling_parent: H, // Introduced in v3
1936	/// Reserved bytes.
1937	reserved2: [u8; 32],
1938	/// Hash of the para header that is being generated by this candidate.
1939	para_head: Hash,
1940	/// The blake2-256 hash of the validation code bytes.
1941	validation_code_hash: ValidationCodeHash,
1942}
1943
1944impl<H: AsRef<[u8]>> CandidateDescriptorV2<H> {
1945	/// Returns the candidate descriptor version.
1946	///
1947	/// NOTE: The candidate descriptor versioning is subtle for as long as we
1948	/// need to support the unversioned V1. The issue is that by default we
1949	/// assume a V1 descriptor - as soon as any of the reserved bytes are
1950	/// non-zero. Now if we introduce any new fields, then there will exist
1951	/// candidates where any old node will think that descriptors of that new
1952	/// version are actually V1 (non-zero contents), while upgraded nodes will
1953	/// either see v3 or an unknown version.
1954	///
1955	/// We solve this by completely gating v3 behavior behind the v3 node
1956	/// feature, which must only be enabled once enough validators have upgraded
1957	/// to support it. Any backers still running on the old version are
1958	/// protected by the relay chain runtime, which will drop any illegally
1959	/// (under v3) backed candidates.
1960	///
1961	/// For this to work we now also require a present UMP signal for any
1962	/// version higher or equal than V3. This is enforced by the runtime.
1963	///
1964	/// Via this, if an old node was presented a v3 candidate, which it would
1965	/// consider a V1, it would either detect itself that it is invalid, because
1966	/// of present UMP signals - which is illegal on v1 or the candidate would
1967	/// get rejected by the runtime, because for v3 UMP signals are mandatory.
1968	/// In both cases the backer wont't be slashed.
1969	///
1970	/// There are also candidates that would be treated as v1 by old nodes, but
1971	/// would result in an Unknown version on updated clients. For this
1972	/// scenario, also the runtime provides protection:
1973	///
1974	/// 1. Before the feature is enabled, all nodes will behave as if no v3
1975	/// would exist - all nodes would detect a V1.
1976	/// 2. After the upgrade, the runtime will also (in addition to upgraded
1977	/// nodes) detect an unknown version and no v1 and thus would drop it.
1978	///
1979	/// TL;DR: Yes old nodes will errorneously treat v3 candidates as v1, but we
1980	/// ensure via the relay chain runtime that this stays harmless for backers.
1981	/// V2 approval voters would get disabled, which means a super majority must
1982	/// have updated before enabling the v3 node feature.
1983	///
1984	/// Crucially for this to work: Behavior must not change before the node
1985	/// feature is present and enabled, together with new UMP signal
1986	/// requirements, the runtime can provide the necessary protection.
1987	///
1988	/// To ease future upgrades, we reduced the v1 check once v3 is enabled, so
1989	/// some actually unused bytes are available (don't affect the v1 version
1990	/// check).
1991	///
1992	/// Always uses the relaxed (v3-capable) detection logic. This means
1993	/// version detection is self-contained and does not require knowing
1994	/// whether the V3 node feature is enabled.
1995	///
1996	/// The safety invariant is maintained by the runtime and backing
1997	/// subsystem: they reject candidates where `version()` and
1998	/// `version_old_rules()` disagree when V3 is not yet enabled, and
1999	/// reject V3 candidates outright when V3 is not enabled.
2000	///
2001	/// During the V3 transition, approval checkers, dispute participants,
2002	/// and on-chain vote scrapers must use [`Self::version_for_candidate_validation`]
2003	/// (and the corresponding `scheduling_parent_for_candidate_validation` /
2004	/// `scheduling_session_for_candidate_validation`) instead of `version()`
2005	/// directly. This ensures they match old backer semantics before the V3
2006	/// node feature is confirmed enabled. See those methods for the full
2007	/// safety argument.
2008	pub fn version(&self) -> CandidateDescriptorVersion {
2009		self.v3_version()
2010	}
2011
2012	/// Detect the version using the pre-V3 (stricter) rules.
2013	///
2014	/// Under these rules, all reserved fields, `scheduling_parent`, and
2015	/// `scheduling_session_offset` must be zero for a descriptor to be
2016	/// considered V2. Any non-zero value in those fields causes V1
2017	/// detection. V3 descriptors appear as V1 under these rules.
2018	///
2019	/// Used together with `version()` in consistency checks: if the two
2020	/// methods disagree, the candidate is ambiguous and must be rejected
2021	/// when V3 is not enabled.
2022	pub fn version_old_rules(&self) -> CandidateDescriptorVersion {
2023		self.v2_version()
2024	}
2025
2026	/// Returns `true` if the old-style and new-style version detection agree.
2027	///
2028	/// When V3 is not enabled, both runtime and backing must reject candidates
2029	/// where this returns `false`, preventing ambiguous candidates from landing
2030	/// on-chain. Once V3 is enabled, disagreement is expected for V3 candidates
2031	/// (old rules see V1, new rules see V3) and this check is skipped.
2032	pub fn check_version_consistency(&self) -> bool {
2033		self.version() == self.version_old_rules()
2034	}
2035
2036	/// Validates that the descriptor version is acceptable given whether V3 is enabled.
2037	///
2038	/// Used by both the runtime (`check_descriptor_version_and_signals`) and the
2039	/// backing subsystem. Serves two distinct purposes:
2040	///
2041	/// 1. **V2 ambiguity protection (long-lived):** Old-style and new-style version detection must
2042	///    agree, unless the candidate is V3 and V3 is enabled (the expected disagreement: old rules
2043	///    see V1, new rules see V3). This prevents a crafted candidate from being treated as V2 (no
2044	///    mandatory UMP signals) by new nodes but as V1 by old nodes. Needed as long as V1 exists
2045	///    (maximum safety) or until we could have valiators not yet using the new rules.
2046	///
2047	/// 2. **V3 gating (transitional):** V3 candidates are rejected when V3 is not enabled.
2048	///
2049	/// Note: Consistent `Unknown` versions are not our concern here — they are caught upstream
2050	/// by the runtime (`check_descriptor_version_and_signals`) and the collator
2051	/// protocol (`descriptor_version_sanity_check`).
2052	pub fn check_version_acceptance(
2053		&self,
2054		v3_enabled: bool,
2055	) -> Result<(), CandidateDescriptorVersionCheckError> {
2056		let version = self.version();
2057
2058		// Version consistency: old and new detection must agree, unless this is the
2059		// expected V3 disagreement (old rules → V1, new rules → V3) with V3 enabled.
2060		let is_expected_v3_disagreement = version == CandidateDescriptorVersion::V3 && v3_enabled;
2061		if !self.check_version_consistency() && !is_expected_v3_disagreement {
2062			return Err(CandidateDescriptorVersionCheckError::Inconsistency);
2063		}
2064
2065		// V3 gating: reject V3 candidates before the feature is enabled.
2066		if version == CandidateDescriptorVersion::V3 && !v3_enabled {
2067			return Err(CandidateDescriptorVersionCheckError::V3NotEnabled);
2068		}
2069
2070		Ok(())
2071	}
2072
2073	fn v2_version(&self) -> CandidateDescriptorVersion {
2074		// V1 detected using the pre-v3 (stricter) check: all reserved and new
2075		// fields must be zero. Once v3 is enabled, the v1 check is relaxed in
2076		// `v3_version()` to free up more bytes for future use.
2077		let old_v1_detected = self.reserved2 != [0u8; 32] ||
2078			self.reserved1 != [0u8; 24] ||
2079			self.scheduling_session_offset != 0 ||
2080			self.scheduling_parent.as_ref() != &[0u8; 32];
2081
2082		if old_v1_detected {
2083			return CandidateDescriptorVersion::V1;
2084		}
2085
2086		match self.version {
2087			0 => CandidateDescriptorVersion::V2,
2088			_ => CandidateDescriptorVersion::Unknown(self.version),
2089		}
2090	}
2091}
2092
2093impl<H> CandidateDescriptorV2<H> {
2094	fn v3_version(&self) -> CandidateDescriptorVersion {
2095		// Reduce checked bits for v1 significantly to make more bytes easier
2096		// usable in future upgrades. 16 bytes is 32 hexadecimal digits which
2097		// must all be 0 by accident to cause any issues. Bitcoin hardest
2098		// difficulty so far has been 24 digits/12 bytes
2099		//
2100		// Impact if it still happened would also be fairly minimal: We would
2101		// drop a parachain block, which is not a big deal on v1, where we are
2102		// not aiming for perfect block confidence.
2103		let new_v1_detected = self.reserved1[0..16] != [0u8; 16];
2104
2105		if new_v1_detected {
2106			return CandidateDescriptorVersion::V1;
2107		}
2108		match self.version {
2109			0 => CandidateDescriptorVersion::V2,
2110			1 => CandidateDescriptorVersion::V3,
2111			_ => CandidateDescriptorVersion::Unknown(self.version),
2112		}
2113	}
2114}
2115
2116macro_rules! impl_getter {
2117	($field:ident, $type:ident) => {
2118		/// Returns the value of `$field` field.
2119		pub fn $field(&self) -> $type {
2120			self.$field
2121		}
2122	};
2123}
2124
2125impl<H: Copy + AsRef<[u8]>> CandidateDescriptorV2<H> {
2126	impl_getter!(erasure_root, Hash);
2127	impl_getter!(para_head, Hash);
2128	impl_getter!(relay_parent, H);
2129	impl_getter!(para_id, ParaId);
2130	impl_getter!(persisted_validation_data_hash, Hash);
2131	impl_getter!(pov_hash, Hash);
2132	impl_getter!(validation_code_hash, ValidationCodeHash);
2133
2134	#[cfg(feature = "test")]
2135	fn rebuild_collator_field(&self) -> CollatorId {
2136		let mut collator_id = Vec::with_capacity(32);
2137		let core_index: [u8; 2] = self.core_index.to_ne_bytes();
2138		let session_index: [u8; 4] = self.session_index.to_ne_bytes();
2139
2140		collator_id.push(self.version);
2141		collator_id.extend_from_slice(core_index.as_slice());
2142		collator_id.extend_from_slice(session_index.as_slice());
2143		collator_id.push(self.scheduling_session_offset);
2144		collator_id.extend_from_slice(self.reserved1.as_slice());
2145
2146		CollatorId::from_slice(&collator_id.as_slice())
2147			.expect("Slice size is exactly 32 bytes; qed")
2148	}
2149
2150	/// Returns the collator id if this is a v1 `CandidateDescriptor`
2151	#[cfg(feature = "test")]
2152	pub fn collator(&self) -> Option<CollatorId> {
2153		if self.version() == CandidateDescriptorVersion::V1 {
2154			Some(self.rebuild_collator_field())
2155		} else {
2156			None
2157		}
2158	}
2159
2160	#[cfg(feature = "test")]
2161	fn rebuild_signature_field(&self) -> CollatorSignature {
2162		let mut signature_bytes = Vec::with_capacity(64);
2163		signature_bytes.extend_from_slice(self.scheduling_parent.as_ref());
2164		signature_bytes.extend_from_slice(self.reserved2.as_slice());
2165
2166		CollatorSignature::from_slice(&signature_bytes)
2167			.expect("Slice size is exactly 64 bytes; qed")
2168	}
2169
2170	#[cfg(feature = "test")]
2171	#[doc(hidden)]
2172	pub fn rebuild_collator_field_for_tests(&self) -> CollatorId {
2173		self.rebuild_collator_field()
2174	}
2175
2176	#[cfg(feature = "test")]
2177	#[doc(hidden)]
2178	pub fn rebuild_signature_field_for_tests(&self) -> CollatorSignature {
2179		self.rebuild_signature_field()
2180	}
2181
2182	/// Returns the collator signature of `V1` candidate descriptors, `None` otherwise.
2183	#[cfg(feature = "test")]
2184	pub fn signature(&self) -> Option<CollatorSignature> {
2185		if self.version() == CandidateDescriptorVersion::V1 {
2186			return Some(self.rebuild_signature_field());
2187		}
2188
2189		None
2190	}
2191
2192	/// Returns the `core_index` of `V2` and `V3` candidate descriptors, `None` for `V1`.
2193	pub fn core_index(&self) -> Option<CoreIndex> {
2194		if self.version() == CandidateDescriptorVersion::V1 {
2195			return None;
2196		}
2197
2198		Some(CoreIndex(self.core_index as u32))
2199	}
2200
2201	/// Returns the `session_index` of `V2` and `V3` candidate descriptors, `None` for `V1`.
2202	pub fn session_index(&self) -> Option<SessionIndex> {
2203		if self.version() == CandidateDescriptorVersion::V1 {
2204			return None;
2205		}
2206
2207		Some(self.session_index)
2208	}
2209
2210	/// Return the scheduling parent of the descriptor.
2211	///
2212	///
2213	/// On v1 and v2 this function will return the relay parent as under these versions the relay
2214	/// parent is also the scheduling parent.
2215	pub fn scheduling_parent(&self) -> H {
2216		match self.version() {
2217			CandidateDescriptorVersion::V1 => self.relay_parent,
2218			CandidateDescriptorVersion::V2 => self.relay_parent,
2219			CandidateDescriptorVersion::V3 => self.scheduling_parent,
2220			CandidateDescriptorVersion::Unknown(_) => self.relay_parent,
2221		}
2222	}
2223
2224	/// Return the scheduling session index of the descriptor.
2225	///
2226	///
2227	/// On v1: Return None.
2228	/// On v2: Return the session index as it equals the scheduling session on v2.
2229	/// On v3: Return the provided scheduling session index.
2230	pub fn scheduling_session(&self) -> Option<SessionIndex> {
2231		match self.version() {
2232			CandidateDescriptorVersion::V1 => None,
2233			CandidateDescriptorVersion::V2 => Some(self.session_index),
2234			CandidateDescriptorVersion::V3 => {
2235				Some(self.session_index.saturating_add(self.scheduling_session_offset as _))
2236			},
2237			CandidateDescriptorVersion::Unknown(_) => None,
2238		}
2239	}
2240
2241	/// Version for use in candidate validation during the V3 transition period.
2242	///
2243	/// Before the `CandidateReceiptV3` node feature is observed, uses
2244	/// [`Self::version_old_rules`] to match old backer behavior. After the feature
2245	/// is seen, trusts [`Self::version`].
2246	///
2247	/// This prevents slashing honest old backers when a malicious collator crafts
2248	/// a pseudo-V3 descriptor that old nodes interpret as V1 but new nodes would
2249	/// interpret as V3 (different PVF inputs → dispute → 100% slash).
2250	///
2251	/// Safety argument: The node feature can only be enabled well after the runtime upgrade that
2252	/// adds `check_version_acceptance()` protection at inclusion time. Once the feature is seen,
2253	/// the runtime has long been upgraded and already rejecting pseudo-V3 candidates (candidates
2254	/// that are valid v1 under the old rules, but are v3 without UMP signals under the new
2255	/// rules), so no ambiguous candidates can exist on-chain.
2256	///
2257	/// Only needed during the V3 transition. Once V3 is universally deployed,
2258	/// callers can switch to [`Self::version`] directly.
2259	pub fn version_for_candidate_validation(
2260		&self,
2261		v3_ever_seen: bool,
2262	) -> CandidateDescriptorVersion {
2263		if v3_ever_seen {
2264			self.version()
2265		} else {
2266			self.version_old_rules()
2267		}
2268	}
2269
2270	/// Scheduling parent for use in candidate validation.
2271	///
2272	/// See [`Self::version_for_candidate_validation`] for the safety argument.
2273	pub fn scheduling_parent_for_candidate_validation(&self, v3_ever_seen: bool) -> H
2274	where
2275		H: Copy,
2276	{
2277		match self.version_for_candidate_validation(v3_ever_seen) {
2278			CandidateDescriptorVersion::V3 => self.scheduling_parent,
2279			_ => self.relay_parent,
2280		}
2281	}
2282
2283	/// Scheduling session for candidate validation.
2284	///
2285	/// See [`Self::version_for_candidate_validation`] for the safety argument.
2286	pub fn scheduling_session_for_candidate_validation(
2287		&self,
2288		v3_ever_seen: bool,
2289	) -> Option<SessionIndex> {
2290		match self.version_for_candidate_validation(v3_ever_seen) {
2291			CandidateDescriptorVersion::V1 => None,
2292			CandidateDescriptorVersion::V2 => Some(self.session_index),
2293			CandidateDescriptorVersion::V3 => {
2294				Some(self.session_index.saturating_add(self.scheduling_session_offset as _))
2295			},
2296			CandidateDescriptorVersion::Unknown(_) => None,
2297		}
2298	}
2299
2300	/// Session index (relay parent session) for candidate validation.
2301	///
2302	/// See [`Self::version_for_candidate_validation`] for the safety argument.
2303	pub fn session_index_for_candidate_validation(
2304		&self,
2305		v3_ever_seen: bool,
2306	) -> Option<SessionIndex> {
2307		match self.version_for_candidate_validation(v3_ever_seen) {
2308			CandidateDescriptorVersion::V1 | CandidateDescriptorVersion::Unknown(_) => None,
2309			CandidateDescriptorVersion::V2 | CandidateDescriptorVersion::V3 => {
2310				Some(self.session_index)
2311			},
2312		}
2313	}
2314}
2315
2316impl<H> core::fmt::Debug for CandidateDescriptorV2<H>
2317where
2318	H: core::fmt::Debug,
2319{
2320	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2321		// A bit imprecise, but should not matter in practice for debug output. (Keeps trait bounds
2322		// sane.)
2323		match self.v3_version() {
2324			CandidateDescriptorVersion::V1 => f
2325				.debug_struct("CandidateDescriptorV1")
2326				.field("para_id", &self.para_id)
2327				.field("relay_parent", &self.relay_parent)
2328				.field("persisted_validation_hash", &self.persisted_validation_data_hash)
2329				.field("pov_hash", &self.pov_hash)
2330				.field("erasure_root", &self.erasure_root)
2331				.field("para_head", &self.para_head)
2332				.field("validation_code_hash", &self.validation_code_hash)
2333				.finish(),
2334			CandidateDescriptorVersion::V2 => f
2335				.debug_struct("CandidateDescriptorV2")
2336				.field("para_id", &self.para_id)
2337				.field("relay_parent", &self.relay_parent)
2338				.field("core_index", &self.core_index)
2339				.field("session_index", &self.session_index)
2340				.field("persisted_validation_data_hash", &self.persisted_validation_data_hash)
2341				.field("pov_hash", &self.pov_hash)
2342				.field("erasure_root", &self.erasure_root)
2343				.field("para_head", &self.para_head)
2344				.field("validation_code_hash", &self.validation_code_hash)
2345				.finish(),
2346			CandidateDescriptorVersion::V3 => f
2347				.debug_struct("CandidateDescriptorV3")
2348				.field("para_id", &self.para_id)
2349				.field("relay_parent", &self.relay_parent)
2350				.field("core_index", &self.core_index)
2351				.field("session_index", &self.session_index)
2352				.field("scheduling_session_offset", &self.scheduling_session_offset)
2353				.field("persisted_validation_data_hash", &self.persisted_validation_data_hash)
2354				.field("pov_hash", &self.pov_hash)
2355				.field("erasure_root", &self.erasure_root)
2356				.field("scheduling_parent", &self.scheduling_parent)
2357				.field("para_head", &self.para_head)
2358				.field("validation_code_hash", &self.validation_code_hash)
2359				.finish(),
2360			CandidateDescriptorVersion::Unknown(raw_version) => {
2361				write!(f, "CandidateDescriptorV2(unknown version={})", raw_version)
2362			},
2363		}
2364	}
2365}
2366
2367impl<H: Copy + AsRef<[u8]>> CandidateDescriptorV2<H> {
2368	/// Constructor for V2 candidate descriptor (scheduling_parent = zero).
2369	pub fn new(
2370		para_id: Id,
2371		relay_parent: H,
2372		core_index: CoreIndex,
2373		session_index: SessionIndex,
2374		persisted_validation_data_hash: Hash,
2375		pov_hash: Hash,
2376		erasure_root: Hash,
2377		para_head: Hash,
2378		validation_code_hash: ValidationCodeHash,
2379	) -> Self
2380	where
2381		H: Default,
2382	{
2383		Self {
2384			para_id,
2385			relay_parent,
2386			version: 0,
2387			core_index: core_index.0 as u16,
2388			session_index,
2389			scheduling_session_offset: 0,
2390			reserved1: [0; 24],
2391			persisted_validation_data_hash,
2392			pov_hash,
2393			erasure_root,
2394			scheduling_parent: H::default(),
2395			reserved2: [0; 32],
2396			para_head,
2397			validation_code_hash,
2398		}
2399	}
2400
2401	/// Constructor for V3 candidate descriptor with explicit scheduling_parent.
2402	///
2403	/// V3 descriptors are identified by `version == 1` and have a non-zero scheduling_parent
2404	/// field, which indicates the relay chain block that was used for scheduling (may differ
2405	/// from relay_parent). V3 descriptors require UMP signals to be present.
2406	pub fn new_v3(
2407		para_id: Id,
2408		relay_parent: H,
2409		core_index: CoreIndex,
2410		session_index: SessionIndex,
2411		scheduling_session_index: SessionIndex,
2412		persisted_validation_data_hash: Hash,
2413		pov_hash: Hash,
2414		erasure_root: Hash,
2415		para_head: Hash,
2416		validation_code_hash: ValidationCodeHash,
2417		scheduling_parent: H,
2418	) -> Self {
2419		Self {
2420			para_id,
2421			relay_parent,
2422			version: 1,
2423			core_index: core_index.0 as u16,
2424			session_index,
2425			scheduling_session_offset: scheduling_session_index
2426				.saturating_sub(session_index)
2427				.try_into()
2428				.expect("scheduling session offset should fit in u8"),
2429			reserved1: [0; 24],
2430			persisted_validation_data_hash,
2431			pov_hash,
2432			erasure_root,
2433			scheduling_parent,
2434			reserved2: [0; 32],
2435			para_head,
2436			validation_code_hash,
2437		}
2438	}
2439
2440	/// Constructor for a V1-like candidate descriptor with non-zero collator
2441	/// fields so that `version()` returns [`CandidateDescriptorVersion::V1`].
2442	pub fn new_v1(
2443		para_id: Id,
2444		relay_parent: H,
2445		persisted_validation_data_hash: Hash,
2446		pov_hash: Hash,
2447		erasure_root: Hash,
2448		para_head: Hash,
2449		validation_code_hash: ValidationCodeHash,
2450	) -> Self
2451	where
2452		H: Default,
2453	{
2454		Self {
2455			para_id,
2456			relay_parent,
2457			version: 0,
2458			core_index: 0,
2459			session_index: 0,
2460			scheduling_session_offset: 0,
2461			reserved1: [1u8; 24],
2462			persisted_validation_data_hash,
2463			pov_hash,
2464			erasure_root,
2465			scheduling_parent: H::default(),
2466			reserved2: [1u8; 32],
2467			para_head,
2468			validation_code_hash,
2469		}
2470	}
2471
2472	#[cfg(feature = "test")]
2473	#[doc(hidden)]
2474	pub fn new_from_raw(
2475		para_id: Id,
2476		relay_parent: H,
2477		version: u8,
2478		core_index: u16,
2479		session_index: SessionIndex,
2480		scheduling_session_offset: u8,
2481		reserved1: [u8; 24],
2482		persisted_validation_data_hash: Hash,
2483		pov_hash: Hash,
2484		erasure_root: Hash,
2485		scheduling_parent: H,
2486		reserved2: [u8; 32],
2487		para_head: Hash,
2488		validation_code_hash: ValidationCodeHash,
2489	) -> Self {
2490		Self {
2491			para_id,
2492			relay_parent,
2493			version,
2494			core_index,
2495			session_index,
2496			scheduling_session_offset,
2497			reserved1,
2498			persisted_validation_data_hash,
2499			pov_hash,
2500			erasure_root,
2501			scheduling_parent,
2502			reserved2,
2503			para_head,
2504			validation_code_hash,
2505		}
2506	}
2507}
2508
2509/// A trait to allow changing the descriptor field values in tests.
2510#[cfg(feature = "test")]
2511pub trait MutateDescriptorV2<H> {
2512	/// Set the relay parent of the descriptor.
2513	fn set_relay_parent(&mut self, relay_parent: H);
2514	/// Set the `ParaId` of the descriptor.
2515	fn set_para_id(&mut self, para_id: Id);
2516	/// Set the PoV hash of the descriptor.
2517	fn set_pov_hash(&mut self, pov_hash: Hash);
2518	/// Set the raw version field of the descriptor.
2519	fn set_version(&mut self, version: u8);
2520	/// Set the PVD of the descriptor.
2521	fn set_persisted_validation_data_hash(&mut self, persisted_validation_data_hash: Hash);
2522	/// Set the validation code hash of the descriptor.
2523	fn set_validation_code_hash(&mut self, validation_code_hash: ValidationCodeHash);
2524	/// Set the erasure root of the descriptor.
2525	fn set_erasure_root(&mut self, erasure_root: Hash);
2526	/// Set the para head of the descriptor.
2527	fn set_para_head(&mut self, para_head: Hash);
2528	/// Set the core index of the descriptor.
2529	fn set_core_index(&mut self, core_index: CoreIndex);
2530	/// Set the session index of the descriptor.
2531	fn set_session_index(&mut self, session_index: SessionIndex);
2532	/// Set the reserved2 field of the descriptor.
2533	fn set_reserved2(&mut self, reserved2: [u8; 32]);
2534	/// Set the scheduling parent of the descriptor.
2535	fn set_scheduling_parent(&mut self, scheduling_parent: H);
2536	/// Set the scheduling session offset of the descriptor.
2537	fn set_scheduling_session_offset(&mut self, offset: u8);
2538}
2539
2540#[cfg(feature = "test")]
2541impl<H> MutateDescriptorV2<H> for CandidateDescriptorV2<H> {
2542	fn set_para_id(&mut self, para_id: Id) {
2543		self.para_id = para_id;
2544	}
2545
2546	fn set_relay_parent(&mut self, relay_parent: H) {
2547		self.relay_parent = relay_parent;
2548	}
2549
2550	fn set_pov_hash(&mut self, pov_hash: Hash) {
2551		self.pov_hash = pov_hash;
2552	}
2553
2554	fn set_version(&mut self, version: u8) {
2555		self.version = version;
2556	}
2557
2558	fn set_core_index(&mut self, core_index: CoreIndex) {
2559		self.core_index = core_index.0 as u16;
2560	}
2561
2562	fn set_session_index(&mut self, session_index: SessionIndex) {
2563		self.session_index = session_index;
2564	}
2565
2566	fn set_persisted_validation_data_hash(&mut self, persisted_validation_data_hash: Hash) {
2567		self.persisted_validation_data_hash = persisted_validation_data_hash;
2568	}
2569
2570	fn set_validation_code_hash(&mut self, validation_code_hash: ValidationCodeHash) {
2571		self.validation_code_hash = validation_code_hash;
2572	}
2573
2574	fn set_erasure_root(&mut self, erasure_root: Hash) {
2575		self.erasure_root = erasure_root;
2576	}
2577
2578	fn set_para_head(&mut self, para_head: Hash) {
2579		self.para_head = para_head;
2580	}
2581
2582	fn set_reserved2(&mut self, reserved2: [u8; 32]) {
2583		self.reserved2 = reserved2;
2584	}
2585
2586	fn set_scheduling_parent(&mut self, scheduling_parent: H) {
2587		self.scheduling_parent = scheduling_parent;
2588	}
2589
2590	fn set_scheduling_session_offset(&mut self, offset: u8) {
2591		self.scheduling_session_offset = offset;
2592	}
2593}
2594
2595/// A candidate-receipt at version 2.
2596#[derive(PartialEq, Eq, Clone, Encode, Decode, DecodeWithMemTracking, TypeInfo, Debug)]
2597pub struct CandidateReceiptV2<H = Hash> {
2598	/// The descriptor of the candidate.
2599	pub descriptor: CandidateDescriptorV2<H>,
2600	/// The hash of the encoded commitments made as a result of candidate execution.
2601	pub commitments_hash: Hash,
2602}
2603
2604/// A candidate-receipt with commitments directly included.
2605#[derive(PartialEq, Eq, Clone, Encode, Decode, DecodeWithMemTracking, TypeInfo, Debug)]
2606pub struct CommittedCandidateReceiptV2<H = Hash> {
2607	/// The descriptor of the candidate.
2608	pub descriptor: CandidateDescriptorV2<H>,
2609	/// The commitments of the candidate receipt.
2610	pub commitments: CandidateCommitments,
2611}
2612
2613/// An event concerning a candidate.
2614#[derive(Clone, Encode, Decode, TypeInfo, Debug)]
2615#[cfg_attr(feature = "std", derive(PartialEq))]
2616pub enum CandidateEvent<H = Hash> {
2617	/// This candidate receipt was backed in the most recent block.
2618	/// This includes the core index the candidate is now occupying.
2619	#[codec(index = 0)]
2620	CandidateBacked(CandidateReceiptV2<H>, HeadData, CoreIndex, GroupIndex),
2621	/// This candidate receipt was included and became a parablock at the most recent block.
2622	/// This includes the core index the candidate was occupying as well as the group responsible
2623	/// for backing the candidate.
2624	#[codec(index = 1)]
2625	CandidateIncluded(CandidateReceiptV2<H>, HeadData, CoreIndex, GroupIndex),
2626	/// This candidate receipt was not made available in time and timed out.
2627	/// This includes the core index the candidate was occupying.
2628	#[codec(index = 2)]
2629	CandidateTimedOut(CandidateReceiptV2<H>, HeadData, CoreIndex),
2630}
2631
2632impl<H> CandidateReceiptV2<H> {
2633	/// Get a reference to the candidate descriptor.
2634	pub fn descriptor(&self) -> &CandidateDescriptorV2<H> {
2635		&self.descriptor
2636	}
2637
2638	/// Computes the blake2-256 hash of the receipt.
2639	pub fn hash(&self) -> CandidateHash
2640	where
2641		H: Encode,
2642	{
2643		CandidateHash(BlakeTwo256::hash_of(self))
2644	}
2645}
2646
2647impl<H: Clone> CommittedCandidateReceiptV2<H> {
2648	/// Transforms this into a plain `CandidateReceipt`.
2649	pub fn to_plain(&self) -> CandidateReceiptV2<H> {
2650		CandidateReceiptV2 {
2651			descriptor: self.descriptor.clone(),
2652			commitments_hash: self.commitments.hash(),
2653		}
2654	}
2655
2656	/// Computes the hash of the committed candidate receipt.
2657	///
2658	/// This computes the canonical hash, not the hash of the directly encoded data.
2659	/// Thus this is a shortcut for `candidate.to_plain().hash()`.
2660	pub fn hash(&self) -> CandidateHash
2661	where
2662		H: Encode,
2663	{
2664		self.to_plain().hash()
2665	}
2666
2667	/// Does this committed candidate receipt corresponds to the given [`CandidateReceiptV2`]?
2668	pub fn corresponds_to(&self, receipt: &CandidateReceiptV2<H>) -> bool
2669	where
2670		H: PartialEq,
2671	{
2672		receipt.descriptor == self.descriptor && receipt.commitments_hash == self.commitments.hash()
2673	}
2674}
2675
2676impl PartialOrd for CommittedCandidateReceiptV2 {
2677	fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
2678		Some(self.cmp(other))
2679	}
2680}
2681
2682impl Ord for CommittedCandidateReceiptV2 {
2683	fn cmp(&self, other: &Self) -> core::cmp::Ordering {
2684		self.descriptor
2685			.para_id
2686			.cmp(&other.descriptor.para_id)
2687			.then_with(|| self.commitments.head_data.cmp(&other.commitments.head_data))
2688	}
2689}
2690
2691/// A strictly increasing sequence number, typically this would be the least significant byte of the
2692/// block number.
2693#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, Debug, Copy)]
2694pub struct CoreSelector(pub u8);
2695
2696impl From<u8> for CoreSelector {
2697	fn from(value: u8) -> Self {
2698		Self(value)
2699	}
2700}
2701
2702/// An offset in the relay chain claim queue.
2703#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, Debug, Copy)]
2704pub struct ClaimQueueOffset(pub u8);
2705
2706impl From<u8> for ClaimQueueOffset {
2707	fn from(value: u8) -> Self {
2708		Self(value)
2709	}
2710}
2711
2712/// Signals that a parachain can send to the relay chain via the UMP queue.
2713#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, Debug)]
2714pub enum UMPSignal {
2715	/// A message sent by a parachain to select the core the candidate is committed to.
2716	/// Relay chain validators, in particular backers, use the `CoreSelector` and
2717	/// `ClaimQueueOffset` to compute the index of the core the candidate has committed to.
2718	SelectCore(CoreSelector, ClaimQueueOffset),
2719	/// A message sent by a parachain to promote the reputation of a given peerid.
2720	ApprovedPeer(ApprovedPeerId),
2721	/// A message sent by a parachain carrying this candidate's outgoing stream commitment root
2722	/// (`Provides(StreamsRoot)`). The relay chain records these into its provides window.
2723	Provides(StreamsRoot),
2724	/// A message sent by a parachain carrying this candidate's expected incoming per-source
2725	/// stream commitment roots (`Requires(RequiresSet)`). The relay chain matches these against
2726	/// the provides window of the corresponding source parachains.
2727	Requires(RequiresSet),
2728}
2729
2730impl UMPSignal {
2731	/// Number of signal variants.
2732	const COUNT: usize = 4;
2733}
2734
2735/// The default claim queue offset to be used if it's not configured/accessible in the parachain
2736/// runtime
2737pub const DEFAULT_CLAIM_QUEUE_OFFSET: u8 = 0;
2738
2739/// Approved PeerId type. PeerIds in polkadot should typically be 32 bytes long but for identity
2740/// multihash can go up to 64. Cannot reuse the PeerId type definition from the networking code as
2741/// it's too generic and extensible.
2742pub type ApprovedPeerId = BoundedVec<u8, ConstU32<64>>;
2743
2744#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, Debug, Default)]
2745/// User-friendly representation of a candidate's UMP signals.
2746pub struct CandidateUMPSignals {
2747	pub(super) select_core: Option<(CoreSelector, ClaimQueueOffset)>,
2748	pub(super) approved_peer: Option<ApprovedPeerId>,
2749	pub(super) provides: Option<StreamsRoot>,
2750	pub(super) requires: Option<RequiresSet>,
2751}
2752
2753impl CandidateUMPSignals {
2754	/// Get the core selector UMP signal.
2755	pub fn core_selector(&self) -> Option<(CoreSelector, ClaimQueueOffset)> {
2756		self.select_core
2757	}
2758
2759	/// Get a reference to the approved peer UMP signal.
2760	pub fn approved_peer(&self) -> Option<&ApprovedPeerId> {
2761		self.approved_peer.as_ref()
2762	}
2763
2764	/// Get a reference to the speculative-messaging `provides` UMP signal.
2765	pub fn provides(&self) -> Option<&StreamsRoot> {
2766		self.provides.as_ref()
2767	}
2768
2769	/// Get a reference to the speculative-messaging `requires` UMP signal.
2770	pub fn requires(&self) -> Option<&RequiresSet> {
2771		self.requires.as_ref()
2772	}
2773
2774	/// Returns `true` if UMP signals are empty.
2775	pub fn is_empty(&self) -> bool {
2776		self.select_core.is_none() &&
2777			self.approved_peer.is_none() &&
2778			self.provides.is_none() &&
2779			self.requires.is_none()
2780	}
2781
2782	fn try_decode_signal(
2783		&mut self,
2784		buffer: &mut impl codec::Input,
2785	) -> Result<(), CommittedCandidateReceiptError> {
2786		match UMPSignal::decode(buffer)
2787			.map_err(|_| CommittedCandidateReceiptError::UmpSignalDecode)?
2788		{
2789			UMPSignal::ApprovedPeer(approved_peer_id) if self.approved_peer.is_none() => {
2790				self.approved_peer = Some(approved_peer_id);
2791			},
2792			UMPSignal::SelectCore(core_selector, cq_offset) if self.select_core.is_none() => {
2793				self.select_core = Some((core_selector, cq_offset));
2794			},
2795			UMPSignal::Provides(provides) if self.provides.is_none() => {
2796				self.provides = Some(provides);
2797			},
2798			UMPSignal::Requires(requires) if self.requires.is_none() => {
2799				self.requires = Some(requires);
2800			},
2801			_ => {
2802				// This means that we got duplicate UMP signals.
2803				return Err(CommittedCandidateReceiptError::DuplicateUMPSignal);
2804			},
2805		};
2806
2807		Ok(())
2808	}
2809
2810	#[cfg(feature = "test")]
2811	#[doc(hidden)]
2812	pub fn dummy(
2813		select_core: Option<(CoreSelector, ClaimQueueOffset)>,
2814		approved_peer: Option<ApprovedPeerId>,
2815	) -> Self {
2816		Self { select_core, approved_peer, provides: None, requires: None }
2817	}
2818}
2819
2820/// Separator between `XCM` and `UMPSignal`.
2821pub const UMP_SEPARATOR: Vec<u8> = vec![];
2822
2823/// The maximum number of `UMPSignal` messages a candidate may carry — one per
2824/// [`UMPSignal`] variant.
2825pub const MAX_UMP_SIGNALS: usize = UMPSignal::COUNT;
2826
2827/// Utility function for skipping the ump signals.
2828pub fn skip_ump_signals<'a>(
2829	upward_messages: impl Iterator<Item = &'a Vec<u8>>,
2830) -> impl Iterator<Item = &'a Vec<u8>> {
2831	upward_messages.take_while(|message| *message != &UMP_SEPARATOR)
2832}
2833
2834impl CandidateCommitments {
2835	/// Returns the ump signals of this candidate, if any, or an error if they violate the expected
2836	/// format.
2837	pub fn ump_signals(&self) -> Result<CandidateUMPSignals, CommittedCandidateReceiptError> {
2838		let mut res = CandidateUMPSignals::default();
2839
2840		let mut signals_iter =
2841			self.upward_messages.iter().skip_while(|message| *message != &UMP_SEPARATOR);
2842
2843		if signals_iter.next().is_none() {
2844			// No UMP separator
2845			return Ok(res);
2846		}
2847
2848		// At most one signal of each `UMPSignal` variant is allowed; `try_decode_signal`
2849		// rejects duplicates. Bound the loop by the number of variants so a malformed
2850		// candidate cannot force unbounded work.
2851		for _ in 0..MAX_UMP_SIGNALS {
2852			let Some(signal) = signals_iter.next() else { return Ok(res) };
2853			res.try_decode_signal(&mut signal.as_slice())?;
2854		}
2855
2856		// No more signals than there are distinct variants are allowed.
2857		if signals_iter.next().is_some() {
2858			return Err(CommittedCandidateReceiptError::TooManyUMPSignals);
2859		}
2860
2861		Ok(res)
2862	}
2863}
2864
2865/// CommittedCandidateReceiptError construction errors.
2866#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, Debug)]
2867#[cfg_attr(feature = "std", derive(thiserror::Error))]
2868pub enum CommittedCandidateReceiptError {
2869	/// The specified core index is invalid.
2870	#[cfg_attr(feature = "std", error("The specified core index is invalid"))]
2871	InvalidCoreIndex,
2872	/// The core index in commitments doesn't match the one in descriptor
2873	#[cfg_attr(
2874		feature = "std",
2875		error("The core index in commitments ({commitments:?}) doesn't match the one in descriptor ({descriptor:?})")
2876	)]
2877	CoreIndexMismatch {
2878		/// The core index as found in the descriptor.
2879		descriptor: CoreIndex,
2880		/// The core index as found in the commitments.
2881		commitments: CoreIndex,
2882	},
2883	/// The core selector or claim queue offset is invalid.
2884	#[cfg_attr(feature = "std", error("The core selector or claim queue offset is invalid"))]
2885	InvalidSelectedCore,
2886	#[cfg_attr(feature = "std", error("Could not decode UMP signal"))]
2887	/// Could not decode UMP signal.
2888	UmpSignalDecode,
2889	/// The parachain is not assigned to any core at specified claim queue offset.
2890	#[cfg_attr(
2891		feature = "std",
2892		error("The parachain is not assigned to any core at specified claim queue offset")
2893	)]
2894	NoAssignment,
2895	/// Unknown version.
2896	#[cfg_attr(feature = "std", error("Unknown internal version"))]
2897	UnknownVersion(u8),
2898	/// The allowed number of `UMPSignal` messages in the queue was exceeded.
2899	#[cfg_attr(feature = "std", error("Too many UMP signals"))]
2900	TooManyUMPSignals,
2901	/// Duplicated UMP signal.
2902	#[cfg_attr(feature = "std", error("Duplicate UMP signal"))]
2903	DuplicateUMPSignal,
2904	/// If the parachain runtime started sending ump signals, v1 descriptors are no longer
2905	/// allowed.
2906	#[cfg_attr(feature = "std", error("Version 1 receipt does not support ump signals"))]
2907	UMPSignalWithV1Descriptor,
2908	/// Starting with v3 ump signals are mandatory.
2909	///
2910	/// This is to avoid nodes only understanding v1 and v2 to getting tricked
2911	/// into backing a candidate that looks like a valid v1 to them, but is
2912	/// actually an invalid v3.
2913	///
2914	/// This is prevented by the runtime rejecting v3 candidates without ump
2915	/// signals. Therefore a candidate that was erroneously backed as v1, while
2916	/// it actually was a v3 would get rejected by the runtime due to missing
2917	/// signals, thus preventing the backer from getting slashed. This is given,
2918	/// because v1 and v2 only nodes would not back a v1 candidate with UMP
2919	/// signals, as that is seen as invalid by them already.
2920	#[cfg_attr(feature = "std", error("Version 3 receipt requires ump signals"))]
2921	NoUMPSignalWithV3Descriptor,
2922}
2923
2924impl<H: Copy + AsRef<[u8]>> CommittedCandidateReceiptV2<H> {
2925	/// Performs checks on the UMP signals and returns them.
2926	///
2927	/// Also checks if descriptor core index is equal to the committed core index.
2928	///
2929	/// Params:
2930	/// - `cores_per_para` is a claim queue snapshot at the candidate's relay parent, stored as
2931	/// a mapping between `ParaId` and the cores assigned per depth.
2932	///
2933	/// NOTE: This must only be called in the runtime and backing - never in approval voting nor
2934	/// disputes! At least not as long as nodes exist which don't understand v3 candidate
2935	/// descriptors. Not checking there is fine, because it is checked by the runtime - if it can be
2936	/// disputed, it has been checked already!
2937	pub fn parse_ump_signals(
2938		&self,
2939		cores_per_para: &TransposedClaimQueue,
2940	) -> Result<CandidateUMPSignals, CommittedCandidateReceiptError> {
2941		parse_ump_signals_for_commitments(
2942			&self.commitments,
2943			self.descriptor.version(),
2944			cores_per_para,
2945			self.descriptor.para_id(),
2946			CoreIndex(self.descriptor.core_index as u32),
2947		)
2948	}
2949}
2950
2951/// Performs the UMP-signal checks and returns the signals.
2952///
2953/// The check is on the commitments: it needs the claim queue plus the three descriptor
2954/// fields the core-index check consumes, and nothing else from a receipt.
2955/// [`CommittedCandidateReceiptV2::parse_ump_signals`] is the convenience wrapper for
2956/// callers that already hold a receipt.
2957pub fn parse_ump_signals_for_commitments(
2958	commitments: &CandidateCommitments,
2959	version: CandidateDescriptorVersion,
2960	cores_per_para: &TransposedClaimQueue,
2961	para_id: Id,
2962	core_index: CoreIndex,
2963) -> Result<CandidateUMPSignals, CommittedCandidateReceiptError> {
2964	let signals = commitments.ump_signals()?;
2965
2966	match version {
2967		CandidateDescriptorVersion::V1 => {
2968			// If the parachain runtime started sending ump signals, v1 descriptors are no
2969			// longer allowed.
2970			if !signals.is_empty() {
2971				return Err(CommittedCandidateReceiptError::UMPSignalWithV1Descriptor);
2972			}
2973
2974			// Nothing else to check for v1 descriptors.
2975			return Ok(CandidateUMPSignals::default());
2976		},
2977		CandidateDescriptorVersion::V2 => {},
2978		CandidateDescriptorVersion::Unknown(version_raw) => {
2979			return Err(CommittedCandidateReceiptError::UnknownVersion(version_raw))
2980		},
2981		_ if signals.is_empty() => {
2982			// V3 and above require UMP signals.
2983			return Err(CommittedCandidateReceiptError::NoUMPSignalWithV3Descriptor);
2984		},
2985		_ => {},
2986	}
2987
2988	// Check the core index
2989	let (maybe_core_index_selector, cq_offset) = signals
2990		.core_selector()
2991		.map(|(selector, offset)| (Some(selector), offset))
2992		.unwrap_or_else(|| (None, ClaimQueueOffset(DEFAULT_CLAIM_QUEUE_OFFSET)));
2993
2994	check_core_index(cores_per_para, maybe_core_index_selector, cq_offset, para_id, core_index)?;
2995
2996	// Nothing to further check for the approved peer. If everything passed so far, return the
2997	// signals.
2998	Ok(signals)
2999}
3000
3001/// Checks if descriptor core index is equal to the committed core index.
3002/// Input `cores_per_para` is a claim queue snapshot at the candidate's relay parent, stored as
3003/// a mapping between `ParaId` and the cores assigned per depth.
3004fn check_core_index(
3005	cores_per_para: &TransposedClaimQueue,
3006	maybe_core_index_selector: Option<CoreSelector>,
3007	cq_offset: ClaimQueueOffset,
3008	para_id: Id,
3009	descriptor_core_index: CoreIndex,
3010) -> Result<(), CommittedCandidateReceiptError> {
3011	let assigned_cores = cores_per_para
3012		.get(&para_id)
3013		.ok_or(CommittedCandidateReceiptError::NoAssignment)?
3014		.get(&cq_offset.0)
3015		.ok_or(CommittedCandidateReceiptError::NoAssignment)?;
3016
3017	if assigned_cores.is_empty() {
3018		return Err(CommittedCandidateReceiptError::NoAssignment);
3019	}
3020
3021	let core_index_selector = if let Some(core_index_selector) = maybe_core_index_selector {
3022		// We have a committed core selector, we can use it.
3023		core_index_selector
3024	} else if assigned_cores.len() > 1 {
3025		// We got more than one assigned core and no core selector. Special care is needed.
3026		if !assigned_cores.contains(&descriptor_core_index) {
3027			// core index in the descriptor is not assigned to the para. Error.
3028			return Err(CommittedCandidateReceiptError::InvalidCoreIndex);
3029		} else {
3030			// the descriptor core index is indeed assigned to the para. This is the most we can
3031			// check for now
3032			return Ok(());
3033		}
3034	} else {
3035		// No core selector but there's only one assigned core, use it.
3036		CoreSelector(0)
3037	};
3038
3039	let core_index = assigned_cores
3040		.iter()
3041		.nth(core_index_selector.0 as usize % assigned_cores.len())
3042		.ok_or(CommittedCandidateReceiptError::InvalidSelectedCore)
3043		.copied()?;
3044
3045	if core_index != descriptor_core_index {
3046		return Err(CommittedCandidateReceiptError::CoreIndexMismatch {
3047			descriptor: descriptor_core_index,
3048			commitments: core_index,
3049		});
3050	}
3051
3052	Ok(())
3053}
3054
3055/// A backed (or backable, depending on context) candidate.
3056#[derive(Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Eq, Debug, TypeInfo)]
3057pub struct BackedCandidate<H = Hash> {
3058	/// The candidate referred to.
3059	candidate: CommittedCandidateReceiptV2<H>,
3060	/// The validity votes themselves, expressed as signatures.
3061	validity_votes: Vec<ValidityAttestation>,
3062	/// The indices of the validators within the group, expressed as a bitfield. May be extended
3063	/// beyond the backing group size to contain the assigned core index, if ElasticScalingMVP is
3064	/// enabled.
3065	validator_indices: BitVec<u8, bitvec::order::Lsb0>,
3066}
3067
3068/// Parachains inherent-data passed into the runtime by a block author
3069#[derive(Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Debug, TypeInfo)]
3070pub struct InherentData<HDR: HeaderT = Header> {
3071	/// Signed bitfields by validators about availability.
3072	pub bitfields: UncheckedSignedAvailabilityBitfields,
3073	/// Backed candidates for inclusion in the block.
3074	pub backed_candidates: Vec<BackedCandidate<HDR::Hash>>,
3075	/// Sets of dispute votes for inclusion,
3076	pub disputes: MultiDisputeStatementSet,
3077	/// The parent block header. Used for checking state proofs.
3078	pub parent_header: HDR,
3079}
3080
3081impl<H> BackedCandidate<H> {
3082	/// Constructor
3083	pub fn new(
3084		candidate: CommittedCandidateReceiptV2<H>,
3085		validity_votes: Vec<ValidityAttestation>,
3086		validator_indices: BitVec<u8, bitvec::order::Lsb0>,
3087		core_index: CoreIndex,
3088	) -> Self {
3089		let mut instance = Self { candidate, validity_votes, validator_indices };
3090		instance.inject_core_index(core_index);
3091		instance
3092	}
3093
3094	/// Get a reference to the committed candidate receipt of the candidate.
3095	pub fn candidate(&self) -> &CommittedCandidateReceiptV2<H> {
3096		&self.candidate
3097	}
3098
3099	/// Get a mutable reference to the committed candidate receipt of the candidate.
3100	/// Only for testing.
3101	#[cfg(feature = "test")]
3102	pub fn candidate_mut(&mut self) -> &mut CommittedCandidateReceiptV2<H> {
3103		&mut self.candidate
3104	}
3105	/// Get a reference to the descriptor of the candidate.
3106	pub fn descriptor(&self) -> &CandidateDescriptorV2<H> {
3107		&self.candidate.descriptor
3108	}
3109
3110	/// Get a mutable reference to the descriptor of the candidate. Only for testing.
3111	#[cfg(feature = "test")]
3112	pub fn descriptor_mut(&mut self) -> &mut CandidateDescriptorV2<H> {
3113		&mut self.candidate.descriptor
3114	}
3115
3116	/// Get a reference to the validity votes of the candidate.
3117	pub fn validity_votes(&self) -> &[ValidityAttestation] {
3118		&self.validity_votes
3119	}
3120
3121	/// Get a mutable reference to validity votes of the para.
3122	pub fn validity_votes_mut(&mut self) -> &mut Vec<ValidityAttestation> {
3123		&mut self.validity_votes
3124	}
3125
3126	/// Compute this candidate's hash.
3127	pub fn hash(&self) -> CandidateHash
3128	where
3129		H: Clone + Encode,
3130	{
3131		self.candidate.to_plain().hash()
3132	}
3133
3134	/// Get this candidate's receipt.
3135	pub fn receipt(&self) -> CandidateReceiptV2<H>
3136	where
3137		H: Clone,
3138	{
3139		self.candidate.to_plain()
3140	}
3141
3142	/// Get a copy of the raw validator indices.
3143	#[cfg(feature = "test")]
3144	pub fn raw_validator_indices(&self) -> BitVec<u8, bitvec::order::Lsb0> {
3145		self.validator_indices.clone()
3146	}
3147
3148	/// Get a copy of the validator indices and the assumed core index, if any.
3149	pub fn validator_indices_and_core_index(
3150		&self,
3151	) -> (&BitSlice<u8, bitvec::order::Lsb0>, Option<CoreIndex>) {
3152		// `BackedCandidate::validity_indices` are extended to store a 8 bit core index.
3153		let core_idx_offset = self.validator_indices.len().saturating_sub(8);
3154		if core_idx_offset > 0 {
3155			let (validator_indices_slice, core_idx_slice) =
3156				self.validator_indices.split_at(core_idx_offset);
3157			return (validator_indices_slice, Some(CoreIndex(core_idx_slice.load::<u8>() as u32)));
3158		}
3159
3160		(&self.validator_indices, None)
3161	}
3162
3163	/// Inject a core index in the validator_indices bitvec.
3164	fn inject_core_index(&mut self, core_index: CoreIndex) {
3165		let core_index_to_inject: BitVec<u8, bitvec::order::Lsb0> =
3166			BitVec::from_vec(vec![core_index.0 as u8]);
3167		self.validator_indices.extend(core_index_to_inject);
3168	}
3169
3170	/// Update the validator indices and core index in the candidate.
3171	pub fn set_validator_indices_and_core_index(
3172		&mut self,
3173		new_indices: BitVec<u8, bitvec::order::Lsb0>,
3174		maybe_core_index: Option<CoreIndex>,
3175	) {
3176		self.validator_indices = new_indices;
3177
3178		if let Some(core_index) = maybe_core_index {
3179			self.inject_core_index(core_index);
3180		}
3181	}
3182}
3183
3184/// Scraped runtime backing votes and resolved disputes.
3185#[derive(Clone, Encode, Decode, Debug, TypeInfo)]
3186#[cfg_attr(feature = "std", derive(PartialEq))]
3187pub struct ScrapedOnChainVotes<H: Encode + Decode = Hash> {
3188	/// The session in which the block was included.
3189	pub session: SessionIndex,
3190	/// Set of backing validators for each candidate, represented by its candidate
3191	/// receipt.
3192	pub backing_validators_per_candidate:
3193		Vec<(CandidateReceiptV2<H>, Vec<(ValidatorIndex, ValidityAttestation)>)>,
3194	/// On-chain-recorded set of disputes.
3195	/// Note that the above `backing_validators` are
3196	/// unrelated to the backers of the disputes candidates.
3197	pub disputes: MultiDisputeStatementSet,
3198}
3199
3200/// Information about a core which is currently occupied.
3201#[derive(Clone, Encode, Decode, TypeInfo, Debug)]
3202#[cfg_attr(feature = "std", derive(PartialEq))]
3203pub struct OccupiedCore<H = Hash, N = BlockNumber> {
3204	// NOTE: this has no ParaId as it can be deduced from the candidate descriptor.
3205	/// If this core is freed by availability, this is the assignment that is next up on this
3206	/// core, if any. None if there is nothing queued for this core.
3207	pub next_up_on_available: Option<ScheduledCore>,
3208	/// The relay-chain block number this began occupying the core at.
3209	pub occupied_since: N,
3210	/// The relay-chain block this will time-out at, if any.
3211	pub time_out_at: N,
3212	/// If this core is freed by being timed-out, this is the assignment that is next up on this
3213	/// core. None if there is nothing queued for this core or there is no possibility of timing
3214	/// out.
3215	pub next_up_on_time_out: Option<ScheduledCore>,
3216	/// A bitfield with 1 bit for each validator in the set. `1` bits mean that the corresponding
3217	/// validators has attested to availability on-chain. A 2/3+ majority of `1` bits means that
3218	/// this will be available.
3219	pub availability: BitVec<u8, bitvec::order::Lsb0>,
3220	/// The group assigned to distribute availability pieces of this candidate.
3221	pub group_responsible: GroupIndex,
3222	/// The hash of the candidate occupying the core.
3223	pub candidate_hash: CandidateHash,
3224	/// The descriptor of the candidate occupying the core.
3225	pub candidate_descriptor: CandidateDescriptorV2<H>,
3226}
3227
3228impl<H, N> OccupiedCore<H, N> {
3229	/// Get the Para currently occupying this core.
3230	pub fn para_id(&self) -> Id {
3231		self.candidate_descriptor.para_id
3232	}
3233}
3234
3235/// The state of a particular availability core.
3236#[derive(Clone, Encode, Decode, TypeInfo, Debug)]
3237#[cfg_attr(feature = "std", derive(PartialEq))]
3238pub enum CoreState<H = Hash, N = BlockNumber> {
3239	/// The core is currently occupied.
3240	#[codec(index = 0)]
3241	Occupied(OccupiedCore<H, N>),
3242	/// The core is currently free, with a para scheduled and given the opportunity
3243	/// to occupy.
3244	///
3245	/// If a particular Collator is required to author this block, that is also present in this
3246	/// variant.
3247	#[codec(index = 1)]
3248	Scheduled(ScheduledCore),
3249	/// The core is currently free and there is nothing scheduled. This can be the case for
3250	/// parathread cores when there are no parathread blocks queued. Parachain cores will never be
3251	/// left idle.
3252	#[codec(index = 2)]
3253	Free,
3254}
3255
3256impl<N> CoreState<N> {
3257	/// Returns the scheduled `ParaId` for the core or `None` if nothing is scheduled.
3258	///
3259	/// This function is deprecated. `ClaimQueue` should be used to obtain the scheduled `ParaId`s
3260	/// for each core.
3261	#[deprecated(
3262		note = "`para_id` will be removed. Use `ClaimQueue` to query the scheduled `para_id` instead."
3263	)]
3264	pub fn para_id(&self) -> Option<Id> {
3265		match self {
3266			Self::Occupied(ref core) => core.next_up_on_available.as_ref().map(|n| n.para_id),
3267			Self::Scheduled(core) => Some(core.para_id),
3268			Self::Free => None,
3269		}
3270	}
3271
3272	/// Is this core state `Self::Occupied`?
3273	pub fn is_occupied(&self) -> bool {
3274		matches!(self, Self::Occupied(_))
3275	}
3276}
3277
3278/// The claim queue mapped by parachain id.
3279pub type TransposedClaimQueue = BTreeMap<ParaId, BTreeMap<u8, BTreeSet<CoreIndex>>>;
3280
3281/// Returns a mapping between the para id and the core indices assigned at different
3282/// depths in the claim queue.
3283pub fn transpose_claim_queue(
3284	claim_queue: BTreeMap<CoreIndex, VecDeque<Id>>,
3285) -> TransposedClaimQueue {
3286	let mut per_para_claim_queue = BTreeMap::new();
3287
3288	for (core, paras) in claim_queue {
3289		// Iterate paras assigned to this core at each depth.
3290		for (depth, para) in paras.into_iter().enumerate() {
3291			let depths: &mut BTreeMap<u8, BTreeSet<CoreIndex>> =
3292				per_para_claim_queue.entry(para).or_insert_with(|| Default::default());
3293
3294			depths.entry(depth as u8).or_default().insert(core);
3295		}
3296	}
3297
3298	per_para_claim_queue
3299}
3300
3301// Approval Slashes primitives
3302/// Supercedes the old 'SlashingOffenceKind' enum.
3303#[derive(PartialEq, Eq, Clone, Copy, Encode, Decode, DecodeWithMemTracking, TypeInfo, Debug)]
3304pub enum DisputeOffenceKind {
3305	/// A severe offence when a validator backed an invalid block
3306	/// (backing only)
3307	#[codec(index = 0)]
3308	ForInvalidBacked,
3309	/// A minor offence when a validator disputed a valid block.
3310	/// (approval checking and dispute vote only)
3311	#[codec(index = 1)]
3312	AgainstValid,
3313	/// A medium offence when a validator approved an invalid block
3314	/// (approval checking and dispute vote only)
3315	#[codec(index = 2)]
3316	ForInvalidApproved,
3317}
3318
3319/// impl for a conversion from SlashingOffenceKind to DisputeOffenceKind
3320/// This creates DisputeOffenceKind that never contains ForInvalidApproved since it was not
3321/// supported in the past
3322impl From<super::v9::slashing::SlashingOffenceKind> for DisputeOffenceKind {
3323	fn from(value: super::v9::slashing::SlashingOffenceKind) -> Self {
3324		match value {
3325			super::v9::slashing::SlashingOffenceKind::ForInvalid => Self::ForInvalidBacked,
3326			super::v9::slashing::SlashingOffenceKind::AgainstValid => Self::AgainstValid,
3327		}
3328	}
3329}
3330
3331/// impl for a tryFrom conversion from DisputeOffenceKind to SlashingOffenceKind
3332impl TryFrom<DisputeOffenceKind> for super::v9::slashing::SlashingOffenceKind {
3333	type Error = ();
3334
3335	fn try_from(value: DisputeOffenceKind) -> Result<Self, Self::Error> {
3336		match value {
3337			DisputeOffenceKind::ForInvalidBacked => Ok(Self::ForInvalid),
3338			DisputeOffenceKind::AgainstValid => Ok(Self::AgainstValid),
3339			DisputeOffenceKind::ForInvalidApproved => Err(()),
3340		}
3341	}
3342}
3343
3344#[cfg(test)]
3345/// Basic tests
3346pub mod tests {
3347	use super::*;
3348
3349	#[test]
3350	fn group_rotation_info_calculations() {
3351		let info =
3352			GroupRotationInfo { session_start_block: 10u32, now: 15, group_rotation_frequency: 5 };
3353
3354		assert_eq!(info.next_rotation_at(), 20);
3355		assert_eq!(info.last_rotation_at(), 15);
3356	}
3357
3358	#[test]
3359	fn ump_signals_extracts_provides_and_requires_roots() {
3360		let provides = StreamsRoot(Hash::repeat_byte(1));
3361		let requires =
3362			RequiresSet::try_from_iter([(Id::from(2u32), StreamsRoot(Hash::repeat_byte(2)))])
3363				.unwrap();
3364
3365		let upward_messages = alloc::vec![
3366			UMP_SEPARATOR,
3367			UMPSignal::Provides(provides).encode(),
3368			UMPSignal::Requires(requires.clone()).encode(),
3369		];
3370
3371		let commitments = CandidateCommitments {
3372			upward_messages: upward_messages.try_into().unwrap(),
3373			..Default::default()
3374		};
3375
3376		let signals = commitments.ump_signals().expect("valid signals");
3377		assert_eq!(signals.provides(), Some(&provides));
3378		assert_eq!(signals.requires(), Some(&requires));
3379	}
3380
3381	#[test]
3382	fn ump_signals_accept_any_order() {
3383		let provides = StreamsRoot(Hash::repeat_byte(1));
3384		let requires =
3385			RequiresSet::try_from_iter([(Id::from(2u32), StreamsRoot(Hash::repeat_byte(2)))])
3386				.unwrap();
3387		let upward_messages = alloc::vec![
3388			UMP_SEPARATOR,
3389			UMPSignal::Requires(requires.clone()).encode(),
3390			UMPSignal::SelectCore(CoreSelector(1), ClaimQueueOffset(0)).encode(),
3391			UMPSignal::Provides(provides).encode(),
3392			UMPSignal::ApprovedPeer(Default::default()).encode(),
3393		];
3394		let commitments = CandidateCommitments {
3395			upward_messages: upward_messages.try_into().unwrap(),
3396			..Default::default()
3397		};
3398
3399		let signals = commitments.ump_signals().expect("one of each, in any order");
3400		assert_eq!(signals.provides(), Some(&provides));
3401		assert_eq!(signals.requires(), Some(&requires));
3402		assert_eq!(signals.core_selector(), Some((CoreSelector(1), ClaimQueueOffset(0))));
3403	}
3404
3405	#[test]
3406	fn ump_signals_reject_a_repeated_spec_msg_signal() {
3407		let requires =
3408			RequiresSet::try_from_iter([(Id::from(2u32), StreamsRoot(Hash::repeat_byte(2)))])
3409				.unwrap();
3410		let provides = |b| UMPSignal::Provides(StreamsRoot(Hash::repeat_byte(b))).encode();
3411		for repeated in [
3412			alloc::vec![provides(1), provides(1)],
3413			alloc::vec![provides(1), provides(2)],
3414			alloc::vec![
3415				UMPSignal::Requires(requires.clone()).encode(),
3416				provides(1),
3417				UMPSignal::Requires(requires.clone()).encode(),
3418			],
3419		] {
3420			let mut upward_messages = alloc::vec![UMP_SEPARATOR];
3421			upward_messages.extend(repeated);
3422			let commitments = CandidateCommitments {
3423				upward_messages: upward_messages.try_into().unwrap(),
3424				..Default::default()
3425			};
3426			assert_eq!(
3427				commitments.ump_signals(),
3428				Err(CommittedCandidateReceiptError::DuplicateUMPSignal)
3429			);
3430		}
3431	}
3432
3433	#[test]
3434	fn ump_signal_count_and_indices_are_pinned() {
3435		let requires = RequiresSet::try_from_iter([(Id::from(1u32), Default::default())]).unwrap();
3436		let all = [
3437			UMPSignal::SelectCore(CoreSelector(0), ClaimQueueOffset(0)),
3438			UMPSignal::ApprovedPeer(Default::default()),
3439			UMPSignal::Provides(Default::default()),
3440			UMPSignal::Requires(requires),
3441		];
3442		for (index, signal) in all.iter().enumerate() {
3443			// Exhaustive, so a new variant fails to compile until it is listed in `all`.
3444			match signal {
3445				UMPSignal::SelectCore(..) |
3446				UMPSignal::ApprovedPeer(..) |
3447				UMPSignal::Provides(..) |
3448				UMPSignal::Requires(..) => {},
3449			}
3450			assert_eq!(signal.encode()[0] as usize, index);
3451		}
3452		assert_eq!(UMPSignal::COUNT, all.len());
3453	}
3454
3455	#[test]
3456	fn ump_signals_rejects_more_than_max_signals() {
3457		// One of every variant (== `MAX_UMP_SIGNALS`) plus one extra is rejected.
3458		let upward_messages = alloc::vec![
3459			UMP_SEPARATOR,
3460			UMPSignal::SelectCore(CoreSelector(0), ClaimQueueOffset(0)).encode(),
3461			UMPSignal::ApprovedPeer(Default::default()).encode(),
3462			UMPSignal::Provides(Default::default()).encode(),
3463			UMPSignal::Requires(
3464				RequiresSet::try_from_iter([(Id::from(3u32), StreamsRoot(Hash::repeat_byte(3)))])
3465					.unwrap(),
3466			)
3467			.encode(),
3468			UMPSignal::SelectCore(CoreSelector(1), ClaimQueueOffset(1)).encode(),
3469		];
3470
3471		let commitments = CandidateCommitments {
3472			upward_messages: upward_messages.try_into().unwrap(),
3473			..Default::default()
3474		};
3475
3476		assert_eq!(
3477			commitments.ump_signals(),
3478			Err(CommittedCandidateReceiptError::TooManyUMPSignals)
3479		);
3480	}
3481
3482	#[test]
3483	fn group_for_core_is_core_for_group() {
3484		for cores in 1..=256 {
3485			for rotations in 0..(cores * 2) {
3486				let info = GroupRotationInfo {
3487					session_start_block: 0u32,
3488					now: rotations,
3489					group_rotation_frequency: 1,
3490				};
3491
3492				for core in 0..cores {
3493					let group = info.group_for_core(CoreIndex(core), cores as usize);
3494					assert_eq!(info.core_for_group(group, cores as usize).0, core);
3495				}
3496			}
3497		}
3498	}
3499
3500	#[test]
3501	fn test_byzantine_threshold() {
3502		assert_eq!(byzantine_threshold(0), 0);
3503		assert_eq!(byzantine_threshold(1), 0);
3504		assert_eq!(byzantine_threshold(2), 0);
3505		assert_eq!(byzantine_threshold(3), 0);
3506		assert_eq!(byzantine_threshold(4), 1);
3507		assert_eq!(byzantine_threshold(5), 1);
3508		assert_eq!(byzantine_threshold(6), 1);
3509		assert_eq!(byzantine_threshold(7), 2);
3510	}
3511
3512	#[test]
3513	fn test_supermajority_threshold() {
3514		assert_eq!(supermajority_threshold(0), 0);
3515		assert_eq!(supermajority_threshold(1), 1);
3516		assert_eq!(supermajority_threshold(2), 2);
3517		assert_eq!(supermajority_threshold(3), 3);
3518		assert_eq!(supermajority_threshold(4), 3);
3519		assert_eq!(supermajority_threshold(5), 4);
3520		assert_eq!(supermajority_threshold(6), 5);
3521		assert_eq!(supermajority_threshold(7), 5);
3522	}
3523
3524	#[test]
3525	fn balance_bigger_than_usize() {
3526		let zero_b: Balance = 0;
3527		let zero_u: usize = 0;
3528
3529		assert!(zero_b.leading_zeros() >= zero_u.leading_zeros());
3530	}
3531
3532	fn make_v2_descriptor() -> CandidateDescriptorV2 {
3533		CandidateDescriptorV2::new(
3534			Id::from(1u32),
3535			Hash::repeat_byte(1),
3536			CoreIndex(0),
3537			1,
3538			Hash::repeat_byte(2),
3539			Hash::repeat_byte(3),
3540			Hash::repeat_byte(4),
3541			Hash::repeat_byte(5),
3542			ValidationCodeHash::from(Hash::repeat_byte(6)),
3543		)
3544	}
3545
3546	fn make_v3_descriptor() -> CandidateDescriptorV2 {
3547		CandidateDescriptorV2::new_v3(
3548			Id::from(1u32),
3549			Hash::repeat_byte(1),
3550			CoreIndex(0),
3551			1, // session_index
3552			1, // scheduling_session_index
3553			Hash::repeat_byte(2),
3554			Hash::repeat_byte(3),
3555			Hash::repeat_byte(4),
3556			Hash::repeat_byte(5),
3557			ValidationCodeHash::from(Hash::repeat_byte(6)),
3558			Hash::repeat_byte(7), // scheduling_parent
3559		)
3560	}
3561
3562	#[test]
3563	fn check_version_acceptance_v1_consistent() {
3564		// A V1 descriptor (created from old-style with non-zero collator fields)
3565		// Both old and new rules agree → passes regardless of v3_enabled.
3566		let mut desc = make_v2_descriptor();
3567		// Put non-zero bytes in first 16 bytes of reserved1 to trigger V1 in both
3568		// old and new detection.
3569		desc.reserved1[0] = 0xFF;
3570
3571		assert_eq!(desc.version(), CandidateDescriptorVersion::V1);
3572		assert_eq!(desc.version_old_rules(), CandidateDescriptorVersion::V1);
3573		assert!(desc.check_version_consistency());
3574
3575		assert!(desc.check_version_acceptance(false).is_ok());
3576		assert!(desc.check_version_acceptance(true).is_ok());
3577	}
3578
3579	#[test]
3580	fn check_version_acceptance_v2_consistent() {
3581		// A clean V2 descriptor: both rules agree → passes always.
3582		let desc = make_v2_descriptor();
3583
3584		assert_eq!(desc.version(), CandidateDescriptorVersion::V2);
3585		assert_eq!(desc.version_old_rules(), CandidateDescriptorVersion::V2);
3586		assert!(desc.check_version_consistency());
3587
3588		assert!(desc.check_version_acceptance(false).is_ok());
3589		assert!(desc.check_version_acceptance(true).is_ok());
3590	}
3591
3592	#[test]
3593	fn check_version_acceptance_v3_when_enabled() {
3594		// V3 descriptor with v3_enabled=true → passes.
3595		let desc = make_v3_descriptor();
3596
3597		assert_eq!(desc.version(), CandidateDescriptorVersion::V3);
3598		assert_eq!(desc.version_old_rules(), CandidateDescriptorVersion::V1);
3599		assert!(!desc.check_version_consistency());
3600
3601		assert!(desc.check_version_acceptance(true).is_ok());
3602	}
3603
3604	#[test]
3605	fn check_version_acceptance_v3_when_disabled() {
3606		// V3 descriptor with v3_enabled=false → rejected.
3607		// The consistency check fires first (old rules see V1, new rules see V3,
3608		// and V3 disagreement is not expected when v3_enabled=false).
3609		let desc = make_v3_descriptor();
3610
3611		assert_eq!(desc.version(), CandidateDescriptorVersion::V3);
3612		assert_eq!(
3613			desc.check_version_acceptance(false),
3614			Err(CandidateDescriptorVersionCheckError::Inconsistency)
3615		);
3616	}
3617
3618	#[test]
3619	fn check_version_acceptance_ambiguous_rejected() {
3620		// Craft descriptor where old rules see V1, new rules see V2.
3621		// reserved1[16..24] non-zero, reserved1[0..16] all zero, version=0.
3622		let mut desc = make_v2_descriptor();
3623		desc.reserved1[16] = 0xFF; // triggers old V1 check but not new
3624
3625		assert_eq!(desc.version(), CandidateDescriptorVersion::V2);
3626		assert_eq!(desc.version_old_rules(), CandidateDescriptorVersion::V1);
3627		assert!(!desc.check_version_consistency());
3628
3629		// Rejected regardless of v3_enabled.
3630		assert_eq!(
3631			desc.check_version_acceptance(false),
3632			Err(CandidateDescriptorVersionCheckError::Inconsistency)
3633		);
3634		assert_eq!(
3635			desc.check_version_acceptance(true),
3636			Err(CandidateDescriptorVersionCheckError::Inconsistency)
3637		);
3638	}
3639
3640	#[test]
3641	fn check_version_consistency_v3_expected_disagreement() {
3642		// V3 descriptor: version() returns V3, version_old_rules() returns V1.
3643		// check_version_consistency() is false — but this is expected.
3644		let desc = make_v3_descriptor();
3645
3646		assert_eq!(desc.version(), CandidateDescriptorVersion::V3);
3647		assert_eq!(desc.version_old_rules(), CandidateDescriptorVersion::V1);
3648		assert!(!desc.check_version_consistency());
3649		// Accepted when V3 is enabled.
3650		assert!(desc.check_version_acceptance(true).is_ok());
3651	}
3652
3653	#[test]
3654	fn v3_feature_activation_changes_descriptor_interpretation() {
3655		let desc = make_v3_descriptor();
3656
3657		// Sanity: the descriptor IS V3 under new rules but looks like V1 under old rules.
3658		assert_eq!(desc.version(), CandidateDescriptorVersion::V3);
3659		assert_eq!(desc.version_old_rules(), CandidateDescriptorVersion::V1);
3660
3661		// Before V3 activation: descriptor is treated as V1 — relay_parent is used.
3662		assert_eq!(desc.version_for_candidate_validation(false), CandidateDescriptorVersion::V1,);
3663		assert_eq!(
3664			desc.scheduling_parent_for_candidate_validation(false),
3665			Hash::repeat_byte(1), // relay_parent
3666		);
3667		assert_eq!(
3668			desc.scheduling_session_for_candidate_validation(false),
3669			None,
3670			"V1 has no embedded session — must be fetched from runtime",
3671		);
3672
3673		// After V3 activation: descriptor is correctly identified as V3.
3674		assert_eq!(desc.version_for_candidate_validation(true), CandidateDescriptorVersion::V3,);
3675		assert_eq!(
3676			desc.scheduling_parent_for_candidate_validation(true),
3677			Hash::repeat_byte(7), // scheduling_parent
3678		);
3679		assert_eq!(
3680			desc.scheduling_session_for_candidate_validation(true),
3681			Some(1), // session_index from descriptor, offset=0
3682		);
3683	}
3684
3685	#[test]
3686	fn check_version_acceptance_ambiguous_scheduling_parent_nonzero() {
3687		// Descriptor with scheduling_parent non-zero but version=0.
3688		// Old rules: V1 (scheduling_parent non-zero triggers old_v1_detected).
3689		// New rules: V2 (only checks reserved1[0..16], which is zero).
3690		let mut desc = make_v2_descriptor();
3691		desc.scheduling_parent = Hash::repeat_byte(0xAB);
3692
3693		assert_eq!(desc.version(), CandidateDescriptorVersion::V2);
3694		assert_eq!(desc.version_old_rules(), CandidateDescriptorVersion::V1);
3695		assert!(!desc.check_version_consistency());
3696
3697		assert_eq!(
3698			desc.check_version_acceptance(false),
3699			Err(CandidateDescriptorVersionCheckError::Inconsistency)
3700		);
3701		assert_eq!(
3702			desc.check_version_acceptance(true),
3703			Err(CandidateDescriptorVersionCheckError::Inconsistency)
3704		);
3705	}
3706
3707	/// Codec index of the `ApprovalCheckingMultipleCandidates` variant (`#[codec(index = 4)]`).
3708	const APPROVAL_MULTIPLE_CANDIDATES_INDEX: u8 = 4;
3709
3710	fn coalesced_candidate_hashes(n: usize) -> Vec<CandidateHash> {
3711		(0..n).map(|i| CandidateHash(Hash::repeat_byte(i as u8))).collect()
3712	}
3713
3714	/// SCALE bytes for the `ApprovalCheckingMultipleCandidates` variant with a plain
3715	/// `Vec<CandidateHash>` body: the codec index byte followed by the `Vec` body (compact length
3716	/// + elements).
3717	fn approval_multiple_candidates_vec_bytes(hashes: &[CandidateHash]) -> Vec<u8> {
3718		let mut bytes = vec![APPROVAL_MULTIPLE_CANDIDATES_INDEX];
3719		bytes.extend(hashes.encode());
3720		bytes
3721	}
3722
3723	#[test]
3724	fn approval_multiple_candidates_bounded_vec_encodes_like_vec() {
3725		let limit = MAX_COALESCE_APPROVALS as usize;
3726		for n in [0, 1, 2, 8, limit - 1, limit] {
3727			let hashes = coalesced_candidate_hashes(n);
3728			let bounded: BoundedVec<CandidateHash, ConstU32<{ MAX_COALESCE_APPROVALS }>> =
3729				hashes.clone().try_into().expect("n <= MAX_COALESCE_APPROVALS; qed");
3730
3731			// The inner collections encode to identical bytes.
3732			assert_eq!(hashes.encode(), bounded.encode(), "inner encoding differs for n = {n}");
3733
3734			// The full enum encodes identically to a plain `Vec` body.
3735			assert_eq!(
3736				ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates(bounded).encode(),
3737				approval_multiple_candidates_vec_bytes(&hashes),
3738				"enum encoding differs from the plain Vec encoding for n = {n}",
3739			);
3740		}
3741	}
3742
3743	#[test]
3744	fn approval_multiple_candidates_decodes_vec_encoding() {
3745		let limit = MAX_COALESCE_APPROVALS as usize;
3746		for n in [0, 1, limit - 1, limit] {
3747			let hashes = coalesced_candidate_hashes(n);
3748			let vec_bytes = approval_multiple_candidates_vec_bytes(&hashes);
3749
3750			// A plain `Vec` encoding decodes into the `BoundedVec`-based variant.
3751			let decoded = ValidDisputeStatementKind::decode(&mut &vec_bytes[..])
3752				.expect("a Vec encoding within the limit must decode; qed");
3753			let expected = ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates(
3754				hashes.clone().try_into().expect("n <= MAX_COALESCE_APPROVALS; qed"),
3755			);
3756			assert_eq!(decoded, expected, "decode mismatch for n = {n}");
3757
3758			// A full round-trip through the type is stable.
3759			assert_eq!(
3760				ValidDisputeStatementKind::decode(&mut &expected.encode()[..]).unwrap(),
3761				expected,
3762			);
3763		}
3764	}
3765
3766	#[test]
3767	fn approval_multiple_candidates_rejects_above_limit() {
3768		let limit = MAX_COALESCE_APPROVALS as usize;
3769
3770		// One past the limit is rejected at the length prefix, directly as the bounded collection.
3771		let too_many = coalesced_candidate_hashes(limit + 1);
3772		assert!(
3773			BoundedVec::<CandidateHash, ConstU32<{ MAX_COALESCE_APPROVALS }>>::decode(
3774				&mut &too_many.encode()[..]
3775			)
3776			.is_err(),
3777			"BoundedVec must reject more than MAX_COALESCE_APPROVALS elements",
3778		);
3779
3780		// Through the enum, using a plain `Vec` body carrying one too many candidates.
3781		let vec_bytes = approval_multiple_candidates_vec_bytes(&too_many);
3782		assert!(
3783			ValidDisputeStatementKind::decode(&mut &vec_bytes[..]).is_err(),
3784			"enum must reject more than MAX_COALESCE_APPROVALS coalesced candidates",
3785		);
3786
3787		// The boundary value of exactly MAX_COALESCE_APPROVALS is accepted.
3788		let at_limit = approval_multiple_candidates_vec_bytes(&coalesced_candidate_hashes(limit));
3789		assert!(ValidDisputeStatementKind::decode(&mut &at_limit[..]).is_ok());
3790	}
3791
3792	#[test]
3793	fn approval_multiple_candidates_signing_payload_matches_vec() {
3794		let session = 7;
3795		for n in [1, 2, MAX_COALESCE_APPROVALS as usize] {
3796			let hashes = coalesced_candidate_hashes(n);
3797			let bounded: BoundedVec<CandidateHash, ConstU32<{ MAX_COALESCE_APPROVALS }>> =
3798				hashes.clone().try_into().expect("n <= MAX_COALESCE_APPROVALS; qed");
3799
3800			// The signing payload is taken over a slice, so `Vec` and `BoundedVec` produce the
3801			// same payload bytes for the same candidate set.
3802			assert_eq!(
3803				ApprovalVoteMultipleCandidates(&hashes).signing_payload(session),
3804				ApprovalVoteMultipleCandidates(&bounded).signing_payload(session),
3805				"signing payload differs for n = {n}",
3806			);
3807		}
3808	}
3809}