git.delta.rocks / unique-network / refs/commits / 20d08c295b0d

difftreelog

source

runtime/src/lib.rs11.5 KiBsourcehistory
1//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.23#![cfg_attr(not(feature = "std"), no_std)]4// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.5#![recursion_limit="256"]67// Make the WASM binary available.8#[cfg(feature = "std")]9include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1011use rstd::prelude::*;12use primitives::{OpaqueMetadata, crypto::key_types};13use sr_primitives::{14	ApplyResult, transaction_validity::TransactionValidity, generic, create_runtime_str,15	impl_opaque_keys, AnySignature16};17use sr_primitives::traits::{NumberFor, BlakeTwo256, Block as BlockT, StaticLookup, Verify, ConvertInto};18use sr_primitives::weights::Weight;19use client::{20	block_builder::api::{CheckInherentsResult, InherentData, self as block_builder_api},21	runtime_api as client_api, impl_runtime_apis22};23use aura_primitives::sr25519::AuthorityId as AuraId;24use grandpa::{AuthorityId as GrandpaId, AuthorityWeight as GrandpaWeight};25use grandpa::fg_primitives;26use version::RuntimeVersion;27#[cfg(feature = "std")]28use version::NativeVersion;2930// A few exports that help ease life for downstream crates.31#[cfg(any(feature = "std", test))]32pub use sr_primitives::BuildStorage;33pub use timestamp::Call as TimestampCall;34pub use balances::Call as BalancesCall;35pub use sr_primitives::{Permill, Perbill};36pub use support::{StorageValue, construct_runtime, parameter_types, traits::Randomness};3738/// An index to a block.39pub type BlockNumber = u32;4041/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.42pub type Signature = AnySignature;4344/// Some way of identifying an account on the chain. We intentionally make it equivalent45/// to the public key of our transaction signing scheme.46pub type AccountId = <Signature as Verify>::Signer;4748/// The type for looking up accounts. We don't expect more than 4 billion of them, but you49/// never know...50pub type AccountIndex = u32;5152/// Balance of an account.53pub type Balance = u128;5455/// Index of a transaction in the chain.56pub type Index = u32;5758/// A hash of some data used by the chain.59pub type Hash = primitives::H256;6061/// Digest item type.62pub type DigestItem = generic::DigestItem<Hash>;6364/// Used for the module template in `./template.rs`65mod template;6667/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know68/// the specifics of the runtime. They can then be made to be agnostic over specific formats69/// of data like extrinsics, allowing for them to continue syncing the network through upgrades70/// to even the core datastructures.71pub mod opaque {72	use super::*;7374	pub use sr_primitives::OpaqueExtrinsic as UncheckedExtrinsic;7576	/// Opaque block header type.77	pub type Header = generic::Header<BlockNumber, BlakeTwo256>;78	/// Opaque block type.79	pub type Block = generic::Block<Header, UncheckedExtrinsic>;80	/// Opaque block identifier type.81	pub type BlockId = generic::BlockId<Block>;8283	impl_opaque_keys! {84		pub struct SessionKeys {85			#[id(key_types::AURA)]86			pub aura: AuraId,87			#[id(key_types::GRANDPA)]88			pub grandpa: GrandpaId,89		}90	}91}9293/// This runtime version.94pub const VERSION: RuntimeVersion = RuntimeVersion {95	spec_name: create_runtime_str!("node-template"),96	impl_name: create_runtime_str!("node-template"),97	authoring_version: 3,98	spec_version: 4,99	impl_version: 4,100	apis: RUNTIME_API_VERSIONS,101};102103pub const MILLISECS_PER_BLOCK: u64 = 6000;104105pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;106107pub const EPOCH_DURATION_IN_BLOCKS: u32 = 10 * MINUTES;108109// These time units are defined in number of blocks.110pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);111pub const HOURS: BlockNumber = MINUTES * 60;112pub const DAYS: BlockNumber = HOURS * 24;113114// 1 in 4 blocks (on average, not counting collisions) will be primary babe blocks.115pub const PRIMARY_PROBABILITY: (u64, u64) = (1, 4);116117/// The version infromation used to identify this runtime when compiled natively.118#[cfg(feature = "std")]119pub fn native_version() -> NativeVersion {120	NativeVersion {121		runtime_version: VERSION,122		can_author_with: Default::default(),123	}124}125126parameter_types! {127	pub const BlockHashCount: BlockNumber = 250;128	pub const MaximumBlockWeight: Weight = 1_000_000;129	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);130	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;131	pub const Version: RuntimeVersion = VERSION;132}133134impl system::Trait for Runtime {135	/// The identifier used to distinguish between accounts.136	type AccountId = AccountId;137	/// The aggregated dispatch type that is available for extrinsics.138	type Call = Call;139	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.140	type Lookup = Indices;141	/// The index type for storing how many extrinsics an account has signed.142	type Index = Index;143	/// The index type for blocks.144	type BlockNumber = BlockNumber;145	/// The type for hashing blocks and tries.146	type Hash = Hash;147	/// The hashing algorithm used.148	type Hashing = BlakeTwo256;149	/// The header type.150	type Header = generic::Header<BlockNumber, BlakeTwo256>;151	/// The ubiquitous event type.152	type Event = Event;153	/// The ubiquitous origin type.154	type Origin = Origin;155	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).156	type BlockHashCount = BlockHashCount;157	/// Maximum weight of each block.158	type MaximumBlockWeight = MaximumBlockWeight;159	/// Maximum size of all encoded transactions (in bytes) that are allowed in one block.160	type MaximumBlockLength = MaximumBlockLength;161	/// Portion of the block weight that is available to all normal transactions.162	type AvailableBlockRatio = AvailableBlockRatio;163	/// Version of the runtime.164	type Version = Version;165}166167impl aura::Trait for Runtime {168	type AuthorityId = AuraId;169}170171impl grandpa::Trait for Runtime {172	type Event = Event;173}174175impl indices::Trait for Runtime {176	/// The type for recording indexing into the account enumeration. If this ever overflows, there177	/// will be problems!178	type AccountIndex = u32;179	/// Use the standard means of resolving an index hint from an id.180	type ResolveHint = indices::SimpleResolveHint<Self::AccountId, Self::AccountIndex>;181	/// Determine whether an account is dead.182	type IsDeadAccount = Balances;183	/// The ubiquitous event type.184	type Event = Event;185}186187parameter_types! {188	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;189}190191impl timestamp::Trait for Runtime {192	/// A timestamp: milliseconds since the unix epoch.193	type Moment = u64;194	type OnTimestampSet = Aura;195	type MinimumPeriod = MinimumPeriod;196}197198parameter_types! {199	pub const ExistentialDeposit: u128 = 500;200	pub const TransferFee: u128 = 0;201	pub const CreationFee: u128 = 0;202}203204impl balances::Trait for Runtime {205	/// The type for recording an account's balance.206	type Balance = Balance;207	/// What to do if an account's free balance gets zeroed.208	type OnFreeBalanceZero = ();209	/// What to do if a new account is created.210	type OnNewAccount = Indices;211	/// The ubiquitous event type.212	type Event = Event;213	type DustRemoval = ();214	type TransferPayment = ();215	type ExistentialDeposit = ExistentialDeposit;216	type TransferFee = TransferFee;217	type CreationFee = CreationFee;218}219220parameter_types! {221	pub const TransactionBaseFee: Balance = 0;222	pub const TransactionByteFee: Balance = 1;223}224225impl transaction_payment::Trait for Runtime {226	type Currency = balances::Module<Runtime>;227	type OnTransactionPayment = ();228	type TransactionBaseFee = TransactionBaseFee;229	type TransactionByteFee = TransactionByteFee;230	type WeightToFee = ConvertInto;231	type FeeMultiplierUpdate = ();232}233234impl sudo::Trait for Runtime {235	type Event = Event;236	type Proposal = Call;237}238239/// Used for the module template in `./template.rs`240impl template::Trait for Runtime {241	type Event = Event;242}243244construct_runtime!(245	pub enum Runtime where246		Block = Block,247		NodeBlock = opaque::Block,248		UncheckedExtrinsic = UncheckedExtrinsic249	{250		System: system::{Module, Call, Storage, Config, Event},251		Timestamp: timestamp::{Module, Call, Storage, Inherent},252		Aura: aura::{Module, Config<T>, Inherent(Timestamp)},253		Grandpa: grandpa::{Module, Call, Storage, Config, Event},254		Indices: indices::{default, Config<T>},255		Balances: balances::{default, Error},256		TransactionPayment: transaction_payment::{Module, Storage},257		Sudo: sudo,258		// Used for the module template in `./template.rs`259		TemplateModule: template::{Module, Call, Storage, Event<T>},260		RandomnessCollectiveFlip: randomness_collective_flip::{Module, Call, Storage},261	}262);263264/// The address format for describing accounts.265pub type Address = <Indices as StaticLookup>::Source;266/// Block header type as expected by this runtime.267pub type Header = generic::Header<BlockNumber, BlakeTwo256>;268/// Block type as expected by this runtime.269pub type Block = generic::Block<Header, UncheckedExtrinsic>;270/// A Block signed with a Justification271pub type SignedBlock = generic::SignedBlock<Block>;272/// BlockId type as expected by this runtime.273pub type BlockId = generic::BlockId<Block>;274/// The SignedExtension to the basic transaction logic.275pub type SignedExtra = (276	system::CheckVersion<Runtime>,277	system::CheckGenesis<Runtime>,278	system::CheckEra<Runtime>,279	system::CheckNonce<Runtime>,280	system::CheckWeight<Runtime>,281	transaction_payment::ChargeTransactionPayment<Runtime>282);283/// Unchecked extrinsic type as expected by this runtime.284pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;285/// Extrinsic type that has already been checked.286pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;287/// Executive: handles dispatch to the various modules.288pub type Executive = executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;289290impl_runtime_apis! {291	impl client_api::Core<Block> for Runtime {292		fn version() -> RuntimeVersion {293			VERSION294		}295296		fn execute_block(block: Block) {297			Executive::execute_block(block)298		}299300		fn initialize_block(header: &<Block as BlockT>::Header) {301			Executive::initialize_block(header)302		}303	}304305	impl client_api::Metadata<Block> for Runtime {306		fn metadata() -> OpaqueMetadata {307			Runtime::metadata().into()308		}309	}310311	impl block_builder_api::BlockBuilder<Block> for Runtime {312		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyResult {313			Executive::apply_extrinsic(extrinsic)314		}315316		fn finalize_block() -> <Block as BlockT>::Header {317			Executive::finalize_block()318		}319320		fn inherent_extrinsics(data: InherentData) -> Vec<<Block as BlockT>::Extrinsic> {321			data.create_extrinsics()322		}323324		fn check_inherents(block: Block, data: InherentData) -> CheckInherentsResult {325			data.check_extrinsics(&block)326		}327328		fn random_seed() -> <Block as BlockT>::Hash {329			RandomnessCollectiveFlip::random_seed()330		}331	}332333	impl client_api::TaggedTransactionQueue<Block> for Runtime {334		fn validate_transaction(tx: <Block as BlockT>::Extrinsic) -> TransactionValidity {335			Executive::validate_transaction(tx)336		}337	}338339	impl offchain_primitives::OffchainWorkerApi<Block> for Runtime {340		fn offchain_worker(number: NumberFor<Block>) {341			Executive::offchain_worker(number)342		}343	}344345	impl aura_primitives::AuraApi<Block, AuraId> for Runtime {346		fn slot_duration() -> u64 {347			Aura::slot_duration()348		}349		350		fn authorities() -> Vec<AuraId> {351			Aura::authorities()352		}353	}354355	impl substrate_session::SessionKeys<Block> for Runtime {356		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {357			let seed = seed.as_ref().map(|s| rstd::str::from_utf8(&s).expect("Seed is an utf8 string"));358			opaque::SessionKeys::generate(seed)359		}360	}361362	impl fg_primitives::GrandpaApi<Block> for Runtime {363		fn grandpa_authorities() -> Vec<(GrandpaId, GrandpaWeight)> {364			Grandpa::grandpa_authorities()365		}366	}367}