From 384c0a165df8652d563496171de359509e5d65d4 Mon Sep 17 00:00:00 2001 From: arkpar Date: Sat, 12 Feb 2022 12:59:53 +0100 Subject: [PATCH 01/14] Started native runtime removal --- Cargo.lock | 12 +- Cargo.toml | 6 +- bin/node-template/node/Cargo.toml | 5 +- bin/node-template/node/src/command.rs | 6 +- bin/node-template/node/src/service.rs | 4 +- bin/node/cli/Cargo.toml | 16 +- bin/node/cli/src/chain_spec.rs | 375 +--------------- bin/node/cli/src/command.rs | 21 +- bin/node/cli/src/service.rs | 94 +--- bin/node/inspect/src/command.rs | 13 +- bin/node/rpc/src/lib.rs | 22 +- bin/node/runtime/src/lib.rs | 2 +- client/api/src/call_executor.rs | 2 +- client/authority-discovery/src/lib.rs | 4 +- client/authority-discovery/src/worker.rs | 1 - .../basic-authorship/src/basic_authorship.rs | 20 +- client/beefy/src/lib.rs | 4 - client/beefy/src/worker.rs | 2 - client/block-builder/src/lib.rs | 20 +- client/cli/src/lib.rs | 2 - client/cli/src/runner.rs | 1 - client/consensus/aura/src/import_queue.rs | 5 +- client/consensus/aura/src/lib.rs | 10 +- client/consensus/babe/rpc/src/lib.rs | 1 - client/consensus/babe/src/lib.rs | 10 +- client/consensus/common/src/block_import.rs | 2 +- .../manual-seal/src/consensus/aura.rs | 4 +- .../manual-seal/src/consensus/babe.rs | 4 +- .../manual-seal/src/consensus/timestamp.rs | 6 +- client/consensus/pow/src/lib.rs | 2 - client/executor/src/lib.rs | 4 + client/executor/src/native_executor.rs | 4 +- client/finality-grandpa/src/environment.rs | 2 - client/finality-grandpa/src/import.rs | 2 - client/finality-grandpa/src/lib.rs | 3 - client/offchain/src/lib.rs | 2 - client/rpc/src/author/mod.rs | 1 - client/rpc/src/state/mod.rs | 3 +- client/rpc/src/state/state_full.rs | 2 - client/service/src/builder.rs | 41 +- client/service/src/client/call_executor.rs | 42 +- client/service/src/client/client.rs | 164 ++----- client/service/src/lib.rs | 2 +- client/tracing/src/block/mod.rs | 3 +- client/transaction-pool/src/api.rs | 3 - .../src/graph/validated_pool.rs | 2 +- client/transaction-pool/src/lib.rs | 2 - frame/contracts/rpc/runtime-api/src/lib.rs | 3 +- frame/contracts/rpc/src/lib.rs | 13 +- frame/merkle-mountain-range/rpc/src/lib.rs | 5 +- frame/transaction-payment/rpc/src/lib.rs | 2 +- .../api/proc-macro/src/decl_runtime_apis.rs | 417 +++++++++++++++++- primitives/api/src/lib.rs | 173 +++++++- primitives/consensus/common/src/lib.rs | 12 +- primitives/consensus/pow/src/lib.rs | 6 +- primitives/core/src/traits.rs | 2 +- primitives/session/src/lib.rs | 1 - primitives/state-machine/src/lib.rs | 12 +- test-utils/client/src/client_ext.rs | 7 +- test-utils/client/src/lib.rs | 39 +- utils/frame/benchmarking-cli/src/command.rs | 10 +- utils/frame/rpc/system/src/lib.rs | 2 - 62 files changed, 790 insertions(+), 872 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index feb721e6092cf..63cc6f36692e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4679,23 +4679,16 @@ dependencies = [ "clap_complete", "criterion", "frame-benchmarking-cli", - "frame-system", - "frame-system-rpc-runtime-api", "futures 0.3.16", "hex-literal", "jsonrpsee-ws-client 0.4.1", "log 0.4.14", "nix", - "node-executor", "node-inspect", "node-primitives", "node-rpc", - "node-runtime", - "pallet-asset-tx-payment", "pallet-balances", - "pallet-im-online", "pallet-timestamp", - "pallet-transaction-payment", "parity-scale-codec", "platforms", "rand 0.8.4", @@ -4947,7 +4940,6 @@ dependencies = [ "frame-benchmarking", "frame-benchmarking-cli", "jsonrpc-core", - "node-template-runtime", "pallet-transaction-payment-rpc", "sc-basic-authorship", "sc-cli", @@ -7582,9 +7574,9 @@ dependencies = [ [[package]] name = "retain_mut" -version = "0.1.4" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "448296241d034b96c11173591deaa1302f2c17b56092106c1f92c1bc0183a8c9" +checksum = "51dd4445360338dab5116712bee1388dc727991d51969558a8882ab552e6db30" [[package]] name = "ring" diff --git a/Cargo.toml b/Cargo.toml index a31d8011a9f44..2015a6167731c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -276,8 +276,9 @@ yamux = { opt-level = 3 } zeroize = { opt-level = 3 } [profile.release] -# Substrate runtime requires unwinding. -panic = "unwind" +panic = "abort" +#lto= "off" +incremental = true [profile.production] inherits = "release" @@ -288,3 +289,4 @@ inherits = "release" lto = "fat" # https://doc.rust-lang.org/rustc/codegen-options/index.html#codegen-units codegen-units = 1 +incremental = false diff --git a/bin/node-template/node/Cargo.toml b/bin/node-template/node/Cargo.toml index 1f8ff0ae1e0d4..a3405f32d9fb6 100644 --- a/bin/node-template/node/Cargo.toml +++ b/bin/node-template/node/Cargo.toml @@ -53,11 +53,12 @@ frame-benchmarking = { version = "4.0.0-dev", path = "../../../frame/benchmarkin frame-benchmarking-cli = { version = "4.0.0-dev", path = "../../../utils/frame/benchmarking-cli" } # Local Dependencies -node-template-runtime = { version = "4.0.0-dev", path = "../runtime" } +#node-template-runtime = { version = "4.0.0-dev", path = "../runtime" } [build-dependencies] substrate-build-script-utils = { version = "3.0.0", path = "../../../utils/build-script-utils" } [features] default = [] -runtime-benchmarks = ["node-template-runtime/runtime-benchmarks"] +runtime-benchmarks = [] +#runtime-benchmarks = ["node-template-runtime/runtime-benchmarks"] diff --git a/bin/node-template/node/src/command.rs b/bin/node-template/node/src/command.rs index e1cfeaeb801e3..3d0652ca6a7bd 100644 --- a/bin/node-template/node/src/command.rs +++ b/bin/node-template/node/src/command.rs @@ -4,7 +4,7 @@ use crate::{ service, }; use node_template_runtime::Block; -use sc_cli::{ChainSpec, RuntimeVersion, SubstrateCli}; +use sc_cli::{SubstrateCli}; use sc_service::PartialComponents; impl SubstrateCli for Cli { @@ -40,10 +40,6 @@ impl SubstrateCli for Cli { Box::new(chain_spec::ChainSpec::from_json_file(std::path::PathBuf::from(path))?), }) } - - fn native_runtime_version(_: &Box) -> &'static RuntimeVersion { - &node_template_runtime::VERSION - } } /// Parse and run command line arguments diff --git a/bin/node-template/node/src/service.rs b/bin/node-template/node/src/service.rs index 4395718a6d680..8b0937b614f7c 100644 --- a/bin/node-template/node/src/service.rs +++ b/bin/node-template/node/src/service.rs @@ -130,7 +130,7 @@ pub fn new_partial( Ok((timestamp, slot)) }, spawner: &task_manager.spawn_essential_handle(), - can_author_with: sp_consensus::CanAuthorWithNativeVersion::new( + can_author_with: sp_consensus::CanAuthorWithVersion::new( client.executor().clone(), ), registry: config.prometheus_registry(), @@ -257,7 +257,7 @@ pub fn new_full(mut config: Configuration) -> Result ); let can_author_with = - sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()); + sp_consensus::CanAuthorWithVersion::new(client.executor().clone()); let slot_duration = sc_consensus_aura::slot_duration(&*client)?; let raw_slot_duration = slot_duration.slot_duration(); diff --git a/bin/node/cli/Cargo.toml b/bin/node/cli/Cargo.toml index 4b14fe31e5a56..d156c73a9ccb2 100644 --- a/bin/node/cli/Cargo.toml +++ b/bin/node/cli/Cargo.toml @@ -77,18 +77,10 @@ sc-executor = { version = "0.10.0-dev", path = "../../../client/executor" } sc-authority-discovery = { version = "0.10.0-dev", path = "../../../client/authority-discovery" } sc-sync-state-rpc = { version = "0.10.0-dev", path = "../../../client/sync-state-rpc" } -# frame dependencies -frame-system = { version = "4.0.0-dev", path = "../../../frame/system" } -frame-system-rpc-runtime-api = { version = "4.0.0-dev", path = "../../../frame/system/rpc/runtime-api" } -pallet-transaction-payment = { version = "4.0.0-dev", path = "../../../frame/transaction-payment" } -pallet-asset-tx-payment = { version = "4.0.0-dev", path = "../../../frame/transaction-payment/asset-tx-payment/" } -pallet-im-online = { version = "4.0.0-dev", default-features = false, path = "../../../frame/im-online" } - # node-specific dependencies -node-runtime = { version = "3.0.0-dev", path = "../runtime" } +# node-runtime = { version = "3.0.0-dev", path = "../runtime" } node-rpc = { version = "3.0.0-dev", path = "../rpc" } node-primitives = { version = "2.0.0", path = "../primitives" } -node-executor = { version = "3.0.0-dev", path = "../executor" } # CLI-specific dependencies sc-cli = { version = "0.10.0-dev", optional = true, path = "../../../client/cli" } @@ -97,7 +89,6 @@ node-inspect = { version = "0.9.0-dev", optional = true, path = "../inspect" } try-runtime-cli = { version = "0.10.0-dev", optional = true, path = "../../../utils/frame/try-runtime/cli" } [target.'cfg(any(target_arch="x86_64", target_arch="aarch64"))'.dependencies] -node-executor = { version = "3.0.0-dev", path = "../executor", features = ["wasmtime"] } sc-cli = { version = "0.10.0-dev", optional = true, path = "../../../client/cli", features = ["wasmtime"] } sc-service = { version = "0.10.0-dev", default-features = false, path = "../../../client/service", features = [ "wasmtime", @@ -146,7 +137,6 @@ pallet-balances = { version = "4.0.0-dev", path = "../../../frame/balances" } [features] default = ["cli"] cli = [ - "node-executor/wasmi-errno", "node-inspect", "sc-cli", "frame-benchmarking-cli", @@ -157,10 +147,10 @@ cli = [ "substrate-build-script-utils", "try-runtime-cli", ] -runtime-benchmarks = ["node-runtime/runtime-benchmarks", "frame-benchmarking-cli"] +runtime-benchmarks = ["frame-benchmarking-cli"] # Enable features that allow the runtime to be tried and debugged. Name might be subject to change # in the near future. -try-runtime = ["node-runtime/try-runtime", "try-runtime-cli"] +try-runtime = ["try-runtime-cli"] [[bench]] name = "transaction_pool" diff --git a/bin/node/cli/src/chain_spec.rs b/bin/node/cli/src/chain_spec.rs index 11516f964903a..c6a1ceb1531dc 100644 --- a/bin/node/cli/src/chain_spec.rs +++ b/bin/node/cli/src/chain_spec.rs @@ -18,33 +18,9 @@ //! Substrate chain configurations. -use grandpa_primitives::AuthorityId as GrandpaId; -use hex_literal::hex; -use node_runtime::{ - constants::currency::*, wasm_binary_unwrap, AuthorityDiscoveryConfig, BabeConfig, - BalancesConfig, Block, CouncilConfig, DemocracyConfig, ElectionsConfig, GrandpaConfig, - ImOnlineConfig, IndicesConfig, MaxNominations, SessionConfig, SessionKeys, SocietyConfig, - StakerStatus, StakingConfig, SudoConfig, SystemConfig, TechnicalCommitteeConfig, -}; -use pallet_im_online::sr25519::AuthorityId as ImOnlineId; use sc_chain_spec::ChainSpecExtension; -use sc_service::ChainType; -use sc_telemetry::TelemetryEndpoints; use serde::{Deserialize, Serialize}; -use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId; -use sp_consensus_babe::AuthorityId as BabeId; -use sp_core::{crypto::UncheckedInto, sr25519, Pair, Public}; -use sp_runtime::{ - traits::{IdentifyAccount, Verify}, - Perbill, -}; - -pub use node_primitives::{AccountId, Balance, Signature}; -pub use node_runtime::GenesisConfig; - -type AccountPublic = ::Signer; - -const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/"; +pub use node_primitives::{AccountId, Balance, Signature, Block}; /// Node `ChainSpec` extensions. /// @@ -62,358 +38,25 @@ pub struct Extensions { } /// Specialized `ChainSpec`. -pub type ChainSpec = sc_service::GenericChainSpec; +pub type ChainSpec = sc_service::GenericChainSpec<(), Extensions>; /// Flaming Fir testnet generator pub fn flaming_fir_config() -> Result { ChainSpec::from_json_bytes(&include_bytes!("../res/flaming-fir.json")[..]) } -fn session_keys( - grandpa: GrandpaId, - babe: BabeId, - im_online: ImOnlineId, - authority_discovery: AuthorityDiscoveryId, -) -> SessionKeys { - SessionKeys { grandpa, babe, im_online, authority_discovery } -} - -fn staging_testnet_config_genesis() -> GenesisConfig { - #[rustfmt::skip] - // stash, controller, session-key - // generated with secret: - // for i in 1 2 3 4 ; do for j in stash controller; do subkey inspect "$secret"/fir/$j/$i; done; done - // - // and - // - // for i in 1 2 3 4 ; do for j in session; do subkey --ed25519 inspect "$secret"//fir//$j//$i; done; done - - let initial_authorities: Vec<( - AccountId, - AccountId, - GrandpaId, - BabeId, - ImOnlineId, - AuthorityDiscoveryId, - )> = vec![ - ( - // 5Fbsd6WXDGiLTxunqeK5BATNiocfCqu9bS1yArVjCgeBLkVy - hex!["9c7a2ee14e565db0c69f78c7b4cd839fbf52b607d867e9e9c5a79042898a0d12"].into(), - // 5EnCiV7wSHeNhjW3FSUwiJNkcc2SBkPLn5Nj93FmbLtBjQUq - hex!["781ead1e2fa9ccb74b44c19d29cb2a7a4b5be3972927ae98cd3877523976a276"].into(), - // 5Fb9ayurnxnaXj56CjmyQLBiadfRCqUbL2VWNbbe1nZU6wiC - hex!["9becad03e6dcac03cee07edebca5475314861492cdfc96a2144a67bbe9699332"] - .unchecked_into(), - // 5EZaeQ8djPcq9pheJUhgerXQZt9YaHnMJpiHMRhwQeinqUW8 - hex!["6e7e4eb42cbd2e0ab4cae8708ce5509580b8c04d11f6758dbf686d50fe9f9106"] - .unchecked_into(), - // 5EZaeQ8djPcq9pheJUhgerXQZt9YaHnMJpiHMRhwQeinqUW8 - hex!["6e7e4eb42cbd2e0ab4cae8708ce5509580b8c04d11f6758dbf686d50fe9f9106"] - .unchecked_into(), - // 5EZaeQ8djPcq9pheJUhgerXQZt9YaHnMJpiHMRhwQeinqUW8 - hex!["6e7e4eb42cbd2e0ab4cae8708ce5509580b8c04d11f6758dbf686d50fe9f9106"] - .unchecked_into(), - ), - ( - // 5ERawXCzCWkjVq3xz1W5KGNtVx2VdefvZ62Bw1FEuZW4Vny2 - hex!["68655684472b743e456907b398d3a44c113f189e56d1bbfd55e889e295dfde78"].into(), - // 5Gc4vr42hH1uDZc93Nayk5G7i687bAQdHHc9unLuyeawHipF - hex!["c8dc79e36b29395413399edaec3e20fcca7205fb19776ed8ddb25d6f427ec40e"].into(), - // 5EockCXN6YkiNCDjpqqnbcqd4ad35nU4RmA1ikM4YeRN4WcE - hex!["7932cff431e748892fa48e10c63c17d30f80ca42e4de3921e641249cd7fa3c2f"] - .unchecked_into(), - // 5DhLtiaQd1L1LU9jaNeeu9HJkP6eyg3BwXA7iNMzKm7qqruQ - hex!["482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e"] - .unchecked_into(), - // 5DhLtiaQd1L1LU9jaNeeu9HJkP6eyg3BwXA7iNMzKm7qqruQ - hex!["482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e"] - .unchecked_into(), - // 5DhLtiaQd1L1LU9jaNeeu9HJkP6eyg3BwXA7iNMzKm7qqruQ - hex!["482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e"] - .unchecked_into(), - ), - ( - // 5DyVtKWPidondEu8iHZgi6Ffv9yrJJ1NDNLom3X9cTDi98qp - hex!["547ff0ab649283a7ae01dbc2eb73932eba2fb09075e9485ff369082a2ff38d65"].into(), - // 5FeD54vGVNpFX3PndHPXJ2MDakc462vBCD5mgtWRnWYCpZU9 - hex!["9e42241d7cd91d001773b0b616d523dd80e13c6c2cab860b1234ef1b9ffc1526"].into(), - // 5E1jLYfLdUQKrFrtqoKgFrRvxM3oQPMbf6DfcsrugZZ5Bn8d - hex!["5633b70b80a6c8bb16270f82cca6d56b27ed7b76c8fd5af2986a25a4788ce440"] - .unchecked_into(), - // 5DhKqkHRkndJu8vq7pi2Q5S3DfftWJHGxbEUNH43b46qNspH - hex!["482a3389a6cf42d8ed83888cfd920fec738ea30f97e44699ada7323f08c3380a"] - .unchecked_into(), - // 5DhKqkHRkndJu8vq7pi2Q5S3DfftWJHGxbEUNH43b46qNspH - hex!["482a3389a6cf42d8ed83888cfd920fec738ea30f97e44699ada7323f08c3380a"] - .unchecked_into(), - // 5DhKqkHRkndJu8vq7pi2Q5S3DfftWJHGxbEUNH43b46qNspH - hex!["482a3389a6cf42d8ed83888cfd920fec738ea30f97e44699ada7323f08c3380a"] - .unchecked_into(), - ), - ( - // 5HYZnKWe5FVZQ33ZRJK1rG3WaLMztxWrrNDb1JRwaHHVWyP9 - hex!["f26cdb14b5aec7b2789fd5ca80f979cef3761897ae1f37ffb3e154cbcc1c2663"].into(), - // 5EPQdAQ39WQNLCRjWsCk5jErsCitHiY5ZmjfWzzbXDoAoYbn - hex!["66bc1e5d275da50b72b15de072a2468a5ad414919ca9054d2695767cf650012f"].into(), - // 5DMa31Hd5u1dwoRKgC4uvqyrdK45RHv3CpwvpUC1EzuwDit4 - hex!["3919132b851ef0fd2dae42a7e734fe547af5a6b809006100f48944d7fae8e8ef"] - .unchecked_into(), - // 5C4vDQxA8LTck2xJEy4Yg1hM9qjDt4LvTQaMo4Y8ne43aU6x - hex!["00299981a2b92f878baaf5dbeba5c18d4e70f2a1fcd9c61b32ea18daf38f4378"] - .unchecked_into(), - // 5C4vDQxA8LTck2xJEy4Yg1hM9qjDt4LvTQaMo4Y8ne43aU6x - hex!["00299981a2b92f878baaf5dbeba5c18d4e70f2a1fcd9c61b32ea18daf38f4378"] - .unchecked_into(), - // 5C4vDQxA8LTck2xJEy4Yg1hM9qjDt4LvTQaMo4Y8ne43aU6x - hex!["00299981a2b92f878baaf5dbeba5c18d4e70f2a1fcd9c61b32ea18daf38f4378"] - .unchecked_into(), - ), - ]; - - // generated with secret: subkey inspect "$secret"/fir - let root_key: AccountId = hex![ - // 5Ff3iXP75ruzroPWRP2FYBHWnmGGBSb63857BgnzCoXNxfPo - "9ee5e5bdc0ec239eb164f865ecc345ce4c88e76ee002e0f7e318097347471809" - ] - .into(); - - let endowed_accounts: Vec = vec![root_key.clone()]; - - testnet_genesis(initial_authorities, vec![], root_key, Some(endowed_accounts)) -} - -/// Staging testnet config. -pub fn staging_testnet_config() -> ChainSpec { - let boot_nodes = vec![]; - ChainSpec::from_genesis( - "Staging Testnet", - "staging_testnet", - ChainType::Live, - staging_testnet_config_genesis, - boot_nodes, - Some( - TelemetryEndpoints::new(vec![(STAGING_TELEMETRY_URL.to_string(), 0)]) - .expect("Staging telemetry url is valid; qed"), - ), - None, - None, - None, - Default::default(), - ) -} - -/// Helper function to generate a crypto pair from seed -pub fn get_from_seed(seed: &str) -> ::Public { - TPublic::Pair::from_string(&format!("//{}", seed), None) - .expect("static values are valid; qed") - .public() -} - -/// Helper function to generate an account ID from seed -pub fn get_account_id_from_seed(seed: &str) -> AccountId -where - AccountPublic: From<::Public>, -{ - AccountPublic::from(get_from_seed::(seed)).into_account() -} - -/// Helper function to generate stash, controller and session key from seed -pub fn authority_keys_from_seed( - seed: &str, -) -> (AccountId, AccountId, GrandpaId, BabeId, ImOnlineId, AuthorityDiscoveryId) { - ( - get_account_id_from_seed::(&format!("{}//stash", seed)), - get_account_id_from_seed::(seed), - get_from_seed::(seed), - get_from_seed::(seed), - get_from_seed::(seed), - get_from_seed::(seed), - ) -} - -/// Helper function to create GenesisConfig for testing -pub fn testnet_genesis( - initial_authorities: Vec<( - AccountId, - AccountId, - GrandpaId, - BabeId, - ImOnlineId, - AuthorityDiscoveryId, - )>, - initial_nominators: Vec, - root_key: AccountId, - endowed_accounts: Option>, -) -> GenesisConfig { - let mut endowed_accounts: Vec = endowed_accounts.unwrap_or_else(|| { - vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - get_account_id_from_seed::("Charlie"), - get_account_id_from_seed::("Dave"), - get_account_id_from_seed::("Eve"), - get_account_id_from_seed::("Ferdie"), - get_account_id_from_seed::("Alice//stash"), - get_account_id_from_seed::("Bob//stash"), - get_account_id_from_seed::("Charlie//stash"), - get_account_id_from_seed::("Dave//stash"), - get_account_id_from_seed::("Eve//stash"), - get_account_id_from_seed::("Ferdie//stash"), - ] - }); - // endow all authorities and nominators. - initial_authorities - .iter() - .map(|x| &x.0) - .chain(initial_nominators.iter()) - .for_each(|x| { - if !endowed_accounts.contains(x) { - endowed_accounts.push(x.clone()) - } - }); - - // stakers: all validators and nominators. - let mut rng = rand::thread_rng(); - let stakers = initial_authorities - .iter() - .map(|x| (x.0.clone(), x.1.clone(), STASH, StakerStatus::Validator)) - .chain(initial_nominators.iter().map(|x| { - use rand::{seq::SliceRandom, Rng}; - let limit = (MaxNominations::get() as usize).min(initial_authorities.len()); - let count = rng.gen::() % limit; - let nominations = initial_authorities - .as_slice() - .choose_multiple(&mut rng, count) - .into_iter() - .map(|choice| choice.0.clone()) - .collect::>(); - (x.clone(), x.clone(), STASH, StakerStatus::Nominator(nominations)) - })) - .collect::>(); - - let num_endowed_accounts = endowed_accounts.len(); - - const ENDOWMENT: Balance = 10_000_000 * DOLLARS; - const STASH: Balance = ENDOWMENT / 1000; - - GenesisConfig { - system: SystemConfig { code: wasm_binary_unwrap().to_vec() }, - balances: BalancesConfig { - balances: endowed_accounts.iter().cloned().map(|x| (x, ENDOWMENT)).collect(), - }, - indices: IndicesConfig { indices: vec![] }, - session: SessionConfig { - keys: initial_authorities - .iter() - .map(|x| { - ( - x.0.clone(), - x.0.clone(), - session_keys(x.2.clone(), x.3.clone(), x.4.clone(), x.5.clone()), - ) - }) - .collect::>(), - }, - staking: StakingConfig { - validator_count: initial_authorities.len() as u32, - minimum_validator_count: initial_authorities.len() as u32, - invulnerables: initial_authorities.iter().map(|x| x.0.clone()).collect(), - slash_reward_fraction: Perbill::from_percent(10), - stakers, - ..Default::default() - }, - democracy: DemocracyConfig::default(), - elections: ElectionsConfig { - members: endowed_accounts - .iter() - .take((num_endowed_accounts + 1) / 2) - .cloned() - .map(|member| (member, STASH)) - .collect(), - }, - council: CouncilConfig::default(), - technical_committee: TechnicalCommitteeConfig { - members: endowed_accounts - .iter() - .take((num_endowed_accounts + 1) / 2) - .cloned() - .collect(), - phantom: Default::default(), - }, - sudo: SudoConfig { key: Some(root_key) }, - babe: BabeConfig { - authorities: vec![], - epoch_config: Some(node_runtime::BABE_GENESIS_EPOCH_CONFIG), - }, - im_online: ImOnlineConfig { keys: vec![] }, - authority_discovery: AuthorityDiscoveryConfig { keys: vec![] }, - grandpa: GrandpaConfig { authorities: vec![] }, - technical_membership: Default::default(), - treasury: Default::default(), - society: SocietyConfig { - members: endowed_accounts - .iter() - .take((num_endowed_accounts + 1) / 2) - .cloned() - .collect(), - pot: 0, - max_members: 999, - }, - vesting: Default::default(), - assets: Default::default(), - gilt: Default::default(), - transaction_storage: Default::default(), - transaction_payment: Default::default(), - } -} - -fn development_config_genesis() -> GenesisConfig { - testnet_genesis( - vec![authority_keys_from_seed("Alice")], - vec![], - get_account_id_from_seed::("Alice"), - None, - ) -} - /// Development config (single validator Alice) -pub fn development_config() -> ChainSpec { - ChainSpec::from_genesis( - "Development", - "dev", - ChainType::Development, - development_config_genesis, - vec![], - None, - None, - None, - None, - Default::default(), - ) +pub fn development_config() -> Result { + ChainSpec::from_json_bytes(&include_bytes!("../res/flaming-fir.json")[..]) } -fn local_testnet_genesis() -> GenesisConfig { - testnet_genesis( - vec![authority_keys_from_seed("Alice"), authority_keys_from_seed("Bob")], - vec![], - get_account_id_from_seed::("Alice"), - None, - ) +/// Staging testnet config. +pub fn staging_testnet_config() -> Result { + ChainSpec::from_json_bytes(&include_bytes!("../res/flaming-fir.json")[..]) } /// Local testnet config (multivalidator Alice + Bob) -pub fn local_testnet_config() -> ChainSpec { - ChainSpec::from_genesis( - "Local Testnet", - "local_testnet", - ChainType::Local, - local_testnet_genesis, - vec![], - None, - None, - None, - None, - Default::default(), - ) +pub fn local_testnet_config() -> Result { + ChainSpec::from_json_bytes(&include_bytes!("../res/flaming-fir.json")[..]) } #[cfg(test)] diff --git a/bin/node/cli/src/command.rs b/bin/node/cli/src/command.rs index d9ba53785ba0c..dc3705b5e4d9d 100644 --- a/bin/node/cli/src/command.rs +++ b/bin/node/cli/src/command.rs @@ -17,9 +17,8 @@ // along with this program. If not, see . use crate::{chain_spec, service, service::new_partial, Cli, Subcommand}; -use node_executor::ExecutorDispatch; -use node_runtime::{Block, RuntimeApi}; -use sc_cli::{ChainSpec, Result, RuntimeVersion, SubstrateCli}; +use node_primitives::Block; +use sc_cli::{Result, SubstrateCli}; use sc_service::PartialComponents; impl SubstrateCli for Cli { @@ -54,19 +53,15 @@ impl SubstrateCli for Cli { "Please specify which chain you want to run, e.g. --dev or --chain=local" .into(), ), - "dev" => Box::new(chain_spec::development_config()), - "local" => Box::new(chain_spec::local_testnet_config()), + "dev" => Box::new(chain_spec::development_config()?), + "local" => Box::new(chain_spec::local_testnet_config()?), "fir" | "flaming-fir" => Box::new(chain_spec::flaming_fir_config()?), - "staging" => Box::new(chain_spec::staging_testnet_config()), + "staging" => Box::new(chain_spec::staging_testnet_config()?), path => Box::new(chain_spec::ChainSpec::from_json_file(std::path::PathBuf::from(path))?), }; Ok(spec) } - - fn native_runtime_version(_: &Box) -> &'static RuntimeVersion { - &node_runtime::VERSION - } } /// Parse command line arguments into service configuration. @@ -83,13 +78,13 @@ pub fn run() -> Result<()> { Some(Subcommand::Inspect(cmd)) => { let runner = cli.create_runner(cmd)?; - runner.sync_run(|config| cmd.run::(config)) + runner.sync_run(|config| cmd.run::(config)) }, Some(Subcommand::Benchmark(cmd)) => if cfg!(feature = "runtime-benchmarks") { let runner = cli.create_runner(cmd)?; - runner.sync_run(|config| cmd.run::(config)) + runner.sync_run(|config| cmd.run::(config)) } else { Err("Benchmarking wasn't enabled when building the node. \ You can enable it with `--features runtime-benchmarks`." @@ -155,7 +150,7 @@ pub fn run() -> Result<()> { sc_service::TaskManager::new(config.tokio_handle.clone(), registry) .map_err(|e| sc_cli::Error::Service(sc_service::Error::Prometheus(e)))?; - Ok((cmd.run::(config), task_manager)) + Ok((cmd.run::(config), task_manager)) }) }, #[cfg(not(feature = "try-runtime"))] diff --git a/bin/node/cli/src/service.rs b/bin/node/cli/src/service.rs index 81c68bf5d3aa7..c0dde8d40f4d4 100644 --- a/bin/node/cli/src/service.rs +++ b/bin/node/cli/src/service.rs @@ -20,26 +20,19 @@ //! Service implementation. Specialized wrapper over substrate service. -use codec::Encode; -use frame_system_rpc_runtime_api::AccountNonceApi; use futures::prelude::*; -use node_executor::ExecutorDispatch; use node_primitives::Block; -use node_runtime::RuntimeApi; use sc_client_api::{BlockBackend, ExecutorProvider}; use sc_consensus_babe::{self, SlotProportion}; -use sc_executor::NativeElseWasmExecutor; +use sc_executor::DefaultExecutor; use sc_network::{Event, NetworkService}; use sc_service::{config::Configuration, error::Error as ServiceError, RpcHandlers, TaskManager}; use sc_telemetry::{Telemetry, TelemetryWorker}; -use sp_api::ProvideRuntimeApi; -use sp_core::crypto::Pair; -use sp_runtime::{generic, traits::Block as BlockT, SaturatedConversion}; +use sp_runtime::{traits::Block as BlockT}; use std::sync::Arc; /// The full client type definition. -pub type FullClient = - sc_service::TFullClient>; +pub type FullClient = sc_service::TFullClient; type FullBackend = sc_service::TFullBackend; type FullSelectChain = sc_consensus::LongestChain; type FullGrandpaBlockImport = @@ -48,78 +41,6 @@ type FullGrandpaBlockImport = /// The transaction pool type defintion. pub type TransactionPool = sc_transaction_pool::FullPool; -/// Fetch the nonce of the given `account` from the chain state. -/// -/// Note: Should only be used for tests. -pub fn fetch_nonce(client: &FullClient, account: sp_core::sr25519::Pair) -> u32 { - let best_hash = client.chain_info().best_hash; - client - .runtime_api() - .account_nonce(&generic::BlockId::Hash(best_hash), account.public().into()) - .expect("Fetching account nonce works; qed") -} - -/// Create a transaction using the given `call`. -/// -/// The transaction will be signed by `sender`. If `nonce` is `None` it will be fetched from the -/// state of the best block. -/// -/// Note: Should only be used for tests. -pub fn create_extrinsic( - client: &FullClient, - sender: sp_core::sr25519::Pair, - function: impl Into, - nonce: Option, -) -> node_runtime::UncheckedExtrinsic { - let function = function.into(); - let genesis_hash = client.block_hash(0).ok().flatten().expect("Genesis block exists; qed"); - let best_hash = client.chain_info().best_hash; - let best_block = client.chain_info().best_number; - let nonce = nonce.unwrap_or_else(|| fetch_nonce(client, sender.clone())); - - let period = node_runtime::BlockHashCount::get() - .checked_next_power_of_two() - .map(|c| c / 2) - .unwrap_or(2) as u64; - let tip = 0; - let extra: node_runtime::SignedExtra = ( - frame_system::CheckNonZeroSender::::new(), - frame_system::CheckSpecVersion::::new(), - frame_system::CheckTxVersion::::new(), - frame_system::CheckGenesis::::new(), - frame_system::CheckEra::::from(generic::Era::mortal( - period, - best_block.saturated_into(), - )), - frame_system::CheckNonce::::from(nonce), - frame_system::CheckWeight::::new(), - pallet_asset_tx_payment::ChargeAssetTxPayment::::from(tip, None), - ); - - let raw_payload = node_runtime::SignedPayload::from_raw( - function.clone(), - extra.clone(), - ( - (), - node_runtime::VERSION.spec_version, - node_runtime::VERSION.transaction_version, - genesis_hash, - best_hash, - (), - (), - (), - ), - ); - let signature = raw_payload.using_encoded(|e| sender.sign(e)); - - node_runtime::UncheckedExtrinsic::new_signed( - function.clone(), - sp_runtime::AccountId32::from(sender.public()).into(), - node_runtime::Signature::Sr25519(signature.clone()), - extra.clone(), - ) -} - /// Creates a new partial node. pub fn new_partial( config: &Configuration, @@ -157,15 +78,16 @@ pub fn new_partial( }) .transpose()?; - let executor = NativeElseWasmExecutor::::new( + let executor = DefaultExecutor::new( config.wasm_method, config.default_heap_pages, config.max_runtime_instances, + None, config.runtime_cache_size, ); let (client, backend, keystore_container, task_manager) = - sc_service::new_full_parts::( + sc_service::new_full_parts::( config, telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()), executor, @@ -224,7 +146,7 @@ pub fn new_partial( }, &task_manager.spawn_essential_handle(), config.prometheus_registry(), - sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()), + sp_consensus::CanAuthorWithVersion::new(client.executor().clone()), telemetry.as_ref().map(|x| x.handle()), )?; @@ -396,7 +318,7 @@ pub fn new_full_base( ); let can_author_with = - sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()); + sp_consensus::CanAuthorWithVersion::new(client.executor().clone()); let client_clone = client.clone(); let slot_duration = babe_link.config().slot_duration(); diff --git a/bin/node/inspect/src/command.rs b/bin/node/inspect/src/command.rs index ce164e0768fbc..a207876c9f022 100644 --- a/bin/node/inspect/src/command.rs +++ b/bin/node/inspect/src/command.rs @@ -23,28 +23,27 @@ use crate::{ Inspector, }; use sc_cli::{CliConfiguration, ImportParams, Result, SharedParams}; -use sc_executor::NativeElseWasmExecutor; -use sc_service::{new_full_client, Configuration, NativeExecutionDispatch}; +use sc_executor::{DefaultExecutor}; +use sc_service::{new_full_client, Configuration}; use sp_runtime::traits::Block; use std::str::FromStr; impl InspectCmd { /// Run the inspect command, passing the inspector. - pub fn run(&self, config: Configuration) -> Result<()> + pub fn run(&self, config: Configuration) -> Result<()> where B: Block, B::Hash: FromStr, - RA: Send + Sync + 'static, - EX: NativeExecutionDispatch + 'static, { - let executor = NativeElseWasmExecutor::::new( + let executor = DefaultExecutor::new( config.wasm_method, config.default_heap_pages, config.max_runtime_instances, + None, config.runtime_cache_size, ); - let client = new_full_client::(&config, None, executor)?; + let client = new_full_client::(&config, None, executor)?; let inspect = Inspector::::new(client); match &self.command { diff --git a/bin/node/rpc/src/lib.rs b/bin/node/rpc/src/lib.rs index 30f7a0fdf023c..13cb82667a357 100644 --- a/bin/node/rpc/src/lib.rs +++ b/bin/node/rpc/src/lib.rs @@ -32,7 +32,7 @@ use std::sync::Arc; -use node_primitives::{AccountId, Balance, Block, BlockNumber, Hash, Index}; +use node_primitives::{Block, BlockNumber, Hash, Index, AccountId, Balance}; use sc_client_api::AuxStore; use sc_consensus_babe::{Config, Epoch}; use sc_consensus_babe_rpc::BabeRpcHandler; @@ -44,11 +44,9 @@ use sc_finality_grandpa_rpc::GrandpaRpcHandler; use sc_rpc::SubscriptionTaskExecutor; pub use sc_rpc_api::DenyUnsafe; use sc_transaction_pool_api::TransactionPool; -use sp_api::ProvideRuntimeApi; -use sp_block_builder::BlockBuilder; +use sp_api::{NumberFor, ProvideRuntimeApi}; use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; use sp_consensus::SelectChain; -use sp_consensus_babe::BabeApi; use sp_keystore::SyncCryptoStorePtr; /// Extra dependencies for BABE. @@ -108,12 +106,6 @@ where + Sync + Send + 'static, - C::Api: substrate_frame_rpc_system::AccountNonceApi, - C::Api: pallet_contracts_rpc::ContractsRuntimeApi, - C::Api: pallet_mmr_rpc::MmrRuntimeApi::Hash>, - C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, - C::Api: BabeApi, - C::Api: BlockBuilder, P: TransactionPool + 'static, SC: SelectChain + 'static, B: sc_client_api::Backend + Send + Sync + 'static, @@ -121,7 +113,7 @@ where { use pallet_contracts_rpc::{Contracts, ContractsApi}; use pallet_mmr_rpc::{Mmr, MmrApi}; - use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi}; + use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi, TransactionPaymentRuntimeDispatchInfo}; use substrate_frame_rpc_system::{FullSystem, SystemApi}; let mut io = jsonrpc_core::IoHandler::default(); @@ -136,13 +128,13 @@ where finality_provider, } = grandpa; - io.extend_with(SystemApi::to_delegate(FullSystem::new(client.clone(), pool, deny_unsafe))); + io.extend_with(SystemApi::::to_delegate(FullSystem::new(client.clone(), pool, deny_unsafe))); // Making synchronous calls in light client freezes the browser currently, // more context: https://github.com/paritytech/substrate/pull/3480 // These RPCs should use an asynchronous caller instead. - io.extend_with(ContractsApi::to_delegate(Contracts::new(client.clone()))); - io.extend_with(MmrApi::to_delegate(Mmr::new(client.clone()))); - io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new(client.clone()))); + io.extend_with(ContractsApi::, AccountId, Balance, Hash>::to_delegate(Contracts::new(client.clone()))); + io.extend_with(MmrApi::::to_delegate(Mmr::new(client.clone()) as Mmr<_, (_, Hash)>)); + io.extend_with(TransactionPaymentApi::<_, TransactionPaymentRuntimeDispatchInfo>::to_delegate(TransactionPayment::new(client.clone()))); io.extend_with(sc_consensus_babe_rpc::BabeApi::to_delegate(BabeRpcHandler::new( client.clone(), shared_epoch_changes.clone(), diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index 0a13b795919c0..1b72c23030b3a 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -1673,7 +1673,7 @@ impl_runtime_apis! { } impl pallet_contracts_rpc_runtime_api::ContractsApi< - Block, AccountId, Balance, BlockNumber, Hash, + Block, AccountId, Balance, Hash, > for Runtime { diff --git a/client/api/src/call_executor.rs b/client/api/src/call_executor.rs index 738f932a47bf0..11a1df2990088 100644 --- a/client/api/src/call_executor.rs +++ b/client/api/src/call_executor.rs @@ -71,7 +71,7 @@ pub trait CallExecutor: RuntimeVersionOf { Result, Self::Error>, Result, Self::Error>, ) -> Result, Self::Error>, - R: Encode + Decode + PartialEq, + R: Encode + Decode, NC: FnOnce() -> result::Result + UnwindSafe, >( &self, diff --git a/client/authority-discovery/src/lib.rs b/client/authority-discovery/src/lib.rs index 8522da9984a6f..50a3b3735a13d 100644 --- a/client/authority-discovery/src/lib.rs +++ b/client/authority-discovery/src/lib.rs @@ -42,7 +42,7 @@ use futures::{ use sc_client_api::blockchain::HeaderBackend; use sc_network::{DhtEvent, Multiaddr, PeerId}; use sp_api::ProvideRuntimeApi; -use sp_authority_discovery::{AuthorityDiscoveryApi, AuthorityId}; +use sp_authority_discovery::{AuthorityId}; use sp_runtime::traits::Block as BlockT; mod error; @@ -122,7 +122,6 @@ where Block: BlockT + Unpin + 'static, Network: NetworkProvider, Client: ProvideRuntimeApi + Send + Sync + 'static + HeaderBackend, - >::Api: AuthorityDiscoveryApi, DhtEventStream: Stream + Unpin, { new_worker_and_service_with_config( @@ -150,7 +149,6 @@ where Block: BlockT + Unpin + 'static, Network: NetworkProvider, Client: ProvideRuntimeApi + Send + Sync + 'static + HeaderBackend, - >::Api: AuthorityDiscoveryApi, DhtEventStream: Stream + Unpin, { let (to_worker, from_service) = mpsc::channel(0); diff --git a/client/authority-discovery/src/worker.rs b/client/authority-discovery/src/worker.rs index 019abaac3cfcb..c8cf91100bed5 100644 --- a/client/authority-discovery/src/worker.rs +++ b/client/authority-discovery/src/worker.rs @@ -153,7 +153,6 @@ where Block: BlockT + Unpin + 'static, Network: NetworkProvider, Client: ProvideRuntimeApi + Send + Sync + 'static + HeaderBackend, - >::Api: AuthorityDiscoveryApi, DhtEventStream: Stream + Unpin, { /// Construct a [`Worker`]. diff --git a/client/basic-authorship/src/basic_authorship.rs b/client/basic-authorship/src/basic_authorship.rs index 23725e5138697..3635556637f46 100644 --- a/client/basic-authorship/src/basic_authorship.rs +++ b/client/basic-authorship/src/basic_authorship.rs @@ -28,11 +28,11 @@ use futures::{ select, }; use log::{debug, error, info, trace, warn}; -use sc_block_builder::{BlockBuilderApi, BlockBuilderProvider}; +use sc_block_builder::{BlockBuilderProvider}; use sc_client_api::backend; use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_INFO}; use sc_transaction_pool_api::{InPoolTransaction, TransactionPool}; -use sp_api::{ApiExt, ProvideRuntimeApi}; +use sp_api::{CallApiAt}; use sp_blockchain::{ApplyExtrinsicFailed::Validity, Error::ApplyExtrinsicFailed, HeaderBackend}; use sp_consensus::{ evaluation, DisableProofRecording, EnableProofRecording, ProofRecording, Proposal, @@ -184,12 +184,10 @@ where Block: BlockT, C: BlockBuilderProvider + HeaderBackend - + ProvideRuntimeApi + + CallApiAt + Send + Sync + 'static, - C::Api: - ApiExt> + BlockBuilderApi, { fn init_with_now( &mut self, @@ -229,12 +227,10 @@ where Block: BlockT, C: BlockBuilderProvider + HeaderBackend - + ProvideRuntimeApi + + CallApiAt + Send + Sync + 'static, - C::Api: - ApiExt> + BlockBuilderApi, PR: ProofRecording, { type CreateProposer = future::Ready>; @@ -270,12 +266,10 @@ where Block: BlockT, C: BlockBuilderProvider + HeaderBackend - + ProvideRuntimeApi + + CallApiAt + Send + Sync + 'static, - C::Api: - ApiExt> + BlockBuilderApi, PR: ProofRecording, { type Transaction = backend::TransactionFor; @@ -330,12 +324,10 @@ where Block: BlockT, C: BlockBuilderProvider + HeaderBackend - + ProvideRuntimeApi + + CallApiAt + Send + Sync + 'static, - C::Api: - ApiExt> + BlockBuilderApi, PR: ProofRecording, { async fn propose_with( diff --git a/client/beefy/src/lib.rs b/client/beefy/src/lib.rs index 9b2bf383df8ef..619cc8153172a 100644 --- a/client/beefy/src/lib.rs +++ b/client/beefy/src/lib.rs @@ -29,8 +29,6 @@ use sp_blockchain::HeaderBackend; use sp_keystore::SyncCryptoStorePtr; use sp_runtime::traits::Block; -use beefy_primitives::BeefyApi; - use crate::notification::{BeefyBestBlockSender, BeefySignedCommitmentSender}; mod error; @@ -111,7 +109,6 @@ where B: Block, BE: Backend, C: Client, - C::Api: BeefyApi, N: GossipNetwork + Clone + Send + 'static, { /// BEEFY client @@ -142,7 +139,6 @@ where B: Block, BE: Backend, C: Client, - C::Api: BeefyApi, N: GossipNetwork + Clone + Send + 'static, { let BeefyParams { diff --git a/client/beefy/src/worker.rs b/client/beefy/src/worker.rs index 3f23638758eca..c3c5c1eb0ccc2 100644 --- a/client/beefy/src/worker.rs +++ b/client/beefy/src/worker.rs @@ -100,7 +100,6 @@ where B: Block + Codec, BE: Backend, C: Client, - C::Api: BeefyApi, { /// Return a new BEEFY worker instance. /// @@ -146,7 +145,6 @@ where B: Block, BE: Backend, C: Client, - C::Api: BeefyApi, { /// Return `true`, if we should vote on block `number` fn should_vote_on(&self, number: NumberFor) -> bool { diff --git a/client/block-builder/src/lib.rs b/client/block-builder/src/lib.rs index a4c6f5aad2aeb..0bce0cb1c1a29 100644 --- a/client/block-builder/src/lib.rs +++ b/client/block-builder/src/lib.rs @@ -29,7 +29,7 @@ use codec::Encode; use sp_api::{ - ApiExt, ApiRef, Core, ProvideRuntimeApi, StorageChanges, StorageProof, TransactionOutcome, + ApiExt, RuntimeApi, Core, StorageChanges, StorageProof, TransactionOutcome, CallApiAt, }; use sp_blockchain::{ApplyExtrinsicFailed, Error}; use sp_core::ExecutionContext; @@ -105,12 +105,12 @@ impl>> } /// Block builder provider -pub trait BlockBuilderProvider +pub trait BlockBuilderProvider where Block: BlockT, B: backend::Backend, + A: CallApiAt, Self: Sized, - RA: ProvideRuntimeApi, { /// Create a new block, built on top of `parent`. /// @@ -122,19 +122,19 @@ where parent: &BlockId, inherent_digests: Digest, record_proof: R, - ) -> sp_blockchain::Result>; + ) -> sp_blockchain::Result>; /// Create a new block, built on the head of the chain. fn new_block( &self, inherent_digests: Digest, - ) -> sp_blockchain::Result>; + ) -> sp_blockchain::Result>; } /// Utility for building new (valid) blocks from a stream of extrinsics. -pub struct BlockBuilder<'a, Block: BlockT, A: ProvideRuntimeApi, B> { +pub struct BlockBuilder<'a, Block: BlockT, A: 'a + CallApiAt, B> { extrinsics: Vec, - api: ApiRef<'a, A::Api>, + api: RuntimeApi<'a, Block, A>, block_id: BlockId, parent_hash: Block::Hash, backend: &'a B, @@ -145,9 +145,7 @@ pub struct BlockBuilder<'a, Block: BlockT, A: ProvideRuntimeApi, B> { impl<'a, Block, A, B> BlockBuilder<'a, Block, A, B> where Block: BlockT, - A: ProvideRuntimeApi + 'a, - A::Api: - BlockBuilderApi + ApiExt>, + A: CallApiAt + 'a, B: backend::Backend, { /// Create a new instance of builder based on the given `parent_hash` and `parent_number`. @@ -173,7 +171,7 @@ where let estimated_header_size = header.encoded_size(); - let mut api = api.runtime_api(); + let mut api = RuntimeApi::new(api); if record_proof.yes() { api.record_proof(); diff --git a/client/cli/src/lib.rs b/client/cli/src/lib.rs index c242050dbf32a..50a0685eeafe7 100644 --- a/client/cli/src/lib.rs +++ b/client/cli/src/lib.rs @@ -241,6 +241,4 @@ pub trait SubstrateCli: Sized { command.init(&Self::support_url(), &Self::impl_version(), logger_hook, &config)?; Runner::new(config, tokio_runtime) } - /// Native runtime version. - fn native_runtime_version(chain_spec: &Box) -> &'static RuntimeVersion; } diff --git a/client/cli/src/runner.rs b/client/cli/src/runner.rs index f6edd8444735a..a38dcfaeee62a 100644 --- a/client/cli/src/runner.rs +++ b/client/cli/src/runner.rs @@ -202,5 +202,4 @@ pub fn print_node_infos(config: &Configuration) { .path() .map_or_else(|| "".to_owned(), |p| p.display().to_string()) ); - info!("⛓ Native runtime: {}", C::native_runtime_version(&config.chain_spec)); } diff --git a/client/consensus/aura/src/import_queue.rs b/client/consensus/aura/src/import_queue.rs index 56eb45c621a1b..dd05b9f0d32ba 100644 --- a/client/consensus/aura/src/import_queue.rs +++ b/client/consensus/aura/src/import_queue.rs @@ -37,7 +37,7 @@ use sp_blockchain::{ }; use sp_consensus::{CanAuthorWith, Error as ConsensusError}; use sp_consensus_aura::{ - digests::CompatibleDigestItem, inherents::AuraInherentData, AuraApi, ConsensusLog, + digests::CompatibleDigestItem, inherents::AuraInherentData, ConsensusLog, AURA_ENGINE_ID, }; use sp_consensus_slots::Slot; @@ -153,7 +153,6 @@ where ) -> Result<(), Error> where C: ProvideRuntimeApi, - C::Api: BlockBuilderApi, CAW: CanAuthorWith, CIDP: CreateInherentDataProviders, { @@ -190,7 +189,6 @@ where impl Verifier for AuraVerifier where C: ProvideRuntimeApi + Send + Sync + sc_client_api::backend::AuxStore + BlockOf, - C::Api: BlockBuilderApi + AuraApi> + ApiExt, P: Pair + Send + Sync + 'static, P::Public: Send + Sync + Hash + Eq + Clone + Decode + Encode + Debug + 'static, P::Signature: Encode + Decode, @@ -375,7 +373,6 @@ pub fn import_queue<'a, P, Block, I, C, S, CAW, CIDP>( ) -> Result, sp_consensus::Error> where Block: BlockT, - C::Api: BlockBuilderApi + AuraApi> + ApiExt, C: 'static + ProvideRuntimeApi + BlockOf diff --git a/client/consensus/aura/src/lib.rs b/client/consensus/aura/src/lib.rs index 61c5610883149..c8b0092e88cd4 100644 --- a/client/consensus/aura/src/lib.rs +++ b/client/consensus/aura/src/lib.rs @@ -86,15 +86,13 @@ type AuthorityId

=

::Public; pub type SlotDuration = sc_consensus_slots::SlotDuration; /// Get the slot duration for Aura. -pub fn slot_duration(client: &C) -> CResult +pub fn slot_duration(client: &C) -> CResult where - A: Codec, B: BlockT, C: AuxStore + ProvideRuntimeApi + UsageProvider, - C::Api: AuraApi, { let best_block_id = BlockId::Hash(client.usage_info().chain.best_hash); - let slot_duration = client.runtime_api().slot_duration(&best_block_id)?; + let slot_duration = AuraApi::::slot_duration(&client.runtime_api(), &best_block_id)?; Ok(SlotDuration::new(slot_duration)) } @@ -183,7 +181,6 @@ where P::Signature: TryFrom> + Hash + Member + Encode + Decode, B: BlockT, C: ProvideRuntimeApi + BlockOf + AuxStore + HeaderBackend + Send + Sync, - C::Api: AuraApi>, SC: SelectChain, I: BlockImport> + Send + Sync + 'static, PF: Environment + Send + Sync + 'static, @@ -272,7 +269,6 @@ pub fn build_aura_worker( where B: BlockT, C: ProvideRuntimeApi + BlockOf + AuxStore + HeaderBackend + Send + Sync, - C::Api: AuraApi>, PF: Environment + Send + Sync + 'static, PF::Proposer: Proposer>, P: Pair + Send + Sync, @@ -321,7 +317,6 @@ impl sc_consensus_slots::SimpleSlotWorker where B: BlockT, C: ProvideRuntimeApi + BlockOf + HeaderBackend + Sync, - C::Api: AuraApi>, E: Environment + Send + Sync, E::Proposer: Proposer>, I: BlockImport> + Send + Sync + 'static, @@ -551,7 +546,6 @@ where A: Codec + Debug, B: BlockT, C: ProvideRuntimeApi + BlockOf, - C::Api: AuraApi, { client .runtime_api() diff --git a/client/consensus/babe/rpc/src/lib.rs b/client/consensus/babe/rpc/src/lib.rs index 88a176e2de10d..2fdc8633ca486 100644 --- a/client/consensus/babe/rpc/src/lib.rs +++ b/client/consensus/babe/rpc/src/lib.rs @@ -83,7 +83,6 @@ where + HeaderBackend + HeaderMetadata + 'static, - C::Api: BabeRuntimeApi, SC: SelectChain + Clone + 'static, { fn epoch_authorship(&self) -> FutureResult> { diff --git a/client/consensus/babe/src/lib.rs b/client/consensus/babe/src/lib.rs index 9ad50eb9c0e5c..357477413d509 100644 --- a/client/consensus/babe/src/lib.rs +++ b/client/consensus/babe/src/lib.rs @@ -342,7 +342,6 @@ impl Config { pub fn get(client: &C) -> ClientResult where C: AuxStore + ProvideRuntimeApi + UsageProvider, - C::Api: BabeApi, { trace!(target: "babe", "Getting slot duration"); @@ -470,7 +469,6 @@ where + Send + Sync + 'static, - C::Api: BabeApi, SC: SelectChain + 'static, E: Environment + Send + Sync + 'static, E::Proposer: Proposer>, @@ -674,7 +672,6 @@ impl sc_consensus_slots::SimpleSlotWorker where B: BlockT, C: ProvideRuntimeApi + HeaderBackend + HeaderMetadata, - C::Api: BabeApi, E: Environment + Sync, E::Proposer: Proposer>, I: BlockImport> + Send + Sync + 'static, @@ -753,7 +750,7 @@ where slot: Slot, epoch_descriptor: &ViableEpochDescriptor, Epoch>, ) { - self.slot_notification_sinks.lock().retain_mut(|sink| { + RetainMut::retain_mut(&mut *self.slot_notification_sinks.lock(), |sink| { match sink.try_send((slot, epoch_descriptor.clone())) { Ok(()) => true, Err(e) => @@ -970,7 +967,6 @@ impl BabeVerifier + HeaderMetadata + ProvideRuntimeApi, - Client::Api: BlockBuilderApi + BabeApi, SelectChain: sp_consensus::SelectChain, CAW: CanAuthorWith, CIDP: CreateInherentDataProviders, @@ -1107,7 +1103,6 @@ where + Send + Sync + AuxStore, - Client::Api: BlockBuilderApi + BabeApi, SelectChain: sp_consensus::SelectChain, CAW: CanAuthorWith + Send + Sync, CIDP: CreateInherentDataProviders + Send + Sync, @@ -1307,7 +1302,6 @@ where + ProvideRuntimeApi + Send + Sync, - Client::Api: BabeApi + ApiExt, { /// Import whole state after warp sync. // This function makes multiple transactions to the DB. If one of them fails we may @@ -1373,7 +1367,6 @@ where + ProvideRuntimeApi + Send + Sync, - Client::Api: BabeApi + ApiExt, { type Error = ConsensusError; type Transaction = sp_api::TransactionFor; @@ -1733,7 +1726,6 @@ where + Send + Sync + 'static, - Client::Api: BlockBuilderApi + BabeApi + ApiExt, SelectChain: sp_consensus::SelectChain + 'static, CAW: CanAuthorWith + Send + Sync + 'static, CIDP: CreateInherentDataProviders + Send + Sync + 'static, diff --git a/client/consensus/common/src/block_import.rs b/client/consensus/common/src/block_import.rs index 24fec9b974a4c..e7140256cd31c 100644 --- a/client/consensus/common/src/block_import.rs +++ b/client/consensus/common/src/block_import.rs @@ -323,7 +323,7 @@ pub trait BlockImport { /// The error type. type Error: std::error::Error + Send + 'static; /// The transaction type used by the backend. - type Transaction: Send + 'static; + type Transaction; /// Check block preconditions. async fn check_block( diff --git a/client/consensus/manual-seal/src/consensus/aura.rs b/client/consensus/manual-seal/src/consensus/aura.rs index 4497a94bdd429..81377ad903732 100644 --- a/client/consensus/manual-seal/src/consensus/aura.rs +++ b/client/consensus/manual-seal/src/consensus/aura.rs @@ -27,7 +27,7 @@ use sp_api::{ProvideRuntimeApi, TransactionFor}; use sp_blockchain::{HeaderBackend, HeaderMetadata}; use sp_consensus_aura::{ digests::CompatibleDigestItem, - sr25519::{AuthorityId, AuthoritySignature}, + sr25519::{AuthoritySignature}, AuraApi, }; use sp_inherents::InherentData; @@ -47,7 +47,6 @@ impl AuraConsensusDataProvider where B: BlockT, C: AuxStore + ProvideRuntimeApi + UsageProvider, - C::Api: AuraApi, { /// Creates a new instance of the [`AuraConsensusDataProvider`], requires that `client` /// implements [`sp_consensus_aura::AuraApi`] @@ -67,7 +66,6 @@ where + HeaderMetadata + UsageProvider + ProvideRuntimeApi, - C::Api: AuraApi, { type Transaction = TransactionFor; diff --git a/client/consensus/manual-seal/src/consensus/babe.rs b/client/consensus/manual-seal/src/consensus/babe.rs index dd3f9a253478a..e12fa4cd0c1c9 100644 --- a/client/consensus/manual-seal/src/consensus/babe.rs +++ b/client/consensus/manual-seal/src/consensus/babe.rs @@ -40,7 +40,7 @@ use sp_consensus::CacheKeyId; use sp_consensus_babe::{ digests::{NextEpochDescriptor, PreDigest, SecondaryPlainPreDigest}, inherents::BabeInherentData, - AuthorityId, BabeApi, BabeAuthorityWeight, ConsensusLog, BABE_ENGINE_ID, + AuthorityId, BabeAuthorityWeight, ConsensusLog, BABE_ENGINE_ID, }; use sp_consensus_slots::Slot; use sp_inherents::InherentData; @@ -139,7 +139,6 @@ where + ProvideRuntimeApi + HeaderMetadata + UsageProvider, - C::Api: BabeApi, { pub fn new( client: Arc, @@ -187,7 +186,6 @@ where + HeaderMetadata + UsageProvider + ProvideRuntimeApi, - C::Api: BabeApi, { type Transaction = TransactionFor; diff --git a/client/consensus/manual-seal/src/consensus/timestamp.rs b/client/consensus/manual-seal/src/consensus/timestamp.rs index 908d218da05ac..086abf0b91f32 100644 --- a/client/consensus/manual-seal/src/consensus/timestamp.rs +++ b/client/consensus/manual-seal/src/consensus/timestamp.rs @@ -26,10 +26,8 @@ use sc_consensus_babe::Config; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; use sp_consensus_aura::{ - sr25519::{AuthorityId, AuthoritySignature}, - AuraApi, + sr25519::{AuthoritySignature}, }; -use sp_consensus_babe::BabeApi; use sp_inherents::{InherentData, InherentDataProvider, InherentIdentifier}; use sp_runtime::{ generic::BlockId, @@ -62,7 +60,6 @@ impl SlotTimestampProvider { where B: BlockT, C: AuxStore + HeaderBackend + ProvideRuntimeApi + UsageProvider, - C::Api: BabeApi, { let slot_duration = Config::get(&*client)?.slot_duration; @@ -81,7 +78,6 @@ impl SlotTimestampProvider { where B: BlockT, C: AuxStore + HeaderBackend + ProvideRuntimeApi + UsageProvider, - C::Api: AuraApi, { let slot_duration = (*slot_duration(&*client)?).get(); diff --git a/client/consensus/pow/src/lib.rs b/client/consensus/pow/src/lib.rs index 6d0bc3fc5a192..776a02efb9e79 100644 --- a/client/consensus/pow/src/lib.rs +++ b/client/consensus/pow/src/lib.rs @@ -246,7 +246,6 @@ where I: BlockImport> + Send + Sync, I::Error: Into, C: ProvideRuntimeApi + Send + Sync + HeaderBackend + AuxStore + BlockOf, - C::Api: BlockBuilderApi, Algorithm: PowAlgorithm, CAW: CanAuthorWith, CIDP: CreateInherentDataProviders, @@ -325,7 +324,6 @@ where I::Error: Into, S: SelectChain, C: ProvideRuntimeApi + Send + Sync + HeaderBackend + AuxStore + BlockOf, - C::Api: BlockBuilderApi, Algorithm: PowAlgorithm + Send + Sync, Algorithm::Difficulty: 'static + Send, CAW: CanAuthorWith + Send + Sync, diff --git a/client/executor/src/lib.rs b/client/executor/src/lib.rs index 5cd04b9e4ee6a..84b9923aff86e 100644 --- a/client/executor/src/lib.rs +++ b/client/executor/src/lib.rs @@ -51,6 +51,10 @@ pub use wasmi; pub use sc_executor_common::{error, sandbox}; +/// Default WASM executor with substrate host function set. +pub type DefaultExecutor = WasmExecutor>; + + /// Extracts the runtime version of a given runtime code. pub trait RuntimeVersionOf { /// Extract [`RuntimeVersion`](sp_version::RuntimeVersion) of the given `runtime_code`. diff --git a/client/executor/src/native_executor.rs b/client/executor/src/native_executor.rs index 1bc87840ba353..d0ba0d78584e7 100644 --- a/client/executor/src/native_executor.rs +++ b/client/executor/src/native_executor.rs @@ -290,7 +290,7 @@ where type Error = Error; fn call< - R: Decode + Encode + PartialEq, + R: Decode + Encode, NC: FnOnce() -> result::Result> + UnwindSafe, >( &self, @@ -532,7 +532,7 @@ impl CodeExecutor for NativeElseWasmExecut type Error = Error; fn call< - R: Decode + Encode + PartialEq, + R: Decode + Encode, NC: FnOnce() -> result::Result> + UnwindSafe, >( &self, diff --git a/client/finality-grandpa/src/environment.rs b/client/finality-grandpa/src/environment.rs index 6ffcdc719a166..e095c1158e0b6 100644 --- a/client/finality-grandpa/src/environment.rs +++ b/client/finality-grandpa/src/environment.rs @@ -477,7 +477,6 @@ where Block: BlockT, BE: BackendT, C: ClientForGrandpa, - C::Api: GrandpaApi, N: NetworkT, SC: SelectChainT, { @@ -631,7 +630,6 @@ where Block: BlockT, B: BackendT, C: ClientForGrandpa + 'static, - C::Api: GrandpaApi, N: NetworkT, SC: SelectChainT + 'static, VR: VotingRuleT + Clone + 'static, diff --git a/client/finality-grandpa/src/import.rs b/client/finality-grandpa/src/import.rs index ae5839d0c24e6..42e3810a4fda3 100644 --- a/client/finality-grandpa/src/import.rs +++ b/client/finality-grandpa/src/import.rs @@ -230,7 +230,6 @@ where NumberFor: finality_grandpa::BlockNumberOps, BE: Backend, Client: ClientForGrandpa, - Client::Api: GrandpaApi, for<'a> &'a Client: BlockImport>, TransactionFor: 'static, @@ -515,7 +514,6 @@ where NumberFor: finality_grandpa::BlockNumberOps, BE: Backend, Client: ClientForGrandpa, - Client::Api: GrandpaApi, for<'a> &'a Client: BlockImport>, TransactionFor: 'static, diff --git a/client/finality-grandpa/src/lib.rs b/client/finality-grandpa/src/lib.rs index 8316e56b5b5e5..be4783d75a245 100644 --- a/client/finality-grandpa/src/lib.rs +++ b/client/finality-grandpa/src/lib.rs @@ -764,7 +764,6 @@ where VR: VotingRule + Clone + 'static, NumberFor: BlockNumberOps, C: ClientForGrandpa + 'static, - C::Api: GrandpaApi, { let GrandpaParams { mut config, @@ -896,7 +895,6 @@ where Block: BlockT, B: Backend + 'static, C: ClientForGrandpa + 'static, - C::Api: GrandpaApi, N: NetworkT + Sync, NumberFor: BlockNumberOps, SC: SelectChain + 'static, @@ -1116,7 +1114,6 @@ where NumberFor: BlockNumberOps, SC: SelectChain + 'static, C: ClientForGrandpa + 'static, - C::Api: GrandpaApi, VR: VotingRule + Clone + 'static, { type Output = Result<(), Error>; diff --git a/client/offchain/src/lib.rs b/client/offchain/src/lib.rs index 8d016e945453b..9af67347da4a2 100644 --- a/client/offchain/src/lib.rs +++ b/client/offchain/src/lib.rs @@ -130,7 +130,6 @@ impl OffchainWorkers where Block: traits::Block, Client: ProvideRuntimeApi + Send + Sync + 'static, - Client::Api: OffchainWorkerApi, { /// Start the offchain workers after given block. #[must_use] @@ -233,7 +232,6 @@ pub async fn notification_future( Block: traits::Block, Client: ProvideRuntimeApi + sc_client_api::BlockchainEvents + Send + Sync + 'static, - Client::Api: OffchainWorkerApi, Spawner: SpawnNamed, { client diff --git a/client/rpc/src/author/mod.rs b/client/rpc/src/author/mod.rs index 2b604d2897c58..99bddd8d1f19f 100644 --- a/client/rpc/src/author/mod.rs +++ b/client/rpc/src/author/mod.rs @@ -84,7 +84,6 @@ impl AuthorApi, BlockHash

> for Author where P: TransactionPool + Sync + Send + 'static, Client: HeaderBackend + ProvideRuntimeApi + Send + Sync + 'static, - Client::Api: SessionKeys, P::Hash: Unpin, ::Hash: Unpin, { diff --git a/client/rpc/src/state/mod.rs b/client/rpc/src/state/mod.rs index 071db5324c836..7fd3a5fc12158 100644 --- a/client/rpc/src/state/mod.rs +++ b/client/rpc/src/state/mod.rs @@ -36,7 +36,7 @@ use sp_core::{ use sp_runtime::traits::Block as BlockT; use sp_version::RuntimeVersion; -use sp_api::{CallApiAt, Metadata, ProvideRuntimeApi}; +use sp_api::{CallApiAt, ProvideRuntimeApi}; use self::error::{Error, FutureResult}; @@ -203,7 +203,6 @@ where + Send + Sync + 'static, - Client::Api: Metadata, { let child_backend = Box::new(self::state_full::FullState::new( client.clone(), diff --git a/client/rpc/src/state/state_full.rs b/client/rpc/src/state/state_full.rs index b8132094fe8d6..23af912056bb2 100644 --- a/client/rpc/src/state/state_full.rs +++ b/client/rpc/src/state/state_full.rs @@ -193,7 +193,6 @@ where + Send + Sync + 'static, - Client::Api: Metadata, { fn call( &self, @@ -530,7 +529,6 @@ where + Send + Sync + 'static, - Client::Api: Metadata, { fn read_child_proof( &self, diff --git a/client/service/src/builder.rs b/client/service/src/builder.rs index bf681aec94c7d..166ef6c258787 100644 --- a/client/service/src/builder.rs +++ b/client/service/src/builder.rs @@ -35,7 +35,6 @@ use sc_client_api::{ }; use sc_client_db::{Backend, DatabaseSettings}; use sc_consensus::import_queue::ImportQueue; -use sc_executor::RuntimeVersionOf; use sc_keystore::LocalKeystore; use sc_network::{ block_request_handler::{self, BlockRequestHandler}, @@ -53,7 +52,7 @@ use sp_blockchain::{HeaderBackend, HeaderMetadata}; use sp_consensus::block_validation::{ BlockAnnounceValidator, Chain, DefaultBlockAnnounceValidator, }; -use sp_core::traits::{CodeExecutor, SpawnNamed}; +use sp_core::traits::{SpawnNamed}; use sp_keystore::{CryptoStore, SyncCryptoStore, SyncCryptoStorePtr}; use sp_runtime::{ generic::BlockId, @@ -126,18 +125,16 @@ where } /// Full client type. -pub type TFullClient = - Client, TFullCallExecutor, TBl, TRtApi>; +pub type TFullClient = Client, TBl>; /// Full client backend type. pub type TFullBackend = sc_client_db::Backend; /// Full client call executor type. -pub type TFullCallExecutor = - crate::client::LocalCallExecutor, TExec>; +//pub type TFullCallExecutor = +// crate::client::LocalCallExecutor, TExec>; -type TFullParts = - (TFullClient, Arc>, KeystoreContainer, TaskManager); +type TFullParts = (TFullClient, Arc>, KeystoreContainer, TaskManager); trait AsCryptoStoreRef { fn keystore_ref(&self) -> Arc; @@ -219,27 +216,25 @@ impl KeystoreContainer { } /// Creates a new full client for the given config. -pub fn new_full_client( +pub fn new_full_client( config: &Configuration, telemetry: Option, - executor: TExec, -) -> Result, Error> + executor: sc_executor::DefaultExecutor, +) -> Result, Error> where TBl: BlockT, - TExec: CodeExecutor + RuntimeVersionOf + Clone, { new_full_parts(config, telemetry, executor).map(|parts| parts.0) } /// Create the initial parts of a full node. -pub fn new_full_parts( +pub fn new_full_parts( config: &Configuration, telemetry: Option, - executor: TExec, -) -> Result, Error> + executor: sc_executor::DefaultExecutor, +) -> Result, Error> where TBl: BlockT, - TExec: CodeExecutor + RuntimeVersionOf + Clone, { let keystore_container = KeystoreContainer::new(&config.keystore)?; @@ -333,9 +328,9 @@ where } /// Create an instance of client backed by given backend. -pub fn new_client( +pub fn new_client( backend: Arc>, - executor: E, + executor: sc_executor::DefaultExecutor, genesis_storage: &dyn BuildStorage, fork_blocks: ForkBlocks, bad_blocks: BadBlocks, @@ -347,15 +342,12 @@ pub fn new_client( ) -> Result< crate::client::Client< Backend, - crate::client::LocalCallExecutor, E>, Block, - RA, >, sp_blockchain::Error, > where Block: BlockT, - E: CodeExecutor + RuntimeVersionOf, { let executor = crate::client::LocalCallExecutor::new( backend.clone(), @@ -411,7 +403,6 @@ pub fn build_offchain_workers( where TBl: BlockT, TCl: Send + Sync + ProvideRuntimeApi + BlockchainEvents + 'static, - >::Api: sc_offchain::OffchainWorkerApi, { let offchain_workers = Some(Arc::new(sc_offchain::OffchainWorkers::new(client.clone()))); @@ -452,11 +443,6 @@ where + CallApiAt + Send + 'static, - >::Api: sp_api::Metadata - + sc_offchain::OffchainWorkerApi - + sp_transaction_pool::runtime_api::TaggedTransactionQueue - + sp_session::SessionKeys - + sp_api::ApiExt, TBl: BlockT, TBl::Hash: Unpin, TBl::Header: Unpin, @@ -662,7 +648,6 @@ where TExPool: MaintainedTransactionPool::Hash> + 'static, TBackend: sc_client_api::backend::Backend + 'static, TRpc: sc_rpc::RpcExtension, - >::Api: sp_session::SessionKeys + sp_api::Metadata, TBl::Hash: Unpin, TBl::Header: Unpin, { diff --git a/client/service/src/client/call_executor.rs b/client/service/src/client/call_executor.rs index f271b35a69ced..311807d3a6cb7 100644 --- a/client/service/src/client/call_executor.rs +++ b/client/service/src/client/call_executor.rs @@ -22,7 +22,7 @@ use sc_client_api::{backend, call_executor::CallExecutor, HeaderBackend}; use sc_executor::{RuntimeVersion, RuntimeVersionOf}; use sp_api::{ProofRecorder, StorageTransactionCache}; use sp_core::{ - traits::{CodeExecutor, RuntimeCode, SpawnNamed}, + traits::{RuntimeCode, SpawnNamed}, NativeOrEncoded, NeverNativeValue, }; use sp_externalities::Extensions; @@ -35,24 +35,23 @@ use std::{cell::RefCell, panic::UnwindSafe, result, sync::Arc}; /// Call executor that executes methods locally, querying all required /// data from local backend. -pub struct LocalCallExecutor { +pub struct LocalCallExecutor { backend: Arc, - executor: E, + executor: sc_executor::DefaultExecutor, wasm_override: Arc>, - wasm_substitutes: WasmSubstitutes, + wasm_substitutes: WasmSubstitutes, spawn_handle: Box, client_config: ClientConfig, } -impl LocalCallExecutor +impl LocalCallExecutor where - E: CodeExecutor + RuntimeVersionOf + Clone + 'static, B: backend::Backend, { /// Creates new instance of local call executor. pub fn new( backend: Arc, - executor: E, + executor: sc_executor::DefaultExecutor, spawn_handle: Box, client_config: ClientConfig, ) -> sp_blockchain::Result { @@ -118,10 +117,7 @@ where } } -impl Clone for LocalCallExecutor -where - E: Clone, -{ +impl Clone for LocalCallExecutor { fn clone(&self) -> Self { LocalCallExecutor { backend: self.backend.clone(), @@ -134,13 +130,12 @@ where } } -impl CallExecutor for LocalCallExecutor +impl CallExecutor for LocalCallExecutor where B: backend::Backend, - E: CodeExecutor + RuntimeVersionOf + Clone + 'static, Block: BlockT, { - type Error = E::Error; + type Error = ::Error; type Backend = B; @@ -188,7 +183,7 @@ where Result, Self::Error>, Result, Self::Error>, ) -> Result, Self::Error>, - R: Encode + Decode + PartialEq, + R: Encode + Decode, NC: FnOnce() -> result::Result + UnwindSafe, >( &self, @@ -319,9 +314,8 @@ where } } -impl RuntimeVersionOf for LocalCallExecutor +impl RuntimeVersionOf for LocalCallExecutor where - E: RuntimeVersionOf, Block: BlockT, { fn runtime_version( @@ -333,10 +327,9 @@ where } } -impl sp_version::GetRuntimeVersionAt for LocalCallExecutor +impl sp_version::GetRuntimeVersionAt for LocalCallExecutor where B: backend::Backend, - E: CodeExecutor + RuntimeVersionOf + Clone + 'static, Block: BlockT, { fn runtime_version(&self, at: &BlockId) -> Result { @@ -344,17 +337,6 @@ where } } -impl sp_version::GetNativeVersion for LocalCallExecutor -where - B: backend::Backend, - E: CodeExecutor + sp_version::GetNativeVersion + Clone + 'static, - Block: BlockT, -{ - fn native_version(&self) -> &sp_version::NativeVersion { - self.executor.native_version() - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/client/service/src/client/client.rs b/client/service/src/client/client.rs index 071af36a23f96..e57df617dfaa5 100644 --- a/client/service/src/client/client.rs +++ b/client/service/src/client/client.rs @@ -20,6 +20,7 @@ use super::{ block_rules::{BlockRules, LookupResult as BlockLookupResult}, + call_executor::LocalCallExecutor, genesis, }; use codec::{Decode, Encode}; @@ -27,7 +28,7 @@ use log::{info, trace, warn}; use parking_lot::{Mutex, RwLock}; use prometheus_endpoint::Registry; use rand::Rng; -use sc_block_builder::{BlockBuilderApi, BlockBuilderProvider, RecordProof}; +use sc_block_builder::{BlockBuilderProvider, RecordProof}; use sc_client_api::{ backend::{ self, apply_aux, BlockImportOperation, ClientImportOperation, FinalizeSummary, Finalizer, @@ -48,8 +49,8 @@ use sc_consensus::{ use sc_executor::{RuntimeVersion, RuntimeVersionOf}; use sc_telemetry::{telemetry, TelemetryHandle, SUBSTRATE_INFO}; use sp_api::{ - ApiExt, ApiRef, CallApiAt, CallApiAtParams, ConstructRuntimeApi, Core as CoreApi, ProvideRuntimeApi, + ApiExt, CallApiAt, CallApiAtParams, Core as CoreApi, RuntimeApi, }; use sp_blockchain::{ self as blockchain, well_known_cache_keys::Id as CacheKeyId, Backend as ChainBackend, @@ -82,7 +83,6 @@ use sp_state_machine::{ use sp_trie::{CompactProof, StorageProof}; use std::{ collections::{hash_map::DefaultHasher, HashMap, HashSet}, - marker::PhantomData, panic::UnwindSafe, path::PathBuf, result, @@ -91,20 +91,20 @@ use std::{ #[cfg(feature = "test-helpers")] use { - super::call_executor::LocalCallExecutor, sc_client_api::in_mem, - sp_core::traits::{CodeExecutor, SpawnNamed}, + sp_core::traits::SpawnNamed, + sc_executor::DefaultExecutor, }; type NotificationSinks = Mutex>>; /// Substrate Client -pub struct Client +pub struct Client where Block: BlockT, { backend: Arc, - executor: E, + executor: LocalCallExecutor, storage_notifications: Mutex>, import_notification_sinks: NotificationSinks>, finality_notification_sinks: NotificationSinks>, @@ -114,7 +114,6 @@ where execution_extensions: ExecutionExtensions, config: ClientConfig, telemetry: Option, - _phantom: PhantomData, } /// Used in importing a block, where additional changes are made after the runtime @@ -153,8 +152,8 @@ enum PrepareStorageChangesResult, Block: BlockT> { /// Create an instance of in-memory client. #[cfg(feature = "test-helpers")] -pub fn new_in_mem( - executor: E, +pub fn new_in_mem( + executor: DefaultExecutor, genesis_storage: &S, keystore: Option, prometheus_registry: Option, @@ -162,10 +161,9 @@ pub fn new_in_mem( spawn_handle: Box, config: ClientConfig, ) -> sp_blockchain::Result< - Client, LocalCallExecutor, E>, Block, RA>, + Client, Block>, > where - E: CodeExecutor + RuntimeVersionOf, S: BuildStorage, Block: BlockT, { @@ -212,18 +210,17 @@ impl Default for ClientConfig { /// Create a client with the explicitly provided backend. /// This is useful for testing backend implementations. #[cfg(feature = "test-helpers")] -pub fn new_with_backend( +pub fn new_with_backend( backend: Arc, - executor: E, + executor: DefaultExecutor, build_genesis_storage: &S, keystore: Option, spawn_handle: Box, prometheus_registry: Option, telemetry: Option, config: ClientConfig, -) -> sp_blockchain::Result, Block, RA>> +) -> sp_blockchain::Result> where - E: CodeExecutor + RuntimeVersionOf, S: BuildStorage, Block: BlockT, B: backend::LocalBackend + 'static, @@ -248,19 +245,17 @@ where ) } -impl BlockOf for Client +impl BlockOf for Client where B: backend::Backend, - E: CallExecutor, Block: BlockT, { type Type = Block; } -impl LockImportRun for Client +impl LockImportRun for Client where B: backend::Backend, - E: CallExecutor, Block: BlockT, { fn lock_import_and_run(&self, f: F) -> Result @@ -295,11 +290,10 @@ where } } -impl LockImportRun for &Client +impl LockImportRun for &Client where Block: BlockT, B: backend::Backend, - E: CallExecutor, { fn lock_import_and_run(&self, f: F) -> Result where @@ -310,17 +304,16 @@ where } } -impl Client +impl Client where B: backend::Backend, - E: CallExecutor, Block: BlockT, Block::Header: Clone, { /// Creates new Substrate Client with given blockchain and code executor. pub fn new( backend: Arc, - executor: E, + executor: LocalCallExecutor, build_genesis_storage: &dyn BuildStorage, fork_blocks: ForkBlocks, bad_blocks: BadBlocks, @@ -372,7 +365,6 @@ where execution_extensions, config, telemetry, - _phantom: Default::default(), }) } @@ -418,12 +410,7 @@ where storage_changes: Option< sc_consensus::StorageChanges>, >, - ) -> sp_blockchain::Result - where - Self: ProvideRuntimeApi, - >::Api: - CoreApi + ApiExt, - { + ) -> sp_blockchain::Result { let BlockImportParams { origin, header, @@ -514,12 +501,7 @@ where aux: Vec<(Vec, Option>)>, fork_choice: ForkChoiceStrategy, import_existing: bool, - ) -> sp_blockchain::Result - where - Self: ProvideRuntimeApi, - >::Api: - CoreApi + ApiExt, - { + ) -> sp_blockchain::Result { let parent_hash = import_headers.post().parent_hash().clone(); let status = self.backend.blockchain().status(BlockId::Hash(hash))?; let parent_exists = self.backend.blockchain().status(BlockId::Hash(parent_hash))? == @@ -736,12 +718,7 @@ where fn prepare_block_storage_changes( &self, import_block: &mut BlockImportParams>, - ) -> sp_blockchain::Result> - where - Self: ProvideRuntimeApi, - >::Api: - CoreApi + ApiExt, - { + ) -> sp_blockchain::Result> { let parent_hash = import_block.header.parent_hash(); let at = BlockId::Hash(*parent_hash); let state_action = std::mem::replace(&mut import_block.state_action, StateAction::Skip); @@ -770,7 +747,7 @@ where // We should enact state, but don't have any storage changes, so we need to execute the // block. (true, None, Some(ref body)) => { - let runtime_api = self.runtime_api(); + let runtime_api = RuntimeApi::new(self); let execution_context = import_block.origin.into(); runtime_api.execute_block_with_context( @@ -1098,7 +1075,7 @@ where fn resolve_state_version_from_wasm( storage: &Storage, - executor: &E, + executor: &LocalCallExecutor, ) -> sp_blockchain::Result { if let Some(wasm) = storage.top.get(well_known_keys::CODE) { let mut ext = sp_state_machine::BasicExternalities::new_empty(); // just to read runtime version. @@ -1126,10 +1103,9 @@ where } } -impl UsageProvider for Client +impl UsageProvider for Client where B: backend::Backend, - E: CallExecutor, Block: BlockT, { /// Get usage info about current client. @@ -1138,10 +1114,9 @@ where } } -impl ProofProvider for Client +impl ProofProvider for Client where B: backend::Backend, - E: CallExecutor, Block: BlockT, { fn read_proof( @@ -1327,14 +1302,10 @@ where } } -impl BlockBuilderProvider for Client +impl BlockBuilderProvider for Client where B: backend::Backend + Send + Sync + 'static, - E: CallExecutor + Send + Sync + 'static, Block: BlockT, - Self: ChainHeaderBackend + ProvideRuntimeApi, - >::Api: - ApiExt> + BlockBuilderApi, { fn new_block_at>( &self, @@ -1368,13 +1339,12 @@ where } } -impl ExecutorProvider for Client +impl ExecutorProvider for Client where B: backend::Backend, - E: CallExecutor, Block: BlockT, { - type Executor = E; + type Executor = LocalCallExecutor; fn executor(&self) -> &Self::Executor { &self.executor @@ -1385,10 +1355,9 @@ where } } -impl StorageProvider for Client +impl StorageProvider for Client where B: backend::Backend, - E: CallExecutor, Block: BlockT, { fn storage_keys( @@ -1502,10 +1471,9 @@ where } } -impl HeaderMetadata for Client +impl HeaderMetadata for Client where B: backend::Backend, - E: CallExecutor, Block: BlockT, { type Error = sp_blockchain::Error; @@ -1526,10 +1494,9 @@ where } } -impl ProvideUncles for Client +impl ProvideUncles for Client where B: backend::Backend, - E: CallExecutor, Block: BlockT, { fn uncles( @@ -1544,12 +1511,10 @@ where } } -impl ChainHeaderBackend for Client +impl ChainHeaderBackend for Client where B: backend::Backend, - E: CallExecutor + Send + Sync, Block: BlockT, - RA: Send + Sync, { fn header(&self, id: BlockId) -> sp_blockchain::Result> { self.backend.blockchain().header(id) @@ -1575,12 +1540,10 @@ where } } -impl sp_runtime::traits::BlockIdTo for Client +impl sp_runtime::traits::BlockIdTo for Client where B: backend::Backend, - E: CallExecutor + Send + Sync, Block: BlockT, - RA: Send + Sync, { type Error = Error; @@ -1596,12 +1559,10 @@ where } } -impl ChainHeaderBackend for &Client +impl ChainHeaderBackend for &Client where B: backend::Backend, - E: CallExecutor + Send + Sync, Block: BlockT, - RA: Send + Sync, { fn header(&self, id: BlockId) -> sp_blockchain::Result> { (**self).backend.blockchain().header(id) @@ -1627,31 +1588,26 @@ where } } -impl ProvideRuntimeApi for Client +impl ProvideRuntimeApi for Client where B: backend::Backend, - E: CallExecutor + Send + Sync, Block: BlockT, - RA: ConstructRuntimeApi, { - type Api = >::RuntimeApi; - - fn runtime_api<'a>(&'a self) -> ApiRef<'a, Self::Api> { - RA::construct_runtime_api(self) + fn runtime_api<'a>(&'a self) -> RuntimeApi<'a, Block, Self> { + RuntimeApi::new(self) } } -impl CallApiAt for Client +impl CallApiAt for Client where B: backend::Backend, - E: CallExecutor + Send + Sync, Block: BlockT, { type StateBackend = B::State; fn call_api_at< 'a, - R: Encode + Decode + PartialEq, + R: Encode + Decode, NC: FnOnce() -> result::Result + UnwindSafe, >( &self, @@ -1686,15 +1642,10 @@ where /// objects. Otherwise, importing blocks directly into the client would be bypassing /// important verification work. #[async_trait::async_trait] -impl sc_consensus::BlockImport for &Client +impl sc_consensus::BlockImport for &Client where B: backend::Backend, - E: CallExecutor + Send + Sync, Block: BlockT, - Client: ProvideRuntimeApi, - as ProvideRuntimeApi>::Api: - CoreApi + ApiExt, - RA: Sync + Send, backend::TransactionFor: Send + 'static, { type Error = ConsensusError; @@ -1800,15 +1751,10 @@ where } #[async_trait::async_trait] -impl sc_consensus::BlockImport for Client +impl sc_consensus::BlockImport for Client where B: backend::Backend, - E: CallExecutor + Send + Sync, Block: BlockT, - Self: ProvideRuntimeApi, - >::Api: - CoreApi + ApiExt, - RA: Sync + Send, backend::TransactionFor: Send + 'static, { type Error = ConsensusError; @@ -1830,10 +1776,9 @@ where } } -impl Finalizer for Client +impl Finalizer for Client where B: backend::Backend, - E: CallExecutor, Block: BlockT, { fn apply_finality( @@ -1866,10 +1811,9 @@ where } } -impl Finalizer for &Client +impl Finalizer for &Client where B: backend::Backend, - E: CallExecutor, Block: BlockT, { fn apply_finality( @@ -1892,9 +1836,8 @@ where } } -impl BlockchainEvents for Client +impl BlockchainEvents for Client where - E: CallExecutor, Block: BlockT, { /// Get block import event stream. @@ -1920,10 +1863,9 @@ where } } -impl BlockBackend for Client +impl BlockBackend for Client where B: backend::Backend, - E: CallExecutor, Block: BlockT, { fn block_body( @@ -1969,13 +1911,10 @@ where } } -impl backend::AuxStore for Client +impl backend::AuxStore for Client where B: backend::Backend, - E: CallExecutor, Block: BlockT, - Self: ProvideRuntimeApi, - >::Api: CoreApi, { /// Insert auxiliary data into key-value store. fn insert_aux< @@ -2001,13 +1940,10 @@ where } } -impl backend::AuxStore for &Client +impl backend::AuxStore for &Client where B: backend::Backend, - E: CallExecutor, Block: BlockT, - Client: ProvideRuntimeApi, - as ProvideRuntimeApi>::Api: CoreApi, { fn insert_aux< 'a, @@ -2028,10 +1964,9 @@ where } } -impl sp_consensus::block_validation::Chain for Client +impl sp_consensus::block_validation::Chain for Client where BE: backend::Backend, - E: CallExecutor, B: BlockT, { fn block_status( @@ -2042,10 +1977,9 @@ where } } -impl sp_transaction_storage_proof::IndexedBody for Client +impl sp_transaction_storage_proof::IndexedBody for Client where BE: backend::Backend, - E: CallExecutor, B: BlockT, { fn block_indexed_body( diff --git a/client/service/src/lib.rs b/client/service/src/lib.rs index d158bbc42e947..34825da75df32 100644 --- a/client/service/src/lib.rs +++ b/client/service/src/lib.rs @@ -51,7 +51,7 @@ pub use self::{ build_network, build_offchain_workers, new_client, new_db_backend, new_full_client, new_full_parts, spawn_tasks, BuildNetworkParams, KeystoreContainer, NetworkStarter, NoopRpcExtensionBuilder, RpcExtensionBuilder, SpawnTasksParams, TFullBackend, - TFullCallExecutor, TFullClient, + TFullClient, }, client::{ClientConfig, LocalCallExecutor}, error::Error, diff --git a/client/tracing/src/block/mod.rs b/client/tracing/src/block/mod.rs index 259827e4b47d9..c8baf418afdf4 100644 --- a/client/tracing/src/block/mod.rs +++ b/client/tracing/src/block/mod.rs @@ -35,7 +35,7 @@ use tracing::{ use crate::{SpanDatum, TraceEvent, Values}; use sc_client_api::BlockBackend; use sc_rpc_server::RPC_MAX_PAYLOAD_DEFAULT; -use sp_api::{Core, Encode, Metadata, ProvideRuntimeApi}; +use sp_api::{Core, Encode, ProvideRuntimeApi}; use sp_blockchain::HeaderBackend; use sp_core::hexdisplay::HexDisplay; use sp_rpc::tracing::{BlockTrace, Span, TraceBlockResponse, TraceError}; @@ -194,7 +194,6 @@ where + Send + Sync + 'static, - Client::Api: Metadata, { /// Create a new `BlockExecutor` pub fn new( diff --git a/client/transaction-pool/src/api.rs b/client/transaction-pool/src/api.rs index 12909f313d100..14e1ce73d7dfe 100644 --- a/client/transaction-pool/src/api.rs +++ b/client/transaction-pool/src/api.rs @@ -114,7 +114,6 @@ where Client: ProvideRuntimeApi + BlockBackend + BlockIdTo + HeaderBackend, Client: Send + Sync + 'static, - Client::Api: TaggedTransactionQueue, { type Block = Block; type Error = error::Error; @@ -205,7 +204,6 @@ where Client: ProvideRuntimeApi + BlockBackend + BlockIdTo + HeaderBackend, Client: Send + Sync + 'static, - Client::Api: TaggedTransactionQueue, { sp_tracing::within_span!(sp_tracing::Level::TRACE, "validate_transaction"; { @@ -267,7 +265,6 @@ where Client: ProvideRuntimeApi + BlockBackend + BlockIdTo + HeaderBackend, Client: Send + Sync + 'static, - Client::Api: TaggedTransactionQueue, { /// Validates a transaction by calling into the runtime, same as /// `validate_transaction` but blocks the current thread when performing diff --git a/client/transaction-pool/src/graph/validated_pool.rs b/client/transaction-pool/src/graph/validated_pool.rs index 7e19941b25684..4ddaf8de5c2bc 100644 --- a/client/transaction-pool/src/graph/validated_pool.rs +++ b/client/transaction-pool/src/graph/validated_pool.rs @@ -203,7 +203,7 @@ impl ValidatedPool { let imported = self.pool.write().import(tx)?; if let base::Imported::Ready { ref hash, .. } = imported { - self.import_notification_sinks.lock().retain_mut(|sink| { + RetainMut::retain_mut(&mut *self.import_notification_sinks.lock(), |sink| { match sink.try_send(*hash) { Ok(()) => true, Err(e) => diff --git a/client/transaction-pool/src/lib.rs b/client/transaction-pool/src/lib.rs index ec93d1f7c51fe..5dae7cc9dba6f 100644 --- a/client/transaction-pool/src/lib.rs +++ b/client/transaction-pool/src/lib.rs @@ -360,7 +360,6 @@ where + Send + Sync + 'static, - Client::Api: sp_transaction_pool::runtime_api::TaggedTransactionQueue, { /// Create new basic transaction pool for a full node with the provided api. pub fn new_full( @@ -397,7 +396,6 @@ where + sc_client_api::blockchain::HeaderBackend + sp_runtime::traits::BlockIdTo, Client: Send + Sync + 'static, - Client::Api: sp_transaction_pool::runtime_api::TaggedTransactionQueue, { type Block = Block; type Hash = graph::ExtrinsicHash>; diff --git a/frame/contracts/rpc/runtime-api/src/lib.rs b/frame/contracts/rpc/runtime-api/src/lib.rs index 59622a21a6593..6c154662a467d 100644 --- a/frame/contracts/rpc/runtime-api/src/lib.rs +++ b/frame/contracts/rpc/runtime-api/src/lib.rs @@ -31,10 +31,9 @@ use sp_std::vec::Vec; sp_api::decl_runtime_apis! { /// The API to interact with contracts without using executive. - pub trait ContractsApi where + pub trait ContractsApi where AccountId: Codec, Balance: Codec, - BlockNumber: Codec, Hash: Codec, { /// Perform a call from a specified account to a given contract. diff --git a/frame/contracts/rpc/src/lib.rs b/frame/contracts/rpc/src/lib.rs index e83e4e6249b92..2ebac0c3451b9 100644 --- a/frame/contracts/rpc/src/lib.rs +++ b/frame/contracts/rpc/src/lib.rs @@ -188,13 +188,6 @@ impl where Block: BlockT, C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, - C::Api: ContractsRuntimeApi< - Block, - AccountId, - Balance, - <::Header as HeaderT>::Number, - Hash, - >, AccountId: Codec, Balance: Codec + Copy + TryFrom + Into, Hash: Codec, @@ -218,7 +211,8 @@ where storage_deposit_limit.map(|l| decode_hex(l, "balance")).transpose()?; limit_gas(gas_limit)?; - api.call(&at, origin, dest, value, gas_limit, storage_deposit_limit, input_data.to_vec()) + ContractsRuntimeApi::::call( + &api, &at, origin, dest, value, gas_limit, storage_deposit_limit, input_data.to_vec()) .map_err(runtime_error_into_rpc_err) } @@ -291,8 +285,7 @@ where // If the block hash is not supplied assume the best block. self.client.info().best_hash)); - let result = api - .get_storage(&at, address, key.into()) + let result = ContractsRuntimeApi::::get_storage(&api, &at, address, key.into()) .map_err(runtime_error_into_rpc_err)? .map_err(ContractAccessError)? .map(Bytes); diff --git a/frame/merkle-mountain-range/rpc/src/lib.rs b/frame/merkle-mountain-range/rpc/src/lib.rs index bf3eb3b694e39..fcc8c98a75381 100644 --- a/frame/merkle-mountain-range/rpc/src/lib.rs +++ b/frame/merkle-mountain-range/rpc/src/lib.rs @@ -93,7 +93,6 @@ impl MmrApi<::Hash> for Mmr + HeaderBackend, - C::Api: MmrRuntimeApi, MmrHash: Codec + Send + Sync + 'static, { fn generate_proof( @@ -106,8 +105,8 @@ where // If the block hash is not supplied assume the best block. self.client.info().best_hash); - let (leaf, proof) = api - .generate_proof_with_context( + let (leaf, proof) = MmrRuntimeApi::::generate_proof_with_context( + &api, &BlockId::hash(block_hash), sp_core::ExecutionContext::OffchainCall(None), leaf_index, diff --git a/frame/transaction-payment/rpc/src/lib.rs b/frame/transaction-payment/rpc/src/lib.rs index 29d94fa260105..00040e3f13893 100644 --- a/frame/transaction-payment/rpc/src/lib.rs +++ b/frame/transaction-payment/rpc/src/lib.rs @@ -22,6 +22,7 @@ use codec::{Codec, Decode}; use jsonrpc_core::{Error as RpcError, ErrorCode, Result}; use jsonrpc_derive::rpc; pub use pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi as TransactionPaymentRuntimeApi; +pub use pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo as TransactionPaymentRuntimeDispatchInfo; use pallet_transaction_payment_rpc_runtime_api::{FeeDetails, InclusionFee, RuntimeDispatchInfo}; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; @@ -80,7 +81,6 @@ impl TransactionPaymentApi<::Hash, RuntimeDi where Block: BlockT, C: 'static + ProvideRuntimeApi + HeaderBackend, - C::Api: TransactionPaymentRuntimeApi, Balance: Codec + MaybeDisplay + Copy + TryInto, { fn query_info( diff --git a/primitives/api/proc-macro/src/decl_runtime_apis.rs b/primitives/api/proc-macro/src/decl_runtime_apis.rs index 85b66eca7061e..6de480aa69b43 100644 --- a/primitives/api/proc-macro/src/decl_runtime_apis.rs +++ b/primitives/api/proc-macro/src/decl_runtime_apis.rs @@ -380,7 +380,7 @@ fn generate_call_api_at_calls(decl: &ItemTrait) -> Result { #[cfg(any(feature = "std", test))] #[allow(clippy::too_many_arguments)] pub fn #fn_name< - R: #crate_::Encode + #crate_::Decode + PartialEq, + R: #crate_::Encode + #crate_::Decode, NC: FnOnce() -> std::result::Result + std::panic::UnwindSafe, Block: #crate_::BlockT, T: #crate_::CallApiAt, @@ -439,6 +439,140 @@ fn generate_call_api_at_calls(decl: &ItemTrait) -> Result { Ok(quote!( #( #result )* )) } +/// Generate the functions that call the api at a given block for a given trait method. +fn _generate_call_api_impls(decl: &ItemTrait) -> Result { + let fns = decl.items.iter().filter_map(|i| match i { + TraitItem::Method(ref m) => Some((&m.attrs, &m.sig)), + _ => None, + }); + + let mut result = Vec::new(); + let mut errors = Vec::new(); + let crate_ = generate_crate_access(HIDDEN_INCLUDES_ID); + let mod_name = generate_runtime_mod_name_for_trait(&decl.ident); + + // Generate a native call generator for each function of the given trait. + for (attrs, sig) in fns { + + if remove_supported_attributes(&mut attrs.clone()).contains_key(CHANGED_IN_ATTRIBUTE) { + continue; + } + + let fn_sig = &sig; + let ret_type = return_type_extract_type(&fn_sig.output); + + // Get types and if the value is borrowed from all parameters. + // If there is an error, we push it as the block to the user. + let param_types = + match extract_parameter_names_types_and_borrows(fn_sig, AllowSelfRefInParameters::No) { + Ok(res) => res + .into_iter() + .map(|v| { + let ty = v.1; + let borrow = v.2; + quote!( #borrow #ty ) + }) + .collect::>(), + Err(e) => { + errors.push(e.to_compile_error()); + Vec::new() + }, + }; + let name = generate_method_runtime_api_impl_name(&decl.ident, &fn_sig.ident); + let block_id = quote!( #crate_::BlockId ); + let call_fn_name = generate_call_api_at_fn_name(&fn_sig.ident); + + result.push(quote! { + #[doc(hidden)] + fn #name( + &self, + at: &#block_id, + context: #crate_::ExecutionContext, + params: Option<( #( #param_types ),* )>, + params_encoded: Vec, + ) -> std::result::Result<#crate_::NativeOrEncoded<#ret_type>, #crate_::ApiError> + { + let changes = Default::default(); + let tx_cache = Default::default(); + #mod_name::#call_fn_name::<_, fn() -> std::result::Result<#ret_type, #crate_::ApiError>, _, _>( + self, at, params_encoded, &changes, &tx_cache, None, context, &None + ) + } + }); + } + + Ok(quote!( #( #result )* )) +} + +/// Generate the implementation for `RuntimeApi` +fn generate_runtime_api_call_impl(decl: &ItemTrait) -> Result { + let fns = decl.items.iter().filter_map(|i| match i { + TraitItem::Method(ref m) => Some((&m.attrs, &m.sig)), + _ => None, + }); + + let mut result = Vec::new(); + let mut errors = Vec::new(); + let crate_ = generate_crate_access(HIDDEN_INCLUDES_ID); + let mod_name = generate_runtime_mod_name_for_trait(&decl.ident); + + // Generate a native call generator for each function of the given trait. + for (attrs, sig) in fns { + if remove_supported_attributes(&mut attrs.clone()).contains_key(CHANGED_IN_ATTRIBUTE) { + continue; + } + + let fn_sig = &sig; + let ret_type = return_type_extract_type(&fn_sig.output); + + // Get types and if the value is borrowed from all parameters. + // If there is an error, we push it as the block to the user. + let param_types = + match extract_parameter_names_types_and_borrows(fn_sig, AllowSelfRefInParameters::No) { + Ok(res) => res + .into_iter() + .map(|v| { + let ty = v.1; + let borrow = v.2; + quote!( #borrow #ty ) + }) + .collect::>(), + Err(e) => { + errors.push(e.to_compile_error()); + Vec::new() + }, + }; + let name = generate_method_runtime_api_impl_name(&decl.ident, &fn_sig.ident); + let block_id = quote!( #crate_::BlockId ); + let call_fn_name = generate_call_api_at_fn_name(&fn_sig.ident); + + result.push(quote! { + #[doc(hidden)] + fn #name( + &self, + at: &#block_id, + context: #crate_::ExecutionContext, + params: Option<( #( #param_types ),* )>, + params_encoded: Vec, + ) -> std::result::Result<#crate_::NativeOrEncoded<#ret_type>, #crate_::ApiError> + { + #mod_name::#call_fn_name::<_, fn() -> std::result::Result<#ret_type, #crate_::ApiError>, _, _>( + self.call, + at, + params_encoded, + &self.changes, + &self.storage_transaction_cache, + None, + context, + &self.recorder, + ) + } + }); + } + + Ok(quote!( #( #result )* )) +} + /// Generate the declaration of the trait for the runtime. fn generate_runtime_decls(decls: &[ItemTrait]) -> Result { let mut result = Vec::new(); @@ -697,6 +831,229 @@ impl<'a> ToClientSideDecl<'a> { } impl<'a> Fold for ToClientSideDecl<'a> { + fn fold_item_trait(&mut self, mut input: ItemTrait) -> ItemTrait { + extend_generics_with_block(&mut input.generics); + + *self.found_attributes = remove_supported_attributes(&mut input.attrs); + // Check if this is the `Core` runtime api trait. + let is_core_trait = self.found_attributes.contains_key(CORE_TRAIT_ATTRIBUTE); + let block_ident = Ident::new(BLOCK_GENERIC_IDENT, Span::call_site()); + + if is_core_trait { + // Add all the supertraits we want to have for `Core`. + //input.supertraits = parse_quote!('static + Send + Sync); + input.supertraits = parse_quote!(); + } else { + // Add the `Core` runtime api as super trait. + let crate_ = &self.crate_; + input.supertraits.push(parse_quote!( #crate_::Core<#block_ident> )); + } + + // The client side trait is only required when compiling with the feature `std` or `test`. + input.attrs.push(parse_quote!( #[cfg(any(feature = "std", test))] )); + input.items = self.fold_item_trait_items(input.items); + + fold::fold_item_trait(self, input) + } +} + +/// Modify the given runtime api declaration to be usable on the client side. +struct ToCallImpl<'a> { + block_id: &'a TokenStream, + crate_: &'a TokenStream, + found_attributes: &'a mut HashMap<&'static str, Attribute>, + /// Any error that we found while converting this declaration. + errors: &'a mut Vec, + trait_: &'a Ident, +} + +impl<'a> ToCallImpl<'a> { + fn fold_item_trait_items(&mut self, items: Vec) -> Vec { + let mut result = Vec::new(); + + items.into_iter().for_each(|i| match i { + TraitItem::Method(method) => { + let (fn_decl, fn_impl, fn_decl_ctx) = self.fold_trait_item_method(method); + result.push(fn_decl.into()); + result.push(fn_decl_ctx.into()); + + if let Some(fn_impl) = fn_impl { + result.push(fn_impl.into()); + } + }, + r => result.push(r), + }); + + result + } + + fn fold_trait_item_method( + &mut self, + method: TraitItemMethod, + ) -> (TraitItemMethod, Option, TraitItemMethod) { + let crate_ = self.crate_; + let context = quote!( #crate_::ExecutionContext::OffchainCall(None) ); + let fn_impl = self.create_method_runtime_api_impl(method.clone()); + let fn_decl = self.create_method_decl(method.clone(), context); + let fn_decl_ctx = self.create_method_decl_with_context(method); + + (fn_decl, fn_impl, fn_decl_ctx) + } + + fn create_method_decl_with_context(&mut self, method: TraitItemMethod) -> TraitItemMethod { + let crate_ = self.crate_; + let context_arg: syn::FnArg = parse_quote!( context: #crate_::ExecutionContext ); + let mut fn_decl_ctx = self.create_method_decl(method, quote!(context)); + fn_decl_ctx.sig.ident = + Ident::new(&format!("{}_with_context", &fn_decl_ctx.sig.ident), Span::call_site()); + fn_decl_ctx.sig.inputs.insert(2, context_arg); + + fn_decl_ctx + } + + /// Takes the given method and creates a `method_runtime_api_impl` method that will be + /// implemented in the runtime for the client side. + fn create_method_runtime_api_impl( + &mut self, + mut method: TraitItemMethod, + ) -> Option { + if remove_supported_attributes(&mut method.attrs).contains_key(CHANGED_IN_ATTRIBUTE) { + return None + } + + let fn_sig = &method.sig; + let ret_type = return_type_extract_type(&fn_sig.output); + + // Get types and if the value is borrowed from all parameters. + // If there is an error, we push it as the block to the user. + let param_types = + match extract_parameter_names_types_and_borrows(fn_sig, AllowSelfRefInParameters::No) { + Ok(res) => res + .into_iter() + .map(|v| { + let ty = v.1; + let borrow = v.2; + quote!( #borrow #ty ) + }) + .collect::>(), + Err(e) => { + self.errors.push(e.to_compile_error()); + Vec::new() + }, + }; + let name = generate_method_runtime_api_impl_name(&self.trait_, &method.sig.ident); + let block_id = self.block_id; + let crate_ = self.crate_; + + Some(parse_quote! { + #[doc(hidden)] + fn #name( + &self, + at: &#block_id, + context: #crate_::ExecutionContext, + params: Option<( #( #param_types ),* )>, + params_encoded: Vec, + ) -> std::result::Result<#crate_::NativeOrEncoded<#ret_type>, #crate_::ApiError>; + }) + } + + /// Takes the method declared by the user and creates the declaration we require for the runtime + /// api client side. This method will call by default the `method_runtime_api_impl` for doing + /// the actual call into the runtime. + fn create_method_decl( + &mut self, + mut method: TraitItemMethod, + context: TokenStream, + ) -> TraitItemMethod { + let params = match extract_parameter_names_types_and_borrows( + &method.sig, + AllowSelfRefInParameters::No, + ) { + Ok(res) => res.into_iter().map(|v| v.0).collect::>(), + Err(e) => { + self.errors.push(e.to_compile_error()); + Vec::new() + }, + }; + let params2 = params.clone(); + let ret_type = return_type_extract_type(&method.sig.output); + + fold_fn_decl_for_client_side(&mut method.sig, &self.block_id, &self.crate_); + + let name_impl = generate_method_runtime_api_impl_name(&self.trait_, &method.sig.ident); + let crate_ = self.crate_; + + let found_attributes = remove_supported_attributes(&mut method.attrs); + // If the method has a `changed_in` attribute, we need to alter the method name to + // `method_before_version_VERSION`. + let (native_handling, param_tuple) = match get_changed_in(&found_attributes) { + Ok(Some(version)) => { + // Make sure that the `changed_in` version is at least the current `api_version`. + if get_api_version(&self.found_attributes).ok() < Some(version) { + self.errors.push( + Error::new( + method.span(), + "`changed_in` version can not be greater than the `api_version`", + ) + .to_compile_error(), + ); + } + + let ident = Ident::new( + &format!("{}_before_version_{}", method.sig.ident, version), + method.sig.ident.span(), + ); + method.sig.ident = ident; + method.attrs.push(parse_quote!( #[deprecated] )); + + let panic = + format!("Calling `{}` should not return a native value!", method.sig.ident); + (quote!(panic!(#panic)), quote!(None)) + }, + Ok(None) => (quote!(Ok(n)), quote!( Some(( #( #params2 ),* )) )), + Err(e) => { + self.errors.push(e.to_compile_error()); + (quote!(unimplemented!()), quote!(None)) + }, + }; + + let function_name = method.sig.ident.to_string(); + + // Generate the default implementation that calls the `method_runtime_api_impl` method. + method.default = Some(parse_quote! { + { + let runtime_api_impl_params_encoded = + #crate_::Encode::encode(&( #( &#params ),* )); + + self.#name_impl( + __runtime_api_at_param__, + #context, + #param_tuple, + runtime_api_impl_params_encoded, + ).and_then(|r| + match r { + #crate_::NativeOrEncoded::Native(n) => { + #native_handling + }, + #crate_::NativeOrEncoded::Encoded(r) => { + <#ret_type as #crate_::Decode>::decode(&mut &r[..]) + .map_err(|err| + #crate_::ApiError::FailedToDecodeReturnValue { + function: #function_name, + error: err, + } + ) + } + } + ) + } + }); + + method + } +} + +impl<'a> Fold for ToCallImpl<'a> { fn fold_item_trait(&mut self, mut input: ItemTrait) -> ItemTrait { extend_generics_with_block(&mut input.generics); @@ -842,6 +1199,61 @@ fn generate_client_side_decls(decls: &[ItemTrait]) -> Result { Ok(quote!( #( #result )* )) } +/// Generate the implementation of the trait for CallApiAt +fn generate_call_impl(decls: &[ItemTrait]) -> Result { + let mut result = Vec::new(); + let crate_ = generate_crate_access(HIDDEN_INCLUDES_ID); + + for decl in decls { + let mut decl = decl.clone(); + extend_generics_with_block(&mut decl.generics); + //let mod_name = generate_runtime_mod_name_for_trait(&decl.ident); + let ident = &decl.ident; + //let found_attributes = remove_supported_attributes(&mut decl.attrs); + //let call_at_impl = _generate_call_api_impls(&decl)?; + let runtime_api_call_impl = generate_runtime_api_call_impl(&decl)?; + + let impl_generics = decl.generics.type_params().map(|t| { + let ident = &t.ident; + let colon_token = &t.colon_token; + let bounds = &t.bounds; + + quote! { #ident #colon_token #bounds } + }); + + + let ty_generics = decl.generics.type_params().map(|t| { + let ident = &t.ident; + quote! { #ident } + }); + + let (_, _, where_clause) = decl.generics.split_for_impl(); + let where_clause = where_clause.map(|w| &w.predicates); + + let impl_generics: Vec<_> = impl_generics.collect(); + let ty_generics: Vec<_> = ty_generics.collect(); + + result.push(quote!( + /* + #[doc(hidden)] + #[cfg(any(feature = "std", test))] + impl #ident< #( #ty_generics, )* > for T + where Block: #crate_::BlockT, T: #crate_::CallApiAt + Send + Sync + 'static, #where_clause { + #call_at_impl + } +*/ + #[doc(hidden)] + #[cfg(any(feature = "std", test))] + impl<'a, C, #( #impl_generics, )* > #ident< #( #ty_generics, )* > for #crate_::RuntimeApi<'a, Block, C> + where Block: #crate_::BlockT, C: #crate_::CallApiAt, #where_clause { + #runtime_api_call_impl + } + )); + } + + Ok(quote!( #( #result )* )) +} + /// Checks that a trait declaration is in the format we expect. struct CheckTraitDecl { errors: Vec, @@ -977,6 +1389,7 @@ fn decl_runtime_apis_impl_inner(api_decls: &[ItemTrait]) -> Result let hidden_includes = generate_hidden_includes(HIDDEN_INCLUDES_ID); let runtime_decls = generate_runtime_decls(api_decls)?; let client_side_decls = generate_client_side_decls(api_decls)?; + let call_impl = generate_call_impl(api_decls)?; Ok(quote!( #hidden_includes @@ -984,5 +1397,7 @@ fn decl_runtime_apis_impl_inner(api_decls: &[ItemTrait]) -> Result #runtime_decls #client_side_decls + + #call_impl )) } diff --git a/primitives/api/src/lib.rs b/primitives/api/src/lib.rs index 964ef15ce5f5a..07f57c58a444c 100644 --- a/primitives/api/src/lib.rs +++ b/primitives/api/src/lib.rs @@ -408,7 +408,7 @@ pub type StorageChanges = sp_state_machine::StorageChanges< /// Extract the state backend type for a type that implements `ProvideRuntimeApi`. #[cfg(feature = "std")] pub type StateBackendFor = - <

>::Api as ApiExt>::StateBackend; +

>::StateBackend; /// Extract the state backend transaction type for a type that implements `ProvideRuntimeApi`. #[cfg(feature = "std")] @@ -521,6 +521,168 @@ pub trait ApiExt { Self: Sized; } +/// Data required to handle a single API call. +#[cfg(any(feature = "std", test))] +pub struct RuntimeApi<'a, Block: BlockT, C: CallApiAt> { + pub call: &'a C, + pub commit_on_success: std::cell::RefCell, + pub changes: std::cell::RefCell, + pub storage_transaction_cache: std::cell::RefCell>, + pub recorder: Option>, +} + +/* +#[cfg(any(feature = "std", test))] +unsafe impl> Send + for RuntimeApiImpl +{} + +#[cfg(any(feature = "std", test))] +unsafe impl> Sync + for RuntimeApiImpl +{} +*/ + +#[cfg(any(feature = "std", test))] +impl<'a, Block: BlockT, C: CallApiAt> ApiExt for RuntimeApi<'a, Block, C> { + type StateBackend = C::StateBackend; + + fn execute_in_transaction TransactionOutcome, R>( + &self, + call: F, + ) -> R where Self: Sized { + self.changes.borrow_mut().start_transaction(); + *self.commit_on_success.borrow_mut() = false; + let res = call(self); + *self.commit_on_success.borrow_mut() = true; + + self.commit_or_rollback(matches!(res, TransactionOutcome::Commit(_))); + + res.into_inner() + } + + fn has_api( + &self, + at: &BlockId, + ) -> std::result::Result where Self: Sized { + self.call + .runtime_version_at(at) + .map(|v| v.has_api_with(&A::ID, |v| v == A::VERSION)) + } + + fn has_api_with bool>( + &self, + at: &BlockId, + pred: P, + ) -> std::result::Result where Self: Sized { + self.call + .runtime_version_at(at) + .map(|v| v.has_api_with(&A::ID, pred)) + } + + fn api_version( + &self, + at: &BlockId, + ) -> std::result::Result, ApiError> where Self: Sized { + self.call + .runtime_version_at(at) + .map(|v| v.api_version(&A::ID)) + } + + fn record_proof(&mut self) { + self.recorder = Some(Default::default()); + } + + fn proof_recorder(&self) -> Option> { + self.recorder.clone() + } + + fn extract_proof(&mut self) -> Option { + self.recorder + .take() + .map(|recorder| recorder.to_storage_proof()) + } + + fn into_storage_changes( + &self, + backend: &Self::StateBackend, + parent_hash: Block::Hash, + ) -> std::result::Result< + StorageChanges, + String + > where Self: Sized { + let at = BlockId::Hash(parent_hash.clone()); + let state_version = self.call + .runtime_version_at(&at) + .map(|v| v.state_version()) + .map_err(|e| format!("Failed to get state version: {}", e))?; + + self.changes.replace(Default::default()).into_storage_changes( + backend, + parent_hash, + self.storage_transaction_cache.replace(Default::default()), + state_version, + ) + } +} + +#[cfg(any(feature = "std", test))] +impl<'a, Block: BlockT, C: CallApiAt> RuntimeApi<'a, Block, C> { + pub fn new( + call: &'a C, + ) -> Self { + RuntimeApi { + call, + commit_on_success: true.into(), + changes: Default::default(), + recorder: Default::default(), + storage_transaction_cache: Default::default(), + } + } + + pub fn call_api_at< + R: Encode + Decode, + F: FnOnce( + &C, + &std::cell::RefCell, + &std::cell::RefCell>, + &Option>, + ) -> std::result::Result, E>, + E, + >( + &self, + call_api_at: F, + ) -> std::result::Result, E> { + if *self.commit_on_success.borrow() { + self.changes.borrow_mut().start_transaction(); + } + let res = call_api_at( + &self.call, + &self.changes, + &self.storage_transaction_cache, + &self.recorder, + ); + + self.commit_or_rollback(res.is_ok()); + res + } + + fn commit_or_rollback(&self, commit: bool) { + let proof = "\ + We only close a transaction when we opened one ourself. + Other parts of the runtime that make use of transactions (state-machine) + also balance their transactions. The runtime cannot close client initiated + transactions. qed"; + if *self.commit_on_success.borrow() { + if commit { + self.changes.borrow_mut().commit_transaction().expect(proof); + } else { + self.changes.borrow_mut().rollback_transaction().expect(proof); + } + } + } +} + /// Parameters for [`CallApiAt::call_api_at`]. #[cfg(feature = "std")] pub struct CallApiAtParams<'a, Block: BlockT, NC, Backend: StateBackend>> { @@ -555,7 +717,7 @@ pub trait CallApiAt { /// the encoded result. fn call_api_at< 'a, - R: Encode + Decode + PartialEq, + R: Encode + Decode, NC: FnOnce() -> result::Result + UnwindSafe, >( &self, @@ -595,16 +757,13 @@ impl<'a, T> std::ops::DerefMut for ApiRef<'a, T> { /// Something that provides a runtime api. #[cfg(feature = "std")] -pub trait ProvideRuntimeApi { - /// The concrete type that provides the api. - type Api: ApiExt; - +pub trait ProvideRuntimeApi: CallApiAt + Sized { /// Returns the runtime api. /// The returned instance will keep track of modifications to the storage. Any successful /// call to an api function, will `commit` its changes to an internal buffer. Otherwise, /// the modifications will be `discarded`. The modifications will not be applied to the /// storage, even on a `commit`. - fn runtime_api<'a>(&'a self) -> ApiRef<'a, Self::Api>; + fn runtime_api<'a>(&'a self) -> RuntimeApi<'a, Block, Self>; } /// Something that provides information about a runtime api. diff --git a/primitives/consensus/common/src/lib.rs b/primitives/consensus/common/src/lib.rs index edf393fa229ad..a26bcb58a7d1a 100644 --- a/primitives/consensus/common/src/lib.rs +++ b/primitives/consensus/common/src/lib.rs @@ -283,23 +283,23 @@ pub trait CanAuthorWith { } /// Checks if the node can author blocks by using -/// [`NativeVersion::can_author_with`](sp_version::NativeVersion::can_author_with). +/// [`Version::can_author_with`](sp_version::Version::can_author_with). #[derive(Clone)] -pub struct CanAuthorWithNativeVersion(T); +pub struct CanAuthorWithVersion(T); -impl CanAuthorWithNativeVersion { +impl CanAuthorWithVersion { /// Creates a new instance of `Self`. pub fn new(inner: T) -> Self { Self(inner) } } -impl + sp_version::GetNativeVersion, Block: BlockT> - CanAuthorWith for CanAuthorWithNativeVersion +impl, Block: BlockT> + CanAuthorWith for CanAuthorWithVersion { fn can_author_with(&self, at: &BlockId) -> Result<(), String> { match self.0.runtime_version(at) { - Ok(version) => self.0.native_version().can_author_with(&version), + Ok(_version) => Ok(()), Err(e) => Err(format!( "Failed to get runtime version at `{}` and will disable authoring. Error: {}", at, e, diff --git a/primitives/consensus/pow/src/lib.rs b/primitives/consensus/pow/src/lib.rs index fe10ee808db98..30ee1e69ff10b 100644 --- a/primitives/consensus/pow/src/lib.rs +++ b/primitives/consensus/pow/src/lib.rs @@ -19,7 +19,7 @@ #![cfg_attr(not(feature = "std"), no_std)] -use codec::Decode; +use codec::Codec; use sp_runtime::ConsensusEngineId; use sp_std::vec::Vec; @@ -50,7 +50,7 @@ impl TotalDifficulty for u128 { sp_api::decl_runtime_apis! { /// API necessary for timestamp-based difficulty adjustment algorithms. - pub trait TimestampApi { + pub trait TimestampApi { /// Return the timestamp in the current block. fn timestamp() -> Moment; } @@ -58,7 +58,7 @@ sp_api::decl_runtime_apis! { /// API for those chains that put their difficulty adjustment algorithm directly /// onto runtime. Note that while putting difficulty adjustment algorithm to /// runtime is safe, putting the PoW algorithm on runtime is not. - pub trait DifficultyApi { + pub trait DifficultyApi { /// Return the target difficulty of the next block. fn difficulty() -> Difficulty; } diff --git a/primitives/core/src/traits.rs b/primitives/core/src/traits.rs index 80e8963a2909d..cd3a7502b550d 100644 --- a/primitives/core/src/traits.rs +++ b/primitives/core/src/traits.rs @@ -33,7 +33,7 @@ pub trait CodeExecutor: Sized + Send + Sync + ReadRuntimeVersion + Clone + 'stat /// Call a given method in the runtime. Returns a tuple of the result (either the output data /// or an execution error) together with a `bool`, which is true if native execution was used. fn call< - R: codec::Codec + PartialEq, + R: codec::Codec, NC: FnOnce() -> Result> + UnwindSafe, >( &self, diff --git a/primitives/session/src/lib.rs b/primitives/session/src/lib.rs index 1b25d285e3bca..0204bb9392385 100644 --- a/primitives/session/src/lib.rs +++ b/primitives/session/src/lib.rs @@ -116,7 +116,6 @@ pub fn generate_initial_session_keys( where Block: BlockT, T: ProvideRuntimeApi, - T::Api: SessionKeys, { let runtime_api = client.runtime_api(); diff --git a/primitives/state-machine/src/lib.rs b/primitives/state-machine/src/lib.rs index 1a69d51d58abf..29d114dae5efd 100644 --- a/primitives/state-machine/src/lib.rs +++ b/primitives/state-machine/src/lib.rs @@ -397,7 +397,7 @@ mod execution { native_call: Option, ) -> (CallResult, bool) where - R: Decode + Encode + PartialEq, + R: Decode + Encode, NC: FnOnce() -> result::Result> + UnwindSafe, { @@ -455,7 +455,7 @@ mod execution { on_consensus_failure: Handler, ) -> CallResult where - R: Decode + Encode + PartialEq, + R: Decode + Encode, NC: FnOnce() -> result::Result> + UnwindSafe, Handler: FnOnce( @@ -471,7 +471,7 @@ mod execution { let (wasm_result, _) = self.execute_aux(false, native_call); if (result.is_ok() && - wasm_result.is_ok() && result.as_ref().ok() == wasm_result.as_ref().ok()) || + wasm_result.is_ok() && result.as_ref().unwrap().as_encoded() == wasm_result.as_ref().unwrap().as_encoded()) || result.is_err() && wasm_result.is_err() { result @@ -489,7 +489,7 @@ mod execution { mut native_call: Option, ) -> CallResult where - R: Decode + Encode + PartialEq, + R: Decode + Encode, NC: FnOnce() -> result::Result> + UnwindSafe, { @@ -521,7 +521,7 @@ mod execution { mut native_call: Option, ) -> Result, Box> where - R: Decode + Encode + PartialEq, + R: Decode + Encode, NC: FnOnce() -> result::Result> + UnwindSafe, Handler: FnOnce( @@ -1376,7 +1376,7 @@ mod tests { type Error = u8; fn call< - R: Encode + Decode + PartialEq, + R: Encode + Decode, NC: FnOnce() -> result::Result> + UnwindSafe, >( &self, diff --git a/test-utils/client/src/client_ext.rs b/test-utils/client/src/client_ext.rs index f2b99a5b355f0..25c27edec5269 100644 --- a/test-utils/client/src/client_ext.rs +++ b/test-utils/client/src/client_ext.rs @@ -66,10 +66,9 @@ pub trait ClientBlockImportExt: Sized { ) -> Result<(), ConsensusError>; } -impl ClientExt for Client +impl ClientExt for Client where B: sc_client_api::backend::Backend, - E: sc_client_api::CallExecutor + sc_executor::RuntimeVersionOf + 'static, Self: BlockImport, Block: BlockT, { @@ -148,12 +147,10 @@ where } #[async_trait::async_trait] -impl ClientBlockImportExt for Client +impl ClientBlockImportExt for Client where Self: BlockImport, - RA: Send, B: Send + Sync, - E: Send, >::Transaction: Send, { async fn import(&mut self, origin: BlockOrigin, block: Block) -> Result<(), ConsensusError> { diff --git a/test-utils/client/src/lib.rs b/test-utils/client/src/lib.rs index 2779656558826..edf52341b006e 100644 --- a/test-utils/client/src/lib.rs +++ b/test-utils/client/src/lib.rs @@ -27,7 +27,7 @@ pub use sc_client_api::{ BadBlocks, ForkBlocks, }; pub use sc_client_db::{self, Backend}; -pub use sc_executor::{self, NativeElseWasmExecutor, WasmExecutionMethod}; +pub use sc_executor::{self, NativeElseWasmExecutor, WasmExecutionMethod, DefaultExecutor}; pub use sc_service::{client, RpcHandlers, RpcSession}; pub use sp_consensus; pub use sp_keyring::{ @@ -65,14 +65,13 @@ impl GenesisInit for () { } /// A builder for creating a test client instance. -pub struct TestClientBuilder { +pub struct TestClientBuilder { execution_strategies: ExecutionStrategies, genesis_init: G, /// The key is an unprefixed storage key, this only contains /// default child trie content. child_storage_extension: HashMap, StorageChild>, backend: Arc, - _executor: std::marker::PhantomData, keystore: Option, fork_blocks: ForkBlocks, bad_blocks: BadBlocks, @@ -80,16 +79,16 @@ pub struct TestClientBuilder Default - for TestClientBuilder, G> +impl Default + for TestClientBuilder, G> { fn default() -> Self { Self::with_default_backend() } } -impl - TestClientBuilder, G> +impl + TestClientBuilder, G> { /// Create new `TestClientBuilder` with default backend. pub fn with_default_backend() -> Self { @@ -114,8 +113,8 @@ impl } } -impl - TestClientBuilder +impl + TestClientBuilder { /// Create a new instance of the test client builder. pub fn with_backend(backend: Arc) -> Self { @@ -124,7 +123,6 @@ impl execution_strategies: ExecutionStrategies::default(), child_storage_extension: Default::default(), genesis_init: Default::default(), - _executor: Default::default(), keystore: None, fork_blocks: None, bad_blocks: None, @@ -200,16 +198,14 @@ impl } /// Build the test client with the given native executor. - pub fn build_with_executor( + pub fn build_with_executor( self, - executor: ExecutorDispatch, + executor: LocalCallExecutor, ) -> ( - client::Client, + client::Client, sc_consensus::LongestChain, ) where - ExecutorDispatch: - sc_client_api::CallExecutor + sc_executor::RuntimeVersionOf + 'static, Backend: sc_client_api::backend::Backend, >::OffchainStorage: 'static, { @@ -256,35 +252,30 @@ impl } } -impl +impl TestClientBuilder< Block, - client::LocalCallExecutor>, Backend, G, > where - D: sc_executor::NativeExecutionDispatch, { /// Build the test client with the given native executor. - pub fn build_with_native_executor( + pub fn build_with_wasm_executor( self, executor: I, ) -> ( client::Client< Backend, - client::LocalCallExecutor>, Block, - RuntimeApi, >, sc_consensus::LongestChain, ) where - I: Into>>, - D: sc_executor::NativeExecutionDispatch + 'static, + I: Into>, Backend: sc_client_api::backend::Backend + 'static, { let executor = executor.into().unwrap_or_else(|| { - NativeElseWasmExecutor::new(WasmExecutionMethod::Interpreted, None, 8, 2) + DefaultExecutor::new(WasmExecutionMethod::Interpreted, None, 8, None, 2) }); let executor = LocalCallExecutor::new( self.backend.clone(), diff --git a/utils/frame/benchmarking-cli/src/command.rs b/utils/frame/benchmarking-cli/src/command.rs index 0ced8b28ce016..3a5fe54d400a2 100644 --- a/utils/frame/benchmarking-cli/src/command.rs +++ b/utils/frame/benchmarking-cli/src/command.rs @@ -25,8 +25,8 @@ use frame_support::traits::StorageInfo; use linked_hash_map::LinkedHashMap; use sc_cli::{CliConfiguration, ExecutionStrategy, Result, SharedParams}; use sc_client_db::BenchmarkingState; -use sc_executor::NativeElseWasmExecutor; -use sc_service::{Configuration, NativeExecutionDispatch}; +use sc_executor::DefaultExecutor; +use sc_service::{Configuration}; use sp_core::offchain::{ testing::{TestOffchainExt, TestTransactionPoolExt}, OffchainDbExt, OffchainWorkerExt, TransactionPoolExt, @@ -89,12 +89,11 @@ fn combine_batches( impl BenchmarkCmd { /// Runs the command and benchmarks the chain. - pub fn run(&self, config: Configuration) -> Result<()> + pub fn run(&self, config: Configuration) -> Result<()> where BB: BlockT + Debug, <<::Header as HeaderT>::Number as std::str::FromStr>::Err: std::fmt::Debug, ::Hash: std::str::FromStr, - ExecDispatch: NativeExecutionDispatch + 'static, { if let Some(output_path) = &self.output { if !output_path.is_dir() && output_path.file_name().is_none() { @@ -134,10 +133,11 @@ impl BenchmarkCmd { )?; let state_without_tracking = BenchmarkingState::::new(genesis_storage, cache_size, self.record_proof, false)?; - let executor = NativeElseWasmExecutor::::new( + let executor = DefaultExecutor::new( wasm_method, self.heap_pages, 2, // The runtime instances cache size. + None, 2, // The runtime cache size ); diff --git a/utils/frame/rpc/system/src/lib.rs b/utils/frame/rpc/system/src/lib.rs index eb1b258c97ec6..cc7f4fa792346 100644 --- a/utils/frame/rpc/system/src/lib.rs +++ b/utils/frame/rpc/system/src/lib.rs @@ -90,8 +90,6 @@ where C: sp_api::ProvideRuntimeApi, C: HeaderBackend, C: Send + Sync + 'static, - C::Api: AccountNonceApi, - C::Api: BlockBuilder, P: TransactionPool + 'static, Block: traits::Block, AccountId: Clone + std::fmt::Display + Codec, From 14ec4aec6759c629555e0c13525930bcfbbe8c09 Mon Sep 17 00:00:00 2001 From: arkpar Date: Mon, 14 Feb 2022 00:11:24 +0100 Subject: [PATCH 02/14] Genesis built in the runtime --- Cargo.lock | 3 + bin/node/cli/Cargo.toml | 2 +- bin/node/cli/build.rs | 15 + bin/node/cli/src/chain_spec.rs | 70 +++- bin/node/cli/src/command.rs | 6 +- bin/node/runtime/Cargo.toml | 3 +- bin/node/runtime/src/lib.rs | 303 +++++++++++++++++- client/chain-spec/Cargo.toml | 2 + client/chain-spec/src/chain_spec.rs | 88 +++-- .../manual-seal/src/consensus/aura.rs | 1 - frame/assets/src/lib.rs | 3 +- frame/authority-discovery/src/lib.rs | 4 +- frame/babe/src/lib.rs | 4 +- frame/balances/src/lib.rs | 8 +- frame/collective/src/lib.rs | 2 +- frame/democracy/src/lib.rs | 3 +- frame/elections-phragmen/src/lib.rs | 5 +- frame/gilt/src/lib.rs | 2 +- frame/grandpa/src/lib.rs | 4 +- frame/im-online/src/lib.rs | 3 +- frame/indices/src/lib.rs | 3 +- frame/membership/src/lib.rs | 3 +- frame/session/src/lib.rs | 3 +- frame/society/src/lib.rs | 3 +- frame/staking/src/lib.rs | 4 +- frame/staking/src/pallet/mod.rs | 3 +- frame/sudo/src/lib.rs | 3 +- .../src/construct_runtime/expand/config.rs | 28 +- .../src/pallet/expand/genesis_build.rs | 10 - .../src/pallet/expand/genesis_config.rs | 14 +- .../src/storage/genesis_config/mod.rs | 2 +- frame/support/src/traits.rs | 1 - frame/support/src/traits/hooks.rs | 7 + frame/system/src/lib.rs | 5 +- frame/transaction-payment/src/lib.rs | 3 +- frame/transaction-storage/src/lib.rs | 3 +- frame/treasury/src/lib.rs | 3 +- frame/vesting/src/lib.rs | 3 +- primitives/api/src/lib.rs | 10 + utils/wasm-builder/src/builder.rs | 2 + 40 files changed, 522 insertions(+), 122 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 63cc6f36692e3..94f19a5ac373b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4739,6 +4739,7 @@ dependencies = [ "sp-trie", "substrate-build-script-utils", "substrate-frame-cli", + "substrate-wasm-builder", "tempfile", "tokio", "try-runtime-cli", @@ -7865,12 +7866,14 @@ dependencies = [ "memmap2 0.5.0", "parity-scale-codec", "sc-chain-spec-derive", + "sc-executor", "sc-network", "sc-telemetry", "serde", "serde_json", "sp-core", "sp-runtime", + "sp-state-machine", ] [[package]] diff --git a/bin/node/cli/Cargo.toml b/bin/node/cli/Cargo.toml index d156c73a9ccb2..af564edbd2ec3 100644 --- a/bin/node/cli/Cargo.toml +++ b/bin/node/cli/Cargo.toml @@ -78,7 +78,6 @@ sc-authority-discovery = { version = "0.10.0-dev", path = "../../../client/autho sc-sync-state-rpc = { version = "0.10.0-dev", path = "../../../client/sync-state-rpc" } # node-specific dependencies -# node-runtime = { version = "3.0.0-dev", path = "../runtime" } node-rpc = { version = "3.0.0-dev", path = "../rpc" } node-primitives = { version = "2.0.0", path = "../primitives" } @@ -133,6 +132,7 @@ substrate-frame-cli = { version = "4.0.0-dev", optional = true, path = "../../.. try-runtime-cli = { version = "0.10.0-dev", optional = true, path = "../../../utils/frame/try-runtime/cli" } sc-cli = { version = "0.10.0-dev", path = "../../../client/cli", optional = true } pallet-balances = { version = "4.0.0-dev", path = "../../../frame/balances" } +substrate-wasm-builder = { version = "5.0.0-dev", path = "../../../utils/wasm-builder" } [features] default = ["cli"] diff --git a/bin/node/cli/build.rs b/bin/node/cli/build.rs index 6a010d8858fe5..008332c6f746f 100644 --- a/bin/node/cli/build.rs +++ b/bin/node/cli/build.rs @@ -16,11 +16,26 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use substrate_wasm_builder::WasmBuilder; + fn main() { + build_runtime(); + #[cfg(feature = "cli")] cli::main(); } +fn build_runtime() { + let mut path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); + path.push("../runtime/Cargo.toml"); + eprintln!("CAN: {:?}", path.canonicalize().unwrap()); + WasmBuilder::new() + .with_project(path.canonicalize().unwrap()).unwrap() + .export_heap_base() + .import_memory() + .build() +} + #[cfg(feature = "cli")] mod cli { include!("src/cli.rs"); diff --git a/bin/node/cli/src/chain_spec.rs b/bin/node/cli/src/chain_spec.rs index c6a1ceb1531dc..fdce351c1749c 100644 --- a/bin/node/cli/src/chain_spec.rs +++ b/bin/node/cli/src/chain_spec.rs @@ -19,9 +19,26 @@ //! Substrate chain configurations. use sc_chain_spec::ChainSpecExtension; +use sc_service::ChainType; +use sc_telemetry::TelemetryEndpoints; use serde::{Deserialize, Serialize}; pub use node_primitives::{AccountId, Balance, Signature, Block}; +const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/"; + +mod runtime { + include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); + /// Wasm binary unwrapped. If built with `SKIP_WASM_BUILD`, the function panics. + pub fn wasm_binary_unwrap() -> &'static [u8] { + WASM_BINARY.expect( + "Development wasm binary is not available. This means the client is built with \ + `SKIP_WASM_BUILD` flag and it is only usable for production chains. Please rebuild with \ + the flag disabled.", + ) + } +} + + /// Node `ChainSpec` extensions. /// /// Additional parameters for some Substrate core modules, @@ -45,20 +62,61 @@ pub fn flaming_fir_config() -> Result { } /// Development config (single validator Alice) -pub fn development_config() -> Result { - ChainSpec::from_json_bytes(&include_bytes!("../res/flaming-fir.json")[..]) +pub fn development_config() -> ChainSpec { + ChainSpec::from_runtime( + "Development", + "dev", + ChainType::Development, + runtime::wasm_binary_unwrap(), + "Genesis_build_dev", + vec![], + None, + None, + None, + None, + Default::default(), + ) } /// Staging testnet config. -pub fn staging_testnet_config() -> Result { - ChainSpec::from_json_bytes(&include_bytes!("../res/flaming-fir.json")[..]) +pub fn staging_testnet_config() -> ChainSpec { + let boot_nodes = vec![]; + ChainSpec::from_runtime( + "Staging Testnet", + "staging_testnet", + ChainType::Live, + runtime::wasm_binary_unwrap(), + "Genesis_build_genesis", + boot_nodes, + Some( + TelemetryEndpoints::new(vec![(STAGING_TELEMETRY_URL.to_string(), 0)]) + .expect("Staging telemetry url is valid; qed"), + ), + None, + None, + None, + Default::default(), + ) } /// Local testnet config (multivalidator Alice + Bob) -pub fn local_testnet_config() -> Result { - ChainSpec::from_json_bytes(&include_bytes!("../res/flaming-fir.json")[..]) +pub fn local_testnet_config() -> ChainSpec { + ChainSpec::from_runtime( + "Local Testnet", + "local_testnet", + ChainType::Local, + runtime::wasm_binary_unwrap(), + "Genesis_build_genesis", + vec![], + None, + None, + None, + None, + Default::default(), + ) } + #[cfg(test)] pub(crate) mod tests { use super::*; diff --git a/bin/node/cli/src/command.rs b/bin/node/cli/src/command.rs index dc3705b5e4d9d..e6d7bd4015fc0 100644 --- a/bin/node/cli/src/command.rs +++ b/bin/node/cli/src/command.rs @@ -53,10 +53,10 @@ impl SubstrateCli for Cli { "Please specify which chain you want to run, e.g. --dev or --chain=local" .into(), ), - "dev" => Box::new(chain_spec::development_config()?), - "local" => Box::new(chain_spec::local_testnet_config()?), + "dev" => Box::new(chain_spec::development_config()), + "local" => Box::new(chain_spec::local_testnet_config()), "fir" | "flaming-fir" => Box::new(chain_spec::flaming_fir_config()?), - "staging" => Box::new(chain_spec::staging_testnet_config()?), + "staging" => Box::new(chain_spec::staging_testnet_config()), path => Box::new(chain_spec::ChainSpec::from_json_file(std::path::PathBuf::from(path))?), }; diff --git a/bin/node/runtime/Cargo.toml b/bin/node/runtime/Cargo.toml index 2aad40b4f121d..ca183e9a93b87 100644 --- a/bin/node/runtime/Cargo.toml +++ b/bin/node/runtime/Cargo.toml @@ -20,7 +20,7 @@ codec = { package = "parity-scale-codec", version = "2.2.0", default-features = ] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } static_assertions = "1.1.0" -hex-literal = { version = "0.3.4", optional = true } +hex-literal = { version = "0.3.4" } log = { version = "0.4.14", default-features = false } # primitives @@ -223,7 +223,6 @@ runtime-benchmarks = [ "pallet-uniques/runtime-benchmarks", "pallet-vesting/runtime-benchmarks", "frame-system-benchmarking", - "hex-literal", ] try-runtime = [ "frame-executive/try-runtime", diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index 1b72c23030b3a..313483443cff8 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -22,6 +22,7 @@ // `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256. #![recursion_limit = "256"] +use hex_literal::hex; use codec::{Decode, Encode, MaxEncodedLen}; use frame_election_provider_support::onchain; use frame_support::{ @@ -29,7 +30,7 @@ use frame_support::{ traits::{ ConstU128, ConstU16, ConstU32, Currency, EnsureOneOf, EqualPrivilegeOnly, Everything, Imbalance, InstanceFilter, KeyOwnerProofSystem, LockIdentifier, Nothing, OnUnbalanced, - U128CurrencyToVote, + U128CurrencyToVote, GenesisBuild, }, weights::{ constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND}, @@ -47,6 +48,7 @@ use pallet_contracts::weights::WeightInfo; use pallet_grandpa::{ fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList, }; +use pallet_babe::{AuthorityId as BabeId}; use pallet_im_online::sr25519::AuthorityId as ImOnlineId; use pallet_session::historical as pallet_session_historical; pub use pallet_transaction_payment::{CurrencyAdapter, Multiplier, TargetedFeeAdjustment}; @@ -54,10 +56,11 @@ use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo}; use sp_api::impl_runtime_apis; use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId; use sp_core::{ - crypto::KeyTypeId, + crypto::{UncheckedInto, KeyTypeId}, u32_trait::{_1, _2, _3, _4, _5}, OpaqueMetadata, }; +use sp_core::{sr25519, ed25519}; use sp_inherents::{CheckInherentsResult, InherentData}; use sp_runtime::{ create_runtime_str, @@ -1855,8 +1858,304 @@ impl_runtime_apis! { Ok(batches) } } + + impl sp_api::Genesis for Runtime { + fn build_dev() { + testnet_genesis( + &[authority_keys(ALICE_SR25519, ALICE_STASH, ALICE_ED25519)], + &[], + ALICE_SR25519.into(), + None, + ).execute() + } + + fn build_local() { + testnet_genesis( + &[ + authority_keys(ALICE_SR25519, ALICE_STASH, ALICE_ED25519), + authority_keys(BOB_SR25519, BOB_STASH, BOB_ED25519), + ], + &[], + ALICE_SR25519.into(), + None, + ).execute() + } + + fn build_genesis() { + // stash, controller, session-key + // generated with secret: + // for i in 1 2 3 4 ; do for j in stash controller; do subkey inspect "$secret"/fir/$j/$i; done; done + // + // and + // + // for i in 1 2 3 4 ; do for j in session; do subkey --ed25519 inspect "$secret"//fir//$j//$i; done; done + + let initial_authorities: &[( + AccountId, + AccountId, + GrandpaId, + BabeId, + ImOnlineId, + AuthorityDiscoveryId, + )] = &[ + ( + // 5Fbsd6WXDGiLTxunqeK5BATNiocfCqu9bS1yArVjCgeBLkVy + hex!["9c7a2ee14e565db0c69f78c7b4cd839fbf52b607d867e9e9c5a79042898a0d12"].into(), + // 5EnCiV7wSHeNhjW3FSUwiJNkcc2SBkPLn5Nj93FmbLtBjQUq + hex!["781ead1e2fa9ccb74b44c19d29cb2a7a4b5be3972927ae98cd3877523976a276"].into(), + // 5Fb9ayurnxnaXj56CjmyQLBiadfRCqUbL2VWNbbe1nZU6wiC + hex!["9becad03e6dcac03cee07edebca5475314861492cdfc96a2144a67bbe9699332"] + .unchecked_into(), + // 5EZaeQ8djPcq9pheJUhgerXQZt9YaHnMJpiHMRhwQeinqUW8 + hex!["6e7e4eb42cbd2e0ab4cae8708ce5509580b8c04d11f6758dbf686d50fe9f9106"] + .unchecked_into(), + // 5EZaeQ8djPcq9pheJUhgerXQZt9YaHnMJpiHMRhwQeinqUW8 + hex!["6e7e4eb42cbd2e0ab4cae8708ce5509580b8c04d11f6758dbf686d50fe9f9106"] + .unchecked_into(), + // 5EZaeQ8djPcq9pheJUhgerXQZt9YaHnMJpiHMRhwQeinqUW8 + hex!["6e7e4eb42cbd2e0ab4cae8708ce5509580b8c04d11f6758dbf686d50fe9f9106"] + .unchecked_into(), + ), + ( + // 5ERawXCzCWkjVq3xz1W5KGNtVx2VdefvZ62Bw1FEuZW4Vny2 + hex!["68655684472b743e456907b398d3a44c113f189e56d1bbfd55e889e295dfde78"].into(), + // 5Gc4vr42hH1uDZc93Nayk5G7i687bAQdHHc9unLuyeawHipF + hex!["c8dc79e36b29395413399edaec3e20fcca7205fb19776ed8ddb25d6f427ec40e"].into(), + // 5EockCXN6YkiNCDjpqqnbcqd4ad35nU4RmA1ikM4YeRN4WcE + hex!["7932cff431e748892fa48e10c63c17d30f80ca42e4de3921e641249cd7fa3c2f"] + .unchecked_into(), + // 5DhLtiaQd1L1LU9jaNeeu9HJkP6eyg3BwXA7iNMzKm7qqruQ + hex!["482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e"] + .unchecked_into(), + // 5DhLtiaQd1L1LU9jaNeeu9HJkP6eyg3BwXA7iNMzKm7qqruQ + hex!["482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e"] + .unchecked_into(), + // 5DhLtiaQd1L1LU9jaNeeu9HJkP6eyg3BwXA7iNMzKm7qqruQ + hex!["482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e"] + .unchecked_into(), + ), + ( + // 5DyVtKWPidondEu8iHZgi6Ffv9yrJJ1NDNLom3X9cTDi98qp + hex!["547ff0ab649283a7ae01dbc2eb73932eba2fb09075e9485ff369082a2ff38d65"].into(), + // 5FeD54vGVNpFX3PndHPXJ2MDakc462vBCD5mgtWRnWYCpZU9 + hex!["9e42241d7cd91d001773b0b616d523dd80e13c6c2cab860b1234ef1b9ffc1526"].into(), + // 5E1jLYfLdUQKrFrtqoKgFrRvxM3oQPMbf6DfcsrugZZ5Bn8d + hex!["5633b70b80a6c8bb16270f82cca6d56b27ed7b76c8fd5af2986a25a4788ce440"] + .unchecked_into(), + // 5DhKqkHRkndJu8vq7pi2Q5S3DfftWJHGxbEUNH43b46qNspH + hex!["482a3389a6cf42d8ed83888cfd920fec738ea30f97e44699ada7323f08c3380a"] + .unchecked_into(), + // 5DhKqkHRkndJu8vq7pi2Q5S3DfftWJHGxbEUNH43b46qNspH + hex!["482a3389a6cf42d8ed83888cfd920fec738ea30f97e44699ada7323f08c3380a"] + .unchecked_into(), + // 5DhKqkHRkndJu8vq7pi2Q5S3DfftWJHGxbEUNH43b46qNspH + hex!["482a3389a6cf42d8ed83888cfd920fec738ea30f97e44699ada7323f08c3380a"] + .unchecked_into(), + ), + ( + // 5HYZnKWe5FVZQ33ZRJK1rG3WaLMztxWrrNDb1JRwaHHVWyP9 + hex!["f26cdb14b5aec7b2789fd5ca80f979cef3761897ae1f37ffb3e154cbcc1c2663"].into(), + // 5EPQdAQ39WQNLCRjWsCk5jErsCitHiY5ZmjfWzzbXDoAoYbn + hex!["66bc1e5d275da50b72b15de072a2468a5ad414919ca9054d2695767cf650012f"].into(), + // 5DMa31Hd5u1dwoRKgC4uvqyrdK45RHv3CpwvpUC1EzuwDit4 + hex!["3919132b851ef0fd2dae42a7e734fe547af5a6b809006100f48944d7fae8e8ef"] + .unchecked_into(), + // 5C4vDQxA8LTck2xJEy4Yg1hM9qjDt4LvTQaMo4Y8ne43aU6x + hex!["00299981a2b92f878baaf5dbeba5c18d4e70f2a1fcd9c61b32ea18daf38f4378"] + .unchecked_into(), + // 5C4vDQxA8LTck2xJEy4Yg1hM9qjDt4LvTQaMo4Y8ne43aU6x + hex!["00299981a2b92f878baaf5dbeba5c18d4e70f2a1fcd9c61b32ea18daf38f4378"] + .unchecked_into(), + // 5C4vDQxA8LTck2xJEy4Yg1hM9qjDt4LvTQaMo4Y8ne43aU6x + hex!["00299981a2b92f878baaf5dbeba5c18d4e70f2a1fcd9c61b32ea18daf38f4378"] + .unchecked_into(), + ), + ]; + + // generated with secret: subkey inspect "$secret"/fir + let root_key: AccountId = hex![ + // 5Ff3iXP75ruzroPWRP2FYBHWnmGGBSb63857BgnzCoXNxfPo + "9ee5e5bdc0ec239eb164f865ecc345ce4c88e76ee002e0f7e318097347471809" + ] + .into(); + + let endowed_accounts: Vec = vec![root_key.clone()]; + testnet_genesis(initial_authorities, &[], root_key, Some(endowed_accounts)).execute() + } + } } +const ALICE_SR25519: sr25519::Public = sr25519::Public(hex!["d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"]); +const ALICE_ED25519: ed25519::Public = ed25519::Public(hex!["88dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee"]); +const BOB_SR25519: sr25519::Public = sr25519::Public(hex!["8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48"]); +const BOB_ED25519: ed25519::Public = ed25519::Public(hex!["d17c2d7823ebf260fd138f2d7e27d114c0145d968b5ff5006125f2414fadae69"]); + +const CHARLIE_SR25519: sr25519::Public = sr25519::Public(hex!["90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22"]); +const DAVE_SR25519: sr25519::Public = sr25519::Public(hex!["306721211d5404bd9da88e0204360a1a9ab8b87c66c1bc2fcdd37f3c2222cc20"]); +const EVE_SR25519: sr25519::Public = sr25519::Public(hex!["e659a7a1628cdd93febc04a4e0646ea20e9f5f0ce097d9a05290d4a9e054df4e"]); +const FERDIE_SR25519: sr25519::Public = sr25519::Public(hex!["1cbd2d43530a44705ad088af313e18f80b53ef16b36177cd4b77b846f2a5f07c"]); + +const ALICE_STASH: sr25519::Public = sr25519::Public(hex!["be5ddb1579b72e84524fc29e78609e3caf42e85aa118ebfe0b0ad404b5bdd25f"]); +const BOB_STASH: sr25519::Public = sr25519::Public(hex!["fe65717dad0447d715f660a0a58411de509b42e6efb8375f562f58a554d5860e"]); +const CHARLIE_STASH: sr25519::Public = sr25519::Public(hex!["1e07379407fecc4b89eb7dbd287c2c781cfb1907a96947a3eb18e4f8e7198625"]); +const DAVE_STASH: sr25519::Public = sr25519::Public(hex!["e860f1b1c7227f7c22602f53f15af80747814dffd839719731ee3bba6edc126c"]); +const EVE_STASH: sr25519::Public = sr25519::Public(hex!["8ac59e11963af19174d0b94d5d78041c233f55d2e19324665bafdfb62925af2d"]); +const FERDIE_STASH: sr25519::Public = sr25519::Public(hex!["101191192fc877c24d725b337120fa3edc63d227bbc92705db1e2cb65f56981a"]); + + +/// Helper function to generate stash, controller and session keys +pub fn authority_keys(sr25519_key: sr25519::Public, stash_key: sr25519::Public, ed25519_key: ed25519::Public) + -> (AccountId, AccountId, GrandpaId, BabeId, ImOnlineId, AuthorityDiscoveryId) { + ( + sr25519_key.into(), + stash_key.into(), + ed25519_key.into(), + sr25519_key.into(), + sr25519_key.into(), + sr25519_key.into(), + ) +} + +fn session_keys( + grandpa: GrandpaId, + babe: BabeId, + im_online: ImOnlineId, + authority_discovery: AuthorityDiscoveryId, +) -> SessionKeys { + SessionKeys { grandpa, babe, im_online, authority_discovery } +} + +/// Helper function to create GenesisConfig for testing +pub fn testnet_genesis( + initial_authorities: &[( + AccountId, + AccountId, + GrandpaId, + BabeId, + ImOnlineId, + AuthorityDiscoveryId, + )], + initial_nominators: &[AccountId], + root_key: AccountId, + endowed_accounts: Option>, +) -> GenesisConfig { + let mut endowed_accounts: Vec = endowed_accounts.unwrap_or_else(|| { + vec![ + ALICE_SR25519.into(), + BOB_SR25519.into(), + CHARLIE_SR25519.into(), + DAVE_SR25519.into(), + EVE_SR25519.into(), + FERDIE_SR25519.into(), + ALICE_STASH.into(), + BOB_STASH.into(), + CHARLIE_STASH.into(), + DAVE_STASH.into(), + EVE_STASH.into(), + FERDIE_STASH.into(), + ] + }); + // endow all authorities and nominators. + initial_authorities + .iter() + .map(|x| &x.0) + .chain(initial_nominators.iter()) + .for_each(|x| { + if !endowed_accounts.contains(x) { + endowed_accounts.push(x.clone()) + } + }); + + // stakers: all validators and nominators. + let stakers = initial_authorities + .iter() + .map(|x| (x.0.clone(), x.1.clone(), STASH, pallet_staking::StakerStatus::Validator)) + .chain(initial_nominators.iter().map(|x| { + let nominations = initial_authorities + .iter() + .map(|choice| choice.0.clone()) + .collect::>(); + (x.clone(), x.clone(), STASH, pallet_staking::StakerStatus::Nominator(nominations)) + })) + .collect::>(); + + let num_endowed_accounts = endowed_accounts.len(); + + const ENDOWMENT: Balance = 10_000_000 * DOLLARS; + const STASH: Balance = ENDOWMENT / 1000; + + GenesisConfig { + system: SystemConfig { code: vec![] }, + balances: BalancesConfig { + balances: endowed_accounts.iter().cloned().map(|x| (x, ENDOWMENT)).collect(), + }, + indices: IndicesConfig { indices: vec![] }, + session: SessionConfig { + keys: initial_authorities + .iter() + .map(|x| { + ( + x.0.clone(), + x.0.clone(), + session_keys(x.2.clone(), x.3.clone(), x.4.clone(), x.5.clone()), + ) + }) + .collect::>(), + }, + staking: StakingConfig { + validator_count: initial_authorities.len() as u32, + minimum_validator_count: initial_authorities.len() as u32, + invulnerables: initial_authorities.iter().map(|x| x.0.clone()).collect(), + slash_reward_fraction: Perbill::from_percent(10), + stakers, + ..Default::default() + }, + democracy: DemocracyConfig::default(), + elections: ElectionsConfig { + members: endowed_accounts + .iter() + .take((num_endowed_accounts + 1) / 2) + .cloned() + .map(|member| (member, STASH)) + .collect(), + }, + council: CouncilConfig::default(), + technical_committee: TechnicalCommitteeConfig { + members: endowed_accounts + .iter() + .take((num_endowed_accounts + 1) / 2) + .cloned() + .collect(), + phantom: Default::default(), + }, + sudo: SudoConfig { key: Some(root_key) }, + babe: BabeConfig { + authorities: vec![], + epoch_config: Some(BABE_GENESIS_EPOCH_CONFIG), + }, + im_online: ImOnlineConfig { keys: vec![] }, + authority_discovery: AuthorityDiscoveryConfig { keys: vec![] }, + grandpa: GrandpaConfig { authorities: vec![] }, + technical_membership: Default::default(), + treasury: Default::default(), + society: SocietyConfig { + members: endowed_accounts + .iter() + .take((num_endowed_accounts + 1) / 2) + .cloned() + .collect(), + pot: 0, + max_members: 999, + }, + vesting: Default::default(), + assets: Default::default(), + gilt: Default::default(), + transaction_storage: Default::default(), + transaction_payment: Default::default(), + } +} + + #[cfg(test)] mod tests { use super::*; diff --git a/client/chain-spec/Cargo.toml b/client/chain-spec/Cargo.toml index 9b299f00a2147..e4efe2f4483d3 100644 --- a/client/chain-spec/Cargo.toml +++ b/client/chain-spec/Cargo.toml @@ -16,7 +16,9 @@ targets = ["x86_64-unknown-linux-gnu"] sc-chain-spec-derive = { version = "4.0.0-dev", path = "./derive" } impl-trait-for-tuples = "0.2.1" sc-network = { version = "0.10.0-dev", path = "../network" } +sc-executor = { version = "0.10.0-dev", path = "../executor" } sp-core = { version = "5.0.0", path = "../../primitives/core" } +sp-state-machine = { version = "0.11.0", path = "../../primitives/state-machine" } serde = { version = "1.0.136", features = ["derive"] } serde_json = "1.0.74" sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" } diff --git a/client/chain-spec/src/chain_spec.rs b/client/chain-spec/src/chain_spec.rs index 2412a7cdf83f0..057247693e8e0 100644 --- a/client/chain-spec/src/chain_spec.rs +++ b/client/chain-spec/src/chain_spec.rs @@ -22,10 +22,12 @@ use crate::{extension::GetExtension, ChainType, Properties, RuntimeGenesis}; use sc_network::config::MultiaddrWithPeerId; use sc_telemetry::TelemetryEndpoints; +use sc_executor::Externalities; use serde::{Deserialize, Serialize}; use serde_json as json; use sp_core::{ - storage::{ChildInfo, Storage, StorageChild, StorageData, StorageKey}, + traits::CodeExecutor, + storage::{ChildInfo, Storage, StorageChild, StorageData, StorageKey, well_known_keys}, Bytes, }; use sp_runtime::BuildStorage; @@ -36,6 +38,10 @@ enum GenesisSource { Binary(Cow<'static, [u8]>), Factory(Arc G + Send + Sync>), Storage(Storage), + Runtime { + code: &'static [u8], + method: &'static str + }, } impl Clone for GenesisSource { @@ -45,11 +51,38 @@ impl Clone for GenesisSource { Self::Binary(ref d) => Self::Binary(d.clone()), Self::Factory(ref f) => Self::Factory(f.clone()), Self::Storage(ref s) => Self::Storage(s.clone()), + Self::Runtime { code, method } => Self::Runtime { code, method }, } } } impl GenesisSource { + + fn from_storage(storage: &Storage) -> Genesis { + let top = storage + .top + .iter() + .map(|(k, v)| (StorageKey(k.clone()), StorageData(v.clone()))) + .collect(); + + let children_default = storage + .children_default + .iter() + .map(|(k, child)| { + ( + StorageKey(k.clone()), + child + .data + .iter() + .map(|(k, v)| (StorageKey(k.clone()), StorageData(v.clone()))) + .collect(), + ) + }) + .collect(); + + Genesis::Raw(RawGenesis { top, children_default }) + } + fn resolve(&self) -> Result, String> { #[derive(Serialize, Deserialize)] struct GenesisContainer { @@ -71,30 +104,28 @@ impl GenesisSource { Ok(genesis.genesis) }, Self::Factory(f) => Ok(Genesis::Runtime(f())), - Self::Storage(storage) => { - let top = storage - .top - .iter() - .map(|(k, v)| (StorageKey(k.clone()), StorageData(v.clone()))) - .collect(); - - let children_default = storage - .children_default - .iter() - .map(|(k, child)| { - ( - StorageKey(k.clone()), - child - .data - .iter() - .map(|(k, v)| (StorageKey(k.clone()), StorageData(v.clone()))) - .collect(), - ) - }) - .collect(); - - Ok(Genesis::Raw(RawGenesis { top, children_default })) - }, + Self::Storage(storage) => Ok(Self::from_storage(storage)), + Self::Runtime { code, method } => { + let mut ext = sp_state_machine::BasicExternalities::default(); + let code_fetcher = sp_core::traits::WrappedRuntimeCode((*code).into()); + let runtime_code = sp_core::traits::RuntimeCode { + code_fetcher: &code_fetcher, + heap_pages: None, + hash: Default::default(), + }; + let executor = sc_executor::DefaultExecutor::new( + sc_executor::WasmExecutionMethod::Interpreted, None, 1, None, 1 + ); + + let (r, _) = executor.call::<(), fn() -> Result<(), _>>(&mut ext, &runtime_code, method, &[], false, None); + if let Err(e) = r { + return Err(format!("Error building genesis with {}: {}", method, e)); + } + + ext.set_storage(well_known_keys::CODE.to_vec(), code.to_vec()); + let storage = ext.into_storages(); + Ok(Self::from_storage(&storage)) + } } } } @@ -259,11 +290,12 @@ impl ChainSpec { } /// Create hardcoded spec. - pub fn from_genesis G + 'static + Send + Sync>( + pub fn from_runtime( name: &str, id: &str, chain_type: ChainType, - constructor: F, + code: &'static [u8], + method: &'static str, boot_nodes: Vec, telemetry_endpoints: Option, protocol_id: Option<&str>, @@ -286,7 +318,7 @@ impl ChainSpec { code_substitutes: BTreeMap::new(), }; - ChainSpec { client_spec, genesis: GenesisSource::Factory(Arc::new(constructor)) } + ChainSpec { client_spec, genesis: GenesisSource::Runtime { code, method } } } /// Type of the chain. diff --git a/client/consensus/manual-seal/src/consensus/aura.rs b/client/consensus/manual-seal/src/consensus/aura.rs index 81377ad903732..020f75e494ce0 100644 --- a/client/consensus/manual-seal/src/consensus/aura.rs +++ b/client/consensus/manual-seal/src/consensus/aura.rs @@ -28,7 +28,6 @@ use sp_blockchain::{HeaderBackend, HeaderMetadata}; use sp_consensus_aura::{ digests::CompatibleDigestItem, sr25519::{AuthoritySignature}, - AuraApi, }; use sp_inherents::InherentData; use sp_runtime::{traits::Block as BlockT, Digest, DigestItem}; diff --git a/frame/assets/src/lib.rs b/frame/assets/src/lib.rs index 71ba7b4d24910..7db6f8b31d52d 100644 --- a/frame/assets/src/lib.rs +++ b/frame/assets/src/lib.rs @@ -155,7 +155,7 @@ use frame_support::{ pallet_prelude::DispatchResultWithPostInfo, traits::{ tokens::{fungibles, DepositConsequence, WithdrawConsequence}, - BalanceStatus::Reserved, + BalanceStatus::Reserved, GenesisBuild, Currency, ReservableCurrency, StoredMap, }, }; @@ -306,7 +306,6 @@ pub mod pallet { pub accounts: Vec<(T::AssetId, T::AccountId, T::Balance)>, } - #[cfg(feature = "std")] impl, I: 'static> Default for GenesisConfig { fn default() -> Self { Self { diff --git a/frame/authority-discovery/src/lib.rs b/frame/authority-discovery/src/lib.rs index a56d8e785f6ac..6657e82c3d130 100644 --- a/frame/authority-discovery/src/lib.rs +++ b/frame/authority-discovery/src/lib.rs @@ -24,7 +24,7 @@ #![cfg_attr(not(feature = "std"), no_std)] use frame_support::{ - traits::{Get, OneSessionHandler}, + traits::{Get, OneSessionHandler, GenesisBuild}, WeakBoundedVec, }; use sp_authority_discovery::AuthorityId; @@ -60,7 +60,7 @@ pub mod pallet { pub(super) type NextKeys = StorageValue<_, WeakBoundedVec, ValueQuery>; - #[cfg_attr(feature = "std", derive(Default))] + #[derive(Default)] #[pallet::genesis_config] pub struct GenesisConfig { pub keys: Vec, diff --git a/frame/babe/src/lib.rs b/frame/babe/src/lib.rs index f673c8b43bee0..2170671584eed 100644 --- a/frame/babe/src/lib.rs +++ b/frame/babe/src/lib.rs @@ -26,7 +26,7 @@ use frame_support::{ dispatch::DispatchResultWithPostInfo, traits::{ ConstU32, DisabledValidators, FindAuthor, Get, KeyOwnerProofSystem, OnTimestampSet, - OneSessionHandler, + OneSessionHandler, GenesisBuild, }, weights::{Pays, Weight}, BoundedVec, WeakBoundedVec, @@ -309,7 +309,7 @@ pub mod pallet { #[pallet::storage] pub(super) type NextEpochConfig = StorageValue<_, BabeEpochConfiguration>; - #[cfg_attr(feature = "std", derive(Default))] + #[derive(Default)] #[pallet::genesis_config] pub struct GenesisConfig { pub authorities: Vec<(AuthorityId, BabeAuthorityWeight)>, diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index 37114f385aa7f..9bede9163fec3 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -163,8 +163,6 @@ pub mod weights; pub use self::imbalances::{NegativeImbalance, PositiveImbalance}; use codec::{Codec, Decode, Encode, MaxEncodedLen}; -#[cfg(feature = "std")] -use frame_support::traits::GenesisBuild; use frame_support::{ ensure, pallet_prelude::DispatchResult, @@ -173,7 +171,7 @@ use frame_support::{ Currency, DefensiveSaturating, ExistenceRequirement, ExistenceRequirement::{AllowDeath, KeepAlive}, Get, Imbalance, LockIdentifier, LockableCurrency, NamedReservableCurrency, OnUnbalanced, - ReservableCurrency, SignedImbalance, StoredMap, TryDrop, WithdrawReasons, + ReservableCurrency, SignedImbalance, StoredMap, TryDrop, WithdrawReasons, GenesisBuild, }, WeakBoundedVec, }; @@ -560,7 +558,6 @@ pub mod pallet { pub balances: Vec<(T::AccountId, T::Balance)>, } - #[cfg(feature = "std")] impl, I: 'static> Default for GenesisConfig { fn default() -> Self { Self { balances: Default::default() } @@ -582,13 +579,12 @@ pub mod pallet { ) } - // ensure no duplicates exist. let endowed_accounts = self .balances .iter() .map(|(x, _)| x) .cloned() - .collect::>(); + .collect::>(); assert!( endowed_accounts.len() == self.balances.len(), diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index 49328aa0bdc68..893e61effa1fa 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -54,6 +54,7 @@ use frame_support::{ ensure, traits::{ Backing, ChangeMembers, EnsureOrigin, Get, GetBacking, InitializeMembers, StorageVersion, + GenesisBuild, }, weights::{GetDispatchInfo, Weight}, }; @@ -215,7 +216,6 @@ pub mod pallet { pub members: Vec, } - #[cfg(feature = "std")] impl, I: 'static> Default for GenesisConfig { fn default() -> Self { Self { phantom: Default::default(), members: Default::default() } diff --git a/frame/democracy/src/lib.rs b/frame/democracy/src/lib.rs index b578df5909306..b0cb1485e4d6e 100644 --- a/frame/democracy/src/lib.rs +++ b/frame/democracy/src/lib.rs @@ -159,7 +159,7 @@ use frame_support::{ defensive_prelude::*, schedule::{DispatchTime, Named as ScheduleNamed}, BalanceStatus, Currency, Get, LockIdentifier, LockableCurrency, OnUnbalanced, - ReservableCurrency, WithdrawReasons, + ReservableCurrency, WithdrawReasons, GenesisBuild, }, weights::Weight, }; @@ -474,7 +474,6 @@ pub mod pallet { _phantom: sp_std::marker::PhantomData, } - #[cfg(feature = "std")] impl Default for GenesisConfig { fn default() -> Self { GenesisConfig { _phantom: Default::default() } diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index 4758c793cfefd..df7fcbbb151f9 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -104,7 +104,7 @@ use frame_support::{ traits::{ defensive_prelude::*, ChangeMembers, Contains, ContainsLengthBound, Currency, CurrencyToVote, Get, InitializeMembers, LockIdentifier, LockableCurrency, OnUnbalanced, - ReservableCurrency, SortedMembers, StorageVersion, WithdrawReasons, + ReservableCurrency, SortedMembers, StorageVersion, WithdrawReasons, GenesisBuild, }, weights::Weight, }; @@ -655,7 +655,6 @@ pub mod pallet { pub members: Vec<(T::AccountId, BalanceOf)>, } - #[cfg(feature = "std")] impl Default for GenesisConfig { fn default() -> Self { Self { members: Default::default() } @@ -686,7 +685,7 @@ pub mod pallet { Members::::mutate(|members| { match members.binary_search_by(|m| m.who.cmp(member)) { Ok(_) => { - panic!("Duplicate member in elections-phragmen genesis: {}", member) + panic!("Duplicate member in elections-phragmen genesis: {:?}", member) }, Err(pos) => members.insert( pos, diff --git a/frame/gilt/src/lib.rs b/frame/gilt/src/lib.rs index 8956e04857f2c..d07842d3bc677 100644 --- a/frame/gilt/src/lib.rs +++ b/frame/gilt/src/lib.rs @@ -79,7 +79,7 @@ pub mod pallet { pub use crate::weights::WeightInfo; use frame_support::{ pallet_prelude::*, - traits::{Currency, DefensiveSaturating, OnUnbalanced, ReservableCurrency}, + traits::{Currency, DefensiveSaturating, OnUnbalanced, ReservableCurrency, GenesisBuild}, }; use frame_system::pallet_prelude::*; use sp_arithmetic::{PerThing, Perquintill}; diff --git a/frame/grandpa/src/lib.rs b/frame/grandpa/src/lib.rs index 68d4cf26a2e23..ac44e9e3f5442 100644 --- a/frame/grandpa/src/lib.rs +++ b/frame/grandpa/src/lib.rs @@ -43,7 +43,7 @@ use frame_support::{ dispatch::DispatchResultWithPostInfo, pallet_prelude::Get, storage, - traits::{KeyOwnerProofSystem, OneSessionHandler, StorageVersion}, + traits::{KeyOwnerProofSystem, OneSessionHandler, StorageVersion, GenesisBuild}, weights::{Pays, Weight}, WeakBoundedVec, }; @@ -326,7 +326,7 @@ pub mod pallet { #[pallet::getter(fn session_for_set)] pub(super) type SetIdSession = StorageMap<_, Twox64Concat, SetId, SessionIndex>; - #[cfg_attr(feature = "std", derive(Default))] + #[derive(Default)] #[pallet::genesis_config] pub struct GenesisConfig { pub authorities: AuthorityList, diff --git a/frame/im-online/src/lib.rs b/frame/im-online/src/lib.rs index e2213ef4169b1..9bf396006dc57 100644 --- a/frame/im-online/src/lib.rs +++ b/frame/im-online/src/lib.rs @@ -86,7 +86,7 @@ use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ traits::{ EstimateNextSessionRotation, Get, OneSessionHandler, ValidatorSet, - ValidatorSetWithIdentification, WrapperOpaque, + ValidatorSetWithIdentification, WrapperOpaque, GenesisBuild, }, BoundedSlice, WeakBoundedVec, }; @@ -447,7 +447,6 @@ pub mod pallet { pub keys: Vec, } - #[cfg(feature = "std")] impl Default for GenesisConfig { fn default() -> Self { GenesisConfig { keys: Default::default() } diff --git a/frame/indices/src/lib.rs b/frame/indices/src/lib.rs index 9c9e3580f2c04..b36056724b5e9 100644 --- a/frame/indices/src/lib.rs +++ b/frame/indices/src/lib.rs @@ -26,7 +26,7 @@ mod tests; pub mod weights; use codec::Codec; -use frame_support::traits::{BalanceStatus::Reserved, Currency, ReservableCurrency}; +use frame_support::traits::{BalanceStatus::Reserved, Currency, ReservableCurrency, GenesisBuild}; use sp_runtime::{ traits::{AtLeast32Bit, LookupError, Saturating, StaticLookup, Zero}, MultiAddress, @@ -298,7 +298,6 @@ pub mod pallet { pub indices: Vec<(T::AccountIndex, T::AccountId)>, } - #[cfg(feature = "std")] impl Default for GenesisConfig { fn default() -> Self { Self { indices: Default::default() } diff --git a/frame/membership/src/lib.rs b/frame/membership/src/lib.rs index e8256fab83af2..b66215b93043c 100644 --- a/frame/membership/src/lib.rs +++ b/frame/membership/src/lib.rs @@ -24,7 +24,7 @@ #![cfg_attr(not(feature = "std"), no_std)] use frame_support::traits::{ - ChangeMembers, Contains, Get, InitializeMembers, SortedMembers, StorageVersion, + ChangeMembers, Contains, Get, InitializeMembers, SortedMembers, StorageVersion, GenesisBuild, }; use sp_std::prelude::*; @@ -105,7 +105,6 @@ pub mod pallet { pub phantom: PhantomData, } - #[cfg(feature = "std")] impl, I: 'static> Default for GenesisConfig { fn default() -> Self { Self { members: Vec::new(), phantom: Default::default() } diff --git a/frame/session/src/lib.rs b/frame/session/src/lib.rs index 4cf793a9b4739..cac8b4997ecdb 100644 --- a/frame/session/src/lib.rs +++ b/frame/session/src/lib.rs @@ -121,7 +121,7 @@ use frame_support::{ ensure, traits::{ EstimateNextNewSession, EstimateNextSessionRotation, FindAuthor, Get, OneSessionHandler, - StorageVersion, ValidatorRegistration, ValidatorSet, + StorageVersion, ValidatorRegistration, ValidatorSet, GenesisBuild, }, weights::Weight, Parameter, @@ -419,7 +419,6 @@ pub mod pallet { pub keys: Vec<(T::AccountId, T::ValidatorId, T::Keys)>, } - #[cfg(feature = "std")] impl Default for GenesisConfig { fn default() -> Self { Self { keys: Default::default() } diff --git a/frame/society/src/lib.rs b/frame/society/src/lib.rs index a9f83094fd49c..0f62f18dc05d5 100644 --- a/frame/society/src/lib.rs +++ b/frame/society/src/lib.rs @@ -255,7 +255,7 @@ use frame_support::{ pallet_prelude::*, traits::{ BalanceStatus, ChangeMembers, Currency, EnsureOrigin, ExistenceRequirement::AllowDeath, - Imbalance, OnUnbalanced, Randomness, ReservableCurrency, + Imbalance, OnUnbalanced, Randomness, ReservableCurrency, GenesisBuild, }, PalletId, }; @@ -650,7 +650,6 @@ pub mod pallet { pub max_members: u32, } - #[cfg(feature = "std")] impl, I: 'static> Default for GenesisConfig { fn default() -> Self { Self { diff --git a/frame/staking/src/lib.rs b/frame/staking/src/lib.rs index 17af4829c0ea8..105774057c7ce 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -301,10 +301,12 @@ mod pallet; use codec::{Decode, Encode, HasCompact}; use frame_support::{ - traits::{ConstU32, Currency, Get}, + traits::{Currency, Get}, weights::Weight, BoundedVec, EqNoBound, PartialEqNoBound, RuntimeDebugNoBound, }; +#[cfg(feature = "std")] +use frame_support::traits::ConstU32; use scale_info::TypeInfo; use sp_runtime::{ curve::PiecewiseLinear, diff --git a/frame/staking/src/pallet/mod.rs b/frame/staking/src/pallet/mod.rs index 2a870fda063d3..a6a9339e2e8a6 100644 --- a/frame/staking/src/pallet/mod.rs +++ b/frame/staking/src/pallet/mod.rs @@ -22,7 +22,7 @@ use frame_support::{ pallet_prelude::*, traits::{ Currency, CurrencyToVote, EnsureOrigin, EstimateNextNewSession, Get, LockIdentifier, - LockableCurrency, OnUnbalanced, UnixTime, + LockableCurrency, OnUnbalanced, UnixTime, GenesisBuild, }, weights::Weight, }; @@ -493,7 +493,6 @@ pub mod pallet { pub max_nominator_count: Option, } - #[cfg(feature = "std")] impl Default for GenesisConfig { fn default() -> Self { GenesisConfig { diff --git a/frame/sudo/src/lib.rs b/frame/sudo/src/lib.rs index d9e72b37f2970..551374fff6cdf 100644 --- a/frame/sudo/src/lib.rs +++ b/frame/sudo/src/lib.rs @@ -95,7 +95,7 @@ use sp_runtime::{traits::StaticLookup, DispatchResult}; use sp_std::prelude::*; -use frame_support::{traits::UnfilteredDispatchable, weights::GetDispatchInfo}; +use frame_support::{traits::{UnfilteredDispatchable, GenesisBuild}, weights::GetDispatchInfo}; #[cfg(test)] mod mock; @@ -276,7 +276,6 @@ pub mod pallet { pub key: Option, } - #[cfg(feature = "std")] impl Default for GenesisConfig { fn default() -> Self { Self { key: None } diff --git a/frame/support/procedural/src/construct_runtime/expand/config.rs b/frame/support/procedural/src/construct_runtime/expand/config.rs index 79176fa7385ec..991bf96414c25 100644 --- a/frame/support/procedural/src/construct_runtime/expand/config.rs +++ b/frame/support/procedural/src/construct_runtime/expand/config.rs @@ -29,6 +29,7 @@ pub fn expand_outer_config( let mut types = TokenStream::new(); let mut fields = TokenStream::new(); let mut build_storage_calls = TokenStream::new(); + let mut build_execute_calls = TokenStream::new(); let mut query_genesis_config_part_macros = Vec::new(); for decl in pallet_decls { @@ -49,6 +50,7 @@ pub fn expand_outer_config( decl, &field_name, )); + build_execute_calls.extend(quote!(#scrate::traits::GenesisBuild::<#runtime, _>::build(&self.#field_name);)); query_genesis_config_part_macros.push(quote! { #path::__substrate_genesis_config_check::is_genesis_config_defined!(#pallet_name); #[cfg(feature = "std")] @@ -64,26 +66,31 @@ pub fn expand_outer_config( #[cfg(any(feature = "std", test))] use #scrate::serde as __genesis_config_serde_import__; - #[cfg(any(feature = "std", test))] - #[derive(#scrate::serde::Serialize, #scrate::serde::Deserialize, Default)] - #[serde(rename_all = "camelCase")] - #[serde(deny_unknown_fields)] - #[serde(crate = "__genesis_config_serde_import__")] + #[derive(Default)] + #[cfg_attr(feature = "std", derive(#scrate::serde::Serialize, #scrate::serde::Deserialize))] + #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] + #[cfg_attr(feature = "std", serde(deny_unknown_fields))] + #[cfg_attr(feature = "std", serde(crate = "__genesis_config_serde_import__"))] pub struct GenesisConfig { #fields } + impl GenesisConfig { + pub fn execute(&self) { + #build_execute_calls + ::on_genesis(); + } + } + #[cfg(any(feature = "std", test))] - impl #scrate::sp_runtime::BuildStorage for GenesisConfig { + impl GenesisConfig { fn assimilate_storage( &self, storage: &mut #scrate::sp_runtime::Storage, ) -> std::result::Result<(), String> { #build_storage_calls - #scrate::BasicExternalities::execute_with_storage(storage, || { - ::on_genesis(); - }); + ::on_genesis(); Ok(()) } @@ -101,15 +108,12 @@ fn expand_config_types( match (decl.instance.as_ref(), part_is_generic) { (Some(inst), true) => quote! { - #[cfg(any(feature = "std", test))] pub type #config = #path::GenesisConfig<#runtime, #path::#inst>; }, (None, true) => quote! { - #[cfg(any(feature = "std", test))] pub type #config = #path::GenesisConfig<#runtime>; }, (_, false) => quote! { - #[cfg(any(feature = "std", test))] pub type #config = #path::GenesisConfig; }, } diff --git a/frame/support/procedural/src/pallet/expand/genesis_build.rs b/frame/support/procedural/src/pallet/expand/genesis_build.rs index 53d0695e5f971..64fa362187c73 100644 --- a/frame/support/procedural/src/pallet/expand/genesis_build.rs +++ b/frame/support/procedural/src/pallet/expand/genesis_build.rs @@ -41,16 +41,6 @@ pub fn expand_genesis_build(def: &mut Def) -> proc_macro2::TokenStream { let gen_cfg_use_gen = genesis_config.gen_kind.type_use_gen(genesis_build.attr_span); - let genesis_build_item = - &mut def.item.content.as_mut().expect("Checked by def parser").1[genesis_build.index]; - - let genesis_build_item_impl = if let syn::Item::Impl(impl_) = genesis_build_item { - impl_ - } else { - unreachable!("Checked by genesis_build parser") - }; - - genesis_build_item_impl.attrs.push(syn::parse_quote!( #[cfg(feature = "std")] )); let where_clause = &genesis_build.where_clause; quote::quote_spanned!(genesis_build.attr_span => diff --git a/frame/support/procedural/src/pallet/expand/genesis_config.rs b/frame/support/procedural/src/pallet/expand/genesis_config.rs index 18fa87a262533..3cb446a2e2509 100644 --- a/frame/support/procedural/src/pallet/expand/genesis_config.rs +++ b/frame/support/procedural/src/pallet/expand/genesis_config.rs @@ -94,15 +94,15 @@ pub fn expand_genesis_config(def: &mut Def) -> proc_macro2::TokenStream { "] )); } - attrs.push(syn::parse_quote!( #[cfg(feature = "std")] )); + //attrs.push(syn::parse_quote!( #[cfg(feature = "std")] )); attrs.push(syn::parse_quote!( - #[derive(#frame_support::Serialize, #frame_support::Deserialize)] + #[cfg_attr(feature = "std", derive(#frame_support::Serialize, #frame_support::Deserialize))] )); - attrs.push(syn::parse_quote!( #[serde(rename_all = "camelCase")] )); - attrs.push(syn::parse_quote!( #[serde(deny_unknown_fields)] )); - attrs.push(syn::parse_quote!( #[serde(bound(serialize = ""))] )); - attrs.push(syn::parse_quote!( #[serde(bound(deserialize = ""))] )); - attrs.push(syn::parse_quote!( #[serde(crate = #serde_crate)] )); + attrs.push(syn::parse_quote!( #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] )); + attrs.push(syn::parse_quote!( #[cfg_attr(feature = "std", serde(deny_unknown_fields))] )); + attrs.push(syn::parse_quote!( #[cfg_attr(feature = "std", serde(bound(serialize = "")))] )); + attrs.push(syn::parse_quote!( #[cfg_attr(feature = "std", serde(bound(deserialize = "")))] )); + attrs.push(syn::parse_quote!( #[cfg_attr(feature = "std", serde(crate = #serde_crate))] )); }, _ => unreachable!("Checked by genesis_config parser"), } diff --git a/frame/support/procedural/src/storage/genesis_config/mod.rs b/frame/support/procedural/src/storage/genesis_config/mod.rs index d4348ee19171c..5581a2ca831a7 100644 --- a/frame/support/procedural/src/storage/genesis_config/mod.rs +++ b/frame/support/procedural/src/storage/genesis_config/mod.rs @@ -72,7 +72,7 @@ fn decl_genesis_config_and_impl_default( #[derive(#scrate::Serialize, #scrate::Deserialize)] #[cfg(feature = "std")] #[serde(rename_all = "camelCase")] - #[serde(deny_unknown_fields)] + #[serde(deny_unknown_field)] #[serde(crate = #serde_crate)] #serde_bug_bound pub struct GenesisConfig #genesis_struct_decl #genesis_where_clause { diff --git a/frame/support/src/traits.rs b/frame/support/src/traits.rs index 5ee2952e445b7..2bf74b102ca80 100644 --- a/frame/support/src/traits.rs +++ b/frame/support/src/traits.rs @@ -72,7 +72,6 @@ pub use metadata::{ }; mod hooks; -#[cfg(feature = "std")] pub use hooks::GenesisBuild; pub use hooks::{ Hooks, OnFinalize, OnGenesis, OnIdle, OnInitialize, OnRuntimeUpgrade, OnTimestampSet, diff --git a/frame/support/src/traits/hooks.rs b/frame/support/src/traits/hooks.rs index 385db4e4d1ad9..03c142629825f 100644 --- a/frame/support/src/traits/hooks.rs +++ b/frame/support/src/traits/hooks.rs @@ -320,6 +320,13 @@ pub trait GenesisBuild: Default + sp_runtime::traits::MaybeSerializeD } } +#[cfg(not(feature = "std"))] +pub trait GenesisBuild: Default { + /// The build function is called within an externalities allowing storage APIs. + /// Thus one can write to storage using regular pallet storages. + fn build(&self); +} + /// A trait which is called when the timestamp is set in the runtime. #[impl_for_tuples(30)] pub trait OnTimestampSet { diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index 3b4de0c472c47..ff052fcdce587 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -97,7 +97,6 @@ use frame_support::{ use scale_info::TypeInfo; use sp_core::storage::well_known_keys; -#[cfg(feature = "std")] use frame_support::traits::GenesisBuild; #[cfg(any(feature = "std", test))] use sp_io::TestExternalities; @@ -634,10 +633,9 @@ pub mod pallet { #[pallet::storage] pub(super) type ExecutionPhase = StorageValue<_, Phase>; - #[cfg_attr(feature = "std", derive(Default))] + #[derive(Default)] #[pallet::genesis_config] pub struct GenesisConfig { - #[serde(with = "sp_core::bytes")] pub code: Vec, } @@ -711,7 +709,6 @@ pub struct EventRecord { // Create a Hash with 69 for each byte, // only used to build genesis config. -#[cfg(feature = "std")] fn hash69 + Default>() -> T { let mut h = T::default(); h.as_mut().iter_mut().for_each(|byte| *byte = 69); diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index e4d77a05f284b..e1d90d3d16280 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -64,7 +64,7 @@ use sp_std::prelude::*; use frame_support::{ dispatch::DispatchResult, - traits::{EstimateCallFee, Get}, + traits::{EstimateCallFee, Get, GenesisBuild}, weights::{ DispatchClass, DispatchInfo, GetDispatchInfo, Pays, PostDispatchInfo, Weight, WeightToFeeCoefficient, WeightToFeePolynomial, @@ -321,7 +321,6 @@ pub mod pallet { #[pallet::genesis_config] pub struct GenesisConfig; - #[cfg(feature = "std")] impl Default for GenesisConfig { fn default() -> Self { Self diff --git a/frame/transaction-storage/src/lib.rs b/frame/transaction-storage/src/lib.rs index d95a60b495121..c8dd660d92205 100644 --- a/frame/transaction-storage/src/lib.rs +++ b/frame/transaction-storage/src/lib.rs @@ -31,7 +31,7 @@ mod tests; use codec::{Decode, Encode}; use frame_support::{ dispatch::{Dispatchable, GetDispatchInfo}, - traits::{Currency, OnUnbalanced, ReservableCurrency}, + traits::{Currency, OnUnbalanced, ReservableCurrency, GenesisBuild}, }; use sp_runtime::traits::{BlakeTwo256, Hash, One, Saturating, Zero}; use sp_std::{prelude::*, result}; @@ -376,7 +376,6 @@ pub mod pallet { pub max_transaction_size: u32, } - #[cfg(feature = "std")] impl Default for GenesisConfig { fn default() -> Self { Self { diff --git a/frame/treasury/src/lib.rs b/frame/treasury/src/lib.rs index 81fca5243afa3..4b26601325b88 100644 --- a/frame/treasury/src/lib.rs +++ b/frame/treasury/src/lib.rs @@ -75,7 +75,7 @@ use frame_support::{ print, traits::{ Currency, ExistenceRequirement::KeepAlive, Get, Imbalance, OnUnbalanced, - ReservableCurrency, WithdrawReasons, + ReservableCurrency, WithdrawReasons, GenesisBuild, }, weights::Weight, PalletId, @@ -224,7 +224,6 @@ pub mod pallet { #[pallet::genesis_config] pub struct GenesisConfig; - #[cfg(feature = "std")] impl Default for GenesisConfig { fn default() -> Self { Self diff --git a/frame/vesting/src/lib.rs b/frame/vesting/src/lib.rs index 747521f4fa536..314162e05f2b1 100644 --- a/frame/vesting/src/lib.rs +++ b/frame/vesting/src/lib.rs @@ -61,7 +61,7 @@ use frame_support::{ pallet_prelude::*, traits::{ Currency, ExistenceRequirement, Get, LockIdentifier, LockableCurrency, VestingSchedule, - WithdrawReasons, + WithdrawReasons, GenesisBuild, }, }; use frame_system::{ensure_root, ensure_signed, pallet_prelude::*}; @@ -210,7 +210,6 @@ pub mod pallet { pub vesting: Vec<(T::AccountId, T::BlockNumber, T::BlockNumber, BalanceOf)>, } - #[cfg(feature = "std")] impl Default for GenesisConfig { fn default() -> Self { GenesisConfig { vesting: Default::default() } diff --git a/primitives/api/src/lib.rs b/primitives/api/src/lib.rs index 07f57c58a444c..73bfcde3510d7 100644 --- a/primitives/api/src/lib.rs +++ b/primitives/api/src/lib.rs @@ -835,4 +835,14 @@ decl_runtime_apis! { /// Returns the metadata of a runtime. fn metadata() -> OpaqueMetadata; } + + /// The `Dev` api trait that returns metadata for the runtime. + pub trait Genesis { + /// Build genesis data for the "development" version of this runtime. + fn build_dev(); + /// Build genesis data for the "local testnet" version of this runtime. + fn build_local(); + /// Build genesis data for the empty or "staging" genesis. + fn build_genesis(); + } } diff --git a/utils/wasm-builder/src/builder.rs b/utils/wasm-builder/src/builder.rs index 81a8693968188..06c4b75e49845 100644 --- a/utils/wasm-builder/src/builder.rs +++ b/utils/wasm-builder/src/builder.rs @@ -196,6 +196,7 @@ fn provide_dummy_wasm_binary_if_not_exist(file_path: &Path) { crate::write_file_if_changed( file_path, "pub const WASM_BINARY: Option<&[u8]> = None;\ + #[allow(dead_code)] \ pub const WASM_BINARY_BLOATY: Option<&[u8]> = None;", ); } @@ -260,6 +261,7 @@ fn build_project( format!( r#" pub const WASM_BINARY: Option<&[u8]> = Some(include_bytes!("{wasm_binary}")); + #[allow(dead_code)] pub const WASM_BINARY_BLOATY: Option<&[u8]> = Some(include_bytes!("{wasm_binary_bloaty}")); "#, wasm_binary = wasm_binary, From d3e357d46f7d32248a789da752836a1cb94fd210 Mon Sep 17 00:00:00 2001 From: arkpar Date: Mon, 14 Feb 2022 00:16:16 +0100 Subject: [PATCH 03/14] Cleanup --- .../api/proc-macro/src/decl_runtime_apis.rs | 287 ------------------ 1 file changed, 287 deletions(-) diff --git a/primitives/api/proc-macro/src/decl_runtime_apis.rs b/primitives/api/proc-macro/src/decl_runtime_apis.rs index 6de480aa69b43..f2996a85d3d34 100644 --- a/primitives/api/proc-macro/src/decl_runtime_apis.rs +++ b/primitives/api/proc-macro/src/decl_runtime_apis.rs @@ -439,71 +439,6 @@ fn generate_call_api_at_calls(decl: &ItemTrait) -> Result { Ok(quote!( #( #result )* )) } -/// Generate the functions that call the api at a given block for a given trait method. -fn _generate_call_api_impls(decl: &ItemTrait) -> Result { - let fns = decl.items.iter().filter_map(|i| match i { - TraitItem::Method(ref m) => Some((&m.attrs, &m.sig)), - _ => None, - }); - - let mut result = Vec::new(); - let mut errors = Vec::new(); - let crate_ = generate_crate_access(HIDDEN_INCLUDES_ID); - let mod_name = generate_runtime_mod_name_for_trait(&decl.ident); - - // Generate a native call generator for each function of the given trait. - for (attrs, sig) in fns { - - if remove_supported_attributes(&mut attrs.clone()).contains_key(CHANGED_IN_ATTRIBUTE) { - continue; - } - - let fn_sig = &sig; - let ret_type = return_type_extract_type(&fn_sig.output); - - // Get types and if the value is borrowed from all parameters. - // If there is an error, we push it as the block to the user. - let param_types = - match extract_parameter_names_types_and_borrows(fn_sig, AllowSelfRefInParameters::No) { - Ok(res) => res - .into_iter() - .map(|v| { - let ty = v.1; - let borrow = v.2; - quote!( #borrow #ty ) - }) - .collect::>(), - Err(e) => { - errors.push(e.to_compile_error()); - Vec::new() - }, - }; - let name = generate_method_runtime_api_impl_name(&decl.ident, &fn_sig.ident); - let block_id = quote!( #crate_::BlockId ); - let call_fn_name = generate_call_api_at_fn_name(&fn_sig.ident); - - result.push(quote! { - #[doc(hidden)] - fn #name( - &self, - at: &#block_id, - context: #crate_::ExecutionContext, - params: Option<( #( #param_types ),* )>, - params_encoded: Vec, - ) -> std::result::Result<#crate_::NativeOrEncoded<#ret_type>, #crate_::ApiError> - { - let changes = Default::default(); - let tx_cache = Default::default(); - #mod_name::#call_fn_name::<_, fn() -> std::result::Result<#ret_type, #crate_::ApiError>, _, _>( - self, at, params_encoded, &changes, &tx_cache, None, context, &None - ) - } - }); - } - - Ok(quote!( #( #result )* )) -} - /// Generate the implementation for `RuntimeApi` fn generate_runtime_api_call_impl(decl: &ItemTrait) -> Result { let fns = decl.items.iter().filter_map(|i| match i { @@ -857,228 +792,6 @@ impl<'a> Fold for ToClientSideDecl<'a> { } } -/// Modify the given runtime api declaration to be usable on the client side. -struct ToCallImpl<'a> { - block_id: &'a TokenStream, - crate_: &'a TokenStream, - found_attributes: &'a mut HashMap<&'static str, Attribute>, - /// Any error that we found while converting this declaration. - errors: &'a mut Vec, - trait_: &'a Ident, -} - -impl<'a> ToCallImpl<'a> { - fn fold_item_trait_items(&mut self, items: Vec) -> Vec { - let mut result = Vec::new(); - - items.into_iter().for_each(|i| match i { - TraitItem::Method(method) => { - let (fn_decl, fn_impl, fn_decl_ctx) = self.fold_trait_item_method(method); - result.push(fn_decl.into()); - result.push(fn_decl_ctx.into()); - - if let Some(fn_impl) = fn_impl { - result.push(fn_impl.into()); - } - }, - r => result.push(r), - }); - - result - } - - fn fold_trait_item_method( - &mut self, - method: TraitItemMethod, - ) -> (TraitItemMethod, Option, TraitItemMethod) { - let crate_ = self.crate_; - let context = quote!( #crate_::ExecutionContext::OffchainCall(None) ); - let fn_impl = self.create_method_runtime_api_impl(method.clone()); - let fn_decl = self.create_method_decl(method.clone(), context); - let fn_decl_ctx = self.create_method_decl_with_context(method); - - (fn_decl, fn_impl, fn_decl_ctx) - } - - fn create_method_decl_with_context(&mut self, method: TraitItemMethod) -> TraitItemMethod { - let crate_ = self.crate_; - let context_arg: syn::FnArg = parse_quote!( context: #crate_::ExecutionContext ); - let mut fn_decl_ctx = self.create_method_decl(method, quote!(context)); - fn_decl_ctx.sig.ident = - Ident::new(&format!("{}_with_context", &fn_decl_ctx.sig.ident), Span::call_site()); - fn_decl_ctx.sig.inputs.insert(2, context_arg); - - fn_decl_ctx - } - - /// Takes the given method and creates a `method_runtime_api_impl` method that will be - /// implemented in the runtime for the client side. - fn create_method_runtime_api_impl( - &mut self, - mut method: TraitItemMethod, - ) -> Option { - if remove_supported_attributes(&mut method.attrs).contains_key(CHANGED_IN_ATTRIBUTE) { - return None - } - - let fn_sig = &method.sig; - let ret_type = return_type_extract_type(&fn_sig.output); - - // Get types and if the value is borrowed from all parameters. - // If there is an error, we push it as the block to the user. - let param_types = - match extract_parameter_names_types_and_borrows(fn_sig, AllowSelfRefInParameters::No) { - Ok(res) => res - .into_iter() - .map(|v| { - let ty = v.1; - let borrow = v.2; - quote!( #borrow #ty ) - }) - .collect::>(), - Err(e) => { - self.errors.push(e.to_compile_error()); - Vec::new() - }, - }; - let name = generate_method_runtime_api_impl_name(&self.trait_, &method.sig.ident); - let block_id = self.block_id; - let crate_ = self.crate_; - - Some(parse_quote! { - #[doc(hidden)] - fn #name( - &self, - at: &#block_id, - context: #crate_::ExecutionContext, - params: Option<( #( #param_types ),* )>, - params_encoded: Vec, - ) -> std::result::Result<#crate_::NativeOrEncoded<#ret_type>, #crate_::ApiError>; - }) - } - - /// Takes the method declared by the user and creates the declaration we require for the runtime - /// api client side. This method will call by default the `method_runtime_api_impl` for doing - /// the actual call into the runtime. - fn create_method_decl( - &mut self, - mut method: TraitItemMethod, - context: TokenStream, - ) -> TraitItemMethod { - let params = match extract_parameter_names_types_and_borrows( - &method.sig, - AllowSelfRefInParameters::No, - ) { - Ok(res) => res.into_iter().map(|v| v.0).collect::>(), - Err(e) => { - self.errors.push(e.to_compile_error()); - Vec::new() - }, - }; - let params2 = params.clone(); - let ret_type = return_type_extract_type(&method.sig.output); - - fold_fn_decl_for_client_side(&mut method.sig, &self.block_id, &self.crate_); - - let name_impl = generate_method_runtime_api_impl_name(&self.trait_, &method.sig.ident); - let crate_ = self.crate_; - - let found_attributes = remove_supported_attributes(&mut method.attrs); - // If the method has a `changed_in` attribute, we need to alter the method name to - // `method_before_version_VERSION`. - let (native_handling, param_tuple) = match get_changed_in(&found_attributes) { - Ok(Some(version)) => { - // Make sure that the `changed_in` version is at least the current `api_version`. - if get_api_version(&self.found_attributes).ok() < Some(version) { - self.errors.push( - Error::new( - method.span(), - "`changed_in` version can not be greater than the `api_version`", - ) - .to_compile_error(), - ); - } - - let ident = Ident::new( - &format!("{}_before_version_{}", method.sig.ident, version), - method.sig.ident.span(), - ); - method.sig.ident = ident; - method.attrs.push(parse_quote!( #[deprecated] )); - - let panic = - format!("Calling `{}` should not return a native value!", method.sig.ident); - (quote!(panic!(#panic)), quote!(None)) - }, - Ok(None) => (quote!(Ok(n)), quote!( Some(( #( #params2 ),* )) )), - Err(e) => { - self.errors.push(e.to_compile_error()); - (quote!(unimplemented!()), quote!(None)) - }, - }; - - let function_name = method.sig.ident.to_string(); - - // Generate the default implementation that calls the `method_runtime_api_impl` method. - method.default = Some(parse_quote! { - { - let runtime_api_impl_params_encoded = - #crate_::Encode::encode(&( #( &#params ),* )); - - self.#name_impl( - __runtime_api_at_param__, - #context, - #param_tuple, - runtime_api_impl_params_encoded, - ).and_then(|r| - match r { - #crate_::NativeOrEncoded::Native(n) => { - #native_handling - }, - #crate_::NativeOrEncoded::Encoded(r) => { - <#ret_type as #crate_::Decode>::decode(&mut &r[..]) - .map_err(|err| - #crate_::ApiError::FailedToDecodeReturnValue { - function: #function_name, - error: err, - } - ) - } - } - ) - } - }); - - method - } -} - -impl<'a> Fold for ToCallImpl<'a> { - fn fold_item_trait(&mut self, mut input: ItemTrait) -> ItemTrait { - extend_generics_with_block(&mut input.generics); - - *self.found_attributes = remove_supported_attributes(&mut input.attrs); - // Check if this is the `Core` runtime api trait. - let is_core_trait = self.found_attributes.contains_key(CORE_TRAIT_ATTRIBUTE); - let block_ident = Ident::new(BLOCK_GENERIC_IDENT, Span::call_site()); - - if is_core_trait { - // Add all the supertraits we want to have for `Core`. - input.supertraits = parse_quote!('static + Send + Sync); - } else { - // Add the `Core` runtime api as super trait. - let crate_ = &self.crate_; - input.supertraits.push(parse_quote!( #crate_::Core<#block_ident> )); - } - - // The client side trait is only required when compiling with the feature `std` or `test`. - input.attrs.push(parse_quote!( #[cfg(any(feature = "std", test))] )); - input.items = self.fold_item_trait_items(input.items); - - fold::fold_item_trait(self, input) - } -} - /// Parse the given attribute as `API_VERSION_ATTRIBUTE`. fn parse_runtime_api_version(version: &Attribute) -> Result { let meta = version.parse_meta()?; From 67dd55ff065c68f9b87883218c637e94c5630c28 Mon Sep 17 00:00:00 2001 From: arkpar Date: Mon, 14 Feb 2022 14:32:13 +0100 Subject: [PATCH 04/14] Updated some tests --- Cargo.lock | 15 +- Cargo.toml | 2 +- bin/node-template/node/Cargo.toml | 1 + bin/node-template/node/build.rs | 13 ++ bin/node-template/node/src/chain_spec.rs | 147 +++--------------- bin/node-template/node/src/command.rs | 4 +- bin/node-template/node/src/rpc.rs | 11 +- bin/node-template/node/src/service.rs | 35 ++--- bin/node-template/runtime/src/lib.rs | 80 +++++++++- bin/node/cli/build.rs | 1 - bin/node/cli/src/chain_spec.rs | 1 - bin/node/runtime/src/lib.rs | 21 +-- bin/node/testing/src/bench.rs | 4 +- bin/node/testing/src/client.rs | 5 +- bin/utils/chain-spec-builder/Cargo.toml | 1 + bin/utils/chain-spec-builder/src/main.rs | 1 + .../authority-discovery/src/worker/tests.rs | 2 - .../basic-authorship/src/basic_authorship.rs | 2 +- client/cli/src/commands/insert_key.rs | 9 +- client/consensus/babe/src/tests.rs | 2 - client/network/test/src/lib.rs | 2 - client/service/src/client/call_executor.rs | 2 - client/service/test/src/client/mod.rs | 15 +- client/service/test/src/lib.rs | 34 ++-- frame/aura/src/lib.rs | 3 +- .../src/construct_runtime/expand/config.rs | 14 +- .../src/pallet/expand/genesis_config.rs | 38 ++--- .../src/storage/genesis_config/mod.rs | 2 +- frame/support/test/Cargo.toml | 1 + frame/support/test/pallet/src/lib.rs | 2 +- frame/support/test/src/lib.rs | 3 + frame/system/src/tests.rs | 4 +- .../api/proc-macro/src/decl_runtime_apis.rs | 11 -- primitives/api/src/lib.rs | 12 -- primitives/api/test/tests/decl_and_impl.rs | 2 - primitives/core/Cargo.toml | 2 +- primitives/core/src/crypto.rs | 35 +++++ .../runtime/client/src/block_builder_ext.rs | 11 +- test-utils/runtime/client/src/lib.rs | 37 ++--- utils/frame/rpc/system/src/lib.rs | 12 +- 40 files changed, 250 insertions(+), 349 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 94f19a5ac373b..a5e162314bf31 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -922,20 +922,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "chain-spec-builder" -version = "2.0.0" -dependencies = [ - "ansi_term", - "clap 3.0.7", - "node-cli", - "rand 0.8.4", - "sc-chain-spec", - "sc-keystore", - "sp-core", - "sp-keystore", -] - [[package]] name = "chrono" version = "0.4.19" @@ -4967,6 +4953,7 @@ dependencies = [ "sp-timestamp", "substrate-build-script-utils", "substrate-frame-rpc-system", + "substrate-wasm-builder", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 2015a6167731c..e8a02e46f9357 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ members = [ "bin/node/rpc", "bin/node/runtime", "bin/node/testing", - "bin/utils/chain-spec-builder", + #"bin/utils/chain-spec-builder", "bin/utils/subkey", "client/api", "client/authority-discovery", diff --git a/bin/node-template/node/Cargo.toml b/bin/node-template/node/Cargo.toml index a3405f32d9fb6..6aa97ba54fdea 100644 --- a/bin/node-template/node/Cargo.toml +++ b/bin/node-template/node/Cargo.toml @@ -57,6 +57,7 @@ frame-benchmarking-cli = { version = "4.0.0-dev", path = "../../../utils/frame/b [build-dependencies] substrate-build-script-utils = { version = "3.0.0", path = "../../../utils/build-script-utils" } +substrate-wasm-builder = { version = "5.0.0-dev", path = "../../../utils/wasm-builder" } [features] default = [] diff --git a/bin/node-template/node/build.rs b/bin/node-template/node/build.rs index e3bfe3116bf28..82930ee9df807 100644 --- a/bin/node-template/node/build.rs +++ b/bin/node-template/node/build.rs @@ -1,7 +1,20 @@ use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed}; +use substrate_wasm_builder::WasmBuilder; fn main() { + build_runtime(); generate_cargo_keys(); rerun_if_git_head_changed(); } + +fn build_runtime() { + let mut path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); + path.push("../runtime/Cargo.toml"); + WasmBuilder::new() + .with_project(path.canonicalize().unwrap()).unwrap() + .export_heap_base() + .import_memory() + .build() +} + diff --git a/bin/node-template/node/src/chain_spec.rs b/bin/node-template/node/src/chain_spec.rs index ef34ec369a77f..04d2cb73b8175 100644 --- a/bin/node-template/node/src/chain_spec.rs +++ b/bin/node-template/node/src/chain_spec.rs @@ -1,156 +1,49 @@ -use node_template_runtime::{ - AccountId, AuraConfig, BalancesConfig, GenesisConfig, GrandpaConfig, Signature, SudoConfig, - SystemConfig, WASM_BINARY, -}; use sc_service::ChainType; -use sp_consensus_aura::sr25519::AuthorityId as AuraId; -use sp_core::{sr25519, Pair, Public}; -use sp_finality_grandpa::AuthorityId as GrandpaId; -use sp_runtime::traits::{IdentifyAccount, Verify}; -// The URL for the telemetry server. -// const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/"; - -/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type. -pub type ChainSpec = sc_service::GenericChainSpec; - -/// Generate a crypto pair from seed. -pub fn get_from_seed(seed: &str) -> ::Public { - TPublic::Pair::from_string(&format!("//{}", seed), None) - .expect("static values are valid; qed") - .public() -} - -type AccountPublic = ::Signer; - -/// Generate an account ID from seed. -pub fn get_account_id_from_seed(seed: &str) -> AccountId -where - AccountPublic: From<::Public>, -{ - AccountPublic::from(get_from_seed::(seed)).into_account() +mod runtime { + include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); + /// Wasm binary unwrapped. If built with `SKIP_WASM_BUILD`, the function panics. + pub fn wasm_binary_unwrap() -> &'static [u8] { + WASM_BINARY.expect( + "Development wasm binary is not available. This means the client is built with \ + `SKIP_WASM_BUILD` flag and it is only usable for production chains. Please rebuild with \ + the flag disabled.", + ) + } } -/// Generate an Aura authority key. -pub fn authority_keys_from_seed(s: &str) -> (AuraId, GrandpaId) { - (get_from_seed::(s), get_from_seed::(s)) -} +/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type. +pub type ChainSpec = sc_service::GenericChainSpec<()>; pub fn development_config() -> Result { - let wasm_binary = WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?; - - Ok(ChainSpec::from_genesis( - // Name + Ok(ChainSpec::from_runtime( "Development", - // ID "dev", ChainType::Development, - move || { - testnet_genesis( - wasm_binary, - // Initial PoA authorities - vec![authority_keys_from_seed("Alice")], - // Sudo account - get_account_id_from_seed::("Alice"), - // Pre-funded accounts - vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - get_account_id_from_seed::("Alice//stash"), - get_account_id_from_seed::("Bob//stash"), - ], - true, - ) - }, - // Bootnodes + runtime::wasm_binary_unwrap(), + "Genesis_build_dev", vec![], - // Telemetry None, - // Protocol ID None, None, - // Properties - None, - // Extensions None, + Default::default(), )) } pub fn local_testnet_config() -> Result { - let wasm_binary = WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?; - - Ok(ChainSpec::from_genesis( - // Name + Ok(ChainSpec::from_runtime( "Local Testnet", - // ID "local_testnet", ChainType::Local, - move || { - testnet_genesis( - wasm_binary, - // Initial PoA authorities - vec![authority_keys_from_seed("Alice"), authority_keys_from_seed("Bob")], - // Sudo account - get_account_id_from_seed::("Alice"), - // Pre-funded accounts - vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - get_account_id_from_seed::("Charlie"), - get_account_id_from_seed::("Dave"), - get_account_id_from_seed::("Eve"), - get_account_id_from_seed::("Ferdie"), - get_account_id_from_seed::("Alice//stash"), - get_account_id_from_seed::("Bob//stash"), - get_account_id_from_seed::("Charlie//stash"), - get_account_id_from_seed::("Dave//stash"), - get_account_id_from_seed::("Eve//stash"), - get_account_id_from_seed::("Ferdie//stash"), - ], - true, - ) - }, - // Bootnodes + runtime::wasm_binary_unwrap(), + "Genesis_build_genesis", vec![], - // Telemetry None, - // Protocol ID None, - // Properties None, None, - // Extensions - None, + Default::default(), )) } -/// Configure initial storage state for FRAME modules. -fn testnet_genesis( - wasm_binary: &[u8], - initial_authorities: Vec<(AuraId, GrandpaId)>, - root_key: AccountId, - endowed_accounts: Vec, - _enable_println: bool, -) -> GenesisConfig { - GenesisConfig { - system: SystemConfig { - // Add Wasm runtime to storage. - code: wasm_binary.to_vec(), - }, - balances: BalancesConfig { - // Configure endowed accounts with initial balance of 1 << 60. - balances: endowed_accounts.iter().cloned().map(|k| (k, 1 << 60)).collect(), - }, - aura: AuraConfig { - authorities: initial_authorities.iter().map(|x| (x.0.clone())).collect(), - }, - grandpa: GrandpaConfig { - authorities: initial_authorities.iter().map(|x| (x.1.clone(), 1)).collect(), - }, - sudo: SudoConfig { - // Assign network admin rights. - key: Some(root_key), - }, - transaction_payment: Default::default(), - } -} diff --git a/bin/node-template/node/src/command.rs b/bin/node-template/node/src/command.rs index 3d0652ca6a7bd..9917c158f7f95 100644 --- a/bin/node-template/node/src/command.rs +++ b/bin/node-template/node/src/command.rs @@ -3,7 +3,7 @@ use crate::{ cli::{Cli, Subcommand}, service, }; -use node_template_runtime::Block; +use service::Block; use sc_cli::{SubstrateCli}; use sc_service::PartialComponents; @@ -98,7 +98,7 @@ pub fn run() -> sc_cli::Result<()> { if cfg!(feature = "runtime-benchmarks") { let runner = cli.create_runner(cmd)?; - runner.sync_run(|config| cmd.run::(config)) + runner.sync_run(|config| cmd.run::(config)) } else { Err("Benchmarking wasn't enabled when building the node. You can enable it with \ `--features runtime-benchmarks`." diff --git a/bin/node-template/node/src/rpc.rs b/bin/node-template/node/src/rpc.rs index d23b23178ec2a..23c8e39a88f8a 100644 --- a/bin/node-template/node/src/rpc.rs +++ b/bin/node-template/node/src/rpc.rs @@ -7,12 +7,12 @@ use std::sync::Arc; -use node_template_runtime::{opaque::Block, AccountId, Balance, Index}; +use crate::service::{Hash, Block, AccountId, Index, Balance}; pub use sc_rpc_api::DenyUnsafe; use sc_transaction_pool_api::TransactionPool; use sp_api::ProvideRuntimeApi; -use sp_block_builder::BlockBuilder; use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; +use pallet_transaction_payment_rpc::TransactionPaymentRuntimeDispatchInfo; /// Full client dependencies. pub struct FullDeps { @@ -30,9 +30,6 @@ where C: ProvideRuntimeApi, C: HeaderBackend + HeaderMetadata + 'static, C: Send + Sync + 'static, - C::Api: substrate_frame_rpc_system::AccountNonceApi, - C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, - C::Api: BlockBuilder, P: TransactionPool + 'static, { use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi}; @@ -41,9 +38,9 @@ where let mut io = jsonrpc_core::IoHandler::default(); let FullDeps { client, pool, deny_unsafe } = deps; - io.extend_with(SystemApi::to_delegate(FullSystem::new(client.clone(), pool, deny_unsafe))); + io.extend_with(SystemApi::::to_delegate(FullSystem::new(client.clone(), pool, deny_unsafe))); - io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new(client.clone()))); + io.extend_with(TransactionPaymentApi::<_, TransactionPaymentRuntimeDispatchInfo>::to_delegate(TransactionPayment::new(client.clone()))); // Extend this RPC with a custom API by using the following syntax. // `YourRpcStruct` should have a reference to a client, which is needed diff --git a/bin/node-template/node/src/service.rs b/bin/node-template/node/src/service.rs index 8b0937b614f7c..5e829566895e8 100644 --- a/bin/node-template/node/src/service.rs +++ b/bin/node-template/node/src/service.rs @@ -1,6 +1,5 @@ //! Service and ServiceFactory implementation. Specialized wrapper over substrate service. -use node_template_runtime::{self, opaque::Block, RuntimeApi}; use sc_client_api::{BlockBackend, ExecutorProvider}; use sc_consensus_aura::{ImportQueueParams, SlotProportion, StartAuraParams}; pub use sc_executor::NativeElseWasmExecutor; @@ -12,28 +11,23 @@ use sp_consensus::SlotData; use sp_consensus_aura::sr25519::AuthorityPair as AuraPair; use std::{sync::Arc, time::Duration}; -// Our native executor instance. -pub struct ExecutorDispatch; +type Header = sp_runtime::generic::Header; +pub type Block = sp_runtime::generic::Block; +/// Some way of identifying an account on the chain. We intentionally make it equivalent +/// to the public key of our transaction signing scheme. +pub type AccountId = <::Signer as sp_runtime::traits::IdentifyAccount>::AccountId; -impl sc_executor::NativeExecutionDispatch for ExecutorDispatch { - /// Only enable the benchmarking host functions when we actually want to benchmark. - #[cfg(feature = "runtime-benchmarks")] - type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions; - /// Otherwise we only use the default Substrate host functions. - #[cfg(not(feature = "runtime-benchmarks"))] - type ExtendHostFunctions = (); +/// Balance of an account. +pub type Balance = u128; - fn dispatch(method: &str, data: &[u8]) -> Option> { - node_template_runtime::api::dispatch(method, data) - } +/// Index of a transaction in the chain. +pub type Index = u32; - fn native_version() -> sc_executor::NativeVersion { - node_template_runtime::native_version() - } -} +/// A hash of some data used by the chain. +pub type Hash = sp_core::H256; type FullClient = - sc_service::TFullClient>; + sc_service::TFullClient; type FullBackend = sc_service::TFullBackend; type FullSelectChain = sc_consensus::LongestChain; @@ -74,15 +68,16 @@ pub fn new_partial( }) .transpose()?; - let executor = NativeElseWasmExecutor::::new( + let executor = sc_executor::DefaultExecutor::new( config.wasm_method, config.default_heap_pages, config.max_runtime_instances, + None, config.runtime_cache_size, ); let (client, backend, keystore_container, task_manager) = - sc_service::new_full_parts::( + sc_service::new_full_parts::( &config, telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()), executor, diff --git a/bin/node-template/runtime/src/lib.rs b/bin/node-template/runtime/src/lib.rs index 0b39d76fe495e..183db23d5bd3f 100644 --- a/bin/node-template/runtime/src/lib.rs +++ b/bin/node-template/runtime/src/lib.rs @@ -11,7 +11,7 @@ use pallet_grandpa::{ }; use sp_api::impl_runtime_apis; use sp_consensus_aura::sr25519::AuthorityId as AuraId; -use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; +use sp_core::{crypto::{KeyTypeId, dev_keys::*}, OpaqueMetadata}; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, NumberFor, Verify}, @@ -515,4 +515,82 @@ impl_runtime_apis! { Ok(batches) } } + + impl sp_api::Genesis for Runtime { + fn build_dev() { + let endowed_accounts = [ + ALICE_SR25519.into(), + BOB_SR25519.into(), + CHARLIE_SR25519.into(), + DAVE_SR25519.into(), + EVE_SR25519.into(), + FERDIE_SR25519.into(), + ALICE_STASH.into(), + BOB_STASH.into(), + CHARLIE_STASH.into(), + DAVE_STASH.into(), + EVE_STASH.into(), + FERDIE_STASH.into(), + ]; + testnet_genesis( + &[(ALICE_SR25519.into(), ALICE_ED25519.into())], + ALICE_SR25519.into(), + &endowed_accounts, + ).execute() + } + + fn build_local() { + let endowed_accounts = [ + ALICE_SR25519.into(), + BOB_SR25519.into(), + CHARLIE_SR25519.into(), + DAVE_SR25519.into(), + EVE_SR25519.into(), + FERDIE_SR25519.into(), + ALICE_STASH.into(), + BOB_STASH.into(), + CHARLIE_STASH.into(), + DAVE_STASH.into(), + EVE_STASH.into(), + FERDIE_STASH.into(), + ]; + testnet_genesis( + &[(ALICE_SR25519.into(), ALICE_ED25519.into()), (BOB_SR25519.into(), BOB_ED25519.into())], + ALICE_SR25519.into(), + &endowed_accounts, + ).execute() + } + + fn build_genesis() { + GenesisConfig::default().execute() + } + } +} + +/// Configure initial storage state for FRAME modules. +fn testnet_genesis( + initial_authorities: &[(AuraId, GrandpaId)], + root_key: AccountId, + endowed_accounts: &[AccountId], +) -> GenesisConfig { + GenesisConfig { + system: SystemConfig { + code: vec![], + }, + balances: BalancesConfig { + // Configure endowed accounts with initial balance of 1 << 60. + balances: endowed_accounts.iter().cloned().map(|k| (k, 1 << 60)).collect(), + }, + aura: AuraConfig { + authorities: initial_authorities.iter().map(|x| (x.0.clone())).collect(), + }, + grandpa: GrandpaConfig { + authorities: initial_authorities.iter().map(|x| (x.1.clone(), 1)).collect(), + }, + sudo: SudoConfig { + // Assign network admin rights. + key: Some(root_key), + }, + transaction_payment: Default::default(), + } } diff --git a/bin/node/cli/build.rs b/bin/node/cli/build.rs index 008332c6f746f..b087bb443a8be 100644 --- a/bin/node/cli/build.rs +++ b/bin/node/cli/build.rs @@ -28,7 +28,6 @@ fn main() { fn build_runtime() { let mut path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); path.push("../runtime/Cargo.toml"); - eprintln!("CAN: {:?}", path.canonicalize().unwrap()); WasmBuilder::new() .with_project(path.canonicalize().unwrap()).unwrap() .export_heap_base() diff --git a/bin/node/cli/src/chain_spec.rs b/bin/node/cli/src/chain_spec.rs index fdce351c1749c..feeb89b50c6ef 100644 --- a/bin/node/cli/src/chain_spec.rs +++ b/bin/node/cli/src/chain_spec.rs @@ -38,7 +38,6 @@ mod runtime { } } - /// Node `ChainSpec` extensions. /// /// Additional parameters for some Substrate core modules, diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index 313483443cff8..2fe6fed276c96 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -30,7 +30,7 @@ use frame_support::{ traits::{ ConstU128, ConstU16, ConstU32, Currency, EnsureOneOf, EqualPrivilegeOnly, Everything, Imbalance, InstanceFilter, KeyOwnerProofSystem, LockIdentifier, Nothing, OnUnbalanced, - U128CurrencyToVote, GenesisBuild, + U128CurrencyToVote, }, weights::{ constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND}, @@ -56,7 +56,7 @@ use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo}; use sp_api::impl_runtime_apis; use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId; use sp_core::{ - crypto::{UncheckedInto, KeyTypeId}, + crypto::{UncheckedInto, KeyTypeId, dev_keys::*}, u32_trait::{_1, _2, _3, _4, _5}, OpaqueMetadata, }; @@ -1985,23 +1985,6 @@ impl_runtime_apis! { } } -const ALICE_SR25519: sr25519::Public = sr25519::Public(hex!["d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"]); -const ALICE_ED25519: ed25519::Public = ed25519::Public(hex!["88dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee"]); -const BOB_SR25519: sr25519::Public = sr25519::Public(hex!["8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48"]); -const BOB_ED25519: ed25519::Public = ed25519::Public(hex!["d17c2d7823ebf260fd138f2d7e27d114c0145d968b5ff5006125f2414fadae69"]); - -const CHARLIE_SR25519: sr25519::Public = sr25519::Public(hex!["90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22"]); -const DAVE_SR25519: sr25519::Public = sr25519::Public(hex!["306721211d5404bd9da88e0204360a1a9ab8b87c66c1bc2fcdd37f3c2222cc20"]); -const EVE_SR25519: sr25519::Public = sr25519::Public(hex!["e659a7a1628cdd93febc04a4e0646ea20e9f5f0ce097d9a05290d4a9e054df4e"]); -const FERDIE_SR25519: sr25519::Public = sr25519::Public(hex!["1cbd2d43530a44705ad088af313e18f80b53ef16b36177cd4b77b846f2a5f07c"]); - -const ALICE_STASH: sr25519::Public = sr25519::Public(hex!["be5ddb1579b72e84524fc29e78609e3caf42e85aa118ebfe0b0ad404b5bdd25f"]); -const BOB_STASH: sr25519::Public = sr25519::Public(hex!["fe65717dad0447d715f660a0a58411de509b42e6efb8375f562f58a554d5860e"]); -const CHARLIE_STASH: sr25519::Public = sr25519::Public(hex!["1e07379407fecc4b89eb7dbd287c2c781cfb1907a96947a3eb18e4f8e7198625"]); -const DAVE_STASH: sr25519::Public = sr25519::Public(hex!["e860f1b1c7227f7c22602f53f15af80747814dffd839719731ee3bba6edc126c"]); -const EVE_STASH: sr25519::Public = sr25519::Public(hex!["8ac59e11963af19174d0b94d5d78041c233f55d2e19324665bafdfb62925af2d"]); -const FERDIE_STASH: sr25519::Public = sr25519::Public(hex!["101191192fc877c24d725b337120fa3edc63d227bbc92705db1e2cb65f56981a"]); - /// Helper function to generate stash, controller and session keys pub fn authority_keys(sr25519_key: sr25519::Public, stash_key: sr25519::Public, ed25519_key: ed25519::Public) diff --git a/bin/node/testing/src/bench.rs b/bin/node/testing/src/bench.rs index 18333280bb8a4..c068496e13bd0 100644 --- a/bin/node/testing/src/bench.rs +++ b/bin/node/testing/src/bench.rs @@ -46,7 +46,7 @@ use sc_client_api::{ }; use sc_client_db::PruningMode; use sc_consensus::{BlockImport, BlockImportParams, ForkChoiceStrategy, ImportResult, ImportedAux}; -use sc_executor::{NativeElseWasmExecutor, WasmExecutionMethod}; +use sc_executor::WasmExecutionMethod; use sp_api::ProvideRuntimeApi; use sp_block_builder::BlockBuilder; use sp_consensus::BlockOrigin; @@ -400,7 +400,7 @@ impl BenchDb { let backend = sc_service::new_db_backend(db_config).expect("Should not fail"); let client = sc_service::new_client( backend.clone(), - NativeElseWasmExecutor::new(WasmExecutionMethod::Compiled, None, 8, 2), + sc_executor::DefaultExecutor::new(WasmExecutionMethod::Compiled, None, 8, None, 2), &keyring.generate_genesis(), None, None, diff --git a/bin/node/testing/src/client.rs b/bin/node/testing/src/client.rs index 8cb98511098f1..7522c4a06ae55 100644 --- a/bin/node/testing/src/client.rs +++ b/bin/node/testing/src/client.rs @@ -32,9 +32,7 @@ pub type Backend = sc_client_db::Backend; /// Test client type. pub type Client = client::Client< Backend, - client::LocalCallExecutor, node_primitives::Block, - node_runtime::RuntimeApi, >; /// Transaction for node-runtime. @@ -62,7 +60,6 @@ pub trait TestClientBuilderExt: Sized { impl TestClientBuilderExt for substrate_test_client::TestClientBuilder< node_primitives::Block, - client::LocalCallExecutor, Backend, GenesisParameters, > @@ -72,6 +69,6 @@ impl TestClientBuilderExt } fn build(self) -> Client { - self.build_with_native_executor(None).0 + self.build_with_wasm_executor(None).0 } } diff --git a/bin/utils/chain-spec-builder/Cargo.toml b/bin/utils/chain-spec-builder/Cargo.toml index f6af82ba42eb0..06de034c10565 100644 --- a/bin/utils/chain-spec-builder/Cargo.toml +++ b/bin/utils/chain-spec-builder/Cargo.toml @@ -21,5 +21,6 @@ rand = "0.8" sc-keystore = { version = "4.0.0-dev", path = "../../../client/keystore" } sc-chain-spec = { version = "4.0.0-dev", path = "../../../client/chain-spec" } node-cli = { version = "3.0.0-dev", path = "../../node/cli" } +node-runtime = { version = "3.0.0-dev", path = "../../node/runtime" } sp-core = { version = "5.0.0", path = "../../../primitives/core" } sp-keystore = { version = "0.11.0", path = "../../../primitives/keystore" } diff --git a/bin/utils/chain-spec-builder/src/main.rs b/bin/utils/chain-spec-builder/src/main.rs index 3e8b1f4ea7523..42570bad8cc63 100644 --- a/bin/utils/chain-spec-builder/src/main.rs +++ b/bin/utils/chain-spec-builder/src/main.rs @@ -27,6 +27,7 @@ use clap::Parser; use rand::{distributions::Alphanumeric, rngs::OsRng, Rng}; use node_cli::chain_spec::{self, AccountId}; +use node_runtime::GenesisConfig; use sc_keystore::LocalKeystore; use sp_core::{ crypto::{ByteArray, Ss58Codec}, diff --git a/client/authority-discovery/src/worker/tests.rs b/client/authority-discovery/src/worker/tests.rs index 904c674d269bc..fd7f0b4c04273 100644 --- a/client/authority-discovery/src/worker/tests.rs +++ b/client/authority-discovery/src/worker/tests.rs @@ -46,8 +46,6 @@ pub(crate) struct TestApi { } impl ProvideRuntimeApi for TestApi { - type Api = RuntimeApi; - fn runtime_api<'a>(&'a self) -> ApiRef<'a, Self::Api> { RuntimeApi { authorities: self.authorities.clone() }.into() } diff --git a/client/basic-authorship/src/basic_authorship.rs b/client/basic-authorship/src/basic_authorship.rs index 3635556637f46..c41ee10265dbc 100644 --- a/client/basic-authorship/src/basic_authorship.rs +++ b/client/basic-authorship/src/basic_authorship.rs @@ -561,7 +561,7 @@ mod tests { use sc_client_api::Backend; use sc_transaction_pool::BasicPool; use sc_transaction_pool_api::{ChainEvent, MaintainedTransactionPool, TransactionSource}; - use sp_api::Core; + use sp_api::{Core, ProvideRuntimeApi}; use sp_blockchain::HeaderBackend; use sp_consensus::{BlockOrigin, Environment, Proposer}; use sp_core::Pair; diff --git a/client/cli/src/commands/insert_key.rs b/client/cli/src/commands/insert_key.rs index 852b4e50376ff..0be90ca5dbdf9 100644 --- a/client/cli/src/commands/insert_key.rs +++ b/client/cli/src/commands/insert_key.rs @@ -124,16 +124,13 @@ mod tests { "test".into() } - fn native_runtime_version(_: &Box) -> &'static sp_version::RuntimeVersion { - unimplemented!("Not required in tests") - } - fn load_spec(&self, _: &str) -> std::result::Result, String> { - Ok(Box::new(GenericChainSpec::from_genesis( + Ok(Box::new(GenericChainSpec::<(), _>::from_runtime( "test", "test_id", ChainType::Development, - || unimplemented!("Not required in tests"), + &[], + "undefined", Vec::new(), None, None, diff --git a/client/consensus/babe/src/tests.rs b/client/consensus/babe/src/tests.rs index 7c04dc03c2f24..dd894346dab7a 100644 --- a/client/consensus/babe/src/tests.rs +++ b/client/consensus/babe/src/tests.rs @@ -55,9 +55,7 @@ type Error = sp_blockchain::Error; type TestClient = substrate_test_runtime_client::client::Client< substrate_test_runtime_client::Backend, - substrate_test_runtime_client::ExecutorDispatch, TestBlock, - substrate_test_runtime_client::runtime::RuntimeApi, >; #[derive(Copy, Clone, PartialEq)] diff --git a/client/network/test/src/lib.rs b/client/network/test/src/lib.rs index 3986ac47f3616..2503780da47c3 100644 --- a/client/network/test/src/lib.rs +++ b/client/network/test/src/lib.rs @@ -122,9 +122,7 @@ impl Verifier for PassThroughVerifier { pub type PeersFullClient = Client< substrate_test_runtime_client::Backend, - substrate_test_runtime_client::ExecutorDispatch, Block, - substrate_test_runtime_client::runtime::RuntimeApi, >; #[derive(Clone)] diff --git a/client/service/src/client/call_executor.rs b/client/service/src/client/call_executor.rs index 311807d3a6cb7..b90f7fc81c698 100644 --- a/client/service/src/client/call_executor.rs +++ b/client/service/src/client/call_executor.rs @@ -373,11 +373,9 @@ mod tests { // client is used for the convenience of creating and inserting the genesis block. let _client = substrate_test_runtime_client::client::new_with_backend::< - _, _, runtime::Block, _, - runtime::RuntimeApi, >( backend.clone(), executor.clone(), diff --git a/client/service/test/src/client/mod.rs b/client/service/test/src/client/mod.rs index 2b0ea460c4dd3..c08ac9e7a1d51 100644 --- a/client/service/test/src/client/mod.rs +++ b/client/service/test/src/client/mod.rs @@ -29,7 +29,7 @@ use sc_client_db::{ use sc_consensus::{ BlockCheckParams, BlockImport, BlockImportParams, ForkChoiceStrategy, ImportResult, }; -use sc_service::client::{new_in_mem, Client, LocalCallExecutor}; +use sc_service::client::{new_in_mem, Client}; use sp_api::ProvideRuntimeApi; use sp_consensus::{BlockOrigin, BlockStatus, Error as ConsensusError, SelectChain}; use sp_core::{testing::TaskExecutor, H256}; @@ -46,10 +46,9 @@ use sp_trie::{LayoutV0, TrieConfiguration}; use std::{collections::HashSet, sync::Arc}; use substrate_test_runtime::TestAPI; use substrate_test_runtime_client::{ - prelude::*, runtime::{ genesismap::{insert_genesis_block, GenesisConfig}, - Block, BlockNumber, Digest, Hash, Header, RuntimeApi, Transfer, + Block, BlockNumber, Digest, Hash, Header, Transfer, }, AccountKeyring, BlockBuilderExt, ClientBlockImportExt, ClientExt, DefaultTestClientBuilderExt, Sr25519Keyring, TestClientBuilder, TestClientBuilderExt, @@ -1723,8 +1722,8 @@ fn cleans_up_closed_notification_sinks_on_block_import() { // NOTE: we need to build the client here instead of using the client // provided by test_runtime_client otherwise we can't access the private // `import_notification_sinks` and `finality_notification_sinks` fields. - let mut client = new_in_mem::<_, Block, _, RuntimeApi>( - substrate_test_runtime_client::new_native_executor(), + let mut client = new_in_mem::( + substrate_test_runtime_client::new_executor(), &substrate_test_runtime_client::GenesisParameters::default().genesis_storage(), None, None, @@ -1736,13 +1735,7 @@ fn cleans_up_closed_notification_sinks_on_block_import() { type TestClient = Client< in_mem::Backend, - LocalCallExecutor< - Block, - in_mem::Backend, - sc_executor::NativeElseWasmExecutor, - >, Block, - RuntimeApi, >; let import_notif1 = client.import_notification_stream(); diff --git a/client/service/test/src/lib.rs b/client/service/test/src/lib.rs index 67b33dfd55d13..f721b111739a0 100644 --- a/client/service/test/src/lib.rs +++ b/client/service/test/src/lib.rs @@ -21,7 +21,7 @@ use futures::{task::Poll, Future, TryFutureExt as _}; use log::{debug, info}; use parking_lot::Mutex; -use sc_client_api::{Backend, CallExecutor}; +use sc_client_api::Backend; use sc_network::{ config::{NetworkConfiguration, TransportConfig}, multiaddr, Multiaddr, @@ -69,11 +69,9 @@ pub trait TestNetNode: { type Block: BlockT; type Backend: Backend; - type Executor: CallExecutor + Send + Sync; - type RuntimeApi: Send + Sync; type TransactionPool: TransactionPool; - fn client(&self) -> Arc>; + fn client(&self) -> Arc>; fn transaction_pool(&self) -> Arc; fn network( &self, @@ -81,19 +79,19 @@ pub trait TestNetNode: fn spawn_handle(&self) -> SpawnTaskHandle; } -pub struct TestNetComponents { +pub struct TestNetComponents { task_manager: Arc>, - client: Arc>, + client: Arc>, transaction_pool: Arc, network: Arc::Hash>>, } -impl - TestNetComponents +impl + TestNetComponents { pub fn new( task_manager: TaskManager, - client: Arc>, + client: Arc>, network: Arc::Hash>>, transaction_pool: Arc, ) -> Self { @@ -101,8 +99,8 @@ impl } } -impl Clone - for TestNetComponents +impl Clone + for TestNetComponents { fn clone(&self) -> Self { Self { @@ -114,8 +112,8 @@ impl Clone } } -impl Future - for TestNetComponents +impl Future + for TestNetComponents { type Output = Result<(), sc_service::Error>; @@ -124,22 +122,18 @@ impl Future } } -impl TestNetNode - for TestNetComponents +impl TestNetNode + for TestNetComponents where TBl: BlockT, TBackend: sc_client_api::Backend + Send + Sync + 'static, - TExec: CallExecutor + Send + Sync + 'static, - TRtApi: Send + Sync + 'static, TExPool: TransactionPool + Send + Sync + 'static, { type Block = TBl; type Backend = TBackend; - type Executor = TExec; - type RuntimeApi = TRtApi; type TransactionPool = TExPool; - fn client(&self) -> Arc> { + fn client(&self) -> Arc> { self.client.clone() } fn transaction_pool(&self) -> Arc { diff --git a/frame/aura/src/lib.rs b/frame/aura/src/lib.rs index 657965c60a3f1..6913c32457e64 100644 --- a/frame/aura/src/lib.rs +++ b/frame/aura/src/lib.rs @@ -40,7 +40,7 @@ use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ - traits::{DisabledValidators, FindAuthor, Get, OnTimestampSet, OneSessionHandler}, + traits::{DisabledValidators, FindAuthor, Get, OnTimestampSet, OneSessionHandler, GenesisBuild}, BoundedSlice, ConsensusEngineId, Parameter, WeakBoundedVec, }; use sp_consensus_aura::{AuthorityIndex, ConsensusLog, Slot, AURA_ENGINE_ID}; @@ -130,7 +130,6 @@ pub mod pallet { pub authorities: Vec, } - #[cfg(feature = "std")] impl Default for GenesisConfig { fn default() -> Self { Self { authorities: Vec::new() } diff --git a/frame/support/procedural/src/construct_runtime/expand/config.rs b/frame/support/procedural/src/construct_runtime/expand/config.rs index 991bf96414c25..23c01c62b602e 100644 --- a/frame/support/procedural/src/construct_runtime/expand/config.rs +++ b/frame/support/procedural/src/construct_runtime/expand/config.rs @@ -67,10 +67,10 @@ pub fn expand_outer_config( #[cfg(any(feature = "std", test))] use #scrate::serde as __genesis_config_serde_import__; #[derive(Default)] - #[cfg_attr(feature = "std", derive(#scrate::serde::Serialize, #scrate::serde::Deserialize))] - #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] - #[cfg_attr(feature = "std", serde(deny_unknown_fields))] - #[cfg_attr(feature = "std", serde(crate = "__genesis_config_serde_import__"))] + #[cfg_attr(any(feature = "std", test), derive(#scrate::serde::Serialize, #scrate::serde::Deserialize))] + #[cfg_attr(any(feature = "std", test), serde(rename_all = "camelCase"))] + #[cfg_attr(any(feature = "std", test), serde(deny_unknown_fields))] + #[cfg_attr(any(feature = "std", test), serde(crate = "__genesis_config_serde_import__"))] pub struct GenesisConfig { #fields } @@ -83,14 +83,16 @@ pub fn expand_outer_config( } #[cfg(any(feature = "std", test))] - impl GenesisConfig { + impl #scrate::sp_runtime::BuildStorage for GenesisConfig { fn assimilate_storage( &self, storage: &mut #scrate::sp_runtime::Storage, ) -> std::result::Result<(), String> { #build_storage_calls - ::on_genesis(); + #scrate::BasicExternalities::execute_with_storage(storage, || { + ::on_genesis(); + }); Ok(()) } diff --git a/frame/support/procedural/src/pallet/expand/genesis_config.rs b/frame/support/procedural/src/pallet/expand/genesis_config.rs index 3cb446a2e2509..ec0fe82c288fd 100644 --- a/frame/support/procedural/src/pallet/expand/genesis_config.rs +++ b/frame/support/procedural/src/pallet/expand/genesis_config.rs @@ -94,15 +94,23 @@ pub fn expand_genesis_config(def: &mut Def) -> proc_macro2::TokenStream { "] )); } - //attrs.push(syn::parse_quote!( #[cfg(feature = "std")] )); attrs.push(syn::parse_quote!( - #[cfg_attr(feature = "std", derive(#frame_support::Serialize, #frame_support::Deserialize))] + #[cfg_attr(any(feature = "std", test), derive(#frame_support::Serialize, #frame_support::Deserialize))] )); - attrs.push(syn::parse_quote!( #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] )); - attrs.push(syn::parse_quote!( #[cfg_attr(feature = "std", serde(deny_unknown_fields))] )); - attrs.push(syn::parse_quote!( #[cfg_attr(feature = "std", serde(bound(serialize = "")))] )); - attrs.push(syn::parse_quote!( #[cfg_attr(feature = "std", serde(bound(deserialize = "")))] )); - attrs.push(syn::parse_quote!( #[cfg_attr(feature = "std", serde(crate = #serde_crate))] )); + attrs.push(syn::parse_quote!( #[cfg_att(any(feature = "std", test), serde(rename_all = "camelCase"))] )); + attrs.push(syn::parse_quote!( #[cfg_att(any(feature = "std", test), serde(deny_unknown_fields))] )); + attrs.push(syn::parse_quote!( #[cfg_att(any(feature = "std", test), serde(bound(serialize = "")))] )); + attrs.push(syn::parse_quote!( #[cfg_att(any(feature = "std", test), serde(bound(deserialize = "")))] )); + attrs.push(syn::parse_quote!( #[cfg_att(any(feature = "std", test), serde(crate = #serde_crate))] )); + + + for a in attrs.iter_mut() { + if let Some(mut segment) = a.path.segments.first_mut() { + if segment.ident == "cfg_att" { + segment.ident = Ident::new("cfg_attr", segment.ident.span()); + } + } + } }, _ => unreachable!("Checked by genesis_config parser"), } @@ -116,22 +124,6 @@ pub fn expand_genesis_config(def: &mut Def) -> proc_macro2::TokenStream { ($pallet_name:ident) => {}; } - #[cfg(not(feature = "std"))] - #[macro_export] - #[doc(hidden)] - macro_rules! #std_macro_ident { - ($pallet_name:ident, $pallet_path:expr) => { - compile_error!(concat!( - "`", - stringify!($pallet_name), - "` does not have the std feature enabled, this will cause the `", - $pallet_path, - "::GenesisConfig` type to be undefined." - )); - }; - } - - #[cfg(feature = "std")] #[macro_export] #[doc(hidden)] macro_rules! #std_macro_ident { diff --git a/frame/support/procedural/src/storage/genesis_config/mod.rs b/frame/support/procedural/src/storage/genesis_config/mod.rs index 5581a2ca831a7..d4348ee19171c 100644 --- a/frame/support/procedural/src/storage/genesis_config/mod.rs +++ b/frame/support/procedural/src/storage/genesis_config/mod.rs @@ -72,7 +72,7 @@ fn decl_genesis_config_and_impl_default( #[derive(#scrate::Serialize, #scrate::Deserialize)] #[cfg(feature = "std")] #[serde(rename_all = "camelCase")] - #[serde(deny_unknown_field)] + #[serde(deny_unknown_fields)] #[serde(crate = #serde_crate)] #serde_bug_bound pub struct GenesisConfig #genesis_struct_decl #genesis_where_clause { diff --git a/frame/support/test/Cargo.toml b/frame/support/test/Cargo.toml index 9f26df4869afc..105853c9cc13b 100644 --- a/frame/support/test/Cargo.toml +++ b/frame/support/test/Cargo.toml @@ -45,6 +45,7 @@ std = [ "sp-state-machine", "sp-arithmetic/std", "sp-version/std", + "test-pallet/std", ] try-runtime = ["frame-support/try-runtime"] # WARNING: CI only execute pallet test with this feature, diff --git a/frame/support/test/pallet/src/lib.rs b/frame/support/test/pallet/src/lib.rs index 25741313c2a03..fddb202518ab0 100644 --- a/frame/support/test/pallet/src/lib.rs +++ b/frame/support/test/pallet/src/lib.rs @@ -30,7 +30,7 @@ pub mod pallet { pub trait Config: frame_system::Config {} #[pallet::genesis_config] - #[cfg_attr(feature = "std", derive(Default))] + #[derive(Default)] pub struct GenesisConfig {} #[pallet::genesis_build] diff --git a/frame/support/test/src/lib.rs b/frame/support/test/src/lib.rs index dd3fbd1f3020d..306d643182b20 100644 --- a/frame/support/test/src/lib.rs +++ b/frame/support/test/src/lib.rs @@ -18,10 +18,13 @@ //! Test crate for frame_support. Allow to make use of `frame_support::decl_storage`. //! See tests directory. + // Make sure we fail compilation on warnings #![warn(missing_docs)] #![deny(warnings)] +mod pallet_with_name_trait_is_valid; + /// The configuration trait pub trait Config: 'static { /// The runtime origin type. diff --git a/frame/system/src/tests.rs b/frame/system/src/tests.rs index 0facd796b2a0c..a0e6fcf9162e7 100644 --- a/frame/system/src/tests.rs +++ b/frame/system/src/tests.rs @@ -412,7 +412,7 @@ fn assert_runtime_updated_digest(num: usize) { #[test] fn set_code_with_real_wasm_blob() { - let executor = substrate_test_runtime_client::new_native_executor(); + let executor = substrate_test_runtime_client::new_executor(); let mut ext = new_test_ext(); ext.register_extension(sp_core::traits::ReadRuntimeVersionExt::new(executor)); ext.execute_with(|| { @@ -436,7 +436,7 @@ fn set_code_with_real_wasm_blob() { #[test] fn runtime_upgraded_with_set_storage() { - let executor = substrate_test_runtime_client::new_native_executor(); + let executor = substrate_test_runtime_client::new_executor(); let mut ext = new_test_ext(); ext.register_extension(sp_core::traits::ReadRuntimeVersionExt::new(executor)); ext.execute_with(|| { diff --git a/primitives/api/proc-macro/src/decl_runtime_apis.rs b/primitives/api/proc-macro/src/decl_runtime_apis.rs index f2996a85d3d34..977bdd8774ade 100644 --- a/primitives/api/proc-macro/src/decl_runtime_apis.rs +++ b/primitives/api/proc-macro/src/decl_runtime_apis.rs @@ -920,10 +920,7 @@ fn generate_call_impl(decls: &[ItemTrait]) -> Result { for decl in decls { let mut decl = decl.clone(); extend_generics_with_block(&mut decl.generics); - //let mod_name = generate_runtime_mod_name_for_trait(&decl.ident); let ident = &decl.ident; - //let found_attributes = remove_supported_attributes(&mut decl.attrs); - //let call_at_impl = _generate_call_api_impls(&decl)?; let runtime_api_call_impl = generate_runtime_api_call_impl(&decl)?; let impl_generics = decl.generics.type_params().map(|t| { @@ -947,14 +944,6 @@ fn generate_call_impl(decls: &[ItemTrait]) -> Result { let ty_generics: Vec<_> = ty_generics.collect(); result.push(quote!( - /* - #[doc(hidden)] - #[cfg(any(feature = "std", test))] - impl #ident< #( #ty_generics, )* > for T - where Block: #crate_::BlockT, T: #crate_::CallApiAt + Send + Sync + 'static, #where_clause { - #call_at_impl - } -*/ #[doc(hidden)] #[cfg(any(feature = "std", test))] impl<'a, C, #( #impl_generics, )* > #ident< #( #ty_generics, )* > for #crate_::RuntimeApi<'a, Block, C> diff --git a/primitives/api/src/lib.rs b/primitives/api/src/lib.rs index 73bfcde3510d7..2689787f01047 100644 --- a/primitives/api/src/lib.rs +++ b/primitives/api/src/lib.rs @@ -531,18 +531,6 @@ pub struct RuntimeApi<'a, Block: BlockT, C: CallApiAt> { pub recorder: Option>, } -/* -#[cfg(any(feature = "std", test))] -unsafe impl> Send - for RuntimeApiImpl -{} - -#[cfg(any(feature = "std", test))] -unsafe impl> Sync - for RuntimeApiImpl -{} -*/ - #[cfg(any(feature = "std", test))] impl<'a, Block: BlockT, C: CallApiAt> ApiExt for RuntimeApi<'a, Block, C> { type StateBackend = C::StateBackend; diff --git a/primitives/api/test/tests/decl_and_impl.rs b/primitives/api/test/tests/decl_and_impl.rs index 1db416a1d3db6..831e67fe52712 100644 --- a/primitives/api/test/tests/decl_and_impl.rs +++ b/primitives/api/test/tests/decl_and_impl.rs @@ -136,9 +136,7 @@ mock_impl_runtime_apis! { type TestClient = substrate_test_runtime_client::client::Client< substrate_test_runtime_client::Backend, - substrate_test_runtime_client::ExecutorDispatch, Block, - RuntimeApi, >; #[test] diff --git a/primitives/core/Cargo.toml b/primitives/core/Cargo.toml index bd41635a1d7a1..ab0be1bb06143 100644 --- a/primitives/core/Cargo.toml +++ b/primitives/core/Cargo.toml @@ -45,6 +45,7 @@ futures = { version = "0.3.1", optional = true } dyn-clonable = { version = "0.9.0", optional = true } thiserror = { version = "1.0.30", optional = true } bitflags = "1.3" +hex-literal = "0.3.4" # full crypto ed25519-dalek = { version = "1.0.1", default-features = false, features = ["u64_backend", "alloc"], optional = true } @@ -65,7 +66,6 @@ sp-runtime-interface = { version = "5.0.0", default-features = false, path = ".. [dev-dependencies] sp-serializer = { version = "4.0.0-dev", path = "../serializer" } -hex-literal = "0.3.4" rand = "0.7.2" criterion = "0.3.3" serde_json = "1.0" diff --git a/primitives/core/src/crypto.rs b/primitives/core/src/crypto.rs index 12f8397eee4a4..7c2812fbdf1c9 100644 --- a/primitives/core/src/crypto.rs +++ b/primitives/core/src/crypto.rs @@ -1123,6 +1123,41 @@ pub mod key_types { pub const DUMMY: KeyTypeId = KeyTypeId(*b"dumy"); } +/// Public keys commonly used for development and testing. +pub mod dev_keys { + use crate::{sr25519, ed25519}; + /// //Alice + pub const ALICE_SR25519: sr25519::Public = sr25519::Public(hex_literal::hex!["d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"]); + /// //Alice + pub const ALICE_ED25519: ed25519::Public = ed25519::Public(hex_literal::hex!["88dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee"]); + /// //Bob + pub const BOB_SR25519: sr25519::Public = sr25519::Public(hex_literal::hex!["8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48"]); + /// //Bob + pub const BOB_ED25519: ed25519::Public = ed25519::Public(hex_literal::hex!["d17c2d7823ebf260fd138f2d7e27d114c0145d968b5ff5006125f2414fadae69"]); + + /// //Charlie + pub const CHARLIE_SR25519: sr25519::Public = sr25519::Public(hex_literal::hex!["90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22"]); + /// //Dave + pub const DAVE_SR25519: sr25519::Public = sr25519::Public(hex_literal::hex!["306721211d5404bd9da88e0204360a1a9ab8b87c66c1bc2fcdd37f3c2222cc20"]); + /// //Eve + pub const EVE_SR25519: sr25519::Public = sr25519::Public(hex_literal::hex!["e659a7a1628cdd93febc04a4e0646ea20e9f5f0ce097d9a05290d4a9e054df4e"]); + /// //Ferdie + pub const FERDIE_SR25519: sr25519::Public = sr25519::Public(hex_literal::hex!["1cbd2d43530a44705ad088af313e18f80b53ef16b36177cd4b77b846f2a5f07c"]); + + /// //Alice//stash + pub const ALICE_STASH: sr25519::Public = sr25519::Public(hex_literal::hex!["be5ddb1579b72e84524fc29e78609e3caf42e85aa118ebfe0b0ad404b5bdd25f"]); + /// //Bob//stash + pub const BOB_STASH: sr25519::Public = sr25519::Public(hex_literal::hex!["fe65717dad0447d715f660a0a58411de509b42e6efb8375f562f58a554d5860e"]); + /// //Charlie//stash + pub const CHARLIE_STASH: sr25519::Public = sr25519::Public(hex_literal::hex!["1e07379407fecc4b89eb7dbd287c2c781cfb1907a96947a3eb18e4f8e7198625"]); + /// //Dave//stash + pub const DAVE_STASH: sr25519::Public = sr25519::Public(hex_literal::hex!["e860f1b1c7227f7c22602f53f15af80747814dffd839719731ee3bba6edc126c"]); + /// //Eve//stash + pub const EVE_STASH: sr25519::Public = sr25519::Public(hex_literal::hex!["8ac59e11963af19174d0b94d5d78041c233f55d2e19324665bafdfb62925af2d"]); + /// //Ferdie//stash + pub const FERDIE_STASH: sr25519::Public = sr25519::Public(hex_literal::hex!["101191192fc877c24d725b337120fa3edc63d227bbc92705db1e2cb65f56981a"]); +} + #[cfg(test)] mod tests { use super::*; diff --git a/test-utils/runtime/client/src/block_builder_ext.rs b/test-utils/runtime/client/src/block_builder_ext.rs index 66b0b4c3b881b..34338d03c06ca 100644 --- a/test-utils/runtime/client/src/block_builder_ext.rs +++ b/test-utils/runtime/client/src/block_builder_ext.rs @@ -18,9 +18,7 @@ //! Block Builder extensions for tests. use sc_client_api::backend; -use sp_api::{ApiExt, ProvideRuntimeApi}; - -use sc_block_builder::BlockBuilderApi; +use sp_api::CallApiAt; /// Extension trait for test block builder. pub trait BlockBuilderExt { @@ -40,12 +38,7 @@ pub trait BlockBuilderExt { impl<'a, A, B> BlockBuilderExt for sc_block_builder::BlockBuilder<'a, substrate_test_runtime::Block, A, B> where - A: ProvideRuntimeApi + 'a, - A::Api: BlockBuilderApi - + ApiExt< - substrate_test_runtime::Block, - StateBackend = backend::StateBackendFor, - >, + A: CallApiAt + 'a, B: backend::Backend, { fn push_transfer( diff --git a/test-utils/runtime/client/src/lib.rs b/test-utils/runtime/client/src/lib.rs index fe0fef3516671..e401a10b53aff 100644 --- a/test-utils/runtime/client/src/lib.rs +++ b/test-utils/runtime/client/src/lib.rs @@ -47,7 +47,7 @@ pub mod prelude { }; // Client structs pub use super::{ - Backend, ExecutorDispatch, LocalExecutorDispatch, NativeElseWasmExecutor, TestClient, + Backend, LocalExecutorDispatch, NativeElseWasmExecutor, TestClient, TestClientBuilder, WasmExecutionMethod, }; // Keyring @@ -73,12 +73,6 @@ impl sc_executor::NativeExecutionDispatch for LocalExecutorDispatch { /// Test client database backend. pub type Backend = substrate_test_client::Backend; -/// Test client executor. -pub type ExecutorDispatch = client::LocalCallExecutor< - substrate_test_runtime::Block, - Backend, - NativeElseWasmExecutor, ->; /// Parameters of test-client builder with test-runtime. #[derive(Default)] @@ -156,9 +150,8 @@ impl substrate_test_client::GenesisInit for GenesisParameters { } /// A `TestClient` with `test-runtime` builder. -pub type TestClientBuilder = substrate_test_client::TestClientBuilder< +pub type TestClientBuilder = substrate_test_client::TestClientBuilder< substrate_test_runtime::Block, - E, B, GenesisParameters, >; @@ -166,13 +159,7 @@ pub type TestClientBuilder = substrate_test_client::TestClientBuilder< /// Test client type with `LocalExecutorDispatch` and generic Backend. pub type Client = client::Client< B, - client::LocalCallExecutor< - substrate_test_runtime::Block, - B, - sc_executor::NativeElseWasmExecutor, - >, substrate_test_runtime::Block, - substrate_test_runtime::RuntimeApi, >; /// A test client with default backend. @@ -184,7 +171,7 @@ pub trait DefaultTestClientBuilderExt: Sized { fn new() -> Self; } -impl DefaultTestClientBuilderExt for TestClientBuilder { +impl DefaultTestClientBuilderExt for TestClientBuilder { fn new() -> Self { Self::with_default_backend() } @@ -256,14 +243,7 @@ pub trait TestClientBuilderExt: Sized { } impl TestClientBuilderExt - for TestClientBuilder< - client::LocalCallExecutor< - substrate_test_runtime::Block, - B, - sc_executor::NativeElseWasmExecutor, - >, - B, - > where + for TestClientBuilder where B: sc_client_api::backend::Backend + 'static, { fn genesis_init_mut(&mut self) -> &mut GenesisParameters { @@ -273,12 +253,12 @@ impl TestClientBuilderExt fn build_with_longest_chain( self, ) -> (Client, sc_consensus::LongestChain) { - self.build_with_native_executor(None) + self.build_with_wasm_executor(None) } fn build_with_backend(self) -> (Client, Arc) { let backend = self.backend(); - (self.build_with_native_executor(None).0, backend) + (self.build_with_wasm_executor(None).0, backend) } } @@ -288,11 +268,12 @@ pub fn new() -> Client { } /// Create a new native executor. -pub fn new_native_executor() -> sc_executor::NativeElseWasmExecutor { - sc_executor::NativeElseWasmExecutor::new( +pub fn new_executor() -> sc_executor::DefaultExecutor { + sc_executor::DefaultExecutor::new( sc_executor::WasmExecutionMethod::Interpreted, None, 8, + None, 2, ) } diff --git a/utils/frame/rpc/system/src/lib.rs b/utils/frame/rpc/system/src/lib.rs index cc7f4fa792346..41aff5b1846dc 100644 --- a/utils/frame/rpc/system/src/lib.rs +++ b/utils/frame/rpc/system/src/lib.rs @@ -197,7 +197,7 @@ mod tests { transaction_validity::{InvalidTransaction, TransactionValidityError}, ApplyExtrinsicResult, }; - use substrate_test_runtime_client::{runtime::Transfer, AccountKeyring}; + use substrate_test_runtime_client::{runtime::{AccountId, Transfer, Index}, AccountKeyring}; #[test] fn should_return_next_nonce_for_some_account() { @@ -228,10 +228,10 @@ mod tests { let accounts = FullSystem::new(client, pool, DenyUnsafe::Yes); // when - let nonce = accounts.nonce(AccountKeyring::Alice.into()); + let nonce = SystemApi::<_, AccountId, Index>::nonce(&accounts, AccountKeyring::Alice.into()); // then - assert_eq!(block_on(nonce).unwrap(), 2); + assert_eq!(block_on(nonce).unwrap() as Index, 2); } #[test] @@ -247,7 +247,7 @@ mod tests { let accounts = FullSystem::new(client, pool, DenyUnsafe::Yes); // when - let res = accounts.dry_run(vec![].into(), None); + let res = SystemApi::<_, AccountId, Index>::dry_run(&accounts, vec![].into(), None); // then assert_eq!(block_on(res), Err(RpcError::method_not_found())); @@ -274,7 +274,7 @@ mod tests { .into_signed_tx(); // when - let res = accounts.dry_run(tx.encode().into(), None); + let res = SystemApi::<_, AccountId, Index>::dry_run(&accounts, tx.encode().into(), None); // then let bytes = block_on(res).unwrap().0; @@ -303,7 +303,7 @@ mod tests { .into_signed_tx(); // when - let res = accounts.dry_run(tx.encode().into(), None); + let res = SystemApi::<_, AccountId, Index>::dry_run(&accounts, tx.encode().into(), None); // then let bytes = block_on(res).unwrap().0; From fcc794f25cb6f8f4dd7499792049ec9e78d23368 Mon Sep 17 00:00:00 2001 From: arkpar Date: Tue, 15 Feb 2022 22:11:53 +0100 Subject: [PATCH 05/14] More fixes --- Cargo.lock | 6 ++ bin/node/cli/Cargo.toml | 8 ++ bin/node/cli/src/chain_spec.rs | 19 ++--- .../authority-discovery/src/worker/tests.rs | 12 +-- .../basic-authorship/src/basic_authorship.rs | 2 +- client/consensus/aura/src/lib.rs | 2 +- client/finality-grandpa/src/tests.rs | 16 ++-- client/service/src/client/call_executor.rs | 7 +- .../src/construct_runtime/expand/config.rs | 4 + .../proc-macro/src/mock_impl_runtime_apis.rs | 82 +++++++++++++++++-- primitives/api/test/tests/decl_and_impl.rs | 7 +- 11 files changed, 118 insertions(+), 47 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a5e162314bf31..c6c729952a03c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4665,6 +4665,8 @@ dependencies = [ "clap_complete", "criterion", "frame-benchmarking-cli", + "frame-system", + "frame-system-rpc-runtime-api", "futures 0.3.16", "hex-literal", "jsonrpsee-ws-client 0.4.1", @@ -4673,8 +4675,12 @@ dependencies = [ "node-inspect", "node-primitives", "node-rpc", + "node-runtime", + "pallet-asset-tx-payment", "pallet-balances", + "pallet-im-online", "pallet-timestamp", + "pallet-transaction-payment", "parity-scale-codec", "platforms", "rand 0.8.4", diff --git a/bin/node/cli/Cargo.toml b/bin/node/cli/Cargo.toml index af564edbd2ec3..ec347c041887a 100644 --- a/bin/node/cli/Cargo.toml +++ b/bin/node/cli/Cargo.toml @@ -122,6 +122,14 @@ wait-timeout = "0.2" remote-externalities = { path = "../../../utils/frame/remote-externalities" } pallet-timestamp = { version = "4.0.0-dev", path = "../../../frame/timestamp" } +# native runtime dependencies used in integration tests +frame-system = { version = "4.0.0-dev", path = "../../../frame/system" } +frame-system-rpc-runtime-api = { version = "4.0.0-dev", path = "../../../frame/system/rpc/runtime-api" } +pallet-transaction-payment = { version = "4.0.0-dev", path = "../../../frame/transaction-payment" } +pallet-asset-tx-payment = { version = "4.0.0-dev", path = "../../../frame/transaction-payment/asset-tx-payment/" } +pallet-im-online = { version = "4.0.0-dev", default-features = false, path = "../../../frame/im-online" } +node-runtime = { version = "3.0.0-dev", path = "../runtime" } + [build-dependencies] clap = { version = "3.0", optional = true } clap_complete = { version = "3.0", optional = true } diff --git a/bin/node/cli/src/chain_spec.rs b/bin/node/cli/src/chain_spec.rs index feeb89b50c6ef..8b9e3577aed24 100644 --- a/bin/node/cli/src/chain_spec.rs +++ b/bin/node/cli/src/chain_spec.rs @@ -123,22 +123,14 @@ pub(crate) mod tests { use sc_service_test; use sp_runtime::BuildStorage; - fn local_testnet_genesis_instant_single() -> GenesisConfig { - testnet_genesis( - vec![authority_keys_from_seed("Alice")], - vec![], - get_account_id_from_seed::("Alice"), - None, - ) - } - /// Local testnet config (single validator - Alice) pub fn integration_test_config_with_single_authority() -> ChainSpec { - ChainSpec::from_genesis( + ChainSpec::from_runtime( "Integration Test", "test", ChainType::Development, - local_testnet_genesis_instant_single, + runtime::wasm_binary_unwrap(), + "Genesis_build_dev", vec![], None, None, @@ -150,11 +142,12 @@ pub(crate) mod tests { /// Local testnet config (multivalidator Alice + Bob) pub fn integration_test_config_with_two_authorities() -> ChainSpec { - ChainSpec::from_genesis( + ChainSpec::from_runtime( "Integration Test", "test", ChainType::Development, - local_testnet_genesis, + runtime::wasm_binary_unwrap(), + "Genesis_build_local", vec![], None, None, diff --git a/client/authority-discovery/src/worker/tests.rs b/client/authority-discovery/src/worker/tests.rs index fd7f0b4c04273..ff578c9df42b8 100644 --- a/client/authority-discovery/src/worker/tests.rs +++ b/client/authority-discovery/src/worker/tests.rs @@ -33,7 +33,7 @@ use futures::{ use libp2p::{core::multiaddr, PeerId}; use prometheus_endpoint::prometheus::default_registry; -use sp_api::{ApiRef, ProvideRuntimeApi}; +use sp_api::{ProvideRuntimeApi}; use sp_keystore::{testing::KeyStore, CryptoStore}; use sp_runtime::traits::{Block as BlockT, NumberFor, Zero}; use substrate_test_runtime_client::runtime::Block; @@ -46,8 +46,8 @@ pub(crate) struct TestApi { } impl ProvideRuntimeApi for TestApi { - fn runtime_api<'a>(&'a self) -> ApiRef<'a, Self::Api> { - RuntimeApi { authorities: self.authorities.clone() }.into() + fn runtime_api<'a>(&'a self) -> sp_api::RuntimeApi<'a, Block, Self> { + sp_api::RuntimeApi::new(self) } } @@ -95,12 +95,8 @@ impl HeaderBackend for TestApi { } } -pub(crate) struct RuntimeApi { - authorities: Vec, -} - sp_api::mock_impl_runtime_apis! { - impl AuthorityDiscoveryApi for RuntimeApi { + impl AuthorityDiscoveryApi for TestApi { fn authorities(&self) -> Vec { self.authorities.clone() } diff --git a/client/basic-authorship/src/basic_authorship.rs b/client/basic-authorship/src/basic_authorship.rs index c41ee10265dbc..adefb53afacc2 100644 --- a/client/basic-authorship/src/basic_authorship.rs +++ b/client/basic-authorship/src/basic_authorship.rs @@ -561,7 +561,7 @@ mod tests { use sc_client_api::Backend; use sc_transaction_pool::BasicPool; use sc_transaction_pool_api::{ChainEvent, MaintainedTransactionPool, TransactionSource}; - use sp_api::{Core, ProvideRuntimeApi}; + use sp_api::{Core, ProvideRuntimeApi, ApiExt}; use sp_blockchain::HeaderBackend; use sp_consensus::{BlockOrigin, Environment, Proposer}; use sp_core::Pair; diff --git a/client/consensus/aura/src/lib.rs b/client/consensus/aura/src/lib.rs index c8b0092e88cd4..849c66f77a6cb 100644 --- a/client/consensus/aura/src/lib.rs +++ b/client/consensus/aura/src/lib.rs @@ -792,7 +792,7 @@ mod tests { assert_eq!(client.chain_info().best_number, 0); assert_eq!( - authorities(&client, &BlockId::Number(0)).unwrap(), + authorities::, _, _>(&client, &BlockId::Number(0)).unwrap(), vec![ Keyring::Alice.public().into(), Keyring::Bob.public().into(), diff --git a/client/finality-grandpa/src/tests.rs b/client/finality-grandpa/src/tests.rs index 2e545b6e88ebf..0a1bfb42c015c 100644 --- a/client/finality-grandpa/src/tests.rs +++ b/client/finality-grandpa/src/tests.rs @@ -33,7 +33,7 @@ use sc_network_test::{ Block, BlockImportAdapter, FullPeerConfig, Hash, PassThroughVerifier, Peer, PeersClient, PeersFullClient, TestClient, TestNetFactory, }; -use sp_api::{ApiRef, ProvideRuntimeApi}; +use sp_api::ProvideRuntimeApi; use sp_blockchain::Result; use sp_consensus::BlockOrigin; use sp_core::H256; @@ -177,22 +177,16 @@ impl TestApi { } } -pub(crate) struct RuntimeApi { - inner: TestApi, -} - impl ProvideRuntimeApi for TestApi { - type Api = RuntimeApi; - - fn runtime_api<'a>(&'a self) -> ApiRef<'a, Self::Api> { - RuntimeApi { inner: self.clone() }.into() + fn runtime_api<'a>(&'a self) -> sp_api::RuntimeApi<'a, Block, Self> { + sp_api::RuntimeApi::new(self) } } sp_api::mock_impl_runtime_apis! { - impl GrandpaApi for RuntimeApi { + impl GrandpaApi for TestApi { fn grandpa_authorities(&self) -> AuthorityList { - self.inner.genesis_authorities.clone() + self.genesis_authorities.clone() } fn current_set_id(&self) -> SetId { diff --git a/client/service/src/client/call_executor.rs b/client/service/src/client/call_executor.rs index b90f7fc81c698..91c5f23eb9fa1 100644 --- a/client/service/src/client/call_executor.rs +++ b/client/service/src/client/call_executor.rs @@ -341,19 +341,20 @@ where mod tests { use super::*; use sc_client_api::in_mem; - use sc_executor::{NativeElseWasmExecutor, WasmExecutionMethod}; + use sc_executor::WasmExecutionMethod; use sp_core::{ testing::TaskExecutor, traits::{FetchRuntimeCode, WrappedRuntimeCode}, }; - use substrate_test_runtime_client::{runtime, GenesisInit, LocalExecutorDispatch}; + use substrate_test_runtime_client::{runtime, GenesisInit}; #[test] fn should_get_override_if_exists() { - let executor = NativeElseWasmExecutor::::new( + let executor = sc_executor::DefaultExecutor::new( WasmExecutionMethod::Interpreted, Some(128), 1, + None, 2, ); diff --git a/frame/support/procedural/src/construct_runtime/expand/config.rs b/frame/support/procedural/src/construct_runtime/expand/config.rs index 23c01c62b602e..1755647436671 100644 --- a/frame/support/procedural/src/construct_runtime/expand/config.rs +++ b/frame/support/procedural/src/construct_runtime/expand/config.rs @@ -76,10 +76,14 @@ pub fn expand_outer_config( } impl GenesisConfig { + #[cfg(not(feature = "std"))] pub fn execute(&self) { #build_execute_calls ::on_genesis(); } + #[cfg(feature = "std")] + pub fn execute(&self) { + } } #[cfg(any(feature = "std", test))] diff --git a/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs b/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs index ffc158ac94d29..3b91eae159eb4 100644 --- a/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs +++ b/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs @@ -18,8 +18,8 @@ use crate::utils::{ extract_block_type_from_trait_path, extract_impl_trait, extract_parameter_names_types_and_borrows, generate_crate_access, generate_hidden_includes, - generate_method_runtime_api_impl_name, return_type_extract_type, AllowSelfRefInParameters, - RequireQualifiedTraitPath, + generate_method_runtime_api_impl_name, return_type_extract_type, prefix_function_with_trait, + AllowSelfRefInParameters, RequireQualifiedTraitPath, }; use proc_macro2::{Span, TokenStream}; @@ -224,6 +224,8 @@ struct FoldRuntimeApiImpl<'a> { block_type: &'a TypePath, /// The identifier of the trait being implemented. impl_trait: &'a Ident, + /// Match arms for mock implementation of `CallApiAt` + call_arms: Vec, } impl<'a> Fold for FoldRuntimeApiImpl<'a> { @@ -272,7 +274,7 @@ impl<'a> Fold for FoldRuntimeApiImpl<'a> { }, }; - let param_types = param_types_and_borrows.iter().map(|v| &v.0); + let param_types: Vec<_> = param_types_and_borrows.iter().map(|v| &v.0).collect(); // Rewrite the input parameters. input.sig.inputs = parse_quote! { &self, @@ -282,14 +284,15 @@ impl<'a> Fold for FoldRuntimeApiImpl<'a> { _: Vec, }; + let call_name = prefix_function_with_trait(&self.impl_trait, &input.sig.ident); + input.sig.ident = generate_method_runtime_api_impl_name(&self.impl_trait, &input.sig.ident); // When using advanced, the user needs to declare the correct return type on its own, // otherwise do it for the user. + let ret_type = return_type_extract_type(&input.sig.output); if !is_advanced { - let ret_type = return_type_extract_type(&input.sig.output); - // Generate the correct return type. input.sig.output = parse_quote!( -> std::result::Result<#crate_::NativeOrEncoded<#ret_type>, #crate_::ApiError> @@ -308,6 +311,27 @@ impl<'a> Fold for FoldRuntimeApiImpl<'a> { } }; + let call_name_str = call_name.to_string(); + + let call_arm = quote!( + #call_name_str => { + let (#( #param_names ),*) : ( #( #param_types ),* ) = + match #crate_::DecodeLimit::decode_all_with_depth_limit( + #crate_::MAX_EXTRINSIC_DEPTH, + ¶ms.arguments, + ) { + Ok(res) => res, + Err(e) => panic!("Bad input data provided to {}: {}", #call_name_str, e), + }; + let at = ¶ms.at; + let r = { #orig_block } as #ret_type; + let encoded = #crate_::Encode::encode(&r); + Ok(#crate_::NativeOrEncoded::Encoded(encoded)) + }, + ); + + self.call_arms.push(call_arm); + // Generate the new method implementation that calls into the runtime. parse_quote!( { @@ -338,6 +362,8 @@ struct GeneratedRuntimeApiImpls { block_type: TypePath, /// The type the traits are implemented for. self_ty: Type, + /// Match arms for mock implementation of `CallApiAt` + call_arms: Vec, } /// Generate the runtime api implementations from the given trait implementations. @@ -349,6 +375,7 @@ fn generate_runtime_api_impls(impls: &[ItemImpl]) -> Result = None; let mut self_ty: Option> = None; + let mut call_arms = Vec::new(); for impl_ in impls { let impl_trait_path = extract_impl_trait(&impl_, RequireQualifiedTraitPath::No)?; let impl_trait = &impl_trait_path @@ -395,13 +422,19 @@ fn generate_runtime_api_impls(impls: &[ItemImpl]) -> Result Some(block_type.clone()), }; - let mut visitor = FoldRuntimeApiImpl { block_type, impl_trait: &impl_trait.ident }; + let mut visitor = FoldRuntimeApiImpl { + block_type, + impl_trait: &impl_trait.ident, + call_arms: Default::default(), + }; result.push(visitor.fold_item_impl(impl_.clone())); + call_arms.extend(visitor.call_arms); } Ok(GeneratedRuntimeApiImpls { impls: quote!( #( #result )* ), + call_arms, block_type: global_block_type.expect("There is a least one runtime api; qed"), self_ty: *self_ty.expect("There is at least one runtime api; qed"), }) @@ -419,9 +452,10 @@ pub fn mock_impl_runtime_apis_impl(input: proc_macro::TokenStream) -> proc_macro fn mock_impl_runtime_apis_impl_inner(api_impls: &[ItemImpl]) -> Result { let hidden_includes = generate_hidden_includes(HIDDEN_INCLUDES_ID); - let GeneratedRuntimeApiImpls { impls, block_type, self_ty } = + let crate_ = generate_crate_access(HIDDEN_INCLUDES_ID); + let GeneratedRuntimeApiImpls { impls, call_arms, block_type, self_ty } = generate_runtime_api_impls(api_impls)?; - let api_traits = implement_common_api_traits(block_type, self_ty)?; + let api_traits = implement_common_api_traits(block_type.clone(), self_ty.clone())?; Ok(quote!( #hidden_includes @@ -429,5 +463,37 @@ fn mock_impl_runtime_apis_impl_inner(api_impls: &[ItemImpl]) -> Result for #self_ty { + type StateBackend = #crate_::InMemoryBackend<#crate_::HashFor<#block_type>>; + + fn call_api_at<'a, R: #crate_::Encode + #crate_::Decode, NC: FnOnce() + -> std::result::Result + std::panic::UnwindSafe>( + &self, + params: sp_api::CallApiAtParams<'a, #block_type, NC, Self::StateBackend>, + ) -> std::result::Result<#crate_::NativeOrEncoded, #crate_::ApiError> { + match params.function { + #( #call_arms )* + f @ _ => { + unimplemented!("Called unexpected mock method {}", f) + } + } + } + + fn runtime_version_at(&self, _at: &#crate_::BlockId<#block_type>) + -> std::result::Result<#crate_::RuntimeVersion, #crate_::ApiError> + { + Ok(#crate_::RuntimeVersion { + spec_name: #crate_::RuntimeString::Borrowed("mock_spec"), + impl_name: #crate_::RuntimeString::Borrowed("mock_impl"), + authoring_version: 0, + spec_version: 0, + impl_version: 0, + apis: std::borrow::Cow::Borrowed(&[]), + transaction_version: 0, + state_version: 0, + }) + } + } )) } diff --git a/primitives/api/test/tests/decl_and_impl.rs b/primitives/api/test/tests/decl_and_impl.rs index 831e67fe52712..26c2ed27c6981 100644 --- a/primitives/api/test/tests/decl_and_impl.rs +++ b/primitives/api/test/tests/decl_and_impl.rs @@ -16,7 +16,7 @@ // limitations under the License. use sp_api::{ - decl_runtime_apis, impl_runtime_apis, mock_impl_runtime_apis, ApiError, ApiExt, RuntimeApiInfo, + decl_runtime_apis, impl_runtime_apis, mock_impl_runtime_apis, ApiError, RuntimeApiInfo, }; use sp_core::NativeOrEncoded; use sp_runtime::{ @@ -89,6 +89,7 @@ struct MockApi { block: Option, } +/* mock_impl_runtime_apis! { impl Api for MockApi { fn test(_: u64) { @@ -132,7 +133,7 @@ mock_impl_runtime_apis! { impl ApiWithCustomVersion for MockApi { fn same_name() {} } -} +}*/ type TestClient = substrate_test_runtime_client::client::Client< substrate_test_runtime_client::Backend, @@ -187,6 +188,7 @@ fn check_runtime_api_versions() { check_runtime_api_versions_contains::>(); } +/* #[test] fn mock_runtime_api_has_api() { let mock = MockApi { block: None }; @@ -215,3 +217,4 @@ fn mock_runtime_api_works_with_advanced() { mock.wild_card(&BlockId::Number(1336), 1).unwrap_err().to_string(), ); } +*/ From 4b2aef8b6f56172ae0015e02f2eaa9d4dfd32de3 Mon Sep 17 00:00:00 2001 From: arkpar Date: Tue, 15 Feb 2022 22:13:43 +0100 Subject: [PATCH 06/14] Restore tests --- frame/support/test/src/lib.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/frame/support/test/src/lib.rs b/frame/support/test/src/lib.rs index 306d643182b20..0b4f9d8773e2a 100644 --- a/frame/support/test/src/lib.rs +++ b/frame/support/test/src/lib.rs @@ -23,8 +23,6 @@ #![warn(missing_docs)] #![deny(warnings)] -mod pallet_with_name_trait_is_valid; - /// The configuration trait pub trait Config: 'static { /// The runtime origin type. From 84990af0e7a493ccf1f8c628903595165fd6a526 Mon Sep 17 00:00:00 2001 From: arkpar Date: Wed, 16 Feb 2022 12:25:26 +0100 Subject: [PATCH 07/14] More test fixes --- bin/node/cli/Cargo.toml | 2 +- client/rpc/src/state/tests.rs | 7 +------ frame/balances/src/lib.rs | 4 +++- test-utils/runtime/src/lib.rs | 27 +++++++++++++++++++++++++++ 4 files changed, 32 insertions(+), 8 deletions(-) diff --git a/bin/node/cli/Cargo.toml b/bin/node/cli/Cargo.toml index ec347c041887a..00db844e7bc5d 100644 --- a/bin/node/cli/Cargo.toml +++ b/bin/node/cli/Cargo.toml @@ -30,7 +30,7 @@ path = "bin/main.rs" required-features = ["cli"] [lib] -crate-type = ["cdylib", "rlib"] +#crate-type = ["cdylib", "rlib"] [dependencies] # third-party dependencies diff --git a/client/rpc/src/state/tests.rs b/client/rpc/src/state/tests.rs index 9dbe02cdb7d64..d7b3ebc9a37a2 100644 --- a/client/rpc/src/state/tests.rs +++ b/client/rpc/src/state/tests.rs @@ -525,12 +525,7 @@ fn should_return_runtime_version() { None, ); - let result = "{\"specName\":\"test\",\"implName\":\"parity-test\",\"authoringVersion\":1,\ - \"specVersion\":2,\"implVersion\":2,\"apis\":[[\"0xdf6acb689907609b\",4],\ - [\"0x37e397fc7c91f5e4\",1],[\"0xd2bc9897eed08f15\",3],[\"0x40fe3ad401f8959a\",5],\ - [\"0xc6e9a76309f39b09\",1],[\"0xdd718d5cc53262d4\",1],[\"0xcbca25e39f142387\",2],\ - [\"0xf78b278be53f454c\",2],[\"0xab3c0572291feb8b\",1],[\"0xbc9d89904f5b923f\",1]],\ - \"transactionVersion\":1,\"stateVersion\":1}"; + let result = "{\"specName\":\"test\",\"implName\":\"parity-test\",\"authoringVersion\":1,\"specVersion\":2,\"implVersion\":2,\"apis\":[[\"0xdf6acb689907609b\",4],[\"0x37e397fc7c91f5e4\",1],[\"0xd2bc9897eed08f15\",3],[\"0x40fe3ad401f8959a\",5],[\"0xc6e9a76309f39b09\",1],[\"0xdd718d5cc53262d4\",1],[\"0xed99c5acb25eedf5\",3],[\"0xcbca25e39f142387\",2],[\"0xf78b278be53f454c\",2],[\"0xab3c0572291feb8b\",1],[\"0xbc9d89904f5b923f\",1]],\"transactionVersion\":1,\"stateVersion\":1}"; let runtime_version = executor::block_on(api.runtime_version(None.into())).unwrap(); let serialized = serde_json::to_string(&runtime_version).unwrap(); diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index 9bede9163fec3..68934878dfa5c 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -579,12 +579,14 @@ pub mod pallet { ) } - let endowed_accounts = self + let mut endowed_accounts = self .balances .iter() .map(|(x, _)| x) .cloned() .collect::>(); + endowed_accounts.sort(); + endowed_accounts.dedup(); assert!( endowed_accounts.len() == self.balances.len(), diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index 861d95efb3087..7fbcaad570e4b 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -1096,6 +1096,33 @@ cfg_if! { } } + impl sp_finality_grandpa::GrandpaApi for Runtime { + fn grandpa_authorities() -> sp_finality_grandpa::AuthorityList { + Vec::new() + } + + fn current_set_id() -> sp_finality_grandpa::SetId { + 0 + } + + fn submit_report_equivocation_unsigned_extrinsic( + _equivocation_proof: sp_finality_grandpa::EquivocationProof< + ::Hash, + BlockNumber, + >, + _key_owner_proof: sp_finality_grandpa::OpaqueKeyOwnershipProof, + ) -> Option<()> { + None + } + + fn generate_key_ownership_proof( + _set_id: sp_finality_grandpa::SetId, + _authority_id: sp_finality_grandpa::AuthorityId, + ) -> Option { + None + } + } + impl sp_consensus_babe::BabeApi for Runtime { fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration { sp_consensus_babe::BabeGenesisConfiguration { From 11bba7916a34ee566862df5a6fa37563eab3b918 Mon Sep 17 00:00:00 2001 From: arkpar Date: Thu, 17 Feb 2022 09:27:09 +0100 Subject: [PATCH 08/14] Additional test fixes --- bin/node/cli/Cargo.toml | 3 - bin/node/cli/build.rs | 1 + client/rpc/src/state/tests.rs | 2 +- .../no_std_genesis_config.rs | 51 ---------- .../no_std_genesis_config.stderr | 51 ---------- .../undefined_genesis_config_part.stderr | 35 +++---- .../tests/derive_no_bound_ui/clone.stderr | 14 +-- .../tests/derive_no_bound_ui/default.stderr | 14 +-- .../call_argument_invalid_bound.stderr | 14 +-- .../call_argument_invalid_bound_2.stderr | 68 +++++-------- .../pallet_ui/event_field_not_member.stderr | 14 +-- ...age_ensure_span_are_ok_on_wrong_gen.stderr | 99 ++++++------------- ...re_span_are_ok_on_wrong_gen_unnamed.stderr | 99 ++++++------------- .../pallet_ui/storage_info_unsatisfied.stderr | 17 ++-- .../storage_info_unsatisfied_nmap.stderr | 5 - .../api/proc-macro/src/decl_runtime_apis.rs | 2 +- .../proc-macro/src/mock_impl_runtime_apis.rs | 21 +++- primitives/api/test/tests/decl_and_impl.rs | 10 +- primitives/api/test/tests/runtime_calls.rs | 25 +---- .../ui/changed_in_no_default_method.stderr | 4 +- test-utils/runtime/src/lib.rs | 12 +-- 21 files changed, 161 insertions(+), 400 deletions(-) delete mode 100644 frame/support/test/tests/construct_runtime_ui/no_std_genesis_config.rs delete mode 100644 frame/support/test/tests/construct_runtime_ui/no_std_genesis_config.stderr diff --git a/bin/node/cli/Cargo.toml b/bin/node/cli/Cargo.toml index 00db844e7bc5d..a1a8219206be6 100644 --- a/bin/node/cli/Cargo.toml +++ b/bin/node/cli/Cargo.toml @@ -29,9 +29,6 @@ name = "substrate" path = "bin/main.rs" required-features = ["cli"] -[lib] -#crate-type = ["cdylib", "rlib"] - [dependencies] # third-party dependencies clap = { version = "3.0", features = ["derive"], optional = true } diff --git a/bin/node/cli/build.rs b/bin/node/cli/build.rs index b087bb443a8be..4325c44597b4f 100644 --- a/bin/node/cli/build.rs +++ b/bin/node/cli/build.rs @@ -32,6 +32,7 @@ fn build_runtime() { .with_project(path.canonicalize().unwrap()).unwrap() .export_heap_base() .import_memory() + .enable_feature("runtime-benchmarks") .build() } diff --git a/client/rpc/src/state/tests.rs b/client/rpc/src/state/tests.rs index d7b3ebc9a37a2..b94ddcc30e04d 100644 --- a/client/rpc/src/state/tests.rs +++ b/client/rpc/src/state/tests.rs @@ -525,7 +525,7 @@ fn should_return_runtime_version() { None, ); - let result = "{\"specName\":\"test\",\"implName\":\"parity-test\",\"authoringVersion\":1,\"specVersion\":2,\"implVersion\":2,\"apis\":[[\"0xdf6acb689907609b\",4],[\"0x37e397fc7c91f5e4\",1],[\"0xd2bc9897eed08f15\",3],[\"0x40fe3ad401f8959a\",5],[\"0xc6e9a76309f39b09\",1],[\"0xdd718d5cc53262d4\",1],[\"0xed99c5acb25eedf5\",3],[\"0xcbca25e39f142387\",2],[\"0xf78b278be53f454c\",2],[\"0xab3c0572291feb8b\",1],[\"0xbc9d89904f5b923f\",1]],\"transactionVersion\":1,\"stateVersion\":1}"; + let result = "{\"specName\":\"test\",\"implName\":\"parity-test\",\"authoringVersion\":1,\"specVersion\":2,\"implVersion\":2,\"apis\":[[\"0xdf6acb689907609b\",4],[\"0x37e397fc7c91f5e4\",1],[\"0xd2bc9897eed08f15\",3],[\"0x40fe3ad401f8959a\",5],[\"0xc6e9a76309f39b09\",2],[\"0xdd718d5cc53262d4\",1],[\"0xed99c5acb25eedf5\",3],[\"0xcbca25e39f142387\",2],[\"0xf78b278be53f454c\",2],[\"0xab3c0572291feb8b\",1],[\"0xbc9d89904f5b923f\",1]],\"transactionVersion\":1,\"stateVersion\":1}"; let runtime_version = executor::block_on(api.runtime_version(None.into())).unwrap(); let serialized = serde_json::to_string(&runtime_version).unwrap(); diff --git a/frame/support/test/tests/construct_runtime_ui/no_std_genesis_config.rs b/frame/support/test/tests/construct_runtime_ui/no_std_genesis_config.rs deleted file mode 100644 index c06333795e3c5..0000000000000 --- a/frame/support/test/tests/construct_runtime_ui/no_std_genesis_config.rs +++ /dev/null @@ -1,51 +0,0 @@ -use frame_support::construct_runtime; -use sp_runtime::{generic, traits::BlakeTwo256}; -use sp_core::sr25519; - -pub type Signature = sr25519::Signature; -pub type BlockNumber = u32; -pub type Header = generic::Header; -pub type Block = generic::Block; -pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; - -impl test_pallet::Config for Runtime {} - -impl frame_system::Config for Runtime { - type BaseCallFilter = frame_support::traits::Everything; - type Origin = Origin; - type Index = u64; - type BlockNumber = u32; - type Call = Call; - type Hash = sp_runtime::testing::H256; - type Hashing = sp_runtime::traits::BlakeTwo256; - type AccountId = u64; - type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; - type Event = Event; - type BlockHashCount = frame_support::traits::ConstU32<250>; - type BlockWeights = (); - type BlockLength = (); - type DbWeight = (); - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = (); - type OnSetCode = (); - type MaxConsumers = frame_support::traits::ConstU32<16>; -} - -construct_runtime! { - pub enum Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic - { - System: frame_system::{Pallet, Call, Storage, Config, Event}, - Pallet: test_pallet::{Pallet, Config}, - } -} - -fn main() {} diff --git a/frame/support/test/tests/construct_runtime_ui/no_std_genesis_config.stderr b/frame/support/test/tests/construct_runtime_ui/no_std_genesis_config.stderr deleted file mode 100644 index 6d5a48bf0909a..0000000000000 --- a/frame/support/test/tests/construct_runtime_ui/no_std_genesis_config.stderr +++ /dev/null @@ -1,51 +0,0 @@ -error: `Pallet` does not have the std feature enabled, this will cause the `test_pallet::GenesisConfig` type to be undefined. - --> tests/construct_runtime_ui/no_std_genesis_config.rs:40:1 - | -40 | / construct_runtime! { -41 | | pub enum Runtime where -42 | | Block = Block, -43 | | NodeBlock = Block, -... | -48 | | } -49 | | } - | |_^ - | - = note: this error originates in the macro `test_pallet::__substrate_genesis_config_check::is_std_enabled_for_genesis` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0412]: cannot find type `GenesisConfig` in crate `test_pallet` - --> tests/construct_runtime_ui/no_std_genesis_config.rs:40:1 - | -40 | / construct_runtime! { -41 | | pub enum Runtime where -42 | | Block = Block, -43 | | NodeBlock = Block, -... | -48 | | } -49 | | } - | |_^ not found in `test_pallet` - | - = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider importing this struct - | -1 | use frame_system::GenesisConfig; - | - -error[E0283]: type annotations needed - --> tests/construct_runtime_ui/no_std_genesis_config.rs:40:1 - | -40 | / construct_runtime! { -41 | | pub enum Runtime where -42 | | Block = Block, -43 | | NodeBlock = Block, -... | -48 | | } -49 | | } - | |_^ cannot infer type - | - = note: cannot satisfy `_: std::default::Default` -note: required by `std::default::Default::default` - --> $RUST/core/src/default.rs - | - | fn default() -> Self; - | ^^^^^^^^^^^^^^^^^^^^^ - = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.stderr b/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.stderr index e8532aa9a064f..ce7cb568f942f 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.stderr @@ -28,27 +28,24 @@ error[E0412]: cannot find type `GenesisConfig` in module `pallet` | |_^ not found in `pallet` | = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider importing this struct +help: consider importing one of these items | 1 | use frame_system::GenesisConfig; | +1 | use test_pallet::GenesisConfig; + | error[E0283]: type annotations needed - --> tests/construct_runtime_ui/undefined_genesis_config_part.rs:49:1 - | -49 | / construct_runtime! { -50 | | pub enum Runtime where -51 | | Block = Block, -52 | | NodeBlock = Block, -... | -57 | | } -58 | | } - | |_^ cannot infer type - | - = note: cannot satisfy `_: std::default::Default` -note: required by `std::default::Default::default` - --> $RUST/core/src/default.rs - | - | fn default() -> Self; - | ^^^^^^^^^^^^^^^^^^^^^ - = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) + --> tests/construct_runtime_ui/undefined_genesis_config_part.rs:49:1 + | +49 | / construct_runtime! { +50 | | pub enum Runtime where +51 | | Block = Block, +52 | | NodeBlock = Block, +... | +57 | | } +58 | | } + | |_^ cannot infer type + | + = note: cannot satisfy `_: std::default::Default` + = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/frame/support/test/tests/derive_no_bound_ui/clone.stderr b/frame/support/test/tests/derive_no_bound_ui/clone.stderr index 45428a8728c21..7744586e56bf4 100644 --- a/frame/support/test/tests/derive_no_bound_ui/clone.stderr +++ b/frame/support/test/tests/derive_no_bound_ui/clone.stderr @@ -1,11 +1,5 @@ error[E0277]: the trait bound `::C: Clone` is not satisfied - --> tests/derive_no_bound_ui/clone.rs:7:2 - | -7 | c: T::C, - | ^ the trait `Clone` is not implemented for `::C` - | -note: required by `clone` - --> $RUST/core/src/clone.rs - | - | fn clone(&self) -> Self; - | ^^^^^^^^^^^^^^^^^^^^^^^^ + --> tests/derive_no_bound_ui/clone.rs:7:2 + | +7 | c: T::C, + | ^ the trait `Clone` is not implemented for `::C` diff --git a/frame/support/test/tests/derive_no_bound_ui/default.stderr b/frame/support/test/tests/derive_no_bound_ui/default.stderr index 7608f877a3b56..d56dd438f2a7f 100644 --- a/frame/support/test/tests/derive_no_bound_ui/default.stderr +++ b/frame/support/test/tests/derive_no_bound_ui/default.stderr @@ -1,11 +1,5 @@ error[E0277]: the trait bound `::C: std::default::Default` is not satisfied - --> $DIR/default.rs:7:2 - | -7 | c: T::C, - | ^ the trait `std::default::Default` is not implemented for `::C` - | -note: required by `std::default::Default::default` - --> $DIR/default.rs:116:5 - | -116 | fn default() -> Self; - | ^^^^^^^^^^^^^^^^^^^^^ + --> tests/derive_no_bound_ui/default.rs:7:2 + | +7 | c: T::C, + | ^ the trait `std::default::Default` is not implemented for `::C` diff --git a/frame/support/test/tests/pallet_ui/call_argument_invalid_bound.stderr b/frame/support/test/tests/pallet_ui/call_argument_invalid_bound.stderr index 9701b1bdd06f3..3a636d9f659c7 100644 --- a/frame/support/test/tests/pallet_ui/call_argument_invalid_bound.stderr +++ b/frame/support/test/tests/pallet_ui/call_argument_invalid_bound.stderr @@ -9,16 +9,10 @@ error[E0277]: `::Bar` doesn't implement `std::fmt::Debug` = note: required for the cast to the object type `dyn std::fmt::Debug` error[E0277]: the trait bound `::Bar: Clone` is not satisfied - --> tests/pallet_ui/call_argument_invalid_bound.rs:20:36 - | -20 | pub fn foo(origin: OriginFor, bar: T::Bar) -> DispatchResultWithPostInfo { - | ^^^ the trait `Clone` is not implemented for `::Bar` - | -note: required by `clone` - --> $RUST/core/src/clone.rs - | - | fn clone(&self) -> Self; - | ^^^^^^^^^^^^^^^^^^^^^^^^ + --> tests/pallet_ui/call_argument_invalid_bound.rs:20:36 + | +20 | pub fn foo(origin: OriginFor, bar: T::Bar) -> DispatchResultWithPostInfo { + | ^^^ the trait `Clone` is not implemented for `::Bar` error[E0369]: binary operation `==` cannot be applied to type `&::Bar` --> tests/pallet_ui/call_argument_invalid_bound.rs:20:36 diff --git a/frame/support/test/tests/pallet_ui/call_argument_invalid_bound_2.stderr b/frame/support/test/tests/pallet_ui/call_argument_invalid_bound_2.stderr index b4a10a6af01f1..c6547df854870 100644 --- a/frame/support/test/tests/pallet_ui/call_argument_invalid_bound_2.stderr +++ b/frame/support/test/tests/pallet_ui/call_argument_invalid_bound_2.stderr @@ -9,16 +9,10 @@ error[E0277]: `::Bar` doesn't implement `std::fmt::Debug` = note: required for the cast to the object type `dyn std::fmt::Debug` error[E0277]: the trait bound `::Bar: Clone` is not satisfied - --> tests/pallet_ui/call_argument_invalid_bound_2.rs:20:36 - | -20 | pub fn foo(origin: OriginFor, bar: T::Bar) -> DispatchResultWithPostInfo { - | ^^^ the trait `Clone` is not implemented for `::Bar` - | -note: required by `clone` - --> $RUST/core/src/clone.rs - | - | fn clone(&self) -> Self; - | ^^^^^^^^^^^^^^^^^^^^^^^^ + --> tests/pallet_ui/call_argument_invalid_bound_2.rs:20:36 + | +20 | pub fn foo(origin: OriginFor, bar: T::Bar) -> DispatchResultWithPostInfo { + | ^^^ the trait `Clone` is not implemented for `::Bar` error[E0369]: binary operation `==` cannot be applied to type `&::Bar` --> tests/pallet_ui/call_argument_invalid_bound_2.rs:20:36 @@ -32,38 +26,26 @@ help: consider further restricting this bound | +++++++++++++++++++++ error[E0277]: the trait bound `::Bar: WrapperTypeEncode` is not satisfied - --> tests/pallet_ui/call_argument_invalid_bound_2.rs:1:1 - | -1 | #[frame_support::pallet] - | ^----------------------- - | | - | _in this procedural macro expansion - | | -2 | | mod pallet { -3 | | use frame_support::pallet_prelude::{Hooks, DispatchResultWithPostInfo}; -4 | | use frame_system::pallet_prelude::{BlockNumberFor, OriginFor}; -... | -16 | | -17 | | #[pallet::call] - | |__________________^ the trait `WrapperTypeEncode` is not implemented for `::Bar` - | - = note: required because of the requirements on the impl of `Encode` for `::Bar` -note: required by a bound in `encode_to` - --> $CARGO/parity-scale-codec-2.3.1/src/codec.rs - | - | fn encode_to(&self, dest: &mut T) { - | ^^^^^^ required by this bound in `encode_to` - = note: this error originates in the derive macro `frame_support::codec::Encode` (in Nightly builds, run with -Z macro-backtrace for more info) + --> tests/pallet_ui/call_argument_invalid_bound_2.rs:20:36 + | +1 | / #[frame_support::pallet] +2 | | mod pallet { +3 | | use frame_support::pallet_prelude::{Hooks, DispatchResultWithPostInfo}; +4 | | use frame_system::pallet_prelude::{BlockNumberFor, OriginFor}; +... | +16 | | +17 | | #[pallet::call] + | |__________________- required by a bound introduced by this call +... +20 | pub fn foo(origin: OriginFor, bar: T::Bar) -> DispatchResultWithPostInfo { + | ^^^ the trait `WrapperTypeEncode` is not implemented for `::Bar` + | + = note: required because of the requirements on the impl of `Encode` for `::Bar` error[E0277]: the trait bound `::Bar: WrapperTypeDecode` is not satisfied - --> tests/pallet_ui/call_argument_invalid_bound_2.rs:20:36 - | -20 | pub fn foo(origin: OriginFor, bar: T::Bar) -> DispatchResultWithPostInfo { - | ^^^ the trait `WrapperTypeDecode` is not implemented for `::Bar` - | - = note: required because of the requirements on the impl of `Decode` for `::Bar` -note: required by a bound in `parity_scale_codec::Decode::decode` - --> $CARGO/parity-scale-codec-2.3.1/src/codec.rs - | - | fn decode(input: &mut I) -> Result; - | ^^^^^ required by this bound in `parity_scale_codec::Decode::decode` + --> tests/pallet_ui/call_argument_invalid_bound_2.rs:20:36 + | +20 | pub fn foo(origin: OriginFor, bar: T::Bar) -> DispatchResultWithPostInfo { + | ^^^ the trait `WrapperTypeDecode` is not implemented for `::Bar` + | + = note: required because of the requirements on the impl of `Decode` for `::Bar` diff --git a/frame/support/test/tests/pallet_ui/event_field_not_member.stderr b/frame/support/test/tests/pallet_ui/event_field_not_member.stderr index ff184db988e3c..3db258a819fcb 100644 --- a/frame/support/test/tests/pallet_ui/event_field_not_member.stderr +++ b/frame/support/test/tests/pallet_ui/event_field_not_member.stderr @@ -1,14 +1,8 @@ error[E0277]: the trait bound `::Bar: Clone` is not satisfied - --> tests/pallet_ui/event_field_not_member.rs:23:7 - | -23 | B { b: T::Bar }, - | ^ the trait `Clone` is not implemented for `::Bar` - | -note: required by `clone` - --> $RUST/core/src/clone.rs - | - | fn clone(&self) -> Self; - | ^^^^^^^^^^^^^^^^^^^^^^^^ + --> tests/pallet_ui/event_field_not_member.rs:23:7 + | +23 | B { b: T::Bar }, + | ^ the trait `Clone` is not implemented for `::Bar` error[E0369]: binary operation `==` cannot be applied to type `&::Bar` --> tests/pallet_ui/event_field_not_member.rs:23:7 diff --git a/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.stderr b/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.stderr index 35f8bbdbd5248..87528751a0a7a 100644 --- a/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.stderr +++ b/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.stderr @@ -7,11 +7,6 @@ error[E0277]: the trait bound `Bar: WrapperTypeDecode` is not satisfied = note: required because of the requirements on the impl of `Decode` for `Bar` = note: required because of the requirements on the impl of `FullCodec` for `Bar` = note: required because of the requirements on the impl of `PartialStorageInfoTrait` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` -note: required by `partial_storage_info` - --> $WORKSPACE/frame/support/src/traits/storage.rs - | - | fn partial_storage_info() -> Vec; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0277]: the trait bound `Bar: EncodeLike` is not satisfied --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:10:12 @@ -22,11 +17,6 @@ error[E0277]: the trait bound `Bar: EncodeLike` is not satisfied = note: required because of the requirements on the impl of `FullEncode` for `Bar` = note: required because of the requirements on the impl of `FullCodec` for `Bar` = note: required because of the requirements on the impl of `PartialStorageInfoTrait` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` -note: required by `partial_storage_info` - --> $WORKSPACE/frame/support/src/traits/storage.rs - | - | fn partial_storage_info() -> Vec; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0277]: the trait bound `Bar: WrapperTypeEncode` is not satisfied --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:10:12 @@ -38,68 +28,43 @@ error[E0277]: the trait bound `Bar: WrapperTypeEncode` is not satisfied = note: required because of the requirements on the impl of `FullEncode` for `Bar` = note: required because of the requirements on the impl of `FullCodec` for `Bar` = note: required because of the requirements on the impl of `PartialStorageInfoTrait` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` -note: required by `partial_storage_info` - --> $WORKSPACE/frame/support/src/traits/storage.rs - | - | fn partial_storage_info() -> Vec; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0277]: the trait bound `Bar: TypeInfo` is not satisfied - --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:21:12 - | -21 | #[pallet::storage] - | ^^^^^^^ the trait `TypeInfo` is not implemented for `Bar` - | - = note: required because of the requirements on the impl of `StaticTypeInfo` for `Bar` - = note: required because of the requirements on the impl of `StorageEntryMetadataBuilder` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` -note: required by `build_metadata` - --> $WORKSPACE/frame/support/src/storage/types/mod.rs - | - | fn build_metadata(doc: Vec<&'static str>, entries: &mut Vec); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:21:12 + | +21 | #[pallet::storage] + | ^^^^^^^ the trait `TypeInfo` is not implemented for `Bar` + | + = note: required because of the requirements on the impl of `StaticTypeInfo` for `Bar` + = note: required because of the requirements on the impl of `StorageEntryMetadataBuilder` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` error[E0277]: the trait bound `Bar: WrapperTypeDecode` is not satisfied - --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:21:12 - | -21 | #[pallet::storage] - | ^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `Bar` - | - = note: required because of the requirements on the impl of `Decode` for `Bar` - = note: required because of the requirements on the impl of `FullCodec` for `Bar` - = note: required because of the requirements on the impl of `StorageEntryMetadataBuilder` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` -note: required by `build_metadata` - --> $WORKSPACE/frame/support/src/storage/types/mod.rs - | - | fn build_metadata(doc: Vec<&'static str>, entries: &mut Vec); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:21:12 + | +21 | #[pallet::storage] + | ^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `Bar` + | + = note: required because of the requirements on the impl of `Decode` for `Bar` + = note: required because of the requirements on the impl of `FullCodec` for `Bar` + = note: required because of the requirements on the impl of `StorageEntryMetadataBuilder` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` error[E0277]: the trait bound `Bar: EncodeLike` is not satisfied - --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:21:12 - | -21 | #[pallet::storage] - | ^^^^^^^ the trait `EncodeLike` is not implemented for `Bar` - | - = note: required because of the requirements on the impl of `FullEncode` for `Bar` - = note: required because of the requirements on the impl of `FullCodec` for `Bar` - = note: required because of the requirements on the impl of `StorageEntryMetadataBuilder` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` -note: required by `build_metadata` - --> $WORKSPACE/frame/support/src/storage/types/mod.rs - | - | fn build_metadata(doc: Vec<&'static str>, entries: &mut Vec); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:21:12 + | +21 | #[pallet::storage] + | ^^^^^^^ the trait `EncodeLike` is not implemented for `Bar` + | + = note: required because of the requirements on the impl of `FullEncode` for `Bar` + = note: required because of the requirements on the impl of `FullCodec` for `Bar` + = note: required because of the requirements on the impl of `StorageEntryMetadataBuilder` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` error[E0277]: the trait bound `Bar: WrapperTypeEncode` is not satisfied - --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:21:12 - | -21 | #[pallet::storage] - | ^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `Bar` - | - = note: required because of the requirements on the impl of `Encode` for `Bar` - = note: required because of the requirements on the impl of `FullEncode` for `Bar` - = note: required because of the requirements on the impl of `FullCodec` for `Bar` - = note: required because of the requirements on the impl of `StorageEntryMetadataBuilder` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` -note: required by `build_metadata` - --> $WORKSPACE/frame/support/src/storage/types/mod.rs - | - | fn build_metadata(doc: Vec<&'static str>, entries: &mut Vec); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:21:12 + | +21 | #[pallet::storage] + | ^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `Bar` + | + = note: required because of the requirements on the impl of `Encode` for `Bar` + = note: required because of the requirements on the impl of `FullEncode` for `Bar` + = note: required because of the requirements on the impl of `FullCodec` for `Bar` + = note: required because of the requirements on the impl of `StorageEntryMetadataBuilder` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` diff --git a/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.stderr b/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.stderr index b5f250bb89718..6c3f6dc662fbc 100644 --- a/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.stderr +++ b/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.stderr @@ -7,11 +7,6 @@ error[E0277]: the trait bound `Bar: WrapperTypeDecode` is not satisfied = note: required because of the requirements on the impl of `Decode` for `Bar` = note: required because of the requirements on the impl of `FullCodec` for `Bar` = note: required because of the requirements on the impl of `PartialStorageInfoTrait` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` -note: required by `partial_storage_info` - --> $WORKSPACE/frame/support/src/traits/storage.rs - | - | fn partial_storage_info() -> Vec; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0277]: the trait bound `Bar: EncodeLike` is not satisfied --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:10:12 @@ -22,11 +17,6 @@ error[E0277]: the trait bound `Bar: EncodeLike` is not satisfied = note: required because of the requirements on the impl of `FullEncode` for `Bar` = note: required because of the requirements on the impl of `FullCodec` for `Bar` = note: required because of the requirements on the impl of `PartialStorageInfoTrait` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` -note: required by `partial_storage_info` - --> $WORKSPACE/frame/support/src/traits/storage.rs - | - | fn partial_storage_info() -> Vec; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0277]: the trait bound `Bar: WrapperTypeEncode` is not satisfied --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:10:12 @@ -38,68 +28,43 @@ error[E0277]: the trait bound `Bar: WrapperTypeEncode` is not satisfied = note: required because of the requirements on the impl of `FullEncode` for `Bar` = note: required because of the requirements on the impl of `FullCodec` for `Bar` = note: required because of the requirements on the impl of `PartialStorageInfoTrait` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` -note: required by `partial_storage_info` - --> $WORKSPACE/frame/support/src/traits/storage.rs - | - | fn partial_storage_info() -> Vec; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0277]: the trait bound `Bar: TypeInfo` is not satisfied - --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:21:12 - | -21 | #[pallet::storage] - | ^^^^^^^ the trait `TypeInfo` is not implemented for `Bar` - | - = note: required because of the requirements on the impl of `StaticTypeInfo` for `Bar` - = note: required because of the requirements on the impl of `StorageEntryMetadataBuilder` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` -note: required by `build_metadata` - --> $WORKSPACE/frame/support/src/storage/types/mod.rs - | - | fn build_metadata(doc: Vec<&'static str>, entries: &mut Vec); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:21:12 + | +21 | #[pallet::storage] + | ^^^^^^^ the trait `TypeInfo` is not implemented for `Bar` + | + = note: required because of the requirements on the impl of `StaticTypeInfo` for `Bar` + = note: required because of the requirements on the impl of `StorageEntryMetadataBuilder` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` error[E0277]: the trait bound `Bar: WrapperTypeDecode` is not satisfied - --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:21:12 - | -21 | #[pallet::storage] - | ^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `Bar` - | - = note: required because of the requirements on the impl of `Decode` for `Bar` - = note: required because of the requirements on the impl of `FullCodec` for `Bar` - = note: required because of the requirements on the impl of `StorageEntryMetadataBuilder` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` -note: required by `build_metadata` - --> $WORKSPACE/frame/support/src/storage/types/mod.rs - | - | fn build_metadata(doc: Vec<&'static str>, entries: &mut Vec); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:21:12 + | +21 | #[pallet::storage] + | ^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `Bar` + | + = note: required because of the requirements on the impl of `Decode` for `Bar` + = note: required because of the requirements on the impl of `FullCodec` for `Bar` + = note: required because of the requirements on the impl of `StorageEntryMetadataBuilder` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` error[E0277]: the trait bound `Bar: EncodeLike` is not satisfied - --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:21:12 - | -21 | #[pallet::storage] - | ^^^^^^^ the trait `EncodeLike` is not implemented for `Bar` - | - = note: required because of the requirements on the impl of `FullEncode` for `Bar` - = note: required because of the requirements on the impl of `FullCodec` for `Bar` - = note: required because of the requirements on the impl of `StorageEntryMetadataBuilder` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` -note: required by `build_metadata` - --> $WORKSPACE/frame/support/src/storage/types/mod.rs - | - | fn build_metadata(doc: Vec<&'static str>, entries: &mut Vec); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:21:12 + | +21 | #[pallet::storage] + | ^^^^^^^ the trait `EncodeLike` is not implemented for `Bar` + | + = note: required because of the requirements on the impl of `FullEncode` for `Bar` + = note: required because of the requirements on the impl of `FullCodec` for `Bar` + = note: required because of the requirements on the impl of `StorageEntryMetadataBuilder` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` error[E0277]: the trait bound `Bar: WrapperTypeEncode` is not satisfied - --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:21:12 - | -21 | #[pallet::storage] - | ^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `Bar` - | - = note: required because of the requirements on the impl of `Encode` for `Bar` - = note: required because of the requirements on the impl of `FullEncode` for `Bar` - = note: required because of the requirements on the impl of `FullCodec` for `Bar` - = note: required because of the requirements on the impl of `StorageEntryMetadataBuilder` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` -note: required by `build_metadata` - --> $WORKSPACE/frame/support/src/storage/types/mod.rs - | - | fn build_metadata(doc: Vec<&'static str>, entries: &mut Vec); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:21:12 + | +21 | #[pallet::storage] + | ^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `Bar` + | + = note: required because of the requirements on the impl of `Encode` for `Bar` + = note: required because of the requirements on the impl of `FullEncode` for `Bar` + = note: required because of the requirements on the impl of `FullCodec` for `Bar` + = note: required because of the requirements on the impl of `StorageEntryMetadataBuilder` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` diff --git a/frame/support/test/tests/pallet_ui/storage_info_unsatisfied.stderr b/frame/support/test/tests/pallet_ui/storage_info_unsatisfied.stderr index 35537cfbc9e07..68856f122c7ac 100644 --- a/frame/support/test/tests/pallet_ui/storage_info_unsatisfied.stderr +++ b/frame/support/test/tests/pallet_ui/storage_info_unsatisfied.stderr @@ -1,12 +1,7 @@ error[E0277]: the trait bound `Bar: MaxEncodedLen` is not satisfied - --> tests/pallet_ui/storage_info_unsatisfied.rs:9:12 - | -9 | #[pallet::pallet] - | ^^^^^^ the trait `MaxEncodedLen` is not implemented for `Bar` - | - = note: required because of the requirements on the impl of `StorageInfoTrait` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` -note: required by `storage_info` - --> $WORKSPACE/frame/support/src/traits/storage.rs - | - | fn storage_info() -> Vec; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + --> tests/pallet_ui/storage_info_unsatisfied.rs:9:12 + | +9 | #[pallet::pallet] + | ^^^^^^ the trait `MaxEncodedLen` is not implemented for `Bar` + | + = note: required because of the requirements on the impl of `StorageInfoTrait` for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` diff --git a/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr b/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr index fb6580bb5a3e7..226cb40f1d48b 100644 --- a/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr +++ b/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr @@ -6,8 +6,3 @@ error[E0277]: the trait bound `Bar: MaxEncodedLen` is not satisfied | = note: required because of the requirements on the impl of `KeyGeneratorMaxEncodedLen` for `Key` = note: required because of the requirements on the impl of `StorageInfoTrait` for `frame_support::pallet_prelude::StorageNMap<_GeneratedPrefixForStorageFoo, Key, u32>` -note: required by `storage_info` - --> $WORKSPACE/frame/support/src/traits/storage.rs - | - | fn storage_info() -> Vec; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/primitives/api/proc-macro/src/decl_runtime_apis.rs b/primitives/api/proc-macro/src/decl_runtime_apis.rs index 977bdd8774ade..13674b804dbdd 100644 --- a/primitives/api/proc-macro/src/decl_runtime_apis.rs +++ b/primitives/api/proc-macro/src/decl_runtime_apis.rs @@ -750,7 +750,7 @@ impl<'a> ToClientSideDecl<'a> { #crate_::NativeOrEncoded::Encoded(r) => { <#ret_type as #crate_::Decode>::decode(&mut &r[..]) .map_err(|err| - #crate_::ApiError::FailedToDecodeReturnValue { + #crate_::ApiError::FailedToConvertReturnValue { function: #function_name, error: err, } diff --git a/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs b/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs index 3b91eae159eb4..d72c56bc1b8a8 100644 --- a/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs +++ b/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs @@ -313,6 +313,23 @@ impl<'a> Fold for FoldRuntimeApiImpl<'a> { let call_name_str = call_name.to_string(); + let call_return_value = if !is_advanced { + quote!( Ok(#crate_::NativeOrEncoded::Encoded( + <#ret_type as #crate_::Encode>::encode(&((move || #orig_block)())) + )) ) + } else { + quote! { + let f = move || #orig_block; + match f() { + Err(e) => Err(e), + Ok(#crate_::NativeOrEncoded::Encoded(e)) => Ok(#crate_::NativeOrEncoded::Encoded(e)), + Ok(#crate_::NativeOrEncoded::Native(r)) => { + Ok(#crate_::NativeOrEncoded::Encoded(#crate_::Encode::encode(&r))) + } + } + } + }; + let call_arm = quote!( #call_name_str => { let (#( #param_names ),*) : ( #( #param_types ),* ) = @@ -324,9 +341,7 @@ impl<'a> Fold for FoldRuntimeApiImpl<'a> { Err(e) => panic!("Bad input data provided to {}: {}", #call_name_str, e), }; let at = ¶ms.at; - let r = { #orig_block } as #ret_type; - let encoded = #crate_::Encode::encode(&r); - Ok(#crate_::NativeOrEncoded::Encoded(encoded)) + #call_return_value }, ); diff --git a/primitives/api/test/tests/decl_and_impl.rs b/primitives/api/test/tests/decl_and_impl.rs index 26c2ed27c6981..f1a84258d270c 100644 --- a/primitives/api/test/tests/decl_and_impl.rs +++ b/primitives/api/test/tests/decl_and_impl.rs @@ -16,7 +16,7 @@ // limitations under the License. use sp_api::{ - decl_runtime_apis, impl_runtime_apis, mock_impl_runtime_apis, ApiError, RuntimeApiInfo, + decl_runtime_apis, impl_runtime_apis, mock_impl_runtime_apis, ApiError, RuntimeApiInfo, ApiExt, }; use sp_core::NativeOrEncoded; use sp_runtime::{ @@ -89,7 +89,6 @@ struct MockApi { block: Option, } -/* mock_impl_runtime_apis! { impl Api for MockApi { fn test(_: u64) { @@ -111,7 +110,8 @@ mock_impl_runtime_apis! { ApiError > { - Ok(().into()) + let x: NativeOrEncoded<()> = ().into(); + Ok(x) } #[advanced] @@ -133,7 +133,7 @@ mock_impl_runtime_apis! { impl ApiWithCustomVersion for MockApi { fn same_name() {} } -}*/ +} type TestClient = substrate_test_runtime_client::client::Client< substrate_test_runtime_client::Backend, @@ -188,7 +188,6 @@ fn check_runtime_api_versions() { check_runtime_api_versions_contains::>(); } -/* #[test] fn mock_runtime_api_has_api() { let mock = MockApi { block: None }; @@ -217,4 +216,3 @@ fn mock_runtime_api_works_with_advanced() { mock.wild_card(&BlockId::Number(1336), 1).unwrap_err().to_string(), ); } -*/ diff --git a/primitives/api/test/tests/runtime_calls.rs b/primitives/api/test/tests/runtime_calls.rs index ba42b342377c7..03bbe8067c707 100644 --- a/primitives/api/test/tests/runtime_calls.rs +++ b/primitives/api/test/tests/runtime_calls.rs @@ -52,7 +52,7 @@ fn calling_wasm_runtime_function() { } #[test] -#[should_panic(expected = "FailedToConvertParameter { function: \"fail_convert_parameter\"")] +#[should_panic(expected = "Trap")] fn calling_native_runtime_function_with_non_decodable_parameter() { let client = TestClientBuilder::new() .set_execution_strategy(ExecutionStrategy::NativeWhenPossible) @@ -84,19 +84,6 @@ fn calling_native_runtime_signature_changed_function() { assert_eq!(runtime_api.function_signature_changed(&block_id).unwrap(), 1); } -#[test] -fn calling_wasm_runtime_signature_changed_old_function() { - let client = TestClientBuilder::new() - .set_execution_strategy(ExecutionStrategy::AlwaysWasm) - .build(); - let runtime_api = client.runtime_api(); - let block_id = BlockId::Number(client.chain_info().best_number); - - #[allow(deprecated)] - let res = runtime_api.function_signature_changed_before_version_2(&block_id).unwrap(); - assert_eq!(&res, &[1, 2]); -} - #[test] fn calling_with_both_strategy_and_fail_on_wasm_should_return_error() { let client = TestClientBuilder::new().set_execution_strategy(ExecutionStrategy::Both).build(); @@ -113,16 +100,6 @@ fn calling_with_both_strategy_and_fail_on_native_should_work() { assert_eq!(runtime_api.fail_on_native(&block_id).unwrap(), 1); } -#[test] -fn calling_with_native_else_wasm_and_fail_on_wasm_should_work() { - let client = TestClientBuilder::new() - .set_execution_strategy(ExecutionStrategy::NativeElseWasm) - .build(); - let runtime_api = client.runtime_api(); - let block_id = BlockId::Number(client.chain_info().best_number); - assert_eq!(runtime_api.fail_on_wasm(&block_id).unwrap(), 1); -} - #[test] fn calling_with_native_else_wasm_and_fail_on_native_should_work() { let client = TestClientBuilder::new() diff --git a/primitives/api/test/tests/ui/changed_in_no_default_method.stderr b/primitives/api/test/tests/ui/changed_in_no_default_method.stderr index ed4c0f9088573..096b1091e6f41 100644 --- a/primitives/api/test/tests/ui/changed_in_no_default_method.stderr +++ b/primitives/api/test/tests/ui/changed_in_no_default_method.stderr @@ -1,6 +1,6 @@ error: There is no 'default' method with this name (without `changed_in` attribute). -The 'default' method is used to call into the latest implementation. - --> $DIR/changed_in_no_default_method.rs:15:6 + The 'default' method is used to call into the latest implementation. + --> tests/ui/changed_in_no_default_method.rs:15:6 | 15 | fn test(data: u64); | ^^^^ diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index 7fbcaad570e4b..3ce8cf18d5d8f 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -364,6 +364,7 @@ cfg_if! { } } else { decl_runtime_apis! { + #[api_version(2)] pub trait TestAPI { /// Return the balance of the given account id. fn balance_of(id: AccountId) -> u64; @@ -376,8 +377,10 @@ cfg_if! { fn fail_convert_parameter(param: DecodeFails); /// A function that always fails to convert its return value between runtime and node. fn fail_convert_return_value() -> DecodeFails; - /// In wasm we just emulate the old behavior. + #[changed_in(2)] fn function_signature_changed() -> Vec; + /// The new signature. + fn function_signature_changed() -> u64; fn fail_on_native() -> u64; fn fail_on_wasm() -> u64; /// trie no_std testing @@ -1013,11 +1016,8 @@ cfg_if! { DecodeFails::default() } - fn function_signature_changed() -> Vec { - let mut vec = Vec::new(); - vec.push(1); - vec.push(2); - vec + fn function_signature_changed() -> u64 { + 1 } fn fail_on_native() -> u64 { From 0e478bf2de1771118bf87d65b0ee8b990b4aa027 Mon Sep 17 00:00:00 2001 From: arkpar Date: Thu, 17 Feb 2022 10:46:43 +0100 Subject: [PATCH 09/14] Genesis builder does not care about host extensions --- client/chain-spec/src/chain_spec.rs | 15 ++++----------- client/executor/src/lib.rs | 2 +- 2 files changed, 5 insertions(+), 12 deletions(-) diff --git a/client/chain-spec/src/chain_spec.rs b/client/chain-spec/src/chain_spec.rs index 057247693e8e0..954523ceff4fe 100644 --- a/client/chain-spec/src/chain_spec.rs +++ b/client/chain-spec/src/chain_spec.rs @@ -26,7 +26,6 @@ use sc_executor::Externalities; use serde::{Deserialize, Serialize}; use serde_json as json; use sp_core::{ - traits::CodeExecutor, storage::{ChildInfo, Storage, StorageChild, StorageData, StorageKey, well_known_keys}, Bytes, }; @@ -107,20 +106,14 @@ impl GenesisSource { Self::Storage(storage) => Ok(Self::from_storage(storage)), Self::Runtime { code, method } => { let mut ext = sp_state_machine::BasicExternalities::default(); - let code_fetcher = sp_core::traits::WrappedRuntimeCode((*code).into()); - let runtime_code = sp_core::traits::RuntimeCode { - code_fetcher: &code_fetcher, - heap_pages: None, - hash: Default::default(), - }; + let runtime_code = sc_executor::RuntimeBlob::uncompress_if_needed(code) + .map_err(|e| format!("Error loading runtime code: {}", e))?; let executor = sc_executor::DefaultExecutor::new( sc_executor::WasmExecutionMethod::Interpreted, None, 1, None, 1 ); - let (r, _) = executor.call::<(), fn() -> Result<(), _>>(&mut ext, &runtime_code, method, &[], false, None); - if let Err(e) = r { - return Err(format!("Error building genesis with {}: {}", method, e)); - } + executor.uncached_call(runtime_code, &mut ext, true, method, &[]) + .map_err(|e| format!("Error building genesis with {}: {}", method, e))?; ext.set_storage(well_known_keys::CODE.to_vec(), code.to_vec()); let storage = ext.into_storages(); diff --git a/client/executor/src/lib.rs b/client/executor/src/lib.rs index 84b9923aff86e..bd1b3fafa3928 100644 --- a/client/executor/src/lib.rs +++ b/client/executor/src/lib.rs @@ -49,7 +49,7 @@ pub use sp_wasm_interface; pub use wasm_runtime::{read_embedded_version, WasmExecutionMethod}; pub use wasmi; -pub use sc_executor_common::{error, sandbox}; +pub use sc_executor_common::{error, sandbox, runtime_blob::RuntimeBlob}; /// Default WASM executor with substrate host function set. pub type DefaultExecutor = WasmExecutor>; From 5129d6954ac267b6b349c4f42d46e251a5815a09 Mon Sep 17 00:00:00 2001 From: arkpar Date: Thu, 17 Feb 2022 10:49:58 +0100 Subject: [PATCH 10/14] Removed chain-spec-builder --- Cargo.toml | 2 - bin/node/cli/build.rs | 1 - bin/utils/chain-spec-builder/Cargo.toml | 26 -- bin/utils/chain-spec-builder/README.md | 1 - bin/utils/chain-spec-builder/build.rs | 25 -- bin/utils/chain-spec-builder/src/main.rs | 293 ----------------------- 6 files changed, 348 deletions(-) delete mode 100644 bin/utils/chain-spec-builder/Cargo.toml delete mode 100644 bin/utils/chain-spec-builder/README.md delete mode 100644 bin/utils/chain-spec-builder/build.rs delete mode 100644 bin/utils/chain-spec-builder/src/main.rs diff --git a/Cargo.toml b/Cargo.toml index e8a02e46f9357..ab8e4e51b434c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,6 @@ members = [ "bin/node/rpc", "bin/node/runtime", "bin/node/testing", - #"bin/utils/chain-spec-builder", "bin/utils/subkey", "client/api", "client/authority-discovery", @@ -277,7 +276,6 @@ zeroize = { opt-level = 3 } [profile.release] panic = "abort" -#lto= "off" incremental = true [profile.production] diff --git a/bin/node/cli/build.rs b/bin/node/cli/build.rs index 4325c44597b4f..b087bb443a8be 100644 --- a/bin/node/cli/build.rs +++ b/bin/node/cli/build.rs @@ -32,7 +32,6 @@ fn build_runtime() { .with_project(path.canonicalize().unwrap()).unwrap() .export_heap_base() .import_memory() - .enable_feature("runtime-benchmarks") .build() } diff --git a/bin/utils/chain-spec-builder/Cargo.toml b/bin/utils/chain-spec-builder/Cargo.toml deleted file mode 100644 index 06de034c10565..0000000000000 --- a/bin/utils/chain-spec-builder/Cargo.toml +++ /dev/null @@ -1,26 +0,0 @@ -[package] -name = "chain-spec-builder" -version = "2.0.0" -authors = ["Parity Technologies "] -edition = "2021" -build = "build.rs" -license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -homepage = "https://substrate.io" -repository = "https://github.com/paritytech/substrate/" -readme = "README.md" -publish = false - -[package.metadata.docs.rs] -targets = ["x86_64-unknown-linux-gnu"] - -[dependencies] -ansi_term = "0.12.1" -clap = { version = "3.0", features = ["derive"] } -rand = "0.8" - -sc-keystore = { version = "4.0.0-dev", path = "../../../client/keystore" } -sc-chain-spec = { version = "4.0.0-dev", path = "../../../client/chain-spec" } -node-cli = { version = "3.0.0-dev", path = "../../node/cli" } -node-runtime = { version = "3.0.0-dev", path = "../../node/runtime" } -sp-core = { version = "5.0.0", path = "../../../primitives/core" } -sp-keystore = { version = "0.11.0", path = "../../../primitives/keystore" } diff --git a/bin/utils/chain-spec-builder/README.md b/bin/utils/chain-spec-builder/README.md deleted file mode 100644 index 3e9ac0bddbdc1..0000000000000 --- a/bin/utils/chain-spec-builder/README.md +++ /dev/null @@ -1 +0,0 @@ -License: GPL-3.0-or-later WITH Classpath-exception-2.0 \ No newline at end of file diff --git a/bin/utils/chain-spec-builder/build.rs b/bin/utils/chain-spec-builder/build.rs deleted file mode 100644 index b700b28e322ca..0000000000000 --- a/bin/utils/chain-spec-builder/build.rs +++ /dev/null @@ -1,25 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2019-2022 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program 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. - -// This program 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 this program. If not, see . - -use std::env; - -fn main() { - if let Ok(profile) = env::var("PROFILE") { - println!("cargo:rustc-cfg=build_type=\"{}\"", profile); - } -} diff --git a/bin/utils/chain-spec-builder/src/main.rs b/bin/utils/chain-spec-builder/src/main.rs deleted file mode 100644 index 42570bad8cc63..0000000000000 --- a/bin/utils/chain-spec-builder/src/main.rs +++ /dev/null @@ -1,293 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2019-2022 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program 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. - -// This program 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 this program. If not, see . - -use std::{ - fs, - path::{Path, PathBuf}, - sync::Arc, -}; - -use ansi_term::Style; -use clap::Parser; -use rand::{distributions::Alphanumeric, rngs::OsRng, Rng}; - -use node_cli::chain_spec::{self, AccountId}; -use node_runtime::GenesisConfig; -use sc_keystore::LocalKeystore; -use sp_core::{ - crypto::{ByteArray, Ss58Codec}, - sr25519, -}; -use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; - -/// A utility to easily create a testnet chain spec definition with a given set -/// of authorities and endowed accounts and/or generate random accounts. -#[derive(Parser)] -#[clap(rename_all = "kebab-case")] -enum ChainSpecBuilder { - /// Create a new chain spec with the given authorities, endowed and sudo - /// accounts. - New { - /// Authority key seed. - #[clap(long, short, required = true)] - authority_seeds: Vec, - /// Active nominators (SS58 format), each backing a random subset of the aforementioned - /// authorities. - #[clap(long, short, default_value = "0")] - nominator_accounts: Vec, - /// Endowed account address (SS58 format). - #[clap(long, short)] - endowed_accounts: Vec, - /// Sudo account address (SS58 format). - #[clap(long, short)] - sudo_account: String, - /// The path where the chain spec should be saved. - #[clap(long, short, default_value = "./chain_spec.json")] - chain_spec_path: PathBuf, - }, - /// Create a new chain spec with the given number of authorities and endowed - /// accounts. Random keys will be generated as required. - Generate { - /// The number of authorities. - #[clap(long, short)] - authorities: usize, - /// The number of nominators backing the aforementioned authorities. - /// - /// Will nominate a random subset of `authorities`. - #[clap(long, short, default_value = "0")] - nominators: usize, - /// The number of endowed accounts. - #[clap(long, short, default_value = "0")] - endowed: usize, - /// The path where the chain spec should be saved. - #[clap(long, short, default_value = "./chain_spec.json")] - chain_spec_path: PathBuf, - /// Path to use when saving generated keystores for each authority. - /// - /// At this path, a new folder will be created for each authority's - /// keystore named `auth-$i` where `i` is the authority index, i.e. - /// `auth-0`, `auth-1`, etc. - #[clap(long, short)] - keystore_path: Option, - }, -} - -impl ChainSpecBuilder { - /// Returns the path where the chain spec should be saved. - fn chain_spec_path(&self) -> &Path { - match self { - ChainSpecBuilder::New { chain_spec_path, .. } => chain_spec_path.as_path(), - ChainSpecBuilder::Generate { chain_spec_path, .. } => chain_spec_path.as_path(), - } - } -} - -fn genesis_constructor( - authority_seeds: &[String], - nominator_accounts: &[AccountId], - endowed_accounts: &[AccountId], - sudo_account: &AccountId, -) -> chain_spec::GenesisConfig { - let authorities = authority_seeds - .iter() - .map(AsRef::as_ref) - .map(chain_spec::authority_keys_from_seed) - .collect::>(); - - chain_spec::testnet_genesis( - authorities, - nominator_accounts.to_vec(), - sudo_account.clone(), - Some(endowed_accounts.to_vec()), - ) -} - -fn generate_chain_spec( - authority_seeds: Vec, - nominator_accounts: Vec, - endowed_accounts: Vec, - sudo_account: String, -) -> Result { - let parse_account = |address: String| { - AccountId::from_string(&address) - .map_err(|err| format!("Failed to parse account address: {:?}", err)) - }; - - let nominator_accounts = nominator_accounts - .into_iter() - .map(parse_account) - .collect::, String>>()?; - - let endowed_accounts = endowed_accounts - .into_iter() - .map(parse_account) - .collect::, String>>()?; - - let sudo_account = parse_account(sudo_account)?; - - let chain_spec = chain_spec::ChainSpec::from_genesis( - "Custom", - "custom", - sc_chain_spec::ChainType::Live, - move || { - genesis_constructor( - &authority_seeds, - &nominator_accounts, - &endowed_accounts, - &sudo_account, - ) - }, - vec![], - None, - None, - None, - None, - Default::default(), - ); - - chain_spec.as_json(false).map_err(|err| err) -} - -fn generate_authority_keys_and_store(seeds: &[String], keystore_path: &Path) -> Result<(), String> { - for (n, seed) in seeds.into_iter().enumerate() { - let keystore: SyncCryptoStorePtr = Arc::new( - LocalKeystore::open(keystore_path.join(format!("auth-{}", n)), None) - .map_err(|err| err.to_string())?, - ); - - let (_, _, grandpa, babe, im_online, authority_discovery) = - chain_spec::authority_keys_from_seed(seed); - - let insert_key = |key_type, public| { - SyncCryptoStore::insert_unknown(&*keystore, key_type, &format!("//{}", seed), public) - .map_err(|_| format!("Failed to insert key: {}", grandpa)) - }; - - insert_key(sp_core::crypto::key_types::BABE, babe.as_slice())?; - - insert_key(sp_core::crypto::key_types::GRANDPA, grandpa.as_slice())?; - - insert_key(sp_core::crypto::key_types::IM_ONLINE, im_online.as_slice())?; - - insert_key( - sp_core::crypto::key_types::AUTHORITY_DISCOVERY, - authority_discovery.as_slice(), - )?; - } - - Ok(()) -} - -fn print_seeds( - authority_seeds: &[String], - nominator_seeds: &[String], - endowed_seeds: &[String], - sudo_seed: &str, -) { - let header = Style::new().bold().underline(); - let entry = Style::new().bold(); - - println!("{}", header.paint("Authority seeds")); - - for (n, seed) in authority_seeds.iter().enumerate() { - println!("{} //{}", entry.paint(format!("auth-{}:", n)), seed); - } - - println!("{}", header.paint("Nominator seeds")); - - for (n, seed) in nominator_seeds.iter().enumerate() { - println!("{} //{}", entry.paint(format!("nom-{}:", n)), seed); - } - - println!(); - - if !endowed_seeds.is_empty() { - println!("{}", header.paint("Endowed seeds")); - for (n, seed) in endowed_seeds.iter().enumerate() { - println!("{} //{}", entry.paint(format!("endowed-{}:", n)), seed); - } - - println!(); - } - - println!("{}", header.paint("Sudo seed")); - println!("//{}", sudo_seed); -} - -fn main() -> Result<(), String> { - #[cfg(build_type = "debug")] - println!( - "The chain spec builder builds a chain specification that includes a Substrate runtime \ - compiled as WASM. To ensure proper functioning of the included runtime compile (or run) \ - the chain spec builder binary in `--release` mode.\n", - ); - - let builder = ChainSpecBuilder::parse(); - let chain_spec_path = builder.chain_spec_path().to_path_buf(); - - let (authority_seeds, nominator_accounts, endowed_accounts, sudo_account) = match builder { - ChainSpecBuilder::Generate { authorities, nominators, endowed, keystore_path, .. } => { - let authorities = authorities.max(1); - let rand_str = || -> String { - OsRng.sample_iter(&Alphanumeric).take(32).map(char::from).collect() - }; - - let authority_seeds = (0..authorities).map(|_| rand_str()).collect::>(); - let nominator_seeds = (0..nominators).map(|_| rand_str()).collect::>(); - let endowed_seeds = (0..endowed).map(|_| rand_str()).collect::>(); - let sudo_seed = rand_str(); - - print_seeds(&authority_seeds, &nominator_seeds, &endowed_seeds, &sudo_seed); - - if let Some(keystore_path) = keystore_path { - generate_authority_keys_and_store(&authority_seeds, &keystore_path)?; - } - - let nominator_accounts = nominator_seeds - .into_iter() - .map(|seed| { - chain_spec::get_account_id_from_seed::(&seed).to_ss58check() - }) - .collect(); - - let endowed_accounts = endowed_seeds - .into_iter() - .map(|seed| { - chain_spec::get_account_id_from_seed::(&seed).to_ss58check() - }) - .collect(); - - let sudo_account = - chain_spec::get_account_id_from_seed::(&sudo_seed).to_ss58check(); - - (authority_seeds, nominator_accounts, endowed_accounts, sudo_account) - }, - ChainSpecBuilder::New { - authority_seeds, - nominator_accounts, - endowed_accounts, - sudo_account, - .. - } => (authority_seeds, nominator_accounts, endowed_accounts, sudo_account), - }; - - let json = - generate_chain_spec(authority_seeds, nominator_accounts, endowed_accounts, sudo_account)?; - - fs::write(chain_spec_path, json).map_err(|err| err.to_string()) -} From 0f503b16f5db00cf3f47f7243ef59db867ff501d Mon Sep 17 00:00:00 2001 From: arkpar Date: Mon, 21 Feb 2022 12:03:07 +0100 Subject: [PATCH 11/14] Started runtiem extendable executor impl --- Cargo.lock | 1 + bin/node/cli/Cargo.toml | 4 +++- bin/node/cli/src/service.rs | 16 +++++++++++++++- client/executor/src/lib.rs | 1 - client/executor/src/native_executor.rs | 6 ++++++ 5 files changed, 25 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c6c729952a03c..5e4accd51824a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4664,6 +4664,7 @@ dependencies = [ "clap 3.0.7", "clap_complete", "criterion", + "frame-benchmarking", "frame-benchmarking-cli", "frame-system", "frame-system-rpc-runtime-api", diff --git a/bin/node/cli/Cargo.toml b/bin/node/cli/Cargo.toml index a1a8219206be6..87a942e5ea6d1 100644 --- a/bin/node/cli/Cargo.toml +++ b/bin/node/cli/Cargo.toml @@ -83,6 +83,7 @@ sc-cli = { version = "0.10.0-dev", optional = true, path = "../../../client/cli" frame-benchmarking-cli = { version = "4.0.0-dev", optional = true, path = "../../../utils/frame/benchmarking-cli" } node-inspect = { version = "0.9.0-dev", optional = true, path = "../inspect" } try-runtime-cli = { version = "0.10.0-dev", optional = true, path = "../../../utils/frame/try-runtime/cli" } +frame-benchmarking = { version = "4.0.0-dev", optional = true, path = "../../../frame/benchmarking" } [target.'cfg(any(target_arch="x86_64", target_arch="aarch64"))'.dependencies] sc-cli = { version = "0.10.0-dev", optional = true, path = "../../../client/cli", features = ["wasmtime"] } @@ -138,6 +139,7 @@ try-runtime-cli = { version = "0.10.0-dev", optional = true, path = "../../../ut sc-cli = { version = "0.10.0-dev", path = "../../../client/cli", optional = true } pallet-balances = { version = "4.0.0-dev", path = "../../../frame/balances" } substrate-wasm-builder = { version = "5.0.0-dev", path = "../../../utils/wasm-builder" } +frame-benchmarking = { version = "4.0.0-dev", optional = true, path = "../../../frame/benchmarking" } [features] default = ["cli"] @@ -152,7 +154,7 @@ cli = [ "substrate-build-script-utils", "try-runtime-cli", ] -runtime-benchmarks = ["frame-benchmarking-cli"] +runtime-benchmarks = ["frame-benchmarking-cli", "frame-benchmarking"] # Enable features that allow the runtime to be tried and debugged. Name might be subject to change # in the near future. try-runtime = ["try-runtime-cli"] diff --git a/bin/node/cli/src/service.rs b/bin/node/cli/src/service.rs index c0dde8d40f4d4..dfbf69c31c420 100644 --- a/bin/node/cli/src/service.rs +++ b/bin/node/cli/src/service.rs @@ -41,6 +41,18 @@ type FullGrandpaBlockImport = /// The transaction pool type defintion. pub type TransactionPool = sc_transaction_pool::FullPool; +#[cfg(feature = "runtime-benchmarks")] +fn extend_host_functions(executor: &mut DefaultExecutor) { + use sc_executor::sp_wasm_interface::HostFunctions; + executor.extend_host_functions( + frame_benchmarking::benchmarking::HostFunctions::host_functions() + ); +} + +#[cfg(not(feature = "runtime-benchmarks"))] +fn extend_host_functions(_executor: &mut DefaultExecutor) { +} + /// Creates a new partial node. pub fn new_partial( config: &Configuration, @@ -78,7 +90,7 @@ pub fn new_partial( }) .transpose()?; - let executor = DefaultExecutor::new( + let mut executor = DefaultExecutor::new( config.wasm_method, config.default_heap_pages, config.max_runtime_instances, @@ -86,6 +98,8 @@ pub fn new_partial( config.runtime_cache_size, ); + extend_host_functions(&mut executor); + let (client, backend, keystore_container, task_manager) = sc_service::new_full_parts::( config, diff --git a/client/executor/src/lib.rs b/client/executor/src/lib.rs index bd1b3fafa3928..f3272463e3d3f 100644 --- a/client/executor/src/lib.rs +++ b/client/executor/src/lib.rs @@ -54,7 +54,6 @@ pub use sc_executor_common::{error, sandbox, runtime_blob::RuntimeBlob}; /// Default WASM executor with substrate host function set. pub type DefaultExecutor = WasmExecutor>; - /// Extracts the runtime version of a given runtime code. pub trait RuntimeVersionOf { /// Extract [`RuntimeVersion`](sp_version::RuntimeVersion) of the given `runtime_code`. diff --git a/client/executor/src/native_executor.rs b/client/executor/src/native_executor.rs index d0ba0d78584e7..b371170634949 100644 --- a/client/executor/src/native_executor.rs +++ b/client/executor/src/native_executor.rs @@ -245,6 +245,12 @@ where } } +impl crate::DefaultExecutor { + /// Add additional host functions potentially overwriting existing functions. + pub fn extend_host_functions(&mut self, functions: Vec<&'static dyn sp_wasm_interface::Function>) { + } +} + impl sp_core::traits::ReadRuntimeVersion for WasmExecutor where H: HostFunctions, From 2e07b32dafdde717c7b778696f30269b49cf96ee Mon Sep 17 00:00:00 2001 From: arkpar Date: Tue, 22 Feb 2022 15:57:50 +0100 Subject: [PATCH 12/14] Sort out executor extensions --- bin/node-template/node/src/service.rs | 2 +- bin/node/cli/src/service.rs | 34 +++-- bin/node/inspect/src/command.rs | 4 +- bin/node/testing/src/bench.rs | 2 +- client/chain-spec/src/chain_spec.rs | 2 +- client/executor/src/integration_tests/mod.rs | 14 +- client/executor/src/lib.rs | 5 +- client/executor/src/native_executor.rs | 137 ++++++++++++------ client/executor/src/wasm_runtime.rs | 55 ++++--- client/executor/wasmi/src/lib.rs | 6 +- client/executor/wasmtime/src/host.rs | 2 +- client/executor/wasmtime/src/imports.rs | 30 +++- .../executor/wasmtime/src/instance_wrapper.rs | 14 +- client/executor/wasmtime/src/lib.rs | 1 + client/executor/wasmtime/src/runtime.rs | 72 ++++----- client/executor/wasmtime/src/tests.rs | 9 +- client/service/src/builder.rs | 6 +- client/service/src/client/call_executor.rs | 10 +- client/service/src/client/client.rs | 6 +- primitives/runtime-interface/test/src/lib.rs | 8 +- test-utils/client/src/lib.rs | 6 +- test-utils/runtime/client/src/lib.rs | 4 +- utils/frame/benchmarking-cli/src/command.rs | 4 +- 23 files changed, 261 insertions(+), 172 deletions(-) diff --git a/bin/node-template/node/src/service.rs b/bin/node-template/node/src/service.rs index 5e829566895e8..853feb1d4c8b0 100644 --- a/bin/node-template/node/src/service.rs +++ b/bin/node-template/node/src/service.rs @@ -68,7 +68,7 @@ pub fn new_partial( }) .transpose()?; - let executor = sc_executor::DefaultExecutor::new( + let executor = sc_executor::WasmExecutor::new_default( config.wasm_method, config.default_heap_pages, config.max_runtime_instances, diff --git a/bin/node/cli/src/service.rs b/bin/node/cli/src/service.rs index dfbf69c31c420..0d648b581f38b 100644 --- a/bin/node/cli/src/service.rs +++ b/bin/node/cli/src/service.rs @@ -24,7 +24,7 @@ use futures::prelude::*; use node_primitives::Block; use sc_client_api::{BlockBackend, ExecutorProvider}; use sc_consensus_babe::{self, SlotProportion}; -use sc_executor::DefaultExecutor; +use sc_executor::WasmExecutor; use sc_network::{Event, NetworkService}; use sc_service::{config::Configuration, error::Error as ServiceError, RpcHandlers, TaskManager}; use sc_telemetry::{Telemetry, TelemetryWorker}; @@ -42,15 +42,25 @@ type FullGrandpaBlockImport = pub type TransactionPool = sc_transaction_pool::FullPool; #[cfg(feature = "runtime-benchmarks")] -fn extend_host_functions(executor: &mut DefaultExecutor) { - use sc_executor::sp_wasm_interface::HostFunctions; - executor.extend_host_functions( - frame_benchmarking::benchmarking::HostFunctions::host_functions() - ); +fn create_executor(config: &Configuration) -> WasmExecutor { + WasmExecutor::new_extended::( + config.wasm_method, + config.default_heap_pages, + config.max_runtime_instances, + None, + config.runtime_cache_size, + ) } #[cfg(not(feature = "runtime-benchmarks"))] -fn extend_host_functions(_executor: &mut DefaultExecutor) { +fn create_executor(config: &Configuration) -> WasmExecutor { + WasmExecutor::new_default( + config.wasm_method, + config.default_heap_pages, + config.max_runtime_instances, + None, + config.runtime_cache_size, + ) } /// Creates a new partial node. @@ -90,15 +100,7 @@ pub fn new_partial( }) .transpose()?; - let mut executor = DefaultExecutor::new( - config.wasm_method, - config.default_heap_pages, - config.max_runtime_instances, - None, - config.runtime_cache_size, - ); - - extend_host_functions(&mut executor); + let executor = create_executor(config); let (client, backend, keystore_container, task_manager) = sc_service::new_full_parts::( diff --git a/bin/node/inspect/src/command.rs b/bin/node/inspect/src/command.rs index a207876c9f022..4a8f411993aff 100644 --- a/bin/node/inspect/src/command.rs +++ b/bin/node/inspect/src/command.rs @@ -23,7 +23,7 @@ use crate::{ Inspector, }; use sc_cli::{CliConfiguration, ImportParams, Result, SharedParams}; -use sc_executor::{DefaultExecutor}; +use sc_executor::WasmExecutor; use sc_service::{new_full_client, Configuration}; use sp_runtime::traits::Block; use std::str::FromStr; @@ -35,7 +35,7 @@ impl InspectCmd { B: Block, B::Hash: FromStr, { - let executor = DefaultExecutor::new( + let executor = WasmExecutor::new_default( config.wasm_method, config.default_heap_pages, config.max_runtime_instances, diff --git a/bin/node/testing/src/bench.rs b/bin/node/testing/src/bench.rs index c068496e13bd0..366c3d8c0e0c2 100644 --- a/bin/node/testing/src/bench.rs +++ b/bin/node/testing/src/bench.rs @@ -400,7 +400,7 @@ impl BenchDb { let backend = sc_service::new_db_backend(db_config).expect("Should not fail"); let client = sc_service::new_client( backend.clone(), - sc_executor::DefaultExecutor::new(WasmExecutionMethod::Compiled, None, 8, None, 2), + sc_executor::WasmExecutor::new_default(WasmExecutionMethod::Compiled, None, 8, None, 2), &keyring.generate_genesis(), None, None, diff --git a/client/chain-spec/src/chain_spec.rs b/client/chain-spec/src/chain_spec.rs index 954523ceff4fe..0c175beeccc53 100644 --- a/client/chain-spec/src/chain_spec.rs +++ b/client/chain-spec/src/chain_spec.rs @@ -108,7 +108,7 @@ impl GenesisSource { let mut ext = sp_state_machine::BasicExternalities::default(); let runtime_code = sc_executor::RuntimeBlob::uncompress_if_needed(code) .map_err(|e| format!("Error loading runtime code: {}", e))?; - let executor = sc_executor::DefaultExecutor::new( + let executor = sc_executor::WasmExecutor::new_default( sc_executor::WasmExecutionMethod::Interpreted, None, 1, None, 1 ); diff --git a/client/executor/src/integration_tests/mod.rs b/client/executor/src/integration_tests/mod.rs index 462a8ba1b8766..56985def25f65 100644 --- a/client/executor/src/integration_tests/mod.rs +++ b/client/executor/src/integration_tests/mod.rs @@ -124,7 +124,7 @@ fn call_in_wasm( ext: &mut E, ) -> Result, Error> { let executor = - crate::WasmExecutor::::new(execution_method, Some(1024), 8, None, 2); + crate::WasmExecutor::new_default(execution_method, Some(1024), 8, None, 2); executor.uncached_call( RuntimeBlob::uncompress_if_needed(wasm_binary_unwrap()).unwrap(), ext, @@ -453,7 +453,7 @@ test_wasm_execution!(should_trap_when_heap_exhausted); fn should_trap_when_heap_exhausted(wasm_method: WasmExecutionMethod) { let mut ext = TestExternalities::default(); - let executor = crate::WasmExecutor::::new( + let executor = crate::WasmExecutor::new_default( wasm_method, Some(17), // `17` is the initial number of pages compiled into the binary. 8, @@ -479,7 +479,9 @@ fn mk_test_runtime(wasm_method: WasmExecutionMethod, pages: u64) -> Arc( + let host_functions = crate::wasm_runtime::HostFunctionCollection::new::(); + crate::wasm_runtime::create_wasm_runtime_with_code( + &host_functions, wasm_method, pages, blob, @@ -566,7 +568,7 @@ fn heap_is_reset_between_calls(wasm_method: WasmExecutionMethod) { test_wasm_execution!(parallel_execution); fn parallel_execution(wasm_method: WasmExecutionMethod) { - let executor = std::sync::Arc::new(crate::WasmExecutor::::new( + let executor = std::sync::Arc::new(crate::WasmExecutor::new_default( wasm_method, Some(1024), 8, @@ -739,7 +741,9 @@ fn memory_is_cleared_between_invocations(wasm_method: WasmExecutionMethod) { ) )"#).unwrap(); - let runtime = crate::wasm_runtime::create_wasm_runtime_with_code::( + let host_functions = crate::wasm_runtime::HostFunctionCollection::new::(); + let runtime = crate::wasm_runtime::create_wasm_runtime_with_code( + &host_functions, wasm_method, 1024, RuntimeBlob::uncompress_if_needed(&binary[..]).unwrap(), diff --git a/client/executor/src/lib.rs b/client/executor/src/lib.rs index f3272463e3d3f..6f4ffc550f2aa 100644 --- a/client/executor/src/lib.rs +++ b/client/executor/src/lib.rs @@ -51,9 +51,6 @@ pub use wasmi; pub use sc_executor_common::{error, sandbox, runtime_blob::RuntimeBlob}; -/// Default WASM executor with substrate host function set. -pub type DefaultExecutor = WasmExecutor>; - /// Extracts the runtime version of a given runtime code. pub trait RuntimeVersionOf { /// Extract [`RuntimeVersion`](sp_version::RuntimeVersion) of the given `runtime_code`. @@ -76,7 +73,7 @@ mod tests { let mut ext = TestExternalities::default(); let mut ext = ext.ext(); - let executor = WasmExecutor::::new( + let executor = WasmExecutor::new_default( WasmExecutionMethod::Interpreted, Some(8), 8, diff --git a/client/executor/src/native_executor.rs b/client/executor/src/native_executor.rs index b371170634949..4af690396457f 100644 --- a/client/executor/src/native_executor.rs +++ b/client/executor/src/native_executor.rs @@ -18,13 +18,12 @@ use crate::{ error::{Error, Result}, - wasm_runtime::{RuntimeCache, WasmExecutionMethod}, + wasm_runtime::{RuntimeCache, WasmExecutionMethod, HostFunctionCollection}, RuntimeVersionOf, }; use std::{ collections::HashMap, - marker::PhantomData, panic::{AssertUnwindSafe, UnwindSafe}, path::PathBuf, result, @@ -90,9 +89,10 @@ pub trait NativeExecutionDispatch: Send + Sync { fn native_version() -> NativeVersion; } + /// An abstraction over Wasm code executor. Supports selecting execution backend and /// manages runtime cache. -pub struct WasmExecutor { +pub struct WasmExecutor { /// Method used to execute fallback Wasm code. method: WasmExecutionMethod, /// The number of 64KB pages to allocate for Wasm execution. @@ -102,26 +102,23 @@ pub struct WasmExecutor { /// The path to a directory which the executor can leverage for a file cache, e.g. put there /// compiled artifacts. cache_path: Option, - - phantom: PhantomData, + /// A set of host functions available to be called from Wasm. + host_functions: HostFunctionCollection, } -impl Clone for WasmExecutor { +impl Clone for WasmExecutor { fn clone(&self) -> Self { Self { method: self.method, default_heap_pages: self.default_heap_pages, cache: self.cache.clone(), cache_path: self.cache_path.clone(), - phantom: self.phantom, + host_functions: self.host_functions.clone(), } } } -impl WasmExecutor -where - H: HostFunctions, -{ +impl WasmExecutor { /// Create new instance. /// /// # Parameters @@ -131,15 +128,16 @@ where /// `default_heap_pages` - Number of 64KB pages to allocate for Wasm execution. /// Defaults to `DEFAULT_HEAP_PAGES` if `None` is provided. /// - /// `host_functions` - The set of host functions to be available for import provided by this - /// executor. - /// /// `max_runtime_instances` - The number of runtime instances to keep in memory ready for reuse. /// /// `cache_path` - A path to a directory where the executor can place its files for purposes of /// caching. This may be important in cases when there are many different modules with the /// compiled execution method is used. - pub fn new( + /// + /// `runtime_cache_size` - The size of the instances cache for each runtime. + /// + /// The list of supported host functions is extracted from the provided `HostFunctions` implementation. + pub fn new( method: WasmExecutionMethod, default_heap_pages: Option, max_runtime_instances: usize, @@ -155,10 +153,74 @@ where runtime_cache_size, )), cache_path, - phantom: PhantomData, + host_functions: HostFunctionCollection::new::(), } } + /// Create a new instance with default set of host functions. + /// + /// # Parameters + /// + /// `method` - Method used to execute Wasm code. + /// + /// `default_heap_pages` - Number of 64KB pages to allocate for Wasm execution. + /// Defaults to `DEFAULT_HEAP_PAGES` if `None` is provided. + /// + /// `max_runtime_instances` - The number of runtime instances to keep in memory ready for reuse. + /// + /// `cache_path` - A path to a directory where the executor can place its files for purposes of + /// caching. This may be important in cases when there are many different modules with the + /// compiled execution method is used. + /// + /// `runtime_cache_size` - The size of the instances cache for each runtime. + pub fn new_default( + method: WasmExecutionMethod, + default_heap_pages: Option, + max_runtime_instances: usize, + cache_path: Option, + runtime_cache_size: u8, + ) -> Self { + Self::new::( + method, + default_heap_pages, + max_runtime_instances, + cache_path, + runtime_cache_size, + ) + } + + /// Create a new instance with default set of host functions extended with custom `HostFunctions` + /// + /// # Parameters + /// + /// `method` - Method used to execute Wasm code. + /// + /// `default_heap_pages` - Number of 64KB pages to allocate for Wasm execution. + /// Defaults to `DEFAULT_HEAP_PAGES` if `None` is provided. + /// + /// `max_runtime_instances` - The number of runtime instances to keep in memory ready for reuse. + /// + /// `cache_path` - A path to a directory where the executor can place its files for purposes of + /// caching. This may be important in cases when there are many different modules with the + /// compiled execution method is used. + /// + /// `runtime_cache_size` - The size of the instances cache for each runtime. + pub fn new_extended( + method: WasmExecutionMethod, + default_heap_pages: Option, + max_runtime_instances: usize, + cache_path: Option, + runtime_cache_size: u8, + ) -> Self { + Self::new::>( + method, + default_heap_pages, + max_runtime_instances, + cache_path, + runtime_cache_size, + ) + } + /// Execute the given closure `f` with the latest runtime (based on `runtime_code`). /// /// The closure `f` is expected to return `Err(_)` when there happened a `panic!` in native code @@ -187,8 +249,9 @@ where AssertUnwindSafe<&mut dyn Externalities>, ) -> Result>, { - match self.cache.with_instance::( + match self.cache.with_instance( runtime_code, + &self.host_functions, ext, self.method, self.default_heap_pages, @@ -221,7 +284,8 @@ where export_name: &str, call_data: &[u8], ) -> std::result::Result, Error> { - let module = crate::wasm_runtime::create_wasm_runtime_with_code::( + let module = crate::wasm_runtime::create_wasm_runtime_with_code( + &self.host_functions, self.method, self.default_heap_pages, runtime_blob, @@ -243,18 +307,14 @@ where }) .and_then(|r| r) } -} -impl crate::DefaultExecutor { - /// Add additional host functions potentially overwriting existing functions. - pub fn extend_host_functions(&mut self, functions: Vec<&'static dyn sp_wasm_interface::Function>) { + #[cfg(test)] + pub fn functions(&self) -> &Vec<&'static dyn sp_wasm_interface::Function> { + self.host_functions.functions() } } -impl sp_core::traits::ReadRuntimeVersion for WasmExecutor -where - H: HostFunctions, -{ +impl sp_core::traits::ReadRuntimeVersion for WasmExecutor { fn read_runtime_version( &self, wasm_code: &[u8], @@ -289,10 +349,7 @@ where } } -impl CodeExecutor for WasmExecutor -where - H: HostFunctions, -{ +impl CodeExecutor for WasmExecutor { type Error = Error; fn call< @@ -322,10 +379,7 @@ where } } -impl RuntimeVersionOf for WasmExecutor -where - H: HostFunctions, -{ +impl RuntimeVersionOf for WasmExecutor { fn runtime_version( &self, ext: &mut dyn Externalities, @@ -348,8 +402,7 @@ where /// Native runtime version info. native_version: NativeVersion, /// Fallback wasm executor. - wasm: - WasmExecutor>, + wasm: WasmExecutor, } impl NativeElseWasmExecutor { @@ -367,7 +420,9 @@ impl NativeElseWasmExecutor { max_runtime_instances: usize, runtime_cache_size: u8, ) -> Self { - let wasm_executor = WasmExecutor::new( + let wasm_executor = WasmExecutor::new:: + > + ( fallback_method, default_heap_pages, max_runtime_instances, @@ -667,13 +722,9 @@ mod tests { 2, ); - fn extract_host_functions( - _: &WasmExecutor, - ) -> Vec<&'static dyn sp_wasm_interface::Function> - where - H: HostFunctions, + fn extract_host_functions(executor: &WasmExecutor) -> Vec<&'static dyn sp_wasm_interface::Function> { - H::host_functions() + executor.functions().clone() } my_interface::HostFunctions::host_functions().iter().for_each(|function| { diff --git a/client/executor/src/wasm_runtime.rs b/client/executor/src/wasm_runtime.rs index 2cccb6f9c38b0..58339c324c337 100644 --- a/client/executor/src/wasm_runtime.rs +++ b/client/executor/src/wasm_runtime.rs @@ -37,7 +37,29 @@ use std::{ sync::Arc, }; -use sp_wasm_interface::HostFunctions; +use sp_wasm_interface::{HostFunctions, Function}; + +#[derive(Clone)] +pub struct HostFunctionCollection { + host_functions: Arc>, + #[cfg(feature = "wasmtime")] + registrar: Arc, +} + +impl HostFunctionCollection { + pub fn new() -> HostFunctionCollection { + HostFunctionCollection { + host_functions: Arc::new(H::host_functions()), + #[cfg(feature = "wasmtime")] + registrar: Arc::new(sc_executor_wasmtime::HostFunctionsRegistrar::::new()), + } + } + + #[cfg(test)] + pub fn functions(&self) -> &Vec<&'static dyn Function> { + self.host_functions.as_ref() + } +} /// Specification of different methods of executing the runtime Wasm code. #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] @@ -214,9 +236,10 @@ impl RuntimeCache { /// /// `Error::InvalidMemoryReference` is returned if no memory export with the /// identifier `memory` can be found in the runtime. - pub fn with_instance<'c, H, R, F>( + pub fn with_instance<'c, R, F>( &self, runtime_code: &'c RuntimeCode<'c>, + host_functions: &HostFunctionCollection, ext: &mut dyn Externalities, wasm_method: WasmExecutionMethod, default_heap_pages: u64, @@ -224,7 +247,6 @@ impl RuntimeCache { f: F, ) -> Result, Error> where - H: HostFunctions, F: FnOnce( &Arc, &mut dyn WasmInstance, @@ -247,8 +269,9 @@ impl RuntimeCache { let time = std::time::Instant::now(); - let result = create_versioned_wasm_runtime::( + let result = create_versioned_wasm_runtime( &code, + host_functions, ext, wasm_method, heap_pages, @@ -287,16 +310,14 @@ impl RuntimeCache { } /// Create a wasm runtime with the given `code`. -pub fn create_wasm_runtime_with_code( +pub fn create_wasm_runtime_with_code( + host_functions: &HostFunctionCollection, wasm_method: WasmExecutionMethod, heap_pages: u64, blob: RuntimeBlob, allow_missing_func_imports: bool, cache_path: Option<&Path>, -) -> Result, WasmError> -where - H: HostFunctions, -{ +) -> Result, WasmError> { match wasm_method { WasmExecutionMethod::Interpreted => { // Wasmi doesn't have any need in a cache directory. @@ -308,13 +329,13 @@ where sc_executor_wasmi::create_runtime( blob, heap_pages, - H::host_functions(), + host_functions.host_functions.clone(), allow_missing_func_imports, ) .map(|runtime| -> Arc { Arc::new(runtime) }) }, #[cfg(feature = "wasmtime")] - WasmExecutionMethod::Compiled => sc_executor_wasmtime::create_runtime::( + WasmExecutionMethod::Compiled => sc_executor_wasmtime::create_runtime( blob, sc_executor_wasmtime::Config { heap_pages, @@ -328,6 +349,7 @@ where parallel_compilation: true, }, }, + host_functions.registrar.clone(), ) .map(|runtime| -> Arc { Arc::new(runtime) }), } @@ -389,18 +411,16 @@ pub fn read_embedded_version(blob: &RuntimeBlob) -> Result( +fn create_versioned_wasm_runtime( code: &[u8], + host_functions: &HostFunctionCollection, ext: &mut dyn Externalities, wasm_method: WasmExecutionMethod, heap_pages: u64, allow_missing_func_imports: bool, max_instances: usize, cache_path: Option<&Path>, -) -> Result -where - H: HostFunctions, -{ +) -> Result { // The incoming code may be actually compressed. We decompress it here and then work with // the uncompressed code from now on. let blob = sc_executor_common::runtime_blob::RuntimeBlob::uncompress_if_needed(&code)?; @@ -410,7 +430,8 @@ where // runtime. let mut version: Option<_> = read_embedded_version(&blob)?; - let runtime = create_wasm_runtime_with_code::( + let runtime = create_wasm_runtime_with_code( + host_functions, wasm_method, heap_pages, blob, diff --git a/client/executor/wasmi/src/lib.rs b/client/executor/wasmi/src/lib.rs index f0488972daca9..83dfb9933d96f 100644 --- a/client/executor/wasmi/src/lib.rs +++ b/client/executor/wasmi/src/lib.rs @@ -710,7 +710,7 @@ impl WasmModule for WasmiRuntime { pub fn create_runtime( blob: RuntimeBlob, heap_pages: u64, - host_functions: Vec<&'static dyn Function>, + host_functions: Arc>, allow_missing_func_imports: bool, ) -> Result { let data_segments_snapshot = @@ -723,7 +723,7 @@ pub fn create_runtime( let (instance, _, _) = instantiate_module( heap_pages as usize, &module, - &host_functions, + &*host_functions, allow_missing_func_imports, ) .map_err(|e| WasmError::Instantiation(e.to_string()))?; @@ -734,7 +734,7 @@ pub fn create_runtime( module, data_segments_snapshot, global_vals_snapshot, - host_functions: Arc::new(host_functions), + host_functions, allow_missing_func_imports, heap_pages, }) diff --git a/client/executor/wasmtime/src/host.rs b/client/executor/wasmtime/src/host.rs index b310ada24b629..71e5cc3674afb 100644 --- a/client/executor/wasmtime/src/host.rs +++ b/client/executor/wasmtime/src/host.rs @@ -69,7 +69,7 @@ impl HostState { /// A `HostContext` implements `FunctionContext` for making host calls from a Wasmtime /// runtime. The `HostContext` exists only for the lifetime of the call and borrows state from /// a longer-living `HostState`. -pub(crate) struct HostContext<'a> { +pub struct HostContext<'a> { pub(crate) caller: Caller<'a, StoreData>, } diff --git a/client/executor/wasmtime/src/imports.rs b/client/executor/wasmtime/src/imports.rs index 636a5761c9475..08eec3649ccb6 100644 --- a/client/executor/wasmtime/src/imports.rs +++ b/client/executor/wasmtime/src/imports.rs @@ -34,15 +34,13 @@ pub struct Imports { /// Goes over all imports of a module and prepares a vector of `Extern`s that can be used for /// instantiation of the module. Returns an error if there are imports that cannot be satisfied. -pub(crate) fn resolve_imports( +pub(crate) fn resolve_imports( store: &mut Store, + registrar: &dyn Registrar, module: &Module, heap_pages: u64, allow_missing_func_imports: bool, -) -> Result -where - H: HostFunctions, -{ +) -> Result { let mut externs = vec![]; let mut memory_import_index = None; let mut pending_func_imports = HashMap::new(); @@ -77,8 +75,8 @@ where } let mut registry = Registry { store, externs, pending_func_imports }; + registrar.register_all(&mut registry)?; - H::register_static(&mut registry)?; let mut externs = registry.externs; if !registry.pending_func_imports.is_empty() { @@ -108,7 +106,7 @@ where Ok(Imports { memory_import_index, externs }) } -struct Registry<'a, 'b> { +pub struct Registry<'a, 'b> { store: &'a mut Store, externs: Vec<(usize, Extern)>, pending_func_imports: HashMap, FuncType)>, @@ -140,6 +138,24 @@ impl<'a, 'b> sp_wasm_interface::HostFunctionRegistry for Registry<'a, 'b> { } } +pub trait Registrar: Send + Sync + 'static { + fn register_all<'a, 'b>(&self, registry: &mut Registry<'a, 'b>) -> Result<(), WasmError>; +} + +pub struct HostFunctionsRegistrar(std::marker::PhantomData); + +impl HostFunctionsRegistrar { + pub fn new() -> Self { + HostFunctionsRegistrar::(Default::default()) + } +} + +impl Registrar for HostFunctionsRegistrar { + fn register_all<'a, 'b>(&self, registry: &mut Registry<'a, 'b>) -> Result<(), WasmError> { + H::register_static(registry) + } +} + /// When the module linking proposal is supported the import's name can be `None`. /// Because we are not using this proposal we could safely unwrap the name. /// However, we opt for an error in order to avoid panics at all costs. diff --git a/client/executor/wasmtime/src/instance_wrapper.rs b/client/executor/wasmtime/src/instance_wrapper.rs index 896b71cea21dd..094f8d4575434 100644 --- a/client/executor/wasmtime/src/instance_wrapper.rs +++ b/client/executor/wasmtime/src/instance_wrapper.rs @@ -20,11 +20,12 @@ //! runtime module. use crate::runtime::{Store, StoreData}; +use crate::imports::Registrar; use sc_executor_common::{ error::{Backtrace, Error, MessageWithBacktrace, Result}, wasm_runtime::InvokeMethod, }; -use sp_wasm_interface::{HostFunctions, Pointer, Value, WordSize}; +use sp_wasm_interface::{Pointer, Value, WordSize}; use wasmtime::{ AsContext, AsContextMut, Extern, Func, Global, Instance, Memory, Module, Table, Val, }; @@ -164,14 +165,13 @@ fn extern_func(extern_: &Extern) -> Option<&Func> { impl InstanceWrapper { /// Create a new instance wrapper from the given wasm module. - pub fn new( + pub fn new( module: &Module, + registrar: &dyn Registrar, heap_pages: u64, allow_missing_func_imports: bool, max_memory_size: Option, ) -> Result - where - H: HostFunctions, { let limits = if let Some(max_memory_size) = max_memory_size { wasmtime::StoreLimitsBuilder::new().memory_size(max_memory_size).build() @@ -189,8 +189,9 @@ impl InstanceWrapper { // Scan all imports, find the matching host functions, and create stubs that adapt arguments // and results. - let imports = crate::imports::resolve_imports::( + let imports = crate::imports::resolve_imports( &mut store, + registrar, module, heap_pages, allow_missing_func_imports, @@ -436,7 +437,8 @@ fn decommit_works() { let engine = wasmtime::Engine::default(); let code = wat::parse_str("(module (memory (export \"memory\") 1 4))").unwrap(); let module = Module::new(&engine, code).unwrap(); - let mut wrapper = InstanceWrapper::new::<()>(&module, 2, true, None).unwrap(); + let registrar = crate::HostFunctionsRegistrar::<()>::new(); + let mut wrapper = InstanceWrapper::new(&module, ®istrar, 2, true, None).unwrap(); unsafe { *wrapper.memory.data_ptr(&wrapper.store) = 42 }; assert_eq!(unsafe { *wrapper.memory.data_ptr(&wrapper.store) }, 42); wrapper.decommit(); diff --git a/client/executor/wasmtime/src/lib.rs b/client/executor/wasmtime/src/lib.rs index c54c8305f3e4b..cad2188e06107 100644 --- a/client/executor/wasmtime/src/lib.rs +++ b/client/executor/wasmtime/src/lib.rs @@ -40,3 +40,4 @@ pub use runtime::{ create_runtime, create_runtime_from_artifact, prepare_runtime_artifact, Config, DeterministicStackLimit, Semantics, }; +pub use imports::{HostFunctionsRegistrar, Registrar}; diff --git a/client/executor/wasmtime/src/runtime.rs b/client/executor/wasmtime/src/runtime.rs index 6533aa194e4c4..b87372d1afed6 100644 --- a/client/executor/wasmtime/src/runtime.rs +++ b/client/executor/wasmtime/src/runtime.rs @@ -21,9 +21,9 @@ use crate::{ host::HostState, instance_wrapper::{EntryPoint, InstanceWrapper}, + imports::{Registrar, HostFunctionsRegistrar}, util, }; -use core::marker::PhantomData; use sc_allocator::FreeingBumpHeapAllocator; use sc_executor_common::{ @@ -44,7 +44,7 @@ use std::{ }; use wasmtime::{Engine, Memory, StoreLimits, Table}; -pub(crate) struct StoreData { +pub struct StoreData { /// The limits we apply to the store. We need to store it here to return a reference to this /// object when we have the limits enabled. pub(crate) limits: StoreLimits, @@ -80,31 +80,29 @@ impl StoreData { pub(crate) type Store = wasmtime::Store; -enum Strategy { +enum Strategy { FastInstanceReuse { instance_wrapper: InstanceWrapper, globals_snapshot: GlobalsSnapshot, data_segments_snapshot: Arc, heap_base: u32, }, - RecreateInstance(InstanceCreator), + RecreateInstance(InstanceCreator), } -struct InstanceCreator { +struct InstanceCreator { module: Arc, + registrar: Arc, heap_pages: u64, allow_missing_func_imports: bool, max_memory_size: Option, - phantom: PhantomData, } -impl InstanceCreator -where - H: HostFunctions, -{ +impl InstanceCreator { fn instantiate(&mut self) -> Result { - InstanceWrapper::new::( + InstanceWrapper::new( &*self.module, + &*self.registrar, self.heap_pages, self.allow_missing_func_imports, self.max_memory_size, @@ -144,21 +142,19 @@ struct InstanceSnapshotData { /// A `WasmModule` implementation using wasmtime to compile the runtime module to machine code /// and execute the compiled code. -pub struct WasmtimeRuntime { +pub struct WasmtimeRuntime { module: Arc, + registrar: Arc, snapshot_data: Option, config: Config, - phantom: PhantomData, } -impl WasmModule for WasmtimeRuntime -where - H: HostFunctions, -{ +impl WasmModule for WasmtimeRuntime { fn new_instance(&self) -> Result> { let strategy = if let Some(ref snapshot_data) = self.snapshot_data { - let mut instance_wrapper = InstanceWrapper::new::( + let mut instance_wrapper = InstanceWrapper::new( &self.module, + &*self.registrar, self.config.heap_pages, self.config.allow_missing_func_imports, self.config.max_memory_size, @@ -174,19 +170,19 @@ where &mut InstanceGlobals { instance: &mut instance_wrapper }, ); - Strategy::::FastInstanceReuse { + Strategy::FastInstanceReuse { instance_wrapper, globals_snapshot, data_segments_snapshot: snapshot_data.data_segments_snapshot.clone(), heap_base, } } else { - Strategy::::RecreateInstance(InstanceCreator { + Strategy::RecreateInstance(InstanceCreator { module: self.module.clone(), + registrar: self.registrar.clone(), heap_pages: self.config.heap_pages, allow_missing_func_imports: self.config.allow_missing_func_imports, max_memory_size: self.config.max_memory_size, - phantom: PhantomData, }) }; @@ -196,14 +192,11 @@ where /// A `WasmInstance` implementation that reuses compiled module and spawns instances /// to execute the compiled code. -pub struct WasmtimeInstance { - strategy: Strategy, +pub struct WasmtimeInstance { + strategy: Strategy, } -impl WasmInstance for WasmtimeInstance -where - H: HostFunctions, -{ +impl WasmInstance for WasmtimeInstance { fn call(&mut self, method: InvokeMethod, data: &[u8]) -> Result> { match &mut self.strategy { Strategy::FastInstanceReuse { @@ -495,15 +488,13 @@ enum CodeSupplyMode<'a> { /// /// The `H` generic parameter is used to statically pass a set of host functions which are exposed /// to the runtime. -pub fn create_runtime( +pub fn create_runtime( blob: RuntimeBlob, config: Config, -) -> std::result::Result, WasmError> -where - H: HostFunctions, -{ + registrar: Arc, +) -> std::result::Result { // SAFETY: this is safe because it doesn't use `CodeSupplyMode::Artifact`. - unsafe { do_create_runtime::(CodeSupplyMode::Verbatim { blob }, config) } + unsafe { do_create_runtime(CodeSupplyMode::Verbatim { blob }, config, registrar) } } /// The same as [`create_runtime`] but takes a precompiled artifact, which makes this function @@ -520,24 +511,23 @@ where pub unsafe fn create_runtime_from_artifact( compiled_artifact: &[u8], config: Config, -) -> std::result::Result, WasmError> +) -> std::result::Result where H: HostFunctions, { - do_create_runtime::(CodeSupplyMode::Artifact { compiled_artifact }, config) + let registrar = Arc::new(HostFunctionsRegistrar::::new()); + do_create_runtime(CodeSupplyMode::Artifact { compiled_artifact }, config, registrar) } /// # Safety /// /// This is only unsafe if called with [`CodeSupplyMode::Artifact`]. See /// [`create_runtime_from_artifact`] to get more details. -unsafe fn do_create_runtime( +unsafe fn do_create_runtime( code_supply_mode: CodeSupplyMode<'_>, config: Config, -) -> std::result::Result, WasmError> -where - H: HostFunctions, -{ + registrar: Arc, +) -> std::result::Result { // Create the engine, store and finally the module from the given code. let mut wasmtime_config = common_config(&config.semantics)?; if let Some(ref cache_path) = config.cache_path { @@ -584,7 +574,7 @@ where }, }; - Ok(WasmtimeRuntime { module: Arc::new(module), snapshot_data, config, phantom: PhantomData }) + Ok(WasmtimeRuntime { module: Arc::new(module), snapshot_data, config, registrar }) } fn instrument( diff --git a/client/executor/wasmtime/src/tests.rs b/client/executor/wasmtime/src/tests.rs index 664d05f5387fc..c6d9573da86db 100644 --- a/client/executor/wasmtime/src/tests.rs +++ b/client/executor/wasmtime/src/tests.rs @@ -78,7 +78,9 @@ impl RuntimeBuilder { .expect("failed to create a runtime blob out of test runtime") }; - let rt = crate::create_runtime::( + let registrar = Arc::new(crate::HostFunctionsRegistrar::::new()); + + let rt = crate::create_runtime( blob, crate::Config { heap_pages: self.heap_pages, @@ -98,6 +100,7 @@ impl RuntimeBuilder { parallel_compilation: true, }, }, + registrar, ) .expect("cannot create runtime"); @@ -314,7 +317,8 @@ fn test_max_memory_pages() { #[cfg_attr(build_type = "debug", ignore)] #[test] fn test_instances_without_reuse_are_not_leaked() { - let runtime = crate::create_runtime::( + let registrar = Arc::new(crate::HostFunctionsRegistrar::::new()); + let runtime = crate::create_runtime( RuntimeBlob::uncompress_if_needed(wasm_binary_unwrap()).unwrap(), crate::Config { heap_pages: 2048, @@ -328,6 +332,7 @@ fn test_instances_without_reuse_are_not_leaked() { parallel_compilation: true, }, }, + registrar, ) .unwrap(); diff --git a/client/service/src/builder.rs b/client/service/src/builder.rs index 166ef6c258787..6a840ef1d2a5b 100644 --- a/client/service/src/builder.rs +++ b/client/service/src/builder.rs @@ -219,7 +219,7 @@ impl KeystoreContainer { pub fn new_full_client( config: &Configuration, telemetry: Option, - executor: sc_executor::DefaultExecutor, + executor: sc_executor::WasmExecutor, ) -> Result, Error> where TBl: BlockT, @@ -231,7 +231,7 @@ where pub fn new_full_parts( config: &Configuration, telemetry: Option, - executor: sc_executor::DefaultExecutor, + executor: sc_executor::WasmExecutor, ) -> Result, Error> where TBl: BlockT, @@ -330,7 +330,7 @@ where /// Create an instance of client backed by given backend. pub fn new_client( backend: Arc>, - executor: sc_executor::DefaultExecutor, + executor: sc_executor::WasmExecutor, genesis_storage: &dyn BuildStorage, fork_blocks: ForkBlocks, bad_blocks: BadBlocks, diff --git a/client/service/src/client/call_executor.rs b/client/service/src/client/call_executor.rs index 91c5f23eb9fa1..94cdc035e8964 100644 --- a/client/service/src/client/call_executor.rs +++ b/client/service/src/client/call_executor.rs @@ -37,9 +37,9 @@ use std::{cell::RefCell, panic::UnwindSafe, result, sync::Arc}; /// data from local backend. pub struct LocalCallExecutor { backend: Arc, - executor: sc_executor::DefaultExecutor, + executor: sc_executor::WasmExecutor, wasm_override: Arc>, - wasm_substitutes: WasmSubstitutes, + wasm_substitutes: WasmSubstitutes, spawn_handle: Box, client_config: ClientConfig, } @@ -51,7 +51,7 @@ where /// Creates new instance of local call executor. pub fn new( backend: Arc, - executor: sc_executor::DefaultExecutor, + executor: sc_executor::WasmExecutor, spawn_handle: Box, client_config: ClientConfig, ) -> sp_blockchain::Result { @@ -135,7 +135,7 @@ where B: backend::Backend, Block: BlockT, { - type Error = ::Error; + type Error = ::Error; type Backend = B; @@ -350,7 +350,7 @@ mod tests { #[test] fn should_get_override_if_exists() { - let executor = sc_executor::DefaultExecutor::new( + let executor = sc_executor::WasmExecutor::new_default( WasmExecutionMethod::Interpreted, Some(128), 1, diff --git a/client/service/src/client/client.rs b/client/service/src/client/client.rs index e57df617dfaa5..234e385f1c8b0 100644 --- a/client/service/src/client/client.rs +++ b/client/service/src/client/client.rs @@ -93,7 +93,7 @@ use std::{ use { sc_client_api::in_mem, sp_core::traits::SpawnNamed, - sc_executor::DefaultExecutor, + sc_executor::WasmExecutor, }; type NotificationSinks = Mutex>>; @@ -153,7 +153,7 @@ enum PrepareStorageChangesResult, Block: BlockT> { /// Create an instance of in-memory client. #[cfg(feature = "test-helpers")] pub fn new_in_mem( - executor: DefaultExecutor, + executor: WasmExecutor, genesis_storage: &S, keystore: Option, prometheus_registry: Option, @@ -212,7 +212,7 @@ impl Default for ClientConfig { #[cfg(feature = "test-helpers")] pub fn new_with_backend( backend: Arc, - executor: DefaultExecutor, + executor: WasmExecutor, build_genesis_storage: &S, keystore: Option, spawn_handle: Box, diff --git a/primitives/runtime-interface/test/src/lib.rs b/primitives/runtime-interface/test/src/lib.rs index 1ab8dbfbbff22..5b3a67367d2f6 100644 --- a/primitives/runtime-interface/test/src/lib.rs +++ b/primitives/runtime-interface/test/src/lib.rs @@ -24,7 +24,7 @@ use sp_runtime_interface_test_wasm::{test_api::HostFunctions, wasm_binary_unwrap use sp_runtime_interface_test_wasm_deprecated::wasm_binary_unwrap as wasm_binary_deprecated_unwrap; use sc_executor_common::runtime_blob::RuntimeBlob; -use sp_wasm_interface::{ExtendedHostFunctions, HostFunctions as HostFunctionsT}; +use sp_wasm_interface::{HostFunctions as HostFunctionsT}; use std::{ collections::HashSet, @@ -40,9 +40,9 @@ fn call_wasm_method_with_result( let mut ext = TestExternalities::default(); let mut ext_ext = ext.ext(); - let executor = sc_executor::WasmExecutor::< - ExtendedHostFunctions, - >::new(sc_executor::WasmExecutionMethod::Interpreted, Some(8), 8, None, 2); + let executor = sc_executor::WasmExecutor::new_extended::( + sc_executor::WasmExecutionMethod::Interpreted, Some(8), 8, None, 2 + ); executor .uncached_call( diff --git a/test-utils/client/src/lib.rs b/test-utils/client/src/lib.rs index edf52341b006e..922e0ced72073 100644 --- a/test-utils/client/src/lib.rs +++ b/test-utils/client/src/lib.rs @@ -27,7 +27,7 @@ pub use sc_client_api::{ BadBlocks, ForkBlocks, }; pub use sc_client_db::{self, Backend}; -pub use sc_executor::{self, NativeElseWasmExecutor, WasmExecutionMethod, DefaultExecutor}; +pub use sc_executor::{self, NativeElseWasmExecutor, WasmExecutionMethod, WasmExecutor}; pub use sc_service::{client, RpcHandlers, RpcSession}; pub use sp_consensus; pub use sp_keyring::{ @@ -271,11 +271,11 @@ impl sc_consensus::LongestChain, ) where - I: Into>, + I: Into>, Backend: sc_client_api::backend::Backend + 'static, { let executor = executor.into().unwrap_or_else(|| { - DefaultExecutor::new(WasmExecutionMethod::Interpreted, None, 8, None, 2) + WasmExecutor::new_default(WasmExecutionMethod::Interpreted, None, 8, None, 2) }); let executor = LocalCallExecutor::new( self.backend.clone(), diff --git a/test-utils/runtime/client/src/lib.rs b/test-utils/runtime/client/src/lib.rs index e401a10b53aff..71b82bd247ef1 100644 --- a/test-utils/runtime/client/src/lib.rs +++ b/test-utils/runtime/client/src/lib.rs @@ -268,8 +268,8 @@ pub fn new() -> Client { } /// Create a new native executor. -pub fn new_executor() -> sc_executor::DefaultExecutor { - sc_executor::DefaultExecutor::new( +pub fn new_executor() -> sc_executor::WasmExecutor { + sc_executor::WasmExecutor::new_default( sc_executor::WasmExecutionMethod::Interpreted, None, 8, diff --git a/utils/frame/benchmarking-cli/src/command.rs b/utils/frame/benchmarking-cli/src/command.rs index 3a5fe54d400a2..116cdc904dd66 100644 --- a/utils/frame/benchmarking-cli/src/command.rs +++ b/utils/frame/benchmarking-cli/src/command.rs @@ -25,7 +25,7 @@ use frame_support::traits::StorageInfo; use linked_hash_map::LinkedHashMap; use sc_cli::{CliConfiguration, ExecutionStrategy, Result, SharedParams}; use sc_client_db::BenchmarkingState; -use sc_executor::DefaultExecutor; +use sc_executor::WasmExecutor; use sc_service::{Configuration}; use sp_core::offchain::{ testing::{TestOffchainExt, TestTransactionPoolExt}, @@ -133,7 +133,7 @@ impl BenchmarkCmd { )?; let state_without_tracking = BenchmarkingState::::new(genesis_storage, cache_size, self.record_proof, false)?; - let executor = DefaultExecutor::new( + let executor = WasmExecutor::new_default( wasm_method, self.heap_pages, 2, // The runtime instances cache size. From 987266fa1b292c4e04d8cb5ab711a39acd1363ed Mon Sep 17 00:00:00 2001 From: arkpar Date: Wed, 23 Feb 2022 09:24:25 +0100 Subject: [PATCH 13/14] Cleanup + formatting --- Cargo.toml | 5 +- bin/node-template/node/build.rs | 4 +- bin/node-template/node/src/chain_spec.rs | 1 - bin/node-template/node/src/command.rs | 4 +- bin/node-template/node/src/rpc.rs | 18 ++++-- bin/node-template/node/src/service.rs | 21 +++--- bin/node-template/runtime/src/lib.rs | 9 +-- bin/node/cli/build.rs | 3 +- bin/node/cli/src/chain_spec.rs | 3 +- bin/node/cli/src/service.rs | 16 ++--- bin/node/rpc/src/lib.rs | 22 +++++-- bin/node/runtime/src/lib.rs | 28 ++++---- bin/node/testing/src/client.rs | 11 +--- client/authority-discovery/src/lib.rs | 2 +- .../authority-discovery/src/worker/tests.rs | 2 +- .../basic-authorship/src/basic_authorship.rs | 14 ++-- client/block-builder/src/lib.rs | 4 +- client/chain-spec/src/chain_spec.rs | 21 +++--- client/consensus/aura/src/import_queue.rs | 3 +- .../manual-seal/src/consensus/aura.rs | 4 +- .../manual-seal/src/consensus/timestamp.rs | 4 +- client/executor/src/integration_tests/mod.rs | 12 +--- client/executor/src/lib.rs | 11 +--- client/executor/src/native_executor.rs | 27 ++++---- client/executor/src/wasm_runtime.rs | 2 +- .../executor/wasmtime/src/instance_wrapper.rs | 9 +-- client/executor/wasmtime/src/lib.rs | 2 +- client/executor/wasmtime/src/runtime.rs | 2 +- client/network/test/src/lib.rs | 5 +- client/service/src/builder.rs | 10 +-- client/service/src/client/call_executor.rs | 27 ++++---- client/service/src/client/client.rs | 15 +---- client/service/src/lib.rs | 3 +- client/service/test/src/client/mod.rs | 5 +- client/service/test/src/lib.rs | 15 ++--- frame/assets/src/lib.rs | 4 +- frame/aura/src/lib.rs | 4 +- frame/authority-discovery/src/lib.rs | 2 +- frame/babe/src/lib.rs | 4 +- frame/balances/src/lib.rs | 12 ++-- frame/collective/src/lib.rs | 4 +- frame/contracts/rpc/src/lib.rs | 25 ++++++-- frame/democracy/src/lib.rs | 4 +- frame/elections-phragmen/src/lib.rs | 9 ++- frame/gilt/src/lib.rs | 2 +- frame/grandpa/src/lib.rs | 2 +- frame/im-online/src/lib.rs | 4 +- frame/indices/src/lib.rs | 2 +- frame/membership/src/lib.rs | 2 +- frame/merkle-mountain-range/rpc/src/lib.rs | 14 ++-- frame/session/src/lib.rs | 4 +- frame/society/src/lib.rs | 2 +- frame/staking/src/lib.rs | 4 +- frame/staking/src/pallet/mod.rs | 4 +- frame/sudo/src/lib.rs | 5 +- .../src/construct_runtime/expand/config.rs | 4 +- .../src/pallet/expand/genesis_config.rs | 21 ++++-- frame/support/src/traits.rs | 4 +- frame/support/test/src/lib.rs | 1 - frame/transaction-payment/rpc/src/lib.rs | 6 +- frame/transaction-payment/src/lib.rs | 2 +- frame/transaction-storage/src/lib.rs | 2 +- frame/treasury/src/lib.rs | 4 +- frame/vesting/src/lib.rs | 4 +- .../api/proc-macro/src/decl_runtime_apis.rs | 3 +- .../proc-macro/src/mock_impl_runtime_apis.rs | 2 +- primitives/api/src/lib.rs | 64 +++++++++---------- primitives/api/test/tests/decl_and_impl.rs | 8 +-- primitives/consensus/common/src/lib.rs | 4 +- primitives/core/src/crypto.rs | 58 ++++++++++++----- primitives/runtime-interface/test/src/lib.rs | 8 ++- primitives/state-machine/src/lib.rs | 3 +- test-utils/client/src/lib.rs | 33 ++-------- .../runtime/client/src/block_builder_ext.rs | 2 +- test-utils/runtime/client/src/lib.rs | 21 ++---- utils/frame/benchmarking-cli/src/command.rs | 4 +- utils/frame/rpc/system/src/lib.rs | 8 ++- 77 files changed, 354 insertions(+), 369 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index ab8e4e51b434c..7030efbf6acb8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -275,8 +275,8 @@ yamux = { opt-level = 3 } zeroize = { opt-level = 3 } [profile.release] -panic = "abort" -incremental = true +# Substrate runtime requires unwinding. +panic = "unwind" [profile.production] inherits = "release" @@ -287,4 +287,3 @@ inherits = "release" lto = "fat" # https://doc.rust-lang.org/rustc/codegen-options/index.html#codegen-units codegen-units = 1 -incremental = false diff --git a/bin/node-template/node/build.rs b/bin/node-template/node/build.rs index 82930ee9df807..8fb412ae2539c 100644 --- a/bin/node-template/node/build.rs +++ b/bin/node-template/node/build.rs @@ -12,9 +12,9 @@ fn build_runtime() { let mut path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); path.push("../runtime/Cargo.toml"); WasmBuilder::new() - .with_project(path.canonicalize().unwrap()).unwrap() + .with_project(path.canonicalize().unwrap()) + .unwrap() .export_heap_base() .import_memory() .build() } - diff --git a/bin/node-template/node/src/chain_spec.rs b/bin/node-template/node/src/chain_spec.rs index 04d2cb73b8175..c941233860f0a 100644 --- a/bin/node-template/node/src/chain_spec.rs +++ b/bin/node-template/node/src/chain_spec.rs @@ -46,4 +46,3 @@ pub fn local_testnet_config() -> Result { Default::default(), )) } - diff --git a/bin/node-template/node/src/command.rs b/bin/node-template/node/src/command.rs index 9917c158f7f95..7ad114b5f5037 100644 --- a/bin/node-template/node/src/command.rs +++ b/bin/node-template/node/src/command.rs @@ -3,9 +3,9 @@ use crate::{ cli::{Cli, Subcommand}, service, }; -use service::Block; -use sc_cli::{SubstrateCli}; +use sc_cli::SubstrateCli; use sc_service::PartialComponents; +use service::Block; impl SubstrateCli for Cli { fn impl_name() -> String { diff --git a/bin/node-template/node/src/rpc.rs b/bin/node-template/node/src/rpc.rs index 23c8e39a88f8a..2b63d601383fe 100644 --- a/bin/node-template/node/src/rpc.rs +++ b/bin/node-template/node/src/rpc.rs @@ -7,12 +7,12 @@ use std::sync::Arc; -use crate::service::{Hash, Block, AccountId, Index, Balance}; +use crate::service::{AccountId, Balance, Block, Hash, Index}; +use pallet_transaction_payment_rpc::TransactionPaymentRuntimeDispatchInfo; pub use sc_rpc_api::DenyUnsafe; use sc_transaction_pool_api::TransactionPool; use sp_api::ProvideRuntimeApi; use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; -use pallet_transaction_payment_rpc::TransactionPaymentRuntimeDispatchInfo; /// Full client dependencies. pub struct FullDeps { @@ -38,9 +38,17 @@ where let mut io = jsonrpc_core::IoHandler::default(); let FullDeps { client, pool, deny_unsafe } = deps; - io.extend_with(SystemApi::::to_delegate(FullSystem::new(client.clone(), pool, deny_unsafe))); - - io.extend_with(TransactionPaymentApi::<_, TransactionPaymentRuntimeDispatchInfo>::to_delegate(TransactionPayment::new(client.clone()))); + io.extend_with(SystemApi::::to_delegate(FullSystem::new( + client.clone(), + pool, + deny_unsafe, + ))); + + io.extend_with( + TransactionPaymentApi::<_, TransactionPaymentRuntimeDispatchInfo>::to_delegate( + TransactionPayment::new(client.clone()), + ), + ); // Extend this RPC with a custom API by using the following syntax. // `YourRpcStruct` should have a reference to a client, which is needed diff --git a/bin/node-template/node/src/service.rs b/bin/node-template/node/src/service.rs index f24e8ffaebd62..58ccc27b41c29 100644 --- a/bin/node-template/node/src/service.rs +++ b/bin/node-template/node/src/service.rs @@ -25,8 +25,7 @@ pub type Index = u32; /// A hash of some data used by the chain. pub type Hash = sp_core::H256; -type FullClient = - sc_service::TFullClient; +type FullClient = sc_service::TFullClient; type FullBackend = sc_service::TFullBackend; type FullSelectChain = sc_consensus::LongestChain; @@ -75,12 +74,11 @@ pub fn new_partial( config.runtime_cache_size, ); - let (client, backend, keystore_container, task_manager) = - sc_service::new_full_parts::( - &config, - telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()), - executor, - )?; + let (client, backend, keystore_container, task_manager) = sc_service::new_full_parts::( + &config, + telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()), + executor, + )?; let client = Arc::new(client); let telemetry = telemetry.map(|(worker, telemetry)| { @@ -124,9 +122,7 @@ pub fn new_partial( Ok((timestamp, slot)) }, spawner: &task_manager.spawn_essential_handle(), - can_author_with: sp_consensus::CanAuthorWithVersion::new( - client.executor().clone(), - ), + can_author_with: sp_consensus::CanAuthorWithVersion::new(client.executor().clone()), registry: config.prometheus_registry(), check_for_equivocation: Default::default(), telemetry: telemetry.as_ref().map(|x| x.handle()), @@ -250,8 +246,7 @@ pub fn new_full(mut config: Configuration) -> Result telemetry.as_ref().map(|x| x.handle()), ); - let can_author_with = - sp_consensus::CanAuthorWithVersion::new(client.executor().clone()); + let can_author_with = sp_consensus::CanAuthorWithVersion::new(client.executor().clone()); let slot_duration = sc_consensus_aura::slot_duration(&*client)?; diff --git a/bin/node-template/runtime/src/lib.rs b/bin/node-template/runtime/src/lib.rs index 183db23d5bd3f..a0ba19603fb16 100644 --- a/bin/node-template/runtime/src/lib.rs +++ b/bin/node-template/runtime/src/lib.rs @@ -11,7 +11,10 @@ use pallet_grandpa::{ }; use sp_api::impl_runtime_apis; use sp_consensus_aura::sr25519::AuthorityId as AuraId; -use sp_core::{crypto::{KeyTypeId, dev_keys::*}, OpaqueMetadata}; +use sp_core::{ + crypto::{dev_keys::*, KeyTypeId}, + OpaqueMetadata, +}; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, NumberFor, Verify}, @@ -574,9 +577,7 @@ fn testnet_genesis( endowed_accounts: &[AccountId], ) -> GenesisConfig { GenesisConfig { - system: SystemConfig { - code: vec![], - }, + system: SystemConfig { code: vec![] }, balances: BalancesConfig { // Configure endowed accounts with initial balance of 1 << 60. balances: endowed_accounts.iter().cloned().map(|k| (k, 1 << 60)).collect(), diff --git a/bin/node/cli/build.rs b/bin/node/cli/build.rs index b087bb443a8be..83d560bed169f 100644 --- a/bin/node/cli/build.rs +++ b/bin/node/cli/build.rs @@ -29,7 +29,8 @@ fn build_runtime() { let mut path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); path.push("../runtime/Cargo.toml"); WasmBuilder::new() - .with_project(path.canonicalize().unwrap()).unwrap() + .with_project(path.canonicalize().unwrap()) + .unwrap() .export_heap_base() .import_memory() .build() diff --git a/bin/node/cli/src/chain_spec.rs b/bin/node/cli/src/chain_spec.rs index 8b9e3577aed24..60abc77beda6f 100644 --- a/bin/node/cli/src/chain_spec.rs +++ b/bin/node/cli/src/chain_spec.rs @@ -18,11 +18,11 @@ //! Substrate chain configurations. +pub use node_primitives::{AccountId, Balance, Block, Signature}; use sc_chain_spec::ChainSpecExtension; use sc_service::ChainType; use sc_telemetry::TelemetryEndpoints; use serde::{Deserialize, Serialize}; -pub use node_primitives::{AccountId, Balance, Signature, Block}; const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/"; @@ -115,7 +115,6 @@ pub fn local_testnet_config() -> ChainSpec { ) } - #[cfg(test)] pub(crate) mod tests { use super::*; diff --git a/bin/node/cli/src/service.rs b/bin/node/cli/src/service.rs index d3a3f697ecc6b..4f498659ebe3b 100644 --- a/bin/node/cli/src/service.rs +++ b/bin/node/cli/src/service.rs @@ -28,7 +28,7 @@ use sc_executor::WasmExecutor; use sc_network::{Event, NetworkService}; use sc_service::{config::Configuration, error::Error as ServiceError, RpcHandlers, TaskManager}; use sc_telemetry::{Telemetry, TelemetryWorker}; -use sp_runtime::{traits::Block as BlockT}; +use sp_runtime::traits::Block as BlockT; use std::sync::Arc; /// The full client type definition. @@ -102,12 +102,11 @@ pub fn new_partial( let executor = create_executor(config); - let (client, backend, keystore_container, task_manager) = - sc_service::new_full_parts::( - config, - telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()), - executor, - )?; + let (client, backend, keystore_container, task_manager) = sc_service::new_full_parts::( + config, + telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()), + executor, + )?; let client = Arc::new(client); let telemetry = telemetry.map(|(worker, telemetry)| { @@ -333,8 +332,7 @@ pub fn new_full_base( telemetry.as_ref().map(|x| x.handle()), ); - let can_author_with = - sp_consensus::CanAuthorWithVersion::new(client.executor().clone()); + let can_author_with = sp_consensus::CanAuthorWithVersion::new(client.executor().clone()); let client_clone = client.clone(); let slot_duration = babe_link.config().slot_duration(); diff --git a/bin/node/rpc/src/lib.rs b/bin/node/rpc/src/lib.rs index efcdde2a00a04..862246843212b 100644 --- a/bin/node/rpc/src/lib.rs +++ b/bin/node/rpc/src/lib.rs @@ -32,7 +32,7 @@ use std::sync::Arc; -use node_primitives::{Block, BlockNumber, Hash, Index, AccountId, Balance}; +use node_primitives::{AccountId, Balance, Block, BlockNumber, Hash, Index}; use sc_client_api::AuxStore; use sc_consensus_babe::{Config, Epoch}; use sc_consensus_babe_rpc::BabeRpcHandler; @@ -113,7 +113,9 @@ where { use pallet_contracts_rpc::{Contracts, ContractsApi}; use pallet_mmr_rpc::{Mmr, MmrApi}; - use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi, TransactionPaymentRuntimeDispatchInfo}; + use pallet_transaction_payment_rpc::{ + TransactionPayment, TransactionPaymentApi, TransactionPaymentRuntimeDispatchInfo, + }; use substrate_frame_rpc_system::{FullSystem, SystemApi}; let mut io = jsonrpc_core::IoHandler::default(); @@ -128,13 +130,23 @@ where finality_provider, } = grandpa; - io.extend_with(SystemApi::::to_delegate(FullSystem::new(client.clone(), pool, deny_unsafe))); + io.extend_with(SystemApi::::to_delegate(FullSystem::new( + client.clone(), + pool, + deny_unsafe, + ))); // Making synchronous calls in light client freezes the browser currently, // more context: https://github.com/paritytech/substrate/pull/3480 // These RPCs should use an asynchronous caller instead. - io.extend_with(ContractsApi::, AccountId, Balance, Hash>::to_delegate(Contracts::new(client.clone()))); + io.extend_with(ContractsApi::, AccountId, Balance, Hash>::to_delegate( + Contracts::new(client.clone()), + )); io.extend_with(MmrApi::::to_delegate(Mmr::new(client.clone()) as Mmr<_, (_, Hash)>)); - io.extend_with(TransactionPaymentApi::<_, TransactionPaymentRuntimeDispatchInfo>::to_delegate(TransactionPayment::new(client.clone()))); + io.extend_with( + TransactionPaymentApi::<_, TransactionPaymentRuntimeDispatchInfo>::to_delegate( + TransactionPayment::new(client.clone()), + ), + ); io.extend_with(sc_consensus_babe_rpc::BabeApi::to_delegate(BabeRpcHandler::new( client.clone(), shared_epoch_changes.clone(), diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index 40cb640b432e2..6d1f26cd62d05 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -22,7 +22,6 @@ // `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256. #![recursion_limit = "256"] -use hex_literal::hex; use codec::{Decode, Encode, MaxEncodedLen}; use frame_election_provider_support::onchain; use frame_support::{ @@ -42,13 +41,14 @@ use frame_system::{ limits::{BlockLength, BlockWeights}, EnsureRoot, }; +use hex_literal::hex; pub use node_primitives::{AccountId, Signature}; use node_primitives::{AccountIndex, Balance, BlockNumber, Hash, Index, Moment}; +use pallet_babe::AuthorityId as BabeId; use pallet_contracts::weights::WeightInfo; use pallet_grandpa::{ fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList, }; -use pallet_babe::{AuthorityId as BabeId}; use pallet_im_online::sr25519::AuthorityId as ImOnlineId; use pallet_session::historical as pallet_session_historical; pub use pallet_transaction_payment::{CurrencyAdapter, Multiplier, TargetedFeeAdjustment}; @@ -56,8 +56,8 @@ use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo}; use sp_api::impl_runtime_apis; use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId; use sp_core::{ - crypto::{UncheckedInto, KeyTypeId, dev_keys::*}, - OpaqueMetadata, sr25519, ed25519, + crypto::{dev_keys::*, KeyTypeId, UncheckedInto}, + ed25519, sr25519, OpaqueMetadata, }; use sp_inherents::{CheckInherentsResult, InherentData}; use sp_runtime::{ @@ -1983,10 +1983,12 @@ impl_runtime_apis! { } } - /// Helper function to generate stash, controller and session keys -pub fn authority_keys(sr25519_key: sr25519::Public, stash_key: sr25519::Public, ed25519_key: ed25519::Public) - -> (AccountId, AccountId, GrandpaId, BabeId, ImOnlineId, AuthorityDiscoveryId) { +pub fn authority_keys( + sr25519_key: sr25519::Public, + stash_key: sr25519::Public, + ed25519_key: ed25519::Public, +) -> (AccountId, AccountId, GrandpaId, BabeId, ImOnlineId, AuthorityDiscoveryId) { ( sr25519_key.into(), stash_key.into(), @@ -2052,10 +2054,8 @@ pub fn testnet_genesis( .iter() .map(|x| (x.0.clone(), x.1.clone(), STASH, pallet_staking::StakerStatus::Validator)) .chain(initial_nominators.iter().map(|x| { - let nominations = initial_authorities - .iter() - .map(|choice| choice.0.clone()) - .collect::>(); + let nominations = + initial_authorities.iter().map(|choice| choice.0.clone()).collect::>(); (x.clone(), x.clone(), STASH, pallet_staking::StakerStatus::Nominator(nominations)) })) .collect::>(); @@ -2110,10 +2110,7 @@ pub fn testnet_genesis( phantom: Default::default(), }, sudo: SudoConfig { key: Some(root_key) }, - babe: BabeConfig { - authorities: vec![], - epoch_config: Some(BABE_GENESIS_EPOCH_CONFIG), - }, + babe: BabeConfig { authorities: vec![], epoch_config: Some(BABE_GENESIS_EPOCH_CONFIG) }, im_online: ImOnlineConfig { keys: vec![] }, authority_discovery: AuthorityDiscoveryConfig { keys: vec![] }, grandpa: GrandpaConfig { authorities: vec![] }, @@ -2136,7 +2133,6 @@ pub fn testnet_genesis( } } - #[cfg(test)] mod tests { use super::*; diff --git a/bin/node/testing/src/client.rs b/bin/node/testing/src/client.rs index 7522c4a06ae55..eea5ad0f95a1d 100644 --- a/bin/node/testing/src/client.rs +++ b/bin/node/testing/src/client.rs @@ -30,10 +30,7 @@ pub type ExecutorDispatch = sc_executor::NativeElseWasmExecutor; /// Test client type. -pub type Client = client::Client< - Backend, - node_primitives::Block, ->; +pub type Client = client::Client; /// Transaction for node-runtime. pub type Transaction = sc_client_api::backend::TransactionFor; @@ -58,11 +55,7 @@ pub trait TestClientBuilderExt: Sized { } impl TestClientBuilderExt - for substrate_test_client::TestClientBuilder< - node_primitives::Block, - Backend, - GenesisParameters, - > + for substrate_test_client::TestClientBuilder { fn new() -> Self { Self::default() diff --git a/client/authority-discovery/src/lib.rs b/client/authority-discovery/src/lib.rs index 50a3b3735a13d..94a01b52539cd 100644 --- a/client/authority-discovery/src/lib.rs +++ b/client/authority-discovery/src/lib.rs @@ -42,7 +42,7 @@ use futures::{ use sc_client_api::blockchain::HeaderBackend; use sc_network::{DhtEvent, Multiaddr, PeerId}; use sp_api::ProvideRuntimeApi; -use sp_authority_discovery::{AuthorityId}; +use sp_authority_discovery::AuthorityId; use sp_runtime::traits::Block as BlockT; mod error; diff --git a/client/authority-discovery/src/worker/tests.rs b/client/authority-discovery/src/worker/tests.rs index ff578c9df42b8..1973110c62fab 100644 --- a/client/authority-discovery/src/worker/tests.rs +++ b/client/authority-discovery/src/worker/tests.rs @@ -33,7 +33,7 @@ use futures::{ use libp2p::{core::multiaddr, PeerId}; use prometheus_endpoint::prometheus::default_registry; -use sp_api::{ProvideRuntimeApi}; +use sp_api::ProvideRuntimeApi; use sp_keystore::{testing::KeyStore, CryptoStore}; use sp_runtime::traits::{Block as BlockT, NumberFor, Zero}; use substrate_test_runtime_client::runtime::Block; diff --git a/client/basic-authorship/src/basic_authorship.rs b/client/basic-authorship/src/basic_authorship.rs index adefb53afacc2..9c54fff736fc2 100644 --- a/client/basic-authorship/src/basic_authorship.rs +++ b/client/basic-authorship/src/basic_authorship.rs @@ -28,11 +28,11 @@ use futures::{ select, }; use log::{debug, error, info, trace, warn}; -use sc_block_builder::{BlockBuilderProvider}; +use sc_block_builder::BlockBuilderProvider; use sc_client_api::backend; use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_INFO}; use sc_transaction_pool_api::{InPoolTransaction, TransactionPool}; -use sp_api::{CallApiAt}; +use sp_api::CallApiAt; use sp_blockchain::{ApplyExtrinsicFailed::Validity, Error::ApplyExtrinsicFailed, HeaderBackend}; use sp_consensus::{ evaluation, DisableProofRecording, EnableProofRecording, ProofRecording, Proposal, @@ -184,7 +184,7 @@ where Block: BlockT, C: BlockBuilderProvider + HeaderBackend - + CallApiAt + + CallApiAt + Send + Sync + 'static, @@ -227,7 +227,7 @@ where Block: BlockT, C: BlockBuilderProvider + HeaderBackend - + CallApiAt + + CallApiAt + Send + Sync + 'static, @@ -266,7 +266,7 @@ where Block: BlockT, C: BlockBuilderProvider + HeaderBackend - + CallApiAt + + CallApiAt + Send + Sync + 'static, @@ -324,7 +324,7 @@ where Block: BlockT, C: BlockBuilderProvider + HeaderBackend - + CallApiAt + + CallApiAt + Send + Sync + 'static, @@ -561,7 +561,7 @@ mod tests { use sc_client_api::Backend; use sc_transaction_pool::BasicPool; use sc_transaction_pool_api::{ChainEvent, MaintainedTransactionPool, TransactionSource}; - use sp_api::{Core, ProvideRuntimeApi, ApiExt}; + use sp_api::{ApiExt, Core, ProvideRuntimeApi}; use sp_blockchain::HeaderBackend; use sp_consensus::{BlockOrigin, Environment, Proposer}; use sp_core::Pair; diff --git a/client/block-builder/src/lib.rs b/client/block-builder/src/lib.rs index 0bce0cb1c1a29..aab8d34501305 100644 --- a/client/block-builder/src/lib.rs +++ b/client/block-builder/src/lib.rs @@ -29,7 +29,7 @@ use codec::Encode; use sp_api::{ - ApiExt, RuntimeApi, Core, StorageChanges, StorageProof, TransactionOutcome, CallApiAt, + ApiExt, CallApiAt, Core, RuntimeApi, StorageChanges, StorageProof, TransactionOutcome, }; use sp_blockchain::{ApplyExtrinsicFailed, Error}; use sp_core::ExecutionContext; @@ -145,7 +145,7 @@ pub struct BlockBuilder<'a, Block: BlockT, A: 'a + CallApiAt, B> { impl<'a, Block, A, B> BlockBuilder<'a, Block, A, B> where Block: BlockT, - A: CallApiAt + 'a, + A: CallApiAt + 'a, B: backend::Backend, { /// Create a new instance of builder based on the given `parent_hash` and `parent_number`. diff --git a/client/chain-spec/src/chain_spec.rs b/client/chain-spec/src/chain_spec.rs index 0c175beeccc53..24143edeca977 100644 --- a/client/chain-spec/src/chain_spec.rs +++ b/client/chain-spec/src/chain_spec.rs @@ -20,13 +20,13 @@ #![warn(missing_docs)] use crate::{extension::GetExtension, ChainType, Properties, RuntimeGenesis}; +use sc_executor::Externalities; use sc_network::config::MultiaddrWithPeerId; use sc_telemetry::TelemetryEndpoints; -use sc_executor::Externalities; use serde::{Deserialize, Serialize}; use serde_json as json; use sp_core::{ - storage::{ChildInfo, Storage, StorageChild, StorageData, StorageKey, well_known_keys}, + storage::{well_known_keys, ChildInfo, Storage, StorageChild, StorageData, StorageKey}, Bytes, }; use sp_runtime::BuildStorage; @@ -37,10 +37,7 @@ enum GenesisSource { Binary(Cow<'static, [u8]>), Factory(Arc G + Send + Sync>), Storage(Storage), - Runtime { - code: &'static [u8], - method: &'static str - }, + Runtime { code: &'static [u8], method: &'static str }, } impl Clone for GenesisSource { @@ -56,7 +53,6 @@ impl Clone for GenesisSource { } impl GenesisSource { - fn from_storage(storage: &Storage) -> Genesis { let top = storage .top @@ -109,16 +105,21 @@ impl GenesisSource { let runtime_code = sc_executor::RuntimeBlob::uncompress_if_needed(code) .map_err(|e| format!("Error loading runtime code: {}", e))?; let executor = sc_executor::WasmExecutor::new_default( - sc_executor::WasmExecutionMethod::Interpreted, None, 1, None, 1 + sc_executor::WasmExecutionMethod::Interpreted, + None, + 1, + None, + 1, ); - executor.uncached_call(runtime_code, &mut ext, true, method, &[]) + executor + .uncached_call(runtime_code, &mut ext, true, method, &[]) .map_err(|e| format!("Error building genesis with {}: {}", method, e))?; ext.set_storage(well_known_keys::CODE.to_vec(), code.to_vec()); let storage = ext.into_storages(); Ok(Self::from_storage(&storage)) - } + }, } } } diff --git a/client/consensus/aura/src/import_queue.rs b/client/consensus/aura/src/import_queue.rs index dd05b9f0d32ba..7fe598cd8c16b 100644 --- a/client/consensus/aura/src/import_queue.rs +++ b/client/consensus/aura/src/import_queue.rs @@ -37,8 +37,7 @@ use sp_blockchain::{ }; use sp_consensus::{CanAuthorWith, Error as ConsensusError}; use sp_consensus_aura::{ - digests::CompatibleDigestItem, inherents::AuraInherentData, ConsensusLog, - AURA_ENGINE_ID, + digests::CompatibleDigestItem, inherents::AuraInherentData, ConsensusLog, AURA_ENGINE_ID, }; use sp_consensus_slots::Slot; use sp_core::{crypto::Pair, ExecutionContext}; diff --git a/client/consensus/manual-seal/src/consensus/aura.rs b/client/consensus/manual-seal/src/consensus/aura.rs index 2edffa72fd807..701d874ae8e00 100644 --- a/client/consensus/manual-seal/src/consensus/aura.rs +++ b/client/consensus/manual-seal/src/consensus/aura.rs @@ -25,9 +25,7 @@ use sc_consensus::BlockImportParams; use sp_api::{ProvideRuntimeApi, TransactionFor}; use sp_blockchain::{HeaderBackend, HeaderMetadata}; use sp_consensus_aura::{ - digests::CompatibleDigestItem, - sr25519::AuthoritySignature, - Slot, SlotDuration, + digests::CompatibleDigestItem, sr25519::AuthoritySignature, Slot, SlotDuration, }; use sp_inherents::InherentData; use sp_runtime::{traits::Block as BlockT, Digest, DigestItem}; diff --git a/client/consensus/manual-seal/src/consensus/timestamp.rs b/client/consensus/manual-seal/src/consensus/timestamp.rs index 1e0bf4bd71e5e..e7753a582f77c 100644 --- a/client/consensus/manual-seal/src/consensus/timestamp.rs +++ b/client/consensus/manual-seal/src/consensus/timestamp.rs @@ -23,9 +23,7 @@ use crate::Error; use sc_client_api::{AuxStore, UsageProvider}; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; -use sp_consensus_aura::{ - sr25519::{AuthoritySignature}, -}; +use sp_consensus_aura::sr25519::AuthoritySignature; use sp_consensus_slots::{Slot, SlotDuration}; use sp_inherents::{InherentData, InherentDataProvider, InherentIdentifier}; use sp_runtime::{ diff --git a/client/executor/src/integration_tests/mod.rs b/client/executor/src/integration_tests/mod.rs index 56985def25f65..8dee06ae0eb01 100644 --- a/client/executor/src/integration_tests/mod.rs +++ b/client/executor/src/integration_tests/mod.rs @@ -123,8 +123,7 @@ fn call_in_wasm( execution_method: WasmExecutionMethod, ext: &mut E, ) -> Result, Error> { - let executor = - crate::WasmExecutor::new_default(execution_method, Some(1024), 8, None, 2); + let executor = crate::WasmExecutor::new_default(execution_method, Some(1024), 8, None, 2); executor.uncached_call( RuntimeBlob::uncompress_if_needed(wasm_binary_unwrap()).unwrap(), ext, @@ -568,13 +567,8 @@ fn heap_is_reset_between_calls(wasm_method: WasmExecutionMethod) { test_wasm_execution!(parallel_execution); fn parallel_execution(wasm_method: WasmExecutionMethod) { - let executor = std::sync::Arc::new(crate::WasmExecutor::new_default( - wasm_method, - Some(1024), - 8, - None, - 2, - )); + let executor = + std::sync::Arc::new(crate::WasmExecutor::new_default(wasm_method, Some(1024), 8, None, 2)); let threads: Vec<_> = (0..8) .map(|_| { let executor = executor.clone(); diff --git a/client/executor/src/lib.rs b/client/executor/src/lib.rs index 6f4ffc550f2aa..bc46e9006c563 100644 --- a/client/executor/src/lib.rs +++ b/client/executor/src/lib.rs @@ -49,7 +49,7 @@ pub use sp_wasm_interface; pub use wasm_runtime::{read_embedded_version, WasmExecutionMethod}; pub use wasmi; -pub use sc_executor_common::{error, sandbox, runtime_blob::RuntimeBlob}; +pub use sc_executor_common::{error, runtime_blob::RuntimeBlob, sandbox}; /// Extracts the runtime version of a given runtime code. pub trait RuntimeVersionOf { @@ -73,13 +73,8 @@ mod tests { let mut ext = TestExternalities::default(); let mut ext = ext.ext(); - let executor = WasmExecutor::new_default( - WasmExecutionMethod::Interpreted, - Some(8), - 8, - None, - 2, - ); + let executor = + WasmExecutor::new_default(WasmExecutionMethod::Interpreted, Some(8), 8, None, 2); let res = executor .uncached_call( RuntimeBlob::uncompress_if_needed(wasm_binary_unwrap()).unwrap(), diff --git a/client/executor/src/native_executor.rs b/client/executor/src/native_executor.rs index 2103a0e768c0f..6ad035e806753 100644 --- a/client/executor/src/native_executor.rs +++ b/client/executor/src/native_executor.rs @@ -18,7 +18,7 @@ use crate::{ error::{Error, Result}, - wasm_runtime::{RuntimeCache, WasmExecutionMethod, HostFunctionCollection}, + wasm_runtime::{HostFunctionCollection, RuntimeCache, WasmExecutionMethod}, RuntimeVersionOf, }; @@ -88,7 +88,6 @@ pub trait NativeExecutionDispatch: Send + Sync { fn native_version() -> NativeVersion; } - /// An abstraction over Wasm code executor. Supports selecting execution backend and /// manages runtime cache. pub struct WasmExecutor { @@ -135,7 +134,8 @@ impl WasmExecutor { /// /// `runtime_cache_size` - The size of the instances cache for each runtime. /// - /// The list of supported host functions is extracted from the provided `HostFunctions` implementation. + /// The list of supported host functions is extracted from the provided `HostFunctions` + /// implementation. pub fn new( method: WasmExecutionMethod, default_heap_pages: Option, @@ -188,7 +188,8 @@ impl WasmExecutor { ) } - /// Create a new instance with default set of host functions extended with custom `HostFunctions` + /// Create a new instance with default set of host functions extended with custom + /// `HostFunctions` /// /// # Parameters /// @@ -425,15 +426,10 @@ impl NativeElseWasmExecutor { max_runtime_instances: usize, runtime_cache_size: u8, ) -> Self { - let wasm_executor = WasmExecutor::new:: - > - ( - fallback_method, - default_heap_pages, - max_runtime_instances, - None, - runtime_cache_size, - ); + let wasm_executor = + WasmExecutor::new::< + ExtendedHostFunctions, + >(fallback_method, default_heap_pages, max_runtime_instances, None, runtime_cache_size); NativeElseWasmExecutor { _dummy: Default::default(), @@ -732,8 +728,9 @@ mod tests { 2, ); - fn extract_host_functions(executor: &WasmExecutor) -> Vec<&'static dyn sp_wasm_interface::Function> - { + fn extract_host_functions( + executor: &WasmExecutor, + ) -> Vec<&'static dyn sp_wasm_interface::Function> { executor.functions().clone() } diff --git a/client/executor/src/wasm_runtime.rs b/client/executor/src/wasm_runtime.rs index 891c228cc9f4b..9189cd8e45dc5 100644 --- a/client/executor/src/wasm_runtime.rs +++ b/client/executor/src/wasm_runtime.rs @@ -37,7 +37,7 @@ use std::{ sync::Arc, }; -use sp_wasm_interface::{HostFunctions, Function}; +use sp_wasm_interface::{Function, HostFunctions}; #[derive(Clone)] pub struct HostFunctionCollection { diff --git a/client/executor/wasmtime/src/instance_wrapper.rs b/client/executor/wasmtime/src/instance_wrapper.rs index 094f8d4575434..af51448007c94 100644 --- a/client/executor/wasmtime/src/instance_wrapper.rs +++ b/client/executor/wasmtime/src/instance_wrapper.rs @@ -19,8 +19,10 @@ //! Defines data and logic needed for interaction with an WebAssembly instance of a substrate //! runtime module. -use crate::runtime::{Store, StoreData}; -use crate::imports::Registrar; +use crate::{ + imports::Registrar, + runtime::{Store, StoreData}, +}; use sc_executor_common::{ error::{Backtrace, Error, MessageWithBacktrace, Result}, wasm_runtime::InvokeMethod, @@ -171,8 +173,7 @@ impl InstanceWrapper { heap_pages: u64, allow_missing_func_imports: bool, max_memory_size: Option, - ) -> Result - { + ) -> Result { let limits = if let Some(max_memory_size) = max_memory_size { wasmtime::StoreLimitsBuilder::new().memory_size(max_memory_size).build() } else { diff --git a/client/executor/wasmtime/src/lib.rs b/client/executor/wasmtime/src/lib.rs index cad2188e06107..fba15c72fb843 100644 --- a/client/executor/wasmtime/src/lib.rs +++ b/client/executor/wasmtime/src/lib.rs @@ -36,8 +36,8 @@ mod util; #[cfg(test)] mod tests; +pub use imports::{HostFunctionsRegistrar, Registrar}; pub use runtime::{ create_runtime, create_runtime_from_artifact, prepare_runtime_artifact, Config, DeterministicStackLimit, Semantics, }; -pub use imports::{HostFunctionsRegistrar, Registrar}; diff --git a/client/executor/wasmtime/src/runtime.rs b/client/executor/wasmtime/src/runtime.rs index b87372d1afed6..e55372ac3e9d0 100644 --- a/client/executor/wasmtime/src/runtime.rs +++ b/client/executor/wasmtime/src/runtime.rs @@ -20,8 +20,8 @@ use crate::{ host::HostState, + imports::{HostFunctionsRegistrar, Registrar}, instance_wrapper::{EntryPoint, InstanceWrapper}, - imports::{Registrar, HostFunctionsRegistrar}, util, }; diff --git a/client/network/test/src/lib.rs b/client/network/test/src/lib.rs index 2503780da47c3..ff326c8373b87 100644 --- a/client/network/test/src/lib.rs +++ b/client/network/test/src/lib.rs @@ -120,10 +120,7 @@ impl Verifier for PassThroughVerifier { } } -pub type PeersFullClient = Client< - substrate_test_runtime_client::Backend, - Block, ->; +pub type PeersFullClient = Client; #[derive(Clone)] pub struct PeersClient { diff --git a/client/service/src/builder.rs b/client/service/src/builder.rs index 6a840ef1d2a5b..2f8c9a289578e 100644 --- a/client/service/src/builder.rs +++ b/client/service/src/builder.rs @@ -52,7 +52,7 @@ use sp_blockchain::{HeaderBackend, HeaderMetadata}; use sp_consensus::block_validation::{ BlockAnnounceValidator, Chain, DefaultBlockAnnounceValidator, }; -use sp_core::traits::{SpawnNamed}; +use sp_core::traits::SpawnNamed; use sp_keystore::{CryptoStore, SyncCryptoStore, SyncCryptoStorePtr}; use sp_runtime::{ generic::BlockId, @@ -339,13 +339,7 @@ pub fn new_client( prometheus_registry: Option, telemetry: Option, config: ClientConfig, -) -> Result< - crate::client::Client< - Backend, - Block, - >, - sp_blockchain::Error, -> +) -> Result, Block>, sp_blockchain::Error> where Block: BlockT, { diff --git a/client/service/src/client/call_executor.rs b/client/service/src/client/call_executor.rs index 94cdc035e8964..f746986bd1e6f 100644 --- a/client/service/src/client/call_executor.rs +++ b/client/service/src/client/call_executor.rs @@ -373,21 +373,18 @@ mod tests { let client_config = ClientConfig::default(); // client is used for the convenience of creating and inserting the genesis block. - let _client = substrate_test_runtime_client::client::new_with_backend::< - _, - runtime::Block, - _, - >( - backend.clone(), - executor.clone(), - &substrate_test_runtime_client::GenesisParameters::default().genesis_storage(), - None, - Box::new(TaskExecutor::new()), - None, - None, - Default::default(), - ) - .expect("Creates a client"); + let _client = + substrate_test_runtime_client::client::new_with_backend::<_, runtime::Block, _>( + backend.clone(), + executor.clone(), + &substrate_test_runtime_client::GenesisParameters::default().genesis_storage(), + None, + Box::new(TaskExecutor::new()), + None, + None, + Default::default(), + ) + .expect("Creates a client"); let call_executor = LocalCallExecutor { backend: backend.clone(), diff --git a/client/service/src/client/client.rs b/client/service/src/client/client.rs index 234e385f1c8b0..701ea77e88170 100644 --- a/client/service/src/client/client.rs +++ b/client/service/src/client/client.rs @@ -48,10 +48,7 @@ use sc_consensus::{ }; use sc_executor::{RuntimeVersion, RuntimeVersionOf}; use sc_telemetry::{telemetry, TelemetryHandle, SUBSTRATE_INFO}; -use sp_api::{ - ProvideRuntimeApi, - ApiExt, CallApiAt, CallApiAtParams, Core as CoreApi, RuntimeApi, -}; +use sp_api::{ApiExt, CallApiAt, CallApiAtParams, Core as CoreApi, ProvideRuntimeApi, RuntimeApi}; use sp_blockchain::{ self as blockchain, well_known_cache_keys::Id as CacheKeyId, Backend as ChainBackend, CachedHeaderMetadata, Error, HeaderBackend as ChainHeaderBackend, HeaderMetadata, @@ -90,11 +87,7 @@ use std::{ }; #[cfg(feature = "test-helpers")] -use { - sc_client_api::in_mem, - sp_core::traits::SpawnNamed, - sc_executor::WasmExecutor, -}; +use {sc_client_api::in_mem, sc_executor::WasmExecutor, sp_core::traits::SpawnNamed}; type NotificationSinks = Mutex>>; @@ -160,9 +153,7 @@ pub fn new_in_mem( telemetry: Option, spawn_handle: Box, config: ClientConfig, -) -> sp_blockchain::Result< - Client, Block>, -> +) -> sp_blockchain::Result, Block>> where S: BuildStorage, Block: BlockT, diff --git a/client/service/src/lib.rs b/client/service/src/lib.rs index 34825da75df32..c4a27fdf47823 100644 --- a/client/service/src/lib.rs +++ b/client/service/src/lib.rs @@ -50,8 +50,7 @@ pub use self::{ builder::{ build_network, build_offchain_workers, new_client, new_db_backend, new_full_client, new_full_parts, spawn_tasks, BuildNetworkParams, KeystoreContainer, NetworkStarter, - NoopRpcExtensionBuilder, RpcExtensionBuilder, SpawnTasksParams, TFullBackend, - TFullClient, + NoopRpcExtensionBuilder, RpcExtensionBuilder, SpawnTasksParams, TFullBackend, TFullClient, }, client::{ClientConfig, LocalCallExecutor}, error::Error, diff --git a/client/service/test/src/client/mod.rs b/client/service/test/src/client/mod.rs index c08ac9e7a1d51..14bce90fbb9fe 100644 --- a/client/service/test/src/client/mod.rs +++ b/client/service/test/src/client/mod.rs @@ -1733,10 +1733,7 @@ fn cleans_up_closed_notification_sinks_on_block_import() { ) .unwrap(); - type TestClient = Client< - in_mem::Backend, - Block, - >; + type TestClient = Client, Block>; let import_notif1 = client.import_notification_stream(); let import_notif2 = client.import_notification_stream(); diff --git a/client/service/test/src/lib.rs b/client/service/test/src/lib.rs index f721b111739a0..af53e7146cc19 100644 --- a/client/service/test/src/lib.rs +++ b/client/service/test/src/lib.rs @@ -86,9 +86,7 @@ pub struct TestNetComponents { network: Arc::Hash>>, } -impl - TestNetComponents -{ +impl TestNetComponents { pub fn new( task_manager: TaskManager, client: Arc>, @@ -99,9 +97,7 @@ impl } } -impl Clone - for TestNetComponents -{ +impl Clone for TestNetComponents { fn clone(&self) -> Self { Self { task_manager: self.task_manager.clone(), @@ -112,9 +108,7 @@ impl Clone } } -impl Future - for TestNetComponents -{ +impl Future for TestNetComponents { type Output = Result<(), sc_service::Error>; fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { @@ -122,8 +116,7 @@ impl Future } } -impl TestNetNode - for TestNetComponents +impl TestNetNode for TestNetComponents where TBl: BlockT, TBackend: sc_client_api::Backend + Send + Sync + 'static, diff --git a/frame/assets/src/lib.rs b/frame/assets/src/lib.rs index 7db6f8b31d52d..78105d5588156 100644 --- a/frame/assets/src/lib.rs +++ b/frame/assets/src/lib.rs @@ -155,8 +155,8 @@ use frame_support::{ pallet_prelude::DispatchResultWithPostInfo, traits::{ tokens::{fungibles, DepositConsequence, WithdrawConsequence}, - BalanceStatus::Reserved, GenesisBuild, - Currency, ReservableCurrency, StoredMap, + BalanceStatus::Reserved, + Currency, GenesisBuild, ReservableCurrency, StoredMap, }, }; use frame_system::Config as SystemConfig; diff --git a/frame/aura/src/lib.rs b/frame/aura/src/lib.rs index 6913c32457e64..53197938aa79b 100644 --- a/frame/aura/src/lib.rs +++ b/frame/aura/src/lib.rs @@ -40,7 +40,9 @@ use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ - traits::{DisabledValidators, FindAuthor, Get, OnTimestampSet, OneSessionHandler, GenesisBuild}, + traits::{ + DisabledValidators, FindAuthor, GenesisBuild, Get, OnTimestampSet, OneSessionHandler, + }, BoundedSlice, ConsensusEngineId, Parameter, WeakBoundedVec, }; use sp_consensus_aura::{AuthorityIndex, ConsensusLog, Slot, AURA_ENGINE_ID}; diff --git a/frame/authority-discovery/src/lib.rs b/frame/authority-discovery/src/lib.rs index 6657e82c3d130..c874297a980e1 100644 --- a/frame/authority-discovery/src/lib.rs +++ b/frame/authority-discovery/src/lib.rs @@ -24,7 +24,7 @@ #![cfg_attr(not(feature = "std"), no_std)] use frame_support::{ - traits::{Get, OneSessionHandler, GenesisBuild}, + traits::{GenesisBuild, Get, OneSessionHandler}, WeakBoundedVec, }; use sp_authority_discovery::AuthorityId; diff --git a/frame/babe/src/lib.rs b/frame/babe/src/lib.rs index 2170671584eed..2ffeeb35520b6 100644 --- a/frame/babe/src/lib.rs +++ b/frame/babe/src/lib.rs @@ -25,8 +25,8 @@ use codec::{Decode, Encode}; use frame_support::{ dispatch::DispatchResultWithPostInfo, traits::{ - ConstU32, DisabledValidators, FindAuthor, Get, KeyOwnerProofSystem, OnTimestampSet, - OneSessionHandler, GenesisBuild, + ConstU32, DisabledValidators, FindAuthor, GenesisBuild, Get, KeyOwnerProofSystem, + OnTimestampSet, OneSessionHandler, }, weights::{Pays, Weight}, BoundedVec, WeakBoundedVec, diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index 1d1ab71d9c694..a764c4e0238ff 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -170,8 +170,8 @@ use frame_support::{ tokens::{fungible, BalanceStatus as Status, DepositConsequence, WithdrawConsequence}, Currency, DefensiveSaturating, ExistenceRequirement, ExistenceRequirement::{AllowDeath, KeepAlive}, - Get, Imbalance, LockIdentifier, LockableCurrency, NamedReservableCurrency, OnUnbalanced, - ReservableCurrency, SignedImbalance, StoredMap, TryDrop, WithdrawReasons, GenesisBuild, + GenesisBuild, Get, Imbalance, LockIdentifier, LockableCurrency, NamedReservableCurrency, + OnUnbalanced, ReservableCurrency, SignedImbalance, StoredMap, TryDrop, WithdrawReasons, }, WeakBoundedVec, }; @@ -586,12 +586,8 @@ pub mod pallet { ) } - let mut endowed_accounts = self - .balances - .iter() - .map(|(x, _)| x) - .cloned() - .collect::>(); + let mut endowed_accounts = + self.balances.iter().map(|(x, _)| x).cloned().collect::>(); endowed_accounts.sort(); endowed_accounts.dedup(); diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index 7ab65813c6b42..a13fcd1eef11a 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -52,8 +52,8 @@ use frame_support::{ dispatch::{DispatchError, DispatchResultWithPostInfo, Dispatchable, PostDispatchInfo}, ensure, traits::{ - Backing, ChangeMembers, EnsureOrigin, Get, GetBacking, InitializeMembers, StorageVersion, - GenesisBuild, + Backing, ChangeMembers, EnsureOrigin, GenesisBuild, Get, GetBacking, InitializeMembers, + StorageVersion, }, weights::{GetDispatchInfo, Weight}, }; diff --git a/frame/contracts/rpc/src/lib.rs b/frame/contracts/rpc/src/lib.rs index 2ebac0c3451b9..f490b313621e5 100644 --- a/frame/contracts/rpc/src/lib.rs +++ b/frame/contracts/rpc/src/lib.rs @@ -212,8 +212,16 @@ where limit_gas(gas_limit)?; ContractsRuntimeApi::::call( - &api, &at, origin, dest, value, gas_limit, storage_deposit_limit, input_data.to_vec()) - .map_err(runtime_error_into_rpc_err) + &api, + &at, + origin, + dest, + value, + gas_limit, + storage_deposit_limit, + input_data.to_vec(), + ) + .map_err(runtime_error_into_rpc_err) } fn instantiate( @@ -285,10 +293,15 @@ where // If the block hash is not supplied assume the best block. self.client.info().best_hash)); - let result = ContractsRuntimeApi::::get_storage(&api, &at, address, key.into()) - .map_err(runtime_error_into_rpc_err)? - .map_err(ContractAccessError)? - .map(Bytes); + let result = ContractsRuntimeApi::::get_storage( + &api, + &at, + address, + key.into(), + ) + .map_err(runtime_error_into_rpc_err)? + .map_err(ContractAccessError)? + .map(Bytes); Ok(result) } diff --git a/frame/democracy/src/lib.rs b/frame/democracy/src/lib.rs index fbfd7aea54cf0..c4f1ad12a03e5 100644 --- a/frame/democracy/src/lib.rs +++ b/frame/democracy/src/lib.rs @@ -158,8 +158,8 @@ use frame_support::{ traits::{ defensive_prelude::*, schedule::{DispatchTime, Named as ScheduleNamed}, - BalanceStatus, Currency, Get, LockIdentifier, LockableCurrency, OnUnbalanced, - ReservableCurrency, WithdrawReasons, GenesisBuild, + BalanceStatus, Currency, GenesisBuild, Get, LockIdentifier, LockableCurrency, OnUnbalanced, + ReservableCurrency, WithdrawReasons, }, weights::Weight, }; diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index df7fcbbb151f9..6e48053465a06 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -103,8 +103,8 @@ use frame_support::{ dispatch::WithPostDispatchInfo, traits::{ defensive_prelude::*, ChangeMembers, Contains, ContainsLengthBound, Currency, - CurrencyToVote, Get, InitializeMembers, LockIdentifier, LockableCurrency, OnUnbalanced, - ReservableCurrency, SortedMembers, StorageVersion, WithdrawReasons, GenesisBuild, + CurrencyToVote, GenesisBuild, Get, InitializeMembers, LockIdentifier, LockableCurrency, + OnUnbalanced, ReservableCurrency, SortedMembers, StorageVersion, WithdrawReasons, }, weights::Weight, }; @@ -685,7 +685,10 @@ pub mod pallet { Members::::mutate(|members| { match members.binary_search_by(|m| m.who.cmp(member)) { Ok(_) => { - panic!("Duplicate member in elections-phragmen genesis: {:?}", member) + panic!( + "Duplicate member in elections-phragmen genesis: {:?}", + member + ) }, Err(pos) => members.insert( pos, diff --git a/frame/gilt/src/lib.rs b/frame/gilt/src/lib.rs index d07842d3bc677..d425e2e38a7d5 100644 --- a/frame/gilt/src/lib.rs +++ b/frame/gilt/src/lib.rs @@ -79,7 +79,7 @@ pub mod pallet { pub use crate::weights::WeightInfo; use frame_support::{ pallet_prelude::*, - traits::{Currency, DefensiveSaturating, OnUnbalanced, ReservableCurrency, GenesisBuild}, + traits::{Currency, DefensiveSaturating, GenesisBuild, OnUnbalanced, ReservableCurrency}, }; use frame_system::pallet_prelude::*; use sp_arithmetic::{PerThing, Perquintill}; diff --git a/frame/grandpa/src/lib.rs b/frame/grandpa/src/lib.rs index ac44e9e3f5442..d069f113cfb14 100644 --- a/frame/grandpa/src/lib.rs +++ b/frame/grandpa/src/lib.rs @@ -43,7 +43,7 @@ use frame_support::{ dispatch::DispatchResultWithPostInfo, pallet_prelude::Get, storage, - traits::{KeyOwnerProofSystem, OneSessionHandler, StorageVersion, GenesisBuild}, + traits::{GenesisBuild, KeyOwnerProofSystem, OneSessionHandler, StorageVersion}, weights::{Pays, Weight}, WeakBoundedVec, }; diff --git a/frame/im-online/src/lib.rs b/frame/im-online/src/lib.rs index 9bf396006dc57..ea2a54abe8f42 100644 --- a/frame/im-online/src/lib.rs +++ b/frame/im-online/src/lib.rs @@ -85,8 +85,8 @@ pub mod weights; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ traits::{ - EstimateNextSessionRotation, Get, OneSessionHandler, ValidatorSet, - ValidatorSetWithIdentification, WrapperOpaque, GenesisBuild, + EstimateNextSessionRotation, GenesisBuild, Get, OneSessionHandler, ValidatorSet, + ValidatorSetWithIdentification, WrapperOpaque, }, BoundedSlice, WeakBoundedVec, }; diff --git a/frame/indices/src/lib.rs b/frame/indices/src/lib.rs index b36056724b5e9..e7e16744f5845 100644 --- a/frame/indices/src/lib.rs +++ b/frame/indices/src/lib.rs @@ -26,7 +26,7 @@ mod tests; pub mod weights; use codec::Codec; -use frame_support::traits::{BalanceStatus::Reserved, Currency, ReservableCurrency, GenesisBuild}; +use frame_support::traits::{BalanceStatus::Reserved, Currency, GenesisBuild, ReservableCurrency}; use sp_runtime::{ traits::{AtLeast32Bit, LookupError, Saturating, StaticLookup, Zero}, MultiAddress, diff --git a/frame/membership/src/lib.rs b/frame/membership/src/lib.rs index b66215b93043c..e9247a6e401a5 100644 --- a/frame/membership/src/lib.rs +++ b/frame/membership/src/lib.rs @@ -24,7 +24,7 @@ #![cfg_attr(not(feature = "std"), no_std)] use frame_support::traits::{ - ChangeMembers, Contains, Get, InitializeMembers, SortedMembers, StorageVersion, GenesisBuild, + ChangeMembers, Contains, GenesisBuild, Get, InitializeMembers, SortedMembers, StorageVersion, }; use sp_std::prelude::*; diff --git a/frame/merkle-mountain-range/rpc/src/lib.rs b/frame/merkle-mountain-range/rpc/src/lib.rs index fcc8c98a75381..d3798cbb128dd 100644 --- a/frame/merkle-mountain-range/rpc/src/lib.rs +++ b/frame/merkle-mountain-range/rpc/src/lib.rs @@ -106,13 +106,13 @@ where self.client.info().best_hash); let (leaf, proof) = MmrRuntimeApi::::generate_proof_with_context( - &api, - &BlockId::hash(block_hash), - sp_core::ExecutionContext::OffchainCall(None), - leaf_index, - ) - .map_err(runtime_error_into_rpc_error)? - .map_err(mmr_error_into_rpc_error)?; + &api, + &BlockId::hash(block_hash), + sp_core::ExecutionContext::OffchainCall(None), + leaf_index, + ) + .map_err(runtime_error_into_rpc_error)? + .map_err(mmr_error_into_rpc_error)?; Ok(LeafProof::new(block_hash, leaf, proof)) } diff --git a/frame/session/src/lib.rs b/frame/session/src/lib.rs index cac8b4997ecdb..bccd07db96855 100644 --- a/frame/session/src/lib.rs +++ b/frame/session/src/lib.rs @@ -120,8 +120,8 @@ use frame_support::{ dispatch::{DispatchError, DispatchResult}, ensure, traits::{ - EstimateNextNewSession, EstimateNextSessionRotation, FindAuthor, Get, OneSessionHandler, - StorageVersion, ValidatorRegistration, ValidatorSet, GenesisBuild, + EstimateNextNewSession, EstimateNextSessionRotation, FindAuthor, GenesisBuild, Get, + OneSessionHandler, StorageVersion, ValidatorRegistration, ValidatorSet, }, weights::Weight, Parameter, diff --git a/frame/society/src/lib.rs b/frame/society/src/lib.rs index 0f62f18dc05d5..8f95d9cd9ccee 100644 --- a/frame/society/src/lib.rs +++ b/frame/society/src/lib.rs @@ -255,7 +255,7 @@ use frame_support::{ pallet_prelude::*, traits::{ BalanceStatus, ChangeMembers, Currency, EnsureOrigin, ExistenceRequirement::AllowDeath, - Imbalance, OnUnbalanced, Randomness, ReservableCurrency, GenesisBuild, + GenesisBuild, Imbalance, OnUnbalanced, Randomness, ReservableCurrency, }, PalletId, }; diff --git a/frame/staking/src/lib.rs b/frame/staking/src/lib.rs index 62e6b4199d1dc..2b174123cb602 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -300,13 +300,13 @@ pub mod weights; mod pallet; use codec::{Decode, Encode, HasCompact}; +#[cfg(feature = "std")] +use frame_support::traits::ConstU32; use frame_support::{ traits::{Currency, Get}, weights::Weight, BoundedVec, EqNoBound, PartialEqNoBound, RuntimeDebugNoBound, }; -#[cfg(feature = "std")] -use frame_support::traits::ConstU32; use scale_info::TypeInfo; use sp_runtime::{ curve::PiecewiseLinear, diff --git a/frame/staking/src/pallet/mod.rs b/frame/staking/src/pallet/mod.rs index 8a5c8c00385f3..0dc168f7cc30e 100644 --- a/frame/staking/src/pallet/mod.rs +++ b/frame/staking/src/pallet/mod.rs @@ -21,8 +21,8 @@ use frame_election_provider_support::SortedListProvider; use frame_support::{ pallet_prelude::*, traits::{ - Currency, CurrencyToVote, EnsureOrigin, EstimateNextNewSession, Get, LockIdentifier, - LockableCurrency, OnUnbalanced, UnixTime, GenesisBuild, + Currency, CurrencyToVote, EnsureOrigin, EstimateNextNewSession, GenesisBuild, Get, + LockIdentifier, LockableCurrency, OnUnbalanced, UnixTime, }, weights::Weight, }; diff --git a/frame/sudo/src/lib.rs b/frame/sudo/src/lib.rs index 551374fff6cdf..5764a341f2b31 100644 --- a/frame/sudo/src/lib.rs +++ b/frame/sudo/src/lib.rs @@ -95,7 +95,10 @@ use sp_runtime::{traits::StaticLookup, DispatchResult}; use sp_std::prelude::*; -use frame_support::{traits::{UnfilteredDispatchable, GenesisBuild}, weights::GetDispatchInfo}; +use frame_support::{ + traits::{GenesisBuild, UnfilteredDispatchable}, + weights::GetDispatchInfo, +}; #[cfg(test)] mod mock; diff --git a/frame/support/procedural/src/construct_runtime/expand/config.rs b/frame/support/procedural/src/construct_runtime/expand/config.rs index 1755647436671..415cd6ee7024e 100644 --- a/frame/support/procedural/src/construct_runtime/expand/config.rs +++ b/frame/support/procedural/src/construct_runtime/expand/config.rs @@ -50,7 +50,9 @@ pub fn expand_outer_config( decl, &field_name, )); - build_execute_calls.extend(quote!(#scrate::traits::GenesisBuild::<#runtime, _>::build(&self.#field_name);)); + build_execute_calls.extend( + quote!(#scrate::traits::GenesisBuild::<#runtime, _>::build(&self.#field_name);), + ); query_genesis_config_part_macros.push(quote! { #path::__substrate_genesis_config_check::is_genesis_config_defined!(#pallet_name); #[cfg(feature = "std")] diff --git a/frame/support/procedural/src/pallet/expand/genesis_config.rs b/frame/support/procedural/src/pallet/expand/genesis_config.rs index ec0fe82c288fd..b3b894b553bc4 100644 --- a/frame/support/procedural/src/pallet/expand/genesis_config.rs +++ b/frame/support/procedural/src/pallet/expand/genesis_config.rs @@ -97,12 +97,21 @@ pub fn expand_genesis_config(def: &mut Def) -> proc_macro2::TokenStream { attrs.push(syn::parse_quote!( #[cfg_attr(any(feature = "std", test), derive(#frame_support::Serialize, #frame_support::Deserialize))] )); - attrs.push(syn::parse_quote!( #[cfg_att(any(feature = "std", test), serde(rename_all = "camelCase"))] )); - attrs.push(syn::parse_quote!( #[cfg_att(any(feature = "std", test), serde(deny_unknown_fields))] )); - attrs.push(syn::parse_quote!( #[cfg_att(any(feature = "std", test), serde(bound(serialize = "")))] )); - attrs.push(syn::parse_quote!( #[cfg_att(any(feature = "std", test), serde(bound(deserialize = "")))] )); - attrs.push(syn::parse_quote!( #[cfg_att(any(feature = "std", test), serde(crate = #serde_crate))] )); - + attrs.push( + syn::parse_quote!( #[cfg_att(any(feature = "std", test), serde(rename_all = "camelCase"))] ), + ); + attrs.push( + syn::parse_quote!( #[cfg_att(any(feature = "std", test), serde(deny_unknown_fields))] ), + ); + attrs.push( + syn::parse_quote!( #[cfg_att(any(feature = "std", test), serde(bound(serialize = "")))] ), + ); + attrs.push( + syn::parse_quote!( #[cfg_att(any(feature = "std", test), serde(bound(deserialize = "")))] ), + ); + attrs.push( + syn::parse_quote!( #[cfg_att(any(feature = "std", test), serde(crate = #serde_crate))] ), + ); for a in attrs.iter_mut() { if let Some(mut segment) = a.path.segments.first_mut() { diff --git a/frame/support/src/traits.rs b/frame/support/src/traits.rs index 2bf74b102ca80..c68202164be80 100644 --- a/frame/support/src/traits.rs +++ b/frame/support/src/traits.rs @@ -72,9 +72,9 @@ pub use metadata::{ }; mod hooks; -pub use hooks::GenesisBuild; pub use hooks::{ - Hooks, OnFinalize, OnGenesis, OnIdle, OnInitialize, OnRuntimeUpgrade, OnTimestampSet, + GenesisBuild, Hooks, OnFinalize, OnGenesis, OnIdle, OnInitialize, OnRuntimeUpgrade, + OnTimestampSet, }; #[cfg(feature = "try-runtime")] pub use hooks::{OnRuntimeUpgradeHelpersExt, ON_RUNTIME_UPGRADE_PREFIX}; diff --git a/frame/support/test/src/lib.rs b/frame/support/test/src/lib.rs index 0b4f9d8773e2a..dd3fbd1f3020d 100644 --- a/frame/support/test/src/lib.rs +++ b/frame/support/test/src/lib.rs @@ -18,7 +18,6 @@ //! Test crate for frame_support. Allow to make use of `frame_support::decl_storage`. //! See tests directory. - // Make sure we fail compilation on warnings #![warn(missing_docs)] #![deny(warnings)] diff --git a/frame/transaction-payment/rpc/src/lib.rs b/frame/transaction-payment/rpc/src/lib.rs index 00040e3f13893..5b3613de6f4a9 100644 --- a/frame/transaction-payment/rpc/src/lib.rs +++ b/frame/transaction-payment/rpc/src/lib.rs @@ -21,9 +21,11 @@ pub use self::gen_client::Client as TransactionPaymentClient; use codec::{Codec, Decode}; use jsonrpc_core::{Error as RpcError, ErrorCode, Result}; use jsonrpc_derive::rpc; -pub use pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi as TransactionPaymentRuntimeApi; -pub use pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo as TransactionPaymentRuntimeDispatchInfo; use pallet_transaction_payment_rpc_runtime_api::{FeeDetails, InclusionFee, RuntimeDispatchInfo}; +pub use pallet_transaction_payment_rpc_runtime_api::{ + RuntimeDispatchInfo as TransactionPaymentRuntimeDispatchInfo, + TransactionPaymentApi as TransactionPaymentRuntimeApi, +}; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; use sp_core::Bytes; diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index e1d90d3d16280..3c8f9173d207d 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -64,7 +64,7 @@ use sp_std::prelude::*; use frame_support::{ dispatch::DispatchResult, - traits::{EstimateCallFee, Get, GenesisBuild}, + traits::{EstimateCallFee, GenesisBuild, Get}, weights::{ DispatchClass, DispatchInfo, GetDispatchInfo, Pays, PostDispatchInfo, Weight, WeightToFeeCoefficient, WeightToFeePolynomial, diff --git a/frame/transaction-storage/src/lib.rs b/frame/transaction-storage/src/lib.rs index c8dd660d92205..45f377ce94e9b 100644 --- a/frame/transaction-storage/src/lib.rs +++ b/frame/transaction-storage/src/lib.rs @@ -31,7 +31,7 @@ mod tests; use codec::{Decode, Encode}; use frame_support::{ dispatch::{Dispatchable, GetDispatchInfo}, - traits::{Currency, OnUnbalanced, ReservableCurrency, GenesisBuild}, + traits::{Currency, GenesisBuild, OnUnbalanced, ReservableCurrency}, }; use sp_runtime::traits::{BlakeTwo256, Hash, One, Saturating, Zero}; use sp_std::{prelude::*, result}; diff --git a/frame/treasury/src/lib.rs b/frame/treasury/src/lib.rs index 4b26601325b88..70f57d6103c70 100644 --- a/frame/treasury/src/lib.rs +++ b/frame/treasury/src/lib.rs @@ -74,8 +74,8 @@ use sp_std::prelude::*; use frame_support::{ print, traits::{ - Currency, ExistenceRequirement::KeepAlive, Get, Imbalance, OnUnbalanced, - ReservableCurrency, WithdrawReasons, GenesisBuild, + Currency, ExistenceRequirement::KeepAlive, GenesisBuild, Get, Imbalance, OnUnbalanced, + ReservableCurrency, WithdrawReasons, }, weights::Weight, PalletId, diff --git a/frame/vesting/src/lib.rs b/frame/vesting/src/lib.rs index 314162e05f2b1..7dc000e8bfa64 100644 --- a/frame/vesting/src/lib.rs +++ b/frame/vesting/src/lib.rs @@ -60,8 +60,8 @@ use frame_support::{ ensure, pallet_prelude::*, traits::{ - Currency, ExistenceRequirement, Get, LockIdentifier, LockableCurrency, VestingSchedule, - WithdrawReasons, GenesisBuild, + Currency, ExistenceRequirement, GenesisBuild, Get, LockIdentifier, LockableCurrency, + VestingSchedule, WithdrawReasons, }, }; use frame_system::{ensure_root, ensure_signed, pallet_prelude::*}; diff --git a/primitives/api/proc-macro/src/decl_runtime_apis.rs b/primitives/api/proc-macro/src/decl_runtime_apis.rs index 51d334958b06e..c7482f6d2da89 100644 --- a/primitives/api/proc-macro/src/decl_runtime_apis.rs +++ b/primitives/api/proc-macro/src/decl_runtime_apis.rs @@ -452,7 +452,7 @@ fn generate_runtime_api_call_impl(decl: &ItemTrait) -> Result { // Generate a native call generator for each function of the given trait. for (attrs, sig) in fns { if remove_supported_attributes(&mut attrs.clone()).contains_key(CHANGED_IN_ATTRIBUTE) { - continue; + continue } let fn_sig = &sig; @@ -931,7 +931,6 @@ fn generate_call_impl(decls: &[ItemTrait]) -> Result { quote! { #ident #colon_token #bounds } }); - let ty_generics = decl.generics.type_params().map(|t| { let ident = &t.ident; quote! { #ident } diff --git a/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs b/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs index d72c56bc1b8a8..ff77e78a651f9 100644 --- a/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs +++ b/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs @@ -18,7 +18,7 @@ use crate::utils::{ extract_block_type_from_trait_path, extract_impl_trait, extract_parameter_names_types_and_borrows, generate_crate_access, generate_hidden_includes, - generate_method_runtime_api_impl_name, return_type_extract_type, prefix_function_with_trait, + generate_method_runtime_api_impl_name, prefix_function_with_trait, return_type_extract_type, AllowSelfRefInParameters, RequireQualifiedTraitPath, }; diff --git a/primitives/api/src/lib.rs b/primitives/api/src/lib.rs index 2689787f01047..17d85a1622051 100644 --- a/primitives/api/src/lib.rs +++ b/primitives/api/src/lib.rs @@ -407,8 +407,7 @@ pub type StorageChanges = sp_state_machine::StorageChanges< /// Extract the state backend type for a type that implements `ProvideRuntimeApi`. #[cfg(feature = "std")] -pub type StateBackendFor = -

>::StateBackend; +pub type StateBackendFor =

>::StateBackend; /// Extract the state backend transaction type for a type that implements `ProvideRuntimeApi`. #[cfg(feature = "std")] @@ -527,7 +526,8 @@ pub struct RuntimeApi<'a, Block: BlockT, C: CallApiAt> { pub call: &'a C, pub commit_on_success: std::cell::RefCell, pub changes: std::cell::RefCell, - pub storage_transaction_cache: std::cell::RefCell>, + pub storage_transaction_cache: + std::cell::RefCell>, pub recorder: Option>, } @@ -535,10 +535,10 @@ pub struct RuntimeApi<'a, Block: BlockT, C: CallApiAt> { impl<'a, Block: BlockT, C: CallApiAt> ApiExt for RuntimeApi<'a, Block, C> { type StateBackend = C::StateBackend; - fn execute_in_transaction TransactionOutcome, R>( - &self, - call: F, - ) -> R where Self: Sized { + fn execute_in_transaction TransactionOutcome, R>(&self, call: F) -> R + where + Self: Sized, + { self.changes.borrow_mut().start_transaction(); *self.commit_on_success.borrow_mut() = false; let res = call(self); @@ -552,7 +552,10 @@ impl<'a, Block: BlockT, C: CallApiAt> ApiExt for RuntimeApi<'a, Bl fn has_api( &self, at: &BlockId, - ) -> std::result::Result where Self: Sized { + ) -> std::result::Result + where + Self: Sized, + { self.call .runtime_version_at(at) .map(|v| v.has_api_with(&A::ID, |v| v == A::VERSION)) @@ -562,19 +565,21 @@ impl<'a, Block: BlockT, C: CallApiAt> ApiExt for RuntimeApi<'a, Bl &self, at: &BlockId, pred: P, - ) -> std::result::Result where Self: Sized { - self.call - .runtime_version_at(at) - .map(|v| v.has_api_with(&A::ID, pred)) + ) -> std::result::Result + where + Self: Sized, + { + self.call.runtime_version_at(at).map(|v| v.has_api_with(&A::ID, pred)) } fn api_version( &self, at: &BlockId, - ) -> std::result::Result, ApiError> where Self: Sized { - self.call - .runtime_version_at(at) - .map(|v| v.api_version(&A::ID)) + ) -> std::result::Result, ApiError> + where + Self: Sized, + { + self.call.runtime_version_at(at).map(|v| v.api_version(&A::ID)) } fn record_proof(&mut self) { @@ -586,21 +591,20 @@ impl<'a, Block: BlockT, C: CallApiAt> ApiExt for RuntimeApi<'a, Bl } fn extract_proof(&mut self) -> Option { - self.recorder - .take() - .map(|recorder| recorder.to_storage_proof()) + self.recorder.take().map(|recorder| recorder.to_storage_proof()) } fn into_storage_changes( &self, backend: &Self::StateBackend, parent_hash: Block::Hash, - ) -> std::result::Result< - StorageChanges, - String - > where Self: Sized { + ) -> std::result::Result, String> + where + Self: Sized, + { let at = BlockId::Hash(parent_hash.clone()); - let state_version = self.call + let state_version = self + .call .runtime_version_at(&at) .map(|v| v.state_version()) .map_err(|e| format!("Failed to get state version: {}", e))?; @@ -616,9 +620,7 @@ impl<'a, Block: BlockT, C: CallApiAt> ApiExt for RuntimeApi<'a, Bl #[cfg(any(feature = "std", test))] impl<'a, Block: BlockT, C: CallApiAt> RuntimeApi<'a, Block, C> { - pub fn new( - call: &'a C, - ) -> Self { + pub fn new(call: &'a C) -> Self { RuntimeApi { call, commit_on_success: true.into(), @@ -644,12 +646,8 @@ impl<'a, Block: BlockT, C: CallApiAt> RuntimeApi<'a, Block, C> { if *self.commit_on_success.borrow() { self.changes.borrow_mut().start_transaction(); } - let res = call_api_at( - &self.call, - &self.changes, - &self.storage_transaction_cache, - &self.recorder, - ); + let res = + call_api_at(&self.call, &self.changes, &self.storage_transaction_cache, &self.recorder); self.commit_or_rollback(res.is_ok()); res diff --git a/primitives/api/test/tests/decl_and_impl.rs b/primitives/api/test/tests/decl_and_impl.rs index f1a84258d270c..bff3d1235eefa 100644 --- a/primitives/api/test/tests/decl_and_impl.rs +++ b/primitives/api/test/tests/decl_and_impl.rs @@ -16,7 +16,7 @@ // limitations under the License. use sp_api::{ - decl_runtime_apis, impl_runtime_apis, mock_impl_runtime_apis, ApiError, RuntimeApiInfo, ApiExt, + decl_runtime_apis, impl_runtime_apis, mock_impl_runtime_apis, ApiError, ApiExt, RuntimeApiInfo, }; use sp_core::NativeOrEncoded; use sp_runtime::{ @@ -135,10 +135,8 @@ mock_impl_runtime_apis! { } } -type TestClient = substrate_test_runtime_client::client::Client< - substrate_test_runtime_client::Backend, - Block, ->; +type TestClient = + substrate_test_runtime_client::client::Client; #[test] fn test_client_side_function_signature() { diff --git a/primitives/consensus/common/src/lib.rs b/primitives/consensus/common/src/lib.rs index 48e7906e0a380..4324f376d9c8d 100644 --- a/primitives/consensus/common/src/lib.rs +++ b/primitives/consensus/common/src/lib.rs @@ -294,8 +294,8 @@ impl CanAuthorWithVersion { } } -impl, Block: BlockT> - CanAuthorWith for CanAuthorWithVersion +impl, Block: BlockT> CanAuthorWith + for CanAuthorWithVersion { fn can_author_with(&self, at: &BlockId) -> Result<(), String> { match self.0.runtime_version(at) { diff --git a/primitives/core/src/crypto.rs b/primitives/core/src/crypto.rs index 7c2812fbdf1c9..3edc39f33aef0 100644 --- a/primitives/core/src/crypto.rs +++ b/primitives/core/src/crypto.rs @@ -1125,37 +1125,65 @@ pub mod key_types { /// Public keys commonly used for development and testing. pub mod dev_keys { - use crate::{sr25519, ed25519}; + use crate::{ed25519, sr25519}; /// //Alice - pub const ALICE_SR25519: sr25519::Public = sr25519::Public(hex_literal::hex!["d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"]); + pub const ALICE_SR25519: sr25519::Public = sr25519::Public(hex_literal::hex![ + "d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d" + ]); /// //Alice - pub const ALICE_ED25519: ed25519::Public = ed25519::Public(hex_literal::hex!["88dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee"]); + pub const ALICE_ED25519: ed25519::Public = ed25519::Public(hex_literal::hex![ + "88dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee" + ]); /// //Bob - pub const BOB_SR25519: sr25519::Public = sr25519::Public(hex_literal::hex!["8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48"]); + pub const BOB_SR25519: sr25519::Public = sr25519::Public(hex_literal::hex![ + "8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48" + ]); /// //Bob - pub const BOB_ED25519: ed25519::Public = ed25519::Public(hex_literal::hex!["d17c2d7823ebf260fd138f2d7e27d114c0145d968b5ff5006125f2414fadae69"]); + pub const BOB_ED25519: ed25519::Public = ed25519::Public(hex_literal::hex![ + "d17c2d7823ebf260fd138f2d7e27d114c0145d968b5ff5006125f2414fadae69" + ]); /// //Charlie - pub const CHARLIE_SR25519: sr25519::Public = sr25519::Public(hex_literal::hex!["90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22"]); + pub const CHARLIE_SR25519: sr25519::Public = sr25519::Public(hex_literal::hex![ + "90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22" + ]); /// //Dave - pub const DAVE_SR25519: sr25519::Public = sr25519::Public(hex_literal::hex!["306721211d5404bd9da88e0204360a1a9ab8b87c66c1bc2fcdd37f3c2222cc20"]); + pub const DAVE_SR25519: sr25519::Public = sr25519::Public(hex_literal::hex![ + "306721211d5404bd9da88e0204360a1a9ab8b87c66c1bc2fcdd37f3c2222cc20" + ]); /// //Eve - pub const EVE_SR25519: sr25519::Public = sr25519::Public(hex_literal::hex!["e659a7a1628cdd93febc04a4e0646ea20e9f5f0ce097d9a05290d4a9e054df4e"]); + pub const EVE_SR25519: sr25519::Public = sr25519::Public(hex_literal::hex![ + "e659a7a1628cdd93febc04a4e0646ea20e9f5f0ce097d9a05290d4a9e054df4e" + ]); /// //Ferdie - pub const FERDIE_SR25519: sr25519::Public = sr25519::Public(hex_literal::hex!["1cbd2d43530a44705ad088af313e18f80b53ef16b36177cd4b77b846f2a5f07c"]); + pub const FERDIE_SR25519: sr25519::Public = sr25519::Public(hex_literal::hex![ + "1cbd2d43530a44705ad088af313e18f80b53ef16b36177cd4b77b846f2a5f07c" + ]); /// //Alice//stash - pub const ALICE_STASH: sr25519::Public = sr25519::Public(hex_literal::hex!["be5ddb1579b72e84524fc29e78609e3caf42e85aa118ebfe0b0ad404b5bdd25f"]); + pub const ALICE_STASH: sr25519::Public = sr25519::Public(hex_literal::hex![ + "be5ddb1579b72e84524fc29e78609e3caf42e85aa118ebfe0b0ad404b5bdd25f" + ]); /// //Bob//stash - pub const BOB_STASH: sr25519::Public = sr25519::Public(hex_literal::hex!["fe65717dad0447d715f660a0a58411de509b42e6efb8375f562f58a554d5860e"]); + pub const BOB_STASH: sr25519::Public = sr25519::Public(hex_literal::hex![ + "fe65717dad0447d715f660a0a58411de509b42e6efb8375f562f58a554d5860e" + ]); /// //Charlie//stash - pub const CHARLIE_STASH: sr25519::Public = sr25519::Public(hex_literal::hex!["1e07379407fecc4b89eb7dbd287c2c781cfb1907a96947a3eb18e4f8e7198625"]); + pub const CHARLIE_STASH: sr25519::Public = sr25519::Public(hex_literal::hex![ + "1e07379407fecc4b89eb7dbd287c2c781cfb1907a96947a3eb18e4f8e7198625" + ]); /// //Dave//stash - pub const DAVE_STASH: sr25519::Public = sr25519::Public(hex_literal::hex!["e860f1b1c7227f7c22602f53f15af80747814dffd839719731ee3bba6edc126c"]); + pub const DAVE_STASH: sr25519::Public = sr25519::Public(hex_literal::hex![ + "e860f1b1c7227f7c22602f53f15af80747814dffd839719731ee3bba6edc126c" + ]); /// //Eve//stash - pub const EVE_STASH: sr25519::Public = sr25519::Public(hex_literal::hex!["8ac59e11963af19174d0b94d5d78041c233f55d2e19324665bafdfb62925af2d"]); + pub const EVE_STASH: sr25519::Public = sr25519::Public(hex_literal::hex![ + "8ac59e11963af19174d0b94d5d78041c233f55d2e19324665bafdfb62925af2d" + ]); /// //Ferdie//stash - pub const FERDIE_STASH: sr25519::Public = sr25519::Public(hex_literal::hex!["101191192fc877c24d725b337120fa3edc63d227bbc92705db1e2cb65f56981a"]); + pub const FERDIE_STASH: sr25519::Public = sr25519::Public(hex_literal::hex![ + "101191192fc877c24d725b337120fa3edc63d227bbc92705db1e2cb65f56981a" + ]); } #[cfg(test)] diff --git a/primitives/runtime-interface/test/src/lib.rs b/primitives/runtime-interface/test/src/lib.rs index 5b3a67367d2f6..11bdc3410570e 100644 --- a/primitives/runtime-interface/test/src/lib.rs +++ b/primitives/runtime-interface/test/src/lib.rs @@ -24,7 +24,7 @@ use sp_runtime_interface_test_wasm::{test_api::HostFunctions, wasm_binary_unwrap use sp_runtime_interface_test_wasm_deprecated::wasm_binary_unwrap as wasm_binary_deprecated_unwrap; use sc_executor_common::runtime_blob::RuntimeBlob; -use sp_wasm_interface::{HostFunctions as HostFunctionsT}; +use sp_wasm_interface::HostFunctions as HostFunctionsT; use std::{ collections::HashSet, @@ -41,7 +41,11 @@ fn call_wasm_method_with_result( let mut ext_ext = ext.ext(); let executor = sc_executor::WasmExecutor::new_extended::( - sc_executor::WasmExecutionMethod::Interpreted, Some(8), 8, None, 2 + sc_executor::WasmExecutionMethod::Interpreted, + Some(8), + 8, + None, + 2, ); executor diff --git a/primitives/state-machine/src/lib.rs b/primitives/state-machine/src/lib.rs index 29d114dae5efd..068ec997c3141 100644 --- a/primitives/state-machine/src/lib.rs +++ b/primitives/state-machine/src/lib.rs @@ -471,7 +471,8 @@ mod execution { let (wasm_result, _) = self.execute_aux(false, native_call); if (result.is_ok() && - wasm_result.is_ok() && result.as_ref().unwrap().as_encoded() == wasm_result.as_ref().unwrap().as_encoded()) || + wasm_result.is_ok() && result.as_ref().unwrap().as_encoded() == + wasm_result.as_ref().unwrap().as_encoded()) || result.is_err() && wasm_result.is_err() { result diff --git a/test-utils/client/src/lib.rs b/test-utils/client/src/lib.rs index 922e0ced72073..565849262354d 100644 --- a/test-utils/client/src/lib.rs +++ b/test-utils/client/src/lib.rs @@ -79,17 +79,13 @@ pub struct TestClientBuilder { no_genesis: bool, } -impl Default - for TestClientBuilder, G> -{ +impl Default for TestClientBuilder, G> { fn default() -> Self { Self::with_default_backend() } } -impl - TestClientBuilder, G> -{ +impl TestClientBuilder, G> { /// Create new `TestClientBuilder` with default backend. pub fn with_default_backend() -> Self { let backend = Arc::new(Backend::new_test(std::u32::MAX, std::u64::MAX)); @@ -113,9 +109,7 @@ impl } } -impl - TestClientBuilder -{ +impl TestClientBuilder { /// Create a new instance of the test client builder. pub fn with_backend(backend: Arc) -> Self { TestClientBuilder { @@ -201,10 +195,7 @@ impl pub fn build_with_executor( self, executor: LocalCallExecutor, - ) -> ( - client::Client, - sc_consensus::LongestChain, - ) + ) -> (client::Client, sc_consensus::LongestChain) where Backend: sc_client_api::backend::Backend, >::OffchainStorage: 'static, @@ -252,24 +243,12 @@ impl } } -impl - TestClientBuilder< - Block, - Backend, - G, - > where -{ +impl TestClientBuilder { /// Build the test client with the given native executor. pub fn build_with_wasm_executor( self, executor: I, - ) -> ( - client::Client< - Backend, - Block, - >, - sc_consensus::LongestChain, - ) + ) -> (client::Client, sc_consensus::LongestChain) where I: Into>, Backend: sc_client_api::backend::Backend + 'static, diff --git a/test-utils/runtime/client/src/block_builder_ext.rs b/test-utils/runtime/client/src/block_builder_ext.rs index 34338d03c06ca..d47f75f067251 100644 --- a/test-utils/runtime/client/src/block_builder_ext.rs +++ b/test-utils/runtime/client/src/block_builder_ext.rs @@ -38,7 +38,7 @@ pub trait BlockBuilderExt { impl<'a, A, B> BlockBuilderExt for sc_block_builder::BlockBuilder<'a, substrate_test_runtime::Block, A, B> where - A: CallApiAt + 'a, + A: CallApiAt + 'a, B: backend::Backend, { fn push_transfer( diff --git a/test-utils/runtime/client/src/lib.rs b/test-utils/runtime/client/src/lib.rs index 71b82bd247ef1..cd59d3fdfcbad 100644 --- a/test-utils/runtime/client/src/lib.rs +++ b/test-utils/runtime/client/src/lib.rs @@ -47,8 +47,8 @@ pub mod prelude { }; // Client structs pub use super::{ - Backend, LocalExecutorDispatch, NativeElseWasmExecutor, TestClient, - TestClientBuilder, WasmExecutionMethod, + Backend, LocalExecutorDispatch, NativeElseWasmExecutor, TestClient, TestClientBuilder, + WasmExecutionMethod, }; // Keyring pub use super::{AccountKeyring, Sr25519Keyring}; @@ -73,7 +73,6 @@ impl sc_executor::NativeExecutionDispatch for LocalExecutorDispatch { /// Test client database backend. pub type Backend = substrate_test_client::Backend; - /// Parameters of test-client builder with test-runtime. #[derive(Default)] pub struct GenesisParameters { @@ -150,17 +149,11 @@ impl substrate_test_client::GenesisInit for GenesisParameters { } /// A `TestClient` with `test-runtime` builder. -pub type TestClientBuilder = substrate_test_client::TestClientBuilder< - substrate_test_runtime::Block, - B, - GenesisParameters, ->; +pub type TestClientBuilder = + substrate_test_client::TestClientBuilder; /// Test client type with `LocalExecutorDispatch` and generic Backend. -pub type Client = client::Client< - B, - substrate_test_runtime::Block, ->; +pub type Client = client::Client; /// A test client with default backend. pub type TestClient = Client; @@ -242,8 +235,8 @@ pub trait TestClientBuilderExt: Sized { fn build_with_backend(self) -> (Client, Arc); } -impl TestClientBuilderExt - for TestClientBuilder where +impl TestClientBuilderExt for TestClientBuilder +where B: sc_client_api::backend::Backend + 'static, { fn genesis_init_mut(&mut self) -> &mut GenesisParameters { diff --git a/utils/frame/benchmarking-cli/src/command.rs b/utils/frame/benchmarking-cli/src/command.rs index 116cdc904dd66..42a68ec3c7c0b 100644 --- a/utils/frame/benchmarking-cli/src/command.rs +++ b/utils/frame/benchmarking-cli/src/command.rs @@ -26,7 +26,7 @@ use linked_hash_map::LinkedHashMap; use sc_cli::{CliConfiguration, ExecutionStrategy, Result, SharedParams}; use sc_client_db::BenchmarkingState; use sc_executor::WasmExecutor; -use sc_service::{Configuration}; +use sc_service::Configuration; use sp_core::offchain::{ testing::{TestOffchainExt, TestTransactionPoolExt}, OffchainDbExt, OffchainWorkerExt, TransactionPoolExt, @@ -133,7 +133,7 @@ impl BenchmarkCmd { )?; let state_without_tracking = BenchmarkingState::::new(genesis_storage, cache_size, self.record_proof, false)?; - let executor = WasmExecutor::new_default( + let executor = WasmExecutor::new_extended::( wasm_method, self.heap_pages, 2, // The runtime instances cache size. diff --git a/utils/frame/rpc/system/src/lib.rs b/utils/frame/rpc/system/src/lib.rs index 41aff5b1846dc..4d6d62444445e 100644 --- a/utils/frame/rpc/system/src/lib.rs +++ b/utils/frame/rpc/system/src/lib.rs @@ -197,7 +197,10 @@ mod tests { transaction_validity::{InvalidTransaction, TransactionValidityError}, ApplyExtrinsicResult, }; - use substrate_test_runtime_client::{runtime::{AccountId, Transfer, Index}, AccountKeyring}; + use substrate_test_runtime_client::{ + runtime::{AccountId, Index, Transfer}, + AccountKeyring, + }; #[test] fn should_return_next_nonce_for_some_account() { @@ -228,7 +231,8 @@ mod tests { let accounts = FullSystem::new(client, pool, DenyUnsafe::Yes); // when - let nonce = SystemApi::<_, AccountId, Index>::nonce(&accounts, AccountKeyring::Alice.into()); + let nonce = + SystemApi::<_, AccountId, Index>::nonce(&accounts, AccountKeyring::Alice.into()); // then assert_eq!(block_on(nonce).unwrap() as Index, 2); From 9744eabc2990170338d9865349b5520df419d5f2 Mon Sep 17 00:00:00 2001 From: arkpar Date: Thu, 24 Feb 2022 11:35:32 +0100 Subject: [PATCH 14/14] Cleanup --- client/service/src/builder.rs | 4 ---- .../src/pallet/expand/genesis_config.rs | 18 +++++------------- frame/support/src/traits/hooks.rs | 10 ++-------- .../api/proc-macro/src/decl_runtime_apis.rs | 6 +----- 4 files changed, 8 insertions(+), 30 deletions(-) diff --git a/client/service/src/builder.rs b/client/service/src/builder.rs index 2f8c9a289578e..c439db4e00462 100644 --- a/client/service/src/builder.rs +++ b/client/service/src/builder.rs @@ -130,10 +130,6 @@ pub type TFullClient = Client, TBl>; /// Full client backend type. pub type TFullBackend = sc_client_db::Backend; -/// Full client call executor type. -//pub type TFullCallExecutor = -// crate::client::LocalCallExecutor, TExec>; - type TFullParts = (TFullClient, Arc>, KeystoreContainer, TaskManager); trait AsCryptoStoreRef { diff --git a/frame/support/procedural/src/pallet/expand/genesis_config.rs b/frame/support/procedural/src/pallet/expand/genesis_config.rs index b3b894b553bc4..018f1e70c29bf 100644 --- a/frame/support/procedural/src/pallet/expand/genesis_config.rs +++ b/frame/support/procedural/src/pallet/expand/genesis_config.rs @@ -98,28 +98,20 @@ pub fn expand_genesis_config(def: &mut Def) -> proc_macro2::TokenStream { #[cfg_attr(any(feature = "std", test), derive(#frame_support::Serialize, #frame_support::Deserialize))] )); attrs.push( - syn::parse_quote!( #[cfg_att(any(feature = "std", test), serde(rename_all = "camelCase"))] ), + syn::parse_quote!( #[cfg_attr(any(feature = "std", test), serde(rename_all = "camelCase"))] ), ); attrs.push( - syn::parse_quote!( #[cfg_att(any(feature = "std", test), serde(deny_unknown_fields))] ), + syn::parse_quote!( #[cfg_attr(any(feature = "std", test), serde(deny_unknown_fields))] ), ); attrs.push( - syn::parse_quote!( #[cfg_att(any(feature = "std", test), serde(bound(serialize = "")))] ), + syn::parse_quote!( #[cfg_attr(any(feature = "std", test), serde(bound(serialize = "")))] ), ); attrs.push( - syn::parse_quote!( #[cfg_att(any(feature = "std", test), serde(bound(deserialize = "")))] ), + syn::parse_quote!( #[cfg_attr(any(feature = "std", test), serde(bound(deserialize = "")))] ), ); attrs.push( - syn::parse_quote!( #[cfg_att(any(feature = "std", test), serde(crate = #serde_crate))] ), + syn::parse_quote!( #[cfg_attr(any(feature = "std", test), serde(crate = #serde_crate))] ), ); - - for a in attrs.iter_mut() { - if let Some(mut segment) = a.path.segments.first_mut() { - if segment.ident == "cfg_att" { - segment.ident = Ident::new("cfg_attr", segment.ident.span()); - } - } - } }, _ => unreachable!("Checked by genesis_config parser"), } diff --git a/frame/support/src/traits/hooks.rs b/frame/support/src/traits/hooks.rs index 03c142629825f..19523ee83e84f 100644 --- a/frame/support/src/traits/hooks.rs +++ b/frame/support/src/traits/hooks.rs @@ -298,13 +298,13 @@ pub trait Hooks { /// A trait to define the build function of a genesis config, T and I are placeholder for pallet /// trait and pallet instance. -#[cfg(feature = "std")] pub trait GenesisBuild: Default + sp_runtime::traits::MaybeSerializeDeserialize { /// The build function is called within an externalities allowing storage APIs. /// Thus one can write to storage using regular pallet storages. fn build(&self); /// Build the storage using `build` inside default storage. + #[cfg(feature = "std")] fn build_storage(&self) -> Result { let mut storage = Default::default(); self.assimilate_storage(&mut storage)?; @@ -312,6 +312,7 @@ pub trait GenesisBuild: Default + sp_runtime::traits::MaybeSerializeD } /// Assimilate the storage for this module into pre-existing overlays. + #[cfg(feature = "std")] fn assimilate_storage(&self, storage: &mut sp_runtime::Storage) -> Result<(), String> { sp_state_machine::BasicExternalities::execute_with_storage(storage, || { self.build(); @@ -320,13 +321,6 @@ pub trait GenesisBuild: Default + sp_runtime::traits::MaybeSerializeD } } -#[cfg(not(feature = "std"))] -pub trait GenesisBuild: Default { - /// The build function is called within an externalities allowing storage APIs. - /// Thus one can write to storage using regular pallet storages. - fn build(&self); -} - /// A trait which is called when the timestamp is set in the runtime. #[impl_for_tuples(30)] pub trait OnTimestampSet { diff --git a/primitives/api/proc-macro/src/decl_runtime_apis.rs b/primitives/api/proc-macro/src/decl_runtime_apis.rs index c7482f6d2da89..ac008a27bac98 100644 --- a/primitives/api/proc-macro/src/decl_runtime_apis.rs +++ b/primitives/api/proc-macro/src/decl_runtime_apis.rs @@ -772,11 +772,7 @@ impl<'a> Fold for ToClientSideDecl<'a> { let is_core_trait = self.found_attributes.contains_key(CORE_TRAIT_ATTRIBUTE); let block_ident = Ident::new(BLOCK_GENERIC_IDENT, Span::call_site()); - if is_core_trait { - // Add all the supertraits we want to have for `Core`. - //input.supertraits = parse_quote!('static + Send + Sync); - input.supertraits = parse_quote!(); - } else { + if !is_core_trait { // Add the `Core` runtime api as super trait. let crate_ = &self.crate_; input.supertraits.push(parse_quote!( #crate_::Core<#block_ident> ));