referrerpolicy=no-referrer-when-downgrade

polkadot_node_primitives/
lib.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Polkadot.
3
4// Polkadot is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Polkadot is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.
16
17//! Primitive types used on the node-side.
18//!
19//! Unlike the `polkadot-primitives` crate, these primitives are only used on the node-side,
20//! not shared between the node and the runtime. This crate builds on top of the primitives defined
21//! there.
22
23#![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
51/// Disputes related types.
52pub 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
59/// The current node version, which takes the basic SemVer form `<major>.<minor>.<patch>`.
60/// In general, minor should be bumped on every release while major or patch releases are
61/// relatively rare.
62///
63/// The associated worker binaries should use the same version as the node that spawns them.
64pub const NODE_VERSION: &'static str = "1.24.1";
65
66// For a 16-ary Merkle Prefix Trie, we can expect at most 16 32-byte hashes per node
67// plus some overhead:
68// header 1 + bitmap 2 + max partial_key 8 + children 16 * (32 + len 1) + value 32 + value len 1
69const MERKLE_NODE_MAX_SIZE: usize = 512 + 100;
70// 16-ary Merkle Prefix Trie for 32-bit ValidatorIndex has depth at most 8.
71const MERKLE_PROOF_MAX_DEPTH: usize = 8;
72
73/// Hard upper bound on `AdvertiseSegment::candidates`.
74/// The bound is enforced by SCALE decoding via `BoundedVec`,
75/// so oversized advertisements are rejected at parse time
76/// without allocation.
77pub const MAX_SEGMENT_LEN: u32 = 32;
78
79/// The bomb limit for decompressing code blobs.
80#[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
86/// The bomb limit for decompressing PoV blobs.
87pub const POV_BOMB_LIMIT: usize = (MAX_POV_SIZE * 4u32) as usize;
88
89/// How many blocks after finalization an information about backed/included candidate should be
90/// pre-loaded (when scraping onchain votes) and kept locally (when pruning).
91///
92/// We don't want to remove scraped candidates on finalization because we want to
93/// be sure that disputes will conclude on abandoned forks.
94/// Removing the candidate on finalization creates a possibility for an attacker to
95/// avoid slashing. If a bad fork is abandoned too quickly because another
96/// better one gets finalized the entries for the bad fork will be pruned and we
97/// might never participate in a dispute for it.
98///
99/// Why pre-load finalized blocks? I dispute might be raised against finalized candidate. In most
100/// of the cases it will conclude valid (otherwise we are in big trouble) but never the less the
101/// node must participate. It's possible to see a vote for such dispute onchain before we have it
102/// imported by `dispute-distribution`. In this case we won't have `CandidateReceipt` and the import
103/// will fail unless we keep them preloaded.
104///
105/// This value should consider the timeout we allow for participation in approval-voting. In
106/// particular, the following condition should hold:
107///
108/// slot time * `DISPUTE_CANDIDATE_LIFETIME_AFTER_FINALIZATION` > `APPROVAL_EXECUTION_TIMEOUT`
109/// + slot time
110///
111/// NOTE: In order to use zombie-bite with the less possible changes in the client we need to set
112/// this value to `1` (checking iff the env var
113/// `ZOMBIE_DISPUTE_CANDIDATE_LIFETIME_AFTER_FINALIZATION` is set).
114pub 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
123/// Linked to `MAX_FINALITY_LAG` in relay chain selection,
124/// `MAX_HEADS_LOOK_BACK` in `approval-voting` and
125/// `MAX_BATCH_SCRAPE_ANCESTORS` in `dispute-coordinator`
126pub const MAX_FINALITY_LAG: u32 = 500;
127
128/// Type of a session window size.
129///
130/// We are not using `NonZeroU32` here because `expect` and `unwrap` are not yet const, so global
131/// constants of `SessionWindowSize` would require `LazyLock` in that case.
132///
133/// See: <https://github.com/rust-lang/rust/issues/67441>
134#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
135pub struct SessionWindowSize(SessionIndex);
136
137#[macro_export]
138/// Create a new checked `SessionWindowSize` which cannot be 0.
139macro_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
157/// It would be nice to draw this from the chain state, but we have no tools for it right now.
158/// On Polkadot this is 1 day, and on Kusama it's 6 hours.
159///
160/// Number of sessions we want to consider in disputes.
161pub const DISPUTE_WINDOW: SessionWindowSize = new_session_window_size!(6);
162
163impl SessionWindowSize {
164	/// Get the value as `SessionIndex` for doing comparisons with those.
165	pub fn get(self) -> SessionIndex {
166		self.0
167	}
168
169	/// Helper function for `new_session_window_size`.
170	///
171	/// Don't use it. The only reason it is public, is because otherwise the
172	/// `new_session_window_size` macro would not work outside of this module.
173	#[doc(hidden)]
174	pub const fn unchecked_new(size: SessionIndex) -> Self {
175		Self(size)
176	}
177}
178
179/// The cumulative weight of a block in a fork-choice rule.
180pub type BlockWeight = u32;
181
182/// A statement, where the candidate receipt is included in the `Seconded` variant.
183///
184/// This is the committed candidate receipt instead of the bare candidate receipt. As such,
185/// it gives access to the commitments to validators who have not executed the candidate. This
186/// is necessary to allow a block-producing validator to include candidates from outside the para
187/// it is assigned to.
188#[derive(Clone, PartialEq, Eq, Encode, Decode)]
189pub enum Statement {
190	/// A statement that a validator seconds a candidate.
191	#[codec(index = 1)]
192	Seconded(CommittedCandidateReceipt),
193	/// A statement that a validator has deemed a candidate valid.
194	#[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	/// Get the candidate hash referenced by this statement.
209	///
210	/// If this is a `Statement::Seconded`, this does hash the candidate receipt, which may be
211	/// expensive for large candidates.
212	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	/// Transform this statement into its compact version, which references only the hash
220	/// of the candidate.
221	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	/// Add the [`PersistedValidationData`] to the statement, if seconded.
229	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/// A statement, exactly the same as [`Statement`] but where seconded messages carry
250/// the [`PersistedValidationData`].
251#[derive(Clone, PartialEq, Eq)]
252pub enum StatementWithPVD {
253	/// A statement that a validator seconds a candidate.
254	Seconded(CommittedCandidateReceipt, PersistedValidationData),
255	/// A statement that a validator has deemed a candidate valid.
256	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	/// Get the candidate hash referenced by this statement.
272	///
273	/// If this is a `Statement::Seconded`, this does hash the candidate receipt, which may be
274	/// expensive for large candidates.
275	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	/// Transform this statement into its compact version, which references only the hash
283	/// of the candidate.
284	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	/// Drop the [`PersistedValidationData`] from the statement.
292	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	/// Drop the [`PersistedValidationData`] from the statement in a signed
300	/// variant.
301	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	/// Converts the statement to a compact signed statement by dropping the
308	/// [`CommittedCandidateReceipt`] and the [`PersistedValidationData`].
309	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
328/// A statement, the corresponding signature, and the index of the sender.
329///
330/// Signing context and validator set should be apparent from context.
331///
332/// This statement is "full" in the sense that the `Seconded` variant includes the candidate
333/// receipt. Only the compact `SignedStatement` is suitable for submission to the chain.
334pub type SignedFullStatement = Signed<Statement, CompactStatement>;
335
336/// Variant of `SignedFullStatement` where the signature has not yet been verified.
337pub type UncheckedSignedFullStatement = UncheckedSigned<Statement, CompactStatement>;
338
339/// A statement, the corresponding signature, and the index of the sender.
340///
341/// Seconded statements are accompanied by the [`PersistedValidationData`]
342///
343/// Signing context and validator set should be apparent from context.
344pub type SignedFullStatementWithPVD = Signed<StatementWithPVD, CompactStatement>;
345
346/// Candidate invalidity details
347#[derive(Debug)]
348pub enum InvalidCandidate {
349	/// Failed to execute `validate_block`. This includes function panicking.
350	ExecutionError(String),
351	/// Validation outputs check doesn't pass.
352	InvalidOutputs,
353	/// Execution timeout.
354	Timeout,
355	/// Validation input is over the limit.
356	ParamsTooLarge(u64),
357	/// Code size is over the limit.
358	CodeTooLarge(u64),
359	/// PoV does not decompress correctly.
360	PoVDecompressionFailure,
361	/// Validation function returned invalid data.
362	BadReturn,
363	/// Invalid relay chain parent.
364	BadParent,
365	/// POV hash does not match.
366	PoVHashMismatch,
367	/// Bad collator signature.
368	BadSignature,
369	/// Para head hash does not match.
370	ParaHeadHashMismatch,
371	/// Validation code hash does not match.
372	CodeHashMismatch,
373	/// Validation has generated different candidate commitments.
374	CommitmentsHashMismatch,
375	/// The descriptor's scheduling session does not match the runtime.
376	InvalidSchedulingSession,
377	/// The relay parent is not recognized in the descriptor's claimed session.
378	InvalidRelayParentSession,
379	/// The candidate receipt invalid UMP signals.
380	InvalidUMPSignals(CommittedCandidateReceiptError),
381}
382
383/// Result of the validation of the candidate.
384#[derive(Debug)]
385pub enum ValidationResult {
386	/// Candidate is valid. The validation process yields these outputs and the persisted
387	/// validation data used to form inputs.
388	Valid(CandidateCommitments, PersistedValidationData),
389	/// Candidate is invalid.
390	Invalid(InvalidCandidate),
391}
392
393/// A Proof-of-Validity
394#[derive(PartialEq, Eq, Clone, Encode, Decode, Debug)]
395pub struct PoV {
396	/// The block witness data.
397	pub block_data: BlockData,
398}
399
400impl PoV {
401	/// Get the blake2-256 hash of the PoV.
402	pub fn hash(&self) -> Hash {
403		BlakeTwo256::hash_of(self)
404	}
405}
406
407/// A type that represents a maybe compressed [`PoV`].
408#[derive(Clone, Encode, Decode)]
409#[cfg(not(target_os = "unknown"))]
410pub enum MaybeCompressedPoV {
411	/// A raw [`PoV`], aka not compressed.
412	Raw(PoV),
413	/// The given [`PoV`] is already compressed.
414	Compressed(PoV),
415}
416
417#[cfg(not(target_os = "unknown"))]
418impl std::fmt::Debug for MaybeCompressedPoV {
419	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
420		let (variant, size) = match self {
421			MaybeCompressedPoV::Raw(pov) => ("Raw", pov.block_data.0.len()),
422			MaybeCompressedPoV::Compressed(pov) => ("Compressed", pov.block_data.0.len()),
423		};
424
425		write!(f, "{} PoV ({} bytes)", variant, size)
426	}
427}
428
429#[cfg(not(target_os = "unknown"))]
430impl MaybeCompressedPoV {
431	/// Convert into a compressed [`PoV`].
432	///
433	/// If `self == Raw` it is compressed using [`maybe_compress_pov`].
434	pub fn into_compressed(self) -> PoV {
435		match self {
436			Self::Raw(raw) => maybe_compress_pov(raw),
437			Self::Compressed(compressed) => compressed,
438		}
439	}
440}
441
442/// The output of a collator.
443///
444/// This differs from `CandidateCommitments` in two ways:
445///
446/// - does not contain the erasure root; that's computed at the Polkadot level, not at Cumulus
447/// - contains a proof of validity.
448#[derive(Debug, Clone, Encode, Decode)]
449#[cfg(not(target_os = "unknown"))]
450pub struct Collation<BlockNumber = polkadot_primitives::BlockNumber> {
451	/// Messages destined to be interpreted by the Relay chain itself.
452	pub upward_messages: UpwardMessages,
453	/// The horizontal messages sent by the parachain.
454	pub horizontal_messages: HorizontalMessages,
455	/// New validation code.
456	pub new_validation_code: Option<ValidationCode>,
457	/// The head-data produced as a result of execution.
458	pub head_data: HeadData,
459	/// Proof to verify the state transition of the parachain.
460	pub proof_of_validity: MaybeCompressedPoV,
461	/// The number of messages processed from the DMQ.
462	pub processed_downward_messages: u32,
463	/// The mark which specifies the block number up to which all inbound HRMP messages are
464	/// processed.
465	pub hrmp_watermark: BlockNumber,
466}
467
468/// Result of the [`CollatorFn`] invocation.
469#[cfg(not(target_os = "unknown"))]
470pub struct CollationResult {
471	/// The collation that was build.
472	pub collation: Collation,
473}
474
475/// Collation function.
476///
477/// Will be called with the hash of the relay chain block the parachain block should be build on and
478/// the [`PersistedValidationData`] that provides information about the state of the parachain on
479/// the relay chain.
480///
481/// Returns an optional [`CollationResult`].
482#[cfg(not(target_os = "unknown"))]
483pub type CollatorFn = Box<
484	dyn Fn(
485			Hash,
486			&PersistedValidationData,
487		) -> Pin<Box<dyn Future<Output = Option<CollationResult>> + Send>>
488		+ Send
489		+ Sync,
490>;
491
492/// Configuration for the collation generator
493#[cfg(not(target_os = "unknown"))]
494pub struct CollationGenerationConfig {
495	/// Collator's authentication key, so it can sign things.
496	pub key: CollatorPair,
497	/// Collation function. See [`CollatorFn`] for more details.
498	///
499	/// If this is `None`, it implies that collations are intended to be submitted
500	/// out-of-band and not pulled out of the function.
501	pub collator: Option<CollatorFn>,
502	/// The parachain that this collator collates for
503	pub para_id: ParaId,
504}
505
506#[cfg(not(target_os = "unknown"))]
507impl std::fmt::Debug for CollationGenerationConfig {
508	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
509		write!(f, "CollationGenerationConfig {{ ... }}")
510	}
511}
512
513/// A single collation in a segment submitted via `CollationGenerationMessage::SubmitSegment`.
514#[derive(Debug)]
515pub struct SegmentCollation {
516	/// The collation itself (PoV and commitments).
517	pub collation: Collation,
518	/// The relay-parent the collation is built against.
519	pub relay_parent: Hash,
520	/// The persisted validation data for this collation. The `parent_head` field must be set
521	/// to the correct parent head-data for the parablock being submitted.
522	pub validation_data: PersistedValidationData,
523	/// The hash of the validation code the collation was created against.
524	pub validation_code_hash: ValidationCodeHash,
525	/// The session index of the relay parent. Goes into the candidate descriptor.
526	/// Must be provided by the caller because the relay parent's state may be pruned.
527	pub session_index: SessionIndex,
528}
529
530/// Parameters for `CollationGenerationMessage::SubmitSegment`.
531///
532/// Submits multiple collations that share a common scheduling parent and target core. Each
533/// [`SegmentCollation`] in `collations` carries the fields that may differ between blocks of the
534/// segment (relay parent, collation payload, validation data, etc.).
535#[derive(Debug)]
536pub struct SubmitSegmentParams {
537	/// The scheduling parent shared by all collations in the segment.
538	///
539	/// For V2 segments this is the collations' relay parent. For V3 segments it
540	/// is the explicit scheduling parent written into every candidate descriptor.
541	pub scheduling_parent: Hash,
542	/// The core index on which the resulting candidates should be backed.
543	pub core_index: CoreIndex,
544	/// Version of the candidates in the segment
545	pub candidates_descriptor_version: CandidateDescriptorVersion,
546	/// The collations in this segment, in the order they should be submitted.
547	pub collations: sp_runtime::BoundedVec<SegmentCollation, ConstU32<MAX_SEGMENT_LEN>>,
548}
549
550/// This is the data we keep available for each candidate included in the relay chain.
551#[derive(Clone, Encode, Decode, PartialEq, Eq, Debug)]
552pub struct AvailableData {
553	/// The Proof-of-Validation of the candidate.
554	pub pov: std::sync::Arc<PoV>,
555	/// The persisted validation data needed for approval checks.
556	pub validation_data: PersistedValidationData,
557}
558
559/// This is a convenience type to allow the Erasure chunk proof to Decode into a nested BoundedVec
560#[derive(PartialEq, Eq, Clone, Debug, Hash)]
561pub struct Proof(BoundedVec<BoundedVec<u8, 1, MERKLE_NODE_MAX_SIZE>, 1, MERKLE_PROOF_MAX_DEPTH>);
562
563impl Proof {
564	/// This function allows to convert back to the standard nested Vec format
565	pub fn iter(&self) -> impl Iterator<Item = &[u8]> {
566		self.0.iter().map(|v| v.as_slice())
567	}
568
569	/// Construct an invalid dummy proof
570	///
571	/// Useful for testing, should absolutely not be used in production.
572	pub fn dummy_proof() -> Proof {
573		Proof(BoundedVec::from_vec(vec![BoundedVec::from_vec(vec![0]).unwrap()]).unwrap())
574	}
575}
576
577/// Possible errors when converting from `Vec<Vec<u8>>` into [`Proof`].
578#[derive(thiserror::Error, Debug)]
579pub enum MerkleProofError {
580	#[error("Merkle max proof depth exceeded {0} > {} .", MERKLE_PROOF_MAX_DEPTH)]
581	/// This error signifies that the Proof length exceeds the trie's max depth
582	MerkleProofDepthExceeded(usize),
583
584	#[error("Merkle node max size exceeded {0} > {} .", MERKLE_NODE_MAX_SIZE)]
585	/// This error signifies that a Proof node exceeds the 16-ary max node size
586	MerkleProofNodeSizeExceeded(usize),
587}
588
589impl TryFrom<Vec<Vec<u8>>> for Proof {
590	type Error = MerkleProofError;
591
592	fn try_from(input: Vec<Vec<u8>>) -> Result<Self, Self::Error> {
593		if input.len() > MERKLE_PROOF_MAX_DEPTH {
594			return Err(Self::Error::MerkleProofDepthExceeded(input.len()));
595		}
596		let mut out = Vec::new();
597		for element in input.into_iter() {
598			let length = element.len();
599			let data: BoundedVec<u8, 1, MERKLE_NODE_MAX_SIZE> = BoundedVec::from_vec(element)
600				.map_err(|_| Self::Error::MerkleProofNodeSizeExceeded(length))?;
601			out.push(data);
602		}
603		Ok(Proof(BoundedVec::from_vec(out).expect("Buffer size is deterined above. qed")))
604	}
605}
606
607impl Decode for Proof {
608	fn decode<I: Input>(value: &mut I) -> Result<Self, CodecError> {
609		let temp: Vec<Vec<u8>> = Decode::decode(value)?;
610		let mut out = Vec::new();
611		for element in temp.into_iter() {
612			let bounded_temp: Result<BoundedVec<u8, 1, MERKLE_NODE_MAX_SIZE>, CodecError> =
613				BoundedVec::from_vec(element)
614					.map_err(|_| "Inner node exceeds maximum node size.".into());
615			out.push(bounded_temp?);
616		}
617		BoundedVec::from_vec(out)
618			.map(Self)
619			.map_err(|_| "Merkle proof depth exceeds maximum trie depth".into())
620	}
621}
622
623impl Encode for Proof {
624	fn size_hint(&self) -> usize {
625		MERKLE_NODE_MAX_SIZE * MERKLE_PROOF_MAX_DEPTH
626	}
627
628	fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
629		let temp = self.0.iter().map(|v| v.as_vec()).collect::<Vec<_>>();
630		temp.using_encoded(f)
631	}
632}
633
634impl Serialize for Proof {
635	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
636	where
637		S: Serializer,
638	{
639		serializer.serialize_bytes(&self.encode())
640	}
641}
642
643impl<'de> Deserialize<'de> for Proof {
644	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
645	where
646		D: Deserializer<'de>,
647	{
648		// Deserialize the string and get individual components
649		let s = Vec::<u8>::deserialize(deserializer)?;
650		let mut slice = s.as_slice();
651		Decode::decode(&mut slice).map_err(de::Error::custom)
652	}
653}
654
655/// A chunk of erasure-encoded block data.
656#[derive(PartialEq, Eq, Clone, Encode, Decode, Serialize, Deserialize, Debug, Hash)]
657pub struct ErasureChunk {
658	/// The erasure-encoded chunk of data belonging to the candidate block.
659	pub chunk: Vec<u8>,
660	/// The index of this erasure-encoded chunk of data.
661	pub index: ChunkIndex,
662	/// Proof for this chunk's branch in the Merkle tree.
663	pub proof: Proof,
664}
665
666impl ErasureChunk {
667	/// Convert bounded Vec Proof to regular `Vec<Vec<u8>>`
668	pub fn proof(&self) -> &Proof {
669		&self.proof
670	}
671}
672
673/// Compress a PoV, unless it exceeds the [`POV_BOMB_LIMIT`].
674#[cfg(not(target_os = "unknown"))]
675pub fn maybe_compress_pov(pov: PoV) -> PoV {
676	let PoV { block_data: BlockData(raw) } = pov;
677	let raw = sp_maybe_compressed_blob::compress_weakly(&raw, POV_BOMB_LIMIT).unwrap_or(raw);
678
679	let pov = PoV { block_data: BlockData(raw) };
680	pov
681}