referrerpolicy=no-referrer-when-downgrade

polkadot_node_primitives/
lib.rs

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