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