1use tetcore_std::prelude::*;
21use tetcore_std::{self, marker::PhantomData, convert::{TryFrom, TryInto}, fmt::Debug};
22use tet_io;
23#[cfg(feature = "std")]
24use std::fmt::Display;
25#[cfg(feature = "std")]
26use std::str::FromStr;
27#[cfg(feature = "std")]
28use serde::{Serialize, Deserialize, de::DeserializeOwned};
29use tet_core::{self, Hasher, TypeId, RuntimeDebug};
30use crate::codec::{Codec, Encode, Decode};
31use crate::transaction_validity::{
32 ValidTransaction, TransactionSource, TransactionValidity, TransactionValidityError,
33 UnknownTransaction,
34};
35use crate::generic::{Digest, DigestItem};
36pub use arithmetic::traits::{
37 AtLeast32Bit, AtLeast32BitUnsigned, UniqueSaturatedInto, UniqueSaturatedFrom, Saturating,
38 SaturatedConversion, Zero, One, Bounded, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv,
39 CheckedShl, CheckedShr, IntegerSquareRoot
40};
41use tet_application_crypto::AppKey;
42use impl_trait_for_tuples::impl_for_tuples;
43use crate::DispatchResult;
44
45pub trait Lazy<T: ?Sized> {
47 fn get(&mut self) -> &T;
51}
52
53impl<'a> Lazy<[u8]> for &'a [u8] {
54 fn get(&mut self) -> &[u8] { &**self }
55}
56
57pub trait IdentifyAccount {
60 type AccountId;
62 fn into_account(self) -> Self::AccountId;
64}
65
66impl IdentifyAccount for tet_core::ed25519::Public {
67 type AccountId = Self;
68 fn into_account(self) -> Self { self }
69}
70
71impl IdentifyAccount for tet_core::sr25519::Public {
72 type AccountId = Self;
73 fn into_account(self) -> Self { self }
74}
75
76impl IdentifyAccount for tet_core::ecdsa::Public {
77 type AccountId = Self;
78 fn into_account(self) -> Self { self }
79}
80
81pub trait Verify {
83 type Signer: IdentifyAccount;
85 fn verify<L: Lazy<[u8]>>(&self, msg: L, signer: &<Self::Signer as IdentifyAccount>::AccountId) -> bool;
89}
90
91impl Verify for tet_core::ed25519::Signature {
92 type Signer = tet_core::ed25519::Public;
93
94 fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &tet_core::ed25519::Public) -> bool {
95 tet_io::crypto::ed25519_verify(self, msg.get(), signer)
96 }
97}
98
99impl Verify for tet_core::sr25519::Signature {
100 type Signer = tet_core::sr25519::Public;
101
102 fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &tet_core::sr25519::Public) -> bool {
103 tet_io::crypto::sr25519_verify(self, msg.get(), signer)
104 }
105}
106
107impl Verify for tet_core::ecdsa::Signature {
108 type Signer = tet_core::ecdsa::Public;
109 fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &tet_core::ecdsa::Public) -> bool {
110 match tet_io::crypto::secp256k1_ecdsa_recover_compressed(
111 self.as_ref(),
112 &tet_io::hashing::blake2_256(msg.get()),
113 ) {
114 Ok(pubkey) => &signer.as_ref()[..] == &pubkey[..],
115 _ => false,
116 }
117 }
118}
119
120pub trait AppVerify {
122 type AccountId;
124 fn verify<L: Lazy<[u8]>>(&self, msg: L, signer: &Self::AccountId) -> bool;
126}
127
128impl<
129 S: Verify<Signer = <<T as AppKey>::Public as tet_application_crypto::AppPublic>::Generic> + From<T>,
130 T: tet_application_crypto::Wraps<Inner=S> + tet_application_crypto::AppKey + tet_application_crypto::AppSignature +
131 AsRef<S> + AsMut<S> + From<S>,
132> AppVerify for T where
133 <S as Verify>::Signer: IdentifyAccount<AccountId = <S as Verify>::Signer>,
134 <<T as AppKey>::Public as tet_application_crypto::AppPublic>::Generic:
135 IdentifyAccount<AccountId = <<T as AppKey>::Public as tet_application_crypto::AppPublic>::Generic>,
136{
137 type AccountId = <T as AppKey>::Public;
138 fn verify<L: Lazy<[u8]>>(&self, msg: L, signer: &<T as AppKey>::Public) -> bool {
139 use tet_application_crypto::IsWrappedBy;
140 let inner: &S = self.as_ref();
141 let inner_pubkey = <<T as AppKey>::Public as tet_application_crypto::AppPublic>::Generic::from_ref(&signer);
142 Verify::verify(inner, msg, inner_pubkey)
143 }
144}
145
146#[derive(Encode, Decode, RuntimeDebug)]
148pub struct BadOrigin;
149
150impl From<BadOrigin> for &'static str {
151 fn from(_: BadOrigin) -> &'static str {
152 "Bad origin"
153 }
154}
155
156#[derive(Encode, Decode, RuntimeDebug)]
158pub enum StoredMapError {
159 NoProviders,
161 ConsumerRemaining,
164}
165
166impl From<StoredMapError> for &'static str {
167 fn from(e: StoredMapError) -> &'static str {
168 match e {
169 StoredMapError::NoProviders => "No providers",
170 StoredMapError::ConsumerRemaining => "Consumer remaining",
171 }
172 }
173}
174
175#[derive(Encode, Decode, RuntimeDebug)]
177pub struct LookupError;
178
179impl From<LookupError> for &'static str {
180 fn from(_: LookupError) -> &'static str {
181 "Can not lookup"
182 }
183}
184
185impl From<LookupError> for TransactionValidityError {
186 fn from(_: LookupError) -> Self {
187 UnknownTransaction::CannotLookup.into()
188 }
189}
190
191pub trait Lookup {
193 type Source;
195 type Target;
197 fn lookup(&self, s: Self::Source) -> Result<Self::Target, LookupError>;
199}
200
201pub trait StaticLookup {
205 type Source: Codec + Clone + PartialEq + Debug;
207 type Target;
209 fn lookup(s: Self::Source) -> Result<Self::Target, LookupError>;
211 fn unlookup(t: Self::Target) -> Self::Source;
213}
214
215#[derive(Default)]
217pub struct IdentityLookup<T>(PhantomData<T>);
218impl<T: Codec + Clone + PartialEq + Debug> StaticLookup for IdentityLookup<T> {
219 type Source = T;
220 type Target = T;
221 fn lookup(x: T) -> Result<T, LookupError> { Ok(x) }
222 fn unlookup(x: T) -> T { x }
223}
224
225impl<T> Lookup for IdentityLookup<T> {
226 type Source = T;
227 type Target = T;
228 fn lookup(&self, x: T) -> Result<T, LookupError> { Ok(x) }
229}
230
231pub struct AccountIdLookup<AccountId, AccountIndex>(PhantomData<(AccountId, AccountIndex)>);
233impl<AccountId, AccountIndex> StaticLookup for AccountIdLookup<AccountId, AccountIndex>
234where
235 AccountId: Codec + Clone + PartialEq + Debug,
236 AccountIndex: Codec + Clone + PartialEq + Debug,
237 crate::MultiAddress<AccountId, AccountIndex>: Codec,
238{
239 type Source = crate::MultiAddress<AccountId, AccountIndex>;
240 type Target = AccountId;
241 fn lookup(x: Self::Source) -> Result<Self::Target, LookupError> {
242 match x {
243 crate::MultiAddress::Id(i) => Ok(i),
244 _ => Err(LookupError),
245 }
246 }
247 fn unlookup(x: Self::Target) -> Self::Source {
248 crate::MultiAddress::Id(x)
249 }
250}
251
252impl<A, B> StaticLookup for (A, B)
254where
255 A: StaticLookup,
256 B: StaticLookup<Source = A::Source, Target = A::Target>,
257{
258 type Source = A::Source;
259 type Target = A::Target;
260
261 fn lookup(x: Self::Source) -> Result<Self::Target, LookupError> {
262 A::lookup(x.clone()).or_else(|_| B::lookup(x))
263 }
264 fn unlookup(x: Self::Target) -> Self::Source {
265 A::unlookup(x)
266 }
267}
268
269pub trait Convert<A, B> {
271 fn convert(a: A) -> B;
273}
274
275impl<A, B: Default> Convert<A, B> for () {
276 fn convert(_: A) -> B { Default::default() }
277}
278
279pub struct Identity;
281impl<T> Convert<T, T> for Identity {
282 fn convert(a: T) -> T { a }
283}
284
285pub struct ConvertInto;
287impl<A, B: From<A>> Convert<A, B> for ConvertInto {
288 fn convert(a: A) -> B { a.into() }
289}
290
291pub trait CheckedConversion {
295 fn checked_from<T>(t: T) -> Option<Self> where Self: TryFrom<T> {
301 <Self as TryFrom<T>>::try_from(t).ok()
302 }
303 fn checked_into<T>(self) -> Option<T> where Self: TryInto<T> {
309 <Self as TryInto<T>>::try_into(self).ok()
310 }
311}
312impl<T: Sized> CheckedConversion for T {}
313
314pub trait Scale<Other> {
317 type Output;
319
320 fn mul(self, other: Other) -> Self::Output;
322
323 fn div(self, other: Other) -> Self::Output;
325
326 fn rem(self, other: Other) -> Self::Output;
328}
329macro_rules! impl_scale {
330 ($self:ty, $other:ty) => {
331 impl Scale<$other> for $self {
332 type Output = Self;
333 fn mul(self, other: $other) -> Self::Output { self * (other as Self) }
334 fn div(self, other: $other) -> Self::Output { self / (other as Self) }
335 fn rem(self, other: $other) -> Self::Output { self % (other as Self) }
336 }
337 }
338}
339impl_scale!(u128, u128);
340impl_scale!(u128, u64);
341impl_scale!(u128, u32);
342impl_scale!(u128, u16);
343impl_scale!(u128, u8);
344impl_scale!(u64, u64);
345impl_scale!(u64, u32);
346impl_scale!(u64, u16);
347impl_scale!(u64, u8);
348impl_scale!(u32, u32);
349impl_scale!(u32, u16);
350impl_scale!(u32, u8);
351impl_scale!(u16, u16);
352impl_scale!(u16, u8);
353impl_scale!(u8, u8);
354
355pub trait Clear {
358 fn is_clear(&self) -> bool;
360
361 fn clear() -> Self;
363}
364
365impl<T: Default + Eq + PartialEq> Clear for T {
366 fn is_clear(&self) -> bool { *self == Self::clear() }
367 fn clear() -> Self { Default::default() }
368}
369
370pub trait SimpleBitOps:
372 Sized + Clear +
373 tetcore_std::ops::BitOr<Self, Output = Self> +
374 tetcore_std::ops::BitXor<Self, Output = Self> +
375 tetcore_std::ops::BitAnd<Self, Output = Self>
376{}
377impl<T:
378 Sized + Clear +
379 tetcore_std::ops::BitOr<Self, Output = Self> +
380 tetcore_std::ops::BitXor<Self, Output = Self> +
381 tetcore_std::ops::BitAnd<Self, Output = Self>
382> SimpleBitOps for T {}
383
384pub trait Hash: 'static + MaybeSerializeDeserialize + Debug + Clone + Eq + PartialEq + Hasher<Out = <Self as Hash>::Output> {
388 type Output: Member + MaybeSerializeDeserialize + Debug + tetcore_std::hash::Hash
390 + AsRef<[u8]> + AsMut<[u8]> + Copy + Default + Encode + Decode;
391
392 fn hash(s: &[u8]) -> Self::Output {
394 <Self as Hasher>::hash(s)
395 }
396
397 fn hash_of<S: Encode>(s: &S) -> Self::Output {
399 Encode::using_encoded(s, <Self as Hasher>::hash)
400 }
401
402 fn ordered_trie_root(input: Vec<Vec<u8>>) -> Self::Output;
404
405 fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>) -> Self::Output;
407}
408
409#[derive(PartialEq, Eq, Clone, RuntimeDebug)]
411#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
412pub struct BlakeTwo256;
413
414impl Hasher for BlakeTwo256 {
415 type Out = tet_core::H256;
416 type StdHasher = tetsy_hash256_std_hasher::Hash256StdHasher;
417 const LENGTH: usize = 32;
418
419 fn hash(s: &[u8]) -> Self::Out {
420 tet_io::hashing::blake2_256(s).into()
421 }
422}
423
424impl Hash for BlakeTwo256 {
425 type Output = tet_core::H256;
426
427 fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>) -> Self::Output {
428 tet_io::trie::blake2_256_root(input)
429 }
430
431 fn ordered_trie_root(input: Vec<Vec<u8>>) -> Self::Output {
432 tet_io::trie::blake2_256_ordered_root(input)
433 }
434}
435
436#[derive(PartialEq, Eq, Clone, RuntimeDebug)]
438#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
439pub struct Keccak256;
440
441impl Hasher for Keccak256 {
442 type Out = tet_core::H256;
443 type StdHasher = tetsy_hash256_std_hasher::Hash256StdHasher;
444 const LENGTH: usize = 32;
445
446 fn hash(s: &[u8]) -> Self::Out {
447 tet_io::hashing::keccak_256(s).into()
448 }
449}
450
451impl Hash for Keccak256 {
452 type Output = tet_core::H256;
453
454 fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>) -> Self::Output {
455 tet_io::trie::keccak_256_root(input)
456 }
457
458 fn ordered_trie_root(input: Vec<Vec<u8>>) -> Self::Output {
459 tet_io::trie::keccak_256_ordered_root(input)
460 }
461}
462
463pub trait CheckEqual {
465 fn check_equal(&self, other: &Self);
467}
468
469impl CheckEqual for tet_core::H256 {
470 #[cfg(feature = "std")]
471 fn check_equal(&self, other: &Self) {
472 use tet_core::hexdisplay::HexDisplay;
473 if self != other {
474 println!(
475 "Hash: given={}, expected={}",
476 HexDisplay::from(self.as_fixed_bytes()),
477 HexDisplay::from(other.as_fixed_bytes()),
478 );
479 }
480 }
481
482 #[cfg(not(feature = "std"))]
483 fn check_equal(&self, other: &Self) {
484 if self != other {
485 "Hash not equal".print();
486 self.as_bytes().print();
487 other.as_bytes().print();
488 }
489 }
490}
491
492impl<H: PartialEq + Eq + Debug> CheckEqual for super::generic::DigestItem<H> where H: Encode {
493 #[cfg(feature = "std")]
494 fn check_equal(&self, other: &Self) {
495 if self != other {
496 println!("DigestItem: given={:?}, expected={:?}", self, other);
497 }
498 }
499
500 #[cfg(not(feature = "std"))]
501 fn check_equal(&self, other: &Self) {
502 if self != other {
503 "DigestItem not equal".print();
504 (&Encode::encode(self)[..]).print();
505 (&Encode::encode(other)[..]).print();
506 }
507 }
508}
509
510tet_core::impl_maybe_marker!(
511 trait MaybeDisplay: Display;
513
514 trait MaybeFromStr: FromStr;
516
517 trait MaybeHash: tetcore_std::hash::Hash;
519
520 trait MaybeSerialize: Serialize;
522
523 trait MaybeSerializeDeserialize: DeserializeOwned, Serialize;
525
526 trait MaybeMallocSizeOf: tetsy_util_mem::MallocSizeOf;
528);
529
530pub trait Member: Send + Sync + Sized + Debug + Eq + PartialEq + Clone + 'static {}
532impl<T: Send + Sync + Sized + Debug + Eq + PartialEq + Clone + 'static> Member for T {}
533
534pub trait IsMember<MemberId> {
536 fn is_member(member_id: &MemberId) -> bool;
538}
539
540pub trait Header:
546 Clone + Send + Sync + Codec + Eq + MaybeSerialize + Debug +
547 MaybeMallocSizeOf + 'static
548{
549 type Number: Member + MaybeSerializeDeserialize + Debug + tetcore_std::hash::Hash + Copy +
551 MaybeDisplay + AtLeast32BitUnsigned + Codec + tetcore_std::str::FromStr + MaybeMallocSizeOf;
552 type Hash: Member + MaybeSerializeDeserialize + Debug + tetcore_std::hash::Hash + Ord
554 + Copy + MaybeDisplay + Default + SimpleBitOps + Codec + AsRef<[u8]>
555 + AsMut<[u8]> + MaybeMallocSizeOf;
556 type Hashing: Hash<Output = Self::Hash>;
558
559 fn new(
561 number: Self::Number,
562 extrinsics_root: Self::Hash,
563 state_root: Self::Hash,
564 parent_hash: Self::Hash,
565 digest: Digest<Self::Hash>,
566 ) -> Self;
567
568 fn number(&self) -> &Self::Number;
570 fn set_number(&mut self, number: Self::Number);
572
573 fn extrinsics_root(&self) -> &Self::Hash;
575 fn set_extrinsics_root(&mut self, root: Self::Hash);
577
578 fn state_root(&self) -> &Self::Hash;
580 fn set_state_root(&mut self, root: Self::Hash);
582
583 fn parent_hash(&self) -> &Self::Hash;
585 fn set_parent_hash(&mut self, hash: Self::Hash);
587
588 fn digest(&self) -> &Digest<Self::Hash>;
590 fn digest_mut(&mut self) -> &mut Digest<Self::Hash>;
592
593 fn hash(&self) -> Self::Hash {
595 <Self::Hashing as Hash>::hash_of(self)
596 }
597}
598
599pub trait Block: Clone + Send + Sync + Codec + Eq + MaybeSerialize + Debug + MaybeMallocSizeOf + 'static {
604 type Extrinsic: Member + Codec + Extrinsic + MaybeSerialize + MaybeMallocSizeOf;
606 type Header: Header<Hash=Self::Hash> + MaybeMallocSizeOf;
608 type Hash: Member + MaybeSerializeDeserialize + Debug + tetcore_std::hash::Hash + Ord
610 + Copy + MaybeDisplay + Default + SimpleBitOps + Codec + AsRef<[u8]> + AsMut<[u8]>
611 + MaybeMallocSizeOf;
612
613 fn header(&self) -> &Self::Header;
615 fn extrinsics(&self) -> &[Self::Extrinsic];
617 fn deconstruct(self) -> (Self::Header, Vec<Self::Extrinsic>);
619 fn new(header: Self::Header, extrinsics: Vec<Self::Extrinsic>) -> Self;
621 fn hash(&self) -> Self::Hash {
623 <<Self::Header as Header>::Hashing as Hash>::hash_of(self.header())
624 }
625 fn encode_from(header: &Self::Header, extrinsics: &[Self::Extrinsic]) -> Vec<u8>;
628}
629
630
631pub trait Extrinsic: Sized + MaybeMallocSizeOf {
633 type Call;
635
636 type SignaturePayload;
642
643 fn is_signed(&self) -> Option<bool> { None }
646
647 fn new(_call: Self::Call, _signed_data: Option<Self::SignaturePayload>) -> Option<Self> { None }
654}
655
656pub trait ExtrinsicMetadata {
658 const VERSION: u8;
660
661 type SignedExtensions: SignedExtension;
663}
664
665pub type HashFor<B> = <<B as Block>::Header as Header>::Hashing;
667pub type NumberFor<B> = <<B as Block>::Header as Header>::Number;
669pub type DigestFor<B> = Digest<<<B as Block>::Header as Header>::Hash>;
671pub type DigestItemFor<B> = DigestItem<<<B as Block>::Header as Header>::Hash>;
673
674pub trait Checkable<Context>: Sized {
679 type Checked;
681
682 fn check(self, c: &Context) -> Result<Self::Checked, TransactionValidityError>;
684}
685
686pub trait BlindCheckable: Sized {
691 type Checked;
693
694 fn check(self) -> Result<Self::Checked, TransactionValidityError>;
696}
697
698impl<T: BlindCheckable, Context> Checkable<Context> for T {
700 type Checked = <Self as BlindCheckable>::Checked;
701
702 fn check(self, _c: &Context) -> Result<Self::Checked, TransactionValidityError> {
703 BlindCheckable::check(self)
704 }
705}
706
707pub trait Dispatchable {
710 type Origin;
714 type Config;
716 type Info;
720 type PostInfo: Eq + PartialEq + Clone + Copy + Encode + Decode + Printable;
723 fn dispatch(self, origin: Self::Origin) -> crate::DispatchResultWithInfo<Self::PostInfo>;
725}
726
727pub type DispatchInfoOf<T> = <T as Dispatchable>::Info;
729pub type PostDispatchInfoOf<T> = <T as Dispatchable>::PostInfo;
731
732impl Dispatchable for () {
733 type Origin = ();
734 type Config = ();
735 type Info = ();
736 type PostInfo = ();
737 fn dispatch(self, _origin: Self::Origin) -> crate::DispatchResultWithInfo<Self::PostInfo> {
738 panic!("This implemention should not be used for actual dispatch.");
739 }
740}
741
742pub trait SignedExtension: Codec + Debug + Sync + Send + Clone + Eq + PartialEq {
745 const IDENTIFIER: &'static str;
750
751 type AccountId;
753
754 type Call: Dispatchable;
756
757 type AdditionalSigned: Encode;
760
761 type Pre: Default;
763
764 fn additional_signed(&self) -> Result<Self::AdditionalSigned, TransactionValidityError>;
767
768 fn validate(
778 &self,
779 _who: &Self::AccountId,
780 _call: &Self::Call,
781 _info: &DispatchInfoOf<Self::Call>,
782 _len: usize,
783 ) -> TransactionValidity {
784 Ok(ValidTransaction::default())
785 }
786
787 fn pre_dispatch(
796 self,
797 who: &Self::AccountId,
798 call: &Self::Call,
799 info: &DispatchInfoOf<Self::Call>,
800 len: usize,
801 ) -> Result<Self::Pre, TransactionValidityError> {
802 self.validate(who, call, info, len)
803 .map(|_| Self::Pre::default())
804 .map_err(Into::into)
805 }
806
807 fn validate_unsigned(
816 _call: &Self::Call,
817 _info: &DispatchInfoOf<Self::Call>,
818 _len: usize,
819 ) -> TransactionValidity {
820 Ok(ValidTransaction::default())
821 }
822
823 fn pre_dispatch_unsigned(
832 call: &Self::Call,
833 info: &DispatchInfoOf<Self::Call>,
834 len: usize,
835 ) -> Result<Self::Pre, TransactionValidityError> {
836 Self::validate_unsigned(call, info, len)
837 .map(|_| Self::Pre::default())
838 .map_err(Into::into)
839 }
840
841 fn post_dispatch(
855 _pre: Self::Pre,
856 _info: &DispatchInfoOf<Self::Call>,
857 _post_info: &PostDispatchInfoOf<Self::Call>,
858 _len: usize,
859 _result: &DispatchResult,
860 ) -> Result<(), TransactionValidityError> {
861 Ok(())
862 }
863
864 fn identifier() -> Vec<&'static str> {
872 tetcore_std::vec![Self::IDENTIFIER]
873 }
874}
875
876#[impl_for_tuples(1, 12)]
877impl<AccountId, Call: Dispatchable> SignedExtension for Tuple {
878 for_tuples!( where #( Tuple: SignedExtension<AccountId=AccountId, Call=Call,> )* );
879 type AccountId = AccountId;
880 type Call = Call;
881 const IDENTIFIER: &'static str = "You should call `identifier()`!";
882 for_tuples!( type AdditionalSigned = ( #( Tuple::AdditionalSigned ),* ); );
883 for_tuples!( type Pre = ( #( Tuple::Pre ),* ); );
884
885 fn additional_signed(&self) -> Result<Self::AdditionalSigned, TransactionValidityError> {
886 Ok(for_tuples!( ( #( Tuple.additional_signed()? ),* ) ))
887 }
888
889 fn validate(
890 &self,
891 who: &Self::AccountId,
892 call: &Self::Call,
893 info: &DispatchInfoOf<Self::Call>,
894 len: usize,
895 ) -> TransactionValidity {
896 let valid = ValidTransaction::default();
897 for_tuples!( #( let valid = valid.combine_with(Tuple.validate(who, call, info, len)?); )* );
898 Ok(valid)
899 }
900
901 fn pre_dispatch(self, who: &Self::AccountId, call: &Self::Call, info: &DispatchInfoOf<Self::Call>, len: usize)
902 -> Result<Self::Pre, TransactionValidityError>
903 {
904 Ok(for_tuples!( ( #( Tuple.pre_dispatch(who, call, info, len)? ),* ) ))
905 }
906
907 fn validate_unsigned(
908 call: &Self::Call,
909 info: &DispatchInfoOf<Self::Call>,
910 len: usize,
911 ) -> TransactionValidity {
912 let valid = ValidTransaction::default();
913 for_tuples!( #( let valid = valid.combine_with(Tuple::validate_unsigned(call, info, len)?); )* );
914 Ok(valid)
915 }
916
917 fn pre_dispatch_unsigned(
918 call: &Self::Call,
919 info: &DispatchInfoOf<Self::Call>,
920 len: usize,
921 ) -> Result<Self::Pre, TransactionValidityError> {
922 Ok(for_tuples!( ( #( Tuple::pre_dispatch_unsigned(call, info, len)? ),* ) ))
923 }
924
925 fn post_dispatch(
926 pre: Self::Pre,
927 info: &DispatchInfoOf<Self::Call>,
928 post_info: &PostDispatchInfoOf<Self::Call>,
929 len: usize,
930 result: &DispatchResult,
931 ) -> Result<(), TransactionValidityError> {
932 for_tuples!( #( Tuple::post_dispatch(pre.Tuple, info, post_info, len, result)?; )* );
933 Ok(())
934 }
935
936 fn identifier() -> Vec<&'static str> {
937 let mut ids = Vec::new();
938 for_tuples!( #( ids.extend(Tuple::identifier()); )* );
939 ids
940 }
941}
942
943#[cfg(feature = "std")]
945impl SignedExtension for () {
946 type AccountId = u64;
947 type AdditionalSigned = ();
948 type Call = ();
949 type Pre = ();
950 const IDENTIFIER: &'static str = "UnitSignedExtension";
951 fn additional_signed(&self) -> tetcore_std::result::Result<(), TransactionValidityError> { Ok(()) }
952}
953
954pub trait Applyable: Sized + Send + Sync {
961 type Call: Dispatchable;
963
964 fn validate<V: ValidateUnsigned<Call=Self::Call>>(
966 &self,
967 source: TransactionSource,
968 info: &DispatchInfoOf<Self::Call>,
969 len: usize,
970 ) -> TransactionValidity;
971
972 fn apply<V: ValidateUnsigned<Call=Self::Call>>(
975 self,
976 info: &DispatchInfoOf<Self::Call>,
977 len: usize,
978 ) -> crate::ApplyExtrinsicResultWithInfo<PostDispatchInfoOf<Self::Call>>;
979}
980
981pub trait GetRuntimeBlockType {
983 type RuntimeBlock: self::Block;
985}
986
987pub trait GetNodeBlockType {
989 type NodeBlock: self::Block;
991}
992
993pub trait ValidateUnsigned {
1000 type Call;
1002
1003 fn pre_dispatch(call: &Self::Call) -> Result<(), TransactionValidityError> {
1014 Self::validate_unsigned(TransactionSource::InBlock, call)
1015 .map(|_| ())
1016 .map_err(Into::into)
1017 }
1018
1019 fn validate_unsigned(source: TransactionSource, call: &Self::Call) -> TransactionValidity;
1026}
1027
1028pub trait OpaqueKeys: Clone {
1031 type KeyTypeIdProviders;
1033
1034 fn key_ids() -> &'static [crate::KeyTypeId];
1036 fn get_raw(&self, i: super::KeyTypeId) -> &[u8];
1038 fn get<T: Decode>(&self, i: super::KeyTypeId) -> Option<T> {
1040 T::decode(&mut self.get_raw(i)).ok()
1041 }
1042 fn ownership_proof_is_valid(&self, _proof: &[u8]) -> bool { true }
1044}
1045
1046pub struct AppendZerosInput<'a, T>(&'a mut T);
1051
1052impl<'a, T> AppendZerosInput<'a, T> {
1053 pub fn new(input: &'a mut T) -> Self {
1055 Self(input)
1056 }
1057}
1058
1059impl<'a, T: codec::Input> codec::Input for AppendZerosInput<'a, T> {
1060 fn remaining_len(&mut self) -> Result<Option<usize>, codec::Error> {
1061 Ok(None)
1062 }
1063
1064 fn read(&mut self, into: &mut [u8]) -> Result<(), codec::Error> {
1065 let remaining = self.0.remaining_len()?;
1066 let completed = if let Some(n) = remaining {
1067 let readable = into.len().min(n);
1068 self.0.read(&mut into[..readable])?;
1070 readable
1071 } else {
1072 let mut i = 0;
1074 while i < into.len() {
1075 if let Ok(b) = self.0.read_byte() {
1076 into[i] = b;
1077 i += 1;
1078 } else {
1079 break;
1080 }
1081 }
1082 i
1083 };
1084 for i in &mut into[completed..] {
1086 *i = 0;
1087 }
1088 Ok(())
1089 }
1090}
1091
1092pub struct TrailingZeroInput<'a>(&'a [u8]);
1094
1095impl<'a> TrailingZeroInput<'a> {
1096 pub fn new(data: &'a [u8]) -> Self {
1098 Self(data)
1099 }
1100}
1101
1102impl<'a> codec::Input for TrailingZeroInput<'a> {
1103 fn remaining_len(&mut self) -> Result<Option<usize>, codec::Error> {
1104 Ok(None)
1105 }
1106
1107 fn read(&mut self, into: &mut [u8]) -> Result<(), codec::Error> {
1108 let len_from_inner = into.len().min(self.0.len());
1109 into[..len_from_inner].copy_from_slice(&self.0[..len_from_inner]);
1110 for i in &mut into[len_from_inner..] {
1111 *i = 0;
1112 }
1113 self.0 = &self.0[len_from_inner..];
1114
1115 Ok(())
1116 }
1117}
1118
1119pub trait AccountIdConversion<AccountId>: Sized {
1121 fn into_account(&self) -> AccountId { self.into_sub_account(&()) }
1123
1124 fn try_from_account(a: &AccountId) -> Option<Self> {
1126 Self::try_from_sub_account::<()>(a).map(|x| x.0)
1127 }
1128
1129 fn into_sub_account<S: Encode>(&self, sub: S) -> AccountId;
1139
1140 fn try_from_sub_account<S: Decode>(x: &AccountId) -> Option<(Self, S)>;
1142}
1143
1144impl<T: Encode + Decode + Default, Id: Encode + Decode + TypeId> AccountIdConversion<T> for Id {
1147 fn into_sub_account<S: Encode>(&self, sub: S) -> T {
1148 (Id::TYPE_ID, self, sub).using_encoded(|b|
1149 T::decode(&mut TrailingZeroInput(b))
1150 ).unwrap_or_default()
1151 }
1152
1153 fn try_from_sub_account<S: Decode>(x: &T) -> Option<(Self, S)> {
1154 x.using_encoded(|d| {
1155 if &d[0..4] != Id::TYPE_ID { return None }
1156 let mut cursor = &d[4..];
1157 let result = Decode::decode(&mut cursor).ok()?;
1158 if cursor.iter().all(|x| *x == 0) {
1159 Some(result)
1160 } else {
1161 None
1162 }
1163 })
1164 }
1165}
1166
1167#[macro_export]
1174macro_rules! count {
1175 ($f:ident ($($x:tt)*) ) => ();
1176 ($f:ident ($($x:tt)*) $x1:tt) => { $f!($($x)* 0); };
1177 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt) => { $f!($($x)* 0); $f!($($x)* 1); };
1178 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt) => { $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); };
1179 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt, $x4:tt) => {
1180 $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); $f!($($x)* 3);
1181 };
1182 ($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt, $x4:tt, $x5:tt) => {
1183 $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); $f!($($x)* 3); $f!($($x)* 4);
1184 };
1185}
1186
1187#[macro_export]
1211macro_rules! impl_opaque_keys {
1212 (
1213 $( #[ $attr:meta ] )*
1214 pub struct $name:ident {
1215 $(
1216 $( #[ $inner_attr:meta ] )*
1217 pub $field:ident: $type:ty,
1218 )*
1219 }
1220 ) => {
1221 $( #[ $attr ] )*
1222 #[derive(
1223 Default, Clone, PartialEq, Eq,
1224 $crate::codec::Encode,
1225 $crate::codec::Decode,
1226 $crate::RuntimeDebug,
1227 )]
1228 #[cfg_attr(feature = "std", derive($crate::serde::Serialize, $crate::serde::Deserialize))]
1229 pub struct $name {
1230 $(
1231 $( #[ $inner_attr ] )*
1232 pub $field: <$type as $crate::BoundToRuntimeAppPublic>::Public,
1233 )*
1234 }
1235
1236 impl $name {
1237 pub fn generate(seed: Option<$crate::tetcore_std::vec::Vec<u8>>) -> $crate::tetcore_std::vec::Vec<u8> {
1243 let keys = Self{
1244 $(
1245 $field: <
1246 <
1247 $type as $crate::BoundToRuntimeAppPublic
1248 >::Public as $crate::RuntimeAppPublic
1249 >::generate_pair(seed.clone()),
1250 )*
1251 };
1252 $crate::codec::Encode::encode(&keys)
1253 }
1254
1255 pub fn into_raw_public_keys(
1257 self,
1258 ) -> $crate::tetcore_std::vec::Vec<($crate::tetcore_std::vec::Vec<u8>, $crate::KeyTypeId)> {
1259 let mut keys = Vec::new();
1260 $(
1261 keys.push((
1262 $crate::RuntimeAppPublic::to_raw_vec(&self.$field),
1263 <
1264 <
1265 $type as $crate::BoundToRuntimeAppPublic
1266 >::Public as $crate::RuntimeAppPublic
1267 >::ID,
1268 ));
1269 )*
1270
1271 keys
1272 }
1273
1274 pub fn decode_into_raw_public_keys(
1279 encoded: &[u8],
1280 ) -> Option<$crate::tetcore_std::vec::Vec<($crate::tetcore_std::vec::Vec<u8>, $crate::KeyTypeId)>> {
1281 <Self as $crate::codec::Decode>::decode(&mut &encoded[..])
1282 .ok()
1283 .map(|s| s.into_raw_public_keys())
1284 }
1285 }
1286
1287 impl $crate::traits::OpaqueKeys for $name {
1288 type KeyTypeIdProviders = ( $( $type, )* );
1289
1290 fn key_ids() -> &'static [$crate::KeyTypeId] {
1291 &[
1292 $(
1293 <
1294 <
1295 $type as $crate::BoundToRuntimeAppPublic
1296 >::Public as $crate::RuntimeAppPublic
1297 >::ID
1298 ),*
1299 ]
1300 }
1301
1302 fn get_raw(&self, i: $crate::KeyTypeId) -> &[u8] {
1303 match i {
1304 $(
1305 i if i == <
1306 <
1307 $type as $crate::BoundToRuntimeAppPublic
1308 >::Public as $crate::RuntimeAppPublic
1309 >::ID =>
1310 self.$field.as_ref(),
1311 )*
1312 _ => &[],
1313 }
1314 }
1315 }
1316 };
1317}
1318
1319pub trait Printable {
1321 fn print(&self);
1323}
1324
1325impl<T: Printable> Printable for &T {
1326 fn print(&self) {
1327 (*self).print()
1328 }
1329}
1330
1331impl Printable for u8 {
1332 fn print(&self) {
1333 (*self as u64).print()
1334 }
1335}
1336
1337impl Printable for u32 {
1338 fn print(&self) {
1339 (*self as u64).print()
1340 }
1341}
1342
1343impl Printable for usize {
1344 fn print(&self) {
1345 (*self as u64).print()
1346 }
1347}
1348
1349impl Printable for u64 {
1350 fn print(&self) {
1351 tet_io::misc::print_num(*self);
1352 }
1353}
1354
1355impl Printable for &[u8] {
1356 fn print(&self) {
1357 tet_io::misc::print_hex(self);
1358 }
1359}
1360
1361impl Printable for &str {
1362 fn print(&self) {
1363 tet_io::misc::print_utf8(self.as_bytes());
1364 }
1365}
1366
1367impl Printable for bool {
1368 fn print(&self) {
1369 if *self {
1370 "true".print()
1371 } else {
1372 "false".print()
1373 }
1374 }
1375}
1376
1377impl Printable for () {
1378 fn print(&self) {
1379 "()".print()
1380 }
1381}
1382
1383#[impl_for_tuples(1, 12)]
1384impl Printable for Tuple {
1385 fn print(&self) {
1386 for_tuples!( #( Tuple.print(); )* )
1387 }
1388}
1389
1390#[cfg(feature = "std")]
1392pub trait BlockIdTo<Block: self::Block> {
1393 type Error: std::fmt::Debug;
1395
1396 fn to_hash(
1398 &self,
1399 block_id: &crate::generic::BlockId<Block>,
1400 ) -> Result<Option<Block::Hash>, Self::Error>;
1401
1402 fn to_number(
1404 &self,
1405 block_id: &crate::generic::BlockId<Block>,
1406 ) -> Result<Option<NumberFor<Block>>, Self::Error>;
1407}
1408
1409#[cfg(test)]
1410mod tests {
1411 use super::*;
1412 use crate::codec::{Encode, Decode, Input};
1413 use tet_core::{crypto::Pair, ecdsa};
1414
1415 mod t {
1416 use tet_core::crypto::KeyTypeId;
1417 use tet_application_crypto::{app_crypto, sr25519};
1418 app_crypto!(sr25519, KeyTypeId(*b"test"));
1419 }
1420
1421 #[test]
1422 fn app_verify_works() {
1423 use t::*;
1424 use super::AppVerify;
1425
1426 let s = Signature::default();
1427 let _ = s.verify(&[0u8; 100][..], &Public::default());
1428 }
1429
1430 #[derive(Encode, Decode, Default, PartialEq, Debug)]
1431 struct U32Value(u32);
1432 impl super::TypeId for U32Value {
1433 const TYPE_ID: [u8; 4] = [0x0d, 0xf0, 0xfe, 0xca];
1434 }
1435 #[derive(Encode, Decode, Default, PartialEq, Debug)]
1438 struct U16Value(u16);
1439 impl super::TypeId for U16Value {
1440 const TYPE_ID: [u8; 4] = [0xfe, 0xca, 0x0d, 0xf0];
1441 }
1442 type AccountId = u64;
1445
1446 #[test]
1447 fn into_account_should_work() {
1448 let r: AccountId = U32Value::into_account(&U32Value(0xdeadbeef));
1449 assert_eq!(r, 0x_deadbeef_cafef00d);
1450 }
1451
1452 #[test]
1453 fn try_from_account_should_work() {
1454 let r = U32Value::try_from_account(&0x_deadbeef_cafef00d_u64);
1455 assert_eq!(r.unwrap(), U32Value(0xdeadbeef));
1456 }
1457
1458 #[test]
1459 fn into_account_with_fill_should_work() {
1460 let r: AccountId = U16Value::into_account(&U16Value(0xc0da));
1461 assert_eq!(r, 0x_0000_c0da_f00dcafe);
1462 }
1463
1464 #[test]
1465 fn try_from_account_with_fill_should_work() {
1466 let r = U16Value::try_from_account(&0x0000_c0da_f00dcafe_u64);
1467 assert_eq!(r.unwrap(), U16Value(0xc0da));
1468 }
1469
1470 #[test]
1471 fn bad_try_from_account_should_fail() {
1472 let r = U16Value::try_from_account(&0x0000_c0de_baadcafe_u64);
1473 assert!(r.is_none());
1474 let r = U16Value::try_from_account(&0x0100_c0da_f00dcafe_u64);
1475 assert!(r.is_none());
1476 }
1477
1478 #[test]
1479 fn trailing_zero_should_work() {
1480 let mut t = super::TrailingZeroInput(&[1, 2, 3]);
1481 assert_eq!(t.remaining_len(), Ok(None));
1482 let mut buffer = [0u8; 2];
1483 assert_eq!(t.read(&mut buffer), Ok(()));
1484 assert_eq!(t.remaining_len(), Ok(None));
1485 assert_eq!(buffer, [1, 2]);
1486 assert_eq!(t.read(&mut buffer), Ok(()));
1487 assert_eq!(t.remaining_len(), Ok(None));
1488 assert_eq!(buffer, [3, 0]);
1489 assert_eq!(t.read(&mut buffer), Ok(()));
1490 assert_eq!(t.remaining_len(), Ok(None));
1491 assert_eq!(buffer, [0, 0]);
1492 }
1493
1494 #[test]
1495 fn ecdsa_verify_works() {
1496 let msg = &b"test-message"[..];
1497 let (pair, _) = ecdsa::Pair::generate();
1498
1499 let signature = pair.sign(&msg);
1500 assert!(ecdsa::Pair::verify(&signature, msg, &pair.public()));
1501
1502 assert!(signature.verify(msg, &pair.public()));
1503 assert!(signature.verify(msg, &pair.public()));
1504 }
1505}