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	BlakeTwo256, BlockNumber, CandidateCommitments, CandidateHash, ChunkIndex, CollatorPair,
34	CommittedCandidateReceipt, CompactStatement, CoreIndex, EncodeAs, Hash, HashT, HeadData,
35	Id as ParaId, PersistedValidationData, SessionIndex, Signed, UncheckedSigned, ValidationCode,
36	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.16.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}
352
353/// Result of the validation of the candidate.
354#[derive(Debug)]
355pub enum ValidationResult {
356	/// Candidate is valid. The validation process yields these outputs and the persisted
357	/// validation data used to form inputs.
358	Valid(CandidateCommitments, PersistedValidationData),
359	/// Candidate is invalid.
360	Invalid(InvalidCandidate),
361}
362
363/// A Proof-of-Validity
364#[derive(PartialEq, Eq, Clone, Encode, Decode, Debug)]
365pub struct PoV {
366	/// The block witness data.
367	pub block_data: BlockData,
368}
369
370impl PoV {
371	/// Get the blake2-256 hash of the PoV.
372	pub fn hash(&self) -> Hash {
373		BlakeTwo256::hash_of(self)
374	}
375}
376
377/// A type that represents a maybe compressed [`PoV`].
378#[derive(Clone, Encode, Decode)]
379#[cfg(not(target_os = "unknown"))]
380pub enum MaybeCompressedPoV {
381	/// A raw [`PoV`], aka not compressed.
382	Raw(PoV),
383	/// The given [`PoV`] is already compressed.
384	Compressed(PoV),
385}
386
387#[cfg(not(target_os = "unknown"))]
388impl std::fmt::Debug for MaybeCompressedPoV {
389	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
390		let (variant, size) = match self {
391			MaybeCompressedPoV::Raw(pov) => ("Raw", pov.block_data.0.len()),
392			MaybeCompressedPoV::Compressed(pov) => ("Compressed", pov.block_data.0.len()),
393		};
394
395		write!(f, "{} PoV ({} bytes)", variant, size)
396	}
397}
398
399#[cfg(not(target_os = "unknown"))]
400impl MaybeCompressedPoV {
401	/// Convert into a compressed [`PoV`].
402	///
403	/// If `self == Raw` it is compressed using [`maybe_compress_pov`].
404	pub fn into_compressed(self) -> PoV {
405		match self {
406			Self::Raw(raw) => maybe_compress_pov(raw),
407			Self::Compressed(compressed) => compressed,
408		}
409	}
410}
411
412/// The output of a collator.
413///
414/// This differs from `CandidateCommitments` in two ways:
415///
416/// - does not contain the erasure root; that's computed at the Polkadot level, not at Cumulus
417/// - contains a proof of validity.
418#[derive(Debug, Clone, Encode, Decode)]
419#[cfg(not(target_os = "unknown"))]
420pub struct Collation<BlockNumber = polkadot_primitives::BlockNumber> {
421	/// Messages destined to be interpreted by the Relay chain itself.
422	pub upward_messages: UpwardMessages,
423	/// The horizontal messages sent by the parachain.
424	pub horizontal_messages: HorizontalMessages,
425	/// New validation code.
426	pub new_validation_code: Option<ValidationCode>,
427	/// The head-data produced as a result of execution.
428	pub head_data: HeadData,
429	/// Proof to verify the state transition of the parachain.
430	pub proof_of_validity: MaybeCompressedPoV,
431	/// The number of messages processed from the DMQ.
432	pub processed_downward_messages: u32,
433	/// The mark which specifies the block number up to which all inbound HRMP messages are
434	/// processed.
435	pub hrmp_watermark: BlockNumber,
436}
437
438/// Signal that is being returned when a collation was seconded by a validator.
439#[derive(Debug)]
440#[cfg(not(target_os = "unknown"))]
441pub struct CollationSecondedSignal {
442	/// The hash of the relay chain block that was used as context to sign [`Self::statement`].
443	pub relay_parent: Hash,
444	/// The statement about seconding the collation.
445	///
446	/// Anything else than [`Statement::Seconded`] is forbidden here.
447	pub statement: SignedFullStatement,
448}
449
450/// Result of the [`CollatorFn`] invocation.
451#[cfg(not(target_os = "unknown"))]
452pub struct CollationResult {
453	/// The collation that was build.
454	pub collation: Collation,
455	/// An optional result sender that should be informed about a successfully seconded collation.
456	///
457	/// There is no guarantee that this sender is informed ever about any result, it is completely
458	/// okay to just drop it. However, if it is called, it should be called with the signed
459	/// statement of a parachain validator seconding the collation.
460	pub result_sender: Option<futures::channel::oneshot::Sender<CollationSecondedSignal>>,
461}
462
463#[cfg(not(target_os = "unknown"))]
464impl CollationResult {
465	/// Convert into the inner values.
466	pub fn into_inner(
467		self,
468	) -> (Collation, Option<futures::channel::oneshot::Sender<CollationSecondedSignal>>) {
469		(self.collation, self.result_sender)
470	}
471}
472
473/// Collation function.
474///
475/// Will be called with the hash of the relay chain block the parachain block should be build on and
476/// the [`PersistedValidationData`] that provides information about the state of the parachain on
477/// the relay chain.
478///
479/// Returns an optional [`CollationResult`].
480#[cfg(not(target_os = "unknown"))]
481pub type CollatorFn = Box<
482	dyn Fn(
483			Hash,
484			&PersistedValidationData,
485		) -> Pin<Box<dyn Future<Output = Option<CollationResult>> + Send>>
486		+ Send
487		+ Sync,
488>;
489
490/// Configuration for the collation generator
491#[cfg(not(target_os = "unknown"))]
492pub struct CollationGenerationConfig {
493	/// Collator's authentication key, so it can sign things.
494	pub key: CollatorPair,
495	/// Collation function. See [`CollatorFn`] for more details.
496	///
497	/// If this is `None`, it implies that collations are intended to be submitted
498	/// out-of-band and not pulled out of the function.
499	pub collator: Option<CollatorFn>,
500	/// The parachain that this collator collates for
501	pub para_id: ParaId,
502}
503
504#[cfg(not(target_os = "unknown"))]
505impl std::fmt::Debug for CollationGenerationConfig {
506	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
507		write!(f, "CollationGenerationConfig {{ ... }}")
508	}
509}
510
511/// Parameters for `CollationGenerationMessage::SubmitCollation`.
512#[derive(Debug)]
513pub struct SubmitCollationParams {
514	/// The relay-parent the collation is built against.
515	pub relay_parent: Hash,
516	/// The collation itself (PoV and commitments)
517	pub collation: Collation,
518	/// The parent block's head-data.
519	pub parent_head: HeadData,
520	/// The hash of the validation code the collation was created against.
521	pub validation_code_hash: ValidationCodeHash,
522	/// An optional result sender that should be informed about a successfully seconded collation.
523	///
524	/// There is no guarantee that this sender is informed ever about any result, it is completely
525	/// okay to just drop it. However, if it is called, it should be called with the signed
526	/// statement of a parachain validator seconding the collation.
527	pub result_sender: Option<futures::channel::oneshot::Sender<CollationSecondedSignal>>,
528	/// The core index on which the resulting candidate should be backed
529	pub core_index: CoreIndex,
530}
531
532/// This is the data we keep available for each candidate included in the relay chain.
533#[derive(Clone, Encode, Decode, PartialEq, Eq, Debug)]
534pub struct AvailableData {
535	/// The Proof-of-Validation of the candidate.
536	pub pov: std::sync::Arc<PoV>,
537	/// The persisted validation data needed for approval checks.
538	pub validation_data: PersistedValidationData,
539}
540
541/// This is a convenience type to allow the Erasure chunk proof to Decode into a nested BoundedVec
542#[derive(PartialEq, Eq, Clone, Debug, Hash)]
543pub struct Proof(BoundedVec<BoundedVec<u8, 1, MERKLE_NODE_MAX_SIZE>, 1, MERKLE_PROOF_MAX_DEPTH>);
544
545impl Proof {
546	/// This function allows to convert back to the standard nested Vec format
547	pub fn iter(&self) -> impl Iterator<Item = &[u8]> {
548		self.0.iter().map(|v| v.as_slice())
549	}
550
551	/// Construct an invalid dummy proof
552	///
553	/// Useful for testing, should absolutely not be used in production.
554	pub fn dummy_proof() -> Proof {
555		Proof(BoundedVec::from_vec(vec![BoundedVec::from_vec(vec![0]).unwrap()]).unwrap())
556	}
557}
558
559/// Possible errors when converting from `Vec<Vec<u8>>` into [`Proof`].
560#[derive(thiserror::Error, Debug)]
561pub enum MerkleProofError {
562	#[error("Merkle max proof depth exceeded {0} > {} .", MERKLE_PROOF_MAX_DEPTH)]
563	/// This error signifies that the Proof length exceeds the trie's max depth
564	MerkleProofDepthExceeded(usize),
565
566	#[error("Merkle node max size exceeded {0} > {} .", MERKLE_NODE_MAX_SIZE)]
567	/// This error signifies that a Proof node exceeds the 16-ary max node size
568	MerkleProofNodeSizeExceeded(usize),
569}
570
571impl TryFrom<Vec<Vec<u8>>> for Proof {
572	type Error = MerkleProofError;
573
574	fn try_from(input: Vec<Vec<u8>>) -> Result<Self, Self::Error> {
575		if input.len() > MERKLE_PROOF_MAX_DEPTH {
576			return Err(Self::Error::MerkleProofDepthExceeded(input.len()))
577		}
578		let mut out = Vec::new();
579		for element in input.into_iter() {
580			let length = element.len();
581			let data: BoundedVec<u8, 1, MERKLE_NODE_MAX_SIZE> = BoundedVec::from_vec(element)
582				.map_err(|_| Self::Error::MerkleProofNodeSizeExceeded(length))?;
583			out.push(data);
584		}
585		Ok(Proof(BoundedVec::from_vec(out).expect("Buffer size is deterined above. qed")))
586	}
587}
588
589impl Decode for Proof {
590	fn decode<I: Input>(value: &mut I) -> Result<Self, CodecError> {
591		let temp: Vec<Vec<u8>> = Decode::decode(value)?;
592		let mut out = Vec::new();
593		for element in temp.into_iter() {
594			let bounded_temp: Result<BoundedVec<u8, 1, MERKLE_NODE_MAX_SIZE>, CodecError> =
595				BoundedVec::from_vec(element)
596					.map_err(|_| "Inner node exceeds maximum node size.".into());
597			out.push(bounded_temp?);
598		}
599		BoundedVec::from_vec(out)
600			.map(Self)
601			.map_err(|_| "Merkle proof depth exceeds maximum trie depth".into())
602	}
603}
604
605impl Encode for Proof {
606	fn size_hint(&self) -> usize {
607		MERKLE_NODE_MAX_SIZE * MERKLE_PROOF_MAX_DEPTH
608	}
609
610	fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
611		let temp = self.0.iter().map(|v| v.as_vec()).collect::<Vec<_>>();
612		temp.using_encoded(f)
613	}
614}
615
616impl Serialize for Proof {
617	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
618	where
619		S: Serializer,
620	{
621		serializer.serialize_bytes(&self.encode())
622	}
623}
624
625impl<'de> Deserialize<'de> for Proof {
626	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
627	where
628		D: Deserializer<'de>,
629	{
630		// Deserialize the string and get individual components
631		let s = Vec::<u8>::deserialize(deserializer)?;
632		let mut slice = s.as_slice();
633		Decode::decode(&mut slice).map_err(de::Error::custom)
634	}
635}
636
637/// A chunk of erasure-encoded block data.
638#[derive(PartialEq, Eq, Clone, Encode, Decode, Serialize, Deserialize, Debug, Hash)]
639pub struct ErasureChunk {
640	/// The erasure-encoded chunk of data belonging to the candidate block.
641	pub chunk: Vec<u8>,
642	/// The index of this erasure-encoded chunk of data.
643	pub index: ChunkIndex,
644	/// Proof for this chunk's branch in the Merkle tree.
645	pub proof: Proof,
646}
647
648impl ErasureChunk {
649	/// Convert bounded Vec Proof to regular `Vec<Vec<u8>>`
650	pub fn proof(&self) -> &Proof {
651		&self.proof
652	}
653}
654
655/// Compress a PoV, unless it exceeds the [`POV_BOMB_LIMIT`].
656#[cfg(not(target_os = "unknown"))]
657pub fn maybe_compress_pov(pov: PoV) -> PoV {
658	let PoV { block_data: BlockData(raw) } = pov;
659	let raw = sp_maybe_compressed_blob::compress(&raw, POV_BOMB_LIMIT).unwrap_or(raw);
660
661	let pov = PoV { block_data: BlockData(raw) };
662	pov
663}