1#![deny(missing_docs)]
24
25use std::{env::var, pin::Pin, sync::LazyLock};
26
27use bounded_vec::BoundedVec;
28use codec::{Decode, Encode, Error as CodecError, Input};
29use futures::Future;
30use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
31
32use polkadot_primitives::{
33 BlakeTwo256, BlockNumber, CandidateCommitments, CandidateDescriptorVersion, CandidateHash,
34 ChunkIndex, CollatorPair, CommittedCandidateReceiptError,
35 CommittedCandidateReceiptV2 as CommittedCandidateReceipt, CompactStatement, CoreIndex,
36 EncodeAs, Hash, HashT, HeadData, Id as ParaId, PersistedValidationData, SessionIndex, Signed,
37 UncheckedSigned, ValidationCode, ValidationCodeHash, MAX_CODE_SIZE, MAX_POV_SIZE,
38};
39pub use sp_consensus_babe::{
40 AllowedSlots as BabeAllowedSlots, BabeEpochConfiguration, Epoch as BabeEpoch,
41 Randomness as BabeRandomness,
42};
43use sp_runtime::{self, traits::ConstU32};
44
45pub use polkadot_parachain_primitives::primitives::{
46 BlockData, HorizontalMessages, UpwardMessages,
47};
48
49pub mod approval;
50
51pub mod disputes;
53pub use disputes::{
54 dispute_is_inactive, CandidateVotes, DisputeMessage, DisputeMessageCheckError, DisputeStatus,
55 InvalidDisputeVote, SignedDisputeStatement, Timestamp, UncheckedDisputeMessage,
56 ValidDisputeVote, ACTIVE_DURATION_SECS,
57};
58
59pub const NODE_VERSION: &'static str = "1.25.2";
65
66const MERKLE_NODE_MAX_SIZE: usize = 512 + 100;
70const MERKLE_PROOF_MAX_DEPTH: usize = 8;
72
73pub const MAX_SEGMENT_LEN: u32 = 32;
78
79#[deprecated(
81 note = "`VALIDATION_CODE_BOMB_LIMIT` will be removed. Use `validation_code_bomb_limit`
82 runtime API to retrieve the value from the runtime"
83)]
84pub const VALIDATION_CODE_BOMB_LIMIT: usize = (MAX_CODE_SIZE * 4u32) as usize;
85
86pub const POV_BOMB_LIMIT: usize = (MAX_POV_SIZE * 4u32) as usize;
88
89pub static DISPUTE_CANDIDATE_LIFETIME_AFTER_FINALIZATION: LazyLock<BlockNumber> =
115 LazyLock::new(|| {
116 if var("ZOMBIE_DISPUTE_CANDIDATE_LIFETIME_AFTER_FINALIZATION").is_ok() {
117 1
118 } else {
119 10
120 }
121 });
122
123pub const MAX_FINALITY_LAG: u32 = 500;
127
128#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
135pub struct SessionWindowSize(SessionIndex);
136
137#[macro_export]
138macro_rules! new_session_window_size {
140 (0) => {
141 compile_error!("Must be non zero");
142 };
143 (0_u32) => {
144 compile_error!("Must be non zero");
145 };
146 (0 as u32) => {
147 compile_error!("Must be non zero");
148 };
149 (0 as _) => {
150 compile_error!("Must be non zero");
151 };
152 ($l:literal) => {
153 SessionWindowSize::unchecked_new($l as _)
154 };
155}
156
157pub const DISPUTE_WINDOW: SessionWindowSize = new_session_window_size!(6);
162
163impl SessionWindowSize {
164 pub fn get(self) -> SessionIndex {
166 self.0
167 }
168
169 #[doc(hidden)]
174 pub const fn unchecked_new(size: SessionIndex) -> Self {
175 Self(size)
176 }
177}
178
179pub type BlockWeight = u32;
181
182#[derive(Clone, PartialEq, Eq, Encode, Decode)]
189pub enum Statement {
190 #[codec(index = 1)]
192 Seconded(CommittedCandidateReceipt),
193 #[codec(index = 2)]
195 Valid(CandidateHash),
196}
197
198impl std::fmt::Debug for Statement {
199 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200 match self {
201 Statement::Seconded(seconded) => write!(f, "Seconded: {:?}", seconded.descriptor),
202 Statement::Valid(hash) => write!(f, "Valid: {:?}", hash),
203 }
204 }
205}
206
207impl Statement {
208 pub fn candidate_hash(&self) -> CandidateHash {
213 match *self {
214 Statement::Valid(ref h) => *h,
215 Statement::Seconded(ref c) => c.hash(),
216 }
217 }
218
219 pub fn to_compact(&self) -> CompactStatement {
222 match *self {
223 Statement::Seconded(ref c) => CompactStatement::Seconded(c.hash()),
224 Statement::Valid(hash) => CompactStatement::Valid(hash),
225 }
226 }
227
228 pub fn supply_pvd(self, pvd: PersistedValidationData) -> StatementWithPVD {
230 match self {
231 Statement::Seconded(c) => StatementWithPVD::Seconded(c, pvd),
232 Statement::Valid(hash) => StatementWithPVD::Valid(hash),
233 }
234 }
235}
236
237impl From<&'_ Statement> for CompactStatement {
238 fn from(stmt: &Statement) -> Self {
239 stmt.to_compact()
240 }
241}
242
243impl EncodeAs<CompactStatement> for Statement {
244 fn encode_as(&self) -> Vec<u8> {
245 self.to_compact().encode()
246 }
247}
248
249#[derive(Clone, PartialEq, Eq)]
252pub enum StatementWithPVD {
253 Seconded(CommittedCandidateReceipt, PersistedValidationData),
255 Valid(CandidateHash),
257}
258
259impl std::fmt::Debug for StatementWithPVD {
260 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
261 match self {
262 StatementWithPVD::Seconded(seconded, _) => {
263 write!(f, "Seconded: {:?}", seconded.descriptor)
264 },
265 StatementWithPVD::Valid(hash) => write!(f, "Valid: {:?}", hash),
266 }
267 }
268}
269
270impl StatementWithPVD {
271 pub fn candidate_hash(&self) -> CandidateHash {
276 match *self {
277 StatementWithPVD::Valid(ref h) => *h,
278 StatementWithPVD::Seconded(ref c, _) => c.hash(),
279 }
280 }
281
282 pub fn to_compact(&self) -> CompactStatement {
285 match *self {
286 StatementWithPVD::Seconded(ref c, _) => CompactStatement::Seconded(c.hash()),
287 StatementWithPVD::Valid(hash) => CompactStatement::Valid(hash),
288 }
289 }
290
291 pub fn drop_pvd(self) -> Statement {
293 match self {
294 StatementWithPVD::Seconded(c, _) => Statement::Seconded(c),
295 StatementWithPVD::Valid(c_h) => Statement::Valid(c_h),
296 }
297 }
298
299 pub fn drop_pvd_from_signed(signed: SignedFullStatementWithPVD) -> SignedFullStatement {
302 signed
303 .convert_to_superpayload_with(|s| s.drop_pvd())
304 .expect("persisted_validation_data doesn't affect encode_as; qed")
305 }
306
307 pub fn signed_to_compact(signed: SignedFullStatementWithPVD) -> Signed<CompactStatement> {
310 signed
311 .convert_to_superpayload_with(|s| s.to_compact())
312 .expect("doesn't affect encode_as; qed")
313 }
314}
315
316impl From<&'_ StatementWithPVD> for CompactStatement {
317 fn from(stmt: &StatementWithPVD) -> Self {
318 stmt.to_compact()
319 }
320}
321
322impl EncodeAs<CompactStatement> for StatementWithPVD {
323 fn encode_as(&self) -> Vec<u8> {
324 self.to_compact().encode()
325 }
326}
327
328pub type SignedFullStatement = Signed<Statement, CompactStatement>;
335
336pub type UncheckedSignedFullStatement = UncheckedSigned<Statement, CompactStatement>;
338
339pub type SignedFullStatementWithPVD = Signed<StatementWithPVD, CompactStatement>;
345
346#[derive(Debug)]
348pub enum InvalidCandidate {
349 ExecutionError(String),
351 InvalidOutputs,
353 Timeout,
355 ParamsTooLarge(u64),
357 CodeTooLarge(u64),
359 PoVDecompressionFailure,
361 BadReturn,
363 BadParent,
365 PoVHashMismatch,
367 BadSignature,
369 ParaHeadHashMismatch,
371 CodeHashMismatch,
373 PersistedValidationDataMismatch,
376 CommitmentsHashMismatch,
378 InvalidSchedulingSession,
380 InvalidRelayParentSession,
382 InvalidUMPSignals(CommittedCandidateReceiptError),
384}
385
386#[derive(Debug)]
388pub enum ValidationResult {
389 Valid(CandidateCommitments, PersistedValidationData),
392 Invalid(InvalidCandidate),
394}
395
396#[derive(PartialEq, Eq, Clone, Encode, Decode, Debug)]
398pub struct PoV {
399 pub block_data: BlockData,
401}
402
403impl PoV {
404 pub fn hash(&self) -> Hash {
406 BlakeTwo256::hash_of(self)
407 }
408}
409
410#[derive(Clone, Encode, Decode)]
412#[cfg(not(target_os = "unknown"))]
413pub enum MaybeCompressedPoV {
414 Raw(PoV),
416 Compressed(PoV),
418}
419
420#[cfg(not(target_os = "unknown"))]
421impl std::fmt::Debug for MaybeCompressedPoV {
422 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
423 let (variant, size) = match self {
424 MaybeCompressedPoV::Raw(pov) => ("Raw", pov.block_data.0.len()),
425 MaybeCompressedPoV::Compressed(pov) => ("Compressed", pov.block_data.0.len()),
426 };
427
428 write!(f, "{} PoV ({} bytes)", variant, size)
429 }
430}
431
432#[cfg(not(target_os = "unknown"))]
433impl MaybeCompressedPoV {
434 pub fn into_compressed(self) -> PoV {
438 match self {
439 Self::Raw(raw) => maybe_compress_pov(raw),
440 Self::Compressed(compressed) => compressed,
441 }
442 }
443}
444
445#[derive(Debug, Clone, Encode, Decode)]
452#[cfg(not(target_os = "unknown"))]
453pub struct Collation<BlockNumber = polkadot_primitives::BlockNumber> {
454 pub upward_messages: UpwardMessages,
456 pub horizontal_messages: HorizontalMessages,
458 pub new_validation_code: Option<ValidationCode>,
460 pub head_data: HeadData,
462 pub proof_of_validity: MaybeCompressedPoV,
464 pub processed_downward_messages: u32,
466 pub hrmp_watermark: BlockNumber,
469}
470
471#[cfg(not(target_os = "unknown"))]
473pub struct CollationResult {
474 pub collation: Collation,
476}
477
478#[cfg(not(target_os = "unknown"))]
486pub type CollatorFn = Box<
487 dyn Fn(
488 Hash,
489 &PersistedValidationData,
490 ) -> Pin<Box<dyn Future<Output = Option<CollationResult>> + Send>>
491 + Send
492 + Sync,
493>;
494
495#[cfg(not(target_os = "unknown"))]
497pub struct CollationGenerationConfig {
498 pub key: CollatorPair,
500 pub collator: Option<CollatorFn>,
505 pub para_id: ParaId,
507}
508
509#[cfg(not(target_os = "unknown"))]
510impl std::fmt::Debug for CollationGenerationConfig {
511 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
512 write!(f, "CollationGenerationConfig {{ ... }}")
513 }
514}
515
516#[derive(Debug)]
518pub struct SegmentCollation {
519 pub collation: Collation,
521 pub relay_parent: Hash,
523 pub validation_data: PersistedValidationData,
526 pub validation_code_hash: ValidationCodeHash,
528 pub session_index: SessionIndex,
531}
532
533#[derive(Debug)]
539pub struct SubmitSegmentParams {
540 pub scheduling_parent: Hash,
545 pub core_index: CoreIndex,
547 pub candidates_descriptor_version: CandidateDescriptorVersion,
549 pub collations: sp_runtime::BoundedVec<SegmentCollation, ConstU32<MAX_SEGMENT_LEN>>,
551}
552
553#[derive(Clone, Encode, Decode, PartialEq, Eq, Debug)]
555pub struct AvailableData {
556 pub pov: std::sync::Arc<PoV>,
558 pub validation_data: PersistedValidationData,
560}
561
562#[derive(PartialEq, Eq, Clone, Debug, Hash)]
564pub struct Proof(BoundedVec<BoundedVec<u8, 1, MERKLE_NODE_MAX_SIZE>, 1, MERKLE_PROOF_MAX_DEPTH>);
565
566impl Proof {
567 pub fn iter(&self) -> impl Iterator<Item = &[u8]> {
569 self.0.iter().map(|v| v.as_slice())
570 }
571
572 pub fn dummy_proof() -> Proof {
576 Proof(BoundedVec::from_vec(vec![BoundedVec::from_vec(vec![0]).unwrap()]).unwrap())
577 }
578}
579
580#[derive(thiserror::Error, Debug)]
582pub enum MerkleProofError {
583 #[error("Merkle max proof depth exceeded {0} > {} .", MERKLE_PROOF_MAX_DEPTH)]
584 MerkleProofDepthExceeded(usize),
586
587 #[error("Merkle node max size exceeded {0} > {} .", MERKLE_NODE_MAX_SIZE)]
588 MerkleProofNodeSizeExceeded(usize),
590}
591
592impl TryFrom<Vec<Vec<u8>>> for Proof {
593 type Error = MerkleProofError;
594
595 fn try_from(input: Vec<Vec<u8>>) -> Result<Self, Self::Error> {
596 if input.len() > MERKLE_PROOF_MAX_DEPTH {
597 return Err(Self::Error::MerkleProofDepthExceeded(input.len()));
598 }
599 let mut out = Vec::new();
600 for element in input.into_iter() {
601 let length = element.len();
602 let data: BoundedVec<u8, 1, MERKLE_NODE_MAX_SIZE> = BoundedVec::from_vec(element)
603 .map_err(|_| Self::Error::MerkleProofNodeSizeExceeded(length))?;
604 out.push(data);
605 }
606 Ok(Proof(BoundedVec::from_vec(out).expect("Buffer size is deterined above. qed")))
607 }
608}
609
610impl Decode for Proof {
611 fn decode<I: Input>(value: &mut I) -> Result<Self, CodecError> {
612 let temp: Vec<Vec<u8>> = Decode::decode(value)?;
613 let mut out = Vec::new();
614 for element in temp.into_iter() {
615 let bounded_temp: Result<BoundedVec<u8, 1, MERKLE_NODE_MAX_SIZE>, CodecError> =
616 BoundedVec::from_vec(element)
617 .map_err(|_| "Inner node exceeds maximum node size.".into());
618 out.push(bounded_temp?);
619 }
620 BoundedVec::from_vec(out)
621 .map(Self)
622 .map_err(|_| "Merkle proof depth exceeds maximum trie depth".into())
623 }
624}
625
626impl Encode for Proof {
627 fn size_hint(&self) -> usize {
628 MERKLE_NODE_MAX_SIZE * MERKLE_PROOF_MAX_DEPTH
629 }
630
631 fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
632 let temp = self.0.iter().map(|v| v.as_vec()).collect::<Vec<_>>();
633 temp.using_encoded(f)
634 }
635}
636
637impl Serialize for Proof {
638 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
639 where
640 S: Serializer,
641 {
642 serializer.serialize_bytes(&self.encode())
643 }
644}
645
646impl<'de> Deserialize<'de> for Proof {
647 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
648 where
649 D: Deserializer<'de>,
650 {
651 let s = Vec::<u8>::deserialize(deserializer)?;
653 let mut slice = s.as_slice();
654 Decode::decode(&mut slice).map_err(de::Error::custom)
655 }
656}
657
658#[derive(PartialEq, Eq, Clone, Encode, Decode, Serialize, Deserialize, Debug, Hash)]
660pub struct ErasureChunk {
661 pub chunk: Vec<u8>,
663 pub index: ChunkIndex,
665 pub proof: Proof,
667}
668
669impl ErasureChunk {
670 pub fn proof(&self) -> &Proof {
672 &self.proof
673 }
674}
675
676#[cfg(not(target_os = "unknown"))]
678pub fn maybe_compress_pov(pov: PoV) -> PoV {
679 let PoV { block_data: BlockData(raw) } = pov;
680 let raw = sp_maybe_compressed_blob::compress_weakly(&raw, POV_BOMB_LIMIT).unwrap_or(raw);
681
682 let pov = PoV { block_data: BlockData(raw) };
683 pov
684}