1use crate::{
21 generic::Digest,
22 scale_info::{StaticTypeInfo, TypeInfo},
23 transaction_validity::{
24 TransactionSource, TransactionValidity, TransactionValidityError, UnknownTransaction,
25 ValidTransaction,
26 },
27 DispatchResult,
28};
29use alloc::vec::Vec;
30use codec::{
31 Codec, Decode, DecodeWithMemTracking, Encode, EncodeLike, FullCodec, HasCompact, MaxEncodedLen,
32};
33#[doc(hidden)]
34pub use core::{fmt::Debug, marker::PhantomData};
35use impl_trait_for_tuples::impl_for_tuples;
36#[cfg(feature = "serde")]
37use serde::{de::DeserializeOwned, Deserialize, Serialize};
38use sp_application_crypto::AppCrypto;
39pub use sp_arithmetic::traits::{
40 checked_pow, ensure_pow, AtLeast32Bit, AtLeast32BitUnsigned, Bounded, CheckedAdd, CheckedDiv,
41 CheckedMul, CheckedShl, CheckedShr, CheckedSub, Ensure, EnsureAdd, EnsureAddAssign, EnsureDiv,
42 EnsureDivAssign, EnsureFixedPointNumber, EnsureFrom, EnsureInto, EnsureMul, EnsureMulAssign,
43 EnsureOp, EnsureOpAssign, EnsureSub, EnsureSubAssign, IntegerSquareRoot, One,
44 SaturatedConversion, Saturating, UniqueSaturatedFrom, UniqueSaturatedInto, Zero,
45};
46use sp_core::{self, storage::StateVersion, Hasher, RuntimeDebug, TypeId, U256};
47#[doc(hidden)]
48pub use sp_core::{
49 parameter_types, ConstBool, ConstI128, ConstI16, ConstI32, ConstI64, ConstI8, ConstInt,
50 ConstU128, ConstU16, ConstU32, ConstU64, ConstU8, ConstUint, Get, GetDefault, TryCollect,
51 TypedGet,
52};
53#[cfg(feature = "std")]
54use std::fmt::Display;
55#[cfg(feature = "std")]
56use std::str::FromStr;
57
58pub mod transaction_extension;
59pub use transaction_extension::{
60 DispatchTransaction, Implication, ImplicationParts, TransactionExtension,
61 TransactionExtensionMetadata, TxBaseImplication, ValidateResult,
62};
63
64pub trait Lazy<T: ?Sized> {
66 fn get(&mut self) -> &T;
70}
71
72impl<'a> Lazy<[u8]> for &'a [u8] {
73 fn get(&mut self) -> &[u8] {
74 self
75 }
76}
77
78pub trait IdentifyAccount {
81 type AccountId;
83 fn into_account(self) -> Self::AccountId;
85}
86
87impl IdentifyAccount for sp_core::ed25519::Public {
88 type AccountId = Self;
89 fn into_account(self) -> Self {
90 self
91 }
92}
93
94impl IdentifyAccount for sp_core::sr25519::Public {
95 type AccountId = Self;
96 fn into_account(self) -> Self {
97 self
98 }
99}
100
101impl IdentifyAccount for sp_core::ecdsa::Public {
102 type AccountId = Self;
103 fn into_account(self) -> Self {
104 self
105 }
106}
107
108pub trait Verify {
110 type Signer: IdentifyAccount;
112 fn verify<L: Lazy<[u8]>>(
116 &self,
117 msg: L,
118 signer: &<Self::Signer as IdentifyAccount>::AccountId,
119 ) -> bool;
120}
121
122impl Verify for sp_core::ed25519::Signature {
123 type Signer = sp_core::ed25519::Public;
124
125 fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &sp_core::ed25519::Public) -> bool {
126 sp_io::crypto::ed25519_verify(self, msg.get(), signer)
127 }
128}
129
130impl Verify for sp_core::sr25519::Signature {
131 type Signer = sp_core::sr25519::Public;
132
133 fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &sp_core::sr25519::Public) -> bool {
134 sp_io::crypto::sr25519_verify(self, msg.get(), signer)
135 }
136}
137
138impl Verify for sp_core::ecdsa::Signature {
139 type Signer = sp_core::ecdsa::Public;
140 fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &sp_core::ecdsa::Public) -> bool {
141 match sp_io::crypto::secp256k1_ecdsa_recover_compressed(
142 self.as_ref(),
143 &sp_io::hashing::blake2_256(msg.get()),
144 ) {
145 Ok(pubkey) => signer.0 == pubkey,
146 _ => false,
147 }
148 }
149}
150
151pub trait AppVerify {
153 type AccountId;
155 fn verify<L: Lazy<[u8]>>(&self, msg: L, signer: &Self::AccountId) -> bool;
157}
158
159impl<
160 S: Verify<Signer = <<T as AppCrypto>::Public as sp_application_crypto::AppPublic>::Generic>
161 + From<T>,
162 T: sp_application_crypto::Wraps<Inner = S>
163 + sp_application_crypto::AppCrypto
164 + sp_application_crypto::AppSignature
165 + AsRef<S>
166 + AsMut<S>
167 + From<S>,
168 > AppVerify for T
169where
170 <S as Verify>::Signer: IdentifyAccount<AccountId = <S as Verify>::Signer>,
171 <<T as AppCrypto>::Public as sp_application_crypto::AppPublic>::Generic: IdentifyAccount<
172 AccountId = <<T as AppCrypto>::Public as sp_application_crypto::AppPublic>::Generic,
173 >,
174{
175 type AccountId = <T as AppCrypto>::Public;
176 fn verify<L: Lazy<[u8]>>(&self, msg: L, signer: &<T as AppCrypto>::Public) -> bool {
177 use sp_application_crypto::IsWrappedBy;
178 let inner: &S = self.as_ref();
179 let inner_pubkey =
180 <<T as AppCrypto>::Public as sp_application_crypto::AppPublic>::Generic::from_ref(
181 signer,
182 );
183 Verify::verify(inner, msg, inner_pubkey)
184 }
185}
186
187#[derive(Encode, Decode, RuntimeDebug)]
189pub struct BadOrigin;
190
191impl From<BadOrigin> for &'static str {
192 fn from(_: BadOrigin) -> &'static str {
193 "Bad origin"
194 }
195}
196
197#[derive(Encode, Decode, RuntimeDebug)]
199pub struct LookupError;
200
201impl From<LookupError> for &'static str {
202 fn from(_: LookupError) -> &'static str {
203 "Can not lookup"
204 }
205}
206
207impl From<LookupError> for TransactionValidityError {
208 fn from(_: LookupError) -> Self {
209 UnknownTransaction::CannotLookup.into()
210 }
211}
212
213pub trait Lookup {
215 type Source;
217 type Target;
219 fn lookup(&self, s: Self::Source) -> Result<Self::Target, LookupError>;
221}
222
223pub trait StaticLookup {
227 type Source: Codec + Clone + PartialEq + Debug + TypeInfo;
229 type Target;
231 fn lookup(s: Self::Source) -> Result<Self::Target, LookupError>;
233 fn unlookup(t: Self::Target) -> Self::Source;
235}
236
237#[derive(Clone, Copy, PartialEq, Eq)]
239pub struct IdentityLookup<T>(PhantomData<T>);
240impl<T> Default for IdentityLookup<T> {
241 fn default() -> Self {
242 Self(PhantomData::<T>::default())
243 }
244}
245
246impl<T: Codec + Clone + PartialEq + Debug + TypeInfo> StaticLookup for IdentityLookup<T> {
247 type Source = T;
248 type Target = T;
249 fn lookup(x: T) -> Result<T, LookupError> {
250 Ok(x)
251 }
252 fn unlookup(x: T) -> T {
253 x
254 }
255}
256
257impl<T> Lookup for IdentityLookup<T> {
258 type Source = T;
259 type Target = T;
260 fn lookup(&self, x: T) -> Result<T, LookupError> {
261 Ok(x)
262 }
263}
264
265pub struct AccountIdLookup<AccountId, AccountIndex>(PhantomData<(AccountId, AccountIndex)>);
267impl<AccountId, AccountIndex> StaticLookup for AccountIdLookup<AccountId, AccountIndex>
268where
269 AccountId: Codec + Clone + PartialEq + Debug,
270 AccountIndex: Codec + Clone + PartialEq + Debug,
271 crate::MultiAddress<AccountId, AccountIndex>: Codec + StaticTypeInfo,
272{
273 type Source = crate::MultiAddress<AccountId, AccountIndex>;
274 type Target = AccountId;
275 fn lookup(x: Self::Source) -> Result<Self::Target, LookupError> {
276 match x {
277 crate::MultiAddress::Id(i) => Ok(i),
278 _ => Err(LookupError),
279 }
280 }
281 fn unlookup(x: Self::Target) -> Self::Source {
282 crate::MultiAddress::Id(x)
283 }
284}
285
286impl<A, B> StaticLookup for (A, B)
288where
289 A: StaticLookup,
290 B: StaticLookup<Source = A::Source, Target = A::Target>,
291{
292 type Source = A::Source;
293 type Target = A::Target;
294
295 fn lookup(x: Self::Source) -> Result<Self::Target, LookupError> {
296 A::lookup(x.clone()).or_else(|_| B::lookup(x))
297 }
298 fn unlookup(x: Self::Target) -> Self::Source {
299 A::unlookup(x)
300 }
301}
302
303pub trait Morph<A> {
306 type Outcome;
308
309 fn morph(a: A) -> Self::Outcome;
311}
312
313impl<T> Morph<T> for Identity {
315 type Outcome = T;
316 fn morph(a: T) -> T {
317 a
318 }
319}
320
321pub trait TryMorph<A> {
324 type Outcome;
326
327 fn try_morph(a: A) -> Result<Self::Outcome, ()>;
329}
330
331impl<T> TryMorph<T> for Identity {
333 type Outcome = T;
334 fn try_morph(a: T) -> Result<T, ()> {
335 Ok(a)
336 }
337}
338
339pub struct MorphInto<T>(core::marker::PhantomData<T>);
341impl<T, A: Into<T>> Morph<A> for MorphInto<T> {
342 type Outcome = T;
343 fn morph(a: A) -> T {
344 a.into()
345 }
346}
347
348pub struct TryMorphInto<T>(core::marker::PhantomData<T>);
350impl<T, A: TryInto<T>> TryMorph<A> for TryMorphInto<T> {
351 type Outcome = T;
352 fn try_morph(a: A) -> Result<T, ()> {
353 a.try_into().map_err(|_| ())
354 }
355}
356
357pub struct TakeFirst;
359impl<T1> Morph<(T1,)> for TakeFirst {
360 type Outcome = T1;
361 fn morph(a: (T1,)) -> T1 {
362 a.0
363 }
364}
365impl<T1, T2> Morph<(T1, T2)> for TakeFirst {
366 type Outcome = T1;
367 fn morph(a: (T1, T2)) -> T1 {
368 a.0
369 }
370}
371impl<T1, T2, T3> Morph<(T1, T2, T3)> for TakeFirst {
372 type Outcome = T1;
373 fn morph(a: (T1, T2, T3)) -> T1 {
374 a.0
375 }
376}
377impl<T1, T2, T3, T4> Morph<(T1, T2, T3, T4)> for TakeFirst {
378 type Outcome = T1;
379 fn morph(a: (T1, T2, T3, T4)) -> T1 {
380 a.0
381 }
382}
383
384#[macro_export]
420macro_rules! morph_types {
421 (
422 @DECL $( #[doc = $doc:expr] )* $vq:vis $name:ident ()
423 ) => {
424 $( #[doc = $doc] )* $vq struct $name;
425 };
426 (
427 @DECL $( #[doc = $doc:expr] )* $vq:vis $name:ident ( $( $bound_id:ident ),+ )
428 ) => {
429 $( #[doc = $doc] )*
430 $vq struct $name < $($bound_id,)* > ( $crate::traits::PhantomData< ( $($bound_id,)* ) > ) ;
431 };
432 (
433 @IMPL $name:ty : ( $( $bounds:tt )* ) ( $( $where:tt )* )
434 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
435 ) => {
436 impl<$($bounds)*> $crate::traits::Morph<$var_type> for $name $( $where )? {
437 type Outcome = $outcome;
438 fn morph($var: $var_type) -> Self::Outcome { $( $ex )* }
439 }
440 };
441 (
442 @IMPL_TRY $name:ty : ( $( $bounds:tt )* ) ( $( $where:tt )* )
443 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
444 ) => {
445 impl<$($bounds)*> $crate::traits::TryMorph<$var_type> for $name $( $where )? {
446 type Outcome = $outcome;
447 fn try_morph($var: $var_type) -> Result<Self::Outcome, ()> { $( $ex )* }
448 }
449 };
450 (
451 @IMPL $name:ty : () ( $( $where:tt )* )
452 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
453 ) => {
454 impl $crate::traits::Morph<$var_type> for $name $( $where )? {
455 type Outcome = $outcome;
456 fn morph($var: $var_type) -> Self::Outcome { $( $ex )* }
457 }
458 };
459 (
460 @IMPL_TRY $name:ty : () ( $( $where:tt )* )
461 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
462 ) => {
463 impl $crate::traits::TryMorph<$var_type> for $name $( $where )? {
464 type Outcome = $outcome;
465 fn try_morph($var: $var_type) -> Result<Self::Outcome, ()> { $( $ex )* }
466 }
467 };
468 (
469 @IMPL_BOTH $name:ty : ( $( $bounds:tt )* ) ( $( $where:tt )* )
470 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
471 ) => {
472 morph_types! {
473 @IMPL $name : ($($bounds)*) ($($where)*)
474 = |$var: $var_type| -> $outcome { $( $ex )* }
475 }
476 morph_types! {
477 @IMPL_TRY $name : ($($bounds)*) ($($where)*)
478 = |$var: $var_type| -> $outcome { Ok({$( $ex )*}) }
479 }
480 };
481
482 (
483 $( #[doc = $doc:expr] )* $vq:vis type $name:ident
484 $( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
485 $(: $type:tt)?
486 = |_| -> $outcome:ty { $( $ex:expr )* };
487 $( $rest:tt )*
488 ) => {
489 morph_types! {
490 $( #[doc = $doc] )* $vq type $name
491 $( < $( $bound_id $( : $bound_head $( | $bound_tail )* )? ),+ > )?
492 EXTRA_GENERIC(X)
493 $(: $type)?
494 = |_x: X| -> $outcome { $( $ex )* };
495 $( $rest )*
496 }
497 };
498 (
499 $( #[doc = $doc:expr] )* $vq:vis type $name:ident
500 $( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
501 $( EXTRA_GENERIC ($extra:ident) )?
502 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
503 $( where $( $where_path:ty : $where_bound_head:path $( | $where_bound_tail:path )* ),* )?;
504 $( $rest:tt )*
505 ) => {
506 morph_types! { @DECL $( #[doc = $doc] )* $vq $name ( $( $( $bound_id ),+ )? ) }
507 morph_types! {
508 @IMPL_BOTH $name $( < $( $bound_id ),* > )? :
509 ( $( $( $bound_id $( : $bound_head $( + $bound_tail )* )? , )+ )? $( $extra )? )
510 ( $( where $( $where_path : $where_bound_head $( + $where_bound_tail )* ),* )? )
511 = |$var: $var_type| -> $outcome { $( $ex )* }
512 }
513 morph_types!{ $($rest)* }
514 };
515 (
516 $( #[doc = $doc:expr] )* $vq:vis type $name:ident
517 $( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
518 $( EXTRA_GENERIC ($extra:ident) )?
519 : Morph
520 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
521 $( where $( $where_path:ty : $where_bound_head:path $( | $where_bound_tail:path )* ),* )?;
522 $( $rest:tt )*
523 ) => {
524 morph_types! { @DECL $( #[doc = $doc] )* $vq $name ( $( $( $bound_id ),+ )? ) }
525 morph_types! {
526 @IMPL $name $( < $( $bound_id ),* > )? :
527 ( $( $( $bound_id $( : $bound_head $( + $bound_tail )* )? , )+ )? $( $extra )? )
528 ( $( where $( $where_path : $where_bound_head $( + $where_bound_tail )* ),* )? )
529 = |$var: $var_type| -> $outcome { $( $ex )* }
530 }
531 morph_types!{ $($rest)* }
532 };
533 (
534 $( #[doc = $doc:expr] )* $vq:vis type $name:ident
535 $( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
536 $( EXTRA_GENERIC ($extra:ident) )?
537 : TryMorph
538 = |$var:ident: $var_type:ty| -> Result<$outcome:ty, ()> { $( $ex:expr )* }
539 $( where $( $where_path:ty : $where_bound_head:path $( | $where_bound_tail:path )* ),* )?;
540 $( $rest:tt )*
541 ) => {
542 morph_types! { @DECL $( #[doc = $doc] )* $vq $name ( $( $( $bound_id ),+ )? ) }
543 morph_types! {
544 @IMPL_TRY $name $( < $( $bound_id ),* > )? :
545 ( $( $( $bound_id $( : $bound_head $( + $bound_tail )* )? , )+ )? $( $extra )? )
546 ( $( where $( $where_path : $where_bound_head $( + $where_bound_tail )* ),* )? )
547 = |$var: $var_type| -> $outcome { $( $ex )* }
548 }
549 morph_types!{ $($rest)* }
550 };
551 () => {}
552}
553
554morph_types! {
555 pub type Replace<V: TypedGet> = |_| -> V::Type { V::get() };
557
558 pub type ReplaceWithDefault<V: Default> = |_| -> V { Default::default() };
560
561 pub type ReduceBy<N: TypedGet> = |r: N::Type| -> N::Type {
563 r.checked_sub(&N::get()).unwrap_or(Zero::zero())
564 } where N::Type: CheckedSub | Zero;
565
566 pub type CheckedReduceBy<N: TypedGet>: TryMorph = |r: N::Type| -> Result<N::Type, ()> {
569 r.checked_sub(&N::get()).ok_or(())
570 } where N::Type: CheckedSub;
571
572 pub type MorphWithUpperLimit<L: TypedGet, M>: TryMorph = |r: L::Type| -> Result<L::Type, ()> {
574 M::try_morph(r).map(|m| m.min(L::get()))
575 } where L::Type: Ord, M: TryMorph<L::Type, Outcome = L::Type>;
576}
577
578pub trait Convert<A, B> {
580 fn convert(a: A) -> B;
582}
583
584impl<A, B: Default> Convert<A, B> for () {
585 fn convert(_: A) -> B {
586 Default::default()
587 }
588}
589
590pub trait ConvertBack<A, B>: Convert<A, B> {
594 fn convert_back(b: B) -> A;
596}
597
598pub trait MaybeConvert<A, B> {
600 fn maybe_convert(a: A) -> Option<B>;
602}
603
604#[impl_trait_for_tuples::impl_for_tuples(30)]
605impl<A: Clone, B> MaybeConvert<A, B> for Tuple {
606 fn maybe_convert(a: A) -> Option<B> {
607 for_tuples!( #(
608 match Tuple::maybe_convert(a.clone()) {
609 Some(b) => return Some(b),
610 None => {},
611 }
612 )* );
613 None
614 }
615}
616
617pub trait MaybeConvertBack<A, B>: MaybeConvert<A, B> {
620 fn maybe_convert_back(b: B) -> Option<A>;
622}
623
624#[impl_trait_for_tuples::impl_for_tuples(30)]
625impl<A: Clone, B: Clone> MaybeConvertBack<A, B> for Tuple {
626 fn maybe_convert_back(b: B) -> Option<A> {
627 for_tuples!( #(
628 match Tuple::maybe_convert_back(b.clone()) {
629 Some(a) => return Some(a),
630 None => {},
631 }
632 )* );
633 None
634 }
635}
636
637pub trait TryConvert<A, B> {
640 fn try_convert(a: A) -> Result<B, A>;
642}
643
644#[impl_trait_for_tuples::impl_for_tuples(30)]
645impl<A, B> TryConvert<A, B> for Tuple {
646 fn try_convert(a: A) -> Result<B, A> {
647 for_tuples!( #(
648 let a = match Tuple::try_convert(a) {
649 Ok(b) => return Ok(b),
650 Err(a) => a,
651 };
652 )* );
653 Err(a)
654 }
655}
656
657pub trait TryConvertBack<A, B>: TryConvert<A, B> {
660 fn try_convert_back(b: B) -> Result<A, B>;
663}
664
665#[impl_trait_for_tuples::impl_for_tuples(30)]
666impl<A, B> TryConvertBack<A, B> for Tuple {
667 fn try_convert_back(b: B) -> Result<A, B> {
668 for_tuples!( #(
669 let b = match Tuple::try_convert_back(b) {
670 Ok(a) => return Ok(a),
671 Err(b) => b,
672 };
673 )* );
674 Err(b)
675 }
676}
677
678pub trait MaybeEquivalence<A, B> {
680 fn convert(a: &A) -> Option<B>;
682 fn convert_back(b: &B) -> Option<A>;
684}
685
686#[impl_trait_for_tuples::impl_for_tuples(30)]
687impl<A, B> MaybeEquivalence<A, B> for Tuple {
688 fn convert(a: &A) -> Option<B> {
689 for_tuples!( #(
690 match Tuple::convert(a) {
691 Some(b) => return Some(b),
692 None => {},
693 }
694 )* );
695 None
696 }
697 fn convert_back(b: &B) -> Option<A> {
698 for_tuples!( #(
699 match Tuple::convert_back(b) {
700 Some(a) => return Some(a),
701 None => {},
702 }
703 )* );
704 None
705 }
706}
707
708pub struct ConvertToValue<T>(core::marker::PhantomData<T>);
711impl<X, Y, T: Get<Y>> Convert<X, Y> for ConvertToValue<T> {
712 fn convert(_: X) -> Y {
713 T::get()
714 }
715}
716impl<X, Y, T: Get<Y>> MaybeConvert<X, Y> for ConvertToValue<T> {
717 fn maybe_convert(_: X) -> Option<Y> {
718 Some(T::get())
719 }
720}
721impl<X, Y, T: Get<Y>> MaybeConvertBack<X, Y> for ConvertToValue<T> {
722 fn maybe_convert_back(_: Y) -> Option<X> {
723 None
724 }
725}
726impl<X, Y, T: Get<Y>> TryConvert<X, Y> for ConvertToValue<T> {
727 fn try_convert(_: X) -> Result<Y, X> {
728 Ok(T::get())
729 }
730}
731impl<X, Y, T: Get<Y>> TryConvertBack<X, Y> for ConvertToValue<T> {
732 fn try_convert_back(y: Y) -> Result<X, Y> {
733 Err(y)
734 }
735}
736impl<X, Y, T: Get<Y>> MaybeEquivalence<X, Y> for ConvertToValue<T> {
737 fn convert(_: &X) -> Option<Y> {
738 Some(T::get())
739 }
740 fn convert_back(_: &Y) -> Option<X> {
741 None
742 }
743}
744
745pub struct Identity;
747impl<T> Convert<T, T> for Identity {
748 fn convert(a: T) -> T {
749 a
750 }
751}
752impl<T> ConvertBack<T, T> for Identity {
753 fn convert_back(a: T) -> T {
754 a
755 }
756}
757impl<T> MaybeConvert<T, T> for Identity {
758 fn maybe_convert(a: T) -> Option<T> {
759 Some(a)
760 }
761}
762impl<T> MaybeConvertBack<T, T> for Identity {
763 fn maybe_convert_back(a: T) -> Option<T> {
764 Some(a)
765 }
766}
767impl<T> TryConvert<T, T> for Identity {
768 fn try_convert(a: T) -> Result<T, T> {
769 Ok(a)
770 }
771}
772impl<T> TryConvertBack<T, T> for Identity {
773 fn try_convert_back(a: T) -> Result<T, T> {
774 Ok(a)
775 }
776}
777impl<T: Clone> MaybeEquivalence<T, T> for Identity {
778 fn convert(a: &T) -> Option<T> {
779 Some(a.clone())
780 }
781 fn convert_back(a: &T) -> Option<T> {
782 Some(a.clone())
783 }
784}
785
786pub struct ConvertInto;
788impl<A: Into<B>, B> Convert<A, B> for ConvertInto {
789 fn convert(a: A) -> B {
790 a.into()
791 }
792}
793impl<A: Into<B>, B> MaybeConvert<A, B> for ConvertInto {
794 fn maybe_convert(a: A) -> Option<B> {
795 Some(a.into())
796 }
797}
798impl<A: Into<B>, B: Into<A>> MaybeConvertBack<A, B> for ConvertInto {
799 fn maybe_convert_back(b: B) -> Option<A> {
800 Some(b.into())
801 }
802}
803impl<A: Into<B>, B> TryConvert<A, B> for ConvertInto {
804 fn try_convert(a: A) -> Result<B, A> {
805 Ok(a.into())
806 }
807}
808impl<A: Into<B>, B: Into<A>> TryConvertBack<A, B> for ConvertInto {
809 fn try_convert_back(b: B) -> Result<A, B> {
810 Ok(b.into())
811 }
812}
813impl<A: Clone + Into<B>, B: Clone + Into<A>> MaybeEquivalence<A, B> for ConvertInto {
814 fn convert(a: &A) -> Option<B> {
815 Some(a.clone().into())
816 }
817 fn convert_back(b: &B) -> Option<A> {
818 Some(b.clone().into())
819 }
820}
821
822pub struct TryConvertInto;
824impl<A: Clone + TryInto<B>, B> MaybeConvert<A, B> for TryConvertInto {
825 fn maybe_convert(a: A) -> Option<B> {
826 a.clone().try_into().ok()
827 }
828}
829impl<A: Clone + TryInto<B>, B: Clone + TryInto<A>> MaybeConvertBack<A, B> for TryConvertInto {
830 fn maybe_convert_back(b: B) -> Option<A> {
831 b.clone().try_into().ok()
832 }
833}
834impl<A: Clone + TryInto<B>, B> TryConvert<A, B> for TryConvertInto {
835 fn try_convert(a: A) -> Result<B, A> {
836 a.clone().try_into().map_err(|_| a)
837 }
838}
839impl<A: Clone + TryInto<B>, B: Clone + TryInto<A>> TryConvertBack<A, B> for TryConvertInto {
840 fn try_convert_back(b: B) -> Result<A, B> {
841 b.clone().try_into().map_err(|_| b)
842 }
843}
844impl<A: Clone + TryInto<B>, B: Clone + TryInto<A>> MaybeEquivalence<A, B> for TryConvertInto {
845 fn convert(a: &A) -> Option<B> {
846 a.clone().try_into().ok()
847 }
848 fn convert_back(b: &B) -> Option<A> {
849 b.clone().try_into().ok()
850 }
851}
852
853pub trait CheckedConversion {
857 fn checked_from<T>(t: T) -> Option<Self>
863 where
864 Self: TryFrom<T>,
865 {
866 <Self as TryFrom<T>>::try_from(t).ok()
867 }
868 fn checked_into<T>(self) -> Option<T>
874 where
875 Self: TryInto<T>,
876 {
877 <Self as TryInto<T>>::try_into(self).ok()
878 }
879}
880impl<T: Sized> CheckedConversion for T {}
881
882pub trait Scale<Other> {
885 type Output;
887
888 fn mul(self, other: Other) -> Self::Output;
890
891 fn div(self, other: Other) -> Self::Output;
893
894 fn rem(self, other: Other) -> Self::Output;
896}
897macro_rules! impl_scale {
898 ($self:ty, $other:ty) => {
899 impl Scale<$other> for $self {
900 type Output = Self;
901 fn mul(self, other: $other) -> Self::Output {
902 self * (other as Self)
903 }
904 fn div(self, other: $other) -> Self::Output {
905 self / (other as Self)
906 }
907 fn rem(self, other: $other) -> Self::Output {
908 self % (other as Self)
909 }
910 }
911 };
912}
913impl_scale!(u128, u128);
914impl_scale!(u128, u64);
915impl_scale!(u128, u32);
916impl_scale!(u128, u16);
917impl_scale!(u128, u8);
918impl_scale!(u64, u64);
919impl_scale!(u64, u32);
920impl_scale!(u64, u16);
921impl_scale!(u64, u8);
922impl_scale!(u32, u32);
923impl_scale!(u32, u16);
924impl_scale!(u32, u8);
925impl_scale!(u16, u16);
926impl_scale!(u16, u8);
927impl_scale!(u8, u8);
928
929pub trait Clear {
932 fn is_clear(&self) -> bool;
934
935 fn clear() -> Self;
937}
938
939impl<T: Default + Eq + PartialEq> Clear for T {
940 fn is_clear(&self) -> bool {
941 *self == Self::clear()
942 }
943 fn clear() -> Self {
944 Default::default()
945 }
946}
947
948pub trait SimpleBitOps:
950 Sized
951 + Clear
952 + core::ops::BitOr<Self, Output = Self>
953 + core::ops::BitXor<Self, Output = Self>
954 + core::ops::BitAnd<Self, Output = Self>
955{
956}
957impl<
958 T: Sized
959 + Clear
960 + core::ops::BitOr<Self, Output = Self>
961 + core::ops::BitXor<Self, Output = Self>
962 + core::ops::BitAnd<Self, Output = Self>,
963 > SimpleBitOps for T
964{
965}
966
967pub trait Hash:
971 'static
972 + MaybeSerializeDeserialize
973 + Debug
974 + Clone
975 + Eq
976 + PartialEq
977 + Hasher<Out = <Self as Hash>::Output>
978{
979 type Output: HashOutput;
981
982 fn hash(s: &[u8]) -> Self::Output {
984 <Self as Hasher>::hash(s)
985 }
986
987 fn hash_of<S: Encode>(s: &S) -> Self::Output {
989 Encode::using_encoded(s, <Self as Hasher>::hash)
990 }
991
992 fn ordered_trie_root(input: Vec<Vec<u8>>, state_version: StateVersion) -> Self::Output;
994
995 fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>, state_version: StateVersion) -> Self::Output;
997}
998
999pub trait HashOutput:
1001 Member
1002 + MaybeSerializeDeserialize
1003 + MaybeDisplay
1004 + MaybeFromStr
1005 + Debug
1006 + core::hash::Hash
1007 + AsRef<[u8]>
1008 + AsMut<[u8]>
1009 + Copy
1010 + Ord
1011 + Default
1012 + Encode
1013 + Decode
1014 + DecodeWithMemTracking
1015 + EncodeLike
1016 + MaxEncodedLen
1017 + TypeInfo
1018{
1019}
1020
1021impl<T> HashOutput for T where
1022 T: Member
1023 + MaybeSerializeDeserialize
1024 + MaybeDisplay
1025 + MaybeFromStr
1026 + Debug
1027 + core::hash::Hash
1028 + AsRef<[u8]>
1029 + AsMut<[u8]>
1030 + Copy
1031 + Ord
1032 + Default
1033 + Encode
1034 + Decode
1035 + DecodeWithMemTracking
1036 + EncodeLike
1037 + MaxEncodedLen
1038 + TypeInfo
1039{
1040}
1041
1042#[derive(PartialEq, Eq, Clone, RuntimeDebug, TypeInfo)]
1044#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1045pub struct BlakeTwo256;
1046
1047impl Hasher for BlakeTwo256 {
1048 type Out = sp_core::H256;
1049 type StdHasher = hash256_std_hasher::Hash256StdHasher;
1050 const LENGTH: usize = 32;
1051
1052 fn hash(s: &[u8]) -> Self::Out {
1053 sp_io::hashing::blake2_256(s).into()
1054 }
1055}
1056
1057impl Hash for BlakeTwo256 {
1058 type Output = sp_core::H256;
1059
1060 fn ordered_trie_root(input: Vec<Vec<u8>>, version: StateVersion) -> Self::Output {
1061 sp_io::trie::blake2_256_ordered_root(input, version)
1062 }
1063
1064 fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>, version: StateVersion) -> Self::Output {
1065 sp_io::trie::blake2_256_root(input, version)
1066 }
1067}
1068
1069#[derive(PartialEq, Eq, Clone, RuntimeDebug, TypeInfo)]
1071#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1072pub struct Keccak256;
1073
1074impl Hasher for Keccak256 {
1075 type Out = sp_core::H256;
1076 type StdHasher = hash256_std_hasher::Hash256StdHasher;
1077 const LENGTH: usize = 32;
1078
1079 fn hash(s: &[u8]) -> Self::Out {
1080 sp_io::hashing::keccak_256(s).into()
1081 }
1082}
1083
1084impl Hash for Keccak256 {
1085 type Output = sp_core::H256;
1086
1087 fn ordered_trie_root(input: Vec<Vec<u8>>, version: StateVersion) -> Self::Output {
1088 sp_io::trie::keccak_256_ordered_root(input, version)
1089 }
1090
1091 fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>, version: StateVersion) -> Self::Output {
1092 sp_io::trie::keccak_256_root(input, version)
1093 }
1094}
1095
1096pub trait CheckEqual {
1098 fn check_equal(&self, other: &Self);
1100}
1101
1102impl CheckEqual for sp_core::H256 {
1103 #[cfg(feature = "std")]
1104 fn check_equal(&self, other: &Self) {
1105 use sp_core::hexdisplay::HexDisplay;
1106 if self != other {
1107 println!(
1108 "Hash: given={}, expected={}",
1109 HexDisplay::from(self.as_fixed_bytes()),
1110 HexDisplay::from(other.as_fixed_bytes()),
1111 );
1112 }
1113 }
1114
1115 #[cfg(not(feature = "std"))]
1116 fn check_equal(&self, other: &Self) {
1117 if self != other {
1118 "Hash not equal".print();
1119 self.as_bytes().print();
1120 other.as_bytes().print();
1121 }
1122 }
1123}
1124
1125impl CheckEqual for super::generic::DigestItem {
1126 #[cfg(feature = "std")]
1127 fn check_equal(&self, other: &Self) {
1128 if self != other {
1129 println!("DigestItem: given={:?}, expected={:?}", self, other);
1130 }
1131 }
1132
1133 #[cfg(not(feature = "std"))]
1134 fn check_equal(&self, other: &Self) {
1135 if self != other {
1136 "DigestItem not equal".print();
1137 (&Encode::encode(self)[..]).print();
1138 (&Encode::encode(other)[..]).print();
1139 }
1140 }
1141}
1142
1143sp_core::impl_maybe_marker!(
1144 trait MaybeDisplay: Display;
1146
1147 trait MaybeFromStr: FromStr;
1149
1150 trait MaybeHash: core::hash::Hash;
1152);
1153
1154sp_core::impl_maybe_marker_std_or_serde!(
1155 trait MaybeSerialize: Serialize;
1157
1158 trait MaybeSerializeDeserialize: DeserializeOwned, Serialize;
1160);
1161
1162pub trait Member: Send + Sync + Sized + Debug + Eq + PartialEq + Clone + 'static {}
1164impl<T: Send + Sync + Sized + Debug + Eq + PartialEq + Clone + 'static> Member for T {}
1165
1166pub trait IsMember<MemberId> {
1168 fn is_member(member_id: &MemberId) -> bool;
1170}
1171
1172pub trait BlockNumber:
1174 Member
1175 + MaybeSerializeDeserialize
1176 + MaybeFromStr
1177 + Debug
1178 + core::hash::Hash
1179 + Copy
1180 + MaybeDisplay
1181 + AtLeast32BitUnsigned
1182 + Into<U256>
1183 + TryFrom<U256>
1184 + Default
1185 + TypeInfo
1186 + MaxEncodedLen
1187 + FullCodec
1188 + DecodeWithMemTracking
1189 + HasCompact<Type: DecodeWithMemTracking>
1190{
1191}
1192
1193impl<
1194 T: Member
1195 + MaybeSerializeDeserialize
1196 + MaybeFromStr
1197 + Debug
1198 + core::hash::Hash
1199 + Copy
1200 + MaybeDisplay
1201 + AtLeast32BitUnsigned
1202 + Into<U256>
1203 + TryFrom<U256>
1204 + Default
1205 + TypeInfo
1206 + MaxEncodedLen
1207 + FullCodec
1208 + DecodeWithMemTracking
1209 + HasCompact<Type: DecodeWithMemTracking>,
1210 > BlockNumber for T
1211{
1212}
1213
1214pub trait Header:
1220 Clone
1221 + Send
1222 + Sync
1223 + Codec
1224 + DecodeWithMemTracking
1225 + Eq
1226 + MaybeSerialize
1227 + Debug
1228 + TypeInfo
1229 + 'static
1230{
1231 type Number: BlockNumber;
1233 type Hash: HashOutput;
1235 type Hashing: Hash<Output = Self::Hash>;
1237
1238 fn new(
1240 number: Self::Number,
1241 extrinsics_root: Self::Hash,
1242 state_root: Self::Hash,
1243 parent_hash: Self::Hash,
1244 digest: Digest,
1245 ) -> Self;
1246
1247 fn number(&self) -> &Self::Number;
1249 fn set_number(&mut self, number: Self::Number);
1251
1252 fn extrinsics_root(&self) -> &Self::Hash;
1254 fn set_extrinsics_root(&mut self, root: Self::Hash);
1256
1257 fn state_root(&self) -> &Self::Hash;
1259 fn set_state_root(&mut self, root: Self::Hash);
1261
1262 fn parent_hash(&self) -> &Self::Hash;
1264 fn set_parent_hash(&mut self, hash: Self::Hash);
1266
1267 fn digest(&self) -> &Digest;
1269 fn digest_mut(&mut self) -> &mut Digest;
1271
1272 fn hash(&self) -> Self::Hash {
1274 <Self::Hashing as Hash>::hash_of(self)
1275 }
1276}
1277
1278#[doc(hidden)]
1298pub trait HeaderProvider {
1299 type HeaderT: Header;
1301}
1302
1303pub trait Block:
1308 HeaderProvider<HeaderT = <Self as Block>::Header>
1309 + Clone
1310 + Send
1311 + Sync
1312 + Codec
1313 + DecodeWithMemTracking
1314 + Eq
1315 + MaybeSerialize
1316 + Debug
1317 + 'static
1318{
1319 type Extrinsic: Member + Codec + ExtrinsicLike + MaybeSerialize;
1321 type Header: Header<Hash = Self::Hash> + MaybeSerializeDeserialize;
1323 type Hash: HashOutput;
1325
1326 fn header(&self) -> &Self::Header;
1328 fn extrinsics(&self) -> &[Self::Extrinsic];
1330 fn deconstruct(self) -> (Self::Header, Vec<Self::Extrinsic>);
1332 fn new(header: Self::Header, extrinsics: Vec<Self::Extrinsic>) -> Self;
1334 fn hash(&self) -> Self::Hash {
1336 <<Self::Header as Header>::Hashing as Hash>::hash_of(self.header())
1337 }
1338 fn encode_from(header: &Self::Header, extrinsics: &[Self::Extrinsic]) -> Vec<u8>;
1341}
1342
1343#[deprecated = "Use `ExtrinsicLike` along with the `CreateTransaction` trait family instead"]
1345pub trait Extrinsic: Sized {
1346 type Call: TypeInfo;
1348
1349 type SignaturePayload: SignaturePayload;
1355
1356 fn is_signed(&self) -> Option<bool> {
1359 None
1360 }
1361
1362 fn is_bare(&self) -> bool {
1364 !self.is_signed().unwrap_or(true)
1365 }
1366
1367 fn new(_call: Self::Call, _signed_data: Option<Self::SignaturePayload>) -> Option<Self> {
1370 None
1371 }
1372}
1373
1374pub trait ExtrinsicLike: Sized {
1376 #[deprecated = "Use and implement `!is_bare()` instead"]
1379 fn is_signed(&self) -> Option<bool> {
1380 None
1381 }
1382
1383 fn is_bare(&self) -> bool {
1385 #[allow(deprecated)]
1386 !self.is_signed().unwrap_or(true)
1387 }
1388}
1389
1390#[allow(deprecated)]
1391impl<T> ExtrinsicLike for T
1392where
1393 T: Extrinsic,
1394{
1395 fn is_signed(&self) -> Option<bool> {
1396 #[allow(deprecated)]
1397 <Self as Extrinsic>::is_signed(&self)
1398 }
1399
1400 fn is_bare(&self) -> bool {
1401 <Self as Extrinsic>::is_bare(&self)
1402 }
1403}
1404
1405pub trait SignaturePayload {
1408 type SignatureAddress: TypeInfo;
1412
1413 type Signature: TypeInfo;
1417
1418 type SignatureExtra: TypeInfo;
1422}
1423
1424impl SignaturePayload for () {
1425 type SignatureAddress = ();
1426 type Signature = ();
1427 type SignatureExtra = ();
1428}
1429
1430pub trait ExtrinsicMetadata {
1432 const VERSIONS: &'static [u8];
1436
1437 type TransactionExtensions;
1439}
1440
1441pub type HashingFor<B> = <<B as Block>::Header as Header>::Hashing;
1443pub type NumberFor<B> = <<B as Block>::Header as Header>::Number;
1445pub trait Checkable<Context>: Sized {
1452 type Checked;
1454
1455 fn check(self, c: &Context) -> Result<Self::Checked, TransactionValidityError>;
1457
1458 #[cfg(feature = "try-runtime")]
1467 fn unchecked_into_checked_i_know_what_i_am_doing(
1468 self,
1469 c: &Context,
1470 ) -> Result<Self::Checked, TransactionValidityError>;
1471}
1472
1473pub trait BlindCheckable: Sized {
1478 type Checked;
1480
1481 fn check(self) -> Result<Self::Checked, TransactionValidityError>;
1483}
1484
1485impl<T: BlindCheckable, Context> Checkable<Context> for T {
1487 type Checked = <Self as BlindCheckable>::Checked;
1488
1489 fn check(self, _c: &Context) -> Result<Self::Checked, TransactionValidityError> {
1490 BlindCheckable::check(self)
1491 }
1492
1493 #[cfg(feature = "try-runtime")]
1494 fn unchecked_into_checked_i_know_what_i_am_doing(
1495 self,
1496 _: &Context,
1497 ) -> Result<Self::Checked, TransactionValidityError> {
1498 unreachable!();
1499 }
1500}
1501
1502pub trait RefundWeight {
1504 fn refund(&mut self, weight: sp_weights::Weight);
1506}
1507
1508pub trait ExtensionPostDispatchWeightHandler<DispatchInfo>: RefundWeight {
1511 fn set_extension_weight(&mut self, info: &DispatchInfo);
1513}
1514
1515impl RefundWeight for () {
1516 fn refund(&mut self, _weight: sp_weights::Weight) {}
1517}
1518
1519impl ExtensionPostDispatchWeightHandler<()> for () {
1520 fn set_extension_weight(&mut self, _info: &()) {}
1521}
1522
1523pub trait Dispatchable {
1526 type RuntimeOrigin: Debug;
1530 type Config;
1532 type Info;
1536 type PostInfo: Eq
1539 + PartialEq
1540 + Clone
1541 + Copy
1542 + Encode
1543 + Decode
1544 + Printable
1545 + ExtensionPostDispatchWeightHandler<Self::Info>;
1546 fn dispatch(self, origin: Self::RuntimeOrigin)
1548 -> crate::DispatchResultWithInfo<Self::PostInfo>;
1549}
1550
1551pub type DispatchOriginOf<T> = <T as Dispatchable>::RuntimeOrigin;
1553pub type DispatchInfoOf<T> = <T as Dispatchable>::Info;
1555pub type PostDispatchInfoOf<T> = <T as Dispatchable>::PostInfo;
1557
1558impl Dispatchable for () {
1559 type RuntimeOrigin = ();
1560 type Config = ();
1561 type Info = ();
1562 type PostInfo = ();
1563 fn dispatch(
1564 self,
1565 _origin: Self::RuntimeOrigin,
1566 ) -> crate::DispatchResultWithInfo<Self::PostInfo> {
1567 panic!("This implementation should not be used for actual dispatch.");
1568 }
1569}
1570
1571#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo)]
1573pub struct FakeDispatchable<Inner>(pub Inner);
1574impl<Inner> From<Inner> for FakeDispatchable<Inner> {
1575 fn from(inner: Inner) -> Self {
1576 Self(inner)
1577 }
1578}
1579impl<Inner> FakeDispatchable<Inner> {
1580 pub fn deconstruct(self) -> Inner {
1582 self.0
1583 }
1584}
1585impl<Inner> AsRef<Inner> for FakeDispatchable<Inner> {
1586 fn as_ref(&self) -> &Inner {
1587 &self.0
1588 }
1589}
1590
1591impl<Inner> Dispatchable for FakeDispatchable<Inner> {
1592 type RuntimeOrigin = ();
1593 type Config = ();
1594 type Info = ();
1595 type PostInfo = ();
1596 fn dispatch(
1597 self,
1598 _origin: Self::RuntimeOrigin,
1599 ) -> crate::DispatchResultWithInfo<Self::PostInfo> {
1600 panic!("This implementation should not be used for actual dispatch.");
1601 }
1602}
1603
1604pub trait AsSystemOriginSigner<AccountId> {
1606 fn as_system_origin_signer(&self) -> Option<&AccountId>;
1609}
1610
1611pub trait AsTransactionAuthorizedOrigin {
1625 fn is_transaction_authorized(&self) -> bool;
1635}
1636
1637#[deprecated = "Use `TransactionExtension` instead."]
1640pub trait SignedExtension:
1641 Codec + DecodeWithMemTracking + Debug + Sync + Send + Clone + Eq + PartialEq + StaticTypeInfo
1642{
1643 const IDENTIFIER: &'static str;
1648
1649 type AccountId;
1651
1652 type Call: Dispatchable;
1654
1655 type AdditionalSigned: Codec + TypeInfo;
1658
1659 type Pre;
1661
1662 fn additional_signed(&self) -> Result<Self::AdditionalSigned, TransactionValidityError>;
1665
1666 fn validate(
1676 &self,
1677 _who: &Self::AccountId,
1678 _call: &Self::Call,
1679 _info: &DispatchInfoOf<Self::Call>,
1680 _len: usize,
1681 ) -> TransactionValidity {
1682 Ok(ValidTransaction::default())
1683 }
1684
1685 fn pre_dispatch(
1689 self,
1690 who: &Self::AccountId,
1691 call: &Self::Call,
1692 info: &DispatchInfoOf<Self::Call>,
1693 len: usize,
1694 ) -> Result<Self::Pre, TransactionValidityError>;
1695
1696 fn post_dispatch(
1713 _pre: Option<Self::Pre>,
1714 _info: &DispatchInfoOf<Self::Call>,
1715 _post_info: &PostDispatchInfoOf<Self::Call>,
1716 _len: usize,
1717 _result: &DispatchResult,
1718 ) -> Result<(), TransactionValidityError> {
1719 Ok(())
1720 }
1721
1722 fn metadata() -> Vec<TransactionExtensionMetadata> {
1731 alloc::vec![TransactionExtensionMetadata {
1732 identifier: Self::IDENTIFIER,
1733 ty: scale_info::meta_type::<Self>(),
1734 implicit: scale_info::meta_type::<Self::AdditionalSigned>()
1735 }]
1736 }
1737
1738 fn validate_unsigned(
1745 _call: &Self::Call,
1746 _info: &DispatchInfoOf<Self::Call>,
1747 _len: usize,
1748 ) -> TransactionValidity {
1749 Ok(ValidTransaction::default())
1750 }
1751
1752 fn pre_dispatch_unsigned(
1761 call: &Self::Call,
1762 info: &DispatchInfoOf<Self::Call>,
1763 len: usize,
1764 ) -> Result<(), TransactionValidityError> {
1765 Self::validate_unsigned(call, info, len).map(|_| ()).map_err(Into::into)
1766 }
1767}
1768
1769pub trait Applyable: Sized + Send + Sync {
1785 type Call: Dispatchable;
1787
1788 fn validate<V: ValidateUnsigned<Call = Self::Call>>(
1793 &self,
1794 source: TransactionSource,
1795 info: &DispatchInfoOf<Self::Call>,
1796 len: usize,
1797 ) -> TransactionValidity;
1798
1799 fn apply<V: ValidateUnsigned<Call = Self::Call>>(
1805 self,
1806 info: &DispatchInfoOf<Self::Call>,
1807 len: usize,
1808 ) -> crate::ApplyExtrinsicResultWithInfo<PostDispatchInfoOf<Self::Call>>;
1809}
1810
1811pub trait GetRuntimeBlockType {
1813 type RuntimeBlock: self::Block;
1815}
1816
1817pub trait GetNodeBlockType {
1819 type NodeBlock: self::Block;
1821}
1822
1823pub trait ValidateUnsigned {
1831 type Call;
1833
1834 fn pre_dispatch(call: &Self::Call) -> Result<(), TransactionValidityError> {
1847 Self::validate_unsigned(TransactionSource::InBlock, call)
1848 .map(|_| ())
1849 .map_err(Into::into)
1850 }
1851
1852 fn validate_unsigned(source: TransactionSource, call: &Self::Call) -> TransactionValidity;
1865}
1866
1867pub trait OpaqueKeys: Clone {
1870 type KeyTypeIdProviders;
1872
1873 fn key_ids() -> &'static [crate::KeyTypeId];
1875 fn get_raw(&self, i: super::KeyTypeId) -> &[u8];
1877 fn get<T: Decode>(&self, i: super::KeyTypeId) -> Option<T> {
1879 T::decode(&mut self.get_raw(i)).ok()
1880 }
1881 fn ownership_proof_is_valid(&self, _proof: &[u8]) -> bool {
1883 true
1884 }
1885}
1886
1887pub struct AppendZerosInput<'a, T>(&'a mut T);
1892
1893impl<'a, T> AppendZerosInput<'a, T> {
1894 pub fn new(input: &'a mut T) -> Self {
1896 Self(input)
1897 }
1898}
1899
1900impl<'a, T: codec::Input> codec::Input for AppendZerosInput<'a, T> {
1901 fn remaining_len(&mut self) -> Result<Option<usize>, codec::Error> {
1902 Ok(None)
1903 }
1904
1905 fn read(&mut self, into: &mut [u8]) -> Result<(), codec::Error> {
1906 let remaining = self.0.remaining_len()?;
1907 let completed = if let Some(n) = remaining {
1908 let readable = into.len().min(n);
1909 self.0.read(&mut into[..readable])?;
1911 readable
1912 } else {
1913 let mut i = 0;
1915 while i < into.len() {
1916 if let Ok(b) = self.0.read_byte() {
1917 into[i] = b;
1918 i += 1;
1919 } else {
1920 break
1921 }
1922 }
1923 i
1924 };
1925 for i in &mut into[completed..] {
1927 *i = 0;
1928 }
1929 Ok(())
1930 }
1931}
1932
1933pub struct TrailingZeroInput<'a>(&'a [u8]);
1935
1936impl<'a> TrailingZeroInput<'a> {
1937 pub fn new(data: &'a [u8]) -> Self {
1939 Self(data)
1940 }
1941
1942 pub fn zeroes() -> Self {
1944 Self::new(&[][..])
1945 }
1946}
1947
1948impl<'a> codec::Input for TrailingZeroInput<'a> {
1949 fn remaining_len(&mut self) -> Result<Option<usize>, codec::Error> {
1950 Ok(None)
1951 }
1952
1953 fn read(&mut self, into: &mut [u8]) -> Result<(), codec::Error> {
1954 let len_from_inner = into.len().min(self.0.len());
1955 into[..len_from_inner].copy_from_slice(&self.0[..len_from_inner]);
1956 for i in &mut into[len_from_inner..] {
1957 *i = 0;
1958 }
1959 self.0 = &self.0[len_from_inner..];
1960
1961 Ok(())
1962 }
1963}
1964
1965pub trait AccountIdConversion<AccountId>: Sized {
1967 fn into_account_truncating(&self) -> AccountId {
1970 self.into_sub_account_truncating(&())
1971 }
1972
1973 fn try_into_account(&self) -> Option<AccountId> {
1976 self.try_into_sub_account(&())
1977 }
1978
1979 fn try_from_account(a: &AccountId) -> Option<Self> {
1981 Self::try_from_sub_account::<()>(a).map(|x| x.0)
1982 }
1983
1984 fn into_sub_account_truncating<S: Encode>(&self, sub: S) -> AccountId;
1998
1999 fn try_into_sub_account<S: Encode>(&self, sub: S) -> Option<AccountId>;
2003
2004 fn try_from_sub_account<S: Decode>(x: &AccountId) -> Option<(Self, S)>;
2006}
2007
2008impl<T: Encode + Decode, Id: Encode + Decode + TypeId> AccountIdConversion<T> for Id {
2011 fn into_sub_account_truncating<S: Encode>(&self, sub: S) -> T {
2015 (Id::TYPE_ID, self, sub)
2016 .using_encoded(|b| T::decode(&mut TrailingZeroInput(b)))
2017 .expect("All byte sequences are valid `AccountIds`; qed")
2018 }
2019
2020 fn try_into_sub_account<S: Encode>(&self, sub: S) -> Option<T> {
2022 let encoded_seed = (Id::TYPE_ID, self, sub).encode();
2023 let account = T::decode(&mut TrailingZeroInput(&encoded_seed))
2024 .expect("All byte sequences are valid `AccountIds`; qed");
2025 if encoded_seed.len() <= account.encoded_size() {
2028 Some(account)
2029 } else {
2030 None
2031 }
2032 }
2033
2034 fn try_from_sub_account<S: Decode>(x: &T) -> Option<(Self, S)> {
2035 x.using_encoded(|d| {
2036 if d[0..4] != Id::TYPE_ID {
2037 return None
2038 }
2039 let mut cursor = &d[4..];
2040 let result = Decode::decode(&mut cursor).ok()?;
2041 if cursor.iter().all(|x| *x == 0) {
2042 Some(result)
2043 } else {
2044 None
2045 }
2046 })
2047 }
2048}
2049
2050#[macro_export]
2057macro_rules! count {
2058 ($f:ident ($($x:tt)*) ) => ();
2059 ($f:ident ($($x:tt)*) $x1:tt) => { $f!($($x)* 0); };
2060 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt) => { $f!($($x)* 0); $f!($($x)* 1); };
2061 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt) => { $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); };
2062 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt, $x4:tt) => {
2063 $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); $f!($($x)* 3);
2064 };
2065 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt, $x4:tt, $x5:tt) => {
2066 $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); $f!($($x)* 3); $f!($($x)* 4);
2067 };
2068}
2069
2070#[doc(hidden)]
2071#[macro_export]
2072macro_rules! impl_opaque_keys_inner {
2073 (
2074 $( #[ $attr:meta ] )*
2075 pub struct $name:ident {
2076 $(
2077 $( #[ $inner_attr:meta ] )*
2078 pub $field:ident: $type:ty,
2079 )*
2080 }
2081 ) => {
2082 $( #[ $attr ] )*
2083 #[derive(
2084 Clone, PartialEq, Eq,
2085 $crate::codec::Encode,
2086 $crate::codec::Decode,
2087 $crate::codec::DecodeWithMemTracking,
2088 $crate::scale_info::TypeInfo,
2089 $crate::RuntimeDebug,
2090 )]
2091 pub struct $name {
2092 $(
2093 $( #[ $inner_attr ] )*
2094 pub $field: <$type as $crate::BoundToRuntimeAppPublic>::Public,
2095 )*
2096 }
2097
2098 impl $name {
2099 pub fn generate(seed: Option<$crate::Vec<u8>>) -> $crate::Vec<u8> {
2105 let keys = Self{
2106 $(
2107 $field: <
2108 <
2109 $type as $crate::BoundToRuntimeAppPublic
2110 >::Public as $crate::RuntimeAppPublic
2111 >::generate_pair(seed.clone()),
2112 )*
2113 };
2114 $crate::codec::Encode::encode(&keys)
2115 }
2116
2117 pub fn into_raw_public_keys(
2119 self,
2120 ) -> $crate::Vec<($crate::Vec<u8>, $crate::KeyTypeId)> {
2121 let mut keys = Vec::new();
2122 $(
2123 keys.push((
2124 $crate::RuntimeAppPublic::to_raw_vec(&self.$field),
2125 <
2126 <
2127 $type as $crate::BoundToRuntimeAppPublic
2128 >::Public as $crate::RuntimeAppPublic
2129 >::ID,
2130 ));
2131 )*
2132
2133 keys
2134 }
2135
2136 pub fn decode_into_raw_public_keys(
2141 encoded: &[u8],
2142 ) -> Option<$crate::Vec<($crate::Vec<u8>, $crate::KeyTypeId)>> {
2143 <Self as $crate::codec::Decode>::decode(&mut &encoded[..])
2144 .ok()
2145 .map(|s| s.into_raw_public_keys())
2146 }
2147 }
2148
2149 impl $crate::traits::OpaqueKeys for $name {
2150 type KeyTypeIdProviders = ( $( $type, )* );
2151
2152 fn key_ids() -> &'static [$crate::KeyTypeId] {
2153 &[
2154 $(
2155 <
2156 <
2157 $type as $crate::BoundToRuntimeAppPublic
2158 >::Public as $crate::RuntimeAppPublic
2159 >::ID
2160 ),*
2161 ]
2162 }
2163
2164 fn get_raw(&self, i: $crate::KeyTypeId) -> &[u8] {
2165 match i {
2166 $(
2167 i if i == <
2168 <
2169 $type as $crate::BoundToRuntimeAppPublic
2170 >::Public as $crate::RuntimeAppPublic
2171 >::ID =>
2172 self.$field.as_ref(),
2173 )*
2174 _ => &[],
2175 }
2176 }
2177 }
2178 };
2179}
2180
2181#[macro_export]
2205#[cfg(any(feature = "serde", feature = "std"))]
2206macro_rules! impl_opaque_keys {
2207 {
2208 $( #[ $attr:meta ] )*
2209 pub struct $name:ident {
2210 $(
2211 $( #[ $inner_attr:meta ] )*
2212 pub $field:ident: $type:ty,
2213 )*
2214 }
2215 } => {
2216 $crate::paste::paste! {
2217 use $crate::serde as [< __opaque_keys_serde_import__ $name >];
2218
2219 $crate::impl_opaque_keys_inner! {
2220 $( #[ $attr ] )*
2221 #[derive($crate::serde::Serialize, $crate::serde::Deserialize)]
2222 #[serde(crate = "__opaque_keys_serde_import__" $name)]
2223 pub struct $name {
2224 $(
2225 $( #[ $inner_attr ] )*
2226 pub $field: $type,
2227 )*
2228 }
2229 }
2230 }
2231 }
2232}
2233
2234#[macro_export]
2235#[cfg(all(not(feature = "std"), not(feature = "serde")))]
2236#[doc(hidden)]
2237macro_rules! impl_opaque_keys {
2238 {
2239 $( #[ $attr:meta ] )*
2240 pub struct $name:ident {
2241 $(
2242 $( #[ $inner_attr:meta ] )*
2243 pub $field:ident: $type:ty,
2244 )*
2245 }
2246 } => {
2247 $crate::impl_opaque_keys_inner! {
2248 $( #[ $attr ] )*
2249 pub struct $name {
2250 $(
2251 $( #[ $inner_attr ] )*
2252 pub $field: $type,
2253 )*
2254 }
2255 }
2256 }
2257}
2258
2259pub trait Printable {
2261 fn print(&self);
2263}
2264
2265impl<T: Printable> Printable for &T {
2266 fn print(&self) {
2267 (*self).print()
2268 }
2269}
2270
2271impl Printable for u8 {
2272 fn print(&self) {
2273 (*self as u64).print()
2274 }
2275}
2276
2277impl Printable for u32 {
2278 fn print(&self) {
2279 (*self as u64).print()
2280 }
2281}
2282
2283impl Printable for usize {
2284 fn print(&self) {
2285 (*self as u64).print()
2286 }
2287}
2288
2289impl Printable for u64 {
2290 fn print(&self) {
2291 sp_io::misc::print_num(*self);
2292 }
2293}
2294
2295impl Printable for &[u8] {
2296 fn print(&self) {
2297 sp_io::misc::print_hex(self);
2298 }
2299}
2300
2301impl<const N: usize> Printable for [u8; N] {
2302 fn print(&self) {
2303 sp_io::misc::print_hex(&self[..]);
2304 }
2305}
2306
2307impl Printable for &str {
2308 fn print(&self) {
2309 sp_io::misc::print_utf8(self.as_bytes());
2310 }
2311}
2312
2313impl Printable for bool {
2314 fn print(&self) {
2315 if *self {
2316 "true".print()
2317 } else {
2318 "false".print()
2319 }
2320 }
2321}
2322
2323impl Printable for sp_weights::Weight {
2324 fn print(&self) {
2325 self.ref_time().print()
2326 }
2327}
2328
2329impl Printable for () {
2330 fn print(&self) {
2331 "()".print()
2332 }
2333}
2334
2335#[impl_for_tuples(1, 12)]
2336impl Printable for Tuple {
2337 fn print(&self) {
2338 for_tuples!( #( Tuple.print(); )* )
2339 }
2340}
2341
2342#[cfg(feature = "std")]
2344pub trait BlockIdTo<Block: self::Block> {
2345 type Error: std::error::Error;
2347
2348 fn to_hash(
2350 &self,
2351 block_id: &crate::generic::BlockId<Block>,
2352 ) -> Result<Option<Block::Hash>, Self::Error>;
2353
2354 fn to_number(
2356 &self,
2357 block_id: &crate::generic::BlockId<Block>,
2358 ) -> Result<Option<NumberFor<Block>>, Self::Error>;
2359}
2360
2361pub trait BlockNumberProvider {
2363 type BlockNumber: Codec
2365 + DecodeWithMemTracking
2366 + Clone
2367 + Ord
2368 + Eq
2369 + AtLeast32BitUnsigned
2370 + TypeInfo
2371 + Debug
2372 + MaxEncodedLen
2373 + Copy
2374 + EncodeLike
2375 + Default;
2376
2377 fn current_block_number() -> Self::BlockNumber;
2393
2394 #[cfg(any(feature = "std", feature = "runtime-benchmarks"))]
2400 fn set_block_number(_block: Self::BlockNumber) {}
2401}
2402
2403impl BlockNumberProvider for () {
2404 type BlockNumber = u32;
2405 fn current_block_number() -> Self::BlockNumber {
2406 0
2407 }
2408}
2409
2410#[cfg(test)]
2411mod tests {
2412 use super::*;
2413 use crate::codec::{Decode, Encode, Input};
2414 use sp_core::{
2415 crypto::{Pair, UncheckedFrom},
2416 ecdsa, ed25519, sr25519,
2417 };
2418
2419 macro_rules! signature_verify_test {
2420 ($algorithm:ident) => {
2421 let msg = &b"test-message"[..];
2422 let wrong_msg = &b"test-msg"[..];
2423 let (pair, _) = $algorithm::Pair::generate();
2424
2425 let signature = pair.sign(&msg);
2426 assert!($algorithm::Pair::verify(&signature, msg, &pair.public()));
2427
2428 assert!(signature.verify(msg, &pair.public()));
2429 assert!(!signature.verify(wrong_msg, &pair.public()));
2430 };
2431 }
2432
2433 mod t {
2434 use sp_application_crypto::{app_crypto, sr25519};
2435 use sp_core::crypto::KeyTypeId;
2436 app_crypto!(sr25519, KeyTypeId(*b"test"));
2437 }
2438
2439 #[test]
2440 fn app_verify_works() {
2441 use super::AppVerify;
2442 use t::*;
2443
2444 let s = Signature::try_from(vec![0; 64]).unwrap();
2445 let _ = s.verify(&[0u8; 100][..], &Public::unchecked_from([0; 32]));
2446 }
2447
2448 #[derive(Encode, Decode, Default, PartialEq, Debug)]
2449 struct U128Value(u128);
2450 impl super::TypeId for U128Value {
2451 const TYPE_ID: [u8; 4] = [0x0d, 0xf0, 0x0d, 0xf0];
2452 }
2453 #[derive(Encode, Decode, Default, PartialEq, Debug)]
2456 struct U32Value(u32);
2457 impl super::TypeId for U32Value {
2458 const TYPE_ID: [u8; 4] = [0x0d, 0xf0, 0xfe, 0xca];
2459 }
2460 #[derive(Encode, Decode, Default, PartialEq, Debug)]
2463 struct U16Value(u16);
2464 impl super::TypeId for U16Value {
2465 const TYPE_ID: [u8; 4] = [0xfe, 0xca, 0x0d, 0xf0];
2466 }
2467 type AccountId = u64;
2470
2471 #[test]
2472 fn into_account_truncating_should_work() {
2473 let r: AccountId = U32Value::into_account_truncating(&U32Value(0xdeadbeef));
2474 assert_eq!(r, 0x_deadbeef_cafef00d);
2475 }
2476
2477 #[test]
2478 fn try_into_account_should_work() {
2479 let r: AccountId = U32Value::try_into_account(&U32Value(0xdeadbeef)).unwrap();
2480 assert_eq!(r, 0x_deadbeef_cafef00d);
2481
2482 let maybe: Option<AccountId> = U128Value::try_into_account(&U128Value(u128::MAX));
2484 assert!(maybe.is_none());
2485 }
2486
2487 #[test]
2488 fn try_from_account_should_work() {
2489 let r = U32Value::try_from_account(&0x_deadbeef_cafef00d_u64);
2490 assert_eq!(r.unwrap(), U32Value(0xdeadbeef));
2491 }
2492
2493 #[test]
2494 fn into_account_truncating_with_fill_should_work() {
2495 let r: AccountId = U16Value::into_account_truncating(&U16Value(0xc0da));
2496 assert_eq!(r, 0x_0000_c0da_f00dcafe);
2497 }
2498
2499 #[test]
2500 fn try_into_sub_account_should_work() {
2501 let r: AccountId = U16Value::try_into_account(&U16Value(0xc0da)).unwrap();
2502 assert_eq!(r, 0x_0000_c0da_f00dcafe);
2503
2504 let maybe: Option<AccountId> = U16Value::try_into_sub_account(
2505 &U16Value(0xc0da),
2506 "a really large amount of additional encoded information which will certainly overflow the account id type ;)"
2507 );
2508
2509 assert!(maybe.is_none())
2510 }
2511
2512 #[test]
2513 fn try_from_account_with_fill_should_work() {
2514 let r = U16Value::try_from_account(&0x0000_c0da_f00dcafe_u64);
2515 assert_eq!(r.unwrap(), U16Value(0xc0da));
2516 }
2517
2518 #[test]
2519 fn bad_try_from_account_should_fail() {
2520 let r = U16Value::try_from_account(&0x0000_c0de_baadcafe_u64);
2521 assert!(r.is_none());
2522 let r = U16Value::try_from_account(&0x0100_c0da_f00dcafe_u64);
2523 assert!(r.is_none());
2524 }
2525
2526 #[test]
2527 fn trailing_zero_should_work() {
2528 let mut t = super::TrailingZeroInput(&[1, 2, 3]);
2529 assert_eq!(t.remaining_len(), Ok(None));
2530 let mut buffer = [0u8; 2];
2531 assert_eq!(t.read(&mut buffer), Ok(()));
2532 assert_eq!(t.remaining_len(), Ok(None));
2533 assert_eq!(buffer, [1, 2]);
2534 assert_eq!(t.read(&mut buffer), Ok(()));
2535 assert_eq!(t.remaining_len(), Ok(None));
2536 assert_eq!(buffer, [3, 0]);
2537 assert_eq!(t.read(&mut buffer), Ok(()));
2538 assert_eq!(t.remaining_len(), Ok(None));
2539 assert_eq!(buffer, [0, 0]);
2540 }
2541
2542 #[test]
2543 fn ed25519_verify_works() {
2544 signature_verify_test!(ed25519);
2545 }
2546
2547 #[test]
2548 fn sr25519_verify_works() {
2549 signature_verify_test!(sr25519);
2550 }
2551
2552 #[test]
2553 fn ecdsa_verify_works() {
2554 signature_verify_test!(ecdsa);
2555 }
2556}