1
// This file is part of Substrate.
2

            
3
// Copyright (C) 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

            
20
use crate::{
21
	generic::Digest,
22
	scale_info::{MetaType, StaticTypeInfo, TypeInfo},
23
	transaction_validity::{
24
		TransactionSource, TransactionValidity, TransactionValidityError, UnknownTransaction,
25
		ValidTransaction,
26
	},
27
	DispatchResult,
28
};
29
use alloc::vec::Vec;
30
use codec::{Codec, Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen};
31
#[doc(hidden)]
32
pub use core::{fmt::Debug, marker::PhantomData};
33
use impl_trait_for_tuples::impl_for_tuples;
34
#[cfg(feature = "serde")]
35
use serde::{de::DeserializeOwned, Deserialize, Serialize};
36
use sp_application_crypto::AppCrypto;
37
pub use sp_arithmetic::traits::{
38
	checked_pow, ensure_pow, AtLeast32Bit, AtLeast32BitUnsigned, Bounded, CheckedAdd, CheckedDiv,
39
	CheckedMul, CheckedShl, CheckedShr, CheckedSub, Ensure, EnsureAdd, EnsureAddAssign, EnsureDiv,
40
	EnsureDivAssign, EnsureFixedPointNumber, EnsureFrom, EnsureInto, EnsureMul, EnsureMulAssign,
41
	EnsureOp, EnsureOpAssign, EnsureSub, EnsureSubAssign, IntegerSquareRoot, One,
42
	SaturatedConversion, Saturating, UniqueSaturatedFrom, UniqueSaturatedInto, Zero,
43
};
44
use sp_core::{self, storage::StateVersion, Hasher, RuntimeDebug, TypeId, U256};
45
#[doc(hidden)]
46
pub use sp_core::{
47
	parameter_types, ConstBool, ConstI128, ConstI16, ConstI32, ConstI64, ConstI8, ConstU128,
48
	ConstU16, ConstU32, ConstU64, ConstU8, Get, GetDefault, TryCollect, TypedGet,
49
};
50
#[cfg(feature = "std")]
51
use std::fmt::Display;
52
#[cfg(feature = "std")]
53
use std::str::FromStr;
54

            
55
/// A lazy value.
56
pub trait Lazy<T: ?Sized> {
57
	/// Get a reference to the underlying value.
58
	///
59
	/// This will compute the value if the function is invoked for the first time.
60
	fn get(&mut self) -> &T;
61
}
62

            
63
impl<'a> Lazy<[u8]> for &'a [u8] {
64
	fn get(&mut self) -> &[u8] {
65
		self
66
	}
67
}
68

            
69
/// Some type that is able to be collapsed into an account ID. It is not possible to recreate the
70
/// original value from the account ID.
71
pub trait IdentifyAccount {
72
	/// The account ID that this can be transformed into.
73
	type AccountId;
74
	/// Transform into an account.
75
	fn into_account(self) -> Self::AccountId;
76
}
77

            
78
impl IdentifyAccount for sp_core::ed25519::Public {
79
	type AccountId = Self;
80
	fn into_account(self) -> Self {
81
		self
82
	}
83
}
84

            
85
impl IdentifyAccount for sp_core::sr25519::Public {
86
	type AccountId = Self;
87
	fn into_account(self) -> Self {
88
		self
89
	}
90
}
91

            
92
impl IdentifyAccount for sp_core::ecdsa::Public {
93
	type AccountId = Self;
94
	fn into_account(self) -> Self {
95
		self
96
	}
97
}
98

            
99
/// Means of signature verification.
100
pub trait Verify {
101
	/// Type of the signer.
102
	type Signer: IdentifyAccount;
103
	/// Verify a signature.
104
	///
105
	/// Return `true` if signature is valid for the value.
106
	fn verify<L: Lazy<[u8]>>(
107
		&self,
108
		msg: L,
109
		signer: &<Self::Signer as IdentifyAccount>::AccountId,
110
	) -> bool;
111
}
112

            
113
impl Verify for sp_core::ed25519::Signature {
114
	type Signer = sp_core::ed25519::Public;
115

            
116
	fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &sp_core::ed25519::Public) -> bool {
117
		sp_io::crypto::ed25519_verify(self, msg.get(), signer)
118
	}
119
}
120

            
121
impl Verify for sp_core::sr25519::Signature {
122
	type Signer = sp_core::sr25519::Public;
123

            
124
	fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &sp_core::sr25519::Public) -> bool {
125
		sp_io::crypto::sr25519_verify(self, msg.get(), signer)
126
	}
127
}
128

            
129
impl Verify for sp_core::ecdsa::Signature {
130
	type Signer = sp_core::ecdsa::Public;
131
	fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &sp_core::ecdsa::Public) -> bool {
132
		match sp_io::crypto::secp256k1_ecdsa_recover_compressed(
133
			self.as_ref(),
134
			&sp_io::hashing::blake2_256(msg.get()),
135
		) {
136
			Ok(pubkey) => signer.0 == pubkey,
137
			_ => false,
138
		}
139
	}
140
}
141

            
142
/// Means of signature verification of an application key.
143
pub trait AppVerify {
144
	/// Type of the signer.
145
	type AccountId;
146
	/// Verify a signature. Return `true` if signature is valid for the value.
147
	fn verify<L: Lazy<[u8]>>(&self, msg: L, signer: &Self::AccountId) -> bool;
148
}
149

            
150
impl<
151
		S: Verify<Signer = <<T as AppCrypto>::Public as sp_application_crypto::AppPublic>::Generic>
152
			+ From<T>,
153
		T: sp_application_crypto::Wraps<Inner = S>
154
			+ sp_application_crypto::AppCrypto
155
			+ sp_application_crypto::AppSignature
156
			+ AsRef<S>
157
			+ AsMut<S>
158
			+ From<S>,
159
	> AppVerify for T
160
where
161
	<S as Verify>::Signer: IdentifyAccount<AccountId = <S as Verify>::Signer>,
162
	<<T as AppCrypto>::Public as sp_application_crypto::AppPublic>::Generic: IdentifyAccount<
163
		AccountId = <<T as AppCrypto>::Public as sp_application_crypto::AppPublic>::Generic,
164
	>,
165
{
166
	type AccountId = <T as AppCrypto>::Public;
167
	fn verify<L: Lazy<[u8]>>(&self, msg: L, signer: &<T as AppCrypto>::Public) -> bool {
168
		use sp_application_crypto::IsWrappedBy;
169
		let inner: &S = self.as_ref();
170
		let inner_pubkey =
171
			<<T as AppCrypto>::Public as sp_application_crypto::AppPublic>::Generic::from_ref(
172
				signer,
173
			);
174
		Verify::verify(inner, msg, inner_pubkey)
175
	}
176
}
177

            
178
/// An error type that indicates that the origin is invalid.
179
#[derive(Encode, Decode, RuntimeDebug)]
180
pub struct BadOrigin;
181

            
182
impl From<BadOrigin> for &'static str {
183
	fn from(_: BadOrigin) -> &'static str {
184
		"Bad origin"
185
	}
186
}
187

            
188
/// An error that indicates that a lookup failed.
189
#[derive(Encode, Decode, RuntimeDebug)]
190
pub struct LookupError;
191

            
192
impl From<LookupError> for &'static str {
193
	fn from(_: LookupError) -> &'static str {
194
		"Can not lookup"
195
	}
196
}
197

            
198
impl From<LookupError> for TransactionValidityError {
199
	fn from(_: LookupError) -> Self {
200
		UnknownTransaction::CannotLookup.into()
201
	}
202
}
203

            
204
/// Means of changing one type into another in a manner dependent on the source type.
205
pub trait Lookup {
206
	/// Type to lookup from.
207
	type Source;
208
	/// Type to lookup into.
209
	type Target;
210
	/// Attempt a lookup.
211
	fn lookup(&self, s: Self::Source) -> Result<Self::Target, LookupError>;
212
}
213

            
214
/// Means of changing one type into another in a manner dependent on the source type.
215
/// This variant is different to `Lookup` in that it doesn't (can cannot) require any
216
/// context.
217
pub trait StaticLookup {
218
	/// Type to lookup from.
219
	type Source: Codec + Clone + PartialEq + Debug + TypeInfo;
220
	/// Type to lookup into.
221
	type Target;
222
	/// Attempt a lookup.
223
	fn lookup(s: Self::Source) -> Result<Self::Target, LookupError>;
224
	/// Convert from Target back to Source.
225
	fn unlookup(t: Self::Target) -> Self::Source;
226
}
227

            
228
/// A lookup implementation returning the input value.
229
#[derive(Default, Clone, Copy, PartialEq, Eq)]
230
pub struct IdentityLookup<T>(PhantomData<T>);
231
impl<T: Codec + Clone + PartialEq + Debug + TypeInfo> StaticLookup for IdentityLookup<T> {
232
	type Source = T;
233
	type Target = T;
234
	fn lookup(x: T) -> Result<T, LookupError> {
235
		Ok(x)
236
	}
237
	fn unlookup(x: T) -> T {
238
		x
239
	}
240
}
241

            
242
impl<T> Lookup for IdentityLookup<T> {
243
	type Source = T;
244
	type Target = T;
245
	fn lookup(&self, x: T) -> Result<T, LookupError> {
246
		Ok(x)
247
	}
248
}
249

            
250
/// A lookup implementation returning the `AccountId` from a `MultiAddress`.
251
pub struct AccountIdLookup<AccountId, AccountIndex>(PhantomData<(AccountId, AccountIndex)>);
252
impl<AccountId, AccountIndex> StaticLookup for AccountIdLookup<AccountId, AccountIndex>
253
where
254
	AccountId: Codec + Clone + PartialEq + Debug,
255
	AccountIndex: Codec + Clone + PartialEq + Debug,
256
	crate::MultiAddress<AccountId, AccountIndex>: Codec + StaticTypeInfo,
257
{
258
	type Source = crate::MultiAddress<AccountId, AccountIndex>;
259
	type Target = AccountId;
260
12777
	fn lookup(x: Self::Source) -> Result<Self::Target, LookupError> {
261
12777
		match x {
262
9375
			crate::MultiAddress::Id(i) => Ok(i),
263
3402
			_ => Err(LookupError),
264
		}
265
12777
	}
266
	fn unlookup(x: Self::Target) -> Self::Source {
267
		crate::MultiAddress::Id(x)
268
	}
269
}
270

            
271
/// Perform a StaticLookup where there are multiple lookup sources of the same type.
272
impl<A, B> StaticLookup for (A, B)
273
where
274
	A: StaticLookup,
275
	B: StaticLookup<Source = A::Source, Target = A::Target>,
276
{
277
	type Source = A::Source;
278
	type Target = A::Target;
279

            
280
	fn lookup(x: Self::Source) -> Result<Self::Target, LookupError> {
281
		A::lookup(x.clone()).or_else(|_| B::lookup(x))
282
	}
283
	fn unlookup(x: Self::Target) -> Self::Source {
284
		A::unlookup(x)
285
	}
286
}
287

            
288
/// Extensible conversion trait. Generic over only source type, with destination type being
289
/// associated.
290
pub trait Morph<A> {
291
	/// The type into which `A` is mutated.
292
	type Outcome;
293

            
294
	/// Make conversion.
295
	fn morph(a: A) -> Self::Outcome;
296
}
297

            
298
/// A structure that performs identity conversion.
299
impl<T> Morph<T> for Identity {
300
	type Outcome = T;
301
	fn morph(a: T) -> T {
302
		a
303
	}
304
}
305

            
306
/// Extensible conversion trait. Generic over only source type, with destination type being
307
/// associated.
308
pub trait TryMorph<A> {
309
	/// The type into which `A` is mutated.
310
	type Outcome;
311

            
312
	/// Make conversion.
313
	fn try_morph(a: A) -> Result<Self::Outcome, ()>;
314
}
315

            
316
/// A structure that performs identity conversion.
317
impl<T> TryMorph<T> for Identity {
318
	type Outcome = T;
319
	fn try_morph(a: T) -> Result<T, ()> {
320
		Ok(a)
321
	}
322
}
323

            
324
/// Implementation of `Morph` which converts between types using `Into`.
325
pub struct MorphInto<T>(core::marker::PhantomData<T>);
326
impl<T, A: Into<T>> Morph<A> for MorphInto<T> {
327
	type Outcome = T;
328
	fn morph(a: A) -> T {
329
		a.into()
330
	}
331
}
332

            
333
/// Implementation of `TryMorph` which attempts to convert between types using `TryInto`.
334
pub struct TryMorphInto<T>(core::marker::PhantomData<T>);
335
impl<T, A: TryInto<T>> TryMorph<A> for TryMorphInto<T> {
336
	type Outcome = T;
337
	fn try_morph(a: A) -> Result<T, ()> {
338
		a.try_into().map_err(|_| ())
339
	}
340
}
341

            
342
/// Implementation of `Morph` to retrieve just the first element of a tuple.
343
pub struct TakeFirst;
344
impl<T1> Morph<(T1,)> for TakeFirst {
345
	type Outcome = T1;
346
	fn morph(a: (T1,)) -> T1 {
347
		a.0
348
	}
349
}
350
impl<T1, T2> Morph<(T1, T2)> for TakeFirst {
351
	type Outcome = T1;
352
	fn morph(a: (T1, T2)) -> T1 {
353
		a.0
354
	}
355
}
356
impl<T1, T2, T3> Morph<(T1, T2, T3)> for TakeFirst {
357
	type Outcome = T1;
358
	fn morph(a: (T1, T2, T3)) -> T1 {
359
		a.0
360
	}
361
}
362
impl<T1, T2, T3, T4> Morph<(T1, T2, T3, T4)> for TakeFirst {
363
	type Outcome = T1;
364
	fn morph(a: (T1, T2, T3, T4)) -> T1 {
365
		a.0
366
	}
367
}
368

            
369
/// Create a `Morph` and/or `TryMorph` impls with a simple closure-like expression.
370
///
371
/// # Examples
372
///
373
/// ```
374
/// # use sp_runtime::{morph_types, traits::{Morph, TryMorph, TypedGet, ConstU32}};
375
/// # use sp_arithmetic::traits::CheckedSub;
376
///
377
/// morph_types! {
378
///    /// Replace by some other value; produce both `Morph` and `TryMorph` implementations
379
///    pub type Replace<V: TypedGet> = |_| -> V::Type { V::get() };
380
///    /// A private `Morph` implementation to reduce a `u32` by 10.
381
///    type ReduceU32ByTen: Morph = |r: u32| -> u32 { r - 10 };
382
///    /// A `TryMorph` implementation to reduce a scalar by a particular amount, checking for
383
///    /// underflow.
384
///    pub type CheckedReduceBy<N: TypedGet>: TryMorph = |r: N::Type| -> Result<N::Type, ()> {
385
///        r.checked_sub(&N::get()).ok_or(())
386
///    } where N::Type: CheckedSub;
387
/// }
388
///
389
/// trait Config {
390
///    type TestMorph1: Morph<u32>;
391
///    type TestTryMorph1: TryMorph<u32>;
392
///    type TestMorph2: Morph<u32>;
393
///    type TestTryMorph2: TryMorph<u32>;
394
/// }
395
///
396
/// struct Runtime;
397
/// impl Config for Runtime {
398
///    type TestMorph1 = Replace<ConstU32<42>>;
399
///    type TestTryMorph1 = Replace<ConstU32<42>>;
400
///    type TestMorph2 = ReduceU32ByTen;
401
///    type TestTryMorph2 = CheckedReduceBy<ConstU32<10>>;
402
/// }
403
/// ```
404
#[macro_export]
405
macro_rules! morph_types {
406
	(
407
		@DECL $( #[doc = $doc:expr] )* $vq:vis $name:ident ()
408
	) => {
409
		$( #[doc = $doc] )* $vq struct $name;
410
	};
411
	(
412
		@DECL $( #[doc = $doc:expr] )* $vq:vis $name:ident ( $( $bound_id:ident ),+ )
413
	) => {
414
		$( #[doc = $doc] )*
415
		$vq struct $name < $($bound_id,)* > ( $crate::traits::PhantomData< ( $($bound_id,)* ) > ) ;
416
	};
417
	(
418
		@IMPL $name:ty : ( $( $bounds:tt )* ) ( $( $where:tt )* )
419
		= |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
420
	) => {
421
		impl<$($bounds)*> $crate::traits::Morph<$var_type> for $name $( $where )? {
422
			type Outcome = $outcome;
423
			fn morph($var: $var_type) -> Self::Outcome { $( $ex )* }
424
		}
425
	};
426
	(
427
		@IMPL_TRY $name:ty : ( $( $bounds:tt )* ) ( $( $where:tt )* )
428
		= |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
429
	) => {
430
		impl<$($bounds)*> $crate::traits::TryMorph<$var_type> for $name $( $where )? {
431
			type Outcome = $outcome;
432
			fn try_morph($var: $var_type) -> Result<Self::Outcome, ()> { $( $ex )* }
433
		}
434
	};
435
	(
436
		@IMPL $name:ty : () ( $( $where:tt )* )
437
		= |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
438
	) => {
439
		impl $crate::traits::Morph<$var_type> for $name $( $where )? {
440
			type Outcome = $outcome;
441
			fn morph($var: $var_type) -> Self::Outcome { $( $ex )* }
442
		}
443
	};
444
	(
445
		@IMPL_TRY $name:ty : () ( $( $where:tt )* )
446
		= |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
447
	) => {
448
		impl $crate::traits::TryMorph<$var_type> for $name $( $where )? {
449
			type Outcome = $outcome;
450
			fn try_morph($var: $var_type) -> Result<Self::Outcome, ()> { $( $ex )* }
451
		}
452
	};
453
	(
454
		@IMPL_BOTH $name:ty : ( $( $bounds:tt )* ) ( $( $where:tt )* )
455
		= |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
456
	) => {
457
		morph_types! {
458
			@IMPL $name : ($($bounds)*) ($($where)*)
459
			= |$var: $var_type| -> $outcome { $( $ex )* }
460
		}
461
		morph_types! {
462
			@IMPL_TRY $name : ($($bounds)*) ($($where)*)
463
			= |$var: $var_type| -> $outcome { Ok({$( $ex )*}) }
464
		}
465
	};
466

            
467
	(
468
		$( #[doc = $doc:expr] )* $vq:vis type $name:ident
469
		$( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
470
		$(: $type:tt)?
471
		= |_| -> $outcome:ty { $( $ex:expr )* };
472
		$( $rest:tt )*
473
	) => {
474
		morph_types! {
475
			$( #[doc = $doc] )* $vq type $name
476
			$( < $( $bound_id $( : $bound_head $( | $bound_tail )* )? ),+ > )?
477
			EXTRA_GENERIC(X)
478
			$(: $type)?
479
			= |_x: X| -> $outcome { $( $ex )* };
480
			$( $rest )*
481
		}
482
	};
483
	(
484
		$( #[doc = $doc:expr] )* $vq:vis type $name:ident
485
		$( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
486
		$( EXTRA_GENERIC ($extra:ident) )?
487
		= |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
488
		$( where $( $where_path:ty : $where_bound_head:path $( | $where_bound_tail:path )* ),* )?;
489
		$( $rest:tt )*
490
	) => {
491
		morph_types! { @DECL $( #[doc = $doc] )* $vq $name ( $( $( $bound_id ),+ )? ) }
492
		morph_types! {
493
			@IMPL_BOTH $name $( < $( $bound_id ),* > )? :
494
			( $( $( $bound_id $( : $bound_head $( + $bound_tail )* )? , )+ )? $( $extra )? )
495
			( $( where $( $where_path : $where_bound_head $( + $where_bound_tail )* ),* )? )
496
			= |$var: $var_type| -> $outcome { $( $ex )* }
497
		}
498
		morph_types!{ $($rest)* }
499
	};
500
	(
501
		$( #[doc = $doc:expr] )* $vq:vis type $name:ident
502
		$( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
503
		$( EXTRA_GENERIC ($extra:ident) )?
504
		: Morph
505
		= |$var:ident: $var_type:ty| -> $outcome:ty { $( $ex:expr )* }
506
		$( where $( $where_path:ty : $where_bound_head:path $( | $where_bound_tail:path )* ),* )?;
507
		$( $rest:tt )*
508
	) => {
509
		morph_types! { @DECL $( #[doc = $doc] )* $vq $name ( $( $( $bound_id ),+ )? ) }
510
		morph_types! {
511
			@IMPL $name $( < $( $bound_id ),* > )? :
512
			( $( $( $bound_id $( : $bound_head $( + $bound_tail )* )? , )+ )? $( $extra )? )
513
			( $( where $( $where_path : $where_bound_head $( + $where_bound_tail )* ),* )? )
514
			= |$var: $var_type| -> $outcome { $( $ex )* }
515
		}
516
		morph_types!{ $($rest)* }
517
	};
518
	(
519
		$( #[doc = $doc:expr] )* $vq:vis type $name:ident
520
		$( < $( $bound_id:ident $( : $bound_head:path $( | $bound_tail:path )* )? ),+ > )?
521
		$( EXTRA_GENERIC ($extra:ident) )?
522
		: TryMorph
523
		= |$var:ident: $var_type:ty| -> Result<$outcome:ty, ()> { $( $ex:expr )* }
524
		$( where $( $where_path:ty : $where_bound_head:path $( | $where_bound_tail:path )* ),* )?;
525
		$( $rest:tt )*
526
	) => {
527
		morph_types! { @DECL $( #[doc = $doc] )* $vq $name ( $( $( $bound_id ),+ )? ) }
528
		morph_types! {
529
			@IMPL_TRY $name $( < $( $bound_id ),* > )? :
530
			( $( $( $bound_id $( : $bound_head $( + $bound_tail )* )? , )+ )? $( $extra )? )
531
			( $( where $( $where_path : $where_bound_head $( + $where_bound_tail )* ),* )? )
532
			= |$var: $var_type| -> $outcome { $( $ex )* }
533
		}
534
		morph_types!{ $($rest)* }
535
	};
536
	() => {}
537
}
538

            
539
morph_types! {
540
	/// Morpher to disregard the source value and replace with another.
541
	pub type Replace<V: TypedGet> = |_| -> V::Type { V::get() };
542

            
543
	/// Morpher to disregard the source value and replace with the default of `V`.
544
	pub type ReplaceWithDefault<V: Default> = |_| -> V { Default::default() };
545

            
546
	/// Mutator which reduces a scalar by a particular amount.
547
	pub type ReduceBy<N: TypedGet> = |r: N::Type| -> N::Type {
548
		r.checked_sub(&N::get()).unwrap_or(Zero::zero())
549
	} where N::Type: CheckedSub | Zero;
550

            
551
	/// A `TryMorph` implementation to reduce a scalar by a particular amount, checking for
552
	/// underflow.
553
	pub type CheckedReduceBy<N: TypedGet>: TryMorph = |r: N::Type| -> Result<N::Type, ()> {
554
		r.checked_sub(&N::get()).ok_or(())
555
	} where N::Type: CheckedSub;
556

            
557
	/// A `TryMorph` implementation to enforce an upper limit for a result of the outer morphed type.
558
	pub type MorphWithUpperLimit<L: TypedGet, M>: TryMorph = |r: L::Type| -> Result<L::Type, ()> {
559
		M::try_morph(r).map(|m| m.min(L::get()))
560
	} where L::Type: Ord, M: TryMorph<L::Type, Outcome = L::Type>;
561
}
562

            
563
/// Infallible conversion trait. Generic over both source and destination types.
564
pub trait Convert<A, B> {
565
	/// Make conversion.
566
	fn convert(a: A) -> B;
567
}
568

            
569
impl<A, B: Default> Convert<A, B> for () {
570
	fn convert(_: A) -> B {
571
		Default::default()
572
	}
573
}
574

            
575
/// Reversing infallible conversion trait. Generic over both source and destination types.
576
///
577
/// This specifically reverses the conversion.
578
pub trait ConvertBack<A, B>: Convert<A, B> {
579
	/// Make conversion back.
580
	fn convert_back(b: B) -> A;
581
}
582

            
583
/// Fallible conversion trait returning an [Option]. Generic over both source and destination types.
584
pub trait MaybeConvert<A, B> {
585
	/// Attempt to make conversion.
586
	fn maybe_convert(a: A) -> Option<B>;
587
}
588

            
589
#[impl_trait_for_tuples::impl_for_tuples(30)]
590
impl<A: Clone, B> MaybeConvert<A, B> for Tuple {
591
	fn maybe_convert(a: A) -> Option<B> {
592
		for_tuples!( #(
593
			match Tuple::maybe_convert(a.clone()) {
594
				Some(b) => return Some(b),
595
				None => {},
596
			}
597
		)* );
598
		None
599
	}
600
}
601

            
602
/// Reversing fallible conversion trait returning an [Option]. Generic over both source and
603
/// destination types.
604
pub trait MaybeConvertBack<A, B>: MaybeConvert<A, B> {
605
	/// Attempt to make conversion back.
606
	fn maybe_convert_back(b: B) -> Option<A>;
607
}
608

            
609
#[impl_trait_for_tuples::impl_for_tuples(30)]
610
impl<A: Clone, B: Clone> MaybeConvertBack<A, B> for Tuple {
611
	fn maybe_convert_back(b: B) -> Option<A> {
612
		for_tuples!( #(
613
			match Tuple::maybe_convert_back(b.clone()) {
614
				Some(a) => return Some(a),
615
				None => {},
616
			}
617
		)* );
618
		None
619
	}
620
}
621

            
622
/// Fallible conversion trait which returns the argument in the case of being unable to convert.
623
/// Generic over both source and destination types.
624
pub trait TryConvert<A, B> {
625
	/// Attempt to make conversion. If returning [Result::Err], the inner must always be `a`.
626
	fn try_convert(a: A) -> Result<B, A>;
627
}
628

            
629
#[impl_trait_for_tuples::impl_for_tuples(30)]
630
impl<A, B> TryConvert<A, B> for Tuple {
631
25392
	fn try_convert(a: A) -> Result<B, A> {
632
		for_tuples!( #(
633
25392
			let a = match Tuple::try_convert(a) {
634
25392
				Ok(b) => return Ok(b),
635
				Err(a) => a,
636
			};
637
		)* );
638
		Err(a)
639
25392
	}
640
}
641

            
642
/// Reversing fallible conversion trait which returns the argument in the case of being unable to
643
/// convert back. Generic over both source and destination types.
644
pub trait TryConvertBack<A, B>: TryConvert<A, B> {
645
	/// Attempt to make conversion back. If returning [Result::Err], the inner must always be `b`.
646

            
647
	fn try_convert_back(b: B) -> Result<A, B>;
648
}
649

            
650
#[impl_trait_for_tuples::impl_for_tuples(30)]
651
impl<A, B> TryConvertBack<A, B> for Tuple {
652
	fn try_convert_back(b: B) -> Result<A, B> {
653
		for_tuples!( #(
654
			let b = match Tuple::try_convert_back(b) {
655
				Ok(a) => return Ok(a),
656
				Err(b) => b,
657
			};
658
		)* );
659
		Err(b)
660
	}
661
}
662

            
663
/// Definition for a bi-directional, fallible conversion between two types.
664
pub trait MaybeEquivalence<A, B> {
665
	/// Attempt to convert reference of `A` into value of `B`, returning `None` if not possible.
666
	fn convert(a: &A) -> Option<B>;
667
	/// Attempt to convert reference of `B` into value of `A`, returning `None` if not possible.
668
	fn convert_back(b: &B) -> Option<A>;
669
}
670

            
671
#[impl_trait_for_tuples::impl_for_tuples(30)]
672
impl<A, B> MaybeEquivalence<A, B> for Tuple {
673
	fn convert(a: &A) -> Option<B> {
674
		for_tuples!( #(
675
			match Tuple::convert(a) {
676
				Some(b) => return Some(b),
677
				None => {},
678
			}
679
		)* );
680
		None
681
	}
682
	fn convert_back(b: &B) -> Option<A> {
683
		for_tuples!( #(
684
			match Tuple::convert_back(b) {
685
				Some(a) => return Some(a),
686
				None => {},
687
			}
688
		)* );
689
		None
690
	}
691
}
692

            
693
/// Adapter which turns a [Get] implementation into a [Convert] implementation which always returns
694
/// in the same value no matter the input.
695
pub struct ConvertToValue<T>(core::marker::PhantomData<T>);
696
impl<X, Y, T: Get<Y>> Convert<X, Y> for ConvertToValue<T> {
697
	fn convert(_: X) -> Y {
698
		T::get()
699
	}
700
}
701
impl<X, Y, T: Get<Y>> MaybeConvert<X, Y> for ConvertToValue<T> {
702
	fn maybe_convert(_: X) -> Option<Y> {
703
		Some(T::get())
704
	}
705
}
706
impl<X, Y, T: Get<Y>> MaybeConvertBack<X, Y> for ConvertToValue<T> {
707
	fn maybe_convert_back(_: Y) -> Option<X> {
708
		None
709
	}
710
}
711
impl<X, Y, T: Get<Y>> TryConvert<X, Y> for ConvertToValue<T> {
712
	fn try_convert(_: X) -> Result<Y, X> {
713
		Ok(T::get())
714
	}
715
}
716
impl<X, Y, T: Get<Y>> TryConvertBack<X, Y> for ConvertToValue<T> {
717
	fn try_convert_back(y: Y) -> Result<X, Y> {
718
		Err(y)
719
	}
720
}
721
impl<X, Y, T: Get<Y>> MaybeEquivalence<X, Y> for ConvertToValue<T> {
722
	fn convert(_: &X) -> Option<Y> {
723
		Some(T::get())
724
	}
725
	fn convert_back(_: &Y) -> Option<X> {
726
		None
727
	}
728
}
729

            
730
/// A structure that performs identity conversion.
731
pub struct Identity;
732
impl<T> Convert<T, T> for Identity {
733
	fn convert(a: T) -> T {
734
		a
735
	}
736
}
737
impl<T> ConvertBack<T, T> for Identity {
738
	fn convert_back(a: T) -> T {
739
		a
740
	}
741
}
742
impl<T> MaybeConvert<T, T> for Identity {
743
	fn maybe_convert(a: T) -> Option<T> {
744
		Some(a)
745
	}
746
}
747
impl<T> MaybeConvertBack<T, T> for Identity {
748
	fn maybe_convert_back(a: T) -> Option<T> {
749
		Some(a)
750
	}
751
}
752
impl<T> TryConvert<T, T> for Identity {
753
	fn try_convert(a: T) -> Result<T, T> {
754
		Ok(a)
755
	}
756
}
757
impl<T> TryConvertBack<T, T> for Identity {
758
	fn try_convert_back(a: T) -> Result<T, T> {
759
		Ok(a)
760
	}
761
}
762
impl<T: Clone> MaybeEquivalence<T, T> for Identity {
763
	fn convert(a: &T) -> Option<T> {
764
		Some(a.clone())
765
	}
766
	fn convert_back(a: &T) -> Option<T> {
767
		Some(a.clone())
768
	}
769
}
770

            
771
/// A structure that performs standard conversion using the standard Rust conversion traits.
772
pub struct ConvertInto;
773
impl<A: Into<B>, B> Convert<A, B> for ConvertInto {
774
	fn convert(a: A) -> B {
775
		a.into()
776
	}
777
}
778
impl<A: Into<B>, B> MaybeConvert<A, B> for ConvertInto {
779
	fn maybe_convert(a: A) -> Option<B> {
780
		Some(a.into())
781
	}
782
}
783
impl<A: Into<B>, B: Into<A>> MaybeConvertBack<A, B> for ConvertInto {
784
	fn maybe_convert_back(b: B) -> Option<A> {
785
		Some(b.into())
786
	}
787
}
788
impl<A: Into<B>, B> TryConvert<A, B> for ConvertInto {
789
	fn try_convert(a: A) -> Result<B, A> {
790
		Ok(a.into())
791
	}
792
}
793
impl<A: Into<B>, B: Into<A>> TryConvertBack<A, B> for ConvertInto {
794
	fn try_convert_back(b: B) -> Result<A, B> {
795
		Ok(b.into())
796
	}
797
}
798
impl<A: Clone + Into<B>, B: Clone + Into<A>> MaybeEquivalence<A, B> for ConvertInto {
799
	fn convert(a: &A) -> Option<B> {
800
		Some(a.clone().into())
801
	}
802
	fn convert_back(b: &B) -> Option<A> {
803
		Some(b.clone().into())
804
	}
805
}
806

            
807
/// A structure that performs standard conversion using the standard Rust conversion traits.
808
pub struct TryConvertInto;
809
impl<A: Clone + TryInto<B>, B> MaybeConvert<A, B> for TryConvertInto {
810
	fn maybe_convert(a: A) -> Option<B> {
811
		a.clone().try_into().ok()
812
	}
813
}
814
impl<A: Clone + TryInto<B>, B: Clone + TryInto<A>> MaybeConvertBack<A, B> for TryConvertInto {
815
	fn maybe_convert_back(b: B) -> Option<A> {
816
		b.clone().try_into().ok()
817
	}
818
}
819
impl<A: Clone + TryInto<B>, B> TryConvert<A, B> for TryConvertInto {
820
	fn try_convert(a: A) -> Result<B, A> {
821
		a.clone().try_into().map_err(|_| a)
822
	}
823
}
824
impl<A: Clone + TryInto<B>, B: Clone + TryInto<A>> TryConvertBack<A, B> for TryConvertInto {
825
	fn try_convert_back(b: B) -> Result<A, B> {
826
		b.clone().try_into().map_err(|_| b)
827
	}
828
}
829
impl<A: Clone + TryInto<B>, B: Clone + TryInto<A>> MaybeEquivalence<A, B> for TryConvertInto {
830
	fn convert(a: &A) -> Option<B> {
831
		a.clone().try_into().ok()
832
	}
833
	fn convert_back(b: &B) -> Option<A> {
834
		b.clone().try_into().ok()
835
	}
836
}
837

            
838
/// Convenience type to work around the highly unergonomic syntax needed
839
/// to invoke the functions of overloaded generic traits, in this case
840
/// `TryFrom` and `TryInto`.
841
pub trait CheckedConversion {
842
	/// Convert from a value of `T` into an equivalent instance of `Option<Self>`.
843
	///
844
	/// This just uses `TryFrom` internally but with this
845
	/// variant you can provide the destination type using turbofish syntax
846
	/// in case Rust happens not to assume the correct type.
847
	fn checked_from<T>(t: T) -> Option<Self>
848
	where
849
		Self: TryFrom<T>,
850
	{
851
		<Self as TryFrom<T>>::try_from(t).ok()
852
	}
853
	/// Consume self to return `Some` equivalent value of `Option<T>`.
854
	///
855
	/// This just uses `TryInto` internally but with this
856
	/// variant you can provide the destination type using turbofish syntax
857
	/// in case Rust happens not to assume the correct type.
858
	fn checked_into<T>(self) -> Option<T>
859
	where
860
		Self: TryInto<T>,
861
	{
862
		<Self as TryInto<T>>::try_into(self).ok()
863
	}
864
}
865
impl<T: Sized> CheckedConversion for T {}
866

            
867
/// Multiply and divide by a number that isn't necessarily the same type. Basically just the same
868
/// as `Mul` and `Div` except it can be used for all basic numeric types.
869
pub trait Scale<Other> {
870
	/// The output type of the product of `self` and `Other`.
871
	type Output;
872

            
873
	/// @return the product of `self` and `other`.
874
	fn mul(self, other: Other) -> Self::Output;
875

            
876
	/// @return the integer division of `self` and `other`.
877
	fn div(self, other: Other) -> Self::Output;
878

            
879
	/// @return the modulo remainder of `self` and `other`.
880
	fn rem(self, other: Other) -> Self::Output;
881
}
882
macro_rules! impl_scale {
883
	($self:ty, $other:ty) => {
884
		impl Scale<$other> for $self {
885
			type Output = Self;
886
			fn mul(self, other: $other) -> Self::Output {
887
				self * (other as Self)
888
			}
889
			fn div(self, other: $other) -> Self::Output {
890
				self / (other as Self)
891
			}
892
			fn rem(self, other: $other) -> Self::Output {
893
				self % (other as Self)
894
			}
895
		}
896
	};
897
}
898
impl_scale!(u128, u128);
899
impl_scale!(u128, u64);
900
impl_scale!(u128, u32);
901
impl_scale!(u128, u16);
902
impl_scale!(u128, u8);
903
impl_scale!(u64, u64);
904
impl_scale!(u64, u32);
905
impl_scale!(u64, u16);
906
impl_scale!(u64, u8);
907
impl_scale!(u32, u32);
908
impl_scale!(u32, u16);
909
impl_scale!(u32, u8);
910
impl_scale!(u16, u16);
911
impl_scale!(u16, u8);
912
impl_scale!(u8, u8);
913

            
914
/// Trait for things that can be clear (have no bits set). For numeric types, essentially the same
915
/// as `Zero`.
916
pub trait Clear {
917
	/// True iff no bits are set.
918
	fn is_clear(&self) -> bool;
919

            
920
	/// Return the value of Self that is clear.
921
	fn clear() -> Self;
922
}
923

            
924
impl<T: Default + Eq + PartialEq> Clear for T {
925
	fn is_clear(&self) -> bool {
926
		*self == Self::clear()
927
	}
928
	fn clear() -> Self {
929
		Default::default()
930
	}
931
}
932

            
933
/// A meta trait for all bit ops.
934
pub trait SimpleBitOps:
935
	Sized
936
	+ Clear
937
	+ core::ops::BitOr<Self, Output = Self>
938
	+ core::ops::BitXor<Self, Output = Self>
939
	+ core::ops::BitAnd<Self, Output = Self>
940
{
941
}
942
impl<
943
		T: Sized
944
			+ Clear
945
			+ core::ops::BitOr<Self, Output = Self>
946
			+ core::ops::BitXor<Self, Output = Self>
947
			+ core::ops::BitAnd<Self, Output = Self>,
948
	> SimpleBitOps for T
949
{
950
}
951

            
952
/// Abstraction around hashing
953
// Stupid bug in the Rust compiler believes derived
954
// traits must be fulfilled by all type parameters.
955
pub trait Hash:
956
	'static
957
	+ MaybeSerializeDeserialize
958
	+ Debug
959
	+ Clone
960
	+ Eq
961
	+ PartialEq
962
	+ Hasher<Out = <Self as Hash>::Output>
963
{
964
	/// The hash type produced.
965
	type Output: HashOutput;
966

            
967
	/// Produce the hash of some byte-slice.
968
776164
	fn hash(s: &[u8]) -> Self::Output {
969
776164
		<Self as Hasher>::hash(s)
970
776164
	}
971

            
972
	/// Produce the hash of some codec-encodable value.
973
393954
	fn hash_of<S: Encode>(s: &S) -> Self::Output {
974
393954
		Encode::using_encoded(s, <Self as Hasher>::hash)
975
393954
	}
976

            
977
	/// The ordered Patricia tree root of the given `input`.
978
	fn ordered_trie_root(input: Vec<Vec<u8>>, state_version: StateVersion) -> Self::Output;
979

            
980
	/// The Patricia tree root of the given mapping.
981
	fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>, state_version: StateVersion) -> Self::Output;
982
}
983

            
984
/// Super trait with all the attributes for a hashing output.
985
pub trait HashOutput:
986
	Member
987
	+ MaybeSerializeDeserialize
988
	+ MaybeDisplay
989
	+ MaybeFromStr
990
	+ Debug
991
	+ core::hash::Hash
992
	+ AsRef<[u8]>
993
	+ AsMut<[u8]>
994
	+ Copy
995
	+ Ord
996
	+ Default
997
	+ Encode
998
	+ Decode
999
	+ EncodeLike
	+ MaxEncodedLen
	+ TypeInfo
{
}
impl<T> HashOutput for T where
	T: Member
		+ MaybeSerializeDeserialize
		+ MaybeDisplay
		+ MaybeFromStr
		+ Debug
		+ core::hash::Hash
		+ AsRef<[u8]>
		+ AsMut<[u8]>
		+ Copy
		+ Ord
		+ Default
		+ Encode
		+ Decode
		+ EncodeLike
		+ MaxEncodedLen
		+ TypeInfo
{
}
/// Blake2-256 Hash implementation.
#[derive(PartialEq, Eq, Clone, RuntimeDebug, TypeInfo)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct BlakeTwo256;
impl Hasher for BlakeTwo256 {
	type Out = sp_core::H256;
	type StdHasher = hash256_std_hasher::Hash256StdHasher;
	const LENGTH: usize = 32;
376638
	fn hash(s: &[u8]) -> Self::Out {
376638
		sp_io::hashing::blake2_256(s).into()
376638
	}
}
impl Hash for BlakeTwo256 {
	type Output = sp_core::H256;
129842
	fn ordered_trie_root(input: Vec<Vec<u8>>, version: StateVersion) -> Self::Output {
129842
		sp_io::trie::blake2_256_ordered_root(input, version)
129842
	}
	fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>, version: StateVersion) -> Self::Output {
		sp_io::trie::blake2_256_root(input, version)
	}
}
/// Keccak-256 Hash implementation.
#[derive(PartialEq, Eq, Clone, RuntimeDebug, TypeInfo)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Keccak256;
impl Hasher for Keccak256 {
	type Out = sp_core::H256;
	type StdHasher = hash256_std_hasher::Hash256StdHasher;
	const LENGTH: usize = 32;
426372
	fn hash(s: &[u8]) -> Self::Out {
426372
		sp_io::hashing::keccak_256(s).into()
426372
	}
}
impl Hash for Keccak256 {
	type Output = sp_core::H256;
	fn ordered_trie_root(input: Vec<Vec<u8>>, version: StateVersion) -> Self::Output {
		sp_io::trie::keccak_256_ordered_root(input, version)
	}
	fn trie_root(input: Vec<(Vec<u8>, Vec<u8>)>, version: StateVersion) -> Self::Output {
		sp_io::trie::keccak_256_root(input, version)
	}
}
/// Something that can be checked for equality and printed out to a debug channel if bad.
pub trait CheckEqual {
	/// Perform the equality check.
	fn check_equal(&self, other: &Self);
}
impl CheckEqual for sp_core::H256 {
	#[cfg(feature = "std")]
	fn check_equal(&self, other: &Self) {
		use sp_core::hexdisplay::HexDisplay;
		if self != other {
			println!(
				"Hash: given={}, expected={}",
				HexDisplay::from(self.as_fixed_bytes()),
				HexDisplay::from(other.as_fixed_bytes()),
			);
		}
	}
	#[cfg(not(feature = "std"))]
	fn check_equal(&self, other: &Self) {
		if self != other {
			"Hash not equal".print();
			self.as_bytes().print();
			other.as_bytes().print();
		}
	}
}
impl CheckEqual for super::generic::DigestItem {
	#[cfg(feature = "std")]
	fn check_equal(&self, other: &Self) {
		if self != other {
			println!("DigestItem: given={:?}, expected={:?}", self, other);
		}
	}
	#[cfg(not(feature = "std"))]
	fn check_equal(&self, other: &Self) {
		if self != other {
			"DigestItem not equal".print();
			(&Encode::encode(self)[..]).print();
			(&Encode::encode(other)[..]).print();
		}
	}
}
sp_core::impl_maybe_marker!(
	/// A type that implements Display when in std environment.
	trait MaybeDisplay: Display;
	/// A type that implements FromStr when in std environment.
	trait MaybeFromStr: FromStr;
	/// A type that implements Hash when in std environment.
	trait MaybeHash: core::hash::Hash;
);
sp_core::impl_maybe_marker_std_or_serde!(
	/// A type that implements Serialize when in std environment or serde feature is activated.
	trait MaybeSerialize: Serialize;
	/// A type that implements Serialize, DeserializeOwned and Debug when in std environment or serde feature is activated.
	trait MaybeSerializeDeserialize: DeserializeOwned, Serialize;
);
/// A type that can be used in runtime structures.
pub trait Member: Send + Sync + Sized + Debug + Eq + PartialEq + Clone + 'static {}
impl<T: Send + Sync + Sized + Debug + Eq + PartialEq + Clone + 'static> Member for T {}
/// Determine if a `MemberId` is a valid member.
pub trait IsMember<MemberId> {
	/// Is the given `MemberId` a valid member?
	fn is_member(member_id: &MemberId) -> bool;
}
/// Super trait with all the attributes for a block number.
pub trait BlockNumber:
	Member
	+ MaybeSerializeDeserialize
	+ MaybeFromStr
	+ Debug
	+ core::hash::Hash
	+ Copy
	+ MaybeDisplay
	+ AtLeast32BitUnsigned
	+ Into<U256>
	+ TryFrom<U256>
	+ Default
	+ TypeInfo
	+ MaxEncodedLen
	+ FullCodec
{
}
impl<
		T: Member
			+ MaybeSerializeDeserialize
			+ MaybeFromStr
			+ Debug
			+ core::hash::Hash
			+ Copy
			+ MaybeDisplay
			+ AtLeast32BitUnsigned
			+ Into<U256>
			+ TryFrom<U256>
			+ Default
			+ TypeInfo
			+ MaxEncodedLen
			+ FullCodec,
	> BlockNumber for T
{
}
/// Something which fulfills the abstract idea of a Substrate header. It has types for a `Number`,
/// a `Hash` and a `Hashing`. It provides access to an `extrinsics_root`, `state_root` and
/// `parent_hash`, as well as a `digest` and a block `number`.
///
/// You can also create a `new` one from those fields.
pub trait Header:
	Clone + Send + Sync + Codec + Eq + MaybeSerialize + Debug + TypeInfo + 'static
{
	/// Header number.
	type Number: BlockNumber;
	/// Header hash type
	type Hash: HashOutput;
	/// Hashing algorithm
	type Hashing: Hash<Output = Self::Hash>;
	/// Creates new header.
	fn new(
		number: Self::Number,
		extrinsics_root: Self::Hash,
		state_root: Self::Hash,
		parent_hash: Self::Hash,
		digest: Digest,
	) -> Self;
	/// Returns a reference to the header number.
	fn number(&self) -> &Self::Number;
	/// Sets the header number.
	fn set_number(&mut self, number: Self::Number);
	/// Returns a reference to the extrinsics root.
	fn extrinsics_root(&self) -> &Self::Hash;
	/// Sets the extrinsic root.
	fn set_extrinsics_root(&mut self, root: Self::Hash);
	/// Returns a reference to the state root.
	fn state_root(&self) -> &Self::Hash;
	/// Sets the state root.
	fn set_state_root(&mut self, root: Self::Hash);
	/// Returns a reference to the parent hash.
	fn parent_hash(&self) -> &Self::Hash;
	/// Sets the parent hash.
	fn set_parent_hash(&mut self, hash: Self::Hash);
	/// Returns a reference to the digest.
	fn digest(&self) -> &Digest;
	/// Get a mutable reference to the digest.
	fn digest_mut(&mut self) -> &mut Digest;
	/// Returns the hash of the header.
196257
	fn hash(&self) -> Self::Hash {
196257
		<Self::Hashing as Hash>::hash_of(self)
196257
	}
}
// Something that provides the Header Type. Only for internal usage and should only be used
// via `HeaderFor` or `BlockNumberFor`.
//
// This is needed to fix the "cyclical" issue in loading Header/BlockNumber as part of a
// `pallet::call`. Essentially, `construct_runtime` aggregates all calls to create a `RuntimeCall`
// that is then used to define `UncheckedExtrinsic`.
// ```ignore
// pub type UncheckedExtrinsic =
// 	generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
// ```
// This `UncheckedExtrinsic` is supplied to the `Block`.
// ```ignore
// pub type Block = generic::Block<Header, UncheckedExtrinsic>;
// ```
// So, if we do not create a trait outside of `Block` that doesn't have `Extrinsic`, we go into a
// recursive loop leading to a build error.
//
// Note that this is a workaround for a compiler bug and should be removed when the compiler
// bug is fixed.
#[doc(hidden)]
pub trait HeaderProvider {
	/// Header type.
	type HeaderT: Header;
}
/// Something which fulfills the abstract idea of a Substrate block. It has types for
/// `Extrinsic` pieces of information as well as a `Header`.
///
/// You can get an iterator over each of the `extrinsics` and retrieve the `header`.
pub trait Block:
	HeaderProvider<HeaderT = <Self as Block>::Header>
	+ Clone
	+ Send
	+ Sync
	+ Codec
	+ Eq
	+ MaybeSerialize
	+ Debug
	+ 'static
{
	/// Type for extrinsics.
	type Extrinsic: Member + Codec + Extrinsic + MaybeSerialize;
	/// Header type.
	type Header: Header<Hash = Self::Hash> + MaybeSerializeDeserialize;
	/// Block hash type.
	type Hash: HashOutput;
	/// Returns a reference to the header.
	fn header(&self) -> &Self::Header;
	/// Returns a reference to the list of extrinsics.
	fn extrinsics(&self) -> &[Self::Extrinsic];
	/// Split the block into header and list of extrinsics.
	fn deconstruct(self) -> (Self::Header, Vec<Self::Extrinsic>);
	/// Creates new block from header and extrinsics.
	fn new(header: Self::Header, extrinsics: Vec<Self::Extrinsic>) -> Self;
	/// Returns the hash of the block.
	fn hash(&self) -> Self::Hash {
		<<Self::Header as Header>::Hashing as Hash>::hash_of(self.header())
	}
	/// Creates an encoded block from the given `header` and `extrinsics` without requiring the
	/// creation of an instance.
	fn encode_from(header: &Self::Header, extrinsics: &[Self::Extrinsic]) -> Vec<u8>;
}
/// Something that acts like an `Extrinsic`.
pub trait Extrinsic: Sized {
	/// The function call.
	type Call: TypeInfo;
	/// The payload we carry for signed extrinsics.
	///
	/// Usually it will contain a `Signature` and
	/// may include some additional data that are specific to signed
	/// extrinsics.
	type SignaturePayload: SignaturePayload;
	/// Is this `Extrinsic` signed?
	/// If no information are available about signed/unsigned, `None` should be returned.
	fn is_signed(&self) -> Option<bool> {
		None
	}
	/// Create new instance of the extrinsic.
	///
	/// Extrinsics can be split into:
	/// 1. Inherents (no signature; created by validators during block production)
	/// 2. Unsigned Transactions (no signature; represent "system calls" or other special kinds of
	/// calls) 3. Signed Transactions (with signature; a regular transactions with known origin)
	fn new(_call: Self::Call, _signed_data: Option<Self::SignaturePayload>) -> Option<Self> {
		None
	}
}
/// Something that acts like a [`SignaturePayload`](Extrinsic::SignaturePayload) of an
/// [`Extrinsic`].
pub trait SignaturePayload {
	/// The type of the address that signed the extrinsic.
	///
	/// Particular to a signed extrinsic.
	type SignatureAddress: TypeInfo;
	/// The signature type of the extrinsic.
	///
	/// Particular to a signed extrinsic.
	type Signature: TypeInfo;
	/// The additional data that is specific to the signed extrinsic.
	///
	/// Particular to a signed extrinsic.
	type SignatureExtra: TypeInfo;
}
impl SignaturePayload for () {
	type SignatureAddress = ();
	type Signature = ();
	type SignatureExtra = ();
}
/// Implementor is an [`Extrinsic`] and provides metadata about this extrinsic.
pub trait ExtrinsicMetadata {
	/// The format version of the `Extrinsic`.
	///
	/// By format is meant the encoded representation of the `Extrinsic`.
	const VERSION: u8;
	/// Signed extensions attached to this `Extrinsic`.
	type SignedExtensions: SignedExtension;
}
/// Extract the hashing type for a block.
pub type HashingFor<B> = <<B as Block>::Header as Header>::Hashing;
/// Extract the number type for a block.
pub type NumberFor<B> = <<B as Block>::Header as Header>::Number;
/// Extract the digest type for a block.
/// A "checkable" piece of information, used by the standard Substrate Executive in order to
/// check the validity of a piece of extrinsic information, usually by verifying the signature.
/// Implement for pieces of information that require some additional context `Context` in order to
/// be checked.
pub trait Checkable<Context>: Sized {
	/// Returned if `check` succeeds.
	type Checked;
	/// Check self, given an instance of Context.
	fn check(self, c: &Context) -> Result<Self::Checked, TransactionValidityError>;
	/// Blindly check self.
	///
	/// ## WARNING
	///
	/// DO NOT USE IN PRODUCTION. This is only meant to be used in testing environments. A runtime
	/// compiled with `try-runtime` should never be in production. Moreover, the name of this
	/// function is deliberately chosen to prevent developers from ever calling it in consensus
	/// code-paths.
	#[cfg(feature = "try-runtime")]
	fn unchecked_into_checked_i_know_what_i_am_doing(
		self,
		c: &Context,
	) -> Result<Self::Checked, TransactionValidityError>;
}
/// A "checkable" piece of information, used by the standard Substrate Executive in order to
/// check the validity of a piece of extrinsic information, usually by verifying the signature.
/// Implement for pieces of information that don't require additional context in order to be
/// checked.
pub trait BlindCheckable: Sized {
	/// Returned if `check` succeeds.
	type Checked;
	/// Check self.
	fn check(self) -> Result<Self::Checked, TransactionValidityError>;
}
// Every `BlindCheckable` is also a `StaticCheckable` for arbitrary `Context`.
impl<T: BlindCheckable, Context> Checkable<Context> for T {
	type Checked = <Self as BlindCheckable>::Checked;
	fn check(self, _c: &Context) -> Result<Self::Checked, TransactionValidityError> {
		BlindCheckable::check(self)
	}
	#[cfg(feature = "try-runtime")]
	fn unchecked_into_checked_i_know_what_i_am_doing(
		self,
		_: &Context,
	) -> Result<Self::Checked, TransactionValidityError> {
		unreachable!();
	}
}
/// A lazy call (module function and argument values) that can be executed via its `dispatch`
/// method.
pub trait Dispatchable {
	/// Every function call from your runtime has an origin, which specifies where the extrinsic was
	/// generated from. In the case of a signed extrinsic (transaction), the origin contains an
	/// identifier for the caller. The origin can be empty in the case of an inherent extrinsic.
	type RuntimeOrigin: Debug;
	/// ...
	type Config;
	/// An opaque set of information attached to the transaction. This could be constructed anywhere
	/// down the line in a runtime. The current Substrate runtime uses a struct with the same name
	/// to represent the dispatch class and weight.
	type Info;
	/// Additional information that is returned by `dispatch`. Can be used to supply the caller
	/// with information about a `Dispatchable` that is only known post dispatch.
	type PostInfo: Eq + PartialEq + Clone + Copy + Encode + Decode + Printable;
	/// Actually dispatch this call and return the result of it.
	fn dispatch(self, origin: Self::RuntimeOrigin)
		-> crate::DispatchResultWithInfo<Self::PostInfo>;
}
/// Shortcut to reference the `Info` type of a `Dispatchable`.
pub type DispatchInfoOf<T> = <T as Dispatchable>::Info;
/// Shortcut to reference the `PostInfo` type of a `Dispatchable`.
pub type PostDispatchInfoOf<T> = <T as Dispatchable>::PostInfo;
impl Dispatchable for () {
	type RuntimeOrigin = ();
	type Config = ();
	type Info = ();
	type PostInfo = ();
	fn dispatch(
		self,
		_origin: Self::RuntimeOrigin,
	) -> crate::DispatchResultWithInfo<Self::PostInfo> {
		panic!("This implementation should not be used for actual dispatch.");
	}
}
/// Means by which a transaction may be extended. This type embodies both the data and the logic
/// that should be additionally associated with the transaction. It should be plain old data.
pub trait SignedExtension:
	Codec + Debug + Sync + Send + Clone + Eq + PartialEq + StaticTypeInfo
{
	/// Unique identifier of this signed extension.
	///
	/// This will be exposed in the metadata to identify the signed extension used
	/// in an extrinsic.
	const IDENTIFIER: &'static str;
	/// The type which encodes the sender identity.
	type AccountId;
	/// The type which encodes the call to be dispatched.
	type Call: Dispatchable;
	/// Any additional data that will go into the signed payload. This may be created dynamically
	/// from the transaction using the `additional_signed` function.
	type AdditionalSigned: Encode + TypeInfo;
	/// The type that encodes information that can be passed from pre_dispatch to post-dispatch.
	type Pre;
	/// Construct any additional data that should be in the signed payload of the transaction. Can
	/// also perform any pre-signature-verification checks and return an error if needed.
	fn additional_signed(&self) -> Result<Self::AdditionalSigned, TransactionValidityError>;
	/// Validate a signed transaction for the transaction queue.
	///
	/// This function can be called frequently by the transaction queue,
	/// to obtain transaction validity against current state.
	/// It should perform all checks that determine a valid transaction,
	/// that can pay for its execution and quickly eliminate ones
	/// that are stale or incorrect.
	///
	/// Make sure to perform the same checks in `pre_dispatch` function.
	fn validate(
		&self,
		_who: &Self::AccountId,
		_call: &Self::Call,
		_info: &DispatchInfoOf<Self::Call>,
		_len: usize,
	) -> TransactionValidity {
		Ok(ValidTransaction::default())
	}
	/// Do any pre-flight stuff for a signed transaction.
	///
	/// Make sure to perform the same checks as in [`Self::validate`].
	fn pre_dispatch(
		self,
		who: &Self::AccountId,
		call: &Self::Call,
		info: &DispatchInfoOf<Self::Call>,
		len: usize,
	) -> Result<Self::Pre, TransactionValidityError>;
	/// Validate an unsigned transaction for the transaction queue.
	///
	/// This function can be called frequently by the transaction queue
	/// to obtain transaction validity against current state.
	/// It should perform all checks that determine a valid unsigned transaction,
	/// and quickly eliminate ones that are stale or incorrect.
	///
	/// Make sure to perform the same checks in `pre_dispatch_unsigned` function.
1558104
	fn validate_unsigned(
1558104
		_call: &Self::Call,
1558104
		_info: &DispatchInfoOf<Self::Call>,
1558104
		_len: usize,
1558104
	) -> TransactionValidity {
1558104
		Ok(ValidTransaction::default())
1558104
	}
	/// Do any pre-flight stuff for a unsigned transaction.
	///
	/// Note this function by default delegates to `validate_unsigned`, so that
	/// all checks performed for the transaction queue are also performed during
	/// the dispatch phase (applying the extrinsic).
	///
	/// If you ever override this function, you need to make sure to always
	/// perform the same validation as in `validate_unsigned`.
1558104
	fn pre_dispatch_unsigned(
1558104
		call: &Self::Call,
1558104
		info: &DispatchInfoOf<Self::Call>,
1558104
		len: usize,
1558104
	) -> Result<(), TransactionValidityError> {
1558104
		Self::validate_unsigned(call, info, len).map(|_| ()).map_err(Into::into)
1558104
	}
	/// Do any post-flight stuff for an extrinsic.
	///
	/// If the transaction is signed, then `_pre` will contain the output of `pre_dispatch`,
	/// and `None` otherwise.
	///
	/// This gets given the `DispatchResult` `_result` from the extrinsic and can, if desired,
	/// introduce a `TransactionValidityError`, causing the block to become invalid for including
	/// it.
	///
	/// WARNING: It is dangerous to return an error here. To do so will fundamentally invalidate the
	/// transaction and any block that it is included in, causing the block author to not be
	/// compensated for their work in validating the transaction or producing the block so far.
	///
	/// It can only be used safely when you *know* that the extrinsic is one that can only be
	/// introduced by the current block author; generally this implies that it is an inherent and
	/// will come from either an offchain-worker or via `InherentData`.
1363341
	fn post_dispatch(
1363341
		_pre: Option<Self::Pre>,
1363341
		_info: &DispatchInfoOf<Self::Call>,
1363341
		_post_info: &PostDispatchInfoOf<Self::Call>,
1363341
		_len: usize,
1363341
		_result: &DispatchResult,
1363341
	) -> Result<(), TransactionValidityError> {
1363341
		Ok(())
1363341
	}
	/// Returns the metadata for this signed extension.
	///
	/// As a [`SignedExtension`] can be a tuple of [`SignedExtension`]s we need to return a `Vec`
	/// that holds the metadata of each one. Each individual `SignedExtension` must return
	/// *exactly* one [`SignedExtensionMetadata`].
	///
	/// This method provides a default implementation that returns a vec containing a single
	/// [`SignedExtensionMetadata`].
	fn metadata() -> Vec<SignedExtensionMetadata> {
		alloc::vec![SignedExtensionMetadata {
			identifier: Self::IDENTIFIER,
			ty: scale_info::meta_type::<Self>(),
			additional_signed: scale_info::meta_type::<Self::AdditionalSigned>()
		}]
	}
}
/// Information about a [`SignedExtension`] for the runtime metadata.
pub struct SignedExtensionMetadata {
	/// The unique identifier of the [`SignedExtension`].
	pub identifier: &'static str,
	/// The type of the [`SignedExtension`].
	pub ty: MetaType,
	/// The type of the [`SignedExtension`] additional signed data for the payload.
	pub additional_signed: MetaType,
}
#[impl_for_tuples(1, 12)]
impl<AccountId, Call: Dispatchable> SignedExtension for Tuple {
	for_tuples!( where #( Tuple: SignedExtension<AccountId=AccountId, Call=Call,> )* );
	type AccountId = AccountId;
	type Call = Call;
	const IDENTIFIER: &'static str = "You should call `identifier()`!";
	for_tuples!( type AdditionalSigned = ( #( Tuple::AdditionalSigned ),* ); );
	for_tuples!( type Pre = ( #( Tuple::Pre ),* ); );
	fn additional_signed(&self) -> Result<Self::AdditionalSigned, TransactionValidityError> {
		Ok(for_tuples!( ( #( Tuple.additional_signed()? ),* ) ))
	}
	fn validate(
		&self,
		who: &Self::AccountId,
		call: &Self::Call,
		info: &DispatchInfoOf<Self::Call>,
		len: usize,
	) -> TransactionValidity {
		let valid = ValidTransaction::default();
		for_tuples!( #( let valid = valid.combine_with(Tuple.validate(who, call, info, len)?); )* );
		Ok(valid)
	}
	fn pre_dispatch(
		self,
		who: &Self::AccountId,
		call: &Self::Call,
		info: &DispatchInfoOf<Self::Call>,
		len: usize,
	) -> Result<Self::Pre, TransactionValidityError> {
		Ok(for_tuples!( ( #( Tuple.pre_dispatch(who, call, info, len)? ),* ) ))
	}
	fn validate_unsigned(
		call: &Self::Call,
		info: &DispatchInfoOf<Self::Call>,
		len: usize,
	) -> TransactionValidity {
		let valid = ValidTransaction::default();
		for_tuples!( #( let valid = valid.combine_with(Tuple::validate_unsigned(call, info, len)?); )* );
		Ok(valid)
	}
194763
	fn pre_dispatch_unsigned(
194763
		call: &Self::Call,
194763
		info: &DispatchInfoOf<Self::Call>,
194763
		len: usize,
194763
	) -> Result<(), TransactionValidityError> {
194763
		for_tuples!( #( Tuple::pre_dispatch_unsigned(call, info, len)?; )* );
194763
		Ok(())
194763
	}
194763
	fn post_dispatch(
194763
		pre: Option<Self::Pre>,
194763
		info: &DispatchInfoOf<Self::Call>,
194763
		post_info: &PostDispatchInfoOf<Self::Call>,
194763
		len: usize,
194763
		result: &DispatchResult,
194763
	) -> Result<(), TransactionValidityError> {
194763
		match pre {
			Some(x) => {
				for_tuples!( #( Tuple::post_dispatch(Some(x.Tuple), info, post_info, len, result)?; )* );
			},
			None => {
194763
				for_tuples!( #( Tuple::post_dispatch(None, info, post_info, len, result)?; )* );
			},
		}
194763
		Ok(())
194763
	}
	fn metadata() -> Vec<SignedExtensionMetadata> {
		let mut ids = Vec::new();
		for_tuples!( #( ids.extend(Tuple::metadata()); )* );
		ids
	}
}
impl SignedExtension for () {
	type AccountId = u64;
	type AdditionalSigned = ();
	type Call = ();
	type Pre = ();
	const IDENTIFIER: &'static str = "UnitSignedExtension";
	fn additional_signed(&self) -> core::result::Result<(), TransactionValidityError> {
		Ok(())
	}
	fn pre_dispatch(
		self,
		who: &Self::AccountId,
		call: &Self::Call,
		info: &DispatchInfoOf<Self::Call>,
		len: usize,
	) -> Result<Self::Pre, TransactionValidityError> {
		self.validate(who, call, info, len).map(|_| ())
	}
}
/// An "executable" piece of information, used by the standard Substrate Executive in order to
/// enact a piece of extrinsic information by marshalling and dispatching to a named function
/// call.
///
/// Also provides information on to whom this information is attributable and an index that allows
/// each piece of attributable information to be disambiguated.
pub trait Applyable: Sized + Send + Sync {
	/// Type by which we can dispatch. Restricts the `UnsignedValidator` type.
	type Call: Dispatchable;
	/// Checks to see if this is a valid *transaction*. It returns information on it if so.
	fn validate<V: ValidateUnsigned<Call = Self::Call>>(
		&self,
		source: TransactionSource,
		info: &DispatchInfoOf<Self::Call>,
		len: usize,
	) -> TransactionValidity;
	/// Executes all necessary logic needed prior to dispatch and deconstructs into function call,
	/// index and sender.
	fn apply<V: ValidateUnsigned<Call = Self::Call>>(
		self,
		info: &DispatchInfoOf<Self::Call>,
		len: usize,
	) -> crate::ApplyExtrinsicResultWithInfo<PostDispatchInfoOf<Self::Call>>;
}
/// A marker trait for something that knows the type of the runtime block.
pub trait GetRuntimeBlockType {
	/// The `RuntimeBlock` type.
	type RuntimeBlock: self::Block;
}
/// A marker trait for something that knows the type of the node block.
pub trait GetNodeBlockType {
	/// The `NodeBlock` type.
	type NodeBlock: self::Block;
}
/// Provide validation for unsigned extrinsics.
///
/// This trait provides two functions [`pre_dispatch`](Self::pre_dispatch) and
/// [`validate_unsigned`](Self::validate_unsigned). The [`pre_dispatch`](Self::pre_dispatch)
/// function is called right before dispatching the call wrapped by an unsigned extrinsic. The
/// [`validate_unsigned`](Self::validate_unsigned) function is mainly being used in the context of
/// the transaction pool to check the validity of the call wrapped by an unsigned extrinsic.
pub trait ValidateUnsigned {
	/// The call to validate
	type Call;
	/// Validate the call right before dispatch.
	///
	/// This method should be used to prevent transactions already in the pool
	/// (i.e. passing [`validate_unsigned`](Self::validate_unsigned)) from being included in blocks
	/// in case they became invalid since being added to the pool.
	///
	/// By default it's a good idea to call [`validate_unsigned`](Self::validate_unsigned) from
	/// within this function again to make sure we never include an invalid transaction. Otherwise
	/// the implementation of the call or this method will need to provide proper validation to
	/// ensure that the transaction is valid.
	///
	/// Changes made to storage *WILL* be persisted if the call returns `Ok`.
	fn pre_dispatch(call: &Self::Call) -> Result<(), TransactionValidityError> {
		Self::validate_unsigned(TransactionSource::InBlock, call)
			.map(|_| ())
			.map_err(Into::into)
	}
	/// Return the validity of the call
	///
	/// This method has no side-effects. It merely checks whether the call would be rejected
	/// by the runtime in an unsigned extrinsic.
	///
	/// The validity checks should be as lightweight as possible because every node will execute
	/// this code before the unsigned extrinsic enters the transaction pool and also periodically
	/// afterwards to ensure the validity. To prevent dos-ing a network with unsigned
	/// extrinsics, these validity checks should include some checks around uniqueness, for example,
	/// checking that the unsigned extrinsic was sent by an authority in the active set.
	///
	/// Changes made to storage should be discarded by caller.
	fn validate_unsigned(source: TransactionSource, call: &Self::Call) -> TransactionValidity;
}
/// Opaque data type that may be destructured into a series of raw byte slices (which represent
/// individual keys).
pub trait OpaqueKeys: Clone {
	/// Types bound to this opaque keys that provide the key type ids returned.
	type KeyTypeIdProviders;
	/// Return the key-type IDs supported by this set.
	fn key_ids() -> &'static [crate::KeyTypeId];
	/// Get the raw bytes of key with key-type ID `i`.
	fn get_raw(&self, i: super::KeyTypeId) -> &[u8];
	/// Get the decoded key with key-type ID `i`.
	fn get<T: Decode>(&self, i: super::KeyTypeId) -> Option<T> {
		T::decode(&mut self.get_raw(i)).ok()
	}
	/// Verify a proof of ownership for the keys.
1806
	fn ownership_proof_is_valid(&self, _proof: &[u8]) -> bool {
1806
		true
1806
	}
}
/// Input that adds infinite number of zero after wrapped input.
///
/// This can add an infinite stream of zeros onto any input, not just a slice as with
/// `TrailingZerosInput`.
pub struct AppendZerosInput<'a, T>(&'a mut T);
impl<'a, T> AppendZerosInput<'a, T> {
	/// Create a new instance from the given byte array.
660
	pub fn new(input: &'a mut T) -> Self {
660
		Self(input)
660
	}
}
impl<'a, T: codec::Input> codec::Input for AppendZerosInput<'a, T> {
1320
	fn remaining_len(&mut self) -> Result<Option<usize>, codec::Error> {
1320
		Ok(None)
1320
	}
80478
	fn read(&mut self, into: &mut [u8]) -> Result<(), codec::Error> {
80478
		let remaining = self.0.remaining_len()?;
80478
		let completed = if let Some(n) = remaining {
80478
			let readable = into.len().min(n);
80478
			// this should never fail if `remaining_len` API is implemented correctly.
80478
			self.0.read(&mut into[..readable])?;
80478
			readable
		} else {
			// Fill it byte-by-byte.
			let mut i = 0;
			while i < into.len() {
				if let Ok(b) = self.0.read_byte() {
					into[i] = b;
					i += 1;
				} else {
					break
				}
			}
			i
		};
		// Fill the rest with zeros.
80478
		for i in &mut into[completed..] {
			*i = 0;
		}
80478
		Ok(())
80478
	}
}
/// Input that adds infinite number of zero after wrapped input.
pub struct TrailingZeroInput<'a>(&'a [u8]);
impl<'a> TrailingZeroInput<'a> {
	/// Create a new instance from the given byte array.
14705
	pub fn new(data: &'a [u8]) -> Self {
14705
		Self(data)
14705
	}
	/// Create a new instance which only contains zeroes as input.
	pub fn zeroes() -> Self {
		Self::new(&[][..])
	}
}
impl<'a> codec::Input for TrailingZeroInput<'a> {
	fn remaining_len(&mut self) -> Result<Option<usize>, codec::Error> {
		Ok(None)
	}
137474
	fn read(&mut self, into: &mut [u8]) -> Result<(), codec::Error> {
137474
		let len_from_inner = into.len().min(self.0.len());
137474
		into[..len_from_inner].copy_from_slice(&self.0[..len_from_inner]);
2631880
		for i in &mut into[len_from_inner..] {
2631880
			*i = 0;
2631880
		}
137474
		self.0 = &self.0[len_from_inner..];
137474

            
137474
		Ok(())
137474
	}
}
/// This type can be converted into and possibly from an AccountId (which itself is generic).
pub trait AccountIdConversion<AccountId>: Sized {
	/// Convert into an account ID. This is infallible, and may truncate bytes to provide a result.
	/// This may lead to duplicate accounts if the size of `AccountId` is less than the seed.
197388
	fn into_account_truncating(&self) -> AccountId {
197388
		self.into_sub_account_truncating(&())
197388
	}
	/// Convert into an account ID, checking that all bytes of the seed are being used in the final
	/// `AccountId` generated. If any bytes are dropped, this returns `None`.
	fn try_into_account(&self) -> Option<AccountId> {
		self.try_into_sub_account(&())
	}
	/// Try to convert an account ID into this type. Might not succeed.
	fn try_from_account(a: &AccountId) -> Option<Self> {
		Self::try_from_sub_account::<()>(a).map(|x| x.0)
	}
	/// Convert this value amalgamated with the a secondary "sub" value into an account ID,
	/// truncating any unused bytes. This is infallible.
	///
	/// NOTE: The account IDs from this and from `into_account` are *not* guaranteed to be distinct
	/// for any given value of `self`, nor are different invocations to this with different types
	/// `T`. For example, the following will all encode to the same account ID value:
	/// - `self.into_sub_account(0u32)`
	/// - `self.into_sub_account(vec![0u8; 0])`
	/// - `self.into_account()`
	///
	/// Also, if the seed provided to this function is greater than the number of bytes which fit
	/// into this `AccountId` type, then it will lead to truncation of the seed, and potentially
	/// non-unique accounts.
	fn into_sub_account_truncating<S: Encode>(&self, sub: S) -> AccountId;
	/// Same as `into_sub_account_truncating`, but ensuring that all bytes of the account's seed are
	/// used when generating an account. This can help guarantee that different accounts are unique,
	/// besides types which encode the same as noted above.
	fn try_into_sub_account<S: Encode>(&self, sub: S) -> Option<AccountId>;
	/// Try to convert an account ID into this type. Might not succeed.
	fn try_from_sub_account<S: Decode>(x: &AccountId) -> Option<(Self, S)>;
}
/// Format is TYPE_ID ++ encode(sub-seed) ++ 00.... where 00... is indefinite trailing zeroes to
/// fill AccountId.
impl<T: Encode + Decode, Id: Encode + Decode + TypeId> AccountIdConversion<T> for Id {
	// Take the `sub` seed, and put as much of it as possible into the generated account, but
	// allowing truncation of the seed if it would not fit into the account id in full. This can
	// lead to two different `sub` seeds with the same account generated.
197388
	fn into_sub_account_truncating<S: Encode>(&self, sub: S) -> T {
197388
		(Id::TYPE_ID, self, sub)
197388
			.using_encoded(|b| T::decode(&mut TrailingZeroInput(b)))
197388
			.expect("All byte sequences are valid `AccountIds`; qed")
197388
	}
	// Same as `into_sub_account_truncating`, but returns `None` if any bytes would be truncated.
	fn try_into_sub_account<S: Encode>(&self, sub: S) -> Option<T> {
		let encoded_seed = (Id::TYPE_ID, self, sub).encode();
		let account = T::decode(&mut TrailingZeroInput(&encoded_seed))
			.expect("All byte sequences are valid `AccountIds`; qed");
		// If the `account` generated has less bytes than the `encoded_seed`, then we know that
		// bytes were truncated, and we return `None`.
		if encoded_seed.len() <= account.encoded_size() {
			Some(account)
		} else {
			None
		}
	}
	fn try_from_sub_account<S: Decode>(x: &T) -> Option<(Self, S)> {
		x.using_encoded(|d| {
			if d[0..4] != Id::TYPE_ID {
				return None
			}
			let mut cursor = &d[4..];
			let result = Decode::decode(&mut cursor).ok()?;
			if cursor.iter().all(|x| *x == 0) {
				Some(result)
			} else {
				None
			}
		})
	}
}
/// Calls a given macro a number of times with a set of fixed params and an incrementing numeral.
/// e.g.
/// ```nocompile
/// count!(println ("{}",) foo, bar, baz);
/// // Will result in three `println!`s: "0", "1" and "2".
/// ```
#[macro_export]
macro_rules! count {
	($f:ident ($($x:tt)*) ) => ();
	($f:ident ($($x:tt)*) $x1:tt) => { $f!($($x)* 0); };
	($f:ident ($($x:tt)*) $x1:tt, $x2:tt) => { $f!($($x)* 0); $f!($($x)* 1); };
	($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt) => { $f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); };
	($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt, $x4:tt) => {
		$f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); $f!($($x)* 3);
	};
	($f:ident ($($x:tt)*) $x1:tt, $x2:tt, $x3:tt, $x4:tt, $x5:tt) => {
		$f!($($x)* 0); $f!($($x)* 1); $f!($($x)* 2); $f!($($x)* 3); $f!($($x)* 4);
	};
}
#[doc(hidden)]
#[macro_export]
macro_rules! impl_opaque_keys_inner {
	(
		$( #[ $attr:meta ] )*
		pub struct $name:ident {
			$(
				$( #[ $inner_attr:meta ] )*
				pub $field:ident: $type:ty,
			)*
		}
	) => {
		$( #[ $attr ] )*
		#[derive(
			Clone, PartialEq, Eq,
			$crate::codec::Encode,
			$crate::codec::Decode,
			$crate::scale_info::TypeInfo,
			$crate::RuntimeDebug,
		)]
		pub struct $name {
			$(
				$( #[ $inner_attr ] )*
				pub $field: <$type as $crate::BoundToRuntimeAppPublic>::Public,
			)*
		}
		impl $name {
			/// Generate a set of keys with optionally using the given seed.
			///
			/// The generated key pairs are stored in the keystore.
			///
			/// Returns the concatenated SCALE encoded public keys.
			pub fn generate(seed: Option<$crate::Vec<u8>>) -> $crate::Vec<u8> {
				let keys = Self{
					$(
						$field: <
							<
								$type as $crate::BoundToRuntimeAppPublic
							>::Public as $crate::RuntimeAppPublic
						>::generate_pair(seed.clone()),
					)*
				};
				$crate::codec::Encode::encode(&keys)
			}
			/// Converts `Self` into a `Vec` of `(raw public key, KeyTypeId)`.
			pub fn into_raw_public_keys(
				self,
			) -> $crate::Vec<($crate::Vec<u8>, $crate::KeyTypeId)> {
				let mut keys = Vec::new();
				$(
					keys.push((
						$crate::RuntimeAppPublic::to_raw_vec(&self.$field),
						<
							<
								$type as $crate::BoundToRuntimeAppPublic
							>::Public as $crate::RuntimeAppPublic
						>::ID,
					));
				)*
				keys
			}
			/// Decode `Self` from the given `encoded` slice and convert `Self` into the raw public
			/// keys (see [`Self::into_raw_public_keys`]).
			///
			/// Returns `None` when the decoding failed, otherwise `Some(_)`.
			pub fn decode_into_raw_public_keys(
				encoded: &[u8],
			) -> Option<$crate::Vec<($crate::Vec<u8>, $crate::KeyTypeId)>> {
				<Self as $crate::codec::Decode>::decode(&mut &encoded[..])
					.ok()
					.map(|s| s.into_raw_public_keys())
			}
		}
		impl $crate::traits::OpaqueKeys for $name {
			type KeyTypeIdProviders = ( $( $type, )* );
4044
			fn key_ids() -> &'static [$crate::KeyTypeId] {
4044
				&[
4044
					$(
4044
						<
4044
							<
4044
								$type as $crate::BoundToRuntimeAppPublic
4044
							>::Public as $crate::RuntimeAppPublic
4044
						>::ID
4044
					),*
4044
				]
4044
			}
34086
			fn get_raw(&self, i: $crate::KeyTypeId) -> &[u8] {
34086
				match i {
					$(
4722
						i if i == <
4722
							<
4722
								$type as $crate::BoundToRuntimeAppPublic
4722
							>::Public as $crate::RuntimeAppPublic
4722
						>::ID =>
4722
							self.$field.as_ref(),
					)*
					_ => &[],
				}
34086
			}
34086
		}
34086
	};
34086
}
34086

            
34086
/// Implement `OpaqueKeys` for a described struct.
34086
///
34086
/// Every field type must implement [`BoundToRuntimeAppPublic`](crate::BoundToRuntimeAppPublic).
34086
/// `KeyTypeIdProviders` is set to the types given as fields.
34086
///
34086
/// ```rust
34086
/// use sp_runtime::{
34086
/// 	impl_opaque_keys, KeyTypeId, BoundToRuntimeAppPublic, app_crypto::{sr25519, ed25519}
34086
/// };
34086
///
34086
/// pub struct KeyModule;
34086
/// impl BoundToRuntimeAppPublic for KeyModule { type Public = ed25519::AppPublic; }
34086
///
34086
/// pub struct KeyModule2;
34086
/// impl BoundToRuntimeAppPublic for KeyModule2 { type Public = sr25519::AppPublic; }
34086
///
34086
/// impl_opaque_keys! {
34086
/// 	pub struct Keys {
34086
/// 		pub key_module: KeyModule,
34086
/// 		pub key_module2: KeyModule2,
34086
/// 	}
34086
/// }
34086
/// ```
34086
#[macro_export]
34086
#[cfg(any(feature = "serde", feature = "std"))]
34086
macro_rules! impl_opaque_keys {
34086
	{
34086
		$( #[ $attr:meta ] )*
34086
		pub struct $name:ident {
34086
			$(
34086
				$( #[ $inner_attr:meta ] )*
34086
				pub $field:ident: $type:ty,
34086
			)*
34086
		}
34086
	} => {
34086
		$crate::paste::paste! {
34086
			use $crate::serde as [< __opaque_keys_serde_import__ $name >];
34086

            
34086
			$crate::impl_opaque_keys_inner! {
34086
				$( #[ $attr ] )*
34086
				#[derive($crate::serde::Serialize, $crate::serde::Deserialize)]
				#[serde(crate = "__opaque_keys_serde_import__" $name)]
				pub struct $name {
					$(
						$( #[ $inner_attr ] )*
						pub $field: $type,
					)*
				}
			}
		}
	}
}
#[macro_export]
#[cfg(all(not(feature = "std"), not(feature = "serde")))]
#[doc(hidden)]
macro_rules! impl_opaque_keys {
	{
		$( #[ $attr:meta ] )*
		pub struct $name:ident {
			$(
				$( #[ $inner_attr:meta ] )*
				pub $field:ident: $type:ty,
			)*
		}
	} => {
		$crate::impl_opaque_keys_inner! {
			$( #[ $attr ] )*
			pub struct $name {
				$(
					$( #[ $inner_attr ] )*
					pub $field: $type,
				)*
			}
		}
	}
}
/// Trait for things which can be printed from the runtime.
pub trait Printable {
	/// Print the object.
	fn print(&self);
}
impl<T: Printable> Printable for &T {
	fn print(&self) {
		(*self).print()
	}
}
impl Printable for u8 {
	fn print(&self) {
		(*self as u64).print()
	}
}
impl Printable for u32 {
	fn print(&self) {
		(*self as u64).print()
	}
}
impl Printable for usize {
	fn print(&self) {
		(*self as u64).print()
	}
}
impl Printable for u64 {
	fn print(&self) {
		sp_io::misc::print_num(*self);
	}
}
impl Printable for &[u8] {
	fn print(&self) {
		sp_io::misc::print_hex(self);
	}
}
impl<const N: usize> Printable for [u8; N] {
	fn print(&self) {
		sp_io::misc::print_hex(&self[..]);
	}
}
impl Printable for &str {
	fn print(&self) {
		sp_io::misc::print_utf8(self.as_bytes());
	}
}
impl Printable for bool {
	fn print(&self) {
		if *self {
			"true".print()
		} else {
			"false".print()
		}
	}
}
impl Printable for sp_weights::Weight {
	fn print(&self) {
		self.ref_time().print()
	}
}
impl Printable for () {
	fn print(&self) {
		"()".print()
	}
}
#[impl_for_tuples(1, 12)]
impl Printable for Tuple {
	fn print(&self) {
		for_tuples!( #( Tuple.print(); )* )
	}
}
/// Something that can convert a [`BlockId`](crate::generic::BlockId) to a number or a hash.
#[cfg(feature = "std")]
pub trait BlockIdTo<Block: self::Block> {
	/// The error type that will be returned by the functions.
	type Error: std::error::Error;
	/// Convert the given `block_id` to the corresponding block hash.
	fn to_hash(
		&self,
		block_id: &crate::generic::BlockId<Block>,
	) -> Result<Option<Block::Hash>, Self::Error>;
	/// Convert the given `block_id` to the corresponding block number.
	fn to_number(
		&self,
		block_id: &crate::generic::BlockId<Block>,
	) -> Result<Option<NumberFor<Block>>, Self::Error>;
}
/// Get current block number
pub trait BlockNumberProvider {
	/// Type of `BlockNumber` to provide.
	type BlockNumber: Codec
		+ Clone
		+ Ord
		+ Eq
		+ AtLeast32BitUnsigned
		+ TypeInfo
		+ Debug
		+ MaxEncodedLen
		+ Copy;
	/// Returns the current block number.
	///
	/// Provides an abstraction over an arbitrary way of providing the
	/// current block number.
	///
	/// In case of using crate `sp_runtime` with the crate `frame-system`,
	/// it is already implemented for
	/// `frame_system::Pallet<T: Config>` as:
	///
	/// ```ignore
	/// fn current_block_number() -> Self {
	///     frame_system::Pallet<Config>::block_number()
	/// }
	/// ```
	/// .
	fn current_block_number() -> Self::BlockNumber;
	/// Utility function only to be used in benchmarking scenarios or tests, to be implemented
	/// optionally, else a noop.
	///
	/// It allows for setting the block number that will later be fetched
	/// This is useful in case the block number provider is different than System
	#[cfg(any(feature = "std", feature = "runtime-benchmarks"))]
	fn set_block_number(_block: Self::BlockNumber) {}
}
impl BlockNumberProvider for () {
	type BlockNumber = u32;
	fn current_block_number() -> Self::BlockNumber {
		0
	}
}
#[cfg(test)]
mod tests {
	use super::*;
	use crate::codec::{Decode, Encode, Input};
	#[cfg(feature = "bls-experimental")]
	use sp_core::{bls377, bls381};
	use sp_core::{
		crypto::{Pair, UncheckedFrom},
		ecdsa, ed25519, sr25519,
	};
	macro_rules! signature_verify_test {
		($algorithm:ident) => {
			let msg = &b"test-message"[..];
			let wrong_msg = &b"test-msg"[..];
			let (pair, _) = $algorithm::Pair::generate();
			let signature = pair.sign(&msg);
			assert!($algorithm::Pair::verify(&signature, msg, &pair.public()));
			assert!(signature.verify(msg, &pair.public()));
			assert!(!signature.verify(wrong_msg, &pair.public()));
		};
	}
	mod t {
		use sp_application_crypto::{app_crypto, sr25519};
		use sp_core::crypto::KeyTypeId;
		app_crypto!(sr25519, KeyTypeId(*b"test"));
	}
	#[test]
	fn app_verify_works() {
		use super::AppVerify;
		use t::*;
		let s = Signature::try_from(vec![0; 64]).unwrap();
		let _ = s.verify(&[0u8; 100][..], &Public::unchecked_from([0; 32]));
	}
	#[derive(Encode, Decode, Default, PartialEq, Debug)]
	struct U128Value(u128);
	impl super::TypeId for U128Value {
		const TYPE_ID: [u8; 4] = [0x0d, 0xf0, 0x0d, 0xf0];
	}
	// f00df00d
	#[derive(Encode, Decode, Default, PartialEq, Debug)]
	struct U32Value(u32);
	impl super::TypeId for U32Value {
		const TYPE_ID: [u8; 4] = [0x0d, 0xf0, 0xfe, 0xca];
	}
	// cafef00d
	#[derive(Encode, Decode, Default, PartialEq, Debug)]
	struct U16Value(u16);
	impl super::TypeId for U16Value {
		const TYPE_ID: [u8; 4] = [0xfe, 0xca, 0x0d, 0xf0];
	}
	// f00dcafe
	type AccountId = u64;
	#[test]
	fn into_account_truncating_should_work() {
		let r: AccountId = U32Value::into_account_truncating(&U32Value(0xdeadbeef));
		assert_eq!(r, 0x_deadbeef_cafef00d);
	}
	#[test]
	fn try_into_account_should_work() {
		let r: AccountId = U32Value::try_into_account(&U32Value(0xdeadbeef)).unwrap();
		assert_eq!(r, 0x_deadbeef_cafef00d);
		// u128 is bigger than u64 would fit
		let maybe: Option<AccountId> = U128Value::try_into_account(&U128Value(u128::MAX));
		assert!(maybe.is_none());
	}
	#[test]
	fn try_from_account_should_work() {
		let r = U32Value::try_from_account(&0x_deadbeef_cafef00d_u64);
		assert_eq!(r.unwrap(), U32Value(0xdeadbeef));
	}
	#[test]
	fn into_account_truncating_with_fill_should_work() {
		let r: AccountId = U16Value::into_account_truncating(&U16Value(0xc0da));
		assert_eq!(r, 0x_0000_c0da_f00dcafe);
	}
	#[test]
	fn try_into_sub_account_should_work() {
		let r: AccountId = U16Value::try_into_account(&U16Value(0xc0da)).unwrap();
		assert_eq!(r, 0x_0000_c0da_f00dcafe);
		let maybe: Option<AccountId> = U16Value::try_into_sub_account(
			&U16Value(0xc0da),
			"a really large amount of additional encoded information which will certainly overflow the account id type ;)"
		);
		assert!(maybe.is_none())
	}
	#[test]
	fn try_from_account_with_fill_should_work() {
		let r = U16Value::try_from_account(&0x0000_c0da_f00dcafe_u64);
		assert_eq!(r.unwrap(), U16Value(0xc0da));
	}
	#[test]
	fn bad_try_from_account_should_fail() {
		let r = U16Value::try_from_account(&0x0000_c0de_baadcafe_u64);
		assert!(r.is_none());
		let r = U16Value::try_from_account(&0x0100_c0da_f00dcafe_u64);
		assert!(r.is_none());
	}
	#[test]
	fn trailing_zero_should_work() {
		let mut t = super::TrailingZeroInput(&[1, 2, 3]);
		assert_eq!(t.remaining_len(), Ok(None));
		let mut buffer = [0u8; 2];
		assert_eq!(t.read(&mut buffer), Ok(()));
		assert_eq!(t.remaining_len(), Ok(None));
		assert_eq!(buffer, [1, 2]);
		assert_eq!(t.read(&mut buffer), Ok(()));
		assert_eq!(t.remaining_len(), Ok(None));
		assert_eq!(buffer, [3, 0]);
		assert_eq!(t.read(&mut buffer), Ok(()));
		assert_eq!(t.remaining_len(), Ok(None));
		assert_eq!(buffer, [0, 0]);
	}
	#[test]
	fn ed25519_verify_works() {
		signature_verify_test!(ed25519);
	}
	#[test]
	fn sr25519_verify_works() {
		signature_verify_test!(sr25519);
	}
	#[test]
	fn ecdsa_verify_works() {
		signature_verify_test!(ecdsa);
	}
	#[cfg(feature = "bls-experimental")]
	fn bls377_verify_works() {
		signature_verify_test!(bls377)
	}
	#[cfg(feature = "bls-experimental")]
	fn bls381_verify_works() {
		signature_verify_test!(bls381)
	}
}