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::{Codec, Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen};
31#[doc(hidden)]
32pub use core::{fmt::Debug, marker::PhantomData};
33use impl_trait_for_tuples::impl_for_tuples;
34#[cfg(feature = "serde")]
35use serde::{de::DeserializeOwned, Deserialize, Serialize};
36use sp_application_crypto::AppCrypto;
37pub use sp_arithmetic::traits::{
38 checked_pow, ensure_pow, AtLeast32Bit, AtLeast32BitUnsigned, Bounded, CheckedAdd, CheckedDiv,
39 CheckedMul, CheckedShl, CheckedShr, CheckedSub, Ensure, EnsureAdd, EnsureAddAssign, EnsureDiv,
40 EnsureDivAssign, EnsureFixedPointNumber, EnsureFrom, EnsureInto, EnsureMul, EnsureMulAssign,
41 EnsureOp, EnsureOpAssign, EnsureSub, EnsureSubAssign, IntegerSquareRoot, One,
42 SaturatedConversion, Saturating, UniqueSaturatedFrom, UniqueSaturatedInto, Zero,
43};
44use sp_core::{self, storage::StateVersion, Hasher, RuntimeDebug, TypeId, U256};
45#[doc(hidden)]
46pub use sp_core::{
47 parameter_types, ConstBool, ConstI128, ConstI16, ConstI32, ConstI64, ConstI8, ConstU128,
48 ConstU16, ConstU32, ConstU64, ConstU8, Get, GetDefault, TryCollect, TypedGet,
49};
50#[cfg(feature = "std")]
51use std::fmt::Display;
52#[cfg(feature = "std")]
53use std::str::FromStr;
54
55pub mod transaction_extension;
56pub use transaction_extension::{
57 DispatchTransaction, Implication, ImplicationParts, TransactionExtension,
58 TransactionExtensionMetadata, TxBaseImplication, ValidateResult,
59};
60
61pub trait Lazy<T: ?Sized> {
63 fn get(&mut self) -> &T;
67}
68
69impl<'a> Lazy<[u8]> for &'a [u8] {
70 fn get(&mut self) -> &[u8] {
71 self
72 }
73}
74
75pub trait IdentifyAccount {
78 type AccountId;
80 fn into_account(self) -> Self::AccountId;
82}
83
84impl IdentifyAccount for sp_core::ed25519::Public {
85 type AccountId = Self;
86 fn into_account(self) -> Self {
87 self
88 }
89}
90
91impl IdentifyAccount for sp_core::sr25519::Public {
92 type AccountId = Self;
93 fn into_account(self) -> Self {
94 self
95 }
96}
97
98impl IdentifyAccount for sp_core::ecdsa::Public {
99 type AccountId = Self;
100 fn into_account(self) -> Self {
101 self
102 }
103}
104
105pub trait Verify {
107 type Signer: IdentifyAccount;
109 fn verify<L: Lazy<[u8]>>(
113 &self,
114 msg: L,
115 signer: &<Self::Signer as IdentifyAccount>::AccountId,
116 ) -> bool;
117}
118
119impl Verify for sp_core::ed25519::Signature {
120 type Signer = sp_core::ed25519::Public;
121
122 fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &sp_core::ed25519::Public) -> bool {
123 sp_io::crypto::ed25519_verify(self, msg.get(), signer)
124 }
125}
126
127impl Verify for sp_core::sr25519::Signature {
128 type Signer = sp_core::sr25519::Public;
129
130 fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &sp_core::sr25519::Public) -> bool {
131 sp_io::crypto::sr25519_verify(self, msg.get(), signer)
132 }
133}
134
135impl Verify for sp_core::ecdsa::Signature {
136 type Signer = sp_core::ecdsa::Public;
137 fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &sp_core::ecdsa::Public) -> bool {
138 match sp_io::crypto::secp256k1_ecdsa_recover_compressed(
139 self.as_ref(),
140 &sp_io::hashing::blake2_256(msg.get()),
141 ) {
142 Ok(pubkey) => signer.0 == pubkey,
143 _ => false,
144 }
145 }
146}
147
148pub trait AppVerify {
150 type AccountId;
152 fn verify<L: Lazy<[u8]>>(&self, msg: L, signer: &Self::AccountId) -> bool;
154}
155
156impl<
157 S: Verify<Signer = <<T as AppCrypto>::Public as sp_application_crypto::AppPublic>::Generic>
158 + From<T>,
159 T: sp_application_crypto::Wraps<Inner = S>
160 + sp_application_crypto::AppCrypto
161 + sp_application_crypto::AppSignature
162 + AsRef<S>
163 + AsMut<S>
164 + From<S>,
165 > AppVerify for T
166where
167 <S as Verify>::Signer: IdentifyAccount<AccountId = <S as Verify>::Signer>,
168 <<T as AppCrypto>::Public as sp_application_crypto::AppPublic>::Generic: IdentifyAccount<
169 AccountId = <<T as AppCrypto>::Public as sp_application_crypto::AppPublic>::Generic,
170 >,
171{
172 type AccountId = <T as AppCrypto>::Public;
173 fn verify<L: Lazy<[u8]>>(&self, msg: L, signer: &<T as AppCrypto>::Public) -> bool {
174 use sp_application_crypto::IsWrappedBy;
175 let inner: &S = self.as_ref();
176 let inner_pubkey =
177 <<T as AppCrypto>::Public as sp_application_crypto::AppPublic>::Generic::from_ref(
178 signer,
179 );
180 Verify::verify(inner, msg, inner_pubkey)
181 }
182}
183
184#[derive(Encode, Decode, RuntimeDebug)]
186pub struct BadOrigin;
187
188impl From<BadOrigin> for &'static str {
189 fn from(_: BadOrigin) -> &'static str {
190 "Bad origin"
191 }
192}
193
194#[derive(Encode, Decode, RuntimeDebug)]
196pub struct LookupError;
197
198impl From<LookupError> for &'static str {
199 fn from(_: LookupError) -> &'static str {
200 "Can not lookup"
201 }
202}
203
204impl From<LookupError> for TransactionValidityError {
205 fn from(_: LookupError) -> Self {
206 UnknownTransaction::CannotLookup.into()
207 }
208}
209
210pub trait Lookup {
212 type Source;
214 type Target;
216 fn lookup(&self, s: Self::Source) -> Result<Self::Target, LookupError>;
218}
219
220pub trait StaticLookup {
224 type Source: Codec + Clone + PartialEq + Debug + TypeInfo;
226 type Target;
228 fn lookup(s: Self::Source) -> Result<Self::Target, LookupError>;
230 fn unlookup(t: Self::Target) -> Self::Source;
232}
233
234#[derive(Clone, Copy, PartialEq, Eq)]
236pub struct IdentityLookup<T>(PhantomData<T>);
237impl<T> Default for IdentityLookup<T> {
238 fn default() -> Self {
239 Self(PhantomData::<T>::default())
240 }
241}
242
243impl<T: Codec + Clone + PartialEq + Debug + TypeInfo> StaticLookup for IdentityLookup<T> {
244 type Source = T;
245 type Target = T;
246 fn lookup(x: T) -> Result<T, LookupError> {
247 Ok(x)
248 }
249 fn unlookup(x: T) -> T {
250 x
251 }
252}
253
254impl<T> Lookup for IdentityLookup<T> {
255 type Source = T;
256 type Target = T;
257 fn lookup(&self, x: T) -> Result<T, LookupError> {
258 Ok(x)
259 }
260}
261
262pub struct AccountIdLookup<AccountId, AccountIndex>(PhantomData<(AccountId, AccountIndex)>);
264impl<AccountId, AccountIndex> StaticLookup for AccountIdLookup<AccountId, AccountIndex>
265where
266 AccountId: Codec + Clone + PartialEq + Debug,
267 AccountIndex: Codec + Clone + PartialEq + Debug,
268 crate::MultiAddress<AccountId, AccountIndex>: Codec + StaticTypeInfo,
269{
270 type Source = crate::MultiAddress<AccountId, AccountIndex>;
271 type Target = AccountId;
272 fn lookup(x: Self::Source) -> Result<Self::Target, LookupError> {
273 match x {
274 crate::MultiAddress::Id(i) => Ok(i),
275 _ => Err(LookupError),
276 }
277 }
278 fn unlookup(x: Self::Target) -> Self::Source {
279 crate::MultiAddress::Id(x)
280 }
281}
282
283impl<A, B> StaticLookup for (A, B)
285where
286 A: StaticLookup,
287 B: StaticLookup<Source = A::Source, Target = A::Target>,
288{
289 type Source = A::Source;
290 type Target = A::Target;
291
292 fn lookup(x: Self::Source) -> Result<Self::Target, LookupError> {
293 A::lookup(x.clone()).or_else(|_| B::lookup(x))
294 }
295 fn unlookup(x: Self::Target) -> Self::Source {
296 A::unlookup(x)
297 }
298}
299
300pub trait Morph<A> {
303 type Outcome;
305
306 fn morph(a: A) -> Self::Outcome;
308}
309
310impl<T> Morph<T> for Identity {
312 type Outcome = T;
313 fn morph(a: T) -> T {
314 a
315 }
316}
317
318pub trait TryMorph<A> {
321 type Outcome;
323
324 fn try_morph(a: A) -> Result<Self::Outcome, ()>;
326}
327
328impl<T> TryMorph<T> for Identity {
330 type Outcome = T;
331 fn try_morph(a: T) -> Result<T, ()> {
332 Ok(a)
333 }
334}
335
336pub struct MorphInto<T>(core::marker::PhantomData<T>);
338impl<T, A: Into<T>> Morph<A> for MorphInto<T> {
339 type Outcome = T;
340 fn morph(a: A) -> T {
341 a.into()
342 }
343}
344
345pub struct TryMorphInto<T>(core::marker::PhantomData<T>);
347impl<T, A: TryInto<T>> TryMorph<A> for TryMorphInto<T> {
348 type Outcome = T;
349 fn try_morph(a: A) -> Result<T, ()> {
350 a.try_into().map_err(|_| ())
351 }
352}
353
354pub struct TakeFirst;
356impl<T1> Morph<(T1,)> for TakeFirst {
357 type Outcome = T1;
358 fn morph(a: (T1,)) -> T1 {
359 a.0
360 }
361}
362impl<T1, T2> Morph<(T1, T2)> for TakeFirst {
363 type Outcome = T1;
364 fn morph(a: (T1, T2)) -> T1 {
365 a.0
366 }
367}
368impl<T1, T2, T3> Morph<(T1, T2, T3)> for TakeFirst {
369 type Outcome = T1;
370 fn morph(a: (T1, T2, T3)) -> T1 {
371 a.0
372 }
373}
374impl<T1, T2, T3, T4> Morph<(T1, T2, T3, T4)> for TakeFirst {
375 type Outcome = T1;
376 fn morph(a: (T1, T2, T3, T4)) -> T1 {
377 a.0
378 }
379}
380
381#[macro_export]
417macro_rules! morph_types {
418 (
419 @DECL $( #[doc = $doc:expr] )* $vq:vis $name:ident ()
420 ) => {
421 $( #[doc = $doc] )* $vq struct $name;
422 };
423 (
424 @DECL $( #[doc = $doc:expr] )* $vq:vis $name:ident ( $( $bound_id:ident ),+ )
425 ) => {
426 $( #[doc = $doc] )*
427 $vq struct $name < $($bound_id,)* > ( $crate::traits::PhantomData< ( $($bound_id,)* ) > ) ;
428 };
429 (
430 @IMPL $name:ty : ( $( $bounds:tt )* ) ( $( $where:tt )* )
431 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
432 ) => {
433 impl<$($bounds)*> $crate::traits::Morph<$var_type> for $name $( $where )? {
434 type Outcome = $outcome;
435 fn morph($var: $var_type) -> Self::Outcome { $( $ex )* }
436 }
437 };
438 (
439 @IMPL_TRY $name:ty : ( $( $bounds:tt )* ) ( $( $where:tt )* )
440 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
441 ) => {
442 impl<$($bounds)*> $crate::traits::TryMorph<$var_type> for $name $( $where )? {
443 type Outcome = $outcome;
444 fn try_morph($var: $var_type) -> Result<Self::Outcome, ()> { $( $ex )* }
445 }
446 };
447 (
448 @IMPL $name:ty : () ( $( $where:tt )* )
449 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
450 ) => {
451 impl $crate::traits::Morph<$var_type> for $name $( $where )? {
452 type Outcome = $outcome;
453 fn morph($var: $var_type) -> Self::Outcome { $( $ex )* }
454 }
455 };
456 (
457 @IMPL_TRY $name:ty : () ( $( $where:tt )* )
458 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
459 ) => {
460 impl $crate::traits::TryMorph<$var_type> for $name $( $where )? {
461 type Outcome = $outcome;
462 fn try_morph($var: $var_type) -> Result<Self::Outcome, ()> { $( $ex )* }
463 }
464 };
465 (
466 @IMPL_BOTH $name:ty : ( $( $bounds:tt )* ) ( $( $where:tt )* )
467 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
468 ) => {
469 morph_types! {
470 @IMPL $name : ($($bounds)*) ($($where)*)
471 = |$var: $var_type| -> $outcome { $( $ex )* }
472 }
473 morph_types! {
474 @IMPL_TRY $name : ($($bounds)*) ($($where)*)
475 = |$var: $var_type| -> $outcome { Ok({$( $ex )*}) }
476 }
477 };
478
479 (
480 $( #[doc = $doc:expr] )* $vq:vis type $name:ident
481 $( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
482 $(: $type:tt)?
483 = |_| -> $outcome:ty { $( $ex:expr )* };
484 $( $rest:tt )*
485 ) => {
486 morph_types! {
487 $( #[doc = $doc] )* $vq type $name
488 $( < $( $bound_id $( : $bound_head $( | $bound_tail )* )? ),+ > )?
489 EXTRA_GENERIC(X)
490 $(: $type)?
491 = |_x: X| -> $outcome { $( $ex )* };
492 $( $rest )*
493 }
494 };
495 (
496 $( #[doc = $doc:expr] )* $vq:vis type $name:ident
497 $( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
498 $( EXTRA_GENERIC ($extra:ident) )?
499 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
500 $( where $( $where_path:ty : $where_bound_head:path $( | $where_bound_tail:path )* ),* )?;
501 $( $rest:tt )*
502 ) => {
503 morph_types! { @DECL $( #[doc = $doc] )* $vq $name ( $( $( $bound_id ),+ )? ) }
504 morph_types! {
505 @IMPL_BOTH $name $( < $( $bound_id ),* > )? :
506 ( $( $( $bound_id $( : $bound_head $( + $bound_tail )* )? , )+ )? $( $extra )? )
507 ( $( where $( $where_path : $where_bound_head $( + $where_bound_tail )* ),* )? )
508 = |$var: $var_type| -> $outcome { $( $ex )* }
509 }
510 morph_types!{ $($rest)* }
511 };
512 (
513 $( #[doc = $doc:expr] )* $vq:vis type $name:ident
514 $( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
515 $( EXTRA_GENERIC ($extra:ident) )?
516 : Morph
517 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
518 $( where $( $where_path:ty : $where_bound_head:path $( | $where_bound_tail:path )* ),* )?;
519 $( $rest:tt )*
520 ) => {
521 morph_types! { @DECL $( #[doc = $doc] )* $vq $name ( $( $( $bound_id ),+ )? ) }
522 morph_types! {
523 @IMPL $name $( < $( $bound_id ),* > )? :
524 ( $( $( $bound_id $( : $bound_head $( + $bound_tail )* )? , )+ )? $( $extra )? )
525 ( $( where $( $where_path : $where_bound_head $( + $where_bound_tail )* ),* )? )
526 = |$var: $var_type| -> $outcome { $( $ex )* }
527 }
528 morph_types!{ $($rest)* }
529 };
530 (
531 $( #[doc = $doc:expr] )* $vq:vis type $name:ident
532 $( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
533 $( EXTRA_GENERIC ($extra:ident) )?
534 : TryMorph
535 = |$var:ident: $var_type:ty| -> Result<$outcome:ty, ()> { $( $ex:expr )* }
536 $( where $( $where_path:ty : $where_bound_head:path $( | $where_bound_tail:path )* ),* )?;
537 $( $rest:tt )*
538 ) => {
539 morph_types! { @DECL $( #[doc = $doc] )* $vq $name ( $( $( $bound_id ),+ )? ) }
540 morph_types! {
541 @IMPL_TRY $name $( < $( $bound_id ),* > )? :
542 ( $( $( $bound_id $( : $bound_head $( + $bound_tail )* )? , )+ )? $( $extra )? )
543 ( $( where $( $where_path : $where_bound_head $( + $where_bound_tail )* ),* )? )
544 = |$var: $var_type| -> $outcome { $( $ex )* }
545 }
546 morph_types!{ $($rest)* }
547 };
548 () => {}
549}
550
551morph_types! {
552 pub type Replace<V: TypedGet> = |_| -> V::Type { V::get() };
554
555 pub type ReplaceWithDefault<V: Default> = |_| -> V { Default::default() };
557
558 pub type ReduceBy<N: TypedGet> = |r: N::Type| -> N::Type {
560 r.checked_sub(&N::get()).unwrap_or(Zero::zero())
561 } where N::Type: CheckedSub | Zero;
562
563 pub type CheckedReduceBy<N: TypedGet>: TryMorph = |r: N::Type| -> Result<N::Type, ()> {
566 r.checked_sub(&N::get()).ok_or(())
567 } where N::Type: CheckedSub;
568
569 pub type MorphWithUpperLimit<L: TypedGet, M>: TryMorph = |r: L::Type| -> Result<L::Type, ()> {
571 M::try_morph(r).map(|m| m.min(L::get()))
572 } where L::Type: Ord, M: TryMorph<L::Type, Outcome = L::Type>;
573}
574
575pub trait Convert<A, B> {
577 fn convert(a: A) -> B;
579}
580
581impl<A, B: Default> Convert<A, B> for () {
582 fn convert(_: A) -> B {
583 Default::default()
584 }
585}
586
587pub trait ConvertBack<A, B>: Convert<A, B> {
591 fn convert_back(b: B) -> A;
593}
594
595pub trait MaybeConvert<A, B> {
597 fn maybe_convert(a: A) -> Option<B>;
599}
600
601#[impl_trait_for_tuples::impl_for_tuples(30)]
602impl<A: Clone, B> MaybeConvert<A, B> for Tuple {
603 fn maybe_convert(a: A) -> Option<B> {
604 for_tuples!( #(
605 match Tuple::maybe_convert(a.clone()) {
606 Some(b) => return Some(b),
607 None => {},
608 }
609 )* );
610 None
611 }
612}
613
614pub trait MaybeConvertBack<A, B>: MaybeConvert<A, B> {
617 fn maybe_convert_back(b: B) -> Option<A>;
619}
620
621#[impl_trait_for_tuples::impl_for_tuples(30)]
622impl<A: Clone, B: Clone> MaybeConvertBack<A, B> for Tuple {
623 fn maybe_convert_back(b: B) -> Option<A> {
624 for_tuples!( #(
625 match Tuple::maybe_convert_back(b.clone()) {
626 Some(a) => return Some(a),
627 None => {},
628 }
629 )* );
630 None
631 }
632}
633
634pub trait TryConvert<A, B> {
637 fn try_convert(a: A) -> Result<B, A>;
639}
640
641#[impl_trait_for_tuples::impl_for_tuples(30)]
642impl<A, B> TryConvert<A, B> for Tuple {
643 fn try_convert(a: A) -> Result<B, A> {
644 for_tuples!( #(
645 let a = match Tuple::try_convert(a) {
646 Ok(b) => return Ok(b),
647 Err(a) => a,
648 };
649 )* );
650 Err(a)
651 }
652}
653
654pub trait TryConvertBack<A, B>: TryConvert<A, B> {
657 fn try_convert_back(b: B) -> Result<A, B>;
660}
661
662#[impl_trait_for_tuples::impl_for_tuples(30)]
663impl<A, B> TryConvertBack<A, B> for Tuple {
664 fn try_convert_back(b: B) -> Result<A, B> {
665 for_tuples!( #(
666 let b = match Tuple::try_convert_back(b) {
667 Ok(a) => return Ok(a),
668 Err(b) => b,
669 };
670 )* );
671 Err(b)
672 }
673}
674
675pub trait MaybeEquivalence<A, B> {
677 fn convert(a: &A) -> Option<B>;
679 fn convert_back(b: &B) -> Option<A>;
681}
682
683#[impl_trait_for_tuples::impl_for_tuples(30)]
684impl<A, B> MaybeEquivalence<A, B> for Tuple {
685 fn convert(a: &A) -> Option<B> {
686 for_tuples!( #(
687 match Tuple::convert(a) {
688 Some(b) => return Some(b),
689 None => {},
690 }
691 )* );
692 None
693 }
694 fn convert_back(b: &B) -> Option<A> {
695 for_tuples!( #(
696 match Tuple::convert_back(b) {
697 Some(a) => return Some(a),
698 None => {},
699 }
700 )* );
701 None
702 }
703}
704
705pub struct ConvertToValue<T>(core::marker::PhantomData<T>);
708impl<X, Y, T: Get<Y>> Convert<X, Y> for ConvertToValue<T> {
709 fn convert(_: X) -> Y {
710 T::get()
711 }
712}
713impl<X, Y, T: Get<Y>> MaybeConvert<X, Y> for ConvertToValue<T> {
714 fn maybe_convert(_: X) -> Option<Y> {
715 Some(T::get())
716 }
717}
718impl<X, Y, T: Get<Y>> MaybeConvertBack<X, Y> for ConvertToValue<T> {
719 fn maybe_convert_back(_: Y) -> Option<X> {
720 None
721 }
722}
723impl<X, Y, T: Get<Y>> TryConvert<X, Y> for ConvertToValue<T> {
724 fn try_convert(_: X) -> Result<Y, X> {
725 Ok(T::get())
726 }
727}
728impl<X, Y, T: Get<Y>> TryConvertBack<X, Y> for ConvertToValue<T> {
729 fn try_convert_back(y: Y) -> Result<X, Y> {
730 Err(y)
731 }
732}
733impl<X, Y, T: Get<Y>> MaybeEquivalence<X, Y> for ConvertToValue<T> {
734 fn convert(_: &X) -> Option<Y> {
735 Some(T::get())
736 }
737 fn convert_back(_: &Y) -> Option<X> {
738 None
739 }
740}
741
742pub struct Identity;
744impl<T> Convert<T, T> for Identity {
745 fn convert(a: T) -> T {
746 a
747 }
748}
749impl<T> ConvertBack<T, T> for Identity {
750 fn convert_back(a: T) -> T {
751 a
752 }
753}
754impl<T> MaybeConvert<T, T> for Identity {
755 fn maybe_convert(a: T) -> Option<T> {
756 Some(a)
757 }
758}
759impl<T> MaybeConvertBack<T, T> for Identity {
760 fn maybe_convert_back(a: T) -> Option<T> {
761 Some(a)
762 }
763}
764impl<T> TryConvert<T, T> for Identity {
765 fn try_convert(a: T) -> Result<T, T> {
766 Ok(a)
767 }
768}
769impl<T> TryConvertBack<T, T> for Identity {
770 fn try_convert_back(a: T) -> Result<T, T> {
771 Ok(a)
772 }
773}
774impl<T: Clone> MaybeEquivalence<T, T> for Identity {
775 fn convert(a: &T) -> Option<T> {
776 Some(a.clone())
777 }
778 fn convert_back(a: &T) -> Option<T> {
779 Some(a.clone())
780 }
781}
782
783pub struct ConvertInto;
785impl<A: Into<B>, B> Convert<A, B> for ConvertInto {
786 fn convert(a: A) -> B {
787 a.into()
788 }
789}
790impl<A: Into<B>, B> MaybeConvert<A, B> for ConvertInto {
791 fn maybe_convert(a: A) -> Option<B> {
792 Some(a.into())
793 }
794}
795impl<A: Into<B>, B: Into<A>> MaybeConvertBack<A, B> for ConvertInto {
796 fn maybe_convert_back(b: B) -> Option<A> {
797 Some(b.into())
798 }
799}
800impl<A: Into<B>, B> TryConvert<A, B> for ConvertInto {
801 fn try_convert(a: A) -> Result<B, A> {
802 Ok(a.into())
803 }
804}
805impl<A: Into<B>, B: Into<A>> TryConvertBack<A, B> for ConvertInto {
806 fn try_convert_back(b: B) -> Result<A, B> {
807 Ok(b.into())
808 }
809}
810impl<A: Clone + Into<B>, B: Clone + Into<A>> MaybeEquivalence<A, B> for ConvertInto {
811 fn convert(a: &A) -> Option<B> {
812 Some(a.clone().into())
813 }
814 fn convert_back(b: &B) -> Option<A> {
815 Some(b.clone().into())
816 }
817}
818
819pub struct TryConvertInto;
821impl<A: Clone + TryInto<B>, B> MaybeConvert<A, B> for TryConvertInto {
822 fn maybe_convert(a: A) -> Option<B> {
823 a.clone().try_into().ok()
824 }
825}
826impl<A: Clone + TryInto<B>, B: Clone + TryInto<A>> MaybeConvertBack<A, B> for TryConvertInto {
827 fn maybe_convert_back(b: B) -> Option<A> {
828 b.clone().try_into().ok()
829 }
830}
831impl<A: Clone + TryInto<B>, B> TryConvert<A, B> for TryConvertInto {
832 fn try_convert(a: A) -> Result<B, A> {
833 a.clone().try_into().map_err(|_| a)
834 }
835}
836impl<A: Clone + TryInto<B>, B: Clone + TryInto<A>> TryConvertBack<A, B> for TryConvertInto {
837 fn try_convert_back(b: B) -> Result<A, B> {
838 b.clone().try_into().map_err(|_| b)
839 }
840}
841impl<A: Clone + TryInto<B>, B: Clone + TryInto<A>> MaybeEquivalence<A, B> for TryConvertInto {
842 fn convert(a: &A) -> Option<B> {
843 a.clone().try_into().ok()
844 }
845 fn convert_back(b: &B) -> Option<A> {
846 b.clone().try_into().ok()
847 }
848}
849
850pub trait CheckedConversion {
854 fn checked_from<T>(t: T) -> Option<Self>
860 where
861 Self: TryFrom<T>,
862 {
863 <Self as TryFrom<T>>::try_from(t).ok()
864 }
865 fn checked_into<T>(self) -> Option<T>
871 where
872 Self: TryInto<T>,
873 {
874 <Self as TryInto<T>>::try_into(self).ok()
875 }
876}
877impl<T: Sized> CheckedConversion for T {}
878
879pub trait Scale<Other> {
882 type Output;
884
885 fn mul(self, other: Other) -> Self::Output;
887
888 fn div(self, other: Other) -> Self::Output;
890
891 fn rem(self, other: Other) -> Self::Output;
893}
894macro_rules! impl_scale {
895 ($self:ty, $other:ty) => {
896 impl Scale<$other> for $self {
897 type Output = Self;
898 fn mul(self, other: $other) -> Self::Output {
899 self * (other as Self)
900 }
901 fn div(self, other: $other) -> Self::Output {
902 self / (other as Self)
903 }
904 fn rem(self, other: $other) -> Self::Output {
905 self % (other as Self)
906 }
907 }
908 };
909}
910impl_scale!(u128, u128);
911impl_scale!(u128, u64);
912impl_scale!(u128, u32);
913impl_scale!(u128, u16);
914impl_scale!(u128, u8);
915impl_scale!(u64, u64);
916impl_scale!(u64, u32);
917impl_scale!(u64, u16);
918impl_scale!(u64, u8);
919impl_scale!(u32, u32);
920impl_scale!(u32, u16);
921impl_scale!(u32, u8);
922impl_scale!(u16, u16);
923impl_scale!(u16, u8);
924impl_scale!(u8, u8);
925
926pub trait Clear {
929 fn is_clear(&self) -> bool;
931
932 fn clear() -> Self;
934}
935
936impl<T: Default + Eq + PartialEq> Clear for T {
937 fn is_clear(&self) -> bool {
938 *self == Self::clear()
939 }
940 fn clear() -> Self {
941 Default::default()
942 }
943}
944
945pub trait SimpleBitOps:
947 Sized
948 + Clear
949 + core::ops::BitOr<Self, Output = Self>
950 + core::ops::BitXor<Self, Output = Self>
951 + core::ops::BitAnd<Self, Output = Self>
952{
953}
954impl<
955 T: Sized
956 + Clear
957 + core::ops::BitOr<Self, Output = Self>
958 + core::ops::BitXor<Self, Output = Self>
959 + core::ops::BitAnd<Self, Output = Self>,
960 > SimpleBitOps for T
961{
962}
963
964pub trait Hash:
968 'static
969 + MaybeSerializeDeserialize
970 + Debug
971 + Clone
972 + Eq
973 + PartialEq
974 + Hasher<Out = <Self as Hash>::Output>
975{
976 type Output: HashOutput;
978
979 fn hash(s: &[u8]) -> Self::Output {
981 <Self as Hasher>::hash(s)
982 }
983
984 fn hash_of<S: Encode>(s: &S) -> Self::Output {
986 Encode::using_encoded(s, <Self as Hasher>::hash)
987 }
988
989 fn ordered_trie_root(input: Vec<Vec<u8>>, state_version: StateVersion) -> Self::Output;
991
992 fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>, state_version: StateVersion) -> Self::Output;
994}
995
996pub trait HashOutput:
998 Member
999 + MaybeSerializeDeserialize
1000 + MaybeDisplay
1001 + MaybeFromStr
1002 + Debug
1003 + core::hash::Hash
1004 + AsRef<[u8]>
1005 + AsMut<[u8]>
1006 + Copy
1007 + Ord
1008 + Default
1009 + Encode
1010 + Decode
1011 + EncodeLike
1012 + MaxEncodedLen
1013 + TypeInfo
1014{
1015}
1016
1017impl<T> HashOutput for T where
1018 T: Member
1019 + MaybeSerializeDeserialize
1020 + MaybeDisplay
1021 + MaybeFromStr
1022 + Debug
1023 + core::hash::Hash
1024 + AsRef<[u8]>
1025 + AsMut<[u8]>
1026 + Copy
1027 + Ord
1028 + Default
1029 + Encode
1030 + Decode
1031 + EncodeLike
1032 + MaxEncodedLen
1033 + TypeInfo
1034{
1035}
1036
1037#[derive(PartialEq, Eq, Clone, RuntimeDebug, TypeInfo)]
1039#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1040pub struct BlakeTwo256;
1041
1042impl Hasher for BlakeTwo256 {
1043 type Out = sp_core::H256;
1044 type StdHasher = hash256_std_hasher::Hash256StdHasher;
1045 const LENGTH: usize = 32;
1046
1047 fn hash(s: &[u8]) -> Self::Out {
1048 sp_io::hashing::blake2_256(s).into()
1049 }
1050}
1051
1052impl Hash for BlakeTwo256 {
1053 type Output = sp_core::H256;
1054
1055 fn ordered_trie_root(input: Vec<Vec<u8>>, version: StateVersion) -> Self::Output {
1056 sp_io::trie::blake2_256_ordered_root(input, version)
1057 }
1058
1059 fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>, version: StateVersion) -> Self::Output {
1060 sp_io::trie::blake2_256_root(input, version)
1061 }
1062}
1063
1064#[derive(PartialEq, Eq, Clone, RuntimeDebug, TypeInfo)]
1066#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1067pub struct Keccak256;
1068
1069impl Hasher for Keccak256 {
1070 type Out = sp_core::H256;
1071 type StdHasher = hash256_std_hasher::Hash256StdHasher;
1072 const LENGTH: usize = 32;
1073
1074 fn hash(s: &[u8]) -> Self::Out {
1075 sp_io::hashing::keccak_256(s).into()
1076 }
1077}
1078
1079impl Hash for Keccak256 {
1080 type Output = sp_core::H256;
1081
1082 fn ordered_trie_root(input: Vec<Vec<u8>>, version: StateVersion) -> Self::Output {
1083 sp_io::trie::keccak_256_ordered_root(input, version)
1084 }
1085
1086 fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>, version: StateVersion) -> Self::Output {
1087 sp_io::trie::keccak_256_root(input, version)
1088 }
1089}
1090
1091pub trait CheckEqual {
1093 fn check_equal(&self, other: &Self);
1095}
1096
1097impl CheckEqual for sp_core::H256 {
1098 #[cfg(feature = "std")]
1099 fn check_equal(&self, other: &Self) {
1100 use sp_core::hexdisplay::HexDisplay;
1101 if self != other {
1102 println!(
1103 "Hash: given={}, expected={}",
1104 HexDisplay::from(self.as_fixed_bytes()),
1105 HexDisplay::from(other.as_fixed_bytes()),
1106 );
1107 }
1108 }
1109
1110 #[cfg(not(feature = "std"))]
1111 fn check_equal(&self, other: &Self) {
1112 if self != other {
1113 "Hash not equal".print();
1114 self.as_bytes().print();
1115 other.as_bytes().print();
1116 }
1117 }
1118}
1119
1120impl CheckEqual for super::generic::DigestItem {
1121 #[cfg(feature = "std")]
1122 fn check_equal(&self, other: &Self) {
1123 if self != other {
1124 println!("DigestItem: given={:?}, expected={:?}", self, other);
1125 }
1126 }
1127
1128 #[cfg(not(feature = "std"))]
1129 fn check_equal(&self, other: &Self) {
1130 if self != other {
1131 "DigestItem not equal".print();
1132 (&Encode::encode(self)[..]).print();
1133 (&Encode::encode(other)[..]).print();
1134 }
1135 }
1136}
1137
1138sp_core::impl_maybe_marker!(
1139 trait MaybeDisplay: Display;
1141
1142 trait MaybeFromStr: FromStr;
1144
1145 trait MaybeHash: core::hash::Hash;
1147);
1148
1149sp_core::impl_maybe_marker_std_or_serde!(
1150 trait MaybeSerialize: Serialize;
1152
1153 trait MaybeSerializeDeserialize: DeserializeOwned, Serialize;
1155);
1156
1157pub trait Member: Send + Sync + Sized + Debug + Eq + PartialEq + Clone + 'static {}
1159impl<T: Send + Sync + Sized + Debug + Eq + PartialEq + Clone + 'static> Member for T {}
1160
1161pub trait IsMember<MemberId> {
1163 fn is_member(member_id: &MemberId) -> bool;
1165}
1166
1167pub trait BlockNumber:
1169 Member
1170 + MaybeSerializeDeserialize
1171 + MaybeFromStr
1172 + Debug
1173 + core::hash::Hash
1174 + Copy
1175 + MaybeDisplay
1176 + AtLeast32BitUnsigned
1177 + Into<U256>
1178 + TryFrom<U256>
1179 + Default
1180 + TypeInfo
1181 + MaxEncodedLen
1182 + FullCodec
1183{
1184}
1185
1186impl<
1187 T: Member
1188 + MaybeSerializeDeserialize
1189 + MaybeFromStr
1190 + Debug
1191 + core::hash::Hash
1192 + Copy
1193 + MaybeDisplay
1194 + AtLeast32BitUnsigned
1195 + Into<U256>
1196 + TryFrom<U256>
1197 + Default
1198 + TypeInfo
1199 + MaxEncodedLen
1200 + FullCodec,
1201 > BlockNumber for T
1202{
1203}
1204
1205pub trait Header:
1211 Clone + Send + Sync + Codec + Eq + MaybeSerialize + Debug + TypeInfo + 'static
1212{
1213 type Number: BlockNumber;
1215 type Hash: HashOutput;
1217 type Hashing: Hash<Output = Self::Hash>;
1219
1220 fn new(
1222 number: Self::Number,
1223 extrinsics_root: Self::Hash,
1224 state_root: Self::Hash,
1225 parent_hash: Self::Hash,
1226 digest: Digest,
1227 ) -> Self;
1228
1229 fn number(&self) -> &Self::Number;
1231 fn set_number(&mut self, number: Self::Number);
1233
1234 fn extrinsics_root(&self) -> &Self::Hash;
1236 fn set_extrinsics_root(&mut self, root: Self::Hash);
1238
1239 fn state_root(&self) -> &Self::Hash;
1241 fn set_state_root(&mut self, root: Self::Hash);
1243
1244 fn parent_hash(&self) -> &Self::Hash;
1246 fn set_parent_hash(&mut self, hash: Self::Hash);
1248
1249 fn digest(&self) -> &Digest;
1251 fn digest_mut(&mut self) -> &mut Digest;
1253
1254 fn hash(&self) -> Self::Hash {
1256 <Self::Hashing as Hash>::hash_of(self)
1257 }
1258}
1259
1260#[doc(hidden)]
1280pub trait HeaderProvider {
1281 type HeaderT: Header;
1283}
1284
1285pub trait Block:
1290 HeaderProvider<HeaderT = <Self as Block>::Header>
1291 + Clone
1292 + Send
1293 + Sync
1294 + Codec
1295 + Eq
1296 + MaybeSerialize
1297 + Debug
1298 + 'static
1299{
1300 type Extrinsic: Member + Codec + ExtrinsicLike + MaybeSerialize;
1302 type Header: Header<Hash = Self::Hash> + MaybeSerializeDeserialize;
1304 type Hash: HashOutput;
1306
1307 fn header(&self) -> &Self::Header;
1309 fn extrinsics(&self) -> &[Self::Extrinsic];
1311 fn deconstruct(self) -> (Self::Header, Vec<Self::Extrinsic>);
1313 fn new(header: Self::Header, extrinsics: Vec<Self::Extrinsic>) -> Self;
1315 fn hash(&self) -> Self::Hash {
1317 <<Self::Header as Header>::Hashing as Hash>::hash_of(self.header())
1318 }
1319 fn encode_from(header: &Self::Header, extrinsics: &[Self::Extrinsic]) -> Vec<u8>;
1322}
1323
1324#[deprecated = "Use `ExtrinsicLike` along with the `CreateTransaction` trait family instead"]
1326pub trait Extrinsic: Sized {
1327 type Call: TypeInfo;
1329
1330 type SignaturePayload: SignaturePayload;
1336
1337 fn is_signed(&self) -> Option<bool> {
1340 None
1341 }
1342
1343 fn is_bare(&self) -> bool {
1345 !self.is_signed().unwrap_or(true)
1346 }
1347
1348 fn new(_call: Self::Call, _signed_data: Option<Self::SignaturePayload>) -> Option<Self> {
1351 None
1352 }
1353}
1354
1355pub trait ExtrinsicLike: Sized {
1357 #[deprecated = "Use and implement `!is_bare()` instead"]
1360 fn is_signed(&self) -> Option<bool> {
1361 None
1362 }
1363
1364 fn is_bare(&self) -> bool {
1366 #[allow(deprecated)]
1367 !self.is_signed().unwrap_or(true)
1368 }
1369}
1370
1371#[allow(deprecated)]
1372impl<T> ExtrinsicLike for T
1373where
1374 T: Extrinsic,
1375{
1376 fn is_signed(&self) -> Option<bool> {
1377 #[allow(deprecated)]
1378 <Self as Extrinsic>::is_signed(&self)
1379 }
1380
1381 fn is_bare(&self) -> bool {
1382 <Self as Extrinsic>::is_bare(&self)
1383 }
1384}
1385
1386pub trait SignaturePayload {
1389 type SignatureAddress: TypeInfo;
1393
1394 type Signature: TypeInfo;
1398
1399 type SignatureExtra: TypeInfo;
1403}
1404
1405impl SignaturePayload for () {
1406 type SignatureAddress = ();
1407 type Signature = ();
1408 type SignatureExtra = ();
1409}
1410
1411pub trait ExtrinsicMetadata {
1413 const VERSIONS: &'static [u8];
1417
1418 type TransactionExtensions;
1420}
1421
1422pub type HashingFor<B> = <<B as Block>::Header as Header>::Hashing;
1424pub type NumberFor<B> = <<B as Block>::Header as Header>::Number;
1426pub trait Checkable<Context>: Sized {
1433 type Checked;
1435
1436 fn check(self, c: &Context) -> Result<Self::Checked, TransactionValidityError>;
1438
1439 #[cfg(feature = "try-runtime")]
1448 fn unchecked_into_checked_i_know_what_i_am_doing(
1449 self,
1450 c: &Context,
1451 ) -> Result<Self::Checked, TransactionValidityError>;
1452}
1453
1454pub trait BlindCheckable: Sized {
1459 type Checked;
1461
1462 fn check(self) -> Result<Self::Checked, TransactionValidityError>;
1464}
1465
1466impl<T: BlindCheckable, Context> Checkable<Context> for T {
1468 type Checked = <Self as BlindCheckable>::Checked;
1469
1470 fn check(self, _c: &Context) -> Result<Self::Checked, TransactionValidityError> {
1471 BlindCheckable::check(self)
1472 }
1473
1474 #[cfg(feature = "try-runtime")]
1475 fn unchecked_into_checked_i_know_what_i_am_doing(
1476 self,
1477 _: &Context,
1478 ) -> Result<Self::Checked, TransactionValidityError> {
1479 unreachable!();
1480 }
1481}
1482
1483pub trait RefundWeight {
1485 fn refund(&mut self, weight: sp_weights::Weight);
1487}
1488
1489pub trait ExtensionPostDispatchWeightHandler<DispatchInfo>: RefundWeight {
1492 fn set_extension_weight(&mut self, info: &DispatchInfo);
1494}
1495
1496impl RefundWeight for () {
1497 fn refund(&mut self, _weight: sp_weights::Weight) {}
1498}
1499
1500impl ExtensionPostDispatchWeightHandler<()> for () {
1501 fn set_extension_weight(&mut self, _info: &()) {}
1502}
1503
1504pub trait Dispatchable {
1507 type RuntimeOrigin: Debug;
1511 type Config;
1513 type Info;
1517 type PostInfo: Eq
1520 + PartialEq
1521 + Clone
1522 + Copy
1523 + Encode
1524 + Decode
1525 + Printable
1526 + ExtensionPostDispatchWeightHandler<Self::Info>;
1527 fn dispatch(self, origin: Self::RuntimeOrigin)
1529 -> crate::DispatchResultWithInfo<Self::PostInfo>;
1530}
1531
1532pub type DispatchOriginOf<T> = <T as Dispatchable>::RuntimeOrigin;
1534pub type DispatchInfoOf<T> = <T as Dispatchable>::Info;
1536pub type PostDispatchInfoOf<T> = <T as Dispatchable>::PostInfo;
1538
1539impl Dispatchable for () {
1540 type RuntimeOrigin = ();
1541 type Config = ();
1542 type Info = ();
1543 type PostInfo = ();
1544 fn dispatch(
1545 self,
1546 _origin: Self::RuntimeOrigin,
1547 ) -> crate::DispatchResultWithInfo<Self::PostInfo> {
1548 panic!("This implementation should not be used for actual dispatch.");
1549 }
1550}
1551
1552#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo)]
1554pub struct FakeDispatchable<Inner>(pub Inner);
1555impl<Inner> From<Inner> for FakeDispatchable<Inner> {
1556 fn from(inner: Inner) -> Self {
1557 Self(inner)
1558 }
1559}
1560impl<Inner> FakeDispatchable<Inner> {
1561 pub fn deconstruct(self) -> Inner {
1563 self.0
1564 }
1565}
1566impl<Inner> AsRef<Inner> for FakeDispatchable<Inner> {
1567 fn as_ref(&self) -> &Inner {
1568 &self.0
1569 }
1570}
1571
1572impl<Inner> Dispatchable for FakeDispatchable<Inner> {
1573 type RuntimeOrigin = ();
1574 type Config = ();
1575 type Info = ();
1576 type PostInfo = ();
1577 fn dispatch(
1578 self,
1579 _origin: Self::RuntimeOrigin,
1580 ) -> crate::DispatchResultWithInfo<Self::PostInfo> {
1581 panic!("This implementation should not be used for actual dispatch.");
1582 }
1583}
1584
1585pub trait AsSystemOriginSigner<AccountId> {
1587 fn as_system_origin_signer(&self) -> Option<&AccountId>;
1590}
1591
1592pub trait AsTransactionAuthorizedOrigin {
1606 fn is_transaction_authorized(&self) -> bool;
1616}
1617
1618#[deprecated = "Use `TransactionExtension` instead."]
1621pub trait SignedExtension:
1622 Codec + Debug + Sync + Send + Clone + Eq + PartialEq + StaticTypeInfo
1623{
1624 const IDENTIFIER: &'static str;
1629
1630 type AccountId;
1632
1633 type Call: Dispatchable;
1635
1636 type AdditionalSigned: Codec + TypeInfo;
1639
1640 type Pre;
1642
1643 fn additional_signed(&self) -> Result<Self::AdditionalSigned, TransactionValidityError>;
1646
1647 fn validate(
1657 &self,
1658 _who: &Self::AccountId,
1659 _call: &Self::Call,
1660 _info: &DispatchInfoOf<Self::Call>,
1661 _len: usize,
1662 ) -> TransactionValidity {
1663 Ok(ValidTransaction::default())
1664 }
1665
1666 fn pre_dispatch(
1670 self,
1671 who: &Self::AccountId,
1672 call: &Self::Call,
1673 info: &DispatchInfoOf<Self::Call>,
1674 len: usize,
1675 ) -> Result<Self::Pre, TransactionValidityError>;
1676
1677 fn post_dispatch(
1694 _pre: Option<Self::Pre>,
1695 _info: &DispatchInfoOf<Self::Call>,
1696 _post_info: &PostDispatchInfoOf<Self::Call>,
1697 _len: usize,
1698 _result: &DispatchResult,
1699 ) -> Result<(), TransactionValidityError> {
1700 Ok(())
1701 }
1702
1703 fn metadata() -> Vec<TransactionExtensionMetadata> {
1712 sp_std::vec![TransactionExtensionMetadata {
1713 identifier: Self::IDENTIFIER,
1714 ty: scale_info::meta_type::<Self>(),
1715 implicit: scale_info::meta_type::<Self::AdditionalSigned>()
1716 }]
1717 }
1718
1719 fn validate_unsigned(
1726 _call: &Self::Call,
1727 _info: &DispatchInfoOf<Self::Call>,
1728 _len: usize,
1729 ) -> TransactionValidity {
1730 Ok(ValidTransaction::default())
1731 }
1732
1733 fn pre_dispatch_unsigned(
1742 call: &Self::Call,
1743 info: &DispatchInfoOf<Self::Call>,
1744 len: usize,
1745 ) -> Result<(), TransactionValidityError> {
1746 Self::validate_unsigned(call, info, len).map(|_| ()).map_err(Into::into)
1747 }
1748}
1749
1750pub trait Applyable: Sized + Send + Sync {
1766 type Call: Dispatchable;
1768
1769 fn validate<V: ValidateUnsigned<Call = Self::Call>>(
1774 &self,
1775 source: TransactionSource,
1776 info: &DispatchInfoOf<Self::Call>,
1777 len: usize,
1778 ) -> TransactionValidity;
1779
1780 fn apply<V: ValidateUnsigned<Call = Self::Call>>(
1786 self,
1787 info: &DispatchInfoOf<Self::Call>,
1788 len: usize,
1789 ) -> crate::ApplyExtrinsicResultWithInfo<PostDispatchInfoOf<Self::Call>>;
1790}
1791
1792pub trait GetRuntimeBlockType {
1794 type RuntimeBlock: self::Block;
1796}
1797
1798pub trait GetNodeBlockType {
1800 type NodeBlock: self::Block;
1802}
1803
1804pub trait ValidateUnsigned {
1812 type Call;
1814
1815 fn pre_dispatch(call: &Self::Call) -> Result<(), TransactionValidityError> {
1828 Self::validate_unsigned(TransactionSource::InBlock, call)
1829 .map(|_| ())
1830 .map_err(Into::into)
1831 }
1832
1833 fn validate_unsigned(source: TransactionSource, call: &Self::Call) -> TransactionValidity;
1846}
1847
1848pub trait OpaqueKeys: Clone {
1851 type KeyTypeIdProviders;
1853
1854 fn key_ids() -> &'static [crate::KeyTypeId];
1856 fn get_raw(&self, i: super::KeyTypeId) -> &[u8];
1858 fn get<T: Decode>(&self, i: super::KeyTypeId) -> Option<T> {
1860 T::decode(&mut self.get_raw(i)).ok()
1861 }
1862 fn ownership_proof_is_valid(&self, _proof: &[u8]) -> bool {
1864 true
1865 }
1866}
1867
1868pub struct AppendZerosInput<'a, T>(&'a mut T);
1873
1874impl<'a, T> AppendZerosInput<'a, T> {
1875 pub fn new(input: &'a mut T) -> Self {
1877 Self(input)
1878 }
1879}
1880
1881impl<'a, T: codec::Input> codec::Input for AppendZerosInput<'a, T> {
1882 fn remaining_len(&mut self) -> Result<Option<usize>, codec::Error> {
1883 Ok(None)
1884 }
1885
1886 fn read(&mut self, into: &mut [u8]) -> Result<(), codec::Error> {
1887 let remaining = self.0.remaining_len()?;
1888 let completed = if let Some(n) = remaining {
1889 let readable = into.len().min(n);
1890 self.0.read(&mut into[..readable])?;
1892 readable
1893 } else {
1894 let mut i = 0;
1896 while i < into.len() {
1897 if let Ok(b) = self.0.read_byte() {
1898 into[i] = b;
1899 i += 1;
1900 } else {
1901 break
1902 }
1903 }
1904 i
1905 };
1906 for i in &mut into[completed..] {
1908 *i = 0;
1909 }
1910 Ok(())
1911 }
1912}
1913
1914pub struct TrailingZeroInput<'a>(&'a [u8]);
1916
1917impl<'a> TrailingZeroInput<'a> {
1918 pub fn new(data: &'a [u8]) -> Self {
1920 Self(data)
1921 }
1922
1923 pub fn zeroes() -> Self {
1925 Self::new(&[][..])
1926 }
1927}
1928
1929impl<'a> codec::Input for TrailingZeroInput<'a> {
1930 fn remaining_len(&mut self) -> Result<Option<usize>, codec::Error> {
1931 Ok(None)
1932 }
1933
1934 fn read(&mut self, into: &mut [u8]) -> Result<(), codec::Error> {
1935 let len_from_inner = into.len().min(self.0.len());
1936 into[..len_from_inner].copy_from_slice(&self.0[..len_from_inner]);
1937 for i in &mut into[len_from_inner..] {
1938 *i = 0;
1939 }
1940 self.0 = &self.0[len_from_inner..];
1941
1942 Ok(())
1943 }
1944}
1945
1946pub trait AccountIdConversion<AccountId>: Sized {
1948 fn into_account_truncating(&self) -> AccountId {
1951 self.into_sub_account_truncating(&())
1952 }
1953
1954 fn try_into_account(&self) -> Option<AccountId> {
1957 self.try_into_sub_account(&())
1958 }
1959
1960 fn try_from_account(a: &AccountId) -> Option<Self> {
1962 Self::try_from_sub_account::<()>(a).map(|x| x.0)
1963 }
1964
1965 fn into_sub_account_truncating<S: Encode>(&self, sub: S) -> AccountId;
1979
1980 fn try_into_sub_account<S: Encode>(&self, sub: S) -> Option<AccountId>;
1984
1985 fn try_from_sub_account<S: Decode>(x: &AccountId) -> Option<(Self, S)>;
1987}
1988
1989impl<T: Encode + Decode, Id: Encode + Decode + TypeId> AccountIdConversion<T> for Id {
1992 fn into_sub_account_truncating<S: Encode>(&self, sub: S) -> T {
1996 (Id::TYPE_ID, self, sub)
1997 .using_encoded(|b| T::decode(&mut TrailingZeroInput(b)))
1998 .expect("All byte sequences are valid `AccountIds`; qed")
1999 }
2000
2001 fn try_into_sub_account<S: Encode>(&self, sub: S) -> Option<T> {
2003 let encoded_seed = (Id::TYPE_ID, self, sub).encode();
2004 let account = T::decode(&mut TrailingZeroInput(&encoded_seed))
2005 .expect("All byte sequences are valid `AccountIds`; qed");
2006 if encoded_seed.len() <= account.encoded_size() {
2009 Some(account)
2010 } else {
2011 None
2012 }
2013 }
2014
2015 fn try_from_sub_account<S: Decode>(x: &T) -> Option<(Self, S)> {
2016 x.using_encoded(|d| {
2017 if d[0..4] != Id::TYPE_ID {
2018 return None
2019 }
2020 let mut cursor = &d[4..];
2021 let result = Decode::decode(&mut cursor).ok()?;
2022 if cursor.iter().all(|x| *x == 0) {
2023 Some(result)
2024 } else {
2025 None
2026 }
2027 })
2028 }
2029}
2030
2031#[macro_export]
2038macro_rules! count {
2039 ($f:ident ($($x:tt)*) ) => ();
2040 ($f:ident ($($x:tt)*) $x1:tt) => { $f!($($x)* 0); };
2041 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt) => { $f!($($x)* 0); $f!($($x)* 1); };
2042 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt) => { $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); };
2043 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt, $x4:tt) => {
2044 $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); $f!($($x)* 3);
2045 };
2046 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt, $x4:tt, $x5:tt) => {
2047 $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); $f!($($x)* 3); $f!($($x)* 4);
2048 };
2049}
2050
2051#[doc(hidden)]
2052#[macro_export]
2053macro_rules! impl_opaque_keys_inner {
2054 (
2055 $( #[ $attr:meta ] )*
2056 pub struct $name:ident {
2057 $(
2058 $( #[ $inner_attr:meta ] )*
2059 pub $field:ident: $type:ty,
2060 )*
2061 }
2062 ) => {
2063 $( #[ $attr ] )*
2064 #[derive(
2065 Clone, PartialEq, Eq,
2066 $crate::codec::Encode,
2067 $crate::codec::Decode,
2068 $crate::scale_info::TypeInfo,
2069 $crate::RuntimeDebug,
2070 )]
2071 pub struct $name {
2072 $(
2073 $( #[ $inner_attr ] )*
2074 pub $field: <$type as $crate::BoundToRuntimeAppPublic>::Public,
2075 )*
2076 }
2077
2078 impl $name {
2079 pub fn generate(seed: Option<$crate::Vec<u8>>) -> $crate::Vec<u8> {
2085 let keys = Self{
2086 $(
2087 $field: <
2088 <
2089 $type as $crate::BoundToRuntimeAppPublic
2090 >::Public as $crate::RuntimeAppPublic
2091 >::generate_pair(seed.clone()),
2092 )*
2093 };
2094 $crate::codec::Encode::encode(&keys)
2095 }
2096
2097 pub fn into_raw_public_keys(
2099 self,
2100 ) -> $crate::Vec<($crate::Vec<u8>, $crate::KeyTypeId)> {
2101 let mut keys = Vec::new();
2102 $(
2103 keys.push((
2104 $crate::RuntimeAppPublic::to_raw_vec(&self.$field),
2105 <
2106 <
2107 $type as $crate::BoundToRuntimeAppPublic
2108 >::Public as $crate::RuntimeAppPublic
2109 >::ID,
2110 ));
2111 )*
2112
2113 keys
2114 }
2115
2116 pub fn decode_into_raw_public_keys(
2121 encoded: &[u8],
2122 ) -> Option<$crate::Vec<($crate::Vec<u8>, $crate::KeyTypeId)>> {
2123 <Self as $crate::codec::Decode>::decode(&mut &encoded[..])
2124 .ok()
2125 .map(|s| s.into_raw_public_keys())
2126 }
2127 }
2128
2129 impl $crate::traits::OpaqueKeys for $name {
2130 type KeyTypeIdProviders = ( $( $type, )* );
2131
2132 fn key_ids() -> &'static [$crate::KeyTypeId] {
2133 &[
2134 $(
2135 <
2136 <
2137 $type as $crate::BoundToRuntimeAppPublic
2138 >::Public as $crate::RuntimeAppPublic
2139 >::ID
2140 ),*
2141 ]
2142 }
2143
2144 fn get_raw(&self, i: $crate::KeyTypeId) -> &[u8] {
2145 match i {
2146 $(
2147 i if i == <
2148 <
2149 $type as $crate::BoundToRuntimeAppPublic
2150 >::Public as $crate::RuntimeAppPublic
2151 >::ID =>
2152 self.$field.as_ref(),
2153 )*
2154 _ => &[],
2155 }
2156 }
2157 }
2158 };
2159}
2160
2161#[macro_export]
2185#[cfg(any(feature = "serde", feature = "std"))]
2186macro_rules! impl_opaque_keys {
2187 {
2188 $( #[ $attr:meta ] )*
2189 pub struct $name:ident {
2190 $(
2191 $( #[ $inner_attr:meta ] )*
2192 pub $field:ident: $type:ty,
2193 )*
2194 }
2195 } => {
2196 $crate::paste::paste! {
2197 use $crate::serde as [< __opaque_keys_serde_import__ $name >];
2198
2199 $crate::impl_opaque_keys_inner! {
2200 $( #[ $attr ] )*
2201 #[derive($crate::serde::Serialize, $crate::serde::Deserialize)]
2202 #[serde(crate = "__opaque_keys_serde_import__" $name)]
2203 pub struct $name {
2204 $(
2205 $( #[ $inner_attr ] )*
2206 pub $field: $type,
2207 )*
2208 }
2209 }
2210 }
2211 }
2212}
2213
2214#[macro_export]
2215#[cfg(all(not(feature = "std"), not(feature = "serde")))]
2216#[doc(hidden)]
2217macro_rules! impl_opaque_keys {
2218 {
2219 $( #[ $attr:meta ] )*
2220 pub struct $name:ident {
2221 $(
2222 $( #[ $inner_attr:meta ] )*
2223 pub $field:ident: $type:ty,
2224 )*
2225 }
2226 } => {
2227 $crate::impl_opaque_keys_inner! {
2228 $( #[ $attr ] )*
2229 pub struct $name {
2230 $(
2231 $( #[ $inner_attr ] )*
2232 pub $field: $type,
2233 )*
2234 }
2235 }
2236 }
2237}
2238
2239pub trait Printable {
2241 fn print(&self);
2243}
2244
2245impl<T: Printable> Printable for &T {
2246 fn print(&self) {
2247 (*self).print()
2248 }
2249}
2250
2251impl Printable for u8 {
2252 fn print(&self) {
2253 (*self as u64).print()
2254 }
2255}
2256
2257impl Printable for u32 {
2258 fn print(&self) {
2259 (*self as u64).print()
2260 }
2261}
2262
2263impl Printable for usize {
2264 fn print(&self) {
2265 (*self as u64).print()
2266 }
2267}
2268
2269impl Printable for u64 {
2270 fn print(&self) {
2271 sp_io::misc::print_num(*self);
2272 }
2273}
2274
2275impl Printable for &[u8] {
2276 fn print(&self) {
2277 sp_io::misc::print_hex(self);
2278 }
2279}
2280
2281impl<const N: usize> Printable for [u8; N] {
2282 fn print(&self) {
2283 sp_io::misc::print_hex(&self[..]);
2284 }
2285}
2286
2287impl Printable for &str {
2288 fn print(&self) {
2289 sp_io::misc::print_utf8(self.as_bytes());
2290 }
2291}
2292
2293impl Printable for bool {
2294 fn print(&self) {
2295 if *self {
2296 "true".print()
2297 } else {
2298 "false".print()
2299 }
2300 }
2301}
2302
2303impl Printable for sp_weights::Weight {
2304 fn print(&self) {
2305 self.ref_time().print()
2306 }
2307}
2308
2309impl Printable for () {
2310 fn print(&self) {
2311 "()".print()
2312 }
2313}
2314
2315#[impl_for_tuples(1, 12)]
2316impl Printable for Tuple {
2317 fn print(&self) {
2318 for_tuples!( #( Tuple.print(); )* )
2319 }
2320}
2321
2322#[cfg(feature = "std")]
2324pub trait BlockIdTo<Block: self::Block> {
2325 type Error: std::error::Error;
2327
2328 fn to_hash(
2330 &self,
2331 block_id: &crate::generic::BlockId<Block>,
2332 ) -> Result<Option<Block::Hash>, Self::Error>;
2333
2334 fn to_number(
2336 &self,
2337 block_id: &crate::generic::BlockId<Block>,
2338 ) -> Result<Option<NumberFor<Block>>, Self::Error>;
2339}
2340
2341pub trait BlockNumberProvider {
2343 type BlockNumber: Codec
2345 + Clone
2346 + Ord
2347 + Eq
2348 + AtLeast32BitUnsigned
2349 + TypeInfo
2350 + Debug
2351 + MaxEncodedLen
2352 + Copy;
2353
2354 fn current_block_number() -> Self::BlockNumber;
2370
2371 #[cfg(any(feature = "std", feature = "runtime-benchmarks"))]
2377 fn set_block_number(_block: Self::BlockNumber) {}
2378}
2379
2380impl BlockNumberProvider for () {
2381 type BlockNumber = u32;
2382 fn current_block_number() -> Self::BlockNumber {
2383 0
2384 }
2385}
2386
2387#[cfg(test)]
2388mod tests {
2389 use super::*;
2390 use crate::codec::{Decode, Encode, Input};
2391 use sp_core::{
2392 crypto::{Pair, UncheckedFrom},
2393 ecdsa, ed25519, sr25519,
2394 };
2395
2396 macro_rules! signature_verify_test {
2397 ($algorithm:ident) => {
2398 let msg = &b"test-message"[..];
2399 let wrong_msg = &b"test-msg"[..];
2400 let (pair, _) = $algorithm::Pair::generate();
2401
2402 let signature = pair.sign(&msg);
2403 assert!($algorithm::Pair::verify(&signature, msg, &pair.public()));
2404
2405 assert!(signature.verify(msg, &pair.public()));
2406 assert!(!signature.verify(wrong_msg, &pair.public()));
2407 };
2408 }
2409
2410 mod t {
2411 use sp_application_crypto::{app_crypto, sr25519};
2412 use sp_core::crypto::KeyTypeId;
2413 app_crypto!(sr25519, KeyTypeId(*b"test"));
2414 }
2415
2416 #[test]
2417 fn app_verify_works() {
2418 use super::AppVerify;
2419 use t::*;
2420
2421 let s = Signature::try_from(vec![0; 64]).unwrap();
2422 let _ = s.verify(&[0u8; 100][..], &Public::unchecked_from([0; 32]));
2423 }
2424
2425 #[derive(Encode, Decode, Default, PartialEq, Debug)]
2426 struct U128Value(u128);
2427 impl super::TypeId for U128Value {
2428 const TYPE_ID: [u8; 4] = [0x0d, 0xf0, 0x0d, 0xf0];
2429 }
2430 #[derive(Encode, Decode, Default, PartialEq, Debug)]
2433 struct U32Value(u32);
2434 impl super::TypeId for U32Value {
2435 const TYPE_ID: [u8; 4] = [0x0d, 0xf0, 0xfe, 0xca];
2436 }
2437 #[derive(Encode, Decode, Default, PartialEq, Debug)]
2440 struct U16Value(u16);
2441 impl super::TypeId for U16Value {
2442 const TYPE_ID: [u8; 4] = [0xfe, 0xca, 0x0d, 0xf0];
2443 }
2444 type AccountId = u64;
2447
2448 #[test]
2449 fn into_account_truncating_should_work() {
2450 let r: AccountId = U32Value::into_account_truncating(&U32Value(0xdeadbeef));
2451 assert_eq!(r, 0x_deadbeef_cafef00d);
2452 }
2453
2454 #[test]
2455 fn try_into_account_should_work() {
2456 let r: AccountId = U32Value::try_into_account(&U32Value(0xdeadbeef)).unwrap();
2457 assert_eq!(r, 0x_deadbeef_cafef00d);
2458
2459 let maybe: Option<AccountId> = U128Value::try_into_account(&U128Value(u128::MAX));
2461 assert!(maybe.is_none());
2462 }
2463
2464 #[test]
2465 fn try_from_account_should_work() {
2466 let r = U32Value::try_from_account(&0x_deadbeef_cafef00d_u64);
2467 assert_eq!(r.unwrap(), U32Value(0xdeadbeef));
2468 }
2469
2470 #[test]
2471 fn into_account_truncating_with_fill_should_work() {
2472 let r: AccountId = U16Value::into_account_truncating(&U16Value(0xc0da));
2473 assert_eq!(r, 0x_0000_c0da_f00dcafe);
2474 }
2475
2476 #[test]
2477 fn try_into_sub_account_should_work() {
2478 let r: AccountId = U16Value::try_into_account(&U16Value(0xc0da)).unwrap();
2479 assert_eq!(r, 0x_0000_c0da_f00dcafe);
2480
2481 let maybe: Option<AccountId> = U16Value::try_into_sub_account(
2482 &U16Value(0xc0da),
2483 "a really large amount of additional encoded information which will certainly overflow the account id type ;)"
2484 );
2485
2486 assert!(maybe.is_none())
2487 }
2488
2489 #[test]
2490 fn try_from_account_with_fill_should_work() {
2491 let r = U16Value::try_from_account(&0x0000_c0da_f00dcafe_u64);
2492 assert_eq!(r.unwrap(), U16Value(0xc0da));
2493 }
2494
2495 #[test]
2496 fn bad_try_from_account_should_fail() {
2497 let r = U16Value::try_from_account(&0x0000_c0de_baadcafe_u64);
2498 assert!(r.is_none());
2499 let r = U16Value::try_from_account(&0x0100_c0da_f00dcafe_u64);
2500 assert!(r.is_none());
2501 }
2502
2503 #[test]
2504 fn trailing_zero_should_work() {
2505 let mut t = super::TrailingZeroInput(&[1, 2, 3]);
2506 assert_eq!(t.remaining_len(), Ok(None));
2507 let mut buffer = [0u8; 2];
2508 assert_eq!(t.read(&mut buffer), Ok(()));
2509 assert_eq!(t.remaining_len(), Ok(None));
2510 assert_eq!(buffer, [1, 2]);
2511 assert_eq!(t.read(&mut buffer), Ok(()));
2512 assert_eq!(t.remaining_len(), Ok(None));
2513 assert_eq!(buffer, [3, 0]);
2514 assert_eq!(t.read(&mut buffer), Ok(()));
2515 assert_eq!(t.remaining_len(), Ok(None));
2516 assert_eq!(buffer, [0, 0]);
2517 }
2518
2519 #[test]
2520 fn ed25519_verify_works() {
2521 signature_verify_test!(ed25519);
2522 }
2523
2524 #[test]
2525 fn sr25519_verify_works() {
2526 signature_verify_test!(sr25519);
2527 }
2528
2529 #[test]
2530 fn ecdsa_verify_works() {
2531 signature_verify_test!(ecdsa);
2532 }
2533}