pezsp_runtime/traits/
mod.rs

1// This file is part of Bizinikiwi.
2
3// Copyright (C) Parity Technologies (UK) Ltd. and Dijital Kurdistan Tech Institute
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Primitives for the runtime modules.
19
20use crate::{
21	generic::Digest,
22	scale_info::{StaticTypeInfo, TypeInfo},
23	transaction_validity::{
24		TransactionSource, TransactionValidity, TransactionValidityError, UnknownTransaction,
25		ValidTransaction,
26	},
27	DispatchResult, OpaqueExtrinsic,
28};
29use alloc::vec::Vec;
30use codec::{
31	Codec, Decode, DecodeWithMemTracking, Encode, EncodeLike, FullCodec, HasCompact, MaxEncodedLen,
32};
33#[doc(hidden)]
34pub use core::{fmt::Debug, marker::PhantomData};
35use impl_trait_for_tuples::impl_for_tuples;
36use pezsp_application_crypto::AppCrypto;
37pub use pezsp_arithmetic::traits::{
38	checked_pow, ensure_pow, AtLeast32Bit, AtLeast32BitUnsigned, Bounded, CheckedAdd, CheckedDiv,
39	CheckedMul, CheckedShl, CheckedShr, CheckedSub, Ensure, EnsureAdd, EnsureAddAssign, EnsureDiv,
40	EnsureDivAssign, EnsureFixedPointNumber, EnsureFrom, EnsureInto, EnsureMul, EnsureMulAssign,
41	EnsureOp, EnsureOpAssign, EnsureSub, EnsureSubAssign, IntegerSquareRoot, One,
42	SaturatedConversion, Saturating, UniqueSaturatedFrom, UniqueSaturatedInto, Zero,
43};
44use pezsp_core::{self, storage::StateVersion, Hasher, RuntimeDebug, TypeId, U256};
45#[doc(hidden)]
46pub use pezsp_core::{
47	parameter_types, ConstBool, ConstI128, ConstI16, ConstI32, ConstI64, ConstI8, ConstInt,
48	ConstU128, ConstU16, ConstU32, ConstU64, ConstU8, ConstUint, Get, GetDefault, TryCollect,
49	TypedGet,
50};
51#[cfg(feature = "serde")]
52use serde::{de::DeserializeOwned, Deserialize, Serialize};
53#[cfg(feature = "std")]
54use std::fmt::Display;
55#[cfg(feature = "std")]
56use std::str::FromStr;
57
58pub mod transaction_extension;
59pub use transaction_extension::{
60	DispatchTransaction, Implication, ImplicationParts, TransactionExtension,
61	TransactionExtensionMetadata, TxBaseImplication, ValidateResult,
62};
63
64/// A lazy value.
65pub trait Lazy<T: ?Sized> {
66	/// Get a reference to the underlying value.
67	///
68	/// This will compute the value if the function is invoked for the first time.
69	fn get(&mut self) -> &T;
70}
71
72impl<'a> Lazy<[u8]> for &'a [u8] {
73	fn get(&mut self) -> &[u8] {
74		self
75	}
76}
77
78/// Some type that is able to be collapsed into an account ID. It is not possible to recreate the
79/// original value from the account ID.
80pub trait IdentifyAccount {
81	/// The account ID that this can be transformed into.
82	type AccountId;
83	/// Transform into an account.
84	fn into_account(self) -> Self::AccountId;
85}
86
87impl IdentifyAccount for pezsp_core::ed25519::Public {
88	type AccountId = Self;
89	fn into_account(self) -> Self {
90		self
91	}
92}
93
94impl IdentifyAccount for pezsp_core::sr25519::Public {
95	type AccountId = Self;
96	fn into_account(self) -> Self {
97		self
98	}
99}
100
101impl IdentifyAccount for pezsp_core::ecdsa::Public {
102	type AccountId = Self;
103	fn into_account(self) -> Self {
104		self
105	}
106}
107
108/// Means of signature verification.
109pub trait Verify {
110	/// Type of the signer.
111	type Signer: IdentifyAccount;
112	/// Verify a signature.
113	///
114	/// Return `true` if signature is valid for the value.
115	fn verify<L: Lazy<[u8]>>(
116		&self,
117		msg: L,
118		signer: &<Self::Signer as IdentifyAccount>::AccountId,
119	) -> bool;
120}
121
122impl Verify for pezsp_core::ed25519::Signature {
123	type Signer = pezsp_core::ed25519::Public;
124
125	fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &pezsp_core::ed25519::Public) -> bool {
126		pezsp_io::crypto::ed25519_verify(self, msg.get(), signer)
127	}
128}
129
130impl Verify for pezsp_core::sr25519::Signature {
131	type Signer = pezsp_core::sr25519::Public;
132
133	fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &pezsp_core::sr25519::Public) -> bool {
134		pezsp_io::crypto::sr25519_verify(self, msg.get(), signer)
135	}
136}
137
138impl Verify for pezsp_core::ecdsa::Signature {
139	type Signer = pezsp_core::ecdsa::Public;
140	fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &pezsp_core::ecdsa::Public) -> bool {
141		match pezsp_io::crypto::secp256k1_ecdsa_recover_compressed(
142			self.as_ref(),
143			&pezsp_io::hashing::blake2_256(msg.get()),
144		) {
145			Ok(pubkey) => signer.0 == pubkey,
146			_ => false,
147		}
148	}
149}
150
151/// Means of signature verification of an application key.
152pub trait AppVerify {
153	/// Type of the signer.
154	type AccountId;
155	/// Verify a signature. Return `true` if signature is valid for the value.
156	fn verify<L: Lazy<[u8]>>(&self, msg: L, signer: &Self::AccountId) -> bool;
157}
158
159impl<
160		S: Verify<
161				Signer = <<T as AppCrypto>::Public as pezsp_application_crypto::AppPublic>::Generic,
162			> + From<T>,
163		T: pezsp_application_crypto::Wraps<Inner = S>
164			+ pezsp_application_crypto::AppCrypto
165			+ pezsp_application_crypto::AppSignature
166			+ AsRef<S>
167			+ AsMut<S>
168			+ From<S>,
169	> AppVerify for T
170where
171	<S as Verify>::Signer: IdentifyAccount<AccountId = <S as Verify>::Signer>,
172	<<T as AppCrypto>::Public as pezsp_application_crypto::AppPublic>::Generic: IdentifyAccount<
173		AccountId = <<T as AppCrypto>::Public as pezsp_application_crypto::AppPublic>::Generic,
174	>,
175{
176	type AccountId = <T as AppCrypto>::Public;
177	fn verify<L: Lazy<[u8]>>(&self, msg: L, signer: &<T as AppCrypto>::Public) -> bool {
178		use pezsp_application_crypto::IsWrappedBy;
179		let inner: &S = self.as_ref();
180		let inner_pubkey =
181			<<T as AppCrypto>::Public as pezsp_application_crypto::AppPublic>::Generic::from_ref(
182				signer,
183			);
184		Verify::verify(inner, msg, inner_pubkey)
185	}
186}
187
188/// An error type that indicates that the origin is invalid.
189#[derive(Encode, Decode, RuntimeDebug)]
190pub struct BadOrigin;
191
192impl From<BadOrigin> for &'static str {
193	fn from(_: BadOrigin) -> &'static str {
194		"Bad origin"
195	}
196}
197
198/// An error that indicates that a lookup failed.
199#[derive(Encode, Decode, RuntimeDebug)]
200pub struct LookupError;
201
202impl From<LookupError> for &'static str {
203	fn from(_: LookupError) -> &'static str {
204		"Can not lookup"
205	}
206}
207
208impl From<LookupError> for TransactionValidityError {
209	fn from(_: LookupError) -> Self {
210		UnknownTransaction::CannotLookup.into()
211	}
212}
213
214/// Means of changing one type into another in a manner dependent on the source type.
215pub trait Lookup {
216	/// Type to lookup from.
217	type Source;
218	/// Type to lookup into.
219	type Target;
220	/// Attempt a lookup.
221	fn lookup(&self, s: Self::Source) -> Result<Self::Target, LookupError>;
222}
223
224/// Means of changing one type into another in a manner dependent on the source type.
225/// This variant is different to `Lookup` in that it doesn't (can cannot) require any
226/// context.
227pub trait StaticLookup {
228	/// Type to lookup from.
229	type Source: Codec + Clone + PartialEq + Debug + TypeInfo;
230	/// Type to lookup into.
231	type Target;
232	/// Attempt a lookup.
233	fn lookup(s: Self::Source) -> Result<Self::Target, LookupError>;
234	/// Convert from Target back to Source.
235	fn unlookup(t: Self::Target) -> Self::Source;
236}
237
238/// A lookup implementation returning the input value.
239#[derive(Clone, Copy, PartialEq, Eq)]
240pub struct IdentityLookup<T>(PhantomData<T>);
241impl<T> Default for IdentityLookup<T> {
242	fn default() -> Self {
243		Self(PhantomData::<T>::default())
244	}
245}
246
247impl<T: Codec + Clone + PartialEq + Debug + TypeInfo> StaticLookup for IdentityLookup<T> {
248	type Source = T;
249	type Target = T;
250	fn lookup(x: T) -> Result<T, LookupError> {
251		Ok(x)
252	}
253	fn unlookup(x: T) -> T {
254		x
255	}
256}
257
258impl<T> Lookup for IdentityLookup<T> {
259	type Source = T;
260	type Target = T;
261	fn lookup(&self, x: T) -> Result<T, LookupError> {
262		Ok(x)
263	}
264}
265
266/// A lookup implementation returning the `AccountId` from a `MultiAddress`.
267pub struct AccountIdLookup<AccountId, AccountIndex>(PhantomData<(AccountId, AccountIndex)>);
268impl<AccountId, AccountIndex> StaticLookup for AccountIdLookup<AccountId, AccountIndex>
269where
270	AccountId: Codec + Clone + PartialEq + Debug,
271	AccountIndex: Codec + Clone + PartialEq + Debug,
272	crate::MultiAddress<AccountId, AccountIndex>: Codec + StaticTypeInfo,
273{
274	type Source = crate::MultiAddress<AccountId, AccountIndex>;
275	type Target = AccountId;
276	fn lookup(x: Self::Source) -> Result<Self::Target, LookupError> {
277		match x {
278			crate::MultiAddress::Id(i) => Ok(i),
279			_ => Err(LookupError),
280		}
281	}
282	fn unlookup(x: Self::Target) -> Self::Source {
283		crate::MultiAddress::Id(x)
284	}
285}
286
287/// Perform a StaticLookup where there are multiple lookup sources of the same type.
288impl<A, B> StaticLookup for (A, B)
289where
290	A: StaticLookup,
291	B: StaticLookup<Source = A::Source, Target = A::Target>,
292{
293	type Source = A::Source;
294	type Target = A::Target;
295
296	fn lookup(x: Self::Source) -> Result<Self::Target, LookupError> {
297		A::lookup(x.clone()).or_else(|_| B::lookup(x))
298	}
299	fn unlookup(x: Self::Target) -> Self::Source {
300		A::unlookup(x)
301	}
302}
303
304/// Extensible conversion trait. Generic over only source type, with destination type being
305/// associated.
306pub trait Morph<A> {
307	/// The type into which `A` is mutated.
308	type Outcome;
309
310	/// Make conversion.
311	fn morph(a: A) -> Self::Outcome;
312}
313
314/// A structure that performs identity conversion.
315impl<T> Morph<T> for Identity {
316	type Outcome = T;
317	fn morph(a: T) -> T {
318		a
319	}
320}
321
322/// Extensible conversion trait. Generic over only source type, with destination type being
323/// associated.
324pub trait TryMorph<A> {
325	/// The type into which `A` is mutated.
326	type Outcome;
327
328	/// Make conversion.
329	fn try_morph(a: A) -> Result<Self::Outcome, ()>;
330}
331
332/// A structure that performs identity conversion.
333impl<T> TryMorph<T> for Identity {
334	type Outcome = T;
335	fn try_morph(a: T) -> Result<T, ()> {
336		Ok(a)
337	}
338}
339
340/// Implementation of `Morph` which converts between types using `Into`.
341pub struct MorphInto<T>(core::marker::PhantomData<T>);
342impl<T, A: Into<T>> Morph<A> for MorphInto<T> {
343	type Outcome = T;
344	fn morph(a: A) -> T {
345		a.into()
346	}
347}
348
349/// Implementation of `TryMorph` which attempts to convert between types using `TryInto`.
350pub struct TryMorphInto<T>(core::marker::PhantomData<T>);
351impl<T, A: TryInto<T>> TryMorph<A> for TryMorphInto<T> {
352	type Outcome = T;
353	fn try_morph(a: A) -> Result<T, ()> {
354		a.try_into().map_err(|_| ())
355	}
356}
357
358/// Implementation of `Morph` to retrieve just the first element of a tuple.
359pub struct TakeFirst;
360impl<T1> Morph<(T1,)> for TakeFirst {
361	type Outcome = T1;
362	fn morph(a: (T1,)) -> T1 {
363		a.0
364	}
365}
366impl<T1, T2> Morph<(T1, T2)> for TakeFirst {
367	type Outcome = T1;
368	fn morph(a: (T1, T2)) -> T1 {
369		a.0
370	}
371}
372impl<T1, T2, T3> Morph<(T1, T2, T3)> for TakeFirst {
373	type Outcome = T1;
374	fn morph(a: (T1, T2, T3)) -> T1 {
375		a.0
376	}
377}
378impl<T1, T2, T3, T4> Morph<(T1, T2, T3, T4)> for TakeFirst {
379	type Outcome = T1;
380	fn morph(a: (T1, T2, T3, T4)) -> T1 {
381		a.0
382	}
383}
384
385/// Create a `Morph` and/or `TryMorph` impls with a simple closure-like expression.
386///
387/// # Examples
388///
389/// ```
390/// # use pezsp_runtime::{morph_types, traits::{Morph, TryMorph, TypedGet, ConstU32}};
391/// # use pezsp_arithmetic::traits::CheckedSub;
392///
393/// morph_types! {
394///    /// Replace by some other value; produce both `Morph` and `TryMorph` implementations
395///    pub type Replace<V: TypedGet> = |_| -> V::Type { V::get() };
396///    /// A private `Morph` implementation to reduce a `u32` by 10.
397///    type ReduceU32ByTen: Morph = |r: u32| -> u32 { r - 10 };
398///    /// A `TryMorph` implementation to reduce a scalar by a particular amount, checking for
399///    /// underflow.
400///    pub type CheckedReduceBy<N: TypedGet>: TryMorph = |r: N::Type| -> Result<N::Type, ()> {
401///        r.checked_sub(&N::get()).ok_or(())
402///    } where N::Type: CheckedSub;
403/// }
404///
405/// trait Config {
406///    type TestMorph1: Morph<u32>;
407///    type TestTryMorph1: TryMorph<u32>;
408///    type TestMorph2: Morph<u32>;
409///    type TestTryMorph2: TryMorph<u32>;
410/// }
411///
412/// struct Runtime;
413/// impl Config for Runtime {
414///    type TestMorph1 = Replace<ConstU32<42>>;
415///    type TestTryMorph1 = Replace<ConstU32<42>>;
416///    type TestMorph2 = ReduceU32ByTen;
417///    type TestTryMorph2 = CheckedReduceBy<ConstU32<10>>;
418/// }
419/// ```
420#[macro_export]
421macro_rules! morph_types {
422	(
423		@DECL $( #[doc = $doc:expr] )* $vq:vis $name:ident ()
424	) => {
425		$( #[doc = $doc] )* $vq struct $name;
426	};
427	(
428		@DECL $( #[doc = $doc:expr] )* $vq:vis $name:ident ( $( $bound_id:ident ),+ )
429	) => {
430		$( #[doc = $doc] )*
431		$vq struct $name < $($bound_id,)* > ( $crate::traits::PhantomData< ( $($bound_id,)* ) > ) ;
432	};
433	(
434		@IMPL $name:ty : ( $( $bounds:tt )* ) ( $( $where:tt )* )
435		= |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
436	) => {
437		impl<$($bounds)*> $crate::traits::Morph<$var_type> for $name $( $where )? {
438			type Outcome = $outcome;
439			fn morph($var: $var_type) -> Self::Outcome { $( $ex )* }
440		}
441	};
442	(
443		@IMPL_TRY $name:ty : ( $( $bounds:tt )* ) ( $( $where:tt )* )
444		= |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
445	) => {
446		impl<$($bounds)*> $crate::traits::TryMorph<$var_type> for $name $( $where )? {
447			type Outcome = $outcome;
448			fn try_morph($var: $var_type) -> Result<Self::Outcome, ()> { $( $ex )* }
449		}
450	};
451	(
452		@IMPL $name:ty : () ( $( $where:tt )* )
453		= |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
454	) => {
455		impl $crate::traits::Morph<$var_type> for $name $( $where )? {
456			type Outcome = $outcome;
457			fn morph($var: $var_type) -> Self::Outcome { $( $ex )* }
458		}
459	};
460	(
461		@IMPL_TRY $name:ty : () ( $( $where:tt )* )
462		= |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
463	) => {
464		impl $crate::traits::TryMorph<$var_type> for $name $( $where )? {
465			type Outcome = $outcome;
466			fn try_morph($var: $var_type) -> Result<Self::Outcome, ()> { $( $ex )* }
467		}
468	};
469	(
470		@IMPL_BOTH $name:ty : ( $( $bounds:tt )* ) ( $( $where:tt )* )
471		= |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
472	) => {
473		morph_types! {
474			@IMPL $name : ($($bounds)*) ($($where)*)
475			= |$var: $var_type| -> $outcome { $( $ex )* }
476		}
477		morph_types! {
478			@IMPL_TRY $name : ($($bounds)*) ($($where)*)
479			= |$var: $var_type| -> $outcome { Ok({$( $ex )*}) }
480		}
481	};
482
483	(
484		$( #[doc = $doc:expr] )* $vq:vis type $name:ident
485		$( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
486		$(: $type:tt)?
487		= |_| -> $outcome:ty { $( $ex:expr )* };
488		$( $rest:tt )*
489	) => {
490		morph_types! {
491			$( #[doc = $doc] )* $vq type $name
492			$( < $( $bound_id $( : $bound_head $( | $bound_tail )* )? ),+ > )?
493			EXTRA_GENERIC(X)
494			$(: $type)?
495			= |_x: X| -> $outcome { $( $ex )* };
496			$( $rest )*
497		}
498	};
499	(
500		$( #[doc = $doc:expr] )* $vq:vis type $name:ident
501		$( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
502		$( EXTRA_GENERIC ($extra:ident) )?
503		= |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
504		$( where $( $where_path:ty : $where_bound_head:path $( | $where_bound_tail:path )* ),* )?;
505		$( $rest:tt )*
506	) => {
507		morph_types! { @DECL $( #[doc = $doc] )* $vq $name ( $( $( $bound_id ),+ )? ) }
508		morph_types! {
509			@IMPL_BOTH $name $( < $( $bound_id ),* > )? :
510			( $( $( $bound_id $( : $bound_head $( + $bound_tail )* )? , )+ )? $( $extra )? )
511			( $( where $( $where_path : $where_bound_head $( + $where_bound_tail )* ),* )? )
512			= |$var: $var_type| -> $outcome { $( $ex )* }
513		}
514		morph_types!{ $($rest)* }
515	};
516	(
517		$( #[doc = $doc:expr] )* $vq:vis type $name:ident
518		$( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
519		$( EXTRA_GENERIC ($extra:ident) )?
520		: Morph
521		= |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
522		$( where $( $where_path:ty : $where_bound_head:path $( | $where_bound_tail:path )* ),* )?;
523		$( $rest:tt )*
524	) => {
525		morph_types! { @DECL $( #[doc = $doc] )* $vq $name ( $( $( $bound_id ),+ )? ) }
526		morph_types! {
527			@IMPL $name $( < $( $bound_id ),* > )? :
528			( $( $( $bound_id $( : $bound_head $( + $bound_tail )* )? , )+ )? $( $extra )? )
529			( $( where $( $where_path : $where_bound_head $( + $where_bound_tail )* ),* )? )
530			= |$var: $var_type| -> $outcome { $( $ex )* }
531		}
532		morph_types!{ $($rest)* }
533	};
534	(
535		$( #[doc = $doc:expr] )* $vq:vis type $name:ident
536		$( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
537		$( EXTRA_GENERIC ($extra:ident) )?
538		: TryMorph
539		= |$var:ident: $var_type:ty| -> Result<$outcome:ty, ()> { $( $ex:expr )* }
540		$( where $( $where_path:ty : $where_bound_head:path $( | $where_bound_tail:path )* ),* )?;
541		$( $rest:tt )*
542	) => {
543		morph_types! { @DECL $( #[doc = $doc] )* $vq $name ( $( $( $bound_id ),+ )? ) }
544		morph_types! {
545			@IMPL_TRY $name $( < $( $bound_id ),* > )? :
546			( $( $( $bound_id $( : $bound_head $( + $bound_tail )* )? , )+ )? $( $extra )? )
547			( $( where $( $where_path : $where_bound_head $( + $where_bound_tail )* ),* )? )
548			= |$var: $var_type| -> $outcome { $( $ex )* }
549		}
550		morph_types!{ $($rest)* }
551	};
552	() => {}
553}
554
555morph_types! {
556	/// Morpher to disregard the source value and replace with another.
557	pub type Replace<V: TypedGet> = |_| -> V::Type { V::get() };
558
559	/// Morpher to disregard the source value and replace with the default of `V`.
560	pub type ReplaceWithDefault<V: Default> = |_| -> V { Default::default() };
561
562	/// Mutator which reduces a scalar by a particular amount.
563	pub type ReduceBy<N: TypedGet> = |r: N::Type| -> N::Type {
564		r.checked_sub(&N::get()).unwrap_or(Zero::zero())
565	} where N::Type: CheckedSub | Zero;
566
567	/// A `TryMorph` implementation to reduce a scalar by a particular amount, checking for
568	/// underflow.
569	pub type CheckedReduceBy<N: TypedGet>: TryMorph = |r: N::Type| -> Result<N::Type, ()> {
570		r.checked_sub(&N::get()).ok_or(())
571	} where N::Type: CheckedSub;
572
573	/// A `TryMorph` implementation to enforce an upper limit for a result of the outer morphed type.
574	pub type MorphWithUpperLimit<L: TypedGet, M>: TryMorph = |r: L::Type| -> Result<L::Type, ()> {
575		M::try_morph(r).map(|m| m.min(L::get()))
576	} where L::Type: Ord, M: TryMorph<L::Type, Outcome = L::Type>;
577}
578
579/// Infallible conversion trait. Generic over both source and destination types.
580pub trait Convert<A, B> {
581	/// Make conversion.
582	fn convert(a: A) -> B;
583}
584
585impl<A, B: Default> Convert<A, B> for () {
586	fn convert(_: A) -> B {
587		Default::default()
588	}
589}
590
591/// Reversing infallible conversion trait. Generic over both source and destination types.
592///
593/// This specifically reverses the conversion.
594pub trait ConvertBack<A, B>: Convert<A, B> {
595	/// Make conversion back.
596	fn convert_back(b: B) -> A;
597}
598
599/// Fallible conversion trait returning an [Option]. Generic over both source and destination types.
600pub trait MaybeConvert<A, B> {
601	/// Attempt to make conversion.
602	fn maybe_convert(a: A) -> Option<B>;
603}
604
605#[impl_trait_for_tuples::impl_for_tuples(30)]
606impl<A: Clone, B> MaybeConvert<A, B> for Tuple {
607	fn maybe_convert(a: A) -> Option<B> {
608		for_tuples!( #(
609			match Tuple::maybe_convert(a.clone()) {
610				Some(b) => return Some(b),
611				None => {},
612			}
613		)* );
614		None
615	}
616}
617
618/// Reversing fallible conversion trait returning an [Option]. Generic over both source and
619/// destination types.
620pub trait MaybeConvertBack<A, B>: MaybeConvert<A, B> {
621	/// Attempt to make conversion back.
622	fn maybe_convert_back(b: B) -> Option<A>;
623}
624
625#[impl_trait_for_tuples::impl_for_tuples(30)]
626impl<A: Clone, B: Clone> MaybeConvertBack<A, B> for Tuple {
627	fn maybe_convert_back(b: B) -> Option<A> {
628		for_tuples!( #(
629			match Tuple::maybe_convert_back(b.clone()) {
630				Some(a) => return Some(a),
631				None => {},
632			}
633		)* );
634		None
635	}
636}
637
638/// Fallible conversion trait which returns the argument in the case of being unable to convert.
639/// Generic over both source and destination types.
640pub trait TryConvert<A, B> {
641	/// Attempt to make conversion. If returning [Result::Err], the inner must always be `a`.
642	fn try_convert(a: A) -> Result<B, A>;
643}
644
645#[impl_trait_for_tuples::impl_for_tuples(30)]
646impl<A, B> TryConvert<A, B> for Tuple {
647	fn try_convert(a: A) -> Result<B, A> {
648		for_tuples!( #(
649			let a = match Tuple::try_convert(a) {
650				Ok(b) => return Ok(b),
651				Err(a) => a,
652			};
653		)* );
654		Err(a)
655	}
656}
657
658/// Reversing fallible conversion trait which returns the argument in the case of being unable to
659/// convert back. Generic over both source and destination types.
660pub trait TryConvertBack<A, B>: TryConvert<A, B> {
661	/// Attempt to make conversion back. If returning [Result::Err], the inner must always be `b`.
662
663	fn try_convert_back(b: B) -> Result<A, B>;
664}
665
666#[impl_trait_for_tuples::impl_for_tuples(30)]
667impl<A, B> TryConvertBack<A, B> for Tuple {
668	fn try_convert_back(b: B) -> Result<A, B> {
669		for_tuples!( #(
670			let b = match Tuple::try_convert_back(b) {
671				Ok(a) => return Ok(a),
672				Err(b) => b,
673			};
674		)* );
675		Err(b)
676	}
677}
678
679/// Definition for a bi-directional, fallible conversion between two types.
680pub trait MaybeEquivalence<A, B> {
681	/// Attempt to convert reference of `A` into value of `B`, returning `None` if not possible.
682	fn convert(a: &A) -> Option<B>;
683	/// Attempt to convert reference of `B` into value of `A`, returning `None` if not possible.
684	fn convert_back(b: &B) -> Option<A>;
685}
686
687#[impl_trait_for_tuples::impl_for_tuples(30)]
688impl<A, B> MaybeEquivalence<A, B> for Tuple {
689	fn convert(a: &A) -> Option<B> {
690		for_tuples!( #(
691			match Tuple::convert(a) {
692				Some(b) => return Some(b),
693				None => {},
694			}
695		)* );
696		None
697	}
698	fn convert_back(b: &B) -> Option<A> {
699		for_tuples!( #(
700			match Tuple::convert_back(b) {
701				Some(a) => return Some(a),
702				None => {},
703			}
704		)* );
705		None
706	}
707}
708
709/// Adapter which turns a [Get] implementation into a [Convert] implementation which always returns
710/// in the same value no matter the input.
711pub struct ConvertToValue<T>(core::marker::PhantomData<T>);
712impl<X, Y, T: Get<Y>> Convert<X, Y> for ConvertToValue<T> {
713	fn convert(_: X) -> Y {
714		T::get()
715	}
716}
717impl<X, Y, T: Get<Y>> MaybeConvert<X, Y> for ConvertToValue<T> {
718	fn maybe_convert(_: X) -> Option<Y> {
719		Some(T::get())
720	}
721}
722impl<X, Y, T: Get<Y>> MaybeConvertBack<X, Y> for ConvertToValue<T> {
723	fn maybe_convert_back(_: Y) -> Option<X> {
724		None
725	}
726}
727impl<X, Y, T: Get<Y>> TryConvert<X, Y> for ConvertToValue<T> {
728	fn try_convert(_: X) -> Result<Y, X> {
729		Ok(T::get())
730	}
731}
732impl<X, Y, T: Get<Y>> TryConvertBack<X, Y> for ConvertToValue<T> {
733	fn try_convert_back(y: Y) -> Result<X, Y> {
734		Err(y)
735	}
736}
737impl<X, Y, T: Get<Y>> MaybeEquivalence<X, Y> for ConvertToValue<T> {
738	fn convert(_: &X) -> Option<Y> {
739		Some(T::get())
740	}
741	fn convert_back(_: &Y) -> Option<X> {
742		None
743	}
744}
745
746/// A structure that performs identity conversion.
747pub struct Identity;
748impl<T> Convert<T, T> for Identity {
749	fn convert(a: T) -> T {
750		a
751	}
752}
753impl<T> ConvertBack<T, T> for Identity {
754	fn convert_back(a: T) -> T {
755		a
756	}
757}
758impl<T> MaybeConvert<T, T> for Identity {
759	fn maybe_convert(a: T) -> Option<T> {
760		Some(a)
761	}
762}
763impl<T> MaybeConvertBack<T, T> for Identity {
764	fn maybe_convert_back(a: T) -> Option<T> {
765		Some(a)
766	}
767}
768impl<T> TryConvert<T, T> for Identity {
769	fn try_convert(a: T) -> Result<T, T> {
770		Ok(a)
771	}
772}
773impl<T> TryConvertBack<T, T> for Identity {
774	fn try_convert_back(a: T) -> Result<T, T> {
775		Ok(a)
776	}
777}
778impl<T: Clone> MaybeEquivalence<T, T> for Identity {
779	fn convert(a: &T) -> Option<T> {
780		Some(a.clone())
781	}
782	fn convert_back(a: &T) -> Option<T> {
783		Some(a.clone())
784	}
785}
786
787/// A structure that performs standard conversion using the standard Rust conversion traits.
788pub struct ConvertInto;
789impl<A: Into<B>, B> Convert<A, B> for ConvertInto {
790	fn convert(a: A) -> B {
791		a.into()
792	}
793}
794impl<A: Into<B>, B> MaybeConvert<A, B> for ConvertInto {
795	fn maybe_convert(a: A) -> Option<B> {
796		Some(a.into())
797	}
798}
799impl<A: Into<B>, B: Into<A>> MaybeConvertBack<A, B> for ConvertInto {
800	fn maybe_convert_back(b: B) -> Option<A> {
801		Some(b.into())
802	}
803}
804impl<A: Into<B>, B> TryConvert<A, B> for ConvertInto {
805	fn try_convert(a: A) -> Result<B, A> {
806		Ok(a.into())
807	}
808}
809impl<A: Into<B>, B: Into<A>> TryConvertBack<A, B> for ConvertInto {
810	fn try_convert_back(b: B) -> Result<A, B> {
811		Ok(b.into())
812	}
813}
814impl<A: Clone + Into<B>, B: Clone + Into<A>> MaybeEquivalence<A, B> for ConvertInto {
815	fn convert(a: &A) -> Option<B> {
816		Some(a.clone().into())
817	}
818	fn convert_back(b: &B) -> Option<A> {
819		Some(b.clone().into())
820	}
821}
822
823/// A structure that performs standard conversion using the standard Rust conversion traits.
824pub struct TryConvertInto;
825impl<A: Clone + TryInto<B>, B> MaybeConvert<A, B> for TryConvertInto {
826	fn maybe_convert(a: A) -> Option<B> {
827		a.clone().try_into().ok()
828	}
829}
830impl<A: Clone + TryInto<B>, B: Clone + TryInto<A>> MaybeConvertBack<A, B> for TryConvertInto {
831	fn maybe_convert_back(b: B) -> Option<A> {
832		b.clone().try_into().ok()
833	}
834}
835impl<A: Clone + TryInto<B>, B> TryConvert<A, B> for TryConvertInto {
836	fn try_convert(a: A) -> Result<B, A> {
837		a.clone().try_into().map_err(|_| a)
838	}
839}
840impl<A: Clone + TryInto<B>, B: Clone + TryInto<A>> TryConvertBack<A, B> for TryConvertInto {
841	fn try_convert_back(b: B) -> Result<A, B> {
842		b.clone().try_into().map_err(|_| b)
843	}
844}
845impl<A: Clone + TryInto<B>, B: Clone + TryInto<A>> MaybeEquivalence<A, B> for TryConvertInto {
846	fn convert(a: &A) -> Option<B> {
847		a.clone().try_into().ok()
848	}
849	fn convert_back(b: &B) -> Option<A> {
850		b.clone().try_into().ok()
851	}
852}
853
854/// Convenience type to work around the highly unergonomic syntax needed
855/// to invoke the functions of overloaded generic traits, in this case
856/// `TryFrom` and `TryInto`.
857pub trait CheckedConversion {
858	/// Convert from a value of `T` into an equivalent instance of `Option<Self>`.
859	///
860	/// This just uses `TryFrom` internally but with this
861	/// variant you can provide the destination type using turbofish syntax
862	/// in case Rust happens not to assume the correct type.
863	fn checked_from<T>(t: T) -> Option<Self>
864	where
865		Self: TryFrom<T>,
866	{
867		<Self as TryFrom<T>>::try_from(t).ok()
868	}
869	/// Consume self to return `Some` equivalent value of `Option<T>`.
870	///
871	/// This just uses `TryInto` internally but with this
872	/// variant you can provide the destination type using turbofish syntax
873	/// in case Rust happens not to assume the correct type.
874	fn checked_into<T>(self) -> Option<T>
875	where
876		Self: TryInto<T>,
877	{
878		<Self as TryInto<T>>::try_into(self).ok()
879	}
880}
881impl<T: Sized> CheckedConversion for T {}
882
883/// Multiply and divide by a number that isn't necessarily the same type. Basically just the same
884/// as `Mul` and `Div` except it can be used for all basic numeric types.
885pub trait Scale<Other> {
886	/// The output type of the product of `self` and `Other`.
887	type Output;
888
889	/// @return the product of `self` and `other`.
890	fn mul(self, other: Other) -> Self::Output;
891
892	/// @return the integer division of `self` and `other`.
893	fn div(self, other: Other) -> Self::Output;
894
895	/// @return the modulo remainder of `self` and `other`.
896	fn rem(self, other: Other) -> Self::Output;
897}
898macro_rules! impl_scale {
899	($self:ty, $other:ty) => {
900		impl Scale<$other> for $self {
901			type Output = Self;
902			fn mul(self, other: $other) -> Self::Output {
903				self * (other as Self)
904			}
905			fn div(self, other: $other) -> Self::Output {
906				self / (other as Self)
907			}
908			fn rem(self, other: $other) -> Self::Output {
909				self % (other as Self)
910			}
911		}
912	};
913}
914impl_scale!(u128, u128);
915impl_scale!(u128, u64);
916impl_scale!(u128, u32);
917impl_scale!(u128, u16);
918impl_scale!(u128, u8);
919impl_scale!(u64, u64);
920impl_scale!(u64, u32);
921impl_scale!(u64, u16);
922impl_scale!(u64, u8);
923impl_scale!(u32, u32);
924impl_scale!(u32, u16);
925impl_scale!(u32, u8);
926impl_scale!(u16, u16);
927impl_scale!(u16, u8);
928impl_scale!(u8, u8);
929
930/// Trait for things that can be clear (have no bits set). For numeric types, essentially the same
931/// as `Zero`.
932pub trait Clear {
933	/// True iff no bits are set.
934	fn is_clear(&self) -> bool;
935
936	/// Return the value of Self that is clear.
937	fn clear() -> Self;
938}
939
940impl<T: Default + Eq + PartialEq> Clear for T {
941	fn is_clear(&self) -> bool {
942		*self == Self::clear()
943	}
944	fn clear() -> Self {
945		Default::default()
946	}
947}
948
949/// A meta trait for all bit ops.
950pub trait SimpleBitOps:
951	Sized
952	+ Clear
953	+ core::ops::BitOr<Self, Output = Self>
954	+ core::ops::BitXor<Self, Output = Self>
955	+ core::ops::BitAnd<Self, Output = Self>
956{
957}
958impl<
959		T: Sized
960			+ Clear
961			+ core::ops::BitOr<Self, Output = Self>
962			+ core::ops::BitXor<Self, Output = Self>
963			+ core::ops::BitAnd<Self, Output = Self>,
964	> SimpleBitOps for T
965{
966}
967
968/// Abstraction around hashing
969// Stupid bug in the Rust compiler believes derived
970// traits must be fulfilled by all type parameters.
971pub trait Hash:
972	'static
973	+ MaybeSerializeDeserialize
974	+ Debug
975	+ Clone
976	+ Eq
977	+ PartialEq
978	+ Hasher<Out = <Self as Hash>::Output>
979{
980	/// The hash type produced.
981	type Output: HashOutput;
982
983	/// Produce the hash of some byte-slice.
984	fn hash(s: &[u8]) -> Self::Output {
985		<Self as Hasher>::hash(s)
986	}
987
988	/// Produce the hash of some codec-encodable value.
989	fn hash_of<S: Encode>(s: &S) -> Self::Output {
990		Encode::using_encoded(s, <Self as Hasher>::hash)
991	}
992
993	/// The ordered Patricia tree root of the given `input`.
994	fn ordered_trie_root(input: Vec<Vec<u8>>, state_version: StateVersion) -> Self::Output;
995
996	/// The Patricia tree root of the given mapping.
997	fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>, state_version: StateVersion) -> Self::Output;
998}
999
1000/// Super trait with all the attributes for a hashing output.
1001pub trait HashOutput:
1002	Member
1003	+ MaybeSerializeDeserialize
1004	+ MaybeDisplay
1005	+ MaybeFromStr
1006	+ Debug
1007	+ core::hash::Hash
1008	+ AsRef<[u8]>
1009	+ AsMut<[u8]>
1010	+ Copy
1011	+ Ord
1012	+ Default
1013	+ Encode
1014	+ Decode
1015	+ DecodeWithMemTracking
1016	+ EncodeLike
1017	+ MaxEncodedLen
1018	+ TypeInfo
1019{
1020}
1021
1022impl<T> HashOutput for T where
1023	T: Member
1024		+ MaybeSerializeDeserialize
1025		+ MaybeDisplay
1026		+ MaybeFromStr
1027		+ Debug
1028		+ core::hash::Hash
1029		+ AsRef<[u8]>
1030		+ AsMut<[u8]>
1031		+ Copy
1032		+ Ord
1033		+ Default
1034		+ Encode
1035		+ Decode
1036		+ DecodeWithMemTracking
1037		+ EncodeLike
1038		+ MaxEncodedLen
1039		+ TypeInfo
1040{
1041}
1042
1043/// Blake2-256 Hash implementation.
1044#[derive(PartialEq, Eq, Clone, RuntimeDebug, TypeInfo)]
1045#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1046pub struct BlakeTwo256;
1047
1048impl Hasher for BlakeTwo256 {
1049	type Out = pezsp_core::H256;
1050	type StdHasher = hash256_std_hasher::Hash256StdHasher;
1051	const LENGTH: usize = 32;
1052
1053	fn hash(s: &[u8]) -> Self::Out {
1054		pezsp_io::hashing::blake2_256(s).into()
1055	}
1056}
1057
1058impl Hash for BlakeTwo256 {
1059	type Output = pezsp_core::H256;
1060
1061	fn ordered_trie_root(input: Vec<Vec<u8>>, version: StateVersion) -> Self::Output {
1062		pezsp_io::trie::blake2_256_ordered_root(input, version)
1063	}
1064
1065	fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>, version: StateVersion) -> Self::Output {
1066		pezsp_io::trie::blake2_256_root(input, version)
1067	}
1068}
1069
1070/// Keccak-256 Hash implementation.
1071#[derive(PartialEq, Eq, Clone, RuntimeDebug, TypeInfo)]
1072#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1073pub struct Keccak256;
1074
1075impl Hasher for Keccak256 {
1076	type Out = pezsp_core::H256;
1077	type StdHasher = hash256_std_hasher::Hash256StdHasher;
1078	const LENGTH: usize = 32;
1079
1080	fn hash(s: &[u8]) -> Self::Out {
1081		pezsp_io::hashing::keccak_256(s).into()
1082	}
1083}
1084
1085impl Hash for Keccak256 {
1086	type Output = pezsp_core::H256;
1087
1088	fn ordered_trie_root(input: Vec<Vec<u8>>, version: StateVersion) -> Self::Output {
1089		pezsp_io::trie::keccak_256_ordered_root(input, version)
1090	}
1091
1092	fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>, version: StateVersion) -> Self::Output {
1093		pezsp_io::trie::keccak_256_root(input, version)
1094	}
1095}
1096
1097/// Something that can be checked for equality and printed out to a debug channel if bad.
1098pub trait CheckEqual {
1099	/// Perform the equality check.
1100	fn check_equal(&self, other: &Self);
1101}
1102
1103impl CheckEqual for pezsp_core::H256 {
1104	#[cfg(feature = "std")]
1105	fn check_equal(&self, other: &Self) {
1106		use pezsp_core::hexdisplay::HexDisplay;
1107		if self != other {
1108			println!(
1109				"Hash: given={}, expected={}",
1110				HexDisplay::from(self.as_fixed_bytes()),
1111				HexDisplay::from(other.as_fixed_bytes()),
1112			);
1113		}
1114	}
1115
1116	#[cfg(not(feature = "std"))]
1117	fn check_equal(&self, other: &Self) {
1118		if self != other {
1119			"Hash not equal".print();
1120			self.as_bytes().print();
1121			other.as_bytes().print();
1122		}
1123	}
1124}
1125
1126impl CheckEqual for super::generic::DigestItem {
1127	#[cfg(feature = "std")]
1128	fn check_equal(&self, other: &Self) {
1129		if self != other {
1130			println!("DigestItem: given={:?}, expected={:?}", self, other);
1131		}
1132	}
1133
1134	#[cfg(not(feature = "std"))]
1135	fn check_equal(&self, other: &Self) {
1136		if self != other {
1137			"DigestItem not equal".print();
1138			(&Encode::encode(self)[..]).print();
1139			(&Encode::encode(other)[..]).print();
1140		}
1141	}
1142}
1143
1144pezsp_core::impl_maybe_marker!(
1145	/// A type that implements Display when in std environment.
1146	trait MaybeDisplay: Display;
1147
1148	/// A type that implements FromStr when in std environment.
1149	trait MaybeFromStr: FromStr;
1150
1151	/// A type that implements Hash when in std environment.
1152	trait MaybeHash: core::hash::Hash;
1153);
1154
1155pezsp_core::impl_maybe_marker_std_or_serde!(
1156	/// A type that implements Serialize when in std environment or serde feature is activated.
1157	trait MaybeSerialize: Serialize;
1158
1159	/// A type that implements Serialize, DeserializeOwned and Debug when in std environment or serde feature is activated.
1160	trait MaybeSerializeDeserialize: DeserializeOwned, Serialize;
1161);
1162
1163/// A type that can be used in runtime structures.
1164pub trait Member: Send + Sync + Sized + Debug + Eq + PartialEq + Clone + 'static {}
1165impl<T: Send + Sync + Sized + Debug + Eq + PartialEq + Clone + 'static> Member for T {}
1166
1167/// Determine if a `MemberId` is a valid member.
1168pub trait IsMember<MemberId> {
1169	/// Is the given `MemberId` a valid member?
1170	fn is_member(member_id: &MemberId) -> bool;
1171}
1172
1173/// Super trait with all the attributes for a block number.
1174pub trait BlockNumber:
1175	Member
1176	+ MaybeSerializeDeserialize
1177	+ MaybeFromStr
1178	+ Debug
1179	+ core::hash::Hash
1180	+ Copy
1181	+ MaybeDisplay
1182	+ AtLeast32BitUnsigned
1183	+ Into<U256>
1184	+ TryFrom<U256>
1185	+ Default
1186	+ TypeInfo
1187	+ MaxEncodedLen
1188	+ FullCodec
1189	+ DecodeWithMemTracking
1190	+ HasCompact<Type: DecodeWithMemTracking>
1191{
1192}
1193
1194impl<
1195		T: Member
1196			+ MaybeSerializeDeserialize
1197			+ MaybeFromStr
1198			+ Debug
1199			+ core::hash::Hash
1200			+ Copy
1201			+ MaybeDisplay
1202			+ AtLeast32BitUnsigned
1203			+ Into<U256>
1204			+ TryFrom<U256>
1205			+ Default
1206			+ TypeInfo
1207			+ MaxEncodedLen
1208			+ FullCodec
1209			+ DecodeWithMemTracking
1210			+ HasCompact<Type: DecodeWithMemTracking>,
1211	> BlockNumber for T
1212{
1213}
1214
1215/// Something which fulfills the abstract idea of a Bizinikiwi header. It has types for a `Number`,
1216/// a `Hash` and a `Hashing`. It provides access to an `extrinsics_root`, `state_root` and
1217/// `parent_hash`, as well as a `digest` and a block `number`.
1218///
1219/// You can also create a `new` one from those fields.
1220pub trait Header:
1221	Clone
1222	+ Send
1223	+ Sync
1224	+ Codec
1225	+ DecodeWithMemTracking
1226	+ Eq
1227	+ MaybeSerialize
1228	+ Debug
1229	+ TypeInfo
1230	+ 'static
1231{
1232	/// Header number.
1233	type Number: BlockNumber;
1234	/// Header hash type
1235	type Hash: HashOutput;
1236	/// Hashing algorithm
1237	type Hashing: Hash<Output = Self::Hash>;
1238
1239	/// Creates new header.
1240	fn new(
1241		number: Self::Number,
1242		extrinsics_root: Self::Hash,
1243		state_root: Self::Hash,
1244		parent_hash: Self::Hash,
1245		digest: Digest,
1246	) -> Self;
1247
1248	/// Returns a reference to the header number.
1249	fn number(&self) -> &Self::Number;
1250	/// Sets the header number.
1251	fn set_number(&mut self, number: Self::Number);
1252
1253	/// Returns a reference to the extrinsics root.
1254	fn extrinsics_root(&self) -> &Self::Hash;
1255	/// Sets the extrinsic root.
1256	fn set_extrinsics_root(&mut self, root: Self::Hash);
1257
1258	/// Returns a reference to the state root.
1259	fn state_root(&self) -> &Self::Hash;
1260	/// Sets the state root.
1261	fn set_state_root(&mut self, root: Self::Hash);
1262
1263	/// Returns a reference to the parent hash.
1264	fn parent_hash(&self) -> &Self::Hash;
1265	/// Sets the parent hash.
1266	fn set_parent_hash(&mut self, hash: Self::Hash);
1267
1268	/// Returns a reference to the digest.
1269	fn digest(&self) -> &Digest;
1270	/// Get a mutable reference to the digest.
1271	fn digest_mut(&mut self) -> &mut Digest;
1272
1273	/// Returns the hash of the header.
1274	fn hash(&self) -> Self::Hash {
1275		<Self::Hashing as Hash>::hash_of(self)
1276	}
1277}
1278
1279// Something that provides the Header Type. Only for internal usage and should only be used
1280// via `HeaderFor` or `BlockNumberFor`.
1281//
1282// This is needed to fix the "cyclical" issue in loading Header/BlockNumber as part of a
1283// `pezpallet::call`. Essentially, `construct_runtime` aggregates all calls to create a
1284// `RuntimeCall` that is then used to define `UncheckedExtrinsic`.
1285// ```ignore
1286// pub type UncheckedExtrinsic =
1287// 	generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
1288// ```
1289// This `UncheckedExtrinsic` is supplied to the `Block`.
1290// ```ignore
1291// pub type Block = generic::Block<Header, UncheckedExtrinsic>;
1292// ```
1293// So, if we do not create a trait outside of `Block` that doesn't have `Extrinsic`, we go into a
1294// recursive loop leading to a build error.
1295//
1296// Note that this is a workaround for a compiler bug and should be removed when the compiler
1297// bug is fixed.
1298#[doc(hidden)]
1299pub trait HeaderProvider {
1300	/// Header type.
1301	type HeaderT: Header;
1302}
1303
1304/// An extrinsic that can be lazily decoded.
1305pub trait LazyExtrinsic: Sized {
1306	/// Try to decode the lazy extrinsic.
1307	///
1308	/// Usually an encoded extrinsic is composed of 2 parts:
1309	/// - a `Compact<u32>` prefix (`len)`
1310	/// - a blob of size `len`
1311	/// This method expects to receive just the blob as a byte slice.
1312	/// The size of the blob is the `len`.
1313	fn decode_unprefixed(data: &[u8]) -> Result<Self, codec::Error>;
1314}
1315
1316/// A Bizinikiwi block that allows us to lazily decode its extrinsics.
1317pub trait LazyBlock: Debug + Encode + Decode + Sized {
1318	/// Type for the decoded extrinsics.
1319	type Extrinsic: LazyExtrinsic;
1320	/// Header type.
1321	type Header: Header;
1322
1323	/// Returns a reference to the header.
1324	fn header(&self) -> &Self::Header;
1325
1326	/// Returns a mut reference to the header.
1327	fn header_mut(&mut self) -> &mut Self::Header;
1328
1329	/// Returns an iterator over all extrinsics.
1330	///
1331	/// The extrinsics are lazily decoded (if possible) as they are pulled by the iterator.
1332	fn extrinsics(&self) -> impl Iterator<Item = Result<Self::Extrinsic, codec::Error>>;
1333}
1334
1335/// Something which fulfills the abstract idea of a Bizinikiwi block. It has types for
1336/// `Extrinsic` pieces of information as well as a `Header`.
1337///
1338/// You can get an iterator over each of the `extrinsics` and retrieve the `header`.
1339pub trait Block:
1340	HeaderProvider<HeaderT = Self::Header>
1341	+ Into<Self::LazyBlock>
1342	+ EncodeLike<Self::LazyBlock>
1343	+ Clone
1344	+ Send
1345	+ Sync
1346	+ Codec
1347	+ DecodeWithMemTracking
1348	+ Eq
1349	+ MaybeSerialize
1350	+ Debug
1351	+ 'static
1352{
1353	/// Type for extrinsics.
1354	type Extrinsic: Member + Codec + ExtrinsicLike + MaybeSerialize + Into<OpaqueExtrinsic>;
1355	/// Header type.
1356	type Header: Header<Hash = Self::Hash> + MaybeSerializeDeserialize;
1357	/// Block hash type.
1358	type Hash: HashOutput;
1359
1360	/// A shadow structure which allows us to lazily decode the extrinsics.
1361	/// The `LazyBlock` must have the same encoded representation as the `Block`.
1362	type LazyBlock: LazyBlock<Extrinsic = Self::Extrinsic, Header = Self::Header> + EncodeLike<Self>;
1363
1364	/// Returns a reference to the header.
1365	fn header(&self) -> &Self::Header;
1366	/// Returns a reference to the list of extrinsics.
1367	fn extrinsics(&self) -> &[Self::Extrinsic];
1368	/// Split the block into header and list of extrinsics.
1369	fn deconstruct(self) -> (Self::Header, Vec<Self::Extrinsic>);
1370	/// Creates new block from header and extrinsics.
1371	fn new(header: Self::Header, extrinsics: Vec<Self::Extrinsic>) -> Self;
1372	/// Returns the hash of the block.
1373	fn hash(&self) -> Self::Hash {
1374		<<Self::Header as Header>::Hashing as Hash>::hash_of(self.header())
1375	}
1376}
1377
1378/// Something that acts like an `Extrinsic`.
1379#[deprecated = "Use `ExtrinsicLike` along with the `CreateTransaction` trait family instead"]
1380pub trait Extrinsic: Sized {
1381	/// The function call.
1382	type Call: TypeInfo;
1383
1384	/// The payload we carry for signed extrinsics.
1385	///
1386	/// Usually it will contain a `Signature` and
1387	/// may include some additional data that are specific to signed
1388	/// extrinsics.
1389	type SignaturePayload: SignaturePayload;
1390
1391	/// Is this `Extrinsic` signed?
1392	/// If no information are available about signed/unsigned, `None` should be returned.
1393	fn is_signed(&self) -> Option<bool> {
1394		None
1395	}
1396
1397	/// Returns `true` if this `Extrinsic` is bare.
1398	fn is_bare(&self) -> bool {
1399		!self.is_signed().unwrap_or(true)
1400	}
1401
1402	/// Create a new old-school extrinsic, either a bare extrinsic if `_signed_data` is `None` or
1403	/// a signed transaction is it is `Some`.
1404	fn new(_call: Self::Call, _signed_data: Option<Self::SignaturePayload>) -> Option<Self> {
1405		None
1406	}
1407}
1408
1409/// Something that acts like an `Extrinsic`.
1410pub trait ExtrinsicLike: Sized {
1411	/// Is this `Extrinsic` signed?
1412	/// If no information are available about signed/unsigned, `None` should be returned.
1413	#[deprecated = "Use and implement `!is_bare()` instead"]
1414	fn is_signed(&self) -> Option<bool> {
1415		None
1416	}
1417
1418	/// Returns `true` if this `Extrinsic` is bare.
1419	fn is_bare(&self) -> bool {
1420		#[allow(deprecated)]
1421		!self.is_signed().unwrap_or(true)
1422	}
1423}
1424
1425#[allow(deprecated)]
1426impl<T> ExtrinsicLike for T
1427where
1428	T: Extrinsic,
1429{
1430	fn is_signed(&self) -> Option<bool> {
1431		#[allow(deprecated)]
1432		<Self as Extrinsic>::is_signed(&self)
1433	}
1434
1435	fn is_bare(&self) -> bool {
1436		<Self as Extrinsic>::is_bare(&self)
1437	}
1438}
1439
1440/// An extrinsic on which we can get access to call.
1441pub trait ExtrinsicCall: ExtrinsicLike {
1442	/// The type of the call.
1443	type Call;
1444
1445	/// Get a reference to the call of the extrinsic.
1446	fn call(&self) -> &Self::Call;
1447
1448	/// Convert the extrinsic into its call.
1449	fn into_call(self) -> Self::Call;
1450}
1451
1452/// Something that acts like a [`SignaturePayload`](Extrinsic::SignaturePayload) of an
1453/// [`Extrinsic`].
1454pub trait SignaturePayload {
1455	/// The type of the address that signed the extrinsic.
1456	///
1457	/// Particular to a signed extrinsic.
1458	type SignatureAddress: TypeInfo;
1459
1460	/// The signature type of the extrinsic.
1461	///
1462	/// Particular to a signed extrinsic.
1463	type Signature: TypeInfo;
1464
1465	/// The additional data that is specific to the signed extrinsic.
1466	///
1467	/// Particular to a signed extrinsic.
1468	type SignatureExtra: TypeInfo;
1469}
1470
1471impl SignaturePayload for () {
1472	type SignatureAddress = ();
1473	type Signature = ();
1474	type SignatureExtra = ();
1475}
1476
1477/// Implementor is an [`Extrinsic`] and provides metadata about this extrinsic.
1478pub trait ExtrinsicMetadata {
1479	/// The format versions of the `Extrinsic`.
1480	///
1481	/// By format we mean the encoded representation of the `Extrinsic`.
1482	const VERSIONS: &'static [u8];
1483
1484	/// Transaction extensions attached to this `Extrinsic`.
1485	type TransactionExtensions;
1486}
1487
1488/// Extract the hashing type for a block.
1489pub type HashingFor<B> = <<B as Block>::Header as Header>::Hashing;
1490/// Extract the number type for a block.
1491pub type NumberFor<B> = <<B as Block>::Header as Header>::Number;
1492/// Extract the digest type for a block.
1493
1494/// A "checkable" piece of information, used by the standard Bizinikiwi Executive in order to
1495/// check the validity of a piece of extrinsic information, usually by verifying the signature.
1496/// Implement for pieces of information that require some additional context `Context` in order to
1497/// be checked.
1498pub trait Checkable<Context>: Sized {
1499	/// Returned if `check` succeeds.
1500	type Checked;
1501
1502	/// Check self, given an instance of Context.
1503	fn check(self, c: &Context) -> Result<Self::Checked, TransactionValidityError>;
1504
1505	/// Blindly check self.
1506	///
1507	/// ## WARNING
1508	///
1509	/// DO NOT USE IN PRODUCTION. This is only meant to be used in testing environments. A runtime
1510	/// compiled with `try-runtime` should never be in production. Moreover, the name of this
1511	/// function is deliberately chosen to prevent developers from ever calling it in consensus
1512	/// code-paths.
1513	#[cfg(feature = "try-runtime")]
1514	fn unchecked_into_checked_i_know_what_i_am_doing(
1515		self,
1516		c: &Context,
1517	) -> Result<Self::Checked, TransactionValidityError>;
1518}
1519
1520/// A "checkable" piece of information, used by the standard Bizinikiwi Executive in order to
1521/// check the validity of a piece of extrinsic information, usually by verifying the signature.
1522/// Implement for pieces of information that don't require additional context in order to be
1523/// checked.
1524pub trait BlindCheckable: Sized {
1525	/// Returned if `check` succeeds.
1526	type Checked;
1527
1528	/// Check self.
1529	fn check(self) -> Result<Self::Checked, TransactionValidityError>;
1530}
1531
1532// Every `BlindCheckable` is also a `StaticCheckable` for arbitrary `Context`.
1533impl<T: BlindCheckable, Context> Checkable<Context> for T {
1534	type Checked = <Self as BlindCheckable>::Checked;
1535
1536	fn check(self, _c: &Context) -> Result<Self::Checked, TransactionValidityError> {
1537		BlindCheckable::check(self)
1538	}
1539
1540	#[cfg(feature = "try-runtime")]
1541	fn unchecked_into_checked_i_know_what_i_am_doing(
1542		self,
1543		_: &Context,
1544	) -> Result<Self::Checked, TransactionValidityError> {
1545		unreachable!();
1546	}
1547}
1548
1549/// A type that can handle weight refunds.
1550pub trait RefundWeight {
1551	/// Refund some unspent weight.
1552	fn refund(&mut self, weight: pezsp_weights::Weight);
1553}
1554
1555/// A type that can handle weight refunds and incorporate extension weights into the call weight
1556/// after dispatch.
1557pub trait ExtensionPostDispatchWeightHandler<DispatchInfo>: RefundWeight {
1558	/// Accrue some weight pertaining to the extension.
1559	fn set_extension_weight(&mut self, info: &DispatchInfo);
1560}
1561
1562impl RefundWeight for () {
1563	fn refund(&mut self, _weight: pezsp_weights::Weight) {}
1564}
1565
1566impl ExtensionPostDispatchWeightHandler<()> for () {
1567	fn set_extension_weight(&mut self, _info: &()) {}
1568}
1569
1570/// A lazy call (module function and argument values) that can be executed via its `dispatch`
1571/// method.
1572pub trait Dispatchable {
1573	/// Every function call from your runtime has an origin, which specifies where the extrinsic was
1574	/// generated from. In the case of a signed extrinsic (transaction), the origin contains an
1575	/// identifier for the caller. The origin can be empty in the case of an inherent extrinsic.
1576	type RuntimeOrigin: Debug;
1577	/// ...
1578	type Config;
1579	/// An opaque set of information attached to the transaction. This could be constructed anywhere
1580	/// down the line in a runtime. The current Bizinikiwi runtime uses a struct with the same name
1581	/// to represent the dispatch class and weight.
1582	type Info;
1583	/// Additional information that is returned by `dispatch`. Can be used to supply the caller
1584	/// with information about a `Dispatchable` that is only known post dispatch.
1585	type PostInfo: Eq
1586		+ PartialEq
1587		+ Clone
1588		+ Copy
1589		+ Encode
1590		+ Decode
1591		+ Printable
1592		+ ExtensionPostDispatchWeightHandler<Self::Info>;
1593	/// Actually dispatch this call and return the result of it.
1594	fn dispatch(self, origin: Self::RuntimeOrigin)
1595		-> crate::DispatchResultWithInfo<Self::PostInfo>;
1596}
1597
1598/// Shortcut to reference the `RuntimeOrigin` type of a `Dispatchable`.
1599pub type DispatchOriginOf<T> = <T as Dispatchable>::RuntimeOrigin;
1600/// Shortcut to reference the `Info` type of a `Dispatchable`.
1601pub type DispatchInfoOf<T> = <T as Dispatchable>::Info;
1602/// Shortcut to reference the `PostInfo` type of a `Dispatchable`.
1603pub type PostDispatchInfoOf<T> = <T as Dispatchable>::PostInfo;
1604
1605impl Dispatchable for () {
1606	type RuntimeOrigin = ();
1607	type Config = ();
1608	type Info = ();
1609	type PostInfo = ();
1610	fn dispatch(
1611		self,
1612		_origin: Self::RuntimeOrigin,
1613	) -> crate::DispatchResultWithInfo<Self::PostInfo> {
1614		panic!("This implementation should not be used for actual dispatch.");
1615	}
1616}
1617
1618/// Dispatchable impl containing an arbitrary value which panics if it actually is dispatched.
1619#[derive(Clone, Eq, PartialEq, Encode, Decode, DecodeWithMemTracking, RuntimeDebug, TypeInfo)]
1620pub struct FakeDispatchable<Inner>(pub Inner);
1621impl<Inner> From<Inner> for FakeDispatchable<Inner> {
1622	fn from(inner: Inner) -> Self {
1623		Self(inner)
1624	}
1625}
1626impl<Inner> FakeDispatchable<Inner> {
1627	/// Take `self` and return the underlying inner value.
1628	pub fn deconstruct(self) -> Inner {
1629		self.0
1630	}
1631}
1632impl<Inner> AsRef<Inner> for FakeDispatchable<Inner> {
1633	fn as_ref(&self) -> &Inner {
1634		&self.0
1635	}
1636}
1637
1638impl<Inner> Dispatchable for FakeDispatchable<Inner> {
1639	type RuntimeOrigin = ();
1640	type Config = ();
1641	type Info = ();
1642	type PostInfo = ();
1643	fn dispatch(
1644		self,
1645		_origin: Self::RuntimeOrigin,
1646	) -> crate::DispatchResultWithInfo<Self::PostInfo> {
1647		panic!("This implementation should not be used for actual dispatch.");
1648	}
1649}
1650
1651/// Runtime Origin which includes a System Origin variant whose `AccountId` is the parameter.
1652pub trait AsSystemOriginSigner<AccountId> {
1653	/// Extract a reference of the inner value of the System `Origin::Signed` variant, if self has
1654	/// that variant.
1655	fn as_system_origin_signer(&self) -> Option<&AccountId>;
1656}
1657
1658/// Interface to differentiate between Runtime Origins authorized to include a transaction into the
1659/// block and dispatch it, and those who aren't.
1660///
1661/// This trait targets transactions, by which we mean extrinsics which are validated through a
1662/// [`TransactionExtension`]. This excludes bare extrinsics (i.e. inherents), which have their call,
1663/// not their origin, validated and authorized.
1664///
1665/// Typically, upon validation or application of a transaction, the origin resulting from the
1666/// transaction extension (see [`TransactionExtension`]) is checked for authorization. The
1667/// transaction is then rejected or applied.
1668///
1669/// In FRAME, an authorized origin is either an `Origin::Signed` System origin or a custom origin
1670/// authorized in a [`TransactionExtension`].
1671pub trait AsTransactionAuthorizedOrigin {
1672	/// Whether the origin is authorized to include a transaction in a block.
1673	///
1674	/// In typical FRAME chains, this function returns `false` if the origin is a System
1675	/// `Origin::None` variant, `true` otherwise, meaning only signed or custom origin resulting
1676	/// from the transaction extension pipeline are authorized.
1677	///
1678	/// NOTE: This function should not be used in the context of bare extrinsics (i.e. inherents),
1679	/// as bare extrinsics do not authorize the origin but rather the call itself, and are not
1680	/// validated through the [`TransactionExtension`] pipeline.
1681	fn is_transaction_authorized(&self) -> bool;
1682}
1683
1684/// Means by which a transaction may be extended. This type embodies both the data and the logic
1685/// that should be additionally associated with the transaction. It should be plain old data.
1686#[deprecated = "Use `TransactionExtension` instead."]
1687pub trait SignedExtension:
1688	Codec + DecodeWithMemTracking + Debug + Sync + Send + Clone + Eq + PartialEq + StaticTypeInfo
1689{
1690	/// Unique identifier of this signed extension.
1691	///
1692	/// This will be exposed in the metadata to identify the signed extension used
1693	/// in an extrinsic.
1694	const IDENTIFIER: &'static str;
1695
1696	/// The type which encodes the sender identity.
1697	type AccountId;
1698
1699	/// The type which encodes the call to be dispatched.
1700	type Call: Dispatchable;
1701
1702	/// Any additional data that will go into the signed payload. This may be created dynamically
1703	/// from the transaction using the `additional_signed` function.
1704	type AdditionalSigned: Codec + TypeInfo;
1705
1706	/// The type that encodes information that can be passed from pre_dispatch to post-dispatch.
1707	type Pre;
1708
1709	/// Construct any additional data that should be in the signed payload of the transaction. Can
1710	/// also perform any pre-signature-verification checks and return an error if needed.
1711	fn additional_signed(&self) -> Result<Self::AdditionalSigned, TransactionValidityError>;
1712
1713	/// Validate a signed transaction for the transaction queue.
1714	///
1715	/// This function can be called frequently by the transaction queue,
1716	/// to obtain transaction validity against current state.
1717	/// It should perform all checks that determine a valid transaction,
1718	/// that can pay for its execution and quickly eliminate ones
1719	/// that are stale or incorrect.
1720	///
1721	/// Make sure to perform the same checks in `pre_dispatch` function.
1722	fn validate(
1723		&self,
1724		_who: &Self::AccountId,
1725		_call: &Self::Call,
1726		_info: &DispatchInfoOf<Self::Call>,
1727		_len: usize,
1728	) -> TransactionValidity {
1729		Ok(ValidTransaction::default())
1730	}
1731
1732	/// Do any pre-flight stuff for a signed transaction.
1733	///
1734	/// Make sure to perform the same checks as in [`Self::validate`].
1735	fn pre_dispatch(
1736		self,
1737		who: &Self::AccountId,
1738		call: &Self::Call,
1739		info: &DispatchInfoOf<Self::Call>,
1740		len: usize,
1741	) -> Result<Self::Pre, TransactionValidityError>;
1742
1743	/// Do any post-flight stuff for an extrinsic.
1744	///
1745	/// If the transaction is signed, then `_pre` will contain the output of `pre_dispatch`,
1746	/// and `None` otherwise.
1747	///
1748	/// This gets given the `DispatchResult` `_result` from the extrinsic and can, if desired,
1749	/// introduce a `TransactionValidityError`, causing the block to become invalid for including
1750	/// it.
1751	///
1752	/// WARNING: It is dangerous to return an error here. To do so will fundamentally invalidate the
1753	/// transaction and any block that it is included in, causing the block author to not be
1754	/// compensated for their work in validating the transaction or producing the block so far.
1755	///
1756	/// It can only be used safely when you *know* that the extrinsic is one that can only be
1757	/// introduced by the current block author; generally this implies that it is an inherent and
1758	/// will come from either an offchain-worker or via `InherentData`.
1759	fn post_dispatch(
1760		_pre: Option<Self::Pre>,
1761		_info: &DispatchInfoOf<Self::Call>,
1762		_post_info: &PostDispatchInfoOf<Self::Call>,
1763		_len: usize,
1764		_result: &DispatchResult,
1765	) -> Result<(), TransactionValidityError> {
1766		Ok(())
1767	}
1768
1769	/// Returns the metadata for this signed extension.
1770	///
1771	/// As a [`SignedExtension`] can be a tuple of [`SignedExtension`]s we need to return a `Vec`
1772	/// that holds the metadata of each one. Each individual `SignedExtension` must return
1773	/// *exactly* one [`TransactionExtensionMetadata`].
1774	///
1775	/// This method provides a default implementation that returns a vec containing a single
1776	/// [`TransactionExtensionMetadata`].
1777	fn metadata() -> Vec<TransactionExtensionMetadata> {
1778		alloc::vec![TransactionExtensionMetadata {
1779			identifier: Self::IDENTIFIER,
1780			ty: scale_info::meta_type::<Self>(),
1781			implicit: scale_info::meta_type::<Self::AdditionalSigned>()
1782		}]
1783	}
1784
1785	/// Validate an unsigned transaction for the transaction queue.
1786	///
1787	/// This function can be called frequently by the transaction queue
1788	/// to obtain transaction validity against current state.
1789	/// It should perform all checks that determine a valid unsigned transaction,
1790	/// and quickly eliminate ones that are stale or incorrect.
1791	fn validate_unsigned(
1792		_call: &Self::Call,
1793		_info: &DispatchInfoOf<Self::Call>,
1794		_len: usize,
1795	) -> TransactionValidity {
1796		Ok(ValidTransaction::default())
1797	}
1798
1799	/// Do any pre-flight stuff for an unsigned transaction.
1800	///
1801	/// Note this function by default delegates to `validate_unsigned`, so that
1802	/// all checks performed for the transaction queue are also performed during
1803	/// the dispatch phase (applying the extrinsic).
1804	///
1805	/// If you ever override this function, you need not perform the same validation as in
1806	/// `validate_unsigned`.
1807	fn pre_dispatch_unsigned(
1808		call: &Self::Call,
1809		info: &DispatchInfoOf<Self::Call>,
1810		len: usize,
1811	) -> Result<(), TransactionValidityError> {
1812		Self::validate_unsigned(call, info, len).map(|_| ()).map_err(Into::into)
1813	}
1814}
1815
1816/// An "executable" piece of information, used by the standard Bizinikiwi Executive in order to
1817/// enact a piece of extrinsic information by marshalling and dispatching to a named function
1818/// call.
1819///
1820/// Also provides information on to whom this information is attributable and an index that allows
1821/// each piece of attributable information to be disambiguated.
1822///
1823/// IMPORTANT: After validation, in both [validate](Applyable::validate) and
1824/// [apply](Applyable::apply), all transactions should have *some* authorized origin, except for
1825/// inherents. This is necessary in order to protect the chain against spam. If no extension in the
1826/// transaction extension pipeline authorized the transaction with an origin, either a system signed
1827/// origin or a custom origin, then the transaction must be rejected, as the extensions provided in
1828/// bizinikiwi which protect the chain, such as `CheckNonce`, `ChargeTransactionPayment` etc., rely
1829/// on the assumption that the system handles system signed transactions, and the pallets handle the
1830/// custom origin that they authorized.
1831pub trait Applyable: Sized + Send + Sync {
1832	/// Type by which we can dispatch. Restricts the `UnsignedValidator` type.
1833	type Call: Dispatchable;
1834
1835	/// Checks to see if this is a valid *transaction*. It returns information on it if so.
1836	///
1837	/// IMPORTANT: Ensure that *some* origin has been authorized after validating the transaction.
1838	/// If no origin was authorized, the transaction must be rejected.
1839	fn validate<V: ValidateUnsigned<Call = Self::Call>>(
1840		&self,
1841		source: TransactionSource,
1842		info: &DispatchInfoOf<Self::Call>,
1843		len: usize,
1844	) -> TransactionValidity;
1845
1846	/// Executes all necessary logic needed prior to dispatch and deconstructs into function call,
1847	/// index and sender.
1848	///
1849	/// IMPORTANT: Ensure that *some* origin has been authorized after validating the
1850	/// transaction. If no origin was authorized, the transaction must be rejected.
1851	fn apply<V: ValidateUnsigned<Call = Self::Call>>(
1852		self,
1853		info: &DispatchInfoOf<Self::Call>,
1854		len: usize,
1855	) -> crate::ApplyExtrinsicResultWithInfo<PostDispatchInfoOf<Self::Call>>;
1856}
1857
1858/// A marker trait for something that knows the type of the runtime block.
1859pub trait GetRuntimeBlockType {
1860	/// The `RuntimeBlock` type.
1861	type RuntimeBlock: self::Block;
1862}
1863
1864/// A marker trait for something that knows the type of the node block.
1865pub trait GetNodeBlockType {
1866	/// The `NodeBlock` type.
1867	type NodeBlock: self::Block;
1868}
1869
1870/// Provide validation for unsigned extrinsics.
1871///
1872/// This trait provides two functions [`pre_dispatch`](Self::pre_dispatch) and
1873/// [`validate_unsigned`](Self::validate_unsigned). The [`pre_dispatch`](Self::pre_dispatch)
1874/// function is called right before dispatching the call wrapped by an unsigned extrinsic. The
1875/// [`validate_unsigned`](Self::validate_unsigned) function is mainly being used in the context of
1876/// the transaction pool to check the validity of the call wrapped by an unsigned extrinsic.
1877pub trait ValidateUnsigned {
1878	/// The call to validate
1879	type Call;
1880
1881	/// Validate the call right before dispatch.
1882	///
1883	/// This method should be used to prevent transactions already in the pool
1884	/// (i.e. passing [`validate_unsigned`](Self::validate_unsigned)) from being included in blocks
1885	/// in case they became invalid since being added to the pool.
1886	///
1887	/// By default it's a good idea to call [`validate_unsigned`](Self::validate_unsigned) from
1888	/// within this function again to make sure we never include an invalid transaction. Otherwise
1889	/// the implementation of the call or this method will need to provide proper validation to
1890	/// ensure that the transaction is valid.
1891	///
1892	/// Changes made to storage *WILL* be persisted if the call returns `Ok`.
1893	fn pre_dispatch(call: &Self::Call) -> Result<(), TransactionValidityError> {
1894		Self::validate_unsigned(TransactionSource::InBlock, call)
1895			.map(|_| ())
1896			.map_err(Into::into)
1897	}
1898
1899	/// Return the validity of the call
1900	///
1901	/// This method has no side-effects. It merely checks whether the call would be rejected
1902	/// by the runtime in an unsigned extrinsic.
1903	///
1904	/// The validity checks should be as lightweight as possible because every node will execute
1905	/// this code before the unsigned extrinsic enters the transaction pool and also periodically
1906	/// afterwards to ensure the validity. To prevent dos-ing a network with unsigned
1907	/// extrinsics, these validity checks should include some checks around uniqueness, for example,
1908	/// checking that the unsigned extrinsic was sent by an authority in the active set.
1909	///
1910	/// Changes made to storage should be discarded by caller.
1911	fn validate_unsigned(source: TransactionSource, call: &Self::Call) -> TransactionValidity;
1912}
1913
1914/// Opaque data type that may be destructured into a series of raw byte slices (which represent
1915/// individual keys).
1916pub trait OpaqueKeys: Clone {
1917	/// Types bound to this opaque keys that provide the key type ids returned.
1918	type KeyTypeIdProviders;
1919
1920	/// Return the key-type IDs supported by this set.
1921	fn key_ids() -> &'static [crate::KeyTypeId];
1922	/// Get the raw bytes of key with key-type ID `i`.
1923	fn get_raw(&self, i: super::KeyTypeId) -> &[u8];
1924	/// Get the decoded key with key-type ID `i`.
1925	fn get<T: Decode>(&self, i: super::KeyTypeId) -> Option<T> {
1926		T::decode(&mut self.get_raw(i)).ok()
1927	}
1928	/// Verify a proof of ownership for the keys.
1929	fn ownership_proof_is_valid(&self, _proof: &[u8]) -> bool {
1930		true
1931	}
1932}
1933
1934/// Input that adds infinite number of zero after wrapped input.
1935///
1936/// This can add an infinite stream of zeros onto any input, not just a slice as with
1937/// `TrailingZerosInput`.
1938pub struct AppendZerosInput<'a, T>(&'a mut T);
1939
1940impl<'a, T> AppendZerosInput<'a, T> {
1941	/// Create a new instance from the given byte array.
1942	pub fn new(input: &'a mut T) -> Self {
1943		Self(input)
1944	}
1945}
1946
1947impl<'a, T: codec::Input> codec::Input for AppendZerosInput<'a, T> {
1948	fn remaining_len(&mut self) -> Result<Option<usize>, codec::Error> {
1949		Ok(None)
1950	}
1951
1952	fn read(&mut self, into: &mut [u8]) -> Result<(), codec::Error> {
1953		let remaining = self.0.remaining_len()?;
1954		let completed = if let Some(n) = remaining {
1955			let readable = into.len().min(n);
1956			// this should never fail if `remaining_len` API is implemented correctly.
1957			self.0.read(&mut into[..readable])?;
1958			readable
1959		} else {
1960			// Fill it byte-by-byte.
1961			let mut i = 0;
1962			while i < into.len() {
1963				if let Ok(b) = self.0.read_byte() {
1964					into[i] = b;
1965					i += 1;
1966				} else {
1967					break;
1968				}
1969			}
1970			i
1971		};
1972		// Fill the rest with zeros.
1973		for i in &mut into[completed..] {
1974			*i = 0;
1975		}
1976		Ok(())
1977	}
1978}
1979
1980/// Input that adds infinite number of zero after wrapped input.
1981pub struct TrailingZeroInput<'a>(&'a [u8]);
1982
1983impl<'a> TrailingZeroInput<'a> {
1984	/// Create a new instance from the given byte array.
1985	pub fn new(data: &'a [u8]) -> Self {
1986		Self(data)
1987	}
1988
1989	/// Create a new instance which only contains zeroes as input.
1990	pub fn zeroes() -> Self {
1991		Self::new(&[][..])
1992	}
1993}
1994
1995impl<'a> codec::Input for TrailingZeroInput<'a> {
1996	fn remaining_len(&mut self) -> Result<Option<usize>, codec::Error> {
1997		Ok(None)
1998	}
1999
2000	fn read(&mut self, into: &mut [u8]) -> Result<(), codec::Error> {
2001		let len_from_inner = into.len().min(self.0.len());
2002		into[..len_from_inner].copy_from_slice(&self.0[..len_from_inner]);
2003		for i in &mut into[len_from_inner..] {
2004			*i = 0;
2005		}
2006		self.0 = &self.0[len_from_inner..];
2007
2008		Ok(())
2009	}
2010}
2011
2012/// This type can be converted into and possibly from an AccountId (which itself is generic).
2013pub trait AccountIdConversion<AccountId>: Sized {
2014	/// Convert into an account ID. This is infallible, and may truncate bytes to provide a result.
2015	/// This may lead to duplicate accounts if the size of `AccountId` is less than the seed.
2016	fn into_account_truncating(&self) -> AccountId {
2017		self.into_sub_account_truncating(&())
2018	}
2019
2020	/// Convert into an account ID, checking that all bytes of the seed are being used in the final
2021	/// `AccountId` generated. If any bytes are dropped, this returns `None`.
2022	fn try_into_account(&self) -> Option<AccountId> {
2023		self.try_into_sub_account(&())
2024	}
2025
2026	/// Try to convert an account ID into this type. Might not succeed.
2027	fn try_from_account(a: &AccountId) -> Option<Self> {
2028		Self::try_from_sub_account::<()>(a).map(|x| x.0)
2029	}
2030
2031	/// Convert this value amalgamated with a secondary "sub" value into an account ID,
2032	/// truncating any unused bytes. This is infallible.
2033	///
2034	/// NOTE: The account IDs from this and from `into_account` are *not* guaranteed to be distinct
2035	/// for any given value of `self`, nor are different invocations to this with different types
2036	/// `T`. For example, the following will all encode to the same account ID value:
2037	/// - `self.into_sub_account(0u32)`
2038	/// - `self.into_sub_account(vec![0u8; 0])`
2039	/// - `self.into_account()`
2040	///
2041	/// Also, if the seed provided to this function is greater than the number of bytes which fit
2042	/// into this `AccountId` type, then it will lead to truncation of the seed, and potentially
2043	/// non-unique accounts.
2044	fn into_sub_account_truncating<S: Encode>(&self, sub: S) -> AccountId;
2045
2046	/// Same as `into_sub_account_truncating`, but ensuring that all bytes of the account's seed are
2047	/// used when generating an account. This can help guarantee that different accounts are unique,
2048	/// besides types which encode the same as noted above.
2049	fn try_into_sub_account<S: Encode>(&self, sub: S) -> Option<AccountId>;
2050
2051	/// Try to convert an account ID into this type. Might not succeed.
2052	fn try_from_sub_account<S: Decode>(x: &AccountId) -> Option<(Self, S)>;
2053}
2054
2055/// Format is TYPE_ID ++ encode(sub-seed) ++ 00.... where 00... is indefinite trailing zeroes to
2056/// fill AccountId.
2057impl<T: Encode + Decode, Id: Encode + Decode + TypeId> AccountIdConversion<T> for Id {
2058	// Take the `sub` seed, and put as much of it as possible into the generated account, but
2059	// allowing truncation of the seed if it would not fit into the account id in full. This can
2060	// lead to two different `sub` seeds with the same account generated.
2061	fn into_sub_account_truncating<S: Encode>(&self, sub: S) -> T {
2062		(Id::TYPE_ID, self, sub)
2063			.using_encoded(|b| T::decode(&mut TrailingZeroInput(b)))
2064			.expect("All byte sequences are valid `AccountIds`; qed")
2065	}
2066
2067	// Same as `into_sub_account_truncating`, but returns `None` if any bytes would be truncated.
2068	fn try_into_sub_account<S: Encode>(&self, sub: S) -> Option<T> {
2069		let encoded_seed = (Id::TYPE_ID, self, sub).encode();
2070		let account = T::decode(&mut TrailingZeroInput(&encoded_seed))
2071			.expect("All byte sequences are valid `AccountIds`; qed");
2072		// If the `account` generated has less bytes than the `encoded_seed`, then we know that
2073		// bytes were truncated, and we return `None`.
2074		if encoded_seed.len() <= account.encoded_size() {
2075			Some(account)
2076		} else {
2077			None
2078		}
2079	}
2080
2081	fn try_from_sub_account<S: Decode>(x: &T) -> Option<(Self, S)> {
2082		x.using_encoded(|d| {
2083			if d[0..4] != Id::TYPE_ID {
2084				return None;
2085			}
2086			let mut cursor = &d[4..];
2087			let result = Decode::decode(&mut cursor).ok()?;
2088			if cursor.iter().all(|x| *x == 0) {
2089				Some(result)
2090			} else {
2091				None
2092			}
2093		})
2094	}
2095}
2096
2097/// Calls a given macro a number of times with a set of fixed params and an incrementing numeral.
2098/// e.g.
2099/// ```nocompile
2100/// count!(println ("{}",) foo, bar, baz);
2101/// // Will result in three `println!`s: "0", "1" and "2".
2102/// ```
2103#[macro_export]
2104macro_rules! count {
2105	($f:ident ($($x:tt)*) ) => ();
2106	($f:ident ($($x:tt)*) $x1:tt) => { $f!($($x)* 0); };
2107	($f:ident ($($x:tt)*) $x1:tt, $x2:tt) => { $f!($($x)* 0); $f!($($x)* 1); };
2108	($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt) => { $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); };
2109	($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt, $x4:tt) => {
2110		$f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); $f!($($x)* 3);
2111	};
2112	($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt, $x4:tt, $x5:tt) => {
2113		$f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); $f!($($x)* 3); $f!($($x)* 4);
2114	};
2115}
2116
2117#[doc(hidden)]
2118#[macro_export]
2119macro_rules! impl_opaque_keys_inner {
2120	(
2121		$( #[ $attr:meta ] )*
2122		pub struct $name:ident {
2123			$(
2124				$( #[ $inner_attr:meta ] )*
2125				pub $field:ident: $type:ty,
2126			)*
2127		}
2128	) => {
2129		$( #[ $attr ] )*
2130		#[derive(
2131			Clone, PartialEq, Eq,
2132			$crate::codec::Encode,
2133			$crate::codec::Decode,
2134			$crate::codec::DecodeWithMemTracking,
2135			$crate::scale_info::TypeInfo,
2136			$crate::RuntimeDebug,
2137		)]
2138		pub struct $name {
2139			$(
2140				$( #[ $inner_attr ] )*
2141				pub $field: <$type as $crate::BoundToRuntimeAppPublic>::Public,
2142			)*
2143		}
2144
2145		impl $name {
2146			/// Generate a set of keys with optionally using the given seed.
2147			///
2148			/// The generated key pairs are stored in the keystore.
2149			///
2150			/// Returns the concatenated SCALE encoded public keys.
2151			pub fn generate(seed: Option<$crate::Vec<u8>>) -> $crate::Vec<u8> {
2152				let keys = Self{
2153					$(
2154						$field: <
2155							<
2156								$type as $crate::BoundToRuntimeAppPublic
2157							>::Public as $crate::RuntimeAppPublic
2158						>::generate_pair(seed.clone()),
2159					)*
2160				};
2161				$crate::codec::Encode::encode(&keys)
2162			}
2163
2164			/// Converts `Self` into a `Vec` of `(raw public key, KeyTypeId)`.
2165			pub fn into_raw_public_keys(
2166				self,
2167			) -> $crate::Vec<($crate::Vec<u8>, $crate::KeyTypeId)> {
2168				let mut keys = Vec::new();
2169				$(
2170					keys.push((
2171						$crate::RuntimeAppPublic::to_raw_vec(&self.$field),
2172						<
2173							<
2174								$type as $crate::BoundToRuntimeAppPublic
2175							>::Public as $crate::RuntimeAppPublic
2176						>::ID,
2177					));
2178				)*
2179
2180				keys
2181			}
2182
2183			/// Decode `Self` from the given `encoded` slice and convert `Self` into the raw public
2184			/// keys (see [`Self::into_raw_public_keys`]).
2185			///
2186			/// Returns `None` when the decoding failed, otherwise `Some(_)`.
2187			pub fn decode_into_raw_public_keys(
2188				encoded: &[u8],
2189			) -> Option<$crate::Vec<($crate::Vec<u8>, $crate::KeyTypeId)>> {
2190				<Self as $crate::codec::Decode>::decode(&mut &encoded[..])
2191					.ok()
2192					.map(|s| s.into_raw_public_keys())
2193			}
2194		}
2195
2196		impl $crate::traits::OpaqueKeys for $name {
2197			type KeyTypeIdProviders = ( $( $type, )* );
2198
2199			fn key_ids() -> &'static [$crate::KeyTypeId] {
2200				&[
2201					$(
2202						<
2203							<
2204								$type as $crate::BoundToRuntimeAppPublic
2205							>::Public as $crate::RuntimeAppPublic
2206						>::ID
2207					),*
2208				]
2209			}
2210
2211			fn get_raw(&self, i: $crate::KeyTypeId) -> &[u8] {
2212				match i {
2213					$(
2214						i if i == <
2215							<
2216								$type as $crate::BoundToRuntimeAppPublic
2217							>::Public as $crate::RuntimeAppPublic
2218						>::ID =>
2219							self.$field.as_ref(),
2220					)*
2221					_ => &[],
2222				}
2223			}
2224		}
2225	};
2226}
2227
2228/// Implement `OpaqueKeys` for a described struct.
2229///
2230/// Every field type must implement [`BoundToRuntimeAppPublic`](crate::BoundToRuntimeAppPublic).
2231/// `KeyTypeIdProviders` is set to the types given as fields.
2232///
2233/// ```rust
2234/// use pezsp_runtime::{
2235/// 	impl_opaque_keys, KeyTypeId, BoundToRuntimeAppPublic, app_crypto::{sr25519, ed25519}
2236/// };
2237///
2238/// pub struct KeyModule;
2239/// impl BoundToRuntimeAppPublic for KeyModule { type Public = ed25519::AppPublic; }
2240///
2241/// pub struct KeyModule2;
2242/// impl BoundToRuntimeAppPublic for KeyModule2 { type Public = sr25519::AppPublic; }
2243///
2244/// impl_opaque_keys! {
2245/// 	pub struct Keys {
2246/// 		pub key_module: KeyModule,
2247/// 		pub key_module2: KeyModule2,
2248/// 	}
2249/// }
2250/// ```
2251#[macro_export]
2252#[cfg(any(feature = "serde", feature = "std"))]
2253macro_rules! impl_opaque_keys {
2254	{
2255		$( #[ $attr:meta ] )*
2256		pub struct $name:ident {
2257			$(
2258				$( #[ $inner_attr:meta ] )*
2259				pub $field:ident: $type:ty,
2260			)*
2261		}
2262	} => {
2263		$crate::paste::paste! {
2264			use $crate::serde as [< __opaque_keys_serde_import__ $name >];
2265
2266			$crate::impl_opaque_keys_inner! {
2267				$( #[ $attr ] )*
2268				#[derive($crate::serde::Serialize, $crate::serde::Deserialize)]
2269				#[serde(crate = "__opaque_keys_serde_import__" $name)]
2270				pub struct $name {
2271					$(
2272						$( #[ $inner_attr ] )*
2273						pub $field: $type,
2274					)*
2275				}
2276			}
2277		}
2278	}
2279}
2280
2281#[macro_export]
2282#[cfg(all(not(feature = "std"), not(feature = "serde")))]
2283#[doc(hidden)]
2284macro_rules! impl_opaque_keys {
2285	{
2286		$( #[ $attr:meta ] )*
2287		pub struct $name:ident {
2288			$(
2289				$( #[ $inner_attr:meta ] )*
2290				pub $field:ident: $type:ty,
2291			)*
2292		}
2293	} => {
2294		$crate::impl_opaque_keys_inner! {
2295			$( #[ $attr ] )*
2296			pub struct $name {
2297				$(
2298					$( #[ $inner_attr ] )*
2299					pub $field: $type,
2300				)*
2301			}
2302		}
2303	}
2304}
2305
2306/// Trait for things which can be printed from the runtime.
2307pub trait Printable {
2308	/// Print the object.
2309	fn print(&self);
2310}
2311
2312impl<T: Printable> Printable for &T {
2313	fn print(&self) {
2314		(*self).print()
2315	}
2316}
2317
2318impl Printable for u8 {
2319	fn print(&self) {
2320		(*self as u64).print()
2321	}
2322}
2323
2324impl Printable for u32 {
2325	fn print(&self) {
2326		(*self as u64).print()
2327	}
2328}
2329
2330impl Printable for usize {
2331	fn print(&self) {
2332		(*self as u64).print()
2333	}
2334}
2335
2336impl Printable for u64 {
2337	fn print(&self) {
2338		pezsp_io::misc::print_num(*self);
2339	}
2340}
2341
2342impl Printable for &[u8] {
2343	fn print(&self) {
2344		pezsp_io::misc::print_hex(self);
2345	}
2346}
2347
2348impl<const N: usize> Printable for [u8; N] {
2349	fn print(&self) {
2350		pezsp_io::misc::print_hex(&self[..]);
2351	}
2352}
2353
2354impl Printable for &str {
2355	fn print(&self) {
2356		pezsp_io::misc::print_utf8(self.as_bytes());
2357	}
2358}
2359
2360impl Printable for bool {
2361	fn print(&self) {
2362		if *self {
2363			"true".print()
2364		} else {
2365			"false".print()
2366		}
2367	}
2368}
2369
2370impl Printable for pezsp_weights::Weight {
2371	fn print(&self) {
2372		self.ref_time().print()
2373	}
2374}
2375
2376impl Printable for () {
2377	fn print(&self) {
2378		"()".print()
2379	}
2380}
2381
2382#[impl_for_tuples(1, 12)]
2383impl Printable for Tuple {
2384	fn print(&self) {
2385		for_tuples!( #( Tuple.print(); )* )
2386	}
2387}
2388
2389/// Something that can convert a [`BlockId`](crate::generic::BlockId) to a number or a hash.
2390#[cfg(feature = "std")]
2391pub trait BlockIdTo<Block: self::Block> {
2392	/// The error type that will be returned by the functions.
2393	type Error: std::error::Error;
2394
2395	/// Convert the given `block_id` to the corresponding block hash.
2396	fn to_hash(
2397		&self,
2398		block_id: &crate::generic::BlockId<Block>,
2399	) -> Result<Option<Block::Hash>, Self::Error>;
2400
2401	/// Convert the given `block_id` to the corresponding block number.
2402	fn to_number(
2403		&self,
2404		block_id: &crate::generic::BlockId<Block>,
2405	) -> Result<Option<NumberFor<Block>>, Self::Error>;
2406}
2407
2408/// Get current block number
2409pub trait BlockNumberProvider {
2410	/// Type of `BlockNumber` to provide.
2411	type BlockNumber: Codec
2412		+ DecodeWithMemTracking
2413		+ Clone
2414		+ Ord
2415		+ Eq
2416		+ AtLeast32BitUnsigned
2417		+ TypeInfo
2418		+ Debug
2419		+ MaxEncodedLen
2420		+ Copy
2421		+ EncodeLike
2422		+ Default;
2423
2424	/// Returns the current block number.
2425	///
2426	/// Provides an abstraction over an arbitrary way of providing the
2427	/// current block number.
2428	///
2429	/// In case of using crate `pezsp_runtime` with the crate `pezframe-system`,
2430	/// it is already implemented for
2431	/// `pezframe_system::Pezpallet<T: Config>` as:
2432	///
2433	/// ```ignore
2434	/// fn current_block_number() -> Self {
2435	///     pezframe_system::Pezpallet<Config>::block_number()
2436	/// }
2437	/// ```
2438	/// .
2439	fn current_block_number() -> Self::BlockNumber;
2440
2441	/// Utility function only to be used in benchmarking scenarios or tests, to be implemented
2442	/// optionally, else a noop.
2443	///
2444	/// It allows for setting the block number that will later be fetched
2445	/// This is useful in case the block number provider is different than System
2446	#[cfg(any(feature = "std", feature = "runtime-benchmarks"))]
2447	fn set_block_number(_block: Self::BlockNumber) {}
2448}
2449
2450impl BlockNumberProvider for () {
2451	type BlockNumber = u32;
2452	fn current_block_number() -> Self::BlockNumber {
2453		0
2454	}
2455}
2456
2457#[cfg(test)]
2458mod tests {
2459	use super::*;
2460	use crate::codec::{Decode, Encode, Input};
2461	use pezsp_core::{
2462		crypto::{Pair, UncheckedFrom},
2463		ecdsa, ed25519, sr25519,
2464	};
2465
2466	macro_rules! signature_verify_test {
2467		($algorithm:ident) => {
2468			let msg = &b"test-message"[..];
2469			let wrong_msg = &b"test-msg"[..];
2470			let (pair, _) = $algorithm::Pair::generate();
2471
2472			let signature = pair.sign(&msg);
2473			assert!($algorithm::Pair::verify(&signature, msg, &pair.public()));
2474
2475			assert!(signature.verify(msg, &pair.public()));
2476			assert!(!signature.verify(wrong_msg, &pair.public()));
2477		};
2478	}
2479
2480	mod t {
2481		use pezsp_application_crypto::{app_crypto, sr25519};
2482		use pezsp_core::crypto::KeyTypeId;
2483		app_crypto!(sr25519, KeyTypeId(*b"test"));
2484	}
2485
2486	#[test]
2487	fn app_verify_works() {
2488		use super::AppVerify;
2489		use t::*;
2490
2491		let s = Signature::try_from(vec![0; 64]).unwrap();
2492		let _ = s.verify(&[0u8; 100][..], &Public::unchecked_from([0; 32]));
2493	}
2494
2495	#[derive(Encode, Decode, Default, PartialEq, Debug)]
2496	struct U128Value(u128);
2497	impl super::TypeId for U128Value {
2498		const TYPE_ID: [u8; 4] = [0x0d, 0xf0, 0x0d, 0xf0];
2499	}
2500	// f00df00d
2501
2502	#[derive(Encode, Decode, Default, PartialEq, Debug)]
2503	struct U32Value(u32);
2504	impl super::TypeId for U32Value {
2505		const TYPE_ID: [u8; 4] = [0x0d, 0xf0, 0xfe, 0xca];
2506	}
2507	// cafef00d
2508
2509	#[derive(Encode, Decode, Default, PartialEq, Debug)]
2510	struct U16Value(u16);
2511	impl super::TypeId for U16Value {
2512		const TYPE_ID: [u8; 4] = [0xfe, 0xca, 0x0d, 0xf0];
2513	}
2514	// f00dcafe
2515
2516	type AccountId = u64;
2517
2518	#[test]
2519	fn into_account_truncating_should_work() {
2520		let r: AccountId = U32Value::into_account_truncating(&U32Value(0xdeadbeef));
2521		assert_eq!(r, 0x_deadbeef_cafef00d);
2522	}
2523
2524	#[test]
2525	fn try_into_account_should_work() {
2526		let r: AccountId = U32Value::try_into_account(&U32Value(0xdeadbeef)).unwrap();
2527		assert_eq!(r, 0x_deadbeef_cafef00d);
2528
2529		// u128 is bigger than u64 would fit
2530		let maybe: Option<AccountId> = U128Value::try_into_account(&U128Value(u128::MAX));
2531		assert!(maybe.is_none());
2532	}
2533
2534	#[test]
2535	fn try_from_account_should_work() {
2536		let r = U32Value::try_from_account(&0x_deadbeef_cafef00d_u64);
2537		assert_eq!(r.unwrap(), U32Value(0xdeadbeef));
2538	}
2539
2540	#[test]
2541	fn into_account_truncating_with_fill_should_work() {
2542		let r: AccountId = U16Value::into_account_truncating(&U16Value(0xc0da));
2543		assert_eq!(r, 0x_0000_c0da_f00dcafe);
2544	}
2545
2546	#[test]
2547	fn try_into_sub_account_should_work() {
2548		let r: AccountId = U16Value::try_into_account(&U16Value(0xc0da)).unwrap();
2549		assert_eq!(r, 0x_0000_c0da_f00dcafe);
2550
2551		let maybe: Option<AccountId> = U16Value::try_into_sub_account(
2552			&U16Value(0xc0da),
2553			"a really large amount of additional encoded information which will certainly overflow the account id type ;)"
2554		);
2555
2556		assert!(maybe.is_none())
2557	}
2558
2559	#[test]
2560	fn try_from_account_with_fill_should_work() {
2561		let r = U16Value::try_from_account(&0x0000_c0da_f00dcafe_u64);
2562		assert_eq!(r.unwrap(), U16Value(0xc0da));
2563	}
2564
2565	#[test]
2566	fn bad_try_from_account_should_fail() {
2567		let r = U16Value::try_from_account(&0x0000_c0de_baadcafe_u64);
2568		assert!(r.is_none());
2569		let r = U16Value::try_from_account(&0x0100_c0da_f00dcafe_u64);
2570		assert!(r.is_none());
2571	}
2572
2573	#[test]
2574	fn trailing_zero_should_work() {
2575		let mut t = super::TrailingZeroInput(&[1, 2, 3]);
2576		assert_eq!(t.remaining_len(), Ok(None));
2577		let mut buffer = [0u8; 2];
2578		assert_eq!(t.read(&mut buffer), Ok(()));
2579		assert_eq!(t.remaining_len(), Ok(None));
2580		assert_eq!(buffer, [1, 2]);
2581		assert_eq!(t.read(&mut buffer), Ok(()));
2582		assert_eq!(t.remaining_len(), Ok(None));
2583		assert_eq!(buffer, [3, 0]);
2584		assert_eq!(t.read(&mut buffer), Ok(()));
2585		assert_eq!(t.remaining_len(), Ok(None));
2586		assert_eq!(buffer, [0, 0]);
2587	}
2588
2589	#[test]
2590	fn ed25519_verify_works() {
2591		signature_verify_test!(ed25519);
2592	}
2593
2594	#[test]
2595	fn sr25519_verify_works() {
2596		signature_verify_test!(sr25519);
2597	}
2598
2599	#[test]
2600	fn ecdsa_verify_works() {
2601		signature_verify_test!(ecdsa);
2602	}
2603}