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