1use crate::{
21 generic::Digest,
22 scale_info::{StaticTypeInfo, TypeInfo},
23 transaction_validity::{
24 TransactionSource, TransactionValidity, TransactionValidityError, UnknownTransaction,
25 ValidTransaction,
26 },
27 DispatchResult, OpaqueExtrinsic,
28};
29use alloc::vec::Vec;
30use codec::{
31 Codec, Decode, DecodeWithMemTracking, Encode, EncodeLike, FullCodec, HasCompact, MaxEncodedLen,
32};
33#[doc(hidden)]
34pub use core::{fmt::Debug, marker::PhantomData};
35use impl_trait_for_tuples::impl_for_tuples;
36#[cfg(feature = "serde")]
37use serde::{de::DeserializeOwned, Deserialize, Serialize};
38use sp_application_crypto::AppCrypto;
39pub use sp_arithmetic::traits::{
40 checked_pow, ensure_pow, AtLeast32Bit, AtLeast32BitUnsigned, Bounded, CheckedAdd, CheckedDiv,
41 CheckedMul, CheckedShl, CheckedShr, CheckedSub, Ensure, EnsureAdd, EnsureAddAssign, EnsureDiv,
42 EnsureDivAssign, EnsureFixedPointNumber, EnsureFrom, EnsureInto, EnsureMul, EnsureMulAssign,
43 EnsureOp, EnsureOpAssign, EnsureSub, EnsureSubAssign, IntegerSquareRoot, One,
44 SaturatedConversion, Saturating, UniqueSaturatedFrom, UniqueSaturatedInto, Zero,
45};
46use sp_core::{self, storage::StateVersion, Hasher, 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 LazyExtrinsic: Sized {
1305 fn decode_unprefixed(data: &[u8]) -> Result<Self, codec::Error>;
1313}
1314
1315pub trait LazyBlock: Debug + Encode + Decode + Sized {
1317 type Extrinsic: LazyExtrinsic;
1319 type Header: Header;
1321
1322 fn header(&self) -> &Self::Header;
1324
1325 fn header_mut(&mut self) -> &mut Self::Header;
1327
1328 fn extrinsics(&self) -> impl Iterator<Item = Result<Self::Extrinsic, codec::Error>>;
1332}
1333
1334pub trait Block:
1339 HeaderProvider<HeaderT = Self::Header>
1340 + Into<Self::LazyBlock>
1341 + EncodeLike<Self::LazyBlock>
1342 + Clone
1343 + Send
1344 + Sync
1345 + Codec
1346 + DecodeWithMemTracking
1347 + Eq
1348 + MaybeSerialize
1349 + Debug
1350 + 'static
1351{
1352 type Extrinsic: Member + Codec + ExtrinsicLike + MaybeSerialize + Into<OpaqueExtrinsic>;
1354 type Header: Header<Hash = Self::Hash> + MaybeSerializeDeserialize;
1356 type Hash: HashOutput;
1358
1359 type LazyBlock: LazyBlock<Extrinsic = Self::Extrinsic, Header = Self::Header> + EncodeLike<Self>;
1362
1363 fn header(&self) -> &Self::Header;
1365 fn extrinsics(&self) -> &[Self::Extrinsic];
1367 fn deconstruct(self) -> (Self::Header, Vec<Self::Extrinsic>);
1369 fn new(header: Self::Header, extrinsics: Vec<Self::Extrinsic>) -> Self;
1371 fn hash(&self) -> Self::Hash {
1373 <<Self::Header as Header>::Hashing as Hash>::hash_of(self.header())
1374 }
1375}
1376
1377#[deprecated = "Use `ExtrinsicLike` along with the `CreateTransaction` trait family instead"]
1379pub trait Extrinsic: Sized {
1380 type Call: TypeInfo;
1382
1383 type SignaturePayload: SignaturePayload;
1389
1390 fn is_signed(&self) -> Option<bool> {
1393 None
1394 }
1395
1396 fn is_bare(&self) -> bool {
1398 !self.is_signed().unwrap_or(true)
1399 }
1400
1401 fn new(_call: Self::Call, _signed_data: Option<Self::SignaturePayload>) -> Option<Self> {
1404 None
1405 }
1406}
1407
1408pub trait ExtrinsicLike: Sized {
1410 #[deprecated = "Use and implement `!is_bare()` instead"]
1413 fn is_signed(&self) -> Option<bool> {
1414 None
1415 }
1416
1417 fn is_bare(&self) -> bool {
1419 #[allow(deprecated)]
1420 !self.is_signed().unwrap_or(true)
1421 }
1422}
1423
1424#[allow(deprecated)]
1425impl<T> ExtrinsicLike for T
1426where
1427 T: Extrinsic,
1428{
1429 fn is_signed(&self) -> Option<bool> {
1430 #[allow(deprecated)]
1431 <Self as Extrinsic>::is_signed(&self)
1432 }
1433
1434 fn is_bare(&self) -> bool {
1435 <Self as Extrinsic>::is_bare(&self)
1436 }
1437}
1438
1439pub trait ExtrinsicCall: ExtrinsicLike {
1441 type Call;
1443
1444 fn call(&self) -> &Self::Call;
1446
1447 fn into_call(self) -> Self::Call;
1449}
1450
1451pub trait SignaturePayload {
1454 type SignatureAddress: TypeInfo;
1458
1459 type Signature: TypeInfo;
1463
1464 type SignatureExtra: TypeInfo;
1468}
1469
1470impl SignaturePayload for () {
1471 type SignatureAddress = ();
1472 type Signature = ();
1473 type SignatureExtra = ();
1474}
1475
1476pub trait ExtrinsicMetadata {
1478 const VERSIONS: &'static [u8];
1482
1483 type TransactionExtensions;
1485}
1486
1487pub type HashingFor<B> = <<B as Block>::Header as Header>::Hashing;
1489pub type NumberFor<B> = <<B as Block>::Header as Header>::Number;
1491pub trait Checkable<Context>: Sized {
1498 type Checked;
1500
1501 fn check(self, c: &Context) -> Result<Self::Checked, TransactionValidityError>;
1503
1504 #[cfg(feature = "try-runtime")]
1513 fn unchecked_into_checked_i_know_what_i_am_doing(
1514 self,
1515 c: &Context,
1516 ) -> Result<Self::Checked, TransactionValidityError>;
1517}
1518
1519pub trait BlindCheckable: Sized {
1524 type Checked;
1526
1527 fn check(self) -> Result<Self::Checked, TransactionValidityError>;
1529}
1530
1531impl<T: BlindCheckable, Context> Checkable<Context> for T {
1533 type Checked = <Self as BlindCheckable>::Checked;
1534
1535 fn check(self, _c: &Context) -> Result<Self::Checked, TransactionValidityError> {
1536 BlindCheckable::check(self)
1537 }
1538
1539 #[cfg(feature = "try-runtime")]
1540 fn unchecked_into_checked_i_know_what_i_am_doing(
1541 self,
1542 _: &Context,
1543 ) -> Result<Self::Checked, TransactionValidityError> {
1544 unreachable!();
1545 }
1546}
1547
1548pub trait RefundWeight {
1550 fn refund(&mut self, weight: sp_weights::Weight);
1552}
1553
1554pub trait ExtensionPostDispatchWeightHandler<DispatchInfo>: RefundWeight {
1557 fn set_extension_weight(&mut self, info: &DispatchInfo);
1559}
1560
1561impl RefundWeight for () {
1562 fn refund(&mut self, _weight: sp_weights::Weight) {}
1563}
1564
1565impl ExtensionPostDispatchWeightHandler<()> for () {
1566 fn set_extension_weight(&mut self, _info: &()) {}
1567}
1568
1569pub trait Dispatchable {
1572 type RuntimeOrigin: Debug;
1576 type Config;
1578 type Info;
1582 type PostInfo: Eq
1585 + PartialEq
1586 + Clone
1587 + Copy
1588 + Encode
1589 + Decode
1590 + Printable
1591 + ExtensionPostDispatchWeightHandler<Self::Info>;
1592 fn dispatch(self, origin: Self::RuntimeOrigin)
1594 -> crate::DispatchResultWithInfo<Self::PostInfo>;
1595}
1596
1597pub type DispatchOriginOf<T> = <T as Dispatchable>::RuntimeOrigin;
1599pub type DispatchInfoOf<T> = <T as Dispatchable>::Info;
1601pub type PostDispatchInfoOf<T> = <T as Dispatchable>::PostInfo;
1603
1604impl Dispatchable for () {
1605 type RuntimeOrigin = ();
1606 type Config = ();
1607 type Info = ();
1608 type PostInfo = ();
1609 fn dispatch(
1610 self,
1611 _origin: Self::RuntimeOrigin,
1612 ) -> crate::DispatchResultWithInfo<Self::PostInfo> {
1613 panic!("This implementation should not be used for actual dispatch.");
1614 }
1615}
1616
1617#[derive(Clone, Eq, PartialEq, Encode, Decode, DecodeWithMemTracking, RuntimeDebug, TypeInfo)]
1619pub struct FakeDispatchable<Inner>(pub Inner);
1620impl<Inner> From<Inner> for FakeDispatchable<Inner> {
1621 fn from(inner: Inner) -> Self {
1622 Self(inner)
1623 }
1624}
1625impl<Inner> FakeDispatchable<Inner> {
1626 pub fn deconstruct(self) -> Inner {
1628 self.0
1629 }
1630}
1631impl<Inner> AsRef<Inner> for FakeDispatchable<Inner> {
1632 fn as_ref(&self) -> &Inner {
1633 &self.0
1634 }
1635}
1636
1637impl<Inner> Dispatchable for FakeDispatchable<Inner> {
1638 type RuntimeOrigin = ();
1639 type Config = ();
1640 type Info = ();
1641 type PostInfo = ();
1642 fn dispatch(
1643 self,
1644 _origin: Self::RuntimeOrigin,
1645 ) -> crate::DispatchResultWithInfo<Self::PostInfo> {
1646 panic!("This implementation should not be used for actual dispatch.");
1647 }
1648}
1649
1650pub trait AsSystemOriginSigner<AccountId> {
1652 fn as_system_origin_signer(&self) -> Option<&AccountId>;
1655}
1656
1657pub trait AsTransactionAuthorizedOrigin {
1671 fn is_transaction_authorized(&self) -> bool;
1681}
1682
1683#[deprecated = "Use `TransactionExtension` instead."]
1686pub trait SignedExtension:
1687 Codec + DecodeWithMemTracking + Debug + Sync + Send + Clone + Eq + PartialEq + StaticTypeInfo
1688{
1689 const IDENTIFIER: &'static str;
1694
1695 type AccountId;
1697
1698 type Call: Dispatchable;
1700
1701 type AdditionalSigned: Codec + TypeInfo;
1704
1705 type Pre;
1707
1708 fn additional_signed(&self) -> Result<Self::AdditionalSigned, TransactionValidityError>;
1711
1712 fn validate(
1722 &self,
1723 _who: &Self::AccountId,
1724 _call: &Self::Call,
1725 _info: &DispatchInfoOf<Self::Call>,
1726 _len: usize,
1727 ) -> TransactionValidity {
1728 Ok(ValidTransaction::default())
1729 }
1730
1731 fn pre_dispatch(
1735 self,
1736 who: &Self::AccountId,
1737 call: &Self::Call,
1738 info: &DispatchInfoOf<Self::Call>,
1739 len: usize,
1740 ) -> Result<Self::Pre, TransactionValidityError>;
1741
1742 fn post_dispatch(
1759 _pre: Option<Self::Pre>,
1760 _info: &DispatchInfoOf<Self::Call>,
1761 _post_info: &PostDispatchInfoOf<Self::Call>,
1762 _len: usize,
1763 _result: &DispatchResult,
1764 ) -> Result<(), TransactionValidityError> {
1765 Ok(())
1766 }
1767
1768 fn metadata() -> Vec<TransactionExtensionMetadata> {
1777 alloc::vec![TransactionExtensionMetadata {
1778 identifier: Self::IDENTIFIER,
1779 ty: scale_info::meta_type::<Self>(),
1780 implicit: scale_info::meta_type::<Self::AdditionalSigned>()
1781 }]
1782 }
1783
1784 fn validate_unsigned(
1791 _call: &Self::Call,
1792 _info: &DispatchInfoOf<Self::Call>,
1793 _len: usize,
1794 ) -> TransactionValidity {
1795 Ok(ValidTransaction::default())
1796 }
1797
1798 fn pre_dispatch_unsigned(
1807 call: &Self::Call,
1808 info: &DispatchInfoOf<Self::Call>,
1809 len: usize,
1810 ) -> Result<(), TransactionValidityError> {
1811 Self::validate_unsigned(call, info, len).map(|_| ()).map_err(Into::into)
1812 }
1813}
1814
1815pub trait Applyable: Sized + Send + Sync {
1831 type Call: Dispatchable;
1833
1834 fn validate<V: ValidateUnsigned<Call = Self::Call>>(
1839 &self,
1840 source: TransactionSource,
1841 info: &DispatchInfoOf<Self::Call>,
1842 len: usize,
1843 ) -> TransactionValidity;
1844
1845 fn apply<V: ValidateUnsigned<Call = Self::Call>>(
1851 self,
1852 info: &DispatchInfoOf<Self::Call>,
1853 len: usize,
1854 ) -> crate::ApplyExtrinsicResultWithInfo<PostDispatchInfoOf<Self::Call>>;
1855}
1856
1857pub trait GetRuntimeBlockType {
1859 type RuntimeBlock: self::Block;
1861}
1862
1863pub trait GetNodeBlockType {
1865 type NodeBlock: self::Block;
1867}
1868
1869pub trait ValidateUnsigned {
1877 type Call;
1879
1880 fn pre_dispatch(call: &Self::Call) -> Result<(), TransactionValidityError> {
1893 Self::validate_unsigned(TransactionSource::InBlock, call)
1894 .map(|_| ())
1895 .map_err(Into::into)
1896 }
1897
1898 fn validate_unsigned(source: TransactionSource, call: &Self::Call) -> TransactionValidity;
1911}
1912
1913pub trait OpaqueKeys: Clone {
1916 type KeyTypeIdProviders;
1918
1919 fn key_ids() -> &'static [crate::KeyTypeId];
1921 fn get_raw(&self, i: super::KeyTypeId) -> &[u8];
1923 fn get<T: Decode>(&self, i: super::KeyTypeId) -> Option<T> {
1925 T::decode(&mut self.get_raw(i)).ok()
1926 }
1927 fn ownership_proof_is_valid(&self, _proof: &[u8]) -> bool {
1929 true
1930 }
1931}
1932
1933pub struct AppendZerosInput<'a, T>(&'a mut T);
1938
1939impl<'a, T> AppendZerosInput<'a, T> {
1940 pub fn new(input: &'a mut T) -> Self {
1942 Self(input)
1943 }
1944}
1945
1946impl<'a, T: codec::Input> codec::Input for AppendZerosInput<'a, T> {
1947 fn remaining_len(&mut self) -> Result<Option<usize>, codec::Error> {
1948 Ok(None)
1949 }
1950
1951 fn read(&mut self, into: &mut [u8]) -> Result<(), codec::Error> {
1952 let remaining = self.0.remaining_len()?;
1953 let completed = if let Some(n) = remaining {
1954 let readable = into.len().min(n);
1955 self.0.read(&mut into[..readable])?;
1957 readable
1958 } else {
1959 let mut i = 0;
1961 while i < into.len() {
1962 if let Ok(b) = self.0.read_byte() {
1963 into[i] = b;
1964 i += 1;
1965 } else {
1966 break
1967 }
1968 }
1969 i
1970 };
1971 for i in &mut into[completed..] {
1973 *i = 0;
1974 }
1975 Ok(())
1976 }
1977}
1978
1979pub struct TrailingZeroInput<'a>(&'a [u8]);
1981
1982impl<'a> TrailingZeroInput<'a> {
1983 pub fn new(data: &'a [u8]) -> Self {
1985 Self(data)
1986 }
1987
1988 pub fn zeroes() -> Self {
1990 Self::new(&[][..])
1991 }
1992}
1993
1994impl<'a> codec::Input for TrailingZeroInput<'a> {
1995 fn remaining_len(&mut self) -> Result<Option<usize>, codec::Error> {
1996 Ok(None)
1997 }
1998
1999 fn read(&mut self, into: &mut [u8]) -> Result<(), codec::Error> {
2000 let len_from_inner = into.len().min(self.0.len());
2001 into[..len_from_inner].copy_from_slice(&self.0[..len_from_inner]);
2002 for i in &mut into[len_from_inner..] {
2003 *i = 0;
2004 }
2005 self.0 = &self.0[len_from_inner..];
2006
2007 Ok(())
2008 }
2009}
2010
2011pub trait AccountIdConversion<AccountId>: Sized {
2013 fn into_account_truncating(&self) -> AccountId {
2016 self.into_sub_account_truncating(&())
2017 }
2018
2019 fn try_into_account(&self) -> Option<AccountId> {
2022 self.try_into_sub_account(&())
2023 }
2024
2025 fn try_from_account(a: &AccountId) -> Option<Self> {
2027 Self::try_from_sub_account::<()>(a).map(|x| x.0)
2028 }
2029
2030 fn into_sub_account_truncating<S: Encode>(&self, sub: S) -> AccountId;
2044
2045 fn try_into_sub_account<S: Encode>(&self, sub: S) -> Option<AccountId>;
2049
2050 fn try_from_sub_account<S: Decode>(x: &AccountId) -> Option<(Self, S)>;
2052}
2053
2054impl<T: Encode + Decode, Id: Encode + Decode + TypeId> AccountIdConversion<T> for Id {
2057 fn into_sub_account_truncating<S: Encode>(&self, sub: S) -> T {
2061 (Id::TYPE_ID, self, sub)
2062 .using_encoded(|b| T::decode(&mut TrailingZeroInput(b)))
2063 .expect("All byte sequences are valid `AccountIds`; qed")
2064 }
2065
2066 fn try_into_sub_account<S: Encode>(&self, sub: S) -> Option<T> {
2068 let encoded_seed = (Id::TYPE_ID, self, sub).encode();
2069 let account = T::decode(&mut TrailingZeroInput(&encoded_seed))
2070 .expect("All byte sequences are valid `AccountIds`; qed");
2071 if encoded_seed.len() <= account.encoded_size() {
2074 Some(account)
2075 } else {
2076 None
2077 }
2078 }
2079
2080 fn try_from_sub_account<S: Decode>(x: &T) -> Option<(Self, S)> {
2081 x.using_encoded(|d| {
2082 if d[0..4] != Id::TYPE_ID {
2083 return None
2084 }
2085 let mut cursor = &d[4..];
2086 let result = Decode::decode(&mut cursor).ok()?;
2087 if cursor.iter().all(|x| *x == 0) {
2088 Some(result)
2089 } else {
2090 None
2091 }
2092 })
2093 }
2094}
2095
2096#[macro_export]
2103macro_rules! count {
2104 ($f:ident ($($x:tt)*) ) => ();
2105 ($f:ident ($($x:tt)*) $x1:tt) => { $f!($($x)* 0); };
2106 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt) => { $f!($($x)* 0); $f!($($x)* 1); };
2107 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt) => { $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); };
2108 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt, $x4:tt) => {
2109 $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); $f!($($x)* 3);
2110 };
2111 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt, $x4:tt, $x5:tt) => {
2112 $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); $f!($($x)* 3); $f!($($x)* 4);
2113 };
2114}
2115
2116#[doc(hidden)]
2117#[macro_export]
2118macro_rules! impl_opaque_keys_inner {
2119 (
2120 $( #[ $attr:meta ] )*
2121 pub struct $name:ident {
2122 $(
2123 $( #[ $inner_attr:meta ] )*
2124 pub $field:ident: $type:ty,
2125 )*
2126 }
2127 ) => {
2128 $( #[ $attr ] )*
2129 #[derive(
2130 Clone, PartialEq, Eq,
2131 $crate::codec::Encode,
2132 $crate::codec::Decode,
2133 $crate::codec::DecodeWithMemTracking,
2134 $crate::scale_info::TypeInfo,
2135 $crate::RuntimeDebug,
2136 )]
2137 pub struct $name {
2138 $(
2139 $( #[ $inner_attr ] )*
2140 pub $field: <$type as $crate::BoundToRuntimeAppPublic>::Public,
2141 )*
2142 }
2143
2144 impl $name {
2145 pub fn generate(seed: Option<$crate::Vec<u8>>) -> $crate::Vec<u8> {
2151 let keys = Self{
2152 $(
2153 $field: <
2154 <
2155 $type as $crate::BoundToRuntimeAppPublic
2156 >::Public as $crate::RuntimeAppPublic
2157 >::generate_pair(seed.clone()),
2158 )*
2159 };
2160 $crate::codec::Encode::encode(&keys)
2161 }
2162
2163 pub fn into_raw_public_keys(
2165 self,
2166 ) -> $crate::Vec<($crate::Vec<u8>, $crate::KeyTypeId)> {
2167 let mut keys = Vec::new();
2168 $(
2169 keys.push((
2170 $crate::RuntimeAppPublic::to_raw_vec(&self.$field),
2171 <
2172 <
2173 $type as $crate::BoundToRuntimeAppPublic
2174 >::Public as $crate::RuntimeAppPublic
2175 >::ID,
2176 ));
2177 )*
2178
2179 keys
2180 }
2181
2182 pub fn decode_into_raw_public_keys(
2187 encoded: &[u8],
2188 ) -> Option<$crate::Vec<($crate::Vec<u8>, $crate::KeyTypeId)>> {
2189 <Self as $crate::codec::Decode>::decode(&mut &encoded[..])
2190 .ok()
2191 .map(|s| s.into_raw_public_keys())
2192 }
2193 }
2194
2195 impl $crate::traits::OpaqueKeys for $name {
2196 type KeyTypeIdProviders = ( $( $type, )* );
2197
2198 fn key_ids() -> &'static [$crate::KeyTypeId] {
2199 &[
2200 $(
2201 <
2202 <
2203 $type as $crate::BoundToRuntimeAppPublic
2204 >::Public as $crate::RuntimeAppPublic
2205 >::ID
2206 ),*
2207 ]
2208 }
2209
2210 fn get_raw(&self, i: $crate::KeyTypeId) -> &[u8] {
2211 match i {
2212 $(
2213 i if i == <
2214 <
2215 $type as $crate::BoundToRuntimeAppPublic
2216 >::Public as $crate::RuntimeAppPublic
2217 >::ID =>
2218 self.$field.as_ref(),
2219 )*
2220 _ => &[],
2221 }
2222 }
2223 }
2224 };
2225}
2226
2227#[macro_export]
2251#[cfg(any(feature = "serde", feature = "std"))]
2252macro_rules! impl_opaque_keys {
2253 {
2254 $( #[ $attr:meta ] )*
2255 pub struct $name:ident {
2256 $(
2257 $( #[ $inner_attr:meta ] )*
2258 pub $field:ident: $type:ty,
2259 )*
2260 }
2261 } => {
2262 $crate::paste::paste! {
2263 use $crate::serde as [< __opaque_keys_serde_import__ $name >];
2264
2265 $crate::impl_opaque_keys_inner! {
2266 $( #[ $attr ] )*
2267 #[derive($crate::serde::Serialize, $crate::serde::Deserialize)]
2268 #[serde(crate = "__opaque_keys_serde_import__" $name)]
2269 pub struct $name {
2270 $(
2271 $( #[ $inner_attr ] )*
2272 pub $field: $type,
2273 )*
2274 }
2275 }
2276 }
2277 }
2278}
2279
2280#[macro_export]
2281#[cfg(all(not(feature = "std"), not(feature = "serde")))]
2282#[doc(hidden)]
2283macro_rules! impl_opaque_keys {
2284 {
2285 $( #[ $attr:meta ] )*
2286 pub struct $name:ident {
2287 $(
2288 $( #[ $inner_attr:meta ] )*
2289 pub $field:ident: $type:ty,
2290 )*
2291 }
2292 } => {
2293 $crate::impl_opaque_keys_inner! {
2294 $( #[ $attr ] )*
2295 pub struct $name {
2296 $(
2297 $( #[ $inner_attr ] )*
2298 pub $field: $type,
2299 )*
2300 }
2301 }
2302 }
2303}
2304
2305pub trait Printable {
2307 fn print(&self);
2309}
2310
2311impl<T: Printable> Printable for &T {
2312 fn print(&self) {
2313 (*self).print()
2314 }
2315}
2316
2317impl Printable for u8 {
2318 fn print(&self) {
2319 (*self as u64).print()
2320 }
2321}
2322
2323impl Printable for u32 {
2324 fn print(&self) {
2325 (*self as u64).print()
2326 }
2327}
2328
2329impl Printable for usize {
2330 fn print(&self) {
2331 (*self as u64).print()
2332 }
2333}
2334
2335impl Printable for u64 {
2336 fn print(&self) {
2337 sp_io::misc::print_num(*self);
2338 }
2339}
2340
2341impl Printable for &[u8] {
2342 fn print(&self) {
2343 sp_io::misc::print_hex(self);
2344 }
2345}
2346
2347impl<const N: usize> Printable for [u8; N] {
2348 fn print(&self) {
2349 sp_io::misc::print_hex(&self[..]);
2350 }
2351}
2352
2353impl Printable for &str {
2354 fn print(&self) {
2355 sp_io::misc::print_utf8(self.as_bytes());
2356 }
2357}
2358
2359impl Printable for bool {
2360 fn print(&self) {
2361 if *self {
2362 "true".print()
2363 } else {
2364 "false".print()
2365 }
2366 }
2367}
2368
2369impl Printable for sp_weights::Weight {
2370 fn print(&self) {
2371 self.ref_time().print()
2372 }
2373}
2374
2375impl Printable for () {
2376 fn print(&self) {
2377 "()".print()
2378 }
2379}
2380
2381#[impl_for_tuples(1, 12)]
2382impl Printable for Tuple {
2383 fn print(&self) {
2384 for_tuples!( #( Tuple.print(); )* )
2385 }
2386}
2387
2388#[cfg(feature = "std")]
2390pub trait BlockIdTo<Block: self::Block> {
2391 type Error: std::error::Error;
2393
2394 fn to_hash(
2396 &self,
2397 block_id: &crate::generic::BlockId<Block>,
2398 ) -> Result<Option<Block::Hash>, Self::Error>;
2399
2400 fn to_number(
2402 &self,
2403 block_id: &crate::generic::BlockId<Block>,
2404 ) -> Result<Option<NumberFor<Block>>, Self::Error>;
2405}
2406
2407pub trait BlockNumberProvider {
2409 type BlockNumber: Codec
2411 + DecodeWithMemTracking
2412 + Clone
2413 + Ord
2414 + Eq
2415 + AtLeast32BitUnsigned
2416 + TypeInfo
2417 + Debug
2418 + MaxEncodedLen
2419 + Copy
2420 + EncodeLike
2421 + Default;
2422
2423 fn current_block_number() -> Self::BlockNumber;
2439
2440 #[cfg(any(feature = "std", feature = "runtime-benchmarks"))]
2446 fn set_block_number(_block: Self::BlockNumber) {}
2447}
2448
2449impl BlockNumberProvider for () {
2450 type BlockNumber = u32;
2451 fn current_block_number() -> Self::BlockNumber {
2452 0
2453 }
2454}
2455
2456#[cfg(test)]
2457mod tests {
2458 use super::*;
2459 use crate::codec::{Decode, Encode, Input};
2460 use sp_core::{
2461 crypto::{Pair, UncheckedFrom},
2462 ecdsa, ed25519, sr25519,
2463 };
2464
2465 macro_rules! signature_verify_test {
2466 ($algorithm:ident) => {
2467 let msg = &b"test-message"[..];
2468 let wrong_msg = &b"test-msg"[..];
2469 let (pair, _) = $algorithm::Pair::generate();
2470
2471 let signature = pair.sign(&msg);
2472 assert!($algorithm::Pair::verify(&signature, msg, &pair.public()));
2473
2474 assert!(signature.verify(msg, &pair.public()));
2475 assert!(!signature.verify(wrong_msg, &pair.public()));
2476 };
2477 }
2478
2479 mod t {
2480 use sp_application_crypto::{app_crypto, sr25519};
2481 use sp_core::crypto::KeyTypeId;
2482 app_crypto!(sr25519, KeyTypeId(*b"test"));
2483 }
2484
2485 #[test]
2486 fn app_verify_works() {
2487 use super::AppVerify;
2488 use t::*;
2489
2490 let s = Signature::try_from(vec![0; 64]).unwrap();
2491 let _ = s.verify(&[0u8; 100][..], &Public::unchecked_from([0; 32]));
2492 }
2493
2494 #[derive(Encode, Decode, Default, PartialEq, Debug)]
2495 struct U128Value(u128);
2496 impl super::TypeId for U128Value {
2497 const TYPE_ID: [u8; 4] = [0x0d, 0xf0, 0x0d, 0xf0];
2498 }
2499 #[derive(Encode, Decode, Default, PartialEq, Debug)]
2502 struct U32Value(u32);
2503 impl super::TypeId for U32Value {
2504 const TYPE_ID: [u8; 4] = [0x0d, 0xf0, 0xfe, 0xca];
2505 }
2506 #[derive(Encode, Decode, Default, PartialEq, Debug)]
2509 struct U16Value(u16);
2510 impl super::TypeId for U16Value {
2511 const TYPE_ID: [u8; 4] = [0xfe, 0xca, 0x0d, 0xf0];
2512 }
2513 type AccountId = u64;
2516
2517 #[test]
2518 fn into_account_truncating_should_work() {
2519 let r: AccountId = U32Value::into_account_truncating(&U32Value(0xdeadbeef));
2520 assert_eq!(r, 0x_deadbeef_cafef00d);
2521 }
2522
2523 #[test]
2524 fn try_into_account_should_work() {
2525 let r: AccountId = U32Value::try_into_account(&U32Value(0xdeadbeef)).unwrap();
2526 assert_eq!(r, 0x_deadbeef_cafef00d);
2527
2528 let maybe: Option<AccountId> = U128Value::try_into_account(&U128Value(u128::MAX));
2530 assert!(maybe.is_none());
2531 }
2532
2533 #[test]
2534 fn try_from_account_should_work() {
2535 let r = U32Value::try_from_account(&0x_deadbeef_cafef00d_u64);
2536 assert_eq!(r.unwrap(), U32Value(0xdeadbeef));
2537 }
2538
2539 #[test]
2540 fn into_account_truncating_with_fill_should_work() {
2541 let r: AccountId = U16Value::into_account_truncating(&U16Value(0xc0da));
2542 assert_eq!(r, 0x_0000_c0da_f00dcafe);
2543 }
2544
2545 #[test]
2546 fn try_into_sub_account_should_work() {
2547 let r: AccountId = U16Value::try_into_account(&U16Value(0xc0da)).unwrap();
2548 assert_eq!(r, 0x_0000_c0da_f00dcafe);
2549
2550 let maybe: Option<AccountId> = U16Value::try_into_sub_account(
2551 &U16Value(0xc0da),
2552 "a really large amount of additional encoded information which will certainly overflow the account id type ;)"
2553 );
2554
2555 assert!(maybe.is_none())
2556 }
2557
2558 #[test]
2559 fn try_from_account_with_fill_should_work() {
2560 let r = U16Value::try_from_account(&0x0000_c0da_f00dcafe_u64);
2561 assert_eq!(r.unwrap(), U16Value(0xc0da));
2562 }
2563
2564 #[test]
2565 fn bad_try_from_account_should_fail() {
2566 let r = U16Value::try_from_account(&0x0000_c0de_baadcafe_u64);
2567 assert!(r.is_none());
2568 let r = U16Value::try_from_account(&0x0100_c0da_f00dcafe_u64);
2569 assert!(r.is_none());
2570 }
2571
2572 #[test]
2573 fn trailing_zero_should_work() {
2574 let mut t = super::TrailingZeroInput(&[1, 2, 3]);
2575 assert_eq!(t.remaining_len(), Ok(None));
2576 let mut buffer = [0u8; 2];
2577 assert_eq!(t.read(&mut buffer), Ok(()));
2578 assert_eq!(t.remaining_len(), Ok(None));
2579 assert_eq!(buffer, [1, 2]);
2580 assert_eq!(t.read(&mut buffer), Ok(()));
2581 assert_eq!(t.remaining_len(), Ok(None));
2582 assert_eq!(buffer, [3, 0]);
2583 assert_eq!(t.read(&mut buffer), Ok(()));
2584 assert_eq!(t.remaining_len(), Ok(None));
2585 assert_eq!(buffer, [0, 0]);
2586 }
2587
2588 #[test]
2589 fn ed25519_verify_works() {
2590 signature_verify_test!(ed25519);
2591 }
2592
2593 #[test]
2594 fn sr25519_verify_works() {
2595 signature_verify_test!(sr25519);
2596 }
2597
2598 #[test]
2599 fn ecdsa_verify_works() {
2600 signature_verify_test!(ecdsa);
2601 }
2602}