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
//! # Substrate Runtime Primitives.
19
//!
20
//! This crate, among other things, contains a large library of types and utilities that are used in
21
//! the Substrate runtime, but are not particularly `FRAME`-oriented.
22
//!
23
//! ## Block, Header and Extrinsics
24
//!
25
//! Most notable, this crate contains some of the types and trait that enable important
26
//! communication between the client and the runtime. This includes:
27
//!
28
//! - A set of traits to declare what any block/header/extrinsic type should provide.
29
//! 	- [`traits::Block`], [`traits::Header`], [`traits::Extrinsic`]
30
//! - A set of types that implement these traits, whilst still providing a high degree of
31
//!   configurability via generics.
32
//! 	- [`generic::Block`], [`generic::Header`], [`generic::UncheckedExtrinsic`] and
33
//!    [`generic::CheckedExtrinsic`]
34
//!
35
//! ## Runtime API Types
36
//!
37
//! This crate also contains some types that are often used in conjuncture with Runtime APIs. Most
38
//! notable:
39
//!
40
//! - [`ApplyExtrinsicResult`], and [`DispatchOutcome`], which dictate how the client and runtime
41
//!   communicate about the success or failure of an extrinsic.
42
//! - [`transaction_validity`], which dictates how the client and runtime communicate about the
43
//!  validity of an extrinsic while still in the transaction-queue.
44

            
45
#![warn(missing_docs)]
46
#![cfg_attr(not(feature = "std"), no_std)]
47

            
48
#[doc(hidden)]
49
extern crate alloc;
50

            
51
#[doc(hidden)]
52
pub use alloc::vec::Vec;
53
#[doc(hidden)]
54
pub use codec;
55
#[doc(hidden)]
56
pub use scale_info;
57
#[cfg(feature = "serde")]
58
#[doc(hidden)]
59
pub use serde;
60
#[doc(hidden)]
61
pub use sp_std;
62

            
63
#[doc(hidden)]
64
pub use paste;
65
#[doc(hidden)]
66
pub use sp_arithmetic::traits::Saturating;
67

            
68
#[doc(hidden)]
69
pub use sp_application_crypto as app_crypto;
70

            
71
pub use sp_core::storage::StateVersion;
72
#[cfg(feature = "std")]
73
pub use sp_core::storage::{Storage, StorageChild};
74

            
75
use sp_core::{
76
	crypto::{self, ByteArray, FromEntropy},
77
	ecdsa, ed25519,
78
	hash::{H256, H512},
79
	sr25519,
80
};
81

            
82
#[cfg(all(not(feature = "std"), feature = "serde"))]
83
use alloc::format;
84
use alloc::vec;
85
use codec::{Decode, Encode, MaxEncodedLen};
86
use scale_info::TypeInfo;
87

            
88
pub mod curve;
89
pub mod generic;
90
pub mod legacy;
91
mod multiaddress;
92
pub mod offchain;
93
pub mod runtime_logger;
94
mod runtime_string;
95
#[cfg(feature = "std")]
96
pub mod testing;
97
pub mod traits;
98
pub mod transaction_validity;
99
pub mod type_with_default;
100

            
101
pub use crate::runtime_string::*;
102

            
103
// Re-export Multiaddress
104
pub use multiaddress::MultiAddress;
105

            
106
/// Re-export these since they're only "kind of" generic.
107
pub use generic::{Digest, DigestItem};
108

            
109
pub use sp_application_crypto::{BoundToRuntimeAppPublic, RuntimeAppPublic};
110
/// Re-export this since it's part of the API of this crate.
111
pub use sp_core::{
112
	bounded::{BoundedBTreeMap, BoundedBTreeSet, BoundedSlice, BoundedVec, WeakBoundedVec},
113
	crypto::{key_types, AccountId32, CryptoType, CryptoTypeId, KeyTypeId},
114
	TypeId,
115
};
116
/// Re-export bounded_vec and bounded_btree_map macros only when std is enabled.
117
#[cfg(feature = "std")]
118
pub use sp_core::{bounded_btree_map, bounded_vec};
119

            
120
/// Re-export `RuntimeDebug`, to avoid dependency clutter.
121
pub use sp_core::RuntimeDebug;
122

            
123
/// Re-export big_uint stuff.
124
pub use sp_arithmetic::biguint;
125
/// Re-export 128 bit helpers.
126
pub use sp_arithmetic::helpers_128bit;
127
/// Re-export top-level arithmetic stuff.
128
pub use sp_arithmetic::{
129
	traits::SaturatedConversion, ArithmeticError, FixedI128, FixedI64, FixedPointNumber,
130
	FixedPointOperand, FixedU128, FixedU64, InnerOf, PerThing, PerU16, Perbill, Percent, Permill,
131
	Perquintill, Rational128, Rounding, UpperOf,
132
};
133

            
134
pub use either::Either;
135

            
136
/// The number of bytes of the module-specific `error` field defined in [`ModuleError`].
137
/// In FRAME, this is the maximum encoded size of a pallet error type.
138
pub const MAX_MODULE_ERROR_ENCODED_SIZE: usize = 4;
139

            
140
/// An abstraction over justification for a block's validity under a consensus algorithm.
141
///
142
/// Essentially a finality proof. The exact formulation will vary between consensus
143
/// algorithms. In the case where there are multiple valid proofs, inclusion within
144
/// the block itself would allow swapping justifications to change the block's hash
145
/// (and thus fork the chain). Sending a `Justification` alongside a block instead
146
/// bypasses this problem.
147
///
148
/// Each justification is provided as an encoded blob, and is tagged with an ID
149
/// to identify the consensus engine that generated the proof (we might have
150
/// multiple justifications from different engines for the same block).
151
pub type Justification = (ConsensusEngineId, EncodedJustification);
152

            
153
/// The encoded justification specific to a consensus engine.
154
pub type EncodedJustification = Vec<u8>;
155

            
156
/// Collection of justifications for a given block, multiple justifications may
157
/// be provided by different consensus engines for the same block.
158
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
159
#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
160
pub struct Justifications(Vec<Justification>);
161

            
162
impl Justifications {
163
	/// Return an iterator over the justifications.
164
	pub fn iter(&self) -> impl Iterator<Item = &Justification> {
165
		self.0.iter()
166
	}
167

            
168
	/// Append a justification. Returns false if a justification with the same
169
	/// `ConsensusEngineId` already exists, in which case the justification is
170
	/// not inserted.
171
	pub fn append(&mut self, justification: Justification) -> bool {
172
		if self.get(justification.0).is_some() {
173
			return false
174
		}
175
		self.0.push(justification);
176
		true
177
	}
178

            
179
	/// Return the encoded justification for the given consensus engine, if it
180
	/// exists.
181
	pub fn get(&self, engine_id: ConsensusEngineId) -> Option<&EncodedJustification> {
182
		self.iter().find(|j| j.0 == engine_id).map(|j| &j.1)
183
	}
184

            
185
	/// Remove the encoded justification for the given consensus engine, if it exists.
186
	pub fn remove(&mut self, engine_id: ConsensusEngineId) {
187
		self.0.retain(|j| j.0 != engine_id)
188
	}
189

            
190
	/// Return a copy of the encoded justification for the given consensus
191
	/// engine, if it exists.
192
	pub fn into_justification(self, engine_id: ConsensusEngineId) -> Option<EncodedJustification> {
193
		self.into_iter().find(|j| j.0 == engine_id).map(|j| j.1)
194
	}
195
}
196

            
197
impl IntoIterator for Justifications {
198
	type Item = Justification;
199
	type IntoIter = alloc::vec::IntoIter<Self::Item>;
200

            
201
	fn into_iter(self) -> Self::IntoIter {
202
		self.0.into_iter()
203
	}
204
}
205

            
206
impl From<Justification> for Justifications {
207
	fn from(justification: Justification) -> Self {
208
		Self(vec![justification])
209
	}
210
}
211

            
212
use traits::{Lazy, Verify};
213

            
214
use crate::traits::IdentifyAccount;
215
#[cfg(feature = "serde")]
216
pub use serde::{de::DeserializeOwned, Deserialize, Serialize};
217

            
218
/// Complex storage builder stuff.
219
#[cfg(feature = "std")]
220
pub trait BuildStorage {
221
	/// Build the storage out of this builder.
222
3
	fn build_storage(&self) -> Result<sp_core::storage::Storage, String> {
223
3
		let mut storage = Default::default();
224
3
		self.assimilate_storage(&mut storage)?;
225
3
		Ok(storage)
226
3
	}
227
	/// Assimilate the storage for this module into pre-existing overlays.
228
	fn assimilate_storage(&self, storage: &mut sp_core::storage::Storage) -> Result<(), String>;
229
}
230

            
231
/// Something that can build the genesis storage of a module.
232
#[cfg(feature = "std")]
233
#[deprecated(
234
	note = "`BuildModuleGenesisStorage` is planned to be removed in December 2023. Use `BuildStorage` instead of it."
235
)]
236
pub trait BuildModuleGenesisStorage<T, I>: Sized {
237
	/// Create the module genesis storage into the given `storage` and `child_storage`.
238
	fn build_module_genesis_storage(
239
		&self,
240
		storage: &mut sp_core::storage::Storage,
241
	) -> Result<(), String>;
242
}
243

            
244
#[cfg(feature = "std")]
245
impl BuildStorage for sp_core::storage::Storage {
246
	fn assimilate_storage(&self, storage: &mut sp_core::storage::Storage) -> Result<(), String> {
247
		storage.top.extend(self.top.iter().map(|(k, v)| (k.clone(), v.clone())));
248
		for (k, other_map) in self.children_default.iter() {
249
			let k = k.clone();
250
			if let Some(map) = storage.children_default.get_mut(&k) {
251
				map.data.extend(other_map.data.iter().map(|(k, v)| (k.clone(), v.clone())));
252
				if !map.child_info.try_update(&other_map.child_info) {
253
					return Err("Incompatible child info update".to_string())
254
				}
255
			} else {
256
				storage.children_default.insert(k, other_map.clone());
257
			}
258
		}
259
		Ok(())
260
	}
261
}
262

            
263
#[cfg(feature = "std")]
264
impl BuildStorage for () {
265
	fn assimilate_storage(&self, _: &mut sp_core::storage::Storage) -> Result<(), String> {
266
		Err("`assimilate_storage` not implemented for `()`".into())
267
	}
268
}
269

            
270
/// Consensus engine unique ID.
271
pub type ConsensusEngineId = [u8; 4];
272

            
273
/// Signature verify that can work with any known signature types.
274
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
275
18
#[derive(Eq, PartialEq, Clone, Encode, Decode, MaxEncodedLen, RuntimeDebug, TypeInfo)]
276
pub enum MultiSignature {
277
357
	/// An Ed25519 signature.
278
357
	Ed25519(ed25519::Signature),
279
90
	/// An Sr25519 signature.
280
90
	Sr25519(sr25519::Signature),
281
39
	/// An ECDSA/SECP256k1 signature.
282
39
	Ecdsa(ecdsa::Signature),
283
}
284

            
285
impl From<ed25519::Signature> for MultiSignature {
286
	fn from(x: ed25519::Signature) -> Self {
287
		Self::Ed25519(x)
288
	}
289
}
290

            
291
impl TryFrom<MultiSignature> for ed25519::Signature {
292
	type Error = ();
293
	fn try_from(m: MultiSignature) -> Result<Self, Self::Error> {
294
		if let MultiSignature::Ed25519(x) = m {
295
			Ok(x)
296
		} else {
297
			Err(())
298
		}
299
	}
300
}
301

            
302
impl From<sr25519::Signature> for MultiSignature {
303
	fn from(x: sr25519::Signature) -> Self {
304
		Self::Sr25519(x)
305
	}
306
}
307

            
308
impl TryFrom<MultiSignature> for sr25519::Signature {
309
	type Error = ();
310
	fn try_from(m: MultiSignature) -> Result<Self, Self::Error> {
311
		if let MultiSignature::Sr25519(x) = m {
312
			Ok(x)
313
		} else {
314
			Err(())
315
		}
316
	}
317
}
318

            
319
impl From<ecdsa::Signature> for MultiSignature {
320
	fn from(x: ecdsa::Signature) -> Self {
321
		Self::Ecdsa(x)
322
	}
323
}
324

            
325
impl TryFrom<MultiSignature> for ecdsa::Signature {
326
	type Error = ();
327
	fn try_from(m: MultiSignature) -> Result<Self, Self::Error> {
328
		if let MultiSignature::Ecdsa(x) = m {
329
			Ok(x)
330
		} else {
331
			Err(())
332
		}
333
	}
334
}
335

            
336
/// Public key for any known crypto algorithm.
337
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
338
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
339
pub enum MultiSigner {
340
	/// An Ed25519 identity.
341
	Ed25519(ed25519::Public),
342
	/// An Sr25519 identity.
343
	Sr25519(sr25519::Public),
344
	/// An SECP256k1/ECDSA identity (actually, the Blake2 hash of the compressed pub key).
345
	Ecdsa(ecdsa::Public),
346
}
347

            
348
impl FromEntropy for MultiSigner {
349
	fn from_entropy(input: &mut impl codec::Input) -> Result<Self, codec::Error> {
350
		Ok(match input.read_byte()? % 3 {
351
			0 => Self::Ed25519(FromEntropy::from_entropy(input)?),
352
			1 => Self::Sr25519(FromEntropy::from_entropy(input)?),
353
			2.. => Self::Ecdsa(FromEntropy::from_entropy(input)?),
354
		})
355
	}
356
}
357

            
358
/// NOTE: This implementations is required by `SimpleAddressDeterminer`,
359
/// we convert the hash into some AccountId, it's fine to use any scheme.
360
impl<T: Into<H256>> crypto::UncheckedFrom<T> for MultiSigner {
361
	fn unchecked_from(x: T) -> Self {
362
		ed25519::Public::unchecked_from(x.into()).into()
363
	}
364
}
365

            
366
impl AsRef<[u8]> for MultiSigner {
367
	fn as_ref(&self) -> &[u8] {
368
		match *self {
369
			Self::Ed25519(ref who) => who.as_ref(),
370
			Self::Sr25519(ref who) => who.as_ref(),
371
			Self::Ecdsa(ref who) => who.as_ref(),
372
		}
373
	}
374
}
375

            
376
impl traits::IdentifyAccount for MultiSigner {
377
	type AccountId = AccountId32;
378
32
	fn into_account(self) -> AccountId32 {
379
32
		match self {
380
			Self::Ed25519(who) => <[u8; 32]>::from(who).into(),
381
32
			Self::Sr25519(who) => <[u8; 32]>::from(who).into(),
382
			Self::Ecdsa(who) => sp_io::hashing::blake2_256(who.as_ref()).into(),
383
		}
384
32
	}
385
}
386

            
387
impl From<ed25519::Public> for MultiSigner {
388
	fn from(x: ed25519::Public) -> Self {
389
		Self::Ed25519(x)
390
	}
391
}
392

            
393
impl TryFrom<MultiSigner> for ed25519::Public {
394
	type Error = ();
395
	fn try_from(m: MultiSigner) -> Result<Self, Self::Error> {
396
		if let MultiSigner::Ed25519(x) = m {
397
			Ok(x)
398
		} else {
399
			Err(())
400
		}
401
	}
402
}
403

            
404
impl From<sr25519::Public> for MultiSigner {
405
64
	fn from(x: sr25519::Public) -> Self {
406
64
		Self::Sr25519(x)
407
64
	}
408
}
409

            
410
impl TryFrom<MultiSigner> for sr25519::Public {
411
	type Error = ();
412
	fn try_from(m: MultiSigner) -> Result<Self, Self::Error> {
413
		if let MultiSigner::Sr25519(x) = m {
414
			Ok(x)
415
		} else {
416
			Err(())
417
		}
418
	}
419
}
420

            
421
impl From<ecdsa::Public> for MultiSigner {
422
	fn from(x: ecdsa::Public) -> Self {
423
		Self::Ecdsa(x)
424
	}
425
}
426

            
427
impl TryFrom<MultiSigner> for ecdsa::Public {
428
	type Error = ();
429
	fn try_from(m: MultiSigner) -> Result<Self, Self::Error> {
430
		if let MultiSigner::Ecdsa(x) = m {
431
			Ok(x)
432
		} else {
433
			Err(())
434
		}
435
	}
436
}
437

            
438
#[cfg(feature = "std")]
439
impl std::fmt::Display for MultiSigner {
440
	fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
441
		match *self {
442
			Self::Ed25519(ref who) => write!(fmt, "ed25519: {}", who),
443
			Self::Sr25519(ref who) => write!(fmt, "sr25519: {}", who),
444
			Self::Ecdsa(ref who) => write!(fmt, "ecdsa: {}", who),
445
		}
446
	}
447
}
448

            
449
impl Verify for MultiSignature {
450
	type Signer = MultiSigner;
451
	fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &AccountId32) -> bool {
452
		match (self, signer) {
453
			(Self::Ed25519(ref sig), who) => match ed25519::Public::from_slice(who.as_ref()) {
454
				Ok(signer) => sig.verify(msg, &signer),
455
				Err(()) => false,
456
			},
457
			(Self::Sr25519(ref sig), who) => match sr25519::Public::from_slice(who.as_ref()) {
458
				Ok(signer) => sig.verify(msg, &signer),
459
				Err(()) => false,
460
			},
461
			(Self::Ecdsa(ref sig), who) => {
462
				let m = sp_io::hashing::blake2_256(msg.get());
463
				match sp_io::crypto::secp256k1_ecdsa_recover_compressed(sig.as_ref(), &m) {
464
					Ok(pubkey) =>
465
						&sp_io::hashing::blake2_256(pubkey.as_ref()) ==
466
							<dyn AsRef<[u8; 32]>>::as_ref(who),
467
					_ => false,
468
				}
469
			},
470
		}
471
	}
472
}
473

            
474
/// Signature verify that can work with any known signature types..
475
#[derive(Eq, PartialEq, Clone, Default, Encode, Decode, RuntimeDebug, TypeInfo)]
476
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
477
pub struct AnySignature(H512);
478

            
479
impl Verify for AnySignature {
480
	type Signer = sr25519::Public;
481
	fn verify<L: Lazy<[u8]>>(&self, mut msg: L, signer: &sr25519::Public) -> bool {
482
		let msg = msg.get();
483
		sr25519::Signature::try_from(self.0.as_fixed_bytes().as_ref())
484
			.map(|s| s.verify(msg, signer))
485
			.unwrap_or(false) ||
486
			ed25519::Signature::try_from(self.0.as_fixed_bytes().as_ref())
487
				.map(|s| match ed25519::Public::from_slice(signer.as_ref()) {
488
					Err(()) => false,
489
					Ok(signer) => s.verify(msg, &signer),
490
				})
491
				.unwrap_or(false)
492
	}
493
}
494

            
495
impl From<sr25519::Signature> for AnySignature {
496
	fn from(s: sr25519::Signature) -> Self {
497
		Self(s.into())
498
	}
499
}
500

            
501
impl From<ed25519::Signature> for AnySignature {
502
	fn from(s: ed25519::Signature) -> Self {
503
		Self(s.into())
504
	}
505
}
506

            
507
impl From<DispatchError> for DispatchOutcome {
508
	fn from(err: DispatchError) -> Self {
509
		Err(err)
510
	}
511
}
512

            
513
/// This is the legacy return type of `Dispatchable`. It is still exposed for compatibility reasons.
514
/// The new return type is `DispatchResultWithInfo`. FRAME runtimes should use
515
/// `frame_support::dispatch::DispatchResult`.
516
pub type DispatchResult = core::result::Result<(), DispatchError>;
517

            
518
/// Return type of a `Dispatchable` which contains the `DispatchResult` and additional information
519
/// about the `Dispatchable` that is only known post dispatch.
520
pub type DispatchResultWithInfo<T> = core::result::Result<T, DispatchErrorWithPostInfo<T>>;
521

            
522
/// Reason why a pallet call failed.
523
#[derive(Eq, Clone, Copy, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)]
524
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
525
pub struct ModuleError {
526
	/// Module index, matching the metadata module index.
527
	pub index: u8,
528
	/// Module specific error value.
529
	pub error: [u8; MAX_MODULE_ERROR_ENCODED_SIZE],
530
	/// Optional error message.
531
	#[codec(skip)]
532
	#[cfg_attr(feature = "serde", serde(skip_deserializing))]
533
	pub message: Option<&'static str>,
534
}
535

            
536
impl PartialEq for ModuleError {
537
	fn eq(&self, other: &Self) -> bool {
538
		(self.index == other.index) && (self.error == other.error)
539
	}
540
}
541

            
542
/// Errors related to transactional storage layers.
543
#[derive(Eq, PartialEq, Clone, Copy, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)]
544
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
545
pub enum TransactionalError {
546
	/// Too many transactional layers have been spawned.
547
	LimitReached,
548
	/// A transactional layer was expected, but does not exist.
549
	NoLayer,
550
}
551

            
552
impl From<TransactionalError> for &'static str {
553
	fn from(e: TransactionalError) -> &'static str {
554
		match e {
555
			TransactionalError::LimitReached => "Too many transactional layers have been spawned",
556
			TransactionalError::NoLayer => "A transactional layer was expected, but does not exist",
557
		}
558
	}
559
}
560

            
561
impl From<TransactionalError> for DispatchError {
562
	fn from(e: TransactionalError) -> DispatchError {
563
		Self::Transactional(e)
564
	}
565
}
566

            
567
/// Reason why a dispatch call failed.
568
#[derive(Eq, Clone, Copy, Encode, Decode, Debug, TypeInfo, PartialEq, MaxEncodedLen)]
569
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
570
pub enum DispatchError {
571
	/// Some error occurred.
572
	Other(
573
		#[codec(skip)]
574
		#[cfg_attr(feature = "serde", serde(skip_deserializing))]
575
		&'static str,
576
	),
577
	/// Failed to lookup some data.
578
	CannotLookup,
579
	/// A bad origin.
580
	BadOrigin,
581
	/// A custom error in a module.
582
	Module(ModuleError),
583
	/// At least one consumer is remaining so the account cannot be destroyed.
584
	ConsumerRemaining,
585
	/// There are no providers so the account cannot be created.
586
	NoProviders,
587
	/// There are too many consumers so the account cannot be created.
588
	TooManyConsumers,
589
	/// An error to do with tokens.
590
	Token(TokenError),
591
	/// An arithmetic error.
592
	Arithmetic(ArithmeticError),
593
	/// The number of transactional layers has been reached, or we are not in a transactional
594
	/// layer.
595
	Transactional(TransactionalError),
596
	/// Resources exhausted, e.g. attempt to read/write data which is too large to manipulate.
597
	Exhausted,
598
	/// The state is corrupt; this is generally not going to fix itself.
599
	Corruption,
600
	/// Some resource (e.g. a preimage) is unavailable right now. This might fix itself later.
601
	Unavailable,
602
	/// Root origin is not allowed.
603
	RootNotAllowed,
604
}
605

            
606
/// Result of a `Dispatchable` which contains the `DispatchResult` and additional information about
607
/// the `Dispatchable` that is only known post dispatch.
608
#[derive(Eq, PartialEq, Clone, Copy, Encode, Decode, RuntimeDebug, TypeInfo)]
609
pub struct DispatchErrorWithPostInfo<Info>
610
where
611
	Info: Eq + PartialEq + Clone + Copy + Encode + Decode + traits::Printable,
612
{
613
	/// Additional information about the `Dispatchable` which is only known post dispatch.
614
	pub post_info: Info,
615
	/// The actual `DispatchResult` indicating whether the dispatch was successful.
616
	pub error: DispatchError,
617
}
618

            
619
impl DispatchError {
620
	/// Return the same error but without the attached message.
621
	pub fn stripped(self) -> Self {
622
		match self {
623
			DispatchError::Module(ModuleError { index, error, message: Some(_) }) =>
624
				DispatchError::Module(ModuleError { index, error, message: None }),
625
			m => m,
626
		}
627
	}
628
}
629

            
630
impl<T, E> From<E> for DispatchErrorWithPostInfo<T>
631
where
632
	T: Eq + PartialEq + Clone + Copy + Encode + Decode + traits::Printable + Default,
633
	E: Into<DispatchError>,
634
{
635
142350
	fn from(error: E) -> Self {
636
142350
		Self { post_info: Default::default(), error: error.into() }
637
142350
	}
638
}
639

            
640
impl From<crate::traits::LookupError> for DispatchError {
641
5670
	fn from(_: crate::traits::LookupError) -> Self {
642
5670
		Self::CannotLookup
643
5670
	}
644
}
645

            
646
impl From<crate::traits::BadOrigin> for DispatchError {
647
134886
	fn from(_: crate::traits::BadOrigin) -> Self {
648
134886
		Self::BadOrigin
649
134886
	}
650
}
651

            
652
/// Description of what went wrong when trying to complete an operation on a token.
653
#[derive(Eq, PartialEq, Clone, Copy, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)]
654
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
655
pub enum TokenError {
656
	/// Funds are unavailable.
657
	FundsUnavailable,
658
	/// Some part of the balance gives the only provider reference to the account and thus cannot
659
	/// be (re)moved.
660
	OnlyProvider,
661
	/// Account cannot exist with the funds that would be given.
662
	BelowMinimum,
663
	/// Account cannot be created.
664
	CannotCreate,
665
	/// The asset in question is unknown.
666
	UnknownAsset,
667
	/// Funds exist but are frozen.
668
	Frozen,
669
	/// Operation is not supported by the asset.
670
	Unsupported,
671
	/// Account cannot be created for a held balance.
672
	CannotCreateHold,
673
	/// Withdrawal would cause unwanted loss of account.
674
	NotExpendable,
675
	/// Account cannot receive the assets.
676
	Blocked,
677
}
678

            
679
impl From<TokenError> for &'static str {
680
6
	fn from(e: TokenError) -> &'static str {
681
6
		match e {
682
2
			TokenError::FundsUnavailable => "Funds are unavailable",
683
			TokenError::OnlyProvider => "Account that must exist would die",
684
4
			TokenError::BelowMinimum => "Account cannot exist with the funds that would be given",
685
			TokenError::CannotCreate => "Account cannot be created",
686
			TokenError::UnknownAsset => "The asset in question is unknown",
687
			TokenError::Frozen => "Funds exist but are frozen",
688
			TokenError::Unsupported => "Operation is not supported by the asset",
689
			TokenError::CannotCreateHold =>
690
				"Account cannot be created for recording amount on hold",
691
			TokenError::NotExpendable => "Account that is desired to remain would die",
692
			TokenError::Blocked => "Account cannot receive the assets",
693
		}
694
6
	}
695
}
696

            
697
impl From<TokenError> for DispatchError {
698
1440
	fn from(e: TokenError) -> DispatchError {
699
1440
		Self::Token(e)
700
1440
	}
701
}
702

            
703
impl From<ArithmeticError> for DispatchError {
704
804
	fn from(e: ArithmeticError) -> DispatchError {
705
804
		Self::Arithmetic(e)
706
804
	}
707
}
708

            
709
impl From<&'static str> for DispatchError {
710
	fn from(err: &'static str) -> DispatchError {
711
		Self::Other(err)
712
	}
713
}
714

            
715
impl From<DispatchError> for &'static str {
716
8
	fn from(err: DispatchError) -> &'static str {
717
		use DispatchError::*;
718
8
		match err {
719
			Other(msg) => msg,
720
			CannotLookup => "Cannot lookup",
721
			BadOrigin => "Bad origin",
722
			Module(ModuleError { message, .. }) => message.unwrap_or("Unknown module error"),
723
			ConsumerRemaining => "Consumer remaining",
724
			NoProviders => "No providers",
725
			TooManyConsumers => "Too many consumers",
726
6
			Token(e) => e.into(),
727
2
			Arithmetic(e) => e.into(),
728
			Transactional(e) => e.into(),
729
			Exhausted => "Resources exhausted",
730
			Corruption => "State corrupt",
731
			Unavailable => "Resource unavailable",
732
			RootNotAllowed => "Root not allowed",
733
		}
734
8
	}
735
}
736

            
737
impl<T> From<DispatchErrorWithPostInfo<T>> for &'static str
738
where
739
	T: Eq + PartialEq + Clone + Copy + Encode + Decode + traits::Printable,
740
{
741
	fn from(err: DispatchErrorWithPostInfo<T>) -> &'static str {
742
		err.error.into()
743
	}
744
}
745

            
746
impl traits::Printable for DispatchError {
747
	fn print(&self) {
748
		use DispatchError::*;
749
		"DispatchError".print();
750
		match self {
751
			Other(err) => err.print(),
752
			CannotLookup => "Cannot lookup".print(),
753
			BadOrigin => "Bad origin".print(),
754
			Module(ModuleError { index, error, message }) => {
755
				index.print();
756
				error.print();
757
				if let Some(msg) = message {
758
					msg.print();
759
				}
760
			},
761
			ConsumerRemaining => "Consumer remaining".print(),
762
			NoProviders => "No providers".print(),
763
			TooManyConsumers => "Too many consumers".print(),
764
			Token(e) => {
765
				"Token error: ".print();
766
				<&'static str>::from(*e).print();
767
			},
768
			Arithmetic(e) => {
769
				"Arithmetic error: ".print();
770
				<&'static str>::from(*e).print();
771
			},
772
			Transactional(e) => {
773
				"Transactional error: ".print();
774
				<&'static str>::from(*e).print();
775
			},
776
			Exhausted => "Resources exhausted".print(),
777
			Corruption => "State corrupt".print(),
778
			Unavailable => "Resource unavailable".print(),
779
			RootNotAllowed => "Root not allowed".print(),
780
		}
781
	}
782
}
783

            
784
impl<T> traits::Printable for DispatchErrorWithPostInfo<T>
785
where
786
	T: Eq + PartialEq + Clone + Copy + Encode + Decode + traits::Printable,
787
{
788
	fn print(&self) {
789
		self.error.print();
790
		"PostInfo: ".print();
791
		self.post_info.print();
792
	}
793
}
794

            
795
/// This type specifies the outcome of dispatching a call to a module.
796
///
797
/// In case of failure an error specific to the module is returned.
798
///
799
/// Failure of the module call dispatching doesn't invalidate the extrinsic and it is still included
800
/// in the block, therefore all state changes performed by the dispatched call are still persisted.
801
///
802
/// For example, if the dispatching of an extrinsic involves inclusion fee payment then these
803
/// changes are going to be preserved even if the call dispatched failed.
804
pub type DispatchOutcome = Result<(), DispatchError>;
805

            
806
/// The result of applying of an extrinsic.
807
///
808
/// This type is typically used in the context of `BlockBuilder` to signal that the extrinsic
809
/// in question cannot be included.
810
///
811
/// A block containing extrinsics that have a negative inclusion outcome is invalid. A negative
812
/// result can only occur during the block production, where such extrinsics are detected and
813
/// removed from the block that is being created and the transaction pool.
814
///
815
/// To rehash: every extrinsic in a valid block must return a positive `ApplyExtrinsicResult`.
816
///
817
/// Examples of reasons preventing inclusion in a block:
818
/// - More block weight is required to process the extrinsic than is left in the block being built.
819
///   This doesn't necessarily mean that the extrinsic is invalid, since it can still be included in
820
///   the next block if it has enough spare weight available.
821
/// - The sender doesn't have enough funds to pay the transaction inclusion fee. Including such a
822
///   transaction in the block doesn't make sense.
823
/// - The extrinsic supplied a bad signature. This transaction won't become valid ever.
824
pub type ApplyExtrinsicResult =
825
	Result<DispatchOutcome, transaction_validity::TransactionValidityError>;
826

            
827
/// Same as `ApplyExtrinsicResult` but augmented with `PostDispatchInfo` on success.
828
pub type ApplyExtrinsicResultWithInfo<T> =
829
	Result<DispatchResultWithInfo<T>, transaction_validity::TransactionValidityError>;
830

            
831
/// The error type used as return type in try runtime hooks.
832
pub type TryRuntimeError = DispatchError;
833

            
834
/// Verify a signature on an encoded value in a lazy manner. This can be
835
/// an optimization if the signature scheme has an "unsigned" escape hash.
836
pub fn verify_encoded_lazy<V: Verify, T: codec::Encode>(
837
	sig: &V,
838
	item: &T,
839
	signer: &<V::Signer as IdentifyAccount>::AccountId,
840
) -> bool {
841
	// The `Lazy<T>` trait expresses something like `X: FnMut<Output = for<'a> &'a T>`.
842
	// unfortunately this is a lifetime relationship that can't
843
	// be expressed without generic associated types, better unification of HRTBs in type position,
844
	// and some kind of integration into the Fn* traits.
845
	struct LazyEncode<F> {
846
		inner: F,
847
		encoded: Option<Vec<u8>>,
848
	}
849

            
850
	impl<F: Fn() -> Vec<u8>> traits::Lazy<[u8]> for LazyEncode<F> {
851
		fn get(&mut self) -> &[u8] {
852
			self.encoded.get_or_insert_with(&self.inner).as_slice()
853
		}
854
	}
855

            
856
	sig.verify(LazyEncode { inner: || item.encode(), encoded: None }, signer)
857
}
858

            
859
/// Checks that `$x` is equal to `$y` with an error rate of `$error`.
860
///
861
/// # Example
862
///
863
/// ```rust
864
/// # fn main() {
865
/// sp_runtime::assert_eq_error_rate!(10, 10, 0);
866
/// sp_runtime::assert_eq_error_rate!(10, 11, 1);
867
/// sp_runtime::assert_eq_error_rate!(12, 10, 2);
868
/// # }
869
/// ```
870
///
871
/// ```rust,should_panic
872
/// # fn main() {
873
/// sp_runtime::assert_eq_error_rate!(12, 10, 1);
874
/// # }
875
/// ```
876
#[macro_export]
877
#[cfg(feature = "std")]
878
macro_rules! assert_eq_error_rate {
879
	($x:expr, $y:expr, $error:expr $(,)?) => {
880
		assert!(
881
			($x >= $crate::Saturating::saturating_sub($y, $error)) &&
882
				($x <= $crate::Saturating::saturating_add($y, $error)),
883
			"{:?} != {:?} (with error rate {:?})",
884
			$x,
885
			$y,
886
			$error,
887
		);
888
	};
889
}
890

            
891
/// Same as [`assert_eq_error_rate`], but intended to be used with floating point number, or
892
/// generally those who do not have over/underflow potentials.
893
#[macro_export]
894
#[cfg(feature = "std")]
895
macro_rules! assert_eq_error_rate_float {
896
	($x:expr, $y:expr, $error:expr $(,)?) => {
897
		assert!(
898
			($x >= $y - $error) && ($x <= $y + $error),
899
			"{:?} != {:?} (with error rate {:?})",
900
			$x,
901
			$y,
902
			$error,
903
		);
904
	};
905
}
906

            
907
/// Simple blob to hold an extrinsic without committing to its format and ensure it is serialized
908
/// correctly.
909
#[derive(PartialEq, Eq, Clone, Default, Encode, Decode, TypeInfo)]
910
pub struct OpaqueExtrinsic(Vec<u8>);
911

            
912
impl OpaqueExtrinsic {
913
	/// Convert an encoded extrinsic to an `OpaqueExtrinsic`.
914
	pub fn from_bytes(mut bytes: &[u8]) -> Result<Self, codec::Error> {
915
		Self::decode(&mut bytes)
916
	}
917
}
918

            
919
impl core::fmt::Debug for OpaqueExtrinsic {
920
	#[cfg(feature = "std")]
921
	fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
922
		write!(fmt, "{}", sp_core::hexdisplay::HexDisplay::from(&self.0))
923
	}
924

            
925
	#[cfg(not(feature = "std"))]
926
	fn fmt(&self, _fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
927
		Ok(())
928
	}
929
}
930

            
931
#[cfg(feature = "serde")]
932
impl ::serde::Serialize for OpaqueExtrinsic {
933
	fn serialize<S>(&self, seq: S) -> Result<S::Ok, S::Error>
934
	where
935
		S: ::serde::Serializer,
936
	{
937
		codec::Encode::using_encoded(&self.0, |bytes| ::sp_core::bytes::serialize(bytes, seq))
938
	}
939
}
940

            
941
#[cfg(feature = "serde")]
942
impl<'a> ::serde::Deserialize<'a> for OpaqueExtrinsic {
943
	fn deserialize<D>(de: D) -> Result<Self, D::Error>
944
	where
945
		D: ::serde::Deserializer<'a>,
946
	{
947
		let r = ::sp_core::bytes::deserialize(de)?;
948
		Decode::decode(&mut &r[..])
949
			.map_err(|e| ::serde::de::Error::custom(format!("Decode error: {}", e)))
950
	}
951
}
952

            
953
impl traits::Extrinsic for OpaqueExtrinsic {
954
	type Call = ();
955
	type SignaturePayload = ();
956
}
957

            
958
/// Print something that implements `Printable` from the runtime.
959
pub fn print(print: impl traits::Printable) {
960
	print.print();
961
}
962

            
963
/// Utility function to declare string literals backed by an array of length N.
964
///
965
/// The input can be shorter than N, in that case the end of the array is padded with zeros.
966
///
967
/// [`str_array`] is useful when converting strings that end up in the storage as fixed size arrays
968
/// or in const contexts where static data types have strings that could also end up in the storage.
969
///
970
/// # Example
971
///
972
/// ```rust
973
/// # use sp_runtime::str_array;
974
/// const MY_STR: [u8; 6] = str_array("data");
975
/// assert_eq!(MY_STR, *b"data\0\0");
976
/// ```
977
pub const fn str_array<const N: usize>(s: &str) -> [u8; N] {
978
	debug_assert!(s.len() <= N, "String literal doesn't fit in array");
979
	let mut i = 0;
980
	let mut arr = [0; N];
981
	let s = s.as_bytes();
982
	while i < s.len() {
983
		arr[i] = s[i];
984
		i += 1;
985
	}
986
	arr
987
}
988

            
989
/// Describes on what should happen with a storage transaction.
990
pub enum TransactionOutcome<R> {
991
	/// Commit the transaction.
992
	Commit(R),
993
	/// Rollback the transaction.
994
	Rollback(R),
995
}
996

            
997
impl<R> TransactionOutcome<R> {
998
	/// Convert into the inner type.
999
	pub fn into_inner(self) -> R {
		match self {
			Self::Commit(r) => r,
			Self::Rollback(r) => r,
		}
	}
}
/// Confines the kind of extrinsics that can be included in a block.
#[derive(Debug, Default, PartialEq, Eq, Clone, Copy, Encode, Decode, TypeInfo)]
pub enum ExtrinsicInclusionMode {
	/// All extrinsics are allowed to be included in this block.
	#[default]
	AllExtrinsics,
	/// Inherents are allowed to be included.
	OnlyInherents,
}
/// Simple blob that hold a value in an encoded form without committing to its type.
#[derive(Decode, Encode, PartialEq, TypeInfo)]
pub struct OpaqueValue(Vec<u8>);
impl OpaqueValue {
	/// Create a new `OpaqueValue` using the given encoded representation.
	pub fn new(inner: Vec<u8>) -> OpaqueValue {
		OpaqueValue(inner)
	}
	/// Try to decode this `OpaqueValue` into the given concrete type.
	pub fn decode<T: Decode>(&self) -> Option<T> {
		Decode::decode(&mut &self.0[..]).ok()
	}
}
#[cfg(test)]
mod tests {
	use crate::traits::BlakeTwo256;
	use super::*;
	use codec::{Decode, Encode};
	use sp_core::crypto::Pair;
	use sp_io::TestExternalities;
	use sp_state_machine::create_proof_check_backend;
	#[test]
	fn opaque_extrinsic_serialization() {
		let ex = super::OpaqueExtrinsic(vec![1, 2, 3, 4]);
		assert_eq!(serde_json::to_string(&ex).unwrap(), "\"0x1001020304\"".to_owned());
	}
	#[test]
	fn dispatch_error_encoding() {
		let error = DispatchError::Module(ModuleError {
			index: 1,
			error: [2, 0, 0, 0],
			message: Some("error message"),
		});
		let encoded = error.encode();
		let decoded = DispatchError::decode(&mut &encoded[..]).unwrap();
		assert_eq!(encoded, vec![3, 1, 2, 0, 0, 0]);
		assert_eq!(
			decoded,
			DispatchError::Module(ModuleError { index: 1, error: [2, 0, 0, 0], message: None })
		);
	}
	#[test]
	fn dispatch_error_equality() {
		use DispatchError::*;
		let variants = vec![
			Other("foo"),
			Other("bar"),
			CannotLookup,
			BadOrigin,
			Module(ModuleError { index: 1, error: [1, 0, 0, 0], message: None }),
			Module(ModuleError { index: 1, error: [2, 0, 0, 0], message: None }),
			Module(ModuleError { index: 2, error: [1, 0, 0, 0], message: None }),
			ConsumerRemaining,
			NoProviders,
			Token(TokenError::FundsUnavailable),
			Token(TokenError::OnlyProvider),
			Token(TokenError::BelowMinimum),
			Token(TokenError::CannotCreate),
			Token(TokenError::UnknownAsset),
			Token(TokenError::Frozen),
			Arithmetic(ArithmeticError::Overflow),
			Arithmetic(ArithmeticError::Underflow),
			Arithmetic(ArithmeticError::DivisionByZero),
		];
		for (i, variant) in variants.iter().enumerate() {
			for (j, other_variant) in variants.iter().enumerate() {
				if i == j {
					assert_eq!(variant, other_variant);
				} else {
					assert_ne!(variant, other_variant);
				}
			}
		}
		// Ignores `message` field in `Module` variant.
		assert_eq!(
			Module(ModuleError { index: 1, error: [1, 0, 0, 0], message: Some("foo") }),
			Module(ModuleError { index: 1, error: [1, 0, 0, 0], message: None }),
		);
	}
	#[test]
	fn multi_signature_ecdsa_verify_works() {
		let msg = &b"test-message"[..];
		let (pair, _) = ecdsa::Pair::generate();
		let signature = pair.sign(&msg);
		assert!(ecdsa::Pair::verify(&signature, msg, &pair.public()));
		let multi_sig = MultiSignature::from(signature);
		let multi_signer = MultiSigner::from(pair.public());
		assert!(multi_sig.verify(msg, &multi_signer.into_account()));
		let multi_signer = MultiSigner::from(pair.public());
		assert!(multi_sig.verify(msg, &multi_signer.into_account()));
	}
	#[test]
	fn execute_and_generate_proof_works() {
		use codec::Encode;
		use sp_state_machine::Backend;
		let mut ext = TestExternalities::default();
		ext.insert(b"a".to_vec(), vec![1u8; 33]);
		ext.insert(b"b".to_vec(), vec![2u8; 33]);
		ext.insert(b"c".to_vec(), vec![3u8; 33]);
		ext.insert(b"d".to_vec(), vec![4u8; 33]);
		let pre_root = *ext.backend.root();
		let (_, proof) = ext.execute_and_prove(|| {
			sp_io::storage::get(b"a");
			sp_io::storage::get(b"b");
			sp_io::storage::get(b"v");
			sp_io::storage::get(b"d");
		});
		let compact_proof = proof.clone().into_compact_proof::<BlakeTwo256>(pre_root).unwrap();
		let compressed_proof = zstd::stream::encode_all(&compact_proof.encode()[..], 0).unwrap();
		// just an example of how you'd inspect the size of the proof.
		println!("proof size: {:?}", proof.encoded_size());
		println!("compact proof size: {:?}", compact_proof.encoded_size());
		println!("zstd-compressed compact proof size: {:?}", &compressed_proof.len());
		// create a new trie-backed from the proof and make sure it contains everything
		let proof_check = create_proof_check_backend::<BlakeTwo256>(pre_root, proof).unwrap();
		assert_eq!(proof_check.storage(b"a",).unwrap().unwrap(), vec![1u8; 33]);
		let _ = ext.execute_and_prove(|| {
			sp_io::storage::set(b"a", &vec![1u8; 44]);
		});
		// ensure that these changes are propagated to the backend.
		ext.execute_with(|| {
			assert_eq!(sp_io::storage::get(b"a").unwrap(), vec![1u8; 44]);
			assert_eq!(sp_io::storage::get(b"b").unwrap(), vec![2u8; 33]);
		});
	}
}
// NOTE: we have to test the sp_core stuff also from a different crate to check that the macro
// can access the sp_core crate.
#[cfg(test)]
mod sp_core_tests {
	use super::*;
	#[test]
	#[should_panic]
	fn generate_feature_enabled_macro_panics() {
		sp_core::generate_feature_enabled_macro!(if_test, test, $);
		if_test!(panic!("This should panic"));
	}
	#[test]
	fn generate_feature_enabled_macro_works() {
		sp_core::generate_feature_enabled_macro!(if_not_test, not(test), $);
		if_not_test!(panic!("This should not panic"));
	}
}