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.25.2";
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	/// Persisted validation data does not match the descriptor's
374	/// `persisted_validation_data_hash`.
375	PersistedValidationDataMismatch,
376	/// Validation has generated different candidate commitments.
377	CommitmentsHashMismatch,
378	/// The descriptor's scheduling session does not match the runtime.
379	InvalidSchedulingSession,
380	/// The relay parent is not recognized in the descriptor's claimed session.
381	InvalidRelayParentSession,
382	/// The candidate receipt invalid UMP signals.
383	InvalidUMPSignals(CommittedCandidateReceiptError),
384}
385
386/// Result of the validation of the candidate.
387#[derive(Debug)]
388pub enum ValidationResult {
389	/// Candidate is valid. The validation process yields these outputs and the persisted
390	/// validation data used to form inputs.
391	Valid(CandidateCommitments, PersistedValidationData),
392	/// Candidate is invalid.
393	Invalid(InvalidCandidate),
394}
395
396/// A Proof-of-Validity
397#[derive(PartialEq, Eq, Clone, Encode, Decode, Debug)]
398pub struct PoV {
399	/// The block witness data.
400	pub block_data: BlockData,
401}
402
403impl PoV {
404	/// Get the blake2-256 hash of the PoV.
405	pub fn hash(&self) -> Hash {
406		BlakeTwo256::hash_of(self)
407	}
408}
409
410/// A type that represents a maybe compressed [`PoV`].
411#[derive(Clone, Encode, Decode)]
412#[cfg(not(target_os = "unknown"))]
413pub enum MaybeCompressedPoV {
414	/// A raw [`PoV`], aka not compressed.
415	Raw(PoV),
416	/// The given [`PoV`] is already compressed.
417	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	/// Convert into a compressed [`PoV`].
435	///
436	/// If `self == Raw` it is compressed using [`maybe_compress_pov`].
437	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/// The output of a collator.
446///
447/// This differs from `CandidateCommitments` in two ways:
448///
449/// - does not contain the erasure root; that's computed at the Polkadot level, not at Cumulus
450/// - contains a proof of validity.
451#[derive(Debug, Clone, Encode, Decode)]
452#[cfg(not(target_os = "unknown"))]
453pub struct Collation<BlockNumber = polkadot_primitives::BlockNumber> {
454	/// Messages destined to be interpreted by the Relay chain itself.
455	pub upward_messages: UpwardMessages,
456	/// The horizontal messages sent by the parachain.
457	pub horizontal_messages: HorizontalMessages,
458	/// New validation code.
459	pub new_validation_code: Option<ValidationCode>,
460	/// The head-data produced as a result of execution.
461	pub head_data: HeadData,
462	/// Proof to verify the state transition of the parachain.
463	pub proof_of_validity: MaybeCompressedPoV,
464	/// The number of messages processed from the DMQ.
465	pub processed_downward_messages: u32,
466	/// The mark which specifies the block number up to which all inbound HRMP messages are
467	/// processed.
468	pub hrmp_watermark: BlockNumber,
469}
470
471/// Result of the [`CollatorFn`] invocation.
472#[cfg(not(target_os = "unknown"))]
473pub struct CollationResult {
474	/// The collation that was build.
475	pub collation: Collation,
476}
477
478/// Collation function.
479///
480/// Will be called with the hash of the relay chain block the parachain block should be build on and
481/// the [`PersistedValidationData`] that provides information about the state of the parachain on
482/// the relay chain.
483///
484/// Returns an optional [`CollationResult`].
485#[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/// Configuration for the collation generator
496#[cfg(not(target_os = "unknown"))]
497pub struct CollationGenerationConfig {
498	/// Collator's authentication key, so it can sign things.
499	pub key: CollatorPair,
500	/// Collation function. See [`CollatorFn`] for more details.
501	///
502	/// If this is `None`, it implies that collations are intended to be submitted
503	/// out-of-band and not pulled out of the function.
504	pub collator: Option<CollatorFn>,
505	/// The parachain that this collator collates for
506	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/// A single collation in a segment submitted via `CollationGenerationMessage::SubmitSegment`.
517#[derive(Debug)]
518pub struct SegmentCollation {
519	/// The collation itself (PoV and commitments).
520	pub collation: Collation,
521	/// The relay-parent the collation is built against.
522	pub relay_parent: Hash,
523	/// The persisted validation data for this collation. The `parent_head` field must be set
524	/// to the correct parent head-data for the parablock being submitted.
525	pub validation_data: PersistedValidationData,
526	/// The hash of the validation code the collation was created against.
527	pub validation_code_hash: ValidationCodeHash,
528	/// The session index of the relay parent. Goes into the candidate descriptor.
529	/// Must be provided by the caller because the relay parent's state may be pruned.
530	pub session_index: SessionIndex,
531}
532
533/// Parameters for `CollationGenerationMessage::SubmitSegment`.
534///
535/// Submits multiple collations that share a common scheduling parent and target core. Each
536/// [`SegmentCollation`] in `collations` carries the fields that may differ between blocks of the
537/// segment (relay parent, collation payload, validation data, etc.).
538#[derive(Debug)]
539pub struct SubmitSegmentParams {
540	/// The scheduling parent shared by all collations in the segment.
541	///
542	/// For V2 segments this is the collations' relay parent. For V3 segments it
543	/// is the explicit scheduling parent written into every candidate descriptor.
544	pub scheduling_parent: Hash,
545	/// The core index on which the resulting candidates should be backed.
546	pub core_index: CoreIndex,
547	/// Version of the candidates in the segment
548	pub candidates_descriptor_version: CandidateDescriptorVersion,
549	/// The collations in this segment, in the order they should be submitted.
550	pub collations: sp_runtime::BoundedVec<SegmentCollation, ConstU32<MAX_SEGMENT_LEN>>,
551}
552
553/// This is the data we keep available for each candidate included in the relay chain.
554#[derive(Clone, Encode, Decode, PartialEq, Eq, Debug)]
555pub struct AvailableData {
556	/// The Proof-of-Validation of the candidate.
557	pub pov: std::sync::Arc<PoV>,
558	/// The persisted validation data needed for approval checks.
559	pub validation_data: PersistedValidationData,
560}
561
562/// This is a convenience type to allow the Erasure chunk proof to Decode into a nested BoundedVec
563#[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	/// This function allows to convert back to the standard nested Vec format
568	pub fn iter(&self) -> impl Iterator<Item = &[u8]> {
569		self.0.iter().map(|v| v.as_slice())
570	}
571
572	/// Construct an invalid dummy proof
573	///
574	/// Useful for testing, should absolutely not be used in production.
575	pub fn dummy_proof() -> Proof {
576		Proof(BoundedVec::from_vec(vec![BoundedVec::from_vec(vec![0]).unwrap()]).unwrap())
577	}
578}
579
580/// Possible errors when converting from `Vec<Vec<u8>>` into [`Proof`].
581#[derive(thiserror::Error, Debug)]
582pub enum MerkleProofError {
583	#[error("Merkle max proof depth exceeded {0} > {} .", MERKLE_PROOF_MAX_DEPTH)]
584	/// This error signifies that the Proof length exceeds the trie's max depth
585	MerkleProofDepthExceeded(usize),
586
587	#[error("Merkle node max size exceeded {0} > {} .", MERKLE_NODE_MAX_SIZE)]
588	/// This error signifies that a Proof node exceeds the 16-ary max node size
589	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		// Deserialize the string and get individual components
652		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/// A chunk of erasure-encoded block data.
659#[derive(PartialEq, Eq, Clone, Encode, Decode, Serialize, Deserialize, Debug, Hash)]
660pub struct ErasureChunk {
661	/// The erasure-encoded chunk of data belonging to the candidate block.
662	pub chunk: Vec<u8>,
663	/// The index of this erasure-encoded chunk of data.
664	pub index: ChunkIndex,
665	/// Proof for this chunk's branch in the Merkle tree.
666	pub proof: Proof,
667}
668
669impl ErasureChunk {
670	/// Convert bounded Vec Proof to regular `Vec<Vec<u8>>`
671	pub fn proof(&self) -> &Proof {
672		&self.proof
673	}
674}
675
676/// Compress a PoV, unless it exceeds the [`POV_BOMB_LIMIT`].
677#[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}