git.delta.rocks / unique-network / refs/commits / b6bfc95d7161

difftreelog

source

runtime/src/lib.rs13.4 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, DigestFor, StaticLookup, Verify, ConvertInto};18use sr_primitives::weights::Weight;19use babe::{AuthorityId as BabeId};20use grandpa::{AuthorityId as GrandpaId, AuthorityWeight as GrandpaWeight};21use grandpa::fg_primitives::{self, ScheduledChange};22use client::{23	block_builder::api::{CheckInherentsResult, InherentData, self as block_builder_api},24	runtime_api as client_api, impl_runtime_apis25};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};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	pub type SessionHandlers = (Grandpa, Babe);8485	impl_opaque_keys! {86		pub struct SessionKeys {87			#[id(key_types::GRANDPA)]88			pub grandpa: GrandpaId,89			#[id(key_types::BABE)]90			pub babe: BabeId,91		}92	}93}9495/// This runtime version.96pub const VERSION: RuntimeVersion = RuntimeVersion {97	spec_name: create_runtime_str!("node-template"),98	impl_name: create_runtime_str!("node-template"),99	authoring_version: 3,100	spec_version: 4,101	impl_version: 4,102	apis: RUNTIME_API_VERSIONS,103};104105/// Constants for Babe.106107/// Since BABE is probabilistic this is the average expected block time that108/// we are targetting. Blocks will be produced at a minimum duration defined109/// by `SLOT_DURATION`, but some slots will not be allocated to any110/// authority and hence no block will be produced. We expect to have this111/// block time on average following the defined slot duration and the value112/// of `c` configured for BABE (where `1 - c` represents the probability of113/// a slot being empty).114/// This value is only used indirectly to define the unit constants below115/// that are expressed in blocks. The rest of the code should use116/// `SLOT_DURATION` instead (like the timestamp module for calculating the117/// minimum period).118/// <https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results>119pub const MILLISECS_PER_BLOCK: u64 = 6000;120121pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;122123pub const EPOCH_DURATION_IN_BLOCKS: u32 = 10 * MINUTES;124125// These time units are defined in number of blocks.126pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);127pub const HOURS: BlockNumber = MINUTES * 60;128pub const DAYS: BlockNumber = HOURS * 24;129130// 1 in 4 blocks (on average, not counting collisions) will be primary babe blocks.131pub const PRIMARY_PROBABILITY: (u64, u64) = (1, 4);132133/// The version infromation used to identify this runtime when compiled natively.134#[cfg(feature = "std")]135pub fn native_version() -> NativeVersion {136	NativeVersion {137		runtime_version: VERSION,138		can_author_with: Default::default(),139	}140}141142parameter_types! {143	pub const BlockHashCount: BlockNumber = 250;144	pub const MaximumBlockWeight: Weight = 1_000_000;145	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);146	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;147	pub const Version: RuntimeVersion = VERSION;148}149150impl system::Trait for Runtime {151	/// The identifier used to distinguish between accounts.152	type AccountId = AccountId;153	/// The aggregated dispatch type that is available for extrinsics.154	type Call = Call;155	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.156	type Lookup = Indices;157	/// The index type for storing how many extrinsics an account has signed.158	type Index = Index;159	/// The index type for blocks.160	type BlockNumber = BlockNumber;161	/// The type for hashing blocks and tries.162	type Hash = Hash;163	/// The hashing algorithm used.164	type Hashing = BlakeTwo256;165	/// The header type.166	type Header = generic::Header<BlockNumber, BlakeTwo256>;167	/// The ubiquitous event type.168	type Event = Event;169	/// Update weight (to fee) multiplier per-block.170	type WeightMultiplierUpdate = ();171	/// The ubiquitous origin type.172	type Origin = Origin;173	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).174	type BlockHashCount = BlockHashCount;175	/// Maximum weight of each block. With a default weight system of 1byte == 1weight, 4mb is ok.176	type MaximumBlockWeight = MaximumBlockWeight;177	/// Maximum size of all encoded transactions (in bytes) that are allowed in one block.178	type MaximumBlockLength = MaximumBlockLength;179	/// Portion of the block weight that is available to all normal transactions.180	type AvailableBlockRatio = AvailableBlockRatio;181	type Version = Version;182}183184parameter_types! {185	pub const EpochDuration: u64 = EPOCH_DURATION_IN_BLOCKS as u64;186	pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;187}188189impl babe::Trait for Runtime {190	type EpochDuration = EpochDuration;191	type ExpectedBlockTime = ExpectedBlockTime;192}193194impl grandpa::Trait for Runtime {195	type Event = Event;196}197198impl indices::Trait for Runtime {199	/// The type for recording indexing into the account enumeration. If this ever overflows, there200	/// will be problems!201	type AccountIndex = u32;202	/// Use the standard means of resolving an index hint from an id.203	type ResolveHint = indices::SimpleResolveHint<Self::AccountId, Self::AccountIndex>;204	/// Determine whether an account is dead.205	type IsDeadAccount = Balances;206	/// The ubiquitous event type.207	type Event = Event;208}209210parameter_types! {211	pub const MinimumPeriod: u64 = 5000;212}213214impl timestamp::Trait for Runtime {215	/// A timestamp: milliseconds since the unix epoch.216	type Moment = u64;217	type OnTimestampSet = Babe;218	type MinimumPeriod = MinimumPeriod;219}220221parameter_types! {222	pub const ExistentialDeposit: u128 = 500;223	pub const TransferFee: u128 = 0;224	pub const CreationFee: u128 = 0;225	pub const TransactionBaseFee: u128 = 0;226	pub const TransactionByteFee: u128 = 1;227}228229impl balances::Trait for Runtime {230	/// The type for recording an account's balance.231	type Balance = Balance;232	/// What to do if an account's free balance gets zeroed.233	type OnFreeBalanceZero = ();234	/// What to do if a new account is created.235	type OnNewAccount = Indices;236	/// The ubiquitous event type.237	type Event = Event;238239	type TransactionPayment = ();240	type DustRemoval = ();241	type TransferPayment = ();242	type ExistentialDeposit = ExistentialDeposit;243	type TransferFee = TransferFee;244	type CreationFee = CreationFee;245	type TransactionBaseFee = TransactionBaseFee;246	type TransactionByteFee = TransactionByteFee;247	type WeightToFee = ConvertInto;248}249250impl sudo::Trait for Runtime {251	type Event = Event;252	type Proposal = Call;253}254255/// Used for the module template in `./template.rs`256impl template::Trait for Runtime {257	type Event = Event;258}259260construct_runtime!(261	pub enum Runtime where262		Block = Block,263		NodeBlock = opaque::Block,264		UncheckedExtrinsic = UncheckedExtrinsic265	{266		System: system::{Module, Call, Storage, Config, Event},267		Timestamp: timestamp::{Module, Call, Storage, Inherent},268		Babe: babe::{Module, Call, Storage, Config, Inherent(Timestamp)},269		Grandpa: grandpa::{Module, Call, Storage, Config, Event},270		Indices: indices::{default, Config<T>},271		Balances: balances,272		Sudo: sudo,273		// Used for the module template in `./template.rs`274		TemplateModule: template::{Module, Call, Storage, Event<T>},275	}276);277278/// The address format for describing accounts.279pub type Address = <Indices as StaticLookup>::Source;280/// Block header type as expected by this runtime.281pub type Header = generic::Header<BlockNumber, BlakeTwo256>;282/// Block type as expected by this runtime.283pub type Block = generic::Block<Header, UncheckedExtrinsic>;284/// A Block signed with a Justification285pub type SignedBlock = generic::SignedBlock<Block>;286/// BlockId type as expected by this runtime.287pub type BlockId = generic::BlockId<Block>;288/// The SignedExtension to the basic transaction logic.289pub type SignedExtra = (290	system::CheckVersion<Runtime>,291	system::CheckGenesis<Runtime>,292	system::CheckEra<Runtime>,293	system::CheckNonce<Runtime>,294	system::CheckWeight<Runtime>,295	balances::TakeFees<Runtime>296);297/// Unchecked extrinsic type as expected by this runtime.298pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;299/// Extrinsic type that has already been checked.300pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;301/// Executive: handles dispatch to the various modules.302pub type Executive = executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;303304impl_runtime_apis! {305	impl client_api::Core<Block> for Runtime {306		fn version() -> RuntimeVersion {307			VERSION308		}309310		fn execute_block(block: Block) {311			Executive::execute_block(block)312		}313314		fn initialize_block(header: &<Block as BlockT>::Header) {315			Executive::initialize_block(header)316		}317	}318319	impl client_api::Metadata<Block> for Runtime {320		fn metadata() -> OpaqueMetadata {321			Runtime::metadata().into()322		}323	}324325	impl block_builder_api::BlockBuilder<Block> for Runtime {326		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyResult {327			Executive::apply_extrinsic(extrinsic)328		}329330		fn finalize_block() -> <Block as BlockT>::Header {331			Executive::finalize_block()332		}333334		fn inherent_extrinsics(data: InherentData) -> Vec<<Block as BlockT>::Extrinsic> {335			data.create_extrinsics()336		}337338		fn check_inherents(block: Block, data: InherentData) -> CheckInherentsResult {339			data.check_extrinsics(&block)340		}341342		fn random_seed() -> <Block as BlockT>::Hash {343			System::random_seed()344		}345	}346347	impl client_api::TaggedTransactionQueue<Block> for Runtime {348		fn validate_transaction(tx: <Block as BlockT>::Extrinsic) -> TransactionValidity {349			Executive::validate_transaction(tx)350		}351	}352353	impl offchain_primitives::OffchainWorkerApi<Block> for Runtime {354		fn offchain_worker(number: NumberFor<Block>) {355			Executive::offchain_worker(number)356		}357	}358359	impl fg_primitives::GrandpaApi<Block> for Runtime {360		fn grandpa_pending_change(digest: &DigestFor<Block>)361			-> Option<ScheduledChange<NumberFor<Block>>>362		{363			Grandpa::pending_change(digest)364		}365366		fn grandpa_forced_change(digest: &DigestFor<Block>)367			-> Option<(NumberFor<Block>, ScheduledChange<NumberFor<Block>>)>368		{369			Grandpa::forced_change(digest)370		}371372		fn grandpa_authorities() -> Vec<(GrandpaId, GrandpaWeight)> {373			Grandpa::grandpa_authorities()374		}375	}376377	impl babe_primitives::BabeApi<Block> for Runtime {378		fn startup_data() -> babe_primitives::BabeConfiguration {379			// The choice of `c` parameter (where `1 - c` represents the380			// probability of a slot being empty), is done in accordance to the381			// slot duration and expected target block time, for safely382			// resisting network delays of maximum two seconds.383			// <https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results>384			babe_primitives::BabeConfiguration {385				median_required_blocks: 1000,386				slot_duration: Babe::slot_duration(),387				c: PRIMARY_PROBABILITY,388			}389		}390391		fn epoch() -> babe_primitives::Epoch {392			babe_primitives::Epoch {393				start_slot: Babe::epoch_start_slot(),394				authorities: Babe::authorities(),395				epoch_index: Babe::epoch_index(),396				randomness: Babe::randomness(),397				duration: EpochDuration::get(),398				secondary_slots: Babe::secondary_slots().0,399			}400		}401	}402403	impl substrate_session::SessionKeys<Block> for Runtime {404		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {405			let seed = seed.as_ref().map(|s| rstd::str::from_utf8(&s).expect("Seed is an utf8 string"));406			opaque::SessionKeys::generate(seed)407		}408	}409}