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