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 ExtrinsicCall: ExtrinsicLike {
1407 type Call;
1409
1410 fn call(&self) -> &Self::Call;
1412}
1413
1414pub trait SignaturePayload {
1417 type SignatureAddress: TypeInfo;
1421
1422 type Signature: TypeInfo;
1426
1427 type SignatureExtra: TypeInfo;
1431}
1432
1433impl SignaturePayload for () {
1434 type SignatureAddress = ();
1435 type Signature = ();
1436 type SignatureExtra = ();
1437}
1438
1439pub trait ExtrinsicMetadata {
1441 const VERSIONS: &'static [u8];
1445
1446 type TransactionExtensions;
1448}
1449
1450pub type HashingFor<B> = <<B as Block>::Header as Header>::Hashing;
1452pub type NumberFor<B> = <<B as Block>::Header as Header>::Number;
1454pub trait Checkable<Context>: Sized {
1461 type Checked;
1463
1464 fn check(self, c: &Context) -> Result<Self::Checked, TransactionValidityError>;
1466
1467 #[cfg(feature = "try-runtime")]
1476 fn unchecked_into_checked_i_know_what_i_am_doing(
1477 self,
1478 c: &Context,
1479 ) -> Result<Self::Checked, TransactionValidityError>;
1480}
1481
1482pub trait BlindCheckable: Sized {
1487 type Checked;
1489
1490 fn check(self) -> Result<Self::Checked, TransactionValidityError>;
1492}
1493
1494impl<T: BlindCheckable, Context> Checkable<Context> for T {
1496 type Checked = <Self as BlindCheckable>::Checked;
1497
1498 fn check(self, _c: &Context) -> Result<Self::Checked, TransactionValidityError> {
1499 BlindCheckable::check(self)
1500 }
1501
1502 #[cfg(feature = "try-runtime")]
1503 fn unchecked_into_checked_i_know_what_i_am_doing(
1504 self,
1505 _: &Context,
1506 ) -> Result<Self::Checked, TransactionValidityError> {
1507 unreachable!();
1508 }
1509}
1510
1511pub trait RefundWeight {
1513 fn refund(&mut self, weight: sp_weights::Weight);
1515}
1516
1517pub trait ExtensionPostDispatchWeightHandler<DispatchInfo>: RefundWeight {
1520 fn set_extension_weight(&mut self, info: &DispatchInfo);
1522}
1523
1524impl RefundWeight for () {
1525 fn refund(&mut self, _weight: sp_weights::Weight) {}
1526}
1527
1528impl ExtensionPostDispatchWeightHandler<()> for () {
1529 fn set_extension_weight(&mut self, _info: &()) {}
1530}
1531
1532pub trait Dispatchable {
1535 type RuntimeOrigin: Debug;
1539 type Config;
1541 type Info;
1545 type PostInfo: Eq
1548 + PartialEq
1549 + Clone
1550 + Copy
1551 + Encode
1552 + Decode
1553 + Printable
1554 + ExtensionPostDispatchWeightHandler<Self::Info>;
1555 fn dispatch(self, origin: Self::RuntimeOrigin)
1557 -> crate::DispatchResultWithInfo<Self::PostInfo>;
1558}
1559
1560pub type DispatchOriginOf<T> = <T as Dispatchable>::RuntimeOrigin;
1562pub type DispatchInfoOf<T> = <T as Dispatchable>::Info;
1564pub type PostDispatchInfoOf<T> = <T as Dispatchable>::PostInfo;
1566
1567impl Dispatchable for () {
1568 type RuntimeOrigin = ();
1569 type Config = ();
1570 type Info = ();
1571 type PostInfo = ();
1572 fn dispatch(
1573 self,
1574 _origin: Self::RuntimeOrigin,
1575 ) -> crate::DispatchResultWithInfo<Self::PostInfo> {
1576 panic!("This implementation should not be used for actual dispatch.");
1577 }
1578}
1579
1580#[derive(Clone, Eq, PartialEq, Encode, Decode, DecodeWithMemTracking, RuntimeDebug, TypeInfo)]
1582pub struct FakeDispatchable<Inner>(pub Inner);
1583impl<Inner> From<Inner> for FakeDispatchable<Inner> {
1584 fn from(inner: Inner) -> Self {
1585 Self(inner)
1586 }
1587}
1588impl<Inner> FakeDispatchable<Inner> {
1589 pub fn deconstruct(self) -> Inner {
1591 self.0
1592 }
1593}
1594impl<Inner> AsRef<Inner> for FakeDispatchable<Inner> {
1595 fn as_ref(&self) -> &Inner {
1596 &self.0
1597 }
1598}
1599
1600impl<Inner> Dispatchable for FakeDispatchable<Inner> {
1601 type RuntimeOrigin = ();
1602 type Config = ();
1603 type Info = ();
1604 type PostInfo = ();
1605 fn dispatch(
1606 self,
1607 _origin: Self::RuntimeOrigin,
1608 ) -> crate::DispatchResultWithInfo<Self::PostInfo> {
1609 panic!("This implementation should not be used for actual dispatch.");
1610 }
1611}
1612
1613pub trait AsSystemOriginSigner<AccountId> {
1615 fn as_system_origin_signer(&self) -> Option<&AccountId>;
1618}
1619
1620pub trait AsTransactionAuthorizedOrigin {
1634 fn is_transaction_authorized(&self) -> bool;
1644}
1645
1646#[deprecated = "Use `TransactionExtension` instead."]
1649pub trait SignedExtension:
1650 Codec + DecodeWithMemTracking + Debug + Sync + Send + Clone + Eq + PartialEq + StaticTypeInfo
1651{
1652 const IDENTIFIER: &'static str;
1657
1658 type AccountId;
1660
1661 type Call: Dispatchable;
1663
1664 type AdditionalSigned: Codec + TypeInfo;
1667
1668 type Pre;
1670
1671 fn additional_signed(&self) -> Result<Self::AdditionalSigned, TransactionValidityError>;
1674
1675 fn validate(
1685 &self,
1686 _who: &Self::AccountId,
1687 _call: &Self::Call,
1688 _info: &DispatchInfoOf<Self::Call>,
1689 _len: usize,
1690 ) -> TransactionValidity {
1691 Ok(ValidTransaction::default())
1692 }
1693
1694 fn pre_dispatch(
1698 self,
1699 who: &Self::AccountId,
1700 call: &Self::Call,
1701 info: &DispatchInfoOf<Self::Call>,
1702 len: usize,
1703 ) -> Result<Self::Pre, TransactionValidityError>;
1704
1705 fn post_dispatch(
1722 _pre: Option<Self::Pre>,
1723 _info: &DispatchInfoOf<Self::Call>,
1724 _post_info: &PostDispatchInfoOf<Self::Call>,
1725 _len: usize,
1726 _result: &DispatchResult,
1727 ) -> Result<(), TransactionValidityError> {
1728 Ok(())
1729 }
1730
1731 fn metadata() -> Vec<TransactionExtensionMetadata> {
1740 alloc::vec![TransactionExtensionMetadata {
1741 identifier: Self::IDENTIFIER,
1742 ty: scale_info::meta_type::<Self>(),
1743 implicit: scale_info::meta_type::<Self::AdditionalSigned>()
1744 }]
1745 }
1746
1747 fn validate_unsigned(
1754 _call: &Self::Call,
1755 _info: &DispatchInfoOf<Self::Call>,
1756 _len: usize,
1757 ) -> TransactionValidity {
1758 Ok(ValidTransaction::default())
1759 }
1760
1761 fn pre_dispatch_unsigned(
1770 call: &Self::Call,
1771 info: &DispatchInfoOf<Self::Call>,
1772 len: usize,
1773 ) -> Result<(), TransactionValidityError> {
1774 Self::validate_unsigned(call, info, len).map(|_| ()).map_err(Into::into)
1775 }
1776}
1777
1778pub trait Applyable: Sized + Send + Sync {
1794 type Call: Dispatchable;
1796
1797 fn validate<V: ValidateUnsigned<Call = Self::Call>>(
1802 &self,
1803 source: TransactionSource,
1804 info: &DispatchInfoOf<Self::Call>,
1805 len: usize,
1806 ) -> TransactionValidity;
1807
1808 fn apply<V: ValidateUnsigned<Call = Self::Call>>(
1814 self,
1815 info: &DispatchInfoOf<Self::Call>,
1816 len: usize,
1817 ) -> crate::ApplyExtrinsicResultWithInfo<PostDispatchInfoOf<Self::Call>>;
1818}
1819
1820pub trait GetRuntimeBlockType {
1822 type RuntimeBlock: self::Block;
1824}
1825
1826pub trait GetNodeBlockType {
1828 type NodeBlock: self::Block;
1830}
1831
1832pub trait ValidateUnsigned {
1840 type Call;
1842
1843 fn pre_dispatch(call: &Self::Call) -> Result<(), TransactionValidityError> {
1856 Self::validate_unsigned(TransactionSource::InBlock, call)
1857 .map(|_| ())
1858 .map_err(Into::into)
1859 }
1860
1861 fn validate_unsigned(source: TransactionSource, call: &Self::Call) -> TransactionValidity;
1874}
1875
1876pub trait OpaqueKeys: Clone {
1879 type KeyTypeIdProviders;
1881
1882 fn key_ids() -> &'static [crate::KeyTypeId];
1884 fn get_raw(&self, i: super::KeyTypeId) -> &[u8];
1886 fn get<T: Decode>(&self, i: super::KeyTypeId) -> Option<T> {
1888 T::decode(&mut self.get_raw(i)).ok()
1889 }
1890 fn ownership_proof_is_valid(&self, _proof: &[u8]) -> bool {
1892 true
1893 }
1894}
1895
1896pub struct AppendZerosInput<'a, T>(&'a mut T);
1901
1902impl<'a, T> AppendZerosInput<'a, T> {
1903 pub fn new(input: &'a mut T) -> Self {
1905 Self(input)
1906 }
1907}
1908
1909impl<'a, T: codec::Input> codec::Input for AppendZerosInput<'a, T> {
1910 fn remaining_len(&mut self) -> Result<Option<usize>, codec::Error> {
1911 Ok(None)
1912 }
1913
1914 fn read(&mut self, into: &mut [u8]) -> Result<(), codec::Error> {
1915 let remaining = self.0.remaining_len()?;
1916 let completed = if let Some(n) = remaining {
1917 let readable = into.len().min(n);
1918 self.0.read(&mut into[..readable])?;
1920 readable
1921 } else {
1922 let mut i = 0;
1924 while i < into.len() {
1925 if let Ok(b) = self.0.read_byte() {
1926 into[i] = b;
1927 i += 1;
1928 } else {
1929 break
1930 }
1931 }
1932 i
1933 };
1934 for i in &mut into[completed..] {
1936 *i = 0;
1937 }
1938 Ok(())
1939 }
1940}
1941
1942pub struct TrailingZeroInput<'a>(&'a [u8]);
1944
1945impl<'a> TrailingZeroInput<'a> {
1946 pub fn new(data: &'a [u8]) -> Self {
1948 Self(data)
1949 }
1950
1951 pub fn zeroes() -> Self {
1953 Self::new(&[][..])
1954 }
1955}
1956
1957impl<'a> codec::Input for TrailingZeroInput<'a> {
1958 fn remaining_len(&mut self) -> Result<Option<usize>, codec::Error> {
1959 Ok(None)
1960 }
1961
1962 fn read(&mut self, into: &mut [u8]) -> Result<(), codec::Error> {
1963 let len_from_inner = into.len().min(self.0.len());
1964 into[..len_from_inner].copy_from_slice(&self.0[..len_from_inner]);
1965 for i in &mut into[len_from_inner..] {
1966 *i = 0;
1967 }
1968 self.0 = &self.0[len_from_inner..];
1969
1970 Ok(())
1971 }
1972}
1973
1974pub trait AccountIdConversion<AccountId>: Sized {
1976 fn into_account_truncating(&self) -> AccountId {
1979 self.into_sub_account_truncating(&())
1980 }
1981
1982 fn try_into_account(&self) -> Option<AccountId> {
1985 self.try_into_sub_account(&())
1986 }
1987
1988 fn try_from_account(a: &AccountId) -> Option<Self> {
1990 Self::try_from_sub_account::<()>(a).map(|x| x.0)
1991 }
1992
1993 fn into_sub_account_truncating<S: Encode>(&self, sub: S) -> AccountId;
2007
2008 fn try_into_sub_account<S: Encode>(&self, sub: S) -> Option<AccountId>;
2012
2013 fn try_from_sub_account<S: Decode>(x: &AccountId) -> Option<(Self, S)>;
2015}
2016
2017impl<T: Encode + Decode, Id: Encode + Decode + TypeId> AccountIdConversion<T> for Id {
2020 fn into_sub_account_truncating<S: Encode>(&self, sub: S) -> T {
2024 (Id::TYPE_ID, self, sub)
2025 .using_encoded(|b| T::decode(&mut TrailingZeroInput(b)))
2026 .expect("All byte sequences are valid `AccountIds`; qed")
2027 }
2028
2029 fn try_into_sub_account<S: Encode>(&self, sub: S) -> Option<T> {
2031 let encoded_seed = (Id::TYPE_ID, self, sub).encode();
2032 let account = T::decode(&mut TrailingZeroInput(&encoded_seed))
2033 .expect("All byte sequences are valid `AccountIds`; qed");
2034 if encoded_seed.len() <= account.encoded_size() {
2037 Some(account)
2038 } else {
2039 None
2040 }
2041 }
2042
2043 fn try_from_sub_account<S: Decode>(x: &T) -> Option<(Self, S)> {
2044 x.using_encoded(|d| {
2045 if d[0..4] != Id::TYPE_ID {
2046 return None
2047 }
2048 let mut cursor = &d[4..];
2049 let result = Decode::decode(&mut cursor).ok()?;
2050 if cursor.iter().all(|x| *x == 0) {
2051 Some(result)
2052 } else {
2053 None
2054 }
2055 })
2056 }
2057}
2058
2059#[macro_export]
2066macro_rules! count {
2067 ($f:ident ($($x:tt)*) ) => ();
2068 ($f:ident ($($x:tt)*) $x1:tt) => { $f!($($x)* 0); };
2069 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt) => { $f!($($x)* 0); $f!($($x)* 1); };
2070 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt) => { $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); };
2071 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt, $x4:tt) => {
2072 $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); $f!($($x)* 3);
2073 };
2074 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt, $x4:tt, $x5:tt) => {
2075 $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); $f!($($x)* 3); $f!($($x)* 4);
2076 };
2077}
2078
2079#[doc(hidden)]
2080#[macro_export]
2081macro_rules! impl_opaque_keys_inner {
2082 (
2083 $( #[ $attr:meta ] )*
2084 pub struct $name:ident {
2085 $(
2086 $( #[ $inner_attr:meta ] )*
2087 pub $field:ident: $type:ty,
2088 )*
2089 }
2090 ) => {
2091 $( #[ $attr ] )*
2092 #[derive(
2093 Clone, PartialEq, Eq,
2094 $crate::codec::Encode,
2095 $crate::codec::Decode,
2096 $crate::codec::DecodeWithMemTracking,
2097 $crate::scale_info::TypeInfo,
2098 $crate::RuntimeDebug,
2099 )]
2100 pub struct $name {
2101 $(
2102 $( #[ $inner_attr ] )*
2103 pub $field: <$type as $crate::BoundToRuntimeAppPublic>::Public,
2104 )*
2105 }
2106
2107 impl $name {
2108 pub fn generate(seed: Option<$crate::Vec<u8>>) -> $crate::Vec<u8> {
2114 let keys = Self{
2115 $(
2116 $field: <
2117 <
2118 $type as $crate::BoundToRuntimeAppPublic
2119 >::Public as $crate::RuntimeAppPublic
2120 >::generate_pair(seed.clone()),
2121 )*
2122 };
2123 $crate::codec::Encode::encode(&keys)
2124 }
2125
2126 pub fn into_raw_public_keys(
2128 self,
2129 ) -> $crate::Vec<($crate::Vec<u8>, $crate::KeyTypeId)> {
2130 let mut keys = Vec::new();
2131 $(
2132 keys.push((
2133 $crate::RuntimeAppPublic::to_raw_vec(&self.$field),
2134 <
2135 <
2136 $type as $crate::BoundToRuntimeAppPublic
2137 >::Public as $crate::RuntimeAppPublic
2138 >::ID,
2139 ));
2140 )*
2141
2142 keys
2143 }
2144
2145 pub fn decode_into_raw_public_keys(
2150 encoded: &[u8],
2151 ) -> Option<$crate::Vec<($crate::Vec<u8>, $crate::KeyTypeId)>> {
2152 <Self as $crate::codec::Decode>::decode(&mut &encoded[..])
2153 .ok()
2154 .map(|s| s.into_raw_public_keys())
2155 }
2156 }
2157
2158 impl $crate::traits::OpaqueKeys for $name {
2159 type KeyTypeIdProviders = ( $( $type, )* );
2160
2161 fn key_ids() -> &'static [$crate::KeyTypeId] {
2162 &[
2163 $(
2164 <
2165 <
2166 $type as $crate::BoundToRuntimeAppPublic
2167 >::Public as $crate::RuntimeAppPublic
2168 >::ID
2169 ),*
2170 ]
2171 }
2172
2173 fn get_raw(&self, i: $crate::KeyTypeId) -> &[u8] {
2174 match i {
2175 $(
2176 i if i == <
2177 <
2178 $type as $crate::BoundToRuntimeAppPublic
2179 >::Public as $crate::RuntimeAppPublic
2180 >::ID =>
2181 self.$field.as_ref(),
2182 )*
2183 _ => &[],
2184 }
2185 }
2186 }
2187 };
2188}
2189
2190#[macro_export]
2214#[cfg(any(feature = "serde", feature = "std"))]
2215macro_rules! impl_opaque_keys {
2216 {
2217 $( #[ $attr:meta ] )*
2218 pub struct $name:ident {
2219 $(
2220 $( #[ $inner_attr:meta ] )*
2221 pub $field:ident: $type:ty,
2222 )*
2223 }
2224 } => {
2225 $crate::paste::paste! {
2226 use $crate::serde as [< __opaque_keys_serde_import__ $name >];
2227
2228 $crate::impl_opaque_keys_inner! {
2229 $( #[ $attr ] )*
2230 #[derive($crate::serde::Serialize, $crate::serde::Deserialize)]
2231 #[serde(crate = "__opaque_keys_serde_import__" $name)]
2232 pub struct $name {
2233 $(
2234 $( #[ $inner_attr ] )*
2235 pub $field: $type,
2236 )*
2237 }
2238 }
2239 }
2240 }
2241}
2242
2243#[macro_export]
2244#[cfg(all(not(feature = "std"), not(feature = "serde")))]
2245#[doc(hidden)]
2246macro_rules! impl_opaque_keys {
2247 {
2248 $( #[ $attr:meta ] )*
2249 pub struct $name:ident {
2250 $(
2251 $( #[ $inner_attr:meta ] )*
2252 pub $field:ident: $type:ty,
2253 )*
2254 }
2255 } => {
2256 $crate::impl_opaque_keys_inner! {
2257 $( #[ $attr ] )*
2258 pub struct $name {
2259 $(
2260 $( #[ $inner_attr ] )*
2261 pub $field: $type,
2262 )*
2263 }
2264 }
2265 }
2266}
2267
2268pub trait Printable {
2270 fn print(&self);
2272}
2273
2274impl<T: Printable> Printable for &T {
2275 fn print(&self) {
2276 (*self).print()
2277 }
2278}
2279
2280impl Printable for u8 {
2281 fn print(&self) {
2282 (*self as u64).print()
2283 }
2284}
2285
2286impl Printable for u32 {
2287 fn print(&self) {
2288 (*self as u64).print()
2289 }
2290}
2291
2292impl Printable for usize {
2293 fn print(&self) {
2294 (*self as u64).print()
2295 }
2296}
2297
2298impl Printable for u64 {
2299 fn print(&self) {
2300 sp_io::misc::print_num(*self);
2301 }
2302}
2303
2304impl Printable for &[u8] {
2305 fn print(&self) {
2306 sp_io::misc::print_hex(self);
2307 }
2308}
2309
2310impl<const N: usize> Printable for [u8; N] {
2311 fn print(&self) {
2312 sp_io::misc::print_hex(&self[..]);
2313 }
2314}
2315
2316impl Printable for &str {
2317 fn print(&self) {
2318 sp_io::misc::print_utf8(self.as_bytes());
2319 }
2320}
2321
2322impl Printable for bool {
2323 fn print(&self) {
2324 if *self {
2325 "true".print()
2326 } else {
2327 "false".print()
2328 }
2329 }
2330}
2331
2332impl Printable for sp_weights::Weight {
2333 fn print(&self) {
2334 self.ref_time().print()
2335 }
2336}
2337
2338impl Printable for () {
2339 fn print(&self) {
2340 "()".print()
2341 }
2342}
2343
2344#[impl_for_tuples(1, 12)]
2345impl Printable for Tuple {
2346 fn print(&self) {
2347 for_tuples!( #( Tuple.print(); )* )
2348 }
2349}
2350
2351#[cfg(feature = "std")]
2353pub trait BlockIdTo<Block: self::Block> {
2354 type Error: std::error::Error;
2356
2357 fn to_hash(
2359 &self,
2360 block_id: &crate::generic::BlockId<Block>,
2361 ) -> Result<Option<Block::Hash>, Self::Error>;
2362
2363 fn to_number(
2365 &self,
2366 block_id: &crate::generic::BlockId<Block>,
2367 ) -> Result<Option<NumberFor<Block>>, Self::Error>;
2368}
2369
2370pub trait BlockNumberProvider {
2372 type BlockNumber: Codec
2374 + DecodeWithMemTracking
2375 + Clone
2376 + Ord
2377 + Eq
2378 + AtLeast32BitUnsigned
2379 + TypeInfo
2380 + Debug
2381 + MaxEncodedLen
2382 + Copy
2383 + EncodeLike
2384 + Default;
2385
2386 fn current_block_number() -> Self::BlockNumber;
2402
2403 #[cfg(any(feature = "std", feature = "runtime-benchmarks"))]
2409 fn set_block_number(_block: Self::BlockNumber) {}
2410}
2411
2412impl BlockNumberProvider for () {
2413 type BlockNumber = u32;
2414 fn current_block_number() -> Self::BlockNumber {
2415 0
2416 }
2417}
2418
2419#[cfg(test)]
2420mod tests {
2421 use super::*;
2422 use crate::codec::{Decode, Encode, Input};
2423 use sp_core::{
2424 crypto::{Pair, UncheckedFrom},
2425 ecdsa, ed25519, sr25519,
2426 };
2427
2428 macro_rules! signature_verify_test {
2429 ($algorithm:ident) => {
2430 let msg = &b"test-message"[..];
2431 let wrong_msg = &b"test-msg"[..];
2432 let (pair, _) = $algorithm::Pair::generate();
2433
2434 let signature = pair.sign(&msg);
2435 assert!($algorithm::Pair::verify(&signature, msg, &pair.public()));
2436
2437 assert!(signature.verify(msg, &pair.public()));
2438 assert!(!signature.verify(wrong_msg, &pair.public()));
2439 };
2440 }
2441
2442 mod t {
2443 use sp_application_crypto::{app_crypto, sr25519};
2444 use sp_core::crypto::KeyTypeId;
2445 app_crypto!(sr25519, KeyTypeId(*b"test"));
2446 }
2447
2448 #[test]
2449 fn app_verify_works() {
2450 use super::AppVerify;
2451 use t::*;
2452
2453 let s = Signature::try_from(vec![0; 64]).unwrap();
2454 let _ = s.verify(&[0u8; 100][..], &Public::unchecked_from([0; 32]));
2455 }
2456
2457 #[derive(Encode, Decode, Default, PartialEq, Debug)]
2458 struct U128Value(u128);
2459 impl super::TypeId for U128Value {
2460 const TYPE_ID: [u8; 4] = [0x0d, 0xf0, 0x0d, 0xf0];
2461 }
2462 #[derive(Encode, Decode, Default, PartialEq, Debug)]
2465 struct U32Value(u32);
2466 impl super::TypeId for U32Value {
2467 const TYPE_ID: [u8; 4] = [0x0d, 0xf0, 0xfe, 0xca];
2468 }
2469 #[derive(Encode, Decode, Default, PartialEq, Debug)]
2472 struct U16Value(u16);
2473 impl super::TypeId for U16Value {
2474 const TYPE_ID: [u8; 4] = [0xfe, 0xca, 0x0d, 0xf0];
2475 }
2476 type AccountId = u64;
2479
2480 #[test]
2481 fn into_account_truncating_should_work() {
2482 let r: AccountId = U32Value::into_account_truncating(&U32Value(0xdeadbeef));
2483 assert_eq!(r, 0x_deadbeef_cafef00d);
2484 }
2485
2486 #[test]
2487 fn try_into_account_should_work() {
2488 let r: AccountId = U32Value::try_into_account(&U32Value(0xdeadbeef)).unwrap();
2489 assert_eq!(r, 0x_deadbeef_cafef00d);
2490
2491 let maybe: Option<AccountId> = U128Value::try_into_account(&U128Value(u128::MAX));
2493 assert!(maybe.is_none());
2494 }
2495
2496 #[test]
2497 fn try_from_account_should_work() {
2498 let r = U32Value::try_from_account(&0x_deadbeef_cafef00d_u64);
2499 assert_eq!(r.unwrap(), U32Value(0xdeadbeef));
2500 }
2501
2502 #[test]
2503 fn into_account_truncating_with_fill_should_work() {
2504 let r: AccountId = U16Value::into_account_truncating(&U16Value(0xc0da));
2505 assert_eq!(r, 0x_0000_c0da_f00dcafe);
2506 }
2507
2508 #[test]
2509 fn try_into_sub_account_should_work() {
2510 let r: AccountId = U16Value::try_into_account(&U16Value(0xc0da)).unwrap();
2511 assert_eq!(r, 0x_0000_c0da_f00dcafe);
2512
2513 let maybe: Option<AccountId> = U16Value::try_into_sub_account(
2514 &U16Value(0xc0da),
2515 "a really large amount of additional encoded information which will certainly overflow the account id type ;)"
2516 );
2517
2518 assert!(maybe.is_none())
2519 }
2520
2521 #[test]
2522 fn try_from_account_with_fill_should_work() {
2523 let r = U16Value::try_from_account(&0x0000_c0da_f00dcafe_u64);
2524 assert_eq!(r.unwrap(), U16Value(0xc0da));
2525 }
2526
2527 #[test]
2528 fn bad_try_from_account_should_fail() {
2529 let r = U16Value::try_from_account(&0x0000_c0de_baadcafe_u64);
2530 assert!(r.is_none());
2531 let r = U16Value::try_from_account(&0x0100_c0da_f00dcafe_u64);
2532 assert!(r.is_none());
2533 }
2534
2535 #[test]
2536 fn trailing_zero_should_work() {
2537 let mut t = super::TrailingZeroInput(&[1, 2, 3]);
2538 assert_eq!(t.remaining_len(), Ok(None));
2539 let mut buffer = [0u8; 2];
2540 assert_eq!(t.read(&mut buffer), Ok(()));
2541 assert_eq!(t.remaining_len(), Ok(None));
2542 assert_eq!(buffer, [1, 2]);
2543 assert_eq!(t.read(&mut buffer), Ok(()));
2544 assert_eq!(t.remaining_len(), Ok(None));
2545 assert_eq!(buffer, [3, 0]);
2546 assert_eq!(t.read(&mut buffer), Ok(()));
2547 assert_eq!(t.remaining_len(), Ok(None));
2548 assert_eq!(buffer, [0, 0]);
2549 }
2550
2551 #[test]
2552 fn ed25519_verify_works() {
2553 signature_verify_test!(ed25519);
2554 }
2555
2556 #[test]
2557 fn sr25519_verify_works() {
2558 signature_verify_test!(sr25519);
2559 }
2560
2561 #[test]
2562 fn ecdsa_verify_works() {
2563 signature_verify_test!(ecdsa);
2564 }
2565}