tp_runtime/
traits.rs

1// This file is part of Tetcore.
2
3// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Primitives for the runtime modules.
19
20use 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
45/// A lazy value.
46pub trait Lazy<T: ?Sized> {
47	/// Get a reference to the underlying value.
48	///
49	/// This will compute the value if the function is invoked for the first time.
50	fn get(&mut self) -> &T;
51}
52
53impl<'a> Lazy<[u8]> for &'a [u8] {
54	fn get(&mut self) -> &[u8] { &**self }
55}
56
57/// Some type that is able to be collapsed into an account ID. It is not possible to recreate the
58/// original value from the account ID.
59pub trait IdentifyAccount {
60	/// The account ID that this can be transformed into.
61	type AccountId;
62	/// Transform into an account.
63	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
81/// Means of signature verification.
82pub trait Verify {
83	/// Type of the signer.
84	type Signer: IdentifyAccount;
85	/// Verify a signature.
86	///
87	/// Return `true` if signature is valid for the value.
88	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
120/// Means of signature verification of an application key.
121pub trait AppVerify {
122	/// Type of the signer.
123	type AccountId;
124	/// Verify a signature. Return `true` if signature is valid for the value.
125	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/// An error type that indicates that the origin is invalid.
147#[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/// Error that can be returned by our impl of `StoredMap`.
157#[derive(Encode, Decode, RuntimeDebug)]
158pub enum StoredMapError {
159	/// Attempt to create map value when it is a consumer and there are no providers in place.
160	NoProviders,
161	/// Attempt to anull/remove value when it is the last provider and there is still at
162	/// least one consumer left.
163	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/// An error that indicates that a lookup failed.
176#[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
191/// Means of changing one type into another in a manner dependent on the source type.
192pub trait Lookup {
193	/// Type to lookup from.
194	type Source;
195	/// Type to lookup into.
196	type Target;
197	/// Attempt a lookup.
198	fn lookup(&self, s: Self::Source) -> Result<Self::Target, LookupError>;
199}
200
201/// Means of changing one type into another in a manner dependent on the source type.
202/// This variant is different to `Lookup` in that it doesn't (can cannot) require any
203/// context.
204pub trait StaticLookup {
205	/// Type to lookup from.
206	type Source: Codec + Clone + PartialEq + Debug;
207	/// Type to lookup into.
208	type Target;
209	/// Attempt a lookup.
210	fn lookup(s: Self::Source) -> Result<Self::Target, LookupError>;
211	/// Convert from Target back to Source.
212	fn unlookup(t: Self::Target) -> Self::Source;
213}
214
215/// A lookup implementation returning the input value.
216#[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
231/// A lookup implementation returning the `AccountId` from a `MultiAddress`.
232pub 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
252/// Perform a StaticLookup where there are multiple lookup sources of the same type.
253impl<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
269/// Extensible conversion trait. Generic over both source and destination types.
270pub trait Convert<A, B> {
271	/// Make conversion.
272	fn convert(a: A) -> B;
273}
274
275impl<A, B: Default> Convert<A, B> for () {
276	fn convert(_: A) -> B { Default::default() }
277}
278
279/// A structure that performs identity conversion.
280pub struct Identity;
281impl<T> Convert<T, T> for Identity {
282	fn convert(a: T) -> T { a }
283}
284
285/// A structure that performs standard conversion using the standard Rust conversion traits.
286pub struct ConvertInto;
287impl<A, B: From<A>> Convert<A, B> for ConvertInto {
288	fn convert(a: A) -> B { a.into() }
289}
290
291/// Convenience type to work around the highly unergonomic syntax needed
292/// to invoke the functions of overloaded generic traits, in this case
293/// `TryFrom` and `TryInto`.
294pub trait CheckedConversion {
295	/// Convert from a value of `T` into an equivalent instance of `Option<Self>`.
296	///
297	/// This just uses `TryFrom` internally but with this
298	/// variant you can provide the destination type using turbofish syntax
299	/// in case Rust happens not to assume the correct type.
300	fn checked_from<T>(t: T) -> Option<Self> where Self: TryFrom<T> {
301		<Self as TryFrom<T>>::try_from(t).ok()
302	}
303	/// Consume self to return `Some` equivalent value of `Option<T>`.
304	///
305	/// This just uses `TryInto` internally but with this
306	/// variant you can provide the destination type using turbofish syntax
307	/// in case Rust happens not to assume the correct type.
308	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
314/// Multiply and divide by a number that isn't necessarily the same type. Basically just the same
315/// as `Mul` and `Div` except it can be used for all basic numeric types.
316pub trait Scale<Other> {
317	/// The output type of the product of `self` and `Other`.
318	type Output;
319
320	/// @return the product of `self` and `other`.
321	fn mul(self, other: Other) -> Self::Output;
322
323	/// @return the integer division of `self` and `other`.
324	fn div(self, other: Other) -> Self::Output;
325
326	/// @return the modulo remainder of `self` and `other`.
327	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
355/// Trait for things that can be clear (have no bits set). For numeric types, essentially the same
356/// as `Zero`.
357pub trait Clear {
358	/// True iff no bits are set.
359	fn is_clear(&self) -> bool;
360
361	/// Return the value of Self that is clear.
362	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
370/// A meta trait for all bit ops.
371pub 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
384/// Abstraction around hashing
385// Stupid bug in the Rust compiler believes derived
386// traits must be fulfilled by all type parameters.
387pub trait Hash: 'static + MaybeSerializeDeserialize + Debug + Clone + Eq + PartialEq + Hasher<Out = <Self as Hash>::Output> {
388	/// The hash type produced.
389	type Output: Member + MaybeSerializeDeserialize + Debug + tetcore_std::hash::Hash
390		+ AsRef<[u8]> + AsMut<[u8]> + Copy + Default + Encode + Decode;
391
392	/// Produce the hash of some byte-slice.
393	fn hash(s: &[u8]) -> Self::Output {
394		<Self as Hasher>::hash(s)
395	}
396
397	/// Produce the hash of some codec-encodable value.
398	fn hash_of<S: Encode>(s: &S) -> Self::Output {
399		Encode::using_encoded(s, <Self as Hasher>::hash)
400	}
401
402	/// The ordered Patricia tree root of the given `input`.
403	fn ordered_trie_root(input: Vec<Vec<u8>>) -> Self::Output;
404
405	/// The Patricia tree root of the given mapping.
406	fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>) -> Self::Output;
407}
408
409/// Blake2-256 Hash implementation.
410#[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/// Keccak-256 Hash implementation.
437#[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
463/// Something that can be checked for equality and printed out to a debug channel if bad.
464pub trait CheckEqual {
465	/// Perform the equality check.
466	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	/// A type that implements Display when in std environment.
512	trait MaybeDisplay: Display;
513
514	/// A type that implements FromStr when in std environment.
515	trait MaybeFromStr: FromStr;
516
517	/// A type that implements Hash when in std environment.
518	trait MaybeHash: tetcore_std::hash::Hash;
519
520	/// A type that implements Serialize when in std environment.
521	trait MaybeSerialize: Serialize;
522
523	/// A type that implements Serialize, DeserializeOwned and Debug when in std environment.
524	trait MaybeSerializeDeserialize: DeserializeOwned, Serialize;
525
526	/// A type that implements MallocSizeOf.
527	trait MaybeMallocSizeOf: tetsy_util_mem::MallocSizeOf;
528);
529
530/// A type that can be used in runtime structures.
531pub trait Member: Send + Sync + Sized + Debug + Eq + PartialEq + Clone + 'static {}
532impl<T: Send + Sync + Sized + Debug + Eq + PartialEq + Clone + 'static> Member for T {}
533
534/// Determine if a `MemberId` is a valid member.
535pub trait IsMember<MemberId> {
536	/// Is the given `MemberId` a valid member?
537	fn is_member(member_id: &MemberId) -> bool;
538}
539
540/// Something which fulfills the abstract idea of a Tetcore header. It has types for a `Number`,
541/// a `Hash` and a `Hashing`. It provides access to an `extrinsics_root`, `state_root` and
542/// `parent_hash`, as well as a `digest` and a block `number`.
543///
544/// You can also create a `new` one from those fields.
545pub trait Header:
546	Clone + Send + Sync + Codec + Eq + MaybeSerialize + Debug +
547	MaybeMallocSizeOf + 'static
548{
549	/// Header number.
550	type Number: Member + MaybeSerializeDeserialize + Debug + tetcore_std::hash::Hash + Copy +
551		MaybeDisplay + AtLeast32BitUnsigned + Codec + tetcore_std::str::FromStr + MaybeMallocSizeOf;
552	/// Header hash type
553	type Hash: Member + MaybeSerializeDeserialize + Debug + tetcore_std::hash::Hash + Ord
554		+ Copy + MaybeDisplay + Default + SimpleBitOps + Codec + AsRef<[u8]>
555		+ AsMut<[u8]> + MaybeMallocSizeOf;
556	/// Hashing algorithm
557	type Hashing: Hash<Output = Self::Hash>;
558
559	/// Creates new header.
560	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	/// Returns a reference to the header number.
569	fn number(&self) -> &Self::Number;
570	/// Sets the header number.
571	fn set_number(&mut self, number: Self::Number);
572
573	/// Returns a reference to the extrinsics root.
574	fn extrinsics_root(&self) -> &Self::Hash;
575	/// Sets the extrinsic root.
576	fn set_extrinsics_root(&mut self, root: Self::Hash);
577
578	/// Returns a reference to the state root.
579	fn state_root(&self) -> &Self::Hash;
580	/// Sets the state root.
581	fn set_state_root(&mut self, root: Self::Hash);
582
583	/// Returns a reference to the parent hash.
584	fn parent_hash(&self) -> &Self::Hash;
585	/// Sets the parent hash.
586	fn set_parent_hash(&mut self, hash: Self::Hash);
587
588	/// Returns a reference to the digest.
589	fn digest(&self) -> &Digest<Self::Hash>;
590	/// Get a mutable reference to the digest.
591	fn digest_mut(&mut self) -> &mut Digest<Self::Hash>;
592
593	/// Returns the hash of the header.
594	fn hash(&self) -> Self::Hash {
595		<Self::Hashing as Hash>::hash_of(self)
596	}
597}
598
599/// Something which fulfills the abstract idea of a Tetcore block. It has types for
600/// `Extrinsic` pieces of information as well as a `Header`.
601///
602/// You can get an iterator over each of the `extrinsics` and retrieve the `header`.
603pub trait Block: Clone + Send + Sync + Codec + Eq + MaybeSerialize + Debug + MaybeMallocSizeOf + 'static {
604	/// Type for extrinsics.
605	type Extrinsic: Member + Codec + Extrinsic + MaybeSerialize + MaybeMallocSizeOf;
606	/// Header type.
607	type Header: Header<Hash=Self::Hash> + MaybeMallocSizeOf;
608	/// Block hash type.
609	type Hash: Member + MaybeSerializeDeserialize + Debug + tetcore_std::hash::Hash + Ord
610		+ Copy + MaybeDisplay + Default + SimpleBitOps + Codec + AsRef<[u8]> + AsMut<[u8]>
611		+ MaybeMallocSizeOf;
612
613	/// Returns a reference to the header.
614	fn header(&self) -> &Self::Header;
615	/// Returns a reference to the list of extrinsics.
616	fn extrinsics(&self) -> &[Self::Extrinsic];
617	/// Split the block into header and list of extrinsics.
618	fn deconstruct(self) -> (Self::Header, Vec<Self::Extrinsic>);
619	/// Creates new block from header and extrinsics.
620	fn new(header: Self::Header, extrinsics: Vec<Self::Extrinsic>) -> Self;
621	/// Returns the hash of the block.
622	fn hash(&self) -> Self::Hash {
623		<<Self::Header as Header>::Hashing as Hash>::hash_of(self.header())
624	}
625	/// Creates an encoded block from the given `header` and `extrinsics` without requiring the
626	/// creation of an instance.
627	fn encode_from(header: &Self::Header, extrinsics: &[Self::Extrinsic]) -> Vec<u8>;
628}
629
630
631/// Something that acts like an `Extrinsic`.
632pub trait Extrinsic: Sized + MaybeMallocSizeOf {
633	/// The function call.
634	type Call;
635
636	/// The payload we carry for signed extrinsics.
637	///
638	/// Usually it will contain a `Signature` and
639	/// may include some additional data that are specific to signed
640	/// extrinsics.
641	type SignaturePayload;
642
643	/// Is this `Extrinsic` signed?
644	/// If no information are available about signed/unsigned, `None` should be returned.
645	fn is_signed(&self) -> Option<bool> { None }
646
647	/// Create new instance of the extrinsic.
648	///
649	/// Extrinsics can be split into:
650	/// 1. Inherents (no signature; created by validators during block production)
651	/// 2. Unsigned Transactions (no signature; represent "system calls" or other special kinds of calls)
652	/// 3. Signed Transactions (with signature; a regular transactions with known origin)
653	fn new(_call: Self::Call, _signed_data: Option<Self::SignaturePayload>) -> Option<Self> { None }
654}
655
656/// Implementor is an [`Extrinsic`] and provides metadata about this extrinsic.
657pub trait ExtrinsicMetadata {
658	/// The version of the `Extrinsic`.
659	const VERSION: u8;
660
661	/// Signed extensions attached to this `Extrinsic`.
662	type SignedExtensions: SignedExtension;
663}
664
665/// Extract the hashing type for a block.
666pub type HashFor<B> = <<B as Block>::Header as Header>::Hashing;
667/// Extract the number type for a block.
668pub type NumberFor<B> = <<B as Block>::Header as Header>::Number;
669/// Extract the digest type for a block.
670pub type DigestFor<B> = Digest<<<B as Block>::Header as Header>::Hash>;
671/// Extract the digest item type for a block.
672pub type DigestItemFor<B> = DigestItem<<<B as Block>::Header as Header>::Hash>;
673
674/// A "checkable" piece of information, used by the standard Tetcore Executive in order to
675/// check the validity of a piece of extrinsic information, usually by verifying the signature.
676/// Implement for pieces of information that require some additional context `Context` in order to be
677/// checked.
678pub trait Checkable<Context>: Sized {
679	/// Returned if `check` succeeds.
680	type Checked;
681
682	/// Check self, given an instance of Context.
683	fn check(self, c: &Context) -> Result<Self::Checked, TransactionValidityError>;
684}
685
686/// A "checkable" piece of information, used by the standard Tetcore Executive in order to
687/// check the validity of a piece of extrinsic information, usually by verifying the signature.
688/// Implement for pieces of information that don't require additional context in order to be
689/// checked.
690pub trait BlindCheckable: Sized {
691	/// Returned if `check` succeeds.
692	type Checked;
693
694	/// Check self.
695	fn check(self) -> Result<Self::Checked, TransactionValidityError>;
696}
697
698// Every `BlindCheckable` is also a `StaticCheckable` for arbitrary `Context`.
699impl<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
707/// A lazy call (module function and argument values) that can be executed via its `dispatch`
708/// method.
709pub trait Dispatchable {
710	/// Every function call from your runtime has an origin, which specifies where the extrinsic was
711	/// generated from. In the case of a signed extrinsic (transaction), the origin contains an
712	/// identifier for the caller. The origin can be empty in the case of an inherent extrinsic.
713	type Origin;
714	/// ...
715	type Config;
716	/// An opaque set of information attached to the transaction. This could be constructed anywhere
717	/// down the line in a runtime. The current Tetcore runtime uses a struct with the same name
718	/// to represent the dispatch class and weight.
719	type Info;
720	/// Additional information that is returned by `dispatch`. Can be used to supply the caller
721	/// with information about a `Dispatchable` that is ownly known post dispatch.
722	type PostInfo: Eq + PartialEq + Clone + Copy + Encode + Decode + Printable;
723	/// Actually dispatch this call and return the result of it.
724	fn dispatch(self, origin: Self::Origin) -> crate::DispatchResultWithInfo<Self::PostInfo>;
725}
726
727/// Shortcut to reference the `Info` type of a `Dispatchable`.
728pub type DispatchInfoOf<T> = <T as Dispatchable>::Info;
729/// Shortcut to reference the `PostInfo` type of a `Dispatchable`.
730pub 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
742/// Means by which a transaction may be extended. This type embodies both the data and the logic
743/// that should be additionally associated with the transaction. It should be plain old data.
744pub trait SignedExtension: Codec + Debug + Sync + Send + Clone + Eq + PartialEq {
745	/// Unique identifier of this signed extension.
746	///
747	/// This will be exposed in the metadata to identify the signed extension used
748	/// in an extrinsic.
749	const IDENTIFIER: &'static str;
750
751	/// The type which encodes the sender identity.
752	type AccountId;
753
754	/// The type which encodes the call to be dispatched.
755	type Call: Dispatchable;
756
757	/// Any additional data that will go into the signed payload. This may be created dynamically
758	/// from the transaction using the `additional_signed` function.
759	type AdditionalSigned: Encode;
760
761	/// The type that encodes information that can be passed from pre_dispatch to post-dispatch.
762	type Pre: Default;
763
764	/// Construct any additional data that should be in the signed payload of the transaction. Can
765	/// also perform any pre-signature-verification checks and return an error if needed.
766	fn additional_signed(&self) -> Result<Self::AdditionalSigned, TransactionValidityError>;
767
768	/// Validate a signed transaction for the transaction queue.
769	///
770	/// This function can be called frequently by the transaction queue,
771	/// to obtain transaction validity against current state.
772	/// It should perform all checks that determine a valid transaction,
773	/// that can pay for its execution and quickly eliminate ones
774	/// that are stale or incorrect.
775	///
776	/// Make sure to perform the same checks in `pre_dispatch` function.
777	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	/// Do any pre-flight stuff for a signed transaction.
788	///
789	/// Note this function by default delegates to `validate`, so that
790	/// all checks performed for the transaction queue are also performed during
791	/// the dispatch phase (applying the extrinsic).
792	///
793	/// If you ever override this function, you need to make sure to always
794	/// perform the same validation as in `validate`.
795	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	/// Validate an unsigned transaction for the transaction queue.
808	///
809	/// This function can be called frequently by the transaction queue
810	/// to obtain transaction validity against current state.
811	/// It should perform all checks that determine a valid unsigned transaction,
812	/// and quickly eliminate ones that are stale or incorrect.
813	///
814	/// Make sure to perform the same checks in `pre_dispatch_unsigned` function.
815	fn validate_unsigned(
816		_call: &Self::Call,
817		_info: &DispatchInfoOf<Self::Call>,
818		_len: usize,
819	) -> TransactionValidity {
820		Ok(ValidTransaction::default())
821	}
822
823	/// Do any pre-flight stuff for a unsigned transaction.
824	///
825	/// Note this function by default delegates to `validate_unsigned`, so that
826	/// all checks performed for the transaction queue are also performed during
827	/// the dispatch phase (applying the extrinsic).
828	///
829	/// If you ever override this function, you need to make sure to always
830	/// perform the same validation as in `validate_unsigned`.
831	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	/// Do any post-flight stuff for an extrinsic.
842	///
843	/// This gets given the `DispatchResult` `_result` from the extrinsic and can, if desired,
844	/// introduce a `TransactionValidityError`, causing the block to become invalid for including
845	/// it.
846	///
847	/// WARNING: It is dangerous to return an error here. To do so will fundamentally invalidate the
848	/// transaction and any block that it is included in, causing the block author to not be
849	/// compensated for their work in validating the transaction or producing the block so far.
850	///
851	/// It can only be used safely when you *know* that the extrinsic is one that can only be
852	/// introduced by the current block author; generally this implies that it is an inherent and
853	/// will come from either an offchain-worker or via `InherentData`.
854	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	/// Returns the list of unique identifier for this signed extension.
865	///
866	/// As a [`SignedExtension`] can be a tuple of [`SignedExtension`]s we need to return a `Vec`
867	/// that holds all the unique identifiers. Each individual `SignedExtension` must return
868	/// *exactly* one identifier.
869	///
870	/// This method provides a default implementation that returns `vec![SELF::IDENTIFIER]`.
871	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/// Only for bare bone testing when you don't care about signed extensions at all.
944#[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
954/// An "executable" piece of information, used by the standard Tetcore Executive in order to
955/// enact a piece of extrinsic information by marshalling and dispatching to a named function
956/// call.
957///
958/// Also provides information on to whom this information is attributable and an index that allows
959/// each piece of attributable information to be disambiguated.
960pub trait Applyable: Sized + Send + Sync {
961	/// Type by which we can dispatch. Restricts the `UnsignedValidator` type.
962	type Call: Dispatchable;
963
964	/// Checks to see if this is a valid *transaction*. It returns information on it if so.
965	fn validate<V: ValidateUnsigned<Call=Self::Call>>(
966		&self,
967		source: TransactionSource,
968		info: &DispatchInfoOf<Self::Call>,
969		len: usize,
970	) -> TransactionValidity;
971
972	/// Executes all necessary logic needed prior to dispatch and deconstructs into function call,
973	/// index and sender.
974	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
981/// A marker trait for something that knows the type of the runtime block.
982pub trait GetRuntimeBlockType {
983	/// The `RuntimeBlock` type.
984	type RuntimeBlock: self::Block;
985}
986
987/// A marker trait for something that knows the type of the node block.
988pub trait GetNodeBlockType {
989	/// The `NodeBlock` type.
990	type NodeBlock: self::Block;
991}
992
993/// Something that can validate unsigned extrinsics for the transaction pool.
994///
995/// Note that any checks done here are only used for determining the validity of
996/// the transaction for the transaction pool.
997/// During block execution phase one need to perform the same checks anyway,
998/// since this function is not being called.
999pub trait ValidateUnsigned {
1000	/// The call to validate
1001	type Call;
1002
1003	/// Validate the call right before dispatch.
1004	///
1005	/// This method should be used to prevent transactions already in the pool
1006	/// (i.e. passing `validate_unsigned`) from being included in blocks
1007	/// in case we know they now became invalid.
1008	///
1009	/// By default it's a good idea to call `validate_unsigned` from within
1010	/// this function again to make sure we never include an invalid transaction.
1011	///
1012	/// Changes made to storage WILL be persisted if the call returns `Ok`.
1013	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	/// Return the validity of the call
1020	///
1021	/// This doesn't execute any side-effects; it merely checks
1022	/// whether the transaction would panic if it were included or not.
1023	///
1024	/// Changes made to storage should be discarded by caller.
1025	fn validate_unsigned(source: TransactionSource, call: &Self::Call) -> TransactionValidity;
1026}
1027
1028/// Opaque data type that may be destructured into a series of raw byte slices (which represent
1029/// individual keys).
1030pub trait OpaqueKeys: Clone {
1031	/// Types bound to this opaque keys that provide the key type ids returned.
1032	type KeyTypeIdProviders;
1033
1034	/// Return the key-type IDs supported by this set.
1035	fn key_ids() -> &'static [crate::KeyTypeId];
1036	/// Get the raw bytes of key with key-type ID `i`.
1037	fn get_raw(&self, i: super::KeyTypeId) -> &[u8];
1038	/// Get the decoded key with key-type ID `i`.
1039	fn get<T: Decode>(&self, i: super::KeyTypeId) -> Option<T> {
1040		T::decode(&mut self.get_raw(i)).ok()
1041	}
1042	/// Verify a proof of ownership for the keys.
1043	fn ownership_proof_is_valid(&self, _proof: &[u8]) -> bool { true }
1044}
1045
1046/// Input that adds infinite number of zero after wrapped input.
1047///
1048/// This can add an infinite stream of zeros onto any input, not just a slice as with
1049/// `TrailingZerosInput`.
1050pub struct AppendZerosInput<'a, T>(&'a mut T);
1051
1052impl<'a, T> AppendZerosInput<'a, T> {
1053	/// Create a new instance from the given byte array.
1054	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			// this should never fail if `remaining_len` API is implemented correctly.
1069			self.0.read(&mut into[..readable])?;
1070			readable
1071		} else {
1072			// Fill it byte-by-byte.
1073			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		// Fill the rest with zeros.
1085		for i in &mut into[completed..] {
1086			*i = 0;
1087		}
1088		Ok(())
1089	}
1090}
1091
1092/// Input that adds infinite number of zero after wrapped input.
1093pub struct TrailingZeroInput<'a>(&'a [u8]);
1094
1095impl<'a> TrailingZeroInput<'a> {
1096	/// Create a new instance from the given byte array.
1097	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
1119/// This type can be converted into and possibly from an AccountId (which itself is generic).
1120pub trait AccountIdConversion<AccountId>: Sized {
1121	/// Convert into an account ID. This is infallible.
1122	fn into_account(&self) -> AccountId { self.into_sub_account(&()) }
1123
1124	/// Try to convert an account ID into this type. Might not succeed.
1125	fn try_from_account(a: &AccountId) -> Option<Self> {
1126		Self::try_from_sub_account::<()>(a).map(|x| x.0)
1127	}
1128
1129	/// Convert this value amalgamated with the a secondary "sub" value into an account ID. This is
1130	/// infallible.
1131	///
1132	/// NOTE: The account IDs from this and from `into_account` are *not* guaranteed to be distinct
1133	/// for any given value of `self`, nor are different invocations to this with different types
1134	/// `T`. For example, the following will all encode to the same account ID value:
1135	/// - `self.into_sub_account(0u32)`
1136	/// - `self.into_sub_account(vec![0u8; 0])`
1137	/// - `self.into_account()`
1138	fn into_sub_account<S: Encode>(&self, sub: S) -> AccountId;
1139
1140	/// Try to convert an account ID into this type. Might not succeed.
1141	fn try_from_sub_account<S: Decode>(x: &AccountId) -> Option<(Self, S)>;
1142}
1143
1144/// Format is TYPE_ID ++ encode(parachain ID) ++ 00.... where 00... is indefinite trailing zeroes to
1145/// fill AccountId.
1146impl<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/// Calls a given macro a number of times with a set of fixed params and an incrementing numeral.
1168/// e.g.
1169/// ```nocompile
1170/// count!(println ("{}",) foo, bar, baz);
1171/// // Will result in three `println!`s: "0", "1" and "2".
1172/// ```
1173#[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/// Implement `OpaqueKeys` for a described struct.
1188///
1189/// Every field type must implement [`BoundToRuntimeAppPublic`](crate::BoundToRuntimeAppPublic).
1190/// `KeyTypeIdProviders` is set to the types given as fields.
1191///
1192/// ```rust
1193/// use tp_runtime::{
1194/// 	impl_opaque_keys, KeyTypeId, BoundToRuntimeAppPublic, app_crypto::{sr25519, ed25519}
1195/// };
1196///
1197/// pub struct KeyModule;
1198/// impl BoundToRuntimeAppPublic for KeyModule { type Public = ed25519::AppPublic; }
1199///
1200/// pub struct KeyModule2;
1201/// impl BoundToRuntimeAppPublic for KeyModule2 { type Public = sr25519::AppPublic; }
1202///
1203/// impl_opaque_keys! {
1204/// 	pub struct Keys {
1205/// 		pub key_module: KeyModule,
1206/// 		pub key_module2: KeyModule2,
1207/// 	}
1208/// }
1209/// ```
1210#[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			/// Generate a set of keys with optionally using the given seed.
1238			///
1239			/// The generated key pairs are stored in the keystore.
1240			///
1241			/// Returns the concatenated SCALE encoded public keys.
1242			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			/// Converts `Self` into a `Vec` of `(raw public key, KeyTypeId)`.
1256			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			/// Decode `Self` from the given `encoded` slice and convert `Self` into the raw public
1275			/// keys (see [`Self::into_raw_public_keys`]).
1276			///
1277			/// Returns `None` when the decoding failed, otherwise `Some(_)`.
1278			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
1319/// Trait for things which can be printed from the runtime.
1320pub trait Printable {
1321	/// Print the object.
1322	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/// Something that can convert a [`BlockId`](crate::generic::BlockId) to a number or a hash.
1391#[cfg(feature = "std")]
1392pub trait BlockIdTo<Block: self::Block> {
1393	/// The error type that will be returned by the functions.
1394	type Error: std::fmt::Debug;
1395
1396	/// Convert the given `block_id` to the corresponding block hash.
1397	fn to_hash(
1398		&self,
1399		block_id: &crate::generic::BlockId<Block>,
1400	) -> Result<Option<Block::Hash>, Self::Error>;
1401
1402	/// Convert the given `block_id` to the corresponding block number.
1403	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	// cafef00d
1436
1437	#[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	// f00dcafe
1443
1444	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}