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