diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 938ee00ad64e4..67519137a4e59 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -150,12 +150,12 @@ check-web-wasm: &test script: # WASM support is in progress. As more and more crates support WASM, we # should add entries here. See https://github.com/paritytech/polkadot/issues/625 - - time cargo build --locked --target=wasm32-unknown-unknown --manifest-path executor/Cargo.toml + - time cargo build --locked --target=wasm32-unknown-unknown --manifest-path runtime/polkadot/Cargo.toml + - time cargo build --locked --target=wasm32-unknown-unknown --manifest-path runtime/kusama/Cargo.toml - time cargo build --locked --target=wasm32-unknown-unknown --manifest-path erasure-coding/Cargo.toml - time cargo build --locked --target=wasm32-unknown-unknown --manifest-path parachain/Cargo.toml - time cargo build --locked --target=wasm32-unknown-unknown --manifest-path primitives/Cargo.toml - time cargo build --locked --target=wasm32-unknown-unknown --manifest-path rpc/Cargo.toml - - time cargo build --locked --target=wasm32-unknown-unknown --manifest-path runtime/Cargo.toml - time cargo build --locked --target=wasm32-unknown-unknown --manifest-path statement-table/Cargo.toml - sccache -s diff --git a/Cargo.lock b/Cargo.lock index 57be83894aa7f..b843ef534b17e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2029,6 +2029,72 @@ dependencies = [ "winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "kusama-runtime" +version = "0.7.11" +dependencies = [ + "bitvec 0.15.2 (registry+https://github.com/rust-lang/crates.io-index)", + "frame-executive 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "frame-support 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "frame-system 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "frame-system-rpc-runtime-api 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "hex-literal 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libsecp256k1 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", + "pallet-authority-discovery 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-authorship 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-babe 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-balances 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-collective 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-democracy 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-elections-phragmen 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-finality-tracker 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-grandpa 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-identity 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-im-online 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-indices 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-membership 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-nicks 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-offences 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-randomness-collective-flip 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-session 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-staking 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-staking-reward-curve 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-timestamp 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-transaction-payment 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-transaction-payment-rpc-runtime-api 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-treasury 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-utility 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "parity-scale-codec 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "polkadot-parachain 0.7.11", + "polkadot-primitives 0.7.11", + "polkadot-runtime-common 0.7.10", + "rustc-hex 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "safe-mix 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.102 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_derive 1.0.102 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.41 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-api 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-authority-discovery 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-block-builder 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-consensus-babe 0.8.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-core 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-inherents 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-io 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-keyring 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-offchain 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-runtime 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-session 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-staking 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-std 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-transaction-pool 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-trie 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-version 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "substrate-wasm-builder-runner 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", + "tiny-keccak 1.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "trie-db 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "kv-log-macro" version = "1.0.4" @@ -3639,7 +3705,6 @@ dependencies = [ "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", "polkadot-erasure-coding 0.7.11", "polkadot-primitives 0.7.11", - "polkadot-runtime 0.7.11", "sc-client 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sc-client-api 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sc-keystore 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", @@ -3686,16 +3751,16 @@ dependencies = [ "polkadot-cli 0.7.11", "polkadot-network 0.7.11", "polkadot-primitives 0.7.11", - "polkadot-runtime 0.7.11", "polkadot-service 0.7.11", "polkadot-validation 0.7.11", "sc-client 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sc-client-api 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sc-network 0.8.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-blockchain 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-consensus 0.8.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-core 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-keyring 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", - "tokio 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", + "tokio 0.1.22 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3710,14 +3775,6 @@ dependencies = [ "sp-trie 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", ] -[[package]] -name = "polkadot-executor" -version = "0.7.11" -dependencies = [ - "polkadot-runtime 0.7.11", - "sc-executor 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", -] - [[package]] name = "polkadot-network" version = "0.7.11" @@ -3774,6 +3831,7 @@ dependencies = [ "sp-api 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-application-crypto 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-core 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-inherents 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-runtime 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-serializer 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-std 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", @@ -3787,8 +3845,8 @@ version = "0.7.11" dependencies = [ "jsonrpc-core 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)", "pallet-transaction-payment-rpc 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "parity-scale-codec 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "polkadot-primitives 0.7.11", - "polkadot-runtime 0.7.11", "sc-client 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sc-rpc 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-runtime 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", @@ -3831,10 +3889,10 @@ dependencies = [ "pallet-transaction-payment 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "pallet-transaction-payment-rpc-runtime-api 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "pallet-treasury 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", - "pallet-utility 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "parity-scale-codec 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "polkadot-parachain 0.7.11", "polkadot-primitives 0.7.11", + "polkadot-runtime-common 0.7.10", "rustc-hex 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "safe-mix 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.102 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3846,11 +3904,9 @@ dependencies = [ "sp-consensus-babe 0.8.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-core 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-inherents 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", - "sp-io 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-keyring 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-offchain 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-runtime 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", - "sp-serializer 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-session 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-staking 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-std 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", @@ -3862,21 +3918,63 @@ dependencies = [ "trie-db 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "polkadot-runtime-common" +version = "0.7.10" +dependencies = [ + "bitvec 0.15.2 (registry+https://github.com/rust-lang/crates.io-index)", + "frame-support 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "frame-system 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "hex-literal 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libsecp256k1 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", + "pallet-authorship 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-babe 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-balances 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-randomness-collective-flip 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-session 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-staking 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-staking-reward-curve 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-timestamp 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-treasury 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "parity-scale-codec 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "polkadot-parachain 0.7.11", + "polkadot-primitives 0.7.11", + "rustc-hex 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.102 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_derive 1.0.102 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.41 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-api 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-core 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-inherents 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-io 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-keyring 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-runtime 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-staking 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-std 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-trie 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "tiny-keccak 1.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "trie-db 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "polkadot-service" version = "0.7.11" dependencies = [ + "frame-system-rpc-runtime-api 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "futures 0.1.29 (registry+https://github.com/rust-lang/crates.io-index)", "futures 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", "hex-literal 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "kusama-runtime 0.7.11", "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "pallet-babe 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "pallet-im-online 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "pallet-staking 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "pallet-transaction-payment-rpc-runtime-api 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "parity-scale-codec 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", "polkadot-availability-store 0.7.11", - "polkadot-executor 0.7.11", "polkadot-network 0.7.11", "polkadot-primitives 0.7.11", "polkadot-rpc 0.7.11", @@ -3897,13 +3995,17 @@ dependencies = [ "slog 2.5.2 (registry+https://github.com/rust-lang/crates.io-index)", "sp-api 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-authority-discovery 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-block-builder 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-blockchain 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-consensus 0.8.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-consensus-babe 0.8.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-core 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-finality-grandpa 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-inherents 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-io 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-offchain 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-runtime 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", + "sp-session 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sp-transaction-pool 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", ] @@ -3933,7 +4035,6 @@ dependencies = [ "polkadot-erasure-coding 0.7.11", "polkadot-parachain 0.7.11", "polkadot-primitives 0.7.11", - "polkadot-runtime 0.7.11", "polkadot-statement-table 0.7.11", "sc-block-builder 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", "sc-client-api 2.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-master)", diff --git a/Cargo.toml b/Cargo.toml index 9506c09a1d5a8..f02f707e8e108 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,10 +24,11 @@ members = [ "cli", "collator", "erasure-coding", - "executor", "network", "primitives", - "runtime", + "runtime/common", + "runtime/polkadot", + "runtime/kusama", "service", "statement-table", "service", @@ -37,7 +38,8 @@ members = [ "test-parachains/adder/collator", ] exclude = [ - "runtime/wasm", + "runtime/polkadot/wasm", + "runtime/kusama/wasm", "test-parachains/adder/wasm", ] diff --git a/availability-store/Cargo.toml b/availability-store/Cargo.toml index 731c765465f15..5650f36e678d5 100644 --- a/availability-store/Cargo.toml +++ b/availability-store/Cargo.toml @@ -8,7 +8,6 @@ edition = "2018" [dependencies] polkadot-primitives = { path = "../primitives" } polkadot-erasure-coding = { path = "../erasure-coding" } -polkadot-runtime = { path = "../runtime" } parking_lot = "0.9.0" derive_more = "0.99" log = "0.4.8" diff --git a/cli/src/chain_spec.rs b/cli/src/chain_spec.rs index 8afb7daa26aa6..837e818d8ae0b 100644 --- a/cli/src/chain_spec.rs +++ b/cli/src/chain_spec.rs @@ -41,12 +41,19 @@ impl Default for ChainSpec { /// Get a chain config from a spec setting. impl ChainSpec { pub(crate) fn load(self) -> Result { - Ok(match self { - ChainSpec::Kusama => service::chain_spec::kusama_config()?, - ChainSpec::Development => service::chain_spec::development_config(), - ChainSpec::LocalTestnet => service::chain_spec::local_testnet_config(), - ChainSpec::StagingTestnet => service::chain_spec::staging_testnet_config(), - }) + match self { + ChainSpec::Development => Ok(service::chain_spec::development_config()), + ChainSpec::LocalTestnet => Ok(service::chain_spec::local_testnet_config()), + ChainSpec::StagingTestnet => Ok(service::chain_spec::staging_testnet_config()), + ChainSpec::Kusama => service::chain_spec::kusama_config(), + } + } + + pub(crate) fn is_kusama(&self) -> bool { + match self { + ChainSpec::Development | ChainSpec::LocalTestnet | ChainSpec::StagingTestnet => false, + ChainSpec::Kusama => true, + } } pub(crate) fn from(s: &str) -> Option { diff --git a/cli/src/lib.rs b/cli/src/lib.rs index c2c1a0255dc88..0ae963e5d1e1f 100644 --- a/cli/src/lib.rs +++ b/cli/src/lib.rs @@ -26,53 +26,27 @@ mod browser; use chain_spec::ChainSpec; use futures::{ Future, FutureExt, TryFutureExt, future::select, channel::oneshot, compat::Future01CompatExt, - task::Spawn }; use tokio::runtime::Runtime; -use log::{info, error}; +use log::info; use structopt::StructOpt; pub use service::{ - AbstractService, CustomConfiguration, - ProvideRuntimeApi, CoreApi, ParachainHost, + AbstractService, CustomConfiguration, ProvideRuntimeApi, CoreApi, ParachainHost, IsKusama, self, WrappedExecutor }; -pub use cli::{VersionInfo, IntoExit, NoCustom}; +pub use cli::{VersionInfo, IntoExit, NoCustom, SharedParams}; pub use cli::{display_role, error}; -fn load_spec(id: &str) -> Result, String> { +/// Load the `ChainSpec` for the given `id`. +pub fn load_spec(id: &str) -> Result, String> { Ok(match ChainSpec::from(id) { Some(spec) => Some(spec.load()?), None => None, }) } -/// Additional worker making use of the node, to run asynchronously before shutdown. -/// -/// This will be invoked with the service and spawn a future that resolves -/// when complete. -pub trait Worker: IntoExit { - /// A future that resolves when the work is done or the node should exit. - /// This will be run on a tokio runtime. - type Work: Future + Unpin + Send + 'static; - - /// Return configuration for the polkadot node. - // TODO: make this the full configuration, so embedded nodes don't need - // string CLI args (https://github.com/paritytech/polkadot/issues/111) - fn configuration(&self) -> service::CustomConfiguration { Default::default() } - - /// Do work and schedule exit. - fn work(self, service: &S, spawner: SP) -> Self::Work - where S: AbstractService, - SC: service::SelectChain + 'static, - B: service::Backend + 'static, - CE: service::CallExecutor + Clone + Send + Sync + 'static, - SP: Spawn + Clone + Send + Sync + 'static; -} - #[derive(Debug, StructOpt, Clone)] enum PolkadotSubCommands { #[structopt(name = "validation-worker", setting = structopt::clap::AppSettings::Hidden)] @@ -96,81 +70,111 @@ struct PolkadotSubParams { } /// Parses polkadot specific CLI arguments and run the service. -pub fn run(worker: W, version: cli::VersionInfo) -> error::Result<()> where - W: Worker, -{ - match cli::parse_and_prepare::( +pub fn run(exit: E, version: cli::VersionInfo) -> error::Result<()> { + let cmd = cli::parse_and_prepare::( &version, "parity-polkadot", std::env::args(), - ) { - cli::ParseAndPrepare::Run(cmd) => cmd.run(load_spec, worker, - |worker, _cli_args, custom_args, mut config| { - info!("{}", version.name); - info!(" version {}", config.full_version()); - info!(" by {}, 2017-2019", version.author); - info!("Chain specification: {}", config.chain_spec.name()); - if config.chain_spec.name().starts_with("Kusama") { - info!("----------------------------"); - info!("This chain is not in any way"); - info!(" endorsed by the "); - info!(" KUSAMA FOUNDATION "); - info!("----------------------------"); - } - info!("Node name: {}", config.name); - info!("Roles: {}", display_role(&config)); - config.custom = worker.configuration(); - config.custom.authority_discovery_enabled = custom_args.authority_discovery_enabled; - let runtime = Runtime::new().map_err(|e| format!("{:?}", e))?; - match config.roles { - service::Roles::LIGHT => - run_until_exit( - runtime, - service::new_light(config).map_err(|e| format!("{:?}", e))?, - worker - ), - _ => run_until_exit( + ); + if cmd + .shared_params() + .and_then(|p| p.chain.as_ref()) + .and_then(|c| ChainSpec::from(c)) + .map_or(false, |c| c.is_kusama()) + { + execute_cmd_with_runtime::< + service::kusama_runtime::RuntimeApi, + service::KusamaExecutor, + service::kusama_runtime::UncheckedExtrinsic, + _ + >(exit, &version, cmd) + } else { + execute_cmd_with_runtime::< + service::polkadot_runtime::RuntimeApi, + service::PolkadotExecutor, + service::polkadot_runtime::UncheckedExtrinsic, + _ + >(exit, &version, cmd) + } +} + +/// Execute the given `cmd` with the given runtime. +fn execute_cmd_with_runtime( + exit: X, + version: &cli::VersionInfo, + cmd: cli::ParseAndPrepare, +) -> error::Result<()> +where + R: service::ConstructRuntimeApi> + + service::ConstructRuntimeApi> + + Send + Sync + 'static, + >>::RuntimeApi: service::RuntimeApiCollection, + >>::RuntimeApi: service::RuntimeApiCollection, + E: service::Codec + Send + Sync + 'static, + D: service::NativeExecutionDispatch + 'static, + X: IntoExit, +{ + match cmd { + cli::ParseAndPrepare::Run(cmd) => cmd.run(&load_spec, exit, + |exit, _cli_args, custom_args, mut config| { + info!("{}", version.name); + info!(" version {}", config.full_version()); + info!(" by {}, 2017-2019", version.author); + info!("Chain specification: {}", config.chain_spec.name()); + if config.is_kusama() { + info!("----------------------------"); + info!("This chain is not in any way"); + info!(" endorsed by the "); + info!(" KUSAMA FOUNDATION "); + info!("----------------------------"); + } + info!("Node name: {}", config.name); + info!("Roles: {}", display_role(&config)); + config.custom = service::CustomConfiguration::default(); + config.custom.authority_discovery_enabled = custom_args.authority_discovery_enabled; + let runtime = Runtime::new().map_err(|e| format!("{:?}", e))?; + match config.roles { + service::Roles::LIGHT => + run_until_exit( + runtime, + service::new_light::(config).map_err(|e| format!("{:?}", e))?, + exit.into_exit(), + ), + _ => run_until_exit( runtime, - service::new_full(config).map_err(|e| format!("{:?}", e))?, - worker + service::new_full::(config).map_err(|e| format!("{:?}", e))?, + exit.into_exit(), ), - }.map_err(|e| format!("{:?}", e)) - }), - cli::ParseAndPrepare::BuildSpec(cmd) => cmd.run::(load_spec), - cli::ParseAndPrepare::ExportBlocks(cmd) => cmd.run_with_builder::<(), _, _, _, _, _, _>(|config| - Ok(service::new_chain_ops(config)?), load_spec, worker), - cli::ParseAndPrepare::ImportBlocks(cmd) => cmd.run_with_builder::<(), _, _, _, _, _, _>(|config| - Ok(service::new_chain_ops(config)?), load_spec, worker), - cli::ParseAndPrepare::CheckBlock(cmd) => cmd.run_with_builder::<(), _, _, _, _, _, _>(|config| - Ok(service::new_chain_ops(config)?), load_spec, worker), - cli::ParseAndPrepare::PurgeChain(cmd) => cmd.run(load_spec), - cli::ParseAndPrepare::RevertChain(cmd) => cmd.run_with_builder::<(), _, _, _, _, _>(|config| - Ok(service::new_chain_ops(config)?), load_spec), - cli::ParseAndPrepare::CustomCommand(PolkadotSubCommands::ValidationWorker(args)) => { - if cfg!(feature = "browser") { - Err(error::Error::Input("Cannot run validation worker in browser".into())) - } else { - #[cfg(not(feature = "browser"))] - service::run_validation_worker(&args.mem_id)?; - Ok(()) + }.map_err(|e| format!("{:?}", e)) + }), + cli::ParseAndPrepare::BuildSpec(cmd) => cmd.run::(&load_spec), + cli::ParseAndPrepare::ExportBlocks(cmd) => cmd.run_with_builder::<_, _, _, _, _, _, _>(|config| + Ok(service::new_chain_ops::(config)?), &load_spec, exit), + cli::ParseAndPrepare::ImportBlocks(cmd) => cmd.run_with_builder::<_, _, _, _, _, _, _>(|config| + Ok(service::new_chain_ops::(config)?), &load_spec, exit), + cli::ParseAndPrepare::CheckBlock(cmd) => cmd.run_with_builder::<_, _, _, _, _, _, _>(|config| + Ok(service::new_chain_ops::(config)?), &load_spec, exit), + cli::ParseAndPrepare::PurgeChain(cmd) => cmd.run(&load_spec), + cli::ParseAndPrepare::RevertChain(cmd) => cmd.run_with_builder::<_, _, _, _, _, _>(|config| + Ok(service::new_chain_ops::(config)?), &load_spec), + cli::ParseAndPrepare::CustomCommand(PolkadotSubCommands::ValidationWorker(args)) => { + if cfg!(feature = "browser") { + Err(error::Error::Input("Cannot run validation worker in browser".into())) + } else { + #[cfg(not(feature = "browser"))] + service::run_validation_worker(&args.mem_id)?; + Ok(()) + } } - } } } -fn run_until_exit( +/// Run the given `service` using the `runtime` until it exits or `e` fires. +pub fn run_until_exit( mut runtime: Runtime, - service: T, - worker: W, -) -> error::Result<()> - where - T: AbstractService, - SC: service::SelectChain + 'static, - B: service::Backend + 'static, - CE: service::CallExecutor + Clone + Send + Sync + 'static, - W: Worker, -{ + service: impl AbstractService, + e: impl Future + Send + Unpin + 'static, +) -> error::Result<()> { let (exit_send, exit) = oneshot::channel(); let executor = runtime.executor(); @@ -185,20 +189,21 @@ fn run_until_exit( // but we need to keep holding a reference to the global telemetry guard let _telemetry = service.telemetry(); - let work = worker.work(&service, WrappedExecutor(executor)); - let service = service - .map_err(|err| error!("Error while running Service: {}", err)) - .compat(); - let future = select(service, work) - .map(|_| Ok::<_, ()>(())) - .compat(); - let _ = runtime.block_on(future); + let service_res = { + let service = service + .map_err(|err| error::Error::Service(err)) + .compat(); + let select = select(service, e) + .map(|_| Ok(())) + .compat(); + runtime.block_on(select) + }; + let _ = exit_send.send(()); use futures01::Future; - // TODO [andre]: timeout this future substrate/#1318 let _ = runtime.shutdown_on_idle().wait(); - Ok(()) + service_res } diff --git a/collator/Cargo.toml b/collator/Cargo.toml index 6b5e0b5fa9caa..16d17e243e1a0 100644 --- a/collator/Cargo.toml +++ b/collator/Cargo.toml @@ -11,15 +11,15 @@ client = { package = "sc-client", git = "https://github.com/paritytech/substrate client-api = { package = "sc-client-api", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } primitives = { package = "sp-core", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } sc-network = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } +sp-blockchain = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } consensus_common = { package = "sp-consensus", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } -polkadot-runtime = { path = "../runtime" } polkadot-primitives = { path = "../primitives" } polkadot-cli = { path = "../cli" } polkadot-network = { path = "../network" } polkadot-validation = { path = "../validation" } polkadot-service = { path = "../service" } log = "0.4.8" -tokio = "0.2.1" +tokio = "0.1.22" futures-timer = "1.0" [dev-dependencies] diff --git a/collator/src/lib.rs b/collator/src/lib.rs index 7afd5e100e8bb..f8e63c51e44f8 100644 --- a/collator/src/lib.rs +++ b/collator/src/lib.rs @@ -51,7 +51,7 @@ use std::time::Duration; use std::pin::Pin; use futures::{future, Future, Stream, FutureExt, TryFutureExt, StreamExt, task::Spawn}; -use log::{warn, error}; +use log::warn; use client::BlockchainEvents; use primitives::{Pair, Blake2Hasher}; use polkadot_primitives::{ @@ -62,13 +62,12 @@ use polkadot_primitives::{ } }; use polkadot_cli::{ - Worker, IntoExit, ProvideRuntimeApi, AbstractService, CustomConfiguration, ParachainHost, + ProvideRuntimeApi, AbstractService, ParachainHost, IsKusama, WrappedExecutor, + service::{self, Roles, SelectChain} }; use polkadot_network::validation::{LeafWorkParams, ValidationNetwork}; -use polkadot_network::PolkadotProtocol; -use polkadot_runtime::RuntimeApi; -pub use polkadot_cli::VersionInfo; +pub use polkadot_cli::{VersionInfo, load_spec, service::Configuration}; pub use polkadot_network::validation::Incoming; pub use polkadot_validation::SignedStatement; pub use polkadot_primitives::parachain::CollatorId; @@ -129,7 +128,7 @@ impl fmt::Display for Error { } /// The Polkadot client type. -pub type PolkadotClient = client::Client; +pub type PolkadotClient = client::Client; /// Something that can build a `ParachainContext`. pub trait BuildParachainContext { @@ -137,9 +136,9 @@ pub trait BuildParachainContext { type ParachainContext: self::ParachainContext; /// Build the `ParachainContext`. - fn build( + fn build( self, - client: Arc>, + client: Arc>, spawner: SP, network: Arc, ) -> Result @@ -266,205 +265,179 @@ impl RelayChainContext for ApiContext { - build_parachain_context: P, +/// Run the collator node using the given `service`. +fn run_collator_node( + service: S, exit: E, para_id: ParaId, key: Arc, -} - -impl IntoExit for CollationNode where - E: futures::Future + Unpin + Send + 'static -{ - type Exit = E; - fn into_exit(self) -> Self::Exit { - self.exit - } -} - -impl Worker for CollationNode where - P: BuildParachainContext + Send + 'static, - P::ParachainContext: Send + 'static, - ::ProduceCandidate: Send + 'static, - E: futures::Future + Clone + Unpin + Send + Sync + 'static, + build_parachain_context: P, +) -> polkadot_cli::error::Result<()> + where + S: AbstractService, + client::Client: ProvideRuntimeApi, + as ProvideRuntimeApi>::Api: + ParachainHost, + // Rust bug: https://github.com/rust-lang/rust/issues/24159 + S::Backend: service::Backend, + // Rust bug: https://github.com/rust-lang/rust/issues/24159 + S::CallExecutor: service::CallExecutor, + // Rust bug: https://github.com/rust-lang/rust/issues/24159 + S::SelectChain: service::SelectChain, + E: futures::Future + Clone + Unpin + Send + Sync + 'static, + P: BuildParachainContext, + P::ParachainContext: Send + 'static, + ::ProduceCandidate: Send, { - type Work = Box + Unpin + Send>; - - fn configuration(&self) -> CustomConfiguration { - let mut config = CustomConfiguration::default(); - config.collating_for = Some(( - self.key.public(), - self.para_id, - )); - config - } + let runtime = tokio::runtime::Runtime::new().map_err(|e| format!("{:?}", e))?; + let spawner = WrappedExecutor(service.spawn_task_handle()); + + let client = service.client(); + let network = service.network(); + let known_oracle = client.clone(); + let select_chain = if let Some(select_chain) = service.select_chain() { + select_chain + } else { + return Err(polkadot_cli::error::Error::Other("The node cannot work because it can't select chain.".into())) + }; - fn work(self, service: &S, spawner: SP) -> Self::Work - where - S: AbstractService< - Block = Block, - RuntimeApi = RuntimeApi, - Backend = B, - SelectChain = SC, - NetworkSpecialization = PolkadotProtocol, - CallExecutor = CE, - >, - SC: polkadot_service::SelectChain + 'static, - B: client_api::backend::Backend + 'static, - CE: client::CallExecutor + Clone + Send + Sync + 'static, - SP: Spawn + Clone + Send + Sync + 'static, - { - let CollationNode { build_parachain_context, exit, para_id, key } = self; - let client = service.client(); - let network = service.network(); - let known_oracle = client.clone(); - let select_chain = if let Some(select_chain) = service.select_chain() { - select_chain - } else { - error!("The node cannot work because it can't select chain."); - return Box::new(future::ready(())); - }; - - let is_known = move |block_hash: &Hash| { - use consensus_common::BlockStatus; - use polkadot_network::gossip::Known; - - match known_oracle.block_status(&BlockId::hash(*block_hash)) { - Err(_) | Ok(BlockStatus::Unknown) | Ok(BlockStatus::Queued) => None, - Ok(BlockStatus::KnownBad) => Some(Known::Bad), - Ok(BlockStatus::InChainWithState) | Ok(BlockStatus::InChainPruned) => - match select_chain.leaves() { - Err(_) => None, - Ok(leaves) => if leaves.contains(block_hash) { - Some(Known::Leaf) - } else { - Some(Known::Old) - }, - } - } - }; + let is_known = move |block_hash: &Hash| { + use consensus_common::BlockStatus; + use polkadot_network::gossip::Known; + + match known_oracle.block_status(&BlockId::hash(*block_hash)) { + Err(_) | Ok(BlockStatus::Unknown) | Ok(BlockStatus::Queued) => None, + Ok(BlockStatus::KnownBad) => Some(Known::Bad), + Ok(BlockStatus::InChainWithState) | Ok(BlockStatus::InChainPruned) => + match select_chain.leaves() { + Err(_) => None, + Ok(leaves) => if leaves.contains(block_hash) { + Some(Known::Leaf) + } else { + Some(Known::Old) + }, + } + } + }; - let message_validator = polkadot_network::gossip::register_validator( - network.clone(), - (is_known, client.clone()), - &spawner - ); + let message_validator = polkadot_network::gossip::register_validator( + network.clone(), + (is_known, client.clone()), + &spawner, + ); + + let validation_network = Arc::new(ValidationNetwork::new( + message_validator, + exit.clone(), + client.clone(), + spawner.clone(), + )); + + let parachain_context = match build_parachain_context.build( + client.clone(), + spawner, + validation_network.clone(), + ) { + Ok(ctx) => ctx, + Err(()) => { + return Err(polkadot_cli::error::Error::Other("Could not build the parachain context!".into())) + } + }; - let validation_network = Arc::new(ValidationNetwork::new( - message_validator, - exit.clone(), - client.clone(), - spawner.clone(), - )); - - let parachain_context = match build_parachain_context.build( - client.clone(), - spawner, - validation_network.clone(), - ) { - Ok(ctx) => ctx, - Err(()) => { - error!("Could not build the parachain context!"); - return Box::new(future::ready(())) - } - }; - - let inner_exit = exit.clone(); - let work = client.import_notification_stream() - .for_each(move |notification| { - macro_rules! try_fr { - ($e:expr) => { - match $e { - Ok(x) => x, - Err(e) => return future::Either::Left(future::err(Error::Polkadot( - format!("{:?}", e) - ))), - } + let inner_exit = exit.clone(); + let work = client.import_notification_stream() + .for_each(move |notification| { + macro_rules! try_fr { + ($e:expr) => { + match $e { + Ok(x) => x, + Err(e) => return future::Either::Left(future::err(Error::Polkadot( + format!("{:?}", e) + ))), } } + } - let relay_parent = notification.hash; - let id = BlockId::hash(relay_parent); - - let network = network.clone(); - let client = client.clone(); - let key = key.clone(); - let parachain_context = parachain_context.clone(); - let validation_network = validation_network.clone(); - let inner_exit_2 = inner_exit.clone(); - - let work = future::lazy(move |_| { - let api = client.runtime_api(); - let status = match try_fr!(api.parachain_status(&id, para_id)) { - Some(status) => status, - None => return future::Either::Left(future::ok(())), - }; - - let validators = try_fr!(api.validators(&id)); - - let targets = compute_targets( - para_id, - validators.as_slice(), - try_fr!(api.duty_roster(&id)), - ); - - let context = ApiContext { - network: validation_network, - parent_hash: relay_parent, - validators, - }; - - let collation_work = collate( - relay_parent, - para_id, - status, - context, - parachain_context, - key, - ).map_ok(move |(collation, outgoing)| { - network.with_spec(move |spec, ctx| { - let res = spec.add_local_collation( - ctx, - relay_parent, - targets, - collation, - outgoing, - ); - - let exit = inner_exit_2.clone(); - tokio::spawn(future::select(res.boxed(), exit).map(drop)); - }) - }); - - future::Either::Right(collation_work) + let relay_parent = notification.hash; + let id = BlockId::hash(relay_parent); + + let network = network.clone(); + let client = client.clone(); + let key = key.clone(); + let parachain_context = parachain_context.clone(); + let validation_network = validation_network.clone(); + let inner_exit_2 = inner_exit.clone(); + + let work = future::lazy(move |_| { + let api = client.runtime_api(); + let status = match try_fr!(api.parachain_status(&id, para_id)) { + Some(status) => status, + None => return future::Either::Left(future::ok(())), + }; + + let validators = try_fr!(api.validators(&id)); + + let targets = compute_targets( + para_id, + validators.as_slice(), + try_fr!(api.duty_roster(&id)), + ); + + let context = ApiContext { + network: validation_network, + parent_hash: relay_parent, + validators, + }; + + let collation_work = collate( + relay_parent, + para_id, + status, + context, + parachain_context, + key, + ).map_ok(move |(collation, outgoing)| { + network.with_spec(move |spec, ctx| { + let res = spec.add_local_collation( + ctx, + relay_parent, + targets, + collation, + outgoing, + ); + + let exit = inner_exit_2.clone(); + tokio::spawn(future::select(res.boxed(), exit).map(drop).map(|_| Ok(())).compat()); + }) }); - let deadlined = future::select( - work, - futures_timer::Delay::new(COLLATION_TIMEOUT) - ); + future::Either::Right(collation_work) + }); - let silenced = deadlined - .map(|either| { - if let future::Either::Right(_) = either { - warn!("Collation failure: timeout"); - } - }); + let deadlined = future::select( + work, + futures_timer::Delay::new(COLLATION_TIMEOUT) + ); + + let silenced = deadlined + .map(|either| { + if let future::Either::Right(_) = either { + warn!("Collation failure: timeout"); + } + }); let future = future::select( silenced, inner_exit.clone() ).map(drop); - tokio::spawn(future); - future::ready(()) - }); + tokio::spawn(future.map(|_| Ok(())).compat()); + future::ready(()) + }); - let work_and_exit = future::select(work, exit) - .map(|_| ()); + service.spawn_essential_task(work.map(|_| Ok::<_, ()>(())).compat()); - Box::new(work_and_exit) - } + polkadot_cli::run_until_exit(runtime, service, exit) } fn compute_targets(para_id: ParaId, session_keys: &[ValidatorId], roster: DutyRoster) -> HashSet { @@ -477,6 +450,11 @@ fn compute_targets(para_id: ParaId, session_keys: &[ValidatorId], roster: DutyRo .collect() } +/// Set the `collating_for` parameter of the configuration. +fn prepare_config(config: &mut Configuration, para_id: ParaId, key: &Arc) { + config.custom.collating_for = Some((key.public(), para_id)); +} + /// Run a collator node with the given `RelayChainContext` and `ParachainContext` /// build by the given `BuildParachainContext` and arguments to the underlying polkadot node. /// @@ -487,15 +465,25 @@ pub fn run_collator( para_id: ParaId, exit: E, key: Arc, - version: VersionInfo, + mut config: Configuration, ) -> polkadot_cli::error::Result<()> where - P: BuildParachainContext + Send + 'static, + P: BuildParachainContext, P::ParachainContext: Send + 'static, - ::ProduceCandidate: Send + 'static, + ::ProduceCandidate: Send, E: futures::Future + Unpin + Send + Clone + Sync + 'static, { - let node_logic = CollationNode { build_parachain_context, exit, para_id, key }; - polkadot_cli::run(node_logic, version) + prepare_config(&mut config, para_id, &key); + + match (config.is_kusama(), config.roles) { + (true, Roles::LIGHT) => + run_collator_node(service::kusama_new_light(config)?, exit, para_id, key, build_parachain_context), + (true, _) => + run_collator_node(service::kusama_new_full(config)?, exit, para_id, key, build_parachain_context), + (false, Roles::LIGHT) => + run_collator_node(service::polkadot_new_light(config)?, exit, para_id, key, build_parachain_context), + (false, _) => + run_collator_node(service::polkadot_new_full(config)?, exit, para_id, key, build_parachain_context), + } } #[cfg(test)] @@ -601,4 +589,3 @@ mod tests { assert_eq!(collation.info.egress_queue_roots, vec![(a, root_a), (b, root_b)]); } } - diff --git a/executor/Cargo.toml b/executor/Cargo.toml deleted file mode 100644 index bd523d267020b..0000000000000 --- a/executor/Cargo.toml +++ /dev/null @@ -1,10 +0,0 @@ -[package] -name = "polkadot-executor" -version = "0.7.11" -authors = ["Parity Technologies "] -description = "Polkadot node implementation in Rust." -edition = "2018" - -[dependencies] -sc-executor = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } -polkadot-runtime = { path = "../runtime" } diff --git a/executor/README.adoc b/executor/README.adoc deleted file mode 100644 index 59b63a1731810..0000000000000 --- a/executor/README.adoc +++ /dev/null @@ -1,5 +0,0 @@ - -= Polkadot Executor - -placeholder -//TODO Write content :) (https://github.com/paritytech/polkadot/issues/159) diff --git a/primitives/Cargo.toml b/primitives/Cargo.toml index 069bd5d4e21ec..6b7c6546a58b1 100644 --- a/primitives/Cargo.toml +++ b/primitives/Cargo.toml @@ -8,6 +8,7 @@ edition = "2018" serde = { version = "1.0.102", optional = true, features = ["derive"] } parity-scale-codec = { version = "1.1.0", default-features = false, features = ["bit-vec", "derive"] } primitives = { package = "sp-core", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +inherents = { package = "sp-inherents", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } application-crypto = { package = "sp-application-crypto", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master", default-features = false } sp-version = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } @@ -27,6 +28,7 @@ default = ["std"] std = [ "parity-scale-codec/std", "primitives/std", + "inherents/std", "trie/std", "sp-api/std", "rstd/std", diff --git a/primitives/src/parachain.rs b/primitives/src/parachain.rs index 91731fd547fb7..31a0f36e09972 100644 --- a/primitives/src/parachain.rs +++ b/primitives/src/parachain.rs @@ -28,6 +28,7 @@ use serde::{Serialize, Deserialize}; #[cfg(feature = "std")] use primitives::bytes; use primitives::RuntimeDebug; +use inherents::InherentIdentifier; use application_crypto::KeyTypeId; #[cfg(feature = "std")] @@ -40,6 +41,10 @@ pub use polkadot_parachain::{ /// The key type ID for a collator key. pub const COLLATOR_KEY_TYPE_ID: KeyTypeId = KeyTypeId(*b"coll"); +/// An identifier for inherent data that provides new minimally-attested +/// parachain heads. +pub const NEW_HEADS_IDENTIFIER: InherentIdentifier = *b"newheads"; + mod collator_app { use application_crypto::{app_crypto, sr25519}; app_crypto!(sr25519, super::COLLATOR_KEY_TYPE_ID); diff --git a/rpc/Cargo.toml b/rpc/Cargo.toml index 17c588e9d57c9..dba35bad34645 100644 --- a/rpc/Cargo.toml +++ b/rpc/Cargo.toml @@ -13,5 +13,4 @@ sc-rpc = { git = "https://github.com/paritytech/substrate", branch = "polkadot-m txpool-api = { package = "sp-transaction-pool", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } frame-rpc-system = { package = "substrate-frame-rpc-system", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } pallet-transaction-payment-rpc = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } -polkadot-runtime = { path = "../runtime" } - +codec = { package = "parity-scale-codec", version = "1.1.0", default-features = false } diff --git a/rpc/src/lib.rs b/rpc/src/lib.rs index ee285bd4b8aae..c9fd97e9edff3 100644 --- a/rpc/src/lib.rs +++ b/rpc/src/lib.rs @@ -23,19 +23,19 @@ use std::sync::Arc; use polkadot_primitives::{Block, AccountId, Nonce, Balance}; use sp_runtime::traits::ProvideRuntimeApi; use txpool_api::TransactionPool; -use polkadot_runtime::UncheckedExtrinsic; /// A type representing all RPC extensions. pub type RpcExtension = jsonrpc_core::IoHandler; /// Instantiate all RPC extensions. -pub fn create_full(client: Arc, pool: Arc

) -> RpcExtension where +pub fn create_full(client: Arc, pool: Arc

) -> RpcExtension where C: ProvideRuntimeApi, C: client::blockchain::HeaderBackend, C: Send + Sync + 'static, C::Api: frame_rpc_system::AccountNonceApi, - C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, + C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, P: TransactionPool + Sync + Send + 'static, + UE: codec::Codec + Send + Sync + 'static, { use frame_rpc_system::{FullSystem, SystemApi}; use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi}; @@ -51,7 +51,7 @@ pub fn create_full(client: Arc, pool: Arc

) -> RpcExtension where } /// Instantiate all RPC extensions for light node. -pub fn create_light( +pub fn create_light( client: Arc, remote_blockchain: Arc>, fetcher: Arc, @@ -62,9 +62,10 @@ pub fn create_light( C: client::blockchain::HeaderBackend, C: Send + Sync + 'static, C::Api: frame_rpc_system::AccountNonceApi, - C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, + C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, P: TransactionPool + Sync + Send + 'static, F: client::light::fetcher::Fetcher + 'static, + UE: codec::Codec + Send + Sync + 'static, { use frame_rpc_system::{LightSystem, SystemApi}; diff --git a/runtime/common/Cargo.toml b/runtime/common/Cargo.toml new file mode 100644 index 0000000000000..a7b2eea716a8c --- /dev/null +++ b/runtime/common/Cargo.toml @@ -0,0 +1,73 @@ +[package] +name = "polkadot-runtime-common" +version = "0.7.10" +authors = ["Parity Technologies "] +edition = "2018" + +[dependencies] +bitvec = { version = "0.15.2", default-features = false, features = ["alloc"] } +codec = { package = "parity-scale-codec", version = "1.1.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 } + +sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master", default-features = false } +inherents = { package = "sp-inherents", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +rstd = { package = "sp-std", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +sp-io = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +sp-staking = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +sp-core = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } + +authorship = { package = "pallet-authorship", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +balances = { package = "pallet-balances", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +session = { package = "pallet-session", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +staking = { package = "pallet-staking", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +system = { package = "frame-system", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +timestamp = { package = "pallet-timestamp", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } + +primitives = { package = "polkadot-primitives", path = "../../primitives", default-features = false } +polkadot-parachain = { path = "../../parachain", 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 = "polkadot-master" } +sp-trie = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } +babe = { package = "pallet-babe", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +randomness-collective-flip = { package = "pallet-randomness-collective-flip", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +pallet-staking-reward-curve = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } +treasury = { package = "pallet-treasury", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +trie-db = "0.16.0" +serde_json = "1.0.41" + +[features] +default = [] +no_std = [] +std = [ + "bitvec/std", + "primitives/std", + "rustc-hex/std", + "codec/std", + "inherents/std", + "sp-core/std", + "polkadot-parachain/std", + "sp-api/std", + "rstd/std", + "sp-io/std", + "frame-support/std", + "authorship/std", + "balances/std", + "sp-runtime/std", + "sp-staking/std", + "session/std", + "staking/std", + "system/std", + "timestamp/std", + "serde_derive", + "serde/std", + "log", +] diff --git a/runtime/src/attestations.rs b/runtime/common/src/attestations.rs similarity index 100% rename from runtime/src/attestations.rs rename to runtime/common/src/attestations.rs diff --git a/runtime/src/claims.rs b/runtime/common/src/claims.rs similarity index 100% rename from runtime/src/claims.rs rename to runtime/common/src/claims.rs diff --git a/runtime/src/crowdfund.rs b/runtime/common/src/crowdfund.rs similarity index 100% rename from runtime/src/crowdfund.rs rename to runtime/common/src/crowdfund.rs diff --git a/runtime/src/impls.rs b/runtime/common/src/impls.rs similarity index 73% rename from runtime/src/impls.rs rename to runtime/common/src/impls.rs index a3ca44d2b2443..70309a09a9b52 100644 --- a/runtime/src/impls.rs +++ b/runtime/common/src/impls.rs @@ -21,32 +21,57 @@ use sp_runtime::traits::{Convert, Saturating}; use sp_runtime::{Fixed64, Perbill}; use frame_support::weights::Weight; use frame_support::traits::{OnUnbalanced, Imbalance, Currency, Get}; -use crate::{Balances, System, Authorship, MaximumBlockWeight, NegativeImbalance}; +use crate::{MaximumBlockWeight, NegativeImbalance}; /// Logic for the author to get a portion of fees. -pub struct ToAuthor; - -impl OnUnbalanced for ToAuthor { - fn on_nonzero_unbalanced(amount: NegativeImbalance) { +pub struct ToAuthor(rstd::marker::PhantomData); + +impl OnUnbalanced> for ToAuthor +where + R: balances::Trait + authorship::Trait, + ::AccountId: From, + ::AccountId: Into, + ::Event: From::AccountId, + ::Balance, + balances::DefaultInstance> + >, +{ + fn on_nonzero_unbalanced(amount: NegativeImbalance) { let numeric_amount = amount.peek(); - let author = Authorship::author(); - Balances::resolve_creating(&author, amount); - System::deposit_event(balances::RawEvent::Deposit(author, numeric_amount)); + let author = >::author(); + >::resolve_creating(&>::author(), amount); + >::deposit_event(balances::RawEvent::Deposit(author, numeric_amount)); } } /// Converter for currencies to votes. -pub struct CurrencyToVoteHandler; - -impl CurrencyToVoteHandler { - fn factor() -> u128 { (Balances::total_issuance() / u64::max_value() as u128).max(1) } +pub struct CurrencyToVoteHandler(rstd::marker::PhantomData); + +impl CurrencyToVoteHandler +where + R: balances::Trait, + R::Balance: Into, +{ + fn factor() -> u128 { + let issuance: u128 = >::total_issuance().into(); + (issuance / u64::max_value() as u128).max(1) + } } -impl Convert for CurrencyToVoteHandler { +impl Convert for CurrencyToVoteHandler +where + R: balances::Trait, + R::Balance: Into, +{ fn convert(x: u128) -> u64 { (x / Self::factor()) as u64 } } -impl Convert for CurrencyToVoteHandler { +impl Convert for CurrencyToVoteHandler +where + R: balances::Trait, + R::Balance: Into, +{ fn convert(x: u128) -> u128 { x * Self::factor() } } @@ -77,11 +102,11 @@ impl Convert for WeightToFee { /// /// Where `target_weight` must be given as the `Get` implementation of the `T` generic type. /// https://research.web3.foundation/en/latest/polkadot/Token%20Economics/#relay-chain-transaction-fees -pub struct TargetedFeeAdjustment(rstd::marker::PhantomData); +pub struct TargetedFeeAdjustment(rstd::marker::PhantomData<(T, R)>); -impl> Convert for TargetedFeeAdjustment { +impl, R: system::Trait> Convert for TargetedFeeAdjustment { fn convert(multiplier: Fixed64) -> Fixed64 { - let block_weight = System::all_extrinsics_weight(); + let block_weight = >::all_extrinsics_weight(); let max_weight = MaximumBlockWeight::get(); let target_weight = (T::get() * max_weight) as u128; let block_weight = block_weight as u128; diff --git a/runtime/common/src/lib.rs b/runtime/common/src/lib.rs new file mode 100644 index 0000000000000..bcb26d30c7a38 --- /dev/null +++ b/runtime/common/src/lib.rs @@ -0,0 +1,56 @@ +// Copyright 2019 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. + +// Polkadot 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 Polkadot. If not, see . + +//! Common runtime code for Polkadot and Kusama. + +#![cfg_attr(not(feature = "std"), no_std)] + +pub mod attestations; +pub mod claims; +pub mod parachains; +pub mod slot_range; +pub mod registrar; +pub mod slots; +pub mod crowdfund; +pub mod impls; + +use primitives::BlockNumber; +use sp_runtime::Perbill; +use frame_support::{ + parameter_types, traits::Currency, + weights::Weight, +}; + +#[cfg(feature = "std")] +pub use staking::StakerStatus; +#[cfg(any(feature = "std", test))] +pub use sp_runtime::BuildStorage; +pub use timestamp::Call as TimestampCall; +pub use balances::Call as BalancesCall; +pub use attestations::{Call as AttestationsCall, MORE_ATTESTATIONS_IDENTIFIER}; +pub use parachains::Call as ParachainsCall; + +/// Implementations of some helper traits passed into runtime modules as associated types. +pub use impls::{CurrencyToVoteHandler, TargetedFeeAdjustment, ToAuthor, WeightToFee}; + +pub type NegativeImbalance = as Currency<::AccountId>>::NegativeImbalance; + +parameter_types! { + pub const BlockHashCount: BlockNumber = 250; + pub const MaximumBlockWeight: Weight = 1_000_000_000; + pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); + pub const MaximumBlockLength: u32 = 5 * 1024 * 1024; +} diff --git a/runtime/src/parachains.rs b/runtime/common/src/parachains.rs similarity index 98% rename from runtime/src/parachains.rs rename to runtime/common/src/parachains.rs index da0bd98e63c8c..fc00d05714acb 100644 --- a/runtime/src/parachains.rs +++ b/runtime/common/src/parachains.rs @@ -30,7 +30,8 @@ use primitives::{ Hash, Balance, parachain::{ self, Id as ParaId, Chain, DutyRoster, AttestedCandidate, Statement, ParachainDispatchOrigin, - UpwardMessage, BlockIngressRoots, ValidatorId, ActiveParas, CollatorId, Retriable + UpwardMessage, BlockIngressRoots, ValidatorId, ActiveParas, CollatorId, Retriable, + NEW_HEADS_IDENTIFIER, }, }; use frame_support::{ @@ -152,7 +153,8 @@ const MAX_QUEUE_COUNT: usize = 100; const WATERMARK_QUEUE_SIZE: usize = 20000; decl_storage! { - trait Store for Module as Parachains { + trait Store for Module as Parachains + { /// All authorities' keys at the moment. pub Authorities get(authorities): Vec; /// The parachains registered at present. @@ -280,7 +282,7 @@ fn majority_of(list_len: usize) -> usize { list_len / 2 + list_len % 2 } -fn localized_payload(statement: Statement, parent_hash: ::primitives::Hash) -> Vec { +fn localized_payload>(statement: Statement, parent_hash: H) -> Vec { let mut encoded = statement.encode(); encoded.extend(parent_hash.as_ref()); encoded @@ -726,7 +728,7 @@ impl Module { let sorted_validators = make_sorted_duties(&duty_roster.validator_duty); - let parent_hash = super::System::parent_hash(); + let parent_hash = >::parent_hash(); let localized_payload = |statement: Statement| localized_payload(statement, parent_hash); let mut validator_groups = GroupedDutyIter::new(&sorted_validators[..]); @@ -865,10 +867,6 @@ impl session::OneSessionHandler for Module { fn on_disabled(_i: usize) { } } -/// An identifier for inherent data that provides new minimally-attested -/// parachain heads. -pub const NEW_HEADS_IDENTIFIER: InherentIdentifier = *b"newheads"; - pub type InherentType = Vec; impl ProvideInherent for Module { @@ -915,7 +913,6 @@ mod tests { }, BlockNumber, }; - use crate::constants::time::*; use keyring::Sr25519Keyring; use frame_support::{ impl_outer_origin, impl_outer_dispatch, assert_ok, assert_err, parameter_types, @@ -996,9 +993,17 @@ mod tests { type MinimumPeriod = MinimumPeriod; } + mod time { + use primitives::{Moment, BlockNumber}; + pub const MILLISECS_PER_BLOCK: Moment = 6000; + pub const EPOCH_DURATION_IN_BLOCKS: BlockNumber = 1 * HOURS; + // These time units are defined in number of blocks. + const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber); + const HOURS: BlockNumber = MINUTES * 60; + } parameter_types! { - pub const EpochDuration: u64 = EPOCH_DURATION_IN_BLOCKS as u64; - pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK; + pub const EpochDuration: u64 = time::EPOCH_DURATION_IN_BLOCKS as u64; + pub const ExpectedBlockTime: u64 = time::MILLISECS_PER_BLOCK; } impl babe::Trait for Test { @@ -1190,7 +1195,7 @@ mod tests { fn make_attestations(candidate: &mut AttestedCandidate) { let mut vote_implicit = false; - let parent_hash = crate::System::parent_hash(); + let parent_hash = >::parent_hash(); let (duty_roster, _) = Parachains::calculate_duty_roster(); let candidate_hash = candidate.candidate.hash(); diff --git a/runtime/src/registrar.rs b/runtime/common/src/registrar.rs similarity index 100% rename from runtime/src/registrar.rs rename to runtime/common/src/registrar.rs diff --git a/runtime/src/slot_range.rs b/runtime/common/src/slot_range.rs similarity index 100% rename from runtime/src/slot_range.rs rename to runtime/common/src/slot_range.rs diff --git a/runtime/src/slots.rs b/runtime/common/src/slots.rs similarity index 100% rename from runtime/src/slots.rs rename to runtime/common/src/slots.rs diff --git a/runtime/src/testing.rs b/runtime/common/src/testing.rs similarity index 100% rename from runtime/src/testing.rs rename to runtime/common/src/testing.rs diff --git a/runtime/Cargo.toml b/runtime/kusama/Cargo.toml similarity index 96% rename from runtime/Cargo.toml rename to runtime/kusama/Cargo.toml index 78050c079c2cf..381a5e2986c77 100644 --- a/runtime/Cargo.toml +++ b/runtime/kusama/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "polkadot-runtime" +name = "kusama-runtime" version = "0.7.11" authors = ["Parity Technologies "] edition = "2018" @@ -24,7 +24,6 @@ sp-io = { git = "https://github.com/paritytech/substrate", default-features = fa sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } sp-staking = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } sp-core = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } -sp-serializer = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } sp-session = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } version = { package = "sp-version", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } tx-pool-api = { package = "sp-transaction-pool", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } @@ -59,8 +58,9 @@ timestamp = { package = "pallet-timestamp", git = "https://github.com/paritytech treasury = { package = "pallet-treasury", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } utility = { package = "pallet-utility", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } -primitives = { package = "polkadot-primitives", path = "../primitives", default-features = false } -polkadot-parachain = { path = "../parachain", default-features = false } +runtime-common = { package = "polkadot-runtime-common", path = "../common", default-features = false } +primitives = { package = "polkadot-primitives", path = "../../primitives", default-features = false } +polkadot-parachain = { path = "../../parachain", default-features = false } [dev-dependencies] hex-literal = "0.2.1" @@ -129,4 +129,5 @@ std = [ "babe-primitives/std", "sp-session/std", "randomness-collective-flip/std", + "runtime-common/std", ] diff --git a/runtime/build.rs b/runtime/kusama/build.rs similarity index 100% rename from runtime/build.rs rename to runtime/kusama/build.rs diff --git a/runtime/src/constants.rs b/runtime/kusama/src/constants.rs similarity index 100% rename from runtime/src/constants.rs rename to runtime/kusama/src/constants.rs diff --git a/runtime/src/lib.rs b/runtime/kusama/src/lib.rs similarity index 94% rename from runtime/src/lib.rs rename to runtime/kusama/src/lib.rs index 815daf6fdb466..b145ad5e5c70a 100644 --- a/runtime/src/lib.rs +++ b/runtime/kusama/src/lib.rs @@ -20,14 +20,6 @@ // `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256. #![recursion_limit="256"] -mod attestations; -mod claims; -mod parachains; -mod slot_range; -mod registrar; -mod slots; -mod crowdfund; - use rstd::prelude::*; use sp_core::u32_trait::{_1, _2, _3, _4, _5}; use codec::{Encode, Decode}; @@ -35,6 +27,12 @@ use primitives::{ AccountId, AccountIndex, Balance, BlockNumber, Hash, Nonce, Signature, Moment, parachain::{self, ActiveParas, CandidateReceipt}, ValidityError, }; +use runtime_common::{attestations, claims, parachains, registrar, slots, + impls::{CurrencyToVoteHandler, TargetedFeeAdjustment, ToAuthor, WeightToFee}, + NegativeImbalance, BlockHashCount, MaximumBlockWeight, AvailableBlockRatio, + MaximumBlockLength, +}; + use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, ApplyExtrinsicResult, Permill, Perbill, RuntimeDebug, @@ -49,8 +47,8 @@ use version::NativeVersion; use sp_core::OpaqueMetadata; use sp_staking::SessionIndex; use frame_support::{ - parameter_types, construct_runtime, traits::{SplitTwoWays, Currency, Randomness}, - weights::{Weight, DispatchInfo}, + parameter_types, construct_runtime, traits::{SplitTwoWays, Randomness}, + weights::DispatchInfo, }; use im_online::sr25519::AuthorityId as ImOnlineId; use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId; @@ -64,11 +62,7 @@ pub use sp_runtime::BuildStorage; pub use timestamp::Call as TimestampCall; pub use balances::Call as BalancesCall; pub use attestations::{Call as AttestationsCall, MORE_ATTESTATIONS_IDENTIFIER}; -pub use parachains::{Call as ParachainsCall, NEW_HEADS_IDENTIFIER}; - -/// Implementations of some helper traits passed into runtime modules as associated types. -pub mod impls; -use impls::{CurrencyToVoteHandler, TargetedFeeAdjustment, ToAuthor, WeightToFee}; +pub use parachains::Call as ParachainsCall; /// Constant values used within the runtime. pub mod constants; @@ -78,20 +72,7 @@ use constants::{time::*, currency::*}; #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); -/* -// KUSAMA: Polkadot version identifier; may be uncommented for Polkadot mainnet. -/// Runtime version (Polkadot). -pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("polkadot"), - impl_name: create_runtime_str!("parity-polkadot"), - authoring_version: 1, - spec_version: 1000, - impl_version: 0, - apis: RUNTIME_API_VERSIONS, -}; -*/ - -// KUSAMA: Kusama version identifier; may be removed for Polkadot mainnet. +// Kusama version identifier; /// Runtime version (Kusama). pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("kusama"), @@ -137,13 +118,7 @@ impl SignedExtension for OnlyStakingAndClaims { } } -type NegativeImbalance = >::NegativeImbalance; - parameter_types! { - pub const BlockHashCount: BlockNumber = 250; - pub const MaximumBlockWeight: Weight = 1_000_000_000; - pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); - pub const MaximumBlockLength: u32 = 5 * 1024 * 1024; pub const Version: RuntimeVersion = VERSION; } @@ -195,9 +170,9 @@ parameter_types! { /// Splits fees 80/20 between treasury and block author. pub type DealWithFees = SplitTwoWays< Balance, - NegativeImbalance, + NegativeImbalance, _4, Treasury, // 4 parts (80%) goes to the treasury. - _1, ToAuthor, // 1 part (20%) goes to the block author. + _1, ToAuthor, // 1 part (20%) goes to the block author. >; impl balances::Trait for Runtime { @@ -225,7 +200,7 @@ impl transaction_payment::Trait for Runtime { type TransactionBaseFee = TransactionBaseFee; type TransactionByteFee = TransactionByteFee; type WeightToFee = WeightToFee; - type FeeMultiplierUpdate = TargetedFeeAdjustment; + type FeeMultiplierUpdate = TargetedFeeAdjustment; } parameter_types! { @@ -310,7 +285,7 @@ parameter_types! { impl staking::Trait for Runtime { type RewardRemainder = Treasury; - type CurrencyToVote = CurrencyToVoteHandler; + type CurrencyToVote = CurrencyToVoteHandler; type Event = Event; type Currency = Balances; type Slash = Treasury; @@ -387,7 +362,7 @@ impl elections_phragmen::Trait for Runtime { type Event = Event; type Currency = Balances; type ChangeMembers = Council; - type CurrencyToVote = CurrencyToVoteHandler; + type CurrencyToVote = CurrencyToVoteHandler; type CandidacyBond = CandidacyBond; type VotingBond = VotingBond; type TermDuration = TermDuration; @@ -525,10 +500,7 @@ impl slots::Trait for Runtime { } parameter_types! { - // KUSAMA: for mainnet this should be removed. pub const Prefix: &'static [u8] = b"Pay KSMs to the Kusama account:"; - // KUSAMA: for mainnet this should be uncommented. - //pub const Prefix: &'static [u8] = b"Pay DOTs to the Polkadot account:"; } impl claims::Trait for Runtime { diff --git a/runtime/polkadot/Cargo.toml b/runtime/polkadot/Cargo.toml new file mode 100644 index 0000000000000..be595a2236d39 --- /dev/null +++ b/runtime/polkadot/Cargo.toml @@ -0,0 +1,129 @@ +[package] +name = "polkadot-runtime" +version = "0.7.11" +authors = ["Parity Technologies "] +edition = "2018" +build = "build.rs" + +[dependencies] +bitvec = { version = "0.15.2", default-features = false, features = ["alloc"] } +codec = { package = "parity-scale-codec", version = "1.1.0", default-features = false, features = ["derive"] } +log = { version = "0.3.9", optional = true } +rustc-hex = { version = "2.0.1", default-features = false } +safe-mix = { version = "1.0.0", default-features = false } +serde = { version = "1.0.102", default-features = false } +serde_derive = { version = "1.0.102", optional = true } + +authority-discovery-primitives = { package = "sp-authority-discovery", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +babe-primitives = { package = "sp-consensus-babe", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master", default-features = false } +inherents = { package = "sp-inherents", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +offchain-primitives = { package = "sp-offchain", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +rstd = { package = "sp-std", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +sp-staking = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +sp-core = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +sp-session = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +version = { package = "sp-version", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +tx-pool-api = { package = "sp-transaction-pool", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +block-builder-api = { package = "sp-block-builder", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } + +authority-discovery = { package = "pallet-authority-discovery", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +authorship = { package = "pallet-authorship", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +babe = { package = "pallet-babe", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +balances = { package = "pallet-balances", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +transaction-payment = { package = "pallet-transaction-payment", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +collective = { package = "pallet-collective", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +democracy = { package = "pallet-democracy", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +elections-phragmen = { package = "pallet-elections-phragmen", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +executive = { package = "frame-executive", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +finality-tracker = { package = "pallet-finality-tracker", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +grandpa = { package = "pallet-grandpa", git = "https://github.com/paritytech/substrate", default-features = false, features = ["migrate-authorities"], branch = "polkadot-master" } +identity = { package = "pallet-identity", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +im-online = { package = "pallet-im-online", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +indices = { package = "pallet-indices", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +membership = { package = "pallet-membership", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +nicks = { package = "pallet-nicks", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +offences = { package = "pallet-offences", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +randomness-collective-flip = { package = "pallet-randomness-collective-flip", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +session = { package = "pallet-session", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +staking = { package = "pallet-staking", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +pallet-staking-reward-curve = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } +system = { package = "frame-system", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +system_rpc_runtime_api = { package = "frame-system-rpc-runtime-api", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +timestamp = { package = "pallet-timestamp", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +treasury = { package = "pallet-treasury", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } + +runtime-common = { package = "polkadot-runtime-common", path = "../common", default-features = false } +primitives = { package = "polkadot-primitives", path = "../../primitives", default-features = false } +polkadot-parachain = { path = "../../parachain", 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 = "polkadot-master" } +sp-trie = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } +trie-db = "0.16.0" +serde_json = "1.0.41" + +[build-dependencies] +wasm-builder-runner = { package = "substrate-wasm-builder-runner", version = "1.0.4" } + +[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", + "polkadot-parachain/std", + "sp-api/std", + "tx-pool-api/std", + "block-builder-api/std", + "offchain-primitives/std", + "rstd/std", + "frame-support/std", + "authorship/std", + "balances/std", + "transaction-payment/std", + "pallet-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", + "nicks/std", + "offences/std", + "sp-runtime/std", + "sp-staking/std", + "session/std", + "staking/std", + "system/std", + "system_rpc_runtime_api/std", + "timestamp/std", + "treasury/std", + "version/std", + "serde_derive", + "serde/std", + "log", + "safe-mix/std", + "babe/std", + "babe-primitives/std", + "sp-session/std", + "randomness-collective-flip/std", + "runtime-common/std", +] diff --git a/runtime/README.adoc b/runtime/polkadot/README.adoc similarity index 100% rename from runtime/README.adoc rename to runtime/polkadot/README.adoc diff --git a/executor/src/lib.rs b/runtime/polkadot/build.rs similarity index 64% rename from executor/src/lib.rs rename to runtime/polkadot/build.rs index dae60088d57c5..571f1e972d54c 100644 --- a/executor/src/lib.rs +++ b/runtime/polkadot/build.rs @@ -1,4 +1,4 @@ -// Copyright 2017 Parity Technologies (UK) Ltd. +// Copyright 2019 Parity Technologies (UK) Ltd. // This file is part of Polkadot. // Substrate is free software: you can redistribute it and/or modify @@ -14,13 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Substrate. If not, see . -//! A `CodeExecutor` specialisation which uses natively compiled runtime when the wasm to be -//! executed is equivalent to the natively compiled code. +use wasm_builder_runner::{build_current_project, WasmBuilderSource}; -use sc_executor::native_executor_instance; - -native_executor_instance!( - pub Executor, - polkadot_runtime::api::dispatch, - polkadot_runtime::native_version -); +fn main() { + build_current_project("wasm_binary.rs", WasmBuilderSource::Crates("1.0.8")); +} diff --git a/runtime/polkadot/src/constants.rs b/runtime/polkadot/src/constants.rs new file mode 100644 index 0000000000000..6eba2a7d97cfd --- /dev/null +++ b/runtime/polkadot/src/constants.rs @@ -0,0 +1,49 @@ +// Copyright 2019 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. + +// Polkadot 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 Polkadot. If not, see . + +/// Money matters. +pub mod currency { + use primitives::Balance; + + pub const DOTS: Balance = 1_000_000_000_000; + pub const DOLLARS: Balance = DOTS / 100; + pub const CENTS: Balance = DOLLARS / 100; + pub const MILLICENTS: Balance = CENTS / 1_000; +} + +/// Time and blocks. +pub mod time { + use primitives::{Moment, BlockNumber}; + pub const MILLISECS_PER_BLOCK: Moment = 6000; + pub const SLOT_DURATION: Moment = MILLISECS_PER_BLOCK; + pub const EPOCH_DURATION_IN_BLOCKS: BlockNumber = 4 * HOURS; + + // 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; + + // 1 in 4 blocks (on average, not counting collisions) will be primary babe blocks. + pub const PRIMARY_PROBABILITY: (u64, u64) = (1, 4); +} + +/// Fee-related. +pub mod fee { + pub use sp_runtime::Perbill; + + /// The block saturation level. Fees will be updates based on this value. + pub const TARGET_BLOCK_FULLNESS: Perbill = Perbill::from_percent(25); +} diff --git a/runtime/polkadot/src/lib.rs b/runtime/polkadot/src/lib.rs new file mode 100644 index 0000000000000..996d3df8e616b --- /dev/null +++ b/runtime/polkadot/src/lib.rs @@ -0,0 +1,779 @@ +// Copyright 2017 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. + +// Polkadot 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 Polkadot. If not, see . + +//! The Polkadot runtime. This can be compiled with `#[no_std]`, ready for Wasm. + +#![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"] + +use runtime_common::{attestations, claims, parachains, registrar, slots, + impls::{CurrencyToVoteHandler, TargetedFeeAdjustment, ToAuthor, WeightToFee}, + NegativeImbalance, BlockHashCount, MaximumBlockWeight, AvailableBlockRatio, + MaximumBlockLength, +}; + +use rstd::prelude::*; +use sp_core::u32_trait::{_1, _2, _3, _4, _5}; +use codec::{Encode, Decode}; +use primitives::{ + AccountId, AccountIndex, Balance, BlockNumber, Hash, Nonce, Signature, Moment, + parachain::{self, ActiveParas, CandidateReceipt}, ValidityError, +}; +use sp_runtime::{ + create_runtime_str, generic, impl_opaque_keys, + ApplyExtrinsicResult, Permill, Perbill, RuntimeDebug, + transaction_validity::{TransactionValidity, InvalidTransaction, TransactionValidityError}, + curve::PiecewiseLinear, + traits::{BlakeTwo256, Block as BlockT, StaticLookup, SignedExtension, OpaqueKeys}, +}; +use version::RuntimeVersion; +use grandpa::{AuthorityId as GrandpaId, fg_primitives}; +#[cfg(any(feature = "std", test))] +use version::NativeVersion; +use sp_core::OpaqueMetadata; +use sp_staking::SessionIndex; +use frame_support::{ + parameter_types, construct_runtime, traits::{SplitTwoWays, Randomness}, + weights::DispatchInfo, +}; +use im_online::sr25519::AuthorityId as ImOnlineId; +use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId; +use system::offchain::TransactionSubmitter; +use pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo; + +#[cfg(feature = "std")] +pub use staking::StakerStatus; +#[cfg(any(feature = "std", test))] +pub use sp_runtime::BuildStorage; +pub use timestamp::Call as TimestampCall; +pub use balances::Call as BalancesCall; +pub use attestations::{Call as AttestationsCall, MORE_ATTESTATIONS_IDENTIFIER}; +pub use parachains::Call as ParachainsCall; + +/// Constant values used within the runtime. +pub mod constants; +use constants::{time::*, currency::*}; + +// Make the WASM binary available. +#[cfg(feature = "std")] +include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); + +// Polkadot version identifier; +/// Runtime version (Polkadot). +pub const VERSION: RuntimeVersion = RuntimeVersion { + spec_name: create_runtime_str!("polkadot"), + impl_name: create_runtime_str!("parity-polkadot"), + authoring_version: 2, + spec_version: 1000, + impl_version: 0, + apis: RUNTIME_API_VERSIONS, +}; + +/// Native version. +#[cfg(any(feature = "std", test))] +pub fn native_version() -> NativeVersion { + NativeVersion { + runtime_version: VERSION, + can_author_with: Default::default(), + } +} + +/// Avoid processing transactions that are anything except staking and claims. +/// +/// RELEASE: This is only relevant for the initial PoA run-in period and may be removed +/// from the release runtime. +#[derive(Default, Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug)] +pub struct OnlyStakingAndClaims; +impl SignedExtension for OnlyStakingAndClaims { + type AccountId = AccountId; + type Call = Call; + type AdditionalSigned = (); + type Pre = (); + type DispatchInfo = DispatchInfo; + + fn additional_signed(&self) -> rstd::result::Result<(), TransactionValidityError> { Ok(()) } + + fn validate(&self, _: &Self::AccountId, call: &Self::Call, _: DispatchInfo, _: usize) + -> TransactionValidity + { + match call { + Call::Slots(_) | Call::Registrar(_) + => Err(InvalidTransaction::Custom(ValidityError::NoPermission.into()).into()), + _ => Ok(Default::default()), + } + } +} + +parameter_types! { + pub const Version: RuntimeVersion = VERSION; +} + +impl system::Trait for Runtime { + type Origin = Origin; + type Call = Call; + type Index = Nonce; + type BlockNumber = BlockNumber; + type Hash = Hash; + type Hashing = BlakeTwo256; + type AccountId = AccountId; + type Lookup = Indices; + type Header = generic::Header; + type Event = Event; + type BlockHashCount = BlockHashCount; + type MaximumBlockWeight = MaximumBlockWeight; + type MaximumBlockLength = MaximumBlockLength; + type AvailableBlockRatio = AvailableBlockRatio; + type Version = Version; + type ModuleToIndex = ModuleToIndex; +} + +parameter_types! { + pub const EpochDuration: u64 = EPOCH_DURATION_IN_BLOCKS as u64; + pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK; +} + +impl babe::Trait for Runtime { + type EpochDuration = EpochDuration; + type ExpectedBlockTime = ExpectedBlockTime; + + // session module is the trigger + type EpochChangeTrigger = babe::ExternalTrigger; +} + +impl indices::Trait for Runtime { + type IsDeadAccount = Balances; + type AccountIndex = AccountIndex; + type ResolveHint = indices::SimpleResolveHint; + type Event = Event; +} + +parameter_types! { + pub const ExistentialDeposit: Balance = 100 * CENTS; + pub const TransferFee: Balance = 1 * CENTS; + pub const CreationFee: Balance = 1 * CENTS; +} + +/// Splits fees 80/20 between treasury and block author. +pub type DealWithFees = SplitTwoWays< + Balance, + NegativeImbalance, + _4, Treasury, // 4 parts (80%) goes to the treasury. + _1, ToAuthor, // 1 part (20%) goes to the block author. +>; + +impl balances::Trait for Runtime { + type Balance = Balance; + type OnFreeBalanceZero = Staking; + type OnNewAccount = Indices; + type Event = Event; + type DustRemoval = (); + type TransferPayment = (); + type ExistentialDeposit = ExistentialDeposit; + type TransferFee = TransferFee; + type CreationFee = CreationFee; +} + +parameter_types! { + pub const TransactionBaseFee: Balance = 1 * CENTS; + pub const TransactionByteFee: Balance = 10 * MILLICENTS; + // for a sane configuration, this should always be less than `AvailableBlockRatio`. + pub const TargetBlockFullness: Perbill = Perbill::from_percent(25); +} + +impl transaction_payment::Trait for Runtime { + type Currency = Balances; + type OnTransactionPayment = DealWithFees; + type TransactionBaseFee = TransactionBaseFee; + type TransactionByteFee = TransactionByteFee; + type WeightToFee = WeightToFee; + type FeeMultiplierUpdate = TargetedFeeAdjustment; +} + +parameter_types! { + pub const MinimumPeriod: u64 = SLOT_DURATION / 2; +} +impl timestamp::Trait for Runtime { + type Moment = u64; + type OnTimestampSet = Babe; + type MinimumPeriod = MinimumPeriod; +} + +parameter_types! { + pub const UncleGenerations: u32 = 0; +} + +// TODO: substrate#2986 implement this properly +impl authorship::Trait for Runtime { + type FindAuthor = session::FindAccountFromAuthorIndex; + type UncleGenerations = UncleGenerations; + type FilterUncle = (); + type EventHandler = (Staking, ImOnline); +} + +parameter_types! { + pub const Period: BlockNumber = 10 * MINUTES; + pub const Offset: BlockNumber = 0; +} + +impl_opaque_keys! { + pub struct SessionKeys { + pub grandpa: Grandpa, + pub babe: Babe, + pub im_online: ImOnline, + pub parachain_validator: Parachains, + pub authority_discovery: AuthorityDiscovery, + } +} + +parameter_types! { + pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17); +} + +impl session::Trait for Runtime { + type OnSessionEnding = Staking; + type SessionHandler = ::KeyTypeIdProviders; + type ShouldEndSession = Babe; + type Event = Event; + type Keys = SessionKeys; + type ValidatorId = AccountId; + type ValidatorIdOf = staking::StashOf; + type SelectInitialValidators = Staking; + type DisabledValidatorsThreshold = DisabledValidatorsThreshold; +} + +impl session::historical::Trait for Runtime { + type FullIdentification = staking::Exposure; + type FullIdentificationOf = staking::ExposureOf; +} + +pallet_staking_reward_curve::build! { + const REWARD_CURVE: PiecewiseLinear<'static> = curve!( + min_inflation: 0_025_000, + max_inflation: 0_100_000, + ideal_stake: 0_500_000, + falloff: 0_050_000, + max_piece_count: 40, + test_precision: 0_005_000, + ); +} + +parameter_types! { + // Six sessions in an era (24 hours). +// pub const SessionsPerEra: SessionIndex = 6; + pub const SessionsPerEra: SessionIndex = 6; + // 28 eras for unbonding (28 days). + // KUSAMA: This value is 1/4 of what we expect for the mainnet, however session length is also + // a quarter, so the figure remains the same. + pub const BondingDuration: staking::EraIndex = 28; + pub const SlashDeferDuration: staking::EraIndex = 28; + pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE; +} + +impl staking::Trait for Runtime { + type RewardRemainder = Treasury; + type CurrencyToVote = CurrencyToVoteHandler; + type Event = Event; + type Currency = Balances; + type Slash = Treasury; + type Reward = (); + type SessionsPerEra = SessionsPerEra; + type BondingDuration = BondingDuration; + type SlashDeferDuration = SlashDeferDuration; + // A super-majority of the council can cancel the slash. + type SlashCancelOrigin = collective::EnsureProportionAtLeast<_3, _4, AccountId, CouncilCollective>; + type SessionInterface = Self; + type Time = Timestamp; + type RewardCurve = RewardCurve; +} + +parameter_types! { + // KUSAMA: These values are 1/4 of what we expect for the mainnet. + pub const LaunchPeriod: BlockNumber = 7 * DAYS; + pub const VotingPeriod: BlockNumber = 7 * DAYS; + pub const EmergencyVotingPeriod: BlockNumber = 3 * HOURS; + pub const MinimumDeposit: Balance = 100 * DOLLARS; + pub const EnactmentPeriod: BlockNumber = 8 * DAYS; + pub const CooloffPeriod: BlockNumber = 7 * DAYS; + // One cent: $10,000 / MB + pub const PreimageByteDeposit: Balance = 1 * CENTS; +} + +impl democracy::Trait for Runtime { + type Proposal = Call; + type Event = Event; + type Currency = Balances; + type EnactmentPeriod = EnactmentPeriod; + type LaunchPeriod = LaunchPeriod; + type VotingPeriod = VotingPeriod; + type EmergencyVotingPeriod = EmergencyVotingPeriod; + type MinimumDeposit = MinimumDeposit; + /// A straight majority of the council can decide what their next motion is. + type ExternalOrigin = collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>; + /// A super-majority can have the next scheduled referendum be a straight majority-carries vote. + // KUSAMA: A majority can have the next scheduled legislation be majority-carries. + type ExternalMajorityOrigin = collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>; + /// A unanimous council can have the next scheduled referendum be a straight default-carries + /// (NTB) vote. + type ExternalDefaultOrigin = collective::EnsureProportionAtLeast<_1, _1, AccountId, CouncilCollective>; + /// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote + /// be tabled immediately and with a shorter voting/enactment period. + type FastTrackOrigin = collective::EnsureProportionAtLeast<_2, _3, AccountId, TechnicalCollective>; + // To cancel a proposal which has been passed, 2/3 of the council must agree to it. + type CancellationOrigin = collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>; + // Any single technical committee member may veto a coming council proposal, however they can + // only do it once and it lasts only for the cooloff period. + type VetoOrigin = collective::EnsureMember; + type CooloffPeriod = CooloffPeriod; + type PreimageByteDeposit = PreimageByteDeposit; + type Slash = Treasury; +} + +type CouncilCollective = collective::Instance1; +impl collective::Trait for Runtime { + type Origin = Origin; + type Proposal = Call; + type Event = Event; +} + +parameter_types! { + pub const CandidacyBond: Balance = 100 * DOLLARS; + pub const VotingBond: Balance = 5 * DOLLARS; + /// Daily council elections. + pub const TermDuration: BlockNumber = 24 * HOURS; + pub const DesiredMembers: u32 = 13; + pub const DesiredRunnersUp: u32 = 7; +} + +impl elections_phragmen::Trait for Runtime { + type Event = Event; + type Currency = Balances; + type ChangeMembers = Council; + type CurrencyToVote = CurrencyToVoteHandler; + type CandidacyBond = CandidacyBond; + type VotingBond = VotingBond; + type TermDuration = TermDuration; + type DesiredMembers = DesiredMembers; + type DesiredRunnersUp = DesiredRunnersUp; + type LoserCandidate = Treasury; + type BadReport = Treasury; + type KickedMember = Treasury; +} + +type TechnicalCollective = collective::Instance2; +impl collective::Trait for Runtime { + type Origin = Origin; + type Proposal = Call; + type Event = Event; +} + +impl membership::Trait for Runtime { + type Event = Event; + type AddOrigin = collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>; + type RemoveOrigin = collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>; + type SwapOrigin = collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>; + type ResetOrigin = collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>; + type MembershipInitialized = TechnicalCommittee; + type MembershipChanged = TechnicalCommittee; +} + +parameter_types! { + pub const ProposalBond: Permill = Permill::from_percent(5); + // KUSAMA: This value is 20x of that expected for mainnet + pub const ProposalBondMinimum: Balance = 2_000 * DOLLARS; + // KUSAMA: This value is 1/4 of that expected for mainnet + pub const SpendPeriod: BlockNumber = 6 * DAYS; + // KUSAMA: No burn - let's try to put it to use! + pub const Burn: Permill = Permill::from_percent(0); +} + +impl treasury::Trait for Runtime { + type Currency = Balances; + type ApproveOrigin = collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective>; + type RejectOrigin = collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>; + type Event = Event; + type ProposalRejection = Treasury; + type ProposalBond = ProposalBond; + type ProposalBondMinimum = ProposalBondMinimum; + type SpendPeriod = SpendPeriod; + type Burn = Burn; +} + +impl offences::Trait for Runtime { + type Event = Event; + type IdentificationTuple = session::historical::IdentificationTuple; + type OnOffenceHandler = Staking; +} + +impl authority_discovery::Trait for Runtime {} + +type SubmitTransaction = TransactionSubmitter; + +parameter_types! { + pub const SessionDuration: BlockNumber = EPOCH_DURATION_IN_BLOCKS as _; +} + +impl im_online::Trait for Runtime { + type AuthorityId = ImOnlineId; + type Event = Event; + type Call = Call; + type SubmitTransaction = SubmitTransaction; + type ReportUnresponsiveness = Offences; + type SessionDuration = SessionDuration; +} + +impl grandpa::Trait for Runtime { + type Event = Event; +} + +parameter_types! { + pub const WindowSize: BlockNumber = finality_tracker::DEFAULT_WINDOW_SIZE.into(); + pub const ReportLatency: BlockNumber = finality_tracker::DEFAULT_REPORT_LATENCY.into(); +} + +impl finality_tracker::Trait for Runtime { + type OnFinalizationStalled = (); + type WindowSize = WindowSize; + type ReportLatency = ReportLatency; +} + +parameter_types! { + pub const AttestationPeriod: BlockNumber = 50; +} + +impl attestations::Trait for Runtime { + type AttestationPeriod = AttestationPeriod; + type ValidatorIdentities = parachains::ValidatorIdentities; + type RewardAttestation = Staking; +} + +impl parachains::Trait for Runtime { + type Origin = Origin; + type Call = Call; + type ParachainCurrency = Balances; + type Randomness = RandomnessCollectiveFlip; + type ActiveParachains = Registrar; + type Registrar = Registrar; +} + +parameter_types! { + pub const ParathreadDeposit: Balance = 500 * DOLLARS; + pub const QueueSize: usize = 2; + pub const MaxRetries: u32 = 3; +} + +impl registrar::Trait for Runtime { + type Event = Event; + type Origin = Origin; + type Currency = Balances; + type ParathreadDeposit = ParathreadDeposit; + type SwapAux = Slots; + type QueueSize = QueueSize; + type MaxRetries = MaxRetries; +} + +parameter_types! { + pub const LeasePeriod: BlockNumber = 100_000; + pub const EndingPeriod: BlockNumber = 1000; +} + +impl slots::Trait for Runtime { + type Event = Event; + type Currency = Balances; + type Parachains = Registrar; + type LeasePeriod = LeasePeriod; + type EndingPeriod = EndingPeriod; + type Randomness = RandomnessCollectiveFlip; +} + +parameter_types! { + pub const Prefix: &'static [u8] = b"Pay DOTs to the Polkadot account:"; +} + +impl claims::Trait for Runtime { + type Event = Event; + type Currency = Balances; + type Prefix = Prefix; +} + +parameter_types! { + // KUSAMA: for mainnet this can be reduced. + pub const ReservationFee: Balance = 1000 * DOLLARS; + pub const MinLength: usize = 3; + pub const MaxLength: usize = 32; +} + +impl nicks::Trait for Runtime { + type Event = Event; + type Currency = Balances; + type ReservationFee = ReservationFee; + type Slashed = Treasury; + type ForceOrigin = collective::EnsureMembers<_2, AccountId, CouncilCollective>; + type MinLength = MinLength; + type MaxLength = MaxLength; +} + +parameter_types! { + // KUSAMA: can be probably be reduced for mainnet + // Minimum 100 bytes/KSM deposited (1 CENT/byte) + pub const BasicDeposit: Balance = 1000 * DOLLARS; // 258 bytes on-chain + pub const FieldDeposit: Balance = 250 * DOLLARS; // 66 bytes on-chain + pub const SubAccountDeposit: Balance = 200 * DOLLARS; // 53 bytes on-chain + pub const MaximumSubAccounts: u32 = 100; +} + +impl identity::Trait for Runtime { + type Event = Event; + type Currency = Balances; + type Slashed = Treasury; + type BasicDeposit = BasicDeposit; + type FieldDeposit = FieldDeposit; + type SubAccountDeposit = SubAccountDeposit; + type MaximumSubAccounts = MaximumSubAccounts; + type RegistrarOrigin = collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>; + type ForceOrigin = collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>; +} + +construct_runtime! { + pub enum Runtime where + Block = Block, + NodeBlock = primitives::Block, + UncheckedExtrinsic = UncheckedExtrinsic + { + // Basic stuff; balances is uncallable initially. + System: system::{Module, Call, Storage, Config, Event}, + RandomnessCollectiveFlip: randomness_collective_flip::{Module, Storage}, + + // Must be before session. + Babe: babe::{Module, Call, Storage, Config, Inherent(Timestamp)}, + + Timestamp: timestamp::{Module, Call, Storage, Inherent}, + Indices: indices, + Balances: balances::{Module, Call, Storage, Config, Event}, + TransactionPayment: transaction_payment::{Module, Storage}, + + // Consensus support. + Authorship: authorship::{Module, Call, Storage}, + Staking: staking::{default, OfflineWorker}, + Offences: offences::{Module, Call, Storage, Event}, + Session: session::{Module, Call, Storage, Event, Config}, + FinalityTracker: finality_tracker::{Module, Call, Inherent}, + Grandpa: grandpa::{Module, Call, Storage, Config, Event}, + ImOnline: im_online::{Module, Call, Storage, Event, ValidateUnsigned, Config}, + AuthorityDiscovery: authority_discovery::{Module, Call, Config}, + + // Governance stuff; uncallable initially. + Democracy: democracy::{Module, Call, Storage, Config, Event}, + Council: collective::::{Module, Call, Storage, Origin, Event, Config}, + TechnicalCommittee: collective::::{Module, Call, Storage, Origin, Event, Config}, + ElectionsPhragmen: elections_phragmen::{Module, Call, Storage, Event}, + TechnicalMembership: membership::::{Module, Call, Storage, Event, Config}, + Treasury: treasury::{Module, Call, Storage, Event}, + + // Claims. Usable initially. + Claims: claims::{Module, Call, Storage, Event, Config, ValidateUnsigned}, + + // Parachains stuff; slots are disabled (no auctions initially). The rest are safe as they + // have no public dispatchables. + Parachains: parachains::{Module, Call, Storage, Config, Inherent, Origin}, + Attestations: attestations::{Module, Call, Storage}, + Slots: slots::{Module, Call, Storage, Event}, + Registrar: registrar::{Module, Call, Storage, Event, Config}, + + // Simple nicknames module. + // KUSAMA: Remove before mainnet + Nicks: nicks::{Module, Call, Storage, Event}, + + // Less simple identity module. + Identity: identity::{Module, Call, Storage, Event}, + } +} + +/// The address format for describing accounts. +pub type Address = ::Source; +/// 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 = ( + // RELEASE: remove this for release build. + OnlyStakingAndClaims, + system::CheckVersion, + system::CheckGenesis, + system::CheckEra, + system::CheckNonce, + system::CheckWeight, + transaction_payment::ChargeTransactionPayment::, + registrar::LimitParathreadCommits +); +/// 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 modules. +pub type Executive = executive::Executive, Runtime, AllModules>; + +sp_api::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 block_builder_api::BlockBuilder for Runtime { + fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { + Executive::apply_extrinsic(extrinsic) + } + + fn finalize_block() -> ::Header { + Executive::finalize_block() + } + + fn inherent_extrinsics(data: inherents::InherentData) -> Vec<::Extrinsic> { + data.create_extrinsics() + } + + fn check_inherents( + block: Block, + data: inherents::InherentData, + ) -> inherents::CheckInherentsResult { + data.check_extrinsics(&block) + } + + fn random_seed() -> ::Hash { + RandomnessCollectiveFlip::random_seed() + } + } + + impl tx_pool_api::runtime_api::TaggedTransactionQueue for Runtime { + fn validate_transaction(tx: ::Extrinsic) -> TransactionValidity { + Executive::validate_transaction(tx) + } + } + + impl offchain_primitives::OffchainWorkerApi for Runtime { + fn offchain_worker(number: sp_runtime::traits::NumberFor) { + Executive::offchain_worker(number) + } + } + + impl parachain::ParachainHost for Runtime { + fn validators() -> Vec { + Parachains::authorities() + } + fn duty_roster() -> parachain::DutyRoster { + Parachains::calculate_duty_roster().0 + } + fn active_parachains() -> Vec<(parachain::Id, Option<(parachain::CollatorId, parachain::Retriable)>)> { + Registrar::active_paras() + } + fn parachain_status(id: parachain::Id) -> Option { + Parachains::parachain_status(&id) + } + fn parachain_code(id: parachain::Id) -> Option> { + Parachains::parachain_code(&id) + } + fn ingress(to: parachain::Id, since: Option) + -> Option + { + Parachains::ingress(to, since).map(parachain::StructuredUnroutedIngress) + } + fn get_heads(extrinsics: Vec<::Extrinsic>) -> Option> { + extrinsics + .into_iter() + .find_map(|ex| match UncheckedExtrinsic::decode(&mut ex.encode().as_slice()) { + Ok(ex) => match ex.function { + Call::Parachains(ParachainsCall::set_heads(heads)) => { + Some(heads.into_iter().map(|c| c.candidate).collect()) + } + _ => None, + } + Err(_) => None, + }) + } + } + + impl fg_primitives::GrandpaApi for Runtime { + fn grandpa_authorities() -> Vec<(GrandpaId, u64)> { + Grandpa::grandpa_authorities() + } + } + + impl babe_primitives::BabeApi for Runtime { + fn configuration() -> babe_primitives::BabeConfiguration { + // 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. + // + babe_primitives::BabeConfiguration { + slot_duration: Babe::slot_duration(), + epoch_length: EpochDuration::get(), + c: PRIMARY_PROBABILITY, + genesis_authorities: Babe::authorities(), + randomness: Babe::randomness(), + secondary_slots: true, + } + } + } + + impl authority_discovery_primitives::AuthorityDiscoveryApi for Runtime { + fn authorities() -> Vec { + AuthorityDiscovery::authorities() + } + } + + impl sp_session::SessionKeys for Runtime { + fn generate_session_keys(seed: Option>) -> Vec { + SessionKeys::generate(seed) + } + } + + impl system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Nonce { + System::account_nonce(account) + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi< + Block, + Balance, + UncheckedExtrinsic, + > for Runtime { + fn query_info(uxt: UncheckedExtrinsic, len: u32) -> RuntimeDispatchInfo { + TransactionPayment::query_info(uxt, len) + } + } +} diff --git a/scripts/gitlab/check_runtime.sh b/scripts/gitlab/check_runtime.sh index 2f3c9e8fe756a..fc42deb2ecc51 100755 --- a/scripts/gitlab/check_runtime.sh +++ b/scripts/gitlab/check_runtime.sh @@ -1,10 +1,10 @@ #!/bin/sh # # -# check for any changes in the node/src/runtime, srml/ and core/sr_* trees. if -# there are any changes found, it should mark the PR breaksconsensus and -# "auto-fail" the PR if there isn't a change in the runtime/src/lib.rs file -# that alters the version. +# check for any changes in the ^runtime/ tree. if there are any changes found, +# it should mark the PR B2-breaksapi and "auto-fail" the PR if there +# isn't a change in the runtime/{kusama,polkadot}/src/lib.rs file that alters +# the version. set -e # fail on any error @@ -13,8 +13,6 @@ set -e # fail on any error git log --graph --oneline --decorate=short -n 10 -VERSIONS_FILE="runtime/src/lib.rs" - github_label () { echo echo "# run github-api job for labeling it ${1}" @@ -29,92 +27,90 @@ github_label () { -# make sure the master branch is available in shallow clones -git fetch --depth=${GIT_DEPTH:-100} origin master - - -# check if the wasm sources changed -if ! git diff --name-only origin/master...${CI_COMMIT_SHA} \ - | grep -q -e '^runtime/' -then - cat <<-EOT - - no changes to the runtime source code detected - - EOT - - exit 0 -fi - - - -# check for spec_version updates: if the spec versions changed, then there is -# consensus-critical logic that has changed. the runtime wasm blobs must be -# rebuilt. - -add_spec_version="$(git diff origin/master...${CI_COMMIT_SHA} ${VERSIONS_FILE} \ - | sed -n -r "s/^\+[[:space:]]+spec_version: +([0-9]+),$/\1/p")" -sub_spec_version="$(git diff origin/master...${CI_COMMIT_SHA} ${VERSIONS_FILE} \ - | sed -n -r "s/^\-[[:space:]]+spec_version: +([0-9]+),$/\1/p")" - - -# see if the version and the binary blob changed -if [ "${add_spec_version}" != "${sub_spec_version}" ] -then - - github_label "B2-breaksapi" - - cat <<-EOT +for VERSIONS_FILE in runtime/kusama/src/lib.rs runtime/polkadot/src/lib.rs +do + # check if the wasm sources changed + if ! git diff --name-only origin/master...${CI_COMMIT_SHA} \ + | grep -q -e '^runtime/' + then + cat <<-EOT - changes to the runtime sources and changes in the spec version. + no changes to the runtime source code detected - spec_version: ${sub_spec_version} -> ${add_spec_version} + EOT - EOT - exit 0 - -else - # check for impl_version updates: if only the impl versions changed, we assume - # there is no consensus-critical logic that has changed. - - add_impl_version="$(git diff origin/master...${CI_COMMIT_SHA} ${VERSIONS_FILE} \ - | sed -n -r 's/^\+[[:space:]]+impl_version: +([0-9]+),$/\1/p')" - sub_impl_version="$(git diff origin/master...${CI_COMMIT_SHA} ${VERSIONS_FILE} \ - | sed -n -r 's/^\-[[:space:]]+impl_version: +([0-9]+),$/\1/p')" - - - # see if the impl version changed - if [ "${add_impl_version}" != "${sub_impl_version}" ] + continue + fi + + + + # check for spec_version updates: if the spec versions changed, then there is + # consensus-critical logic that has changed. the runtime wasm blobs must be + # rebuilt. + + add_spec_version="$(git diff origin/master...${CI_COMMIT_SHA} ${VERSIONS_FILE} \ + | sed -n -r "s/^\+[[:space:]]+spec_version: +([0-9]+),$/\1/p")" + sub_spec_version="$(git diff origin/master...${CI_COMMIT_SHA} ${VERSIONS_FILE} \ + | sed -n -r "s/^\-[[:space:]]+spec_version: +([0-9]+),$/\1/p")" + + + # see if the version and the binary blob changed + if [ "${add_spec_version}" != "${sub_spec_version}" ] then + + github_label "B2-breaksapi" + cat <<-EOT + + changes to the runtime sources and changes in the spec version. + + spec_version: ${sub_spec_version} -> ${add_spec_version} - changes to the runtime sources and changes in the impl version. - - impl_version: ${sub_impl_version} -> ${add_impl_version} - EOT - exit 0 - fi - - - cat <<-EOT - - wasm source files changed but not the spec/impl version and the runtime - binary blob. If changes made do not alter logic, just bump 'impl_version'. - If they do change logic, bump 'spec_version' and rebuild wasm. - - source file directories: - - runtime - - versions file: ${VERSIONS_FILE} - - EOT + continue + + else + # check for impl_version updates: if only the impl versions changed, we assume + # there is no consensus-critical logic that has changed. + + add_impl_version="$(git diff origin/master...${CI_COMMIT_SHA} ${VERSIONS_FILE} \ + | sed -n -r 's/^\+[[:space:]]+impl_version: +([0-9]+),$/\1/p')" + sub_impl_version="$(git diff origin/master...${CI_COMMIT_SHA} ${VERSIONS_FILE} \ + | sed -n -r 's/^\-[[:space:]]+impl_version: +([0-9]+),$/\1/p')" + + + # see if the impl version changed + if [ "${add_impl_version}" != "${sub_impl_version}" ] + then + cat <<-EOT + + changes to the runtime sources and changes in the impl version. + + impl_version: ${sub_impl_version} -> ${add_impl_version} + + EOT + continue + fi + + + cat <<-EOT + + wasm source files changed but not the spec/impl version and the runtime + binary blob. If changes made do not alter logic, just bump 'impl_version'. + If they do change logic, bump 'spec_version' and rebuild wasm. + + source file directories: + - runtime + + versions file: ${VERSIONS_FILE} + + EOT - # drop through into pushing `gotissues` and exit 1... -fi + exit 1 + fi +done -# dropped through. there's something wrong; exit 1. -exit 1 +exit 0 # vim: noexpandtab diff --git a/service/Cargo.toml b/service/Cargo.toml index 9335144e3456b..39efab8e52bc9 100644 --- a/service/Cargo.toml +++ b/service/Cargo.toml @@ -15,13 +15,14 @@ hex-literal = "0.2.1" av_store = { package = "polkadot-availability-store", path = "../availability-store" } consensus = { package = "polkadot-validation", path = "../validation" } polkadot-primitives = { path = "../primitives" } -polkadot-runtime = { path = "../runtime" } -polkadot-executor = { path = "../executor" } +polkadot-runtime = { path = "../runtime/polkadot" } +kusama-runtime = { path = "../runtime/kusama" } polkadot-network = { path = "../network" } polkadot-rpc = { path = "../rpc" } sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } +sp-blockchain = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } primitives = { package = "sp-core", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } client = { package = "sc-client", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } client-api = { package = "sc-client-api", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } @@ -34,16 +35,22 @@ grandpa_primitives = { package = "sp-finality-grandpa", git = "https://github.co inherents = { package = "sp-inherents", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } service = { package = "sc-service", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } telemetry = { package = "sc-telemetry", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } -txpool = { package = "sc-transaction-pool", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } -txpool-api = { package = "sp-transaction-pool", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } +sc-transaction-pool = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } +sp-transaction-pool = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } sc-keystore = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } -pallet-babe = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } -pallet-staking = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } -im-online = { package = "pallet-im-online", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +pallet-babe = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } +pallet-staking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } +im-online = { package = "pallet-im-online", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } authority-discovery = { package = "sc-authority-discovery", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } authority-discovery-primitives = { package = "sp-authority-discovery", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } babe = { package = "sc-consensus-babe", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } -babe-primitives = { package = "sp-consensus-babe", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" } +babe-primitives = { package = "sp-consensus-babe", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } +sp-block-builder = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } +pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } +system_rpc_runtime_api = { package = "frame-system-rpc-runtime-api", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } +codec = { package = "parity-scale-codec", version = "1.1.0" } +sp-session = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } +sp-offchain = { package = "sp-offchain", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } [features] default = ["rocksdb"] diff --git a/service/src/chain_spec.rs b/service/src/chain_spec.rs index 384318d038f85..f52160a549076 100644 --- a/service/src/chain_spec.rs +++ b/service/src/chain_spec.rs @@ -18,11 +18,7 @@ use primitives::{Pair, Public, crypto::UncheckedInto, sr25519}; use polkadot_primitives::{AccountId, AccountPublic, parachain::ValidatorId}; -use polkadot_runtime::{ - AuthorityDiscoveryConfig, GenesisConfig, CouncilConfig, DemocracyConfig, SystemConfig, - SessionConfig, StakingConfig, BalancesConfig, SessionKeys, TechnicalCommitteeConfig, - IndicesConfig, StakerStatus, WASM_BINARY, ClaimsConfig, ParachainsConfig, RegistrarConfig -}; +use polkadot_runtime as polkadot; use polkadot_runtime::constants::currency::DOTS; use sp_runtime::{traits::IdentifyAccount, Perbill}; use telemetry::TelemetryEndpoints; @@ -36,8 +32,11 @@ use pallet_staking::Forcing; const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/"; const DEFAULT_PROTOCOL_ID: &str = "dot"; -/// Specialised `ChainSpec`. -pub type ChainSpec = ::service::ChainSpec; +/// The `ChainSpec`. +/// +/// We use the same `ChainSpec` type for Polkadot and Kusama. As Kusama +/// is only loaded from a file, the `GenesisConfig` type is not used. +pub type ChainSpec = service::ChainSpec; pub fn kusama_config() -> Result { ChainSpec::from_json_bytes(&include_bytes!("../res/kusama.json")[..]) @@ -49,11 +48,11 @@ fn session_keys( im_online: ImOnlineId, parachain_validator: ValidatorId, authority_discovery: AuthorityDiscoveryId -) -> SessionKeys { - SessionKeys { babe, grandpa, im_online, parachain_validator, authority_discovery } +) -> polkadot::SessionKeys { + polkadot::SessionKeys { babe, grandpa, im_online, parachain_validator, authority_discovery } } -fn staging_testnet_config_genesis() -> GenesisConfig { +fn staging_testnet_config_genesis() -> polkadot::GenesisConfig { // subkey inspect "$SECRET" let endowed_accounts = vec![ // 5CVFESwfkk7NmhQ6FwHCM9roBvr9BGa4vJHFYU8DnGQxrXvz @@ -138,45 +137,48 @@ fn staging_testnet_config_genesis() -> GenesisConfig { const ENDOWMENT: u128 = 1_000_000 * DOTS; const STASH: u128 = 100 * DOTS; - GenesisConfig { - system: Some(SystemConfig { - code: WASM_BINARY.to_vec(), + polkadot::GenesisConfig { + system: Some(polkadot::SystemConfig { + code: polkadot::WASM_BINARY.to_vec(), changes_trie_config: Default::default(), }), - balances: Some(BalancesConfig { + balances: Some(polkadot::BalancesConfig { balances: endowed_accounts.iter() .map(|k: &AccountId| (k.clone(), ENDOWMENT)) .chain(initial_authorities.iter().map(|x| (x.0.clone(), STASH))) .collect(), vesting: vec![], }), - indices: Some(IndicesConfig { + indices: Some(polkadot::IndicesConfig { ids: endowed_accounts.iter().cloned() .chain(initial_authorities.iter().map(|x| x.0.clone())) .collect::>(), }), - session: Some(SessionConfig { + session: Some(polkadot::SessionConfig { keys: initial_authorities.iter().map(|x| ( x.0.clone(), session_keys(x.2.clone(), x.3.clone(), x.4.clone(), x.5.clone(), x.6.clone()), )).collect::>(), }), - staking: Some(StakingConfig { + staking: Some(polkadot::StakingConfig { current_era: 0, validator_count: 50, minimum_validator_count: 4, - stakers: initial_authorities.iter().map(|x| (x.0.clone(), x.1.clone(), STASH, StakerStatus::Validator)).collect(), + stakers: initial_authorities + .iter() + .map(|x| (x.0.clone(), x.1.clone(), STASH, polkadot::StakerStatus::Validator)) + .collect(), invulnerables: initial_authorities.iter().map(|x| x.0.clone()).collect(), force_era: Forcing::ForceNone, slash_reward_fraction: Perbill::from_percent(10), .. Default::default() }), democracy: Some(Default::default()), - collective_Instance1: Some(CouncilConfig { + collective_Instance1: Some(polkadot::CouncilConfig { members: vec![], phantom: Default::default(), }), - collective_Instance2: Some(TechnicalCommitteeConfig { + collective_Instance2: Some(polkadot::TechnicalCommitteeConfig { members: vec![], phantom: Default::default(), }), @@ -184,17 +186,17 @@ fn staging_testnet_config_genesis() -> GenesisConfig { babe: Some(Default::default()), grandpa: Some(Default::default()), im_online: Some(Default::default()), - authority_discovery: Some(AuthorityDiscoveryConfig { + authority_discovery: Some(polkadot::AuthorityDiscoveryConfig { keys: vec![], }), - parachains: Some(ParachainsConfig { + parachains: Some(polkadot::ParachainsConfig { authorities: vec![], }), - registrar: Some(RegistrarConfig { + registrar: Some(polkadot::RegistrarConfig { parachains: vec![], _phdata: Default::default(), }), - claims: Some(ClaimsConfig { + claims: Some(polkadot::ClaimsConfig { claims: vec![], vesting: vec![], }) @@ -257,7 +259,7 @@ pub fn testnet_genesis( initial_authorities: Vec<(AccountId, AccountId, BabeId, GrandpaId, ImOnlineId, ValidatorId, AuthorityDiscoveryId)>, _root_key: AccountId, endowed_accounts: Option>, -) -> GenesisConfig { +) -> polkadot::GenesisConfig { let endowed_accounts: Vec = endowed_accounts.unwrap_or_else(|| { vec![ get_account_id_from_seed::("Alice"), @@ -278,42 +280,42 @@ pub fn testnet_genesis( const ENDOWMENT: u128 = 1_000_000 * DOTS; const STASH: u128 = 100 * DOTS; - GenesisConfig { - system: Some(SystemConfig { - code: WASM_BINARY.to_vec(), + polkadot::GenesisConfig { + system: Some(polkadot::SystemConfig { + code: polkadot::WASM_BINARY.to_vec(), changes_trie_config: Default::default(), }), - indices: Some(IndicesConfig { + indices: Some(polkadot::IndicesConfig { ids: endowed_accounts.clone(), }), - balances: Some(BalancesConfig { + balances: Some(polkadot::BalancesConfig { balances: endowed_accounts.iter().map(|k| (k.clone(), ENDOWMENT)).collect(), vesting: vec![], }), - session: Some(SessionConfig { + session: Some(polkadot::SessionConfig { keys: initial_authorities.iter().map(|x| ( x.0.clone(), session_keys(x.2.clone(), x.3.clone(), x.4.clone(), x.5.clone(), x.6.clone()), )).collect::>(), }), - staking: Some(StakingConfig { + staking: Some(polkadot::StakingConfig { current_era: 0, minimum_validator_count: 1, validator_count: 2, stakers: initial_authorities.iter() - .map(|x| (x.0.clone(), x.1.clone(), STASH, StakerStatus::Validator)) + .map(|x| (x.0.clone(), x.1.clone(), STASH, polkadot::StakerStatus::Validator)) .collect(), invulnerables: initial_authorities.iter().map(|x| x.0.clone()).collect(), force_era: Forcing::NotForcing, slash_reward_fraction: Perbill::from_percent(10), .. Default::default() }), - democracy: Some(DemocracyConfig::default()), - collective_Instance1: Some(CouncilConfig { + democracy: Some(polkadot::DemocracyConfig::default()), + collective_Instance1: Some(polkadot::CouncilConfig { members: vec![], phantom: Default::default(), }), - collective_Instance2: Some(TechnicalCommitteeConfig { + collective_Instance2: Some(polkadot::TechnicalCommitteeConfig { members: vec![], phantom: Default::default(), }), @@ -321,17 +323,17 @@ pub fn testnet_genesis( babe: Some(Default::default()), grandpa: Some(Default::default()), im_online: Some(Default::default()), - authority_discovery: Some(AuthorityDiscoveryConfig { + authority_discovery: Some(polkadot::AuthorityDiscoveryConfig { keys: vec![], }), - parachains: Some(ParachainsConfig { + parachains: Some(polkadot::ParachainsConfig { authorities: vec![], }), - registrar: Some(RegistrarConfig{ + registrar: Some(polkadot::RegistrarConfig{ parachains: vec![], _phdata: Default::default(), }), - claims: Some(ClaimsConfig { + claims: Some(polkadot::ClaimsConfig { claims: vec![], vesting: vec![], }) @@ -339,7 +341,7 @@ pub fn testnet_genesis( } -fn development_config_genesis() -> GenesisConfig { +fn development_config_genesis() -> polkadot::GenesisConfig { testnet_genesis( vec![ get_authority_keys_from_seed("Alice"), @@ -363,7 +365,7 @@ pub fn development_config() -> ChainSpec { ) } -fn local_testnet_genesis() -> GenesisConfig { +fn local_testnet_genesis() -> polkadot::GenesisConfig { testnet_genesis( vec![ get_authority_keys_from_seed("Alice"), diff --git a/service/src/lib.rs b/service/src/lib.rs index c391787d001db..26b04609f108d 100644 --- a/service/src/lib.rs +++ b/service/src/lib.rs @@ -23,30 +23,35 @@ use futures::{FutureExt, TryFutureExt, task::{Spawn, SpawnError, FutureObj}}; use client::LongestChain; use std::sync::Arc; use std::time::Duration; -use polkadot_primitives::{parachain, Hash, BlockId}; -use polkadot_runtime::GenesisConfig; +use polkadot_primitives::{parachain, Hash, BlockId, AccountId, Nonce, Balance}; use polkadot_network::{gossip::{self as network_gossip, Known}, validation::ValidationNetwork}; -use service::{error::{Error as ServiceError}, Configuration, ServiceBuilder}; +use service::{error::{Error as ServiceError}, ServiceBuilder}; use grandpa::{self, FinalityProofProvider as GrandpaFinalityProofProvider}; use inherents::InherentDataProviders; +use sc_executor::native_executor_instance; use log::info; -pub use service::{AbstractService, Roles, PruningMode, TransactionPoolOptions, Error}; -pub use service::ServiceBuilderCommand; +pub use service::{ + AbstractService, Roles, PruningMode, TransactionPoolOptions, Error, RuntimeGenesis, ServiceBuilderCommand, + TFullClient, TLightClient, TFullBackend, TLightBackend, TFullCallExecutor, TLightCallExecutor, +}; pub use service::config::{DatabaseConfig, full_version_from_strs}; -pub use client::{ExecutionStrategy, CallExecutor}; +pub use sc_executor::NativeExecutionDispatch; +pub use client::{ExecutionStrategy, CallExecutor, Client}; pub use client_api::backend::Backend; pub use sp_api::{Core as CoreApi, ConstructRuntimeApi}; pub use consensus_common::SelectChain; pub use polkadot_network::{PolkadotProtocol}; pub use polkadot_primitives::parachain::{CollatorId, ParachainHost}; pub use polkadot_primitives::Block; -pub use polkadot_runtime::RuntimeApi; pub use primitives::Blake2Hasher; -pub use sp_runtime::traits::ProvideRuntimeApi; +pub use sp_runtime::traits::{Block as BlockT, ProvideRuntimeApi, self as runtime_traits}; pub use sc_network::specialization::NetworkSpecialization; pub use chain_spec::ChainSpec; #[cfg(not(target_os = "unknown"))] pub use consensus::run_validation_worker; +pub use codec::Codec; +pub use polkadot_runtime; +pub use kusama_runtime; /// Wrap a futures01 executor as a futures03 spawn. #[derive(Clone)] @@ -71,50 +76,117 @@ pub struct CustomConfiguration { /// Whether to enable or disable the authority discovery module. pub authority_discovery_enabled: bool, + + /// Milliseconds per block. + pub slot_duration: u64, } +/// Configuration type that is being used. +/// +/// See [`ChainSpec`] for more information why Polkadot `GenesisConfig` is safe here. +pub type Configuration = service::Configuration; + impl Default for CustomConfiguration { fn default() -> Self { Self { collating_for: None, max_block_data_size: None, authority_discovery_enabled: false, + slot_duration: 6000, } } } -/// Chain API type for the transaction pool. -pub type TxChainApi = txpool::FullChainApi< - client::Client, - Block, ->; +native_executor_instance!( + pub PolkadotExecutor, + polkadot_runtime::api::dispatch, + polkadot_runtime::native_version +); + +native_executor_instance!( + pub KusamaExecutor, + kusama_runtime::api::dispatch, + kusama_runtime::native_version +); + +/// A set of APIs that polkadot-like runtimes must implement. +pub trait RuntimeApiCollection : + sp_transaction_pool::runtime_api::TaggedTransactionQueue + + sp_api::ApiExt + + babe_primitives::BabeApi + + ParachainHost + + sp_block_builder::BlockBuilder + + system_rpc_runtime_api::AccountNonceApi + + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi + + sp_api::Metadata + + sp_offchain::OffchainWorkerApi + + sp_session::SessionKeys + + authority_discovery_primitives::AuthorityDiscoveryApi +where + Extrinsic: RuntimeExtrinsic, +{} + +impl RuntimeApiCollection for Api +where + Api: + sp_transaction_pool::runtime_api::TaggedTransactionQueue + + sp_api::ApiExt + + babe_primitives::BabeApi + + ParachainHost + + sp_block_builder::BlockBuilder + + system_rpc_runtime_api::AccountNonceApi + + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi + + sp_api::Metadata + + sp_offchain::OffchainWorkerApi + + sp_session::SessionKeys + + authority_discovery_primitives::AuthorityDiscoveryApi, + Extrinsic: RuntimeExtrinsic, +{} + +pub trait RuntimeExtrinsic: codec::Codec + Send + Sync + 'static +{} + +impl RuntimeExtrinsic for E where E: codec::Codec + Send + Sync + 'static +{} + +/// Can be called for a `Configuration` to check if it is a configuration for the `Kusama` network. +pub trait IsKusama { + /// Returns if this is a configuration for the `Kusama` network. + fn is_kusama(&self) -> bool; +} + +impl IsKusama for Configuration { + fn is_kusama(&self) -> bool { + self.chain_spec.name().starts_with("Kusama") + } +} /// Starts a `ServiceBuilder` for a full service. /// /// Use this macro if you don't actually need the full service, but just the builder in order to /// be able to perform chain operations. macro_rules! new_full_start { - ($config:expr) => {{ + ($config:expr, $runtime:ty, $executor:ty) => {{ let mut import_setup = None; let inherent_data_providers = inherents::InherentDataProviders::new(); let builder = service::ServiceBuilder::new_full::< - Block, RuntimeApi, polkadot_executor::Executor + Block, $runtime, $executor >($config)? .with_select_chain(|_, backend| { Ok(client::LongestChain::new(backend.clone())) })? .with_transaction_pool(|config, client, _fetcher| { - let pool_api = txpool::FullChainApi::new(client.clone()); - let pool = txpool::BasicPool::new(config, pool_api); - let maintainer = txpool::FullBasicPoolMaintainer::new(pool.pool().clone(), client); - let maintainable_pool = txpool_api::MaintainableTransactionPool::new(pool, maintainer); + let pool_api = sc_transaction_pool::FullChainApi::new(client.clone()); + let pool = sc_transaction_pool::BasicPool::new(config, pool_api); + let maintainer = sc_transaction_pool::FullBasicPoolMaintainer::new(pool.pool().clone(), client); + let maintainable_pool = sp_transaction_pool::MaintainableTransactionPool::new(pool, maintainer); Ok(maintainable_pool) })? .with_import_queue(|_config, client, mut select_chain, _| { let select_chain = select_chain.take() .ok_or_else(|| service::Error::SelectChainRequired)?; let (grandpa_block_import, grandpa_link) = - grandpa::block_import::<_, _, _, RuntimeApi, _>( + grandpa::block_import::<_, _, _, Runtime, _>( client.clone(), &*client, select_chain )?; let justification_import = grandpa_block_import.clone(); @@ -149,20 +221,60 @@ macro_rules! new_full_start { } /// Builds a new object suitable for chain operations. -pub fn new_chain_ops(config: Configuration) +pub fn new_chain_ops(config: Configuration) -> Result, ServiceError> +where + Runtime: ConstructRuntimeApi> + Send + Sync + 'static, + Runtime::RuntimeApi: RuntimeApiCollection, + Dispatch: NativeExecutionDispatch + 'static, + Extrinsic: RuntimeExtrinsic, { - Ok(new_full_start!(config).0) + Ok(new_full_start!(config, Runtime, Dispatch).0) +} + +/// Create a new Polkadot service for a full node. +pub fn polkadot_new_full(config: Configuration) + -> Result, + SelectChain = LongestChain, Block>, + CallExecutor = TFullCallExecutor, + >, ServiceError> +{ + new_full(config) +} + +/// Create a new Kusama service for a full node. +pub fn kusama_new_full(config: Configuration) + -> Result, + SelectChain = LongestChain, Block>, + CallExecutor = TFullCallExecutor, + >, ServiceError> +{ + new_full(config) } /// Builds a new service for a full client. -pub fn new_full(config: Configuration) +pub fn new_full(config: Configuration) -> Result + 'static, - SelectChain = impl SelectChain, - CallExecutor = impl CallExecutor + Clone + Send + Sync + 'static, + Block = Block, + RuntimeApi = Runtime, + NetworkSpecialization = PolkadotProtocol, + Backend = TFullBackend, + SelectChain = LongestChain, Block>, + CallExecutor = TFullCallExecutor, >, ServiceError> + where + Runtime: ConstructRuntimeApi> + Send + Sync + 'static, + Runtime::RuntimeApi: RuntimeApiCollection, + Dispatch: NativeExecutionDispatch + 'static, + Extrinsic: RuntimeExtrinsic, { use sc_network::DhtEvent; use futures::{compat::Stream01CompatExt, stream::StreamExt}; @@ -180,13 +292,14 @@ pub fn new_full(config: Configuration) let name = config.name.clone(); let authority_discovery_enabled = config.custom.authority_discovery_enabled; let sentry_nodes = config.network.sentry_nodes.clone(); + let slot_duration = config.custom.slot_duration; // sentry nodes announce themselves as authorities to the network // and should run the same protocols authorities do, but it should // never actively participate in any consensus process. let participates_in_consensus = is_authority && !config.sentry_mode; - let (builder, mut import_setup, inherent_data_providers) = new_full_start!(config); + let (builder, mut import_setup, inherent_data_providers) = new_full_start!(config, Runtime, Dispatch); // Dht event channel from the network to the authority discovery module. Use // bounded channel to ensure back-pressure. Authority discovery is triggering one @@ -290,7 +403,7 @@ pub fn new_full(config: Configuration) Arc::new(WrappedExecutor(service.spawn_task_handle())), service.keystore(), availability_store.clone(), - polkadot_runtime::constants::time::SLOT_DURATION, + slot_duration, max_block_data_size, ); @@ -315,7 +428,7 @@ pub fn new_full(config: Configuration) env: proposer, sync_oracle: service.network(), inherent_data_providers: inherent_data_providers.clone(), - force_authoring: force_authoring, + force_authoring, babe_link, can_author_with, }; @@ -367,7 +480,7 @@ pub fn new_full(config: Configuration) // provide better guarantees of block and vote data availability than // the observer. let grandpa_config = grandpa::GrandpaParams { - config: config, + config, link: link_half, network: service.network(), inherent_data_providers: inherent_data_providers.clone(), @@ -388,35 +501,70 @@ pub fn new_full(config: Configuration) Ok(service) } +/// Create a new Polkadot service for a light client. +pub fn polkadot_new_light(config: Configuration) + -> Result, + SelectChain = LongestChain, Block>, + CallExecutor = TLightCallExecutor, + >, ServiceError> +{ + new_light(config) +} + +/// Create a new Kusama service for a light client. +pub fn kusama_new_light(config: Configuration) + -> Result, + SelectChain = LongestChain, Block>, + CallExecutor = TLightCallExecutor, + >, ServiceError> +{ + new_light(config) +} + /// Builds a new service for a light client. -pub fn new_light(config: Configuration) +pub fn new_light(config: Configuration) -> Result + 'static, - SelectChain = impl SelectChain, - CallExecutor = impl CallExecutor + Clone + Send + Sync + 'static, + Block = Block, + RuntimeApi = Runtime, + NetworkSpecialization = PolkadotProtocol, + Backend = TLightBackend, + SelectChain = LongestChain, Block>, + CallExecutor = TLightCallExecutor, >, ServiceError> +where + Runtime: ConstructRuntimeApi> + Send + Sync + 'static, + Runtime::RuntimeApi: RuntimeApiCollection, + Dispatch: NativeExecutionDispatch + 'static, + Extrinsic: RuntimeExtrinsic, { let inherent_data_providers = InherentDataProviders::new(); - ServiceBuilder::new_light::(config)? + ServiceBuilder::new_light::(config)? .with_select_chain(|_, backend| { Ok(LongestChain::new(backend.clone())) })? .with_transaction_pool(|config, client, fetcher| { let fetcher = fetcher .ok_or_else(|| "Trying to start light transaction pool without active fetcher")?; - let pool_api = txpool::LightChainApi::new(client.clone(), fetcher.clone()); - let pool = txpool::BasicPool::new(config, pool_api); - let maintainer = txpool::LightBasicPoolMaintainer::with_defaults(pool.pool().clone(), client, fetcher); - let maintainable_pool = txpool_api::MaintainableTransactionPool::new(pool, maintainer); + let pool_api = sc_transaction_pool::LightChainApi::new(client.clone(), fetcher.clone()); + let pool = sc_transaction_pool::BasicPool::new(config, pool_api); + let maintainer = sc_transaction_pool::LightBasicPoolMaintainer::with_defaults(pool.pool().clone(), client, fetcher); + let maintainable_pool = sp_transaction_pool::MaintainableTransactionPool::new(pool, maintainer); Ok(maintainable_pool) })? .with_import_queue_and_fprb(|_config, client, backend, fetcher, _select_chain, _| { let fetch_checker = fetcher .map(|fetcher| fetcher.checker().clone()) .ok_or_else(|| "Trying to start light import queue without active fetch checker")?; - let grandpa_block_import = grandpa::light_block_import::<_, _, _, RuntimeApi>( + let grandpa_block_import = grandpa::light_block_import::<_, _, _, Runtime>( client.clone(), backend, &*client, Arc::new(fetch_checker) )?; diff --git a/src/main.rs b/src/main.rs index 662283d9cc24b..3f11c729d559a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -18,14 +18,14 @@ #![warn(missing_docs)] -use cli::{AbstractService, VersionInfo}; -use futures::{channel::oneshot, future, FutureExt, task::Spawn}; +use cli::VersionInfo; +use futures::{channel::oneshot, future, FutureExt}; use std::cell::RefCell; // the regular polkadot worker simply does nothing until ctrl-c -struct Worker; -impl cli::IntoExit for Worker { +struct Exit; +impl cli::IntoExit for Exit { type Exit = future::Map, fn(Result<(), oneshot::Canceled>) -> ()>; fn into_exit(self) -> Self::Exit { // can't use signal directly here because CtrlC takes only `Fn`. @@ -43,21 +43,6 @@ impl cli::IntoExit for Worker { } } -impl cli::Worker for Worker { - type Work = ::Exit; - fn work(self, _: &S, _: SP) -> Self::Work - where S: AbstractService, - SC: service::SelectChain + 'static, - B: service::Backend + 'static, - CE: service::CallExecutor + Clone + Send + Sync + 'static, - SP: Spawn + Clone + Send + Sync + 'static { - use cli::IntoExit; - self.into_exit() - } -} - fn main() -> Result<(), cli::error::Error> { let version = VersionInfo { name: "Parity Polkadot", @@ -69,5 +54,5 @@ fn main() -> Result<(), cli::error::Error> { support_url: "https://github.com/paritytech/polkadot/issues/new", }; - cli::run(Worker, version) + cli::run(Exit, version) } diff --git a/test-parachains/adder/collator/src/main.rs b/test-parachains/adder/collator/src/main.rs index 6c4823b5eb5fd..a107bd745d4de 100644 --- a/test-parachains/adder/collator/src/main.rs +++ b/test-parachains/adder/collator/src/main.rs @@ -29,7 +29,9 @@ use primitives::{ HeadData, BlockData, Id as ParaId, Message, OutgoingMessages, Status as ParachainStatus, }, }; -use collator::{InvalidHead, ParachainContext, VersionInfo, Network, BuildParachainContext}; +use collator::{ + InvalidHead, ParachainContext, Network, BuildParachainContext, load_spec, Configuration, +}; use parking_lot::Mutex; use futures::{future::{Ready, ok, err}, task::Spawn}; @@ -106,9 +108,9 @@ impl ParachainContext for AdderContext { impl BuildParachainContext for AdderContext { type ParachainContext = Self; - fn build( + fn build( self, - _: Arc>, + _: Arc>, _: SP, network: Arc, ) -> Result @@ -153,20 +155,12 @@ fn main() { _network: None, }; - let res = ::collator::run_collator( + let res = collator::run_collator( context, id, exit, key, - VersionInfo { - name: "", - version: "", - commit: "", - executable_name: "adder-collator", - description: "collator for adder parachain", - author: "parity technologies", - support_url: "https://github.com/paritytech/polkadot/issues/new", - } + Configuration::default_with_spec_and_base_path(load_spec("dev").unwrap().unwrap(), None), ); if let Err(e) = res { diff --git a/validation/Cargo.toml b/validation/Cargo.toml index 6203a47961906..9d115f64e5ad1 100644 --- a/validation/Cargo.toml +++ b/validation/Cargo.toml @@ -18,7 +18,6 @@ availability_store = { package = "polkadot-availability-store", path = "../avail parachain = { package = "polkadot-parachain", path = "../parachain" } polkadot-primitives = { path = "../primitives" } polkadot-erasure-coding = { path = "../erasure-coding" } -polkadot-runtime = { path = "../runtime" } table = { package = "polkadot-statement-table", path = "../statement-table" } grandpa = { package = "sc-finality-grandpa", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } inherents = { package = "sp-inherents", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" } diff --git a/validation/src/lib.rs b/validation/src/lib.rs index 3412dab26a11a..22bed3b60b171 100644 --- a/validation/src/lib.rs +++ b/validation/src/lib.rs @@ -49,7 +49,7 @@ use polkadot_primitives::parachain::{ Id as ParaId, Chain, DutyRoster, CandidateReceipt, ParachainHost, AttestedCandidate, Statement as PrimitiveStatement, Message, OutgoingMessages, Collation, PoVBlock, ErasureChunk, ValidatorSignature, ValidatorIndex, - ValidatorPair, ValidatorId, + ValidatorPair, ValidatorId, NEW_HEADS_IDENTIFIER, }; use primitives::Pair; use runtime_primitives::traits::{ProvideRuntimeApi, DigestFor}; @@ -717,7 +717,7 @@ impl CreateProposalData where let mut inherent_data = self.inherent_data .take() .expect("CreateProposal is not polled after finishing; qed"); - inherent_data.put_data(polkadot_runtime::NEW_HEADS_IDENTIFIER, &candidates) + inherent_data.put_data(NEW_HEADS_IDENTIFIER, &candidates) .map_err(Error::InherentError)?; let runtime_api = self.client.runtime_api();