1use crate::{
21 generic::Digest,
22 scale_info::{MetaType, StaticTypeInfo, TypeInfo},
23 transaction_validity::{
24 TransactionSource, TransactionValidity, TransactionValidityError, UnknownTransaction,
25 ValidTransaction,
26 },
27 DispatchResult,
28};
29use alloc::vec::Vec;
30use codec::{Codec, Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen};
31#[doc(hidden)]
32pub use core::{fmt::Debug, marker::PhantomData};
33use impl_trait_for_tuples::impl_for_tuples;
34#[cfg(feature = "serde")]
35use serde::{de::DeserializeOwned, Deserialize, Serialize};
36use sp_application_crypto::AppCrypto;
37pub use sp_arithmetic::traits::{
38 checked_pow, ensure_pow, AtLeast32Bit, AtLeast32BitUnsigned, Bounded, CheckedAdd, CheckedDiv,
39 CheckedMul, CheckedShl, CheckedShr, CheckedSub, Ensure, EnsureAdd, EnsureAddAssign, EnsureDiv,
40 EnsureDivAssign, EnsureFixedPointNumber, EnsureFrom, EnsureInto, EnsureMul, EnsureMulAssign,
41 EnsureOp, EnsureOpAssign, EnsureSub, EnsureSubAssign, IntegerSquareRoot, One,
42 SaturatedConversion, Saturating, UniqueSaturatedFrom, UniqueSaturatedInto, Zero,
43};
44use sp_core::{self, storage::StateVersion, Hasher, RuntimeDebug, TypeId, U256};
45#[doc(hidden)]
46pub use sp_core::{
47 parameter_types, ConstBool, ConstI128, ConstI16, ConstI32, ConstI64, ConstI8, ConstU128,
48 ConstU16, ConstU32, ConstU64, ConstU8, Get, GetDefault, TryCollect, TypedGet,
49};
50#[cfg(feature = "std")]
51use std::fmt::Display;
52#[cfg(feature = "std")]
53use std::str::FromStr;
54
55pub trait Lazy<T: ?Sized> {
57 fn get(&mut self) -> &T;
61}
62
63impl<'a> Lazy<[u8]> for &'a [u8] {
64 fn get(&mut self) -> &[u8] {
65 self
66 }
67}
68
69pub trait IdentifyAccount {
72 type AccountId;
74 fn into_account(self) -> Self::AccountId;
76}
77
78impl IdentifyAccount for sp_core::ed25519::Public {
79 type AccountId = Self;
80 fn into_account(self) -> Self {
81 self
82 }
83}
84
85impl IdentifyAccount for sp_core::sr25519::Public {
86 type AccountId = Self;
87 fn into_account(self) -> Self {
88 self
89 }
90}
91
92impl IdentifyAccount for sp_core::ecdsa::Public {
93 type AccountId = Self;
94 fn into_account(self) -> Self {
95 self
96 }
97}
98
99pub trait Verify {
101 type Signer: IdentifyAccount;
103 fn verify<L: Lazy<[u8]>>(
107 &self,
108 msg: L,
109 signer: &<Self::Signer as IdentifyAccount>::AccountId,
110 ) -> bool;
111}
112
113impl Verify for sp_core::ed25519::Signature {
114 type Signer = sp_core::ed25519::Public;
115
116 fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &sp_core::ed25519::Public) -> bool {
117 sp_io::crypto::ed25519_verify(self, msg.get(), signer)
118 }
119}
120
121impl Verify for sp_core::sr25519::Signature {
122 type Signer = sp_core::sr25519::Public;
123
124 fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &sp_core::sr25519::Public) -> bool {
125 sp_io::crypto::sr25519_verify(self, msg.get(), signer)
126 }
127}
128
129impl Verify for sp_core::ecdsa::Signature {
130 type Signer = sp_core::ecdsa::Public;
131 fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &sp_core::ecdsa::Public) -> bool {
132 match sp_io::crypto::secp256k1_ecdsa_recover_compressed(
133 self.as_ref(),
134 &sp_io::hashing::blake2_256(msg.get()),
135 ) {
136 Ok(pubkey) => signer.0 == pubkey,
137 _ => false,
138 }
139 }
140}
141
142pub trait AppVerify {
144 type AccountId;
146 fn verify<L: Lazy<[u8]>>(&self, msg: L, signer: &Self::AccountId) -> bool;
148}
149
150impl<
151 S: Verify<Signer = <<T as AppCrypto>::Public as sp_application_crypto::AppPublic>::Generic>
152 + From<T>,
153 T: sp_application_crypto::Wraps<Inner = S>
154 + sp_application_crypto::AppCrypto
155 + sp_application_crypto::AppSignature
156 + AsRef<S>
157 + AsMut<S>
158 + From<S>,
159 > AppVerify for T
160where
161 <S as Verify>::Signer: IdentifyAccount<AccountId = <S as Verify>::Signer>,
162 <<T as AppCrypto>::Public as sp_application_crypto::AppPublic>::Generic: IdentifyAccount<
163 AccountId = <<T as AppCrypto>::Public as sp_application_crypto::AppPublic>::Generic,
164 >,
165{
166 type AccountId = <T as AppCrypto>::Public;
167 fn verify<L: Lazy<[u8]>>(&self, msg: L, signer: &<T as AppCrypto>::Public) -> bool {
168 use sp_application_crypto::IsWrappedBy;
169 let inner: &S = self.as_ref();
170 let inner_pubkey =
171 <<T as AppCrypto>::Public as sp_application_crypto::AppPublic>::Generic::from_ref(
172 signer,
173 );
174 Verify::verify(inner, msg, inner_pubkey)
175 }
176}
177
178#[derive(Encode, Decode, RuntimeDebug)]
180pub struct BadOrigin;
181
182impl From<BadOrigin> for &'static str {
183 fn from(_: BadOrigin) -> &'static str {
184 "Bad origin"
185 }
186}
187
188#[derive(Encode, Decode, RuntimeDebug)]
190pub struct LookupError;
191
192impl From<LookupError> for &'static str {
193 fn from(_: LookupError) -> &'static str {
194 "Can not lookup"
195 }
196}
197
198impl From<LookupError> for TransactionValidityError {
199 fn from(_: LookupError) -> Self {
200 UnknownTransaction::CannotLookup.into()
201 }
202}
203
204pub trait Lookup {
206 type Source;
208 type Target;
210 fn lookup(&self, s: Self::Source) -> Result<Self::Target, LookupError>;
212}
213
214pub trait StaticLookup {
218 type Source: Codec + Clone + PartialEq + Debug + TypeInfo;
220 type Target;
222 fn lookup(s: Self::Source) -> Result<Self::Target, LookupError>;
224 fn unlookup(t: Self::Target) -> Self::Source;
226}
227
228#[derive(Default, Clone, Copy, PartialEq, Eq)]
230pub struct IdentityLookup<T>(PhantomData<T>);
231impl<T: Codec + Clone + PartialEq + Debug + TypeInfo> StaticLookup for IdentityLookup<T> {
232 type Source = T;
233 type Target = T;
234 fn lookup(x: T) -> Result<T, LookupError> {
235 Ok(x)
236 }
237 fn unlookup(x: T) -> T {
238 x
239 }
240}
241
242impl<T> Lookup for IdentityLookup<T> {
243 type Source = T;
244 type Target = T;
245 fn lookup(&self, x: T) -> Result<T, LookupError> {
246 Ok(x)
247 }
248}
249
250pub struct AccountIdLookup<AccountId, AccountIndex>(PhantomData<(AccountId, AccountIndex)>);
252impl<AccountId, AccountIndex> StaticLookup for AccountIdLookup<AccountId, AccountIndex>
253where
254 AccountId: Codec + Clone + PartialEq + Debug,
255 AccountIndex: Codec + Clone + PartialEq + Debug,
256 crate::MultiAddress<AccountId, AccountIndex>: Codec + StaticTypeInfo,
257{
258 type Source = crate::MultiAddress<AccountId, AccountIndex>;
259 type Target = AccountId;
260 fn lookup(x: Self::Source) -> Result<Self::Target, LookupError> {
261 match x {
262 crate::MultiAddress::Id(i) => Ok(i),
263 _ => Err(LookupError),
264 }
265 }
266 fn unlookup(x: Self::Target) -> Self::Source {
267 crate::MultiAddress::Id(x)
268 }
269}
270
271impl<A, B> StaticLookup for (A, B)
273where
274 A: StaticLookup,
275 B: StaticLookup<Source = A::Source, Target = A::Target>,
276{
277 type Source = A::Source;
278 type Target = A::Target;
279
280 fn lookup(x: Self::Source) -> Result<Self::Target, LookupError> {
281 A::lookup(x.clone()).or_else(|_| B::lookup(x))
282 }
283 fn unlookup(x: Self::Target) -> Self::Source {
284 A::unlookup(x)
285 }
286}
287
288pub trait Morph<A> {
291 type Outcome;
293
294 fn morph(a: A) -> Self::Outcome;
296}
297
298impl<T> Morph<T> for Identity {
300 type Outcome = T;
301 fn morph(a: T) -> T {
302 a
303 }
304}
305
306pub trait TryMorph<A> {
309 type Outcome;
311
312 fn try_morph(a: A) -> Result<Self::Outcome, ()>;
314}
315
316impl<T> TryMorph<T> for Identity {
318 type Outcome = T;
319 fn try_morph(a: T) -> Result<T, ()> {
320 Ok(a)
321 }
322}
323
324pub struct MorphInto<T>(core::marker::PhantomData<T>);
326impl<T, A: Into<T>> Morph<A> for MorphInto<T> {
327 type Outcome = T;
328 fn morph(a: A) -> T {
329 a.into()
330 }
331}
332
333pub struct TryMorphInto<T>(core::marker::PhantomData<T>);
335impl<T, A: TryInto<T>> TryMorph<A> for TryMorphInto<T> {
336 type Outcome = T;
337 fn try_morph(a: A) -> Result<T, ()> {
338 a.try_into().map_err(|_| ())
339 }
340}
341
342pub struct TakeFirst;
344impl<T1> Morph<(T1,)> for TakeFirst {
345 type Outcome = T1;
346 fn morph(a: (T1,)) -> T1 {
347 a.0
348 }
349}
350impl<T1, T2> Morph<(T1, T2)> for TakeFirst {
351 type Outcome = T1;
352 fn morph(a: (T1, T2)) -> T1 {
353 a.0
354 }
355}
356impl<T1, T2, T3> Morph<(T1, T2, T3)> for TakeFirst {
357 type Outcome = T1;
358 fn morph(a: (T1, T2, T3)) -> T1 {
359 a.0
360 }
361}
362impl<T1, T2, T3, T4> Morph<(T1, T2, T3, T4)> for TakeFirst {
363 type Outcome = T1;
364 fn morph(a: (T1, T2, T3, T4)) -> T1 {
365 a.0
366 }
367}
368
369#[macro_export]
405macro_rules! morph_types {
406 (
407 @DECL $( #[doc = $doc:expr] )* $vq:vis $name:ident ()
408 ) => {
409 $( #[doc = $doc] )* $vq struct $name;
410 };
411 (
412 @DECL $( #[doc = $doc:expr] )* $vq:vis $name:ident ( $( $bound_id:ident ),+ )
413 ) => {
414 $( #[doc = $doc] )*
415 $vq struct $name < $($bound_id,)* > ( $crate::traits::PhantomData< ( $($bound_id,)* ) > ) ;
416 };
417 (
418 @IMPL $name:ty : ( $( $bounds:tt )* ) ( $( $where:tt )* )
419 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
420 ) => {
421 impl<$($bounds)*> $crate::traits::Morph<$var_type> for $name $( $where )? {
422 type Outcome = $outcome;
423 fn morph($var: $var_type) -> Self::Outcome { $( $ex )* }
424 }
425 };
426 (
427 @IMPL_TRY $name:ty : ( $( $bounds:tt )* ) ( $( $where:tt )* )
428 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
429 ) => {
430 impl<$($bounds)*> $crate::traits::TryMorph<$var_type> for $name $( $where )? {
431 type Outcome = $outcome;
432 fn try_morph($var: $var_type) -> Result<Self::Outcome, ()> { $( $ex )* }
433 }
434 };
435 (
436 @IMPL $name:ty : () ( $( $where:tt )* )
437 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
438 ) => {
439 impl $crate::traits::Morph<$var_type> for $name $( $where )? {
440 type Outcome = $outcome;
441 fn morph($var: $var_type) -> Self::Outcome { $( $ex )* }
442 }
443 };
444 (
445 @IMPL_TRY $name:ty : () ( $( $where:tt )* )
446 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
447 ) => {
448 impl $crate::traits::TryMorph<$var_type> for $name $( $where )? {
449 type Outcome = $outcome;
450 fn try_morph($var: $var_type) -> Result<Self::Outcome, ()> { $( $ex )* }
451 }
452 };
453 (
454 @IMPL_BOTH $name:ty : ( $( $bounds:tt )* ) ( $( $where:tt )* )
455 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
456 ) => {
457 morph_types! {
458 @IMPL $name : ($($bounds)*) ($($where)*)
459 = |$var: $var_type| -> $outcome { $( $ex )* }
460 }
461 morph_types! {
462 @IMPL_TRY $name : ($($bounds)*) ($($where)*)
463 = |$var: $var_type| -> $outcome { Ok({$( $ex )*}) }
464 }
465 };
466
467 (
468 $( #[doc = $doc:expr] )* $vq:vis type $name:ident
469 $( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
470 $(: $type:tt)?
471 = |_| -> $outcome:ty { $( $ex:expr )* };
472 $( $rest:tt )*
473 ) => {
474 morph_types! {
475 $( #[doc = $doc] )* $vq type $name
476 $( < $( $bound_id $( : $bound_head $( | $bound_tail )* )? ),+ > )?
477 EXTRA_GENERIC(X)
478 $(: $type)?
479 = |_x: X| -> $outcome { $( $ex )* };
480 $( $rest )*
481 }
482 };
483 (
484 $( #[doc = $doc:expr] )* $vq:vis type $name:ident
485 $( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
486 $( EXTRA_GENERIC ($extra:ident) )?
487 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
488 $( where $( $where_path:ty : $where_bound_head:path $( | $where_bound_tail:path )* ),* )?;
489 $( $rest:tt )*
490 ) => {
491 morph_types! { @DECL $( #[doc = $doc] )* $vq $name ( $( $( $bound_id ),+ )? ) }
492 morph_types! {
493 @IMPL_BOTH $name $( < $( $bound_id ),* > )? :
494 ( $( $( $bound_id $( : $bound_head $( + $bound_tail )* )? , )+ )? $( $extra )? )
495 ( $( where $( $where_path : $where_bound_head $( + $where_bound_tail )* ),* )? )
496 = |$var: $var_type| -> $outcome { $( $ex )* }
497 }
498 morph_types!{ $($rest)* }
499 };
500 (
501 $( #[doc = $doc:expr] )* $vq:vis type $name:ident
502 $( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
503 $( EXTRA_GENERIC ($extra:ident) )?
504 : Morph
505 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
506 $( where $( $where_path:ty : $where_bound_head:path $( | $where_bound_tail:path )* ),* )?;
507 $( $rest:tt )*
508 ) => {
509 morph_types! { @DECL $( #[doc = $doc] )* $vq $name ( $( $( $bound_id ),+ )? ) }
510 morph_types! {
511 @IMPL $name $( < $( $bound_id ),* > )? :
512 ( $( $( $bound_id $( : $bound_head $( + $bound_tail )* )? , )+ )? $( $extra )? )
513 ( $( where $( $where_path : $where_bound_head $( + $where_bound_tail )* ),* )? )
514 = |$var: $var_type| -> $outcome { $( $ex )* }
515 }
516 morph_types!{ $($rest)* }
517 };
518 (
519 $( #[doc = $doc:expr] )* $vq:vis type $name:ident
520 $( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
521 $( EXTRA_GENERIC ($extra:ident) )?
522 : TryMorph
523 = |$var:ident: $var_type:ty| -> Result<$outcome:ty, ()> { $( $ex:expr )* }
524 $( where $( $where_path:ty : $where_bound_head:path $( | $where_bound_tail:path )* ),* )?;
525 $( $rest:tt )*
526 ) => {
527 morph_types! { @DECL $( #[doc = $doc] )* $vq $name ( $( $( $bound_id ),+ )? ) }
528 morph_types! {
529 @IMPL_TRY $name $( < $( $bound_id ),* > )? :
530 ( $( $( $bound_id $( : $bound_head $( + $bound_tail )* )? , )+ )? $( $extra )? )
531 ( $( where $( $where_path : $where_bound_head $( + $where_bound_tail )* ),* )? )
532 = |$var: $var_type| -> $outcome { $( $ex )* }
533 }
534 morph_types!{ $($rest)* }
535 };
536 () => {}
537}
538
539morph_types! {
540 pub type Replace<V: TypedGet> = |_| -> V::Type { V::get() };
542
543 pub type ReplaceWithDefault<V: Default> = |_| -> V { Default::default() };
545
546 pub type ReduceBy<N: TypedGet> = |r: N::Type| -> N::Type {
548 r.checked_sub(&N::get()).unwrap_or(Zero::zero())
549 } where N::Type: CheckedSub | Zero;
550
551 pub type CheckedReduceBy<N: TypedGet>: TryMorph = |r: N::Type| -> Result<N::Type, ()> {
554 r.checked_sub(&N::get()).ok_or(())
555 } where N::Type: CheckedSub;
556
557 pub type MorphWithUpperLimit<L: TypedGet, M>: TryMorph = |r: L::Type| -> Result<L::Type, ()> {
559 M::try_morph(r).map(|m| m.min(L::get()))
560 } where L::Type: Ord, M: TryMorph<L::Type, Outcome = L::Type>;
561}
562
563pub trait Convert<A, B> {
565 fn convert(a: A) -> B;
567}
568
569impl<A, B: Default> Convert<A, B> for () {
570 fn convert(_: A) -> B {
571 Default::default()
572 }
573}
574
575pub trait ConvertBack<A, B>: Convert<A, B> {
579 fn convert_back(b: B) -> A;
581}
582
583pub trait MaybeConvert<A, B> {
585 fn maybe_convert(a: A) -> Option<B>;
587}
588
589#[impl_trait_for_tuples::impl_for_tuples(30)]
590impl<A: Clone, B> MaybeConvert<A, B> for Tuple {
591 fn maybe_convert(a: A) -> Option<B> {
592 for_tuples!( #(
593 match Tuple::maybe_convert(a.clone()) {
594 Some(b) => return Some(b),
595 None => {},
596 }
597 )* );
598 None
599 }
600}
601
602pub trait MaybeConvertBack<A, B>: MaybeConvert<A, B> {
605 fn maybe_convert_back(b: B) -> Option<A>;
607}
608
609#[impl_trait_for_tuples::impl_for_tuples(30)]
610impl<A: Clone, B: Clone> MaybeConvertBack<A, B> for Tuple {
611 fn maybe_convert_back(b: B) -> Option<A> {
612 for_tuples!( #(
613 match Tuple::maybe_convert_back(b.clone()) {
614 Some(a) => return Some(a),
615 None => {},
616 }
617 )* );
618 None
619 }
620}
621
622pub trait TryConvert<A, B> {
625 fn try_convert(a: A) -> Result<B, A>;
627}
628
629#[impl_trait_for_tuples::impl_for_tuples(30)]
630impl<A, B> TryConvert<A, B> for Tuple {
631 fn try_convert(a: A) -> Result<B, A> {
632 for_tuples!( #(
633 let a = match Tuple::try_convert(a) {
634 Ok(b) => return Ok(b),
635 Err(a) => a,
636 };
637 )* );
638 Err(a)
639 }
640}
641
642pub trait TryConvertBack<A, B>: TryConvert<A, B> {
645 fn try_convert_back(b: B) -> Result<A, B>;
648}
649
650#[impl_trait_for_tuples::impl_for_tuples(30)]
651impl<A, B> TryConvertBack<A, B> for Tuple {
652 fn try_convert_back(b: B) -> Result<A, B> {
653 for_tuples!( #(
654 let b = match Tuple::try_convert_back(b) {
655 Ok(a) => return Ok(a),
656 Err(b) => b,
657 };
658 )* );
659 Err(b)
660 }
661}
662
663pub trait MaybeEquivalence<A, B> {
665 fn convert(a: &A) -> Option<B>;
667 fn convert_back(b: &B) -> Option<A>;
669}
670
671#[impl_trait_for_tuples::impl_for_tuples(30)]
672impl<A, B> MaybeEquivalence<A, B> for Tuple {
673 fn convert(a: &A) -> Option<B> {
674 for_tuples!( #(
675 match Tuple::convert(a) {
676 Some(b) => return Some(b),
677 None => {},
678 }
679 )* );
680 None
681 }
682 fn convert_back(b: &B) -> Option<A> {
683 for_tuples!( #(
684 match Tuple::convert_back(b) {
685 Some(a) => return Some(a),
686 None => {},
687 }
688 )* );
689 None
690 }
691}
692
693pub struct ConvertToValue<T>(core::marker::PhantomData<T>);
696impl<X, Y, T: Get<Y>> Convert<X, Y> for ConvertToValue<T> {
697 fn convert(_: X) -> Y {
698 T::get()
699 }
700}
701impl<X, Y, T: Get<Y>> MaybeConvert<X, Y> for ConvertToValue<T> {
702 fn maybe_convert(_: X) -> Option<Y> {
703 Some(T::get())
704 }
705}
706impl<X, Y, T: Get<Y>> MaybeConvertBack<X, Y> for ConvertToValue<T> {
707 fn maybe_convert_back(_: Y) -> Option<X> {
708 None
709 }
710}
711impl<X, Y, T: Get<Y>> TryConvert<X, Y> for ConvertToValue<T> {
712 fn try_convert(_: X) -> Result<Y, X> {
713 Ok(T::get())
714 }
715}
716impl<X, Y, T: Get<Y>> TryConvertBack<X, Y> for ConvertToValue<T> {
717 fn try_convert_back(y: Y) -> Result<X, Y> {
718 Err(y)
719 }
720}
721impl<X, Y, T: Get<Y>> MaybeEquivalence<X, Y> for ConvertToValue<T> {
722 fn convert(_: &X) -> Option<Y> {
723 Some(T::get())
724 }
725 fn convert_back(_: &Y) -> Option<X> {
726 None
727 }
728}
729
730pub struct Identity;
732impl<T> Convert<T, T> for Identity {
733 fn convert(a: T) -> T {
734 a
735 }
736}
737impl<T> ConvertBack<T, T> for Identity {
738 fn convert_back(a: T) -> T {
739 a
740 }
741}
742impl<T> MaybeConvert<T, T> for Identity {
743 fn maybe_convert(a: T) -> Option<T> {
744 Some(a)
745 }
746}
747impl<T> MaybeConvertBack<T, T> for Identity {
748 fn maybe_convert_back(a: T) -> Option<T> {
749 Some(a)
750 }
751}
752impl<T> TryConvert<T, T> for Identity {
753 fn try_convert(a: T) -> Result<T, T> {
754 Ok(a)
755 }
756}
757impl<T> TryConvertBack<T, T> for Identity {
758 fn try_convert_back(a: T) -> Result<T, T> {
759 Ok(a)
760 }
761}
762impl<T: Clone> MaybeEquivalence<T, T> for Identity {
763 fn convert(a: &T) -> Option<T> {
764 Some(a.clone())
765 }
766 fn convert_back(a: &T) -> Option<T> {
767 Some(a.clone())
768 }
769}
770
771pub struct ConvertInto;
773impl<A: Into<B>, B> Convert<A, B> for ConvertInto {
774 fn convert(a: A) -> B {
775 a.into()
776 }
777}
778impl<A: Into<B>, B> MaybeConvert<A, B> for ConvertInto {
779 fn maybe_convert(a: A) -> Option<B> {
780 Some(a.into())
781 }
782}
783impl<A: Into<B>, B: Into<A>> MaybeConvertBack<A, B> for ConvertInto {
784 fn maybe_convert_back(b: B) -> Option<A> {
785 Some(b.into())
786 }
787}
788impl<A: Into<B>, B> TryConvert<A, B> for ConvertInto {
789 fn try_convert(a: A) -> Result<B, A> {
790 Ok(a.into())
791 }
792}
793impl<A: Into<B>, B: Into<A>> TryConvertBack<A, B> for ConvertInto {
794 fn try_convert_back(b: B) -> Result<A, B> {
795 Ok(b.into())
796 }
797}
798impl<A: Clone + Into<B>, B: Clone + Into<A>> MaybeEquivalence<A, B> for ConvertInto {
799 fn convert(a: &A) -> Option<B> {
800 Some(a.clone().into())
801 }
802 fn convert_back(b: &B) -> Option<A> {
803 Some(b.clone().into())
804 }
805}
806
807pub struct TryConvertInto;
809impl<A: Clone + TryInto<B>, B> MaybeConvert<A, B> for TryConvertInto {
810 fn maybe_convert(a: A) -> Option<B> {
811 a.clone().try_into().ok()
812 }
813}
814impl<A: Clone + TryInto<B>, B: Clone + TryInto<A>> MaybeConvertBack<A, B> for TryConvertInto {
815 fn maybe_convert_back(b: B) -> Option<A> {
816 b.clone().try_into().ok()
817 }
818}
819impl<A: Clone + TryInto<B>, B> TryConvert<A, B> for TryConvertInto {
820 fn try_convert(a: A) -> Result<B, A> {
821 a.clone().try_into().map_err(|_| a)
822 }
823}
824impl<A: Clone + TryInto<B>, B: Clone + TryInto<A>> TryConvertBack<A, B> for TryConvertInto {
825 fn try_convert_back(b: B) -> Result<A, B> {
826 b.clone().try_into().map_err(|_| b)
827 }
828}
829impl<A: Clone + TryInto<B>, B: Clone + TryInto<A>> MaybeEquivalence<A, B> for TryConvertInto {
830 fn convert(a: &A) -> Option<B> {
831 a.clone().try_into().ok()
832 }
833 fn convert_back(b: &B) -> Option<A> {
834 b.clone().try_into().ok()
835 }
836}
837
838pub trait CheckedConversion {
842 fn checked_from<T>(t: T) -> Option<Self>
848 where
849 Self: TryFrom<T>,
850 {
851 <Self as TryFrom<T>>::try_from(t).ok()
852 }
853 fn checked_into<T>(self) -> Option<T>
859 where
860 Self: TryInto<T>,
861 {
862 <Self as TryInto<T>>::try_into(self).ok()
863 }
864}
865impl<T: Sized> CheckedConversion for T {}
866
867pub trait Scale<Other> {
870 type Output;
872
873 fn mul(self, other: Other) -> Self::Output;
875
876 fn div(self, other: Other) -> Self::Output;
878
879 fn rem(self, other: Other) -> Self::Output;
881}
882macro_rules! impl_scale {
883 ($self:ty, $other:ty) => {
884 impl Scale<$other> for $self {
885 type Output = Self;
886 fn mul(self, other: $other) -> Self::Output {
887 self * (other as Self)
888 }
889 fn div(self, other: $other) -> Self::Output {
890 self / (other as Self)
891 }
892 fn rem(self, other: $other) -> Self::Output {
893 self % (other as Self)
894 }
895 }
896 };
897}
898impl_scale!(u128, u128);
899impl_scale!(u128, u64);
900impl_scale!(u128, u32);
901impl_scale!(u128, u16);
902impl_scale!(u128, u8);
903impl_scale!(u64, u64);
904impl_scale!(u64, u32);
905impl_scale!(u64, u16);
906impl_scale!(u64, u8);
907impl_scale!(u32, u32);
908impl_scale!(u32, u16);
909impl_scale!(u32, u8);
910impl_scale!(u16, u16);
911impl_scale!(u16, u8);
912impl_scale!(u8, u8);
913
914pub trait Clear {
917 fn is_clear(&self) -> bool;
919
920 fn clear() -> Self;
922}
923
924impl<T: Default + Eq + PartialEq> Clear for T {
925 fn is_clear(&self) -> bool {
926 *self == Self::clear()
927 }
928 fn clear() -> Self {
929 Default::default()
930 }
931}
932
933pub trait SimpleBitOps:
935 Sized
936 + Clear
937 + core::ops::BitOr<Self, Output = Self>
938 + core::ops::BitXor<Self, Output = Self>
939 + core::ops::BitAnd<Self, Output = Self>
940{
941}
942impl<
943 T: Sized
944 + Clear
945 + core::ops::BitOr<Self, Output = Self>
946 + core::ops::BitXor<Self, Output = Self>
947 + core::ops::BitAnd<Self, Output = Self>,
948 > SimpleBitOps for T
949{
950}
951
952pub trait Hash:
956 'static
957 + MaybeSerializeDeserialize
958 + Debug
959 + Clone
960 + Eq
961 + PartialEq
962 + Hasher<Out = <Self as Hash>::Output>
963{
964 type Output: HashOutput;
966
967 fn hash(s: &[u8]) -> Self::Output {
969 <Self as Hasher>::hash(s)
970 }
971
972 fn hash_of<S: Encode>(s: &S) -> Self::Output {
974 Encode::using_encoded(s, <Self as Hasher>::hash)
975 }
976
977 fn ordered_trie_root(input: Vec<Vec<u8>>, state_version: StateVersion) -> Self::Output;
979
980 fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>, state_version: StateVersion) -> Self::Output;
982}
983
984pub trait HashOutput:
986 Member
987 + MaybeSerializeDeserialize
988 + MaybeDisplay
989 + MaybeFromStr
990 + Debug
991 + core::hash::Hash
992 + AsRef<[u8]>
993 + AsMut<[u8]>
994 + Copy
995 + Ord
996 + Default
997 + Encode
998 + Decode
999 + EncodeLike
1000 + MaxEncodedLen
1001 + TypeInfo
1002{
1003}
1004
1005impl<T> HashOutput for T where
1006 T: Member
1007 + MaybeSerializeDeserialize
1008 + MaybeDisplay
1009 + MaybeFromStr
1010 + Debug
1011 + core::hash::Hash
1012 + AsRef<[u8]>
1013 + AsMut<[u8]>
1014 + Copy
1015 + Ord
1016 + Default
1017 + Encode
1018 + Decode
1019 + EncodeLike
1020 + MaxEncodedLen
1021 + TypeInfo
1022{
1023}
1024
1025#[derive(PartialEq, Eq, Clone, RuntimeDebug, TypeInfo)]
1027#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1028pub struct BlakeTwo256;
1029
1030impl Hasher for BlakeTwo256 {
1031 type Out = sp_core::H256;
1032 type StdHasher = hash256_std_hasher::Hash256StdHasher;
1033 const LENGTH: usize = 32;
1034
1035 fn hash(s: &[u8]) -> Self::Out {
1036 sp_io::hashing::blake2_256(s).into()
1037 }
1038}
1039
1040impl Hash for BlakeTwo256 {
1041 type Output = sp_core::H256;
1042
1043 fn ordered_trie_root(input: Vec<Vec<u8>>, version: StateVersion) -> Self::Output {
1044 sp_io::trie::blake2_256_ordered_root(input, version)
1045 }
1046
1047 fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>, version: StateVersion) -> Self::Output {
1048 sp_io::trie::blake2_256_root(input, version)
1049 }
1050}
1051
1052#[derive(PartialEq, Eq, Clone, RuntimeDebug, TypeInfo)]
1054#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1055pub struct Keccak256;
1056
1057impl Hasher for Keccak256 {
1058 type Out = sp_core::H256;
1059 type StdHasher = hash256_std_hasher::Hash256StdHasher;
1060 const LENGTH: usize = 32;
1061
1062 fn hash(s: &[u8]) -> Self::Out {
1063 sp_io::hashing::keccak_256(s).into()
1064 }
1065}
1066
1067impl Hash for Keccak256 {
1068 type Output = sp_core::H256;
1069
1070 fn ordered_trie_root(input: Vec<Vec<u8>>, version: StateVersion) -> Self::Output {
1071 sp_io::trie::keccak_256_ordered_root(input, version)
1072 }
1073
1074 fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>, version: StateVersion) -> Self::Output {
1075 sp_io::trie::keccak_256_root(input, version)
1076 }
1077}
1078
1079pub trait CheckEqual {
1081 fn check_equal(&self, other: &Self);
1083}
1084
1085impl CheckEqual for sp_core::H256 {
1086 #[cfg(feature = "std")]
1087 fn check_equal(&self, other: &Self) {
1088 use sp_core::hexdisplay::HexDisplay;
1089 if self != other {
1090 println!(
1091 "Hash: given={}, expected={}",
1092 HexDisplay::from(self.as_fixed_bytes()),
1093 HexDisplay::from(other.as_fixed_bytes()),
1094 );
1095 }
1096 }
1097
1098 #[cfg(not(feature = "std"))]
1099 fn check_equal(&self, other: &Self) {
1100 if self != other {
1101 "Hash not equal".print();
1102 self.as_bytes().print();
1103 other.as_bytes().print();
1104 }
1105 }
1106}
1107
1108impl CheckEqual for super::generic::DigestItem {
1109 #[cfg(feature = "std")]
1110 fn check_equal(&self, other: &Self) {
1111 if self != other {
1112 println!("DigestItem: given={:?}, expected={:?}", self, other);
1113 }
1114 }
1115
1116 #[cfg(not(feature = "std"))]
1117 fn check_equal(&self, other: &Self) {
1118 if self != other {
1119 "DigestItem not equal".print();
1120 (&Encode::encode(self)[..]).print();
1121 (&Encode::encode(other)[..]).print();
1122 }
1123 }
1124}
1125
1126sp_core::impl_maybe_marker!(
1127 trait MaybeDisplay: Display;
1129
1130 trait MaybeFromStr: FromStr;
1132
1133 trait MaybeHash: core::hash::Hash;
1135);
1136
1137sp_core::impl_maybe_marker_std_or_serde!(
1138 trait MaybeSerialize: Serialize;
1140
1141 trait MaybeSerializeDeserialize: DeserializeOwned, Serialize;
1143);
1144
1145pub trait Member: Send + Sync + Sized + Debug + Eq + PartialEq + Clone + 'static {}
1147impl<T: Send + Sync + Sized + Debug + Eq + PartialEq + Clone + 'static> Member for T {}
1148
1149pub trait IsMember<MemberId> {
1151 fn is_member(member_id: &MemberId) -> bool;
1153}
1154
1155pub trait BlockNumber:
1157 Member
1158 + MaybeSerializeDeserialize
1159 + MaybeFromStr
1160 + Debug
1161 + core::hash::Hash
1162 + Copy
1163 + MaybeDisplay
1164 + AtLeast32BitUnsigned
1165 + Into<U256>
1166 + TryFrom<U256>
1167 + Default
1168 + TypeInfo
1169 + MaxEncodedLen
1170 + FullCodec
1171{
1172}
1173
1174impl<
1175 T: Member
1176 + MaybeSerializeDeserialize
1177 + MaybeFromStr
1178 + Debug
1179 + core::hash::Hash
1180 + Copy
1181 + MaybeDisplay
1182 + AtLeast32BitUnsigned
1183 + Into<U256>
1184 + TryFrom<U256>
1185 + Default
1186 + TypeInfo
1187 + MaxEncodedLen
1188 + FullCodec,
1189 > BlockNumber for T
1190{
1191}
1192
1193pub trait Header:
1199 Clone + Send + Sync + Codec + Eq + MaybeSerialize + Debug + TypeInfo + 'static
1200{
1201 type Number: BlockNumber;
1203 type Hash: HashOutput;
1205 type Hashing: Hash<Output = Self::Hash>;
1207
1208 fn new(
1210 number: Self::Number,
1211 extrinsics_root: Self::Hash,
1212 state_root: Self::Hash,
1213 parent_hash: Self::Hash,
1214 digest: Digest,
1215 ) -> Self;
1216
1217 fn number(&self) -> &Self::Number;
1219 fn set_number(&mut self, number: Self::Number);
1221
1222 fn extrinsics_root(&self) -> &Self::Hash;
1224 fn set_extrinsics_root(&mut self, root: Self::Hash);
1226
1227 fn state_root(&self) -> &Self::Hash;
1229 fn set_state_root(&mut self, root: Self::Hash);
1231
1232 fn parent_hash(&self) -> &Self::Hash;
1234 fn set_parent_hash(&mut self, hash: Self::Hash);
1236
1237 fn digest(&self) -> &Digest;
1239 fn digest_mut(&mut self) -> &mut Digest;
1241
1242 fn hash(&self) -> Self::Hash {
1244 <Self::Hashing as Hash>::hash_of(self)
1245 }
1246}
1247
1248#[doc(hidden)]
1268pub trait HeaderProvider {
1269 type HeaderT: Header;
1271}
1272
1273pub trait Block:
1278 HeaderProvider<HeaderT = <Self as Block>::Header>
1279 + Clone
1280 + Send
1281 + Sync
1282 + Codec
1283 + Eq
1284 + MaybeSerialize
1285 + Debug
1286 + 'static
1287{
1288 type Extrinsic: Member + Codec + Extrinsic + MaybeSerialize;
1290 type Header: Header<Hash = Self::Hash> + MaybeSerializeDeserialize;
1292 type Hash: HashOutput;
1294
1295 fn header(&self) -> &Self::Header;
1297 fn extrinsics(&self) -> &[Self::Extrinsic];
1299 fn deconstruct(self) -> (Self::Header, Vec<Self::Extrinsic>);
1301 fn new(header: Self::Header, extrinsics: Vec<Self::Extrinsic>) -> Self;
1303 fn hash(&self) -> Self::Hash {
1305 <<Self::Header as Header>::Hashing as Hash>::hash_of(self.header())
1306 }
1307 fn encode_from(header: &Self::Header, extrinsics: &[Self::Extrinsic]) -> Vec<u8>;
1310}
1311
1312pub trait Extrinsic: Sized {
1314 type Call: TypeInfo;
1316
1317 type SignaturePayload: SignaturePayload;
1323
1324 fn is_signed(&self) -> Option<bool> {
1327 None
1328 }
1329
1330 fn new(_call: Self::Call, _signed_data: Option<Self::SignaturePayload>) -> Option<Self> {
1337 None
1338 }
1339}
1340
1341pub trait SignaturePayload {
1344 type SignatureAddress: TypeInfo;
1348
1349 type Signature: TypeInfo;
1353
1354 type SignatureExtra: TypeInfo;
1358}
1359
1360impl SignaturePayload for () {
1361 type SignatureAddress = ();
1362 type Signature = ();
1363 type SignatureExtra = ();
1364}
1365
1366pub trait ExtrinsicMetadata {
1368 const VERSION: u8;
1372
1373 type SignedExtensions: SignedExtension;
1375}
1376
1377pub type HashingFor<B> = <<B as Block>::Header as Header>::Hashing;
1379pub type NumberFor<B> = <<B as Block>::Header as Header>::Number;
1381pub trait Checkable<Context>: Sized {
1388 type Checked;
1390
1391 fn check(self, c: &Context) -> Result<Self::Checked, TransactionValidityError>;
1393
1394 #[cfg(feature = "try-runtime")]
1403 fn unchecked_into_checked_i_know_what_i_am_doing(
1404 self,
1405 c: &Context,
1406 ) -> Result<Self::Checked, TransactionValidityError>;
1407}
1408
1409pub trait BlindCheckable: Sized {
1414 type Checked;
1416
1417 fn check(self) -> Result<Self::Checked, TransactionValidityError>;
1419}
1420
1421impl<T: BlindCheckable, Context> Checkable<Context> for T {
1423 type Checked = <Self as BlindCheckable>::Checked;
1424
1425 fn check(self, _c: &Context) -> Result<Self::Checked, TransactionValidityError> {
1426 BlindCheckable::check(self)
1427 }
1428
1429 #[cfg(feature = "try-runtime")]
1430 fn unchecked_into_checked_i_know_what_i_am_doing(
1431 self,
1432 _: &Context,
1433 ) -> Result<Self::Checked, TransactionValidityError> {
1434 unreachable!();
1435 }
1436}
1437
1438pub trait Dispatchable {
1441 type RuntimeOrigin: Debug;
1445 type Config;
1447 type Info;
1451 type PostInfo: Eq + PartialEq + Clone + Copy + Encode + Decode + Printable;
1454 fn dispatch(self, origin: Self::RuntimeOrigin)
1456 -> crate::DispatchResultWithInfo<Self::PostInfo>;
1457}
1458
1459pub type DispatchInfoOf<T> = <T as Dispatchable>::Info;
1461pub type PostDispatchInfoOf<T> = <T as Dispatchable>::PostInfo;
1463
1464impl Dispatchable for () {
1465 type RuntimeOrigin = ();
1466 type Config = ();
1467 type Info = ();
1468 type PostInfo = ();
1469 fn dispatch(
1470 self,
1471 _origin: Self::RuntimeOrigin,
1472 ) -> crate::DispatchResultWithInfo<Self::PostInfo> {
1473 panic!("This implementation should not be used for actual dispatch.");
1474 }
1475}
1476
1477pub trait SignedExtension:
1480 Codec + Debug + Sync + Send + Clone + Eq + PartialEq + StaticTypeInfo
1481{
1482 const IDENTIFIER: &'static str;
1487
1488 type AccountId;
1490
1491 type Call: Dispatchable;
1493
1494 type AdditionalSigned: Encode + TypeInfo;
1497
1498 type Pre;
1500
1501 fn additional_signed(&self) -> Result<Self::AdditionalSigned, TransactionValidityError>;
1504
1505 fn validate(
1515 &self,
1516 _who: &Self::AccountId,
1517 _call: &Self::Call,
1518 _info: &DispatchInfoOf<Self::Call>,
1519 _len: usize,
1520 ) -> TransactionValidity {
1521 Ok(ValidTransaction::default())
1522 }
1523
1524 fn pre_dispatch(
1528 self,
1529 who: &Self::AccountId,
1530 call: &Self::Call,
1531 info: &DispatchInfoOf<Self::Call>,
1532 len: usize,
1533 ) -> Result<Self::Pre, TransactionValidityError>;
1534
1535 fn validate_unsigned(
1544 _call: &Self::Call,
1545 _info: &DispatchInfoOf<Self::Call>,
1546 _len: usize,
1547 ) -> TransactionValidity {
1548 Ok(ValidTransaction::default())
1549 }
1550
1551 fn pre_dispatch_unsigned(
1560 call: &Self::Call,
1561 info: &DispatchInfoOf<Self::Call>,
1562 len: usize,
1563 ) -> Result<(), TransactionValidityError> {
1564 Self::validate_unsigned(call, info, len).map(|_| ()).map_err(Into::into)
1565 }
1566
1567 fn post_dispatch(
1584 _pre: Option<Self::Pre>,
1585 _info: &DispatchInfoOf<Self::Call>,
1586 _post_info: &PostDispatchInfoOf<Self::Call>,
1587 _len: usize,
1588 _result: &DispatchResult,
1589 ) -> Result<(), TransactionValidityError> {
1590 Ok(())
1591 }
1592
1593 fn metadata() -> Vec<SignedExtensionMetadata> {
1602 alloc::vec![SignedExtensionMetadata {
1603 identifier: Self::IDENTIFIER,
1604 ty: scale_info::meta_type::<Self>(),
1605 additional_signed: scale_info::meta_type::<Self::AdditionalSigned>()
1606 }]
1607 }
1608}
1609
1610pub struct SignedExtensionMetadata {
1612 pub identifier: &'static str,
1614 pub ty: MetaType,
1616 pub additional_signed: MetaType,
1618}
1619
1620#[impl_for_tuples(1, 12)]
1621impl<AccountId, Call: Dispatchable> SignedExtension for Tuple {
1622 for_tuples!( where #( Tuple: SignedExtension<AccountId=AccountId, Call=Call,> )* );
1623 type AccountId = AccountId;
1624 type Call = Call;
1625 const IDENTIFIER: &'static str = "You should call `identifier()`!";
1626 for_tuples!( type AdditionalSigned = ( #( Tuple::AdditionalSigned ),* ); );
1627 for_tuples!( type Pre = ( #( Tuple::Pre ),* ); );
1628
1629 fn additional_signed(&self) -> Result<Self::AdditionalSigned, TransactionValidityError> {
1630 Ok(for_tuples!( ( #( Tuple.additional_signed()? ),* ) ))
1631 }
1632
1633 fn validate(
1634 &self,
1635 who: &Self::AccountId,
1636 call: &Self::Call,
1637 info: &DispatchInfoOf<Self::Call>,
1638 len: usize,
1639 ) -> TransactionValidity {
1640 let valid = ValidTransaction::default();
1641 for_tuples!( #( let valid = valid.combine_with(Tuple.validate(who, call, info, len)?); )* );
1642 Ok(valid)
1643 }
1644
1645 fn pre_dispatch(
1646 self,
1647 who: &Self::AccountId,
1648 call: &Self::Call,
1649 info: &DispatchInfoOf<Self::Call>,
1650 len: usize,
1651 ) -> Result<Self::Pre, TransactionValidityError> {
1652 Ok(for_tuples!( ( #( Tuple.pre_dispatch(who, call, info, len)? ),* ) ))
1653 }
1654
1655 fn validate_unsigned(
1656 call: &Self::Call,
1657 info: &DispatchInfoOf<Self::Call>,
1658 len: usize,
1659 ) -> TransactionValidity {
1660 let valid = ValidTransaction::default();
1661 for_tuples!( #( let valid = valid.combine_with(Tuple::validate_unsigned(call, info, len)?); )* );
1662 Ok(valid)
1663 }
1664
1665 fn pre_dispatch_unsigned(
1666 call: &Self::Call,
1667 info: &DispatchInfoOf<Self::Call>,
1668 len: usize,
1669 ) -> Result<(), TransactionValidityError> {
1670 for_tuples!( #( Tuple::pre_dispatch_unsigned(call, info, len)?; )* );
1671 Ok(())
1672 }
1673
1674 fn post_dispatch(
1675 pre: Option<Self::Pre>,
1676 info: &DispatchInfoOf<Self::Call>,
1677 post_info: &PostDispatchInfoOf<Self::Call>,
1678 len: usize,
1679 result: &DispatchResult,
1680 ) -> Result<(), TransactionValidityError> {
1681 match pre {
1682 Some(x) => {
1683 for_tuples!( #( Tuple::post_dispatch(Some(x.Tuple), info, post_info, len, result)?; )* );
1684 },
1685 None => {
1686 for_tuples!( #( Tuple::post_dispatch(None, info, post_info, len, result)?; )* );
1687 },
1688 }
1689 Ok(())
1690 }
1691
1692 fn metadata() -> Vec<SignedExtensionMetadata> {
1693 let mut ids = Vec::new();
1694 for_tuples!( #( ids.extend(Tuple::metadata()); )* );
1695 ids
1696 }
1697}
1698
1699impl SignedExtension for () {
1700 type AccountId = u64;
1701 type AdditionalSigned = ();
1702 type Call = ();
1703 type Pre = ();
1704 const IDENTIFIER: &'static str = "UnitSignedExtension";
1705 fn additional_signed(&self) -> core::result::Result<(), TransactionValidityError> {
1706 Ok(())
1707 }
1708 fn pre_dispatch(
1709 self,
1710 who: &Self::AccountId,
1711 call: &Self::Call,
1712 info: &DispatchInfoOf<Self::Call>,
1713 len: usize,
1714 ) -> Result<Self::Pre, TransactionValidityError> {
1715 self.validate(who, call, info, len).map(|_| ())
1716 }
1717}
1718
1719pub trait Applyable: Sized + Send + Sync {
1726 type Call: Dispatchable;
1728
1729 fn validate<V: ValidateUnsigned<Call = Self::Call>>(
1731 &self,
1732 source: TransactionSource,
1733 info: &DispatchInfoOf<Self::Call>,
1734 len: usize,
1735 ) -> TransactionValidity;
1736
1737 fn apply<V: ValidateUnsigned<Call = Self::Call>>(
1740 self,
1741 info: &DispatchInfoOf<Self::Call>,
1742 len: usize,
1743 ) -> crate::ApplyExtrinsicResultWithInfo<PostDispatchInfoOf<Self::Call>>;
1744}
1745
1746pub trait GetRuntimeBlockType {
1748 type RuntimeBlock: self::Block;
1750}
1751
1752pub trait GetNodeBlockType {
1754 type NodeBlock: self::Block;
1756}
1757
1758pub trait ValidateUnsigned {
1766 type Call;
1768
1769 fn pre_dispatch(call: &Self::Call) -> Result<(), TransactionValidityError> {
1782 Self::validate_unsigned(TransactionSource::InBlock, call)
1783 .map(|_| ())
1784 .map_err(Into::into)
1785 }
1786
1787 fn validate_unsigned(source: TransactionSource, call: &Self::Call) -> TransactionValidity;
1800}
1801
1802pub trait OpaqueKeys: Clone {
1805 type KeyTypeIdProviders;
1807
1808 fn key_ids() -> &'static [crate::KeyTypeId];
1810 fn get_raw(&self, i: super::KeyTypeId) -> &[u8];
1812 fn get<T: Decode>(&self, i: super::KeyTypeId) -> Option<T> {
1814 T::decode(&mut self.get_raw(i)).ok()
1815 }
1816 fn ownership_proof_is_valid(&self, _proof: &[u8]) -> bool {
1818 true
1819 }
1820}
1821
1822pub struct AppendZerosInput<'a, T>(&'a mut T);
1827
1828impl<'a, T> AppendZerosInput<'a, T> {
1829 pub fn new(input: &'a mut T) -> Self {
1831 Self(input)
1832 }
1833}
1834
1835impl<'a, T: codec::Input> codec::Input for AppendZerosInput<'a, T> {
1836 fn remaining_len(&mut self) -> Result<Option<usize>, codec::Error> {
1837 Ok(None)
1838 }
1839
1840 fn read(&mut self, into: &mut [u8]) -> Result<(), codec::Error> {
1841 let remaining = self.0.remaining_len()?;
1842 let completed = if let Some(n) = remaining {
1843 let readable = into.len().min(n);
1844 self.0.read(&mut into[..readable])?;
1846 readable
1847 } else {
1848 let mut i = 0;
1850 while i < into.len() {
1851 if let Ok(b) = self.0.read_byte() {
1852 into[i] = b;
1853 i += 1;
1854 } else {
1855 break
1856 }
1857 }
1858 i
1859 };
1860 for i in &mut into[completed..] {
1862 *i = 0;
1863 }
1864 Ok(())
1865 }
1866}
1867
1868pub struct TrailingZeroInput<'a>(&'a [u8]);
1870
1871impl<'a> TrailingZeroInput<'a> {
1872 pub fn new(data: &'a [u8]) -> Self {
1874 Self(data)
1875 }
1876
1877 pub fn zeroes() -> Self {
1879 Self::new(&[][..])
1880 }
1881}
1882
1883impl<'a> codec::Input for TrailingZeroInput<'a> {
1884 fn remaining_len(&mut self) -> Result<Option<usize>, codec::Error> {
1885 Ok(None)
1886 }
1887
1888 fn read(&mut self, into: &mut [u8]) -> Result<(), codec::Error> {
1889 let len_from_inner = into.len().min(self.0.len());
1890 into[..len_from_inner].copy_from_slice(&self.0[..len_from_inner]);
1891 for i in &mut into[len_from_inner..] {
1892 *i = 0;
1893 }
1894 self.0 = &self.0[len_from_inner..];
1895
1896 Ok(())
1897 }
1898}
1899
1900pub trait AccountIdConversion<AccountId>: Sized {
1902 fn into_account_truncating(&self) -> AccountId {
1905 self.into_sub_account_truncating(&())
1906 }
1907
1908 fn try_into_account(&self) -> Option<AccountId> {
1911 self.try_into_sub_account(&())
1912 }
1913
1914 fn try_from_account(a: &AccountId) -> Option<Self> {
1916 Self::try_from_sub_account::<()>(a).map(|x| x.0)
1917 }
1918
1919 fn into_sub_account_truncating<S: Encode>(&self, sub: S) -> AccountId;
1933
1934 fn try_into_sub_account<S: Encode>(&self, sub: S) -> Option<AccountId>;
1938
1939 fn try_from_sub_account<S: Decode>(x: &AccountId) -> Option<(Self, S)>;
1941}
1942
1943impl<T: Encode + Decode, Id: Encode + Decode + TypeId> AccountIdConversion<T> for Id {
1946 fn into_sub_account_truncating<S: Encode>(&self, sub: S) -> T {
1950 (Id::TYPE_ID, self, sub)
1951 .using_encoded(|b| T::decode(&mut TrailingZeroInput(b)))
1952 .expect("All byte sequences are valid `AccountIds`; qed")
1953 }
1954
1955 fn try_into_sub_account<S: Encode>(&self, sub: S) -> Option<T> {
1957 let encoded_seed = (Id::TYPE_ID, self, sub).encode();
1958 let account = T::decode(&mut TrailingZeroInput(&encoded_seed))
1959 .expect("All byte sequences are valid `AccountIds`; qed");
1960 if encoded_seed.len() <= account.encoded_size() {
1963 Some(account)
1964 } else {
1965 None
1966 }
1967 }
1968
1969 fn try_from_sub_account<S: Decode>(x: &T) -> Option<(Self, S)> {
1970 x.using_encoded(|d| {
1971 if d[0..4] != Id::TYPE_ID {
1972 return None
1973 }
1974 let mut cursor = &d[4..];
1975 let result = Decode::decode(&mut cursor).ok()?;
1976 if cursor.iter().all(|x| *x == 0) {
1977 Some(result)
1978 } else {
1979 None
1980 }
1981 })
1982 }
1983}
1984
1985#[macro_export]
1992macro_rules! count {
1993 ($f:ident ($($x:tt)*) ) => ();
1994 ($f:ident ($($x:tt)*) $x1:tt) => { $f!($($x)* 0); };
1995 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt) => { $f!($($x)* 0); $f!($($x)* 1); };
1996 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt) => { $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); };
1997 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt, $x4:tt) => {
1998 $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); $f!($($x)* 3);
1999 };
2000 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt, $x4:tt, $x5:tt) => {
2001 $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); $f!($($x)* 3); $f!($($x)* 4);
2002 };
2003}
2004
2005#[doc(hidden)]
2006#[macro_export]
2007macro_rules! impl_opaque_keys_inner {
2008 (
2009 $( #[ $attr:meta ] )*
2010 pub struct $name:ident {
2011 $(
2012 $( #[ $inner_attr:meta ] )*
2013 pub $field:ident: $type:ty,
2014 )*
2015 }
2016 ) => {
2017 $( #[ $attr ] )*
2018 #[derive(
2019 Clone, PartialEq, Eq,
2020 $crate::codec::Encode,
2021 $crate::codec::Decode,
2022 $crate::scale_info::TypeInfo,
2023 $crate::RuntimeDebug,
2024 )]
2025 pub struct $name {
2026 $(
2027 $( #[ $inner_attr ] )*
2028 pub $field: <$type as $crate::BoundToRuntimeAppPublic>::Public,
2029 )*
2030 }
2031
2032 impl $name {
2033 pub fn generate(seed: Option<$crate::Vec<u8>>) -> $crate::Vec<u8> {
2039 let keys = Self{
2040 $(
2041 $field: <
2042 <
2043 $type as $crate::BoundToRuntimeAppPublic
2044 >::Public as $crate::RuntimeAppPublic
2045 >::generate_pair(seed.clone()),
2046 )*
2047 };
2048 $crate::codec::Encode::encode(&keys)
2049 }
2050
2051 pub fn into_raw_public_keys(
2053 self,
2054 ) -> $crate::Vec<($crate::Vec<u8>, $crate::KeyTypeId)> {
2055 let mut keys = Vec::new();
2056 $(
2057 keys.push((
2058 $crate::RuntimeAppPublic::to_raw_vec(&self.$field),
2059 <
2060 <
2061 $type as $crate::BoundToRuntimeAppPublic
2062 >::Public as $crate::RuntimeAppPublic
2063 >::ID,
2064 ));
2065 )*
2066
2067 keys
2068 }
2069
2070 pub fn decode_into_raw_public_keys(
2075 encoded: &[u8],
2076 ) -> Option<$crate::Vec<($crate::Vec<u8>, $crate::KeyTypeId)>> {
2077 <Self as $crate::codec::Decode>::decode(&mut &encoded[..])
2078 .ok()
2079 .map(|s| s.into_raw_public_keys())
2080 }
2081 }
2082
2083 impl $crate::traits::OpaqueKeys for $name {
2084 type KeyTypeIdProviders = ( $( $type, )* );
2085
2086 fn key_ids() -> &'static [$crate::KeyTypeId] {
2087 &[
2088 $(
2089 <
2090 <
2091 $type as $crate::BoundToRuntimeAppPublic
2092 >::Public as $crate::RuntimeAppPublic
2093 >::ID
2094 ),*
2095 ]
2096 }
2097
2098 fn get_raw(&self, i: $crate::KeyTypeId) -> &[u8] {
2099 match i {
2100 $(
2101 i if i == <
2102 <
2103 $type as $crate::BoundToRuntimeAppPublic
2104 >::Public as $crate::RuntimeAppPublic
2105 >::ID =>
2106 self.$field.as_ref(),
2107 )*
2108 _ => &[],
2109 }
2110 }
2111 }
2112 };
2113}
2114
2115#[macro_export]
2139#[cfg(any(feature = "serde", feature = "std"))]
2140macro_rules! impl_opaque_keys {
2141 {
2142 $( #[ $attr:meta ] )*
2143 pub struct $name:ident {
2144 $(
2145 $( #[ $inner_attr:meta ] )*
2146 pub $field:ident: $type:ty,
2147 )*
2148 }
2149 } => {
2150 $crate::paste::paste! {
2151 use $crate::serde as [< __opaque_keys_serde_import__ $name >];
2152
2153 $crate::impl_opaque_keys_inner! {
2154 $( #[ $attr ] )*
2155 #[derive($crate::serde::Serialize, $crate::serde::Deserialize)]
2156 #[serde(crate = "__opaque_keys_serde_import__" $name)]
2157 pub struct $name {
2158 $(
2159 $( #[ $inner_attr ] )*
2160 pub $field: $type,
2161 )*
2162 }
2163 }
2164 }
2165 }
2166}
2167
2168#[macro_export]
2169#[cfg(all(not(feature = "std"), not(feature = "serde")))]
2170#[doc(hidden)]
2171macro_rules! impl_opaque_keys {
2172 {
2173 $( #[ $attr:meta ] )*
2174 pub struct $name:ident {
2175 $(
2176 $( #[ $inner_attr:meta ] )*
2177 pub $field:ident: $type:ty,
2178 )*
2179 }
2180 } => {
2181 $crate::impl_opaque_keys_inner! {
2182 $( #[ $attr ] )*
2183 pub struct $name {
2184 $(
2185 $( #[ $inner_attr ] )*
2186 pub $field: $type,
2187 )*
2188 }
2189 }
2190 }
2191}
2192
2193pub trait Printable {
2195 fn print(&self);
2197}
2198
2199impl<T: Printable> Printable for &T {
2200 fn print(&self) {
2201 (*self).print()
2202 }
2203}
2204
2205impl Printable for u8 {
2206 fn print(&self) {
2207 (*self as u64).print()
2208 }
2209}
2210
2211impl Printable for u32 {
2212 fn print(&self) {
2213 (*self as u64).print()
2214 }
2215}
2216
2217impl Printable for usize {
2218 fn print(&self) {
2219 (*self as u64).print()
2220 }
2221}
2222
2223impl Printable for u64 {
2224 fn print(&self) {
2225 sp_io::misc::print_num(*self);
2226 }
2227}
2228
2229impl Printable for &[u8] {
2230 fn print(&self) {
2231 sp_io::misc::print_hex(self);
2232 }
2233}
2234
2235impl<const N: usize> Printable for [u8; N] {
2236 fn print(&self) {
2237 sp_io::misc::print_hex(&self[..]);
2238 }
2239}
2240
2241impl Printable for &str {
2242 fn print(&self) {
2243 sp_io::misc::print_utf8(self.as_bytes());
2244 }
2245}
2246
2247impl Printable for bool {
2248 fn print(&self) {
2249 if *self {
2250 "true".print()
2251 } else {
2252 "false".print()
2253 }
2254 }
2255}
2256
2257impl Printable for sp_weights::Weight {
2258 fn print(&self) {
2259 self.ref_time().print()
2260 }
2261}
2262
2263impl Printable for () {
2264 fn print(&self) {
2265 "()".print()
2266 }
2267}
2268
2269#[impl_for_tuples(1, 12)]
2270impl Printable for Tuple {
2271 fn print(&self) {
2272 for_tuples!( #( Tuple.print(); )* )
2273 }
2274}
2275
2276#[cfg(feature = "std")]
2278pub trait BlockIdTo<Block: self::Block> {
2279 type Error: std::error::Error;
2281
2282 fn to_hash(
2284 &self,
2285 block_id: &crate::generic::BlockId<Block>,
2286 ) -> Result<Option<Block::Hash>, Self::Error>;
2287
2288 fn to_number(
2290 &self,
2291 block_id: &crate::generic::BlockId<Block>,
2292 ) -> Result<Option<NumberFor<Block>>, Self::Error>;
2293}
2294
2295pub trait BlockNumberProvider {
2297 type BlockNumber: Codec
2299 + Clone
2300 + Ord
2301 + Eq
2302 + AtLeast32BitUnsigned
2303 + TypeInfo
2304 + Debug
2305 + MaxEncodedLen
2306 + Copy;
2307
2308 fn current_block_number() -> Self::BlockNumber;
2324
2325 #[cfg(any(feature = "std", feature = "runtime-benchmarks"))]
2331 fn set_block_number(_block: Self::BlockNumber) {}
2332}
2333
2334impl BlockNumberProvider for () {
2335 type BlockNumber = u32;
2336 fn current_block_number() -> Self::BlockNumber {
2337 0
2338 }
2339}
2340
2341#[cfg(test)]
2342mod tests {
2343 use super::*;
2344 use crate::codec::{Decode, Encode, Input};
2345 use sp_core::{
2346 crypto::{Pair, UncheckedFrom},
2347 ecdsa, ed25519, sr25519,
2348 };
2349
2350 macro_rules! signature_verify_test {
2351 ($algorithm:ident) => {
2352 let msg = &b"test-message"[..];
2353 let wrong_msg = &b"test-msg"[..];
2354 let (pair, _) = $algorithm::Pair::generate();
2355
2356 let signature = pair.sign(&msg);
2357 assert!($algorithm::Pair::verify(&signature, msg, &pair.public()));
2358
2359 assert!(signature.verify(msg, &pair.public()));
2360 assert!(!signature.verify(wrong_msg, &pair.public()));
2361 };
2362 }
2363
2364 mod t {
2365 use sp_application_crypto::{app_crypto, sr25519};
2366 use sp_core::crypto::KeyTypeId;
2367 app_crypto!(sr25519, KeyTypeId(*b"test"));
2368 }
2369
2370 #[test]
2371 fn app_verify_works() {
2372 use super::AppVerify;
2373 use t::*;
2374
2375 let s = Signature::try_from(vec![0; 64]).unwrap();
2376 let _ = s.verify(&[0u8; 100][..], &Public::unchecked_from([0; 32]));
2377 }
2378
2379 #[derive(Encode, Decode, Default, PartialEq, Debug)]
2380 struct U128Value(u128);
2381 impl super::TypeId for U128Value {
2382 const TYPE_ID: [u8; 4] = [0x0d, 0xf0, 0x0d, 0xf0];
2383 }
2384 #[derive(Encode, Decode, Default, PartialEq, Debug)]
2387 struct U32Value(u32);
2388 impl super::TypeId for U32Value {
2389 const TYPE_ID: [u8; 4] = [0x0d, 0xf0, 0xfe, 0xca];
2390 }
2391 #[derive(Encode, Decode, Default, PartialEq, Debug)]
2394 struct U16Value(u16);
2395 impl super::TypeId for U16Value {
2396 const TYPE_ID: [u8; 4] = [0xfe, 0xca, 0x0d, 0xf0];
2397 }
2398 type AccountId = u64;
2401
2402 #[test]
2403 fn into_account_truncating_should_work() {
2404 let r: AccountId = U32Value::into_account_truncating(&U32Value(0xdeadbeef));
2405 assert_eq!(r, 0x_deadbeef_cafef00d);
2406 }
2407
2408 #[test]
2409 fn try_into_account_should_work() {
2410 let r: AccountId = U32Value::try_into_account(&U32Value(0xdeadbeef)).unwrap();
2411 assert_eq!(r, 0x_deadbeef_cafef00d);
2412
2413 let maybe: Option<AccountId> = U128Value::try_into_account(&U128Value(u128::MAX));
2415 assert!(maybe.is_none());
2416 }
2417
2418 #[test]
2419 fn try_from_account_should_work() {
2420 let r = U32Value::try_from_account(&0x_deadbeef_cafef00d_u64);
2421 assert_eq!(r.unwrap(), U32Value(0xdeadbeef));
2422 }
2423
2424 #[test]
2425 fn into_account_truncating_with_fill_should_work() {
2426 let r: AccountId = U16Value::into_account_truncating(&U16Value(0xc0da));
2427 assert_eq!(r, 0x_0000_c0da_f00dcafe);
2428 }
2429
2430 #[test]
2431 fn try_into_sub_account_should_work() {
2432 let r: AccountId = U16Value::try_into_account(&U16Value(0xc0da)).unwrap();
2433 assert_eq!(r, 0x_0000_c0da_f00dcafe);
2434
2435 let maybe: Option<AccountId> = U16Value::try_into_sub_account(
2436 &U16Value(0xc0da),
2437 "a really large amount of additional encoded information which will certainly overflow the account id type ;)"
2438 );
2439
2440 assert!(maybe.is_none())
2441 }
2442
2443 #[test]
2444 fn try_from_account_with_fill_should_work() {
2445 let r = U16Value::try_from_account(&0x0000_c0da_f00dcafe_u64);
2446 assert_eq!(r.unwrap(), U16Value(0xc0da));
2447 }
2448
2449 #[test]
2450 fn bad_try_from_account_should_fail() {
2451 let r = U16Value::try_from_account(&0x0000_c0de_baadcafe_u64);
2452 assert!(r.is_none());
2453 let r = U16Value::try_from_account(&0x0100_c0da_f00dcafe_u64);
2454 assert!(r.is_none());
2455 }
2456
2457 #[test]
2458 fn trailing_zero_should_work() {
2459 let mut t = super::TrailingZeroInput(&[1, 2, 3]);
2460 assert_eq!(t.remaining_len(), Ok(None));
2461 let mut buffer = [0u8; 2];
2462 assert_eq!(t.read(&mut buffer), Ok(()));
2463 assert_eq!(t.remaining_len(), Ok(None));
2464 assert_eq!(buffer, [1, 2]);
2465 assert_eq!(t.read(&mut buffer), Ok(()));
2466 assert_eq!(t.remaining_len(), Ok(None));
2467 assert_eq!(buffer, [3, 0]);
2468 assert_eq!(t.read(&mut buffer), Ok(()));
2469 assert_eq!(t.remaining_len(), Ok(None));
2470 assert_eq!(buffer, [0, 0]);
2471 }
2472
2473 #[test]
2474 fn ed25519_verify_works() {
2475 signature_verify_test!(ed25519);
2476 }
2477
2478 #[test]
2479 fn sr25519_verify_works() {
2480 signature_verify_test!(sr25519);
2481 }
2482
2483 #[test]
2484 fn ecdsa_verify_works() {
2485 signature_verify_test!(ecdsa);
2486 }
2487}