sp_runtime/traits/
mod.rs

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