From ef002a2b22e1335416de1166706a33c3399c258b Mon Sep 17 00:00:00 2001 From: Bernhard Schuster Date: Fri, 3 Jul 2020 15:44:01 +0200 Subject: [PATCH] add test runtime named origami, a relay chain runtime --- Cargo.lock | 74 ++++++ Cargo.toml | 2 + node/service/Cargo.toml | 1 + node/service/src/lib.rs | 41 +++ runtime/origami/Cargo.toml | 172 ++++++++++++ runtime/origami/README.adoc | 5 + runtime/origami/build.rs | 26 ++ runtime/origami/src/constants.rs | 85 ++++++ runtime/origami/src/lib.rs | 435 +++++++++++++++++++++++++++++++ 9 files changed, 841 insertions(+) create mode 100644 runtime/origami/Cargo.toml create mode 100644 runtime/origami/README.adoc create mode 100644 runtime/origami/build.rs create mode 100644 runtime/origami/src/constants.rs create mode 100644 runtime/origami/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index e9756cfd539e..3c4c650d1aa3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3363,6 +3363,80 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77af24da69f9d9341038eba93a073b1fdaaa1b788221b00a69bce9e762cb32de" +[[package]] +name = "origami-runtime" +version = "0.0.1" +dependencies = [ + "bitvec", + "frame-benchmarking", + "frame-executive", + "frame-support", + "frame-system", + "frame-system-benchmarking", + "frame-system-rpc-runtime-api", + "hex-literal", + "libsecp256k1", + "log 0.3.9", + "pallet-authority-discovery", + "pallet-authorship", + "pallet-babe", + "pallet-balances", + "pallet-collective", + "pallet-democracy", + "pallet-elections-phragmen", + "pallet-finality-tracker", + "pallet-grandpa", + "pallet-identity", + "pallet-im-online", + "pallet-indices", + "pallet-membership", + "pallet-multisig", + "pallet-nicks", + "pallet-offences", + "pallet-offences-benchmarking", + "pallet-proxy", + "pallet-randomness-collective-flip", + "pallet-scheduler", + "pallet-session", + "pallet-session-benchmarking", + "pallet-staking", + "pallet-staking-reward-curve", + "pallet-sudo", + "pallet-timestamp", + "pallet-transaction-payment", + "pallet-transaction-payment-rpc-runtime-api", + "pallet-treasury", + "pallet-utility", + "pallet-vesting", + "parity-scale-codec", + "polkadot-primitives", + "polkadot-runtime-common", + "rustc-hex", + "serde", + "serde_derive", + "serde_json", + "smallvec 1.4.0", + "sp-api", + "sp-authority-discovery", + "sp-block-builder", + "sp-consensus-babe", + "sp-core", + "sp-inherents", + "sp-keyring", + "sp-offchain", + "sp-runtime", + "sp-session", + "sp-staking", + "sp-std", + "sp-transaction-pool", + "sp-trie", + "sp-version", + "static_assertions", + "substrate-wasm-builder-runner 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", + "tiny-keccak 1.5.0", + "trie-db 0.20.1", +] + [[package]] name = "owning_ref" version = "0.4.1" diff --git a/Cargo.toml b/Cargo.toml index f6632f77a14d..6750a25e6078 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,6 +36,7 @@ members = [ "runtime/polkadot", "runtime/kusama", "runtime/westend", + "runtime/origami", "runtime/test-runtime", "runtime/test-runtime/client", "service", @@ -59,6 +60,7 @@ exclude = [ "runtime/polkadot/wasm", "runtime/kusama/wasm", "runtime/westend/wasm", + "runtime/origami/wasm", "parachain/test-parachains/adder/wasm", ] diff --git a/node/service/Cargo.toml b/node/service/Cargo.toml index f1a56acfad95..3f63d54e8881 100644 --- a/node/service/Cargo.toml +++ b/node/service/Cargo.toml @@ -18,6 +18,7 @@ polkadot-overseer = { path = "../overseer" } polkadot-subsystem = { package = "polkadot-node-subsystem", path = "../subsystem" } kusama-runtime = { path = "../../runtime/kusama" } westend-runtime = { path = "../../runtime/westend" } +origami-runtime = { path = "../../runtime/origami" } polkadot-network = { path = "../../network", optional = true } polkadot-rpc = { path = "../../rpc" } sp-io = { git = "https://github.com/paritytech/substrate", branch = "master" } diff --git a/node/service/src/lib.rs b/node/service/src/lib.rs index c798d3e9aa71..6cf309b8767b 100644 --- a/node/service/src/lib.rs +++ b/node/service/src/lib.rs @@ -53,6 +53,7 @@ pub use chain_spec::{PolkadotChainSpec, KusamaChainSpec, WestendChainSpec}; #[cfg(feature = "full-node")] pub use codec::Codec; pub use polkadot_runtime; +pub use origami_runtime; pub use kusama_runtime; pub use westend_runtime; use prometheus_endpoint::Registry; @@ -79,6 +80,14 @@ native_executor_instance!( frame_benchmarking::benchmarking::HostFunctions, ); + +native_executor_instance!( + pub OrigamiExecutor, + origami_runtime::api::dispatch, + origami_runtime::native_version, + frame_benchmarking::benchmarking::HostFunctions, +); + /// A set of APIs that polkadot-like runtimes must implement. pub trait RuntimeApiCollection: sp_transaction_pool::runtime_api::TaggedTransactionQueue @@ -686,6 +695,38 @@ pub fn westend_new_full( Ok((components, client, FullNodeHandles)) } +/// Create a new Polkadot service for a full node. +#[cfg(feature = "full-node")] +pub fn origami_new_full( + mut config: Configuration, + collating_for: Option<(CollatorId, parachain::Id)>, + _max_block_data_size: Option, + _authority_discovery_enabled: bool, + _slot_duration: u64, + grandpa_pause: Option<(u32, u32)>, +) + -> Result<( + TaskManager, + Arc, + polkadot_runtime::RuntimeApi + >>, + FullNodeHandles, + ), ServiceError> +{ + let (components, client) = new_full!( + config, + collating_for, + authority_discovery_enabled, + grandpa_pause, + origami_runtime::RuntimeApi, + OrigamiExecutor, + ); + + Ok((components, client, FullNodeHandles)) +} + /// Create a new Polkadot service for a light client. pub fn polkadot_new_light(mut config: Configuration) -> Result { diff --git a/runtime/origami/Cargo.toml b/runtime/origami/Cargo.toml new file mode 100644 index 000000000000..199ed8a8a47f --- /dev/null +++ b/runtime/origami/Cargo.toml @@ -0,0 +1,172 @@ +[package] +name = "origami-runtime" +version = "0.0.1" +authors = ["Parity Technologies "] +edition = "2018" +build = "build.rs" + +[dependencies] +bitvec = { version = "0.17.4", default-features = false, features = ["alloc"] } +codec = { package = "parity-scale-codec", version = "1.2.0", default-features = false, features = ["derive"] } +log = { version = "0.3.9", optional = true } +rustc-hex = { version = "2.0.1", default-features = false } +serde = { version = "1.0.102", default-features = false } +serde_derive = { version = "1.0.102", optional = true } +static_assertions = "1.1.0" +smallvec = "1.4.0" + +authority-discovery-primitives = { package = "sp-authority-discovery", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +babe-primitives = { package = "sp-consensus-babe", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +sp-api = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +inherents = { package = "sp-inherents", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +offchain-primitives = { package = "sp-offchain", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +sp-std = { package = "sp-std", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +sp-staking = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +sp-session = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +version = { package = "sp-version", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +tx-pool-api = { package = "sp-transaction-pool", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +block-builder-api = { package = "sp-block-builder", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } + +authority-discovery = { package = "pallet-authority-discovery", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +authorship = { package = "pallet-authorship", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +babe = { package = "pallet-babe", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +balances = { package = "pallet-balances", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +transaction-payment = { package = "pallet-transaction-payment", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +transaction-payment-rpc-runtime-api = { package = "pallet-transaction-payment-rpc-runtime-api", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +collective = { package = "pallet-collective", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +democracy = { package = "pallet-democracy", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +elections-phragmen = { package = "pallet-elections-phragmen", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +executive = { package = "frame-executive", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +finality-tracker = { package = "pallet-finality-tracker", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +grandpa = { package = "pallet-grandpa", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +identity = { package = "pallet-identity", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +im-online = { package = "pallet-im-online", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +indices = { package = "pallet-indices", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +membership = { package = "pallet-membership", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +multisig = { package = "pallet-multisig", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +nicks = { package = "pallet-nicks", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +offences = { package = "pallet-offences", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +proxy = { package = "pallet-proxy", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +randomness-collective-flip = { package = "pallet-randomness-collective-flip", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +scheduler = { package = "pallet-scheduler", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +session = { package = "pallet-session", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +frame-support = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +staking = { package = "pallet-staking", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +pallet-staking-reward-curve = { git = "https://github.com/paritytech/substrate", branch = "master" } +system = { package = "frame-system", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +system_rpc_runtime_api = { package = "frame-system-rpc-runtime-api", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +timestamp = { package = "pallet-timestamp", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +treasury = { package = "pallet-treasury", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +sudo = { package = "pallet-sudo", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +vesting = { package = "pallet-vesting", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +utility = { package = "pallet-utility", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } + +frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false, optional = true } +frame-system-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false, optional = true } +pallet-offences-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false, optional = true } +pallet-session-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false, optional = true } +hex-literal = { version = "0.2.1", optional = true } + +runtime-common = { package = "polkadot-runtime-common", path = "../common", default-features = false } +primitives = { package = "polkadot-primitives", path = "../../primitives", default-features = false } + +[dev-dependencies] +hex-literal = "0.2.1" +libsecp256k1 = "0.3.2" +tiny-keccak = "1.5.0" +keyring = { package = "sp-keyring", git = "https://github.com/paritytech/substrate", branch = "master" } +sp-trie = { git = "https://github.com/paritytech/substrate", branch = "master" } +trie-db = "0.20.0" +serde_json = "1.0.41" + +[build-dependencies] +wasm-builder-runner = { package = "substrate-wasm-builder-runner", version = "1.0.6" } + +[features] +default = ["std"] +no_std = [] +only-staking = [] +std = [ + "authority-discovery-primitives/std", + "authority-discovery/std", + "bitvec/std", + "primitives/std", + "rustc-hex/std", + "codec/std", + "inherents/std", + "sp-core/std", + "sp-api/std", + "tx-pool-api/std", + "block-builder-api/std", + "offchain-primitives/std", + "sp-std/std", + "frame-support/std", + "authorship/std", + "balances/std", + "transaction-payment/std", + "transaction-payment-rpc-runtime-api/std", + "collective/std", + "elections-phragmen/std", + "democracy/std", + "executive/std", + "finality-tracker/std", + "grandpa/std", + "identity/std", + "im-online/std", + "indices/std", + "membership/std", + "multisig/std", + "nicks/std", + "offences/std", + "proxy/std", + "sp-runtime/std", + "sp-staking/std", + "scheduler/std", + "session/std", + "staking/std", + "system/std", + "system_rpc_runtime_api/std", + "timestamp/std", + "treasury/std", + "version/std", + "serde_derive", + "serde/std", + "log", + "babe/std", + "babe-primitives/std", + "sp-session/std", + "randomness-collective-flip/std", + "runtime-common/std", + "sudo/std", + "vesting/std", + "utility/std", +] +runtime-benchmarks = [ + "runtime-common/runtime-benchmarks", + "frame-benchmarking", + "frame-support/runtime-benchmarks", + "frame-system-benchmarking", + "system/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", + "balances/runtime-benchmarks", + "collective/runtime-benchmarks", + "democracy/runtime-benchmarks", + "elections-phragmen/runtime-benchmarks", + "im-online/runtime-benchmarks", + "scheduler/runtime-benchmarks", + "staking/runtime-benchmarks", + "timestamp/runtime-benchmarks", + "treasury/runtime-benchmarks", + "vesting/runtime-benchmarks", + "pallet-offences-benchmarking", + "pallet-session-benchmarking", + "hex-literal", +] +# When enabled, the runtime api will not be build. +# +# This is required by Cumulus to access certain types of the +# runtime without clashing with the runtime api exported functions +# in WASM. +disable-runtime-api = [] diff --git a/runtime/origami/README.adoc b/runtime/origami/README.adoc new file mode 100644 index 000000000000..d51607f7bdae --- /dev/null +++ b/runtime/origami/README.adoc @@ -0,0 +1,5 @@ + += Origami Runtime + +A simple test runtime pulling in all parachain relevant blocks, to create a test +runtime for a relay-chain. \ No newline at end of file diff --git a/runtime/origami/build.rs b/runtime/origami/build.rs new file mode 100644 index 000000000000..4ad34b2b5293 --- /dev/null +++ b/runtime/origami/build.rs @@ -0,0 +1,26 @@ +// Copyright 2019-2020 Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Substrate is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Substrate. If not, see . + +use wasm_builder_runner::WasmBuilder; + +fn main() { + WasmBuilder::new() + .with_current_project() + .with_wasm_builder_from_crates("1.0.11") + .import_memory() + .export_heap_base() + .build() +} diff --git a/runtime/origami/src/constants.rs b/runtime/origami/src/constants.rs new file mode 100644 index 000000000000..04758a9d07c7 --- /dev/null +++ b/runtime/origami/src/constants.rs @@ -0,0 +1,85 @@ +//! Helper module to build a genesis configuration for the super-runtime + +use super::{ + AccountId, BabeConfig, BalancesConfig, GenesisConfig, GrandpaConfig, Signature, SudoConfig, + SystemConfig, WASM_BINARY, +}; +use sp_consensus_babe::AuthorityId as BabeId; +use sp_core::{sr25519, Pair, Public}; +use sp_finality_grandpa::AuthorityId as GrandpaId; +use sp_runtime::traits::{IdentifyAccount, Verify}; + +/// Helper function to generate a crypto pair from seed +fn get_from_seed(seed: &str) -> ::Public { + TPublic::Pair::from_string(&format!("//{}", seed), None) + .expect("static values are valid; qed") + .public() +} + +type AccountPublic = ::Signer; + +/// Helper function to generate an account ID from seed +pub fn account_id_from_seed(seed: &str) -> AccountId +where + AccountPublic: From<::Public>, +{ + AccountPublic::from(get_from_seed::(seed)).into_account() +} + +/// Helper function to generate session key from seed +pub fn authority_keys_from_seed(seed: &str) -> (BabeId, GrandpaId) { + ( + get_from_seed::(seed), + get_from_seed::(seed), + ) +} + +pub fn dev_genesis() -> GenesisConfig { + testnet_genesis( + // Initial Authorities + vec![authority_keys_from_seed("Alice")], + // Root Key + account_id_from_seed::("Alice"), + // Endowed Accounts + vec![ + account_id_from_seed::("Alice"), + account_id_from_seed::("Bob"), + account_id_from_seed::("Alice//stash"), + account_id_from_seed::("Bob//stash"), + ], + ) +} + +/// Helper function to build a genesis configuration +pub fn testnet_genesis( + initial_authorities: Vec<(BabeId, GrandpaId)>, + root_key: AccountId, + endowed_accounts: Vec, +) -> GenesisConfig { + GenesisConfig { + system: Some(SystemConfig { + code: WASM_BINARY.to_vec(), + changes_trie_config: Default::default(), + }), + balances: Some(BalancesConfig { + balances: endowed_accounts + .iter() + .cloned() + .map(|k| (k, 1 << 60)) + .collect(), + }), + sudo: Some(SudoConfig { key: root_key }), + babe: Some(BabeConfig { + authorities: initial_authorities + .iter() + .map(|x| (x.0.clone(), 1)) + .collect(), + }), + grandpa: Some(GrandpaConfig { + authorities: initial_authorities + .iter() + .map(|x| (x.1.clone(), 1)) + .collect(), + }), + } +} diff --git a/runtime/origami/src/lib.rs b/runtime/origami/src/lib.rs new file mode 100644 index 000000000000..d89fccf1408f --- /dev/null +++ b/runtime/origami/src/lib.rs @@ -0,0 +1,435 @@ +//! A Super Runtime. This runtime demonstrates most the recipe pallets in a single super runtime. + +#![cfg_attr(not(feature = "std"), no_std)] +// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256. +#![recursion_limit = "256"] +#![allow(clippy::large_enum_variant)] + +// Make the WASM binary available. +#[cfg(feature = "std")] +include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); + +// Include the genesis helper module when building to std +#[cfg(feature = "std")] +pub mod genesis; + +use babe::SameAuthoritiesForever; +use frame_system as system; +use grandpa::{AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList}; +use sp_api::impl_runtime_apis; +use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256}; +use sp_runtime::traits::{ + BlakeTwo256, Block as BlockT, IdentifyAccount, IdentityLookup, NumberFor, Saturating, Verify, +}; +use sp_runtime::{ + create_runtime_str, generic, impl_opaque_keys, + transaction_validity::{TransactionSource, TransactionValidity}, + ApplyExtrinsicResult, MultiSignature, +}; +use sp_std::prelude::*; + +#[cfg(feature = "std")] +use sp_version::NativeVersion; +use sp_version::RuntimeVersion; + +// A few exports that help ease life for downstream crates. +pub use balances::Call as BalancesCall; +pub use frame_support::{ + construct_runtime, debug, parameter_types, + traits::{KeyOwnerProofSystem, Randomness}, + weights::{ + constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND}, + IdentityFee, Weight, + }, + StorageValue, +}; +#[cfg(any(feature = "std", test))] +pub use sp_runtime::BuildStorage; +pub use sp_runtime::{Perbill, Permill}; +pub use timestamp::Call as TimestampCall; + +/// An index to a block. +pub type BlockNumber = u32; + +/// Alias to 512-bit hash when used in the context of a transaction signature on the chain. +pub type Signature = MultiSignature; + +/// Some way of identifying an account on the chain. We intentionally make it equivalent +/// to the public key of our transaction signing scheme. +pub type AccountId = <::Signer as IdentifyAccount>::AccountId; + +/// The type for looking up accounts. We don't expect more than 4 billion of them, but you +/// never know... +pub type AccountIndex = u32; + +/// Balance of an account. +pub type Balance = u128; + +/// Index of a transaction in the chain. +pub type Index = u32; + +/// A hash of some data used by the chain. +pub type Hash = H256; + +/// Digest item type. +pub type DigestItem = generic::DigestItem; + +/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know +/// the specifics of the runtime. They can then be made to be agnostic over specific formats +/// of data like extrinsics, allowing for them to continue syncing the network through upgrades +/// to even the core datastructures. +pub mod opaque { + use super::*; + + pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic; + + /// Opaque block header type. + pub type Header = generic::Header; + /// Opaque block type. + pub type Block = generic::Block; + /// Opaque block identifier type. + pub type BlockId = generic::BlockId; + + impl_opaque_keys! { + pub struct SessionKeys { + pub grandpa: Grandpa, //TODO is this order correct? I changed stuff in chainspec. + pub babe: Babe, + } + } +} + +/// This runtime version. +pub const VERSION: RuntimeVersion = RuntimeVersion { + spec_name: create_runtime_str!("super-runtime"), + impl_name: create_runtime_str!("super-runtime"), + authoring_version: 1, + spec_version: 1, + impl_version: 1, + apis: RUNTIME_API_VERSIONS, + transaction_version: 1, +}; + +pub const MILLISECS_PER_BLOCK: u64 = 6000; + +pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK; + +// These time units are defined in number of blocks. +pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber); +pub const HOURS: BlockNumber = MINUTES * 60; +pub const DAYS: BlockNumber = HOURS * 24; + +// Some BABE-specific stuff +// 1 in 4 blocks (on average, not counting collisions) will be primary babe blocks. +pub const PRIMARY_PROBABILITY: (u64, u64) = (1, 4); +pub const EPOCH_DURATION_IN_BLOCKS: u32 = 10 * MINUTES; + +/// The version infromation used to identify this runtime when compiled natively. +#[cfg(feature = "std")] +pub fn native_version() -> NativeVersion { + NativeVersion { + runtime_version: VERSION, + can_author_with: Default::default(), + } +} + +parameter_types! { + pub const BlockHashCount: BlockNumber = 250; + pub const MaximumBlockWeight: Weight = 2 * WEIGHT_PER_SECOND; + pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); + /// Assume 10% of weight for average on_initialize calls. + pub MaximumExtrinsicWeight: Weight = AvailableBlockRatio::get() + .saturating_sub(Perbill::from_percent(10)) * MaximumBlockWeight::get(); + pub const MaximumBlockLength: u32 = 5 * 1024 * 1024; + pub const Version: RuntimeVersion = VERSION; +} + +impl system::Trait for Runtime { + /// The identifier used to distinguish between accounts. + type AccountId = AccountId; + /// The aggregated dispatch type that is available for extrinsics. + type Call = Call; + /// The lookup mechanism to get account ID from whatever is passed in dispatchers. + type Lookup = IdentityLookup; + /// The index type for storing how many extrinsics an account has signed. + type Index = Index; + /// The index type for blocks. + type BlockNumber = BlockNumber; + /// The type for hashing blocks and tries. + type Hash = Hash; + /// The hashing algorithm used. + type Hashing = BlakeTwo256; + /// The header type. + type Header = generic::Header; + /// The ubiquitous event type. + type Event = Event; + /// The ubiquitous origin type. + type Origin = Origin; + /// Maximum number of block number to block hash mappings to keep (oldest pruned first). + type BlockHashCount = BlockHashCount; + /// Maximum weight of each block. With a default weight system of 1byte == 1weight, 4mb is ok. + type MaximumBlockWeight = MaximumBlockWeight; + /// The weight of database operations that the runtime can invoke. + type DbWeight = RocksDbWeight; + /// The weight of the overhead invoked on the block import process, independent of the + /// extrinsics included in that block. + type BlockExecutionWeight = BlockExecutionWeight; + /// The base weight of any extrinsic processed by the runtime, independent of the + /// logic of that extrinsic. (Signature verification, nonce increment, fee, etc...) + type ExtrinsicBaseWeight = ExtrinsicBaseWeight; + /// The maximum weight that a single extrinsic of `Normal` dispatch class can have, + /// idependent of the logic of that extrinsic. (Roughly max block weight - average + /// on_initialize cost). + type MaximumExtrinsicWeight = MaximumExtrinsicWeight; + /// Maximum size of all encoded transactions (in bytes) that are allowed in one block. + type MaximumBlockLength = MaximumBlockLength; + /// Portion of the block weight that is available to all normal transactions. + type AvailableBlockRatio = AvailableBlockRatio; + /// Version of the runtime. + type Version = Version; + /// Converts a module to the index of the module in `construct_runtime!`. + /// + /// This type is being generated by `construct_runtime!`. + type ModuleToIndex = ModuleToIndex; + /// What to do if a new account is created. + type OnNewAccount = (); + /// What to do if an account is fully reaped from the system. + type OnKilledAccount = (); + /// The data to be stored in an account. + type AccountData = balances::AccountData; +} + +parameter_types! { + pub const EpochDuration: u64 = EPOCH_DURATION_IN_BLOCKS as u64; + pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK; +} + +impl babe::Trait for Runtime { + type EpochDuration = EpochDuration; + type ExpectedBlockTime = ExpectedBlockTime; + type EpochChangeTrigger = SameAuthoritiesForever; +} + +impl grandpa::Trait for Runtime { + type Event = Event; + type Call = Call; + type KeyOwnerProofSystem = (); + type KeyOwnerProof = + >::Proof; + type KeyOwnerIdentification = >::IdentificationTuple; + type HandleEquivocation = (); +} + +parameter_types! { + pub const MinimumPeriod: u64 = SLOT_DURATION / 2; +} + +impl timestamp::Trait for Runtime { + /// A timestamp: milliseconds since the unix epoch. + type Moment = u64; + type OnTimestampSet = Babe; + type MinimumPeriod = MinimumPeriod; +} + +parameter_types! { + pub const ExistentialDeposit: u128 = 500; + pub const TransferFee: u128 = 0; + pub const CreationFee: u128 = 0; +} + +impl balances::Trait for Runtime { + /// The type for recording an account's balance. + type Balance = Balance; + /// The ubiquitous event type. + type Event = Event; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; +} + +parameter_types! { + pub const TransactionByteFee: u128 = 1; +} + +impl transaction_payment::Trait for Runtime { + type Currency = balances::Module; + type OnTransactionPayment = (); + type TransactionByteFee = TransactionByteFee; + type WeightToFee = IdentityFee; + type FeeMultiplierUpdate = (); +} + +impl sudo::Trait for Runtime { + type Event = Event; + type Call = Call; +} + +construct_runtime!( + pub enum Runtime where + Block = Block, + NodeBlock = opaque::Block, + UncheckedExtrinsic = UncheckedExtrinsic + { + System: system::{Module, Call, Storage, Config, Event}, + Timestamp: timestamp::{Module, Call, Storage, Inherent}, + Babe: babe::{Module, Call, Storage, Config, Inherent(Timestamp)}, + Grandpa: grandpa::{Module, Call, Storage, Config, Event}, + Balances: balances::{Module, Call, Storage, Config, Event}, + RandomnessCollectiveFlip: randomness_collective_flip::{Module, Call, Storage}, + Sudo: sudo::{Module, Call, Config, Storage, Event}, + TransactionPayment: transaction_payment::{Module, Storage}, + // The Recipe Pallets + // (None) + } +); + +/// The address format for describing accounts. +pub type Address = AccountId; +/// Block header type as expected by this runtime. +pub type Header = generic::Header; +/// Block type as expected by this runtime. +pub type Block = generic::Block; +/// A Block signed with a Justification +pub type SignedBlock = generic::SignedBlock; +/// BlockId type as expected by this runtime. +pub type BlockId = generic::BlockId; +/// The SignedExtension to the basic transaction logic. +pub type SignedExtra = ( + system::CheckTxVersion, + system::CheckGenesis, + system::CheckEra, + system::CheckNonce, + system::CheckWeight, + transaction_payment::ChargeTransactionPayment, +); +/// Unchecked extrinsic type as expected by this runtime. +pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; +/// Extrinsic type that has already been checked. +pub type CheckedExtrinsic = generic::CheckedExtrinsic; +/// Executive: handles dispatch to the various pallets. +pub type Executive = + frame_executive::Executive, Runtime, AllModules>; + +impl_runtime_apis! { + impl sp_api::Core for Runtime { + fn version() -> RuntimeVersion { + VERSION + } + + fn execute_block(block: Block) { + Executive::execute_block(block) + } + + fn initialize_block(header: &::Header) { + Executive::initialize_block(header) + } + } + + impl sp_api::Metadata for Runtime { + fn metadata() -> OpaqueMetadata { + Runtime::metadata().into() + } + } + + impl sp_block_builder::BlockBuilder for Runtime { + fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { + Executive::apply_extrinsic(extrinsic) + } + + fn finalize_block() -> ::Header { + Executive::finalize_block() + } + + fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { + data.create_extrinsics() + } + + fn check_inherents( + block: Block, + data: sp_inherents::InherentData + ) -> sp_inherents::CheckInherentsResult { + data.check_extrinsics(&block) + } + + fn random_seed() -> ::Hash { + RandomnessCollectiveFlip::random_seed() + } + } + + impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { + fn validate_transaction( + source: TransactionSource, + tx: ::Extrinsic + ) -> TransactionValidity { + Executive::validate_transaction(source, tx) + } + } + + impl sp_offchain::OffchainWorkerApi for Runtime { + fn offchain_worker(header: &::Header) { + Executive::offchain_worker(header) + } + } + + impl sp_finality_grandpa::GrandpaApi for Runtime { + fn grandpa_authorities() -> GrandpaAuthorityList { + Grandpa::grandpa_authorities() + } + + fn submit_report_equivocation_extrinsic( + _equivocation_proof: sp_finality_grandpa::EquivocationProof< + ::Hash, + NumberFor, + >, + _key_owner_proof: sp_finality_grandpa::OpaqueKeyOwnershipProof, + ) -> Option<()> { + None + } + + fn generate_key_ownership_proof( + _set_id: sp_finality_grandpa::SetId, + _authority_id: GrandpaId, + ) -> Option { + // NOTE: this is the only implementation possible since we've + // defined our key owner proof type as a bottom type (i.e. a type + // with no values). + None + } + } + + impl sp_consensus_babe::BabeApi for Runtime { + fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration { + // The choice of `c` parameter (where `1 - c` represents the + // probability of a slot being empty), is done in accordance to the + // slot duration and expected target block time, for safely + // resisting network delays of maximum two seconds. + // + sp_consensus_babe::BabeGenesisConfiguration { + slot_duration: Babe::slot_duration(), + epoch_length: EpochDuration::get(), + c: PRIMARY_PROBABILITY, + genesis_authorities: Babe::authorities(), + randomness: Babe::randomness(), + allowed_slots: sp_consensus_babe::AllowedSlots::PrimaryAndSecondaryPlainSlots, + } + } + + fn current_epoch_start() -> sp_consensus_babe::SlotNumber { + Babe::current_epoch_start() + } + } + + impl sp_session::SessionKeys for Runtime { + fn generate_session_keys(seed: Option>) -> Vec { + opaque::SessionKeys::generate(seed) + } + + fn decode_session_keys( + encoded: Vec, + ) -> Option, sp_core::crypto::KeyTypeId)>> { + opaque::SessionKeys::decode_into_raw_public_keys(&encoded) + } + } +}