1use 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
48pub 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
57pub 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
64pub use polkadot_parachain_primitives::primitives::{
66 HeadData, HorizontalMessages, HrmpChannelId, Id, Id as ParaId, UpwardMessage, UpwardMessages,
67 ValidationCode, ValidationCodeHash, LOWEST_PUBLIC_ID,
68};
69
70mod 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
92pub 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
101pub type CollatorId = collator_app::Public;
103
104#[cfg(feature = "std")]
106pub type CollatorPair = collator_app::Pair;
107
108pub type CollatorSignature = collator_app::Signature;
110
111pub 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
119pub type ValidatorId = validator_app::Public;
124
125pub trait TypeIndex {
127 fn type_index(&self) -> usize;
129}
130
131#[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#[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
177impl 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 pub type ValidatorPair = validator_app::Pair;
193}
194
195pub type ValidatorSignature = validator_app::Signature;
200
201pub 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 pub const EPOCH_INDEX: &[u8] =
225 &hex!["1cb6f36e027abb2091cfb5110ab5087f38316cbf8fa0da822a20ac1c55bf1be3"];
226
227 pub const CURRENT_BLOCK_RANDOMNESS: &[u8] =
231 &hex!["1cb6f36e027abb2091cfb5110ab5087fd077dfdb8adb10f78f10a5df8742c545"];
232
233 pub const ONE_EPOCH_AGO_RANDOMNESS: &[u8] =
237 &hex!["1cb6f36e027abb2091cfb5110ab5087f7ce678799d3eff024253b90e84927cc6"];
238
239 pub const TWO_EPOCHS_AGO_RANDOMNESS: &[u8] =
243 &hex!["1cb6f36e027abb2091cfb5110ab5087f7a414cb008e0e61e46722aa60abdd672"];
244
245 pub const CURRENT_SLOT: &[u8] =
249 &hex!["1cb6f36e027abb2091cfb5110ab5087f06155b3cd9a8c9e5e9a23fd5dc13a5ed"];
250
251 pub const ACTIVE_CONFIG: &[u8] =
255 &hex!["06de3d8a54d27e44a9d5ce189618f22db4b49d95320d9021994c850f25b8e385"];
256
257 pub const AUTHORITIES: &[u8] =
262 &hex!["1cb6f36e027abb2091cfb5110ab5087f5e0621c4869aa60c02be9adcc98a0d1d"];
263
264 pub const NEXT_AUTHORITIES: &[u8] =
269 &hex!["1cb6f36e027abb2091cfb5110ab5087faacf00b9b41fda7a9268821c2a2b3e4c"];
270
271 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 #[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 #[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 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 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 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 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 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 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 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
433pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u64 = 6000;
436
437pub const PARACHAINS_INHERENT_IDENTIFIER: InherentIdentifier = *b"parachn0";
439
440pub const ASSIGNMENT_KEY_TYPE_ID: KeyTypeId = KeyTypeId(*b"asgn");
442
443pub const MIN_CODE_SIZE: u32 = 9;
445
446pub const MAX_CODE_SIZE: u32 = 5 * 1024 * 1024;
455
456pub const MAX_HEAD_DATA_SIZE: u32 = 1 * 1024 * 1024;
463
464pub const MAX_POV_SIZE: u32 = 10 * 1024 * 1024;
472
473pub const ON_DEMAND_DEFAULT_QUEUE_MAX_SIZE: u32 = 10_000;
477
478pub const ON_DEMAND_MAX_QUEUE_MAX_SIZE: u32 = 10_000;
482
483pub const LEGACY_MIN_BACKING_VOTES: u32 = 2;
486
487pub const DEFAULT_SCHEDULING_LOOKAHEAD: u32 = 3;
489
490mod assignment_app {
493 use sp_application_crypto::{app_crypto, sr25519};
494 app_crypto!(sr25519, super::ASSIGNMENT_KEY_TYPE_ID);
495}
496
497pub type AssignmentId = assignment_app::Public;
500
501sp_application_crypto::with_pair! {
502 pub type AssignmentPair = assignment_app::Pair;
505}
506
507pub type CandidateIndex = u32;
509
510#[derive(PartialEq, Eq, Clone, Encode, Decode, DecodeWithMemTracking, TypeInfo, Debug)]
532#[cfg_attr(feature = "std", derive(Default))]
533pub struct PersistedValidationData<H = Hash, N = BlockNumber> {
534 pub parent_head: HeadData,
536 pub relay_parent_number: N,
538 pub relay_parent_storage_root: H,
540 pub max_pov_size: u32,
542}
543
544impl<H: Encode, N: Encode> PersistedValidationData<H, N> {
545 pub fn hash(&self) -> Hash {
547 BlakeTwo256::hash_of(self)
548 }
549}
550
551#[derive(PartialEq, Eq, Clone, Encode, Decode, DecodeWithMemTracking, TypeInfo, Debug)]
553#[cfg_attr(feature = "std", derive(Default, Hash))]
554pub struct CandidateCommitments<N = BlockNumber> {
555 pub upward_messages: UpwardMessages,
557 pub horizontal_messages: HorizontalMessages,
559 pub new_validation_code: Option<ValidationCode>,
561 pub head_data: HeadData,
563 pub processed_downward_messages: u32,
565 pub hrmp_watermark: N,
568}
569
570impl CandidateCommitments {
571 pub fn hash(&self) -> Hash {
573 BlakeTwo256::hash_of(self)
574 }
575}
576
577#[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
589pub type SignedStatement = Signed<CompactStatement>;
591pub type UncheckedSignedStatement = UncheckedSigned<CompactStatement>;
593
594pub type SignedAvailabilityBitfield = Signed<AvailabilityBitfield>;
596pub type UncheckedSignedAvailabilityBitfield = UncheckedSigned<AvailabilityBitfield>;
598
599pub type SignedAvailabilityBitfields = Vec<SignedAvailabilityBitfield>;
601pub type UncheckedSignedAvailabilityBitfields = Vec<UncheckedSignedAvailabilityBitfield>;
604
605pub 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#[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#[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#[derive(Clone, Encode, Decode, TypeInfo, PartialEq, Debug)]
742pub struct ParathreadClaim(pub Id, pub Option<CollatorId>);
743
744#[derive(Clone, Encode, Decode, TypeInfo, PartialEq, Debug)]
746pub struct ParathreadEntry {
747 pub claim: ParathreadClaim,
749 pub retries: u32,
751}
752
753#[derive(Clone, Encode, Decode, TypeInfo, Debug)]
755#[cfg_attr(feature = "std", derive(PartialEq))]
756pub struct GroupRotationInfo<N = BlockNumber> {
757 pub session_start_block: N,
759 pub group_rotation_frequency: N,
761 pub now: N,
763}
764
765impl GroupRotationInfo {
766 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 let idx = (core_index.0 as usize + rotations as usize) % cores;
785 GroupIndex(idx as u32)
786 }
787
788 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 let idx = (group_index.0 as usize + cores - rotations as usize) % cores;
811 CoreIndex(idx as u32)
812 }
813
814 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 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 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#[derive(Clone, Encode, Decode, TypeInfo, Debug)]
843#[cfg_attr(feature = "std", derive(PartialEq))]
844pub struct ScheduledCore {
845 pub para_id: Id,
847 pub collator: Option<CollatorId>,
851}
852
853#[derive(Clone, Copy, Encode, Decode, TypeInfo, Debug)]
855#[cfg_attr(feature = "std", derive(PartialEq, Eq, Hash))]
856pub enum OccupiedCoreAssumption {
857 #[codec(index = 0)]
859 Included,
860 #[codec(index = 1)]
862 TimedOut,
863 #[codec(index = 2)]
865 Free,
866}
867
868#[derive(Clone, Debug)]
870pub struct ApprovalVote(pub CandidateHash);
871
872impl ApprovalVote {
873 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#[derive(Clone, Debug)]
883pub struct ApprovalVoteMultipleCandidates<'a>(pub &'a [CandidateHash]);
884
885impl<'a> ApprovalVoteMultipleCandidates<'a> {
886 pub fn signing_payload(&self, session_index: SessionIndex) -> Vec<u8> {
888 const MAGIC: [u8; 4] = *b"APPR";
889 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#[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 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#[repr(u8)]
930pub enum ValidityError {
931 InvalidEthereumSignature = 0,
933 SignerHasNoClaim = 1,
935 NoPermission = 2,
937 InvalidStatement = 3,
939}
940
941impl From<ValidityError> for u8 {
942 fn from(err: ValidityError) -> Self {
943 err as u8
944 }
945}
946
947#[derive(Clone, Encode, Decode, Debug, TypeInfo)]
950#[cfg_attr(feature = "std", derive(PartialEq))]
951pub struct AbridgedHostConfiguration {
952 pub max_code_size: u32,
954 pub max_head_data_size: u32,
956 pub max_upward_queue_count: u32,
958 pub max_upward_queue_size: u32,
962 pub max_upward_message_size: u32,
966 pub max_upward_message_num_per_candidate: u32,
970 pub hrmp_max_message_num_per_candidate: u32,
974 pub validation_upgrade_cooldown: BlockNumber,
976 pub validation_upgrade_delay: BlockNumber,
978 pub async_backing_params: AsyncBackingParams,
980}
981
982#[derive(Clone, Encode, Decode, Debug, TypeInfo)]
985#[cfg_attr(feature = "std", derive(Default, PartialEq))]
986pub struct AbridgedHrmpChannel {
987 pub max_capacity: u32,
989 pub max_total_size: u32,
991 pub max_message_size: u32,
993 pub msg_count: u32,
996 pub total_size: u32,
999 pub mqc_head: Option<Hash>,
1007}
1008
1009#[derive(Copy, Clone, Encode, Decode, PartialEq, Debug, TypeInfo)]
1011pub enum UpgradeRestriction {
1012 #[codec(index = 0)]
1015 Present,
1016}
1017
1018#[derive(Copy, Clone, Encode, Decode, PartialEq, Debug, TypeInfo)]
1024pub enum UpgradeGoAhead {
1025 #[codec(index = 0)]
1034 Abort,
1035 #[codec(index = 1)]
1039 GoAhead,
1040}
1041
1042pub const POLKADOT_ENGINE_ID: sp_runtime::ConsensusEngineId = *b"POL1";
1044
1045#[derive(Decode, Encode, Clone, PartialEq, Eq)]
1047pub enum ConsensusLog {
1048 #[codec(index = 1)]
1050 ParaUpgradeCode(Id, ValidationCodeHash),
1051 #[codec(index = 2)]
1053 ParaScheduleUpgradeCode(Id, ValidationCodeHash, BlockNumber),
1054 #[codec(index = 3)]
1057 ForceApprove(BlockNumber),
1058 #[codec(index = 4)]
1067 Revert(BlockNumber),
1068}
1069
1070impl ConsensusLog {
1071 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#[derive(Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Debug, TypeInfo)]
1094pub enum DisputeStatement {
1095 #[codec(index = 0)]
1097 Valid(ValidDisputeStatementKind),
1098 #[codec(index = 1)]
1100 Invalid(InvalidDisputeStatementKind),
1101}
1102
1103impl DisputeStatement {
1104 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 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 pub fn indicates_validity(&self) -> bool {
1168 match *self {
1169 DisputeStatement::Valid(_) => true,
1170 DisputeStatement::Invalid(_) => false,
1171 }
1172 }
1173
1174 pub fn indicates_invalidity(&self) -> bool {
1176 match *self {
1177 DisputeStatement::Valid(_) => false,
1178 DisputeStatement::Invalid(_) => true,
1179 }
1180 }
1181
1182 pub fn is_backing(&self) -> bool {
1184 match self {
1185 Self::Valid(s) => s.is_backing(),
1186 Self::Invalid(_) => false,
1187 }
1188 }
1189}
1190
1191pub const MAX_COALESCE_APPROVALS: u32 = 16;
1196
1197pub type CoalescedApprovalCandidateHashes =
1201 BoundedVec<CandidateHash, ConstU32<{ MAX_COALESCE_APPROVALS }>>;
1202
1203#[derive(Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Debug, TypeInfo)]
1205pub enum ValidDisputeStatementKind {
1206 #[codec(index = 0)]
1208 Explicit,
1209 #[codec(index = 1)]
1211 BackingSeconded(Hash),
1212 #[codec(index = 2)]
1214 BackingValid(Hash),
1215 #[codec(index = 3)]
1217 ApprovalChecking,
1218 #[codec(index = 4)]
1228 ApprovalCheckingMultipleCandidates(
1229 BoundedVec<CandidateHash, ConstU32<{ MAX_COALESCE_APPROVALS }>>,
1230 ),
1231}
1232
1233impl ValidDisputeStatementKind {
1234 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#[derive(Encode, Decode, DecodeWithMemTracking, Copy, Clone, PartialEq, Debug, TypeInfo)]
1248pub enum InvalidDisputeStatementKind {
1249 #[codec(index = 0)]
1251 Explicit,
1252}
1253
1254#[derive(Clone, PartialEq, Debug)]
1256pub struct ExplicitDisputeStatement {
1257 pub valid: bool,
1259 pub candidate_hash: CandidateHash,
1261 pub session: SessionIndex,
1263}
1264
1265impl ExplicitDisputeStatement {
1266 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#[derive(Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Debug, TypeInfo)]
1276pub struct DisputeStatementSet {
1277 pub candidate_hash: CandidateHash,
1279 pub session: SessionIndex,
1281 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
1297pub type MultiDisputeStatementSet = Vec<DisputeStatementSet>;
1299
1300#[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 pub fn unchecked_from_unchecked(unchecked: DisputeStatementSet) -> Self {
1320 Self(unchecked)
1321 }
1322}
1323
1324pub type CheckedMultiDisputeStatementSet = Vec<CheckedDisputeStatementSet>;
1326
1327#[derive(Encode, Decode, Clone, Debug, PartialEq, TypeInfo)]
1329pub struct DisputeState<N = BlockNumber> {
1330 pub validators_for: BitVec<u8, bitvec::order::Lsb0>, pub validators_against: BitVec<u8, bitvec::order::Lsb0>, pub start: N,
1336 pub concluded_at: Option<N>,
1338}
1339
1340#[derive(Clone, Eq, PartialEq, Decode, DecodeWithMemTracking, Encode, Debug, TypeInfo)]
1343pub enum ValidityAttestation {
1344 #[codec(index = 1)]
1347 Implicit(ValidatorSignature),
1348 #[codec(index = 2)]
1351 Explicit(ValidatorSignature),
1352}
1353
1354impl ValidityAttestation {
1355 pub fn to_compact_statement(&self, candidate_hash: CandidateHash) -> CompactStatement {
1358 match *self {
1362 ValidityAttestation::Implicit(_) => CompactStatement::Seconded(candidate_hash),
1363 ValidityAttestation::Explicit(_) => CompactStatement::Valid(candidate_hash),
1364 }
1365 }
1366
1367 pub fn signature(&self) -> &ValidatorSignature {
1369 match *self {
1370 ValidityAttestation::Implicit(ref sig) => sig,
1371 ValidityAttestation::Explicit(ref sig) => sig,
1372 }
1373 }
1374
1375 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#[derive(Clone, Eq, PartialEq, Default, Decode, Encode, Debug)]
1395pub struct SigningContext<H = Hash> {
1396 pub session_index: sp_staking::SessionIndex,
1398 pub parent_hash: H,
1400}
1401
1402const BACKING_STATEMENT_MAGIC: [u8; 4] = *b"BKNG";
1403
1404#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
1407#[cfg_attr(feature = "std", derive(Hash))]
1408pub enum CompactStatement {
1409 Seconded(CandidateHash),
1411 Valid(CandidateHash),
1413}
1414
1415impl CompactStatement {
1416 pub fn signing_payload(&self, context: &SigningContext) -> Vec<u8> {
1419 (self, context).encode()
1420 }
1421
1422 pub fn candidate_hash(&self) -> &CandidateHash {
1424 match *self {
1425 CompactStatement::Seconded(ref h) | CompactStatement::Valid(ref h) => h,
1426 }
1427 }
1428}
1429
1430#[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 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#[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 pub fn get(&self, index: K) -> Option<&V>
1503 where
1504 K: TypeIndex,
1505 {
1506 self.0.get(index.type_index())
1507 }
1508
1509 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 pub fn len(&self) -> usize {
1519 self.0.len()
1520 }
1521
1522 pub fn to_vec(&self) -> Vec<V> {
1524 self.0.clone()
1525 }
1526
1527 pub fn iter(&self) -> Iter<'_, V> {
1529 self.0.iter()
1530 }
1531
1532 pub fn iter_mut(&mut self) -> IterMut<'_, V> {
1534 self.0.iter_mut()
1535 }
1536
1537 pub fn into_iter(self) -> IntoIter<V> {
1539 self.0.into_iter()
1540 }
1541
1542 pub fn is_empty(&self) -> bool {
1544 self.0.is_empty()
1545 }
1546}
1547
1548pub const fn byzantine_threshold(n: usize) -> usize {
1552 n.saturating_sub(1) / 3
1553}
1554
1555pub const fn supermajority_threshold(n: usize) -> usize {
1558 n - byzantine_threshold(n)
1559}
1560
1561pub 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#[derive(Clone, Encode, Decode, Debug, TypeInfo)]
1574#[cfg_attr(feature = "std", derive(PartialEq))]
1575pub struct SessionInfo {
1576 pub active_validator_indices: Vec<ValidatorIndex>,
1580 pub random_seed: [u8; 32],
1582 pub dispute_period: SessionIndex,
1584
1585 pub validators: IndexedVec<ValidatorIndex, ValidatorId>,
1594 pub discovery_keys: Vec<AuthorityDiscoveryId>,
1601 pub assignment_keys: Vec<AssignmentId>,
1612 pub validator_groups: IndexedVec<GroupIndex, Vec<ValidatorIndex>>,
1616 pub n_cores: u32,
1618 pub zeroth_delay_tranche_width: u32,
1620 pub relay_vrf_modulo_samples: u32,
1622 pub n_delay_tranches: u32,
1624 pub no_show_slots: u32,
1627 pub needed_approvals: u32,
1629}
1630
1631#[derive(Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Debug, TypeInfo)]
1634pub struct PvfCheckStatement {
1635 pub accept: bool,
1637 pub subject: ValidationCodeHash,
1639 pub session_index: SessionIndex,
1641 pub validator_index: ValidatorIndex,
1643}
1644
1645impl PvfCheckStatement {
1646 pub fn signing_payload(&self) -> Vec<u8> {
1651 const MAGIC: [u8; 4] = *b"VCPC"; (MAGIC, self.accept, self.subject, self.session_index, self.validator_index).encode()
1653 }
1654}
1655
1656pub struct WellKnownKey<T> {
1660 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 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 pub fn set(&self, value: T) {
1688 sp_io::storage::set(&self.key, &value.encode());
1689 }
1690}
1691
1692#[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 Precheck,
1709
1710 Prepare,
1712}
1713
1714#[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 Backing,
1731 Approval,
1733}
1734
1735pub type NodeFeatures = BitVec<u8, bitvec::order::Lsb0>;
1737
1738pub mod node_features {
1740 use crate::NodeFeatures;
1741
1742 #[repr(u8)]
1745 #[derive(Clone, Copy)]
1746 pub enum FeatureIndex {
1747 EnableAssignmentsV2 = 0,
1750 ElasticScalingMVP = 1,
1754 AvailabilityChunkMapping = 2,
1760 CandidateReceiptV2 = 3,
1764 CandidateReceiptV3 = 4,
1766 FirstUnassigned = 5,
1770 }
1771
1772 impl FeatureIndex {
1773 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#[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 pub group_rotation_frequency: BlockNumber,
1798 pub paras_availability_period: BlockNumber,
1813 pub max_validators_per_core: Option<u32>,
1817 pub lookahead: u32,
1819 pub num_cores: u32,
1821 #[deprecated]
1824 pub max_availability_timeouts: u32,
1825 pub on_demand_queue_max_size: u32,
1827 pub on_demand_target_queue_utilization: Perbill,
1829 pub on_demand_fee_variability: Perbill,
1832 pub on_demand_base_fee: Balance,
1834 #[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#[derive(PartialEq, Eq, Copy, Clone, Encode, Decode, TypeInfo, Debug, PartialOrd, Ord, Hash)]
1861pub enum CandidateDescriptorVersion {
1862 V1,
1864 V2,
1872 V3,
1874 Unknown(u8),
1878}
1879
1880#[derive(Debug, Copy, Clone, PartialEq, Eq)]
1882pub enum CandidateDescriptorVersionCheckError {
1883 Inconsistency,
1886 V3NotEnabled,
1888}
1889
1890impl 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#[derive(PartialEq, Eq, Clone, Encode, Decode, DecodeWithMemTracking, TypeInfo)]
1905pub struct CandidateDescriptorV2<H = Hash> {
1906 pub(super) para_id: ParaId,
1908 relay_parent: H,
1910 pub(super) version: u8,
1915 pub(super) core_index: u16,
1917 session_index: SessionIndex,
1919 scheduling_session_offset: u8,
1924 reserved1: [u8; 24],
1926 persisted_validation_data_hash: Hash,
1930 pov_hash: Hash,
1932 erasure_root: Hash,
1934 scheduling_parent: H, reserved2: [u8; 32],
1938 para_head: Hash,
1940 validation_code_hash: ValidationCodeHash,
1942}
1943
1944impl<H: AsRef<[u8]>> CandidateDescriptorV2<H> {
1945 pub fn version(&self) -> CandidateDescriptorVersion {
2009 self.v3_version()
2010 }
2011
2012 pub fn version_old_rules(&self) -> CandidateDescriptorVersion {
2023 self.v2_version()
2024 }
2025
2026 pub fn check_version_consistency(&self) -> bool {
2033 self.version() == self.version_old_rules()
2034 }
2035
2036 pub fn check_version_acceptance(
2053 &self,
2054 v3_enabled: bool,
2055 ) -> Result<(), CandidateDescriptorVersionCheckError> {
2056 let version = self.version();
2057
2058 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 if version == CandidateDescriptorVersion::V3 && !v3_enabled {
2067 return Err(CandidateDescriptorVersionCheckError::V3NotEnabled);
2068 }
2069
2070 Ok(())
2071 }
2072
2073 fn v2_version(&self) -> CandidateDescriptorVersion {
2074 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 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 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 #[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 #[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 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 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 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 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 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 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 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 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 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 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 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 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#[cfg(feature = "test")]
2511pub trait MutateDescriptorV2<H> {
2512 fn set_relay_parent(&mut self, relay_parent: H);
2514 fn set_para_id(&mut self, para_id: Id);
2516 fn set_pov_hash(&mut self, pov_hash: Hash);
2518 fn set_version(&mut self, version: u8);
2520 fn set_persisted_validation_data_hash(&mut self, persisted_validation_data_hash: Hash);
2522 fn set_validation_code_hash(&mut self, validation_code_hash: ValidationCodeHash);
2524 fn set_erasure_root(&mut self, erasure_root: Hash);
2526 fn set_para_head(&mut self, para_head: Hash);
2528 fn set_core_index(&mut self, core_index: CoreIndex);
2530 fn set_session_index(&mut self, session_index: SessionIndex);
2532 fn set_reserved2(&mut self, reserved2: [u8; 32]);
2534 fn set_scheduling_parent(&mut self, scheduling_parent: H);
2536 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#[derive(PartialEq, Eq, Clone, Encode, Decode, DecodeWithMemTracking, TypeInfo, Debug)]
2597pub struct CandidateReceiptV2<H = Hash> {
2598 pub descriptor: CandidateDescriptorV2<H>,
2600 pub commitments_hash: Hash,
2602}
2603
2604#[derive(PartialEq, Eq, Clone, Encode, Decode, DecodeWithMemTracking, TypeInfo, Debug)]
2606pub struct CommittedCandidateReceiptV2<H = Hash> {
2607 pub descriptor: CandidateDescriptorV2<H>,
2609 pub commitments: CandidateCommitments,
2611}
2612
2613#[derive(Clone, Encode, Decode, TypeInfo, Debug)]
2615#[cfg_attr(feature = "std", derive(PartialEq))]
2616pub enum CandidateEvent<H = Hash> {
2617 #[codec(index = 0)]
2620 CandidateBacked(CandidateReceiptV2<H>, HeadData, CoreIndex, GroupIndex),
2621 #[codec(index = 1)]
2625 CandidateIncluded(CandidateReceiptV2<H>, HeadData, CoreIndex, GroupIndex),
2626 #[codec(index = 2)]
2629 CandidateTimedOut(CandidateReceiptV2<H>, HeadData, CoreIndex),
2630}
2631
2632impl<H> CandidateReceiptV2<H> {
2633 pub fn descriptor(&self) -> &CandidateDescriptorV2<H> {
2635 &self.descriptor
2636 }
2637
2638 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 pub fn to_plain(&self) -> CandidateReceiptV2<H> {
2650 CandidateReceiptV2 {
2651 descriptor: self.descriptor.clone(),
2652 commitments_hash: self.commitments.hash(),
2653 }
2654 }
2655
2656 pub fn hash(&self) -> CandidateHash
2661 where
2662 H: Encode,
2663 {
2664 self.to_plain().hash()
2665 }
2666
2667 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#[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#[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#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, Debug)]
2714pub enum UMPSignal {
2715 SelectCore(CoreSelector, ClaimQueueOffset),
2719 ApprovedPeer(ApprovedPeerId),
2721 Provides(StreamsRoot),
2724 Requires(RequiresSet),
2728}
2729
2730impl UMPSignal {
2731 const COUNT: usize = 4;
2733}
2734
2735pub const DEFAULT_CLAIM_QUEUE_OFFSET: u8 = 0;
2738
2739pub type ApprovedPeerId = BoundedVec<u8, ConstU32<64>>;
2743
2744#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, Debug, Default)]
2745pub 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 pub fn core_selector(&self) -> Option<(CoreSelector, ClaimQueueOffset)> {
2756 self.select_core
2757 }
2758
2759 pub fn approved_peer(&self) -> Option<&ApprovedPeerId> {
2761 self.approved_peer.as_ref()
2762 }
2763
2764 pub fn provides(&self) -> Option<&StreamsRoot> {
2766 self.provides.as_ref()
2767 }
2768
2769 pub fn requires(&self) -> Option<&RequiresSet> {
2771 self.requires.as_ref()
2772 }
2773
2774 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 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
2820pub const UMP_SEPARATOR: Vec<u8> = vec![];
2822
2823pub const MAX_UMP_SIGNALS: usize = UMPSignal::COUNT;
2826
2827pub 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 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 return Ok(res);
2846 }
2847
2848 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 if signals_iter.next().is_some() {
2858 return Err(CommittedCandidateReceiptError::TooManyUMPSignals);
2859 }
2860
2861 Ok(res)
2862 }
2863}
2864
2865#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, Debug)]
2867#[cfg_attr(feature = "std", derive(thiserror::Error))]
2868pub enum CommittedCandidateReceiptError {
2869 #[cfg_attr(feature = "std", error("The specified core index is invalid"))]
2871 InvalidCoreIndex,
2872 #[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 descriptor: CoreIndex,
2880 commitments: CoreIndex,
2882 },
2883 #[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 UmpSignalDecode,
2889 #[cfg_attr(
2891 feature = "std",
2892 error("The parachain is not assigned to any core at specified claim queue offset")
2893 )]
2894 NoAssignment,
2895 #[cfg_attr(feature = "std", error("Unknown internal version"))]
2897 UnknownVersion(u8),
2898 #[cfg_attr(feature = "std", error("Too many UMP signals"))]
2900 TooManyUMPSignals,
2901 #[cfg_attr(feature = "std", error("Duplicate UMP signal"))]
2903 DuplicateUMPSignal,
2904 #[cfg_attr(feature = "std", error("Version 1 receipt does not support ump signals"))]
2907 UMPSignalWithV1Descriptor,
2908 #[cfg_attr(feature = "std", error("Version 3 receipt requires ump signals"))]
2921 NoUMPSignalWithV3Descriptor,
2922}
2923
2924impl<H: Copy + AsRef<[u8]>> CommittedCandidateReceiptV2<H> {
2925 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
2951pub 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 !signals.is_empty() {
2971 return Err(CommittedCandidateReceiptError::UMPSignalWithV1Descriptor);
2972 }
2973
2974 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 return Err(CommittedCandidateReceiptError::NoUMPSignalWithV3Descriptor);
2984 },
2985 _ => {},
2986 }
2987
2988 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 Ok(signals)
2999}
3000
3001fn 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(¶_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 core_index_selector
3024 } else if assigned_cores.len() > 1 {
3025 if !assigned_cores.contains(&descriptor_core_index) {
3027 return Err(CommittedCandidateReceiptError::InvalidCoreIndex);
3029 } else {
3030 return Ok(());
3033 }
3034 } else {
3035 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#[derive(Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Eq, Debug, TypeInfo)]
3057pub struct BackedCandidate<H = Hash> {
3058 candidate: CommittedCandidateReceiptV2<H>,
3060 validity_votes: Vec<ValidityAttestation>,
3062 validator_indices: BitVec<u8, bitvec::order::Lsb0>,
3066}
3067
3068#[derive(Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Debug, TypeInfo)]
3070pub struct InherentData<HDR: HeaderT = Header> {
3071 pub bitfields: UncheckedSignedAvailabilityBitfields,
3073 pub backed_candidates: Vec<BackedCandidate<HDR::Hash>>,
3075 pub disputes: MultiDisputeStatementSet,
3077 pub parent_header: HDR,
3079}
3080
3081impl<H> BackedCandidate<H> {
3082 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 pub fn candidate(&self) -> &CommittedCandidateReceiptV2<H> {
3096 &self.candidate
3097 }
3098
3099 #[cfg(feature = "test")]
3102 pub fn candidate_mut(&mut self) -> &mut CommittedCandidateReceiptV2<H> {
3103 &mut self.candidate
3104 }
3105 pub fn descriptor(&self) -> &CandidateDescriptorV2<H> {
3107 &self.candidate.descriptor
3108 }
3109
3110 #[cfg(feature = "test")]
3112 pub fn descriptor_mut(&mut self) -> &mut CandidateDescriptorV2<H> {
3113 &mut self.candidate.descriptor
3114 }
3115
3116 pub fn validity_votes(&self) -> &[ValidityAttestation] {
3118 &self.validity_votes
3119 }
3120
3121 pub fn validity_votes_mut(&mut self) -> &mut Vec<ValidityAttestation> {
3123 &mut self.validity_votes
3124 }
3125
3126 pub fn hash(&self) -> CandidateHash
3128 where
3129 H: Clone + Encode,
3130 {
3131 self.candidate.to_plain().hash()
3132 }
3133
3134 pub fn receipt(&self) -> CandidateReceiptV2<H>
3136 where
3137 H: Clone,
3138 {
3139 self.candidate.to_plain()
3140 }
3141
3142 #[cfg(feature = "test")]
3144 pub fn raw_validator_indices(&self) -> BitVec<u8, bitvec::order::Lsb0> {
3145 self.validator_indices.clone()
3146 }
3147
3148 pub fn validator_indices_and_core_index(
3150 &self,
3151 ) -> (&BitSlice<u8, bitvec::order::Lsb0>, Option<CoreIndex>) {
3152 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 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 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#[derive(Clone, Encode, Decode, Debug, TypeInfo)]
3186#[cfg_attr(feature = "std", derive(PartialEq))]
3187pub struct ScrapedOnChainVotes<H: Encode + Decode = Hash> {
3188 pub session: SessionIndex,
3190 pub backing_validators_per_candidate:
3193 Vec<(CandidateReceiptV2<H>, Vec<(ValidatorIndex, ValidityAttestation)>)>,
3194 pub disputes: MultiDisputeStatementSet,
3198}
3199
3200#[derive(Clone, Encode, Decode, TypeInfo, Debug)]
3202#[cfg_attr(feature = "std", derive(PartialEq))]
3203pub struct OccupiedCore<H = Hash, N = BlockNumber> {
3204 pub next_up_on_available: Option<ScheduledCore>,
3208 pub occupied_since: N,
3210 pub time_out_at: N,
3212 pub next_up_on_time_out: Option<ScheduledCore>,
3216 pub availability: BitVec<u8, bitvec::order::Lsb0>,
3220 pub group_responsible: GroupIndex,
3222 pub candidate_hash: CandidateHash,
3224 pub candidate_descriptor: CandidateDescriptorV2<H>,
3226}
3227
3228impl<H, N> OccupiedCore<H, N> {
3229 pub fn para_id(&self) -> Id {
3231 self.candidate_descriptor.para_id
3232 }
3233}
3234
3235#[derive(Clone, Encode, Decode, TypeInfo, Debug)]
3237#[cfg_attr(feature = "std", derive(PartialEq))]
3238pub enum CoreState<H = Hash, N = BlockNumber> {
3239 #[codec(index = 0)]
3241 Occupied(OccupiedCore<H, N>),
3242 #[codec(index = 1)]
3248 Scheduled(ScheduledCore),
3249 #[codec(index = 2)]
3253 Free,
3254}
3255
3256impl<N> CoreState<N> {
3257 #[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 pub fn is_occupied(&self) -> bool {
3274 matches!(self, Self::Occupied(_))
3275 }
3276}
3277
3278pub type TransposedClaimQueue = BTreeMap<ParaId, BTreeMap<u8, BTreeSet<CoreIndex>>>;
3280
3281pub 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 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#[derive(PartialEq, Eq, Clone, Copy, Encode, Decode, DecodeWithMemTracking, TypeInfo, Debug)]
3304pub enum DisputeOffenceKind {
3305 #[codec(index = 0)]
3308 ForInvalidBacked,
3309 #[codec(index = 1)]
3312 AgainstValid,
3313 #[codec(index = 2)]
3316 ForInvalidApproved,
3317}
3318
3319impl 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
3331impl 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)]
3345pub 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 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 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, 1, 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), )
3560 }
3561
3562 #[test]
3563 fn check_version_acceptance_v1_consistent() {
3564 let mut desc = make_v2_descriptor();
3567 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 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 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 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 let mut desc = make_v2_descriptor();
3623 desc.reserved1[16] = 0xFF; assert_eq!(desc.version(), CandidateDescriptorVersion::V2);
3626 assert_eq!(desc.version_old_rules(), CandidateDescriptorVersion::V1);
3627 assert!(!desc.check_version_consistency());
3628
3629 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 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 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 assert_eq!(desc.version(), CandidateDescriptorVersion::V3);
3659 assert_eq!(desc.version_old_rules(), CandidateDescriptorVersion::V1);
3660
3661 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), );
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 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), );
3679 assert_eq!(
3680 desc.scheduling_session_for_candidate_validation(true),
3681 Some(1), );
3683 }
3684
3685 #[test]
3686 fn check_version_acceptance_ambiguous_scheduling_parent_nonzero() {
3687 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 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 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 assert_eq!(hashes.encode(), bounded.encode(), "inner encoding differs for n = {n}");
3733
3734 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 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 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 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 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 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 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}