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;
36use pezsp_application_crypto::AppCrypto;
37pub use pezsp_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 pezsp_core::{self, storage::StateVersion, Hasher, RuntimeDebug, TypeId, U256};
45#[doc(hidden)]
46pub use pezsp_core::{
47 parameter_types, ConstBool, ConstI128, ConstI16, ConstI32, ConstI64, ConstI8, ConstInt,
48 ConstU128, ConstU16, ConstU32, ConstU64, ConstU8, ConstUint, Get, GetDefault, TryCollect,
49 TypedGet,
50};
51#[cfg(feature = "serde")]
52use serde::{de::DeserializeOwned, Deserialize, Serialize};
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 pezsp_core::ed25519::Public {
88 type AccountId = Self;
89 fn into_account(self) -> Self {
90 self
91 }
92}
93
94impl IdentifyAccount for pezsp_core::sr25519::Public {
95 type AccountId = Self;
96 fn into_account(self) -> Self {
97 self
98 }
99}
100
101impl IdentifyAccount for pezsp_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 pezsp_core::ed25519::Signature {
123 type Signer = pezsp_core::ed25519::Public;
124
125 fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &pezsp_core::ed25519::Public) -> bool {
126 pezsp_io::crypto::ed25519_verify(self, msg.get(), signer)
127 }
128}
129
130impl Verify for pezsp_core::sr25519::Signature {
131 type Signer = pezsp_core::sr25519::Public;
132
133 fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &pezsp_core::sr25519::Public) -> bool {
134 pezsp_io::crypto::sr25519_verify(self, msg.get(), signer)
135 }
136}
137
138impl Verify for pezsp_core::ecdsa::Signature {
139 type Signer = pezsp_core::ecdsa::Public;
140 fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &pezsp_core::ecdsa::Public) -> bool {
141 match pezsp_io::crypto::secp256k1_ecdsa_recover_compressed(
142 self.as_ref(),
143 &pezsp_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<
161 Signer = <<T as AppCrypto>::Public as pezsp_application_crypto::AppPublic>::Generic,
162 > + From<T>,
163 T: pezsp_application_crypto::Wraps<Inner = S>
164 + pezsp_application_crypto::AppCrypto
165 + pezsp_application_crypto::AppSignature
166 + AsRef<S>
167 + AsMut<S>
168 + From<S>,
169 > AppVerify for T
170where
171 <S as Verify>::Signer: IdentifyAccount<AccountId = <S as Verify>::Signer>,
172 <<T as AppCrypto>::Public as pezsp_application_crypto::AppPublic>::Generic: IdentifyAccount<
173 AccountId = <<T as AppCrypto>::Public as pezsp_application_crypto::AppPublic>::Generic,
174 >,
175{
176 type AccountId = <T as AppCrypto>::Public;
177 fn verify<L: Lazy<[u8]>>(&self, msg: L, signer: &<T as AppCrypto>::Public) -> bool {
178 use pezsp_application_crypto::IsWrappedBy;
179 let inner: &S = self.as_ref();
180 let inner_pubkey =
181 <<T as AppCrypto>::Public as pezsp_application_crypto::AppPublic>::Generic::from_ref(
182 signer,
183 );
184 Verify::verify(inner, msg, inner_pubkey)
185 }
186}
187
188#[derive(Encode, Decode, RuntimeDebug)]
190pub struct BadOrigin;
191
192impl From<BadOrigin> for &'static str {
193 fn from(_: BadOrigin) -> &'static str {
194 "Bad origin"
195 }
196}
197
198#[derive(Encode, Decode, RuntimeDebug)]
200pub struct LookupError;
201
202impl From<LookupError> for &'static str {
203 fn from(_: LookupError) -> &'static str {
204 "Can not lookup"
205 }
206}
207
208impl From<LookupError> for TransactionValidityError {
209 fn from(_: LookupError) -> Self {
210 UnknownTransaction::CannotLookup.into()
211 }
212}
213
214pub trait Lookup {
216 type Source;
218 type Target;
220 fn lookup(&self, s: Self::Source) -> Result<Self::Target, LookupError>;
222}
223
224pub trait StaticLookup {
228 type Source: Codec + Clone + PartialEq + Debug + TypeInfo;
230 type Target;
232 fn lookup(s: Self::Source) -> Result<Self::Target, LookupError>;
234 fn unlookup(t: Self::Target) -> Self::Source;
236}
237
238#[derive(Clone, Copy, PartialEq, Eq)]
240pub struct IdentityLookup<T>(PhantomData<T>);
241impl<T> Default for IdentityLookup<T> {
242 fn default() -> Self {
243 Self(PhantomData::<T>::default())
244 }
245}
246
247impl<T: Codec + Clone + PartialEq + Debug + TypeInfo> StaticLookup for IdentityLookup<T> {
248 type Source = T;
249 type Target = T;
250 fn lookup(x: T) -> Result<T, LookupError> {
251 Ok(x)
252 }
253 fn unlookup(x: T) -> T {
254 x
255 }
256}
257
258impl<T> Lookup for IdentityLookup<T> {
259 type Source = T;
260 type Target = T;
261 fn lookup(&self, x: T) -> Result<T, LookupError> {
262 Ok(x)
263 }
264}
265
266pub struct AccountIdLookup<AccountId, AccountIndex>(PhantomData<(AccountId, AccountIndex)>);
268impl<AccountId, AccountIndex> StaticLookup for AccountIdLookup<AccountId, AccountIndex>
269where
270 AccountId: Codec + Clone + PartialEq + Debug,
271 AccountIndex: Codec + Clone + PartialEq + Debug,
272 crate::MultiAddress<AccountId, AccountIndex>: Codec + StaticTypeInfo,
273{
274 type Source = crate::MultiAddress<AccountId, AccountIndex>;
275 type Target = AccountId;
276 fn lookup(x: Self::Source) -> Result<Self::Target, LookupError> {
277 match x {
278 crate::MultiAddress::Id(i) => Ok(i),
279 _ => Err(LookupError),
280 }
281 }
282 fn unlookup(x: Self::Target) -> Self::Source {
283 crate::MultiAddress::Id(x)
284 }
285}
286
287impl<A, B> StaticLookup for (A, B)
289where
290 A: StaticLookup,
291 B: StaticLookup<Source = A::Source, Target = A::Target>,
292{
293 type Source = A::Source;
294 type Target = A::Target;
295
296 fn lookup(x: Self::Source) -> Result<Self::Target, LookupError> {
297 A::lookup(x.clone()).or_else(|_| B::lookup(x))
298 }
299 fn unlookup(x: Self::Target) -> Self::Source {
300 A::unlookup(x)
301 }
302}
303
304pub trait Morph<A> {
307 type Outcome;
309
310 fn morph(a: A) -> Self::Outcome;
312}
313
314impl<T> Morph<T> for Identity {
316 type Outcome = T;
317 fn morph(a: T) -> T {
318 a
319 }
320}
321
322pub trait TryMorph<A> {
325 type Outcome;
327
328 fn try_morph(a: A) -> Result<Self::Outcome, ()>;
330}
331
332impl<T> TryMorph<T> for Identity {
334 type Outcome = T;
335 fn try_morph(a: T) -> Result<T, ()> {
336 Ok(a)
337 }
338}
339
340pub struct MorphInto<T>(core::marker::PhantomData<T>);
342impl<T, A: Into<T>> Morph<A> for MorphInto<T> {
343 type Outcome = T;
344 fn morph(a: A) -> T {
345 a.into()
346 }
347}
348
349pub struct TryMorphInto<T>(core::marker::PhantomData<T>);
351impl<T, A: TryInto<T>> TryMorph<A> for TryMorphInto<T> {
352 type Outcome = T;
353 fn try_morph(a: A) -> Result<T, ()> {
354 a.try_into().map_err(|_| ())
355 }
356}
357
358pub struct TakeFirst;
360impl<T1> Morph<(T1,)> for TakeFirst {
361 type Outcome = T1;
362 fn morph(a: (T1,)) -> T1 {
363 a.0
364 }
365}
366impl<T1, T2> Morph<(T1, T2)> for TakeFirst {
367 type Outcome = T1;
368 fn morph(a: (T1, T2)) -> T1 {
369 a.0
370 }
371}
372impl<T1, T2, T3> Morph<(T1, T2, T3)> for TakeFirst {
373 type Outcome = T1;
374 fn morph(a: (T1, T2, T3)) -> T1 {
375 a.0
376 }
377}
378impl<T1, T2, T3, T4> Morph<(T1, T2, T3, T4)> for TakeFirst {
379 type Outcome = T1;
380 fn morph(a: (T1, T2, T3, T4)) -> T1 {
381 a.0
382 }
383}
384
385#[macro_export]
421macro_rules! morph_types {
422 (
423 @DECL $( #[doc = $doc:expr] )* $vq:vis $name:ident ()
424 ) => {
425 $( #[doc = $doc] )* $vq struct $name;
426 };
427 (
428 @DECL $( #[doc = $doc:expr] )* $vq:vis $name:ident ( $( $bound_id:ident ),+ )
429 ) => {
430 $( #[doc = $doc] )*
431 $vq struct $name < $($bound_id,)* > ( $crate::traits::PhantomData< ( $($bound_id,)* ) > ) ;
432 };
433 (
434 @IMPL $name:ty : ( $( $bounds:tt )* ) ( $( $where:tt )* )
435 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
436 ) => {
437 impl<$($bounds)*> $crate::traits::Morph<$var_type> for $name $( $where )? {
438 type Outcome = $outcome;
439 fn morph($var: $var_type) -> Self::Outcome { $( $ex )* }
440 }
441 };
442 (
443 @IMPL_TRY $name:ty : ( $( $bounds:tt )* ) ( $( $where:tt )* )
444 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
445 ) => {
446 impl<$($bounds)*> $crate::traits::TryMorph<$var_type> for $name $( $where )? {
447 type Outcome = $outcome;
448 fn try_morph($var: $var_type) -> Result<Self::Outcome, ()> { $( $ex )* }
449 }
450 };
451 (
452 @IMPL $name:ty : () ( $( $where:tt )* )
453 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
454 ) => {
455 impl $crate::traits::Morph<$var_type> for $name $( $where )? {
456 type Outcome = $outcome;
457 fn morph($var: $var_type) -> Self::Outcome { $( $ex )* }
458 }
459 };
460 (
461 @IMPL_TRY $name:ty : () ( $( $where:tt )* )
462 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
463 ) => {
464 impl $crate::traits::TryMorph<$var_type> for $name $( $where )? {
465 type Outcome = $outcome;
466 fn try_morph($var: $var_type) -> Result<Self::Outcome, ()> { $( $ex )* }
467 }
468 };
469 (
470 @IMPL_BOTH $name:ty : ( $( $bounds:tt )* ) ( $( $where:tt )* )
471 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
472 ) => {
473 morph_types! {
474 @IMPL $name : ($($bounds)*) ($($where)*)
475 = |$var: $var_type| -> $outcome { $( $ex )* }
476 }
477 morph_types! {
478 @IMPL_TRY $name : ($($bounds)*) ($($where)*)
479 = |$var: $var_type| -> $outcome { Ok({$( $ex )*}) }
480 }
481 };
482
483 (
484 $( #[doc = $doc:expr] )* $vq:vis type $name:ident
485 $( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
486 $(: $type:tt)?
487 = |_| -> $outcome:ty { $( $ex:expr )* };
488 $( $rest:tt )*
489 ) => {
490 morph_types! {
491 $( #[doc = $doc] )* $vq type $name
492 $( < $( $bound_id $( : $bound_head $( | $bound_tail )* )? ),+ > )?
493 EXTRA_GENERIC(X)
494 $(: $type)?
495 = |_x: X| -> $outcome { $( $ex )* };
496 $( $rest )*
497 }
498 };
499 (
500 $( #[doc = $doc:expr] )* $vq:vis type $name:ident
501 $( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
502 $( EXTRA_GENERIC ($extra:ident) )?
503 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
504 $( where $( $where_path:ty : $where_bound_head:path $( | $where_bound_tail:path )* ),* )?;
505 $( $rest:tt )*
506 ) => {
507 morph_types! { @DECL $( #[doc = $doc] )* $vq $name ( $( $( $bound_id ),+ )? ) }
508 morph_types! {
509 @IMPL_BOTH $name $( < $( $bound_id ),* > )? :
510 ( $( $( $bound_id $( : $bound_head $( + $bound_tail )* )? , )+ )? $( $extra )? )
511 ( $( where $( $where_path : $where_bound_head $( + $where_bound_tail )* ),* )? )
512 = |$var: $var_type| -> $outcome { $( $ex )* }
513 }
514 morph_types!{ $($rest)* }
515 };
516 (
517 $( #[doc = $doc:expr] )* $vq:vis type $name:ident
518 $( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
519 $( EXTRA_GENERIC ($extra:ident) )?
520 : Morph
521 = |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
522 $( where $( $where_path:ty : $where_bound_head:path $( | $where_bound_tail:path )* ),* )?;
523 $( $rest:tt )*
524 ) => {
525 morph_types! { @DECL $( #[doc = $doc] )* $vq $name ( $( $( $bound_id ),+ )? ) }
526 morph_types! {
527 @IMPL $name $( < $( $bound_id ),* > )? :
528 ( $( $( $bound_id $( : $bound_head $( + $bound_tail )* )? , )+ )? $( $extra )? )
529 ( $( where $( $where_path : $where_bound_head $( + $where_bound_tail )* ),* )? )
530 = |$var: $var_type| -> $outcome { $( $ex )* }
531 }
532 morph_types!{ $($rest)* }
533 };
534 (
535 $( #[doc = $doc:expr] )* $vq:vis type $name:ident
536 $( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
537 $( EXTRA_GENERIC ($extra:ident) )?
538 : TryMorph
539 = |$var:ident: $var_type:ty| -> Result<$outcome:ty, ()> { $( $ex:expr )* }
540 $( where $( $where_path:ty : $where_bound_head:path $( | $where_bound_tail:path )* ),* )?;
541 $( $rest:tt )*
542 ) => {
543 morph_types! { @DECL $( #[doc = $doc] )* $vq $name ( $( $( $bound_id ),+ )? ) }
544 morph_types! {
545 @IMPL_TRY $name $( < $( $bound_id ),* > )? :
546 ( $( $( $bound_id $( : $bound_head $( + $bound_tail )* )? , )+ )? $( $extra )? )
547 ( $( where $( $where_path : $where_bound_head $( + $where_bound_tail )* ),* )? )
548 = |$var: $var_type| -> $outcome { $( $ex )* }
549 }
550 morph_types!{ $($rest)* }
551 };
552 () => {}
553}
554
555morph_types! {
556 pub type Replace<V: TypedGet> = |_| -> V::Type { V::get() };
558
559 pub type ReplaceWithDefault<V: Default> = |_| -> V { Default::default() };
561
562 pub type ReduceBy<N: TypedGet> = |r: N::Type| -> N::Type {
564 r.checked_sub(&N::get()).unwrap_or(Zero::zero())
565 } where N::Type: CheckedSub | Zero;
566
567 pub type CheckedReduceBy<N: TypedGet>: TryMorph = |r: N::Type| -> Result<N::Type, ()> {
570 r.checked_sub(&N::get()).ok_or(())
571 } where N::Type: CheckedSub;
572
573 pub type MorphWithUpperLimit<L: TypedGet, M>: TryMorph = |r: L::Type| -> Result<L::Type, ()> {
575 M::try_morph(r).map(|m| m.min(L::get()))
576 } where L::Type: Ord, M: TryMorph<L::Type, Outcome = L::Type>;
577}
578
579pub trait Convert<A, B> {
581 fn convert(a: A) -> B;
583}
584
585impl<A, B: Default> Convert<A, B> for () {
586 fn convert(_: A) -> B {
587 Default::default()
588 }
589}
590
591pub trait ConvertBack<A, B>: Convert<A, B> {
595 fn convert_back(b: B) -> A;
597}
598
599pub trait MaybeConvert<A, B> {
601 fn maybe_convert(a: A) -> Option<B>;
603}
604
605#[impl_trait_for_tuples::impl_for_tuples(30)]
606impl<A: Clone, B> MaybeConvert<A, B> for Tuple {
607 fn maybe_convert(a: A) -> Option<B> {
608 for_tuples!( #(
609 match Tuple::maybe_convert(a.clone()) {
610 Some(b) => return Some(b),
611 None => {},
612 }
613 )* );
614 None
615 }
616}
617
618pub trait MaybeConvertBack<A, B>: MaybeConvert<A, B> {
621 fn maybe_convert_back(b: B) -> Option<A>;
623}
624
625#[impl_trait_for_tuples::impl_for_tuples(30)]
626impl<A: Clone, B: Clone> MaybeConvertBack<A, B> for Tuple {
627 fn maybe_convert_back(b: B) -> Option<A> {
628 for_tuples!( #(
629 match Tuple::maybe_convert_back(b.clone()) {
630 Some(a) => return Some(a),
631 None => {},
632 }
633 )* );
634 None
635 }
636}
637
638pub trait TryConvert<A, B> {
641 fn try_convert(a: A) -> Result<B, A>;
643}
644
645#[impl_trait_for_tuples::impl_for_tuples(30)]
646impl<A, B> TryConvert<A, B> for Tuple {
647 fn try_convert(a: A) -> Result<B, A> {
648 for_tuples!( #(
649 let a = match Tuple::try_convert(a) {
650 Ok(b) => return Ok(b),
651 Err(a) => a,
652 };
653 )* );
654 Err(a)
655 }
656}
657
658pub trait TryConvertBack<A, B>: TryConvert<A, B> {
661 fn try_convert_back(b: B) -> Result<A, B>;
664}
665
666#[impl_trait_for_tuples::impl_for_tuples(30)]
667impl<A, B> TryConvertBack<A, B> for Tuple {
668 fn try_convert_back(b: B) -> Result<A, B> {
669 for_tuples!( #(
670 let b = match Tuple::try_convert_back(b) {
671 Ok(a) => return Ok(a),
672 Err(b) => b,
673 };
674 )* );
675 Err(b)
676 }
677}
678
679pub trait MaybeEquivalence<A, B> {
681 fn convert(a: &A) -> Option<B>;
683 fn convert_back(b: &B) -> Option<A>;
685}
686
687#[impl_trait_for_tuples::impl_for_tuples(30)]
688impl<A, B> MaybeEquivalence<A, B> for Tuple {
689 fn convert(a: &A) -> Option<B> {
690 for_tuples!( #(
691 match Tuple::convert(a) {
692 Some(b) => return Some(b),
693 None => {},
694 }
695 )* );
696 None
697 }
698 fn convert_back(b: &B) -> Option<A> {
699 for_tuples!( #(
700 match Tuple::convert_back(b) {
701 Some(a) => return Some(a),
702 None => {},
703 }
704 )* );
705 None
706 }
707}
708
709pub struct ConvertToValue<T>(core::marker::PhantomData<T>);
712impl<X, Y, T: Get<Y>> Convert<X, Y> for ConvertToValue<T> {
713 fn convert(_: X) -> Y {
714 T::get()
715 }
716}
717impl<X, Y, T: Get<Y>> MaybeConvert<X, Y> for ConvertToValue<T> {
718 fn maybe_convert(_: X) -> Option<Y> {
719 Some(T::get())
720 }
721}
722impl<X, Y, T: Get<Y>> MaybeConvertBack<X, Y> for ConvertToValue<T> {
723 fn maybe_convert_back(_: Y) -> Option<X> {
724 None
725 }
726}
727impl<X, Y, T: Get<Y>> TryConvert<X, Y> for ConvertToValue<T> {
728 fn try_convert(_: X) -> Result<Y, X> {
729 Ok(T::get())
730 }
731}
732impl<X, Y, T: Get<Y>> TryConvertBack<X, Y> for ConvertToValue<T> {
733 fn try_convert_back(y: Y) -> Result<X, Y> {
734 Err(y)
735 }
736}
737impl<X, Y, T: Get<Y>> MaybeEquivalence<X, Y> for ConvertToValue<T> {
738 fn convert(_: &X) -> Option<Y> {
739 Some(T::get())
740 }
741 fn convert_back(_: &Y) -> Option<X> {
742 None
743 }
744}
745
746pub struct Identity;
748impl<T> Convert<T, T> for Identity {
749 fn convert(a: T) -> T {
750 a
751 }
752}
753impl<T> ConvertBack<T, T> for Identity {
754 fn convert_back(a: T) -> T {
755 a
756 }
757}
758impl<T> MaybeConvert<T, T> for Identity {
759 fn maybe_convert(a: T) -> Option<T> {
760 Some(a)
761 }
762}
763impl<T> MaybeConvertBack<T, T> for Identity {
764 fn maybe_convert_back(a: T) -> Option<T> {
765 Some(a)
766 }
767}
768impl<T> TryConvert<T, T> for Identity {
769 fn try_convert(a: T) -> Result<T, T> {
770 Ok(a)
771 }
772}
773impl<T> TryConvertBack<T, T> for Identity {
774 fn try_convert_back(a: T) -> Result<T, T> {
775 Ok(a)
776 }
777}
778impl<T: Clone> MaybeEquivalence<T, T> for Identity {
779 fn convert(a: &T) -> Option<T> {
780 Some(a.clone())
781 }
782 fn convert_back(a: &T) -> Option<T> {
783 Some(a.clone())
784 }
785}
786
787pub struct ConvertInto;
789impl<A: Into<B>, B> Convert<A, B> for ConvertInto {
790 fn convert(a: A) -> B {
791 a.into()
792 }
793}
794impl<A: Into<B>, B> MaybeConvert<A, B> for ConvertInto {
795 fn maybe_convert(a: A) -> Option<B> {
796 Some(a.into())
797 }
798}
799impl<A: Into<B>, B: Into<A>> MaybeConvertBack<A, B> for ConvertInto {
800 fn maybe_convert_back(b: B) -> Option<A> {
801 Some(b.into())
802 }
803}
804impl<A: Into<B>, B> TryConvert<A, B> for ConvertInto {
805 fn try_convert(a: A) -> Result<B, A> {
806 Ok(a.into())
807 }
808}
809impl<A: Into<B>, B: Into<A>> TryConvertBack<A, B> for ConvertInto {
810 fn try_convert_back(b: B) -> Result<A, B> {
811 Ok(b.into())
812 }
813}
814impl<A: Clone + Into<B>, B: Clone + Into<A>> MaybeEquivalence<A, B> for ConvertInto {
815 fn convert(a: &A) -> Option<B> {
816 Some(a.clone().into())
817 }
818 fn convert_back(b: &B) -> Option<A> {
819 Some(b.clone().into())
820 }
821}
822
823pub struct TryConvertInto;
825impl<A: Clone + TryInto<B>, B> MaybeConvert<A, B> for TryConvertInto {
826 fn maybe_convert(a: A) -> Option<B> {
827 a.clone().try_into().ok()
828 }
829}
830impl<A: Clone + TryInto<B>, B: Clone + TryInto<A>> MaybeConvertBack<A, B> for TryConvertInto {
831 fn maybe_convert_back(b: B) -> Option<A> {
832 b.clone().try_into().ok()
833 }
834}
835impl<A: Clone + TryInto<B>, B> TryConvert<A, B> for TryConvertInto {
836 fn try_convert(a: A) -> Result<B, A> {
837 a.clone().try_into().map_err(|_| a)
838 }
839}
840impl<A: Clone + TryInto<B>, B: Clone + TryInto<A>> TryConvertBack<A, B> for TryConvertInto {
841 fn try_convert_back(b: B) -> Result<A, B> {
842 b.clone().try_into().map_err(|_| b)
843 }
844}
845impl<A: Clone + TryInto<B>, B: Clone + TryInto<A>> MaybeEquivalence<A, B> for TryConvertInto {
846 fn convert(a: &A) -> Option<B> {
847 a.clone().try_into().ok()
848 }
849 fn convert_back(b: &B) -> Option<A> {
850 b.clone().try_into().ok()
851 }
852}
853
854pub trait CheckedConversion {
858 fn checked_from<T>(t: T) -> Option<Self>
864 where
865 Self: TryFrom<T>,
866 {
867 <Self as TryFrom<T>>::try_from(t).ok()
868 }
869 fn checked_into<T>(self) -> Option<T>
875 where
876 Self: TryInto<T>,
877 {
878 <Self as TryInto<T>>::try_into(self).ok()
879 }
880}
881impl<T: Sized> CheckedConversion for T {}
882
883pub trait Scale<Other> {
886 type Output;
888
889 fn mul(self, other: Other) -> Self::Output;
891
892 fn div(self, other: Other) -> Self::Output;
894
895 fn rem(self, other: Other) -> Self::Output;
897}
898macro_rules! impl_scale {
899 ($self:ty, $other:ty) => {
900 impl Scale<$other> for $self {
901 type Output = Self;
902 fn mul(self, other: $other) -> Self::Output {
903 self * (other as Self)
904 }
905 fn div(self, other: $other) -> Self::Output {
906 self / (other as Self)
907 }
908 fn rem(self, other: $other) -> Self::Output {
909 self % (other as Self)
910 }
911 }
912 };
913}
914impl_scale!(u128, u128);
915impl_scale!(u128, u64);
916impl_scale!(u128, u32);
917impl_scale!(u128, u16);
918impl_scale!(u128, u8);
919impl_scale!(u64, u64);
920impl_scale!(u64, u32);
921impl_scale!(u64, u16);
922impl_scale!(u64, u8);
923impl_scale!(u32, u32);
924impl_scale!(u32, u16);
925impl_scale!(u32, u8);
926impl_scale!(u16, u16);
927impl_scale!(u16, u8);
928impl_scale!(u8, u8);
929
930pub trait Clear {
933 fn is_clear(&self) -> bool;
935
936 fn clear() -> Self;
938}
939
940impl<T: Default + Eq + PartialEq> Clear for T {
941 fn is_clear(&self) -> bool {
942 *self == Self::clear()
943 }
944 fn clear() -> Self {
945 Default::default()
946 }
947}
948
949pub trait SimpleBitOps:
951 Sized
952 + Clear
953 + core::ops::BitOr<Self, Output = Self>
954 + core::ops::BitXor<Self, Output = Self>
955 + core::ops::BitAnd<Self, Output = Self>
956{
957}
958impl<
959 T: Sized
960 + Clear
961 + core::ops::BitOr<Self, Output = Self>
962 + core::ops::BitXor<Self, Output = Self>
963 + core::ops::BitAnd<Self, Output = Self>,
964 > SimpleBitOps for T
965{
966}
967
968pub trait Hash:
972 'static
973 + MaybeSerializeDeserialize
974 + Debug
975 + Clone
976 + Eq
977 + PartialEq
978 + Hasher<Out = <Self as Hash>::Output>
979{
980 type Output: HashOutput;
982
983 fn hash(s: &[u8]) -> Self::Output {
985 <Self as Hasher>::hash(s)
986 }
987
988 fn hash_of<S: Encode>(s: &S) -> Self::Output {
990 Encode::using_encoded(s, <Self as Hasher>::hash)
991 }
992
993 fn ordered_trie_root(input: Vec<Vec<u8>>, state_version: StateVersion) -> Self::Output;
995
996 fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>, state_version: StateVersion) -> Self::Output;
998}
999
1000pub trait HashOutput:
1002 Member
1003 + MaybeSerializeDeserialize
1004 + MaybeDisplay
1005 + MaybeFromStr
1006 + Debug
1007 + core::hash::Hash
1008 + AsRef<[u8]>
1009 + AsMut<[u8]>
1010 + Copy
1011 + Ord
1012 + Default
1013 + Encode
1014 + Decode
1015 + DecodeWithMemTracking
1016 + EncodeLike
1017 + MaxEncodedLen
1018 + TypeInfo
1019{
1020}
1021
1022impl<T> HashOutput for T where
1023 T: Member
1024 + MaybeSerializeDeserialize
1025 + MaybeDisplay
1026 + MaybeFromStr
1027 + Debug
1028 + core::hash::Hash
1029 + AsRef<[u8]>
1030 + AsMut<[u8]>
1031 + Copy
1032 + Ord
1033 + Default
1034 + Encode
1035 + Decode
1036 + DecodeWithMemTracking
1037 + EncodeLike
1038 + MaxEncodedLen
1039 + TypeInfo
1040{
1041}
1042
1043#[derive(PartialEq, Eq, Clone, RuntimeDebug, TypeInfo)]
1045#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1046pub struct BlakeTwo256;
1047
1048impl Hasher for BlakeTwo256 {
1049 type Out = pezsp_core::H256;
1050 type StdHasher = hash256_std_hasher::Hash256StdHasher;
1051 const LENGTH: usize = 32;
1052
1053 fn hash(s: &[u8]) -> Self::Out {
1054 pezsp_io::hashing::blake2_256(s).into()
1055 }
1056}
1057
1058impl Hash for BlakeTwo256 {
1059 type Output = pezsp_core::H256;
1060
1061 fn ordered_trie_root(input: Vec<Vec<u8>>, version: StateVersion) -> Self::Output {
1062 pezsp_io::trie::blake2_256_ordered_root(input, version)
1063 }
1064
1065 fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>, version: StateVersion) -> Self::Output {
1066 pezsp_io::trie::blake2_256_root(input, version)
1067 }
1068}
1069
1070#[derive(PartialEq, Eq, Clone, RuntimeDebug, TypeInfo)]
1072#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1073pub struct Keccak256;
1074
1075impl Hasher for Keccak256 {
1076 type Out = pezsp_core::H256;
1077 type StdHasher = hash256_std_hasher::Hash256StdHasher;
1078 const LENGTH: usize = 32;
1079
1080 fn hash(s: &[u8]) -> Self::Out {
1081 pezsp_io::hashing::keccak_256(s).into()
1082 }
1083}
1084
1085impl Hash for Keccak256 {
1086 type Output = pezsp_core::H256;
1087
1088 fn ordered_trie_root(input: Vec<Vec<u8>>, version: StateVersion) -> Self::Output {
1089 pezsp_io::trie::keccak_256_ordered_root(input, version)
1090 }
1091
1092 fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>, version: StateVersion) -> Self::Output {
1093 pezsp_io::trie::keccak_256_root(input, version)
1094 }
1095}
1096
1097pub trait CheckEqual {
1099 fn check_equal(&self, other: &Self);
1101}
1102
1103impl CheckEqual for pezsp_core::H256 {
1104 #[cfg(feature = "std")]
1105 fn check_equal(&self, other: &Self) {
1106 use pezsp_core::hexdisplay::HexDisplay;
1107 if self != other {
1108 println!(
1109 "Hash: given={}, expected={}",
1110 HexDisplay::from(self.as_fixed_bytes()),
1111 HexDisplay::from(other.as_fixed_bytes()),
1112 );
1113 }
1114 }
1115
1116 #[cfg(not(feature = "std"))]
1117 fn check_equal(&self, other: &Self) {
1118 if self != other {
1119 "Hash not equal".print();
1120 self.as_bytes().print();
1121 other.as_bytes().print();
1122 }
1123 }
1124}
1125
1126impl CheckEqual for super::generic::DigestItem {
1127 #[cfg(feature = "std")]
1128 fn check_equal(&self, other: &Self) {
1129 if self != other {
1130 println!("DigestItem: given={:?}, expected={:?}", self, other);
1131 }
1132 }
1133
1134 #[cfg(not(feature = "std"))]
1135 fn check_equal(&self, other: &Self) {
1136 if self != other {
1137 "DigestItem not equal".print();
1138 (&Encode::encode(self)[..]).print();
1139 (&Encode::encode(other)[..]).print();
1140 }
1141 }
1142}
1143
1144pezsp_core::impl_maybe_marker!(
1145 trait MaybeDisplay: Display;
1147
1148 trait MaybeFromStr: FromStr;
1150
1151 trait MaybeHash: core::hash::Hash;
1153);
1154
1155pezsp_core::impl_maybe_marker_std_or_serde!(
1156 trait MaybeSerialize: Serialize;
1158
1159 trait MaybeSerializeDeserialize: DeserializeOwned, Serialize;
1161);
1162
1163pub trait Member: Send + Sync + Sized + Debug + Eq + PartialEq + Clone + 'static {}
1165impl<T: Send + Sync + Sized + Debug + Eq + PartialEq + Clone + 'static> Member for T {}
1166
1167pub trait IsMember<MemberId> {
1169 fn is_member(member_id: &MemberId) -> bool;
1171}
1172
1173pub trait BlockNumber:
1175 Member
1176 + MaybeSerializeDeserialize
1177 + MaybeFromStr
1178 + Debug
1179 + core::hash::Hash
1180 + Copy
1181 + MaybeDisplay
1182 + AtLeast32BitUnsigned
1183 + Into<U256>
1184 + TryFrom<U256>
1185 + Default
1186 + TypeInfo
1187 + MaxEncodedLen
1188 + FullCodec
1189 + DecodeWithMemTracking
1190 + HasCompact<Type: DecodeWithMemTracking>
1191{
1192}
1193
1194impl<
1195 T: Member
1196 + MaybeSerializeDeserialize
1197 + MaybeFromStr
1198 + Debug
1199 + core::hash::Hash
1200 + Copy
1201 + MaybeDisplay
1202 + AtLeast32BitUnsigned
1203 + Into<U256>
1204 + TryFrom<U256>
1205 + Default
1206 + TypeInfo
1207 + MaxEncodedLen
1208 + FullCodec
1209 + DecodeWithMemTracking
1210 + HasCompact<Type: DecodeWithMemTracking>,
1211 > BlockNumber for T
1212{
1213}
1214
1215pub trait Header:
1221 Clone
1222 + Send
1223 + Sync
1224 + Codec
1225 + DecodeWithMemTracking
1226 + Eq
1227 + MaybeSerialize
1228 + Debug
1229 + TypeInfo
1230 + 'static
1231{
1232 type Number: BlockNumber;
1234 type Hash: HashOutput;
1236 type Hashing: Hash<Output = Self::Hash>;
1238
1239 fn new(
1241 number: Self::Number,
1242 extrinsics_root: Self::Hash,
1243 state_root: Self::Hash,
1244 parent_hash: Self::Hash,
1245 digest: Digest,
1246 ) -> Self;
1247
1248 fn number(&self) -> &Self::Number;
1250 fn set_number(&mut self, number: Self::Number);
1252
1253 fn extrinsics_root(&self) -> &Self::Hash;
1255 fn set_extrinsics_root(&mut self, root: Self::Hash);
1257
1258 fn state_root(&self) -> &Self::Hash;
1260 fn set_state_root(&mut self, root: Self::Hash);
1262
1263 fn parent_hash(&self) -> &Self::Hash;
1265 fn set_parent_hash(&mut self, hash: Self::Hash);
1267
1268 fn digest(&self) -> &Digest;
1270 fn digest_mut(&mut self) -> &mut Digest;
1272
1273 fn hash(&self) -> Self::Hash {
1275 <Self::Hashing as Hash>::hash_of(self)
1276 }
1277}
1278
1279#[doc(hidden)]
1299pub trait HeaderProvider {
1300 type HeaderT: Header;
1302}
1303
1304pub trait LazyExtrinsic: Sized {
1306 fn decode_unprefixed(data: &[u8]) -> Result<Self, codec::Error>;
1314}
1315
1316pub trait LazyBlock: Debug + Encode + Decode + Sized {
1318 type Extrinsic: LazyExtrinsic;
1320 type Header: Header;
1322
1323 fn header(&self) -> &Self::Header;
1325
1326 fn header_mut(&mut self) -> &mut Self::Header;
1328
1329 fn extrinsics(&self) -> impl Iterator<Item = Result<Self::Extrinsic, codec::Error>>;
1333}
1334
1335pub trait Block:
1340 HeaderProvider<HeaderT = Self::Header>
1341 + Into<Self::LazyBlock>
1342 + EncodeLike<Self::LazyBlock>
1343 + Clone
1344 + Send
1345 + Sync
1346 + Codec
1347 + DecodeWithMemTracking
1348 + Eq
1349 + MaybeSerialize
1350 + Debug
1351 + 'static
1352{
1353 type Extrinsic: Member + Codec + ExtrinsicLike + MaybeSerialize + Into<OpaqueExtrinsic>;
1355 type Header: Header<Hash = Self::Hash> + MaybeSerializeDeserialize;
1357 type Hash: HashOutput;
1359
1360 type LazyBlock: LazyBlock<Extrinsic = Self::Extrinsic, Header = Self::Header> + EncodeLike<Self>;
1363
1364 fn header(&self) -> &Self::Header;
1366 fn extrinsics(&self) -> &[Self::Extrinsic];
1368 fn deconstruct(self) -> (Self::Header, Vec<Self::Extrinsic>);
1370 fn new(header: Self::Header, extrinsics: Vec<Self::Extrinsic>) -> Self;
1372 fn hash(&self) -> Self::Hash {
1374 <<Self::Header as Header>::Hashing as Hash>::hash_of(self.header())
1375 }
1376}
1377
1378#[deprecated = "Use `ExtrinsicLike` along with the `CreateTransaction` trait family instead"]
1380pub trait Extrinsic: Sized {
1381 type Call: TypeInfo;
1383
1384 type SignaturePayload: SignaturePayload;
1390
1391 fn is_signed(&self) -> Option<bool> {
1394 None
1395 }
1396
1397 fn is_bare(&self) -> bool {
1399 !self.is_signed().unwrap_or(true)
1400 }
1401
1402 fn new(_call: Self::Call, _signed_data: Option<Self::SignaturePayload>) -> Option<Self> {
1405 None
1406 }
1407}
1408
1409pub trait ExtrinsicLike: Sized {
1411 #[deprecated = "Use and implement `!is_bare()` instead"]
1414 fn is_signed(&self) -> Option<bool> {
1415 None
1416 }
1417
1418 fn is_bare(&self) -> bool {
1420 #[allow(deprecated)]
1421 !self.is_signed().unwrap_or(true)
1422 }
1423}
1424
1425#[allow(deprecated)]
1426impl<T> ExtrinsicLike for T
1427where
1428 T: Extrinsic,
1429{
1430 fn is_signed(&self) -> Option<bool> {
1431 #[allow(deprecated)]
1432 <Self as Extrinsic>::is_signed(&self)
1433 }
1434
1435 fn is_bare(&self) -> bool {
1436 <Self as Extrinsic>::is_bare(&self)
1437 }
1438}
1439
1440pub trait ExtrinsicCall: ExtrinsicLike {
1442 type Call;
1444
1445 fn call(&self) -> &Self::Call;
1447
1448 fn into_call(self) -> Self::Call;
1450}
1451
1452pub trait SignaturePayload {
1455 type SignatureAddress: TypeInfo;
1459
1460 type Signature: TypeInfo;
1464
1465 type SignatureExtra: TypeInfo;
1469}
1470
1471impl SignaturePayload for () {
1472 type SignatureAddress = ();
1473 type Signature = ();
1474 type SignatureExtra = ();
1475}
1476
1477pub trait ExtrinsicMetadata {
1479 const VERSIONS: &'static [u8];
1483
1484 type TransactionExtensions;
1486}
1487
1488pub type HashingFor<B> = <<B as Block>::Header as Header>::Hashing;
1490pub type NumberFor<B> = <<B as Block>::Header as Header>::Number;
1492pub trait Checkable<Context>: Sized {
1499 type Checked;
1501
1502 fn check(self, c: &Context) -> Result<Self::Checked, TransactionValidityError>;
1504
1505 #[cfg(feature = "try-runtime")]
1514 fn unchecked_into_checked_i_know_what_i_am_doing(
1515 self,
1516 c: &Context,
1517 ) -> Result<Self::Checked, TransactionValidityError>;
1518}
1519
1520pub trait BlindCheckable: Sized {
1525 type Checked;
1527
1528 fn check(self) -> Result<Self::Checked, TransactionValidityError>;
1530}
1531
1532impl<T: BlindCheckable, Context> Checkable<Context> for T {
1534 type Checked = <Self as BlindCheckable>::Checked;
1535
1536 fn check(self, _c: &Context) -> Result<Self::Checked, TransactionValidityError> {
1537 BlindCheckable::check(self)
1538 }
1539
1540 #[cfg(feature = "try-runtime")]
1541 fn unchecked_into_checked_i_know_what_i_am_doing(
1542 self,
1543 _: &Context,
1544 ) -> Result<Self::Checked, TransactionValidityError> {
1545 unreachable!();
1546 }
1547}
1548
1549pub trait RefundWeight {
1551 fn refund(&mut self, weight: pezsp_weights::Weight);
1553}
1554
1555pub trait ExtensionPostDispatchWeightHandler<DispatchInfo>: RefundWeight {
1558 fn set_extension_weight(&mut self, info: &DispatchInfo);
1560}
1561
1562impl RefundWeight for () {
1563 fn refund(&mut self, _weight: pezsp_weights::Weight) {}
1564}
1565
1566impl ExtensionPostDispatchWeightHandler<()> for () {
1567 fn set_extension_weight(&mut self, _info: &()) {}
1568}
1569
1570pub trait Dispatchable {
1573 type RuntimeOrigin: Debug;
1577 type Config;
1579 type Info;
1583 type PostInfo: Eq
1586 + PartialEq
1587 + Clone
1588 + Copy
1589 + Encode
1590 + Decode
1591 + Printable
1592 + ExtensionPostDispatchWeightHandler<Self::Info>;
1593 fn dispatch(self, origin: Self::RuntimeOrigin)
1595 -> crate::DispatchResultWithInfo<Self::PostInfo>;
1596}
1597
1598pub type DispatchOriginOf<T> = <T as Dispatchable>::RuntimeOrigin;
1600pub type DispatchInfoOf<T> = <T as Dispatchable>::Info;
1602pub type PostDispatchInfoOf<T> = <T as Dispatchable>::PostInfo;
1604
1605impl Dispatchable for () {
1606 type RuntimeOrigin = ();
1607 type Config = ();
1608 type Info = ();
1609 type PostInfo = ();
1610 fn dispatch(
1611 self,
1612 _origin: Self::RuntimeOrigin,
1613 ) -> crate::DispatchResultWithInfo<Self::PostInfo> {
1614 panic!("This implementation should not be used for actual dispatch.");
1615 }
1616}
1617
1618#[derive(Clone, Eq, PartialEq, Encode, Decode, DecodeWithMemTracking, RuntimeDebug, TypeInfo)]
1620pub struct FakeDispatchable<Inner>(pub Inner);
1621impl<Inner> From<Inner> for FakeDispatchable<Inner> {
1622 fn from(inner: Inner) -> Self {
1623 Self(inner)
1624 }
1625}
1626impl<Inner> FakeDispatchable<Inner> {
1627 pub fn deconstruct(self) -> Inner {
1629 self.0
1630 }
1631}
1632impl<Inner> AsRef<Inner> for FakeDispatchable<Inner> {
1633 fn as_ref(&self) -> &Inner {
1634 &self.0
1635 }
1636}
1637
1638impl<Inner> Dispatchable for FakeDispatchable<Inner> {
1639 type RuntimeOrigin = ();
1640 type Config = ();
1641 type Info = ();
1642 type PostInfo = ();
1643 fn dispatch(
1644 self,
1645 _origin: Self::RuntimeOrigin,
1646 ) -> crate::DispatchResultWithInfo<Self::PostInfo> {
1647 panic!("This implementation should not be used for actual dispatch.");
1648 }
1649}
1650
1651pub trait AsSystemOriginSigner<AccountId> {
1653 fn as_system_origin_signer(&self) -> Option<&AccountId>;
1656}
1657
1658pub trait AsTransactionAuthorizedOrigin {
1672 fn is_transaction_authorized(&self) -> bool;
1682}
1683
1684#[deprecated = "Use `TransactionExtension` instead."]
1687pub trait SignedExtension:
1688 Codec + DecodeWithMemTracking + Debug + Sync + Send + Clone + Eq + PartialEq + StaticTypeInfo
1689{
1690 const IDENTIFIER: &'static str;
1695
1696 type AccountId;
1698
1699 type Call: Dispatchable;
1701
1702 type AdditionalSigned: Codec + TypeInfo;
1705
1706 type Pre;
1708
1709 fn additional_signed(&self) -> Result<Self::AdditionalSigned, TransactionValidityError>;
1712
1713 fn validate(
1723 &self,
1724 _who: &Self::AccountId,
1725 _call: &Self::Call,
1726 _info: &DispatchInfoOf<Self::Call>,
1727 _len: usize,
1728 ) -> TransactionValidity {
1729 Ok(ValidTransaction::default())
1730 }
1731
1732 fn pre_dispatch(
1736 self,
1737 who: &Self::AccountId,
1738 call: &Self::Call,
1739 info: &DispatchInfoOf<Self::Call>,
1740 len: usize,
1741 ) -> Result<Self::Pre, TransactionValidityError>;
1742
1743 fn post_dispatch(
1760 _pre: Option<Self::Pre>,
1761 _info: &DispatchInfoOf<Self::Call>,
1762 _post_info: &PostDispatchInfoOf<Self::Call>,
1763 _len: usize,
1764 _result: &DispatchResult,
1765 ) -> Result<(), TransactionValidityError> {
1766 Ok(())
1767 }
1768
1769 fn metadata() -> Vec<TransactionExtensionMetadata> {
1778 alloc::vec![TransactionExtensionMetadata {
1779 identifier: Self::IDENTIFIER,
1780 ty: scale_info::meta_type::<Self>(),
1781 implicit: scale_info::meta_type::<Self::AdditionalSigned>()
1782 }]
1783 }
1784
1785 fn validate_unsigned(
1792 _call: &Self::Call,
1793 _info: &DispatchInfoOf<Self::Call>,
1794 _len: usize,
1795 ) -> TransactionValidity {
1796 Ok(ValidTransaction::default())
1797 }
1798
1799 fn pre_dispatch_unsigned(
1808 call: &Self::Call,
1809 info: &DispatchInfoOf<Self::Call>,
1810 len: usize,
1811 ) -> Result<(), TransactionValidityError> {
1812 Self::validate_unsigned(call, info, len).map(|_| ()).map_err(Into::into)
1813 }
1814}
1815
1816pub trait Applyable: Sized + Send + Sync {
1832 type Call: Dispatchable;
1834
1835 fn validate<V: ValidateUnsigned<Call = Self::Call>>(
1840 &self,
1841 source: TransactionSource,
1842 info: &DispatchInfoOf<Self::Call>,
1843 len: usize,
1844 ) -> TransactionValidity;
1845
1846 fn apply<V: ValidateUnsigned<Call = Self::Call>>(
1852 self,
1853 info: &DispatchInfoOf<Self::Call>,
1854 len: usize,
1855 ) -> crate::ApplyExtrinsicResultWithInfo<PostDispatchInfoOf<Self::Call>>;
1856}
1857
1858pub trait GetRuntimeBlockType {
1860 type RuntimeBlock: self::Block;
1862}
1863
1864pub trait GetNodeBlockType {
1866 type NodeBlock: self::Block;
1868}
1869
1870pub trait ValidateUnsigned {
1878 type Call;
1880
1881 fn pre_dispatch(call: &Self::Call) -> Result<(), TransactionValidityError> {
1894 Self::validate_unsigned(TransactionSource::InBlock, call)
1895 .map(|_| ())
1896 .map_err(Into::into)
1897 }
1898
1899 fn validate_unsigned(source: TransactionSource, call: &Self::Call) -> TransactionValidity;
1912}
1913
1914pub trait OpaqueKeys: Clone {
1917 type KeyTypeIdProviders;
1919
1920 fn key_ids() -> &'static [crate::KeyTypeId];
1922 fn get_raw(&self, i: super::KeyTypeId) -> &[u8];
1924 fn get<T: Decode>(&self, i: super::KeyTypeId) -> Option<T> {
1926 T::decode(&mut self.get_raw(i)).ok()
1927 }
1928 fn ownership_proof_is_valid(&self, _proof: &[u8]) -> bool {
1930 true
1931 }
1932}
1933
1934pub struct AppendZerosInput<'a, T>(&'a mut T);
1939
1940impl<'a, T> AppendZerosInput<'a, T> {
1941 pub fn new(input: &'a mut T) -> Self {
1943 Self(input)
1944 }
1945}
1946
1947impl<'a, T: codec::Input> codec::Input for AppendZerosInput<'a, T> {
1948 fn remaining_len(&mut self) -> Result<Option<usize>, codec::Error> {
1949 Ok(None)
1950 }
1951
1952 fn read(&mut self, into: &mut [u8]) -> Result<(), codec::Error> {
1953 let remaining = self.0.remaining_len()?;
1954 let completed = if let Some(n) = remaining {
1955 let readable = into.len().min(n);
1956 self.0.read(&mut into[..readable])?;
1958 readable
1959 } else {
1960 let mut i = 0;
1962 while i < into.len() {
1963 if let Ok(b) = self.0.read_byte() {
1964 into[i] = b;
1965 i += 1;
1966 } else {
1967 break;
1968 }
1969 }
1970 i
1971 };
1972 for i in &mut into[completed..] {
1974 *i = 0;
1975 }
1976 Ok(())
1977 }
1978}
1979
1980pub struct TrailingZeroInput<'a>(&'a [u8]);
1982
1983impl<'a> TrailingZeroInput<'a> {
1984 pub fn new(data: &'a [u8]) -> Self {
1986 Self(data)
1987 }
1988
1989 pub fn zeroes() -> Self {
1991 Self::new(&[][..])
1992 }
1993}
1994
1995impl<'a> codec::Input for TrailingZeroInput<'a> {
1996 fn remaining_len(&mut self) -> Result<Option<usize>, codec::Error> {
1997 Ok(None)
1998 }
1999
2000 fn read(&mut self, into: &mut [u8]) -> Result<(), codec::Error> {
2001 let len_from_inner = into.len().min(self.0.len());
2002 into[..len_from_inner].copy_from_slice(&self.0[..len_from_inner]);
2003 for i in &mut into[len_from_inner..] {
2004 *i = 0;
2005 }
2006 self.0 = &self.0[len_from_inner..];
2007
2008 Ok(())
2009 }
2010}
2011
2012pub trait AccountIdConversion<AccountId>: Sized {
2014 fn into_account_truncating(&self) -> AccountId {
2017 self.into_sub_account_truncating(&())
2018 }
2019
2020 fn try_into_account(&self) -> Option<AccountId> {
2023 self.try_into_sub_account(&())
2024 }
2025
2026 fn try_from_account(a: &AccountId) -> Option<Self> {
2028 Self::try_from_sub_account::<()>(a).map(|x| x.0)
2029 }
2030
2031 fn into_sub_account_truncating<S: Encode>(&self, sub: S) -> AccountId;
2045
2046 fn try_into_sub_account<S: Encode>(&self, sub: S) -> Option<AccountId>;
2050
2051 fn try_from_sub_account<S: Decode>(x: &AccountId) -> Option<(Self, S)>;
2053}
2054
2055impl<T: Encode + Decode, Id: Encode + Decode + TypeId> AccountIdConversion<T> for Id {
2058 fn into_sub_account_truncating<S: Encode>(&self, sub: S) -> T {
2062 (Id::TYPE_ID, self, sub)
2063 .using_encoded(|b| T::decode(&mut TrailingZeroInput(b)))
2064 .expect("All byte sequences are valid `AccountIds`; qed")
2065 }
2066
2067 fn try_into_sub_account<S: Encode>(&self, sub: S) -> Option<T> {
2069 let encoded_seed = (Id::TYPE_ID, self, sub).encode();
2070 let account = T::decode(&mut TrailingZeroInput(&encoded_seed))
2071 .expect("All byte sequences are valid `AccountIds`; qed");
2072 if encoded_seed.len() <= account.encoded_size() {
2075 Some(account)
2076 } else {
2077 None
2078 }
2079 }
2080
2081 fn try_from_sub_account<S: Decode>(x: &T) -> Option<(Self, S)> {
2082 x.using_encoded(|d| {
2083 if d[0..4] != Id::TYPE_ID {
2084 return None;
2085 }
2086 let mut cursor = &d[4..];
2087 let result = Decode::decode(&mut cursor).ok()?;
2088 if cursor.iter().all(|x| *x == 0) {
2089 Some(result)
2090 } else {
2091 None
2092 }
2093 })
2094 }
2095}
2096
2097#[macro_export]
2104macro_rules! count {
2105 ($f:ident ($($x:tt)*) ) => ();
2106 ($f:ident ($($x:tt)*) $x1:tt) => { $f!($($x)* 0); };
2107 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt) => { $f!($($x)* 0); $f!($($x)* 1); };
2108 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt) => { $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); };
2109 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt, $x4:tt) => {
2110 $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); $f!($($x)* 3);
2111 };
2112 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt, $x4:tt, $x5:tt) => {
2113 $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); $f!($($x)* 3); $f!($($x)* 4);
2114 };
2115}
2116
2117#[doc(hidden)]
2118#[macro_export]
2119macro_rules! impl_opaque_keys_inner {
2120 (
2121 $( #[ $attr:meta ] )*
2122 pub struct $name:ident {
2123 $(
2124 $( #[ $inner_attr:meta ] )*
2125 pub $field:ident: $type:ty,
2126 )*
2127 }
2128 ) => {
2129 $( #[ $attr ] )*
2130 #[derive(
2131 Clone, PartialEq, Eq,
2132 $crate::codec::Encode,
2133 $crate::codec::Decode,
2134 $crate::codec::DecodeWithMemTracking,
2135 $crate::scale_info::TypeInfo,
2136 $crate::RuntimeDebug,
2137 )]
2138 pub struct $name {
2139 $(
2140 $( #[ $inner_attr ] )*
2141 pub $field: <$type as $crate::BoundToRuntimeAppPublic>::Public,
2142 )*
2143 }
2144
2145 impl $name {
2146 pub fn generate(seed: Option<$crate::Vec<u8>>) -> $crate::Vec<u8> {
2152 let keys = Self{
2153 $(
2154 $field: <
2155 <
2156 $type as $crate::BoundToRuntimeAppPublic
2157 >::Public as $crate::RuntimeAppPublic
2158 >::generate_pair(seed.clone()),
2159 )*
2160 };
2161 $crate::codec::Encode::encode(&keys)
2162 }
2163
2164 pub fn into_raw_public_keys(
2166 self,
2167 ) -> $crate::Vec<($crate::Vec<u8>, $crate::KeyTypeId)> {
2168 let mut keys = Vec::new();
2169 $(
2170 keys.push((
2171 $crate::RuntimeAppPublic::to_raw_vec(&self.$field),
2172 <
2173 <
2174 $type as $crate::BoundToRuntimeAppPublic
2175 >::Public as $crate::RuntimeAppPublic
2176 >::ID,
2177 ));
2178 )*
2179
2180 keys
2181 }
2182
2183 pub fn decode_into_raw_public_keys(
2188 encoded: &[u8],
2189 ) -> Option<$crate::Vec<($crate::Vec<u8>, $crate::KeyTypeId)>> {
2190 <Self as $crate::codec::Decode>::decode(&mut &encoded[..])
2191 .ok()
2192 .map(|s| s.into_raw_public_keys())
2193 }
2194 }
2195
2196 impl $crate::traits::OpaqueKeys for $name {
2197 type KeyTypeIdProviders = ( $( $type, )* );
2198
2199 fn key_ids() -> &'static [$crate::KeyTypeId] {
2200 &[
2201 $(
2202 <
2203 <
2204 $type as $crate::BoundToRuntimeAppPublic
2205 >::Public as $crate::RuntimeAppPublic
2206 >::ID
2207 ),*
2208 ]
2209 }
2210
2211 fn get_raw(&self, i: $crate::KeyTypeId) -> &[u8] {
2212 match i {
2213 $(
2214 i if i == <
2215 <
2216 $type as $crate::BoundToRuntimeAppPublic
2217 >::Public as $crate::RuntimeAppPublic
2218 >::ID =>
2219 self.$field.as_ref(),
2220 )*
2221 _ => &[],
2222 }
2223 }
2224 }
2225 };
2226}
2227
2228#[macro_export]
2252#[cfg(any(feature = "serde", feature = "std"))]
2253macro_rules! impl_opaque_keys {
2254 {
2255 $( #[ $attr:meta ] )*
2256 pub struct $name:ident {
2257 $(
2258 $( #[ $inner_attr:meta ] )*
2259 pub $field:ident: $type:ty,
2260 )*
2261 }
2262 } => {
2263 $crate::paste::paste! {
2264 use $crate::serde as [< __opaque_keys_serde_import__ $name >];
2265
2266 $crate::impl_opaque_keys_inner! {
2267 $( #[ $attr ] )*
2268 #[derive($crate::serde::Serialize, $crate::serde::Deserialize)]
2269 #[serde(crate = "__opaque_keys_serde_import__" $name)]
2270 pub struct $name {
2271 $(
2272 $( #[ $inner_attr ] )*
2273 pub $field: $type,
2274 )*
2275 }
2276 }
2277 }
2278 }
2279}
2280
2281#[macro_export]
2282#[cfg(all(not(feature = "std"), not(feature = "serde")))]
2283#[doc(hidden)]
2284macro_rules! impl_opaque_keys {
2285 {
2286 $( #[ $attr:meta ] )*
2287 pub struct $name:ident {
2288 $(
2289 $( #[ $inner_attr:meta ] )*
2290 pub $field:ident: $type:ty,
2291 )*
2292 }
2293 } => {
2294 $crate::impl_opaque_keys_inner! {
2295 $( #[ $attr ] )*
2296 pub struct $name {
2297 $(
2298 $( #[ $inner_attr ] )*
2299 pub $field: $type,
2300 )*
2301 }
2302 }
2303 }
2304}
2305
2306pub trait Printable {
2308 fn print(&self);
2310}
2311
2312impl<T: Printable> Printable for &T {
2313 fn print(&self) {
2314 (*self).print()
2315 }
2316}
2317
2318impl Printable for u8 {
2319 fn print(&self) {
2320 (*self as u64).print()
2321 }
2322}
2323
2324impl Printable for u32 {
2325 fn print(&self) {
2326 (*self as u64).print()
2327 }
2328}
2329
2330impl Printable for usize {
2331 fn print(&self) {
2332 (*self as u64).print()
2333 }
2334}
2335
2336impl Printable for u64 {
2337 fn print(&self) {
2338 pezsp_io::misc::print_num(*self);
2339 }
2340}
2341
2342impl Printable for &[u8] {
2343 fn print(&self) {
2344 pezsp_io::misc::print_hex(self);
2345 }
2346}
2347
2348impl<const N: usize> Printable for [u8; N] {
2349 fn print(&self) {
2350 pezsp_io::misc::print_hex(&self[..]);
2351 }
2352}
2353
2354impl Printable for &str {
2355 fn print(&self) {
2356 pezsp_io::misc::print_utf8(self.as_bytes());
2357 }
2358}
2359
2360impl Printable for bool {
2361 fn print(&self) {
2362 if *self {
2363 "true".print()
2364 } else {
2365 "false".print()
2366 }
2367 }
2368}
2369
2370impl Printable for pezsp_weights::Weight {
2371 fn print(&self) {
2372 self.ref_time().print()
2373 }
2374}
2375
2376impl Printable for () {
2377 fn print(&self) {
2378 "()".print()
2379 }
2380}
2381
2382#[impl_for_tuples(1, 12)]
2383impl Printable for Tuple {
2384 fn print(&self) {
2385 for_tuples!( #( Tuple.print(); )* )
2386 }
2387}
2388
2389#[cfg(feature = "std")]
2391pub trait BlockIdTo<Block: self::Block> {
2392 type Error: std::error::Error;
2394
2395 fn to_hash(
2397 &self,
2398 block_id: &crate::generic::BlockId<Block>,
2399 ) -> Result<Option<Block::Hash>, Self::Error>;
2400
2401 fn to_number(
2403 &self,
2404 block_id: &crate::generic::BlockId<Block>,
2405 ) -> Result<Option<NumberFor<Block>>, Self::Error>;
2406}
2407
2408pub trait BlockNumberProvider {
2410 type BlockNumber: Codec
2412 + DecodeWithMemTracking
2413 + Clone
2414 + Ord
2415 + Eq
2416 + AtLeast32BitUnsigned
2417 + TypeInfo
2418 + Debug
2419 + MaxEncodedLen
2420 + Copy
2421 + EncodeLike
2422 + Default;
2423
2424 fn current_block_number() -> Self::BlockNumber;
2440
2441 #[cfg(any(feature = "std", feature = "runtime-benchmarks"))]
2447 fn set_block_number(_block: Self::BlockNumber) {}
2448}
2449
2450impl BlockNumberProvider for () {
2451 type BlockNumber = u32;
2452 fn current_block_number() -> Self::BlockNumber {
2453 0
2454 }
2455}
2456
2457#[cfg(test)]
2458mod tests {
2459 use super::*;
2460 use crate::codec::{Decode, Encode, Input};
2461 use pezsp_core::{
2462 crypto::{Pair, UncheckedFrom},
2463 ecdsa, ed25519, sr25519,
2464 };
2465
2466 macro_rules! signature_verify_test {
2467 ($algorithm:ident) => {
2468 let msg = &b"test-message"[..];
2469 let wrong_msg = &b"test-msg"[..];
2470 let (pair, _) = $algorithm::Pair::generate();
2471
2472 let signature = pair.sign(&msg);
2473 assert!($algorithm::Pair::verify(&signature, msg, &pair.public()));
2474
2475 assert!(signature.verify(msg, &pair.public()));
2476 assert!(!signature.verify(wrong_msg, &pair.public()));
2477 };
2478 }
2479
2480 mod t {
2481 use pezsp_application_crypto::{app_crypto, sr25519};
2482 use pezsp_core::crypto::KeyTypeId;
2483 app_crypto!(sr25519, KeyTypeId(*b"test"));
2484 }
2485
2486 #[test]
2487 fn app_verify_works() {
2488 use super::AppVerify;
2489 use t::*;
2490
2491 let s = Signature::try_from(vec![0; 64]).unwrap();
2492 let _ = s.verify(&[0u8; 100][..], &Public::unchecked_from([0; 32]));
2493 }
2494
2495 #[derive(Encode, Decode, Default, PartialEq, Debug)]
2496 struct U128Value(u128);
2497 impl super::TypeId for U128Value {
2498 const TYPE_ID: [u8; 4] = [0x0d, 0xf0, 0x0d, 0xf0];
2499 }
2500 #[derive(Encode, Decode, Default, PartialEq, Debug)]
2503 struct U32Value(u32);
2504 impl super::TypeId for U32Value {
2505 const TYPE_ID: [u8; 4] = [0x0d, 0xf0, 0xfe, 0xca];
2506 }
2507 #[derive(Encode, Decode, Default, PartialEq, Debug)]
2510 struct U16Value(u16);
2511 impl super::TypeId for U16Value {
2512 const TYPE_ID: [u8; 4] = [0xfe, 0xca, 0x0d, 0xf0];
2513 }
2514 type AccountId = u64;
2517
2518 #[test]
2519 fn into_account_truncating_should_work() {
2520 let r: AccountId = U32Value::into_account_truncating(&U32Value(0xdeadbeef));
2521 assert_eq!(r, 0x_deadbeef_cafef00d);
2522 }
2523
2524 #[test]
2525 fn try_into_account_should_work() {
2526 let r: AccountId = U32Value::try_into_account(&U32Value(0xdeadbeef)).unwrap();
2527 assert_eq!(r, 0x_deadbeef_cafef00d);
2528
2529 let maybe: Option<AccountId> = U128Value::try_into_account(&U128Value(u128::MAX));
2531 assert!(maybe.is_none());
2532 }
2533
2534 #[test]
2535 fn try_from_account_should_work() {
2536 let r = U32Value::try_from_account(&0x_deadbeef_cafef00d_u64);
2537 assert_eq!(r.unwrap(), U32Value(0xdeadbeef));
2538 }
2539
2540 #[test]
2541 fn into_account_truncating_with_fill_should_work() {
2542 let r: AccountId = U16Value::into_account_truncating(&U16Value(0xc0da));
2543 assert_eq!(r, 0x_0000_c0da_f00dcafe);
2544 }
2545
2546 #[test]
2547 fn try_into_sub_account_should_work() {
2548 let r: AccountId = U16Value::try_into_account(&U16Value(0xc0da)).unwrap();
2549 assert_eq!(r, 0x_0000_c0da_f00dcafe);
2550
2551 let maybe: Option<AccountId> = U16Value::try_into_sub_account(
2552 &U16Value(0xc0da),
2553 "a really large amount of additional encoded information which will certainly overflow the account id type ;)"
2554 );
2555
2556 assert!(maybe.is_none())
2557 }
2558
2559 #[test]
2560 fn try_from_account_with_fill_should_work() {
2561 let r = U16Value::try_from_account(&0x0000_c0da_f00dcafe_u64);
2562 assert_eq!(r.unwrap(), U16Value(0xc0da));
2563 }
2564
2565 #[test]
2566 fn bad_try_from_account_should_fail() {
2567 let r = U16Value::try_from_account(&0x0000_c0de_baadcafe_u64);
2568 assert!(r.is_none());
2569 let r = U16Value::try_from_account(&0x0100_c0da_f00dcafe_u64);
2570 assert!(r.is_none());
2571 }
2572
2573 #[test]
2574 fn trailing_zero_should_work() {
2575 let mut t = super::TrailingZeroInput(&[1, 2, 3]);
2576 assert_eq!(t.remaining_len(), Ok(None));
2577 let mut buffer = [0u8; 2];
2578 assert_eq!(t.read(&mut buffer), Ok(()));
2579 assert_eq!(t.remaining_len(), Ok(None));
2580 assert_eq!(buffer, [1, 2]);
2581 assert_eq!(t.read(&mut buffer), Ok(()));
2582 assert_eq!(t.remaining_len(), Ok(None));
2583 assert_eq!(buffer, [3, 0]);
2584 assert_eq!(t.read(&mut buffer), Ok(()));
2585 assert_eq!(t.remaining_len(), Ok(None));
2586 assert_eq!(buffer, [0, 0]);
2587 }
2588
2589 #[test]
2590 fn ed25519_verify_works() {
2591 signature_verify_test!(ed25519);
2592 }
2593
2594 #[test]
2595 fn sr25519_verify_works() {
2596 signature_verify_test!(sr25519);
2597 }
2598
2599 #[test]
2600 fn ecdsa_verify_works() {
2601 signature_verify_test!(ecdsa);
2602 }
2603}