Skip to content
lib.rs 84.2 KiB
Newer Older
// This file is part of Substrate.
Gav Wood's avatar
Gav Wood committed

// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
Gav Wood's avatar
Gav Wood committed

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Gav Wood's avatar
Gav Wood committed

//! # System Module
//! The System module provides low-level access to core types and cross-cutting utilities.
//! It acts as the base layer for other pallets to interact with the Substrate framework components.
//!
//! - [`system::Trait`](./trait.Trait.html)
//! ## Overview
//! The System module defines the core data types used in a Substrate runtime.
//! It also provides several utility functions (see [`Module`](./struct.Module.html)) for other FRAME pallets.
//! In addition, it manages the storage items for extrinsics data, indexes, event records, and digest items,
//! among other things that support the execution of the current block.
//! It also handles low-level tasks like depositing logs, basic set up and take down of
//! temporary storage entries, and access to previous block hashes.
//! ## Interface
//! ### Dispatchable Functions
//! The System module does not implement any dispatchable functions.
//! ### Public Functions
//! See the [`Module`](./struct.Module.html) struct for details of publicly available functions.
//! The System module defines the following extensions:
//!
//!   - [`CheckWeight`]: Checks the weight and length of the block and ensure that it does not
//!     exceed the limits.
yjh's avatar
yjh committed
//!   - [`CheckNonce`]: Checks the nonce of the transaction. Contains a single payload of type
//!     `T::Index`.
//!   - [`CheckEra`]: Checks the era of the transaction. Contains a single payload of type `Era`.
//!   - [`CheckGenesis`]: Checks the provided genesis hash of the transaction. Must be a part of the
//!     signed payload of the transaction.
//!   - [`CheckSpecVersion`]: Checks that the runtime version is the same as the one used to sign the
//!     transaction.
//!   - [`CheckTxVersion`]: Checks that the transaction version is the same as the one used to sign the
//!     transaction.
//!
//! Lookup the runtime aggregator file (e.g. `node/runtime`) to see the full list of signed
//! extensions included in a chain.
//!
//! ### Prerequisites
//! Import the System module and derive your module's configuration trait from the system trait.
//! ### Example - Get extrinsic count and parent hash for the current block
//! use frame_support::{decl_module, dispatch};
//! use frame_system::{self as system, ensure_signed};
//! pub trait Trait: system::Trait {}
//! decl_module! {
//! 	pub struct Module<T: Trait> for enum Call where origin: T::Origin {
//! 		pub fn system_module_example(origin) -> dispatch::DispatchResult {
//! 			let _sender = ensure_signed(origin)?;
//! 			let _extrinsic_count = <system::Module<T>>::extrinsic_count();
//! 			let _parent_hash = <system::Module<T>>::parent_hash();
//! 			Ok(())
//! 		}
//! 	}
//! }
//! # fn main() { }
//! ```
Gav Wood's avatar
Gav Wood committed

#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(feature = "std")]
use serde::Serialize;
use sp_std::prelude::*;
#[cfg(any(feature = "std", test))]
Gavin Wood's avatar
Gavin Wood committed
use sp_std::convert::Infallible;
use sp_std::marker::PhantomData;
use sp_std::fmt::Debug;
use sp_version::RuntimeVersion;
use sp_runtime::{
	RuntimeDebug, Perbill, DispatchError, DispatchResult,
Kian Paimani's avatar
Kian Paimani committed
	generic::{self, Era},
	transaction_validity::{
		ValidTransaction, TransactionPriority, TransactionLongevity, TransactionValidityError,
		InvalidTransaction, TransactionValidity,
	},
	traits::{
Kian Paimani's avatar
Kian Paimani committed
		self, CheckEqual, AtLeast32Bit, Zero, SignedExtension, Lookup, LookupError,
		SimpleBitOps, Hash, Member, MaybeDisplay, BadOrigin, SaturatedConversion,
		MaybeSerialize, MaybeSerializeDeserialize, MaybeMallocSizeOf, StaticLookup, One, Bounded,
		Dispatchable, DispatchInfoOf, PostDispatchInfoOf,
use sp_core::{ChangesTrieConfiguration, storage::well_known_keys};
use frame_support::{
	decl_module, decl_event, decl_storage, decl_error, Parameter, ensure, debug,
Gavin Wood's avatar
Gavin Wood committed
	traits::{
Gavin Wood's avatar
Gavin Wood committed
		Contains, Get, ModuleToIndex, OnNewAccount, OnKilledAccount, IsDeadAccount, Happened,
Gavin Wood's avatar
Gavin Wood committed
	},
	weights::{
		Weight, RuntimeDbWeight, DispatchInfo, PostDispatchInfo, DispatchClass,
		FunctionOf, Pays, extract_actual_weight,
	},
	dispatch::DispatchResultWithPostInfo,
Gavin Wood's avatar
Gavin Wood committed
use codec::{Encode, Decode, FullCodec, EncodeLike};
Gav Wood's avatar
Gav Wood committed

#[cfg(any(feature = "std", test))]
use sp_io::TestExternalities;
/// Compute the trie root of a list of extrinsics.
pub fn extrinsics_root<H: Hash, E: codec::Encode>(extrinsics: &[E]) -> H::Output {
	extrinsics_data_root::<H>(extrinsics.iter().map(codec::Encode::encode).collect())
/// Compute the trie root of a list of extrinsics.
pub fn extrinsics_data_root<H: Hash>(xts: Vec<Vec<u8>>) -> H::Output {
Bastian Köcher's avatar
Bastian Köcher committed
	H::ordered_trie_root(xts)
pub trait Trait: 'static + Eq + Clone {
	/// The aggregated `Origin` type used by dispatchable calls.
		Into<Result<RawOrigin<Self::AccountId>, Self::Origin>>
		+ From<RawOrigin<Self::AccountId>>
		+ Clone;
	/// The aggregated `Call` type.
	type Call: Dispatchable + Debug;
	/// Account index (aka nonce) type. This stores the number of previous transactions associated
	/// with a sender account.
Kian Paimani's avatar
Kian Paimani committed
		Parameter + Member + MaybeSerialize + Debug + Default + MaybeDisplay + AtLeast32Bit

	/// The block number type used by the runtime.
	type BlockNumber:
Kian Paimani's avatar
Kian Paimani committed
		Parameter + Member + MaybeSerializeDeserialize + Debug + MaybeDisplay + AtLeast32Bit
		+ Default + Bounded + Copy + sp_std::hash::Hash + sp_std::str::FromStr + MaybeMallocSizeOf;
	/// The output of the `Hashing` function.
	type Hash:
		Parameter + Member + MaybeSerializeDeserialize + Debug + MaybeDisplay + SimpleBitOps + Ord
		+ Default + Copy + CheckEqual + sp_std::hash::Hash + AsRef<[u8]> + AsMut<[u8]> + MaybeMallocSizeOf;
	/// The hashing system (algorithm) being used in the runtime (e.g. Blake2).
	type Hashing: Hash<Output = Self::Hash>;

	/// The user account identifier type for the runtime.
	type AccountId: Parameter + Member + MaybeSerializeDeserialize + Debug + MaybeDisplay + Ord
		+ Default;

	/// Converting trait to take a source type and convert to `AccountId`.
	///
	/// Used to define the type and conversion mechanism for referencing accounts in transactions.
	/// It's perfectly reasonable for this to be an identity conversion (with the source type being
	/// `AccountId`), but other modules (e.g. Indices module) may provide more functional/efficient
	/// alternatives.
	type Lookup: StaticLookup<Target = Self::AccountId>;

	/// The block header.
Gav Wood's avatar
Gav Wood committed
	type Header: Parameter + traits::Header<
		Number = Self::BlockNumber,
		Hash = Self::Hash,

	/// The aggregated event type of the runtime.
Gavin Wood's avatar
Gavin Wood committed
	type Event: Parameter + Member + From<Event<Self>> + Debug;

	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
Loading full blame...