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