git.delta.rocks / unique-network / refs/commits / 5cd3d42aeddb

difftreelog

source

runtime/src/lib.rs12.9 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 babe::{AuthorityId as BabeId};20use grandpa::{AuthorityId as GrandpaId, AuthorityWeight as GrandpaWeight};21use grandpa::fg_primitives;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 = SLOT_DURATION / 2;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;238	type TransactionPayment = ();239	type DustRemoval = ();240	type TransferPayment = ();241	type ExistentialDeposit = ExistentialDeposit;242	type TransferFee = TransferFee;243	type CreationFee = CreationFee;244	type TransactionBaseFee = TransactionBaseFee;245	type TransactionByteFee = TransactionByteFee;246	type WeightToFee = ConvertInto;247}248249impl sudo::Trait for Runtime {250	type Event = Event;251	type Proposal = Call;252}253254/// Used for the module template in `./template.rs`255impl template::Trait for Runtime {256	type Event = Event;257}258259construct_runtime!(260	pub enum Runtime where261		Block = Block,262		NodeBlock = opaque::Block,263		UncheckedExtrinsic = UncheckedExtrinsic264	{265		System: system::{Module, Call, Storage, Config, Event},266		Timestamp: timestamp::{Module, Call, Storage, Inherent},267		Babe: babe::{Module, Call, Storage, Config, Inherent(Timestamp)},268		Grandpa: grandpa::{Module, Call, Storage, Config, Event},269		Indices: indices::{default, Config<T>},270		Balances: balances::{default, Error},271		Sudo: sudo,272		// Used for the module template in `./template.rs`273		TemplateModule: template::{Module, Call, Storage, Event<T>},274	}275);276277/// The address format for describing accounts.278pub type Address = <Indices as StaticLookup>::Source;279/// Block header type as expected by this runtime.280pub type Header = generic::Header<BlockNumber, BlakeTwo256>;281/// Block type as expected by this runtime.282pub type Block = generic::Block<Header, UncheckedExtrinsic>;283/// A Block signed with a Justification284pub type SignedBlock = generic::SignedBlock<Block>;285/// BlockId type as expected by this runtime.286pub type BlockId = generic::BlockId<Block>;287/// The SignedExtension to the basic transaction logic.288pub type SignedExtra = (289	system::CheckVersion<Runtime>,290	system::CheckGenesis<Runtime>,291	system::CheckEra<Runtime>,292	system::CheckNonce<Runtime>,293	system::CheckWeight<Runtime>,294	balances::TakeFees<Runtime>295);296/// Unchecked extrinsic type as expected by this runtime.297pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;298/// Extrinsic type that has already been checked.299pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;300/// Executive: handles dispatch to the various modules.301pub type Executive = executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;302303impl_runtime_apis! {304	impl client_api::Core<Block> for Runtime {305		fn version() -> RuntimeVersion {306			VERSION307		}308309		fn execute_block(block: Block) {310			Executive::execute_block(block)311		}312313		fn initialize_block(header: &<Block as BlockT>::Header) {314			Executive::initialize_block(header)315		}316	}317318	impl client_api::Metadata<Block> for Runtime {319		fn metadata() -> OpaqueMetadata {320			Runtime::metadata().into()321		}322	}323324	impl block_builder_api::BlockBuilder<Block> for Runtime {325		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyResult {326			Executive::apply_extrinsic(extrinsic)327		}328329		fn finalize_block() -> <Block as BlockT>::Header {330			Executive::finalize_block()331		}332333		fn inherent_extrinsics(data: InherentData) -> Vec<<Block as BlockT>::Extrinsic> {334			data.create_extrinsics()335		}336337		fn check_inherents(block: Block, data: InherentData) -> CheckInherentsResult {338			data.check_extrinsics(&block)339		}340341		fn random_seed() -> <Block as BlockT>::Hash {342			System::random_seed()343		}344	}345346	impl client_api::TaggedTransactionQueue<Block> for Runtime {347		fn validate_transaction(tx: <Block as BlockT>::Extrinsic) -> TransactionValidity {348			Executive::validate_transaction(tx)349		}350	}351352	impl offchain_primitives::OffchainWorkerApi<Block> for Runtime {353		fn offchain_worker(number: NumberFor<Block>) {354			Executive::offchain_worker(number)355		}356	}357358	impl fg_primitives::GrandpaApi<Block> for Runtime {359		fn grandpa_authorities() -> Vec<(GrandpaId, GrandpaWeight)> {360			Grandpa::grandpa_authorities()361		}362	}363364	impl babe_primitives::BabeApi<Block> for Runtime {365		fn configuration() -> babe_primitives::BabeConfiguration {366			// The choice of `c` parameter (where `1 - c` represents the367			// probability of a slot being empty), is done in accordance to the368			// slot duration and expected target block time, for safely369			// resisting network delays of maximum two seconds.370			// <https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results>371			babe_primitives::BabeConfiguration {372				slot_duration: Babe::slot_duration(),373				epoch_length: EpochDuration::get(),374				c: PRIMARY_PROBABILITY,375				genesis_authorities: Babe::authorities(),376				randomness: Babe::randomness(),377				secondary_slots: true,378			}379		}380	}381382	impl substrate_session::SessionKeys<Block> for Runtime {383		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {384			let seed = seed.as_ref().map(|s| rstd::str::from_utf8(&s).expect("Seed is an utf8 string"));385			opaque::SessionKeys::generate(seed)386		}387	}388}