referrerpolicy=no-referrer-when-downgrade

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