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::pin::Pin;
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	vstaging::{
34		CommittedCandidateReceiptError, CommittedCandidateReceiptV2 as CommittedCandidateReceipt,
35	},
36	BlakeTwo256, BlockNumber, CandidateCommitments, CandidateHash, ChunkIndex, CollatorPair,
37	CompactStatement, CoreIndex, EncodeAs, Hash, HashT, HeadData, Id as ParaId,
38	PersistedValidationData, SessionIndex, Signed, UncheckedSigned, ValidationCode,
39	ValidationCodeHash, MAX_CODE_SIZE, MAX_POV_SIZE,
40};
41pub use sp_consensus_babe::{
42	AllowedSlots as BabeAllowedSlots, BabeEpochConfiguration, Epoch as BabeEpoch,
43	Randomness as BabeRandomness,
44};
45
46pub use polkadot_parachain_primitives::primitives::{
47	BlockData, HorizontalMessages, UpwardMessages,
48};
49
50pub mod approval;
51
52/// Disputes related types.
53pub mod disputes;
54pub use disputes::{
55	dispute_is_inactive, CandidateVotes, DisputeMessage, DisputeMessageCheckError, DisputeStatus,
56	InvalidDisputeVote, SignedDisputeStatement, Timestamp, UncheckedDisputeMessage,
57	ValidDisputeVote, ACTIVE_DURATION_SECS,
58};
59
60/// The current node version, which takes the basic SemVer form `<major>.<minor>.<patch>`.
61/// In general, minor should be bumped on every release while major or patch releases are
62/// relatively rare.
63///
64/// The associated worker binaries should use the same version as the node that spawns them.
65pub const NODE_VERSION: &'static str = "1.20.0";
66
67// For a 16-ary Merkle Prefix Trie, we can expect at most 16 32-byte hashes per node
68// plus some overhead:
69// header 1 + bitmap 2 + max partial_key 8 + children 16 * (32 + len 1) + value 32 + value len 1
70const MERKLE_NODE_MAX_SIZE: usize = 512 + 100;
71// 16-ary Merkle Prefix Trie for 32-bit ValidatorIndex has depth at most 8.
72const MERKLE_PROOF_MAX_DEPTH: usize = 8;
73
74/// The bomb limit for decompressing code blobs.
75#[deprecated(
76	note = "`VALIDATION_CODE_BOMB_LIMIT` will be removed. Use `validation_code_bomb_limit`
77	runtime API to retrieve the value from the runtime"
78)]
79pub const VALIDATION_CODE_BOMB_LIMIT: usize = (MAX_CODE_SIZE * 4u32) as usize;
80
81/// The bomb limit for decompressing PoV blobs.
82pub const POV_BOMB_LIMIT: usize = (MAX_POV_SIZE * 4u32) as usize;
83
84/// How many blocks after finalization an information about backed/included candidate should be
85/// pre-loaded (when scraping onchain votes) and kept locally (when pruning).
86///
87/// We don't want to remove scraped candidates on finalization because we want to
88/// be sure that disputes will conclude on abandoned forks.
89/// Removing the candidate on finalization creates a possibility for an attacker to
90/// avoid slashing. If a bad fork is abandoned too quickly because another
91/// better one gets finalized the entries for the bad fork will be pruned and we
92/// might never participate in a dispute for it.
93///
94/// Why pre-load finalized blocks? I dispute might be raised against finalized candidate. In most
95/// of the cases it will conclude valid (otherwise we are in big trouble) but never the less the
96/// node must participate. It's possible to see a vote for such dispute onchain before we have it
97/// imported by `dispute-distribution`. In this case we won't have `CandidateReceipt` and the import
98/// will fail unless we keep them preloaded.
99///
100/// This value should consider the timeout we allow for participation in approval-voting. In
101/// particular, the following condition should hold:
102///
103/// slot time * `DISPUTE_CANDIDATE_LIFETIME_AFTER_FINALIZATION` > `APPROVAL_EXECUTION_TIMEOUT`
104/// + slot time
105pub const DISPUTE_CANDIDATE_LIFETIME_AFTER_FINALIZATION: BlockNumber = 10;
106
107/// Linked to `MAX_FINALITY_LAG` in relay chain selection,
108/// `MAX_HEADS_LOOK_BACK` in `approval-voting` and
109/// `MAX_BATCH_SCRAPE_ANCESTORS` in `dispute-coordinator`
110pub const MAX_FINALITY_LAG: u32 = 500;
111
112/// Type of a session window size.
113///
114/// We are not using `NonZeroU32` here because `expect` and `unwrap` are not yet const, so global
115/// constants of `SessionWindowSize` would require `LazyLock` in that case.
116///
117/// See: <https://github.com/rust-lang/rust/issues/67441>
118#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
119pub struct SessionWindowSize(SessionIndex);
120
121#[macro_export]
122/// Create a new checked `SessionWindowSize` which cannot be 0.
123macro_rules! new_session_window_size {
124	(0) => {
125		compile_error!("Must be non zero");
126	};
127	(0_u32) => {
128		compile_error!("Must be non zero");
129	};
130	(0 as u32) => {
131		compile_error!("Must be non zero");
132	};
133	(0 as _) => {
134		compile_error!("Must be non zero");
135	};
136	($l:literal) => {
137		SessionWindowSize::unchecked_new($l as _)
138	};
139}
140
141/// It would be nice to draw this from the chain state, but we have no tools for it right now.
142/// On Polkadot this is 1 day, and on Kusama it's 6 hours.
143///
144/// Number of sessions we want to consider in disputes.
145pub const DISPUTE_WINDOW: SessionWindowSize = new_session_window_size!(6);
146
147impl SessionWindowSize {
148	/// Get the value as `SessionIndex` for doing comparisons with those.
149	pub fn get(self) -> SessionIndex {
150		self.0
151	}
152
153	/// Helper function for `new_session_window_size`.
154	///
155	/// Don't use it. The only reason it is public, is because otherwise the
156	/// `new_session_window_size` macro would not work outside of this module.
157	#[doc(hidden)]
158	pub const fn unchecked_new(size: SessionIndex) -> Self {
159		Self(size)
160	}
161}
162
163/// The cumulative weight of a block in a fork-choice rule.
164pub type BlockWeight = u32;
165
166/// A statement, where the candidate receipt is included in the `Seconded` variant.
167///
168/// This is the committed candidate receipt instead of the bare candidate receipt. As such,
169/// it gives access to the commitments to validators who have not executed the candidate. This
170/// is necessary to allow a block-producing validator to include candidates from outside the para
171/// it is assigned to.
172#[derive(Clone, PartialEq, Eq, Encode, Decode)]
173pub enum Statement {
174	/// A statement that a validator seconds a candidate.
175	#[codec(index = 1)]
176	Seconded(CommittedCandidateReceipt),
177	/// A statement that a validator has deemed a candidate valid.
178	#[codec(index = 2)]
179	Valid(CandidateHash),
180}
181
182impl std::fmt::Debug for Statement {
183	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
184		match self {
185			Statement::Seconded(seconded) => write!(f, "Seconded: {:?}", seconded.descriptor),
186			Statement::Valid(hash) => write!(f, "Valid: {:?}", hash),
187		}
188	}
189}
190
191impl Statement {
192	/// Get the candidate hash referenced by this statement.
193	///
194	/// If this is a `Statement::Seconded`, this does hash the candidate receipt, which may be
195	/// expensive for large candidates.
196	pub fn candidate_hash(&self) -> CandidateHash {
197		match *self {
198			Statement::Valid(ref h) => *h,
199			Statement::Seconded(ref c) => c.hash(),
200		}
201	}
202
203	/// Transform this statement into its compact version, which references only the hash
204	/// of the candidate.
205	pub fn to_compact(&self) -> CompactStatement {
206		match *self {
207			Statement::Seconded(ref c) => CompactStatement::Seconded(c.hash()),
208			Statement::Valid(hash) => CompactStatement::Valid(hash),
209		}
210	}
211
212	/// Add the [`PersistedValidationData`] to the statement, if seconded.
213	pub fn supply_pvd(self, pvd: PersistedValidationData) -> StatementWithPVD {
214		match self {
215			Statement::Seconded(c) => StatementWithPVD::Seconded(c, pvd),
216			Statement::Valid(hash) => StatementWithPVD::Valid(hash),
217		}
218	}
219}
220
221impl From<&'_ Statement> for CompactStatement {
222	fn from(stmt: &Statement) -> Self {
223		stmt.to_compact()
224	}
225}
226
227impl EncodeAs<CompactStatement> for Statement {
228	fn encode_as(&self) -> Vec<u8> {
229		self.to_compact().encode()
230	}
231}
232
233/// A statement, exactly the same as [`Statement`] but where seconded messages carry
234/// the [`PersistedValidationData`].
235#[derive(Clone, PartialEq, Eq)]
236pub enum StatementWithPVD {
237	/// A statement that a validator seconds a candidate.
238	Seconded(CommittedCandidateReceipt, PersistedValidationData),
239	/// A statement that a validator has deemed a candidate valid.
240	Valid(CandidateHash),
241}
242
243impl std::fmt::Debug for StatementWithPVD {
244	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
245		match self {
246			StatementWithPVD::Seconded(seconded, _) =>
247				write!(f, "Seconded: {:?}", seconded.descriptor),
248			StatementWithPVD::Valid(hash) => write!(f, "Valid: {:?}", hash),
249		}
250	}
251}
252
253impl StatementWithPVD {
254	/// Get the candidate hash referenced by this statement.
255	///
256	/// If this is a `Statement::Seconded`, this does hash the candidate receipt, which may be
257	/// expensive for large candidates.
258	pub fn candidate_hash(&self) -> CandidateHash {
259		match *self {
260			StatementWithPVD::Valid(ref h) => *h,
261			StatementWithPVD::Seconded(ref c, _) => c.hash(),
262		}
263	}
264
265	/// Transform this statement into its compact version, which references only the hash
266	/// of the candidate.
267	pub fn to_compact(&self) -> CompactStatement {
268		match *self {
269			StatementWithPVD::Seconded(ref c, _) => CompactStatement::Seconded(c.hash()),
270			StatementWithPVD::Valid(hash) => CompactStatement::Valid(hash),
271		}
272	}
273
274	/// Drop the [`PersistedValidationData`] from the statement.
275	pub fn drop_pvd(self) -> Statement {
276		match self {
277			StatementWithPVD::Seconded(c, _) => Statement::Seconded(c),
278			StatementWithPVD::Valid(c_h) => Statement::Valid(c_h),
279		}
280	}
281
282	/// Drop the [`PersistedValidationData`] from the statement in a signed
283	/// variant.
284	pub fn drop_pvd_from_signed(signed: SignedFullStatementWithPVD) -> SignedFullStatement {
285		signed
286			.convert_to_superpayload_with(|s| s.drop_pvd())
287			.expect("persisted_validation_data doesn't affect encode_as; qed")
288	}
289
290	/// Converts the statement to a compact signed statement by dropping the
291	/// [`CommittedCandidateReceipt`] and the [`PersistedValidationData`].
292	pub fn signed_to_compact(signed: SignedFullStatementWithPVD) -> Signed<CompactStatement> {
293		signed
294			.convert_to_superpayload_with(|s| s.to_compact())
295			.expect("doesn't affect encode_as; qed")
296	}
297}
298
299impl From<&'_ StatementWithPVD> for CompactStatement {
300	fn from(stmt: &StatementWithPVD) -> Self {
301		stmt.to_compact()
302	}
303}
304
305impl EncodeAs<CompactStatement> for StatementWithPVD {
306	fn encode_as(&self) -> Vec<u8> {
307		self.to_compact().encode()
308	}
309}
310
311/// A statement, the corresponding signature, and the index of the sender.
312///
313/// Signing context and validator set should be apparent from context.
314///
315/// This statement is "full" in the sense that the `Seconded` variant includes the candidate
316/// receipt. Only the compact `SignedStatement` is suitable for submission to the chain.
317pub type SignedFullStatement = Signed<Statement, CompactStatement>;
318
319/// Variant of `SignedFullStatement` where the signature has not yet been verified.
320pub type UncheckedSignedFullStatement = UncheckedSigned<Statement, CompactStatement>;
321
322/// A statement, the corresponding signature, and the index of the sender.
323///
324/// Seconded statements are accompanied by the [`PersistedValidationData`]
325///
326/// Signing context and validator set should be apparent from context.
327pub type SignedFullStatementWithPVD = Signed<StatementWithPVD, CompactStatement>;
328
329/// Candidate invalidity details
330#[derive(Debug)]
331pub enum InvalidCandidate {
332	/// Failed to execute `validate_block`. This includes function panicking.
333	ExecutionError(String),
334	/// Validation outputs check doesn't pass.
335	InvalidOutputs,
336	/// Execution timeout.
337	Timeout,
338	/// Validation input is over the limit.
339	ParamsTooLarge(u64),
340	/// Code size is over the limit.
341	CodeTooLarge(u64),
342	/// PoV does not decompress correctly.
343	PoVDecompressionFailure,
344	/// Validation function returned invalid data.
345	BadReturn,
346	/// Invalid relay chain parent.
347	BadParent,
348	/// POV hash does not match.
349	PoVHashMismatch,
350	/// Bad collator signature.
351	BadSignature,
352	/// Para head hash does not match.
353	ParaHeadHashMismatch,
354	/// Validation code hash does not match.
355	CodeHashMismatch,
356	/// Validation has generated different candidate commitments.
357	CommitmentsHashMismatch,
358	/// The candidate receipt contains an invalid session index.
359	InvalidSessionIndex,
360	/// The candidate receipt invalid UMP signals.
361	InvalidUMPSignals(CommittedCandidateReceiptError),
362}
363
364/// Result of the validation of the candidate.
365#[derive(Debug)]
366pub enum ValidationResult {
367	/// Candidate is valid. The validation process yields these outputs and the persisted
368	/// validation data used to form inputs.
369	Valid(CandidateCommitments, PersistedValidationData),
370	/// Candidate is invalid.
371	Invalid(InvalidCandidate),
372}
373
374/// A Proof-of-Validity
375#[derive(PartialEq, Eq, Clone, Encode, Decode, Debug)]
376pub struct PoV {
377	/// The block witness data.
378	pub block_data: BlockData,
379}
380
381impl PoV {
382	/// Get the blake2-256 hash of the PoV.
383	pub fn hash(&self) -> Hash {
384		BlakeTwo256::hash_of(self)
385	}
386}
387
388/// A type that represents a maybe compressed [`PoV`].
389#[derive(Clone, Encode, Decode)]
390#[cfg(not(target_os = "unknown"))]
391pub enum MaybeCompressedPoV {
392	/// A raw [`PoV`], aka not compressed.
393	Raw(PoV),
394	/// The given [`PoV`] is already compressed.
395	Compressed(PoV),
396}
397
398#[cfg(not(target_os = "unknown"))]
399impl std::fmt::Debug for MaybeCompressedPoV {
400	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
401		let (variant, size) = match self {
402			MaybeCompressedPoV::Raw(pov) => ("Raw", pov.block_data.0.len()),
403			MaybeCompressedPoV::Compressed(pov) => ("Compressed", pov.block_data.0.len()),
404		};
405
406		write!(f, "{} PoV ({} bytes)", variant, size)
407	}
408}
409
410#[cfg(not(target_os = "unknown"))]
411impl MaybeCompressedPoV {
412	/// Convert into a compressed [`PoV`].
413	///
414	/// If `self == Raw` it is compressed using [`maybe_compress_pov`].
415	pub fn into_compressed(self) -> PoV {
416		match self {
417			Self::Raw(raw) => maybe_compress_pov(raw),
418			Self::Compressed(compressed) => compressed,
419		}
420	}
421}
422
423/// The output of a collator.
424///
425/// This differs from `CandidateCommitments` in two ways:
426///
427/// - does not contain the erasure root; that's computed at the Polkadot level, not at Cumulus
428/// - contains a proof of validity.
429#[derive(Debug, Clone, Encode, Decode)]
430#[cfg(not(target_os = "unknown"))]
431pub struct Collation<BlockNumber = polkadot_primitives::BlockNumber> {
432	/// Messages destined to be interpreted by the Relay chain itself.
433	pub upward_messages: UpwardMessages,
434	/// The horizontal messages sent by the parachain.
435	pub horizontal_messages: HorizontalMessages,
436	/// New validation code.
437	pub new_validation_code: Option<ValidationCode>,
438	/// The head-data produced as a result of execution.
439	pub head_data: HeadData,
440	/// Proof to verify the state transition of the parachain.
441	pub proof_of_validity: MaybeCompressedPoV,
442	/// The number of messages processed from the DMQ.
443	pub processed_downward_messages: u32,
444	/// The mark which specifies the block number up to which all inbound HRMP messages are
445	/// processed.
446	pub hrmp_watermark: BlockNumber,
447}
448
449/// Signal that is being returned when a collation was seconded by a validator.
450#[derive(Debug)]
451#[cfg(not(target_os = "unknown"))]
452pub struct CollationSecondedSignal {
453	/// The hash of the relay chain block that was used as context to sign [`Self::statement`].
454	pub relay_parent: Hash,
455	/// The statement about seconding the collation.
456	///
457	/// Anything else than [`Statement::Seconded`] is forbidden here.
458	pub statement: SignedFullStatement,
459}
460
461/// Result of the [`CollatorFn`] invocation.
462#[cfg(not(target_os = "unknown"))]
463pub struct CollationResult {
464	/// The collation that was build.
465	pub collation: Collation,
466	/// An optional result sender that should be informed about a successfully seconded collation.
467	///
468	/// There is no guarantee that this sender is informed ever about any result, it is completely
469	/// okay to just drop it. However, if it is called, it should be called with the signed
470	/// statement of a parachain validator seconding the collation.
471	pub result_sender: Option<futures::channel::oneshot::Sender<CollationSecondedSignal>>,
472}
473
474#[cfg(not(target_os = "unknown"))]
475impl CollationResult {
476	/// Convert into the inner values.
477	pub fn into_inner(
478		self,
479	) -> (Collation, Option<futures::channel::oneshot::Sender<CollationSecondedSignal>>) {
480		(self.collation, self.result_sender)
481	}
482}
483
484/// Collation function.
485///
486/// Will be called with the hash of the relay chain block the parachain block should be build on and
487/// the [`PersistedValidationData`] that provides information about the state of the parachain on
488/// the relay chain.
489///
490/// Returns an optional [`CollationResult`].
491#[cfg(not(target_os = "unknown"))]
492pub type CollatorFn = Box<
493	dyn Fn(
494			Hash,
495			&PersistedValidationData,
496		) -> Pin<Box<dyn Future<Output = Option<CollationResult>> + Send>>
497		+ Send
498		+ Sync,
499>;
500
501/// Configuration for the collation generator
502#[cfg(not(target_os = "unknown"))]
503pub struct CollationGenerationConfig {
504	/// Collator's authentication key, so it can sign things.
505	pub key: CollatorPair,
506	/// Collation function. See [`CollatorFn`] for more details.
507	///
508	/// If this is `None`, it implies that collations are intended to be submitted
509	/// out-of-band and not pulled out of the function.
510	pub collator: Option<CollatorFn>,
511	/// The parachain that this collator collates for
512	pub para_id: ParaId,
513}
514
515#[cfg(not(target_os = "unknown"))]
516impl std::fmt::Debug for CollationGenerationConfig {
517	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
518		write!(f, "CollationGenerationConfig {{ ... }}")
519	}
520}
521
522/// Parameters for `CollationGenerationMessage::SubmitCollation`.
523#[derive(Debug)]
524pub struct SubmitCollationParams {
525	/// The relay-parent the collation is built against.
526	pub relay_parent: Hash,
527	/// The collation itself (PoV and commitments)
528	pub collation: Collation,
529	/// The parent block's head-data.
530	pub parent_head: HeadData,
531	/// The hash of the validation code the collation was created against.
532	pub validation_code_hash: ValidationCodeHash,
533	/// An optional result sender that should be informed about a successfully seconded collation.
534	///
535	/// There is no guarantee that this sender is informed ever about any result, it is completely
536	/// okay to just drop it. However, if it is called, it should be called with the signed
537	/// statement of a parachain validator seconding the collation.
538	pub result_sender: Option<futures::channel::oneshot::Sender<CollationSecondedSignal>>,
539	/// The core index on which the resulting candidate should be backed
540	pub core_index: CoreIndex,
541}
542
543/// This is the data we keep available for each candidate included in the relay chain.
544#[derive(Clone, Encode, Decode, PartialEq, Eq, Debug)]
545pub struct AvailableData {
546	/// The Proof-of-Validation of the candidate.
547	pub pov: std::sync::Arc<PoV>,
548	/// The persisted validation data needed for approval checks.
549	pub validation_data: PersistedValidationData,
550}
551
552/// This is a convenience type to allow the Erasure chunk proof to Decode into a nested BoundedVec
553#[derive(PartialEq, Eq, Clone, Debug, Hash)]
554pub struct Proof(BoundedVec<BoundedVec<u8, 1, MERKLE_NODE_MAX_SIZE>, 1, MERKLE_PROOF_MAX_DEPTH>);
555
556impl Proof {
557	/// This function allows to convert back to the standard nested Vec format
558	pub fn iter(&self) -> impl Iterator<Item = &[u8]> {
559		self.0.iter().map(|v| v.as_slice())
560	}
561
562	/// Construct an invalid dummy proof
563	///
564	/// Useful for testing, should absolutely not be used in production.
565	pub fn dummy_proof() -> Proof {
566		Proof(BoundedVec::from_vec(vec![BoundedVec::from_vec(vec![0]).unwrap()]).unwrap())
567	}
568}
569
570/// Possible errors when converting from `Vec<Vec<u8>>` into [`Proof`].
571#[derive(thiserror::Error, Debug)]
572pub enum MerkleProofError {
573	#[error("Merkle max proof depth exceeded {0} > {} .", MERKLE_PROOF_MAX_DEPTH)]
574	/// This error signifies that the Proof length exceeds the trie's max depth
575	MerkleProofDepthExceeded(usize),
576
577	#[error("Merkle node max size exceeded {0} > {} .", MERKLE_NODE_MAX_SIZE)]
578	/// This error signifies that a Proof node exceeds the 16-ary max node size
579	MerkleProofNodeSizeExceeded(usize),
580}
581
582impl TryFrom<Vec<Vec<u8>>> for Proof {
583	type Error = MerkleProofError;
584
585	fn try_from(input: Vec<Vec<u8>>) -> Result<Self, Self::Error> {
586		if input.len() > MERKLE_PROOF_MAX_DEPTH {
587			return Err(Self::Error::MerkleProofDepthExceeded(input.len()))
588		}
589		let mut out = Vec::new();
590		for element in input.into_iter() {
591			let length = element.len();
592			let data: BoundedVec<u8, 1, MERKLE_NODE_MAX_SIZE> = BoundedVec::from_vec(element)
593				.map_err(|_| Self::Error::MerkleProofNodeSizeExceeded(length))?;
594			out.push(data);
595		}
596		Ok(Proof(BoundedVec::from_vec(out).expect("Buffer size is deterined above. qed")))
597	}
598}
599
600impl Decode for Proof {
601	fn decode<I: Input>(value: &mut I) -> Result<Self, CodecError> {
602		let temp: Vec<Vec<u8>> = Decode::decode(value)?;
603		let mut out = Vec::new();
604		for element in temp.into_iter() {
605			let bounded_temp: Result<BoundedVec<u8, 1, MERKLE_NODE_MAX_SIZE>, CodecError> =
606				BoundedVec::from_vec(element)
607					.map_err(|_| "Inner node exceeds maximum node size.".into());
608			out.push(bounded_temp?);
609		}
610		BoundedVec::from_vec(out)
611			.map(Self)
612			.map_err(|_| "Merkle proof depth exceeds maximum trie depth".into())
613	}
614}
615
616impl Encode for Proof {
617	fn size_hint(&self) -> usize {
618		MERKLE_NODE_MAX_SIZE * MERKLE_PROOF_MAX_DEPTH
619	}
620
621	fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
622		let temp = self.0.iter().map(|v| v.as_vec()).collect::<Vec<_>>();
623		temp.using_encoded(f)
624	}
625}
626
627impl Serialize for Proof {
628	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
629	where
630		S: Serializer,
631	{
632		serializer.serialize_bytes(&self.encode())
633	}
634}
635
636impl<'de> Deserialize<'de> for Proof {
637	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
638	where
639		D: Deserializer<'de>,
640	{
641		// Deserialize the string and get individual components
642		let s = Vec::<u8>::deserialize(deserializer)?;
643		let mut slice = s.as_slice();
644		Decode::decode(&mut slice).map_err(de::Error::custom)
645	}
646}
647
648/// A chunk of erasure-encoded block data.
649#[derive(PartialEq, Eq, Clone, Encode, Decode, Serialize, Deserialize, Debug, Hash)]
650pub struct ErasureChunk {
651	/// The erasure-encoded chunk of data belonging to the candidate block.
652	pub chunk: Vec<u8>,
653	/// The index of this erasure-encoded chunk of data.
654	pub index: ChunkIndex,
655	/// Proof for this chunk's branch in the Merkle tree.
656	pub proof: Proof,
657}
658
659impl ErasureChunk {
660	/// Convert bounded Vec Proof to regular `Vec<Vec<u8>>`
661	pub fn proof(&self) -> &Proof {
662		&self.proof
663	}
664}
665
666/// Compress a PoV, unless it exceeds the [`POV_BOMB_LIMIT`].
667#[cfg(not(target_os = "unknown"))]
668pub fn maybe_compress_pov(pov: PoV) -> PoV {
669	let PoV { block_data: BlockData(raw) } = pov;
670	let raw = sp_maybe_compressed_blob::compress(&raw, POV_BOMB_LIMIT).unwrap_or(raw);
671
672	let pov = PoV { block_data: BlockData(raw) };
673	pov
674}