diff --git a/substrate/Cargo.lock b/substrate/Cargo.lock index c921244587..679fa8d59a 100644 --- a/substrate/Cargo.lock +++ b/substrate/Cargo.lock @@ -6076,6 +6076,7 @@ dependencies = [ name = "sp-application-crypto-test" version = "2.0.0" dependencies = [ + "sp-application-crypto 2.0.0", "sp-core 2.0.0", "sp-runtime 2.0.0", "substrate-test-runtime-client 2.0.0", diff --git a/substrate/bin/node-template/Cargo.toml b/substrate/bin/node-template/Cargo.toml index 966c03549f..01a7840993 100644 --- a/substrate/bin/node-template/Cargo.toml +++ b/substrate/bin/node-template/Cargo.toml @@ -20,22 +20,22 @@ codec = { package = "parity-scale-codec", version = "1.0.0" } trie-root = "0.15.2" sp-io = { path = "../../primitives/io" } sc-cli = { path = "../../client/cli" } -primitives = { package = "sp-core", path = "../../primitives/core" } +sp-core = { path = "../../primitives/core" } sc-executor = { path = "../../client/executor" } sc-service = { path = "../../client/service" } -inherents = { package = "sp-inherents", path = "../../primitives/inherents" } -txpool = { package = "sc-transaction-pool", path = "../../client/transaction-pool" } -txpool-api = { package = "sp-transaction-pool", path = "../../primitives/transaction-pool" } -network = { package = "sc-network", path = "../../client/network" } -aura = { package = "sc-consensus-aura", path = "../../client/consensus/aura" } -aura-primitives = { package = "sp-consensus-aura", path = "../../primitives/consensus/aura" } -consensus-common = { package = "sp-consensus", path = "../../primitives/consensus/common" } +sp-inherents = { path = "../../primitives/inherents" } +sc-transaction-pool = { path = "../../client/transaction-pool" } +sp-transaction-pool = { path = "../../primitives/transaction-pool" } +sc-network = { path = "../../client/network" } +sc-consensus-aura = { path = "../../client/consensus/aura" } +sp-consensus-aura = { path = "../../primitives/consensus/aura" } +sp-consensus = { path = "../../primitives/consensus/common" } grandpa = { package = "sc-finality-grandpa", path = "../../client/finality-grandpa" } grandpa-primitives = { package = "sp-finality-grandpa", path = "../../primitives/finality-grandpa" } sc-client = { path = "../../client/" } -runtime = { package = "node-template-runtime", path = "runtime" } +node-template-runtime = { path = "runtime" } sp-runtime = { path = "../../primitives/runtime" } -basic-authorship = { package = "sc-basic-authority", path = "../../client/basic-authorship"} +sc-basic-authority = { path = "../../client/basic-authorship"} [build-dependencies] vergen = "3.0.4" diff --git a/substrate/bin/node-template/runtime/Cargo.toml b/substrate/bin/node-template/runtime/Cargo.toml index c1c30d3adc..398cf2ddb6 100644 --- a/substrate/bin/node-template/runtime/Cargo.toml +++ b/substrate/bin/node-template/runtime/Cargo.toml @@ -6,31 +6,32 @@ edition = "2018" [dependencies] aura = { package = "pallet-aura", path = "../../../frame/aura", default-features = false } -aura-primitives = { package = "sp-consensus-aura", path = "../../../primitives/consensus/aura", default-features = false } balances = { package = "pallet-balances", path = "../../../frame/balances", default-features = false } -block-builder-api = { package = "sp-block-builder", path = "../../../primitives/block-builder", default-features = false} -codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } -executive = { package = "frame-executive", path = "../../../frame/executive", default-features = false } +frame-support = { path = "../../../frame/support", default-features = false } grandpa = { package = "pallet-grandpa", path = "../../../frame/grandpa", default-features = false } indices = { package = "pallet-indices", path = "../../../frame/indices", default-features = false } -inherents = { package = "sp-inherents", path = "../../../primitives/inherents", default-features = false} -offchain-primitives = { package = "sp-offchain", path = "../../../primitives/offchain", default-features = false } -primitives = { package = "sp-core", path = "../../../primitives/core", default-features = false } randomness-collective-flip = { package = "pallet-randomness-collective-flip", path = "../../../frame/randomness-collective-flip", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } -sp-io = { path = "../../../primitives/io", default-features = false } -safe-mix = { version = "1.0.0", default-features = false } -serde = { version = "1.0.101", optional = true, features = ["derive"] } -sp-api = { path = "../../../primitives/api", default-features = false } -sp-runtime = { path = "../../../primitives/runtime", default-features = false } -sp-session = { path = "../../../primitives/session", default-features = false } sudo = { package = "pallet-sudo", path = "../../../frame/sudo", default-features = false } -support = { package = "frame-support", path = "../../../frame/support", default-features = false } system = { package = "frame-system", path = "../../../frame/system", default-features = false } timestamp = { package = "pallet-timestamp", path = "../../../frame/timestamp", default-features = false } transaction-payment = { package = "pallet-transaction-payment", path = "../../../frame/transaction-payment", default-features = false } -sp-transaction-pool = { package = "sp-transaction-pool", path = "../../../primitives/transaction-pool", default-features = false } -version = { package = "sp-version", path = "../../../primitives/version", default-features = false } + +codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } +frame-executive = { path = "../../../frame/executive", default-features = false } +safe-mix = { version = "1.0.0", default-features = false } +serde = { version = "1.0.101", optional = true, features = ["derive"] } +sp-api = { path = "../../../primitives/api", default-features = false } +sp-block-builder = { path = "../../../primitives/block-builder", default-features = false} +sp-consensus-aura = { path = "../../../primitives/consensus/aura", default-features = false } +sp-core = { path = "../../../primitives/core", default-features = false } +sp-inherents = { path = "../../../primitives/inherents", default-features = false} +sp-io = { path = "../../../primitives/io", default-features = false } +sp-offchain = { path = "../../../primitives/offchain", default-features = false } +sp-runtime = { path = "../../../primitives/runtime", default-features = false } +sp-session = { path = "../../../primitives/session", default-features = false } +sp-std = { path = "../../../primitives/std", default-features = false } +sp-transaction-pool = { path = "../../../primitives/transaction-pool", default-features = false } +sp-version = { path = "../../../primitives/version", default-features = false } [build-dependencies] wasm-builder-runner = { package = "substrate-wasm-builder-runner", path = "../../../utils/wasm-builder-runner", version = "1.0.4" } @@ -38,30 +39,30 @@ wasm-builder-runner = { package = "substrate-wasm-builder-runner", path = "../.. [features] default = ["std"] std = [ - "aura-primitives/std", "aura/std", "balances/std", - "block-builder-api/std", "codec/std", - "executive/std", + "frame-executive/std", + "frame-support/std", "grandpa/std", "indices/std", - "inherents/std", - "offchain-primitives/std", - "primitives/std", "randomness-collective-flip/std", - "sp-std/std", - "sp-io/std", "safe-mix/std", "serde", "sp-api/std", + "sp-block-builder/std", + "sp-consensus-aura/std", + "sp-core/std", + "sp-inherents/std", + "sp-io/std", + "sp-offchain/std", "sp-runtime/std", "sp-session/std", + "sp-std/std", + "sp-transaction-pool/std", + "sp-version/std", "sudo/std", - "support/std", "system/std", "timestamp/std", "transaction-payment/std", - "sp-transaction-pool/std", - "version/std", ] diff --git a/substrate/bin/node-template/runtime/src/lib.rs b/substrate/bin/node-template/runtime/src/lib.rs index 7abe43c066..04f9d03363 100644 --- a/substrate/bin/node-template/runtime/src/lib.rs +++ b/substrate/bin/node-template/runtime/src/lib.rs @@ -9,7 +9,7 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); use sp_std::prelude::*; -use primitives::OpaqueMetadata; +use sp_core::OpaqueMetadata; use sp_runtime::{ ApplyExtrinsicResult, transaction_validity::TransactionValidity, generic, create_runtime_str, impl_opaque_keys, MultiSignature @@ -18,12 +18,12 @@ use sp_runtime::traits::{ NumberFor, BlakeTwo256, Block as BlockT, StaticLookup, Verify, ConvertInto, IdentifyAccount }; use sp_api::impl_runtime_apis; -use aura_primitives::sr25519::AuthorityId as AuraId; +use sp_consensus_aura::sr25519::AuthorityId as AuraId; use grandpa::AuthorityList as GrandpaAuthorityList; use grandpa::fg_primitives; -use version::RuntimeVersion; +use sp_version::RuntimeVersion; #[cfg(feature = "std")] -use version::NativeVersion; +use sp_version::NativeVersion; // A few exports that help ease life for downstream crates. #[cfg(any(feature = "std", test))] @@ -31,7 +31,7 @@ pub use sp_runtime::BuildStorage; pub use timestamp::Call as TimestampCall; pub use balances::Call as BalancesCall; pub use sp_runtime::{Permill, Perbill}; -pub use support::{ +pub use frame_support::{ StorageValue, construct_runtime, parameter_types, traits::Randomness, weights::Weight, @@ -58,7 +58,7 @@ pub type Balance = u128; pub type Index = u32; /// A hash of some data used by the chain. -pub type Hash = primitives::H256; +pub type Hash = sp_core::H256; /// Digest item type. pub type DigestItem = generic::DigestItem; @@ -280,7 +280,7 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; /// Executive: handles dispatch to the various modules. -pub type Executive = executive::Executive, Runtime, AllModules>; +pub type Executive = frame_executive::Executive, Runtime, AllModules>; impl_runtime_apis! { impl sp_api::Core for Runtime { @@ -303,7 +303,7 @@ impl_runtime_apis! { } } - impl block_builder_api::BlockBuilder for Runtime { + impl sp_block_builder::BlockBuilder for Runtime { fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { Executive::apply_extrinsic(extrinsic) } @@ -312,14 +312,14 @@ impl_runtime_apis! { Executive::finalize_block() } - fn inherent_extrinsics(data: inherents::InherentData) -> Vec<::Extrinsic> { + fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { data.create_extrinsics() } fn check_inherents( block: Block, - data: inherents::InherentData, - ) -> inherents::CheckInherentsResult { + data: sp_inherents::InherentData, + ) -> sp_inherents::CheckInherentsResult { data.check_extrinsics(&block) } @@ -334,13 +334,13 @@ impl_runtime_apis! { } } - impl offchain_primitives::OffchainWorkerApi for Runtime { + impl sp_offchain::OffchainWorkerApi for Runtime { fn offchain_worker(number: NumberFor) { Executive::offchain_worker(number) } } - impl aura_primitives::AuraApi for Runtime { + impl sp_consensus_aura::AuraApi for Runtime { fn slot_duration() -> u64 { Aura::slot_duration() } diff --git a/substrate/bin/node-template/runtime/src/template.rs b/substrate/bin/node-template/runtime/src/template.rs index 231f9b9a2b..b800eae70c 100644 --- a/substrate/bin/node-template/runtime/src/template.rs +++ b/substrate/bin/node-template/runtime/src/template.rs @@ -8,7 +8,7 @@ /// For more guidance on Substrate modules, see the example module /// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs -use support::{decl_module, decl_storage, decl_event, dispatch}; +use frame_support::{decl_module, decl_storage, decl_event, dispatch}; use system::ensure_signed; /// The module's configuration trait. @@ -69,8 +69,8 @@ decl_event!( mod tests { use super::*; - use primitives::H256; - use support::{impl_outer_origin, assert_ok, parameter_types, weights::Weight}; + use sp_core::H256; + use frame_support::{impl_outer_origin, assert_ok, parameter_types, weights::Weight}; use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, testing::Header, Perbill, }; diff --git a/substrate/bin/node-template/src/chain_spec.rs b/substrate/bin/node-template/src/chain_spec.rs index 6b979b16dd..fae9feaf51 100644 --- a/substrate/bin/node-template/src/chain_spec.rs +++ b/substrate/bin/node-template/src/chain_spec.rs @@ -1,9 +1,9 @@ -use primitives::{Pair, Public, sr25519}; -use runtime::{ +use sp_core::{Pair, Public, sr25519}; +use node_template_runtime::{ AccountId, AuraConfig, BalancesConfig, GenesisConfig, GrandpaConfig, SudoConfig, IndicesConfig, SystemConfig, WASM_BINARY, Signature }; -use aura_primitives::sr25519::{AuthorityId as AuraId}; +use sp_consensus_aura::sr25519::{AuthorityId as AuraId}; use grandpa_primitives::{AuthorityId as GrandpaId}; use sc_service; use sp_runtime::traits::{Verify, IdentifyAccount}; diff --git a/substrate/bin/node-template/src/cli.rs b/substrate/bin/node-template/src/cli.rs index 5d29cdf8df..16638c4af9 100644 --- a/substrate/bin/node-template/src/cli.rs +++ b/substrate/bin/node-template/src/cli.rs @@ -5,7 +5,7 @@ use tokio::runtime::Runtime; pub use sc_cli::{VersionInfo, IntoExit, error}; use sc_cli::{display_role, informant, parse_and_prepare, ParseAndPrepare, NoCustom}; use sc_service::{AbstractService, Roles as ServiceRoles, Configuration}; -use aura_primitives::sr25519::{AuthorityPair as AuraPair}; +use sp_consensus_aura::sr25519::{AuthorityPair as AuraPair}; use crate::chain_spec; use log::info; diff --git a/substrate/bin/node-template/src/service.rs b/substrate/bin/node-template/src/service.rs index 9161e26732..e1379d2200 100644 --- a/substrate/bin/node-template/src/service.rs +++ b/substrate/bin/node-template/src/service.rs @@ -3,21 +3,21 @@ use std::sync::Arc; use std::time::Duration; use sc_client::LongestChain; -use runtime::{self, GenesisConfig, opaque::Block, RuntimeApi}; +use node_template_runtime::{self, GenesisConfig, opaque::Block, RuntimeApi}; use sc_service::{error::{Error as ServiceError}, AbstractService, Configuration, ServiceBuilder}; -use inherents::InherentDataProviders; -use network::{construct_simple_protocol}; +use sp_inherents::InherentDataProviders; +use sc_network::{construct_simple_protocol}; use sc_executor::native_executor_instance; pub use sc_executor::NativeExecutor; -use aura_primitives::sr25519::{AuthorityPair as AuraPair}; +use sp_consensus_aura::sr25519::{AuthorityPair as AuraPair}; use grandpa::{self, FinalityProofProvider as GrandpaFinalityProofProvider}; -use basic_authorship; +use sc_basic_authority; // Our native executor instance. native_executor_instance!( pub Executor, - runtime::api::dispatch, - runtime::native_version, + node_template_runtime::api::dispatch, + node_template_runtime::native_version, ); construct_simple_protocol! { @@ -32,19 +32,19 @@ construct_simple_protocol! { macro_rules! new_full_start { ($config:expr) => {{ let mut import_setup = None; - let inherent_data_providers = inherents::InherentDataProviders::new(); + let inherent_data_providers = sp_inherents::InherentDataProviders::new(); let builder = sc_service::ServiceBuilder::new_full::< - runtime::opaque::Block, runtime::RuntimeApi, crate::service::Executor + node_template_runtime::opaque::Block, node_template_runtime::RuntimeApi, crate::service::Executor >($config)? .with_select_chain(|_config, backend| { Ok(sc_client::LongestChain::new(backend.clone())) })? .with_transaction_pool(|config, client, _fetcher| { - let pool_api = txpool::FullChainApi::new(client.clone()); - let pool = txpool::BasicPool::new(config, pool_api); - let maintainer = txpool::FullBasicPoolMaintainer::new(pool.pool().clone(), client); - let maintainable_pool = txpool_api::MaintainableTransactionPool::new(pool, maintainer); + let pool_api = sc_transaction_pool::FullChainApi::new(client.clone()); + let pool = sc_transaction_pool::BasicPool::new(config, pool_api); + let maintainer = sc_transaction_pool::FullBasicPoolMaintainer::new(pool.pool().clone(), client); + let maintainable_pool = sp_transaction_pool::MaintainableTransactionPool::new(pool, maintainer); Ok(maintainable_pool) })? .with_import_queue(|_config, client, mut select_chain, transaction_pool| { @@ -52,12 +52,12 @@ macro_rules! new_full_start { .ok_or_else(|| sc_service::Error::SelectChainRequired)?; let (grandpa_block_import, grandpa_link) = - grandpa::block_import::<_, _, _, runtime::RuntimeApi, _>( + grandpa::block_import::<_, _, _, node_template_runtime::RuntimeApi, _>( client.clone(), &*client, select_chain )?; - let import_queue = aura::import_queue::<_, _, AuraPair, _>( - aura::SlotDuration::get_or_compute(&*client)?, + let import_queue = sc_consensus_aura::import_queue::<_, _, AuraPair, _>( + sc_consensus_aura::SlotDuration::get_or_compute(&*client)?, Box::new(grandpa_block_import.clone()), Some(Box::new(grandpa_block_import.clone())), None, @@ -102,7 +102,7 @@ pub fn new_full(config: Configuration(config: Configuration( - aura::SlotDuration::get_or_compute(&*client)?, + let aura = sc_consensus_aura::start_aura::<_, _, _, _, _, AuraPair, _, _, _, _>( + sc_consensus_aura::SlotDuration::get_or_compute(&*client)?, client, select_chain, block_import, @@ -203,10 +203,10 @@ pub fn new_light(config: Configuration(config: Configuration( - aura::SlotDuration::get_or_compute(&*client)?, + let import_queue = sc_consensus_aura::import_queue::<_, _, AuraPair, ()>( + sc_consensus_aura::SlotDuration::get_or_compute(&*client)?, Box::new(grandpa_block_import), None, Some(Box::new(finality_proof_import)), diff --git a/substrate/bin/node/cli/Cargo.toml b/substrate/bin/node/cli/Cargo.toml index 3d356ce5e4..e87d590614 100644 --- a/substrate/bin/node/cli/Cargo.toml +++ b/substrate/bin/node/cli/Cargo.toml @@ -34,45 +34,45 @@ rand = "0.7.2" structopt = "0.3.3" # primitives -authority-discovery-primitives = { package = "sp-authority-discovery", path = "../../../primitives/authority-discovery"} -babe-primitives = { package = "sp-consensus-babe", path = "../../../primitives/consensus/babe" } +sp-authority-discovery = { path = "../../../primitives/authority-discovery"} +sp-consensus-babe = { path = "../../../primitives/consensus/babe" } grandpa-primitives = { package = "sp-finality-grandpa", path = "../../../primitives/finality-grandpa" } -primitives = { package = "sp-core", path = "../../../primitives/core" } +sp-core = { path = "../../../primitives/core" } sp-runtime = { path = "../../../primitives/runtime" } sp-timestamp = { path = "../../../primitives/timestamp", default-features = false } sp-finality-tracker = { path = "../../../primitives/finality-tracker", default-features = false } -inherents = { package = "sp-inherents", path = "../../../primitives/inherents" } -keyring = { package = "sp-keyring", path = "../../../primitives/keyring" } +sp-inherents = { path = "../../../primitives/inherents" } +sp-keyring = { path = "../../../primitives/keyring" } sp-io = { path = "../../../primitives/io" } -consensus-common = { package = "sp-consensus", path = "../../../primitives/consensus/common" } +sp-consensus = { path = "../../../primitives/consensus/common" } # client dependencies -client-api = { package = "sc-client-api", path = "../../../client/api" } -client = { package = "sc-client", path = "../../../client/" } -chain-spec = { package = "sc-chain-spec", path = "../../../client/chain-spec" } -txpool = { package = "sc-transaction-pool", path = "../../../client/transaction-pool" } -txpool-api = { package = "sp-transaction-pool", path = "../../../primitives/transaction-pool" } -network = { package = "sc-network", path = "../../../client/network" } -babe = { package = "sc-consensus-babe", path = "../../../client/consensus/babe" } +sc-client-api = { path = "../../../client/api" } +sc-client = { path = "../../../client/" } +sc-chain-spec = { path = "../../../client/chain-spec" } +sc-transaction-pool = { path = "../../../client/transaction-pool" } +sp-transaction-pool = { path = "../../../primitives/transaction-pool" } +sc-network = { path = "../../../client/network" } +sc-consensus-babe = { path = "../../../client/consensus/babe" } grandpa = { package = "sc-finality-grandpa", path = "../../../client/finality-grandpa" } -client-db = { package = "sc-client-db", path = "../../../client/db", default-features = false } -offchain = { package = "sc-offchain", path = "../../../client/offchain" } +sc-client-db = { path = "../../../client/db", default-features = false } +sc-offchain = { path = "../../../client/offchain" } sc-rpc = { path = "../../../client/rpc" } sc-basic-authority = { path = "../../../client/basic-authorship" } sc-service = { path = "../../../client/service", default-features = false } sc-telemetry = { path = "../../../client/telemetry" } -authority-discovery = { package = "sc-authority-discovery", path = "../../../client/authority-discovery"} +sc-authority-discovery = { path = "../../../client/authority-discovery"} # frame dependencies -indices = { package = "pallet-indices", path = "../../../frame/indices" } -timestamp = { package = "pallet-timestamp", path = "../../../frame/timestamp", default-features = false } -contracts = { package = "pallet-contracts", path = "../../../frame/contracts" } -system = { package = "frame-system", path = "../../../frame/system" } -balances = { package = "pallet-balances", path = "../../../frame/balances" } -transaction-payment = { package = "pallet-transaction-payment", path = "../../../frame/transaction-payment" } -support = { package = "frame-support", path = "../../../frame/support", default-features = false } -im_online = { package = "pallet-im-online", path = "../../../frame/im-online", default-features = false } -sr-authority-discovery = { package = "pallet-authority-discovery", path = "../../../frame/authority-discovery"} +pallet-indices = { path = "../../../frame/indices" } +pallet-timestamp = { path = "../../../frame/timestamp", default-features = false } +pallet-contracts = { path = "../../../frame/contracts" } +frame-system = { path = "../../../frame/system" } +pallet-balances = { path = "../../../frame/balances" } +pallet-transaction-payment = { path = "../../../frame/transaction-payment" } +frame-support = { path = "../../../frame/support", default-features = false } +pallet-im-online = { path = "../../../frame/im-online", default-features = false } +pallet-authority-discovery = { path = "../../../frame/authority-discovery"} # node-specific dependencies node-runtime = { path = "../runtime" } @@ -98,9 +98,9 @@ kvdb-memorydb = { version = "0.1.1", optional = true } rand6 = { package = "rand", version = "0.6", features = ["wasm-bindgen"], optional = true } # Imported just for the `wasm-bindgen` feature [dev-dependencies] -keystore = { package = "sc-keystore", path = "../../../client/keystore" } -babe = { package = "sc-consensus-babe", path = "../../../client/consensus/babe", features = ["test-helpers"] } -service-test = { package = "sc-service-test", path = "../../../client/service/test" } +sc-keystore = { path = "../../../client/keystore" } +sc-consensus-babe = { path = "../../../client/consensus/babe", features = ["test-helpers"] } +sc-service-test = { path = "../../../client/service/test" } futures = "0.3.1" tempfile = "3.1.0" diff --git a/substrate/bin/node/cli/src/browser.rs b/substrate/bin/node/cli/src/browser.rs index b09bb74026..cd1d453d8b 100644 --- a/substrate/bin/node/cli/src/browser.rs +++ b/substrate/bin/node/cli/src/browser.rs @@ -40,7 +40,7 @@ fn start_inner(wasm_ext: wasm_ext::ffi::Transport) -> Result::default_with_spec_and_base_path(chain_spec, None); - config.network.transport = network::config::TransportConfig::Normal { + config.network.transport = sc_network::config::TransportConfig::Normal { wasm_external_transport: Some(wasm_ext.clone()), allow_private_ipv4: true, enable_mdns: false, diff --git a/substrate/bin/node/cli/src/chain_spec.rs b/substrate/bin/node/cli/src/chain_spec.rs index fd65ec0624..8b86cb865b 100644 --- a/substrate/bin/node/cli/src/chain_spec.rs +++ b/substrate/bin/node/cli/src/chain_spec.rs @@ -16,8 +16,8 @@ //! Substrate chain configurations. -use chain_spec::ChainSpecExtension; -use primitives::{Pair, Public, crypto::UncheckedInto, sr25519}; +use sc_chain_spec::ChainSpecExtension; +use sp_core::{Pair, Public, crypto::UncheckedInto, sr25519}; use serde::{Serialize, Deserialize}; use node_runtime::{ AuthorityDiscoveryConfig, BabeConfig, BalancesConfig, ContractsConfig, CouncilConfig, DemocracyConfig, @@ -30,9 +30,9 @@ use sc_service; use hex_literal::hex; use sc_telemetry::TelemetryEndpoints; use grandpa_primitives::{AuthorityId as GrandpaId}; -use babe_primitives::{AuthorityId as BabeId}; -use im_online::sr25519::{AuthorityId as ImOnlineId}; -use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId; +use sp_consensus_babe::{AuthorityId as BabeId}; +use pallet_im_online::sr25519::{AuthorityId as ImOnlineId}; +use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId; use sp_runtime::{Perbill, traits::{Verify, IdentifyAccount}}; pub use node_primitives::{AccountId, Balance, Signature}; @@ -49,7 +49,7 @@ const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/"; #[derive(Default, Clone, Serialize, Deserialize, ChainSpecExtension)] pub struct Extensions { /// Block numbers with known hashes. - pub fork_blocks: client::ForkBlocks, + pub fork_blocks: sc_client::ForkBlocks, } /// Specialized `ChainSpec`. @@ -229,24 +229,24 @@ pub fn testnet_genesis( code: WASM_BINARY.to_vec(), changes_trie_config: Default::default(), }), - balances: Some(BalancesConfig { + pallet_balances: Some(BalancesConfig { balances: endowed_accounts.iter().cloned() .map(|k| (k, ENDOWMENT)) .chain(initial_authorities.iter().map(|x| (x.0.clone(), STASH))) .collect(), vesting: vec![], }), - indices: Some(IndicesConfig { + pallet_indices: Some(IndicesConfig { ids: endowed_accounts.iter().cloned() .chain(initial_authorities.iter().map(|x| x.0.clone())) .collect::>(), }), - session: Some(SessionConfig { + pallet_session: Some(SessionConfig { keys: initial_authorities.iter().map(|x| { (x.0.clone(), session_keys(x.2.clone(), x.3.clone(), x.4.clone(), x.5.clone())) }).collect::>(), }), - staking: Some(StakingConfig { + pallet_staking: Some(StakingConfig { current_era: 0, validator_count: initial_authorities.len() as u32 * 2, minimum_validator_count: initial_authorities.len() as u32, @@ -257,41 +257,41 @@ pub fn testnet_genesis( slash_reward_fraction: Perbill::from_percent(10), .. Default::default() }), - democracy: Some(DemocracyConfig::default()), - collective_Instance1: Some(CouncilConfig { + pallet_democracy: Some(DemocracyConfig::default()), + pallet_collective_Instance1: Some(CouncilConfig { members: endowed_accounts.iter().cloned() .collect::>()[..(num_endowed_accounts + 1) / 2].to_vec(), phantom: Default::default(), }), - collective_Instance2: Some(TechnicalCommitteeConfig { + pallet_collective_Instance2: Some(TechnicalCommitteeConfig { members: endowed_accounts.iter().cloned() .collect::>()[..(num_endowed_accounts + 1) / 2].to_vec(), phantom: Default::default(), }), - contracts: Some(ContractsConfig { - current_schedule: contracts::Schedule { + pallet_contracts: Some(ContractsConfig { + current_schedule: pallet_contracts::Schedule { enable_println, // this should only be enabled on development chains ..Default::default() }, gas_price: 1 * MILLICENTS, }), - sudo: Some(SudoConfig { + pallet_sudo: Some(SudoConfig { key: root_key, }), - babe: Some(BabeConfig { + pallet_babe: Some(BabeConfig { authorities: vec![], }), - im_online: Some(ImOnlineConfig { + pallet_im_online: Some(ImOnlineConfig { keys: vec![], }), - authority_discovery: Some(AuthorityDiscoveryConfig { + pallet_authority_discovery: Some(AuthorityDiscoveryConfig { keys: vec![], }), - grandpa: Some(GrandpaConfig { + pallet_grandpa: Some(GrandpaConfig { authorities: vec![], }), - membership_Instance1: Some(Default::default()), - treasury: Some(Default::default()), + pallet_membership_Instance1: Some(Default::default()), + pallet_treasury: Some(Default::default()), } } @@ -351,7 +351,7 @@ pub(crate) mod tests { use super::*; use crate::service::new_full; use sc_service::Roles; - use service_test; + use sc_service_test; fn local_testnet_genesis_instant_single() -> GenesisConfig { testnet_genesis( @@ -395,7 +395,7 @@ pub(crate) mod tests { #[test] #[ignore] fn test_connectivity() { - service_test::connectivity( + sc_service_test::connectivity( integration_test_config_with_two_authorities(), |config| new_full(config), |mut config| { diff --git a/substrate/bin/node/cli/src/factory_impl.rs b/substrate/bin/node/cli/src/factory_impl.rs index b586337a2b..2a77bb5caa 100644 --- a/substrate/bin/node/cli/src/factory_impl.rs +++ b/substrate/bin/node/cli/src/factory_impl.rs @@ -22,19 +22,19 @@ use rand::{Rng, SeedableRng}; use rand::rngs::StdRng; use codec::{Encode, Decode}; -use keyring::sr25519::Keyring; +use sp_keyring::sr25519::Keyring; use node_runtime::{ Call, CheckedExtrinsic, UncheckedExtrinsic, SignedExtra, BalancesCall, ExistentialDeposit, MinimumPeriod }; use node_primitives::Signature; -use primitives::{sr25519, crypto::Pair}; +use sp_core::{sr25519, crypto::Pair}; use sp_runtime::{ generic::Era, traits::{Block as BlockT, Header as HeaderT, SignedExtension, Verify, IdentifyAccount} }; use node_transaction_factory::RuntimeAdapter; use node_transaction_factory::modes::Mode; -use inherents::InherentData; +use sp_inherents::InherentData; use sp_timestamp; use sp_finality_tracker; @@ -56,12 +56,12 @@ type Number = <::Header as HeaderT>::Number; impl FactoryState { fn build_extra(index: node_primitives::Index, phase: u64) -> node_runtime::SignedExtra { ( - system::CheckVersion::new(), - system::CheckGenesis::new(), - system::CheckEra::from(Era::mortal(256, phase)), - system::CheckNonce::from(index), - system::CheckWeight::new(), - transaction_payment::ChargeTransactionPayment::from(0), + frame_system::CheckVersion::new(), + frame_system::CheckGenesis::new(), + frame_system::CheckEra::from(Era::mortal(256, phase)), + frame_system::CheckNonce::from(index), + frame_system::CheckWeight::new(), + pallet_transaction_payment::ChargeTransactionPayment::from(0), Default::default(), ) } @@ -149,7 +149,7 @@ impl RuntimeAdapter for FactoryState { signed: Some((sender.clone(), Self::build_extra(index, phase))), function: Call::Balances( BalancesCall::transfer( - indices::address::Address::Id(destination.clone().into()), + pallet_indices::address::Address::Id(destination.clone().into()), (*amount).into() ) ) @@ -253,7 +253,7 @@ fn sign( } }).into(); UncheckedExtrinsic { - signature: Some((indices::address::Address::Id(signed), signature, extra)), + signature: Some((pallet_indices::address::Address::Id(signed), signature, extra)), function: payload.0, } } diff --git a/substrate/bin/node/cli/src/service.rs b/substrate/bin/node/cli/src/service.rs index 025af2715c..7716f5a1c3 100644 --- a/substrate/bin/node/cli/src/service.rs +++ b/substrate/bin/node/cli/src/service.rs @@ -20,8 +20,8 @@ use std::sync::Arc; -use babe; -use client::{self, LongestChain}; +use sc_consensus_babe; +use sc_client::{self, LongestChain}; use grandpa::{self, FinalityProofProvider as GrandpaFinalityProofProvider}; use node_executor; use node_primitives::Block; @@ -29,17 +29,17 @@ use node_runtime::{GenesisConfig, RuntimeApi}; use sc_service::{ AbstractService, ServiceBuilder, config::Configuration, error::{Error as ServiceError}, }; -use inherents::InherentDataProviders; -use network::construct_simple_protocol; +use sp_inherents::InherentDataProviders; +use sc_network::construct_simple_protocol; use sc_service::{Service, NetworkStatus}; -use client::{Client, LocalCallExecutor}; -use client_db::Backend; +use sc_client::{Client, LocalCallExecutor}; +use sc_client_db::Backend; use sp_runtime::traits::Block as BlockT; use node_executor::NativeExecutor; -use network::NetworkService; -use offchain::OffchainWorkers; -use primitives::Blake2Hasher; +use sc_network::NetworkService; +use sc_offchain::OffchainWorkers; +use sp_core::Blake2Hasher; construct_simple_protocol! { /// Demo protocol attachment for substrate. @@ -54,19 +54,19 @@ macro_rules! new_full_start { ($config:expr) => {{ type RpcExtension = jsonrpc_core::IoHandler; let mut import_setup = None; - let inherent_data_providers = inherents::InherentDataProviders::new(); + let inherent_data_providers = sp_inherents::InherentDataProviders::new(); let builder = sc_service::ServiceBuilder::new_full::< node_primitives::Block, node_runtime::RuntimeApi, node_executor::Executor >($config)? .with_select_chain(|_config, backend| { - Ok(client::LongestChain::new(backend.clone())) + Ok(sc_client::LongestChain::new(backend.clone())) })? .with_transaction_pool(|config, client, _fetcher| { - let pool_api = txpool::FullChainApi::new(client.clone()); - let pool = txpool::BasicPool::new(config, pool_api); - let maintainer = txpool::FullBasicPoolMaintainer::new(pool.pool().clone(), client); - let maintainable_pool = txpool_api::MaintainableTransactionPool::new(pool, maintainer); + let pool_api = sc_transaction_pool::FullChainApi::new(client.clone()); + let pool = sc_transaction_pool::BasicPool::new(config, pool_api); + let maintainer = sc_transaction_pool::FullBasicPoolMaintainer::new(pool.pool().clone(), client); + let maintainable_pool = sp_transaction_pool::MaintainableTransactionPool::new(pool, maintainer); Ok(maintainable_pool) })? .with_import_queue(|_config, client, mut select_chain, _transaction_pool| { @@ -79,14 +79,14 @@ macro_rules! new_full_start { )?; let justification_import = grandpa_block_import.clone(); - let (block_import, babe_link) = babe::block_import( - babe::Config::get_or_compute(&*client)?, + let (block_import, babe_link) = sc_consensus_babe::block_import( + sc_consensus_babe::Config::get_or_compute(&*client)?, grandpa_block_import, client.clone(), client.clone(), )?; - let import_queue = babe::import_queue( + let import_queue = sc_consensus_babe::import_queue( babe_link.clone(), block_import.clone(), Some(Box::new(justification_import)), @@ -114,7 +114,7 @@ macro_rules! new_full_start { macro_rules! new_full { ($config:expr, $with_startup_data: expr) => {{ use futures01::sync::mpsc; - use network::DhtEvent; + use sc_network::DhtEvent; use futures::{ compat::Stream01CompatExt, stream::StreamExt, @@ -172,9 +172,9 @@ macro_rules! new_full { .ok_or(sc_service::Error::SelectChainRequired)?; let can_author_with = - consensus_common::CanAuthorWithNativeVersion::new(client.executor().clone()); + sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()); - let babe_config = babe::BabeParams { + let babe_config = sc_consensus_babe::BabeParams { keystore: service.keystore(), client, select_chain, @@ -187,13 +187,13 @@ macro_rules! new_full { can_author_with, }; - let babe = babe::start_babe(babe_config)?; + let babe = sc_consensus_babe::start_babe(babe_config)?; service.spawn_essential_task(babe); let future03_dht_event_rx = dht_event_rx.compat() .map(|x| x.expect(" never returns an error; qed")) .boxed(); - let authority_discovery = authority_discovery::AuthorityDiscovery::new( + let authority_discovery = sc_authority_discovery::AuthorityDiscovery::new( service.client(), service.network(), sentry_nodes, @@ -280,14 +280,14 @@ type ConcreteClient = #[allow(dead_code)] type ConcreteBackend = Backend; #[allow(dead_code)] -type ConcreteTransactionPool = txpool_api::MaintainableTransactionPool< - txpool::BasicPool< - txpool::FullChainApi, +type ConcreteTransactionPool = sp_transaction_pool::MaintainableTransactionPool< + sc_transaction_pool::BasicPool< + sc_transaction_pool::FullChainApi, ConcreteBlock >, - txpool::FullBasicPoolMaintainer< + sc_transaction_pool::FullBasicPoolMaintainer< ConcreteClient, - txpool::FullChainApi + sc_transaction_pool::FullChainApi > >; @@ -306,7 +306,7 @@ pub fn new_full(config: NodeConfiguration) ConcreteTransactionPool, OffchainWorkers< ConcreteClient, - >::OffchainStorage, + >::OffchainStorage, ConcreteBlock, > >, @@ -329,10 +329,10 @@ pub fn new_light(config: NodeConfiguration) .with_transaction_pool(|config, client, fetcher| { let fetcher = fetcher .ok_or_else(|| "Trying to start light transaction pool without active fetcher")?; - let pool_api = txpool::LightChainApi::new(client.clone(), fetcher.clone()); - let pool = txpool::BasicPool::new(config, pool_api); - let maintainer = txpool::LightBasicPoolMaintainer::with_defaults(pool.pool().clone(), client, fetcher); - let maintainable_pool = txpool_api::MaintainableTransactionPool::new(pool, maintainer); + let pool_api = sc_transaction_pool::LightChainApi::new(client.clone(), fetcher.clone()); + let pool = sc_transaction_pool::BasicPool::new(config, pool_api); + let maintainer = sc_transaction_pool::LightBasicPoolMaintainer::with_defaults(pool.pool().clone(), client, fetcher); + let maintainable_pool = sp_transaction_pool::MaintainableTransactionPool::new(pool, maintainer); Ok(maintainable_pool) })? .with_import_queue_and_fprb(|_config, client, backend, fetcher, _select_chain, _tx_pool| { @@ -350,14 +350,14 @@ pub fn new_light(config: NodeConfiguration) let finality_proof_request_builder = finality_proof_import.create_finality_proof_request_builder(); - let (babe_block_import, babe_link) = babe::block_import( - babe::Config::get_or_compute(&*client)?, + let (babe_block_import, babe_link) = sc_consensus_babe::block_import( + sc_consensus_babe::Config::get_or_compute(&*client)?, grandpa_block_import, client.clone(), client.clone(), )?; - let import_queue = babe::import_queue( + let import_queue = sc_consensus_babe::import_queue( babe_link, babe_block_import, None, @@ -390,15 +390,15 @@ pub fn new_light(config: NodeConfiguration) #[cfg(test)] mod tests { use std::sync::Arc; - use babe::CompatibleDigestItem; - use consensus_common::{ + use sc_consensus_babe::CompatibleDigestItem; + use sp_consensus::{ Environment, Proposer, BlockImportParams, BlockOrigin, ForkChoiceStrategy, BlockImport, }; use node_primitives::{Block, DigestItem, Signature}; use node_runtime::{BalancesCall, Call, UncheckedExtrinsic, Address}; use node_runtime::constants::{currency::CENTS, time::SLOT_DURATION}; use codec::{Encode, Decode}; - use primitives::{crypto::Pair as CryptoPair, H256}; + use sp_core::{crypto::Pair as CryptoPair, H256}; use sp_runtime::{ generic::{BlockId, Era, Digest, SignedPayload}, traits::Block as BlockT, @@ -407,7 +407,7 @@ mod tests { }; use sp_timestamp; use sp_finality_tracker; - use keyring::AccountKeyring; + use sp_keyring::AccountKeyring; use sc_service::{AbstractService, Roles}; use crate::service::new_full; use sp_runtime::traits::IdentifyAccount; @@ -416,10 +416,10 @@ mod tests { #[cfg(feature = "rhd")] fn test_sync() { - use primitives::ed25519::Pair; + use sp_core::ed25519::Pair; use {service_test, Factory}; - use client::{BlockImportParams, BlockOrigin}; + use sc_client::{BlockImportParams, BlockOrigin}; let alice: Arc = Arc::new(Keyring::Alice.into()); let bob: Arc = Arc::new(Keyring::Bob.into()); @@ -467,8 +467,8 @@ mod tests { let v: Vec = Decode::decode(&mut xt.as_slice()).unwrap(); OpaqueExtrinsic(v) }; - service_test::sync( - chain_spec::integration_test_config(), + sc_service_test::sync( + sc_chain_spec::integration_test_config(), |config| new_full(config), |mut config| { // light nodes are unsupported @@ -484,9 +484,9 @@ mod tests { #[ignore] fn test_sync() { let keystore_path = tempfile::tempdir().expect("Creates keystore path"); - let keystore = keystore::Store::open(keystore_path.path(), None) + let keystore = sc_keystore::Store::open(keystore_path.path(), None) .expect("Creates keystore"); - let alice = keystore.write().insert_ephemeral_from_seed::("//Alice") + let alice = keystore.write().insert_ephemeral_from_seed::("//Alice") .expect("Creates authority pair"); let chain_spec = crate::chain_spec::tests::integration_test_config_with_single_authority(); @@ -499,13 +499,13 @@ mod tests { let charlie = Arc::new(AccountKeyring::Charlie.pair()); let mut index = 0; - service_test::sync( + sc_service_test::sync( chain_spec, |config| { let mut setup_handles = None; new_full!(config, | - block_import: &babe::BabeBlockImport<_, _, Block, _, _, _>, - babe_link: &babe::BabeLink, + block_import: &sc_consensus_babe::BabeBlockImport<_, _, Block, _, _, _>, + babe_link: &sc_consensus_babe::BabeLink, | { setup_handles = Some((block_import.clone(), babe_link.clone())); }).map(move |(node, x)| (node, (x, setup_handles.unwrap()))) @@ -534,7 +534,7 @@ mod tests { // so we must keep trying the next slots until we can claim one. let babe_pre_digest = loop { inherent_data.replace_data(sp_timestamp::INHERENT_IDENTIFIER, &(slot_num * SLOT_DURATION)); - if let Some(babe_pre_digest) = babe::test_helpers::claim_slot( + if let Some(babe_pre_digest) = sc_consensus_babe::test_helpers::claim_slot( slot_num, &parent_header, &*service.client(), @@ -594,12 +594,12 @@ mod tests { let function = Call::Balances(BalancesCall::transfer(to.into(), amount)); - let check_version = system::CheckVersion::new(); - let check_genesis = system::CheckGenesis::new(); - let check_era = system::CheckEra::from(Era::Immortal); - let check_nonce = system::CheckNonce::from(index); - let check_weight = system::CheckWeight::new(); - let payment = transaction_payment::ChargeTransactionPayment::from(0); + let check_version = frame_system::CheckVersion::new(); + let check_genesis = frame_system::CheckGenesis::new(); + let check_era = frame_system::CheckEra::from(Era::Immortal); + let check_nonce = frame_system::CheckNonce::from(index); + let check_weight = frame_system::CheckWeight::new(); + let payment = pallet_transaction_payment::ChargeTransactionPayment::from(0); let extra = ( check_version, check_genesis, @@ -635,7 +635,7 @@ mod tests { #[test] #[ignore] fn test_consensus() { - service_test::consensus( + sc_service_test::consensus( crate::chain_spec::tests::integration_test_config_with_two_authorities(), |config| new_full(config), |mut config| { diff --git a/substrate/bin/node/executor/Cargo.toml b/substrate/bin/node/executor/Cargo.toml index 7633c256e7..68765ddff6 100644 --- a/substrate/bin/node/executor/Cargo.toml +++ b/substrate/bin/node/executor/Cargo.toml @@ -9,27 +9,27 @@ edition = "2018" trie-root = "0.15.2" codec = { package = "parity-scale-codec", version = "1.0.0" } sp-io = { path = "../../../primitives/io" } -state_machine = { package = "sp-state-machine", path = "../../../primitives/state-machine" } +sp-state-machine = { path = "../../../primitives/state-machine" } sc-executor = { path = "../../../client/executor" } -primitives = { package = "sp-core", path = "../../../primitives/core" } -trie = { package = "sp-trie", path = "../../../primitives/trie" } +sp-core = { path = "../../../primitives/core" } +sp-trie = { path = "../../../primitives/trie" } node-primitives = { path = "../primitives" } node-runtime = { path = "../runtime" } [dev-dependencies] node-testing = { path = "../testing" } -test-client = { package = "substrate-test-client", path = "../../../test-utils/client" } +substrate-test-client = { path = "../../../test-utils/client" } sp-runtime = { path = "../../../primitives/runtime" } -runtime_support = { package = "frame-support", path = "../../../frame/support" } -balances = { package = "pallet-balances", path = "../../../frame/balances" } -transaction-payment = { package = "pallet-transaction-payment", path = "../../../frame/transaction-payment" } -session = { package = "pallet-session", path = "../../../frame/session" } -system = { package = "frame-system", path = "../../../frame/system" } -timestamp = { package = "pallet-timestamp", path = "../../../frame/timestamp" } -treasury = { package = "pallet-treasury", path = "../../../frame/treasury" } -contracts = { package = "pallet-contracts", path = "../../../frame/contracts" } -grandpa = { package = "pallet-grandpa", path = "../../../frame/grandpa" } -indices = { package = "pallet-indices", path = "../../../frame/indices" } +frame-support = { path = "../../../frame/support" } +pallet-balances = { path = "../../../frame/balances" } +pallet-transaction-payment = { path = "../../../frame/transaction-payment" } +pallet-session = { path = "../../../frame/session" } +frame-system = { path = "../../../frame/system" } +pallet-timestamp = { path = "../../../frame/timestamp" } +pallet-treasury = { path = "../../../frame/treasury" } +pallet-contracts = { path = "../../../frame/contracts" } +pallet-grandpa = { path = "../../../frame/grandpa" } +pallet-indices = { path = "../../../frame/indices" } wabt = "0.9.2" criterion = "0.3.0" diff --git a/substrate/bin/node/executor/benches/bench.rs b/substrate/bin/node/executor/benches/bench.rs index 86a9c1c672..74999a404e 100644 --- a/substrate/bin/node/executor/benches/bench.rs +++ b/substrate/bin/node/executor/benches/bench.rs @@ -23,11 +23,11 @@ use node_runtime::{ }; use node_runtime::constants::currency::*; use node_testing::keyring::*; -use primitives::{Blake2Hasher, NativeOrEncoded, NeverNativeValue}; -use primitives::storage::well_known_keys; -use primitives::traits::CodeExecutor; -use runtime_support::Hashable; -use state_machine::TestExternalities as CoreTestExternalities; +use sp_core::{Blake2Hasher, NativeOrEncoded, NeverNativeValue}; +use sp_core::storage::well_known_keys; +use sp_core::traits::CodeExecutor; +use frame_support::Hashable; +use sp_state_machine::TestExternalities as CoreTestExternalities; use sc_executor::{NativeExecutor, RuntimeInfo, WasmExecutionMethod, Externalities}; criterion_group!(benches, bench_execute_block); @@ -70,7 +70,7 @@ fn construct_block( parent_hash: Hash, extrinsics: Vec, ) -> (Vec, Hash) { - use trie::{TrieConfiguration, trie_types::Layout}; + use sp_trie::{TrieConfiguration, trie_types::Layout}; // sign extrinsics. let extrinsics = extrinsics.into_iter().map(sign).collect::>(); @@ -131,13 +131,13 @@ fn test_blocks(genesis_config: &GenesisConfig, executor: &NativeExecutor::WeightToFee::convert(weight); + let weight_fee = ::WeightToFee::convert(weight); fee_multiplier.saturated_multiply_accumulate(length_fee + weight_fee) + TransferFee::get() } - fn default_transfer_call() -> balances::Call { - balances::Call::transfer::(bob().into(), 69 * DOLLARS) + fn default_transfer_call() -> pallet_balances::Call { + pallet_balances::Call::transfer::(bob().into(), 69 * DOLLARS) } fn xt() -> UncheckedExtrinsic { @@ -145,16 +144,16 @@ mod tests { fn panic_execution_with_foreign_code_gives_error() { let mut t = TestExternalities::::new_with_code(BLOATY_CODE, Storage { top: map![ - >::hashed_key_for(alice()) => { + >::hashed_key_for(alice()) => { 69_u128.encode() }, - >::hashed_key().to_vec() => { + >::hashed_key().to_vec() => { 69_u128.encode() }, - >::hashed_key().to_vec() => { + >::hashed_key().to_vec() => { 0_u128.encode() }, - >::hashed_key_for(0) => { + >::hashed_key_for(0) => { vec![0u8; 32] } ], @@ -184,16 +183,16 @@ mod tests { fn bad_extrinsic_with_native_equivalent_code_gives_error() { let mut t = TestExternalities::::new_with_code(COMPACT_CODE, Storage { top: map![ - >::hashed_key_for(alice()) => { + >::hashed_key_for(alice()) => { 69_u128.encode() }, - >::hashed_key().to_vec() => { + >::hashed_key().to_vec() => { 69_u128.encode() }, - >::hashed_key().to_vec() => { + >::hashed_key().to_vec() => { 0_u128.encode() }, - >::hashed_key_for(0) => { + >::hashed_key_for(0) => { vec![0u8; 32] } ], @@ -223,14 +222,14 @@ mod tests { fn successful_execution_with_native_equivalent_code_gives_ok() { let mut t = TestExternalities::::new_with_code(COMPACT_CODE, Storage { top: map![ - >::hashed_key_for(alice()) => { + >::hashed_key_for(alice()) => { (111 * DOLLARS).encode() }, - >::hashed_key().to_vec() => { + >::hashed_key().to_vec() => { (111 * DOLLARS).encode() }, - >::hashed_key().to_vec() => vec![0u8; 16], - >::hashed_key_for(0) => vec![0u8; 32] + >::hashed_key().to_vec() => vec![0u8; 16], + >::hashed_key_for(0) => vec![0u8; 32] ], children: map![], }); @@ -265,14 +264,14 @@ mod tests { fn successful_execution_with_foreign_code_gives_ok() { let mut t = TestExternalities::::new_with_code(BLOATY_CODE, Storage { top: map![ - >::hashed_key_for(alice()) => { + >::hashed_key_for(alice()) => { (111 * DOLLARS).encode() }, - >::hashed_key().to_vec() => { + >::hashed_key().to_vec() => { (111 * DOLLARS).encode() }, - >::hashed_key().to_vec() => vec![0u8; 16], - >::hashed_key_for(0) => vec![0u8; 32] + >::hashed_key().to_vec() => vec![0u8; 16], + >::hashed_key_for(0) => vec![0u8; 32] ], children: map![], }); @@ -318,7 +317,7 @@ mod tests { parent_hash: Hash, extrinsics: Vec, ) -> (Vec, Hash) { - use trie::{TrieConfiguration, trie_types::Layout}; + use sp_trie::{TrieConfiguration, trie_types::Layout}; // sign extrinsics. let extrinsics = extrinsics.into_iter().map(sign).collect::>(); @@ -379,11 +378,11 @@ mod tests { vec![ CheckedExtrinsic { signed: None, - function: Call::Timestamp(timestamp::Call::set(42 * 1000)), + function: Call::Timestamp(pallet_timestamp::Call::set(42 * 1000)), }, CheckedExtrinsic { signed: Some((alice(), signed_extra(0, 0))), - function: Call::Balances(balances::Call::transfer(bob().into(), 69 * DOLLARS)), + function: Call::Balances(pallet_balances::Call::transfer(bob().into(), 69 * DOLLARS)), }, ] ) @@ -401,11 +400,11 @@ mod tests { vec![ CheckedExtrinsic { signed: None, - function: Call::Timestamp(timestamp::Call::set(42 * 1000)), + function: Call::Timestamp(pallet_timestamp::Call::set(42 * 1000)), }, CheckedExtrinsic { signed: Some((alice(), signed_extra(0, 0))), - function: Call::Balances(balances::Call::transfer(bob().into(), 69 * DOLLARS)), + function: Call::Balances(pallet_balances::Call::transfer(bob().into(), 69 * DOLLARS)), }, ] ); @@ -416,15 +415,15 @@ mod tests { vec![ CheckedExtrinsic { signed: None, - function: Call::Timestamp(timestamp::Call::set(52 * 1000)), + function: Call::Timestamp(pallet_timestamp::Call::set(52 * 1000)), }, CheckedExtrinsic { signed: Some((bob(), signed_extra(0, 0))), - function: Call::Balances(balances::Call::transfer(alice().into(), 5 * DOLLARS)), + function: Call::Balances(pallet_balances::Call::transfer(alice().into(), 5 * DOLLARS)), }, CheckedExtrinsic { signed: Some((alice(), signed_extra(1, 0))), - function: Call::Balances(balances::Call::transfer(bob().into(), 15 * DOLLARS)), + function: Call::Balances(pallet_balances::Call::transfer(bob().into(), 15 * DOLLARS)), } ] ); @@ -444,11 +443,11 @@ mod tests { vec![ CheckedExtrinsic { signed: None, - function: Call::Timestamp(timestamp::Call::set(time * 1000)), + function: Call::Timestamp(pallet_timestamp::Call::set(time * 1000)), }, CheckedExtrinsic { signed: Some((alice(), signed_extra(nonce, 0))), - function: Call::System(system::Call::remark(vec![0; size])), + function: Call::System(frame_system::Call::remark(vec![0; size])), } ] ) @@ -478,19 +477,19 @@ mod tests { let events = vec![ EventRecord { phase: Phase::ApplyExtrinsic(0), - event: Event::system(system::Event::ExtrinsicSuccess( + event: Event::system(frame_system::Event::ExtrinsicSuccess( DispatchInfo { weight: 10000, class: DispatchClass::Operational, pays_fee: true } )), topics: vec![], }, EventRecord { phase: Phase::ApplyExtrinsic(1), - event: Event::treasury(treasury::RawEvent::Deposit(1984800000000)), + event: Event::pallet_treasury(pallet_treasury::RawEvent::Deposit(1984800000000)), topics: vec![], }, EventRecord { phase: Phase::ApplyExtrinsic(1), - event: Event::balances(balances::RawEvent::Transfer( + event: Event::pallet_balances(pallet_balances::RawEvent::Transfer( alice().into(), bob().into(), 69 * DOLLARS, @@ -500,7 +499,7 @@ mod tests { }, EventRecord { phase: Phase::ApplyExtrinsic(1), - event: Event::system(system::Event::ExtrinsicSuccess( + event: Event::system(frame_system::Event::ExtrinsicSuccess( DispatchInfo { weight: 1000000, class: DispatchClass::Normal, pays_fee: true } )), topics: vec![], @@ -531,20 +530,20 @@ mod tests { let events = vec![ EventRecord { phase: Phase::ApplyExtrinsic(0), - event: Event::system(system::Event::ExtrinsicSuccess( + event: Event::system(frame_system::Event::ExtrinsicSuccess( DispatchInfo { weight: 10000, class: DispatchClass::Operational, pays_fee: true } )), topics: vec![], }, EventRecord { phase: Phase::ApplyExtrinsic(1), - event: Event::treasury(treasury::RawEvent::Deposit(1984780231392)), + event: Event::pallet_treasury(pallet_treasury::RawEvent::Deposit(1984780231392)), topics: vec![], }, EventRecord { phase: Phase::ApplyExtrinsic(1), - event: Event::balances( - balances::RawEvent::Transfer( + event: Event::pallet_balances( + pallet_balances::RawEvent::Transfer( bob().into(), alice().into(), 5 * DOLLARS, @@ -555,20 +554,20 @@ mod tests { }, EventRecord { phase: Phase::ApplyExtrinsic(1), - event: Event::system(system::Event::ExtrinsicSuccess( + event: Event::system(frame_system::Event::ExtrinsicSuccess( DispatchInfo { weight: 1000000, class: DispatchClass::Normal, pays_fee: true } )), topics: vec![], }, EventRecord { phase: Phase::ApplyExtrinsic(2), - event: Event::treasury(treasury::RawEvent::Deposit(1984780231392)), + event: Event::pallet_treasury(pallet_treasury::RawEvent::Deposit(1984780231392)), topics: vec![], }, EventRecord { phase: Phase::ApplyExtrinsic(2), - event: Event::balances( - balances::RawEvent::Transfer( + event: Event::pallet_balances( + pallet_balances::RawEvent::Transfer( alice().into(), bob().into(), 15 * DOLLARS, @@ -579,7 +578,7 @@ mod tests { }, EventRecord { phase: Phase::ApplyExtrinsic(2), - event: Event::system(system::Event::ExtrinsicSuccess( + event: Event::system(frame_system::Event::ExtrinsicSuccess( DispatchInfo { weight: 1000000, class: DispatchClass::Normal, pays_fee: true } )), topics: vec![], @@ -729,9 +728,9 @@ mod tests { #[test] fn deploying_wasm_contract_should_work() { let transfer_code = wabt::wat2wasm(CODE_TRANSFER).unwrap(); - let transfer_ch = ::Hashing::hash(&transfer_code); + let transfer_ch = ::Hashing::hash(&transfer_code); - let addr = ::DetermineContractAddress::contract_address_for( + let addr = ::DetermineContractAddress::contract_address_for( &transfer_ch, &[], &charlie(), @@ -744,25 +743,25 @@ mod tests { vec![ CheckedExtrinsic { signed: None, - function: Call::Timestamp(timestamp::Call::set(42 * 1000)), + function: Call::Timestamp(pallet_timestamp::Call::set(42 * 1000)), }, CheckedExtrinsic { signed: Some((charlie(), signed_extra(0, 0))), function: Call::Contracts( - contracts::Call::put_code::(10_000, transfer_code) + pallet_contracts::Call::put_code::(10_000, transfer_code) ), }, CheckedExtrinsic { signed: Some((charlie(), signed_extra(1, 0))), function: Call::Contracts( - contracts::Call::instantiate::(1 * DOLLARS, 10_000, transfer_ch, Vec::new()) + pallet_contracts::Call::instantiate::(1 * DOLLARS, 10_000, transfer_ch, Vec::new()) ), }, CheckedExtrinsic { signed: Some((charlie(), signed_extra(2, 0))), function: Call::Contracts( - contracts::Call::call::( - indices::address::Address::Id(addr.clone()), + pallet_contracts::Call::call::( + pallet_indices::address::Address::Id(addr.clone()), 10, 10_000, vec![0x00, 0x01, 0x02, 0x03] @@ -785,7 +784,7 @@ mod tests { t.execute_with(|| { // Verify that the contract constructor worked well and code of TRANSFER contract is actually deployed. assert_eq!( - &contracts::ContractInfoOf::::get(addr) + &pallet_contracts::ContractInfoOf::::get(addr) .and_then(|c| c.get_alive()) .unwrap() .code_hash, @@ -842,14 +841,14 @@ mod tests { fn panic_execution_gives_error() { let mut t = TestExternalities::::new_with_code(BLOATY_CODE, Storage { top: map![ - >::hashed_key_for(alice()) => { + >::hashed_key_for(alice()) => { 0_u128.encode() }, - >::hashed_key().to_vec() => { + >::hashed_key().to_vec() => { 0_u128.encode() }, - >::hashed_key().to_vec() => vec![0u8; 16], - >::hashed_key_for(0) => vec![0u8; 32] + >::hashed_key().to_vec() => vec![0u8; 16], + >::hashed_key_for(0) => vec![0u8; 32] ], children: map![], }); @@ -877,14 +876,14 @@ mod tests { fn successful_execution_gives_ok() { let mut t = TestExternalities::::new_with_code(COMPACT_CODE, Storage { top: map![ - >::hashed_key_for(alice()) => { + >::hashed_key_for(alice()) => { (111 * DOLLARS).encode() }, - >::hashed_key().to_vec() => { + >::hashed_key().to_vec() => { (111 * DOLLARS).encode() }, - >::hashed_key().to_vec() => vec![0u8; 16], - >::hashed_key_for(0) => vec![0u8; 32] + >::hashed_key().to_vec() => vec![0u8; 16], + >::hashed_key_for(0) => vec![0u8; 32] ], children: map![], }); @@ -952,7 +951,9 @@ mod tests { #[test] fn should_import_block_with_test_client() { - use node_testing::client::{ClientExt, TestClientBuilderExt, TestClientBuilder, consensus::BlockOrigin}; + use node_testing::client::{ + ClientExt, TestClientBuilderExt, TestClientBuilder, sp_consensus::BlockOrigin + }; let client = TestClientBuilder::new().build(); let block1 = changes_trie_block(); @@ -984,11 +985,11 @@ mod tests { vec![ CheckedExtrinsic { signed: None, - function: Call::Timestamp(timestamp::Call::set(42 * 1000)), + function: Call::Timestamp(pallet_timestamp::Call::set(42 * 1000)), }, CheckedExtrinsic { signed: Some((charlie(), signed_extra(0, 0))), - function: Call::System(system::Call::fill_block()), + function: Call::System(frame_system::Call::fill_block()), } ] ); @@ -1001,11 +1002,11 @@ mod tests { vec![ CheckedExtrinsic { signed: None, - function: Call::Timestamp(timestamp::Call::set(52 * 1000)), + function: Call::Timestamp(pallet_timestamp::Call::set(52 * 1000)), }, CheckedExtrinsic { signed: Some((charlie(), signed_extra(1, 0))), - function: Call::System(system::Call::remark(vec![0; 1])), + function: Call::System(frame_system::Call::remark(vec![0; 1])), } ] ); @@ -1057,17 +1058,17 @@ mod tests { // (this baed on assigning 0.1 CENT to the cheapest tx with `weight = 100`) let mut t = TestExternalities::::new_with_code(COMPACT_CODE, Storage { top: map![ - >::hashed_key_for(alice()) => { + >::hashed_key_for(alice()) => { (100 * DOLLARS).encode() }, - >::hashed_key_for(bob()) => { + >::hashed_key_for(bob()) => { (10 * DOLLARS).encode() }, - >::hashed_key().to_vec() => { + >::hashed_key().to_vec() => { (110 * DOLLARS).encode() }, - >::hashed_key().to_vec() => vec![0u8; 16], - >::hashed_key_for(0) => vec![0u8; 32] + >::hashed_key().to_vec() => vec![0u8; 16], + >::hashed_key_for(0) => vec![0u8; 32] ], children: map![], }); @@ -1147,12 +1148,12 @@ mod tests { let num_transfers = block_number * factor; let mut xts = (0..num_transfers).map(|i| CheckedExtrinsic { signed: Some((charlie(), signed_extra(nonce + i as Index, 0))), - function: Call::Balances(balances::Call::transfer(bob().into(), 0)), + function: Call::Balances(pallet_balances::Call::transfer(bob().into(), 0)), }).collect::>(); xts.insert(0, CheckedExtrinsic { signed: None, - function: Call::Timestamp(timestamp::Call::set(time * 1000)), + function: Call::Timestamp(pallet_timestamp::Call::set(time * 1000)), }); // NOTE: this is super slow. Can probably be improved. @@ -1219,11 +1220,11 @@ mod tests { vec![ CheckedExtrinsic { signed: None, - function: Call::Timestamp(timestamp::Call::set(time * 1000)), + function: Call::Timestamp(pallet_timestamp::Call::set(time * 1000)), }, CheckedExtrinsic { signed: Some((charlie(), signed_extra(nonce, 0))), - function: Call::System(system::Call::remark(vec![0u8; (block_number * factor) as usize])), + function: Call::System(frame_system::Call::remark(vec![0u8; (block_number * factor) as usize])), }, ] ); diff --git a/substrate/bin/node/primitives/Cargo.toml b/substrate/bin/node/primitives/Cargo.toml index 7141dbbbca..956a346d2e 100644 --- a/substrate/bin/node/primitives/Cargo.toml +++ b/substrate/bin/node/primitives/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -primitives = { package = "sp-core", path = "../../../primitives/core", default-features = false } +sp-core = { path = "../../../primitives/core", default-features = false } sp-runtime = { path = "../../../primitives/runtime", default-features = false } [dev-dependencies] @@ -15,6 +15,6 @@ pretty_assertions = "0.6.1" [features] default = ["std"] std = [ - "primitives/std", + "sp-core/std", "sp-runtime/std", ] diff --git a/substrate/bin/node/primitives/src/lib.rs b/substrate/bin/node/primitives/src/lib.rs index eeb03a1b9b..9cd9c047c9 100644 --- a/substrate/bin/node/primitives/src/lib.rs +++ b/substrate/bin/node/primitives/src/lib.rs @@ -47,7 +47,7 @@ pub type Moment = u64; pub type Index = u32; /// A hash of some data used by the chain. -pub type Hash = primitives::H256; +pub type Hash = sp_core::H256; /// A timestamp: milliseconds since the unix epoch. /// `u64` is enough to represent a duration of half a billion years, when the diff --git a/substrate/bin/node/rpc/Cargo.toml b/substrate/bin/node/rpc/Cargo.toml index 2aead3b969..7b8f8a6cc3 100644 --- a/substrate/bin/node/rpc/Cargo.toml +++ b/substrate/bin/node/rpc/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -client = { package = "sc-client", path = "../../../client/" } +sc-client = { path = "../../../client/" } jsonrpc-core = "14.0.3" node-primitives = { path = "../primitives" } node-runtime = { path = "../runtime" } @@ -13,4 +13,4 @@ sp-runtime = { path = "../../../primitives/runtime" } pallet-contracts-rpc = { path = "../../../frame/contracts/rpc/" } pallet-transaction-payment-rpc = { path = "../../../frame/transaction-payment/rpc/" } substrate-frame-rpc-system = { path = "../../../utils/frame/rpc/system" } -txpool-api = { package = "sp-transaction-pool", path = "../../../primitives/transaction-pool" } +sp-transaction-pool = { path = "../../../primitives/transaction-pool" } diff --git a/substrate/bin/node/rpc/src/lib.rs b/substrate/bin/node/rpc/src/lib.rs index 718250d1d4..67a349598f 100644 --- a/substrate/bin/node/rpc/src/lib.rs +++ b/substrate/bin/node/rpc/src/lib.rs @@ -34,12 +34,12 @@ use std::sync::Arc; use node_primitives::{Block, AccountId, Index, Balance}; use node_runtime::UncheckedExtrinsic; use sp_runtime::traits::ProvideRuntimeApi; -use txpool_api::TransactionPool; +use sp_transaction_pool::TransactionPool; /// Light client extra dependencies. pub struct LightDeps { /// Remote access to the blockchain (async). - pub remote_blockchain: Arc>, + pub remote_blockchain: Arc>, /// Fetcher instance. pub fetcher: Arc, } @@ -63,12 +63,12 @@ pub fn create( light_deps: Option>, ) -> jsonrpc_core::IoHandler where C: ProvideRuntimeApi, - C: client::blockchain::HeaderBackend, + C: sc_client::blockchain::HeaderBackend, C: Send + Sync + 'static, C::Api: substrate_frame_rpc_system::AccountNonceApi, C::Api: pallet_contracts_rpc::ContractsRuntimeApi, C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, - F: client::light::fetcher::Fetcher + 'static, + F: sc_client::light::fetcher::Fetcher + 'static, P: TransactionPool + 'static, M: jsonrpc_core::Metadata + Default, { diff --git a/substrate/bin/node/runtime/Cargo.toml b/substrate/bin/node/runtime/Cargo.toml index 1cc4fc831b..b8d669784d 100644 --- a/substrate/bin/node/runtime/Cargo.toml +++ b/substrate/bin/node/runtime/Cargo.toml @@ -14,53 +14,53 @@ rustc-hex = { version = "2.0", optional = true } serde = { version = "1.0.102", optional = true } # primitives -authority-discovery-primitives = { package = "sp-authority-discovery", path = "../../../primitives/authority-discovery", default-features = false } -babe-primitives = { package = "sp-consensus-babe", path = "../../../primitives/consensus/babe", default-features = false } -block-builder-api = { package = "sp-block-builder", path = "../../../primitives/block-builder", default-features = false} -inherents = { package = "sp-inherents", path = "../../../primitives/inherents", default-features = false } +sp-authority-discovery = { path = "../../../primitives/authority-discovery", default-features = false } +sp-consensus-babe = { path = "../../../primitives/consensus/babe", default-features = false } +sp-block-builder = { path = "../../../primitives/block-builder", default-features = false} +sp-inherents = { path = "../../../primitives/inherents", default-features = false } node-primitives = { path = "../primitives", default-features = false } -offchain-primitives = { package = "sp-offchain", path = "../../../primitives/offchain", default-features = false } -primitives = { package = "sp-core", path = "../../../primitives/core", default-features = false } +sp-offchain = { path = "../../../primitives/offchain", default-features = false } +sp-core = { path = "../../../primitives/core", default-features = false } sp-std = { path = "../../../primitives/std", default-features = false } sp-api = { path = "../../../primitives/api", default-features = false } sp-runtime = { path = "../../../primitives/runtime", default-features = false } sp-staking = { path = "../../../primitives/staking", default-features = false } sp-keyring = { path = "../../../primitives/keyring", optional = true } sp-session = { path = "../../../primitives/session", default-features = false } -sp-transaction-pool = { package = "sp-transaction-pool", path = "../../../primitives/transaction-pool", default-features = false } -version = { package = "sp-version", path = "../../../primitives/version", default-features = false } +sp-transaction-pool = { path = "../../../primitives/transaction-pool", default-features = false } +sp-version = { path = "../../../primitives/version", default-features = false } # frame dependencies -authority-discovery = { package = "pallet-authority-discovery", path = "../../../frame/authority-discovery", default-features = false } -authorship = { package = "pallet-authorship", path = "../../../frame/authorship", default-features = false } -babe = { package = "pallet-babe", path = "../../../frame/babe", default-features = false } -balances = { package = "pallet-balances", path = "../../../frame/balances", default-features = false } -collective = { package = "pallet-collective", path = "../../../frame/collective", default-features = false } -contracts = { package = "pallet-contracts", path = "../../../frame/contracts", default-features = false } -contracts-rpc-runtime-api = { package = "pallet-contracts-rpc-runtime-api", path = "../../../frame/contracts/rpc/runtime-api/", default-features = false } -democracy = { package = "pallet-democracy", path = "../../../frame/democracy", default-features = false } -elections-phragmen = { package = "pallet-elections-phragmen", path = "../../../frame/elections-phragmen", default-features = false } -executive = { package = "frame-executive", path = "../../../frame/executive", default-features = false } -finality-tracker = { package = "pallet-finality-tracker", path = "../../../frame/finality-tracker", default-features = false } -grandpa = { package = "pallet-grandpa", path = "../../../frame/grandpa", default-features = false } -im-online = { package = "pallet-im-online", path = "../../../frame/im-online", default-features = false } -indices = { package = "pallet-indices", path = "../../../frame/indices", default-features = false } -membership = { package = "pallet-membership", path = "../../../frame/membership", default-features = false } -nicks = { package = "pallet-nicks", path = "../../../frame/nicks", default-features = false } -offences = { package = "pallet-offences", path = "../../../frame/offences", default-features = false } -randomness-collective-flip = { package = "pallet-randomness-collective-flip", path = "../../../frame/randomness-collective-flip", default-features = false } -session = { package = "pallet-session", path = "../../../frame/session", default-features = false, features = ["historical"] } -staking = { package = "pallet-staking", path = "../../../frame/staking", default-features = false, features = ["migrate"] } +pallet-authority-discovery = { path = "../../../frame/authority-discovery", default-features = false } +pallet-authorship = { path = "../../../frame/authorship", default-features = false } +pallet-babe = { path = "../../../frame/babe", default-features = false } +pallet-balances = { path = "../../../frame/balances", default-features = false } +pallet-collective = { path = "../../../frame/collective", default-features = false } +pallet-contracts = { path = "../../../frame/contracts", default-features = false } +pallet-contracts-rpc-runtime-api = { path = "../../../frame/contracts/rpc/runtime-api/", default-features = false } +pallet-democracy = { path = "../../../frame/democracy", default-features = false } +pallet-elections-phragmen = { path = "../../../frame/elections-phragmen", default-features = false } +frame-executive = { path = "../../../frame/executive", default-features = false } +pallet-finality-tracker = { path = "../../../frame/finality-tracker", default-features = false } +pallet-grandpa = { path = "../../../frame/grandpa", default-features = false } +pallet-im-online = { path = "../../../frame/im-online", default-features = false } +pallet-indices = { path = "../../../frame/indices", default-features = false } +pallet-membership = { path = "../../../frame/membership", default-features = false } +pallet-nicks = { path = "../../../frame/nicks", default-features = false } +pallet-offences = { path = "../../../frame/offences", default-features = false } +pallet-randomness-collective-flip = { path = "../../../frame/randomness-collective-flip", default-features = false } +pallet-session = { path = "../../../frame/session", default-features = false, features = ["historical"] } +pallet-staking = { path = "../../../frame/staking", default-features = false, features = ["migrate"] } pallet-staking-reward-curve = { path = "../../../frame/staking/reward-curve"} -sudo = { package = "pallet-sudo", path = "../../../frame/sudo", default-features = false } -support = { package = "frame-support", path = "../../../frame/support", default-features = false } -system = { package = "frame-system", path = "../../../frame/system", default-features = false } -system-rpc-runtime-api = { package = "frame-system-rpc-runtime-api", path = "../../../frame/system/rpc/runtime-api/", default-features = false } -timestamp = { package = "pallet-timestamp", path = "../../../frame/timestamp", default-features = false } -treasury = { package = "pallet-treasury", path = "../../../frame/treasury", default-features = false } -utility = { package = "frame-utility", path = "../../../frame/utility", default-features = false } -transaction-payment = { package = "pallet-transaction-payment", path = "../../../frame/transaction-payment", default-features = false } -transaction-payment-rpc-runtime-api = { package = "pallet-transaction-payment-rpc-runtime-api", path = "../../../frame/transaction-payment/rpc/runtime-api/", default-features = false } +pallet-sudo = { path = "../../../frame/sudo", default-features = false } +frame-support = { path = "../../../frame/support", default-features = false } +frame-system = { path = "../../../frame/system", default-features = false } +frame-system-rpc-runtime-api = { path = "../../../frame/system/rpc/runtime-api/", default-features = false } +pallet-timestamp = { path = "../../../frame/timestamp", default-features = false } +pallet-treasury = { path = "../../../frame/treasury", default-features = false } +frame-utility = { path = "../../../frame/utility", default-features = false } +pallet-transaction-payment = { path = "../../../frame/transaction-payment", default-features = false } +pallet-transaction-payment-rpc-runtime-api = { path = "../../../frame/transaction-payment/rpc/runtime-api/", default-features = false } [build-dependencies] wasm-builder-runner = { package = "substrate-wasm-builder-runner", path = "../../../utils/wasm-builder-runner", version = "1.0.4" } @@ -71,52 +71,52 @@ sp-io = { path = "../../../primitives/io" } [features] default = ["std"] std = [ - "authority-discovery-primitives/std", - "authority-discovery/std", - "authorship/std", - "babe-primitives/std", - "babe/std", - "balances/std", - "block-builder-api/std", + "sp-authority-discovery/std", + "pallet-authority-discovery/std", + "pallet-authorship/std", + "sp-consensus-babe/std", + "pallet-babe/std", + "pallet-balances/std", + "sp-block-builder/std", "codec/std", - "collective/std", - "contracts-rpc-runtime-api/std", - "contracts/std", - "democracy/std", - "elections-phragmen/std", - "executive/std", - "finality-tracker/std", - "grandpa/std", - "im-online/std", - "indices/std", - "inherents/std", - "membership/std", - "nicks/std", + "pallet-collective/std", + "pallet-contracts-rpc-runtime-api/std", + "pallet-contracts/std", + "pallet-democracy/std", + "pallet-elections-phragmen/std", + "frame-executive/std", + "pallet-finality-tracker/std", + "pallet-grandpa/std", + "pallet-im-online/std", + "pallet-indices/std", + "sp-inherents/std", + "pallet-membership/std", + "pallet-nicks/std", "node-primitives/std", - "offchain-primitives/std", - "offences/std", - "primitives/std", - "randomness-collective-flip/std", + "sp-offchain/std", + "pallet-offences/std", + "sp-core/std", + "pallet-randomness-collective-flip/std", "sp-std/std", "rustc-hex", "safe-mix/std", "serde", - "session/std", + "pallet-session/std", "sp-api/std", "sp-runtime/std", "sp-staking/std", - "staking/std", + "pallet-staking/std", "sp-keyring", "sp-session/std", - "sudo/std", - "support/std", - "system-rpc-runtime-api/std", - "system/std", - "timestamp/std", - "transaction-payment-rpc-runtime-api/std", - "transaction-payment/std", - "treasury/std", + "pallet-sudo/std", + "frame-support/std", + "frame-system-rpc-runtime-api/std", + "frame-system/std", + "pallet-timestamp/std", + "pallet-transaction-payment-rpc-runtime-api/std", + "pallet-transaction-payment/std", + "pallet-treasury/std", "sp-transaction-pool/std", - "utility/std", - "version/std", + "frame-utility/std", + "sp-version/std", ] diff --git a/substrate/bin/node/runtime/src/impls.rs b/substrate/bin/node/runtime/src/impls.rs index 3d034a2fb1..75aba8b707 100644 --- a/substrate/bin/node/runtime/src/impls.rs +++ b/substrate/bin/node/runtime/src/impls.rs @@ -19,7 +19,7 @@ use node_primitives::Balance; use sp_runtime::traits::{Convert, Saturating}; use sp_runtime::{Fixed64, Perbill}; -use support::{traits::{OnUnbalanced, Currency, Get}, weights::Weight}; +use frame_support::{traits::{OnUnbalanced, Currency, Get}, weights::Weight}; use crate::{Balances, System, Authorship, MaximumBlockWeight, NegativeImbalance}; pub struct Author; @@ -118,7 +118,7 @@ mod tests { use sp_runtime::assert_eq_error_rate; use crate::{MaximumBlockWeight, AvailableBlockRatio, Runtime}; use crate::{constants::currency::*, TransactionPayment, TargetBlockFullness}; - use support::weights::Weight; + use frame_support::weights::Weight; fn max() -> Weight { MaximumBlockWeight::get() @@ -151,7 +151,7 @@ mod tests { fn run_with_system_weight(w: Weight, assertions: F) where F: Fn() -> () { let mut t: sp_io::TestExternalities = - system::GenesisConfig::default().build_storage::().unwrap().into(); + frame_system::GenesisConfig::default().build_storage::().unwrap().into(); t.execute_with(|| { System::set_block_limits(w, 0); assertions() @@ -227,7 +227,7 @@ mod tests { if fm == next { panic!("The fee should ever increase"); } fm = next; iterations += 1; - let fee = ::WeightToFee::convert(tx_weight); + let fee = ::WeightToFee::convert(tx_weight); let adjusted_fee = fm.saturated_multiply_accumulate(fee); println!( "iteration {}, new fm = {:?}. Fee at this point is: {} units / {} millicents, \ diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index e78e873142..fbf765fee5 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -21,12 +21,12 @@ #![recursion_limit="256"] use sp_std::prelude::*; -use support::{ +use frame_support::{ construct_runtime, parameter_types, weights::Weight, traits::{SplitTwoWays, Currency, Randomness}, }; -use primitives::u32_trait::{_1, _2, _3, _4}; +use sp_core::u32_trait::{_1, _2, _3, _4}; use node_primitives::{AccountId, AccountIndex, Balance, BlockNumber, Hash, Index, Moment, Signature}; use sp_api::impl_runtime_apis; use sp_runtime::{Permill, Perbill, ApplyExtrinsicResult, impl_opaque_keys, generic, create_runtime_str}; @@ -36,26 +36,26 @@ use sp_runtime::traits::{ self, BlakeTwo256, Block as BlockT, NumberFor, StaticLookup, SaturatedConversion, OpaqueKeys, }; -use version::RuntimeVersion; +use sp_version::RuntimeVersion; #[cfg(any(feature = "std", test))] -use version::NativeVersion; -use primitives::OpaqueMetadata; -use grandpa::AuthorityList as GrandpaAuthorityList; -use grandpa::fg_primitives; -use im_online::sr25519::{AuthorityId as ImOnlineId}; -use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId; -use transaction_payment_rpc_runtime_api::RuntimeDispatchInfo; -use contracts_rpc_runtime_api::ContractExecResult; -use system::offchain::TransactionSubmitter; -use inherents::{InherentData, CheckInherentsResult}; +use sp_version::NativeVersion; +use sp_core::OpaqueMetadata; +use pallet_grandpa::AuthorityList as GrandpaAuthorityList; +use pallet_grandpa::fg_primitives; +use pallet_im_online::sr25519::{AuthorityId as ImOnlineId}; +use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId; +use pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo; +use pallet_contracts_rpc_runtime_api::ContractExecResult; +use frame_system::offchain::TransactionSubmitter; +use sp_inherents::{InherentData, CheckInherentsResult}; #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; -pub use timestamp::Call as TimestampCall; -pub use balances::Call as BalancesCall; -pub use contracts::Gas; -pub use support::StorageValue; -pub use staking::StakerStatus; +pub use pallet_timestamp::Call as TimestampCall; +pub use pallet_balances::Call as BalancesCall; +pub use pallet_contracts::Gas; +pub use frame_support::StorageValue; +pub use pallet_staking::StakerStatus; /// Implementations of some helper traits passed into runtime modules as associated types. pub mod impls; @@ -109,7 +109,7 @@ parameter_types! { pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); } -impl system::Trait for Runtime { +impl frame_system::Trait for Runtime { type Origin = Origin; type Call = Call; type Index = Index; @@ -127,7 +127,7 @@ impl system::Trait for Runtime { type Version = Version; } -impl utility::Trait for Runtime { +impl frame_utility::Trait for Runtime { type Event = Event; type Call = Call; } @@ -137,16 +137,16 @@ parameter_types! { pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK; } -impl babe::Trait for Runtime { +impl pallet_babe::Trait for Runtime { type EpochDuration = EpochDuration; type ExpectedBlockTime = ExpectedBlockTime; - type EpochChangeTrigger = babe::ExternalTrigger; + type EpochChangeTrigger = pallet_babe::ExternalTrigger; } -impl indices::Trait for Runtime { +impl pallet_indices::Trait for Runtime { type AccountIndex = AccountIndex; type IsDeadAccount = Balances; - type ResolveHint = indices::SimpleResolveHint; + type ResolveHint = pallet_indices::SimpleResolveHint; type Event = Event; } @@ -156,7 +156,7 @@ parameter_types! { pub const CreationFee: Balance = 1 * CENTS; } -impl balances::Trait for Runtime { +impl pallet_balances::Trait for Runtime { type Balance = Balance; type OnFreeBalanceZero = ((Staking, Contracts), Session); type OnNewAccount = Indices; @@ -177,7 +177,7 @@ parameter_types! { pub const TargetBlockFullness: Perbill = Perbill::from_percent(25); } -impl transaction_payment::Trait for Runtime { +impl pallet_transaction_payment::Trait for Runtime { type Currency = Balances; type OnTransactionPayment = DealWithFees; type TransactionBaseFee = TransactionBaseFee; @@ -189,7 +189,7 @@ impl transaction_payment::Trait for Runtime { parameter_types! { pub const MinimumPeriod: Moment = SLOT_DURATION / 2; } -impl timestamp::Trait for Runtime { +impl pallet_timestamp::Trait for Runtime { type Moment = Moment; type OnTimestampSet = Babe; type MinimumPeriod = MinimumPeriod; @@ -199,8 +199,8 @@ parameter_types! { pub const UncleGenerations: BlockNumber = 5; } -impl authorship::Trait for Runtime { - type FindAuthor = session::FindAccountFromAuthorIndex; +impl pallet_authorship::Trait for Runtime { + type FindAuthor = pallet_session::FindAccountFromAuthorIndex; type UncleGenerations = UncleGenerations; type FilterUncle = (); type EventHandler = (Staking, ImOnline); @@ -219,21 +219,21 @@ parameter_types! { pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17); } -impl session::Trait for Runtime { +impl pallet_session::Trait for Runtime { type OnSessionEnding = Staking; type SessionHandler = ::KeyTypeIdProviders; type ShouldEndSession = Babe; type Event = Event; type Keys = SessionKeys; - type ValidatorId = ::AccountId; - type ValidatorIdOf = staking::StashOf; + type ValidatorId = ::AccountId; + type ValidatorIdOf = pallet_staking::StashOf; type SelectInitialValidators = Staking; type DisabledValidatorsThreshold = DisabledValidatorsThreshold; } -impl session::historical::Trait for Runtime { - type FullIdentification = staking::Exposure; - type FullIdentificationOf = staking::ExposureOf; +impl pallet_session::historical::Trait for Runtime { + type FullIdentification = pallet_staking::Exposure; + type FullIdentificationOf = pallet_staking::ExposureOf; } pallet_staking_reward_curve::build! { @@ -249,12 +249,12 @@ pallet_staking_reward_curve::build! { parameter_types! { pub const SessionsPerEra: sp_staking::SessionIndex = 6; - pub const BondingDuration: staking::EraIndex = 24 * 28; - pub const SlashDeferDuration: staking::EraIndex = 24 * 7; // 1/4 the bonding duration. + pub const BondingDuration: pallet_staking::EraIndex = 24 * 28; + pub const SlashDeferDuration: pallet_staking::EraIndex = 24 * 7; // 1/4 the bonding duration. pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE; } -impl staking::Trait for Runtime { +impl pallet_staking::Trait for Runtime { type Currency = Balances; type Time = Timestamp; type CurrencyToVote = CurrencyToVoteHandler; @@ -266,7 +266,7 @@ impl staking::Trait for Runtime { type BondingDuration = BondingDuration; type SlashDeferDuration = SlashDeferDuration; /// A super-majority of the council can cancel the slash. - type SlashCancelOrigin = collective::EnsureProportionAtLeast<_3, _4, AccountId, CouncilCollective>; + type SlashCancelOrigin = pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, CouncilCollective>; type SessionInterface = Self; type RewardCurve = RewardCurve; } @@ -282,7 +282,7 @@ parameter_types! { pub const PreimageByteDeposit: Balance = 1 * CENTS; } -impl democracy::Trait for Runtime { +impl pallet_democracy::Trait for Runtime { type Proposal = Call; type Event = Event; type Currency = Balances; @@ -292,27 +292,27 @@ impl democracy::Trait for Runtime { type EmergencyVotingPeriod = EmergencyVotingPeriod; type MinimumDeposit = MinimumDeposit; /// A straight majority of the council can decide what their next motion is. - type ExternalOrigin = collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>; + type ExternalOrigin = pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>; /// A super-majority can have the next scheduled referendum be a straight majority-carries vote. - type ExternalMajorityOrigin = collective::EnsureProportionAtLeast<_3, _4, AccountId, CouncilCollective>; + type ExternalMajorityOrigin = pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, CouncilCollective>; /// A unanimous council can have the next scheduled referendum be a straight default-carries /// (NTB) vote. - type ExternalDefaultOrigin = collective::EnsureProportionAtLeast<_1, _1, AccountId, CouncilCollective>; + type ExternalDefaultOrigin = pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, CouncilCollective>; /// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote /// be tabled immediately and with a shorter voting/enactment period. - type FastTrackOrigin = collective::EnsureProportionAtLeast<_2, _3, AccountId, TechnicalCollective>; + type FastTrackOrigin = pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, TechnicalCollective>; // To cancel a proposal which has been passed, 2/3 of the council must agree to it. - type CancellationOrigin = collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>; + type CancellationOrigin = pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>; // Any single technical committee member may veto a coming council proposal, however they can // only do it once and it lasts only for the cooloff period. - type VetoOrigin = collective::EnsureMember; + type VetoOrigin = pallet_collective::EnsureMember; type CooloffPeriod = CooloffPeriod; type PreimageByteDeposit = PreimageByteDeposit; type Slash = Treasury; } -type CouncilCollective = collective::Instance1; -impl collective::Trait for Runtime { +type CouncilCollective = pallet_collective::Instance1; +impl pallet_collective::Trait for Runtime { type Origin = Origin; type Proposal = Call; type Event = Event; @@ -326,7 +326,7 @@ parameter_types! { pub const DesiredRunnersUp: u32 = 7; } -impl elections_phragmen::Trait for Runtime { +impl pallet_elections_phragmen::Trait for Runtime { type Event = Event; type Currency = Balances; type CurrencyToVote = CurrencyToVoteHandler; @@ -341,19 +341,19 @@ impl elections_phragmen::Trait for Runtime { type ChangeMembers = Council; } -type TechnicalCollective = collective::Instance2; -impl collective::Trait for Runtime { +type TechnicalCollective = pallet_collective::Instance2; +impl pallet_collective::Trait for Runtime { type Origin = Origin; type Proposal = Call; type Event = Event; } -impl membership::Trait for Runtime { +impl pallet_membership::Trait for Runtime { type Event = Event; - type AddOrigin = collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>; - type RemoveOrigin = collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>; - type SwapOrigin = collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>; - type ResetOrigin = collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>; + type AddOrigin = pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>; + type RemoveOrigin = pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>; + type SwapOrigin = pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>; + type ResetOrigin = pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>; type MembershipInitialized = TechnicalCommittee; type MembershipChanged = TechnicalCommittee; } @@ -365,10 +365,10 @@ parameter_types! { pub const Burn: Permill = Permill::from_percent(50); } -impl treasury::Trait for Runtime { +impl pallet_treasury::Trait for Runtime { type Currency = Balances; - type ApproveOrigin = collective::EnsureMembers<_4, AccountId, CouncilCollective>; - type RejectOrigin = collective::EnsureMembers<_2, AccountId, CouncilCollective>; + type ApproveOrigin = pallet_collective::EnsureMembers<_4, AccountId, CouncilCollective>; + type RejectOrigin = pallet_collective::EnsureMembers<_2, AccountId, CouncilCollective>; type Event = Event; type ProposalRejection = (); type ProposalBond = ProposalBond; @@ -389,20 +389,20 @@ parameter_types! { pub const SurchargeReward: Balance = 150 * DOLLARS; } -impl contracts::Trait for Runtime { +impl pallet_contracts::Trait for Runtime { type Currency = Balances; type Time = Timestamp; type Randomness = RandomnessCollectiveFlip; type Call = Call; type Event = Event; - type DetermineContractAddress = contracts::SimpleAddressDeterminator; - type ComputeDispatchFee = contracts::DefaultDispatchFeeComputor; - type TrieIdGenerator = contracts::TrieIdFromParentCounter; + type DetermineContractAddress = pallet_contracts::SimpleAddressDeterminator; + type ComputeDispatchFee = pallet_contracts::DefaultDispatchFeeComputor; + type TrieIdGenerator = pallet_contracts::TrieIdFromParentCounter; type GasPayment = (); type RentPayment = (); - type SignedClaimHandicap = contracts::DefaultSignedClaimHandicap; + type SignedClaimHandicap = pallet_contracts::DefaultSignedClaimHandicap; type TombstoneDeposit = TombstoneDeposit; - type StorageSizeOffset = contracts::DefaultStorageSizeOffset; + type StorageSizeOffset = pallet_contracts::DefaultStorageSizeOffset; type RentByteFee = RentByteFee; type RentDepositOffset = RentDepositOffset; type SurchargeReward = SurchargeReward; @@ -411,14 +411,14 @@ impl contracts::Trait for Runtime { type TransactionBaseFee = ContractTransactionBaseFee; type TransactionByteFee = ContractTransactionByteFee; type ContractFee = ContractFee; - type CallBaseFee = contracts::DefaultCallBaseFee; - type InstantiateBaseFee = contracts::DefaultInstantiateBaseFee; - type MaxDepth = contracts::DefaultMaxDepth; - type MaxValueSize = contracts::DefaultMaxValueSize; - type BlockGasLimit = contracts::DefaultBlockGasLimit; + type CallBaseFee = pallet_contracts::DefaultCallBaseFee; + type InstantiateBaseFee = pallet_contracts::DefaultInstantiateBaseFee; + type MaxDepth = pallet_contracts::DefaultMaxDepth; + type MaxValueSize = pallet_contracts::DefaultMaxValueSize; + type BlockGasLimit = pallet_contracts::DefaultBlockGasLimit; } -impl sudo::Trait for Runtime { +impl pallet_sudo::Trait for Runtime { type Event = Event; type Proposal = Call; } @@ -429,7 +429,7 @@ parameter_types! { pub const SessionDuration: BlockNumber = EPOCH_DURATION_IN_SLOTS as _; } -impl im_online::Trait for Runtime { +impl pallet_im_online::Trait for Runtime { type AuthorityId = ImOnlineId; type Call = Call; type Event = Event; @@ -438,15 +438,15 @@ impl im_online::Trait for Runtime { type SessionDuration = SessionDuration; } -impl offences::Trait for Runtime { +impl pallet_offences::Trait for Runtime { type Event = Event; - type IdentificationTuple = session::historical::IdentificationTuple; + type IdentificationTuple = pallet_session::historical::IdentificationTuple; type OnOffenceHandler = Staking; } -impl authority_discovery::Trait for Runtime {} +impl pallet_authority_discovery::Trait for Runtime {} -impl grandpa::Trait for Runtime { +impl pallet_grandpa::Trait for Runtime { type Event = Event; } @@ -455,7 +455,7 @@ parameter_types! { pub const ReportLatency: BlockNumber = 1000; } -impl finality_tracker::Trait for Runtime { +impl pallet_finality_tracker::Trait for Runtime { type OnFinalizationStalled = Grandpa; type WindowSize = WindowSize; type ReportLatency = ReportLatency; @@ -467,21 +467,21 @@ parameter_types! { pub const MaxLength: usize = 16; } -impl nicks::Trait for Runtime { +impl pallet_nicks::Trait for Runtime { type Event = Event; type Currency = Balances; type ReservationFee = ReservationFee; type Slashed = Treasury; - type ForceOrigin = collective::EnsureMember; + type ForceOrigin = pallet_collective::EnsureMember; type MinLength = MinLength; type MaxLength = MaxLength; } -impl system::offchain::CreateTransaction for Runtime { +impl frame_system::offchain::CreateTransaction for Runtime { type Public = ::Signer; type Signature = Signature; - fn create_transaction>( + fn create_transaction>( call: Call, public: Self::Public, account: AccountId, @@ -491,12 +491,12 @@ impl system::offchain::CreateTransaction for Runtim let current_block = System::block_number().saturated_into::(); let tip = 0; let extra: SignedExtra = ( - system::CheckVersion::::new(), - system::CheckGenesis::::new(), - system::CheckEra::::from(generic::Era::mortal(period, current_block)), - system::CheckNonce::::from(index), - system::CheckWeight::::new(), - transaction_payment::ChargeTransactionPayment::::from(tip), + frame_system::CheckVersion::::new(), + frame_system::CheckGenesis::::new(), + frame_system::CheckEra::::from(generic::Era::mortal(period, current_block)), + frame_system::CheckNonce::::from(index), + frame_system::CheckWeight::::new(), + pallet_transaction_payment::ChargeTransactionPayment::::from(tip), Default::default(), ); let raw_payload = SignedPayload::new(call, extra).ok()?; @@ -507,6 +507,7 @@ impl system::offchain::CreateTransaction for Runtim } } +use frame_system as system; construct_runtime!( pub enum Runtime where Block = Block, @@ -514,30 +515,30 @@ construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic { System: system::{Module, Call, Storage, Config, Event}, - Utility: utility::{Module, Call, Event}, - Babe: babe::{Module, Call, Storage, Config, Inherent(Timestamp)}, - Timestamp: timestamp::{Module, Call, Storage, Inherent}, - Authorship: authorship::{Module, Call, Storage, Inherent}, - Indices: indices, - Balances: balances::{default, Error}, - TransactionPayment: transaction_payment::{Module, Storage}, - Staking: staking::{default, OfflineWorker}, - Session: session::{Module, Call, Storage, Event, Config}, - Democracy: democracy::{Module, Call, Storage, Config, Event}, - Council: collective::::{Module, Call, Storage, Origin, Event, Config}, - TechnicalCommittee: collective::::{Module, Call, Storage, Origin, Event, Config}, - Elections: elections_phragmen::{Module, Call, Storage, Event}, - TechnicalMembership: membership::::{Module, Call, Storage, Event, Config}, - FinalityTracker: finality_tracker::{Module, Call, Inherent}, - Grandpa: grandpa::{Module, Call, Storage, Config, Event}, - Treasury: treasury::{Module, Call, Storage, Config, Event}, - Contracts: contracts, - Sudo: sudo, - ImOnline: im_online::{Module, Call, Storage, Event, ValidateUnsigned, Config}, - AuthorityDiscovery: authority_discovery::{Module, Call, Config}, - Offences: offences::{Module, Call, Storage, Event}, - RandomnessCollectiveFlip: randomness_collective_flip::{Module, Call, Storage}, - Nicks: nicks::{Module, Call, Storage, Event}, + Utility: frame_utility::{Module, Call, Event}, + Babe: pallet_babe::{Module, Call, Storage, Config, Inherent(Timestamp)}, + Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent}, + Authorship: pallet_authorship::{Module, Call, Storage, Inherent}, + Indices: pallet_indices, + Balances: pallet_balances::{default, Error}, + TransactionPayment: pallet_transaction_payment::{Module, Storage}, + Staking: pallet_staking::{default, OfflineWorker}, + Session: pallet_session::{Module, Call, Storage, Event, Config}, + Democracy: pallet_democracy::{Module, Call, Storage, Config, Event}, + Council: pallet_collective::::{Module, Call, Storage, Origin, Event, Config}, + TechnicalCommittee: pallet_collective::::{Module, Call, Storage, Origin, Event, Config}, + Elections: pallet_elections_phragmen::{Module, Call, Storage, Event}, + TechnicalMembership: pallet_membership::::{Module, Call, Storage, Event, Config}, + FinalityTracker: pallet_finality_tracker::{Module, Call, Inherent}, + Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event}, + Treasury: pallet_treasury::{Module, Call, Storage, Config, Event}, + Contracts: pallet_contracts, + Sudo: pallet_sudo, + ImOnline: pallet_im_online::{Module, Call, Storage, Event, ValidateUnsigned, Config}, + AuthorityDiscovery: pallet_authority_discovery::{Module, Call, Config}, + Offences: pallet_offences::{Module, Call, Storage, Event}, + RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage}, + Nicks: pallet_nicks::{Module, Call, Storage, Event}, } ); @@ -553,13 +554,13 @@ pub type SignedBlock = generic::SignedBlock; pub type BlockId = generic::BlockId; /// The SignedExtension to the basic transaction logic. pub type SignedExtra = ( - system::CheckVersion, - system::CheckGenesis, - system::CheckEra, - system::CheckNonce, - system::CheckWeight, - transaction_payment::ChargeTransactionPayment, - contracts::CheckBlockGasLimit, + frame_system::CheckVersion, + frame_system::CheckGenesis, + frame_system::CheckEra, + frame_system::CheckNonce, + frame_system::CheckWeight, + pallet_transaction_payment::ChargeTransactionPayment, + pallet_contracts::CheckBlockGasLimit, ); /// Unchecked extrinsic type as expected by this runtime. pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; @@ -568,7 +569,7 @@ pub type SignedPayload = generic::SignedPayload; /// Extrinsic type that has already been checked. pub type CheckedExtrinsic = generic::CheckedExtrinsic; /// Executive: handles dispatch to the various modules. -pub type Executive = executive::Executive, Runtime, AllModules>; +pub type Executive = frame_executive::Executive, Runtime, AllModules>; impl_runtime_apis! { impl sp_api::Core for Runtime { @@ -591,7 +592,7 @@ impl_runtime_apis! { } } - impl block_builder_api::BlockBuilder for Runtime { + impl sp_block_builder::BlockBuilder for Runtime { fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { Executive::apply_extrinsic(extrinsic) } @@ -619,7 +620,7 @@ impl_runtime_apis! { } } - impl offchain_primitives::OffchainWorkerApi for Runtime { + impl sp_offchain::OffchainWorkerApi for Runtime { fn offchain_worker(number: NumberFor) { Executive::offchain_worker(number) } @@ -631,14 +632,14 @@ impl_runtime_apis! { } } - impl babe_primitives::BabeApi for Runtime { - fn configuration() -> babe_primitives::BabeConfiguration { + impl sp_consensus_babe::BabeApi for Runtime { + fn configuration() -> sp_consensus_babe::BabeConfiguration { // The choice of `c` parameter (where `1 - c` represents the // probability of a slot being empty), is done in accordance to the // slot duration and expected target block time, for safely // resisting network delays of maximum two seconds. // - babe_primitives::BabeConfiguration { + sp_consensus_babe::BabeConfiguration { slot_duration: Babe::slot_duration(), epoch_length: EpochDuration::get(), c: PRIMARY_PROBABILITY, @@ -649,19 +650,19 @@ impl_runtime_apis! { } } - impl authority_discovery_primitives::AuthorityDiscoveryApi for Runtime { + impl sp_authority_discovery::AuthorityDiscoveryApi for Runtime { fn authorities() -> Vec { AuthorityDiscovery::authorities() } } - impl system_rpc_runtime_api::AccountNonceApi for Runtime { + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { fn account_nonce(account: AccountId) -> Index { System::account_nonce(account) } } - impl contracts_rpc_runtime_api::ContractsApi for Runtime { + impl pallet_contracts_rpc_runtime_api::ContractsApi for Runtime { fn call( origin: AccountId, dest: AccountId, @@ -688,10 +689,10 @@ impl_runtime_apis! { fn get_storage( address: AccountId, key: [u8; 32], - ) -> contracts_rpc_runtime_api::GetStorageResult { + ) -> pallet_contracts_rpc_runtime_api::GetStorageResult { Contracts::get_storage(address, key).map_err(|rpc_err| { - use contracts::GetStorageError; - use contracts_rpc_runtime_api::{GetStorageError as RpcGetStorageError}; + use pallet_contracts::GetStorageError; + use pallet_contracts_rpc_runtime_api::{GetStorageError as RpcGetStorageError}; /// Map the contract error into the RPC layer error. match rpc_err { GetStorageError::ContractDoesntExist => RpcGetStorageError::ContractDoesntExist, @@ -701,7 +702,7 @@ impl_runtime_apis! { } } - impl transaction_payment_rpc_runtime_api::TransactionPaymentApi< + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi< Block, Balance, UncheckedExtrinsic, @@ -721,7 +722,7 @@ impl_runtime_apis! { #[cfg(test)] mod tests { use super::*; - use system::offchain::SubmitSignedTransaction; + use frame_system::offchain::SubmitSignedTransaction; fn is_submit_signed_transaction(_arg: T) where T: SubmitSignedTransaction< @@ -741,7 +742,7 @@ mod tests { #[test] fn block_hooks_weight_should_not_exceed_limits() { - use support::weights::WeighBlock; + use frame_support::weights::WeighBlock; let check_for_block = |b| { let block_hooks_weight = >::on_initialize(b) + diff --git a/substrate/bin/node/testing/Cargo.toml b/substrate/bin/node/testing/Cargo.toml index ce5aa78a5d..e23901d7f7 100644 --- a/substrate/bin/node/testing/Cargo.toml +++ b/substrate/bin/node/testing/Cargo.toml @@ -6,26 +6,26 @@ description = "Test utilities for Substrate node." edition = "2018" [dependencies] -balances = { package = "pallet-balances", path = "../../../frame/balances" } -client = { package = "sc-client", path = "../../../client/" } +pallet-balances = { path = "../../../frame/balances" } +sc-client = { path = "../../../client/" } codec = { package = "parity-scale-codec", version = "1.0.0" } -contracts = { package = "pallet-contracts", path = "../../../frame/contracts" } -grandpa = { package = "pallet-grandpa", path = "../../../frame/grandpa" } -indices = { package = "pallet-indices", path = "../../../frame/indices" } -keyring = { package = "sp-keyring", path = "../../../primitives/keyring" } +pallet-contracts = { path = "../../../frame/contracts" } +pallet-grandpa = { path = "../../../frame/grandpa" } +pallet-indices = { path = "../../../frame/indices" } +sp-keyring = { path = "../../../primitives/keyring" } node-executor = { path = "../executor" } node-primitives = { path = "../primitives" } node-runtime = { path = "../runtime" } -primitives = { package = "sp-core", path = "../../../primitives/core" } +sp-core = { path = "../../../primitives/core" } sp-io = { path = "../../../primitives/io" } -runtime_support = { package = "frame-support", path = "../../../frame/support" } -session = { package = "pallet-session", path = "../../../frame/session" } +frame-support = { path = "../../../frame/support" } +pallet-session = { path = "../../../frame/session" } sp-runtime = { path = "../../../primitives/runtime" } -staking = { package = "pallet-staking", path = "../../../frame/staking" } +pallet-staking = { path = "../../../frame/staking" } sc-executor = { path = "../../../client/executor" } -system = { package = "frame-system", path = "../../../frame/system" } -test-client = { package = "substrate-test-client", path = "../../../test-utils/client" } -timestamp = { package = "pallet-timestamp", path = "../../../frame/timestamp" } -transaction-payment = { package = "pallet-transaction-payment", path = "../../../frame/transaction-payment" } -treasury = { package = "pallet-treasury", path = "../../../frame/treasury" } +frame-system = { path = "../../../frame/system" } +substrate-test-client = { path = "../../../test-utils/client" } +pallet-timestamp = { path = "../../../frame/timestamp" } +pallet-transaction-payment = { path = "../../../frame/transaction-payment" } +pallet-treasury = { path = "../../../frame/treasury" } wabt = "0.9.2" diff --git a/substrate/bin/node/testing/src/client.rs b/substrate/bin/node/testing/src/client.rs index a6964b3915..4cd193a69e 100644 --- a/substrate/bin/node/testing/src/client.rs +++ b/substrate/bin/node/testing/src/client.rs @@ -19,18 +19,18 @@ use sp_runtime::BuildStorage; /// Re-export test-client utilities. -pub use test_client::*; +pub use substrate_test_client::*; /// Call executor for `node-runtime` `TestClient`. pub type Executor = sc_executor::NativeExecutor; /// Default backend type. -pub type Backend = client_db::Backend; +pub type Backend = sc_client_db::Backend; /// Test client type. -pub type Client = client::Client< +pub type Client = sc_client::Client< Backend, - client::LocalCallExecutor, + sc_client::LocalCallExecutor, node_primitives::Block, node_runtime::RuntimeApi, >; @@ -41,7 +41,7 @@ pub struct GenesisParameters { support_changes_trie: bool, } -impl test_client::GenesisInit for GenesisParameters { +impl substrate_test_client::GenesisInit for GenesisParameters { fn genesis_storage(&self) -> Storage { crate::genesis::config(self.support_changes_trie, None).build_storage().unwrap() } @@ -56,8 +56,8 @@ pub trait TestClientBuilderExt: Sized { fn build(self) -> Client; } -impl TestClientBuilderExt for test_client::TestClientBuilder< - client::LocalCallExecutor, +impl TestClientBuilderExt for substrate_test_client::TestClientBuilder< + sc_client::LocalCallExecutor, Backend, GenesisParameters, > { diff --git a/substrate/bin/node/testing/src/genesis.rs b/substrate/bin/node/testing/src/genesis.rs index dae5c2c4a4..feb9ed526f 100644 --- a/substrate/bin/node/testing/src/genesis.rs +++ b/substrate/bin/node/testing/src/genesis.rs @@ -17,13 +17,13 @@ //! Genesis Configuration. use crate::keyring::*; -use keyring::{Ed25519Keyring, Sr25519Keyring}; +use sp_keyring::{Ed25519Keyring, Sr25519Keyring}; use node_runtime::{ GenesisConfig, BalancesConfig, SessionConfig, StakingConfig, SystemConfig, GrandpaConfig, IndicesConfig, ContractsConfig, WASM_BINARY, }; use node_runtime::constants::currency::*; -use primitives::ChangesTrieConfiguration; +use sp_core::ChangesTrieConfiguration; use sp_runtime::Perbill; @@ -37,10 +37,10 @@ pub fn config(support_changes_trie: bool, code: Option<&[u8]>) -> GenesisConfig }) } else { None }, code: code.map(|x| x.to_vec()).unwrap_or_else(|| WASM_BINARY.to_vec()), }), - indices: Some(IndicesConfig { + pallet_indices: Some(IndicesConfig { ids: vec![alice(), bob(), charlie(), dave(), eve(), ferdie()], }), - balances: Some(BalancesConfig { + pallet_balances: Some(BalancesConfig { balances: vec![ (alice(), 111 * DOLLARS), (bob(), 100 * DOLLARS), @@ -51,7 +51,7 @@ pub fn config(support_changes_trie: bool, code: Option<&[u8]>) -> GenesisConfig ], vesting: vec![], }), - session: Some(SessionConfig { + pallet_session: Some(SessionConfig { keys: vec![ (alice(), to_session_keys( &Ed25519Keyring::Alice, @@ -67,12 +67,12 @@ pub fn config(support_changes_trie: bool, code: Option<&[u8]>) -> GenesisConfig )), ] }), - staking: Some(StakingConfig { + pallet_staking: Some(StakingConfig { current_era: 0, stakers: vec![ - (dave(), alice(), 111 * DOLLARS, staking::StakerStatus::Validator), - (eve(), bob(), 100 * DOLLARS, staking::StakerStatus::Validator), - (ferdie(), charlie(), 100 * DOLLARS, staking::StakerStatus::Validator) + (dave(), alice(), 111 * DOLLARS, pallet_staking::StakerStatus::Validator), + (eve(), bob(), 100 * DOLLARS, pallet_staking::StakerStatus::Validator), + (ferdie(), charlie(), 100 * DOLLARS, pallet_staking::StakerStatus::Validator) ], validator_count: 3, minimum_validator_count: 0, @@ -80,21 +80,21 @@ pub fn config(support_changes_trie: bool, code: Option<&[u8]>) -> GenesisConfig invulnerables: vec![alice(), bob(), charlie()], .. Default::default() }), - contracts: Some(ContractsConfig { + pallet_contracts: Some(ContractsConfig { current_schedule: Default::default(), gas_price: 1 * MILLICENTS, }), - babe: Some(Default::default()), - grandpa: Some(GrandpaConfig { + pallet_babe: Some(Default::default()), + pallet_grandpa: Some(GrandpaConfig { authorities: vec![], }), - im_online: Some(Default::default()), - authority_discovery: Some(Default::default()), - democracy: Some(Default::default()), - collective_Instance1: Some(Default::default()), - collective_Instance2: Some(Default::default()), - membership_Instance1: Some(Default::default()), - sudo: Some(Default::default()), - treasury: Some(Default::default()), + pallet_im_online: Some(Default::default()), + pallet_authority_discovery: Some(Default::default()), + pallet_democracy: Some(Default::default()), + pallet_collective_Instance1: Some(Default::default()), + pallet_collective_Instance2: Some(Default::default()), + pallet_membership_Instance1: Some(Default::default()), + pallet_sudo: Some(Default::default()), + pallet_treasury: Some(Default::default()), } } diff --git a/substrate/bin/node/testing/src/keyring.rs b/substrate/bin/node/testing/src/keyring.rs index 53dac68096..b3dd18b539 100644 --- a/substrate/bin/node/testing/src/keyring.rs +++ b/substrate/bin/node/testing/src/keyring.rs @@ -16,7 +16,7 @@ //! Test accounts. -use keyring::{AccountKeyring, Sr25519Keyring, Ed25519Keyring}; +use sp_keyring::{AccountKeyring, Sr25519Keyring, Ed25519Keyring}; use node_primitives::{AccountId, Balance, Index}; use node_runtime::{CheckedExtrinsic, UncheckedExtrinsic, SessionKeys, SignedExtra}; use sp_runtime::generic::Era; @@ -66,12 +66,12 @@ pub fn to_session_keys( /// Returns transaction extra. pub fn signed_extra(nonce: Index, extra_fee: Balance) -> SignedExtra { ( - system::CheckVersion::new(), - system::CheckGenesis::new(), - system::CheckEra::from(Era::mortal(256, 0)), - system::CheckNonce::from(nonce), - system::CheckWeight::new(), - transaction_payment::ChargeTransactionPayment::from(extra_fee), + frame_system::CheckVersion::new(), + frame_system::CheckGenesis::new(), + frame_system::CheckEra::from(Era::mortal(256, 0)), + frame_system::CheckNonce::from(nonce), + frame_system::CheckWeight::new(), + pallet_transaction_payment::ChargeTransactionPayment::from(extra_fee), Default::default(), ) } @@ -90,7 +90,7 @@ pub fn sign(xt: CheckedExtrinsic, version: u32, genesis_hash: [u8; 32]) -> Unche } }).into(); UncheckedExtrinsic { - signature: Some((indices::address::Address::Id(signed), signature, extra)), + signature: Some((pallet_indices::address::Address::Id(signed), signature, extra)), function: payload.0, } } diff --git a/substrate/bin/node/transaction-factory/Cargo.toml b/substrate/bin/node/transaction-factory/Cargo.toml index ab17c52b0d..c873877ac3 100644 --- a/substrate/bin/node/transaction-factory/Cargo.toml +++ b/substrate/bin/node/transaction-factory/Cargo.toml @@ -5,14 +5,14 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -block-builder-api = { package = "sp-block-builder", path = "../../../primitives/block-builder" } -cli = { package = "sc-cli", path = "../../../client/cli" } -client-api = { package = "sc-client-api", path = "../../../client/api" } -client = { package = "sc-client", path = "../../../client" } +sp-block-builder = { path = "../../../primitives/block-builder" } +sc-cli = { path = "../../../client/cli" } +sc-client-api = { path = "../../../client/api" } +sc-client = { path = "../../../client" } codec = { package = "parity-scale-codec", version = "1.0.0", features = ["derive"] } -consensus_common = { package = "sp-consensus", path = "../../../primitives/consensus/common" } +sp-consensus = { path = "../../../primitives/consensus/common" } log = "0.4.8" -primitives = { package = "sp-core", path = "../../../primitives/core" } +sp-core = { path = "../../../primitives/core" } sp-api = { path = "../../../primitives/api" } sp-runtime = { path = "../../../primitives/runtime" } sc-service = { path = "../../../client/service" } diff --git a/substrate/bin/node/transaction-factory/src/complex_mode.rs b/substrate/bin/node/transaction-factory/src/complex_mode.rs index 2c82be3b4c..61be2ab987 100644 --- a/substrate/bin/node/transaction-factory/src/complex_mode.rs +++ b/substrate/bin/node/transaction-factory/src/complex_mode.rs @@ -41,10 +41,10 @@ use std::sync::Arc; use log::info; -use client::Client; -use block_builder_api::BlockBuilder; +use sc_client::Client; +use sp_block_builder::BlockBuilder; use sp_api::ConstructRuntimeApi; -use primitives::{Blake2Hasher, Hasher}; +use sp_core::{Blake2Hasher, Hasher}; use sp_runtime::generic::BlockId; use sp_runtime::traits::{Block as BlockT, ProvideRuntimeApi, One, Zero}; @@ -60,8 +60,8 @@ pub fn next( ) -> Option where Block: BlockT::Out>, - Exec: client::CallExecutor + Send + Sync + Clone, - Backend: client_api::backend::Backend + Send, + Exec: sc_client::CallExecutor + Send + Sync + Clone, + Backend: sc_client_api::backend::Backend + Send, Client: ProvideRuntimeApi, as ProvideRuntimeApi>::Api: BlockBuilder, diff --git a/substrate/bin/node/transaction-factory/src/lib.rs b/substrate/bin/node/transaction-factory/src/lib.rs index e9526e6259..effb9c6d80 100644 --- a/substrate/bin/node/transaction-factory/src/lib.rs +++ b/substrate/bin/node/transaction-factory/src/lib.rs @@ -26,16 +26,16 @@ use std::fmt::Display; use log::info; -use client::Client; -use block_builder_api::BlockBuilder; +use sc_client::Client; +use sp_block_builder::BlockBuilder; use sp_api::ConstructRuntimeApi; -use consensus_common::{ +use sp_consensus::{ BlockOrigin, BlockImportParams, InherentData, ForkChoiceStrategy, SelectChain }; -use consensus_common::block_import::BlockImport; +use sp_consensus::block_import::BlockImport; use codec::{Decode, Encode}; -use primitives::{Blake2Hasher, Hasher}; +use sp_core::{Blake2Hasher, Hasher}; use sp_runtime::generic::BlockId; use sp_runtime::traits::{ Block as BlockT, Header as HeaderT, ProvideRuntimeApi, SimpleArithmetic, @@ -98,25 +98,25 @@ pub fn factory( mut factory_state: RA, client: &Arc>, select_chain: &Sc, -) -> cli::error::Result<()> +) -> sc_cli::error::Result<()> where Block: BlockT::Out>, - Exec: client::CallExecutor + Send + Sync + Clone, - Backend: client_api::backend::Backend + Send, + Exec: sc_client::CallExecutor + Send + Sync + Clone, + Backend: sc_client_api::backend::Backend + Send, Client: ProvideRuntimeApi, as ProvideRuntimeApi>::Api: BlockBuilder, RtApi: ConstructRuntimeApi> + Send + Sync, Sc: SelectChain, RA: RuntimeAdapter, - <::Block as BlockT>::Hash: From, + <::Block as BlockT>::Hash: From, { if *factory_state.mode() != Mode::MasterToNToM && factory_state.rounds() > RA::Number::one() { let msg = "The factory can only be used with rounds set to 1 in this mode.".into(); - return Err(cli::error::Error::Input(msg)); + return Err(sc_cli::error::Error::Input(msg)); } - let best_header: Result<::Header, cli::error::Error> = + let best_header: Result<::Header, sc_cli::error::Error> = select_chain.best_chain().map_err(|e| format!("{:?}", e).into()); let mut best_hash = best_header?.hash(); let mut best_block_id = BlockId::::hash(best_hash); @@ -160,8 +160,8 @@ pub fn create_block( ) -> Block where Block: BlockT::Out>, - Exec: client::CallExecutor + Send + Sync + Clone, - Backend: client_api::backend::Backend + Send, + Exec: sc_client::CallExecutor + Send + Sync + Clone, + Backend: sc_client_api::backend::Backend + Send, Client: ProvideRuntimeApi, RtApi: ConstructRuntimeApi> + Send + Sync, as ProvideRuntimeApi>::Api: @@ -186,8 +186,8 @@ fn import_block( block: Block ) -> () where Block: BlockT::Out>, - Exec: client::CallExecutor + Send + Sync + Clone, - Backend: client_api::backend::Backend + Send, + Exec: sc_client::CallExecutor + Send + Sync + Clone, + Backend: sc_client_api::backend::Backend + Send, { let import = BlockImportParams { origin: BlockOrigin::File, diff --git a/substrate/bin/node/transaction-factory/src/simple_modes.rs b/substrate/bin/node/transaction-factory/src/simple_modes.rs index 756708b17f..c8ea77f5fe 100644 --- a/substrate/bin/node/transaction-factory/src/simple_modes.rs +++ b/substrate/bin/node/transaction-factory/src/simple_modes.rs @@ -36,10 +36,10 @@ use std::sync::Arc; use log::info; -use client::Client; -use block_builder_api::BlockBuilder; +use sc_client::Client; +use sp_block_builder::BlockBuilder; use sp_api::ConstructRuntimeApi; -use primitives::{Blake2Hasher, Hasher}; +use sp_core::{Blake2Hasher, Hasher}; use sp_runtime::traits::{Block as BlockT, ProvideRuntimeApi, One}; use sp_runtime::generic::BlockId; @@ -55,8 +55,8 @@ pub fn next( ) -> Option where Block: BlockT::Out>, - Exec: client::CallExecutor + Send + Sync + Clone, - Backend: client_api::backend::Backend + Send, + Exec: sc_client::CallExecutor + Send + Sync + Clone, + Backend: sc_client_api::backend::Backend + Send, Client: ProvideRuntimeApi, as ProvideRuntimeApi>::Api: BlockBuilder, diff --git a/substrate/bin/utils/chain-spec-builder/Cargo.toml b/substrate/bin/utils/chain-spec-builder/Cargo.toml index 4d317d3a54..1e2bd0bc36 100644 --- a/substrate/bin/utils/chain-spec-builder/Cargo.toml +++ b/substrate/bin/utils/chain-spec-builder/Cargo.toml @@ -7,8 +7,8 @@ build = "build.rs" [dependencies] ansi_term = "0.12.1" -keystore = { package = "sc-keystore", path = "../../../client/keystore" } +sc-keystore = { path = "../../../client/keystore" } node-cli = { path = "../../node/cli" } -primitives = { package = "sp-core", path = "../../../primitives/core" } +sp-core = { path = "../../../primitives/core" } rand = "0.7.2" structopt = "0.3.3" diff --git a/substrate/bin/utils/chain-spec-builder/src/main.rs b/substrate/bin/utils/chain-spec-builder/src/main.rs index b277987e1e..c370469d64 100644 --- a/substrate/bin/utils/chain-spec-builder/src/main.rs +++ b/substrate/bin/utils/chain-spec-builder/src/main.rs @@ -20,9 +20,9 @@ use ansi_term::Style; use rand::{Rng, distributions::Alphanumeric, rngs::OsRng}; use structopt::StructOpt; -use keystore::{Store as Keystore}; +use sc_keystore::{Store as Keystore}; use node_cli::chain_spec::{self, AccountId}; -use primitives::{sr25519, crypto::{Public, Ss58Codec}, traits::BareCryptoStore}; +use sp_core::{sr25519, crypto::{Public, Ss58Codec}, traits::BareCryptoStore}; /// A utility to easily create a testnet chain spec definition with a given set /// of authorities and endowed accounts and/or generate random accounts. @@ -153,22 +153,22 @@ fn generate_authority_keys_and_store( }; insert_key( - primitives::crypto::key_types::BABE, + sp_core::crypto::key_types::BABE, babe.as_slice(), )?; insert_key( - primitives::crypto::key_types::GRANDPA, + sp_core::crypto::key_types::GRANDPA, grandpa.as_slice(), )?; insert_key( - primitives::crypto::key_types::IM_ONLINE, + sp_core::crypto::key_types::IM_ONLINE, im_online.as_slice(), )?; insert_key( - primitives::crypto::key_types::AUTHORITY_DISCOVERY, + sp_core::crypto::key_types::AUTHORITY_DISCOVERY, authority_discovery.as_slice(), )?; } diff --git a/substrate/bin/utils/subkey/Cargo.toml b/substrate/bin/utils/subkey/Cargo.toml index a173c10130..3c998c9c9c 100644 --- a/substrate/bin/utils/subkey/Cargo.toml +++ b/substrate/bin/utils/subkey/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -primitives = { package = "sp-core", version = "*", path = "../../../primitives/core" } +sp-core = { version = "*", path = "../../../primitives/core" } node-runtime = { version = "*", path = "../../node/runtime" } node-primitives = { version = "*", path = "../../node/primitives" } sp-runtime = { version = "*", path = "../../../primitives/runtime" } @@ -17,9 +17,9 @@ substrate-bip39 = "0.3.1" hex = "0.4.0" hex-literal = "0.2.1" codec = { package = "parity-scale-codec", version = "1.0.0" } -system = { package = "frame-system", path = "../../../frame/system" } -balances = { package = "pallet-balances", path = "../../../frame/balances" } -transaction-payment = { package = "pallet-transaction-payment", path = "../../../frame/transaction-payment" } +frame-system = { path = "../../../frame/system" } +pallet-balances = { path = "../../../frame/balances" } +pallet-transaction-payment = { path = "../../../frame/transaction-payment" } [features] bench = [] diff --git a/substrate/bin/utils/subkey/src/main.rs b/substrate/bin/utils/subkey/src/main.rs index 24ecbb0686..05d22cd57b 100644 --- a/substrate/bin/utils/subkey/src/main.rs +++ b/substrate/bin/utils/subkey/src/main.rs @@ -24,7 +24,7 @@ use codec::{Decode, Encode}; use hex_literal::hex; use node_primitives::{Balance, Hash, Index, AccountId, Signature}; use node_runtime::{BalancesCall, Call, Runtime, SignedPayload, UncheckedExtrinsic, VERSION}; -use primitives::{ +use sp_core::{ crypto::{set_default_ss58_version, Ss58AddressFormat, Ss58Codec}, ed25519, sr25519, ecdsa, Pair, Public, H256, hexdisplay::HexDisplay, }; @@ -197,7 +197,7 @@ fn get_app<'a, 'b>() -> App<'a, 'b> { -s, --suri 'The secret key URI.' "), SubCommand::with_name("transfer") - .about("Author and sign a Node balances::Transfer transaction with a given (secret) key") + .about("Author and sign a Node pallet_balances::Transfer transaction with a given (secret) key") .args_from_usage(" -g, --genesis 'The genesis hash or a recognised \ chain identifier (dev, elm, alex).' @@ -484,12 +484,12 @@ fn create_extrinsic( { let extra = |i: Index, f: Balance| { ( - system::CheckVersion::::new(), - system::CheckGenesis::::new(), - system::CheckEra::::from(Era::Immortal), - system::CheckNonce::::from(i), - system::CheckWeight::::new(), - transaction_payment::ChargeTransactionPayment::::from(f), + frame_system::CheckVersion::::new(), + frame_system::CheckGenesis::::new(), + frame_system::CheckEra::::from(Era::Immortal), + frame_system::CheckNonce::::from(i), + frame_system::CheckWeight::::new(), + pallet_transaction_payment::ChargeTransactionPayment::::from(f), Default::default(), ) }; diff --git a/substrate/bin/utils/subkey/src/vanity.rs b/substrate/bin/utils/subkey/src/vanity.rs index 835001a0aa..33e8559b1f 100644 --- a/substrate/bin/utils/subkey/src/vanity.rs +++ b/substrate/bin/utils/subkey/src/vanity.rs @@ -15,7 +15,7 @@ // along with Substrate. If not, see . use super::{PublicOf, PublicT, Crypto}; -use primitives::Pair; +use sp_core::Pair; use rand::{rngs::OsRng, RngCore}; fn good_waypoint(done: u64) -> u64 { @@ -110,7 +110,7 @@ pub(super) fn generate_key(desired: &str) -> Result, &str> mod tests { use super::super::Ed25519; use super::*; - use primitives::{crypto::Ss58Codec, Pair}; + use sp_core::{crypto::Ss58Codec, Pair}; #[cfg(feature = "bench")] use test::Bencher; diff --git a/substrate/client/Cargo.toml b/substrate/client/Cargo.toml index c259c8db30..a30dfc00ff 100644 --- a/substrate/client/Cargo.toml +++ b/substrate/client/Cargo.toml @@ -5,36 +5,36 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -block-builder = { package = "sc-block-builder", path = "block-builder" } -client-api = { package = "sc-client-api", path = "api" } +sc-block-builder = { path = "block-builder" } +sc-client-api = { path = "api" } codec = { package = "parity-scale-codec", version = "1.0.0", features = ["derive"] } -consensus = { package = "sp-consensus", path = "../primitives/consensus/common" } +sp-consensus = { path = "../primitives/consensus/common" } derive_more = { version = "0.99.2" } -executor = { package = "sc-executor", path = "executor" } -externalities = { package = "sp-externalities", path = "../primitives/externalities" } +sc-executor = { path = "executor" } +sp-externalities = { path = "../primitives/externalities" } fnv = { version = "1.0.6" } futures = { version = "0.3.1", features = ["compat"] } hash-db = { version = "0.15.2" } hex-literal = { version = "0.2.1" } -inherents = { package = "sp-inherents", path = "../primitives/inherents" } -keyring = { package = "sp-keyring", path = "../primitives/keyring" } +sp-inherents = { path = "../primitives/inherents" } +sp-keyring = { path = "../primitives/keyring" } kvdb = "0.1.1" log = { version = "0.4.8" } parking_lot = { version = "0.9.0" } -primitives = { package = "sp-core", path = "../primitives/core" } +sp-core = { path = "../primitives/core" } sp-std = { path = "../primitives/std" } -runtime-version = { package = "sp-version", path = "../primitives/version" } +sp-version = { path = "../primitives/version" } sp-api = { path = "../primitives/api" } sp-runtime = { path = "../primitives/runtime" } sp-blockchain = { path = "../primitives/blockchain" } -state-machine = { package = "sp-state-machine", path = "../primitives/state-machine" } +sp-state-machine = { path = "../primitives/state-machine" } sc-telemetry = { path = "telemetry" } -trie = { package = "sp-trie", path = "../primitives/trie" } +sp-trie = { path = "../primitives/trie" } tracing = "0.1.10" [dev-dependencies] env_logger = "0.7.0" tempfile = "3.1.0" -test-client = { package = "substrate-test-runtime-client", path = "../test-utils/runtime/client" } +substrate-test-runtime-client = { path = "../test-utils/runtime/client" } kvdb-memorydb = "0.1.2" -panic-handler = { package = "sp-panic-handler", path = "../primitives/panic-handler" } +sp-panic-handler = { path = "../primitives/panic-handler" } diff --git a/substrate/client/api/Cargo.toml b/substrate/client/api/Cargo.toml index f47294d571..12a6901c0e 100644 --- a/substrate/client/api/Cargo.toml +++ b/substrate/client/api/Cargo.toml @@ -6,29 +6,29 @@ edition = "2018" [dependencies] codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } -consensus = { package = "sp-consensus", path = "../../primitives/consensus/common" } +sp-consensus = { path = "../../primitives/consensus/common" } derive_more = { version = "0.99.2" } -executor = { package = "sc-executor", path = "../executor" } -externalities = { package = "sp-externalities", path = "../../primitives/externalities" } +sc-executor = { path = "../executor" } +sp-externalities = { path = "../../primitives/externalities" } fnv = { version = "1.0.6" } futures = { version = "0.3.1" } hash-db = { version = "0.15.2", default-features = false } sp-blockchain = { path = "../../primitives/blockchain" } hex-literal = { version = "0.2.1" } -inherents = { package = "sp-inherents", path = "../../primitives/inherents", default-features = false } -keyring = { package = "sp-keyring", path = "../../primitives/keyring" } +sp-inherents = { path = "../../primitives/inherents", default-features = false } +sp-keyring = { path = "../../primitives/keyring" } kvdb = "0.1.1" log = { version = "0.4.8" } parking_lot = { version = "0.9.0" } -primitives = { package = "sp-core", path = "../../primitives/core", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false } sp-std = { path = "../../primitives/std", default-features = false } -runtime-version = { package = "sp-version", path = "../../primitives/version", default-features = false } +sp-version = { path = "../../primitives/version", default-features = false } sp-api = { path = "../../primitives/api" } sp-runtime = { path = "../../primitives/runtime", default-features = false } -state-machine = { package = "sp-state-machine", path = "../../primitives/state-machine" } +sp-state-machine = { path = "../../primitives/state-machine" } sc-telemetry = { path = "../telemetry" } -trie = { package = "sp-trie", path = "../../primitives/trie" } -txpool-api = { package = "sp-transaction-pool", path = "../../primitives/transaction-pool" } +sp-trie = { path = "../../primitives/trie" } +sp-transaction-pool = { path = "../../primitives/transaction-pool" } [dev-dependencies] -test-primitives = { package = "sp-test-primitives", path = "../../primitives/test-primitives" } \ No newline at end of file +sp-test-primitives = { path = "../../primitives/test-primitives" } \ No newline at end of file diff --git a/substrate/client/api/src/backend.rs b/substrate/client/api/src/backend.rs index a71ffff74b..963bb6083b 100644 --- a/substrate/client/api/src/backend.rs +++ b/substrate/client/api/src/backend.rs @@ -18,12 +18,12 @@ use std::sync::Arc; use std::collections::HashMap; -use primitives::ChangesTrieConfiguration; -use primitives::offchain::OffchainStorage; +use sp_core::ChangesTrieConfiguration; +use sp_core::offchain::OffchainStorage; use sp_runtime::{generic::BlockId, Justification, Storage}; use sp_runtime::traits::{Block as BlockT, NumberFor}; -use state_machine::backend::Backend as StateBackend; -use state_machine::{ChangesTrieStorage as StateChangesTrieStorage, ChangesTrieTransaction}; +use sp_state_machine::backend::Backend as StateBackend; +use sp_state_machine::{ChangesTrieStorage as StateChangesTrieStorage, ChangesTrieTransaction}; use crate::{ blockchain::{ Backend as BlockchainBackend, well_known_cache_keys @@ -31,7 +31,7 @@ use crate::{ light::RemoteBlockchain, }; use sp_blockchain; -use consensus::BlockOrigin; +use sp_consensus::BlockOrigin; use hash_db::Hasher; use parking_lot::RwLock; diff --git a/substrate/client/api/src/call_executor.rs b/substrate/client/api/src/call_executor.rs index 8bd4bb9015..b54f6f5205 100644 --- a/substrate/client/api/src/call_executor.rs +++ b/substrate/client/api/src/call_executor.rs @@ -21,14 +21,14 @@ use codec::{Encode, Decode}; use sp_runtime::{ generic::BlockId, traits::Block as BlockT, traits::NumberFor, }; -use state_machine::{ +use sp_state_machine::{ self, OverlayedChanges, ExecutionManager, ExecutionStrategy, ChangesTrieTransaction, StorageProof, }; -use executor::{RuntimeVersion, NativeVersion}; -use externalities::Extensions; +use sc_executor::{RuntimeVersion, NativeVersion}; +use sp_externalities::Extensions; use hash_db::Hasher; -use primitives::{Blake2Hasher, NativeOrEncoded}; +use sp_core::{Blake2Hasher, NativeOrEncoded}; use sp_api::{ProofRecorder, InitializeBlock}; use sp_blockchain; @@ -41,7 +41,7 @@ where H::Out: Ord, { /// Externalities error type. - type Error: state_machine::Error; + type Error: sp_state_machine::Error; /// Execute a call to a contract on top of state in a block of given hash. /// @@ -92,7 +92,7 @@ where /// /// No changes are made. fn call_at_state< - S: state_machine::Backend, + S: sp_state_machine::Backend, F: FnOnce( Result, Self::Error>, Result, Self::Error>, @@ -119,7 +119,7 @@ where /// Execute a call to a contract on top of given state, gathering execution proof. /// /// No changes are made. - fn prove_at_state>( + fn prove_at_state>( &self, mut state: S, overlay: &mut OverlayedChanges, @@ -128,8 +128,8 @@ where ) -> Result<(Vec, StorageProof), sp_blockchain::Error> { let trie_state = state.as_trie_backend() .ok_or_else(|| - Box::new(state_machine::ExecutionError::UnableToGenerateProof) - as Box + Box::new(sp_state_machine::ExecutionError::UnableToGenerateProof) + as Box )?; self.prove_at_trie_state(trie_state, overlay, method, call_data) } @@ -137,9 +137,9 @@ where /// Execute a call to a contract on top of given trie state, gathering execution proof. /// /// No changes are made. - fn prove_at_trie_state>( + fn prove_at_trie_state>( &self, - trie_state: &state_machine::TrieBackend, + trie_state: &sp_state_machine::TrieBackend, overlay: &mut OverlayedChanges, method: &str, call_data: &[u8] diff --git a/substrate/client/api/src/client.rs b/substrate/client/api/src/client.rs index d053e11732..17da85b5de 100644 --- a/substrate/client/api/src/client.rs +++ b/substrate/client/api/src/client.rs @@ -18,12 +18,12 @@ use std::collections::HashMap; use futures::channel::mpsc; -use primitives::storage::StorageKey; +use sp_core::storage::StorageKey; use sp_runtime::{ traits::{Block as BlockT, NumberFor}, generic::BlockId }; -use consensus::BlockOrigin; +use sp_consensus::BlockOrigin; use crate::blockchain::Info; use crate::notifications::StorageEventStream; diff --git a/substrate/client/api/src/execution_extensions.rs b/substrate/client/api/src/execution_extensions.rs index 3e0cf44b84..e1be4d8ec0 100644 --- a/substrate/client/api/src/execution_extensions.rs +++ b/substrate/client/api/src/execution_extensions.rs @@ -22,7 +22,7 @@ use std::sync::{Weak, Arc}; use codec::Decode; -use primitives::{ +use sp_core::{ ExecutionContext, offchain::{self, OffchainExt, TransactionPoolExt}, traits::{BareCryptoStorePtr, KeystoreExt}, @@ -31,8 +31,8 @@ use sp_runtime::{ generic::BlockId, traits, }; -use state_machine::{ExecutionStrategy, ExecutionManager, DefaultHandler}; -use externalities::Extensions; +use sp_state_machine::{ExecutionStrategy, ExecutionManager, DefaultHandler}; +use sp_externalities::Extensions; use parking_lot::RwLock; /// Execution strategies settings. @@ -70,7 +70,7 @@ impl Default for ExecutionStrategies { pub struct ExecutionExtensions { strategies: ExecutionStrategies, keystore: Option, - transaction_pool: RwLock>>>, + transaction_pool: RwLock>>>, } impl Default for ExecutionExtensions { @@ -104,7 +104,7 @@ impl ExecutionExtensions { /// extension to be a `Weak` reference. /// That's also the reason why it's being registered lazily instead of /// during initialisation. - pub fn register_transaction_pool(&self, pool: Weak>) { + pub fn register_transaction_pool(&self, pool: Weak>) { *self.transaction_pool.write() = Some(pool); } @@ -165,7 +165,7 @@ impl ExecutionExtensions { /// A wrapper type to pass `BlockId` to the actual transaction pool. struct TransactionPoolAdapter { at: BlockId, - pool: Arc>, + pool: Arc>, } impl offchain::TransactionPool for TransactionPoolAdapter { diff --git a/substrate/client/api/src/lib.rs b/substrate/client/api/src/lib.rs index ab2f521df2..d51157d245 100644 --- a/substrate/client/api/src/lib.rs +++ b/substrate/client/api/src/lib.rs @@ -32,13 +32,13 @@ pub use client::*; pub use light::*; pub use notifications::*; -pub use state_machine::{StorageProof, ExecutionStrategy}; +pub use sp_state_machine::{StorageProof, ExecutionStrategy}; /// Utility methods for the client. pub mod utils { use sp_blockchain::{HeaderBackend, HeaderMetadata, Error}; - use primitives::H256; + use sp_core::H256; use sp_runtime::traits::{Block as BlockT}; use std::borrow::Borrow; diff --git a/substrate/client/api/src/light.rs b/substrate/client/api/src/light.rs index 2c52aeca83..073e62e687 100644 --- a/substrate/client/api/src/light.rs +++ b/substrate/client/api/src/light.rs @@ -26,8 +26,8 @@ use sp_runtime::{ }, generic::BlockId }; -use primitives::ChangesTrieConfiguration; -use state_machine::StorageProof; +use sp_core::ChangesTrieConfiguration; +use sp_state_machine::StorageProof; use sp_blockchain::{ HeaderMetadata, well_known_cache_keys, HeaderBackend, Cache as BlockchainCache, Error as ClientError, Result as ClientResult, @@ -304,7 +304,7 @@ pub mod tests { use futures::future::Ready; use parking_lot::Mutex; use sp_blockchain::Error as ClientError; - use test_primitives::{Block, Header, Extrinsic}; + use sp_test_primitives::{Block, Header, Extrinsic}; use super::*; pub type OkCallFetcher = Mutex>; diff --git a/substrate/client/api/src/notifications.rs b/substrate/client/api/src/notifications.rs index 1706f07b96..88b0b2d307 100644 --- a/substrate/client/api/src/notifications.rs +++ b/substrate/client/api/src/notifications.rs @@ -23,7 +23,7 @@ use std::{ use fnv::{FnvHashSet, FnvHashMap}; use futures::channel::mpsc; -use primitives::storage::{StorageKey, StorageData}; +use sp_core::storage::{StorageKey, StorageData}; use sp_runtime::traits::Block as BlockT; /// Storage change set diff --git a/substrate/client/authority-discovery/Cargo.toml b/substrate/client/authority-discovery/Cargo.toml index 72e4345166..8dcd29a2a7 100644 --- a/substrate/client/authority-discovery/Cargo.toml +++ b/substrate/client/authority-discovery/Cargo.toml @@ -9,18 +9,18 @@ build = "build.rs" prost-build = "0.5.0" [dependencies] -authority-discovery-primitives = { package = "sp-authority-discovery", path = "../../primitives/authority-discovery" } +sp-authority-discovery = { path = "../../primitives/authority-discovery" } bytes = "0.4.12" -client-api = { package = "sc-client-api", path = "../api" } +sc-client-api = { path = "../api" } codec = { package = "parity-scale-codec", default-features = false, version = "1.0.3" } derive_more = "0.99.2" futures = "0.3.1" futures-timer = "2.0" -keystore = { package = "sc-keystore", path = "../keystore" } +sc-keystore = { path = "../keystore" } libp2p = { version = "0.13.0", default-features = false, features = ["secp256k1", "libp2p-websocket"] } log = "0.4.8" -network = { package = "sc-network", path = "../network" } -primitives = { package = "sp-core", path = "../../primitives/core" } +sc-network = { path = "../network" } +sp-core = { path = "../../primitives/core" } sp-blockchain = { path = "../../primitives/blockchain" } prost = "0.5.0" serde_json = "1.0.41" @@ -29,6 +29,6 @@ sp-runtime = { path = "../../primitives/runtime" } [dev-dependencies] env_logger = "0.7.0" parking_lot = "0.9.0" -peerset = { package = "sc-peerset", path = "../peerset" } +sc-peerset = { path = "../peerset" } sp-test-primitives = { path = "../../primitives/test-primitives" } sp-api = { path = "../../primitives/api" } diff --git a/substrate/client/authority-discovery/src/lib.rs b/substrate/client/authority-discovery/src/lib.rs index a70683f682..6ab2d899a5 100644 --- a/substrate/client/authority-discovery/src/lib.rs +++ b/substrate/client/authority-discovery/src/lib.rs @@ -55,18 +55,18 @@ use futures::task::{Context, Poll}; use futures::{Future, FutureExt, Stream, StreamExt}; use futures_timer::Delay; -use authority_discovery_primitives::{ +use sp_authority_discovery::{ AuthorityDiscoveryApi, AuthorityId, AuthoritySignature, AuthorityPair }; -use client_api::blockchain::HeaderBackend; +use sc_client_api::blockchain::HeaderBackend; use codec::{Decode, Encode}; use error::{Error, Result}; use log::{debug, error, log_enabled, warn}; use libp2p::Multiaddr; -use network::specialization::NetworkSpecialization; -use network::{DhtEvent, ExHashT}; -use primitives::crypto::{key_types, Pair}; -use primitives::traits::BareCryptoStorePtr; +use sc_network::specialization::NetworkSpecialization; +use sc_network::{DhtEvent, ExHashT}; +use sp_core::crypto::{key_types, Pair}; +use sp_core::traits::BareCryptoStorePtr; use prost::Message; use sp_runtime::generic::BlockId; use sp_runtime::traits::{Block as BlockT, ProvideRuntimeApi}; @@ -501,7 +501,7 @@ pub trait NetworkProvider { fn get_value(&self, key: &libp2p::kad::record::Key); } -impl NetworkProvider for network::NetworkService +impl NetworkProvider for sc_network::NetworkService where B: BlockT + 'static, S: NetworkSpecialization, @@ -551,7 +551,7 @@ mod tests { use futures::channel::mpsc::channel; use futures::executor::block_on; use futures::future::poll_fn; - use primitives::{ExecutionContext, NativeOrEncoded, testing::KeyStore}; + use sp_core::{ExecutionContext, NativeOrEncoded, testing::KeyStore}; use sp_runtime::traits::Zero; use sp_runtime::traits::{ApiRef, Block as BlockT, NumberFor, ProvideRuntimeApi}; use std::sync::{Arc, Mutex}; @@ -642,8 +642,8 @@ mod tests { Ok(None) } - fn info(&self) -> client_api::blockchain::Info { - client_api::blockchain::Info { + fn info(&self) -> sc_client_api::blockchain::Info { + sc_client_api::blockchain::Info { best_hash: Default::default(), best_number: Zero::zero(), finalized_hash: Default::default(), @@ -655,8 +655,8 @@ mod tests { fn status( &self, _id: BlockId, - ) -> std::result::Result { - Ok(client_api::blockchain::BlockStatus::Unknown) + ) -> std::result::Result { + Ok(sc_client_api::blockchain::BlockStatus::Unknown) } fn number( @@ -865,7 +865,7 @@ mod tests { .encode(&mut signed_addresses) .unwrap(); - let dht_event = network::DhtEvent::ValueFound(vec![(authority_id_1, signed_addresses)]); + let dht_event = sc_network::DhtEvent::ValueFound(vec![(authority_id_1, signed_addresses)]); dht_event_tx.try_send(dht_event).unwrap(); // Make authority discovery handle the event. diff --git a/substrate/client/basic-authorship/Cargo.toml b/substrate/client/basic-authorship/Cargo.toml index f361ebe477..3b0aa79b97 100644 --- a/substrate/client/basic-authorship/Cargo.toml +++ b/substrate/client/basic-authorship/Cargo.toml @@ -9,18 +9,18 @@ log = "0.4.8" futures = "0.3.1" codec = { package = "parity-scale-codec", version = "1.0.0" } sp-runtime = { path = "../../primitives/runtime" } -primitives = { package = "sp-core", path = "../../primitives/core" } +sp-core = { path = "../../primitives/core" } sp-blockchain = { path = "../../primitives/blockchain" } -client = { package = "sc-client", path = "../" } -client-api = { package = "sc-client-api", path = "../api" } -consensus_common = { package = "sp-consensus", path = "../../primitives/consensus/common" } -inherents = { package = "sp-inherents", path = "../../primitives/inherents" } +sc-client = { path = "../" } +sc-client-api = { path = "../api" } +sp-consensus = { path = "../../primitives/consensus/common" } +sp-inherents = { path = "../../primitives/inherents" } sc-telemetry = { path = "../telemetry" } -txpool-api = { package = "sp-transaction-pool", path = "../../primitives/transaction-pool" } -block-builder = { package = "sc-block-builder", path = "../block-builder" } +sp-transaction-pool = { path = "../../primitives/transaction-pool" } +sc-block-builder = { path = "../block-builder" } tokio-executor = { version = "0.2.0-alpha.6", features = ["blocking"] } [dev-dependencies] -txpool = { package = "sc-transaction-pool", path = "../../client/transaction-pool" } -test-client = { package = "substrate-test-runtime-client", path = "../../test-utils/runtime/client" } +sc-transaction-pool = { path = "../../client/transaction-pool" } +substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } parking_lot = "0.9" diff --git a/substrate/client/basic-authorship/src/basic_authorship.rs b/substrate/client/basic-authorship/src/basic_authorship.rs index 131a4e9f2d..55f358cdd7 100644 --- a/substrate/client/basic-authorship/src/basic_authorship.rs +++ b/substrate/client/basic-authorship/src/basic_authorship.rs @@ -19,23 +19,23 @@ // FIXME #1021 move this into sp-consensus use std::{time, sync::Arc}; -use client_api::CallExecutor; +use sc_client_api::CallExecutor; use sp_blockchain; -use client::Client as SubstrateClient; +use sc_client::Client as SubstrateClient; use codec::Decode; -use consensus_common::{evaluation}; -use inherents::InherentData; +use sp_consensus::{evaluation}; +use sp_inherents::InherentData; use log::{error, info, debug, trace}; -use primitives::{H256, Blake2Hasher, ExecutionContext}; +use sp_core::{H256, Blake2Hasher, ExecutionContext}; use sp_runtime::{ traits::{ Block as BlockT, Hash as HashT, Header as HeaderT, ProvideRuntimeApi, DigestFor, BlakeTwo256 }, generic::BlockId, }; -use txpool_api::{TransactionPool, InPoolTransaction}; +use sp_transaction_pool::{TransactionPool, InPoolTransaction}; use sc_telemetry::{telemetry, CONSENSUS_INFO}; -use block_builder::BlockBuilderApi; +use sc_block_builder::BlockBuilderApi; /// Proposer factory. pub struct ProposerFactory where A: TransactionPool { @@ -48,7 +48,7 @@ pub struct ProposerFactory where A: TransactionPool { impl ProposerFactory, A> where A: TransactionPool + 'static, - B: client_api::backend::Backend + Send + Sync + 'static, + B: sc_client_api::backend::Backend + Send + Sync + 'static, E: CallExecutor + Send + Sync + Clone + 'static, Block: BlockT, RA: Send + Sync + 'static, @@ -82,11 +82,11 @@ where } } -impl consensus_common::Environment for +impl sp_consensus::Environment for ProposerFactory, A> where A: TransactionPool + 'static, - B: client_api::backend::Backend + Send + Sync + 'static, + B: sc_client_api::backend::Backend + Send + Sync + 'static, E: CallExecutor + Send + Sync + Clone + 'static, Block: BlockT, RA: Send + Sync + 'static, @@ -120,11 +120,11 @@ struct ProposerInner { now: Box time::Instant + Send + Sync>, } -impl consensus_common::Proposer for +impl sp_consensus::Proposer for Proposer, A> where A: TransactionPool + 'static, - B: client_api::backend::Backend + Send + Sync + 'static, + B: sc_client_api::backend::Backend + Send + Sync + 'static, E: CallExecutor + Send + Sync + Clone + 'static, Block: BlockT, RA: Send + Sync + 'static, @@ -152,7 +152,7 @@ where impl ProposerInner, A> where A: TransactionPool + 'static, - B: client_api::backend::Backend + Send + Sync + 'static, + B: sc_client_api::backend::Backend + Send + Sync + 'static, E: CallExecutor + Send + Sync + Clone + 'static, Block: BlockT, RA: Send + Sync + 'static, @@ -201,7 +201,7 @@ impl ProposerInner, let pending_tx_data = pending_tx.data().clone(); let pending_tx_hash = pending_tx.hash().clone(); trace!("[{:?}] Pushing to the block.", pending_tx_hash); - match block_builder::BlockBuilder::push(&mut block_builder, pending_tx_data) { + match sc_block_builder::BlockBuilder::push(&mut block_builder, pending_tx_data) { Ok(()) => { debug!("[{:?}] Pushed to the block.", pending_tx_hash); } @@ -266,9 +266,9 @@ mod tests { use super::*; use parking_lot::Mutex; - use consensus_common::Proposer; - use test_client::{self, runtime::{Extrinsic, Transfer}, AccountKeyring}; - use txpool::{BasicPool, FullChainApi}; + use sp_consensus::Proposer; + use substrate_test_runtime_client::{self, runtime::{Extrinsic, Transfer}, AccountKeyring}; + use sc_transaction_pool::{BasicPool, FullChainApi}; fn extrinsic(nonce: u64) -> Extrinsic { Transfer { @@ -282,7 +282,7 @@ mod tests { #[test] fn should_cease_building_block_when_deadline_is_reached() { // given - let client = Arc::new(test_client::new()); + let client = Arc::new(substrate_test_runtime_client::new()); let txpool = Arc::new(BasicPool::new(Default::default(), FullChainApi::new(client.clone()))); futures::executor::block_on( diff --git a/substrate/client/basic-authorship/src/lib.rs b/substrate/client/basic-authorship/src/lib.rs index f27ce9cb52..65ac39f9ff 100644 --- a/substrate/client/basic-authorship/src/lib.rs +++ b/substrate/client/basic-authorship/src/lib.rs @@ -20,12 +20,12 @@ //! //! ``` //! # use sc_basic_authority::ProposerFactory; -//! # use consensus_common::{Environment, Proposer}; +//! # use sp_consensus::{Environment, Proposer}; //! # use sp_runtime::generic::BlockId; //! # use std::{sync::Arc, time::Duration}; -//! # use test_client::{self, runtime::{Extrinsic, Transfer}, AccountKeyring}; -//! # use txpool::{BasicPool, FullChainApi}; -//! # let client = Arc::new(test_client::new()); +//! # use substrate_test_runtime_client::{self, runtime::{Extrinsic, Transfer}, AccountKeyring}; +//! # use sc_transaction_pool::{BasicPool, FullChainApi}; +//! # let client = Arc::new(substrate_test_runtime_client::new()); //! # let txpool = Arc::new(BasicPool::new(Default::default(), FullChainApi::new(client.clone()))); //! // The first step is to create a `ProposerFactory`. //! let mut proposer_factory = ProposerFactory { diff --git a/substrate/client/block-builder/Cargo.toml b/substrate/client/block-builder/Cargo.toml index 3ed6d56ba8..421419c122 100644 --- a/substrate/client/block-builder/Cargo.toml +++ b/substrate/client/block-builder/Cargo.toml @@ -5,10 +5,10 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -state-machine = { package = "sp-state-machine", path = "../../primitives/state-machine" } +sp-state-machine = { path = "../../primitives/state-machine" } sp-runtime = { path = "../../primitives/runtime" } sp-blockchain = { path = "../../primitives/blockchain" } -primitives = { package = "sp-core", path = "../../primitives/core" } +sp-core = { path = "../../primitives/core" } codec = { package = "parity-scale-codec", version = "1.0.6", features = ["derive"] } -runtime_api = { package = "sp-block-builder", path = "../../primitives/block-builder" } +sp-block-builder = { path = "../../primitives/block-builder" } sp-api = { path = "../../primitives/api" } diff --git a/substrate/client/block-builder/src/lib.rs b/substrate/client/block-builder/src/lib.rs index c378bede38..ba5c5694c1 100644 --- a/substrate/client/block-builder/src/lib.rs +++ b/substrate/client/block-builder/src/lib.rs @@ -34,11 +34,11 @@ use sp_runtime::{ } }; use sp_blockchain::{ApplyExtrinsicFailed, Error}; -use primitives::ExecutionContext; -use state_machine::StorageProof; +use sp_core::ExecutionContext; +use sp_state_machine::StorageProof; use sp_api::{Core, ApiExt, ApiErrorFor}; -pub use runtime_api::BlockBuilder as BlockBuilderApi; +pub use sp_block_builder::BlockBuilder as BlockBuilderApi; /// Utility for building new (valid) blocks from a stream of extrinsics. diff --git a/substrate/client/chain-spec/Cargo.toml b/substrate/client/chain-spec/Cargo.toml index f1035e8d56..91dd4a2814 100644 --- a/substrate/client/chain-spec/Cargo.toml +++ b/substrate/client/chain-spec/Cargo.toml @@ -7,9 +7,9 @@ edition = "2018" [dependencies] sc-chain-spec-derive = { path = "./derive" } impl-trait-for-tuples = "0.1.3" -network = { package = "sc-network", path = "../network" } -primitives = { package = "sp-core", path = "../../primitives/core" } +sc-network = { path = "../network" } +sp-core = { path = "../../primitives/core" } serde = { version = "1.0.101", features = ["derive"] } serde_json = "1.0.41" sp-runtime = { path = "../../primitives/runtime" } -tel = { package = "sc-telemetry", path = "../telemetry" } +sc-telemetry = { path = "../telemetry" } diff --git a/substrate/client/chain-spec/src/chain_spec.rs b/substrate/client/chain-spec/src/chain_spec.rs index 3c4cc7a54a..c5d0fcf402 100644 --- a/substrate/client/chain-spec/src/chain_spec.rs +++ b/substrate/client/chain-spec/src/chain_spec.rs @@ -22,12 +22,12 @@ use std::fs::File; use std::path::PathBuf; use std::rc::Rc; use serde::{Serialize, Deserialize}; -use primitives::storage::{StorageKey, StorageData, ChildInfo, Storage, StorageChild}; +use sp_core::storage::{StorageKey, StorageData, ChildInfo, Storage, StorageChild}; use sp_runtime::BuildStorage; use serde_json as json; use crate::RuntimeGenesis; -use network::Multiaddr; -use tel::TelemetryEndpoints; +use sc_network::Multiaddr; +use sc_telemetry::TelemetryEndpoints; enum GenesisSource { File(PathBuf), @@ -77,7 +77,7 @@ impl<'a, G: RuntimeGenesis, E> BuildStorage for &'a ChainSpec { Genesis::Raw(RawGenesis { top: map, children: children_map }) => Ok(Storage { top: map.into_iter().map(|(k, v)| (k.0, v.0)).collect(), children: children_map.into_iter().map(|(sk, child_content)| { - let child_info = ChildInfo::resolve_child_info( + let child_info = ChildInfo::resolve_child_info( child_content.child_type, child_content.child_info.as_slice(), ).expect("chainspec contains correct content").to_owned(); @@ -292,7 +292,7 @@ impl ChainSpec { StorageKey(sk), ChildRawStorage { data: child.data.into_iter() - .map(|(k, v)| (StorageKey(k), StorageData(v))) + .map(|(k, v)| (StorageKey(k), StorageData(v))) .collect(), child_info: info.to_vec(), child_type: ci_type, diff --git a/substrate/client/cli/Cargo.toml b/substrate/client/cli/Cargo.toml index 7e65e59faa..3f76ff0b72 100644 --- a/substrate/client/cli/Cargo.toml +++ b/substrate/client/cli/Cargo.toml @@ -20,19 +20,19 @@ tokio = "0.2.1" futures = { version = "0.3.1", features = ["compat"] } fdlimit = "0.1.1" serde_json = "1.0.41" -panic-handler = { package = "sp-panic-handler", path = "../../primitives/panic-handler" } -client-api = { package = "sc-client-api", path = "../api" } +sp-panic-handler = { path = "../../primitives/panic-handler" } +sc-client-api = { path = "../api" } sp-blockchain = { path = "../../primitives/blockchain" } -network = { package = "sc-network", path = "../network" } +sc-network = { path = "../network" } sp-runtime = { path = "../../primitives/runtime" } -primitives = { package = "sp-core", path = "../../primitives/core" } -service = { package = "sc-service", path = "../service", default-features = false } -state-machine = { package = "sp-state-machine", path = "../../primitives/state-machine" } +sp-core = { path = "../../primitives/core" } +sc-service = { path = "../service", default-features = false } +sp-state-machine = { path = "../../primitives/state-machine" } sc-telemetry = { path = "../telemetry" } -keyring = { package = "sp-keyring", path = "../../primitives/keyring" } +sp-keyring = { path = "../../primitives/keyring" } names = "0.11.0" structopt = "0.3.3" -sc-tracing = { package = "sc-tracing", path = "../tracing" } +sc-tracing = { path = "../tracing" } [target.'cfg(not(target_os = "unknown"))'.dependencies] rpassword = "4.0.1" @@ -42,5 +42,5 @@ tempfile = "3.1.0" [features] wasmtime = [ - "service/wasmtime", + "sc-service/wasmtime", ] diff --git a/substrate/client/cli/src/error.rs b/substrate/client/cli/src/error.rs index bec3aa1ec7..80fbdd553b 100644 --- a/substrate/client/cli/src/error.rs +++ b/substrate/client/cli/src/error.rs @@ -27,7 +27,7 @@ pub enum Error { /// Cli error Cli(clap::Error), /// Service error - Service(service::Error), + Service(sc_service::Error), /// Client error Client(sp_blockchain::Error), /// Input error diff --git a/substrate/client/cli/src/informant.rs b/substrate/client/cli/src/informant.rs index 169fb2a660..be896e180d 100644 --- a/substrate/client/cli/src/informant.rs +++ b/substrate/client/cli/src/informant.rs @@ -16,11 +16,11 @@ //! Console informant. Prints sync progress and block events. Runs on the calling thread. -use client_api::BlockchainEvents; +use sc_client_api::BlockchainEvents; use futures::{StreamExt, TryStreamExt, FutureExt, future, compat::Stream01CompatExt}; use log::{info, warn}; use sp_runtime::traits::Header; -use service::AbstractService; +use sc_service::AbstractService; use std::time::Duration; mod display; diff --git a/substrate/client/cli/src/informant/display.rs b/substrate/client/cli/src/informant/display.rs index e91b41b227..1742becb86 100644 --- a/substrate/client/cli/src/informant/display.rs +++ b/substrate/client/cli/src/informant/display.rs @@ -15,11 +15,11 @@ // along with Substrate. If not, see . use ansi_term::Colour; -use client_api::ClientInfo; +use sc_client_api::ClientInfo; use log::info; -use network::SyncState; +use sc_network::SyncState; use sp_runtime::traits::{Block as BlockT, CheckedDiv, NumberFor, Zero, Saturating}; -use service::NetworkStatus; +use sc_service::NetworkStatus; use std::{convert::{TryFrom, TryInto}, fmt, time}; /// State of the informant display system. diff --git a/substrate/client/cli/src/lib.rs b/substrate/client/cli/src/lib.rs index 70beedc427..d4387c984f 100644 --- a/substrate/client/cli/src/lib.rs +++ b/substrate/client/cli/src/lib.rs @@ -26,20 +26,20 @@ mod execution_strategy; pub mod error; pub mod informant; -use client_api::execution_extensions::ExecutionStrategies; -use service::{ +use sc_client_api::execution_extensions::ExecutionStrategies; +use sc_service::{ config::{Configuration, DatabaseConfig}, ServiceBuilderCommand, RuntimeGenesis, ChainSpecExtension, PruningMode, ChainSpec, }; -use network::{ +use sc_network::{ self, multiaddr::Protocol, config::{ NetworkConfiguration, TransportConfig, NonReservedPeerMode, NodeKeyConfig, build_multiaddr }, }; -use primitives::H256; +use sp_core::H256; use std::{ io::{Write, Read, Seek, Cursor, stdin, stdout, ErrorKind}, iter, fs::{self, File}, @@ -200,12 +200,12 @@ where I: IntoIterator, ::Item: Into + Clone, { - let full_version = service::config::full_version_from_strs( + let full_version = sc_service::config::full_version_from_strs( version.version, version.commit ); - panic_handler::set(version.support_url, &full_version); + sp_panic_handler::set(version.support_url, &full_version); let matches = CoreParams::::clap() .name(version.executable_name) .author(version.author) @@ -333,7 +333,7 @@ impl<'a> ParseAndPrepareBuildSpec<'a> { if spec.boot_nodes().is_empty() && !self.params.disable_default_bootnode { let base_path = base_path(&self.params.shared_params, self.version); - let cfg = service::Configuration::::default_with_spec_and_base_path(spec.clone(), Some(base_path)); + let cfg = sc_service::Configuration::::default_with_spec_and_base_path(spec.clone(), Some(base_path)); let node_key = node_key_config( self.params.node_key_params, &Some(cfg.in_chain_config_dir(DEFAULT_NETWORK_CONFIG_PATH).expect("We provided a base_path")) @@ -348,7 +348,7 @@ impl<'a> ParseAndPrepareBuildSpec<'a> { spec.add_boot_node(addr) } - let json = service::chain_ops::build_spec(spec, raw_output)?; + let json = sc_service::chain_ops::build_spec(spec, raw_output)?; print!("{}", json); @@ -440,7 +440,7 @@ impl<'a> ParseAndPrepareImport<'a> { Exit: IntoExit { let mut config = create_config_with_db_path(spec_factory, &self.params.shared_params, self.version)?; - fill_import_params(&mut config, &self.params.import_params, service::Roles::FULL)?; + fill_import_params(&mut config, &self.params.import_params, sc_service::Roles::FULL)?; let file: Box = match self.params.input { Some(filename) => Box::new(File::open(filename)?), @@ -500,7 +500,7 @@ impl<'a> CheckBlock<'a> { Exit: IntoExit { let mut config = create_config_with_db_path(spec_factory, &self.params.shared_params, self.version)?; - fill_import_params(&mut config, &self.params.import_params, service::Roles::FULL)?; + fill_import_params(&mut config, &self.params.import_params, sc_service::Roles::FULL)?; let input = if self.params.input.starts_with("0x") { &self.params.input[2..] } else { &self.params.input[..] }; let block_id = match FromStr::from_str(input) { @@ -621,8 +621,8 @@ where params.node_key.as_ref().map(parse_ed25519_secret).unwrap_or_else(|| Ok(params.node_key_file .or_else(|| net_config_file(net_config_dir, NODE_KEY_ED25519_FILE)) - .map(network::config::Secret::File) - .unwrap_or(network::config::Secret::New))) + .map(sc_network::config::Secret::File) + .unwrap_or(sc_network::config::Secret::New))) .map(NodeKeyConfig::Ed25519) } } @@ -639,11 +639,11 @@ fn invalid_node_key(e: impl std::fmt::Display) -> error::Error { error::Error::Input(format!("Invalid node key: {}", e)) } -/// Parse a Ed25519 secret key from a hex string into a `network::Secret`. -fn parse_ed25519_secret(hex: &String) -> error::Result { +/// Parse a Ed25519 secret key from a hex string into a `sc_network::Secret`. +fn parse_ed25519_secret(hex: &String) -> error::Result { H256::from_str(&hex).map_err(invalid_node_key).and_then(|bytes| - network::config::identity::ed25519::SecretKey::from_bytes(bytes) - .map(network::config::Secret::Input) + sc_network::config::identity::ed25519::SecretKey::from_bytes(bytes) + .map(sc_network::config::Secret::Input) .map_err(invalid_node_key)) } @@ -728,7 +728,7 @@ fn input_keystore_password() -> Result { /// Fill the password field of the given config instance. fn fill_config_keystore_password( - config: &mut service::Configuration, + config: &mut sc_service::Configuration, cli: &RunCmd, ) -> Result<(), String> { config.keystore_password = if cli.password_interactive { @@ -753,7 +753,7 @@ fn fill_config_keystore_password( pub fn fill_import_params( config: &mut Configuration, cli: &ImportParams, - role: service::Roles, + role: sc_service::Roles, ) -> error::Result<()> where C: Default, @@ -774,10 +774,10 @@ pub fn fill_import_params( // unless `unsafe_pruning` is set. config.pruning = match &cli.pruning { Some(ref s) if s == "archive" => PruningMode::ArchiveAll, - None if role == service::Roles::AUTHORITY => PruningMode::ArchiveAll, + None if role == sc_service::Roles::AUTHORITY => PruningMode::ArchiveAll, None => PruningMode::default(), Some(s) => { - if role == service::Roles::AUTHORITY && !cli.unsafe_pruning { + if role == sc_service::Roles::AUTHORITY && !cli.unsafe_pruning { return Err(error::Error::Input( "Validators should run with state pruning disabled (i.e. archive). \ You can ignore this check with `--unsafe-pruning`.".to_string() @@ -821,11 +821,11 @@ where let is_authority = cli.validator || cli.sentry || is_dev || cli.keyring.account.is_some(); let role = if cli.light { - service::Roles::LIGHT + sc_service::Roles::LIGHT } else if is_authority { - service::Roles::AUTHORITY + sc_service::Roles::AUTHORITY } else { - service::Roles::FULL + sc_service::Roles::FULL }; fill_import_params(&mut config, &cli.import_params, role)?; @@ -856,7 +856,7 @@ where config.sentry_mode = cli.sentry; config.offchain_worker = match (cli.offchain_worker, role) { - (params::OffchainWorkerEnabled::WhenValidating, service::Roles::AUTHORITY) => true, + (params::OffchainWorkerEnabled::WhenValidating, sc_service::Roles::AUTHORITY) => true, (params::OffchainWorkerEnabled::Always, _) => true, (params::OffchainWorkerEnabled::Never, _) => false, (params::OffchainWorkerEnabled::WhenValidating, _) => false, @@ -939,7 +939,7 @@ where let spec = load_spec(cli, spec_factory)?; let base_path = base_path(cli, version); - let mut config = service::Configuration::default_with_spec_and_base_path( + let mut config = sc_service::Configuration::default_with_spec_and_base_path( spec.clone(), Some(base_path), ); @@ -1043,7 +1043,7 @@ fn kill_color(s: &str) -> String { #[cfg(test)] mod tests { use super::*; - use network::config::identity::ed25519; + use sc_network::config::identity::ed25519; #[test] fn tests_node_name_good() { @@ -1074,7 +1074,7 @@ mod tests { node_key_file: None }; node_key_config(params, &net_config_dir).and_then(|c| match c { - NodeKeyConfig::Ed25519(network::config::Secret::Input(ref ski)) + NodeKeyConfig::Ed25519(sc_network::config::Secret::Input(ref ski)) if node_key_type == NodeKeyType::Ed25519 && &sk[..] == ski.as_ref() => Ok(()), _ => Err(error::Error::Input("Unexpected node key config".into())) @@ -1099,7 +1099,7 @@ mod tests { node_key_file: Some(file.clone()) }; node_key_config(params, &net_config_dir).and_then(|c| match c { - NodeKeyConfig::Ed25519(network::config::Secret::File(ref f)) + NodeKeyConfig::Ed25519(sc_network::config::Secret::File(ref f)) if node_key_type == NodeKeyType::Ed25519 && f == &file => Ok(()), _ => Err(error::Error::Input("Unexpected node key config".into())) }) @@ -1131,7 +1131,7 @@ mod tests { let typ = params.node_key_type; node_key_config::(params, &None) .and_then(|c| match c { - NodeKeyConfig::Ed25519(network::config::Secret::New) + NodeKeyConfig::Ed25519(sc_network::config::Secret::New) if typ == NodeKeyType::Ed25519 => Ok(()), _ => Err(error::Error::Input("Unexpected node key config".into())) }) @@ -1144,7 +1144,7 @@ mod tests { let typ = params.node_key_type; node_key_config(params, &Some(net_config_dir.clone())) .and_then(move |c| match c { - NodeKeyConfig::Ed25519(network::config::Secret::File(ref f)) + NodeKeyConfig::Ed25519(sc_network::config::Secret::File(ref f)) if typ == NodeKeyType::Ed25519 && f == &dir.join(NODE_KEY_ED25519_FILE) => Ok(()), _ => Err(error::Error::Input("Unexpected node key config".into())) diff --git a/substrate/client/cli/src/params.rs b/substrate/client/cli/src/params.rs index d81abaa724..7121c53858 100644 --- a/substrate/client/cli/src/params.rs +++ b/substrate/client/cli/src/params.rs @@ -32,13 +32,13 @@ macro_rules! impl_get_log_filter { } } -impl Into for ExecutionStrategy { - fn into(self) -> client_api::ExecutionStrategy { +impl Into for ExecutionStrategy { + fn into(self) -> sc_client_api::ExecutionStrategy { match self { - ExecutionStrategy::Native => client_api::ExecutionStrategy::NativeWhenPossible, - ExecutionStrategy::Wasm => client_api::ExecutionStrategy::AlwaysWasm, - ExecutionStrategy::Both => client_api::ExecutionStrategy::Both, - ExecutionStrategy::NativeElseWasm => client_api::ExecutionStrategy::NativeElseWasm, + ExecutionStrategy::Native => sc_client_api::ExecutionStrategy::NativeWhenPossible, + ExecutionStrategy::Wasm => sc_client_api::ExecutionStrategy::AlwaysWasm, + ExecutionStrategy::Both => sc_client_api::ExecutionStrategy::Both, + ExecutionStrategy::NativeElseWasm => sc_client_api::ExecutionStrategy::NativeElseWasm, } } } @@ -66,12 +66,12 @@ impl WasmExecutionMethod { } } -impl Into for WasmExecutionMethod { - fn into(self) -> service::config::WasmExecutionMethod { +impl Into for WasmExecutionMethod { + fn into(self) -> sc_service::config::WasmExecutionMethod { match self { - WasmExecutionMethod::Interpreted => service::config::WasmExecutionMethod::Interpreted, + WasmExecutionMethod::Interpreted => sc_service::config::WasmExecutionMethod::Interpreted, #[cfg(feature = "wasmtime")] - WasmExecutionMethod::Compiled => service::config::WasmExecutionMethod::Compiled, + WasmExecutionMethod::Compiled => sc_service::config::WasmExecutionMethod::Compiled, #[cfg(not(feature = "wasmtime"))] WasmExecutionMethod::Compiled => panic!( "Substrate must be compiled with \"wasmtime\" feature for compiled Wasm execution" @@ -584,19 +584,19 @@ struct KeyringTestAccountCliValues { help: String, conflicts_with: Vec, name: String, - variant: keyring::Sr25519Keyring, + variant: sp_keyring::Sr25519Keyring, } lazy_static::lazy_static! { /// The Cli values for all test accounts. static ref TEST_ACCOUNTS_CLI_VALUES: Vec = { - keyring::Sr25519Keyring::iter().map(|a| { + sp_keyring::Sr25519Keyring::iter().map(|a| { let help = format!( "Shortcut for `--name {} --validator` with session keys for `{}` added to keystore.", a, a, ); - let conflicts_with = keyring::Sr25519Keyring::iter() + let conflicts_with = sp_keyring::Sr25519Keyring::iter() .filter(|b| a != *b) .map(|b| b.to_string().to_lowercase()) .chain(std::iter::once("name".to_string())) @@ -616,7 +616,7 @@ lazy_static::lazy_static! { /// Wrapper for exposing the keyring test accounts into the Cli. #[derive(Debug, Clone)] pub struct Keyring { - pub account: Option, + pub account: Option, } impl StructOpt for Keyring { diff --git a/substrate/client/consensus/aura/Cargo.toml b/substrate/client/consensus/aura/Cargo.toml index c35d72bd67..cf237b9f82 100644 --- a/substrate/client/consensus/aura/Cargo.toml +++ b/substrate/client/consensus/aura/Cargo.toml @@ -6,38 +6,38 @@ description = "Aura consensus algorithm for substrate" edition = "2018" [dependencies] -app-crypto = { package = "sp-application-crypto", path = "../../../primitives/application-crypto" } -aura_primitives = { package = "sp-consensus-aura", path = "../../../primitives/consensus/aura" } -block-builder-api = { package = "sp-block-builder", path = "../../../primitives/block-builder" } -client = { package = "sc-client", path = "../../" } -client-api = { package = "sc-client-api", path = "../../api" } +sp-application-crypto = { path = "../../../primitives/application-crypto" } +sp-consensus-aura = { path = "../../../primitives/consensus/aura" } +sp-block-builder = { path = "../../../primitives/block-builder" } +sc-client = { path = "../../" } +sc-client-api = { path = "../../api" } codec = { package = "parity-scale-codec", version = "1.0.0" } -consensus_common = { package = "sp-consensus", path = "../../../primitives/consensus/common" } +sp-consensus = { path = "../../../primitives/consensus/common" } derive_more = "0.99.2" futures = { version = "0.3.1", features = ["compat"] } futures01 = { package = "futures", version = "0.1" } futures-timer = "0.4.0" -inherents = { package = "sp-inherents", path = "../../../primitives/inherents" } -keystore = { package = "sc-keystore", path = "../../keystore" } +sp-inherents = { path = "../../../primitives/inherents" } +sc-keystore = { path = "../../keystore" } log = "0.4.8" parking_lot = "0.9.0" -primitives = { package = "sp-core", path = "../../../primitives/core" } +sp-core = { path = "../../../primitives/core" } sp-blockchain = { path = "../../../primitives/blockchain" } sp-io = { path = "../../../primitives/io" } -runtime_version = { package = "sp-version", path = "../../../primitives/version" } -slots = { package = "sc-consensus-slots", path = "../slots" } +sp-version = { path = "../../../primitives/version" } +sc-consensus-slots = { path = "../slots" } sp-api = { path = "../../../primitives/api" } sp-runtime = { path = "../../../primitives/runtime" } sp-timestamp = { path = "../../../primitives/timestamp" } sc-telemetry = { path = "../../telemetry" } [dev-dependencies] -keyring = { package = "sp-keyring", path = "../../../primitives/keyring" } +sp-keyring = { path = "../../../primitives/keyring" } sc-executor = { path = "../../executor" } sc-network = { path = "../../network" } sc-network-test = { path = "../../network/test" } -service = { package = "sc-service", path = "../../service" } -test-client = { package = "substrate-test-runtime-client", path = "../../../test-utils/runtime/client" } +sc-service = { path = "../../service" } +substrate-test-runtime-client = { path = "../../../test-utils/runtime/client" } tokio = "0.1.22" env_logger = "0.7.0" tempfile = "3.1.0" diff --git a/substrate/client/consensus/aura/src/digest.rs b/substrate/client/consensus/aura/src/digest.rs index e788586616..b1633fbfc8 100644 --- a/substrate/client/consensus/aura/src/digest.rs +++ b/substrate/client/consensus/aura/src/digest.rs @@ -19,8 +19,8 @@ //! This implements the digests for AuRa, to allow the private //! `CompatibleDigestItem` trait to appear in public interfaces. -use primitives::Pair; -use aura_primitives::AURA_ENGINE_ID; +use sp_core::Pair; +use sp_consensus_aura::AURA_ENGINE_ID; use sp_runtime::generic::{DigestItem, OpaqueDigestItemId}; use codec::{Encode, Codec}; use std::fmt::Debug; diff --git a/substrate/client/consensus/aura/src/lib.rs b/substrate/client/consensus/aura/src/lib.rs index c9be311b11..82ea2e764c 100644 --- a/substrate/client/consensus/aura/src/lib.rs +++ b/substrate/client/consensus/aura/src/lib.rs @@ -31,28 +31,28 @@ use std::{sync::Arc, time::Duration, thread, marker::PhantomData, hash::Hash, fmt::Debug, pin::Pin}; use codec::{Encode, Decode, Codec}; -use consensus_common::{ +use sp_consensus::{ self, BlockImport, Environment, Proposer, CanAuthorWith, ForkChoiceStrategy, BlockImportParams, BlockOrigin, Error as ConsensusError, SelectChain, SlotData, }; -use consensus_common::import_queue::{ +use sp_consensus::import_queue::{ Verifier, BasicQueue, BoxBlockImport, BoxJustificationImport, BoxFinalityProofImport, }; -use client_api::backend::AuxStore; -use client::{ +use sc_client_api::backend::AuxStore; +use sc_client::{ blockchain::ProvideCache, BlockOf }; use sp_blockchain::{ Result as CResult, well_known_cache_keys::{self, Id as CacheKeyId}, }; -use block_builder_api::BlockBuilder as BlockBuilderApi; +use sp_block_builder::BlockBuilder as BlockBuilderApi; use sp_runtime::{generic::{BlockId, OpaqueDigestItemId}, Justification}; use sp_runtime::traits::{Block as BlockT, Header, DigestItemFor, ProvideRuntimeApi, Zero, Member}; -use primitives::crypto::Pair; -use inherents::{InherentDataProviders, InherentData}; +use sp_core::crypto::Pair; +use sp_inherents::{InherentDataProviders, InherentData}; use futures::prelude::*; use parking_lot::Mutex; @@ -65,21 +65,21 @@ use sp_timestamp::{ use sc_telemetry::{telemetry, CONSENSUS_TRACE, CONSENSUS_DEBUG, CONSENSUS_INFO}; -use slots::{CheckedHeader, SlotWorker, SlotInfo, SlotCompatible}; -use slots::check_equivocation; +use sc_consensus_slots::{CheckedHeader, SlotWorker, SlotInfo, SlotCompatible}; +use sc_consensus_slots::check_equivocation; -use keystore::KeyStorePtr; +use sc_keystore::KeyStorePtr; use sp_api::ApiExt; -pub use aura_primitives::{ +pub use sp_consensus_aura::{ ConsensusLog, AuraApi, AURA_ENGINE_ID, inherents::{ InherentType as AuraInherent, AuraInherentData, INHERENT_IDENTIFIER, InherentDataProvider, }, }; -pub use consensus_common::SyncOracle; +pub use sp_consensus::SyncOracle; pub use digest::CompatibleDigestItem; mod digest; @@ -88,7 +88,7 @@ type AuthorityId

=

::Public; /// A slot duration. Create with `get_or_compute`. #[derive(Clone, Copy, Debug, Encode, Decode, Hash, PartialOrd, Ord, PartialEq, Eq)] -pub struct SlotDuration(slots::SlotDuration); +pub struct SlotDuration(sc_consensus_slots::SlotDuration); impl SlotDuration { /// Either fetch the slot duration from disk or compute it from the genesis @@ -100,7 +100,7 @@ impl SlotDuration { C: AuxStore + ProvideRuntimeApi, C::Api: AuraApi, { - slots::SlotDuration::get_or_compute(client, |a, b| a.slot_duration(b)).map(Self) + sc_consensus_slots::SlotDuration::get_or_compute(client, |a, b| a.slot_duration(b)).map(Self) } /// Get the slot duration in milliseconds. @@ -133,11 +133,11 @@ impl SlotCompatible for AuraSlotCompatible { fn extract_timestamp_and_slot( &self, data: &InherentData - ) -> Result<(TimestampInherent, AuraInherent, std::time::Duration), consensus_common::Error> { + ) -> Result<(TimestampInherent, AuraInherent, std::time::Duration), sp_consensus::Error> { data.timestamp_inherent_data() .and_then(|t| data.aura_inherent_data().map(|a| (t, a))) .map_err(Into::into) - .map_err(consensus_common::Error::InherentData) + .map_err(sp_consensus::Error::InherentData) .map(|(x, y)| (x, y, Default::default())) } } @@ -154,7 +154,7 @@ pub fn start_aura( force_authoring: bool, keystore: KeyStorePtr, can_author_with: CAW, -) -> Result, consensus_common::Error> where +) -> Result, sp_consensus::Error> where B: BlockT, C: ProvideRuntimeApi + BlockOf + ProvideCache + AuxStore + Send + Sync, C::Api: AuraApi>, @@ -167,7 +167,7 @@ pub fn start_aura( P::Signature: Hash + Member + Encode + Decode, H: Header, I: BlockImport + Send + Sync + 'static, - Error: ::std::error::Error + Send + From<::consensus_common::Error> + From + 'static, + Error: ::std::error::Error + Send + From<::sp_consensus::Error> + From + 'static, SO: SyncOracle + Send + Sync + Clone, CAW: CanAuthorWith + Send, { @@ -184,7 +184,7 @@ pub fn start_aura( &inherent_data_providers, slot_duration.0.slot_duration() )?; - Ok(slots::start_slot_worker::<_, _, _, _, _, AuraSlotCompatible, _>( + Ok(sc_consensus_slots::start_slot_worker::<_, _, _, _, _, AuraSlotCompatible, _>( slot_duration.0, select_chain, worker, @@ -205,7 +205,7 @@ struct AuraWorker { _key_type: PhantomData

, } -impl slots::SimpleSlotWorker for AuraWorker where +impl sc_consensus_slots::SimpleSlotWorker for AuraWorker where B: BlockT, C: ProvideRuntimeApi + BlockOf + ProvideCache + Sync, C::Api: AuraApi>, @@ -218,7 +218,7 @@ impl slots::SimpleSlotWorker for AuraWorker + From + 'static, + Error: ::std::error::Error + Send + From<::sp_consensus::Error> + From + 'static, { type EpochData = Vec>; type Claim = P; @@ -234,7 +234,7 @@ impl slots::SimpleSlotWorker for AuraWorker Result { + fn epoch_data(&self, header: &B::Header, _slot_number: u64) -> Result { authorities(self.client.as_ref(), &BlockId::Hash(header.hash())) } @@ -252,7 +252,7 @@ impl slots::SimpleSlotWorker for AuraWorker(&p, app_crypto::key_types::AURA).ok() + .key_pair_by_type::

(&p, sp_application_crypto::key_types::AURA).ok() }) } @@ -267,7 +267,7 @@ impl slots::SimpleSlotWorker for AuraWorker, Self::Claim, - ) -> consensus_common::BlockImportParams + Send> { + ) -> sp_consensus::BlockImportParams + Send> { Box::new(|header, header_hash, body, pair| { // sign the pre-sealed hash of the block and then // add it to a digest item. @@ -297,9 +297,9 @@ impl slots::SimpleSlotWorker for AuraWorker Result { + fn proposer(&mut self, block: &B::Header) -> Result { self.env.init(block).map_err(|e| { - consensus_common::Error::ClientImport(format!("{:?}", e)).into() + sp_consensus::Error::ClientImport(format!("{:?}", e)).into() }) } @@ -343,12 +343,12 @@ impl SlotWorker for AuraWorker + From + 'static, + Error: ::std::error::Error + Send + From<::sp_consensus::Error> + From + 'static, { - type OnSlot = Pin> + Send>>; + type OnSlot = Pin> + Send>>; fn on_slot(&mut self, chain_head: B::Header, slot_info: SlotInfo) -> Self::OnSlot { - >::on_slot(self, chain_head, slot_info) + >::on_slot(self, chain_head, slot_info) } } @@ -416,7 +416,7 @@ fn check_header( ) -> Result)>, Error> where DigestItemFor: CompatibleDigestItem

, P::Signature: Decode, - C: client_api::backend::AuxStore, + C: sc_client_api::backend::AuxStore, P::Public: Encode + Decode + PartialEq + Clone, T: Send + Sync + 'static, { @@ -471,7 +471,7 @@ fn check_header( pub struct AuraVerifier { client: Arc, phantom: PhantomData

, - inherent_data_providers: inherents::InherentDataProviders, + inherent_data_providers: sp_inherents::InherentDataProviders, transaction_pool: Option>, } @@ -531,7 +531,7 @@ impl AuraVerifier #[forbid(deprecated)] impl Verifier for AuraVerifier where - C: ProvideRuntimeApi + Send + Sync + client_api::backend::AuxStore + ProvideCache + BlockOf, + C: ProvideRuntimeApi + Send + Sync + sc_client_api::backend::AuxStore + ProvideCache + BlockOf, C::Api: BlockBuilderApi + AuraApi> + ApiExt, DigestItemFor: CompatibleDigestItem

, P: Pair + Send + Sync + 'static, @@ -661,7 +661,7 @@ fn initialize_authorities_cache(client: &C) -> Result<(), ConsensusErro return Ok(()); } - let map_err = |error| consensus_common::Error::from(consensus_common::Error::ClientImport( + let map_err = |error| sp_consensus::Error::from(sp_consensus::Error::ClientImport( format!( "Error initializing authorities cache: {}", error, @@ -687,7 +687,7 @@ fn authorities(client: &C, at: &BlockId) -> Result, Consensus .and_then(|(_, _, v)| Decode::decode(&mut &v[..]).ok()) ) .or_else(|| AuraApi::authorities(&*client.runtime_api(), at).ok()) - .ok_or_else(|| consensus_common::Error::InvalidAuthoritiesSet.into()) + .ok_or_else(|| sp_consensus::Error::InvalidAuthoritiesSet.into()) } /// The Aura import queue type. @@ -697,12 +697,12 @@ pub type AuraImportQueue = BasicQueue; fn register_aura_inherent_data_provider( inherent_data_providers: &InherentDataProviders, slot_duration: u64, -) -> Result<(), consensus_common::Error> { +) -> Result<(), sp_consensus::Error> { if !inherent_data_providers.has_provider(&INHERENT_IDENTIFIER) { inherent_data_providers .register_provider(InherentDataProvider::new(slot_duration)) .map_err(Into::into) - .map_err(consensus_common::Error::InherentData) + .map_err(sp_consensus::Error::InherentData) } else { Ok(()) } @@ -717,7 +717,7 @@ pub fn import_queue( client: Arc, inherent_data_providers: InherentDataProviders, transaction_pool: Option>, -) -> Result, consensus_common::Error> where +) -> Result, sp_consensus::Error> where B: BlockT, C: 'static + ProvideRuntimeApi + BlockOf + ProvideCache + Send + Sync + AuxStore, C::Api: BlockBuilderApi + AuraApi> + ApiExt, @@ -747,24 +747,23 @@ pub fn import_queue( #[cfg(test)] mod tests { use super::*; - use consensus_common::NoNetwork as DummyOracle; + use sp_consensus::NoNetwork as DummyOracle; use sc_network_test::{Block as TestBlock, *}; use sp_runtime::traits::{Block as BlockT, DigestFor}; use sc_network::config::ProtocolConfig; use parking_lot::Mutex; use tokio::runtime::current_thread; - use keyring::sr25519::Keyring; - use client::BlockchainEvents; - use test_client; - use aura_primitives::sr25519::AuthorityPair; + use sp_keyring::sr25519::Keyring; + use sc_client::BlockchainEvents; + use sp_consensus_aura::sr25519::AuthorityPair; type Error = sp_blockchain::Error; - type TestClient = client::Client< - test_client::Backend, - test_client::Executor, + type TestClient = sc_client::Client< + substrate_test_runtime_client::Backend, + substrate_test_runtime_client::Executor, TestBlock, - test_client::runtime::RuntimeApi + substrate_test_runtime_client::runtime::RuntimeApi >; struct DummyFactory(Arc); @@ -875,7 +874,7 @@ mod tests { let client = peer.client().as_full().expect("full clients are created").clone(); let select_chain = peer.select_chain().expect("full client has a select chain"); let keystore_path = tempfile::tempdir().expect("Creates keystore path"); - let keystore = keystore::Store::open(keystore_path.path(), None).expect("Creates keystore."); + let keystore = sc_keystore::Store::open(keystore_path.path(), None).expect("Creates keystore."); keystore.write().insert_ephemeral_from_seed::(&key.to_seed()) .expect("Creates authority key"); @@ -906,7 +905,7 @@ mod tests { inherent_data_providers, false, keystore, - consensus_common::AlwaysCanAuthor, + sp_consensus::AlwaysCanAuthor, ).expect("Starts aura"); runtime.spawn(aura); @@ -923,7 +922,7 @@ mod tests { #[test] fn authorities_call_works() { - let client = test_client::new(); + let client = substrate_test_runtime_client::new(); assert_eq!(client.info().chain.best_number, 0); assert_eq!(authorities(&client, &BlockId::Number(0)).unwrap(), vec![ diff --git a/substrate/client/consensus/babe/Cargo.toml b/substrate/client/consensus/babe/Cargo.toml index d03157415a..d9f3eaabb0 100644 --- a/substrate/client/consensus/babe/Cargo.toml +++ b/substrate/client/consensus/babe/Cargo.toml @@ -7,26 +7,26 @@ edition = "2018" [dependencies] codec = { package = "parity-scale-codec", version = "1.0.0", features = ["derive"] } -babe_primitives = { package = "sp-consensus-babe", path = "../../../primitives/consensus/babe" } -primitives = { package = "sp-core", path = "../../../primitives/core" } -app-crypto = { package = "sp-application-crypto", path = "../../../primitives/application-crypto" } +sp-consensus-babe = { path = "../../../primitives/consensus/babe" } +sp-core = { path = "../../../primitives/core" } +sp-application-crypto = { path = "../../../primitives/application-crypto" } num-bigint = "0.2.3" num-rational = "0.2.2" num-traits = "0.2.8" -runtime-version = { package = "sp-version", path = "../../../primitives/version" } +sp-version = { path = "../../../primitives/version" } sp-io = { path = "../../../primitives/io" } -inherents = { package = "sp-inherents", path = "../../../primitives/inherents" } +sp-inherents = { path = "../../../primitives/inherents" } sp-timestamp = { path = "../../../primitives/timestamp" } sc-telemetry = { path = "../../telemetry" } -keystore = { package = "sc-keystore", path = "../../keystore" } -client-api = { package = "sc-client-api", path = "../../api" } -client = { package = "sc-client", path = "../../" } +sc-keystore = { path = "../../keystore" } +sc-client-api = { path = "../../api" } +sc-client = { path = "../../" } sp-api = { path = "../../../primitives/api" } -block-builder-api = { package = "sp-block-builder", path = "../../../primitives/block-builder" } +sp-block-builder = { path = "../../../primitives/block-builder" } sp-blockchain = { path = "../../../primitives/blockchain" } -consensus-common = { package = "sp-consensus", path = "../../../primitives/consensus/common" } -uncles = { package = "sc-consensus-uncles", path = "../uncles" } -slots = { package = "sc-consensus-slots", path = "../slots" } +sp-consensus = { path = "../../../primitives/consensus/common" } +sc-consensus-uncles = { path = "../uncles" } +sc-consensus-slots = { path = "../slots" } sp-runtime = { path = "../../../primitives/runtime" } fork-tree = { path = "../../../utils/fork-tree" } futures = { version = "0.3.1", features = ["compat"] } @@ -41,13 +41,13 @@ pdqselect = "0.1.0" derive_more = "0.99.2" [dev-dependencies] -keyring = { package = "sp-keyring", path = "../../../primitives/keyring" } +sp-keyring = { path = "../../../primitives/keyring" } sc-executor = { path = "../../executor" } sc-network = { path = "../../network" } sc-network-test = { path = "../../network/test" } -service = { package = "sc-service", path = "../../service" } -test-client = { package = "substrate-test-runtime-client", path = "../../../test-utils/runtime/client" } -block-builder = { package = "sc-block-builder", path = "../../block-builder" } +sc-service = { path = "../../service" } +substrate-test-runtime-client = { path = "../../../test-utils/runtime/client" } +sc-block-builder = { path = "../../block-builder" } tokio = "0.1.22" env_logger = "0.7.0" tempfile = "3.1.0" diff --git a/substrate/client/consensus/babe/src/authorship.rs b/substrate/client/consensus/babe/src/authorship.rs index 93405ff777..52d593c763 100644 --- a/substrate/client/consensus/babe/src/authorship.rs +++ b/substrate/client/consensus/babe/src/authorship.rs @@ -17,13 +17,13 @@ //! BABE authority selection and slot claiming. use merlin::Transcript; -use babe_primitives::{AuthorityId, BabeAuthorityWeight, BABE_ENGINE_ID, BABE_VRF_PREFIX}; -use babe_primitives::{Epoch, SlotNumber, AuthorityPair, BabePreDigest, BabeConfiguration}; -use primitives::{U256, blake2_256}; +use sp_consensus_babe::{AuthorityId, BabeAuthorityWeight, BABE_ENGINE_ID, BABE_VRF_PREFIX}; +use sp_consensus_babe::{Epoch, SlotNumber, AuthorityPair, BabePreDigest, BabeConfiguration}; +use sp_core::{U256, blake2_256}; use codec::Encode; use schnorrkel::vrf::VRFInOut; -use primitives::Pair; -use keystore::KeyStorePtr; +use sp_core::Pair; +use sc_keystore::KeyStorePtr; /// Calculates the primary selection threshold for a given authority, taking /// into account `c` (`1 - c` represents the probability of a slot being empty). @@ -162,8 +162,8 @@ pub(super) fn claim_slot( } fn get_keypair(q: &AuthorityPair) -> &schnorrkel::Keypair { - use primitives::crypto::IsWrappedBy; - primitives::sr25519::Pair::from_ref(q).as_ref() + use sp_core::crypto::IsWrappedBy; + sp_core::sr25519::Pair::from_ref(q).as_ref() } /// Claim a primary slot if it is our turn. Returns `None` if it is not our turn. diff --git a/substrate/client/consensus/babe/src/aux_schema.rs b/substrate/client/consensus/babe/src/aux_schema.rs index f90c3e233a..0e37a8b3a5 100644 --- a/substrate/client/consensus/babe/src/aux_schema.rs +++ b/substrate/client/consensus/babe/src/aux_schema.rs @@ -19,10 +19,10 @@ use log::info; use codec::{Decode, Encode}; -use client_api::backend::AuxStore; +use sc_client_api::backend::AuxStore; use sp_blockchain::{Result as ClientResult, Error as ClientError}; use sp_runtime::traits::Block as BlockT; -use babe_primitives::BabeBlockWeight; +use sp_consensus_babe::BabeBlockWeight; use super::{epoch_changes::EpochChangesFor, SharedEpochChanges}; diff --git a/substrate/client/consensus/babe/src/epoch_changes.rs b/substrate/client/consensus/babe/src/epoch_changes.rs index 5cb1c4f607..06b459c0f7 100644 --- a/substrate/client/consensus/babe/src/epoch_changes.rs +++ b/substrate/client/consensus/babe/src/epoch_changes.rs @@ -20,14 +20,14 @@ //! persistent DAG superimposed over the forks of the blockchain. use std::sync::Arc; -use babe_primitives::{Epoch, SlotNumber, NextEpochDescriptor}; +use sp_consensus_babe::{Epoch, SlotNumber, NextEpochDescriptor}; use fork_tree::ForkTree; use parking_lot::{Mutex, MutexGuard}; use sp_runtime::traits::{Block as BlockT, NumberFor, One, Zero}; use codec::{Encode, Decode}; -use client_api::utils::is_descendent_of; +use sc_client_api::utils::is_descendent_of; use sp_blockchain::{HeaderMetadata, HeaderBackend, Error as ClientError}; -use primitives::H256; +use sp_core::H256; use std::ops::Add; /// A builder for `is_descendent_of` functions. diff --git a/substrate/client/consensus/babe/src/lib.rs b/substrate/client/consensus/babe/src/lib.rs index 84b018ac59..d46486b1d8 100644 --- a/substrate/client/consensus/babe/src/lib.rs +++ b/substrate/client/consensus/babe/src/lib.rs @@ -58,15 +58,15 @@ #![forbid(unsafe_code)] #![warn(missing_docs)] -pub use babe_primitives::{ +pub use sp_consensus_babe::{ BabeApi, ConsensusLog, BABE_ENGINE_ID, BabePreDigest, SlotNumber, BabeConfiguration, CompatibleDigestItem, }; -pub use consensus_common::SyncOracle; +pub use sp_consensus::SyncOracle; use std::{collections::HashMap, sync::Arc, u64, pin::Pin, time::{Instant, Duration}}; -use babe_primitives; -use consensus_common::{ImportResult, CanAuthorWith}; -use consensus_common::import_queue::{ +use sp_consensus_babe; +use sp_consensus::{ImportResult, CanAuthorWith}; +use sp_consensus::import_queue::{ BoxJustificationImport, BoxFinalityProofImport, }; use sp_runtime::{generic::{BlockId, OpaqueDigestItemId}, Justification}; @@ -74,32 +74,32 @@ use sp_runtime::traits::{ Block as BlockT, Header, DigestItemFor, ProvideRuntimeApi, Zero, }; -use keystore::KeyStorePtr; +use sc_keystore::KeyStorePtr; use parking_lot::Mutex; -use primitives::{Blake2Hasher, H256, Pair}; -use inherents::{InherentDataProviders, InherentData}; +use sp_core::{Blake2Hasher, H256, Pair}; +use sp_inherents::{InherentDataProviders, InherentData}; use sc_telemetry::{telemetry, CONSENSUS_TRACE, CONSENSUS_DEBUG}; -use consensus_common::{ +use sp_consensus::{ self, BlockImport, Environment, Proposer, BlockCheckParams, ForkChoiceStrategy, BlockImportParams, BlockOrigin, Error as ConsensusError, SelectChain, SlotData, }; -use babe_primitives::inherents::BabeInherentData; +use sp_consensus_babe::inherents::BabeInherentData; use sp_timestamp::{TimestampInherentData, InherentType as TimestampInherent}; -use consensus_common::import_queue::{Verifier, BasicQueue, CacheKeyId}; -use client_api::{ +use sp_consensus::import_queue::{Verifier, BasicQueue, CacheKeyId}; +use sc_client_api::{ backend::{AuxStore, Backend}, call_executor::CallExecutor, BlockchainEvents, ProvideUncles, }; -use client::Client; +use sc_client::Client; -use block_builder_api::BlockBuilder as BlockBuilderApi; +use sp_block_builder::BlockBuilder as BlockBuilderApi; -use slots::{CheckedHeader, check_equivocation}; +use sc_consensus_slots::{CheckedHeader, check_equivocation}; use futures::prelude::*; use log::{warn, debug, info, trace}; -use slots::{SlotWorker, SlotInfo, SlotCompatible}; +use sc_consensus_slots::{SlotWorker, SlotInfo, SlotCompatible}; use epoch_changes::descendent_query; use sp_blockchain::{ Result as ClientResult, Error as ClientError, @@ -115,7 +115,7 @@ mod epoch_changes; mod authorship; #[cfg(test)] mod tests; -pub use babe_primitives::{ +pub use sp_consensus_babe::{ AuthorityId, AuthorityPair, AuthoritySignature, Epoch, NextEpochDescriptor, }; pub use epoch_changes::{EpochChanges, EpochChangesFor, SharedEpochChanges}; @@ -130,7 +130,7 @@ enum Error { #[display(fmt = "Multiple BABE epoch change digests, rejecting!")] MultipleEpochChangeDigests, #[display(fmt = "Could not extract timestamp and slot: {:?}", _0)] - Extraction(consensus_common::Error), + Extraction(sp_consensus::Error), #[display(fmt = "Could not fetch epoch at {:?}", _0)] FetchEpoch(B::Hash), #[display(fmt = "Header {:?} rejected: too far in the future", _0)] @@ -172,7 +172,7 @@ enum Error { #[display(fmt = "Checking inherents failed: {}", _0)] CheckInherents(String), Client(sp_blockchain::Error), - Runtime(inherents::Error), + Runtime(sp_inherents::Error), ForkTree(Box>), } @@ -201,7 +201,7 @@ macro_rules! babe_info { // and `super::babe::Config` can be eliminated. // https://github.com/paritytech/substrate/issues/2434 #[derive(Clone)] -pub struct Config(slots::SlotDuration); +pub struct Config(sc_consensus_slots::SlotDuration); impl Config { /// Either fetch the slot duration from disk or compute it from the genesis @@ -210,7 +210,7 @@ impl Config { C: AuxStore + ProvideRuntimeApi, C::Api: BabeApi, { trace!(target: "babe", "Getting slot duration"); - match slots::SlotDuration::get_or_compute(client, |a, b| a.configuration(b)).map(Self) { + match sc_consensus_slots::SlotDuration::get_or_compute(client, |a, b| a.configuration(b)).map(Self) { Ok(s) => Ok(s), Err(s) => { warn!(target: "babe", "Failed to get slot duration"); @@ -289,7 +289,7 @@ pub fn start_babe(BabeParams { can_author_with, }: BabeParams) -> Result< impl futures01::Future, - consensus_common::Error, + sp_consensus::Error, > where B: BlockT, C: ProvideRuntimeApi + ProvideCache + ProvideUncles + BlockchainEvents @@ -300,7 +300,7 @@ pub fn start_babe(BabeParams { E::Proposer: Proposer, >::Create: Unpin + Send + 'static, I: BlockImport + Send + Sync + 'static, - Error: std::error::Error + Send + From<::consensus_common::Error> + From + 'static, + Error: std::error::Error + Send + From<::sp_consensus::Error> + From + 'static, SO: SyncOracle + Send + Sync + Clone, CAW: CanAuthorWith + Send, { @@ -317,14 +317,14 @@ pub fn start_babe(BabeParams { }; register_babe_inherent_data_provider(&inherent_data_providers, config.slot_duration())?; - uncles::register_uncles_inherent_data_provider( + sc_consensus_uncles::register_uncles_inherent_data_provider( client.clone(), select_chain.clone(), &inherent_data_providers, )?; babe_info!("Starting BABE Authorship worker"); - let slot_worker = slots::start_slot_worker( + let slot_worker = sc_consensus_slots::start_slot_worker( config.0, select_chain, worker, @@ -348,7 +348,7 @@ struct BabeWorker { config: Config, } -impl slots::SimpleSlotWorker for BabeWorker where +impl sc_consensus_slots::SimpleSlotWorker for BabeWorker where B: BlockT, C: ProvideRuntimeApi + ProvideCache + HeaderBackend + HeaderMetadata, C::Api: BabeApi, @@ -357,7 +357,7 @@ impl slots::SimpleSlotWorker for BabeWorker>::Create: Unpin + Send + 'static, I: BlockImport + Send + Sync + 'static, SO: SyncOracle + Send + Clone, - Error: std::error::Error + Send + From<::consensus_common::Error> + From + 'static, + Error: std::error::Error + Send + From<::sp_consensus::Error> + From + 'static, { type EpochData = Epoch; type Claim = (BabePreDigest, AuthorityPair); @@ -373,7 +373,7 @@ impl slots::SimpleSlotWorker for BabeWorker Result { + fn epoch_data(&self, parent: &B::Header, slot_number: u64) -> Result { self.epoch_changes.lock().epoch_for_child_of( descendent_query(&*self.client), &parent.hash(), @@ -383,7 +383,7 @@ impl slots::SimpleSlotWorker for BabeWorker usize { @@ -422,7 +422,7 @@ impl slots::SimpleSlotWorker for BabeWorker, Self::Claim, - ) -> consensus_common::BlockImportParams + Send> { + ) -> sp_consensus::BlockImportParams + Send> { Box::new(|header, header_hash, body, (_, pair)| { // sign the pre-sealed hash of the block and then // add it to a digest item. @@ -455,9 +455,9 @@ impl slots::SimpleSlotWorker for BabeWorker Result { + fn proposer(&mut self, block: &B::Header) -> Result { self.env.init(block).map_err(|e| { - consensus_common::Error::ClientImport(format!("{:?}", e)) + sp_consensus::Error::ClientImport(format!("{:?}", e)) }) } @@ -510,12 +510,12 @@ impl SlotWorker for BabeWorker where >::Create: Unpin + Send + 'static, I: BlockImport + Send + Sync + 'static, SO: SyncOracle + Send + Sync + Clone, - Error: std::error::Error + Send + From<::consensus_common::Error> + From + 'static, + Error: std::error::Error + Send + From<::sp_consensus::Error> + From + 'static, { - type OnSlot = Pin> + Send>>; + type OnSlot = Pin> + Send>>; fn on_slot(&mut self, chain_head: B::Header, slot_info: SlotInfo) -> Self::OnSlot { - >::on_slot(self, chain_head, slot_info) + >::on_slot(self, chain_head, slot_info) } } @@ -571,12 +571,12 @@ impl SlotCompatible for TimeSource { fn extract_timestamp_and_slot( &self, data: &InherentData, - ) -> Result<(TimestampInherent, u64, std::time::Duration), consensus_common::Error> { + ) -> Result<(TimestampInherent, u64, std::time::Duration), sp_consensus::Error> { trace!(target: "babe", "extract timestamp"); data.timestamp_inherent_data() .and_then(|t| data.babe_inherent_data().map(|a| (t, a))) .map_err(Into::into) - .map_err(consensus_common::Error::InherentData) + .map_err(sp_consensus::Error::InherentData) .map(|(x, y)| (x, y, self.0.lock().0.take().unwrap_or_default())) } } @@ -592,7 +592,7 @@ pub struct BabeLink { pub struct BabeVerifier { client: Arc>, api: Arc, - inherent_data_providers: inherents::InherentDataProviders, + inherent_data_providers: sp_inherents::InherentDataProviders, config: Config, epoch_changes: SharedEpochChanges, time_source: TimeSource, @@ -818,13 +818,13 @@ pub type BabeImportQueue = BasicQueue; fn register_babe_inherent_data_provider( inherent_data_providers: &InherentDataProviders, slot_duration: u64, -) -> Result<(), consensus_common::Error> { +) -> Result<(), sp_consensus::Error> { debug!(target: "babe", "Registering"); - if !inherent_data_providers.has_provider(&babe_primitives::inherents::INHERENT_IDENTIFIER) { + if !inherent_data_providers.has_provider(&sp_consensus_babe::inherents::INHERENT_IDENTIFIER) { inherent_data_providers - .register_provider(babe_primitives::inherents::InherentDataProvider::new(slot_duration)) + .register_provider(sp_consensus_babe::inherents::InherentDataProvider::new(slot_duration)) .map_err(Into::into) - .map_err(consensus_common::Error::InherentData) + .map_err(sp_consensus::Error::InherentData) } else { Ok(()) } diff --git a/substrate/client/consensus/babe/src/tests.rs b/substrate/client/consensus/babe/src/tests.rs index 48b58eacd8..8ee4ae22e2 100644 --- a/substrate/client/consensus/babe/src/tests.rs +++ b/substrate/client/consensus/babe/src/tests.rs @@ -22,10 +22,10 @@ use super::*; use authorship::claim_slot; -use babe_primitives::{AuthorityPair, SlotNumber}; -use block_builder::BlockBuilder; -use consensus_common::NoNetwork as DummyOracle; -use consensus_common::import_queue::{ +use sp_consensus_babe::{AuthorityPair, SlotNumber}; +use sc_block_builder::BlockBuilder; +use sp_consensus::NoNetwork as DummyOracle; +use sp_consensus::import_queue::{ BoxBlockImport, BoxJustificationImport, BoxFinalityProofImport, }; use sc_network_test::*; @@ -33,8 +33,7 @@ use sc_network_test::{Block as TestBlock, PeersClient}; use sc_network::config::{BoxFinalityProofRequestBuilder, ProtocolConfig}; use sp_runtime::{generic::DigestItem, traits::{Block as BlockT, DigestFor}}; use tokio::runtime::current_thread; -use client_api::BlockchainEvents; -use test_client; +use sc_client_api::BlockchainEvents; use log::debug; use std::{time::Duration, cell::RefCell}; @@ -42,11 +41,11 @@ type Item = DigestItem; type Error = sp_blockchain::Error; -type TestClient = client::Client< - test_client::Backend, - test_client::Executor, +type TestClient = sc_client::Client< + substrate_test_runtime_client::Backend, + substrate_test_runtime_client::Executor, TestBlock, - test_client::runtime::RuntimeApi, + substrate_test_runtime_client::runtime::RuntimeApi, >; #[derive(Copy, Clone, PartialEq)] @@ -196,10 +195,10 @@ type TestExtrinsic = ::Extrinsic; pub struct TestVerifier { inner: BabeVerifier< - test_client::Backend, - test_client::Executor, + substrate_test_runtime_client::Backend, + substrate_test_runtime_client::Executor, TestBlock, - test_client::runtime::RuntimeApi, + substrate_test_runtime_client::runtime::RuntimeApi, PeersFullClient, >, mutator: Mutator, @@ -358,7 +357,7 @@ fn run_one_test( let select_chain = peer.select_chain().expect("Full client has select_chain"); let keystore_path = tempfile::tempdir().expect("Creates keystore path"); - let keystore = keystore::Store::open(keystore_path.path(), None).expect("Creates keystore"); + let keystore = sc_keystore::Store::open(keystore_path.path(), None).expect("Creates keystore"); keystore.write().insert_ephemeral_from_seed::(seed).expect("Generates authority key"); keystore_paths.push(keystore_path); @@ -403,7 +402,7 @@ fn run_one_test( force_authoring: false, babe_link: data.link.clone(), keystore, - can_author_with: consensus_common::AlwaysCanAuthor, + can_author_with: sp_consensus::AlwaysCanAuthor, }).expect("Starts babe")); } @@ -483,7 +482,7 @@ fn sig_is_not_pre_digest() { fn can_author_block() { let _ = env_logger::try_init(); let keystore_path = tempfile::tempdir().expect("Creates keystore path"); - let keystore = keystore::Store::open(keystore_path.path(), None).expect("Creates keystore"); + let keystore = sc_keystore::Store::open(keystore_path.path(), None).expect("Creates keystore"); let pair = keystore.write().insert_ephemeral_from_seed::("//Alice") .expect("Generates authority pair"); @@ -634,7 +633,7 @@ fn importing_block_one_sets_genesis_epoch() { #[test] fn importing_epoch_change_block_prunes_tree() { - use client_api::Finalizer; + use sc_client_api::Finalizer; let mut net = BabeTestNet::new(1); diff --git a/substrate/client/consensus/babe/src/verification.rs b/substrate/client/consensus/babe/src/verification.rs index 353fed808c..0717e81a49 100644 --- a/substrate/client/consensus/babe/src/verification.rs +++ b/substrate/client/consensus/babe/src/verification.rs @@ -17,10 +17,10 @@ //! Verification for BABE headers. use schnorrkel::vrf::{VRFOutput, VRFProof}; use sp_runtime::{traits::Header, traits::DigestItemFor}; -use primitives::{Pair, Public}; -use babe_primitives::{Epoch, BabePreDigest, CompatibleDigestItem, AuthorityId}; -use babe_primitives::{AuthoritySignature, SlotNumber, AuthorityIndex, AuthorityPair}; -use slots::CheckedHeader; +use sp_core::{Pair, Public}; +use sp_consensus_babe::{Epoch, BabePreDigest, CompatibleDigestItem, AuthorityId}; +use sp_consensus_babe::{AuthoritySignature, SlotNumber, AuthorityIndex, AuthorityPair}; +use sc_consensus_slots::CheckedHeader; use log::{debug, trace}; use super::{find_pre_digest, babe_err, BlockT, Error}; use super::authorship::{make_transcript, calculate_primary_threshold, check_primary_threshold, secondary_slot_author}; diff --git a/substrate/client/consensus/pow/Cargo.toml b/substrate/client/consensus/pow/Cargo.toml index b4195c0e0e..eeea954f77 100644 --- a/substrate/client/consensus/pow/Cargo.toml +++ b/substrate/client/consensus/pow/Cargo.toml @@ -7,14 +7,14 @@ edition = "2018" [dependencies] codec = { package = "parity-scale-codec", version = "1.0.0", features = ["derive"] } -primitives = { package = "sp-core", path = "../../../primitives/core" } +sp-core = { path = "../../../primitives/core" } sp-blockchain = { path = "../../../primitives/blockchain" } sp-runtime = { path = "../../../primitives/runtime" } -client-api = { package = "sc-client-api", path = "../../api" } -block-builder-api = { package = "sp-block-builder", path = "../../../primitives/block-builder" } -inherents = { package = "sp-inherents", path = "../../../primitives/inherents" } -pow-primitives = { package = "sp-consensus-pow", path = "../../../primitives/consensus/pow" } -consensus-common = { package = "sp-consensus", path = "../../../primitives/consensus/common" } +sc-client-api = { path = "../../api" } +sp-block-builder = { path = "../../../primitives/block-builder" } +sp-inherents = { path = "../../../primitives/inherents" } +sp-consensus-pow = { path = "../../../primitives/consensus/pow" } +sp-consensus = { path = "../../../primitives/consensus/common" } log = "0.4.8" futures = { version = "0.3.1", features = ["compat"] } sp-timestamp = { path = "../../../primitives/timestamp" } diff --git a/substrate/client/consensus/pow/src/lib.rs b/substrate/client/consensus/pow/src/lib.rs index 087791ce89..b620a78525 100644 --- a/substrate/client/consensus/pow/src/lib.rs +++ b/substrate/client/consensus/pow/src/lib.rs @@ -32,23 +32,23 @@ use std::sync::Arc; use std::thread; use std::collections::HashMap; -use client_api::{BlockOf, backend::AuxStore}; +use sc_client_api::{BlockOf, backend::AuxStore}; use sp_blockchain::{HeaderBackend, ProvideCache, well_known_cache_keys::Id as CacheKeyId}; -use block_builder_api::BlockBuilder as BlockBuilderApi; +use sp_block_builder::BlockBuilder as BlockBuilderApi; use sp_runtime::{Justification, RuntimeString}; use sp_runtime::generic::{BlockId, Digest, DigestItem}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT, ProvideRuntimeApi}; use sp_timestamp::{TimestampInherentData, InherentError as TIError}; -use pow_primitives::{Seal, TotalDifficulty, POW_ENGINE_ID}; -use primitives::H256; -use inherents::{InherentDataProviders, InherentData}; -use consensus_common::{ +use sp_consensus_pow::{Seal, TotalDifficulty, POW_ENGINE_ID}; +use sp_core::H256; +use sp_inherents::{InherentDataProviders, InherentData}; +use sp_consensus::{ BlockImportParams, BlockOrigin, ForkChoiceStrategy, SyncOracle, Environment, Proposer, SelectChain, Error as ConsensusError, CanAuthorWith, }; -use consensus_common::import_queue::{BoxBlockImport, BasicQueue, Verifier}; +use sp_consensus::import_queue::{BoxBlockImport, BasicQueue, Verifier}; use codec::{Encode, Decode}; -use client_api; +use sc_client_api; use log::*; #[derive(derive_more::Display, Debug)] @@ -74,7 +74,7 @@ pub enum Error { #[display(fmt = "Error with block built on {:?}: {:?}", _0, _1)] BlockBuiltError(B::Hash, ConsensusError), #[display(fmt = "Creating inherents failed: {}", _0)] - CreateInherents(inherents::Error), + CreateInherents(sp_inherents::Error), #[display(fmt = "Checking inherents failed: {}", _0)] CheckInherents(String), Client(sp_blockchain::Error), @@ -151,7 +151,7 @@ pub trait PowAlgorithm { pub struct PowVerifier, C, S, Algorithm> { client: Arc, algorithm: Algorithm, - inherent_data_providers: inherents::InherentDataProviders, + inherent_data_providers: sp_inherents::InherentDataProviders, select_chain: Option, check_inherents_after: <::Header as HeaderT>::Number, } @@ -162,7 +162,7 @@ impl, C, S, Algorithm> PowVerifier { algorithm: Algorithm, check_inherents_after: <::Header as HeaderT>::Number, select_chain: Option, - inherent_data_providers: inherents::InherentDataProviders, + inherent_data_providers: sp_inherents::InherentDataProviders, ) -> Self { Self { client, algorithm, inherent_data_providers, select_chain, check_inherents_after } } @@ -314,12 +314,12 @@ impl, C, S, Algorithm> Verifier for PowVerifier Result<(), consensus_common::Error> { +) -> Result<(), sp_consensus::Error> { if !inherent_data_providers.has_provider(&sp_timestamp::INHERENT_IDENTIFIER) { inherent_data_providers .register_provider(sp_timestamp::InherentDataProvider) .map_err(Into::into) - .map_err(consensus_common::Error::InherentData) + .map_err(sp_consensus::Error::InherentData) } else { Ok(()) } @@ -336,7 +336,7 @@ pub fn import_queue( check_inherents_after: <::Header as HeaderT>::Number, select_chain: Option, inherent_data_providers: InherentDataProviders, -) -> Result, consensus_common::Error> where +) -> Result, sp_consensus::Error> where B: BlockT, C: ProvideRuntimeApi + HeaderBackend + BlockOf + ProvideCache + AuxStore, C: Send + Sync + AuxStore + 'static, @@ -382,7 +382,7 @@ pub fn start_mine, C, Algorithm, E, SO, S, CAW>( mut sync_oracle: SO, build_time: std::time::Duration, select_chain: Option, - inherent_data_providers: inherents::InherentDataProviders, + inherent_data_providers: sp_inherents::InherentDataProviders, can_author_with: CAW, ) where C: HeaderBackend + AuxStore + 'static, @@ -433,7 +433,7 @@ fn mine_loop, C, Algorithm, E, SO, S, CAW>( sync_oracle: &mut SO, build_time: std::time::Duration, select_chain: Option<&S>, - inherent_data_providers: &inherents::InherentDataProviders, + inherent_data_providers: &sp_inherents::InherentDataProviders, can_author_with: &CAW, ) -> Result<(), Error> where C: HeaderBackend + AuxStore, diff --git a/substrate/client/consensus/slots/Cargo.toml b/substrate/client/consensus/slots/Cargo.toml index 18d9f97b19..01f6bf5251 100644 --- a/substrate/client/consensus/slots/Cargo.toml +++ b/substrate/client/consensus/slots/Cargo.toml @@ -8,17 +8,17 @@ build = "build.rs" [dependencies] codec = { package = "parity-scale-codec", version = "1.0.0" } -client-api = { package = "sc-client-api", path = "../../api" } -primitives = { package = "sp-core", path = "../../../primitives/core" } +sc-client-api = { path = "../../api" } +sp-core = { path = "../../../primitives/core" } sp-blockchain = { path = "../../../primitives/blockchain" } sp-runtime = { path = "../../../primitives/runtime" } sc-telemetry = { path = "../../telemetry" } -consensus_common = { package = "sp-consensus", path = "../../../primitives/consensus/common" } -inherents = { package = "sp-inherents", path = "../../../primitives/inherents" } +sp-consensus = { path = "../../../primitives/consensus/common" } +sp-inherents = { path = "../../../primitives/inherents" } futures = "0.3.1" futures-timer = "2.0" parking_lot = "0.9.0" log = "0.4.8" [dev-dependencies] -test-client = { package = "substrate-test-runtime-client", path = "../../../test-utils/runtime/client" } +substrate-test-runtime-client = { path = "../../../test-utils/runtime/client" } diff --git a/substrate/client/consensus/slots/src/aux_schema.rs b/substrate/client/consensus/slots/src/aux_schema.rs index 76f165e8d5..ada9661550 100644 --- a/substrate/client/consensus/slots/src/aux_schema.rs +++ b/substrate/client/consensus/slots/src/aux_schema.rs @@ -17,7 +17,7 @@ //! Schema for slots in the aux-db. use codec::{Encode, Decode}; -use client_api::backend::AuxStore; +use sc_client_api::backend::AuxStore; use sp_blockchain::{Result as ClientResult, Error as ClientError}; use sp_runtime::traits::Header; @@ -151,10 +151,10 @@ pub fn check_equivocation( #[cfg(test)] mod test { - use primitives::{sr25519, Pair}; - use primitives::hash::H256; + use sp_core::{sr25519, Pair}; + use sp_core::hash::H256; use sp_runtime::testing::{Header as HeaderTest, Digest as DigestTest}; - use test_client; + use substrate_test_runtime_client; use super::{MAX_SLOT_CAPACITY, PRUNING_BOUND, check_equivocation}; @@ -175,7 +175,7 @@ mod test { #[test] fn check_equivocation_works() { - let client = test_client::new(); + let client = substrate_test_runtime_client::new(); let (pair, _seed) = sr25519::Pair::generate(); let public = pair.public(); diff --git a/substrate/client/consensus/slots/src/lib.rs b/substrate/client/consensus/slots/src/lib.rs index e95974fb92..9010771145 100644 --- a/substrate/client/consensus/slots/src/lib.rs +++ b/substrate/client/consensus/slots/src/lib.rs @@ -31,23 +31,23 @@ use slots::Slots; pub use aux_schema::{check_equivocation, MAX_SLOT_CAPACITY, PRUNING_BOUND}; use codec::{Decode, Encode}; -use consensus_common::{BlockImport, Proposer, SyncOracle, SelectChain, CanAuthorWith, SlotData}; +use sp_consensus::{BlockImport, Proposer, SyncOracle, SelectChain, CanAuthorWith, SlotData}; use futures::{prelude::*, future::{self, Either}}; use futures_timer::Delay; -use inherents::{InherentData, InherentDataProviders}; +use sp_inherents::{InherentData, InherentDataProviders}; use log::{debug, error, info, warn}; use sp_runtime::generic::BlockId; use sp_runtime::traits::{ApiRef, Block as BlockT, Header, ProvideRuntimeApi}; use std::{fmt::Debug, ops::Deref, pin::Pin, sync::Arc, time::{Instant, Duration}}; use sc_telemetry::{telemetry, CONSENSUS_DEBUG, CONSENSUS_WARN, CONSENSUS_INFO}; use parking_lot::Mutex; -use client_api; +use sc_client_api; /// A worker that should be invoked at every new slot. pub trait SlotWorker { /// The type of the future that will be returned when a new slot is /// triggered. - type OnSlot: Future>; + type OnSlot: Future>; /// Called when a new slot is triggered. fn on_slot(&mut self, chain_head: B::Header, slot_info: SlotInfo) -> Self::OnSlot; @@ -80,7 +80,7 @@ pub trait SimpleSlotWorker { /// Returns the epoch data necessary for authoring. For time-dependent epochs, /// use the provided slot number as a canonical source of time. - fn epoch_data(&self, header: &B::Header, slot_number: u64) -> Result; + fn epoch_data(&self, header: &B::Header, slot_number: u64) -> Result; /// Returns the number of authorities given the epoch data. fn authorities_len(&self, epoch_data: &Self::EpochData) -> usize; @@ -102,7 +102,7 @@ pub trait SimpleSlotWorker { &B::Hash, Vec, Self::Claim, - ) -> consensus_common::BlockImportParams + Send>; + ) -> sp_consensus::BlockImportParams + Send>; /// Whether to force authoring if offline. fn force_authoring(&self) -> bool; @@ -111,7 +111,7 @@ pub trait SimpleSlotWorker { fn sync_oracle(&mut self) -> &mut Self::SyncOracle; /// Returns a `Proposer` to author on top of the given block. - fn proposer(&mut self, block: &B::Header) -> Result; + fn proposer(&mut self, block: &B::Header) -> Result; /// Remaining duration of the slot. fn slot_remaining_duration(&self, slot_info: &SlotInfo) -> Duration { @@ -134,7 +134,7 @@ pub trait SimpleSlotWorker { /// Implements the `on_slot` functionality from `SlotWorker`. fn on_slot(&mut self, chain_head: B::Header, slot_info: SlotInfo) - -> Pin> + Send>> where + -> Pin> + Send>> where Self: Send + Sync, >::Create: Unpin + Send + 'static, { @@ -222,7 +222,7 @@ pub trait SimpleSlotWorker { logs, }, slot_remaining_duration, - ).map_err(|e| consensus_common::Error::ClientImport(format!("{:?}", e))); + ).map_err(|e| sp_consensus::Error::ClientImport(format!("{:?}", e))); let delay: Box + Unpin + Send> = match proposing_remaining_duration { Some(r) => Box::new(Delay::new(r)), None => Box::new(future::pending()), @@ -239,7 +239,7 @@ pub trait SimpleSlotWorker { telemetry!(CONSENSUS_INFO; "slots.discarding_proposal_took_too_long"; "slot" => slot_number, ); - Err(consensus_common::Error::ClientImport("Timeout in the Slots proposer".into())) + Err(sp_consensus::Error::ClientImport("Timeout in the Slots proposer".into())) }, })); @@ -293,7 +293,7 @@ pub trait SlotCompatible { fn extract_timestamp_and_slot( &self, inherent: &InherentData, - ) -> Result<(u64, u64, std::time::Duration), consensus_common::Error>; + ) -> Result<(u64, u64, std::time::Duration), sp_consensus::Error>; /// Get the difference between chain time and local time. Defaults to /// always returning zero. @@ -417,7 +417,7 @@ impl SlotDuration { /// `slot_key` is marked as `'static`, as it should really be a /// compile-time constant. pub fn get_or_compute(client: &C, cb: CB) -> sp_blockchain::Result where - C: client_api::backend::AuxStore, + C: sc_client_api::backend::AuxStore, C: ProvideRuntimeApi, CB: FnOnce(ApiRef, &BlockId) -> sp_blockchain::Result, T: SlotData + Encode + Decode + Debug, diff --git a/substrate/client/consensus/slots/src/slots.rs b/substrate/client/consensus/slots/src/slots.rs index 640b24ec1c..16d53fc54a 100644 --- a/substrate/client/consensus/slots/src/slots.rs +++ b/substrate/client/consensus/slots/src/slots.rs @@ -19,9 +19,9 @@ //! This is used instead of `futures_timer::Interval` because it was unreliable. use super::SlotCompatible; -use consensus_common::Error; +use sp_consensus::Error; use futures::{prelude::*, task::Context, task::Poll}; -use inherents::{InherentData, InherentDataProviders}; +use sp_inherents::{InherentData, InherentDataProviders}; use std::{pin::Pin, time::{Duration, Instant}}; use futures_timer::Delay; @@ -135,7 +135,7 @@ impl Stream for Slots { let inherent_data = match self.inherent_data_providers.create_inherent_data() { Ok(id) => id, - Err(err) => return Poll::Ready(Some(Err(consensus_common::Error::InherentData(err)))), + Err(err) => return Poll::Ready(Some(Err(sp_consensus::Error::InherentData(err)))), }; let result = self.timestamp_extractor.extract_timestamp_and_slot(&inherent_data); let (timestamp, slot_num, offset) = match result { diff --git a/substrate/client/consensus/uncles/Cargo.toml b/substrate/client/consensus/uncles/Cargo.toml index 62fc7476f1..c017358ca4 100644 --- a/substrate/client/consensus/uncles/Cargo.toml +++ b/substrate/client/consensus/uncles/Cargo.toml @@ -6,10 +6,10 @@ description = "Generic uncle inclusion utilities for consensus" edition = "2018" [dependencies] -client-api = { package = "sc-client-api", path = "../../api" } -primitives = { package = "sp-core", path = "../../../primitives/core" } +sc-client-api = { path = "../../api" } +sp-core = { path = "../../../primitives/core" } sp-runtime = { path = "../../../primitives/runtime" } sp-authorship = { path = "../../../primitives/authorship" } -consensus_common = { package = "sp-consensus", path = "../../../primitives/consensus/common" } -inherents = { package = "sp-inherents", path = "../../../primitives/inherents" } +sp-consensus = { path = "../../../primitives/consensus/common" } +sp-inherents = { path = "../../../primitives/inherents" } log = "0.4.8" diff --git a/substrate/client/consensus/uncles/src/lib.rs b/substrate/client/consensus/uncles/src/lib.rs index f7b1a8fa84..5839fb0a01 100644 --- a/substrate/client/consensus/uncles/src/lib.rs +++ b/substrate/client/consensus/uncles/src/lib.rs @@ -19,10 +19,10 @@ #![deny(warnings)] #![forbid(unsafe_code, missing_docs)] -use consensus_common::SelectChain; -use inherents::{InherentDataProviders}; +use sp_consensus::SelectChain; +use sp_inherents::{InherentDataProviders}; use log::warn; -use client_api::ProvideUncles; +use sc_client_api::ProvideUncles; use sp_runtime::traits::{Block as BlockT, Header}; use std::sync::Arc; use sp_authorship; @@ -35,7 +35,7 @@ pub fn register_uncles_inherent_data_provider( client: Arc, select_chain: SC, inherent_data_providers: &InherentDataProviders, -) -> Result<(), consensus_common::Error> where +) -> Result<(), sp_consensus::Error> where B: BlockT, C: ProvideUncles + Send + Sync + 'static, SC: SelectChain + 'static, @@ -60,7 +60,7 @@ pub fn register_uncles_inherent_data_provider( } } })) - .map_err(|err| consensus_common::Error::InherentData(err.into()))?; + .map_err(|err| sp_consensus::Error::InherentData(err.into()))?; } Ok(()) } diff --git a/substrate/client/db/Cargo.toml b/substrate/client/db/Cargo.toml index c6c256b7eb..20eba6fc13 100644 --- a/substrate/client/db/Cargo.toml +++ b/substrate/client/db/Cargo.toml @@ -12,21 +12,21 @@ kvdb-rocksdb = { version = "0.2", optional = true } kvdb-memorydb = "0.1.2" linked-hash-map = "0.5.2" hash-db = "0.15.2" -client-api = { package = "sc-client-api", path = "../api" } -primitives = { package = "sp-core", path = "../../primitives/core" } +sc-client-api = { path = "../api" } +sp-core = { path = "../../primitives/core" } sp-runtime = { path = "../../primitives/runtime" } -client = { package = "sc-client", path = "../" } -state-machine = { package = "sp-state-machine", path = "../../primitives/state-machine" } +sc-client = { path = "../" } +sp-state-machine = { path = "../../primitives/state-machine" } codec = { package = "parity-scale-codec", version = "1.0.0", features = ["derive"] } -executor = { package = "sc-executor", path = "../executor" } -state_db = { package = "sc-state-db", path = "../state-db" } -trie = { package = "sp-trie", path = "../../primitives/trie" } -consensus_common = { package = "sp-consensus", path = "../../primitives/consensus/common" } +sc-executor = { path = "../executor" } +sc-state-db = { path = "../state-db" } +sp-trie = { path = "../../primitives/trie" } +sp-consensus = { path = "../../primitives/consensus/common" } sp-blockchain = { path = "../../primitives/blockchain" } [dev-dependencies] sp-keyring = { path = "../../primitives/keyring" } -test-client = { package = "substrate-test-runtime-client", path = "../../test-utils/runtime/client" } +substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } env_logger = "0.7.0" quickcheck = "0.9" diff --git a/substrate/client/db/src/cache/list_cache.rs b/substrate/client/db/src/cache/list_cache.rs index 36219d479a..3760838bdf 100644 --- a/substrate/client/db/src/cache/list_cache.rs +++ b/substrate/client/db/src/cache/list_cache.rs @@ -724,7 +724,7 @@ fn read_forks>( #[cfg(test)] pub mod tests { - use test_client::runtime::H256; + use substrate_test_runtime_client::runtime::H256; use sp_runtime::testing::{Header, Block as RawBlock, ExtrinsicWrapper}; use sp_runtime::traits::Header as HeaderT; use crate::cache::list_storage::tests::{DummyStorage, FaultyStorage, DummyTransaction}; diff --git a/substrate/client/db/src/cache/mod.rs b/substrate/client/db/src/cache/mod.rs index 0087d34d19..a25b4e4fd7 100644 --- a/substrate/client/db/src/cache/mod.rs +++ b/substrate/client/db/src/cache/mod.rs @@ -21,7 +21,7 @@ use parking_lot::RwLock; use kvdb::{KeyValueDB, DBTransaction}; -use client_api::blockchain::{well_known_cache_keys::{self, Id as CacheKeyId}, Cache as BlockchainCache}; +use sc_client_api::blockchain::{well_known_cache_keys::{self, Id as CacheKeyId}, Cache as BlockchainCache}; use sp_blockchain::Result as ClientResult; use codec::{Encode, Decode}; use sp_runtime::generic::BlockId; diff --git a/substrate/client/db/src/lib.rs b/substrate/client/db/src/lib.rs index a7320ec1c3..8523ff30a3 100644 --- a/substrate/client/db/src/lib.rs +++ b/substrate/client/db/src/lib.rs @@ -39,9 +39,9 @@ use std::path::PathBuf; use std::io; use std::collections::{HashMap, HashSet}; -use client_api::{execution_extensions::ExecutionExtensions, ForkBlocks}; -use client_api::backend::NewBlockState; -use client_api::backend::{StorageCollection, ChildStorageCollection}; +use sc_client_api::{execution_extensions::ExecutionExtensions, ForkBlocks}; +use sc_client_api::backend::NewBlockState; +use sc_client_api::backend::{StorageCollection, ChildStorageCollection}; use sp_blockchain::{ Result as ClientResult, Error as ClientError, well_known_cache_keys, HeaderBackend, @@ -49,10 +49,10 @@ use sp_blockchain::{ use codec::{Decode, Encode}; use hash_db::{Hasher, Prefix}; use kvdb::{KeyValueDB, DBTransaction}; -use trie::{MemoryDB, PrefixedMemoryDB, prefixed_key}; +use sp_trie::{MemoryDB, PrefixedMemoryDB, prefixed_key}; use parking_lot::{Mutex, RwLock}; -use primitives::{H256, Blake2Hasher, ChangesTrieConfiguration, convert_hash, traits::CodeExecutor}; -use primitives::storage::{well_known_keys, ChildInfo}; +use sp_core::{H256, Blake2Hasher, ChangesTrieConfiguration, convert_hash, traits::CodeExecutor}; +use sp_core::storage::{well_known_keys, ChildInfo}; use sp_runtime::{ generic::{BlockId, DigestItem}, Justification, Storage, BuildStorage, @@ -60,21 +60,21 @@ use sp_runtime::{ use sp_runtime::traits::{ Block as BlockT, Header as HeaderT, NumberFor, Zero, One, SaturatedConversion }; -use executor::RuntimeInfo; -use state_machine::{ +use sc_executor::RuntimeInfo; +use sp_state_machine::{ DBValue, ChangesTrieTransaction, ChangesTrieCacheAction, ChangesTrieBuildCache, backend::Backend as StateBackend, }; use crate::utils::{Meta, db_err, meta_keys, read_db, read_meta}; -use client::leaves::{LeafSet, FinalizationDisplaced}; -use state_db::StateDb; +use sc_client::leaves::{LeafSet, FinalizationDisplaced}; +use sc_state_db::StateDb; use sp_blockchain::{CachedHeaderMetadata, HeaderMetadata, HeaderMetadataCache}; use crate::storage_cache::{CachingState, SharedCache, new_shared_cache}; use log::{trace, debug, warn}; -pub use state_db::PruningMode; +pub use sc_state_db::PruningMode; #[cfg(feature = "test-helpers")] -use client::in_mem::Backend as InMemoryBackend; +use sc_client::in_mem::Backend as InMemoryBackend; const CANONICALIZATION_DELAY: u64 = 4096; const MIN_BLOCKS_TO_KEEP_CHANGES_TRIES_FOR: u32 = 32768; @@ -83,7 +83,7 @@ const MIN_BLOCKS_TO_KEEP_CHANGES_TRIES_FOR: u32 = 32768; const DEFAULT_CHILD_RATIO: (usize, usize) = (1, 10); /// DB-backed patricia trie state, transaction type is an overlay of changes to commit. -pub type DbState = state_machine::TrieBackend>, Blake2Hasher>; +pub type DbState = sp_state_machine::TrieBackend>, Blake2Hasher>; /// Re-export the KVDB trait so that one can pass an implementation of it. pub use kvdb; @@ -239,7 +239,7 @@ impl StateBackend for RefTrackingState { fn as_trie_backend( &mut self, - ) -> Option<&state_machine::TrieBackend> { + ) -> Option<&sp_state_machine::TrieBackend> { self.state.as_trie_backend() } } @@ -278,9 +278,9 @@ pub fn new_client( fork_blocks: ForkBlocks, execution_extensions: ExecutionExtensions, ) -> Result<( - client::Client< + sc_client::Client< Backend, - client::LocalCallExecutor, E>, + sc_client::LocalCallExecutor, E>, Block, RA, >, @@ -294,9 +294,9 @@ pub fn new_client( S: BuildStorage, { let backend = Arc::new(Backend::new(settings, CANONICALIZATION_DELAY)?); - let executor = client::LocalCallExecutor::new(backend.clone(), executor); + let executor = sc_client::LocalCallExecutor::new(backend.clone(), executor); Ok(( - client::Client::new(backend.clone(), executor, genesis_storage, fork_blocks, execution_extensions)?, + sc_client::Client::new(backend.clone(), executor, genesis_storage, fork_blocks, execution_extensions)?, backend, )) } @@ -326,7 +326,7 @@ struct PendingBlock { // wrapper that implements trait required for state_db struct StateMetaDb<'a>(&'a dyn KeyValueDB); -impl<'a> state_db::MetaDb for StateMetaDb<'a> { +impl<'a> sc_state_db::MetaDb for StateMetaDb<'a> { type Error = io::Error; fn get_meta(&self, key: &[u8]) -> Result>, Self::Error> { @@ -379,14 +379,14 @@ impl BlockchainDb { } } -impl client::blockchain::HeaderBackend for BlockchainDb { +impl sc_client::blockchain::HeaderBackend for BlockchainDb { fn header(&self, id: BlockId) -> ClientResult> { utils::read_header(&*self.db, columns::KEY_LOOKUP, columns::HEADER, id) } - fn info(&self) -> client::blockchain::Info { + fn info(&self) -> sc_client::blockchain::Info { let meta = self.meta.read(); - client::blockchain::Info { + sc_client::blockchain::Info { best_hash: meta.best_hash, best_number: meta.best_number, genesis_hash: meta.genesis_hash, @@ -395,7 +395,7 @@ impl client::blockchain::HeaderBackend for BlockchainDb) -> ClientResult { + fn status(&self, id: BlockId) -> ClientResult { let exists = match id { BlockId::Hash(_) => read_db( &*self.db, @@ -406,8 +406,8 @@ impl client::blockchain::HeaderBackend for BlockchainDb n <= self.meta.read().best_number, }; match exists { - true => Ok(client::blockchain::BlockStatus::InChain), - false => Ok(client::blockchain::BlockStatus::Unknown), + true => Ok(sc_client::blockchain::BlockStatus::InChain), + false => Ok(sc_client::blockchain::BlockStatus::Unknown), } } @@ -423,7 +423,7 @@ impl client::blockchain::HeaderBackend for BlockchainDb client::blockchain::Backend for BlockchainDb { +impl sc_client::blockchain::Backend for BlockchainDb { fn body(&self, id: BlockId) -> ClientResult>> { match read_db(&*self.db, columns::KEY_LOOKUP, columns::BODY, id)? { Some(body) => match Decode::decode(&mut &body[..]) { @@ -452,7 +452,7 @@ impl client::blockchain::Backend for BlockchainDb { Ok(self.meta.read().finalized_hash.clone()) } - fn cache(&self) -> Option>> { + fn cache(&self) -> Option>> { None } @@ -465,8 +465,8 @@ impl client::blockchain::Backend for BlockchainDb { } } -impl client::blockchain::ProvideCache for BlockchainDb { - fn cache(&self) -> Option>> { +impl sc_client::blockchain::ProvideCache for BlockchainDb { + fn cache(&self) -> Option>> { None } } @@ -522,7 +522,7 @@ impl BlockImportOperation { } } -impl client_api::backend::BlockImportOperation +impl sc_client_api::backend::BlockImportOperation for BlockImportOperation where Block: BlockT, { type State = CachingState, Block>; @@ -630,7 +630,7 @@ struct StorageDb { pub state_db: StateDb>, } -impl state_machine::Storage for StorageDb { +impl sp_state_machine::Storage for StorageDb { fn get(&self, key: &H256, prefix: Prefix) -> Result, String> { let key = prefixed_key::(key, prefix); self.state_db.get(&key, self).map(|r| r.map(|v| DBValue::from_slice(&v))) @@ -638,7 +638,7 @@ impl state_machine::Storage for StorageDb { } } -impl state_db::NodeDb for StorageDb { +impl sc_state_db::NodeDb for StorageDb { type Error = io::Error; type Key = [u8]; @@ -653,12 +653,12 @@ impl DbGenesisStorage { pub fn new() -> Self { let mut root = H256::default(); let mut mdb = MemoryDB::::default(); - state_machine::TrieDBMut::::new(&mut mdb, &mut root); + sp_state_machine::TrieDBMut::::new(&mut mdb, &mut root); DbGenesisStorage(root) } } -impl state_machine::Storage for DbGenesisStorage { +impl sp_state_machine::Storage for DbGenesisStorage { fn get(&self, _key: &H256, _prefix: Prefix) -> Result, String> { Ok(None) } @@ -700,11 +700,11 @@ impl> DbChangesTrieStorage { None => return, }; - state_machine::prune_changes_tries( + sp_state_machine::prune_changes_tries( config, &*self, min_blocks_to_keep.into(), - &state_machine::ChangesTrieAnchorBlockId { + &sp_state_machine::ChangesTrieAnchorBlockId { hash: convert_hash(&block_hash), number: block_num, }, @@ -712,7 +712,7 @@ impl> DbChangesTrieStorage { } } -impl client_api::backend::PrunableStateChangesTrieStorage +impl sc_client_api::backend::PrunableStateChangesTrieStorage for DbChangesTrieStorage where Block: BlockT, @@ -723,7 +723,7 @@ where best_finalized_block: NumberFor, ) -> NumberFor { match self.min_blocks_to_keep { - Some(min_blocks_to_keep) => state_machine::oldest_non_pruned_changes_trie( + Some(min_blocks_to_keep) => sp_state_machine::oldest_non_pruned_changes_trie( config, min_blocks_to_keep.into(), best_finalized_block, @@ -733,7 +733,7 @@ where } } -impl state_machine::ChangesTrieRootsStorage> +impl sp_state_machine::ChangesTrieRootsStorage> for DbChangesTrieStorage where Block: BlockT, @@ -741,11 +741,11 @@ where fn build_anchor( &self, hash: H256, - ) -> Result>, String> { + ) -> Result>, String> { utils::read_header::(&*self.db, columns::KEY_LOOKUP, columns::HEADER, BlockId::Hash(hash)) .map_err(|e| e.to_string()) .and_then(|maybe_header| maybe_header.map(|header| - state_machine::ChangesTrieAnchorBlockId { + sp_state_machine::ChangesTrieAnchorBlockId { hash, number: *header.number(), } @@ -754,7 +754,7 @@ where fn root( &self, - anchor: &state_machine::ChangesTrieAnchorBlockId>, + anchor: &sp_state_machine::ChangesTrieAnchorBlockId>, block: NumberFor, ) -> Result, String> { // check API requirement: we can't get NEXT block(s) based on anchor @@ -800,12 +800,12 @@ where } } -impl state_machine::ChangesTrieStorage> +impl sp_state_machine::ChangesTrieStorage> for DbChangesTrieStorage where Block: BlockT, { - fn as_roots_storage(&self) -> &dyn state_machine::ChangesTrieRootsStorage> { + fn as_roots_storage(&self) -> &dyn sp_state_machine::ChangesTrieRootsStorage> { self } @@ -870,7 +870,7 @@ impl> Backend { let is_archive_pruning = config.pruning.is_archive(); let blockchain = BlockchainDb::new(db.clone())?; let meta = blockchain.meta.clone(); - let map_e = |e: state_db::Error| ::sp_blockchain::Error::from(format!("State database error: {:?}", e)); + let map_e = |e: sc_state_db::Error| ::sp_blockchain::Error::from(format!("State database error: {:?}", e)); let state_db: StateDb<_, _> = StateDb::new(config.pruning.clone(), &StateMetaDb(&*db)).map_err(map_e)?; let storage_db = StorageDb { db: db.clone(), @@ -904,8 +904,8 @@ impl> Backend { /// Returns in-memory blockchain that contains the same set of blocks that the self. #[cfg(feature = "test-helpers")] pub fn as_in_memory(&self) -> InMemoryBackend { - use client_api::backend::{Backend as ClientBackend, BlockImportOperation}; - use client::blockchain::Backend as BlockchainBackend; + use sc_client_api::backend::{Backend as ClientBackend, BlockImportOperation}; + use sc_client::blockchain::Backend as BlockchainBackend; let inmem = InMemoryBackend::::new(); @@ -965,7 +965,7 @@ impl> Backend { match cached_changes_trie_config.clone() { Some(cached_changes_trie_config) => Ok(cached_changes_trie_config), None => { - use client_api::backend::Backend; + use sc_client_api::backend::Backend; let changes_trie_config = self .state_at(BlockId::Hash(block))? .storage(well_known_keys::CHANGES_TRIE_CONFIG)? @@ -1109,14 +1109,14 @@ impl> Backend { let hash = if new_canonical == number_u64 { hash } else { - ::client::blockchain::HeaderBackend::hash(&self.blockchain, new_canonical.saturated_into())? + ::sc_client::blockchain::HeaderBackend::hash(&self.blockchain, new_canonical.saturated_into())? .expect("existence of block with number `new_canonical` \ implies existence of blocks with all numbers before it; qed") }; trace!(target: "db", "Canonicalize block #{} ({:?})", new_canonical, hash); let commit = self.storage.state_db.canonicalize_block(&hash) - .map_err(|e: state_db::Error| sp_blockchain::Error::from(format!("State database error: {:?}", e)))?; + .map_err(|e: sc_state_db::Error| sp_blockchain::Error::from(format!("State database error: {:?}", e)))?; apply_state_commit(transaction, commit); }; @@ -1190,7 +1190,7 @@ impl> Backend { } let finalized = if operation.commit_state { - let mut changeset: state_db::ChangeSet> = state_db::ChangeSet::default(); + let mut changeset: sc_state_db::ChangeSet> = sc_state_db::ChangeSet::default(); for (key, (val, rc)) in operation.db_updates.drain() { if rc > 0 { changeset.inserted.push((key, val.to_vec())); @@ -1200,7 +1200,7 @@ impl> Backend { } let number_u64 = number.saturated_into::(); let commit = self.storage.state_db.insert_block(&hash, number_u64, &pending_block.header.parent_hash(), changeset) - .map_err(|e: state_db::Error| sp_blockchain::Error::from(format!("State database error: {:?}", e)))?; + .map_err(|e: sc_state_db::Error| sp_blockchain::Error::from(format!("State database error: {:?}", e)))?; apply_state_commit(&mut transaction, commit); // Check if need to finalize. Genesis is always finalized instantly. @@ -1253,7 +1253,7 @@ impl> Backend { }; let cache_update = if let Some(set_head) = operation.set_head { - if let Some(header) = ::client::blockchain::HeaderBackend::header(&self.blockchain, set_head)? { + if let Some(header) = ::sc_client::blockchain::HeaderBackend::header(&self.blockchain, set_head)? { let number = header.number(); let hash = header.hash(); @@ -1336,7 +1336,7 @@ impl> Backend { transaction.put(columns::META, meta_keys::FINALIZED_BLOCK, &lookup_key); let commit = self.storage.state_db.canonicalize_block(&f_hash) - .map_err(|e: state_db::Error| sp_blockchain::Error::from(format!("State database error: {:?}", e)))?; + .map_err(|e: sc_state_db::Error| sp_blockchain::Error::from(format!("State database error: {:?}", e)))?; apply_state_commit(transaction, commit); let changes_trie_config = self.changes_trie_config(parent_hash)?; @@ -1355,7 +1355,7 @@ impl> Backend { } } -fn apply_state_commit(transaction: &mut DBTransaction, commit: state_db::CommitSet>) { +fn apply_state_commit(transaction: &mut DBTransaction, commit: sc_state_db::CommitSet>) { for (key, val) in commit.data.inserted.into_iter() { transaction.put(columns::STATE, &key[..], &val); } @@ -1370,7 +1370,7 @@ fn apply_state_commit(transaction: &mut DBTransaction, commit: state_db::CommitS } } -impl client_api::backend::AuxStore for Backend where Block: BlockT { +impl sc_client_api::backend::AuxStore for Backend where Block: BlockT { fn insert_aux< 'a, 'b: 'a, @@ -1394,7 +1394,7 @@ impl client_api::backend::AuxStore for Backend where Block: BlockT } } -impl client_api::backend::Backend for Backend where Block: BlockT { +impl sc_client_api::backend::Backend for Backend where Block: BlockT { type BlockImportOperation = BlockImportOperation; type Blockchain = BlockchainDb; type State = CachingState, Block>; @@ -1530,7 +1530,7 @@ impl client_api::backend::Backend for Backend } fn state_at(&self, block: BlockId) -> ClientResult { - use client::blockchain::HeaderBackend as BcHeaderBackend; + use sc_client::blockchain::HeaderBackend as BcHeaderBackend; // special case for genesis initialization match block { @@ -1568,7 +1568,7 @@ impl client_api::backend::Backend for Backend if self.is_archive { match self.blockchain.header(BlockId::Hash(hash.clone())) { Ok(Some(header)) => { - state_machine::Storage::get(self.storage.as_ref(), &header.state_root(), (&[], None)).unwrap_or(None).is_some() + sp_state_machine::Storage::get(self.storage.as_ref(), &header.state_root(), (&[], None)).unwrap_or(None).is_some() }, _ => false, } @@ -1590,7 +1590,7 @@ impl client_api::backend::Backend for Backend } } -impl client_api::backend::LocalBackend for Backend +impl sc_client_api::backend::LocalBackend for Backend where Block: BlockT {} /// TODO: remove me in #3201 @@ -1604,15 +1604,13 @@ mod tests { use hash_db::{HashDB, EMPTY_PREFIX}; use super::*; use crate::columns; - use client_api::backend::{Backend as BTrait, BlockImportOperation as Op}; - use client::blockchain::Backend as BLBTrait; + use sc_client_api::backend::{Backend as BTrait, BlockImportOperation as Op}; + use sc_client::blockchain::Backend as BLBTrait; use sp_runtime::testing::{Header, Block as RawBlock, ExtrinsicWrapper}; use sp_runtime::traits::{Hash, BlakeTwo256}; - use state_machine::{TrieMut, TrieDBMut, ChangesTrieRootsStorage, ChangesTrieStorage}; + use sp_state_machine::{TrieMut, TrieDBMut, ChangesTrieRootsStorage, ChangesTrieStorage}; use sp_blockchain::{lowest_common_ancestor, tree_route}; - use test_client; - type Block = RawBlock>; fn prepare_changes(changes: Vec<(Vec, Vec)>) -> (H256, MemoryDB) { @@ -1849,7 +1847,7 @@ mod tests { backend.commit_operation(op).unwrap(); assert_eq!(backend.storage.db.get( columns::STATE, - &trie::prefixed_key::(&key, EMPTY_PREFIX) + &sp_trie::prefixed_key::(&key, EMPTY_PREFIX) ).unwrap().unwrap(), &b"hello"[..]); hash }; @@ -1886,7 +1884,7 @@ mod tests { backend.commit_operation(op).unwrap(); assert_eq!(backend.storage.db.get( columns::STATE, - &trie::prefixed_key::(&key, EMPTY_PREFIX) + &sp_trie::prefixed_key::(&key, EMPTY_PREFIX) ).unwrap().unwrap(), &b"hello"[..]); hash }; @@ -1924,7 +1922,7 @@ mod tests { assert!(backend.storage.db.get( columns::STATE, - &trie::prefixed_key::(&key, EMPTY_PREFIX) + &sp_trie::prefixed_key::(&key, EMPTY_PREFIX) ).unwrap().is_some()); hash }; @@ -1958,7 +1956,7 @@ mod tests { backend.commit_operation(op).unwrap(); assert!(backend.storage.db.get( columns::STATE, - &trie::prefixed_key::(&key, EMPTY_PREFIX) + &sp_trie::prefixed_key::(&key, EMPTY_PREFIX) ).unwrap().is_none()); } @@ -1967,7 +1965,7 @@ mod tests { backend.finalize_block(BlockId::Number(3), None).unwrap(); assert!(backend.storage.db.get( columns::STATE, - &trie::prefixed_key::(&key, EMPTY_PREFIX) + &sp_trie::prefixed_key::(&key, EMPTY_PREFIX) ).unwrap().is_none()); } @@ -1979,7 +1977,7 @@ mod tests { let check_changes = |backend: &Backend, block: u64, changes: Vec<(Vec, Vec)>| { let (changes_root, mut changes_trie_update) = prepare_changes(changes); - let anchor = state_machine::ChangesTrieAnchorBlockId { + let anchor = sp_state_machine::ChangesTrieAnchorBlockId { hash: backend.blockchain().header(BlockId::Number(block)).unwrap().unwrap().hash(), number: block }; @@ -2033,21 +2031,21 @@ mod tests { // branch1: when asking for finalized block hash let (changes1_root, _) = prepare_changes(changes1); - let anchor = state_machine::ChangesTrieAnchorBlockId { hash: block2_1_1, number: 4 }; + let anchor = sp_state_machine::ChangesTrieAnchorBlockId { hash: block2_1_1, number: 4 }; assert_eq!(backend.changes_tries_storage.root(&anchor, 1), Ok(Some(changes1_root))); // branch2: when asking for finalized block hash - let anchor = state_machine::ChangesTrieAnchorBlockId { hash: block2_2_1, number: 4 }; + let anchor = sp_state_machine::ChangesTrieAnchorBlockId { hash: block2_2_1, number: 4 }; assert_eq!(backend.changes_tries_storage.root(&anchor, 1), Ok(Some(changes1_root))); // branch1: when asking for non-finalized block hash (search by traversal) let (changes2_1_0_root, _) = prepare_changes(changes2_1_0); - let anchor = state_machine::ChangesTrieAnchorBlockId { hash: block2_1_1, number: 4 }; + let anchor = sp_state_machine::ChangesTrieAnchorBlockId { hash: block2_1_1, number: 4 }; assert_eq!(backend.changes_tries_storage.root(&anchor, 3), Ok(Some(changes2_1_0_root))); // branch2: when asking for non-finalized block hash (search using canonicalized hint) let (changes2_2_0_root, _) = prepare_changes(changes2_2_0); - let anchor = state_machine::ChangesTrieAnchorBlockId { hash: block2_2_1, number: 4 }; + let anchor = sp_state_machine::ChangesTrieAnchorBlockId { hash: block2_2_1, number: 4 }; assert_eq!(backend.changes_tries_storage.root(&anchor, 3), Ok(Some(changes2_2_0_root))); // finalize first block of branch2 (block2_2_0) @@ -2059,7 +2057,7 @@ mod tests { // branch1: when asking for finalized block of other branch // => result is incorrect (returned for the block of branch1), but this is expected, // because the other fork is abandoned (forked before finalized header) - let anchor = state_machine::ChangesTrieAnchorBlockId { hash: block2_1_1, number: 4 }; + let anchor = sp_state_machine::ChangesTrieAnchorBlockId { hash: block2_1_1, number: 4 }; assert_eq!(backend.changes_tries_storage.root(&anchor, 3), Ok(Some(changes2_2_0_root))); } @@ -2090,7 +2088,7 @@ mod tests { backend.changes_tries_storage.meta.write().finalized_number = 13; // check that roots of all tries are in the columns::CHANGES_TRIE - let anchor = state_machine::ChangesTrieAnchorBlockId { hash: block13, number: 13 }; + let anchor = sp_state_machine::ChangesTrieAnchorBlockId { hash: block13, number: 13 }; fn read_changes_trie_root(backend: &Backend, num: u64) -> H256 { backend.blockchain().header(BlockId::Number(num)).unwrap().unwrap().digest().logs().iter() .find(|i| i.as_changes_trie_root().is_some()).unwrap().as_changes_trie_root().unwrap().clone() @@ -2161,7 +2159,7 @@ mod tests { let block6 = insert_header(&backend, 6, block5, vec![(b"key_at_6".to_vec(), b"val_at_6".to_vec())], Default::default()); // check that roots of all tries are in the columns::CHANGES_TRIE - let anchor = state_machine::ChangesTrieAnchorBlockId { hash: block6, number: 6 }; + let anchor = sp_state_machine::ChangesTrieAnchorBlockId { hash: block6, number: 6 }; fn read_changes_trie_root(backend: &Backend, num: u64) -> H256 { backend.blockchain().header(BlockId::Number(num)).unwrap().unwrap().digest().logs().iter() .find(|i| i.as_changes_trie_root().is_some()).unwrap().as_changes_trie_root().unwrap().clone() @@ -2348,20 +2346,20 @@ mod tests { #[test] fn test_leaves_with_complex_block_tree() { - let backend: Arc> = Arc::new(Backend::new_test(20, 20)); - test_client::trait_tests::test_leaves_for_backend(backend); + let backend: Arc> = Arc::new(Backend::new_test(20, 20)); + substrate_test_runtime_client::trait_tests::test_leaves_for_backend(backend); } #[test] fn test_children_with_complex_block_tree() { - let backend: Arc> = Arc::new(Backend::new_test(20, 20)); - test_client::trait_tests::test_children_for_backend(backend); + let backend: Arc> = Arc::new(Backend::new_test(20, 20)); + substrate_test_runtime_client::trait_tests::test_children_for_backend(backend); } #[test] fn test_blockchain_query_by_number_gets_canonical() { - let backend: Arc> = Arc::new(Backend::new_test(20, 20)); - test_client::trait_tests::test_blockchain_query_by_number_gets_canonical(backend); + let backend: Arc> = Arc::new(Backend::new_test(20, 20)); + substrate_test_runtime_client::trait_tests::test_blockchain_query_by_number_gets_canonical(backend); } #[test] @@ -2390,7 +2388,7 @@ mod tests { #[test] fn test_aux() { - let backend: Backend = Backend::new_test(0, 0); + let backend: Backend = Backend::new_test(0, 0); assert!(backend.get_aux(b"test").unwrap().is_none()); backend.insert_aux(&[(&b"test"[..], &b"hello"[..])], &[]).unwrap(); assert_eq!(b"hello", &backend.get_aux(b"test").unwrap().unwrap()[..]); @@ -2400,7 +2398,7 @@ mod tests { #[test] fn test_finalize_block_with_justification() { - use client::blockchain::{Backend as BlockChainBackend}; + use sc_client::blockchain::{Backend as BlockChainBackend}; let backend = Backend::::new_test(10, 10); diff --git a/substrate/client/db/src/light.rs b/substrate/client/db/src/light.rs index 9267a96b2f..31ed012622 100644 --- a/substrate/client/db/src/light.rs +++ b/substrate/client/db/src/light.rs @@ -22,20 +22,20 @@ use parking_lot::RwLock; use kvdb::{KeyValueDB, DBTransaction}; -use client_api::backend::{AuxStore, NewBlockState}; -use client::blockchain::{ +use sc_client_api::backend::{AuxStore, NewBlockState}; +use sc_client::blockchain::{ BlockStatus, Cache as BlockchainCache,Info as BlockchainInfo, }; -use client::cht; +use sc_client::cht; use sp_blockchain::{ CachedHeaderMetadata, HeaderMetadata, HeaderMetadataCache, Error as ClientError, Result as ClientResult, HeaderBackend as BlockchainHeaderBackend, well_known_cache_keys, }; -use client::light::blockchain::Storage as LightBlockchainStorage; +use sc_client::light::blockchain::Storage as LightBlockchainStorage; use codec::{Decode, Encode}; -use primitives::Blake2Hasher; +use sp_core::Blake2Hasher; use sp_runtime::generic::{DigestItem, BlockId}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT, Zero, One, NumberFor}; use crate::cache::{DbCacheSync, DbCache, ComplexBlockId, EntryType as CacheEntryType}; @@ -559,14 +559,14 @@ fn cht_key>(cht_type: u8, block: N) -> ClientResult<[u8; 5]> { #[cfg(test)] pub(crate) mod tests { - use client::cht; + use sc_client::cht; use sp_runtime::generic::DigestItem; use sp_runtime::testing::{H256 as Hash, Header, Block as RawBlock, ExtrinsicWrapper}; use sp_blockchain::{lowest_common_ancestor, tree_route}; use super::*; type Block = RawBlock>; - type AuthorityId = primitives::ed25519::Public; + type AuthorityId = sp_core::ed25519::Public; pub fn default_header(parent: &Hash, number: u64) -> Header { Header { diff --git a/substrate/client/db/src/offchain.rs b/substrate/client/db/src/offchain.rs index 565e113ddd..44be8b0768 100644 --- a/substrate/client/db/src/offchain.rs +++ b/substrate/client/db/src/offchain.rs @@ -56,7 +56,7 @@ impl LocalStorage { } } -impl primitives::offchain::OffchainStorage for LocalStorage { +impl sp_core::offchain::OffchainStorage for LocalStorage { fn set(&mut self, prefix: &[u8], key: &[u8], value: &[u8]) { let key: Vec = prefix.iter().chain(key).cloned().collect(); let mut tx = self.db.transaction(); @@ -117,7 +117,7 @@ impl primitives::offchain::OffchainStorage for LocalStorage { #[cfg(test)] mod tests { use super::*; - use primitives::offchain::OffchainStorage; + use sp_core::offchain::OffchainStorage; #[test] fn should_compare_and_set_and_clear_the_locks_map() { diff --git a/substrate/client/db/src/storage_cache.rs b/substrate/client/db/src/storage_cache.rs index 9053491b17..9f28539e3e 100644 --- a/substrate/client/db/src/storage_cache.rs +++ b/substrate/client/db/src/storage_cache.rs @@ -22,11 +22,11 @@ use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard}; use linked_hash_map::{LinkedHashMap, Entry}; use hash_db::Hasher; use sp_runtime::traits::{Block as BlockT, Header}; -use primitives::hexdisplay::HexDisplay; -use primitives::storage::ChildInfo; -use state_machine::{backend::Backend as StateBackend, TrieBackend}; +use sp_core::hexdisplay::HexDisplay; +use sp_core::storage::ChildInfo; +use sp_state_machine::{backend::Backend as StateBackend, TrieBackend}; use log::trace; -use client_api::backend::{StorageCollection, ChildStorageCollection}; +use sc_client_api::backend::{StorageCollection, ChildStorageCollection}; use std::hash::Hash as StdHash; const STATE_CACHE_BLOCKS: usize = 12; @@ -642,8 +642,8 @@ impl, B: BlockT> StateBackend for CachingState< mod tests { use super::*; use sp_runtime::testing::{H256, Block as RawBlock, ExtrinsicWrapper}; - use state_machine::backend::InMemory; - use primitives::Blake2Hasher; + use sp_state_machine::backend::InMemory; + use sp_core::Blake2Hasher; type Block = RawBlock>; @@ -890,8 +890,8 @@ mod qc { use super::*; use sp_runtime::testing::{H256, Block as RawBlock, ExtrinsicWrapper}; - use state_machine::backend::InMemory; - use primitives::Blake2Hasher; + use sp_state_machine::backend::InMemory; + use sp_core::Blake2Hasher; type Block = RawBlock>; diff --git a/substrate/client/db/src/utils.rs b/substrate/client/db/src/utils.rs index 5db1ff8d66..c45fe1c064 100644 --- a/substrate/client/db/src/utils.rs +++ b/substrate/client/db/src/utils.rs @@ -26,7 +26,7 @@ use kvdb_rocksdb::{Database, DatabaseConfig}; use log::debug; use codec::Decode; -use trie::DBValue; +use sp_trie::DBValue; use sp_runtime::generic::BlockId; use sp_runtime::traits::{ Block as BlockT, Header as HeaderT, Zero, diff --git a/substrate/client/executor/Cargo.toml b/substrate/client/executor/Cargo.toml index 6dc4b46017..ec5f7c2a2c 100644 --- a/substrate/client/executor/Cargo.toml +++ b/substrate/client/executor/Cargo.toml @@ -8,17 +8,17 @@ edition = "2018" derive_more = "0.99.2" codec = { package = "parity-scale-codec", version = "1.0.0" } sp-io = { path = "../../primitives/io" } -primitives = { package = "sp-core", path = "../../primitives/core" } -trie = { package = "sp-trie", path = "../../primitives/trie" } -serializer = { package = "sp-serializer", path = "../../primitives/serializer" } -runtime_version = { package = "sp-version", path = "../../primitives/version" } -panic-handler = { package = "sp-panic-handler", path = "../../primitives/panic-handler" } +sp-core = { path = "../../primitives/core" } +sp-trie = { path = "../../primitives/trie" } +sp-serializer = { path = "../../primitives/serializer" } +sp-version = { path = "../../primitives/version" } +sp-panic-handler = { path = "../../primitives/panic-handler" } wasmi = "0.6.2" parity-wasm = "0.41.0" lazy_static = "1.4.0" -wasm-interface = { package = "sp-wasm-interface", path = "../../primitives/wasm-interface" } -runtime-interface = { package = "sp-runtime-interface", path = "../../primitives/runtime-interface" } -externalities = { package = "sp-externalities", path = "../../primitives/externalities" } +sp-wasm-interface = { path = "../../primitives/wasm-interface" } +sp-runtime-interface = { path = "../../primitives/runtime-interface" } +sp-externalities = { path = "../../primitives/externalities" } parking_lot = "0.9.0" log = "0.4.8" libsecp256k1 = "0.3.2" @@ -36,10 +36,9 @@ wasmtime-runtime = { version = "0.8", optional = true } assert_matches = "1.3.0" wabt = "0.9.2" hex-literal = "0.2.1" -runtime-test = { package = "sc-runtime-test", path = "runtime-test" } -test-runtime = { package = "substrate-test-runtime", path = "../../test-utils/runtime" } -runtime-interface = { package = "sp-runtime-interface", path = "../../primitives/runtime-interface" } -state_machine = { package = "sp-state-machine", path = "../../primitives/state-machine" } +sc-runtime-test = { path = "runtime-test" } +substrate-test-runtime = { path = "../../test-utils/runtime" } +sp-state-machine = { path = "../../primitives/state-machine" } test-case = "0.3.3" [features] diff --git a/substrate/client/executor/runtime-test/Cargo.toml b/substrate/client/executor/runtime-test/Cargo.toml index 5d781a7249..00e53199a2 100644 --- a/substrate/client/executor/runtime-test/Cargo.toml +++ b/substrate/client/executor/runtime-test/Cargo.toml @@ -8,13 +8,13 @@ build = "build.rs" [dependencies] sp-std = { path = "../../../primitives/std", default-features = false } sp-io = { path = "../../../primitives/io", default-features = false } -sandbox = { package = "sp-sandbox", path = "../../../primitives/sandbox", default-features = false } -primitives = { package = "sp-core", path = "../../../primitives/core", default-features = false } -sp-runtime = { package = "sp-runtime", path = "../../../primitives/runtime", default-features = false } +sp-sandbox = { path = "../../../primitives/sandbox", default-features = false } +sp-core = { path = "../../../primitives/core", default-features = false } +sp-runtime = { path = "../../../primitives/runtime", default-features = false } [build-dependencies] wasm-builder-runner = { package = "substrate-wasm-builder-runner", path = "../../../utils/wasm-builder-runner", version = "1.0.4" } [features] default = [ "std" ] -std = ["sp-io/std", "sandbox/std", "sp-std/std"] +std = ["sp-io/std", "sp-sandbox/std", "sp-std/std"] diff --git a/substrate/client/executor/runtime-test/src/lib.rs b/substrate/client/executor/runtime-test/src/lib.rs index 7a97aebc90..c49b9e70b4 100644 --- a/substrate/client/executor/runtime-test/src/lib.rs +++ b/substrate/client/executor/runtime-test/src/lib.rs @@ -16,9 +16,9 @@ use sp_io::{ #[cfg(not(feature = "std"))] use sp_runtime::{print, traits::{BlakeTwo256, Hash}}; #[cfg(not(feature = "std"))] -use primitives::{ed25519, sr25519}; +use sp_core::{ed25519, sr25519}; -primitives::wasm_export_functions! { +sp_core::wasm_export_functions! { fn test_data_in(input: Vec) -> Vec { print("set_storage"); storage::set(b"input", &input); @@ -112,8 +112,8 @@ primitives::wasm_export_functions! { execute_sandboxed( &code, &[ - sandbox::TypedValue::I32(0x12345678), - sandbox::TypedValue::I64(0x1234567887654321), + sp_sandbox::TypedValue::I32(0x12345678), + sp_sandbox::TypedValue::I64(0x1234567887654321), ], ).is_ok() } @@ -122,10 +122,10 @@ primitives::wasm_export_functions! { let ok = match execute_sandboxed( &code, &[ - sandbox::TypedValue::I32(0x1336), + sp_sandbox::TypedValue::I32(0x1336), ] ) { - Ok(sandbox::ReturnValue::Value(sandbox::TypedValue::I32(0x1337))) => true, + Ok(sp_sandbox::ReturnValue::Value(sp_sandbox::TypedValue::I32(0x1337))) => true, _ => false, }; @@ -133,19 +133,19 @@ primitives::wasm_export_functions! { } fn test_sandbox_instantiate(code: Vec) -> u8 { - let env_builder = sandbox::EnvironmentDefinitionBuilder::new(); - let code = match sandbox::Instance::new(&code, &env_builder, &mut ()) { + let env_builder = sp_sandbox::EnvironmentDefinitionBuilder::new(); + let code = match sp_sandbox::Instance::new(&code, &env_builder, &mut ()) { Ok(_) => 0, - Err(sandbox::Error::Module) => 1, - Err(sandbox::Error::Execution) => 2, - Err(sandbox::Error::OutOfBounds) => 3, + Err(sp_sandbox::Error::Module) => 1, + Err(sp_sandbox::Error::Execution) => 2, + Err(sp_sandbox::Error::OutOfBounds) => 3, }; code } fn test_offchain_local_storage() -> bool { - let kind = primitives::offchain::StorageKind::PERSISTENT; + let kind = sp_core::offchain::StorageKind::PERSISTENT; assert_eq!(sp_io::offchain::local_storage_get(kind, b"test"), None); sp_io::offchain::local_storage_set(kind, b"test", b"asd"); assert_eq!(sp_io::offchain::local_storage_get(kind, b"test"), Some(b"asd".to_vec())); @@ -161,7 +161,7 @@ primitives::wasm_export_functions! { } fn test_offchain_local_storage_with_none() { - let kind = primitives::offchain::StorageKind::PERSISTENT; + let kind = sp_core::offchain::StorageKind::PERSISTENT; assert_eq!(sp_io::offchain::local_storage_get(kind, b"test"), None); let res = sp_io::offchain::local_storage_compare_and_set(kind, b"test", None, b"value"); @@ -170,7 +170,7 @@ primitives::wasm_export_functions! { } fn test_offchain_http() -> bool { - use primitives::offchain::HttpRequestStatus; + use sp_core::offchain::HttpRequestStatus; let run = || -> Option<()> { let id = sp_io::offchain::http_request_start( "POST", @@ -201,45 +201,45 @@ primitives::wasm_export_functions! { #[cfg(not(feature = "std"))] fn execute_sandboxed( code: &[u8], - args: &[sandbox::TypedValue], -) -> Result { + args: &[sp_sandbox::TypedValue], +) -> Result { struct State { counter: u32, } fn env_assert( _e: &mut State, - args: &[sandbox::TypedValue], - ) -> Result { + args: &[sp_sandbox::TypedValue], + ) -> Result { if args.len() != 1 { - return Err(sandbox::HostError); + return Err(sp_sandbox::HostError); } - let condition = args[0].as_i32().ok_or_else(|| sandbox::HostError)?; + let condition = args[0].as_i32().ok_or_else(|| sp_sandbox::HostError)?; if condition != 0 { - Ok(sandbox::ReturnValue::Unit) + Ok(sp_sandbox::ReturnValue::Unit) } else { - Err(sandbox::HostError) + Err(sp_sandbox::HostError) } } fn env_inc_counter( e: &mut State, - args: &[sandbox::TypedValue], - ) -> Result { + args: &[sp_sandbox::TypedValue], + ) -> Result { if args.len() != 1 { - return Err(sandbox::HostError); + return Err(sp_sandbox::HostError); } - let inc_by = args[0].as_i32().ok_or_else(|| sandbox::HostError)?; + let inc_by = args[0].as_i32().ok_or_else(|| sp_sandbox::HostError)?; e.counter += inc_by as u32; - Ok(sandbox::ReturnValue::Value(sandbox::TypedValue::I32(e.counter as i32))) + Ok(sp_sandbox::ReturnValue::Value(sp_sandbox::TypedValue::I32(e.counter as i32))) } let mut state = State { counter: 0 }; let env_builder = { - let mut env_builder = sandbox::EnvironmentDefinitionBuilder::new(); + let mut env_builder = sp_sandbox::EnvironmentDefinitionBuilder::new(); env_builder.add_host_func("env", "assert", env_assert); env_builder.add_host_func("env", "inc_counter", env_inc_counter); - let memory = match sandbox::Memory::new(1, Some(16)) { + let memory = match sp_sandbox::Memory::new(1, Some(16)) { Ok(m) => m, Err(_) => unreachable!(" Memory::new() can return Err only if parameters are borked; \ @@ -251,8 +251,8 @@ fn execute_sandboxed( env_builder }; - let mut instance = sandbox::Instance::new(code, &env_builder, &mut state)?; + let mut instance = sp_sandbox::Instance::new(code, &env_builder, &mut state)?; let result = instance.invoke("call", args, &mut state); - result.map_err(|_| sandbox::HostError) + result.map_err(|_| sp_sandbox::HostError) } diff --git a/substrate/client/executor/src/allocator.rs b/substrate/client/executor/src/allocator.rs index 523499db71..88624a0ec2 100644 --- a/substrate/client/executor/src/allocator.rs +++ b/substrate/client/executor/src/allocator.rs @@ -50,7 +50,7 @@ use crate::error::{Error, Result}; use log::trace; use std::convert::{TryFrom, TryInto}; use std::ops::Range; -use wasm_interface::{Pointer, WordSize}; +use sp_wasm_interface::{Pointer, WordSize}; // The pointers need to be aligned to 8 bytes. This is because the // maximum value type handled by wasm32 is u64. diff --git a/substrate/client/executor/src/deprecated_host_interface.rs b/substrate/client/executor/src/deprecated_host_interface.rs index f585659d9e..2339dcdf70 100644 --- a/substrate/client/executor/src/deprecated_host_interface.rs +++ b/substrate/client/executor/src/deprecated_host_interface.rs @@ -18,12 +18,12 @@ use codec::Encode; use std::{convert::TryFrom, str}; -use primitives::{ +use sp_core::{ blake2_128, blake2_256, twox_64, twox_128, twox_256, ed25519, sr25519, keccak_256, Blake2Hasher, Pair, crypto::KeyTypeId, offchain, }; -use trie::{TrieConfiguration, trie_types::Layout}; -use wasm_interface::{ +use sp_trie::{TrieConfiguration, trie_types::Layout}; +use sp_wasm_interface::{ Pointer, WordSize, WritePrimitive, ReadPrimitive, FunctionContext, Result as WResult, }; diff --git a/substrate/client/executor/src/error.rs b/substrate/client/executor/src/error.rs index 84ae79a789..a15452c48b 100644 --- a/substrate/client/executor/src/error.rs +++ b/substrate/client/executor/src/error.rs @@ -16,7 +16,7 @@ //! Rust executor possible errors. -use serializer; +use sp_serializer; use wasmi; #[cfg(feature = "wasmtime")] use wasmtime_jit::{ActionError, SetupError}; @@ -28,7 +28,7 @@ pub type Result = std::result::Result; #[derive(Debug, derive_more::Display, derive_more::From)] pub enum Error { /// Unserializable Data - InvalidData(serializer::Error), + InvalidData(sp_serializer::Error), /// Trap occured during execution Trap(wasmi::Trap), /// Wasmi loading/instantiating error diff --git a/substrate/client/executor/src/integration_tests/mod.rs b/substrate/client/executor/src/integration_tests/mod.rs index f02b532619..24e9e022f7 100644 --- a/substrate/client/executor/src/integration_tests/mod.rs +++ b/substrate/client/executor/src/integration_tests/mod.rs @@ -18,15 +18,15 @@ mod sandbox; use codec::{Encode, Decode}; use hex_literal::hex; -use primitives::{ +use sp_core::{ Blake2Hasher, blake2_128, blake2_256, ed25519, sr25519, map, Pair, offchain::{OffchainExt, testing}, traits::Externalities, }; -use runtime_test::WASM_BINARY; -use state_machine::TestExternalities as CoreTestExternalities; +use sc_runtime_test::WASM_BINARY; +use sp_state_machine::TestExternalities as CoreTestExternalities; use test_case::test_case; -use trie::{TrieConfiguration, trie_types::Layout}; +use sp_trie::{TrieConfiguration, trie_types::Layout}; use crate::WasmExecutionMethod; @@ -128,7 +128,7 @@ fn storage_should_work(wasm_method: WasmExecutionMethod) { assert_eq!(output, b"all ok!".to_vec().encode()); } - let expected = TestExternalities::new(primitives::storage::Storage { + let expected = TestExternalities::new(sp_core::storage::Storage { top: map![ b"input".to_vec() => b"Hello world".to_vec(), b"foo".to_vec() => b"bar".to_vec(), @@ -165,7 +165,7 @@ fn clear_prefix_should_work(wasm_method: WasmExecutionMethod) { assert_eq!(output, b"all ok!".to_vec().encode()); } - let expected = TestExternalities::new(primitives::storage::Storage { + let expected = TestExternalities::new(sp_core::storage::Storage { top: map![ b"aaa".to_vec() => b"1".to_vec(), b"aab".to_vec() => b"2".to_vec(), @@ -443,7 +443,7 @@ fn ordered_trie_root_should_work(wasm_method: WasmExecutionMethod) { #[test_case(WasmExecutionMethod::Interpreted)] #[cfg_attr(feature = "wasmtime", test_case(WasmExecutionMethod::Compiled))] fn offchain_local_storage_should_work(wasm_method: WasmExecutionMethod) { - use primitives::offchain::OffchainStorage; + use sp_core::offchain::OffchainStorage; let mut ext = TestExternalities::default(); let (offchain, state) = testing::TestOffchainExt::new(); diff --git a/substrate/client/executor/src/integration_tests/sandbox.rs b/substrate/client/executor/src/integration_tests/sandbox.rs index c18b848acc..f18291da67 100644 --- a/substrate/client/executor/src/integration_tests/sandbox.rs +++ b/substrate/client/executor/src/integration_tests/sandbox.rs @@ -18,7 +18,7 @@ use super::{TestExternalities, call_in_wasm}; use crate::WasmExecutionMethod; use codec::Encode; -use runtime_test::WASM_BINARY; +use sc_runtime_test::WASM_BINARY; use test_case::test_case; use wabt; diff --git a/substrate/client/executor/src/lib.rs b/substrate/client/executor/src/lib.rs index 97bdb0e20d..5045874859 100644 --- a/substrate/client/executor/src/lib.rs +++ b/substrate/client/executor/src/lib.rs @@ -46,12 +46,12 @@ mod integration_tests; pub mod error; pub use wasmi; pub use native_executor::{with_native_environment, NativeExecutor, NativeExecutionDispatch}; -pub use runtime_version::{RuntimeVersion, NativeVersion}; +pub use sp_version::{RuntimeVersion, NativeVersion}; pub use codec::Codec; #[doc(hidden)] -pub use primitives::traits::Externalities; +pub use sp_core::traits::Externalities; #[doc(hidden)] -pub use wasm_interface; +pub use sp_wasm_interface; pub use wasm_runtime::WasmExecutionMethod; /// Call the given `function` in the given wasm `code`. @@ -64,7 +64,7 @@ pub use wasm_runtime::WasmExecutionMethod; /// - `heap_pages`: The number of heap pages to allocate. /// /// Returns the `Vec` that contains the return value of the function. -pub fn call_in_wasm( +pub fn call_in_wasm( function: &str, call_data: &[u8], execution_method: WasmExecutionMethod, @@ -93,7 +93,7 @@ pub trait RuntimeInfo { #[cfg(test)] mod tests { use super::*; - use runtime_test::WASM_BINARY; + use sc_runtime_test::WASM_BINARY; use sp_io::TestExternalities; #[test] diff --git a/substrate/client/executor/src/native_executor.rs b/substrate/client/executor/src/native_executor.rs index 635acc8716..09e514f603 100644 --- a/substrate/client/executor/src/native_executor.rs +++ b/substrate/client/executor/src/native_executor.rs @@ -19,17 +19,17 @@ use crate::{ wasm_runtime::{RuntimesCache, WasmExecutionMethod, WasmRuntime}, }; -use runtime_version::{NativeVersion, RuntimeVersion}; +use sp_version::{NativeVersion, RuntimeVersion}; use codec::{Decode, Encode}; -use primitives::{NativeOrEncoded, traits::{CodeExecutor, Externalities}}; +use sp_core::{NativeOrEncoded, traits::{CodeExecutor, Externalities}}; use log::trace; use std::{result, cell::RefCell, panic::{UnwindSafe, AssertUnwindSafe}}; -use wasm_interface::{HostFunctions, Function}; +use sp_wasm_interface::{HostFunctions, Function}; thread_local! { static RUNTIMES_CACHE: RefCell = RefCell::new(RuntimesCache::new()); @@ -43,7 +43,7 @@ pub(crate) fn safe_call(f: F) -> Result { // Substrate uses custom panic hook that terminates process on panic. Disable // termination for the native call. - let _guard = panic_handler::AbortGuard::force_unwind(); + let _guard = sp_panic_handler::AbortGuard::force_unwind(); std::panic::catch_unwind(f).map_err(|_| Error::Runtime) } @@ -53,7 +53,7 @@ pub(crate) fn safe_call(f: F) -> Result pub fn with_native_environment(ext: &mut dyn Externalities, f: F) -> Result where F: UnwindSafe + FnOnce() -> U { - externalities::set_and_run_with_externalities(ext, move || safe_call(f)) + sp_externalities::set_and_run_with_externalities(ext, move || safe_call(f)) } /// Delegate for dispatching a CodeExecutor call. @@ -267,8 +267,8 @@ impl CodeExecutor for NativeExecutor { /// ``` /// sc_executor::native_executor_instance!( /// pub MyExecutor, -/// test_runtime::api::dispatch, -/// test_runtime::native_version, +/// substrate_test_runtime::api::dispatch, +/// substrate_test_runtime::native_version, /// ); /// ``` /// @@ -278,7 +278,7 @@ impl CodeExecutor for NativeExecutor { /// executor aware of the host functions for these interfaces. /// /// ``` -/// # use runtime_interface::runtime_interface; +/// # use sp_runtime_interface::runtime_interface; /// /// #[runtime_interface] /// trait MyInterface { @@ -289,8 +289,8 @@ impl CodeExecutor for NativeExecutor { /// /// sc_executor::native_executor_instance!( /// pub MyExecutor, -/// test_runtime::api::dispatch, -/// test_runtime::native_version, +/// substrate_test_runtime::api::dispatch, +/// substrate_test_runtime::native_version, /// my_interface::HostFunctions, /// ); /// ``` @@ -337,7 +337,7 @@ macro_rules! native_executor_instance { #[cfg(test)] mod tests { use super::*; - use runtime_interface::runtime_interface; + use sp_runtime_interface::runtime_interface; #[runtime_interface] trait MyInterface { @@ -348,8 +348,8 @@ mod tests { native_executor_instance!( pub MyExecutor, - test_runtime::api::dispatch, - test_runtime::native_version, + substrate_test_runtime::api::dispatch, + substrate_test_runtime::native_version, (my_interface::HostFunctions, my_interface::HostFunctions), ); diff --git a/substrate/client/executor/src/sandbox.rs b/substrate/client/executor/src/sandbox.rs index da71b06672..e0e1780a14 100644 --- a/substrate/client/executor/src/sandbox.rs +++ b/substrate/client/executor/src/sandbox.rs @@ -21,12 +21,12 @@ use crate::error::{Result, Error}; use std::{collections::HashMap, rc::Rc}; use codec::{Decode, Encode}; -use primitives::sandbox as sandbox_primitives; +use sp_core::sandbox as sandbox_primitives; use wasmi::{ Externals, ImportResolver, MemoryInstance, MemoryRef, Module, ModuleInstance, ModuleRef, RuntimeArgs, RuntimeValue, Trap, TrapKind, memory_units::Pages, }; -use wasm_interface::{Pointer, WordSize}; +use sp_wasm_interface::{Pointer, WordSize}; /// Index of a function inside the supervisor. /// diff --git a/substrate/client/executor/src/wasm_runtime.rs b/substrate/client/executor/src/wasm_runtime.rs index e033285232..6181a1aab2 100644 --- a/substrate/client/executor/src/wasm_runtime.rs +++ b/substrate/client/executor/src/wasm_runtime.rs @@ -26,12 +26,12 @@ use log::{trace, warn}; use codec::Decode; -use primitives::{storage::well_known_keys, traits::Externalities}; +use sp_core::{storage::well_known_keys, traits::Externalities}; -use runtime_version::RuntimeVersion; +use sp_version::RuntimeVersion; use std::{collections::hash_map::{Entry, HashMap}, panic::AssertUnwindSafe}; -use wasm_interface::Function; +use sp_wasm_interface::Function; /// The Substrate Wasm runtime. pub trait WasmRuntime { @@ -259,7 +259,7 @@ fn create_versioned_wasm_runtime( #[cfg(test)] mod tests { - use wasm_interface::HostFunctions; + use sp_wasm_interface::HostFunctions; #[test] fn host_functions_are_equal() { diff --git a/substrate/client/executor/src/wasm_utils.rs b/substrate/client/executor/src/wasm_utils.rs index caa63ddbf2..95b1db65ce 100644 --- a/substrate/client/executor/src/wasm_utils.rs +++ b/substrate/client/executor/src/wasm_utils.rs @@ -16,28 +16,28 @@ //! Utilities for defining the wasm host environment. -use wasm_interface::{Pointer, WordSize}; +use sp_wasm_interface::{Pointer, WordSize}; /// Converts arguments into respective WASM types. #[macro_export] macro_rules! convert_args { () => ([]); - ( $( $t:ty ),* ) => ( [ $( <$t as $crate::wasm_interface::IntoValue>::VALUE_TYPE, )* ] ); + ( $( $t:ty ),* ) => ( [ $( <$t as $crate::sp_wasm_interface::IntoValue>::VALUE_TYPE, )* ] ); } /// Generates a WASM signature for given list of parameters. #[macro_export] macro_rules! gen_signature { ( ( $( $params: ty ),* ) ) => ( - $crate::wasm_interface::Signature { + $crate::sp_wasm_interface::Signature { args: std::borrow::Cow::Borrowed(&convert_args!( $( $params ),* )[..]), return_value: None, } ); ( ( $( $params: ty ),* ) -> $returns:ty ) => ( - $crate::wasm_interface::Signature { + $crate::sp_wasm_interface::Signature { args: std::borrow::Cow::Borrowed(&convert_args!( $( $params ),* )[..]), - return_value: Some(<$returns as $crate::wasm_interface::IntoValue>::VALUE_TYPE), + return_value: Some(<$returns as $crate::sp_wasm_interface::IntoValue>::VALUE_TYPE), } ); } @@ -63,18 +63,18 @@ macro_rules! gen_functions { struct $name; #[allow(unused)] - impl $crate::wasm_interface::Function for $name { + impl $crate::sp_wasm_interface::Function for $name { fn name(&self) -> &str { stringify!($name) } - fn signature(&self) -> $crate::wasm_interface::Signature { + fn signature(&self) -> $crate::sp_wasm_interface::Signature { gen_signature!( ( $( $params ),* ) $( -> $returns )? ) } fn execute( &self, - context: &mut dyn $crate::wasm_interface::FunctionContext, - args: &mut dyn Iterator, - ) -> ::std::result::Result, String> { + context: &mut dyn $crate::sp_wasm_interface::FunctionContext, + args: &mut dyn Iterator, + ) -> ::std::result::Result, String> { let mut $context = context; marshall! { args, @@ -83,7 +83,7 @@ macro_rules! gen_functions { } } - &$name as &dyn $crate::wasm_interface::Function + &$name as &dyn $crate::sp_wasm_interface::Function }, } $context, @@ -103,7 +103,7 @@ macro_rules! unmarshall_args { $( let $names : $params = $args_iter.next() - .and_then(|val| <$params as $crate::wasm_interface::TryFromValue>::try_from_value(val)) + .and_then(|val| <$params as $crate::sp_wasm_interface::TryFromValue>::try_from_value(val)) .expect( "`$args_iter` comes from an argument of Externals::execute_function; args to an external call always matches the signature of the external; @@ -140,7 +140,7 @@ macro_rules! marshall { unmarshall_args!($body, $args_iter, $( $names : $params ),*) }); let r = body()?; - return Ok(Some($crate::wasm_interface::IntoValue::into_value(r))) + return Ok(Some($crate::sp_wasm_interface::IntoValue::into_value(r))) }); ( $args_iter:ident, ( $( $names:ident : $params:ty ),* ) => $body:tt ) => ({ let body = $crate::wasm_utils::constrain_closure::<(), _>(|| { @@ -162,9 +162,9 @@ macro_rules! impl_wasm_host_interface { )* } ) => ( - impl $crate::wasm_interface::HostFunctions for $interface_name { + impl $crate::sp_wasm_interface::HostFunctions for $interface_name { #[allow(non_camel_case_types)] - fn host_functions() -> Vec<&'static dyn $crate::wasm_interface::Function> { + fn host_functions() -> Vec<&'static dyn $crate::sp_wasm_interface::Function> { gen_functions!( $context, $( $name( $( $names: $params ),* ) $( -> $returns )? { $( $body )* } )* diff --git a/substrate/client/executor/src/wasmi_execution.rs b/substrate/client/executor/src/wasmi_execution.rs index 2593de68c2..cdead6cee1 100644 --- a/substrate/client/executor/src/wasmi_execution.rs +++ b/substrate/client/executor/src/wasmi_execution.rs @@ -23,14 +23,14 @@ use wasmi::{ }; use crate::error::{Error, WasmError}; use codec::{Encode, Decode}; -use primitives::{sandbox as sandbox_primitives, traits::Externalities}; +use sp_core::{sandbox as sandbox_primitives, traits::Externalities}; use crate::sandbox; use crate::allocator; use crate::wasm_utils::interpret_runtime_api_result; use crate::wasm_runtime::WasmRuntime; use log::{error, trace}; use parity_wasm::elements::{deserialize_buffer, DataSegment, Instruction, Module as RawModule}; -use wasm_interface::{ +use sp_wasm_interface::{ FunctionContext, Pointer, WordSize, Sandbox, MemoryId, Result as WResult, Function, }; @@ -273,7 +273,7 @@ impl<'a> wasmi::ModuleImportResolver for Resolver<'a> { fn resolve_func(&self, name: &str, signature: &wasmi::Signature) -> std::result::Result { - let signature = wasm_interface::Signature::from(signature); + let signature = sp_wasm_interface::Signature::from(signature); for (function_index, function) in self.0.iter().enumerate() { if name == function.name() { if signature == function.signature() { @@ -364,7 +364,7 @@ fn call_in_wasm_module( let offset = fec.allocate_memory(data.len() as u32)?; fec.write_memory(offset, data)?; - let result = externalities::set_and_run_with_externalities( + let result = sp_externalities::set_and_run_with_externalities( ext, || module_instance.invoke_export( method, diff --git a/substrate/client/executor/src/wasmtime/function_executor.rs b/substrate/client/executor/src/wasmtime/function_executor.rs index 34a3007689..4db7adc83a 100644 --- a/substrate/client/executor/src/wasmtime/function_executor.rs +++ b/substrate/client/executor/src/wasmtime/function_executor.rs @@ -25,12 +25,12 @@ use codec::{Decode, Encode}; use cranelift_codegen::ir; use cranelift_codegen::isa::TargetFrontendConfig; use log::trace; -use primitives::sandbox as sandbox_primitives; +use sp_core::sandbox as sandbox_primitives; use std::{cmp, mem, ptr}; use wasmtime_environ::translate_signature; use wasmtime_jit::{ActionError, Compiler}; use wasmtime_runtime::{Export, VMCallerCheckedAnyfunc, VMContext, wasmtime_call_trampoline}; -use wasm_interface::{ +use sp_wasm_interface::{ FunctionContext, MemoryId, Pointer, Result as WResult, Sandbox, Signature, Value, ValueType, WordSize, }; diff --git a/substrate/client/executor/src/wasmtime/runtime.rs b/substrate/client/executor/src/wasmtime/runtime.rs index 1a7385cc46..6fdf9f0e9e 100644 --- a/substrate/client/executor/src/wasmtime/runtime.rs +++ b/substrate/client/executor/src/wasmtime/runtime.rs @@ -33,7 +33,7 @@ use std::cell::RefCell; use std::collections::HashMap; use std::convert::TryFrom; use std::rc::Rc; -use wasm_interface::{Pointer, WordSize, Function}; +use sp_wasm_interface::{Pointer, WordSize, Function}; use wasmtime_environ::{Module, translate_signature}; use wasmtime_jit::{ ActionOutcome, ActionError, CodeMemory, CompilationStrategy, CompiledModule, Compiler, Context, @@ -175,7 +175,7 @@ fn call_method( let args = [RuntimeValue::I32(u32::from(data_ptr) as i32), RuntimeValue::I32(data_len as i32)]; // Invoke the function in the runtime. - let outcome = externalities::set_and_run_with_externalities(ext, || { + let outcome = sp_externalities::set_and_run_with_externalities(ext, || { context .invoke(&mut instance, method, &args[..]) .map_err(Error::Wasmtime) diff --git a/substrate/client/executor/src/wasmtime/trampoline.rs b/substrate/client/executor/src/wasmtime/trampoline.rs index 25b3fefbfa..1251125251 100644 --- a/substrate/client/executor/src/wasmtime/trampoline.rs +++ b/substrate/client/executor/src/wasmtime/trampoline.rs @@ -26,7 +26,7 @@ use cranelift_codegen::print_errors::pretty_error; use wasmtime_jit::{CodeMemory, Compiler}; use wasmtime_environ::CompiledFunction; use wasmtime_runtime::{VMContext, VMFunctionBody}; -use wasm_interface::{Function, Value, ValueType}; +use sp_wasm_interface::{Function, Value, ValueType}; use std::{cmp, panic::{self, AssertUnwindSafe}, ptr}; use crate::error::{Error, WasmError}; diff --git a/substrate/client/executor/src/wasmtime/util.rs b/substrate/client/executor/src/wasmtime/util.rs index 874ccc8c85..55cb5ecc50 100644 --- a/substrate/client/executor/src/wasmtime/util.rs +++ b/substrate/client/executor/src/wasmtime/util.rs @@ -18,7 +18,7 @@ use crate::error::{Error, Result}; use cranelift_codegen::{ir, isa}; use std::ops::Range; -use wasm_interface::{Pointer, Signature, ValueType}; +use sp_wasm_interface::{Pointer, Signature, ValueType}; /// Read data from a slice of memory into a destination buffer. /// diff --git a/substrate/client/finality-grandpa/Cargo.toml b/substrate/client/finality-grandpa/Cargo.toml index 3b1d57d213..8f4cb2298d 100644 --- a/substrate/client/finality-grandpa/Cargo.toml +++ b/substrate/client/finality-grandpa/Cargo.toml @@ -12,31 +12,31 @@ futures-timer = "2.0.2" log = "0.4.8" parking_lot = "0.9.0" rand = "0.7.2" -codec = { package = "parity-scale-codec", version = "1.0.0", features = ["derive"] } +parity-scale-codec = { version = "1.0.0", features = ["derive"] } sp-runtime = { path = "../../primitives/runtime" } -consensus_common = { package = "sp-consensus", path = "../../primitives/consensus/common" } -primitives = { package = "sp-core", path = "../../primitives/core" } +sp-consensus = { path = "../../primitives/consensus/common" } +sp-core = { path = "../../primitives/core" } sc-telemetry = { path = "../telemetry" } -keystore = { package = "sc-keystore", path = "../keystore" } +sc-keystore = { path = "../keystore" } serde_json = "1.0.41" -client-api = { package = "sc-client-api", path = "../api" } -client = { package = "sc-client", path = "../" } -inherents = { package = "sp-inherents", path = "../../primitives/inherents" } +sc-client-api = { path = "../api" } +sc-client = { path = "../" } +sp-inherents = { path = "../../primitives/inherents" } sp-blockchain = { path = "../../primitives/blockchain" } -network = { package = "sc-network", path = "../network" } -network-gossip = { package = "sc-network-gossip", path = "../network-gossip" } +sc-network = { path = "../network" } +sc-network-gossip = { path = "../network-gossip" } sp-finality-tracker = { path = "../../primitives/finality-tracker" } -fg_primitives = { package = "sp-finality-grandpa", path = "../../primitives/finality-grandpa" } -grandpa = { package = "finality-grandpa", version = "0.10.1", features = ["derive-codec"] } +sp-finality-grandpa = { path = "../../primitives/finality-grandpa" } +finality-grandpa = { version = "0.10.1", features = ["derive-codec"] } [dev-dependencies] -grandpa = { package = "finality-grandpa", version = "0.10.1", features = ["derive-codec", "test-helpers"] } -network = { package = "sc-network", path = "../network" } +finality-grandpa = { version = "0.10.1", features = ["derive-codec", "test-helpers"] } +sc-network = { path = "../network" } sc-network-test = { path = "../network/test" } -keyring = { package = "sp-keyring", path = "../../primitives/keyring" } -test-client = { package = "substrate-test-runtime-client", path = "../../test-utils/runtime/client"} -babe_primitives = { package = "sp-consensus-babe", path = "../../primitives/consensus/babe" } -state_machine = { package = "sp-state-machine", path = "../../primitives/state-machine" } +sp-keyring = { path = "../../primitives/keyring" } +substrate-test-runtime-client = { path = "../../test-utils/runtime/client"} +sp-consensus-babe = { path = "../../primitives/consensus/babe" } +sp-state-machine = { path = "../../primitives/state-machine" } env_logger = "0.7.0" tokio = "0.1.22" tempfile = "3.1.0" diff --git a/substrate/client/finality-grandpa/src/authorities.rs b/substrate/client/finality-grandpa/src/authorities.rs index 4bc4e3c7b8..aa9b850779 100644 --- a/substrate/client/finality-grandpa/src/authorities.rs +++ b/substrate/client/finality-grandpa/src/authorities.rs @@ -18,11 +18,11 @@ use fork_tree::ForkTree; use parking_lot::RwLock; -use grandpa::voter_set::VoterSet; -use codec::{Encode, Decode}; +use finality_grandpa::voter_set::VoterSet; +use parity_scale_codec::{Encode, Decode}; use log::{debug, info}; use sc_telemetry::{telemetry, CONSENSUS_INFO}; -use fg_primitives::{AuthorityId, AuthorityList}; +use sp_finality_grandpa::{AuthorityId, AuthorityList}; use std::cmp::Ord; use std::fmt::Debug; @@ -403,7 +403,7 @@ pub(crate) struct PendingChange { } impl Decode for PendingChange { - fn decode(value: &mut I) -> Result { + fn decode(value: &mut I) -> Result { let next_authorities = Decode::decode(value)?; let delay = Decode::decode(value)?; let canon_height = Decode::decode(value)?; @@ -431,7 +431,7 @@ impl + Clone> PendingChange { #[cfg(test)] mod tests { use super::*; - use primitives::crypto::Public; + use sp_core::crypto::Public; fn static_is_descendent_of(value: bool) -> impl Fn(&A, &A) -> Result diff --git a/substrate/client/finality-grandpa/src/aux_schema.rs b/substrate/client/finality-grandpa/src/aux_schema.rs index 3e171a9441..63394dcbe1 100644 --- a/substrate/client/finality-grandpa/src/aux_schema.rs +++ b/substrate/client/finality-grandpa/src/aux_schema.rs @@ -18,14 +18,14 @@ use std::fmt::Debug; use std::sync::Arc; -use codec::{Encode, Decode}; -use client_api::backend::AuxStore; +use parity_scale_codec::{Encode, Decode}; +use sc_client_api::backend::AuxStore; use sp_blockchain::{Result as ClientResult, Error as ClientError}; use fork_tree::ForkTree; -use grandpa::round::State as RoundState; +use finality_grandpa::round::State as RoundState; use sp_runtime::traits::{Block as BlockT, NumberFor}; use log::{info, warn}; -use fg_primitives::{AuthorityList, SetId, RoundNumber}; +use sp_finality_grandpa::{AuthorityList, SetId, RoundNumber}; use crate::authorities::{AuthoritySet, SharedAuthoritySet, PendingChange, DelayKind}; use crate::consensus_changes::{SharedConsensusChanges, ConsensusChanges}; @@ -439,14 +439,14 @@ pub(crate) fn load_authorities(backend: &B) #[cfg(test)] mod test { - use fg_primitives::AuthorityId; - use primitives::H256; - use test_client; + use sp_finality_grandpa::AuthorityId; + use sp_core::H256; + use substrate_test_runtime_client; use super::*; #[test] fn load_decode_from_v0_migrates_data_format() { - let client = test_client::new(); + let client = substrate_test_runtime_client::new(); let authorities = vec![(AuthorityId::default(), 100)]; let set_id = 3; @@ -482,7 +482,7 @@ mod test { ); // should perform the migration - load_persistent::( + load_persistent::( &client, H256::random(), 0, @@ -494,7 +494,7 @@ mod test { Some(2), ); - let PersistentData { authority_set, set_state, .. } = load_persistent::( + let PersistentData { authority_set, set_state, .. } = load_persistent::( &client, H256::random(), 0, @@ -534,7 +534,7 @@ mod test { #[test] fn load_decode_from_v1_migrates_data_format() { - let client = test_client::new(); + let client = substrate_test_runtime_client::new(); let authorities = vec![(AuthorityId::default(), 100)]; let set_id = 3; @@ -572,7 +572,7 @@ mod test { ); // should perform the migration - load_persistent::( + load_persistent::( &client, H256::random(), 0, @@ -584,7 +584,7 @@ mod test { Some(2), ); - let PersistentData { authority_set, set_state, .. } = load_persistent::( + let PersistentData { authority_set, set_state, .. } = load_persistent::( &client, H256::random(), 0, @@ -624,11 +624,11 @@ mod test { #[test] fn write_read_concluded_rounds() { - let client = test_client::new(); + let client = substrate_test_runtime_client::new(); let hash = H256::random(); let round_state = RoundState::genesis((hash, 0)); - let completed_round = CompletedRound:: { + let completed_round = CompletedRound:: { number: 42, state: round_state.clone(), base: round_state.prevote_ghost.unwrap(), @@ -642,7 +642,7 @@ mod test { round_number.using_encoded(|n| key.extend(n)); assert_eq!( - load_decode::<_, CompletedRound::>(&client, &key).unwrap(), + load_decode::<_, CompletedRound::>(&client, &key).unwrap(), Some(completed_round), ); } diff --git a/substrate/client/finality-grandpa/src/communication/gossip.rs b/substrate/client/finality-grandpa/src/communication/gossip.rs index 6ed70b66ae..2ac6c9cf49 100644 --- a/substrate/client/finality-grandpa/src/communication/gossip.rs +++ b/substrate/client/finality-grandpa/src/communication/gossip.rs @@ -83,10 +83,10 @@ //! We only send polite messages to peers, use sp_runtime::traits::{NumberFor, Block as BlockT, Zero}; -use network_gossip::{GossipEngine, MessageIntent, ValidatorContext}; -use network::{config::Roles, PeerId, ReputationChange}; -use codec::{Encode, Decode}; -use fg_primitives::AuthorityId; +use sc_network_gossip::{GossipEngine, MessageIntent, ValidatorContext}; +use sc_network::{config::Roles, PeerId, ReputationChange}; +use parity_scale_codec::{Encode, Decode}; +use sp_finality_grandpa::AuthorityId; use sc_telemetry::{telemetry, CONSENSUS_DEBUG}; use log::{trace, debug, warn}; @@ -908,15 +908,15 @@ impl Inner { // too many equivocations (we exceed the fault-tolerance bound). for vote in last_completed_round.votes { match vote.message { - grandpa::Message::Prevote(prevote) => { - prevotes.push(grandpa::SignedPrevote { + finality_grandpa::Message::Prevote(prevote) => { + prevotes.push(finality_grandpa::SignedPrevote { prevote, signature: vote.signature, id: vote.id, }); }, - grandpa::Message::Precommit(precommit) => { - precommits.push(grandpa::SignedPrecommit { + finality_grandpa::Message::Precommit(precommit) => { + precommits.push(finality_grandpa::SignedPrecommit { precommit, signature: vote.signature, id: vote.id, @@ -1280,7 +1280,7 @@ impl GossipValidator { } } -impl network_gossip::Validator for GossipValidator { +impl sc_network_gossip::Validator for GossipValidator { fn new_peer(&self, context: &mut dyn ValidatorContext, who: &PeerId, roles: Roles) { let packet = { let mut inner = self.inner.write(); @@ -1306,7 +1306,7 @@ impl network_gossip::Validator for GossipValidator } fn validate(&self, context: &mut dyn ValidatorContext, who: &PeerId, data: &[u8]) - -> network_gossip::ValidationResult + -> sc_network_gossip::ValidationResult { let (action, broadcast_topics, peer_reply) = self.do_validate(who, data); @@ -1323,15 +1323,15 @@ impl network_gossip::Validator for GossipValidator Action::Keep(topic, cb) => { self.report(who.clone(), cb); context.broadcast_message(topic, data.to_vec(), false); - network_gossip::ValidationResult::ProcessAndKeep(topic) + sc_network_gossip::ValidationResult::ProcessAndKeep(topic) } Action::ProcessAndDiscard(topic, cb) => { self.report(who.clone(), cb); - network_gossip::ValidationResult::ProcessAndDiscard(topic) + sc_network_gossip::ValidationResult::ProcessAndDiscard(topic) } Action::Discard(cb) => { self.report(who.clone(), cb); - network_gossip::ValidationResult::Discard + sc_network_gossip::ValidationResult::Discard } } } @@ -1502,9 +1502,9 @@ impl Future for ReportingTask { mod tests { use super::*; use super::environment::SharedVoterSetState; - use network_gossip::Validator as GossipValidatorT; + use sc_network_gossip::Validator as GossipValidatorT; use sc_network_test::Block; - use primitives::{crypto::Public, H256}; + use sp_core::{crypto::Public, H256}; // some random config (not really needed) fn config() -> crate::Config { @@ -1726,7 +1726,7 @@ mod tests { round: Round(1), set_id: SetId(set_id), message: SignedMessage:: { - message: grandpa::Message::Prevote(grandpa::Prevote { + message: finality_grandpa::Message::Prevote(finality_grandpa::Prevote { target_hash: Default::default(), target_number: 10, }), @@ -1739,7 +1739,7 @@ mod tests { round: Round(1), set_id: SetId(set_id), message: SignedMessage:: { - message: grandpa::Message::Prevote(grandpa::Prevote { + message: finality_grandpa::Message::Prevote(finality_grandpa::Prevote { target_hash: Default::default(), target_number: 10, }), @@ -1770,7 +1770,7 @@ mod tests { let mut inner = val.inner.write(); inner.validate_catch_up_message(&peer, &FullCatchUpMessage { set_id: SetId(set_id), - message: grandpa::CatchUp { + message: finality_grandpa::CatchUp { round_number: 10, prevotes: Default::default(), precommits: Default::default(), @@ -1806,7 +1806,7 @@ mod tests { completed_rounds.push(environment::CompletedRound { number: 2, - state: grandpa::round::State::genesis(Default::default()), + state: finality_grandpa::round::State::genesis(Default::default()), base: Default::default(), votes: Default::default(), }); diff --git a/substrate/client/finality-grandpa/src/communication/mod.rs b/substrate/client/finality-grandpa/src/communication/mod.rs index e535f85776..c690376193 100644 --- a/substrate/client/finality-grandpa/src/communication/mod.rs +++ b/substrate/client/finality-grandpa/src/communication/mod.rs @@ -31,13 +31,13 @@ use std::sync::Arc; use futures::{prelude::*, future::Executor as _, sync::mpsc}; use futures03::{compat::Compat, stream::StreamExt, future::FutureExt as _, future::TryFutureExt as _}; -use grandpa::Message::{Prevote, Precommit, PrimaryPropose}; -use grandpa::{voter, voter_set::VoterSet}; +use finality_grandpa::Message::{Prevote, Precommit, PrimaryPropose}; +use finality_grandpa::{voter, voter_set::VoterSet}; use log::{debug, trace}; -use network::ReputationChange; -use network_gossip::{GossipEngine, Network}; -use codec::{Encode, Decode}; -use primitives::Pair; +use sc_network::ReputationChange; +use sc_network_gossip::{GossipEngine, Network}; +use parity_scale_codec::{Encode, Decode}; +use sp_core::Pair; use sp_runtime::traits::{Block as BlockT, Hash as HashT, Header as HeaderT, NumberFor}; use sc_telemetry::{telemetry, CONSENSUS_DEBUG, CONSENSUS_INFO}; @@ -49,7 +49,7 @@ use crate::environment::HasVoted; use gossip::{ GossipMessage, FullCatchUpMessage, FullCommitMessage, VoteMessage, GossipValidator }; -use fg_primitives::{ +use sp_finality_grandpa::{ AuthorityPair, AuthorityId, AuthoritySignature, SetId as SetIdNumber, RoundNumber, }; @@ -59,11 +59,11 @@ mod periodic; #[cfg(test)] mod tests; -pub use fg_primitives::GRANDPA_ENGINE_ID; +pub use sp_finality_grandpa::GRANDPA_ENGINE_ID; // cost scalars for reporting peers. mod cost { - use network::ReputationChange as Rep; + use sc_network::ReputationChange as Rep; pub(super) const PAST_REJECTION: Rep = Rep::new(-50, "Grandpa: Past message"); pub(super) const BAD_SIGNATURE: Rep = Rep::new(-100, "Grandpa: Bad signature"); pub(super) const MALFORMED_CATCH_UP: Rep = Rep::new(-1000, "Grandpa: Malformed cath-up"); @@ -87,7 +87,7 @@ mod cost { // benefit scalars for reporting peers. mod benefit { - use network::ReputationChange as Rep; + use sc_network::ReputationChange as Rep; pub(super) const NEIGHBOR_MESSAGE: Rep = Rep::new(100, "Grandpa: Neighbor message"); pub(super) const ROUND_MESSAGE: Rep = Rep::new(100, "Grandpa: Round message"); pub(super) const BASIC_VALIDATED_CATCH_UP: Rep = Rep::new(200, "Grandpa: Catch-up message"); @@ -356,7 +356,7 @@ impl NetworkBridge { /// If the given vector of peers is empty then the underlying implementation /// should make a best effort to fetch the block from any peers it is /// connected to (NOTE: this assumption will change in the future #3629). - pub(crate) fn set_sync_fork_request(&self, peers: Vec, hash: B::Hash, number: NumberFor) { + pub(crate) fn set_sync_fork_request(&self, peers: Vec, hash: B::Hash, number: NumberFor) { self.gossip_engine.set_sync_fork_request(peers, hash, number) } } @@ -370,7 +370,7 @@ fn incoming_global( ) -> impl Stream, Error = Error> { let process_commit = move | msg: FullCommitMessage, - mut notification: network_gossip::TopicNotification, + mut notification: sc_network_gossip::TopicNotification, gossip_engine: &mut GossipEngine, gossip_validator: &Arc>, voters: &VoterSet, @@ -432,7 +432,7 @@ fn incoming_global( let process_catch_up = move | msg: FullCatchUpMessage, - mut notification: network_gossip::TopicNotification, + mut notification: sc_network_gossip::TopicNotification, gossip_engine: &mut GossipEngine, gossip_validator: &Arc>, voters: &VoterSet, @@ -557,15 +557,15 @@ impl Sink for OutgoingMessages fn start_send(&mut self, mut msg: Message) -> StartSend, Error> { // if we've voted on this round previously under the same key, send that vote instead match &mut msg { - grandpa::Message::PrimaryPropose(ref mut vote) => + finality_grandpa::Message::PrimaryPropose(ref mut vote) => if let Some(propose) = self.has_voted.propose() { *vote = propose.clone(); }, - grandpa::Message::Prevote(ref mut vote) => + finality_grandpa::Message::Prevote(ref mut vote) => if let Some(prevote) = self.has_voted.prevote() { *vote = prevote.clone(); }, - grandpa::Message::Precommit(ref mut vote) => + finality_grandpa::Message::Precommit(ref mut vote) => if let Some(precommit) = self.has_voted.precommit() { *vote = precommit.clone(); }, @@ -660,7 +660,7 @@ fn check_compact_commit( .enumerate() { use crate::communication::gossip::Misbehavior; - use grandpa::Message as GrandpaMessage; + use finality_grandpa::Message as GrandpaMessage; if let Err(()) = check_message_sig::( &GrandpaMessage::Precommit(precommit.clone()), @@ -772,7 +772,7 @@ fn check_catch_up( // check signatures on all contained prevotes. let signatures_checked = check_signatures::( msg.prevotes.iter().map(|vote| { - (grandpa::Message::Prevote(vote.prevote.clone()), &vote.id, &vote.signature) + (finality_grandpa::Message::Prevote(vote.prevote.clone()), &vote.id, &vote.signature) }), msg.round_number, set_id.0, @@ -782,7 +782,7 @@ fn check_catch_up( // check signatures on all contained precommits. let _ = check_signatures::( msg.precommits.iter().map(|vote| { - (grandpa::Message::Precommit(vote.precommit.clone()), &vote.id, &vote.signature) + (finality_grandpa::Message::Precommit(vote.precommit.clone()), &vote.id, &vote.signature) }), msg.round_number, set_id.0, diff --git a/substrate/client/finality-grandpa/src/communication/periodic.rs b/substrate/client/finality-grandpa/src/communication/periodic.rs index 3f9cc0dd8e..318c84c22c 100644 --- a/substrate/client/finality-grandpa/src/communication/periodic.rs +++ b/substrate/client/finality-grandpa/src/communication/periodic.rs @@ -18,15 +18,15 @@ use std::time::{Instant, Duration}; -use codec::Encode; +use parity_scale_codec::Encode; use futures::prelude::*; use futures::sync::mpsc; use futures_timer::Delay; use futures03::future::{FutureExt as _, TryFutureExt as _}; use log::{debug, warn}; -use network::PeerId; -use network_gossip::GossipEngine; +use sc_network::PeerId; +use sc_network_gossip::GossipEngine; use sp_runtime::traits::{NumberFor, Block as BlockT}; use super::gossip::{NeighborPacket, GossipMessage}; @@ -47,7 +47,7 @@ impl NeighborPacketSender { /// Send a neighbor packet for the background worker to gossip to peers. pub fn send( &self, - who: Vec, + who: Vec, neighbor_packet: NeighborPacket>, ) { if let Err(err) = self.0.unbounded_send((who, neighbor_packet)) { diff --git a/substrate/client/finality-grandpa/src/communication/tests.rs b/substrate/client/finality-grandpa/src/communication/tests.rs index 6e80291c40..4c0223402f 100644 --- a/substrate/client/finality-grandpa/src/communication/tests.rs +++ b/substrate/client/finality-grandpa/src/communication/tests.rs @@ -18,24 +18,24 @@ use futures::sync::mpsc; use futures::prelude::*; -use network::{Event as NetworkEvent, PeerId, config::Roles}; +use sc_network::{Event as NetworkEvent, PeerId, config::Roles}; use sc_network_test::{Block, Hash}; -use network_gossip::Validator; +use sc_network_gossip::Validator; use tokio::runtime::current_thread; use std::sync::Arc; -use keyring::Ed25519Keyring; -use codec::Encode; +use sp_keyring::Ed25519Keyring; +use parity_scale_codec::Encode; use sp_runtime::{ConsensusEngineId, traits::NumberFor}; use std::{pin::Pin, task::{Context, Poll}}; use crate::environment::SharedVoterSetState; -use fg_primitives::{AuthorityList, GRANDPA_ENGINE_ID}; +use sp_finality_grandpa::{AuthorityList, GRANDPA_ENGINE_ID}; use super::gossip::{self, GossipValidator}; use super::{AuthorityId, VoterSet, Round, SetId}; enum Event { EventStream(mpsc::UnboundedSender), - WriteNotification(network::PeerId, Vec), - Report(network::PeerId, network::ReputationChange), + WriteNotification(sc_network::PeerId, Vec), + Report(sc_network::PeerId, sc_network::ReputationChange), Announce(Hash), } @@ -44,7 +44,7 @@ struct TestNetwork { sender: mpsc::UnboundedSender, } -impl network_gossip::Network for TestNetwork { +impl sc_network_gossip::Network for TestNetwork { fn event_stream(&self) -> Box + Send> { let (tx, rx) = mpsc::unbounded(); @@ -52,7 +52,7 @@ impl network_gossip::Network for TestNetwork { Box::new(rx) } - fn report_peer(&self, who: network::PeerId, cost_benefit: network::ReputationChange) { + fn report_peer(&self, who: sc_network::PeerId, cost_benefit: sc_network::ReputationChange) { let _ = self.sender.unbounded_send(Event::Report(who, cost_benefit)); } @@ -70,19 +70,19 @@ impl network_gossip::Network for TestNetwork { fn set_sync_fork_request( &self, - _peers: Vec, + _peers: Vec, _hash: Hash, _number: NumberFor, ) {} } -impl network_gossip::ValidatorContext for TestNetwork { +impl sc_network_gossip::ValidatorContext for TestNetwork { fn broadcast_topic(&mut self, _: Hash, _: bool) { } fn broadcast_message(&mut self, _: Hash, _: Vec, _: bool) { } - fn send_message(&mut self, who: &network::PeerId, data: Vec) { - >::write_notification( + fn send_message(&mut self, who: &sc_network::PeerId, data: Vec) { + >::write_notification( self, who.clone(), GRANDPA_ENGINE_ID, @@ -90,7 +90,7 @@ impl network_gossip::ValidatorContext for TestNetwork { ); } - fn send_topic(&mut self, _: &network::PeerId, _: Hash, _: bool) { } + fn send_topic(&mut self, _: &sc_network::PeerId, _: Hash, _: bool) { } } struct Tester { @@ -132,8 +132,8 @@ fn config() -> crate::Config { fn voter_set_state() -> SharedVoterSetState { use crate::authorities::AuthoritySet; use crate::environment::VoterSetState; - use grandpa::round::State as RoundState; - use primitives::H256; + use finality_grandpa::round::State as RoundState; + use sp_core::H256; let state = RoundState::genesis((H256::zero(), 0)); let base = state.prevote_ghost.unwrap(); @@ -193,11 +193,11 @@ fn make_ids(keys: &[Ed25519Keyring]) -> AuthorityList { struct NoopContext; -impl network_gossip::ValidatorContext for NoopContext { +impl sc_network_gossip::ValidatorContext for NoopContext { fn broadcast_topic(&mut self, _: Hash, _: bool) { } fn broadcast_message(&mut self, _: Hash, _: Vec, _: bool) { } - fn send_message(&mut self, _: &network::PeerId, _: Vec) { } - fn send_topic(&mut self, _: &network::PeerId, _: Hash, _: bool) { } + fn send_message(&mut self, _: &sc_network::PeerId, _: Vec) { } + fn send_topic(&mut self, _: &sc_network::PeerId, _: Hash, _: bool) { } } #[test] @@ -213,9 +213,9 @@ fn good_commit_leads_to_relay() { let target_hash: Hash = [1; 32].into(); let target_number = 500; - let precommit = grandpa::Precommit { target_hash: target_hash.clone(), target_number }; + let precommit = finality_grandpa::Precommit { target_hash: target_hash.clone(), target_number }; let payload = super::localized_payload( - round, set_id, &grandpa::Message::Precommit(precommit.clone()) + round, set_id, &finality_grandpa::Message::Precommit(precommit.clone()) ); let mut precommits = Vec::new(); @@ -224,11 +224,11 @@ fn good_commit_leads_to_relay() { for (i, key) in private.iter().enumerate() { precommits.push(precommit.clone()); - let signature = fg_primitives::AuthoritySignature::from(key.sign(&payload[..])); + let signature = sp_finality_grandpa::AuthoritySignature::from(key.sign(&payload[..])); auth_data.push((signature, public[i].0.clone())) } - grandpa::CompactCommit { + finality_grandpa::CompactCommit { target_hash, target_number, precommits, @@ -242,14 +242,14 @@ fn good_commit_leads_to_relay() { message: commit, }).encode(); - let id = network::PeerId::random(); + let id = sc_network::PeerId::random(); let global_topic = super::global_topic::(set_id); let threads_pool = futures03::executor::ThreadPool::new().unwrap(); let test = make_test_network(&threads_pool).0 .and_then(move |tester| { // register a peer. - tester.gossip_validator.new_peer(&mut NoopContext, &id, network::config::Roles::FULL); + tester.gossip_validator.new_peer(&mut NoopContext, &id, sc_network::config::Roles::FULL); Ok((tester, id)) }) .and_then(move |(tester, id)| { @@ -291,8 +291,8 @@ fn good_commit_leads_to_relay() { let handle_commit = commits_in.into_future() .map(|(item, _)| { match item.unwrap() { - grandpa::voter::CommunicationIn::Commit(_, _, mut callback) => { - callback.run(grandpa::voter::CommitProcessingOutcome::good()); + finality_grandpa::voter::CommunicationIn::Commit(_, _, mut callback) => { + callback.run(finality_grandpa::voter::CommitProcessingOutcome::good()); }, _ => panic!("commit expected"), } @@ -330,9 +330,9 @@ fn bad_commit_leads_to_report() { let target_hash: Hash = [1; 32].into(); let target_number = 500; - let precommit = grandpa::Precommit { target_hash: target_hash.clone(), target_number }; + let precommit = finality_grandpa::Precommit { target_hash: target_hash.clone(), target_number }; let payload = super::localized_payload( - round, set_id, &grandpa::Message::Precommit(precommit.clone()) + round, set_id, &finality_grandpa::Message::Precommit(precommit.clone()) ); let mut precommits = Vec::new(); @@ -341,11 +341,11 @@ fn bad_commit_leads_to_report() { for (i, key) in private.iter().enumerate() { precommits.push(precommit.clone()); - let signature = fg_primitives::AuthoritySignature::from(key.sign(&payload[..])); + let signature = sp_finality_grandpa::AuthoritySignature::from(key.sign(&payload[..])); auth_data.push((signature, public[i].0.clone())) } - grandpa::CompactCommit { + finality_grandpa::CompactCommit { target_hash, target_number, precommits, @@ -359,14 +359,14 @@ fn bad_commit_leads_to_report() { message: commit, }).encode(); - let id = network::PeerId::random(); + let id = sc_network::PeerId::random(); let global_topic = super::global_topic::(set_id); let threads_pool = futures03::executor::ThreadPool::new().unwrap(); let test = make_test_network(&threads_pool).0 .and_then(move |tester| { // register a peer. - tester.gossip_validator.new_peer(&mut NoopContext, &id, network::config::Roles::FULL); + tester.gossip_validator.new_peer(&mut NoopContext, &id, sc_network::config::Roles::FULL); Ok((tester, id)) }) .and_then(move |(tester, id)| { @@ -408,8 +408,8 @@ fn bad_commit_leads_to_report() { let handle_commit = commits_in.into_future() .map(|(item, _)| { match item.unwrap() { - grandpa::voter::CommunicationIn::Commit(_, _, mut callback) => { - callback.run(grandpa::voter::CommitProcessingOutcome::bad()); + finality_grandpa::voter::CommunicationIn::Commit(_, _, mut callback) => { + callback.run(finality_grandpa::voter::CommitProcessingOutcome::bad()); }, _ => panic!("commit expected"), } @@ -435,14 +435,14 @@ fn bad_commit_leads_to_report() { #[test] fn peer_with_higher_view_leads_to_catch_up_request() { - let id = network::PeerId::random(); + let id = sc_network::PeerId::random(); let threads_pool = futures03::executor::ThreadPool::new().unwrap(); let (tester, mut net) = make_test_network(&threads_pool); let test = tester .and_then(move |tester| { // register a peer with authority role. - tester.gossip_validator.new_peer(&mut NoopContext, &id, network::config::Roles::AUTHORITY); + tester.gossip_validator.new_peer(&mut NoopContext, &id, sc_network::config::Roles::AUTHORITY); Ok((tester, id)) }) .and_then(move |(tester, id)| { @@ -459,7 +459,7 @@ fn peer_with_higher_view_leads_to_catch_up_request() { // neighbor packets are always discard match result { - network_gossip::ValidationResult::Discard => {}, + sc_network_gossip::ValidationResult::Discard => {}, _ => panic!("wrong expected outcome from neighbor validation"), } diff --git a/substrate/client/finality-grandpa/src/consensus_changes.rs b/substrate/client/finality-grandpa/src/consensus_changes.rs index 5f7828f02b..c89335e34c 100644 --- a/substrate/client/finality-grandpa/src/consensus_changes.rs +++ b/substrate/client/finality-grandpa/src/consensus_changes.rs @@ -15,7 +15,7 @@ // along with Substrate. If not, see . use std::sync::Arc; -use codec::{Encode, Decode}; +use parity_scale_codec::{Encode, Decode}; /// Consensus-related data changes tracker. #[derive(Clone, Debug, Encode, Decode)] diff --git a/substrate/client/finality-grandpa/src/environment.rs b/substrate/client/finality-grandpa/src/environment.rs index a252668481..998e63b6b5 100644 --- a/substrate/client/finality-grandpa/src/environment.rs +++ b/substrate/client/finality-grandpa/src/environment.rs @@ -20,28 +20,28 @@ use std::sync::Arc; use std::time::Duration; use log::{debug, warn, info}; -use codec::{Decode, Encode}; +use parity_scale_codec::{Decode, Encode}; use futures::prelude::*; use futures03::future::{FutureExt as _, TryFutureExt as _}; use futures_timer::Delay; use parking_lot::RwLock; use sp_blockchain::{HeaderBackend, Error as ClientError}; -use client_api::{ +use sc_client_api::{ BlockchainEvents, backend::{Backend}, Finalizer, call_executor::CallExecutor, utils::is_descendent_of, }; -use client::{ +use sc_client::{ apply_aux, Client, }; -use grandpa::{ +use finality_grandpa::{ BlockNumberOps, Equivocation, Error as GrandpaError, round::State as RoundState, voter, voter_set::VoterSet, }; -use primitives::{Blake2Hasher, H256, Pair}; +use sp_core::{Blake2Hasher, H256, Pair}; use sp_runtime::generic::BlockId; use sp_runtime::traits::{ Block as BlockT, Header as HeaderT, NumberFor, One, Zero, @@ -53,16 +53,16 @@ use crate::{ PrimaryPropose, SignedMessage, NewAuthoritySet, VoterCommand, }; -use consensus_common::SelectChain; +use sp_consensus::SelectChain; use crate::authorities::{AuthoritySet, SharedAuthoritySet}; use crate::consensus_changes::SharedConsensusChanges; use crate::justification::GrandpaJustification; use crate::until_imported::UntilVoteTargetImported; use crate::voting_rule::VotingRule; -use fg_primitives::{AuthorityId, AuthoritySignature, SetId, RoundNumber}; +use sp_finality_grandpa::{AuthorityId, AuthoritySignature, SetId, RoundNumber}; -type HistoricalVotes = grandpa::HistoricalVotes< +type HistoricalVotes = finality_grandpa::HistoricalVotes< ::Hash, NumberFor, AuthoritySignature, @@ -105,10 +105,10 @@ impl Encode for CompletedRounds { } } -impl codec::EncodeLike for CompletedRounds {} +impl parity_scale_codec::EncodeLike for CompletedRounds {} impl Decode for CompletedRounds { - fn decode(value: &mut I) -> Result { + fn decode(value: &mut I) -> Result { <(Vec>, SetId, Vec)>::decode(value) .map(|(rounds, set_id, voters)| CompletedRounds { rounds: rounds.into(), @@ -406,7 +406,7 @@ impl Environment { } impl, B, E, RA, SC, VR> - grandpa::Chain> + finality_grandpa::Chain> for Environment where Block: 'static, @@ -572,11 +572,11 @@ where // regular round message streams type In = Box, Self::Signature, Self::Id>, + Item = ::finality_grandpa::SignedMessage, Self::Signature, Self::Id>, Error = Self::Error, > + Send>; type Out = Box>, + SinkItem = ::finality_grandpa::Message>, SinkError = Self::Error, > + Send>; @@ -906,7 +906,7 @@ where fn prevote_equivocation( &self, _round: RoundNumber, - equivocation: ::grandpa::Equivocation, Self::Signature> + equivocation: ::finality_grandpa::Equivocation, Self::Signature> ) { warn!(target: "afg", "Detected prevote equivocation in the finality worker: {:?}", equivocation); // nothing yet; this could craft misbehavior reports of some kind. diff --git a/substrate/client/finality-grandpa/src/finality_proof.rs b/substrate/client/finality-grandpa/src/finality_proof.rs index 0420320e0b..1e17845471 100644 --- a/substrate/client/finality-grandpa/src/finality_proof.rs +++ b/substrate/client/finality-grandpa/src/finality_proof.rs @@ -39,20 +39,20 @@ use std::sync::Arc; use log::{trace, warn}; use sp_blockchain::{Backend as BlockchainBackend, Error as ClientError, Result as ClientResult}; -use client_api::{ +use sc_client_api::{ backend::Backend, CallExecutor, StorageProof, light::{FetchChecker, RemoteReadRequest}, }; -use client::Client; -use codec::{Encode, Decode}; -use grandpa::BlockNumberOps; +use sc_client::Client; +use parity_scale_codec::{Encode, Decode}; +use finality_grandpa::BlockNumberOps; use sp_runtime::{ Justification, generic::BlockId, traits::{NumberFor, Block as BlockT, Header as HeaderT, One}, }; -use primitives::{H256, Blake2Hasher, storage::StorageKey}; +use sp_core::{H256, Blake2Hasher, storage::StorageKey}; use sc_telemetry::{telemetry, CONSENSUS_INFO}; -use fg_primitives::{AuthorityId, AuthorityList, VersionedAuthorityList, GRANDPA_AUTHORITIES_KEY}; +use sp_finality_grandpa::{AuthorityId, AuthorityList, VersionedAuthorityList, GRANDPA_AUTHORITIES_KEY}; use crate::justification::GrandpaJustification; @@ -154,7 +154,7 @@ impl> FinalityProofProvider } } -impl network::FinalityProofProvider for FinalityProofProvider +impl sc_network::FinalityProofProvider for FinalityProofProvider where Block: BlockT, NumberFor: BlockNumberOps, @@ -580,11 +580,11 @@ impl> ProvableJustification for GrandpaJ #[cfg(test)] pub(crate) mod tests { - use test_client::runtime::{Block, Header, H256}; - use client_api::NewBlockState; - use test_client::client::in_mem::Blockchain as InMemoryBlockchain; + use substrate_test_runtime_client::runtime::{Block, Header, H256}; + use sc_client_api::NewBlockState; + use substrate_test_runtime_client::sc_client::in_mem::Blockchain as InMemoryBlockchain; use super::*; - use primitives::crypto::Public; + use sp_core::crypto::Public; type FinalityProof = super::FinalityProof

; diff --git a/substrate/client/finality-grandpa/src/import.rs b/substrate/client/finality-grandpa/src/import.rs index e7cfa46d4a..2132d6f36d 100644 --- a/substrate/client/finality-grandpa/src/import.rs +++ b/substrate/client/finality-grandpa/src/import.rs @@ -17,25 +17,25 @@ use std::{sync::Arc, collections::HashMap}; use log::{debug, trace, info}; -use codec::Encode; +use parity_scale_codec::Encode; use futures::sync::mpsc; use parking_lot::RwLockWriteGuard; use sp_blockchain::{HeaderBackend, BlockStatus, well_known_cache_keys}; -use client_api::{backend::Backend, CallExecutor, utils::is_descendent_of}; -use client::Client; -use consensus_common::{ +use sc_client_api::{backend::Backend, CallExecutor, utils::is_descendent_of}; +use sc_client::Client; +use sp_consensus::{ BlockImport, Error as ConsensusError, BlockCheckParams, BlockImportParams, ImportResult, JustificationImport, SelectChain, }; -use fg_primitives::{GRANDPA_ENGINE_ID, ScheduledChange, ConsensusLog}; +use sp_finality_grandpa::{GRANDPA_ENGINE_ID, ScheduledChange, ConsensusLog}; use sp_runtime::Justification; use sp_runtime::generic::{BlockId, OpaqueDigestItemId}; use sp_runtime::traits::{ Block as BlockT, DigestFor, Header as HeaderT, NumberFor, Zero, }; -use primitives::{H256, Blake2Hasher}; +use sp_core::{H256, Blake2Hasher}; use crate::{Error, CommandOrError, NewAuthoritySet, VoterCommand}; use crate::authorities::{AuthoritySet, SharedAuthoritySet, DelayKind, PendingChange}; @@ -76,7 +76,7 @@ impl, RA, SC: Clone> Clone for impl, RA, SC> JustificationImport for GrandpaBlockImport where - NumberFor: grandpa::BlockNumberOps, + NumberFor: finality_grandpa::BlockNumberOps, B: Backend + 'static, E: CallExecutor + 'static + Clone + Send + Sync, DigestFor: Encode, @@ -204,7 +204,7 @@ fn find_forced_change(header: &B::Header) impl, RA, SC> GrandpaBlockImport where - NumberFor: grandpa::BlockNumberOps, + NumberFor: finality_grandpa::BlockNumberOps, B: Backend + 'static, E: CallExecutor + 'static + Clone + Send + Sync, DigestFor: Encode, @@ -381,7 +381,7 @@ where impl, RA, SC> BlockImport for GrandpaBlockImport where - NumberFor: grandpa::BlockNumberOps, + NumberFor: finality_grandpa::BlockNumberOps, B: Backend + 'static, E: CallExecutor + 'static + Clone + Send + Sync, DigestFor: Encode, @@ -532,7 +532,7 @@ impl, RA, SC> impl, RA, SC> GrandpaBlockImport where - NumberFor: grandpa::BlockNumberOps, + NumberFor: finality_grandpa::BlockNumberOps, B: Backend + 'static, E: CallExecutor + 'static + Clone + Send + Sync, RA: Send + Sync, diff --git a/substrate/client/finality-grandpa/src/justification.rs b/substrate/client/finality-grandpa/src/justification.rs index 2851fa2132..d7650a39f8 100644 --- a/substrate/client/finality-grandpa/src/justification.rs +++ b/substrate/client/finality-grandpa/src/justification.rs @@ -16,16 +16,16 @@ use std::collections::{HashMap, HashSet}; -use client::Client; -use client_api::{CallExecutor, backend::Backend}; +use sc_client::Client; +use sc_client_api::{CallExecutor, backend::Backend}; use sp_blockchain::Error as ClientError; -use codec::{Encode, Decode}; -use grandpa::voter_set::VoterSet; -use grandpa::{Error as GrandpaError}; +use parity_scale_codec::{Encode, Decode}; +use finality_grandpa::voter_set::VoterSet; +use finality_grandpa::{Error as GrandpaError}; use sp_runtime::generic::BlockId; use sp_runtime::traits::{NumberFor, Block as BlockT, Header as HeaderT}; -use primitives::{H256, Blake2Hasher}; -use fg_primitives::AuthorityId; +use sp_core::{H256, Blake2Hasher}; +use sp_finality_grandpa::AuthorityId; use crate::{Commit, Error}; use crate::communication; @@ -98,7 +98,7 @@ impl> GrandpaJustification { set_id: u64, voters: &VoterSet, ) -> Result, ClientError> where - NumberFor: grandpa::BlockNumberOps, + NumberFor: finality_grandpa::BlockNumberOps, { let justification = GrandpaJustification::::decode(&mut &*encoded) @@ -115,13 +115,13 @@ impl> GrandpaJustification { /// Validate the commit and the votes' ancestry proofs. pub(crate) fn verify(&self, set_id: u64, voters: &VoterSet) -> Result<(), ClientError> where - NumberFor: grandpa::BlockNumberOps, + NumberFor: finality_grandpa::BlockNumberOps, { - use grandpa::Chain; + use finality_grandpa::Chain; let ancestry_chain = AncestryChain::::new(&self.votes_ancestries); - match grandpa::validate_commit( + match finality_grandpa::validate_commit( &self.commit, voters, &ancestry_chain, @@ -136,7 +136,7 @@ impl> GrandpaJustification { let mut visited_hashes = HashSet::new(); for signed in self.commit.precommits.iter() { if let Err(_) = communication::check_message_sig::( - &grandpa::Message::Precommit(signed.precommit.clone()), + &finality_grandpa::Message::Precommit(signed.precommit.clone()), &signed.id, &signed.signature, self.round, @@ -179,7 +179,7 @@ impl> GrandpaJustification { } } -/// A utility trait implementing `grandpa::Chain` using a given set of headers. +/// A utility trait implementing `finality_grandpa::Chain` using a given set of headers. /// This is useful when validating commits, using the given set of headers to /// verify a valid ancestry route to the target commit block. struct AncestryChain { @@ -198,8 +198,8 @@ impl AncestryChain { } } -impl grandpa::Chain> for AncestryChain where - NumberFor: grandpa::BlockNumberOps +impl finality_grandpa::Chain> for AncestryChain where + NumberFor: finality_grandpa::BlockNumberOps { fn ancestry(&self, base: Block::Hash, block: Block::Hash) -> Result, GrandpaError> { let mut route = Vec::new(); diff --git a/substrate/client/finality-grandpa/src/lib.rs b/substrate/client/finality-grandpa/src/lib.rs index 82c0400612..7d3b26a632 100644 --- a/substrate/client/finality-grandpa/src/lib.rs +++ b/substrate/client/finality-grandpa/src/lib.rs @@ -55,23 +55,23 @@ use futures::prelude::*; use log::{debug, error, info}; use futures::sync::mpsc; -use client_api::{BlockchainEvents, CallExecutor, backend::Backend, ExecutionStrategy}; +use sc_client_api::{BlockchainEvents, CallExecutor, backend::Backend, ExecutionStrategy}; use sp_blockchain::{HeaderBackend, Error as ClientError}; -use client::Client; -use codec::{Decode, Encode}; +use sc_client::Client; +use parity_scale_codec::{Decode, Encode}; use sp_runtime::generic::BlockId; use sp_runtime::traits::{NumberFor, Block as BlockT, DigestFor, Zero}; -use keystore::KeyStorePtr; -use inherents::InherentDataProviders; -use consensus_common::SelectChain; -use primitives::{H256, Blake2Hasher, Pair}; +use sc_keystore::KeyStorePtr; +use sp_inherents::InherentDataProviders; +use sp_consensus::SelectChain; +use sp_core::{H256, Blake2Hasher, Pair}; use sc_telemetry::{telemetry, CONSENSUS_INFO, CONSENSUS_DEBUG, CONSENSUS_WARN}; use serde_json; use sp_finality_tracker; -use grandpa::Error as GrandpaError; -use grandpa::{voter, BlockNumberOps, voter_set::VoterSet}; +use finality_grandpa::Error as GrandpaError; +use finality_grandpa::{voter, BlockNumberOps, voter_set::VoterSet}; use std::{fmt, io}; use std::sync::Arc; @@ -90,7 +90,7 @@ mod observer; mod until_imported; mod voting_rule; -pub use network_gossip::Network; +pub use sc_network_gossip::Network; pub use finality_proof::FinalityProofProvider; pub use justification::GrandpaJustification; pub use light_import::light_block_import; @@ -104,18 +104,18 @@ use environment::{Environment, VoterSetState}; use import::GrandpaBlockImport; use until_imported::UntilGlobalMessageBlocksImported; use communication::NetworkBridge; -use fg_primitives::{AuthorityList, AuthorityPair, AuthoritySignature, SetId}; +use sp_finality_grandpa::{AuthorityList, AuthorityPair, AuthoritySignature, SetId}; // Re-export these two because it's just so damn convenient. -pub use fg_primitives::{AuthorityId, ScheduledChange}; +pub use sp_finality_grandpa::{AuthorityId, ScheduledChange}; #[cfg(test)] mod tests; /// A GRANDPA message for a substrate chain. -pub type Message = grandpa::Message<::Hash, NumberFor>; +pub type Message = finality_grandpa::Message<::Hash, NumberFor>; /// A signed message. -pub type SignedMessage = grandpa::SignedMessage< +pub type SignedMessage = finality_grandpa::SignedMessage< ::Hash, NumberFor, AuthoritySignature, @@ -123,27 +123,27 @@ pub type SignedMessage = grandpa::SignedMessage< >; /// A primary propose message for this chain's block type. -pub type PrimaryPropose = grandpa::PrimaryPropose<::Hash, NumberFor>; +pub type PrimaryPropose = finality_grandpa::PrimaryPropose<::Hash, NumberFor>; /// A prevote message for this chain's block type. -pub type Prevote = grandpa::Prevote<::Hash, NumberFor>; +pub type Prevote = finality_grandpa::Prevote<::Hash, NumberFor>; /// A precommit message for this chain's block type. -pub type Precommit = grandpa::Precommit<::Hash, NumberFor>; +pub type Precommit = finality_grandpa::Precommit<::Hash, NumberFor>; /// A catch up message for this chain's block type. -pub type CatchUp = grandpa::CatchUp< +pub type CatchUp = finality_grandpa::CatchUp< ::Hash, NumberFor, AuthoritySignature, AuthorityId, >; /// A commit message for this chain's block type. -pub type Commit = grandpa::Commit< +pub type Commit = finality_grandpa::Commit< ::Hash, NumberFor, AuthoritySignature, AuthorityId, >; /// A compact commit message for this chain's block type. -pub type CompactCommit = grandpa::CompactCommit< +pub type CompactCommit = finality_grandpa::CompactCommit< ::Hash, NumberFor, AuthoritySignature, @@ -152,7 +152,7 @@ pub type CompactCommit = grandpa::CompactCommit< /// A global communication input stream for commits and catch up messages. Not /// exposed publicly, used internally to simplify types in the communication /// layer. -type CommunicationIn = grandpa::voter::CommunicationIn< +type CommunicationIn = finality_grandpa::voter::CommunicationIn< ::Hash, NumberFor, AuthoritySignature, @@ -162,7 +162,7 @@ type CommunicationIn = grandpa::voter::CommunicationIn< /// Global communication input stream for commits and catch up messages, with /// the hash type not being derived from the block, useful for forcing the hash /// to some type (e.g. `H256`) when the compiler can't do the inference. -type CommunicationInH = grandpa::voter::CommunicationIn< +type CommunicationInH = finality_grandpa::voter::CommunicationIn< H, NumberFor, AuthoritySignature, @@ -171,7 +171,7 @@ type CommunicationInH = grandpa::voter::CommunicationIn< /// A global communication sink for commits. Not exposed publicly, used /// internally to simplify types in the communication layer. -type CommunicationOut = grandpa::voter::CommunicationOut< +type CommunicationOut = finality_grandpa::voter::CommunicationOut< ::Hash, NumberFor, AuthoritySignature, @@ -181,7 +181,7 @@ type CommunicationOut = grandpa::voter::CommunicationOut< /// Global communication sink for commits with the hash type not being derived /// from the block, useful for forcing the hash to some type (e.g. `H256`) when /// the compiler can't do the inference. -type CommunicationOutH = grandpa::voter::CommunicationOut< +type CommunicationOutH = finality_grandpa::voter::CommunicationOut< H, NumberFor, AuthoritySignature, @@ -207,7 +207,7 @@ pub struct Config { /// Some local identifier of the voter. pub name: Option, /// The keystore that manages the keys of this node. - pub keystore: Option, + pub keystore: Option, } impl Config { @@ -273,13 +273,13 @@ pub(crate) trait BlockSyncRequester { /// If the given vector of peers is empty then the underlying implementation /// should make a best effort to fetch the block from any peers it is /// connected to (NOTE: this assumption will change in the future #3629). - fn set_sync_fork_request(&self, peers: Vec, hash: Block::Hash, number: NumberFor); + fn set_sync_fork_request(&self, peers: Vec, hash: Block::Hash, number: NumberFor); } impl BlockSyncRequester for NetworkBridge where Block: BlockT, { - fn set_sync_fork_request(&self, peers: Vec, hash: Block::Hash, number: NumberFor) { + fn set_sync_fork_request(&self, peers: Vec, hash: Block::Hash, number: NumberFor) { NetworkBridge::set_sync_fork_request(self, peers, hash, number) } } @@ -332,8 +332,8 @@ impl From for CommandOrError { } } -impl From for CommandOrError { - fn from(e: grandpa::Error) -> Self { +impl From for CommandOrError { + fn from(e: finality_grandpa::Error) -> Self { CommandOrError::Error(Error::from(e)) } } @@ -496,7 +496,7 @@ fn global_communication, B, E, RA>( fn register_finality_tracker_inherent_data_provider, RA>( client: Arc>, inherent_data_providers: &InherentDataProviders, -) -> Result<(), consensus_common::Error> where +) -> Result<(), sp_consensus::Error> where B: Backend + 'static, E: CallExecutor + Send + Sync + 'static, RA: Send + Sync + 'static, @@ -514,7 +514,7 @@ fn register_finality_tracker_inherent_data_provider, RA, N>( client: Arc>, inherent_data_providers: &InherentDataProviders, network: N, -) -> Result<(), consensus_common::Error> where +) -> Result<(), sp_consensus::Error> where B: Backend + 'static, E: CallExecutor + Send + Sync + 'static, RA: Send + Sync + 'static, diff --git a/substrate/client/finality-grandpa/src/light_import.rs b/substrate/client/finality-grandpa/src/light_import.rs index 344c6110cc..8907ac8226 100644 --- a/substrate/client/finality-grandpa/src/light_import.rs +++ b/substrate/client/finality-grandpa/src/light_import.rs @@ -18,21 +18,21 @@ use std::collections::HashMap; use std::sync::Arc; use log::{info, trace, warn}; use parking_lot::RwLock; -use client::Client; -use client_api::{CallExecutor, backend::{AuxStore, Backend, Finalizer}}; +use sc_client::Client; +use sc_client_api::{CallExecutor, backend::{AuxStore, Backend, Finalizer}}; use sp_blockchain::{HeaderBackend, Error as ClientError, well_known_cache_keys}; -use codec::{Encode, Decode}; -use consensus_common::{ +use parity_scale_codec::{Encode, Decode}; +use sp_consensus::{ import_queue::Verifier, BlockOrigin, BlockImport, FinalityProofImport, BlockImportParams, ImportResult, ImportedAux, BlockCheckParams, Error as ConsensusError, }; -use network::config::{BoxFinalityProofRequestBuilder, FinalityProofRequestBuilder}; +use sc_network::config::{BoxFinalityProofRequestBuilder, FinalityProofRequestBuilder}; use sp_runtime::Justification; use sp_runtime::traits::{NumberFor, Block as BlockT, Header as HeaderT, DigestFor}; -use fg_primitives::{self, AuthorityList}; +use sp_finality_grandpa::{self, AuthorityList}; use sp_runtime::generic::BlockId; -use primitives::{H256, Blake2Hasher}; +use sp_core::{H256, Blake2Hasher}; use crate::GenesisAuthoritySetProvider; use crate::aux_schema::load_decode; @@ -120,7 +120,7 @@ impl, RA> GrandpaLightBlockImport, RA> BlockImport for GrandpaLightBlockImport where - NumberFor: grandpa::BlockNumberOps, + NumberFor: finality_grandpa::BlockNumberOps, B: Backend + 'static, E: CallExecutor + 'static + Clone + Send + Sync, DigestFor: Encode, @@ -148,7 +148,7 @@ impl, RA> BlockImport impl, RA> FinalityProofImport for GrandpaLightBlockImport where - NumberFor: grandpa::BlockNumberOps, + NumberFor: finality_grandpa::BlockNumberOps, B: Backend + 'static, E: CallExecutor + 'static + Clone + Send + Sync, DigestFor: Encode, @@ -194,7 +194,7 @@ impl LightAuthoritySet { /// Get a genesis set with given authorities. pub fn genesis(initial: AuthorityList) -> Self { LightAuthoritySet { - set_id: fg_primitives::SetId::default(), + set_id: sp_finality_grandpa::SetId::default(), authorities: initial, } } @@ -242,7 +242,7 @@ fn do_import_block, J>( + BlockImport + Clone, B: Backend + 'static, - NumberFor: grandpa::BlockNumberOps, + NumberFor: finality_grandpa::BlockNumberOps, DigestFor: Encode, J: ProvableJustification, { @@ -306,7 +306,7 @@ fn do_import_finality_proof, J>( + Clone, B: Backend + 'static, DigestFor: Encode, - NumberFor: grandpa::BlockNumberOps, + NumberFor: finality_grandpa::BlockNumberOps, J: ProvableJustification, { let authority_set_id = data.authority_set.set_id(); @@ -369,7 +369,7 @@ fn do_import_justification, J>( + Finalizer + Clone, B: Backend + 'static, - NumberFor: grandpa::BlockNumberOps, + NumberFor: finality_grandpa::BlockNumberOps, J: ProvableJustification, { // with justification, we have two cases @@ -440,7 +440,7 @@ fn do_finalize_block>( + Finalizer + Clone, B: Backend + 'static, - NumberFor: grandpa::BlockNumberOps, + NumberFor: finality_grandpa::BlockNumberOps, { // finalize the block client.finalize_block(BlockId::Hash(hash), Some(justification), true).map_err(|e| { @@ -540,11 +540,11 @@ fn on_post_finalization_error(error: ClientError, value_type: &str) -> Consensus #[cfg(test)] pub mod tests { use super::*; - use consensus_common::ForkChoiceStrategy; - use fg_primitives::AuthorityId; - use primitives::{H256, crypto::Public}; - use test_client::client::in_mem::Blockchain as InMemoryAuxStore; - use test_client::runtime::{Block, Header}; + use sp_consensus::ForkChoiceStrategy; + use sp_finality_grandpa::AuthorityId; + use sp_core::{H256, crypto::Public}; + use substrate_test_runtime_client::sc_client::in_mem::Blockchain as InMemoryAuxStore; + use substrate_test_runtime_client::runtime::{Block, Header}; use crate::tests::TestApi; use crate::finality_proof::tests::TestJustification; @@ -554,7 +554,7 @@ pub mod tests { impl, RA> Clone for NoJustificationsImport where - NumberFor: grandpa::BlockNumberOps, + NumberFor: finality_grandpa::BlockNumberOps, B: Backend + 'static, E: CallExecutor + 'static + Clone + Send + Sync, DigestFor: Encode, @@ -567,7 +567,7 @@ pub mod tests { impl, RA> BlockImport for NoJustificationsImport where - NumberFor: grandpa::BlockNumberOps, + NumberFor: finality_grandpa::BlockNumberOps, B: Backend + 'static, E: CallExecutor + 'static + Clone + Send + Sync, DigestFor: Encode, @@ -594,7 +594,7 @@ pub mod tests { impl, RA> FinalityProofImport for NoJustificationsImport where - NumberFor: grandpa::BlockNumberOps, + NumberFor: finality_grandpa::BlockNumberOps, B: Backend + 'static, E: CallExecutor + 'static + Clone + Send + Sync, DigestFor: Encode, @@ -637,7 +637,7 @@ pub mod tests { new_cache: HashMap>, justification: Option, ) -> ImportResult { - let (client, _backend) = test_client::new_light(); + let (client, _backend) = substrate_test_runtime_client::new_light(); let mut import_data = LightImportData { last_finalized: Default::default(), authority_set: LightAuthoritySet::genesis(vec![(AuthorityId::from_slice(&[1; 32]), 1)]), diff --git a/substrate/client/finality-grandpa/src/observer.rs b/substrate/client/finality-grandpa/src/observer.rs index 4681c12753..350d9d31c0 100644 --- a/substrate/client/finality-grandpa/src/observer.rs +++ b/substrate/client/finality-grandpa/src/observer.rs @@ -19,16 +19,16 @@ use std::sync::Arc; use futures::prelude::*; use futures::{future, sync::mpsc}; -use grandpa::{ +use finality_grandpa::{ BlockNumberOps, Error as GrandpaError, voter, voter_set::VoterSet }; use log::{debug, info, warn}; -use consensus_common::SelectChain; -use client_api::{CallExecutor, backend::Backend}; -use client::Client; +use sp_consensus::SelectChain; +use sc_client_api::{CallExecutor, backend::Backend}; +use sc_client::Client; use sp_runtime::traits::{NumberFor, Block as BlockT}; -use primitives::{H256, Blake2Hasher}; +use sp_core::{H256, Blake2Hasher}; use crate::{ global_communication, CommandOrError, CommunicationIn, Config, environment, @@ -37,11 +37,11 @@ use crate::{ use crate::authorities::SharedAuthoritySet; use crate::communication::NetworkBridge; use crate::consensus_changes::SharedConsensusChanges; -use fg_primitives::AuthorityId; +use sp_finality_grandpa::AuthorityId; struct ObserverChain<'a, Block: BlockT, B, E, RA>(&'a Client); -impl<'a, Block: BlockT, B, E, RA> grandpa::Chain> +impl<'a, Block: BlockT, B, E, RA> finality_grandpa::Chain> for ObserverChain<'a, Block, B, E, RA> where B: Backend, E: CallExecutor, @@ -84,7 +84,7 @@ fn grandpa_observer, RA, S, F>( let observer = commits.fold(last_finalized_number, move |last_finalized_number, global| { let (round, commit, callback) = match global { voter::CommunicationIn::Commit(round, commit, callback) => { - let commit = grandpa::Commit::from(commit); + let commit = finality_grandpa::Commit::from(commit); (round, commit, callback) }, voter::CommunicationIn::CatchUp(..) => { @@ -99,7 +99,7 @@ fn grandpa_observer, RA, S, F>( return future::ok(last_finalized_number); } - let validation_result = match grandpa::validate_commit( + let validation_result = match finality_grandpa::validate_commit( &commit, &voters, &ObserverChain(&*client), @@ -130,14 +130,14 @@ fn grandpa_observer, RA, S, F>( // and that implies that the next round has started. note_round(round + 1); - grandpa::process_commit_validation_result(validation_result, callback); + finality_grandpa::process_commit_validation_result(validation_result, callback); // proceed processing with new finalized block number future::ok(finalized_number) } else { debug!(target: "afg", "Received invalid commit: ({:?}, {:?})", round, commit); - grandpa::process_commit_validation_result(validation_result, callback); + finality_grandpa::process_commit_validation_result(validation_result, callback); // commit is invalid, continue processing commits with the current state future::ok(last_finalized_number) @@ -207,7 +207,7 @@ struct ObserverWork, E, Backend, RA> { client: Arc>, network: NetworkBridge, persistent_data: PersistentData, - keystore: Option, + keystore: Option, voter_commands_rx: mpsc::UnboundedReceiver>>, } @@ -223,7 +223,7 @@ where client: Arc>, network: NetworkBridge, persistent_data: PersistentData, - keystore: Option, + keystore: Option, voter_commands_rx: mpsc::UnboundedReceiver>>, ) -> Self { diff --git a/substrate/client/finality-grandpa/src/tests.rs b/substrate/client/finality-grandpa/src/tests.rs index 68512a9853..7b52aad6e3 100644 --- a/substrate/client/finality-grandpa/src/tests.rs +++ b/substrate/client/finality-grandpa/src/tests.rs @@ -20,26 +20,26 @@ use super::*; use environment::HasVoted; use sc_network_test::{Block, DummySpecialization, Hash, TestNetFactory, Peer, PeersClient}; use sc_network_test::{PassThroughVerifier}; -use network::config::{ProtocolConfig, Roles, BoxFinalityProofRequestBuilder}; +use sc_network::config::{ProtocolConfig, Roles, BoxFinalityProofRequestBuilder}; use parking_lot::Mutex; use futures_timer::Delay; use futures03::{StreamExt as _, TryStreamExt as _}; use tokio::runtime::current_thread; -use keyring::Ed25519Keyring; -use client::LongestChain; +use sp_keyring::Ed25519Keyring; +use sc_client::LongestChain; use sp_blockchain::Result; use sp_api::{Core, RuntimeVersion, ApiExt, StorageProof}; -use test_client::{self, runtime::BlockNumber}; -use consensus_common::{BlockOrigin, ForkChoiceStrategy, ImportedAux, BlockImportParams, ImportResult}; -use consensus_common::import_queue::{BoxBlockImport, BoxJustificationImport, BoxFinalityProofImport}; +use substrate_test_runtime_client::{self, runtime::BlockNumber}; +use sp_consensus::{BlockOrigin, ForkChoiceStrategy, ImportedAux, BlockImportParams, ImportResult}; +use sp_consensus::import_queue::{BoxBlockImport, BoxJustificationImport, BoxFinalityProofImport}; use std::collections::{HashMap, HashSet}; use std::result; -use codec::Decode; +use parity_scale_codec::Decode; use sp_runtime::traits::{ApiRef, ProvideRuntimeApi, Header as HeaderT}; use sp_runtime::generic::{BlockId, DigestItem}; -use primitives::{NativeOrEncoded, ExecutionContext, crypto::Public}; -use fg_primitives::{GRANDPA_ENGINE_ID, AuthorityList, GrandpaApi}; -use state_machine::{backend::InMemory, prove_read, read_proof_check}; +use sp_core::{NativeOrEncoded, ExecutionContext, crypto::Public}; +use sp_finality_grandpa::{GRANDPA_ENGINE_ID, AuthorityList, GrandpaApi}; +use sp_state_machine::{backend::InMemory, prove_read, read_proof_check}; use std::{pin::Pin, task}; use authorities::AuthoritySet; @@ -50,11 +50,11 @@ type PeerData = Mutex< Option< LinkHalf< - test_client::Backend, - test_client::Executor, + substrate_test_runtime_client::Backend, + substrate_test_runtime_client::Executor, Block, - test_client::runtime::RuntimeApi, - LongestChain + substrate_test_runtime_client::runtime::RuntimeApi, + LongestChain > > >; @@ -151,7 +151,7 @@ impl TestNetFactory for GrandpaTestNet { fn make_finality_proof_provider( &self, client: PeersClient - ) -> Option>> { + ) -> Option>> { match client { PeersClient::Full(_, ref backend) => { let authorities_provider = Arc::new(self.test_config.clone()); @@ -328,7 +328,7 @@ fn make_ids(keys: &[Ed25519Keyring]) -> AuthorityList { fn create_keystore(authority: Ed25519Keyring) -> (KeyStorePtr, tempfile::TempDir) { let keystore_path = tempfile::tempdir().expect("Creates keystore path"); - let keystore = keystore::Store::open(keystore_path.path(), None).expect("Creates keystore"); + let keystore = sc_keystore::Store::open(keystore_path.path(), None).expect("Creates keystore"); keystore.write().insert_ephemeral_from_seed::(&authority.to_seed()) .expect("Creates authority key"); @@ -441,7 +441,7 @@ fn run_to_completion( fn add_scheduled_change(block: &mut Block, change: ScheduledChange) { block.header.digest_mut().push(DigestItem::Consensus( GRANDPA_ENGINE_ID, - fg_primitives::ConsensusLog::ScheduledChange(change).encode(), + sp_finality_grandpa::ConsensusLog::ScheduledChange(change).encode(), )); } @@ -452,7 +452,7 @@ fn add_forced_change( ) { block.header.digest_mut().push(DigestItem::Consensus( GRANDPA_ENGINE_ID, - fg_primitives::ConsensusLog::ForcedChange(median_last_finalized, change).encode(), + sp_finality_grandpa::ConsensusLog::ForcedChange(median_last_finalized, change).encode(), )); } @@ -740,7 +740,7 @@ fn justification_is_emitted_when_consensus_data_changes() { let mut net = GrandpaTestNet::new(TestApi::new(make_ids(peers)), 3); // import block#1 WITH consensus data change - let new_authorities = vec![babe_primitives::AuthorityId::from_slice(&[42; 32])]; + let new_authorities = vec![sp_consensus_babe::AuthorityId::from_slice(&[42; 32])]; net.peer(0).push_authorities_change_block(new_authorities); net.block_until_sync(&mut runtime); let net = Arc::new(Mutex::new(net)); @@ -1241,7 +1241,7 @@ fn voter_persists_its_votes() { if state.compare_and_swap(0, 1, Ordering::SeqCst) == 0 { // the first message we receive should be a prevote from alice. let prevote = match signed.message { - grandpa::Message::Prevote(prevote) => prevote, + finality_grandpa::Message::Prevote(prevote) => prevote, _ => panic!("voter should prevote."), }; @@ -1276,19 +1276,19 @@ fn voter_persists_its_votes() { voter_tx.unbounded_send(()).unwrap(); // and we push our own prevote for block 30 - let prevote = grandpa::Prevote { + let prevote = finality_grandpa::Prevote { target_number: 30, target_hash: block_30_hash, }; - round_tx.lock().start_send(grandpa::Message::Prevote(prevote)).unwrap(); + round_tx.lock().start_send(finality_grandpa::Message::Prevote(prevote)).unwrap(); Ok(()) }).map_err(|_| panic!())) } else if state.compare_and_swap(1, 2, Ordering::SeqCst) == 1 { // the next message we receive should be our own prevote let prevote = match signed.message { - grandpa::Message::Prevote(prevote) => prevote, + finality_grandpa::Message::Prevote(prevote) => prevote, _ => panic!("We should receive our own prevote."), }; @@ -1305,7 +1305,7 @@ fn voter_persists_its_votes() { // we then receive a precommit from alice for block 15 // even though we casted a prevote for block 30 let precommit = match signed.message { - grandpa::Message::Precommit(precommit) => precommit, + finality_grandpa::Message::Precommit(precommit) => precommit, _ => panic!("voter should precommit."), }; @@ -1388,7 +1388,7 @@ fn finality_proof_is_fetched_by_light_client_when_consensus_data_changes() { // import block#1 WITH consensus data change. Light client ignores justification // && instead fetches finality proof for block #1 - net.peer(0).push_authorities_change_block(vec![babe_primitives::AuthorityId::from_slice(&[42; 32])]); + net.peer(0).push_authorities_change_block(vec![sp_consensus_babe::AuthorityId::from_slice(&[42; 32])]); let net = Arc::new(Mutex::new(net)); run_to_completion(&mut runtime, &threads_pool, 1, net.clone(), peers); net.lock().block_until_sync(&mut runtime); @@ -1453,7 +1453,7 @@ fn empty_finality_proof_is_returned_to_light_client_when_authority_set_is_differ // normally it will reach light client, but because of the forced change, it will not net.lock().peer(0).push_blocks(8, false); // best is #9 net.lock().peer(0).push_authorities_change_block( - vec![babe_primitives::AuthorityId::from_slice(&[42; 32])] + vec![sp_consensus_babe::AuthorityId::from_slice(&[42; 32])] ); // #10 net.lock().peer(0).push_blocks(1, false); // best is #11 net.lock().block_until_sync(&mut runtime); @@ -1589,7 +1589,7 @@ fn voter_catches_up_to_latest_round_when_behind() { #[test] fn grandpa_environment_respects_voting_rules() { - use grandpa::Chain; + use finality_grandpa::Chain; use sc_network_test::TestClient; let threads_pool = futures03::executor::ThreadPool::new().unwrap(); @@ -1741,22 +1741,22 @@ fn imports_justification_for_regular_blocks_on_import() { let round = 1; let set_id = 0; - let precommit = grandpa::Precommit { + let precommit = finality_grandpa::Precommit { target_hash: block_hash, target_number: *block.header.number(), }; - let msg = grandpa::Message::Precommit(precommit.clone()); + let msg = finality_grandpa::Message::Precommit(precommit.clone()); let encoded = communication::localized_payload(round, set_id, &msg); let signature = peers[0].sign(&encoded[..]).into(); - let precommit = grandpa::SignedPrecommit { + let precommit = finality_grandpa::SignedPrecommit { precommit, signature, id: peers[0].public().into(), }; - let commit = grandpa::Commit { + let commit = finality_grandpa::Commit { target_hash: block_hash, target_number: *block.header.number(), precommits: vec![precommit], diff --git a/substrate/client/finality-grandpa/src/until_imported.rs b/substrate/client/finality-grandpa/src/until_imported.rs index c843547a7b..23ab5c5daa 100644 --- a/substrate/client/finality-grandpa/src/until_imported.rs +++ b/substrate/client/finality-grandpa/src/until_imported.rs @@ -29,19 +29,19 @@ use super::{ }; use log::{debug, warn}; -use client_api::{BlockImportNotification, ImportNotifications}; +use sc_client_api::{BlockImportNotification, ImportNotifications}; use futures::prelude::*; use futures::stream::Fuse; use futures_timer::Delay; use futures03::{StreamExt as _, TryStreamExt as _}; -use grandpa::voter; +use finality_grandpa::voter; use parking_lot::Mutex; use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor}; use std::collections::{HashMap, VecDeque}; use std::sync::{atomic::{AtomicUsize, Ordering}, Arc}; use std::time::{Duration, Instant}; -use fg_primitives::AuthorityId; +use sp_finality_grandpa::AuthorityId; const LOG_PENDING_INTERVAL: Duration = Duration::from_secs(15); @@ -475,13 +475,13 @@ mod tests { use super::*; use crate::{CatchUp, CompactCommit}; use tokio::runtime::current_thread::Runtime; - use test_client::runtime::{Block, Hash, Header}; - use consensus_common::BlockOrigin; - use client_api::BlockImportNotification; + use substrate_test_runtime_client::runtime::{Block, Hash, Header}; + use sp_consensus::BlockOrigin; + use sc_client_api::BlockImportNotification; use futures::future::Either; use futures_timer::Delay; use futures03::{channel::mpsc, future::FutureExt as _, future::TryFutureExt as _}; - use grandpa::Precommit; + use finality_grandpa::Precommit; #[derive(Clone)] struct TestChainState { @@ -543,7 +543,7 @@ mod tests { } impl BlockSyncRequesterT for TestBlockSyncRequester { - fn set_sync_fork_request(&self, _peers: Vec, hash: Hash, number: NumberFor) { + fn set_sync_fork_request(&self, _peers: Vec, hash: Hash, number: NumberFor) { self.requests.lock().push((hash, number)); } } @@ -741,10 +741,10 @@ mod tests { let h3 = make_header(7); let signed_prevote = |header: &Header| { - grandpa::SignedPrevote { + finality_grandpa::SignedPrevote { id: Default::default(), signature: Default::default(), - prevote: grandpa::Prevote { + prevote: finality_grandpa::Prevote { target_hash: header.hash(), target_number: *header.number(), }, @@ -752,10 +752,10 @@ mod tests { }; let signed_precommit = |header: &Header| { - grandpa::SignedPrecommit { + finality_grandpa::SignedPrecommit { id: Default::default(), signature: Default::default(), - precommit: grandpa::Precommit { + precommit: finality_grandpa::Precommit { target_hash: header.hash(), target_number: *header.number(), }, @@ -772,7 +772,7 @@ mod tests { signed_precommit(&h2), ]; - let unknown_catch_up = grandpa::CatchUp { + let unknown_catch_up = finality_grandpa::CatchUp { round_number: 1, prevotes, precommits, @@ -807,10 +807,10 @@ mod tests { let h3 = make_header(7); let signed_prevote = |header: &Header| { - grandpa::SignedPrevote { + finality_grandpa::SignedPrevote { id: Default::default(), signature: Default::default(), - prevote: grandpa::Prevote { + prevote: finality_grandpa::Prevote { target_hash: header.hash(), target_number: *header.number(), }, @@ -818,10 +818,10 @@ mod tests { }; let signed_precommit = |header: &Header| { - grandpa::SignedPrecommit { + finality_grandpa::SignedPrecommit { id: Default::default(), signature: Default::default(), - precommit: grandpa::Precommit { + precommit: finality_grandpa::Precommit { target_hash: header.hash(), target_number: *header.number(), }, @@ -838,7 +838,7 @@ mod tests { signed_precommit(&h2), ]; - let unknown_catch_up = grandpa::CatchUp { + let unknown_catch_up = finality_grandpa::CatchUp { round_number: 1, prevotes, precommits, diff --git a/substrate/client/finality-grandpa/src/voting_rule.rs b/substrate/client/finality-grandpa/src/voting_rule.rs index cfa28d03fe..424677433f 100644 --- a/substrate/client/finality-grandpa/src/voting_rule.rs +++ b/substrate/client/finality-grandpa/src/voting_rule.rs @@ -22,7 +22,7 @@ use std::sync::Arc; -use client_api::blockchain::HeaderBackend; +use sc_client_api::blockchain::HeaderBackend; use sp_runtime::generic::BlockId; use sp_runtime::traits::{Block as BlockT, Header, NumberFor, One, Zero}; diff --git a/substrate/client/keystore/Cargo.toml b/substrate/client/keystore/Cargo.toml index 32bd3d460b..93629956fe 100644 --- a/substrate/client/keystore/Cargo.toml +++ b/substrate/client/keystore/Cargo.toml @@ -6,8 +6,8 @@ edition = "2018" [dependencies] derive_more = "0.99.2" -primitives = { package = "sp-core", path = "../../primitives/core" } -app-crypto = { package = "sp-application-crypto", path = "../../primitives/application-crypto" } +sp-core = { path = "../../primitives/core" } +sp-application-crypto = { path = "../../primitives/application-crypto" } hex = "0.4.0" rand = "0.7.2" serde_json = "1.0.41" diff --git a/substrate/client/keystore/src/lib.rs b/substrate/client/keystore/src/lib.rs index 36cbcb5786..b51ab5a0a0 100644 --- a/substrate/client/keystore/src/lib.rs +++ b/substrate/client/keystore/src/lib.rs @@ -20,11 +20,11 @@ use std::{collections::HashMap, path::PathBuf, fs::{self, File}, io::{self, Write}, sync::Arc}; -use primitives::{ +use sp_core::{ crypto::{KeyTypeId, Pair as PairT, Public, IsWrappedBy, Protected}, traits::BareCryptoStore, }; -use app_crypto::{AppKey, AppPublic, AppPair, ed25519, sr25519}; +use sp_application_crypto::{AppKey, AppPublic, AppPair, ed25519, sr25519}; use parking_lot::RwLock; @@ -318,7 +318,7 @@ impl BareCryptoStore for Store { mod tests { use super::*; use tempfile::TempDir; - use primitives::{testing::{SR25519}, crypto::{Ss58Codec}}; + use sp_core::{testing::{SR25519}, crypto::{Ss58Codec}}; #[test] fn basic_store() { diff --git a/substrate/client/network-gossip/Cargo.toml b/substrate/client/network-gossip/Cargo.toml index b0fcd1fe72..cc521e65f1 100644 --- a/substrate/client/network-gossip/Cargo.toml +++ b/substrate/client/network-gossip/Cargo.toml @@ -13,6 +13,6 @@ futures = { version = "0.3.1", features = ["compat"] } futures-timer = "0.4.0" lru = "0.1.2" libp2p = { version = "0.13.0", default-features = false, features = ["libp2p-websocket"] } -network = { package = "sc-network", path = "../network" } +sc-network = { path = "../network" } parking_lot = "0.9.0" sp-runtime = { path = "../../primitives/runtime" } diff --git a/substrate/client/network-gossip/src/bridge.rs b/substrate/client/network-gossip/src/bridge.rs index 28f0e3f9b4..34d2fa6180 100644 --- a/substrate/client/network-gossip/src/bridge.rs +++ b/substrate/client/network-gossip/src/bridge.rs @@ -17,9 +17,9 @@ use crate::Network; use crate::state_machine::{ConsensusGossip, Validator, TopicNotification}; -use network::Context; -use network::message::generic::ConsensusMessage; -use network::{Event, ReputationChange}; +use sc_network::Context; +use sc_network::message::generic::ConsensusMessage; +use sc_network::{Event, ReputationChange}; use futures::{prelude::*, channel::mpsc, compat::Compat01As03, task::SpawnExt as _}; use libp2p::PeerId; @@ -215,7 +215,7 @@ impl GossipEngine { /// Send addressed message to the given peers. The message is not kept or multicast /// later on. - pub fn send_message(&self, who: Vec, data: Vec) { + pub fn send_message(&self, who: Vec, data: Vec) { let mut inner = self.inner.lock(); let inner = &mut *inner; @@ -244,7 +244,7 @@ impl GossipEngine { /// /// Note: this method isn't strictly related to gossiping and should eventually be moved /// somewhere else. - pub fn set_sync_fork_request(&self, peers: Vec, hash: B::Hash, number: NumberFor) { + pub fn set_sync_fork_request(&self, peers: Vec, hash: B::Hash, number: NumberFor) { self.inner.lock().context_ext.set_sync_fork_request(peers, hash, number); } } @@ -287,7 +287,7 @@ impl> Context for ContextOverService { trait ContextExt { fn announce(&self, block: B::Hash, associated_data: Vec); - fn set_sync_fork_request(&self, peers: Vec, hash: B::Hash, number: NumberFor); + fn set_sync_fork_request(&self, peers: Vec, hash: B::Hash, number: NumberFor); } impl> ContextExt for ContextOverService { @@ -295,7 +295,7 @@ impl> ContextExt for ContextOverService { Network::announce(&self.network, block, associated_data) } - fn set_sync_fork_request(&self, peers: Vec, hash: B::Hash, number: NumberFor) { + fn set_sync_fork_request(&self, peers: Vec, hash: B::Hash, number: NumberFor) { Network::set_sync_fork_request(&self.network, peers, hash, number) } } diff --git a/substrate/client/network-gossip/src/lib.rs b/substrate/client/network-gossip/src/lib.rs index 6decda05c5..5459123c41 100644 --- a/substrate/client/network-gossip/src/lib.rs +++ b/substrate/client/network-gossip/src/lib.rs @@ -59,7 +59,7 @@ pub use self::state_machine::{TopicNotification, MessageIntent}; pub use self::state_machine::{Validator, ValidatorContext, ValidationResult}; pub use self::state_machine::DiscardAll; -use network::{specialization::NetworkSpecialization, Event, ExHashT, NetworkService, PeerId, ReputationChange}; +use sc_network::{specialization::NetworkSpecialization, Event, ExHashT, NetworkService, PeerId, ReputationChange}; use sp_runtime::{traits::{Block as BlockT, NumberFor}, ConsensusEngineId}; use std::sync::Arc; @@ -134,7 +134,7 @@ impl, H: ExHashT> Network for Arc, hash: B::Hash, number: NumberFor) { + fn set_sync_fork_request(&self, peers: Vec, hash: B::Hash, number: NumberFor) { NetworkService::set_sync_fork_request(self, peers, hash, number) } } diff --git a/substrate/client/network-gossip/src/state_machine.rs b/substrate/client/network-gossip/src/state_machine.rs index 48854fc2a8..e2d1ebc8eb 100644 --- a/substrate/client/network-gossip/src/state_machine.rs +++ b/substrate/client/network-gossip/src/state_machine.rs @@ -24,9 +24,9 @@ use lru::LruCache; use libp2p::PeerId; use sp_runtime::traits::{Block as BlockT, Hash, HashFor}; use sp_runtime::ConsensusEngineId; -pub use network::message::generic::{Message, ConsensusMessage}; -use network::Context; -use network::config::Roles; +pub use sc_network::message::generic::{Message, ConsensusMessage}; +use sc_network::Context; +use sc_network::config::Roles; // FIXME: Add additional spam/DoS attack protection: https://github.com/paritytech/substrate/issues/1115 const KNOWN_MESSAGES_CACHE_SIZE: usize = 4096; @@ -34,7 +34,7 @@ const KNOWN_MESSAGES_CACHE_SIZE: usize = 4096; const REBROADCAST_INTERVAL: time::Duration = time::Duration::from_secs(30); mod rep { - use network::ReputationChange as Rep; + use sc_network::ReputationChange as Rep; /// Reputation change when a peer sends us a gossip message that we didn't know about. pub const GOSSIP_SUCCESS: Rep = Rep::new(1 << 4, "Successfull gossip"); /// Reputation change when a peer sends us a gossip message that we already knew about. diff --git a/substrate/client/network/Cargo.toml b/substrate/client/network/Cargo.toml index d7ac7c3b6d..ba20f06e5f 100644 --- a/substrate/client/network/Cargo.toml +++ b/substrate/client/network/Cargo.toml @@ -24,16 +24,16 @@ rustc-hex = "2.0.1" rand = "0.7.2" libp2p = { version = "0.13.0", default-features = false, features = ["libp2p-websocket"] } fork-tree = { path = "../../utils/fork-tree" } -consensus = { package = "sp-consensus", path = "../../primitives/consensus/common" } -client = { package = "sc-client", path = "../" } -client-api = { package = "sc-client-api", path = "../api" } +sp-consensus = { path = "../../primitives/consensus/common" } +sc-client = { path = "../" } +sc-client-api = { path = "../api" } sp-blockchain = { path = "../../primitives/blockchain" } sp-runtime = { path = "../../primitives/runtime" } sp-arithmetic = { path = "../../primitives/arithmetic" } -primitives = { package = "sp-core", path = "../../primitives/core" } -block-builder = { package = "sc-block-builder", path = "../block-builder" } +sp-core = { path = "../../primitives/core" } +sc-block-builder = { path = "../block-builder" } codec = { package = "parity-scale-codec", version = "1.0.0", features = ["derive"] } -peerset = { package = "sc-peerset", path = "../peerset" } +sc-peerset = { path = "../peerset" } serde = { version = "1.0.101", features = ["derive"] } serde_json = "1.0.41" slog = { version = "2.5.2", features = ["nested-values"] } @@ -42,18 +42,18 @@ smallvec = "0.6.10" tokio-io = "0.1.12" tokio = { version = "0.1.22", optional = true } unsigned-varint = { version = "0.2.2", features = ["codec"] } -keyring = { package = "sp-keyring", path = "../../primitives/keyring", optional = true } -test_client = { package = "substrate-test-client", path = "../../test-utils/client", optional = true } -test-client = { package = "substrate-test-runtime-client", path = "../../test-utils/runtime/client", optional = true } +sp-keyring = { path = "../../primitives/keyring", optional = true } +substrate-test-client = { path = "../../test-utils/client", optional = true } +substrate-test-runtime-client = { path = "../../test-utils/runtime/client", optional = true } erased-serde = "0.3.9" void = "1.0.2" zeroize = "1.0.0" -babe-primitives = { package = "sp-consensus-babe", path = "../../primitives/consensus/babe" } +sp-consensus-babe = { path = "../../primitives/consensus/babe" } [dev-dependencies] sp-test-primitives = { path = "../../primitives/test-primitives" } env_logger = "0.7.0" -keyring = { package = "sp-keyring", path = "../../primitives/keyring" } +sp-keyring = { path = "../../primitives/keyring" } quickcheck = "0.9.0" rand = "0.7.2" tempfile = "3.1.0" @@ -61,4 +61,4 @@ tokio = "0.1.22" [features] default = [] -test-helpers = ["keyring", "test-client", "tokio"] +test-helpers = ["sp-keyring", "substrate-test-runtime-client", "tokio"] diff --git a/substrate/client/network/src/behaviour.rs b/substrate/client/network/src/behaviour.rs index ae00c71757..705fa2a27a 100644 --- a/substrate/client/network/src/behaviour.rs +++ b/substrate/client/network/src/behaviour.rs @@ -20,7 +20,6 @@ use crate::{ }; use crate::{ExHashT, specialization::NetworkSpecialization}; use crate::protocol::{CustomMessageOutcome, Protocol}; -use consensus::{BlockOrigin, import_queue::{IncomingBlock, Origin}}; use futures::prelude::*; use libp2p::NetworkBehaviour; use libp2p::core::{Multiaddr, PeerId, PublicKey}; @@ -28,6 +27,7 @@ use libp2p::kad::record; use libp2p::swarm::{NetworkBehaviourAction, NetworkBehaviourEventProcess}; use libp2p::core::{nodes::Substream, muxing::StreamMuxerBox}; use log::{debug, warn}; +use sp_consensus::{BlockOrigin, import_queue::{IncomingBlock, Origin}}; use sp_runtime::{traits::{Block as BlockT, NumberFor}, Justification}; use std::iter; use void; diff --git a/substrate/client/network/src/chain.rs b/substrate/client/network/src/chain.rs index 59fd15bbf1..8231f3bb53 100644 --- a/substrate/client/network/src/chain.rs +++ b/substrate/client/network/src/chain.rs @@ -16,15 +16,15 @@ //! Blockchain access trait -use client::Client as SubstrateClient; +use sc_client::Client as SubstrateClient; use sp_blockchain::Error; -use client_api::{ChangesProof, StorageProof, ClientInfo, CallExecutor}; -use consensus::{BlockImport, BlockStatus, Error as ConsensusError}; +use sc_client_api::{ChangesProof, StorageProof, ClientInfo, CallExecutor}; +use sp_consensus::{BlockImport, BlockStatus, Error as ConsensusError}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; use sp_runtime::generic::{BlockId}; use sp_runtime::Justification; -use primitives::{H256, Blake2Hasher}; -use primitives::storage::{StorageKey, ChildInfo}; +use sp_core::{H256, Blake2Hasher}; +use sp_core::storage::{StorageKey, ChildInfo}; /// Local client abstraction for the network. pub trait Client: Send + Sync { @@ -93,7 +93,7 @@ impl FinalityProofProvider for () { } impl Client for SubstrateClient where - B: client_api::backend::Backend + Send + Sync + 'static, + B: sc_client_api::backend::Backend + Send + Sync + 'static, E: CallExecutor + Send + Sync + 'static, Self: BlockImport, Block: BlockT, diff --git a/substrate/client/network/src/config.rs b/substrate/client/network/src/config.rs index 9a55be7fe9..199b4abd9d 100644 --- a/substrate/client/network/src/config.rs +++ b/substrate/client/network/src/config.rs @@ -26,7 +26,7 @@ use crate::chain::{Client, FinalityProofProvider}; use crate::on_demand_layer::OnDemand; use crate::service::{ExHashT, TransactionPool}; use bitflags::bitflags; -use consensus::{block_validation::BlockAnnounceValidator, import_queue::ImportQueue}; +use sp_consensus::{block_validation::BlockAnnounceValidator, import_queue::ImportQueue}; use sp_runtime::traits::{Block as BlockT}; use libp2p::identity::{Keypair, ed25519}; use libp2p::wasm_ext; diff --git a/substrate/client/network/src/discovery.rs b/substrate/client/network/src/discovery.rs index 2e0a6fe244..0e05ff8b03 100644 --- a/substrate/client/network/src/discovery.rs +++ b/substrate/client/network/src/discovery.rs @@ -63,7 +63,7 @@ use libp2p::multiaddr::Protocol; use log::{debug, info, trace, warn}; use std::{cmp, collections::VecDeque, time::Duration}; use tokio_io::{AsyncRead, AsyncWrite}; -use primitives::hexdisplay::HexDisplay; +use sp_core::hexdisplay::HexDisplay; /// Implementation of `NetworkBehaviour` that discovers the nodes on the network. pub struct DiscoveryBehaviour { diff --git a/substrate/client/network/src/lib.rs b/substrate/client/network/src/lib.rs index ad98986276..a60087751f 100644 --- a/substrate/client/network/src/lib.rs +++ b/substrate/client/network/src/lib.rs @@ -195,7 +195,7 @@ pub use libp2p::multiaddr; pub use message::{generic as generic_message, RequestId, Status as StatusMessage}; pub use on_demand_layer::{OnDemand, RemoteResponse}; -pub use peerset::ReputationChange; +pub use sc_peerset::ReputationChange; // Used by the `construct_simple_protocol!` macro. #[doc(hidden)] diff --git a/substrate/client/network/src/on_demand_layer.rs b/substrate/client/network/src/on_demand_layer.rs index 91c8464b78..db75de5e34 100644 --- a/substrate/client/network/src/on_demand_layer.rs +++ b/substrate/client/network/src/on_demand_layer.rs @@ -23,7 +23,7 @@ use futures::{prelude::*, sync::mpsc, sync::oneshot}; use futures03::compat::{Compat01As03, Future01CompatExt as _}; use parking_lot::Mutex; use sp_blockchain::Error as ClientError; -use client_api::{Fetcher, FetchChecker, RemoteHeaderRequest, +use sc_client_api::{Fetcher, FetchChecker, RemoteHeaderRequest, RemoteCallRequest, RemoteReadRequest, RemoteChangesRequest, RemoteReadChildRequest, RemoteBodyRequest}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor}; diff --git a/substrate/client/network/src/protocol.rs b/substrate/client/network/src/protocol.rs index d4283d588c..165cef0c68 100644 --- a/substrate/client/network/src/protocol.rs +++ b/substrate/client/network/src/protocol.rs @@ -24,8 +24,8 @@ use libp2p::{Multiaddr, PeerId}; use libp2p::core::{ConnectedPoint, nodes::Substream, muxing::StreamMuxerBox}; use libp2p::swarm::{ProtocolsHandler, IntoProtocolsHandler}; use libp2p::swarm::{NetworkBehaviour, NetworkBehaviourAction, PollParameters}; -use primitives::storage::{StorageKey, ChildInfo}; -use consensus::{ +use sp_core::storage::{StorageKey, ChildInfo}; +use sp_consensus::{ BlockOrigin, block_validation::BlockAnnounceValidator, import_queue::{BlockImportResult, BlockImportError, IncomingBlock, Origin} @@ -50,7 +50,7 @@ use std::fmt::Write; use std::{cmp, num::NonZeroUsize, time}; use log::{log, Level, trace, debug, warn, error}; use crate::chain::{Client, FinalityProofProvider}; -use client_api::{FetchChecker, ChangesProof, StorageProof}; +use sc_client_api::{FetchChecker, ChangesProof, StorageProof}; use crate::error; use util::LruHashSet; @@ -89,7 +89,7 @@ const MAX_CONSENSUS_MESSAGES: usize = 256; const LIGHT_MAXIMAL_BLOCKS_DIFFERENCE: u64 = 8192; mod rep { - use peerset::ReputationChange as Rep; + use sc_peerset::ReputationChange as Rep; /// Reputation change when a peer is "clogged", meaning that it's not fast enough to process our /// messages. pub const CLOGGED_PEER: Rep = Rep::new(-(1 << 12), "Clogged message queue"); @@ -140,7 +140,7 @@ pub struct Protocol, H: ExHashT> { // Connected peers pending Status message. handshaking_peers: HashMap, /// Used to report reputation changes. - peerset_handle: peerset::PeersetHandle, + peerset_handle: sc_peerset::PeersetHandle, transaction_pool: Arc>, /// When asked for a proof of finality, we use this struct to build one. finality_proof_provider: Option>>, @@ -195,11 +195,11 @@ pub struct PeerInfo { struct LightDispatchIn<'a> { behaviour: &'a mut LegacyProto>, - peerset: peerset::PeersetHandle, + peerset: sc_peerset::PeersetHandle, } impl<'a, B: BlockT> LightDispatchNetwork for LightDispatchIn<'a> { - fn report_peer(&mut self, who: &PeerId, reputation: peerset::ReputationChange) { + fn report_peer(&mut self, who: &PeerId, reputation: sc_peerset::ReputationChange) { self.peerset.report_peer(who.clone(), reputation) } @@ -323,7 +323,7 @@ impl<'a, B: BlockT> LightDispatchNetwork for LightDispatchIn<'a> { pub trait Context { /// Adjusts the reputation of the peer. Use this to point out that a peer has been malign or /// irresponsible or appeared lazy. - fn report_peer(&mut self, who: PeerId, reputation: peerset::ReputationChange); + fn report_peer(&mut self, who: PeerId, reputation: sc_peerset::ReputationChange); /// Force disconnecting from a peer. Use this when a peer misbehaved. fn disconnect_peer(&mut self, who: PeerId); @@ -339,21 +339,21 @@ pub trait Context { struct ProtocolContext<'a, B: 'a + BlockT, H: 'a + ExHashT> { behaviour: &'a mut LegacyProto>, context_data: &'a mut ContextData, - peerset_handle: &'a peerset::PeersetHandle, + peerset_handle: &'a sc_peerset::PeersetHandle, } impl<'a, B: BlockT + 'a, H: 'a + ExHashT> ProtocolContext<'a, B, H> { fn new( context_data: &'a mut ContextData, behaviour: &'a mut LegacyProto>, - peerset_handle: &'a peerset::PeersetHandle, + peerset_handle: &'a sc_peerset::PeersetHandle, ) -> Self { ProtocolContext { context_data, peerset_handle, behaviour } } } impl<'a, B: BlockT + 'a, H: ExHashT + 'a> Context for ProtocolContext<'a, B, H> { - fn report_peer(&mut self, who: PeerId, reputation: peerset::ReputationChange) { + fn report_peer(&mut self, who: PeerId, reputation: sc_peerset::ReputationChange) { self.peerset_handle.report_peer(who, reputation) } @@ -437,9 +437,9 @@ impl, H: ExHashT> Protocol { finality_proof_provider: Option>>, finality_proof_request_builder: Option>, protocol_id: ProtocolId, - peerset_config: peerset::PeersetConfig, + peerset_config: sc_peerset::PeersetConfig, block_announce_validator: Box + Send> - ) -> error::Result<(Protocol, peerset::PeersetHandle)> { + ) -> error::Result<(Protocol, sc_peerset::PeersetHandle)> { let info = chain.info(); let sync = ChainSync::new( config.roles, @@ -459,7 +459,7 @@ impl, H: ExHashT> Protocol { imp_p }; - let (peerset, peerset_handle) = peerset::Peerset::from_config(peerset_config); + let (peerset, peerset_handle) = sc_peerset::Peerset::from_config(peerset_config); let versions = &((MIN_VERSION as u8)..=(CURRENT_VERSION as u8)).collect::>(); let behaviour = LegacyProto::new(protocol_id, versions, peerset); @@ -853,7 +853,7 @@ impl, H: ExHashT> Protocol { } /// Adjusts the reputation of a node. - pub fn report_peer(&self, who: PeerId, reputation: peerset::ReputationChange) { + pub fn report_peer(&self, who: PeerId, reputation: sc_peerset::ReputationChange) { self.peerset_handle.report_peer(who, reputation) } diff --git a/substrate/client/network/src/protocol/legacy_proto/behaviour.rs b/substrate/client/network/src/protocol/legacy_proto/behaviour.rs index ed3ea8af4d..31e162a589 100644 --- a/substrate/client/network/src/protocol/legacy_proto/behaviour.rs +++ b/substrate/client/network/src/protocol/legacy_proto/behaviour.rs @@ -65,7 +65,7 @@ pub struct LegacyProto< TSubstream> { protocol: RegisteredProtocol, /// Receiver for instructions about who to connect to or disconnect from. - peerset: peerset::Peerset, + peerset: sc_peerset::Peerset, /// List of peers in our state. peers: FnvHashMap, @@ -76,7 +76,7 @@ pub struct LegacyProto< TSubstream> { /// We generate indices to identify incoming connections. This is the next value for the index /// to use when a connection is incoming. - next_incoming_index: peerset::IncomingIndex, + next_incoming_index: sc_peerset::IncomingIndex, /// Events to produce from `poll()`. events: SmallVec<[NetworkBehaviourAction; 4]>, @@ -183,7 +183,7 @@ struct IncomingPeer { /// connection corresponding to it has been closed or replaced already. alive: bool, /// Id that the we sent to the peerset. - incoming_id: peerset::IncomingIndex, + incoming_id: sc_peerset::IncomingIndex, } /// Event that can be emitted by the `LegacyProto`. @@ -230,7 +230,7 @@ impl LegacyProto { pub fn new( protocol: impl Into, versions: &[u8], - peerset: peerset::Peerset, + peerset: sc_peerset::Peerset, ) -> Self { let protocol = RegisteredProtocol::new(protocol, versions); @@ -239,7 +239,7 @@ impl LegacyProto { peerset, peers: FnvHashMap::default(), incoming: SmallVec::new(), - next_incoming_index: peerset::IncomingIndex(0), + next_incoming_index: sc_peerset::IncomingIndex(0), events: SmallVec::new(), marker: PhantomData, } @@ -520,7 +520,7 @@ impl LegacyProto { } /// Function that is called when the peerset wants us to accept an incoming node. - fn peerset_report_accept(&mut self, index: peerset::IncomingIndex) { + fn peerset_report_accept(&mut self, index: sc_peerset::IncomingIndex) { let incoming = if let Some(pos) = self.incoming.iter().position(|i| i.incoming_id == index) { self.incoming.remove(pos) } else { @@ -564,7 +564,7 @@ impl LegacyProto { } /// Function that is called when the peerset wants us to reject an incoming node. - fn peerset_report_reject(&mut self, index: peerset::IncomingIndex) { + fn peerset_report_reject(&mut self, index: sc_peerset::IncomingIndex) { let incoming = if let Some(pos) = self.incoming.iter().position(|i| i.incoming_id == index) { self.incoming.remove(pos) } else { @@ -942,7 +942,7 @@ where // again in the short term. self.peerset.report_peer( source.clone(), - peerset::ReputationChange::new(i32::min_value(), "Protocol error") + sc_peerset::ReputationChange::new(i32::min_value(), "Protocol error") ); self.disconnect_peer_inner(&source, Some(Duration::from_secs(5))); } @@ -965,16 +965,16 @@ where futures03::Stream::poll_next(Pin::new(&mut self.peerset), cx) ).map(|v| Ok::<_, ()>(v)).compat(); match peerset01.poll() { - Ok(Async::Ready(Some(peerset::Message::Accept(index)))) => { + Ok(Async::Ready(Some(sc_peerset::Message::Accept(index)))) => { self.peerset_report_accept(index); } - Ok(Async::Ready(Some(peerset::Message::Reject(index)))) => { + Ok(Async::Ready(Some(sc_peerset::Message::Reject(index)))) => { self.peerset_report_reject(index); } - Ok(Async::Ready(Some(peerset::Message::Connect(id)))) => { + Ok(Async::Ready(Some(sc_peerset::Message::Connect(id)))) => { self.peerset_report_connect(id); } - Ok(Async::Ready(Some(peerset::Message::Drop(id)))) => { + Ok(Async::Ready(Some(sc_peerset::Message::Drop(id)))) => { self.peerset_report_disconnect(id); } Ok(Async::Ready(None)) => { diff --git a/substrate/client/network/src/protocol/legacy_proto/tests.rs b/substrate/client/network/src/protocol/legacy_proto/tests.rs index 32af2198b7..eaf25e5119 100644 --- a/substrate/client/network/src/protocol/legacy_proto/tests.rs +++ b/substrate/client/network/src/protocol/legacy_proto/tests.rs @@ -68,7 +68,7 @@ fn build_nodes() .map_err(|err| io::Error::new(io::ErrorKind::Other, err)) .boxed(); - let (peerset, _) = peerset::Peerset::from_config(peerset::PeersetConfig { + let (peerset, _) = sc_peerset::Peerset::from_config(sc_peerset::PeersetConfig { in_peers: 25, out_peers: 25, bootnodes: if index == 0 { diff --git a/substrate/client/network/src/protocol/light_dispatch.rs b/substrate/client/network/src/protocol/light_dispatch.rs index 047961250f..83e0331325 100644 --- a/substrate/client/network/src/protocol/light_dispatch.rs +++ b/substrate/client/network/src/protocol/light_dispatch.rs @@ -26,14 +26,14 @@ use log::{trace, info}; use futures::sync::oneshot::{Sender as OneShotSender}; use linked_hash_map::{Entry, LinkedHashMap}; use sp_blockchain::Error as ClientError; -use client_api::{FetchChecker, RemoteHeaderRequest, +use sc_client_api::{FetchChecker, RemoteHeaderRequest, RemoteCallRequest, RemoteReadRequest, RemoteChangesRequest, ChangesProof, RemoteReadChildRequest, RemoteBodyRequest, StorageProof}; use crate::message::{self, BlockAttributes, Direction, FromBlock, RequestId}; use libp2p::PeerId; use crate::config::Roles; use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor}; -use peerset::ReputationChange; +use sc_peerset::ReputationChange; /// Remote request timeout. const REQUEST_TIMEOUT: Duration = Duration::from_secs(15); @@ -681,10 +681,10 @@ pub mod tests { use std::sync::Arc; use std::time::Instant; use futures::{Future, sync::oneshot}; - use primitives::storage::ChildInfo; + use sp_core::storage::ChildInfo; use sp_runtime::traits::{Block as BlockT, NumberFor, Header as HeaderT}; use sp_blockchain::{Error as ClientError, Result as ClientResult}; - use client_api::{FetchChecker, RemoteHeaderRequest, + use sc_client_api::{FetchChecker, RemoteHeaderRequest, ChangesProof, RemoteCallRequest, RemoteReadRequest, RemoteReadChildRequest, RemoteChangesRequest, RemoteBodyRequest}; use crate::config::Roles; @@ -1233,7 +1233,7 @@ pub mod tests { assert_eq!(light_dispatch.active_peers.len(), 1); let block = message::BlockData:: { - hash: primitives::H256::random(), + hash: sp_core::H256::random(), header: None, body: Some(Vec::new()), message_queue: None, @@ -1271,7 +1271,7 @@ pub mod tests { let response = { let blocks: Vec<_> = (0..3).map(|_| message::BlockData:: { - hash: primitives::H256::random(), + hash: sp_core::H256::random(), header: None, body: Some(Vec::new()), message_queue: None, diff --git a/substrate/client/network/src/protocol/message.rs b/substrate/client/network/src/protocol/message.rs index b7267f376f..0bb9d8c64f 100644 --- a/substrate/client/network/src/protocol/message.rs +++ b/substrate/client/network/src/protocol/message.rs @@ -26,7 +26,7 @@ pub use self::generic::{ FinalityProofRequest, FinalityProofResponse, FromBlock, RemoteReadChildRequest, }; -use client_api::StorageProof; +use sc_client_api::StorageProof; /// A unique ID of a request. pub type RequestId = u64; diff --git a/substrate/client/network/src/protocol/sync.rs b/substrate/client/network/src/protocol/sync.rs index ca332d46f1..4e248b7fe4 100644 --- a/substrate/client/network/src/protocol/sync.rs +++ b/substrate/client/network/src/protocol/sync.rs @@ -28,9 +28,9 @@ //! use blocks::BlockCollection; -use client_api::ClientInfo; +use sc_client_api::ClientInfo; use sp_blockchain::Error as ClientError; -use consensus::{BlockOrigin, BlockStatus, +use sp_consensus::{BlockOrigin, BlockStatus, block_validation::{BlockAnnounceValidator, Validation}, import_queue::{IncomingBlock, BlockImportResult, BlockImportError} }; @@ -73,7 +73,7 @@ const MAJOR_SYNC_BLOCKS: u8 = 5; const ANNOUNCE_HISTORY_SIZE: usize = 64; mod rep { - use peerset::ReputationChange as Rep; + use sc_peerset::ReputationChange as Rep; /// Reputation change when a peer sent us a message that led to a /// database read error. pub const BLOCKCHAIN_READ_ERROR: Rep = Rep::new(-(1 << 16), "DB Error"); @@ -230,7 +230,7 @@ pub struct Status { /// A peer did not behave as expected and should be reported. #[derive(Debug, Clone, PartialEq, Eq)] -pub struct BadPeer(pub PeerId, pub peerset::ReputationChange); +pub struct BadPeer(pub PeerId, pub sc_peerset::ReputationChange); impl fmt::Display for BadPeer { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { diff --git a/substrate/client/network/src/protocol/sync/blocks.rs b/substrate/client/network/src/protocol/sync/blocks.rs index f89772a8e7..ef08d7320d 100644 --- a/substrate/client/network/src/protocol/sync/blocks.rs +++ b/substrate/client/network/src/protocol/sync/blocks.rs @@ -216,7 +216,7 @@ mod test { use super::{BlockCollection, BlockData, BlockRangeState}; use crate::{message, PeerId}; use sp_runtime::testing::{Block as RawBlock, ExtrinsicWrapper}; - use primitives::H256; + use sp_core::H256; type Block = RawBlock>; diff --git a/substrate/client/network/src/service.rs b/substrate/client/network/src/service.rs index c137932090..3b3a64b41a 100644 --- a/substrate/client/network/src/service.rs +++ b/substrate/client/network/src/service.rs @@ -28,8 +28,8 @@ use std::{collections::{HashMap, HashSet}, fs, marker::PhantomData, io, path::Path}; use std::sync::{Arc, atomic::{AtomicBool, AtomicUsize, Ordering}}; -use consensus::import_queue::{ImportQueue, Link}; -use consensus::import_queue::{BlockImportResult, BlockImportError}; +use sp_consensus::import_queue::{ImportQueue, Link}; +use sp_consensus::import_queue::{BlockImportResult, BlockImportError}; use futures::{prelude::*, sync::mpsc}; use futures03::TryFutureExt as _; use log::{warn, error, info}; @@ -37,7 +37,7 @@ use libp2p::{PeerId, Multiaddr, kad::record}; use libp2p::core::{transport::boxed::Boxed, muxing::StreamMuxerBox}; use libp2p::swarm::NetworkBehaviour; use parking_lot::Mutex; -use peerset::PeersetHandle; +use sc_peerset::PeersetHandle; use sp_runtime::{traits::{Block as BlockT, NumberFor}, ConsensusEngineId}; use crate::{behaviour::{Behaviour, BehaviourOut}, config::{parse_str_addr, parse_addr}}; @@ -176,7 +176,7 @@ impl, H: ExHashT> NetworkWorker } } - let peerset_config = peerset::PeersetConfig { + let peerset_config = sc_peerset::PeersetConfig { in_peers: params.network_config.in_peers, out_peers: params.network_config.out_peers, bootnodes, @@ -604,7 +604,7 @@ impl, H: ExHashT> NetworkServic } } -impl, H: ExHashT> consensus::SyncOracle +impl, H: ExHashT> sp_consensus::SyncOracle for NetworkService { fn is_major_syncing(&mut self) -> bool { @@ -616,7 +616,7 @@ impl, H: ExHashT> consensus::Sy } } -impl<'a, B: BlockT + 'static, S: NetworkSpecialization, H: ExHashT> consensus::SyncOracle +impl<'a, B: BlockT + 'static, S: NetworkSpecialization, H: ExHashT> sp_consensus::SyncOracle for &'a NetworkService { fn is_major_syncing(&mut self) -> bool { diff --git a/substrate/client/network/test/Cargo.toml b/substrate/client/network/test/Cargo.toml index e92ae0f7fc..c3f95894f8 100644 --- a/substrate/client/network/test/Cargo.toml +++ b/substrate/client/network/test/Cargo.toml @@ -15,16 +15,16 @@ futures03 = { package = "futures", version = "0.3.1", features = ["compat"] } futures-timer = "0.4.0" rand = "0.7.2" libp2p = { version = "0.13.0", default-features = false, features = ["libp2p-websocket"] } -consensus = { package = "sp-consensus", path = "../../../primitives/consensus/common" } -client = { package = "sc-client", path = "../../" } -client-api = { package = "sc-client-api", path = "../../api" } +sp-consensus = { path = "../../../primitives/consensus/common" } +sc-client = { path = "../../" } +sc-client-api = { path = "../../api" } sp-blockchain = { path = "../../../primitives/blockchain" } sp-runtime = { path = "../../../primitives/runtime" } -primitives = { package = "sp-core", path = "../../../primitives/core" } -block-builder = { package = "sc-block-builder", path = "../../block-builder" } -babe-primitives = { package = "sp-consensus-babe", path = "../../../primitives/consensus/babe" } +sp-core = { path = "../../../primitives/core" } +sc-block-builder = { path = "../../block-builder" } +sp-consensus-babe = { path = "../../../primitives/consensus/babe" } env_logger = "0.7.0" -test-client = { package = "substrate-test-runtime-client", path = "../../../test-utils/runtime/client" } -test_runtime = { package = "substrate-test-runtime", path = "../../../test-utils/runtime" } +substrate-test-runtime-client = { path = "../../../test-utils/runtime/client" } +substrate-test-runtime = { path = "../../../test-utils/runtime" } tempfile = "3.1.0" tokio = "0.1.22" diff --git a/substrate/client/network/test/src/block_import.rs b/substrate/client/network/test/src/block_import.rs index 5cb7b6b606..7ea317c2b4 100644 --- a/substrate/client/network/test/src/block_import.rs +++ b/substrate/client/network/test/src/block_import.rs @@ -16,17 +16,17 @@ //! Testing block import logic. -use consensus::ImportedAux; -use consensus::import_queue::{ +use sp_consensus::ImportedAux; +use sp_consensus::import_queue::{ import_single_block, BasicQueue, BlockImportError, BlockImportResult, IncomingBlock, }; -use test_client::{self, prelude::*}; -use test_client::runtime::{Block, Hash}; +use substrate_test_runtime_client::{self, prelude::*}; +use substrate_test_runtime_client::runtime::{Block, Hash}; use sp_runtime::generic::BlockId; use super::*; fn prepare_good_block() -> (TestClient, Hash, u64, PeerId, IncomingBlock) { - let client = test_client::new(); + let client = substrate_test_runtime_client::new(); let block = client.new_block(Default::default()).unwrap().bake().unwrap(); client.import(BlockOrigin::File, block).unwrap(); @@ -52,7 +52,7 @@ fn import_single_good_block_works() { let mut expected_aux = ImportedAux::default(); expected_aux.is_new_best = true; - match import_single_block(&mut test_client::new(), BlockOrigin::File, block, &mut PassThroughVerifier(true)) { + match import_single_block(&mut substrate_test_runtime_client::new(), BlockOrigin::File, block, &mut PassThroughVerifier(true)) { Ok(BlockImportResult::ImportedUnknown(ref num, ref aux, ref org)) if *num == number && *aux == expected_aux && *org == Some(peer_id) => {} r @ _ => panic!("{:?}", r) @@ -72,7 +72,7 @@ fn import_single_good_known_block_is_ignored() { fn import_single_good_block_without_header_fails() { let (_, _, _, peer_id, mut block) = prepare_good_block(); block.header = None; - match import_single_block(&mut test_client::new(), BlockOrigin::File, block, &mut PassThroughVerifier(true)) { + match import_single_block(&mut substrate_test_runtime_client::new(), BlockOrigin::File, block, &mut PassThroughVerifier(true)) { Err(BlockImportError::IncompleteHeader(ref org)) if *org == Some(peer_id) => {} _ => panic!() } @@ -83,7 +83,7 @@ fn async_import_queue_drops() { // Perform this test multiple times since it exhibits non-deterministic behavior. for _ in 0..100 { let verifier = PassThroughVerifier(true); - let queue = BasicQueue::new(verifier, Box::new(test_client::new()), None, None); + let queue = BasicQueue::new(verifier, Box::new(substrate_test_runtime_client::new()), None, None); drop(queue); } } diff --git a/substrate/client/network/test/src/lib.rs b/substrate/client/network/test/src/lib.rs index cc81789e24..8e598c95a3 100644 --- a/substrate/client/network/test/src/lib.rs +++ b/substrate/client/network/test/src/lib.rs @@ -30,42 +30,42 @@ use sc_network::FinalityProofProvider; use sp_blockchain::{ Result as ClientResult, well_known_cache_keys::{self, Id as CacheKeyId}, }; -use client_api::{ +use sc_client_api::{ ClientInfo, BlockchainEvents, BlockImportNotification, FinalityNotifications, ImportNotifications, FinalityNotification, backend::{AuxStore, Backend, Finalizer} }; -use block_builder::BlockBuilder; -use client::LongestChain; +use sc_block_builder::BlockBuilder; +use sc_client::LongestChain; use sc_network::config::Roles; -use consensus::block_validation::DefaultBlockAnnounceValidator; -use consensus::import_queue::BasicQueue; -use consensus::import_queue::{ +use sp_consensus::block_validation::DefaultBlockAnnounceValidator; +use sp_consensus::import_queue::BasicQueue; +use sp_consensus::import_queue::{ BoxBlockImport, BoxJustificationImport, Verifier, BoxFinalityProofImport, }; -use consensus::block_import::{BlockImport, ImportResult}; -use consensus::Error as ConsensusError; -use consensus::{BlockOrigin, ForkChoiceStrategy, BlockImportParams, BlockCheckParams, JustificationImport}; +use sp_consensus::block_import::{BlockImport, ImportResult}; +use sp_consensus::Error as ConsensusError; +use sp_consensus::{BlockOrigin, ForkChoiceStrategy, BlockImportParams, BlockCheckParams, JustificationImport}; use futures::prelude::*; use futures03::{StreamExt as _, TryStreamExt as _}; use sc_network::{NetworkWorker, NetworkService, ReportHandle, config::ProtocolId}; use sc_network::config::{NetworkConfiguration, TransportConfig, BoxFinalityProofRequestBuilder}; use libp2p::PeerId; use parking_lot::Mutex; -use primitives::H256; +use sp_core::H256; use sc_network::{Context, ProtocolConfig}; use sp_runtime::generic::{BlockId, OpaqueDigestItemId}; use sp_runtime::traits::{Block as BlockT, Header, NumberFor}; use sp_runtime::Justification; use sc_network::TransactionPool; use sc_network::specialization::NetworkSpecialization; -use test_client::{self, AccountKeyring}; +use substrate_test_runtime_client::{self, AccountKeyring}; -pub use test_client::runtime::{Block, Extrinsic, Hash, Transfer}; -pub use test_client::{TestClient, TestClientBuilder, TestClientBuilderExt}; +pub use substrate_test_runtime_client::runtime::{Block, Extrinsic, Hash, Transfer}; +pub use substrate_test_runtime_client::{TestClient, TestClientBuilder, TestClientBuilderExt}; -type AuthorityId = babe_primitives::AuthorityId; +type AuthorityId = sp_consensus_babe::AuthorityId; /// A Verifier that accepts all blocks and passes them on with the configured /// finality to be imported. @@ -129,14 +129,14 @@ impl NetworkSpecialization for DummySpecialization { } pub type PeersFullClient = - client::Client; + sc_client::Client; pub type PeersLightClient = - client::Client; + sc_client::Client; #[derive(Clone)] pub enum PeersClient { - Full(Arc, Arc), - Light(Arc, Arc), + Full(Arc, Arc), + Light(Arc, Arc), } impl PeersClient { @@ -218,8 +218,8 @@ pub struct Peer> { /// We keep a copy of the block_import so that we can invoke it for locally-generated blocks, /// instead of going through the import queue. block_import: Box>, - select_chain: Option>, - backend: Option>, + select_chain: Option>, + backend: Option>, network: NetworkWorker::Hash>, imported_blocks_stream: Box, Error = ()> + Send>, finality_notification_stream: Box, Error = ()> + Send>, @@ -237,7 +237,7 @@ impl> Peer { } // Returns a clone of the local SelectChain, only available on full nodes - pub fn select_chain(&self) -> Option> { + pub fn select_chain(&self) -> Option> { self.select_chain.clone() } @@ -608,7 +608,7 @@ pub trait TestNetFactory: Sized { let mut config = config.clone(); config.roles = Roles::LIGHT; - let (c, backend) = test_client::new_light(); + let (c, backend) = substrate_test_runtime_client::new_light(); let client = Arc::new(c); let ( block_import, diff --git a/substrate/client/network/test/src/sync.rs b/substrate/client/network/test/src/sync.rs index b4e166be67..0160c081e3 100644 --- a/substrate/client/network/test/src/sync.rs +++ b/substrate/client/network/test/src/sync.rs @@ -15,7 +15,7 @@ // along with Substrate. If not, see . use sc_network::config::Roles; -use consensus::BlockOrigin; +use sp_consensus::BlockOrigin; use futures03::TryFutureExt as _; use std::time::Duration; use tokio::runtime::current_thread; diff --git a/substrate/client/offchain/Cargo.toml b/substrate/client/offchain/Cargo.toml index 755453fa21..2e1255eab2 100644 --- a/substrate/client/offchain/Cargo.toml +++ b/substrate/client/offchain/Cargo.toml @@ -8,7 +8,7 @@ edition = "2018" [dependencies] bytes = "0.4.12" -client-api = { package = "sc-client-api", path = "../api" } +sc-client-api = { path = "../api" } sp-api = { path = "../../primitives/api" } fnv = "1.0.6" futures01 = { package = "futures", version = "0.1" } @@ -17,26 +17,26 @@ futures-timer = "2.0" log = "0.4.8" threadpool = "1.7" num_cpus = "1.10" -offchain-primitives = { package = "sp-offchain", path = "../../primitives/offchain" } +sp-offchain = { path = "../../primitives/offchain" } codec = { package = "parity-scale-codec", version = "1.0.0", features = ["derive"] } parking_lot = "0.9.0" -primitives = { package = "sp-core", path = "../../primitives/core" } +sp-core = { path = "../../primitives/core" } rand = "0.7.2" sp-runtime = { path = "../../primitives/runtime" } -network = { package = "sc-network", path = "../network" } -keystore = { package = "sc-keystore", path = "../keystore" } +sc-network = { path = "../network" } +sc-keystore = { path = "../keystore" } [target.'cfg(not(target_os = "unknown"))'.dependencies] hyper = "0.12.35" hyper-rustls = "0.17.1" [dev-dependencies] -client-db = { package = "sc-client-db", path = "../db/", default-features = true } +sc-client-db = { path = "../db/", default-features = true } env_logger = "0.7.0" -test-client = { package = "substrate-test-runtime-client", path = "../../test-utils/runtime/client" } +substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } tokio = "0.1.22" -txpool = { package = "sc-transaction-pool", path = "../../client/transaction-pool" } -txpool-api = { package = "sp-transaction-pool", path = "../../primitives/transaction-pool" } +sc-transaction-pool = { path = "../../client/transaction-pool" } +sp-transaction-pool = { path = "../../primitives/transaction-pool" } [features] default = [] diff --git a/substrate/client/offchain/src/api.rs b/substrate/client/offchain/src/api.rs index ff2a5a433a..4db08c145d 100644 --- a/substrate/client/offchain/src/api.rs +++ b/substrate/client/offchain/src/api.rs @@ -21,16 +21,16 @@ use std::{ thread::sleep, }; -use primitives::offchain::OffchainStorage; +use sp_core::offchain::OffchainStorage; use futures::Future; use log::error; -use network::{PeerId, Multiaddr, NetworkStateInfo}; +use sc_network::{PeerId, Multiaddr, NetworkStateInfo}; use codec::{Encode, Decode}; -use primitives::offchain::{ +use sp_core::offchain::{ Externalities as OffchainExt, HttpRequestId, Timestamp, HttpRequestStatus, HttpError, OpaqueNetworkState, OpaquePeerId, OpaqueMultiaddr, StorageKind, }; -pub use offchain_primitives::STORAGE_PREFIX; +pub use sp_offchain::STORAGE_PREFIX; #[cfg(not(target_os = "unknown"))] mod http; @@ -282,8 +282,8 @@ impl AsyncApi { mod tests { use super::*; use std::{convert::{TryFrom, TryInto}, time::SystemTime}; - use client_db::offchain::LocalStorage; - use network::PeerId; + use sc_client_db::offchain::LocalStorage; + use sc_network::PeerId; struct MockNetworkStateInfo(); @@ -331,7 +331,7 @@ mod tests { // Arrange. let now = api.timestamp(); - let delta = primitives::offchain::Duration::from_millis(100); + let delta = sp_core::offchain::Duration::from_millis(100); let deadline = now.add(delta); // Act. diff --git a/substrate/client/offchain/src/api/http.rs b/substrate/client/offchain/src/api/http.rs index 30cadf0918..6744e1b90f 100644 --- a/substrate/client/offchain/src/api/http.rs +++ b/substrate/client/offchain/src/api/http.rs @@ -30,7 +30,7 @@ use bytes::Buf as _; use fnv::FnvHashMap; use futures::{prelude::*, channel::mpsc, compat::Compat01As03}; use log::error; -use primitives::offchain::{HttpRequestId, Timestamp, HttpRequestStatus, HttpError}; +use sp_core::offchain::{HttpRequestId, Timestamp, HttpRequestStatus, HttpError}; use std::{fmt, io::Read as _, mem, pin::Pin, task::Context, task::Poll}; /// Creates a pair of [`HttpApi`] and [`HttpWorker`]. @@ -696,7 +696,7 @@ mod tests { use super::http; use futures::prelude::*; use futures01::Future as _; - use primitives::offchain::{HttpError, HttpRequestId, HttpRequestStatus, Duration}; + use sp_core::offchain::{HttpError, HttpRequestId, HttpRequestStatus, Duration}; // Returns an `HttpApi` whose worker is ran in the background, and a `SocketAddr` to an HTTP // server that runs in the background as well. diff --git a/substrate/client/offchain/src/api/http_dummy.rs b/substrate/client/offchain/src/api/http_dummy.rs index e3cb272a0d..83c3b3c80c 100644 --- a/substrate/client/offchain/src/api/http_dummy.rs +++ b/substrate/client/offchain/src/api/http_dummy.rs @@ -16,7 +16,7 @@ //! Contains the same API as the `http` module, except that everything returns an error. -use primitives::offchain::{HttpRequestId, Timestamp, HttpRequestStatus, HttpError}; +use sp_core::offchain::{HttpRequestId, Timestamp, HttpRequestStatus, HttpError}; use std::{future::Future, pin::Pin, task::Context, task::Poll}; /// Creates a pair of [`HttpApi`] and [`HttpWorker`]. diff --git a/substrate/client/offchain/src/api/timestamp.rs b/substrate/client/offchain/src/api/timestamp.rs index 445c7f3878..8c45fce0cd 100644 --- a/substrate/client/offchain/src/api/timestamp.rs +++ b/substrate/client/offchain/src/api/timestamp.rs @@ -16,7 +16,7 @@ //! Helper methods dedicated to timestamps. -use primitives::offchain::Timestamp; +use sp_core::offchain::Timestamp; use std::convert::TryInto; use std::time::{SystemTime, Duration}; diff --git a/substrate/client/offchain/src/lib.rs b/substrate/client/offchain/src/lib.rs index 174aee89d9..208cfdfb0f 100644 --- a/substrate/client/offchain/src/lib.rs +++ b/substrate/client/offchain/src/lib.rs @@ -40,13 +40,13 @@ use threadpool::ThreadPool; use sp_api::ApiExt; use futures::future::Future; use log::{debug, warn}; -use network::NetworkStateInfo; -use primitives::{offchain::{self, OffchainStorage}, ExecutionContext}; +use sc_network::NetworkStateInfo; +use sp_core::{offchain::{self, OffchainStorage}, ExecutionContext}; use sp_runtime::{generic::BlockId, traits::{self, ProvideRuntimeApi}}; mod api; -pub use offchain_primitives::{OffchainWorkerApi, STORAGE_PREFIX}; +pub use sp_offchain::{OffchainWorkerApi, STORAGE_PREFIX}; /// An offchain workers manager. pub struct OffchainWorkers { @@ -146,10 +146,10 @@ impl OffchainWorkers< mod tests { use super::*; use std::sync::Arc; - use network::{Multiaddr, PeerId}; - use test_client::runtime::Block; - use txpool::{BasicPool, FullChainApi}; - use txpool_api::{TransactionPool, InPoolTransaction}; + use sc_network::{Multiaddr, PeerId}; + use substrate_test_runtime_client::runtime::Block; + use sc_transaction_pool::{BasicPool, FullChainApi}; + use sp_transaction_pool::{TransactionPool, InPoolTransaction}; struct MockNetworkStateInfo(); @@ -163,9 +163,9 @@ mod tests { } } - struct TestPool(BasicPool, Block>); + struct TestPool(BasicPool, Block>); - impl txpool_api::OffchainSubmitTransaction for TestPool { + impl sp_transaction_pool::OffchainSubmitTransaction for TestPool { fn submit_at( &self, at: &BlockId, @@ -181,11 +181,11 @@ mod tests { fn should_call_into_runtime_and_produce_extrinsic() { // given let _ = env_logger::try_init(); - let client = Arc::new(test_client::new()); + let client = Arc::new(substrate_test_runtime_client::new()); let pool = Arc::new(TestPool(BasicPool::new(Default::default(), FullChainApi::new(client.clone())))); client.execution_extensions() .register_transaction_pool(Arc::downgrade(&pool.clone()) as _); - let db = client_db::offchain::LocalStorage::new_test(); + let db = sc_client_db::offchain::LocalStorage::new_test(); let network_state = Arc::new(MockNetworkStateInfo()); // when diff --git a/substrate/client/rpc-api/Cargo.toml b/substrate/client/rpc-api/Cargo.toml index 58fb3ca904..7b1f68c512 100644 --- a/substrate/client/rpc-api/Cargo.toml +++ b/substrate/client/rpc-api/Cargo.toml @@ -14,9 +14,9 @@ jsonrpc-derive = "14.0.3" jsonrpc-pubsub = "14.0.3" log = "0.4.8" parking_lot = "0.9.0" -primitives = { package = "sp-core", path = "../../primitives/core" } -runtime_version = { package = "sp-version", path = "../../primitives/version" } +sp-core = { path = "../../primitives/core" } +sp-version = { path = "../../primitives/version" } serde = { version = "1.0.101", features = ["derive"] } serde_json = "1.0.41" -txpool-api = { package = "sp-transaction-pool", path = "../../primitives/transaction-pool" } -rpc-primitives = { package = "sp-rpc", path = "../../primitives/rpc" } +sp-transaction-pool = { path = "../../primitives/transaction-pool" } +sp-rpc = { path = "../../primitives/rpc" } diff --git a/substrate/client/rpc-api/src/author/error.rs b/substrate/client/rpc-api/src/author/error.rs index eb98fbda51..b1dfcc140a 100644 --- a/substrate/client/rpc-api/src/author/error.rs +++ b/substrate/client/rpc-api/src/author/error.rs @@ -34,7 +34,7 @@ pub enum Error { Client(Box), /// Transaction pool error, #[display(fmt="Transaction pool error: {}", _0)] - Pool(txpool_api::error::Error), + Pool(sp_transaction_pool::error::Error), /// Verification error #[display(fmt="Extrinsic verification error: {}", _0)] #[from(ignore)] @@ -93,7 +93,7 @@ const UNSUPPORTED_KEY_TYPE: i64 = POOL_INVALID_TX + 7; impl From for rpc::Error { fn from(e: Error) -> Self { - use txpool_api::error::{Error as PoolError}; + use sp_transaction_pool::error::{Error as PoolError}; match e { Error::BadFormat(e) => rpc::Error { diff --git a/substrate/client/rpc-api/src/author/hash.rs b/substrate/client/rpc-api/src/author/hash.rs index a01e26de3c..9d2f658ae6 100644 --- a/substrate/client/rpc-api/src/author/hash.rs +++ b/substrate/client/rpc-api/src/author/hash.rs @@ -16,7 +16,7 @@ //! Extrinsic helpers for author RPC module. -use primitives::Bytes; +use sp_core::Bytes; use serde::{Serialize, Deserialize}; /// RPC Extrinsic or hash diff --git a/substrate/client/rpc-api/src/author/mod.rs b/substrate/client/rpc-api/src/author/mod.rs index 927bb530ea..c2fbe229c1 100644 --- a/substrate/client/rpc-api/src/author/mod.rs +++ b/substrate/client/rpc-api/src/author/mod.rs @@ -21,8 +21,8 @@ pub mod hash; use jsonrpc_derive::rpc; use jsonrpc_pubsub::{typed::Subscriber, SubscriptionId}; -use primitives::Bytes; -use txpool_api::TransactionStatus; +use sp_core::Bytes; +use sp_transaction_pool::TransactionStatus; use self::error::{FutureResult, Result}; pub use self::gen_client::Client as AuthorClient; diff --git a/substrate/client/rpc-api/src/chain/mod.rs b/substrate/client/rpc-api/src/chain/mod.rs index fd7576f988..f3c51d3871 100644 --- a/substrate/client/rpc-api/src/chain/mod.rs +++ b/substrate/client/rpc-api/src/chain/mod.rs @@ -22,7 +22,7 @@ use jsonrpc_core::Result as RpcResult; use jsonrpc_core::futures::Future; use jsonrpc_derive::rpc; use jsonrpc_pubsub::{typed::Subscriber, SubscriptionId}; -use rpc_primitives::{number::NumberOrHex, list::ListOrValue}; +use sp_rpc::{number::NumberOrHex, list::ListOrValue}; use self::error::{FutureResult, Result}; pub use self::gen_client::Client as ChainClient; diff --git a/substrate/client/rpc-api/src/state/mod.rs b/substrate/client/rpc-api/src/state/mod.rs index 9a549b00c4..ecc31581c6 100644 --- a/substrate/client/rpc-api/src/state/mod.rs +++ b/substrate/client/rpc-api/src/state/mod.rs @@ -22,9 +22,9 @@ use jsonrpc_core::Result as RpcResult; use jsonrpc_core::futures::Future; use jsonrpc_derive::rpc; use jsonrpc_pubsub::{typed::Subscriber, SubscriptionId}; -use primitives::Bytes; -use primitives::storage::{StorageKey, StorageData, StorageChangeSet}; -use runtime_version::RuntimeVersion; +use sp_core::Bytes; +use sp_core::storage::{StorageKey, StorageData, StorageChangeSet}; +use sp_version::RuntimeVersion; use self::error::FutureResult; pub use self::gen_client::Client as StateClient; diff --git a/substrate/client/rpc/Cargo.toml b/substrate/client/rpc/Cargo.toml index 61ad753c84..91274ed34b 100644 --- a/substrate/client/rpc/Cargo.toml +++ b/substrate/client/rpc/Cargo.toml @@ -5,25 +5,25 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -api = { package = "sc-rpc-api", path = "../rpc-api" } -client-api = { package = "sc-client-api", path = "../api" } -client = { package = "sc-client", path = "../" } +sc-rpc-api = { path = "../rpc-api" } +sc-client-api = { path = "../api" } +sc-client = { path = "../" } sp-api = { path = "../../primitives/api" } codec = { package = "parity-scale-codec", version = "1.0.0" } futures = { version = "0.3.1", features = ["compat"] } jsonrpc-pubsub = "14.0.3" log = "0.4.8" -primitives = { package = "sp-core", path = "../../primitives/core" } +sp-core = { path = "../../primitives/core" } rpc = { package = "jsonrpc-core", version = "14.0.3" } -runtime_version = { package = "sp-version", path = "../../primitives/version" } +sp-version = { path = "../../primitives/version" } serde_json = "1.0.41" -session = { package = "sp-session", path = "../../primitives/session" } +sp-session = { path = "../../primitives/session" } sp-runtime = { path = "../../primitives/runtime" } -rpc-primitives = { package = "sp-rpc", path = "../../primitives/rpc" } -state_machine = { package = "sp-state-machine", path = "../../primitives/state-machine" } +sp-rpc = { path = "../../primitives/rpc" } +sp-state-machine = { path = "../../primitives/state-machine" } sc-executor = { path = "../executor" } sc-keystore = { path = "../keystore" } -txpool-api = { package = "sp-transaction-pool", path = "../../primitives/transaction-pool" } +sp-transaction-pool = { path = "../../primitives/transaction-pool" } sp-blockchain = { path = "../../primitives/blockchain" } hash-db = { version = "0.15.2", default-features = false } parking_lot = { version = "0.9.0" } @@ -31,9 +31,9 @@ parking_lot = { version = "0.9.0" } [dev-dependencies] assert_matches = "1.3.0" futures01 = { package = "futures", version = "0.1.29" } -network = { package = "sc-network", path = "../network" } +sc-network = { path = "../network" } rustc-hex = "2.0.1" sp-io = { path = "../../primitives/io" } -test-client = { package = "substrate-test-runtime-client", path = "../../test-utils/runtime/client" } +substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } tokio = "0.1.22" -txpool = { package = "sc-transaction-pool", path = "../transaction-pool" } +sc-transaction-pool = { path = "../transaction-pool" } diff --git a/substrate/client/rpc/src/author/mod.rs b/substrate/client/rpc/src/author/mod.rs index c710016003..1cdbda5904 100644 --- a/substrate/client/rpc/src/author/mod.rs +++ b/substrate/client/rpc/src/author/mod.rs @@ -22,7 +22,7 @@ mod tests; use std::{sync::Arc, convert::TryInto}; use log::warn; -use client::Client; +use sc_client::Client; use sp_blockchain::Error as ClientError; use rpc::futures::{ @@ -31,20 +31,20 @@ use rpc::futures::{ }; use futures::{StreamExt as _, compat::Compat}; use futures::future::{ready, FutureExt, TryFutureExt}; -use api::Subscriptions; +use sc_rpc_api::Subscriptions; use jsonrpc_pubsub::{typed::Subscriber, SubscriptionId}; use codec::{Encode, Decode}; -use primitives::{Bytes, Blake2Hasher, H256, traits::BareCryptoStorePtr}; +use sp_core::{Bytes, Blake2Hasher, H256, traits::BareCryptoStorePtr}; use sp_api::ConstructRuntimeApi; use sp_runtime::{generic, traits::{self, ProvideRuntimeApi}}; -use txpool_api::{ +use sp_transaction_pool::{ TransactionPool, InPoolTransaction, TransactionStatus, BlockHash, TxHash, TransactionFor, error::IntoPoolError, }; -use session::SessionKeys; +use sp_session::SessionKeys; /// Re-export the API for backward compatibility. -pub use api::author::*; +pub use sc_rpc_api::author::*; use self::error::{Error, FutureResult, Result}; /// Authoring API @@ -78,8 +78,8 @@ impl Author { impl AuthorApi for Author where Block: traits::Block, - B: client_api::backend::Backend + Send + Sync + 'static, - E: client_api::CallExecutor + Clone + Send + Sync + 'static, + B: sc_client_api::backend::Backend + Send + Sync + 'static, + E: sc_client_api::CallExecutor + Clone + Send + Sync + 'static, P: TransactionPool + Sync + Send + 'static, RA: ConstructRuntimeApi> + Send + Sync + 'static, Client: ProvideRuntimeApi, diff --git a/substrate/client/rpc/src/author/tests.rs b/substrate/client/rpc/src/author/tests.rs index 14aa03a643..f672e38fa5 100644 --- a/substrate/client/rpc/src/author/tests.rs +++ b/substrate/client/rpc/src/author/tests.rs @@ -19,16 +19,16 @@ use super::*; use std::sync::Arc; use assert_matches::assert_matches; use codec::Encode; -use primitives::{ +use sp_core::{ H256, blake2_256, hexdisplay::HexDisplay, testing::{ED25519, SR25519, KeyStore}, traits::BareCryptoStorePtr, ed25519, crypto::Pair, }; use rpc::futures::Stream as _; -use test_client::{ +use substrate_test_runtime_client::{ self, AccountKeyring, runtime::{Extrinsic, Transfer, SessionKeys, RuntimeApi, Block}, DefaultTestClientBuilderExt, TestClientBuilderExt, Backend, Client, Executor, }; -use txpool::{BasicPool, FullChainApi}; +use sc_transaction_pool::{BasicPool, FullChainApi}; use tokio::runtime; fn uxt(sender: AccountKeyring, nonce: u64) -> Extrinsic { @@ -56,7 +56,7 @@ struct TestSetup { impl Default for TestSetup { fn default() -> Self { let keystore = KeyStore::new(); - let client = Arc::new(test_client::TestClientBuilder::new().set_keystore(keystore.clone()).build()); + let client = Arc::new(substrate_test_runtime_client::TestClientBuilder::new().set_keystore(keystore.clone()).build()); let pool = Arc::new(BasicPool::new(Default::default(), FullChainApi::new(client.clone()))); TestSetup { runtime: runtime::Runtime::new().expect("Failed to create runtime in test setup"), diff --git a/substrate/client/rpc/src/chain/chain_full.rs b/substrate/client/rpc/src/chain/chain_full.rs index aa11481a3e..f0a0b180c3 100644 --- a/substrate/client/rpc/src/chain/chain_full.rs +++ b/substrate/client/rpc/src/chain/chain_full.rs @@ -19,10 +19,10 @@ use std::sync::Arc; use rpc::futures::future::result; -use api::Subscriptions; -use client_api::{CallExecutor, backend::Backend}; -use client::Client; -use primitives::{H256, Blake2Hasher}; +use sc_rpc_api::Subscriptions; +use sc_client_api::{CallExecutor, backend::Backend}; +use sc_client::Client; +use sp_core::{H256, Blake2Hasher}; use sp_runtime::{ generic::{BlockId, SignedBlock}, traits::{Block as BlockT}, diff --git a/substrate/client/rpc/src/chain/chain_light.rs b/substrate/client/rpc/src/chain/chain_light.rs index 63cb067619..0c850153f7 100644 --- a/substrate/client/rpc/src/chain/chain_light.rs +++ b/substrate/client/rpc/src/chain/chain_light.rs @@ -20,15 +20,15 @@ use std::sync::Arc; use futures::{future::ready, FutureExt, TryFutureExt}; use rpc::futures::future::{result, Future, Either}; -use api::Subscriptions; -use client::{ +use sc_rpc_api::Subscriptions; +use sc_client::{ self, Client, light::{ fetcher::{Fetcher, RemoteBodyRequest}, blockchain::RemoteBlockchain, }, }; -use primitives::{H256, Blake2Hasher}; +use sp_core::{H256, Blake2Hasher}; use sp_runtime::{ generic::{BlockId, SignedBlock}, traits::{Block as BlockT}, @@ -68,8 +68,8 @@ impl> LightChain impl ChainBackend for LightChain where Block: BlockT + 'static, - B: client_api::backend::Backend + Send + Sync + 'static, - E: client::CallExecutor + Send + Sync + 'static, + B: sc_client_api::backend::Backend + Send + Sync + 'static, + E: sc_client::CallExecutor + Send + Sync + 'static, RA: Send + Sync + 'static, F: Fetcher + Send + Sync + 'static, { @@ -85,7 +85,7 @@ impl ChainBackend for LightChain: Send + Sync + 'static where Block: BlockT + 'static, - B: client_api::backend::Backend + Send + Sync + 'static, - E: client::CallExecutor + Send + Sync + 'static, + B: sc_client_api::backend::Backend + Send + Sync + 'static, + E: sc_client::CallExecutor + Send + Sync + 'static, { /// Get client reference. fn client(&self) -> &Arc>; @@ -156,8 +156,8 @@ pub fn new_full( ) -> Chain where Block: BlockT + 'static, - B: client_api::backend::Backend + Send + Sync + 'static, - E: client::CallExecutor + Send + Sync + 'static + Clone, + B: sc_client_api::backend::Backend + Send + Sync + 'static, + E: sc_client::CallExecutor + Send + Sync + 'static + Clone, RA: Send + Sync + 'static, { Chain { @@ -174,8 +174,8 @@ pub fn new_light>( ) -> Chain where Block: BlockT + 'static, - B: client_api::backend::Backend + Send + Sync + 'static, - E: client::CallExecutor + Send + Sync + 'static + Clone, + B: sc_client_api::backend::Backend + Send + Sync + 'static, + E: sc_client::CallExecutor + Send + Sync + 'static + Clone, RA: Send + Sync + 'static, F: Send + Sync + 'static, { @@ -196,8 +196,8 @@ pub struct Chain { impl ChainApi, Block::Hash, Block::Header, SignedBlock> for Chain where Block: BlockT + 'static, - B: client_api::backend::Backend + Send + Sync + 'static, - E: client::CallExecutor + Send + Sync + 'static, + B: sc_client_api::backend::Backend + Send + Sync + 'static, + E: sc_client::CallExecutor + Send + Sync + 'static, RA: Send + Sync + 'static { type Metadata = crate::metadata::Metadata; @@ -256,8 +256,8 @@ fn subscribe_headers( stream: F, ) where Block: BlockT + 'static, - B: client_api::backend::Backend + Send + Sync + 'static, - E: client::CallExecutor + Send + Sync + 'static, + B: sc_client_api::backend::Backend + Send + Sync + 'static, + E: sc_client::CallExecutor + Send + Sync + 'static, F: FnOnce() -> S, G: FnOnce() -> Block::Hash, ERR: ::std::fmt::Debug, diff --git a/substrate/client/rpc/src/chain/tests.rs b/substrate/client/rpc/src/chain/tests.rs index 4f7c1f65cf..c07ea2044c 100644 --- a/substrate/client/rpc/src/chain/tests.rs +++ b/substrate/client/rpc/src/chain/tests.rs @@ -16,19 +16,19 @@ use super::*; use assert_matches::assert_matches; -use test_client::{ +use substrate_test_runtime_client::{ prelude::*, - consensus::BlockOrigin, + sp_consensus::BlockOrigin, runtime::{H256, Block, Header}, }; -use rpc_primitives::list::ListOrValue; +use sp_rpc::list::ListOrValue; #[test] fn should_return_header() { let core = ::tokio::runtime::Runtime::new().unwrap(); let remote = core.executor(); - let client = Arc::new(test_client::new()); + let client = Arc::new(substrate_test_runtime_client::new()); let api = new_full(client.clone(), Subscriptions::new(Arc::new(remote))); assert_matches!( @@ -64,7 +64,7 @@ fn should_return_a_block() { let core = ::tokio::runtime::Runtime::new().unwrap(); let remote = core.executor(); - let client = Arc::new(test_client::new()); + let client = Arc::new(substrate_test_runtime_client::new()); let api = new_full(client.clone(), Subscriptions::new(Arc::new(remote))); let block = client.new_block(Default::default()).unwrap().bake().unwrap(); @@ -116,7 +116,7 @@ fn should_return_block_hash() { let core = ::tokio::runtime::Runtime::new().unwrap(); let remote = core.executor(); - let client = Arc::new(test_client::new()); + let client = Arc::new(substrate_test_runtime_client::new()); let api = new_full(client.clone(), Subscriptions::new(Arc::new(remote))); assert_matches!( @@ -147,7 +147,7 @@ fn should_return_block_hash() { Ok(ListOrValue::Value(Some(ref x))) if x == &block.hash() ); assert_matches!( - api.block_hash(Some(ListOrValue::Value(primitives::U256::from(1u64).into())).into()), + api.block_hash(Some(ListOrValue::Value(sp_core::U256::from(1u64).into())).into()), Ok(ListOrValue::Value(Some(ref x))) if x == &block.hash() ); @@ -163,7 +163,7 @@ fn should_return_finalized_hash() { let core = ::tokio::runtime::Runtime::new().unwrap(); let remote = core.executor(); - let client = Arc::new(test_client::new()); + let client = Arc::new(substrate_test_runtime_client::new()); let api = new_full(client.clone(), Subscriptions::new(Arc::new(remote))); assert_matches!( @@ -195,7 +195,7 @@ fn should_notify_about_latest_block() { let (subscriber, id, transport) = Subscriber::new_test("test"); { - let client = Arc::new(test_client::new()); + let client = Arc::new(substrate_test_runtime_client::new()); let api = new_full(client.clone(), Subscriptions::new(Arc::new(remote))); api.subscribe_new_heads(Default::default(), subscriber); @@ -224,7 +224,7 @@ fn should_notify_about_finalized_block() { let (subscriber, id, transport) = Subscriber::new_test("test"); { - let client = Arc::new(test_client::new()); + let client = Arc::new(substrate_test_runtime_client::new()); let api = new_full(client.clone(), Subscriptions::new(Arc::new(remote))); api.subscribe_finalized_heads(Default::default(), subscriber); diff --git a/substrate/client/rpc/src/lib.rs b/substrate/client/rpc/src/lib.rs index 1341acb63d..748a78f131 100644 --- a/substrate/client/rpc/src/lib.rs +++ b/substrate/client/rpc/src/lib.rs @@ -22,7 +22,7 @@ mod metadata; -pub use api::Subscriptions; +pub use sc_rpc_api::Subscriptions; pub use self::metadata::Metadata; pub use rpc::IoHandlerExtension as RpcExtension; diff --git a/substrate/client/rpc/src/state/mod.rs b/substrate/client/rpc/src/state/mod.rs index 53aabaf699..f0dce85932 100644 --- a/substrate/client/rpc/src/state/mod.rs +++ b/substrate/client/rpc/src/state/mod.rs @@ -26,13 +26,13 @@ use std::sync::Arc; use jsonrpc_pubsub::{typed::Subscriber, SubscriptionId}; use rpc::{Result as RpcResult, futures::Future}; -use api::Subscriptions; -use client::{Client, CallExecutor, light::{blockchain::RemoteBlockchain, fetcher::Fetcher}}; -use primitives::{ +use sc_rpc_api::Subscriptions; +use sc_client::{Client, CallExecutor, light::{blockchain::RemoteBlockchain, fetcher::Fetcher}}; +use sp_core::{ Blake2Hasher, Bytes, H256, storage::{StorageKey, StorageData, StorageChangeSet}, }; -use runtime_version::RuntimeVersion; +use sp_version::RuntimeVersion; use sp_runtime::{ traits::{Block as BlockT, ProvideRuntimeApi}, }; @@ -41,14 +41,14 @@ use sp_api::Metadata; use self::error::{Error, FutureResult}; -pub use api::state::*; +pub use sc_rpc_api::state::*; /// State backend API. pub trait StateBackend: Send + Sync + 'static where Block: BlockT + 'static, - B: client_api::backend::Backend + Send + Sync + 'static, - E: client::CallExecutor + Send + Sync + 'static, + B: sc_client_api::backend::Backend + Send + Sync + 'static, + E: sc_client::CallExecutor + Send + Sync + 'static, RA: Send + Sync + 'static, { /// Call runtime method at given block. @@ -187,7 +187,7 @@ pub fn new_full( ) -> State where Block: BlockT + 'static, - B: client_api::backend::Backend + Send + Sync + 'static, + B: sc_client_api::backend::Backend + Send + Sync + 'static, E: CallExecutor + Send + Sync + 'static + Clone, RA: Send + Sync + 'static, Client: ProvideRuntimeApi, @@ -208,7 +208,7 @@ pub fn new_light>( ) -> State where Block: BlockT + 'static, - B: client_api::backend::Backend + Send + Sync + 'static, + B: sc_client_api::backend::Backend + Send + Sync + 'static, E: CallExecutor + Send + Sync + 'static + Clone, RA: Send + Sync + 'static, F: Send + Sync + 'static, @@ -231,7 +231,7 @@ pub struct State { impl StateApi for State where Block: BlockT + 'static, - B: client_api::backend::Backend + Send + Sync + 'static, + B: sc_client_api::backend::Backend + Send + Sync + 'static, E: CallExecutor + Send + Sync + 'static + Clone, RA: Send + Sync + 'static, { diff --git a/substrate/client/rpc/src/state/state_full.rs b/substrate/client/rpc/src/state/state_full.rs index d5de8d6441..05bb64c36f 100644 --- a/substrate/client/rpc/src/state/state_full.rs +++ b/substrate/client/rpc/src/state/state_full.rs @@ -27,20 +27,20 @@ use rpc::{ futures::{stream, Future, Sink, Stream, future::result}, }; -use api::Subscriptions; -use client_api::backend::Backend; +use sc_rpc_api::Subscriptions; +use sc_client_api::backend::Backend; use sp_blockchain::{ Result as ClientResult, Error as ClientError, HeaderMetadata, CachedHeaderMetadata }; -use client::{ - Client, CallExecutor, BlockchainEvents, +use sc_client::{ + Client, CallExecutor, BlockchainEvents, }; -use primitives::{ +use sp_core::{ H256, Blake2Hasher, Bytes, storage::{well_known_keys, StorageKey, StorageData, StorageChangeSet, ChildInfo}, }; -use runtime_version::RuntimeVersion; -use state_machine::ExecutionStrategy; +use sp_version::RuntimeVersion; +use sp_state_machine::ExecutionStrategy; use sp_runtime::{ generic::BlockId, traits::{Block as BlockT, NumberFor, ProvideRuntimeApi, SaturatedConversion}, diff --git a/substrate/client/rpc/src/state/state_light.rs b/substrate/client/rpc/src/state/state_light.rs index d90ef02c3d..a00ce72945 100644 --- a/substrate/client/rpc/src/state/state_light.rs +++ b/substrate/client/rpc/src/state/state_light.rs @@ -38,21 +38,21 @@ use rpc::{ futures::stream::Stream, }; -use api::Subscriptions; -use client_api::backend::Backend; +use sc_rpc_api::Subscriptions; +use sc_client_api::backend::Backend; use sp_blockchain::Error as ClientError; -use client::{ +use sc_client::{ BlockchainEvents, Client, CallExecutor, light::{ blockchain::{future_header, RemoteBlockchain}, fetcher::{Fetcher, RemoteCallRequest, RemoteReadRequest, RemoteReadChildRequest}, }, }; -use primitives::{ +use sp_core::{ H256, Blake2Hasher, Bytes, OpaqueMetadata, storage::{StorageKey, StorageData, StorageChangeSet}, }; -use runtime_version::RuntimeVersion; +use sp_version::RuntimeVersion; use sp_runtime::{ generic::BlockId, traits::Block as BlockT, @@ -711,7 +711,7 @@ fn ignore_error(future: F) -> impl std::future::Future>>(sync: T) -> System { let _ = sender.send(peers); } Request::NetworkState(sender) => { - let _ = sender.send(serde_json::to_value(&network::NetworkState { + let _ = sender.send(serde_json::to_value(&sc_network::NetworkState { peer_id: String::new(), listened_addresses: Default::default(), external_addresses: Default::default(), @@ -211,8 +211,8 @@ fn system_peers() { fn system_network_state() { let res = wait_receiver(api(None).system_network_state()); assert_eq!( - serde_json::from_value::(res).unwrap(), - network::NetworkState { + serde_json::from_value::(res).unwrap(), + sc_network::NetworkState { peer_id: String::new(), listened_addresses: Default::default(), external_addresses: Default::default(), diff --git a/substrate/client/service/Cargo.toml b/substrate/client/service/Cargo.toml index fe01818d20..39b2fb2676 100644 --- a/substrate/client/service/Cargo.toml +++ b/substrate/client/service/Cargo.toml @@ -8,7 +8,7 @@ edition = "2018" default = ["rocksdb"] # The RocksDB feature activates the RocksDB database backend. If it is not activated, and you pass # a path to a database, an error will be produced at runtime. -rocksdb = ["client_db/kvdb-rocksdb"] +rocksdb = ["sc-client-db/kvdb-rocksdb"] wasmtime = [ "sc-executor/wasmtime", ] @@ -28,36 +28,36 @@ serde = "1.0.101" serde_json = "1.0.41" sysinfo = "0.9.5" target_info = "0.1.0" -keystore = { package = "sc-keystore", path = "../keystore" } +sc-keystore = { path = "../keystore" } sp-io = { path = "../../primitives/io" } sp-runtime = { path = "../../primitives/runtime" } sp-blockchain = { path = "../../primitives/blockchain" } -primitives = { package = "sp-core", path = "../../primitives/core" } -session = { package = "sp-session", path = "../../primitives/session" } -app-crypto = { package = "sp-application-crypto", path = "../../primitives/application-crypto" } -consensus_common = { package = "sp-consensus", path = "../../primitives/consensus/common" } -network = { package = "sc-network", path = "../network" } -chain-spec = { package = "sc-chain-spec", path = "../chain-spec" } -client-api = { package = "sc-client-api", path = "../api" } -client = { package = "sc-client", path = "../" } +sp-core = { path = "../../primitives/core" } +sp-session = { path = "../../primitives/session" } +sp-application-crypto = { path = "../../primitives/application-crypto" } +sp-consensus = { path = "../../primitives/consensus/common" } +sc-network = { path = "../network" } +sc-chain-spec = { path = "../chain-spec" } +sc-client-api = { path = "../api" } +sc-client = { path = "../" } sp-api = { path = "../../primitives/api" } -client_db = { package = "sc-client-db", path = "../db" } +sc-client-db = { path = "../db" } codec = { package = "parity-scale-codec", version = "1.0.0" } sc-executor = { path = "../executor" } -txpool = { package = "sc-transaction-pool", path = "../transaction-pool" } -sp-transaction-pool = { package = "sp-transaction-pool", path = "../../primitives/transaction-pool" } -rpc-servers = { package = "sc-rpc-server", path = "../rpc-servers" } -rpc = { package = "sc-rpc", path = "../rpc" } -tel = { package = "sc-telemetry", path = "../telemetry" } -offchain = { package = "sc-offchain", path = "../offchain" } +sc-transaction-pool = { path = "../transaction-pool" } +sp-transaction-pool = { path = "../../primitives/transaction-pool" } +sc-rpc-server = { path = "../rpc-servers" } +sc-rpc = { path = "../rpc" } +sc-telemetry = { path = "../telemetry" } +sc-offchain = { path = "../offchain" } parity-multiaddr = { package = "parity-multiaddr", version = "0.5.0" } grafana-data-source = { path = "../../utils/grafana-data-source" } -sc-tracing = { package = "sc-tracing", path = "../tracing" } +sc-tracing = { path = "../tracing" } tracing = "0.1.10" [dev-dependencies] substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } -babe-primitives = { package = "sp-consensus-babe", path = "../../primitives/consensus/babe" } +sp-consensus-babe = { path = "../../primitives/consensus/babe" } grandpa = { package = "sc-finality-grandpa", path = "../finality-grandpa" } grandpa-primitives = { package = "sp-finality-grandpa", path = "../../primitives/finality-grandpa" } tokio = "0.1" diff --git a/substrate/client/service/src/builder.rs b/substrate/client/service/src/builder.rs index 526983974a..713b873ff9 100644 --- a/substrate/client/service/src/builder.rs +++ b/substrate/client/service/src/builder.rs @@ -18,14 +18,14 @@ use crate::{Service, NetworkStatus, NetworkState, error::Error, DEFAULT_PROTOCOL use crate::{SpawnTaskHandle, start_rpc_servers, build_network_future, TransactionPoolAdapter}; use crate::status_sinks; use crate::config::{Configuration, DatabaseConfig}; -use client_api::{ +use sc_client_api::{ self, BlockchainEvents, backend::RemoteBackend, light::RemoteBlockchain, }; -use client::Client; -use chain_spec::{RuntimeGenesis, Extension}; -use consensus_common::import_queue::ImportQueue; +use sc_client::Client; +use sc_chain_spec::{RuntimeGenesis, Extension}; +use sp_consensus::import_queue::ImportQueue; use futures::{prelude::*, sync::mpsc}; use futures03::{ compat::Compat, @@ -33,13 +33,13 @@ use futures03::{ StreamExt as _, TryStreamExt as _, future::{select, Either} }; -use keystore::{Store as Keystore}; +use sc_keystore::{Store as Keystore}; use log::{info, warn, error}; -use network::{FinalityProofProvider, OnDemand, NetworkService, NetworkStateInfo, DhtEvent}; -use network::{config::BoxFinalityProofRequestBuilder, specialization::NetworkSpecialization}; +use sc_network::{FinalityProofProvider, OnDemand, NetworkService, NetworkStateInfo, DhtEvent}; +use sc_network::{config::BoxFinalityProofRequestBuilder, specialization::NetworkSpecialization}; use parking_lot::{Mutex, RwLock}; -use primitives::{Blake2Hasher, H256, Hasher}; -use rpc; +use sp_core::{Blake2Hasher, H256, Hasher}; +use sc_rpc; use sp_api::ConstructRuntimeApi; use sp_runtime::generic::BlockId; use sp_runtime::traits::{ @@ -51,7 +51,7 @@ use std::{ marker::PhantomData, sync::Arc, time::SystemTime }; use sysinfo::{get_current_pid, ProcessExt, System, SystemExt}; -use tel::{telemetry, SUBSTRATE_INFO}; +use sc_telemetry::{telemetry, SUBSTRATE_INFO}; use sp_transaction_pool::{TransactionPool, TransactionPoolMaintainer}; use sp_blockchain; use grafana_data_source::{self, record_metrics}; @@ -103,11 +103,11 @@ type TFullClient = Client< >; /// Full client backend type. -type TFullBackend = client_db::Backend; +type TFullBackend = sc_client_db::Backend; /// Full client call executor type. -type TFullCallExecutor = client::LocalCallExecutor< - client_db::Backend, +type TFullCallExecutor = sc_client::LocalCallExecutor< + sc_client_db::Backend, NativeExecutor, >; @@ -120,20 +120,20 @@ type TLightClient = Client< >; /// Light client backend type. -type TLightBackend = client::light::backend::Backend< - client_db::light::LightStorage, +type TLightBackend = sc_client::light::backend::Backend< + sc_client_db::light::LightStorage, Blake2Hasher, >; /// Light call executor type. -type TLightCallExecutor = client::light::call_executor::GenesisCallExecutor< - client::light::backend::Backend< - client_db::light::LightStorage, +type TLightCallExecutor = sc_client::light::call_executor::GenesisCallExecutor< + sc_client::light::backend::Backend< + sc_client_db::light::LightStorage, Blake2Hasher >, - client::LocalCallExecutor< - client::light::backend::Backend< - client_db::light::LightStorage, + sc_client::LocalCallExecutor< + sc_client::light::backend::Backend< + sc_client_db::light::LightStorage, Blake2Hasher >, NativeExecutor @@ -174,33 +174,33 @@ where TGen: RuntimeGenesis, TCSExt: Extension { let fork_blocks = config.chain_spec .extensions() - .get::>() + .get::>() .cloned() .unwrap_or_default(); let (client, backend) = { - let db_config = client_db::DatabaseSettings { + let db_config = sc_client_db::DatabaseSettings { state_cache_size: config.state_cache_size, state_cache_child_ratio: config.state_cache_child_ratio.map(|v| (v, 100)), pruning: config.pruning.clone(), source: match &config.database { DatabaseConfig::Path { path, cache_size } => - client_db::DatabaseSettingsSrc::Path { + sc_client_db::DatabaseSettingsSrc::Path { path: path.clone(), cache_size: cache_size.clone().map(|u| u as usize), }, DatabaseConfig::Custom(db) => - client_db::DatabaseSettingsSrc::Custom(db.clone()), + sc_client_db::DatabaseSettingsSrc::Custom(db.clone()), }, }; - let extensions = client_api::execution_extensions::ExecutionExtensions::new( + let extensions = sc_client_api::execution_extensions::ExecutionExtensions::new( config.execution_strategies.clone(), Some(keystore.clone()), ); - client_db::new_client( + sc_client_db::new_client( db_config, executor, &config.chain_spec, @@ -261,29 +261,29 @@ where TGen: RuntimeGenesis, TCSExt: Extension { ); let db_storage = { - let db_settings = client_db::DatabaseSettings { + let db_settings = sc_client_db::DatabaseSettings { state_cache_size: config.state_cache_size, state_cache_child_ratio: config.state_cache_child_ratio.map(|v| (v, 100)), pruning: config.pruning.clone(), source: match &config.database { DatabaseConfig::Path { path, cache_size } => - client_db::DatabaseSettingsSrc::Path { + sc_client_db::DatabaseSettingsSrc::Path { path: path.clone(), cache_size: cache_size.clone().map(|u| u as usize), }, DatabaseConfig::Custom(db) => - client_db::DatabaseSettingsSrc::Custom(db.clone()), + sc_client_db::DatabaseSettingsSrc::Custom(db.clone()), }, }; - client_db::light::LightStorage::new(db_settings)? + sc_client_db::light::LightStorage::new(db_settings)? }; - let light_blockchain = client::light::new_light_blockchain(db_storage); - let fetch_checker = Arc::new(client::light::new_fetch_checker(light_blockchain.clone(), executor.clone())); - let fetcher = Arc::new(network::OnDemand::new(fetch_checker)); - let backend = client::light::new_light_backend(light_blockchain); + let light_blockchain = sc_client::light::new_light_blockchain(db_storage); + let fetch_checker = Arc::new(sc_client::light::new_fetch_checker(light_blockchain.clone(), executor.clone())); + let fetcher = Arc::new(sc_network::OnDemand::new(fetch_checker)); + let backend = sc_client::light::new_light_backend(light_blockchain); let remote_blockchain = backend.remote_blockchain(); - let client = Arc::new(client::light::new_light( + let client = Arc::new(sc_client::light::new_light( backend.clone(), &config.chain_spec, executor, @@ -559,7 +559,7 @@ impl( self, transaction_pool_builder: impl FnOnce( - txpool::txpool::Options, + sc_transaction_pool::txpool::Options, Arc, Option, ) -> Result @@ -713,24 +713,24 @@ ServiceBuilder< Client: ProvideRuntimeApi, as ProvideRuntimeApi>::Api: sp_api::Metadata + - offchain::OffchainWorkerApi + + sc_offchain::OffchainWorkerApi + sp_transaction_pool::runtime_api::TaggedTransactionQueue + - session::SessionKeys + + sp_session::SessionKeys + sp_api::ApiExt, TBl: BlockT::Out>, TRtApi: ConstructRuntimeApi> + 'static + Send + Sync, TCfg: Default, TGen: RuntimeGenesis, TCSExt: Extension, - TBackend: 'static + client_api::backend::Backend + Send, - TExec: 'static + client::CallExecutor + Send + Sync + Clone, + TBackend: 'static + sc_client_api::backend::Backend + Send, + TExec: 'static + sc_client::CallExecutor + Send + Sync + Clone, TSc: Clone, TImpQu: 'static + ImportQueue, TNetP: NetworkSpecialization, TExPool: 'static + TransactionPool::Hash> + TransactionPoolMaintainer::Hash>, - TRpc: rpc::RpcExtension + Clone, + TRpc: sc_rpc::RpcExtension + Clone, { /// Builds the service. pub fn build(self) -> Result, NetworkService::Hash>, TExPool, - offchain::OffchainWorkers< + sc_offchain::OffchainWorkers< Client, TBackend::OffchainStorage, TBl @@ -764,7 +764,7 @@ ServiceBuilder< dht_event_tx, } = self; - session::generate_initial_session_keys( + sp_session::generate_initial_session_keys( client.clone(), &BlockId::Hash(client.info().chain.best_hash), config.dev_key_seed.clone().map(|s| vec![s]).unwrap_or_default(), @@ -812,13 +812,13 @@ ServiceBuilder< DEFAULT_PROTOCOL_ID } }.as_bytes(); - network::config::ProtocolId::from(protocol_id_full) + sc_network::config::ProtocolId::from(protocol_id_full) }; let block_announce_validator = - Box::new(consensus_common::block_validation::DefaultBlockAnnounceValidator::new(client.clone())); + Box::new(sp_consensus::block_validation::DefaultBlockAnnounceValidator::new(client.clone())); - let network_params = network::config::Params { + let network_params = sc_network::config::Params { roles: config.roles, network_config: config.network.clone(), chain: client.clone(), @@ -833,14 +833,14 @@ ServiceBuilder< }; let has_bootnodes = !network_params.network_config.boot_nodes.is_empty(); - let network_mut = network::NetworkWorker::new(network_params)?; + let network_mut = sc_network::NetworkWorker::new(network_params)?; let network = network_mut.service().clone(); let network_status_sinks = Arc::new(Mutex::new(status_sinks::StatusSinks::new())); let offchain_storage = backend.offchain_storage(); let offchain_workers = match (config.offchain_worker, offchain_storage) { (true, Some(db)) => { - Some(Arc::new(offchain::OffchainWorkers::new(client.clone(), db))) + Some(Arc::new(sc_offchain::OffchainWorkers::new(client.clone(), db))) }, (true, None) => { log::warn!("Offchain workers disabled, due to lack of offchain storage support in backend."); @@ -986,16 +986,16 @@ ServiceBuilder< // RPC let (system_rpc_tx, system_rpc_rx) = futures03::channel::mpsc::unbounded(); let gen_handler = || { - use rpc::{chain, state, author, system}; + use sc_rpc::{chain, state, author, system}; - let system_info = rpc::system::SystemInfo { + let system_info = sc_rpc::system::SystemInfo { chain_name: config.chain_spec.name().into(), impl_name: config.impl_name.into(), impl_version: config.impl_version.into(), properties: config.chain_spec.properties().clone(), }; - let subscriptions = rpc::Subscriptions::new(Arc::new(SpawnTaskHandle { + let subscriptions = sc_rpc::Subscriptions::new(Arc::new(SpawnTaskHandle { sender: to_spawn_tx.clone(), on_exit: exit.clone() })); @@ -1003,13 +1003,13 @@ ServiceBuilder< let (chain, state) = if let (Some(remote_backend), Some(on_demand)) = (remote_backend.as_ref(), on_demand.as_ref()) { // Light clients - let chain = rpc::chain::new_light( + let chain = sc_rpc::chain::new_light( client.clone(), subscriptions.clone(), remote_backend.clone(), on_demand.clone() ); - let state = rpc::state::new_light( + let state = sc_rpc::state::new_light( client.clone(), subscriptions.clone(), remote_backend.clone(), @@ -1019,12 +1019,12 @@ ServiceBuilder< } else { // Full nodes - let chain = rpc::chain::new_full(client.clone(), subscriptions.clone()); - let state = rpc::state::new_full(client.clone(), subscriptions.clone()); + let chain = sc_rpc::chain::new_full(client.clone(), subscriptions.clone()); + let state = sc_rpc::state::new_full(client.clone(), subscriptions.clone()); (chain, state) }; - let author = rpc::author::Author::new( + let author = sc_rpc::author::Author::new( client.clone(), transaction_pool.clone(), subscriptions, @@ -1032,7 +1032,7 @@ ServiceBuilder< ); let system = system::System::new(system_info, system_rpc_tx.clone()); - rpc_servers::rpc_handler(( + sc_rpc_server::rpc_handler(( state::StateApi::to_delegate(state), chain::ChainApi::to_delegate(chain), author::AuthorApi::to_delegate(author), @@ -1068,7 +1068,7 @@ ServiceBuilder< let version = version.clone(); let chain_name = config.chain_spec.name().to_owned(); let telemetry_connection_sinks_ = telemetry_connection_sinks.clone(); - let telemetry = tel::init_telemetry(tel::TelemetryConfig { + let telemetry = sc_telemetry::init_telemetry(sc_telemetry::TelemetryConfig { endpoints, wasm_external_transport: config.telemetry_external_transport.take(), }); @@ -1080,7 +1080,7 @@ ServiceBuilder< .compat() .for_each(move |event| { // Safe-guard in case we add more events in the future. - let tel::TelemetryEvent::Connected = event; + let sc_telemetry::TelemetryEvent::Connected = event; telemetry!(SUBSTRATE_INFO; "system.connected"; "name" => name.clone(), diff --git a/substrate/client/service/src/chain_ops.rs b/substrate/client/service/src/chain_ops.rs index 742167069a..fb62cd3399 100644 --- a/substrate/client/service/src/chain_ops.rs +++ b/substrate/client/service/src/chain_ops.rs @@ -19,27 +19,27 @@ use crate::error; use crate::builder::{ServiceBuilderCommand, ServiceBuilder}; use crate::error::Error; -use chain_spec::{ChainSpec, RuntimeGenesis, Extension}; +use sc_chain_spec::{ChainSpec, RuntimeGenesis, Extension}; use log::{warn, info}; use futures::{future, prelude::*}; use futures03::{ TryFutureExt as _, }; -use primitives::{Blake2Hasher, Hasher}; +use sp_core::{Blake2Hasher, Hasher}; use sp_runtime::traits::{ Block as BlockT, NumberFor, One, Zero, Header, SaturatedConversion }; use sp_runtime::generic::{BlockId, SignedBlock}; use codec::{Decode, Encode, IoReader}; -use client::Client; -use consensus_common::import_queue::{IncomingBlock, Link, BlockImportError, BlockImportResult, ImportQueue}; -use consensus_common::BlockOrigin; +use sc_client::Client; +use sp_consensus::import_queue::{IncomingBlock, Link, BlockImportError, BlockImportResult, ImportQueue}; +use sp_consensus::BlockOrigin; use std::{ io::{Read, Write, Seek}, }; -use network::message; +use sc_network::message; /// Build a chain spec json pub fn build_spec(spec: ChainSpec, raw: bool) -> error::Result where @@ -58,8 +58,8 @@ impl< TFchr, TSc, TImpQu, TFprb, TFpp, TNetP, TExPool, TRpc, Backend > where TBl: BlockT::Out>, - TBackend: 'static + client_api::backend::Backend + Send, - TExec: 'static + client::CallExecutor + Send + Sync + Clone, + TBackend: 'static + sc_client_api::backend::Backend + Send, + TExec: 'static + sc_client::CallExecutor + Send + Sync + Clone, TImpQu: 'static + ImportQueue, TRtApi: 'static + Send + Sync, { diff --git a/substrate/client/service/src/config.rs b/substrate/client/service/src/config.rs index 310d185b4d..0b5152e248 100644 --- a/substrate/client/service/src/config.rs +++ b/substrate/client/service/src/config.rs @@ -16,17 +16,17 @@ //! Service configuration. -pub use client::ExecutionStrategies; -pub use client_db::{kvdb::KeyValueDB, PruningMode}; -pub use network::config::{ExtTransport, NetworkConfiguration, Roles}; +pub use sc_client::ExecutionStrategies; +pub use sc_client_db::{kvdb::KeyValueDB, PruningMode}; +pub use sc_network::config::{ExtTransport, NetworkConfiguration, Roles}; pub use sc_executor::WasmExecutionMethod; use std::{path::PathBuf, net::SocketAddr, sync::Arc}; -pub use txpool::txpool::Options as TransactionPoolOptions; -use chain_spec::{ChainSpec, RuntimeGenesis, Extension, NoExtension}; -use primitives::crypto::Protected; +pub use sc_transaction_pool::txpool::Options as TransactionPoolOptions; +use sc_chain_spec::{ChainSpec, RuntimeGenesis, Extension, NoExtension}; +use sp_core::crypto::Protected; use target_info::Target; -use tel::TelemetryEndpoints; +use sc_telemetry::TelemetryEndpoints; /// Service configuration. #[derive(Clone)] diff --git a/substrate/client/service/src/error.rs b/substrate/client/service/src/error.rs index cd2fce6bde..d1dc827a38 100644 --- a/substrate/client/service/src/error.rs +++ b/substrate/client/service/src/error.rs @@ -16,9 +16,9 @@ //! Errors that can occur during the service operation. -use network; -use keystore; -use consensus_common; +use sc_network; +use sc_keystore; +use sp_consensus; use sp_blockchain; /// Service Result typedef. @@ -32,11 +32,11 @@ pub enum Error { /// IO error. Io(std::io::Error), /// Consensus error. - Consensus(consensus_common::Error), + Consensus(sp_consensus::Error), /// Network error. - Network(network::error::Error), + Network(sc_network::error::Error), /// Keystore error. - Keystore(keystore::Error), + Keystore(sc_keystore::Error), /// Best chain selection strategy is missing. #[display(fmt="Best chain selection strategy (SelectChain) is not provided.")] SelectChainRequired, diff --git a/substrate/client/service/src/lib.rs b/substrate/client/service/src/lib.rs index de6077e12f..d23e2a988c 100644 --- a/substrate/client/service/src/lib.rs +++ b/substrate/client/service/src/lib.rs @@ -35,35 +35,35 @@ use std::time::{Duration, Instant}; use futures::sync::mpsc; use parking_lot::Mutex; -use client::Client; +use sc_client::Client; use exit_future::Signal; use futures::prelude::*; use futures03::{ future::{ready, FutureExt as _, TryFutureExt as _}, stream::{StreamExt as _, TryStreamExt as _}, }; -use network::{ +use sc_network::{ NetworkService, NetworkState, specialization::NetworkSpecialization, Event, DhtEvent, PeerId, ReportHandle, }; use log::{log, warn, debug, error, Level}; use codec::{Encode, Decode}; -use primitives::{Blake2Hasher, H256}; +use sp_core::{Blake2Hasher, H256}; use sp_runtime::generic::BlockId; use sp_runtime::traits::{NumberFor, Block as BlockT}; pub use self::error::Error; pub use self::builder::{ServiceBuilder, ServiceBuilderCommand}; pub use config::{Configuration, Roles, PruningMode}; -pub use chain_spec::{ChainSpec, Properties, RuntimeGenesis, Extension as ChainSpecExtension}; +pub use sc_chain_spec::{ChainSpec, Properties, RuntimeGenesis, Extension as ChainSpecExtension}; pub use sp_transaction_pool::{TransactionPool, TransactionPoolMaintainer, InPoolTransaction, error::IntoPoolError}; -pub use txpool::txpool::Options as TransactionPoolOptions; -pub use client::FinalityNotifications; -pub use rpc::Metadata as RpcMetadata; +pub use sc_transaction_pool::txpool::Options as TransactionPoolOptions; +pub use sc_client::FinalityNotifications; +pub use sc_rpc::Metadata as RpcMetadata; #[doc(hidden)] pub use std::{ops::Deref, result::Result, sync::Arc}; #[doc(hidden)] -pub use network::{FinalityProofProvider, OnDemand, config::BoxFinalityProofRequestBuilder}; +pub use sc_network::{FinalityProofProvider, OnDemand, config::BoxFinalityProofRequestBuilder}; #[doc(hidden)] pub use futures::future::Executor; @@ -96,12 +96,12 @@ pub struct Service { /// If spawning a background task is not possible, we instead push the task into this `Vec`. /// The elements must then be polled manually. to_poll: Vec + Send>>, - rpc_handlers: rpc_servers::RpcHandler, + rpc_handlers: sc_rpc_server::RpcHandler, _rpc: Box, - _telemetry: Option, + _telemetry: Option, _telemetry_on_connect_sinks: Arc>>>, _offchain_workers: Option>, - keystore: keystore::KeyStorePtr, + keystore: sc_keystore::KeyStorePtr, marker: PhantomData, } @@ -145,13 +145,13 @@ pub trait AbstractService: 'static + Future + /// Type of block of this chain. type Block: BlockT; /// Backend storage for the client. - type Backend: 'static + client_api::backend::Backend; + type Backend: 'static + sc_client_api::backend::Backend; /// How to execute calls towards the runtime. - type CallExecutor: 'static + client::CallExecutor + Send + Sync + Clone; + type CallExecutor: 'static + sc_client::CallExecutor + Send + Sync + Clone; /// API that the runtime provides. type RuntimeApi: Send + Sync; /// Chain selection algorithm. - type SelectChain: consensus_common::SelectChain; + type SelectChain: sp_consensus::SelectChain; /// Transaction pool. type TransactionPool: TransactionPool + TransactionPoolMaintainer; @@ -162,7 +162,7 @@ pub trait AbstractService: 'static + Future + fn telemetry_on_connect_stream(&self) -> mpsc::UnboundedReceiver<()>; /// return a shared instance of Telemetry (if enabled) - fn telemetry(&self) -> Option; + fn telemetry(&self) -> Option; /// Spawns a task in the background that runs the future passed as parameter. fn spawn_task(&self, task: impl Future + Send + 'static); @@ -176,7 +176,7 @@ pub trait AbstractService: 'static + Future + fn spawn_task_handle(&self) -> SpawnTaskHandle; /// Returns the keystore that stores keys. - fn keystore(&self) -> keystore::KeyStorePtr; + fn keystore(&self) -> sc_keystore::KeyStorePtr; /// Starts an RPC query. /// @@ -190,7 +190,7 @@ pub trait AbstractService: 'static + Future + fn rpc_query(&self, mem: &RpcSession, request: &str) -> Box, Error = ()> + Send>; /// Get shared client instance. - fn client(&self) -> Arc>; + fn client(&self) -> Arc>; /// Get clone of select chain. fn select_chain(&self) -> Option; @@ -213,10 +213,10 @@ impl AbstractService NetworkService, TExPool, TOc> where TBl: BlockT, - TBackend: 'static + client_api::backend::Backend, - TExec: 'static + client::CallExecutor + Send + Sync + Clone, + TBackend: 'static + sc_client_api::backend::Backend, + TExec: 'static + sc_client::CallExecutor + Send + Sync + Clone, TRtApi: 'static + Send + Sync, - TSc: consensus_common::SelectChain + 'static + Clone + Send, + TSc: sp_consensus::SelectChain + 'static + Clone + Send, TExPool: 'static + TransactionPool + TransactionPoolMaintainer, TOc: 'static + Send + Sync, @@ -236,11 +236,11 @@ where stream } - fn telemetry(&self) -> Option { + fn telemetry(&self) -> Option { self._telemetry.as_ref().map(|t| t.clone()) } - fn keystore(&self) -> keystore::KeyStorePtr { + fn keystore(&self) -> sc_keystore::KeyStorePtr { self.keystore.clone() } @@ -276,7 +276,7 @@ where Box::new(self.rpc_handlers.handle_request(request, mem.metadata.clone())) } - fn client(&self) -> Arc> { + fn client(&self) -> Arc> { self.client.clone() } @@ -362,15 +362,15 @@ impl Executor, - S: network::specialization::NetworkSpecialization, - H: network::ExHashT + C: sc_client::BlockchainEvents, + S: sc_network::specialization::NetworkSpecialization, + H: sc_network::ExHashT > ( roles: Roles, - mut network: network::NetworkWorker, + mut network: sc_network::NetworkWorker, client: Arc, status_sinks: Arc, NetworkState)>>>, - rpc_rx: futures03::channel::mpsc::UnboundedReceiver>, + rpc_rx: futures03::channel::mpsc::UnboundedReceiver>, should_have_peers: bool, dht_event_tx: Option>, ) -> impl Future { @@ -406,16 +406,16 @@ fn build_network_future< // Poll the RPC requests and answer them. while let Ok(Async::Ready(Some(request))) = rpc_rx.poll() { match request { - rpc::system::Request::Health(sender) => { - let _ = sender.send(rpc::system::Health { + sc_rpc::system::Request::Health(sender) => { + let _ = sender.send(sc_rpc::system::Health { peers: network.peers_debug_info().len(), is_syncing: network.service().is_major_syncing(), should_have_peers, }); }, - rpc::system::Request::Peers(sender) => { + sc_rpc::system::Request::Peers(sender) => { let _ = sender.send(network.peers_debug_info().into_iter().map(|(peer_id, p)| - rpc::system::PeerInfo { + sc_rpc::system::PeerInfo { peer_id: peer_id.to_base58(), roles: format!("{:?}", p.roles), protocol_version: p.protocol_version, @@ -424,13 +424,13 @@ fn build_network_future< } ).collect()); } - rpc::system::Request::NetworkState(sender) => { + sc_rpc::system::Request::NetworkState(sender) => { if let Some(network_state) = serde_json::to_value(&network.network_state()).ok() { let _ = sender.send(network_state); } } - rpc::system::Request::NodeRoles(sender) => { - use rpc::system::NodeRole; + sc_rpc::system::Request::NodeRoles(sender) => { + use sc_rpc::system::NodeRole; let node_roles = (0 .. 8) .filter(|&bit_number| (roles.bits() >> bit_number) & 1 == 1) @@ -506,7 +506,7 @@ fn build_network_future< #[derive(Clone)] pub struct NetworkStatus { /// Current global sync state. - pub sync_state: network::SyncState, + pub sync_state: sc_network::SyncState, /// Target sync block number. pub best_seen_block: Option>, /// Number of peers participating in syncing. @@ -534,7 +534,7 @@ impl Drop for /// Starts RPC servers that run in their own thread, and returns an opaque object that keeps them alive. #[cfg(not(target_os = "unknown"))] -fn start_rpc_servers rpc_servers::RpcHandler>( +fn start_rpc_servers sc_rpc_server::RpcHandler>( config: &Configuration, mut gen_handler: H ) -> Result, error::Error> { @@ -559,11 +559,11 @@ fn start_rpc_servers rpc_servers::RpcHandler rpc_servers::RpcHandler rpc_servers::RpcHandler>( +fn start_rpc_servers sc_rpc_server::RpcHandler>( _: &Configuration, _: H ) -> Result, error::Error> { @@ -586,7 +586,7 @@ fn start_rpc_servers rpc_servers::RpcHandler network::TransactionPool for +impl sc_network::TransactionPool for TransactionPoolAdapter where - C: network::ClientHandle + Send + Sync, + C: sc_network::ClientHandle + Send + Sync, Pool: 'static + TransactionPool, B: BlockT, H: std::hash::Hash + Eq + sp_runtime::traits::Member + sp_runtime::traits::MaybeSerialize, @@ -653,8 +653,8 @@ where &self, report_handle: ReportHandle, who: PeerId, - reputation_change_good: network::ReputationChange, - reputation_change_bad: network::ReputationChange, + reputation_change_good: sc_network::ReputationChange, + reputation_change_bad: sc_network::ReputationChange, transaction: B::Extrinsic ) { if !self.imports_external_transactions { @@ -701,10 +701,10 @@ where mod tests { use super::*; use futures03::executor::block_on; - use consensus_common::SelectChain; + use sp_consensus::SelectChain; use sp_runtime::traits::BlindCheckable; use substrate_test_runtime_client::{prelude::*, runtime::{Extrinsic, Transfer}}; - use txpool::{BasicPool, FullChainApi}; + use sc_transaction_pool::{BasicPool, FullChainApi}; #[test] fn should_not_propagate_transactions_that_are_marked_as_such() { diff --git a/substrate/client/service/test/Cargo.toml b/substrate/client/service/test/Cargo.toml index 0a85fe0f6d..aa0d4b5414 100644 --- a/substrate/client/service/test/Cargo.toml +++ b/substrate/client/service/test/Cargo.toml @@ -12,10 +12,10 @@ log = "0.4.8" env_logger = "0.7.0" fdlimit = "0.1.1" futures03 = { package = "futures", version = "0.3.1", features = ["compat"] } -service = { package = "sc-service", path = "../../service", default-features = false } -network = { package = "sc-network", path = "../../network" } -consensus = { package = "sp-consensus", path = "../../../primitives/consensus/common" } -client = { package = "sc-client", path = "../../" } +sc-service = { path = "../../service", default-features = false } +sc-network = { path = "../../network" } +sp-consensus = { path = "../../../primitives/consensus/common" } +sc-client = { path = "../../" } sp-runtime = { path = "../../../primitives/runtime" } -primitives = { package = "sp-core", path = "../../../primitives/core" } -txpool-api = { package = "sp-transaction-pool", path = "../../../primitives/transaction-pool" } +sp-core = { path = "../../../primitives/core" } +sp-transaction-pool = { path = "../../../primitives/transaction-pool" } diff --git a/substrate/client/service/test/src/lib.rs b/substrate/client/service/test/src/lib.rs index e3b46c7720..e1eb919a6f 100644 --- a/substrate/client/service/test/src/lib.rs +++ b/substrate/client/service/test/src/lib.rs @@ -25,7 +25,7 @@ use futures::{Future, Stream, Poll}; use tempfile::TempDir; use tokio::{runtime::Runtime, prelude::FutureExt}; use tokio::timer::Interval; -use service::{ +use sc_service::{ AbstractService, ChainSpec, Configuration, @@ -33,10 +33,10 @@ use service::{ Roles, Error, }; -use network::{multiaddr, Multiaddr}; -use network::config::{NetworkConfiguration, TransportConfig, NodeKeyConfig, Secret, NonReservedPeerMode}; +use sc_network::{multiaddr, Multiaddr}; +use sc_network::config::{NetworkConfiguration, TransportConfig, NodeKeyConfig, Secret, NonReservedPeerMode}; use sp_runtime::{generic::BlockId, traits::Block as BlockT}; -use txpool_api::TransactionPool; +use sp_transaction_pool::TransactionPool; /// Maximum duration of single wait call. const MAX_WAIT_TIME: Duration = Duration::from_secs(60 * 3); @@ -72,9 +72,9 @@ impl From for SyncService { } } -impl> Future for SyncService { +impl> Future for SyncService { type Item = (); - type Error = service::Error; + type Error = sc_service::Error; fn poll(&mut self) -> Poll { self.0.lock().unwrap().poll() @@ -186,7 +186,7 @@ fn node_config ( chain_spec: (*spec).clone(), custom: Default::default(), name: format!("Node {}", index), - wasm_method: service::config::WasmExecutionMethod::Interpreted, + wasm_method: sc_service::config::WasmExecutionMethod::Interpreted, execution_strategies: Default::default(), rpc_http: None, rpc_ws: None, diff --git a/substrate/client/src/call_executor.rs b/substrate/client/src/call_executor.rs index e069885047..3115c78103 100644 --- a/substrate/client/src/call_executor.rs +++ b/substrate/client/src/call_executor.rs @@ -19,19 +19,19 @@ use codec::{Encode, Decode}; use sp_runtime::{ generic::BlockId, traits::Block as BlockT, traits::NumberFor, }; -use state_machine::{ +use sp_state_machine::{ self, OverlayedChanges, Ext, ExecutionManager, StateMachine, ExecutionStrategy, backend::Backend as _, ChangesTrieTransaction, StorageProof, }; -use executor::{RuntimeVersion, RuntimeInfo, NativeVersion}; -use externalities::Extensions; +use sc_executor::{RuntimeVersion, RuntimeInfo, NativeVersion}; +use sp_externalities::Extensions; use hash_db::Hasher; -use primitives::{ +use sp_core::{ H256, Blake2Hasher, NativeOrEncoded, NeverNativeValue, traits::CodeExecutor, }; use sp_api::{ProofRecorder, InitializeBlock}; -use client_api::{backend, call_executor::CallExecutor}; +use sc_client_api::{backend, call_executor::CallExecutor}; /// Call executor that executes methods locally, querying all required /// data from local backend. @@ -138,11 +138,11 @@ impl CallExecutor for LocalCallExecutor Some(recorder) => { let trie_state = state.as_trie_backend() .ok_or_else(|| - Box::new(state_machine::ExecutionError::UnableToGenerateProof) - as Box + Box::new(sp_state_machine::ExecutionError::UnableToGenerateProof) + as Box )?; - let backend = state_machine::ProvingBackend::new_with_recorder( + let backend = sp_state_machine::ProvingBackend::new_with_recorder( trie_state, recorder.clone() ); @@ -206,7 +206,7 @@ impl CallExecutor for LocalCallExecutor } fn call_at_state< - S: state_machine::Backend, + S: sp_state_machine::Backend, F: FnOnce( Result, Self::Error>, Result, Self::Error>, @@ -247,14 +247,14 @@ impl CallExecutor for LocalCallExecutor .map_err(Into::into) } - fn prove_at_trie_state>( + fn prove_at_trie_state>( &self, - trie_state: &state_machine::TrieBackend, + trie_state: &sp_state_machine::TrieBackend, overlay: &mut OverlayedChanges, method: &str, call_data: &[u8] ) -> Result<(Vec, StorageProof), sp_blockchain::Error> { - state_machine::prove_execution_on_trie_backend( + sp_state_machine::prove_execution_on_trie_backend( trie_state, overlay, &self.executor, @@ -269,20 +269,20 @@ impl CallExecutor for LocalCallExecutor } } -impl runtime_version::GetRuntimeVersion for LocalCallExecutor +impl sp_version::GetRuntimeVersion for LocalCallExecutor where B: backend::Backend, E: CodeExecutor + RuntimeInfo, Block: BlockT, { - fn native_version(&self) -> &runtime_version::NativeVersion { + fn native_version(&self) -> &sp_version::NativeVersion { self.executor.native_version() } fn runtime_version( &self, at: &BlockId, - ) -> Result { + ) -> Result { CallExecutor::runtime_version(self, at).map_err(|e| format!("{:?}", e)) } } diff --git a/substrate/client/src/cht.rs b/substrate/client/src/cht.rs index 389560223a..7eeea10bb3 100644 --- a/substrate/client/src/cht.rs +++ b/substrate/client/src/cht.rs @@ -25,12 +25,12 @@ use hash_db; use codec::Encode; -use trie; +use sp_trie; -use primitives::{H256, convert_hash}; +use sp_core::{H256, convert_hash}; use sp_runtime::traits::{Header as HeaderT, SimpleArithmetic, Zero, One}; -use state_machine::backend::InMemory as InMemoryState; -use state_machine::{MemoryDB, TrieBackend, Backend as StateBackend, StorageProof, +use sp_state_machine::backend::InMemory as InMemoryState; +use sp_state_machine::{MemoryDB, TrieBackend, Backend as StateBackend, StorageProof, prove_read_on_trie_backend, read_proof_check, read_proof_check_on_proving_backend}; use sp_blockchain::{Error as ClientError, Result as ClientResult}; @@ -76,8 +76,8 @@ pub fn compute_root( Hasher::Out: Ord, I: IntoIterator>>, { - use trie::TrieConfiguration; - Ok(trie::trie_types::Layout::::trie_root( + use sp_trie::TrieConfiguration; + Ok(sp_trie::trie_types::Layout::::trie_root( build_pairs::(cht_size, cht_num, hashes)? )) } @@ -317,8 +317,8 @@ pub fn decode_cht_value(value: &[u8]) -> Option { #[cfg(test)] mod tests { - use primitives::{Blake2Hasher}; - use test_client::runtime::Header; + use sp_core::{Blake2Hasher}; + use substrate_test_runtime_client::runtime::Header; use super::*; #[test] diff --git a/substrate/client/src/client.rs b/substrate/client/src/client.rs index fe3dfbead3..a0fc940d24 100644 --- a/substrate/client/src/client.rs +++ b/substrate/client/src/client.rs @@ -25,7 +25,7 @@ use futures::channel::mpsc; use parking_lot::{Mutex, RwLock}; use codec::{Encode, Decode}; use hash_db::{Hasher, Prefix}; -use primitives::{ +use sp_core::{ Blake2Hasher, H256, ChangesTrieConfiguration, convert_hash, NeverNativeValue, ExecutionContext, NativeOrEncoded, storage::{StorageKey, StorageData, well_known_keys, ChildInfo}, @@ -40,14 +40,14 @@ use sp_runtime::{ ApiRef, ProvideRuntimeApi, SaturatedConversion, One, DigestFor, }, }; -use state_machine::{ +use sp_state_machine::{ DBValue, Backend as StateBackend, ChangesTrieAnchorBlockId, ExecutionStrategy, ExecutionManager, prove_read, prove_child_read, ChangesTrieRootsStorage, ChangesTrieStorage, ChangesTrieTransaction, ChangesTrieConfigurationRange, key_changes, key_changes_proof, OverlayedChanges, BackendTrustLevel, StorageProof, merge_storage_proofs, }; -use executor::{RuntimeVersion, RuntimeInfo}; -use consensus::{ +use sc_executor::{RuntimeVersion, RuntimeInfo}; +use sp_consensus::{ Error as ConsensusError, BlockStatus, BlockImportParams, BlockCheckParams, ImportResult, BlockOrigin, ForkChoiceStrategy, SelectChain, self, @@ -60,9 +60,9 @@ use sp_blockchain::{self as blockchain, }; use sp_api::{CallRuntimeAt, ConstructRuntimeApi, Core as CoreApi, ProofRecorder, InitializeBlock}; -use block_builder::BlockBuilderApi; +use sc_block_builder::BlockBuilderApi; -pub use client_api::{ +pub use sc_client_api::{ backend::{ self, BlockImportOperation, PrunableStateChangesTrieStorage, ClientImportOperation, Finalizer, ImportSummary, NewBlockState, @@ -88,7 +88,7 @@ type StorageUpdate = < < >::BlockImportOperation as BlockImportOperation - >::State as state_machine::Backend>::Transaction; + >::State as sp_state_machine::Backend>::Transaction; type ChangesUpdate = ChangesTrieTransaction>; /// Substrate Client @@ -144,7 +144,7 @@ impl PrePostHeader { pub fn new_in_mem( executor: E, genesis_storage: S, - keystore: Option, + keystore: Option, ) -> sp_blockchain::Result, LocalCallExecutor, E>, @@ -164,7 +164,7 @@ pub fn new_with_backend( backend: Arc, executor: E, build_genesis_storage: S, - keystore: Option, + keystore: Option, ) -> sp_blockchain::Result, Block, RA>> where E: CodeExecutor + RuntimeInfo, @@ -525,7 +525,7 @@ impl Client where } impl<'a, Block: BlockT> ChangesTrieStorage> for AccessedRootsRecorder<'a, Block> { - fn as_roots_storage(&self) -> &dyn state_machine::ChangesTrieRootsStorage> { + fn as_roots_storage(&self) -> &dyn sp_state_machine::ChangesTrieRootsStorage> { self } @@ -649,14 +649,14 @@ impl Client where pub fn new_block( &self, inherent_digests: DigestFor, - ) -> sp_blockchain::Result> where + ) -> sp_blockchain::Result> where E: Clone + Send + Sync, RA: Send + Sync, Self: ProvideRuntimeApi, ::Api: BlockBuilderApi { let info = self.info(); - block_builder::BlockBuilder::new( + sc_block_builder::BlockBuilder::new( self, info.chain.best_hash, info.chain.best_number, @@ -670,13 +670,13 @@ impl Client where &self, parent: &BlockId, inherent_digests: DigestFor, - ) -> sp_blockchain::Result> where + ) -> sp_blockchain::Result> where E: Clone + Send + Sync, RA: Send + Sync, Self: ProvideRuntimeApi, ::Api: BlockBuilderApi { - block_builder::BlockBuilder::new( + sc_block_builder::BlockBuilder::new( self, self.expect_block_hash_from_id(parent)?, self.expect_block_number_from_id(parent)?, @@ -694,13 +694,13 @@ impl Client where &self, parent: &BlockId, inherent_digests: DigestFor, - ) -> sp_blockchain::Result> where + ) -> sp_blockchain::Result> where E: Clone + Send + Sync, RA: Send + Sync, Self: ProvideRuntimeApi, ::Api: BlockBuilderApi { - block_builder::BlockBuilder::new( + sc_block_builder::BlockBuilder::new( self, self.expect_block_hash_from_id(parent)?, self.expect_block_number_from_id(parent)?, @@ -1432,7 +1432,7 @@ impl CallRuntimeAt for Client where /// NOTE: only use this implementation when you are sure there are NO consensus-level BlockImport /// objects. Otherwise, importing blocks directly into the client would be bypassing /// important verification work. -impl<'a, B, E, Block, RA> consensus::BlockImport for &'a Client where +impl<'a, B, E, Block, RA> sp_consensus::BlockImport for &'a Client where B: backend::Backend, E: CallExecutor + Clone + Send + Sync, Block: BlockT, @@ -1507,7 +1507,7 @@ impl<'a, B, E, Block, RA> consensus::BlockImport for &'a Client consensus::BlockImport for Client where +impl sp_consensus::BlockImport for Client where B: backend::Backend, E: CallExecutor + Clone + Send + Sync, Block: BlockT, @@ -1758,7 +1758,7 @@ where ) } -impl consensus::block_validation::Chain for Client +impl sp_consensus::block_validation::Chain for Client where BE: backend::Backend, E: CallExecutor, @@ -1773,13 +1773,13 @@ impl consensus::block_validation::Chain for Client ( - test_client::client::Client, + substrate_test_runtime_client::sc_client::Client, Vec, Vec<(u64, u64, Vec, Vec<(u64, u32)>)>, ) { @@ -1858,7 +1858,7 @@ pub(crate) mod tests { #[test] fn client_initializes_from_genesis_ok() { - let client = test_client::new(); + let client = substrate_test_runtime_client::new(); assert_eq!( client.runtime_api().balance_of( @@ -1878,7 +1878,7 @@ pub(crate) mod tests { #[test] fn block_builder_works_with_no_transactions() { - let client = test_client::new(); + let client = substrate_test_runtime_client::new(); let builder = client.new_block(Default::default()).unwrap(); @@ -1889,7 +1889,7 @@ pub(crate) mod tests { #[test] fn block_builder_works_with_transactions() { - let client = test_client::new(); + let client = substrate_test_runtime_client::new(); let mut builder = client.new_block(Default::default()).unwrap(); @@ -1925,7 +1925,7 @@ pub(crate) mod tests { #[test] fn block_builder_does_not_include_invalid() { - let client = test_client::new(); + let client = substrate_test_runtime_client::new(); let mut builder = client.new_block(Default::default()).unwrap(); @@ -1987,7 +1987,7 @@ pub(crate) mod tests { fn uncles_with_only_ancestors() { // block tree: // G -> A1 -> A2 - let client = test_client::new(); + let client = substrate_test_runtime_client::new(); // G -> A1 let a1 = client.new_block(Default::default()).unwrap().bake().unwrap(); @@ -2007,7 +2007,7 @@ pub(crate) mod tests { // A1 -> B2 -> B3 -> B4 // B2 -> C3 // A1 -> D2 - let client = test_client::new(); + let client = substrate_test_runtime_client::new(); // G -> A1 let a1 = client.new_block(Default::default()).unwrap().bake().unwrap(); @@ -2444,7 +2444,7 @@ pub(crate) mod tests { #[test] fn import_with_justification() { - let client = test_client::new(); + let client = substrate_test_runtime_client::new(); // G -> A1 let a1 = client.new_block(Default::default()).unwrap().bake().unwrap(); @@ -2483,7 +2483,7 @@ pub(crate) mod tests { #[test] fn importing_diverged_finalized_block_should_trigger_reorg() { - let client = test_client::new(); + let client = substrate_test_runtime_client::new(); // G -> A1 -> A2 // \ @@ -2599,7 +2599,7 @@ pub(crate) mod tests { #[test] fn get_header_by_block_number_doesnt_panic() { - let client = test_client::new(); + let client = substrate_test_runtime_client::new(); // backend uses u32 for block numbers, make sure we don't panic when // trying to convert @@ -2610,7 +2610,7 @@ pub(crate) mod tests { #[test] fn state_reverted_on_reorg() { let _ = env_logger::try_init(); - let client = test_client::new(); + let client = substrate_test_runtime_client::new(); let current_balance = || client.runtime_api().balance_of( diff --git a/substrate/client/src/genesis.rs b/substrate/client/src/genesis.rs index a080a87cf4..506771217d 100644 --- a/substrate/client/src/genesis.rs +++ b/substrate/client/src/genesis.rs @@ -43,27 +43,27 @@ pub fn construct_genesis_block< #[cfg(test)] mod tests { use codec::{Encode, Decode, Joiner}; - use executor::native_executor_instance; - use state_machine::{ + use sc_executor::native_executor_instance; + use sp_state_machine::{ StateMachine, OverlayedChanges, ExecutionStrategy, InMemoryChangesTrieStorage, }; - use state_machine::backend::InMemory; - use test_client::{ + use sp_state_machine::backend::InMemory; + use substrate_test_runtime_client::{ runtime::genesismap::{GenesisConfig, insert_genesis_block}, runtime::{Hash, Transfer, Block, BlockNumber, Header, Digest}, AccountKeyring, Sr25519Keyring, }; - use primitives::Blake2Hasher; + use sp_core::Blake2Hasher; use hex_literal::*; native_executor_instance!( Executor, - test_client::runtime::api::dispatch, - test_client::runtime::native_version + substrate_test_runtime_client::runtime::api::dispatch, + substrate_test_runtime_client::runtime::native_version ); - fn executor() -> executor::NativeExecutor { - executor::NativeExecutor::new(executor::WasmExecutionMethod::Interpreted, None) + fn executor() -> sc_executor::NativeExecutor { + sc_executor::NativeExecutor::new(sc_executor::WasmExecutionMethod::Interpreted, None) } fn construct_block( @@ -73,7 +73,7 @@ mod tests { state_root: Hash, txs: Vec ) -> (Vec, Hash) { - use trie::{TrieConfiguration, trie_types::Layout}; + use sp_trie::{TrieConfiguration, trie_types::Layout}; let transactions = txs.into_iter().map(|tx| tx.into_signed_tx()).collect::>(); diff --git a/substrate/client/src/in_mem.rs b/substrate/client/src/in_mem.rs index 85bdd954c8..58e88934f3 100644 --- a/substrate/client/src/in_mem.rs +++ b/substrate/client/src/in_mem.rs @@ -19,20 +19,20 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; use parking_lot::RwLock; -use primitives::{ChangesTrieConfiguration, storage::well_known_keys}; -use primitives::offchain::storage::{ +use sp_core::{ChangesTrieConfiguration, storage::well_known_keys}; +use sp_core::offchain::storage::{ InMemOffchainStorage as OffchainStorage }; use sp_runtime::generic::{BlockId, DigestItem}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT, Zero, NumberFor}; use sp_runtime::{Justification, Storage}; -use state_machine::backend::{Backend as StateBackend, InMemory}; -use state_machine::{self, InMemoryChangesTrieStorage, ChangesTrieAnchorBlockId, ChangesTrieTransaction}; +use sp_state_machine::backend::{Backend as StateBackend, InMemory}; +use sp_state_machine::{self, InMemoryChangesTrieStorage, ChangesTrieAnchorBlockId, ChangesTrieTransaction}; use hash_db::{Hasher, Prefix}; -use trie::MemoryDB; +use sp_trie::MemoryDB; use sp_blockchain::{CachedHeaderMetadata, HeaderMetadata}; -use client_api::{ +use sc_client_api::{ backend::{self, NewBlockState, StorageCollection, ChildStorageCollection}, blockchain::{ self, BlockStatus, HeaderBackend, well_known_cache_keys::Id as CacheKeyId @@ -398,7 +398,7 @@ impl backend::AuxStore for Blockchain { } } -impl client_api::light::Storage for Blockchain +impl sc_client_api::light::Storage for Blockchain where Block::Hash: From<[u8; 32]>, { @@ -752,7 +752,7 @@ impl backend::PrunableStateChangesTrieStorage state_machine::ChangesTrieRootsStorage> for ChangesTrieStorage +impl sp_state_machine::ChangesTrieRootsStorage> for ChangesTrieStorage where Block: BlockT, H: Hasher, @@ -760,7 +760,7 @@ impl state_machine::ChangesTrieRootsStorage> for C fn build_anchor( &self, _hash: H::Out, - ) -> Result>, String> { + ) -> Result>, String> { Err("Dummy implementation".into()) } @@ -773,12 +773,12 @@ impl state_machine::ChangesTrieRootsStorage> for C } } -impl state_machine::ChangesTrieStorage> for ChangesTrieStorage +impl sp_state_machine::ChangesTrieStorage> for ChangesTrieStorage where Block: BlockT, H: Hasher, { - fn as_roots_storage(&self) -> &dyn state_machine::ChangesTrieRootsStorage> { + fn as_roots_storage(&self) -> &dyn sp_state_machine::ChangesTrieRootsStorage> { self } @@ -790,7 +790,7 @@ impl state_machine::ChangesTrieStorage> for Change false } - fn get(&self, key: &H::Out, prefix: Prefix) -> Result, String> { + fn get(&self, key: &H::Out, prefix: Prefix) -> Result, String> { self.0.get(key, prefix) } } @@ -810,25 +810,25 @@ pub fn check_genesis_storage(storage: &Storage) -> sp_blockchain::Result<()> { #[cfg(test)] mod tests { - use primitives::offchain::{OffchainStorage, storage::InMemOffchainStorage}; + use sp_core::offchain::{OffchainStorage, storage::InMemOffchainStorage}; use std::sync::Arc; - use test_client; - use primitives::Blake2Hasher; + use substrate_test_runtime_client; + use sp_core::Blake2Hasher; - type TestBackend = test_client::client::in_mem::Backend; + type TestBackend = substrate_test_runtime_client::sc_client::in_mem::Backend; #[test] fn test_leaves_with_complex_block_tree() { let backend = Arc::new(TestBackend::new()); - test_client::trait_tests::test_leaves_for_backend(backend); + substrate_test_runtime_client::trait_tests::test_leaves_for_backend(backend); } #[test] fn test_blockchain_query_by_number_gets_canonical() { let backend = Arc::new(TestBackend::new()); - test_client::trait_tests::test_blockchain_query_by_number_gets_canonical(backend); + substrate_test_runtime_client::trait_tests::test_blockchain_query_by_number_gets_canonical(backend); } #[test] diff --git a/substrate/client/src/lib.rs b/substrate/client/src/lib.rs index 364733f1a4..70d1f28659 100644 --- a/substrate/client/src/lib.rs +++ b/substrate/client/src/lib.rs @@ -47,15 +47,15 @@ //! ``` //! use std::sync::Arc; //! use sc_client::{Client, in_mem::Backend, LocalCallExecutor}; -//! use primitives::Blake2Hasher; +//! use sp_core::Blake2Hasher; //! use sp_runtime::Storage; -//! use executor::{NativeExecutor, WasmExecutionMethod}; +//! use sc_executor::{NativeExecutor, WasmExecutionMethod}; //! //! // In this example, we're using the `Block` and `RuntimeApi` types from the //! // `substrate-test-runtime-client` crate. These types are automatically generated when //! // compiling a runtime. In a typical use-case, these types would have been to be generated //! // from your runtime. -//! use test_client::{LocalExecutor, runtime::Block, runtime::RuntimeApi}; +//! use substrate_test_runtime_client::{LocalExecutor, runtime::Block, runtime::RuntimeApi}; //! //! let backend = Arc::new(Backend::::new()); //! let client = Client::<_, _, _, RuntimeApi>::new( @@ -83,7 +83,7 @@ pub mod leaves; mod call_executor; mod client; -pub use client_api::{ +pub use sc_client_api::{ blockchain, blockchain::well_known_cache_keys, blockchain::Info as ChainInfo, @@ -102,4 +102,4 @@ pub use crate::{ }, leaves::LeafSet, }; -pub use state_machine::{ExecutionStrategy, StorageProof}; +pub use sp_state_machine::{ExecutionStrategy, StorageProof}; diff --git a/substrate/client/src/light/backend.rs b/substrate/client/src/light/backend.rs index 5f770394fc..f946d91b3c 100644 --- a/substrate/client/src/light/backend.rs +++ b/substrate/client/src/light/backend.rs @@ -21,16 +21,16 @@ use std::collections::HashMap; use std::sync::Arc; use parking_lot::RwLock; -use primitives::storage::{ChildInfo, OwnedChildInfo}; -use state_machine::{ +use sp_core::storage::{ChildInfo, OwnedChildInfo}; +use sp_core::offchain::storage::InMemOffchainStorage; +use sp_state_machine::{ Backend as StateBackend, TrieBackend, backend::InMemory as InMemoryState, ChangesTrieTransaction }; -use primitives::offchain::storage::InMemOffchainStorage; use sp_runtime::{generic::BlockId, Justification, Storage}; use sp_runtime::traits::{Block as BlockT, NumberFor, Zero, Header}; use crate::in_mem::{self, check_genesis_storage}; use sp_blockchain::{ Error as ClientError, Result as ClientResult }; -use client_api::{ +use sc_client_api::{ backend::{ AuxStore, Backend as ClientBackend, BlockImportOperation, RemoteBackend, NewBlockState, StorageCollection, ChildStorageCollection, @@ -42,7 +42,7 @@ use client_api::{ }; use crate::light::blockchain::Blockchain; use hash_db::Hasher; -use trie::MemoryDB; +use sp_trie::MemoryDB; const IN_MEMORY_EXPECT_PROOF: &str = "InMemory state backend has Void error type and always succeeds; qed"; @@ -487,16 +487,16 @@ impl StateBackend for GenesisOrUnavailableState #[cfg(test)] mod tests { - use primitives::Blake2Hasher; - use test_client::{self, runtime::Block}; - use client_api::backend::NewBlockState; + use sp_core::Blake2Hasher; + use substrate_test_runtime_client::{self, runtime::Block}; + use sc_client_api::backend::NewBlockState; use crate::light::blockchain::tests::{DummyBlockchain, DummyStorage}; use super::*; #[test] fn local_state_is_created_when_genesis_state_is_available() { let def = Default::default(); - let header0 = test_client::runtime::Header::new(0, def, def, def, Default::default()); + let header0 = substrate_test_runtime_client::runtime::Header::new(0, def, def, def, Default::default()); let backend: Backend<_, Blake2Hasher> = Backend::new(Arc::new(DummyBlockchain::new(DummyStorage::new()))); let mut op = backend.begin_operation().unwrap(); diff --git a/substrate/client/src/light/blockchain.rs b/substrate/client/src/light/blockchain.rs index 03ee035031..54cb8d9b09 100644 --- a/substrate/client/src/light/blockchain.rs +++ b/substrate/client/src/light/blockchain.rs @@ -27,7 +27,7 @@ use sp_blockchain::{ HeaderMetadata, CachedHeaderMetadata, Error as ClientError, Result as ClientResult, }; -pub use client_api::{ +pub use sc_client_api::{ backend::{ AuxStore, NewBlockState }, @@ -195,8 +195,8 @@ pub fn future_header>( pub mod tests { use std::collections::HashMap; use parking_lot::Mutex; - use test_client::runtime::{Hash, Block, Header}; - use client_api::blockchain::Info; + use substrate_test_runtime_client::runtime::{Hash, Block, Header}; + use sc_client_api::blockchain::Info; use super::*; pub type DummyBlockchain = Blockchain; diff --git a/substrate/client/src/light/call_executor.rs b/substrate/client/src/light/call_executor.rs index 8571c331b2..656271b932 100644 --- a/substrate/client/src/light/call_executor.rs +++ b/substrate/client/src/light/call_executor.rs @@ -21,15 +21,15 @@ use std::{ }; use codec::{Encode, Decode}; -use primitives::{ +use sp_core::{ H256, Blake2Hasher, convert_hash, NativeOrEncoded, traits::CodeExecutor, }; use sp_runtime::{ generic::BlockId, traits::{One, Block as BlockT, Header as HeaderT, NumberFor}, }; -use externalities::Extensions; -use state_machine::{ +use sp_externalities::Extensions; +use sp_state_machine::{ self, Backend as StateBackend, OverlayedChanges, ExecutionStrategy, create_proof_check_backend, execution_proof_check_on_trie_backend, ExecutionManager, ChangesTrieTransaction, StorageProof, merge_storage_proofs, @@ -40,12 +40,12 @@ use sp_api::{ProofRecorder, InitializeBlock}; use sp_blockchain::{Error as ClientError, Result as ClientResult}; -use client_api::{ +use sc_client_api::{ backend::RemoteBackend, light::RemoteCallRequest, call_executor::CallExecutor }; -use executor::{RuntimeVersion, NativeVersion}; +use sc_executor::{RuntimeVersion, NativeVersion}; /// Call executor that is able to execute calls only on genesis state. /// @@ -176,9 +176,9 @@ impl CallExecutor for Err(ClientError::NotAvailableOnLightClient) } - fn prove_at_trie_state>( + fn prove_at_trie_state>( &self, - _state: &state_machine::TrieBackend, + _state: &sp_state_machine::TrieBackend, _changes: &mut OverlayedChanges, _method: &str, _call_data: &[u8] @@ -208,7 +208,7 @@ pub fn prove_execution( E: CallExecutor, { let trie_state = state.as_trie_backend() - .ok_or_else(|| Box::new(state_machine::ExecutionError::UnableToGenerateProof) as Box)?; + .ok_or_else(|| Box::new(sp_state_machine::ExecutionError::UnableToGenerateProof) as Box)?; // prepare execution environment + record preparation proof let mut changes = Default::default(); @@ -293,11 +293,11 @@ fn check_execution_proof_with_make_header, + S: sp_state_machine::Backend, F: FnOnce( Result, Self::Error>, Result, Self::Error> @@ -372,9 +372,9 @@ mod tests { unreachable!() } - fn prove_at_trie_state>( + fn prove_at_trie_state>( &self, - _trie_state: &state_machine::TrieBackend, + _trie_state: &sp_state_machine::TrieBackend, _overlay: &mut OverlayedChanges, _method: &str, _call_data: &[u8] @@ -387,7 +387,7 @@ mod tests { } } - fn local_executor() -> NativeExecutor { + fn local_executor() -> NativeExecutor { NativeExecutor::new(WasmExecutionMethod::Interpreted, None) } @@ -408,7 +408,7 @@ mod tests { let local_result = check_execution_proof::<_, _, Blake2Hasher>( &local_executor(), &RemoteCallRequest { - block: test_client::runtime::Hash::default(), + block: substrate_test_runtime_client::runtime::Hash::default(), header: remote_header, method: method.into(), call_data: vec![], @@ -435,7 +435,7 @@ mod tests { let execution_result = check_execution_proof_with_make_header::<_, _, Blake2Hasher, _>( &local_executor(), &RemoteCallRequest { - block: test_client::runtime::Hash::default(), + block: substrate_test_runtime_client::runtime::Hash::default(), header: remote_header, method: method.into(), call_data: vec![], @@ -457,7 +457,7 @@ mod tests { } // prepare remote client - let remote_client = test_client::new(); + let remote_client = substrate_test_runtime_client::new(); for i in 1u32..3u32 { let mut digest = Digest::default(); digest.push(sp_runtime::generic::DigestItem::Other::(i.to_le_bytes().to_vec())); @@ -488,7 +488,7 @@ mod tests { execute_with_proof_failure(&remote_client, 2, "Core_version"); // check that proof check doesn't panic even if proof is incorrect AND panic handler is set - panic_handler::set("TEST", "1.2.3"); + sp_panic_handler::set("TEST", "1.2.3"); execute_with_proof_failure(&remote_client, 2, "Core_version"); } @@ -496,9 +496,9 @@ mod tests { fn code_is_executed_at_genesis_only() { let backend = Arc::new(InMemBackend::::new()); let def = H256::default(); - let header0 = test_client::runtime::Header::new(0, def, def, def, Default::default()); + let header0 = substrate_test_runtime_client::runtime::Header::new(0, def, def, def, Default::default()); let hash0 = header0.hash(); - let header1 = test_client::runtime::Header::new(1, def, def, hash0, Default::default()); + let header1 = substrate_test_runtime_client::runtime::Header::new(1, def, def, hash0, Default::default()); let hash1 = header1.hash(); backend.blockchain().insert(hash0, header0, None, None, NewBlockState::Final).unwrap(); backend.blockchain().insert(hash1, header1, None, None, NewBlockState::Final).unwrap(); diff --git a/substrate/client/src/light/fetcher.rs b/substrate/client/src/light/fetcher.rs index babd83cfc9..c081f6bb9e 100644 --- a/substrate/client/src/light/fetcher.rs +++ b/substrate/client/src/light/fetcher.rs @@ -22,21 +22,21 @@ use std::marker::PhantomData; use hash_db::{HashDB, Hasher, EMPTY_PREFIX}; use codec::{Decode, Encode}; -use primitives::{convert_hash, traits::CodeExecutor, H256}; +use sp_core::{convert_hash, traits::CodeExecutor, H256}; use sp_runtime::traits::{ Block as BlockT, Header as HeaderT, Hash, HashFor, NumberFor, SimpleArithmetic, CheckedConversion, Zero, }; -use state_machine::{ +use sp_state_machine::{ ChangesTrieRootsStorage, ChangesTrieAnchorBlockId, ChangesTrieConfigurationRange, TrieBackend, read_proof_check, key_changes_proof_check, create_proof_check_backend_storage, read_child_proof_check, }; -pub use state_machine::StorageProof; +pub use sp_state_machine::StorageProof; use sp_blockchain::{Error as ClientError, Result as ClientResult}; use crate::cht; -pub use client_api::{ +pub use sc_client_api::{ light::{ RemoteCallRequest, RemoteHeaderRequest, RemoteReadRequest, RemoteReadChildRequest, RemoteChangesRequest, ChangesProof, RemoteBodyRequest, Fetcher, FetchChecker, @@ -294,7 +294,7 @@ impl<'a, H, Number, Hash> ChangesTrieRootsStorage for RootsStorage<'a fn build_anchor( &self, _hash: H::Out, - ) -> Result, String> { + ) -> Result, String> { Err("build_anchor is only called when building block".into()) } @@ -326,40 +326,40 @@ impl<'a, H, Number, Hash> ChangesTrieRootsStorage for RootsStorage<'a pub mod tests { use codec::Decode; use crate::client::tests::prepare_client_with_key_changes; - use executor::{NativeExecutor, WasmExecutionMethod}; + use sc_executor::{NativeExecutor, WasmExecutionMethod}; use sp_blockchain::Error as ClientError; - use client_api::backend::NewBlockState; - use test_client::{ + use sc_client_api::backend::NewBlockState; + use substrate_test_runtime_client::{ self, ClientExt, blockchain::HeaderBackend, AccountKeyring, runtime::{self, Hash, Block, Header, Extrinsic} }; - use consensus::BlockOrigin; + use sp_consensus::BlockOrigin; use crate::in_mem::{Blockchain as InMemoryBlockchain}; use crate::light::fetcher::{FetchChecker, LightDataChecker, RemoteHeaderRequest}; use crate::light::blockchain::tests::{DummyStorage, DummyBlockchain}; - use primitives::{blake2_256, Blake2Hasher, H256}; - use primitives::storage::{well_known_keys, StorageKey, ChildInfo}; + use sp_core::{blake2_256, Blake2Hasher, H256}; + use sp_core::storage::{well_known_keys, StorageKey, ChildInfo}; use sp_runtime::generic::BlockId; - use state_machine::Backend; + use sp_state_machine::Backend; use super::*; const CHILD_INFO_1: ChildInfo<'static> = ChildInfo::new_default(b"unique_id_1"); type TestChecker = LightDataChecker< - NativeExecutor, + NativeExecutor, Blake2Hasher, Block, DummyStorage, >; - fn local_executor() -> NativeExecutor { + fn local_executor() -> NativeExecutor { NativeExecutor::new(WasmExecutionMethod::Interpreted, None) } fn prepare_for_read_proof_check() -> (TestChecker, Header, StorageProof, u32) { // prepare remote client - let remote_client = test_client::new(); + let remote_client = substrate_test_runtime_client::new(); let remote_block_id = BlockId::Number(0); let remote_block_hash = remote_client.block_hash(0).unwrap().unwrap(); let mut remote_block_header = remote_client.header(&remote_block_id).unwrap().unwrap(); @@ -392,10 +392,10 @@ pub mod tests { } fn prepare_for_read_child_proof_check() -> (TestChecker, Header, StorageProof, Vec) { - use test_client::DefaultTestClientBuilderExt; - use test_client::TestClientBuilderExt; + use substrate_test_runtime_client::DefaultTestClientBuilderExt; + use substrate_test_runtime_client::TestClientBuilderExt; // prepare remote client - let remote_client = test_client::TestClientBuilder::new() + let remote_client = substrate_test_runtime_client::TestClientBuilder::new() .add_extra_child_storage( b":child_storage:default:child1".to_vec(), CHILD_INFO_1, @@ -441,7 +441,7 @@ pub mod tests { fn prepare_for_header_proof_check(insert_cht: bool) -> (TestChecker, Hash, Header, StorageProof) { // prepare remote client - let remote_client = test_client::new(); + let remote_client = substrate_test_runtime_client::new(); let mut local_headers_hashes = Vec::new(); for i in 0..4 { let builder = remote_client.new_block(Default::default()).unwrap(); @@ -468,7 +468,7 @@ pub mod tests { } fn header_with_computed_extrinsics_root(extrinsics: Vec) -> Header { - use trie::{TrieConfiguration, trie_types::Layout}; + use sp_trie::{TrieConfiguration, trie_types::Layout}; let iter = extrinsics.iter().map(Encode::encode); let extrinsics_root = Layout::::ordered_trie_root(iter); diff --git a/substrate/client/src/light/mod.rs b/substrate/client/src/light/mod.rs index bd8040d22b..cc27bc698b 100644 --- a/substrate/client/src/light/mod.rs +++ b/substrate/client/src/light/mod.rs @@ -23,15 +23,15 @@ pub mod fetcher; use std::sync::Arc; -use executor::RuntimeInfo; -use primitives::{H256, Blake2Hasher, traits::CodeExecutor}; +use sc_executor::RuntimeInfo; +use sp_core::{H256, Blake2Hasher, traits::CodeExecutor}; use sp_runtime::BuildStorage; use sp_runtime::traits::Block as BlockT; use sp_blockchain::Result as ClientResult; use crate::call_executor::LocalCallExecutor; use crate::client::Client; -use client_api::{ +use sc_client_api::{ light::Storage as BlockchainStorage, }; use crate::light::backend::Backend; diff --git a/substrate/client/state-db/Cargo.toml b/substrate/client/state-db/Cargo.toml index 175b38f7f0..97079c8f18 100644 --- a/substrate/client/state-db/Cargo.toml +++ b/substrate/client/state-db/Cargo.toml @@ -7,7 +7,7 @@ edition = "2018" [dependencies] parking_lot = "0.9.0" log = "0.4.8" -primitives = { package = "sp-core", path = "../../primitives/core" } +sp-core = { path = "../../primitives/core" } codec = { package = "parity-scale-codec", version = "1.0.0", features = ["derive"] } [dev-dependencies] diff --git a/substrate/client/state-db/src/lib.rs b/substrate/client/state-db/src/lib.rs index e561d9ce96..331da7d575 100644 --- a/substrate/client/state-db/src/lib.rs +++ b/substrate/client/state-db/src/lib.rs @@ -471,7 +471,7 @@ impl StateDb { #[cfg(test)] mod tests { use std::io; - use primitives::H256; + use sp_core::H256; use crate::{StateDb, PruningMode, Constraints}; use crate::test::{make_db, make_changeset, TestDb}; diff --git a/substrate/client/state-db/src/noncanonical.rs b/substrate/client/state-db/src/noncanonical.rs index 58715715cc..6e4cd079ae 100644 --- a/substrate/client/state-db/src/noncanonical.rs +++ b/substrate/client/state-db/src/noncanonical.rs @@ -436,7 +436,7 @@ impl NonCanonicalOverlay { #[cfg(test)] mod tests { use std::io; - use primitives::H256; + use sp_core::H256; use super::{NonCanonicalOverlay, to_journal_key}; use crate::{ChangeSet, CommitSet}; use crate::test::{make_db, make_changeset}; diff --git a/substrate/client/state-db/src/pruning.rs b/substrate/client/state-db/src/pruning.rs index 21f472fe69..4cb130eff8 100644 --- a/substrate/client/state-db/src/pruning.rs +++ b/substrate/client/state-db/src/pruning.rs @@ -201,7 +201,7 @@ impl RefWindow { #[cfg(test)] mod tests { use super::RefWindow; - use primitives::H256; + use sp_core::H256; use crate::CommitSet; use crate::test::{make_db, make_commit, TestDb}; diff --git a/substrate/client/state-db/src/test.rs b/substrate/client/state-db/src/test.rs index d90c369906..dfbb08998b 100644 --- a/substrate/client/state-db/src/test.rs +++ b/substrate/client/state-db/src/test.rs @@ -17,7 +17,7 @@ //! Test utils use std::collections::HashMap; -use primitives::H256; +use sp_core::H256; use crate::{DBValue, ChangeSet, CommitSet, MetaDb, NodeDb}; #[derive(Default, Debug, Clone, PartialEq, Eq)] diff --git a/substrate/client/transaction-pool/Cargo.toml b/substrate/client/transaction-pool/Cargo.toml index f1ab17927d..b9d7bf59ab 100644 --- a/substrate/client/transaction-pool/Cargo.toml +++ b/substrate/client/transaction-pool/Cargo.toml @@ -10,14 +10,14 @@ derive_more = "0.99.2" futures = { version = "0.3.1", features = ["compat"] } log = "0.4.8" parking_lot = "0.9.0" -primitives = { package = "sp-core", path = "../../primitives/core" } +sp-core = { path = "../../primitives/core" } sp-api = { path = "../../primitives/api" } sp-runtime = { path = "../../primitives/runtime" } -txpool = { package = "sc-transaction-graph", path = "./graph" } -txpool-api = { package = "sp-transaction-pool", path = "../../primitives/transaction-pool" } -client-api = { package = "sc-client-api", path = "../api" } +sc-transaction-graph = { path = "./graph" } +sp-transaction-pool = { path = "../../primitives/transaction-pool" } +sc-client-api = { path = "../api" } sp-blockchain = { path = "../../primitives/blockchain" } [dev-dependencies] -keyring = { package = "sp-keyring", path = "../../primitives/keyring" } -test-client = { package = "substrate-test-runtime-client", path = "../../test-utils/runtime/client" } +sp-keyring = { path = "../../primitives/keyring" } +substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } diff --git a/substrate/client/transaction-pool/graph/Cargo.toml b/substrate/client/transaction-pool/graph/Cargo.toml index cda2fb93e8..8da67ef9c6 100644 --- a/substrate/client/transaction-pool/graph/Cargo.toml +++ b/substrate/client/transaction-pool/graph/Cargo.toml @@ -10,14 +10,14 @@ futures = "0.3.1" log = "0.4.8" parking_lot = "0.9.0" serde = { version = "1.0.101", features = ["derive"] } -primitives = { package = "sp-core", path = "../../../primitives/core" } +sp-core = { path = "../../../primitives/core" } sp-runtime = { path = "../../../primitives/runtime" } -txpool-api = { package = "sp-transaction-pool", path = "../../../primitives/transaction-pool" } +sp-transaction-pool = { path = "../../../primitives/transaction-pool" } [dev-dependencies] assert_matches = "1.3.0" codec = { package = "parity-scale-codec", version = "1.0.0" } -test_runtime = { package = "substrate-test-runtime", path = "../../../test-utils/runtime" } +substrate-test-runtime = { path = "../../../test-utils/runtime" } criterion = "0.3" [[bench]] diff --git a/substrate/client/transaction-pool/graph/benches/basics.rs b/substrate/client/transaction-pool/graph/benches/basics.rs index 884cffea74..bd65efe448 100644 --- a/substrate/client/transaction-pool/graph/benches/basics.rs +++ b/substrate/client/transaction-pool/graph/benches/basics.rs @@ -20,12 +20,12 @@ use futures::executor::block_on; use sc_transaction_graph::*; use sp_runtime::transaction_validity::{ValidTransaction, InvalidTransaction}; use codec::Encode; -use test_runtime::{Block, Extrinsic, Transfer, H256, AccountId}; +use substrate_test_runtime::{Block, Extrinsic, Transfer, H256, AccountId}; use sp_runtime::{ generic::BlockId, transaction_validity::{TransactionValidity, TransactionTag as Tag}, }; -use primitives::blake2_256; +use sp_core::blake2_256; #[derive(Clone, Debug, Default)] struct TestApi { @@ -48,8 +48,8 @@ fn to_tag(nonce: u64, from: AccountId) -> Tag { impl ChainApi for TestApi { type Block = Block; type Hash = H256; - type Error = txpool_api::error::Error; - type ValidationFuture = futures::future::Ready>; + type Error = sp_transaction_pool::error::Error; + type ValidationFuture = futures::future::Ready>; fn validate_transaction( &self, diff --git a/substrate/client/transaction-pool/graph/src/base_pool.rs b/substrate/client/transaction-pool/graph/src/base_pool.rs index 77ba175963..8878e9e6dd 100644 --- a/substrate/client/transaction-pool/graph/src/base_pool.rs +++ b/substrate/client/transaction-pool/graph/src/base_pool.rs @@ -27,14 +27,14 @@ use std::{ use log::{trace, debug, warn}; use serde::Serialize; -use primitives::hexdisplay::HexDisplay; +use sp_core::hexdisplay::HexDisplay; use sp_runtime::traits::Member; use sp_runtime::transaction_validity::{ TransactionTag as Tag, TransactionLongevity as Longevity, TransactionPriority as Priority, }; -use txpool_api::{error, PoolStatus, InPoolTransaction}; +use sp_transaction_pool::{error, PoolStatus, InPoolTransaction}; use crate::future::{FutureTransactions, WaitingTransaction}; use crate::ready::ReadyTransactions; diff --git a/substrate/client/transaction-pool/graph/src/future.rs b/substrate/client/transaction-pool/graph/src/future.rs index 1c653cc6e6..2902f03b26 100644 --- a/substrate/client/transaction-pool/graph/src/future.rs +++ b/substrate/client/transaction-pool/graph/src/future.rs @@ -22,7 +22,7 @@ use std::{ time, }; -use primitives::hexdisplay::HexDisplay; +use sp_core::hexdisplay::HexDisplay; use sp_runtime::transaction_validity::{ TransactionTag as Tag, }; diff --git a/substrate/client/transaction-pool/graph/src/pool.rs b/substrate/client/transaction-pool/graph/src/pool.rs index d29a513d97..bb5f59ef87 100644 --- a/substrate/client/transaction-pool/graph/src/pool.rs +++ b/substrate/client/transaction-pool/graph/src/pool.rs @@ -34,7 +34,7 @@ use sp_runtime::{ traits::{self, SaturatedConversion}, transaction_validity::{TransactionValidity, TransactionTag as Tag, TransactionValidityError}, }; -use txpool_api::{error, PoolStatus}; +use sp_transaction_pool::{error, PoolStatus}; use crate::validated_pool::{ValidatedPool, ValidatedTransaction}; @@ -466,10 +466,10 @@ mod tests { use parking_lot::Mutex; use futures::executor::block_on; use super::*; - use txpool_api::TransactionStatus; + use sp_transaction_pool::TransactionStatus; use sp_runtime::transaction_validity::{ValidTransaction, InvalidTransaction}; use codec::Encode; - use test_runtime::{Block, Extrinsic, Transfer, H256, AccountId}; + use substrate_test_runtime::{Block, Extrinsic, Transfer, H256, AccountId}; use assert_matches::assert_matches; use crate::base_pool::Limit; diff --git a/substrate/client/transaction-pool/graph/src/ready.rs b/substrate/client/transaction-pool/graph/src/ready.rs index a358047dd7..9fd11ab959 100644 --- a/substrate/client/transaction-pool/graph/src/ready.rs +++ b/substrate/client/transaction-pool/graph/src/ready.rs @@ -28,7 +28,7 @@ use sp_runtime::traits::Member; use sp_runtime::transaction_validity::{ TransactionTag as Tag, }; -use txpool_api::error; +use sp_transaction_pool::error; use crate::future::WaitingTransaction; use crate::base_pool::Transaction; diff --git a/substrate/client/transaction-pool/graph/src/validated_pool.rs b/substrate/client/transaction-pool/graph/src/validated_pool.rs index 7f9e407727..49b86bbca0 100644 --- a/substrate/client/transaction-pool/graph/src/validated_pool.rs +++ b/substrate/client/transaction-pool/graph/src/validated_pool.rs @@ -36,7 +36,7 @@ use sp_runtime::{ traits::{self, SaturatedConversion}, transaction_validity::TransactionTag as Tag, }; -use txpool_api::{error, PoolStatus}; +use sp_transaction_pool::{error, PoolStatus}; use crate::base_pool::PruneStatus; use crate::pool::{EventStream, Options, ChainApi, BlockHash, ExHash, ExtrinsicFor, TransactionFor}; diff --git a/substrate/client/transaction-pool/graph/src/watcher.rs b/substrate/client/transaction-pool/graph/src/watcher.rs index fa93386c8c..f222c8b621 100644 --- a/substrate/client/transaction-pool/graph/src/watcher.rs +++ b/substrate/client/transaction-pool/graph/src/watcher.rs @@ -20,7 +20,7 @@ use futures::{ Stream, channel::mpsc, }; -use txpool_api::TransactionStatus; +use sp_transaction_pool::TransactionStatus; /// Extrinsic watcher. /// diff --git a/substrate/client/transaction-pool/src/api.rs b/substrate/client/transaction-pool/src/api.rs index 8d2fdd9702..6f4899995f 100644 --- a/substrate/client/transaction-pool/src/api.rs +++ b/substrate/client/transaction-pool/src/api.rs @@ -20,13 +20,13 @@ use std::{marker::PhantomData, pin::Pin, sync::Arc}; use codec::{Decode, Encode}; use futures::{channel::oneshot, executor::{ThreadPool, ThreadPoolBuilder}, future::{Future, FutureExt, ready}}; -use client_api::{ +use sc_client_api::{ blockchain::HeaderBackend, light::{Fetcher, RemoteCallRequest} }; -use primitives::{H256, Blake2Hasher, Hasher}; +use sp_core::{H256, Blake2Hasher, Hasher}; use sp_runtime::{generic::BlockId, traits::{self, Block as BlockT}, transaction_validity::TransactionValidity}; -use txpool_api::runtime_api::TaggedTransactionQueue; +use sp_transaction_pool::runtime_api::TaggedTransactionQueue; use crate::error::{self, Error}; @@ -54,7 +54,7 @@ impl FullChainApi where } } -impl txpool::ChainApi for FullChainApi where +impl sc_transaction_graph::ChainApi for FullChainApi where Block: BlockT, T: traits::ProvideRuntimeApi + traits::BlockIdTo + 'static + Send + Sync, T::Api: TaggedTransactionQueue, @@ -68,7 +68,7 @@ impl txpool::ChainApi for FullChainApi where fn validate_transaction( &self, at: &BlockId, - uxt: txpool::ExtrinsicFor, + uxt: sc_transaction_graph::ExtrinsicFor, ) -> Self::ValidationFuture { let (tx, rx) = oneshot::channel(); let client = self.client.clone(); @@ -93,18 +93,18 @@ impl txpool::ChainApi for FullChainApi where fn block_id_to_number( &self, at: &BlockId, - ) -> error::Result>> { + ) -> error::Result>> { self.client.to_number(at).map_err(|e| Error::BlockIdConversion(format!("{:?}", e))) } fn block_id_to_hash( &self, at: &BlockId, - ) -> error::Result>> { + ) -> error::Result>> { self.client.to_hash(at).map_err(|e| Error::BlockIdConversion(format!("{:?}", e))) } - fn hash_and_length(&self, ex: &txpool::ExtrinsicFor) -> (Self::Hash, usize) { + fn hash_and_length(&self, ex: &sc_transaction_graph::ExtrinsicFor) -> (Self::Hash, usize) { ex.using_encoded(|x| { (Blake2Hasher::hash(x), x.len()) }) @@ -133,7 +133,7 @@ impl LightChainApi where } } -impl txpool::ChainApi for LightChainApi where +impl sc_transaction_graph::ChainApi for LightChainApi where Block: BlockT, T: HeaderBackend + 'static, F: Fetcher + 'static, @@ -146,7 +146,7 @@ impl txpool::ChainApi for LightChainApi where fn validate_transaction( &self, at: &BlockId, - uxt: txpool::ExtrinsicFor, + uxt: sc_transaction_graph::ExtrinsicFor, ) -> Self::ValidationFuture { let header_hash = self.client.expect_block_hash_from_id(at); let header_and_hash = header_hash @@ -177,15 +177,15 @@ impl txpool::ChainApi for LightChainApi where Box::new(remote_validation_request) } - fn block_id_to_number(&self, at: &BlockId) -> error::Result>> { + fn block_id_to_number(&self, at: &BlockId) -> error::Result>> { Ok(self.client.block_number_from_id(at)?) } - fn block_id_to_hash(&self, at: &BlockId) -> error::Result>> { + fn block_id_to_hash(&self, at: &BlockId) -> error::Result>> { Ok(self.client.block_hash_from_id(at)?) } - fn hash_and_length(&self, ex: &txpool::ExtrinsicFor) -> (Self::Hash, usize) { + fn hash_and_length(&self, ex: &sc_transaction_graph::ExtrinsicFor) -> (Self::Hash, usize) { ex.using_encoded(|x| { (Blake2Hasher::hash(x), x.len()) }) diff --git a/substrate/client/transaction-pool/src/error.rs b/substrate/client/transaction-pool/src/error.rs index 6ba1d8e825..5394393c46 100644 --- a/substrate/client/transaction-pool/src/error.rs +++ b/substrate/client/transaction-pool/src/error.rs @@ -16,7 +16,7 @@ //! Transaction pool error. -use txpool_api::error::Error as TxPoolError; +use sp_transaction_pool::error::Error as TxPoolError; /// Transaction pool result. pub type Result = std::result::Result; @@ -47,7 +47,7 @@ impl std::error::Error for Error { } } -impl txpool_api::error::IntoPoolError for Error { +impl sp_transaction_pool::error::IntoPoolError for Error { fn into_pool_error(self) -> std::result::Result { match self { Error::Pool(e) => Ok(e), diff --git a/substrate/client/transaction-pool/src/lib.rs b/substrate/client/transaction-pool/src/lib.rs index 62e88af74e..9ca4cc0a1e 100644 --- a/substrate/client/transaction-pool/src/lib.rs +++ b/substrate/client/transaction-pool/src/lib.rs @@ -26,7 +26,7 @@ pub mod error; #[cfg(test)] mod tests; -pub use txpool; +pub use sc_transaction_graph as txpool; pub use crate::api::{FullChainApi, LightChainApi}; pub use crate::maintainer::{FullBasicPoolMaintainer, LightBasicPoolMaintainer}; @@ -37,7 +37,7 @@ use sp_runtime::{ generic::BlockId, traits::Block as BlockT, }; -use txpool_api::{ +use sp_transaction_pool::{ TransactionPool, PoolStatus, ImportNotificationStream, TxHash, TransactionFor, TransactionStatusStreamFor, }; @@ -46,25 +46,25 @@ use txpool_api::{ pub struct BasicPool where Block: BlockT, - PoolApi: txpool::ChainApi, + PoolApi: sc_transaction_graph::ChainApi, { - pool: Arc>, + pool: Arc>, } impl BasicPool where Block: BlockT, - PoolApi: txpool::ChainApi, + PoolApi: sc_transaction_graph::ChainApi, { /// Create new basic transaction pool with provided api. - pub fn new(options: txpool::Options, pool_api: PoolApi) -> Self { + pub fn new(options: sc_transaction_graph::Options, pool_api: PoolApi) -> Self { BasicPool { - pool: Arc::new(txpool::Pool::new(options, pool_api)), + pool: Arc::new(sc_transaction_graph::Pool::new(options, pool_api)), } } /// Gets shared reference to the underlying pool. - pub fn pool(&self) -> &Arc> { + pub fn pool(&self) -> &Arc> { &self.pool } } @@ -72,11 +72,11 @@ impl BasicPool impl TransactionPool for BasicPool where Block: BlockT, - PoolApi: 'static + txpool::ChainApi, + PoolApi: 'static + sc_transaction_graph::ChainApi, { type Block = PoolApi::Block; - type Hash = txpool::ExHash; - type InPoolTransaction = txpool::base_pool::Transaction, TransactionFor>; + type Hash = sc_transaction_graph::ExHash; + type InPoolTransaction = sc_transaction_graph::base_pool::Transaction, TransactionFor>; type Error = error::Error; fn submit_at( diff --git a/substrate/client/transaction-pool/src/maintainer.rs b/substrate/client/transaction-pool/src/maintainer.rs index 5867192dce..799aa8bd12 100644 --- a/substrate/client/transaction-pool/src/maintainer.rs +++ b/substrate/client/transaction-pool/src/maintainer.rs @@ -26,31 +26,31 @@ use futures::{ use log::{warn, debug, trace}; use parking_lot::Mutex; -use client_api::{ +use sc_client_api::{ client::BlockBody, light::{Fetcher, RemoteBodyRequest}, }; -use primitives::{Blake2Hasher, H256}; +use sp_core::{Blake2Hasher, H256}; use sp_runtime::{ generic::BlockId, traits::{Block as BlockT, Extrinsic, Header, NumberFor, ProvideRuntimeApi, SimpleArithmetic}, }; use sp_blockchain::HeaderBackend; -use txpool_api::TransactionPoolMaintainer; -use txpool_api::runtime_api::TaggedTransactionQueue; +use sp_transaction_pool::TransactionPoolMaintainer; +use sp_transaction_pool::runtime_api::TaggedTransactionQueue; -use txpool::{self, ChainApi}; +use sc_transaction_graph::{self, ChainApi}; /// Basic transaction pool maintainer for full clients. pub struct FullBasicPoolMaintainer { - pool: Arc>, + pool: Arc>, client: Arc, } impl FullBasicPoolMaintainer { /// Create new basic full pool maintainer. pub fn new( - pool: Arc>, + pool: Arc>, client: Arc, ) -> Self { FullBasicPoolMaintainer { pool, client } @@ -61,7 +61,7 @@ impl TransactionPoolMaintainer for FullBasicPoolMaintainer where - Block: BlockT::Out>, + Block: BlockT::Out>, Client: ProvideRuntimeApi + HeaderBackend + BlockBody + 'static, Client::Api: TaggedTransactionQueue, PoolApi: ChainApi + 'static, @@ -143,7 +143,7 @@ where /// Basic transaction pool maintainer for light clients. pub struct LightBasicPoolMaintainer { - pool: Arc>, + pool: Arc>, client: Arc, fetcher: Arc, revalidate_time_period: Option, @@ -154,7 +154,7 @@ pub struct LightBasicPoolMaintainer impl LightBasicPoolMaintainer where - Block: BlockT::Out>, + Block: BlockT::Out>, Client: ProvideRuntimeApi + HeaderBackend + BlockBody + 'static, Client::Api: TaggedTransactionQueue, PoolApi: ChainApi + 'static, @@ -165,7 +165,7 @@ impl LightBasicPoolMaintainer>, + pool: Arc>, client: Arc, fetcher: Arc, ) -> Self { @@ -180,7 +180,7 @@ impl LightBasicPoolMaintainer>, + pool: Arc>, client: Arc, fetcher: Arc, revalidate_time_period: Option, @@ -261,7 +261,7 @@ impl TransactionPoolMaintainer for LightBasicPoolMaintainer where - Block: BlockT::Out>, + Block: BlockT::Out>, Client: ProvideRuntimeApi + HeaderBackend + BlockBody + 'static, Client::Api: TaggedTransactionQueue, PoolApi: ChainApi + 'static, @@ -355,15 +355,15 @@ mod tests { use super::*; use futures::executor::block_on; use codec::Encode; - use test_client::{prelude::*, runtime::{Block, Transfer}, consensus::{BlockOrigin, SelectChain}}; - use txpool_api::PoolStatus; + use substrate_test_runtime_client::{prelude::*, runtime::{Block, Transfer}, sp_consensus::{BlockOrigin, SelectChain}}; + use sp_transaction_pool::PoolStatus; use crate::api::{FullChainApi, LightChainApi}; #[test] fn should_remove_transactions_from_the_full_pool() { let (client, longest_chain) = TestClientBuilder::new().build_with_longest_chain(); let client = Arc::new(client); - let pool = txpool::Pool::new(Default::default(), FullChainApi::new(client.clone())); + let pool = sc_transaction_graph::Pool::new(Default::default(), FullChainApi::new(client.clone())); let pool = Arc::new(pool); let transaction = Transfer { amount: 5, @@ -401,7 +401,7 @@ mod tests { to: Default::default(), }.into_signed_tx(); let fetcher_transaction = transaction.clone(); - let fetcher = Arc::new(test_client::new_light_fetcher() + let fetcher = Arc::new(substrate_test_runtime_client::new_light_fetcher() .with_remote_body(Some(Box::new(move |_| Ok(vec![fetcher_transaction.clone()])))) .with_remote_call(Some(Box::new(move |_| { let validity: sp_runtime::transaction_validity::TransactionValidity = @@ -417,7 +417,7 @@ mod tests { let (client, longest_chain) = TestClientBuilder::new().build_with_longest_chain(); let client = Arc::new(client); - let pool = txpool::Pool::new(Default::default(), LightChainApi::new( + let pool = sc_transaction_graph::Pool::new(Default::default(), LightChainApi::new( client.clone(), fetcher.clone(), )); @@ -473,7 +473,7 @@ mod tests { let build_fetcher = || { let validated = Arc::new(atomic::AtomicBool::new(false)); - Arc::new(test_client::new_light_fetcher() + Arc::new(substrate_test_runtime_client::new_light_fetcher() .with_remote_body(Some(Box::new(move |_| Ok(vec![])))) .with_remote_call(Some(Box::new(move |_| { let is_inserted = validated.swap(true, atomic::Ordering::SeqCst); @@ -504,7 +504,7 @@ mod tests { let client = Arc::new(client); // now let's prepare pool - let pool = txpool::Pool::new(Default::default(), LightChainApi::new( + let pool = sc_transaction_graph::Pool::new(Default::default(), LightChainApi::new( client.clone(), fetcher.clone(), )); @@ -563,7 +563,7 @@ mod tests { fn should_add_reverted_transactions_to_the_pool() { let (client, longest_chain) = TestClientBuilder::new().build_with_longest_chain(); let client = Arc::new(client); - let pool = txpool::Pool::new(Default::default(), FullChainApi::new(client.clone())); + let pool = sc_transaction_graph::Pool::new(Default::default(), FullChainApi::new(client.clone())); let pool = Arc::new(pool); let transaction = Transfer { amount: 5, diff --git a/substrate/client/transaction-pool/src/tests.rs b/substrate/client/transaction-pool/src/tests.rs index 65ca06c2c3..e6bdffa945 100644 --- a/substrate/client/transaction-pool/src/tests.rs +++ b/substrate/client/transaction-pool/src/tests.rs @@ -19,8 +19,8 @@ use super::*; use codec::Encode; use futures::executor::block_on; -use txpool::{self, Pool}; -use test_client::{runtime::{AccountId, Block, Hash, Index, Extrinsic, Transfer}, AccountKeyring::{self, *}}; +use sc_transaction_graph::{self, Pool}; +use substrate_test_runtime_client::{runtime::{AccountId, Block, Hash, Index, Extrinsic, Transfer}, AccountKeyring::{self, *}}; use sp_runtime::{ generic::{self, BlockId}, traits::{Hash as HashT, BlakeTwo256}, @@ -39,7 +39,7 @@ impl TestApi { } } -impl txpool::ChainApi for TestApi { +impl sc_transaction_graph::ChainApi for TestApi { type Block = Block; type Hash = Hash; type Error = error::Error; @@ -48,7 +48,7 @@ impl txpool::ChainApi for TestApi { fn validate_transaction( &self, at: &BlockId, - uxt: txpool::ExtrinsicFor, + uxt: sc_transaction_graph::ExtrinsicFor, ) -> Self::ValidationFuture { let expected = index(at); let requires = if expected == uxt.transfer().nonce { @@ -73,18 +73,18 @@ impl txpool::ChainApi for TestApi { )) } - fn block_id_to_number(&self, at: &BlockId) -> error::Result>> { + fn block_id_to_number(&self, at: &BlockId) -> error::Result>> { Ok(Some(number_of(at))) } - fn block_id_to_hash(&self, at: &BlockId) -> error::Result>> { + fn block_id_to_hash(&self, at: &BlockId) -> error::Result>> { Ok(match at { generic::BlockId::Hash(x) => Some(x.clone()), _ => Some(Default::default()), }) } - fn hash_and_length(&self, ex: &txpool::ExtrinsicFor) -> (Self::Hash, usize) { + fn hash_and_length(&self, ex: &sc_transaction_graph::ExtrinsicFor) -> (Self::Hash, usize) { let encoded = ex.encode(); (BlakeTwo256::hash(&encoded), encoded.len()) } diff --git a/substrate/frame/assets/Cargo.toml b/substrate/frame/assets/Cargo.toml index 4618c2a831..72de7d2b8b 100644 --- a/substrate/frame/assets/Cargo.toml +++ b/substrate/frame/assets/Cargo.toml @@ -10,12 +10,12 @@ codec = { package = "parity-scale-codec", version = "1.0.0", default-features = # Needed for various traits. In our case, `OnFinalize`. sp-runtime = { path = "../../primitives/runtime", default-features = false } # Needed for type-safe access to storage DB. -support = { package = "frame-support", path = "../support", default-features = false } +frame-support = { path = "../support", default-features = false } # `system` module provides us with all sorts of useful stuff and macros depend on it being around. -system = { package = "frame-system", path = "../system", default-features = false } +frame-system = { path = "../system", default-features = false } [dev-dependencies] -primitives = { package = "sp-core", path = "../../primitives/core" } +sp-core = { path = "../../primitives/core" } sp-std = { path = "../../primitives/std" } sp-io = { path = "../../primitives/io" } @@ -25,6 +25,6 @@ std = [ "serde", "codec/std", "sp-runtime/std", - "support/std", - "system/std", + "frame-support/std", + "frame-system/std", ] diff --git a/substrate/frame/assets/src/lib.rs b/substrate/frame/assets/src/lib.rs index af2baae62b..87e74c0c6c 100644 --- a/substrate/frame/assets/src/lib.rs +++ b/substrate/frame/assets/src/lib.rs @@ -84,8 +84,8 @@ //! ### Simple Code Snippet //! //! ```rust,ignore -//! use support::{decl_module, dispatch}; -//! use system::ensure_signed; +//! use frame_support::{decl_module, dispatch}; +//! use frame_system::{self as system, ensure_signed}; //! //! pub trait Trait: assets::Trait { } //! @@ -130,15 +130,15 @@ // Ensure we're `no_std` when compiling for Wasm. #![cfg_attr(not(feature = "std"), no_std)] -use support::{Parameter, decl_module, decl_event, decl_storage, ensure}; +use frame_support::{Parameter, decl_module, decl_event, decl_storage, ensure}; use sp_runtime::traits::{Member, SimpleArithmetic, Zero, StaticLookup}; -use system::ensure_signed; +use frame_system::{self as system, ensure_signed}; use sp_runtime::traits::One; /// The module configuration trait. -pub trait Trait: system::Trait { +pub trait Trait: frame_system::Trait { /// The overarching event type. - type Event: From> + Into<::Event>; + type Event: From> + Into<::Event>; /// The units in which we record balances. type Balance: Member + Parameter + SimpleArithmetic + Default + Copy; @@ -197,7 +197,7 @@ decl_module! { decl_event!( pub enum Event where - ::AccountId, + ::AccountId, ::Balance, ::AssetId, { @@ -240,14 +240,14 @@ impl Module { mod tests { use super::*; - use support::{impl_outer_origin, assert_ok, assert_noop, parameter_types, weights::Weight}; - use primitives::H256; + use frame_support::{impl_outer_origin, assert_ok, assert_noop, parameter_types, weights::Weight}; + use sp_core::H256; // The testing primitives are very useful for avoiding having to work with signatures // or public keys. `u64` is used as the `AccountId` and no `Signature`s are required. use sp_runtime::{Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header}; impl_outer_origin! { - pub enum Origin for Test {} + pub enum Origin for Test where system = frame_system {} } // For testing the module, we construct most of a mock runtime. This means @@ -261,7 +261,7 @@ mod tests { pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } - impl system::Trait for Test { + impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type Call = (); @@ -288,7 +288,7 @@ mod tests { // This function basically just builds a genesis storage key/value store according to // our desired mockup. fn new_test_ext() -> sp_io::TestExternalities { - system::GenesisConfig::default().build_storage::().unwrap().into() + frame_system::GenesisConfig::default().build_storage::().unwrap().into() } #[test] diff --git a/substrate/frame/aura/Cargo.toml b/substrate/frame/aura/Cargo.toml index 68083e075f..767056aaf6 100644 --- a/substrate/frame/aura/Cargo.toml +++ b/substrate/frame/aura/Cargo.toml @@ -5,20 +5,20 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -app-crypto = { package = "sp-application-crypto", path = "../../primitives/application-crypto", default-features = false } +sp-application-crypto = { path = "../../primitives/application-crypto", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } -inherents = { package = "sp-inherents", path = "../../primitives/inherents", default-features = false } -primitives = { package = "sp-core", path = "../../primitives/core", default-features = false } +sp-inherents = { path = "../../primitives/inherents", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false } sp-std = { path = "../../primitives/std", default-features = false } serde = { version = "1.0.101", optional = true } -session = { package = "pallet-session", path = "../session", default-features = false } +pallet-session = { path = "../session", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } sp-io ={ path = "../../primitives/io", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } +frame-support = { path = "../support", default-features = false } sp-consensus-aura = { path = "../../primitives/consensus/aura", default-features = false} -system = { package = "frame-system", path = "../system", default-features = false } -sp-timestamp = { package = "sp-timestamp", path = "../../primitives/timestamp", default-features = false } -pallet-timestamp = { package = "pallet-timestamp", path = "../timestamp", default-features = false } +frame-system = { path = "../system", default-features = false } +sp-timestamp = { path = "../../primitives/timestamp", default-features = false } +pallet-timestamp = { path = "../timestamp", default-features = false } [dev-dependencies] @@ -28,17 +28,17 @@ parking_lot = "0.9.0" [features] default = ["std"] std = [ - "app-crypto/std", + "sp-application-crypto/std", "codec/std", - "inherents/std", + "sp-inherents/std", "sp-io/std", - "primitives/std", + "sp-core/std", "sp-std/std", "serde", "sp-runtime/std", - "support/std", + "frame-support/std", "sp-consensus-aura/std", - "system/std", + "frame-system/std", "sp-timestamp/std", "pallet-timestamp/std", ] diff --git a/substrate/frame/aura/src/lib.rs b/substrate/frame/aura/src/lib.rs index 3e691e14cb..462c30b648 100644 --- a/substrate/frame/aura/src/lib.rs +++ b/substrate/frame/aura/src/lib.rs @@ -49,7 +49,7 @@ use pallet_timestamp; use sp_std::{result, prelude::*}; use codec::{Encode, Decode}; -use support::{ +use frame_support::{ decl_storage, decl_module, Parameter, traits::{Get, FindAuthor}, ConsensusEngineId, }; @@ -58,7 +58,7 @@ use sp_runtime::{ traits::{SaturatedConversion, Saturating, Zero, Member, IsMember}, generic::DigestItem, }; use sp_timestamp::OnTimestampSet; -use inherents::{InherentIdentifier, InherentData, ProvideInherent, MakeFatalError}; +use sp_inherents::{InherentIdentifier, InherentData, ProvideInherent, MakeFatalError}; use sp_consensus_aura::{ AURA_ENGINE_ID, ConsensusLog, AuthorityIndex, inherents::{INHERENT_IDENTIFIER, AuraInherentData}, @@ -98,7 +98,7 @@ impl Module { AURA_ENGINE_ID, ConsensusLog::AuthoritiesChange(new).encode() ); - >::deposit_log(log.into()); + >::deposit_log(log.into()); } fn initialize_authorities(authorities: &[T::AuthorityId]) { @@ -113,7 +113,7 @@ impl sp_runtime::BoundToRuntimeAppPublic for Module { type Public = T::AuthorityId; } -impl session::OneSessionHandler for Module { +impl pallet_session::OneSessionHandler for Module { type Key = T::AuthorityId; fn on_genesis_session<'a, I: 'a>(validators: I) @@ -142,7 +142,7 @@ impl session::OneSessionHandler for Module { ConsensusLog::::OnDisabled(i as AuthorityIndex).encode(), ); - >::deposit_log(log.into()); + >::deposit_log(log.into()); } } @@ -206,7 +206,7 @@ impl OnTimestampSet for Module { impl ProvideInherent for Module { type Call = pallet_timestamp::Call; - type Error = MakeFatalError; + type Error = MakeFatalError; const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER; fn create_inherent(_: &InherentData) -> Option { @@ -227,7 +227,7 @@ impl ProvideInherent for Module { if timestamp_based_slot == seal_slot { Ok(()) } else { - Err(inherents::Error::from("timestamp set in block doesn't match slot in seal").into()) + Err(sp_inherents::Error::from("timestamp set in block doesn't match slot in seal").into()) } } } diff --git a/substrate/frame/aura/src/mock.rs b/substrate/frame/aura/src/mock.rs index 241f904617..758bb72597 100644 --- a/substrate/frame/aura/src/mock.rs +++ b/substrate/frame/aura/src/mock.rs @@ -24,12 +24,12 @@ use sp_runtime::{ traits::IdentityLookup, Perbill, testing::{Header, UintAuthorityId}, }; -use support::{impl_outer_origin, parameter_types, weights::Weight}; +use frame_support::{impl_outer_origin, parameter_types, weights::Weight}; use sp_io; -use primitives::H256; +use sp_core::H256; impl_outer_origin!{ - pub enum Origin for Test {} + pub enum Origin for Test where system = frame_system {} } // Workaround for https://github.com/rust-lang/rust/issues/26925 . Remove when sorted. @@ -44,7 +44,7 @@ parameter_types! { pub const MinimumPeriod: u64 = 1; } -impl system::Trait for Test { +impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -73,7 +73,7 @@ impl Trait for Test { } pub fn new_test_ext(authorities: Vec) -> sp_io::TestExternalities { - let mut t = system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); GenesisConfig::{ authorities: authorities.into_iter().map(|a| UintAuthorityId(a).to_public_key()).collect(), }.assimilate_storage(&mut t).unwrap(); diff --git a/substrate/frame/authority-discovery/Cargo.toml b/substrate/frame/authority-discovery/Cargo.toml index a6c5d65659..4d7b43417a 100644 --- a/substrate/frame/authority-discovery/Cargo.toml +++ b/substrate/frame/authority-discovery/Cargo.toml @@ -5,17 +5,17 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -authority-discovery-primitives = { package = "sp-authority-discovery", path = "../../primitives/authority-discovery", default-features = false } -app-crypto = { package = "sp-application-crypto", path = "../../primitives/application-crypto", default-features = false } +sp-authority-discovery = { path = "../../primitives/authority-discovery", default-features = false } +sp-application-crypto = { path = "../../primitives/application-crypto", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } -primitives = { package = "sp-core", path = "../../primitives/core", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false } sp-std = { path = "../../primitives/std", default-features = false } serde = { version = "1.0.101", optional = true } sp-io = { path = "../../primitives/io", default-features = false } -session = { package = "pallet-session", path = "../session", default-features = false, features = ["historical" ] } +pallet-session = { path = "../session", default-features = false, features = ["historical" ] } sp-runtime = { path = "../../primitives/runtime", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } [dev-dependencies] sp-staking = { path = "../../primitives/staking", default-features = false } @@ -23,15 +23,15 @@ sp-staking = { path = "../../primitives/staking", default-features = false } [features] default = ["std"] std = [ - "app-crypto/std", - "authority-discovery-primitives/std", + "sp-application-crypto/std", + "sp-authority-discovery/std", "codec/std", - "primitives/std", + "sp-core/std", "sp-io/std", "sp-std/std", "serde", - "session/std", + "pallet-session/std", "sp-runtime/std", - "support/std", - "system/std", + "frame-support/std", + "frame-system/std", ] diff --git a/substrate/frame/authority-discovery/src/lib.rs b/substrate/frame/authority-discovery/src/lib.rs index c63b5d5811..b4abae88dd 100644 --- a/substrate/frame/authority-discovery/src/lib.rs +++ b/substrate/frame/authority-discovery/src/lib.rs @@ -23,11 +23,11 @@ #![cfg_attr(not(feature = "std"), no_std)] use sp_std::prelude::*; -use support::{decl_module, decl_storage}; -use authority_discovery_primitives::AuthorityId; +use frame_support::{decl_module, decl_storage}; +use sp_authority_discovery::AuthorityId; /// The module's config trait. -pub trait Trait: system::Trait + session::Trait {} +pub trait Trait: frame_system::Trait + pallet_session::Trait {} decl_storage! { trait Store for Module as AuthorityDiscovery { @@ -63,7 +63,7 @@ impl sp_runtime::BoundToRuntimeAppPublic for Module { type Public = AuthorityId; } -impl session::OneSessionHandler for Module { +impl pallet_session::OneSessionHandler for Module { type Key = AuthorityId; fn on_genesis_session<'a, I: 'a>(authorities: I) @@ -92,15 +92,15 @@ impl session::OneSessionHandler for Module { #[cfg(test)] mod tests { use super::*; - use authority_discovery_primitives::{AuthorityPair}; - use app_crypto::Pair; - use primitives::{crypto::key_types, H256}; + use sp_authority_discovery::{AuthorityPair}; + use sp_application_crypto::Pair; + use sp_core::{crypto::key_types, H256}; use sp_io::TestExternalities; use sp_runtime::{ testing::{Header, UintAuthorityId}, traits::{ConvertInto, IdentityLookup, OpaqueKeys}, Perbill, KeyTypeId, }; - use support::{impl_outer_origin, parameter_types, weights::Weight}; + use frame_support::{impl_outer_origin, parameter_types, weights::Weight}; type AuthorityDiscovery = Module; type SessionIndex = u32; @@ -110,7 +110,7 @@ mod tests { impl Trait for Test {} pub struct TestOnSessionEnding; - impl session::OnSessionEnding for TestOnSessionEnding { + impl pallet_session::OnSessionEnding for TestOnSessionEnding { fn on_session_ending(_: SessionIndex, _: SessionIndex) -> Option> { None } @@ -120,10 +120,10 @@ mod tests { pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(33); } - impl session::Trait for Test { + impl pallet_session::Trait for Test { type OnSessionEnding = TestOnSessionEnding; type Keys = UintAuthorityId; - type ShouldEndSession = session::PeriodicSessions; + type ShouldEndSession = pallet_session::PeriodicSessions; type SessionHandler = TestSessionHandler; type Event = (); type ValidatorId = AuthorityId; @@ -132,7 +132,7 @@ mod tests { type DisabledValidatorsThreshold = DisabledValidatorsThreshold; } - impl session::historical::Trait for Test { + impl pallet_session::historical::Trait for Test { type FullIdentification = (); type FullIdentificationOf = (); } @@ -149,7 +149,7 @@ mod tests { pub const AvailableBlockRatio: Perbill = Perbill::one(); } - impl system::Trait for Test { + impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = BlockNumber; @@ -168,11 +168,11 @@ mod tests { } impl_outer_origin! { - pub enum Origin for Test {} + pub enum Origin for Test where system = frame_system {} } pub struct TestSessionHandler; - impl session::SessionHandler for TestSessionHandler { + impl pallet_session::SessionHandler for TestSessionHandler { const KEY_TYPE_IDS: &'static [KeyTypeId] = &[key_types::DUMMY]; fn on_new_session( @@ -190,7 +190,7 @@ mod tests { #[test] fn authorities_returns_current_authority_set() { // The whole authority discovery module ignores account ids, but we still need it for - // `session::OneSessionHandler::on_new_session`, thus its safe to use the same value everywhere. + // `pallet_session::OneSessionHandler::on_new_session`, thus its safe to use the same value everywhere. let account_id = AuthorityPair::from_seed_slice(vec![10; 32].as_ref()).unwrap().public(); let first_authorities: Vec = vec![0, 1].into_iter() @@ -203,14 +203,14 @@ mod tests { .map(AuthorityId::from) .collect(); - // Needed for `session::OneSessionHandler::on_new_session`. + // Needed for `pallet_session::OneSessionHandler::on_new_session`. let second_authorities_and_account_ids: Vec<(&AuthorityId, AuthorityId)> = second_authorities.clone() .into_iter() .map(|id| (&account_id, id)) .collect(); // Build genesis. - let mut t = system::GenesisConfig::default() + let mut t = frame_system::GenesisConfig::default() .build_storage::() .unwrap(); @@ -224,7 +224,7 @@ mod tests { let mut externalities = TestExternalities::new(t); externalities.execute_with(|| { - use session::OneSessionHandler; + use pallet_session::OneSessionHandler; AuthorityDiscovery::on_genesis_session( first_authorities.iter().map(|id| (id, id.clone())) diff --git a/substrate/frame/authorship/Cargo.toml b/substrate/frame/authorship/Cargo.toml index 40a045998c..c21ed24be1 100644 --- a/substrate/frame/authorship/Cargo.toml +++ b/substrate/frame/authorship/Cargo.toml @@ -6,14 +6,14 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -primitives = { package = "sp-core", path = "../../primitives/core", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } -inherents = { package = "sp-inherents", path = "../../primitives/inherents", default-features = false } +sp-inherents = { path = "../../primitives/inherents", default-features = false } sp-authorship = { path = "../../primitives/authorship", default-features = false } sp-std = { path = "../../primitives/std", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } sp-io ={ path = "../../primitives/io", default-features = false } impl-trait-for-tuples = "0.1.3" @@ -21,12 +21,12 @@ impl-trait-for-tuples = "0.1.3" default = ["std"] std = [ "codec/std", - "primitives/std", - "inherents/std", + "sp-core/std", + "sp-inherents/std", "sp-runtime/std", "sp-std/std", - "support/std", - "system/std", + "frame-support/std", + "frame-system/std", "sp-io/std", "sp-authorship/std", ] diff --git a/substrate/frame/authorship/src/lib.rs b/substrate/frame/authorship/src/lib.rs index 4aa188cf71..882e8161da 100644 --- a/substrate/frame/authorship/src/lib.rs +++ b/substrate/frame/authorship/src/lib.rs @@ -22,18 +22,18 @@ use sp_std::{result, prelude::*}; use sp_std::collections::btree_set::BTreeSet; -use support::{decl_module, decl_storage, dispatch, ensure}; -use support::traits::{FindAuthor, VerifySeal, Get}; +use frame_support::{decl_module, decl_storage, dispatch, ensure}; +use frame_support::traits::{FindAuthor, VerifySeal, Get}; use codec::{Encode, Decode}; -use system::ensure_none; +use frame_system::ensure_none; use sp_runtime::traits::{Header as HeaderT, One, Zero}; -use support::weights::SimpleDispatchInfo; -use inherents::{InherentIdentifier, ProvideInherent, InherentData}; +use frame_support::weights::SimpleDispatchInfo; +use sp_inherents::{InherentIdentifier, ProvideInherent, InherentData}; use sp_authorship::{INHERENT_IDENTIFIER, UnclesInherentData, InherentError}; const MAX_UNCLES: usize = 10; -pub trait Trait: system::Trait { +pub trait Trait: frame_system::Trait { /// Find the author of a block. type FindAuthor: FindAuthor; /// The number of blocks back we should accept uncles. @@ -209,7 +209,7 @@ impl Module { return author; } - let digest = >::digest(); + let digest = >::digest(); let pre_runtime_digests = digest.logs.iter().filter_map(|d| d.as_pre_runtime()); if let Some(author) = T::FindAuthor::find_author(pre_runtime_digests) { ::Author::put(&author); @@ -220,7 +220,7 @@ impl Module { } fn verify_and_import_uncles(new_uncles: Vec) -> dispatch::Result { - let now = >::block_number(); + let now = >::block_number(); let mut uncles = ::Uncles::get(); uncles.push(UncleEntryItem::InclusionHeight(now)); @@ -253,7 +253,7 @@ impl Module { accumulator: &mut >::Accumulator, ) -> Result, &'static str> { - let now = >::block_number(); + let now = >::block_number(); let (minimum_height, maximum_height) = { let uncle_generations = T::UncleGenerations::get(); @@ -278,7 +278,7 @@ impl Module { { let parent_number = uncle.number().clone() - One::one(); - let parent_hash = >::block_hash(&parent_number); + let parent_hash = >::block_hash(&parent_number); if &parent_hash != uncle.parent_hash() { return Err("uncle parent not in chain"); } @@ -289,7 +289,7 @@ impl Module { } let duplicate = existing_uncles.into_iter().find(|h| **h == hash).is_some(); - let in_chain = >::block_hash(uncle.number()) == hash; + let in_chain = >::block_hash(uncle.number()) == hash; if duplicate || in_chain { return Err("uncle already included") @@ -372,14 +372,14 @@ impl ProvideInherent for Module { #[cfg(test)] mod tests { use super::*; - use primitives::H256; + use sp_core::H256; use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, testing::Header, generic::DigestItem, Perbill, }; - use support::{parameter_types, impl_outer_origin, ConsensusEngineId, weights::Weight}; + use frame_support::{parameter_types, impl_outer_origin, ConsensusEngineId, weights::Weight}; impl_outer_origin!{ - pub enum Origin for Test {} + pub enum Origin for Test where system = frame_system {} } #[derive(Clone, Eq, PartialEq)] @@ -392,7 +392,7 @@ mod tests { pub const AvailableBlockRatio: Perbill = Perbill::one(); } - impl system::Trait for Test { + impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -421,7 +421,7 @@ mod tests { type EventHandler = (); } - type System = system::Module; + type System = frame_system::Module; type Authorship = Module; const TEST_ID: ConsensusEngineId = [1, 2, 3, 4]; @@ -493,7 +493,7 @@ mod tests { } fn new_test_ext() -> sp_io::TestExternalities { - let t = system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); t.into() } diff --git a/substrate/frame/babe/Cargo.toml b/substrate/frame/babe/Cargo.toml index ebfc436f7a..d9f9dec339 100644 --- a/substrate/frame/babe/Cargo.toml +++ b/substrate/frame/babe/Cargo.toml @@ -8,24 +8,24 @@ edition = "2018" hex-literal = "0.2.1" codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } serde = { version = "1.0.101", optional = true } -inherents = { package = "sp-inherents", path = "../../primitives/inherents", default-features = false } +sp-inherents = { path = "../../primitives/inherents", default-features = false } sp-std = { path = "../../primitives/std", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } sp-staking = { path = "../../primitives/staking", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } -timestamp = { package = "pallet-timestamp", path = "../timestamp", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } +pallet-timestamp = { path = "../timestamp", default-features = false } sp-timestamp = { path = "../../primitives/timestamp", default-features = false } -session = { package = "pallet-session", path = "../session", default-features = false } -babe-primitives = { package = "sp-consensus-babe", path = "../../primitives/consensus/babe", default-features = false } +pallet-session = { path = "../session", default-features = false } +sp-consensus-babe = { path = "../../primitives/consensus/babe", default-features = false } sp-io ={ path = "../../primitives/io", default-features = false } [dev-dependencies] lazy_static = "1.4.0" parking_lot = "0.9.0" sp-version = { path = "../../primitives/version", default-features = false } -primitives = { package = "sp-core", path = "../../primitives/core" } -test-runtime = { package = "substrate-test-runtime", path = "../../test-utils/runtime" } +sp-core = { path = "../../primitives/core" } +substrate-test-runtime = { path = "../../test-utils/runtime" } [features] default = ["std"] @@ -33,14 +33,14 @@ std = [ "serde", "codec/std", "sp-std/std", - "support/std", + "frame-support/std", "sp-runtime/std", "sp-staking/std", - "system/std", - "timestamp/std", + "frame-system/std", + "pallet-timestamp/std", "sp-timestamp/std", - "inherents/std", - "babe-primitives/std", - "session/std", + "sp-inherents/std", + "sp-consensus-babe/std", + "pallet-session/std", "sp-io/std", ] diff --git a/substrate/frame/babe/src/lib.rs b/substrate/frame/babe/src/lib.rs index 663f29ee0c..cdc29e203c 100644 --- a/substrate/frame/babe/src/lib.rs +++ b/substrate/frame/babe/src/lib.rs @@ -20,11 +20,10 @@ #![cfg_attr(not(feature = "std"), no_std)] #![forbid(unused_must_use, unsafe_code, unused_variables, unused_must_use)] #![deny(unused_imports)] -pub use timestamp; -use sp_timestamp; +pub use pallet_timestamp; use sp_std::{result, prelude::*}; -use support::{decl_storage, decl_module, traits::FindAuthor, traits::Get}; +use frame_support::{decl_storage, decl_module, traits::FindAuthor, traits::Get}; use sp_timestamp::OnTimestampSet; use sp_runtime::{generic::DigestItem, ConsensusEngineId, Perbill}; use sp_runtime::traits::{IsMember, SaturatedConversion, Saturating, RandomnessBeacon}; @@ -34,12 +33,12 @@ use sp_staking::{ }; use codec::{Encode, Decode}; -use inherents::{InherentIdentifier, InherentData, ProvideInherent, MakeFatalError}; -use babe_primitives::{ +use sp_inherents::{InherentIdentifier, InherentData, ProvideInherent, MakeFatalError}; +use sp_consensus_babe::{ BABE_ENGINE_ID, ConsensusLog, BabeAuthorityWeight, NextEpochDescriptor, RawBabePreDigest, SlotNumber, inherents::{INHERENT_IDENTIFIER, BabeInherentData} }; -pub use babe_primitives::{AuthorityId, VRF_OUTPUT_LENGTH, PUBLIC_KEY_LENGTH}; +pub use sp_consensus_babe::{AuthorityId, VRF_OUTPUT_LENGTH, PUBLIC_KEY_LENGTH}; #[cfg(all(feature = "std", test))] mod tests; @@ -47,7 +46,7 @@ mod tests; #[cfg(all(feature = "std", test))] mod mock; -pub trait Trait: timestamp::Trait { +pub trait Trait: pallet_timestamp::Trait { /// The amount of time, in slots, that each epoch should last. type EpochDuration: Get; @@ -228,11 +227,11 @@ impl IsMember for Module { } } -impl session::ShouldEndSession for Module { +impl pallet_session::ShouldEndSession for Module { fn should_end_session(now: T::BlockNumber) -> bool { // it might be (and it is in current implementation) that session module is calling // should_end_session() from it's own on_initialize() handler - // => because session on_initialize() is called earlier than ours, let's ensure + // => because pallet_session on_initialize() is called earlier than ours, let's ensure // that we have synced with digest before checking if session should be ended. Self::do_initialize(now); @@ -292,7 +291,7 @@ impl Module { pub fn slot_duration() -> T::Moment { // we double the minimum block-period so each author can always propose within // the majority of their slot. - ::MinimumPeriod::get().saturating_mul(2.into()) + ::MinimumPeriod::get().saturating_mul(2.into()) } /// Determine whether an epoch change should take place at this block. @@ -367,7 +366,7 @@ impl Module { fn deposit_consensus(new: U) { let log: DigestItem = DigestItem::Consensus(BABE_ENGINE_ID, new.encode()); - >::deposit_log(log.into()) + >::deposit_log(log.into()) } fn deposit_vrf_output(vrf_output: &[u8; VRF_OUTPUT_LENGTH]) { @@ -393,7 +392,7 @@ impl Module { return; } - let maybe_pre_digest = >::digest() + let maybe_pre_digest = >::digest() .logs .iter() .filter_map(|s| s.as_pre_runtime()) @@ -476,7 +475,7 @@ impl sp_runtime::BoundToRuntimeAppPublic for Module { type Public = AuthorityId; } -impl session::OneSessionHandler for Module { +impl pallet_session::OneSessionHandler for Module { type Key = AuthorityId; fn on_genesis_session<'a, I: 'a>(validators: I) @@ -527,8 +526,8 @@ fn compute_randomness( } impl ProvideInherent for Module { - type Call = timestamp::Call; - type Error = MakeFatalError; + type Call = pallet_timestamp::Call; + type Error = MakeFatalError; const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER; fn create_inherent(_: &InherentData) -> Option { @@ -537,7 +536,7 @@ impl ProvideInherent for Module { fn check_inherent(call: &Self::Call, data: &InherentData) -> result::Result<(), Self::Error> { let timestamp = match call { - timestamp::Call::set(ref timestamp) => timestamp.clone(), + pallet_timestamp::Call::set(ref timestamp) => timestamp.clone(), _ => return Ok(()), }; @@ -547,7 +546,7 @@ impl ProvideInherent for Module { if timestamp_based_slot == seal_slot { Ok(()) } else { - Err(inherents::Error::from("timestamp set in block doesn't match slot in seal").into()) + Err(sp_inherents::Error::from("timestamp set in block doesn't match slot in seal").into()) } } } diff --git a/substrate/frame/babe/src/mock.rs b/substrate/frame/babe/src/mock.rs index 35a423e2ad..a8acfee291 100644 --- a/substrate/frame/babe/src/mock.rs +++ b/substrate/frame/babe/src/mock.rs @@ -18,17 +18,17 @@ #![allow(dead_code, unused_imports)] use super::{Trait, Module, GenesisConfig}; -use babe_primitives::AuthorityId; +use sp_consensus_babe::AuthorityId; use sp_runtime::{ traits::IdentityLookup, Perbill, testing::{Header, UintAuthorityId}, impl_opaque_keys, }; use sp_version::RuntimeVersion; -use support::{impl_outer_origin, parameter_types, weights::Weight}; +use frame_support::{impl_outer_origin, parameter_types, weights::Weight}; use sp_io; -use primitives::{H256, Blake2Hasher}; +use sp_core::{H256, Blake2Hasher}; impl_outer_origin!{ - pub enum Origin for Test {} + pub enum Origin for Test where system = frame_system {} } type DummyValidatorId = u64; @@ -45,11 +45,11 @@ parameter_types! { pub const MinimumPeriod: u64 = 1; pub const EpochDuration: u64 = 3; pub const ExpectedBlockTime: u64 = 1; - pub const Version: RuntimeVersion = test_runtime::VERSION; + pub const Version: RuntimeVersion = substrate_test_runtime::VERSION; pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(16); } -impl system::Trait for Test { +impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -73,9 +73,9 @@ impl_opaque_keys! { } } -impl session::Trait for Test { +impl pallet_session::Trait for Test { type Event = (); - type ValidatorId = ::AccountId; + type ValidatorId = ::AccountId; type ShouldEndSession = Babe; type SessionHandler = (Babe,Babe,); type OnSessionEnding = (); @@ -85,7 +85,7 @@ impl session::Trait for Test { type DisabledValidatorsThreshold = DisabledValidatorsThreshold; } -impl timestamp::Trait for Test { +impl pallet_timestamp::Trait for Test { type Moment = u64; type OnTimestampSet = Babe; type MinimumPeriod = MinimumPeriod; @@ -98,12 +98,12 @@ impl Trait for Test { } pub fn new_test_ext(authorities: Vec) -> sp_io::TestExternalities { - let mut t = system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); GenesisConfig { authorities: authorities.into_iter().map(|a| (UintAuthorityId(a).to_public_key(), 1)).collect(), }.assimilate_storage::(&mut t).unwrap(); t.into() } -pub type System = system::Module; +pub type System = frame_system::Module; pub type Babe = Module; diff --git a/substrate/frame/babe/src/tests.rs b/substrate/frame/babe/src/tests.rs index 7ce256b43b..1ae57a6d6e 100644 --- a/substrate/frame/babe/src/tests.rs +++ b/substrate/frame/babe/src/tests.rs @@ -19,7 +19,7 @@ use super::*; use mock::{new_test_ext, Babe, Test}; use sp_runtime::{traits::OnFinalize, testing::{Digest, DigestItem}}; -use session::ShouldEndSession; +use pallet_session::ShouldEndSession; const EMPTY_RANDOMNESS: [u8; 32] = [ 74, 25, 49, 128, 53, 97, 244, 49, @@ -29,18 +29,18 @@ const EMPTY_RANDOMNESS: [u8; 32] = [ ]; fn make_pre_digest( - authority_index: babe_primitives::AuthorityIndex, - slot_number: babe_primitives::SlotNumber, - vrf_output: [u8; babe_primitives::VRF_OUTPUT_LENGTH], - vrf_proof: [u8; babe_primitives::VRF_PROOF_LENGTH], + authority_index: sp_consensus_babe::AuthorityIndex, + slot_number: sp_consensus_babe::SlotNumber, + vrf_output: [u8; sp_consensus_babe::VRF_OUTPUT_LENGTH], + vrf_proof: [u8; sp_consensus_babe::VRF_PROOF_LENGTH], ) -> Digest { - let digest_data = babe_primitives::RawBabePreDigest::Primary { + let digest_data = sp_consensus_babe::RawBabePreDigest::Primary { authority_index, slot_number, vrf_output, vrf_proof, }; - let log = DigestItem::PreRuntime(babe_primitives::BABE_ENGINE_ID, digest_data.encode()); + let log = DigestItem::PreRuntime(sp_consensus_babe::BABE_ENGINE_ID, digest_data.encode()); Digest { logs: vec![log] } } @@ -66,7 +66,7 @@ fn check_module() { }) } -type System = system::Module; +type System = frame_system::Module; #[test] fn first_block_epoch_zero_start() { @@ -103,8 +103,8 @@ fn first_block_epoch_zero_start() { assert_eq!(header.digest.logs[0], pre_digest.logs[0]); let authorities = Babe::authorities(); - let consensus_log = babe_primitives::ConsensusLog::NextEpochData( - babe_primitives::NextEpochDescriptor { + let consensus_log = sp_consensus_babe::ConsensusLog::NextEpochData( + sp_consensus_babe::NextEpochDescriptor { authorities, randomness: Babe::randomness(), } diff --git a/substrate/frame/balances/Cargo.toml b/substrate/frame/balances/Cargo.toml index 9c71401b36..cc29e3c502 100644 --- a/substrate/frame/balances/Cargo.toml +++ b/substrate/frame/balances/Cargo.toml @@ -10,13 +10,13 @@ safe-mix = { version = "1.0.0", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } sp-std = { path = "../../primitives/std", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } [dev-dependencies] sp-io = { path = "../../primitives/io" } -primitives = { package = "sp-core", path = "../../primitives/core" } -transaction-payment = { package = "pallet-transaction-payment", path = "../transaction-payment" } +sp-core = { path = "../../primitives/core" } +pallet-transaction-payment = { path = "../transaction-payment" } [features] default = ["std"] @@ -25,7 +25,7 @@ std = [ "safe-mix/std", "codec/std", "sp-std/std", - "support/std", + "frame-support/std", "sp-runtime/std", - "system/std", + "frame-system/std", ] diff --git a/substrate/frame/balances/src/lib.rs b/substrate/frame/balances/src/lib.rs index 96737c64db..8829964238 100644 --- a/substrate/frame/balances/src/lib.rs +++ b/substrate/frame/balances/src/lib.rs @@ -107,13 +107,13 @@ //! The Contract module uses the `Currency` trait to handle gas payment, and its types inherit from `Currency`: //! //! ``` -//! use support::traits::Currency; -//! # pub trait Trait: system::Trait { +//! use frame_support::traits::Currency; +//! # pub trait Trait: frame_system::Trait { //! # type Currency: Currency; //! # } //! -//! pub type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; -//! pub type NegativeImbalanceOf = <::Currency as Currency<::AccountId>>::NegativeImbalance; +//! pub type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; +//! pub type NegativeImbalanceOf = <::Currency as Currency<::AccountId>>::NegativeImbalance; //! //! # fn main() {} //! ``` @@ -121,14 +121,14 @@ //! The Staking module uses the `LockableCurrency` trait to lock a stash account's funds: //! //! ``` -//! use support::traits::{WithdrawReasons, LockableCurrency}; +//! use frame_support::traits::{WithdrawReasons, LockableCurrency}; //! use sp_runtime::traits::Bounded; -//! pub trait Trait: system::Trait { +//! pub trait Trait: frame_system::Trait { //! type Currency: LockableCurrency; //! } //! # struct StakingLedger { -//! # stash: ::AccountId, -//! # total: <::Currency as support::traits::Currency<::AccountId>>::Balance, +//! # stash: ::AccountId, +//! # total: <::Currency as frame_support::traits::Currency<::AccountId>>::Balance, //! # phantom: std::marker::PhantomData, //! # } //! # const STAKING_ID: [u8; 8] = *b"staking "; @@ -162,7 +162,7 @@ use sp_std::prelude::*; use sp_std::{cmp, result, mem, fmt::Debug}; use codec::{Codec, Encode, Decode}; -use support::{ +use frame_support::{ StorageValue, Parameter, decl_event, decl_storage, decl_module, traits::{ UpdateBalanceOutcome, Currency, OnFreeBalanceZero, OnUnbalanced, TryDrop, @@ -179,7 +179,7 @@ use sp_runtime::{ Saturating, Bounded, }, }; -use system::{IsDeadAccount, OnNewAccount, ensure_signed, ensure_root}; +use frame_system::{self as system, IsDeadAccount, OnNewAccount, ensure_signed, ensure_root}; #[cfg(test)] mod mock; @@ -188,7 +188,7 @@ mod tests; pub use self::imbalances::{PositiveImbalance, NegativeImbalance}; -pub trait Subtrait: system::Trait { +pub trait Subtrait: frame_system::Trait { /// The balance of an account. type Balance: Parameter + Member + SimpleArithmetic + Codec + Default + Copy + MaybeSerializeDeserialize + Debug + From; @@ -212,7 +212,7 @@ pub trait Subtrait: system::Trait { type CreationFee: Get; } -pub trait Trait: system::Trait { +pub trait Trait: frame_system::Trait { /// The balance of an account. type Balance: Parameter + Member + SimpleArithmetic + Codec + Default + Copy + MaybeSerializeDeserialize + Debug + From; @@ -234,7 +234,7 @@ pub trait Trait: system::Trait { type DustRemoval: OnUnbalanced>; /// The overarching event type. - type Event: From> + Into<::Event>; + type Event: From> + Into<::Event>; /// The minimum amount required to keep an account open. type ExistentialDeposit: Get; @@ -257,7 +257,7 @@ impl, I: Instance> Subtrait for T { decl_event!( pub enum Event where - ::AccountId, + ::AccountId, >::Balance { /// A new account was created. @@ -348,7 +348,7 @@ decl_storage! { /// is invoked, giving a chance to external modules to clean up data associated with /// the deleted account. /// - /// `system::AccountNonce` is also deleted if `ReservedBalance` is also zero (it also gets + /// `frame_system::AccountNonce` is also deleted if `ReservedBalance` is also zero (it also gets /// collapsed to zero if it ever becomes less than `ExistentialDeposit`. pub FreeBalance get(fn free_balance) build(|config: &GenesisConfig| config.balances.clone()): @@ -363,7 +363,7 @@ decl_storage! { /// When this balance falls below the value of `ExistentialDeposit`, then this 'reserve account' /// is deleted: specifically, `ReservedBalance`. /// - /// `system::AccountNonce` is also deleted if `FreeBalance` is also zero (it also gets + /// `frame_system::AccountNonce` is also deleted if `FreeBalance` is also zero (it also gets /// collapsed to zero if it ever becomes less than `ExistentialDeposit`.) pub ReservedBalance get(fn reserved_balance): map T::AccountId => T::Balance; @@ -439,7 +439,7 @@ decl_module! { /// This will alter `FreeBalance` and `ReservedBalance` in storage. it will /// also decrease the total issuance of the system (`TotalIssuance`). /// If the new free or reserved balance is below the existential deposit, - /// it will reset the account nonce (`system::AccountNonce`). + /// it will reset the account nonce (`frame_system::AccountNonce`). /// /// The dispatch origin for this call is `root`. /// @@ -565,7 +565,7 @@ impl, I: Instance> Module { /// /// This just removes the nonce and leaves an event. fn reap_account(who: &T::AccountId) { - >::remove(who); + >::remove(who); Self::deposit_event(RawEvent::ReapedAccount(who.clone())); } @@ -781,7 +781,7 @@ impl, I: Instance> PartialEq for ElevatedTrait { fn eq(&self, _: &Self) -> bool { unimplemented!() } } impl, I: Instance> Eq for ElevatedTrait {} -impl, I: Instance> system::Trait for ElevatedTrait { +impl, I: Instance> frame_system::Trait for ElevatedTrait { type Origin = T::Origin; type Call = T::Call; type Index = T::Index; @@ -878,7 +878,7 @@ where return Ok(()) } - let now = >::block_number(); + let now = >::block_number(); if locks.into_iter() .all(|l| now >= l.until @@ -1140,7 +1140,7 @@ where until: T::BlockNumber, reasons: WithdrawReasons, ) { - let now = >::block_number(); + let now = >::block_number(); let mut new_lock = Some(BalanceLock { id, amount, until, reasons }); let mut locks = Self::locks(who).into_iter().filter_map(|l| if l.id == id { @@ -1163,7 +1163,7 @@ where until: T::BlockNumber, reasons: WithdrawReasons, ) { - let now = >::block_number(); + let now = >::block_number(); let mut new_lock = Some(BalanceLock { id, amount, until, reasons }); let mut locks = Self::locks(who).into_iter().filter_map(|l| if l.id == id { @@ -1190,7 +1190,7 @@ where id: LockIdentifier, who: &T::AccountId, ) { - let now = >::block_number(); + let now = >::block_number(); let locks = Self::locks(who).into_iter().filter_map(|l| if l.until > now && l.id != id { Some(l) @@ -1211,7 +1211,7 @@ where fn vesting_balance(who: &T::AccountId) -> T::Balance { if let Some(v) = Self::vesting(who) { Self::free_balance(who) - .min(v.locked_at(>::block_number())) + .min(v.locked_at(>::block_number())) } else { Zero::zero() } diff --git a/substrate/frame/balances/src/mock.rs b/substrate/frame/balances/src/mock.rs index 944aab1493..2ae15d977a 100644 --- a/substrate/frame/balances/src/mock.rs +++ b/substrate/frame/balances/src/mock.rs @@ -17,14 +17,15 @@ //! Test utilities use sp_runtime::{Perbill, traits::{ConvertInto, IdentityLookup}, testing::Header}; -use primitives::H256; +use sp_core::H256; use sp_io; -use support::{impl_outer_origin, parameter_types}; -use support::traits::Get; -use support::weights::{Weight, DispatchInfo}; +use frame_support::{impl_outer_origin, parameter_types}; +use frame_support::traits::Get; +use frame_support::weights::{Weight, DispatchInfo}; use std::cell::RefCell; use crate::{GenesisConfig, Module, Trait}; +use frame_system as system; impl_outer_origin!{ pub enum Origin for Runtime {} } @@ -59,7 +60,7 @@ parameter_types! { pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } -impl system::Trait for Runtime { +impl frame_system::Trait for Runtime { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -80,7 +81,7 @@ parameter_types! { pub const TransactionBaseFee: u64 = 0; pub const TransactionByteFee: u64 = 1; } -impl transaction_payment::Trait for Runtime { +impl pallet_transaction_payment::Trait for Runtime { type Currency = Module; type OnTransactionPayment = (); type TransactionBaseFee = TransactionBaseFee; @@ -150,7 +151,7 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { self.set_associated_consts(); - let mut t = system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); GenesisConfig:: { balances: if self.monied { vec![ @@ -177,10 +178,10 @@ impl ExtBuilder { } } -pub type System = system::Module; +pub type System = frame_system::Module; pub type Balances = Module; -pub const CALL: &::Call = &(); +pub const CALL: &::Call = &(); /// create a transaction info struct from weight. Handy to avoid building the whole struct. pub fn info_from_weight(w: Weight) -> DispatchInfo { diff --git a/substrate/frame/balances/src/tests.rs b/substrate/frame/balances/src/tests.rs index b26ac5c691..bf0fa392fc 100644 --- a/substrate/frame/balances/src/tests.rs +++ b/substrate/frame/balances/src/tests.rs @@ -19,13 +19,13 @@ use super::*; use mock::{Balances, ExtBuilder, Runtime, System, info_from_weight, CALL}; use sp_runtime::traits::SignedExtension; -use support::{ +use frame_support::{ assert_noop, assert_ok, assert_err, traits::{LockableCurrency, LockIdentifier, WithdrawReason, WithdrawReasons, Currency, ReservableCurrency, ExistenceRequirement::AllowDeath} }; -use transaction_payment::ChargeTransactionPayment; -use system::RawOrigin; +use pallet_transaction_payment::ChargeTransactionPayment; +use frame_system::RawOrigin; const ID_1: LockIdentifier = *b"1 "; const ID_2: LockIdentifier = *b"2 "; @@ -763,7 +763,7 @@ fn transfer_keep_alive_works() { #[should_panic="the balance of any account should always be more than existential deposit."] fn cannot_set_genesis_value_below_ed() { mock::EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = 11); - let mut t = system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); let _ = GenesisConfig:: { balances: vec![(1, 10)], vesting: vec![], diff --git a/substrate/frame/collective/Cargo.toml b/substrate/frame/collective/Cargo.toml index 5e24e72228..7c298dd887 100644 --- a/substrate/frame/collective/Cargo.toml +++ b/substrate/frame/collective/Cargo.toml @@ -8,27 +8,27 @@ edition = "2018" serde = { version = "1.0.101", optional = true } safe-mix = { version = "1.0.0", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } -primitives = { package = "sp-core", path = "../../primitives/core", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false } sp-std = { path = "../../primitives/std", default-features = false } sp-io = { path = "../../primitives/io", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } [dev-dependencies] hex-literal = "0.2.1" -balances = { package = "pallet-balances", path = "../balances" } +pallet-balances = { path = "../balances" } [features] default = ["std"] std = [ "safe-mix/std", "codec/std", - "primitives/std", + "sp-core/std", "sp-std/std", "serde", "sp-io/std", - "support/std", + "frame-support/std", "sp-runtime/std", - "system/std", + "frame-system/std", ] diff --git a/substrate/frame/collective/src/lib.rs b/substrate/frame/collective/src/lib.rs index 20f61e54ed..1fd718bc01 100644 --- a/substrate/frame/collective/src/lib.rs +++ b/substrate/frame/collective/src/lib.rs @@ -24,16 +24,16 @@ #![recursion_limit="128"] use sp_std::{prelude::*, result}; -use primitives::u32_trait::Value as U32; +use sp_core::u32_trait::Value as U32; use sp_runtime::RuntimeDebug; use sp_runtime::traits::{Hash, EnsureOrigin}; -use support::weights::SimpleDispatchInfo; -use support::{ +use frame_support::weights::SimpleDispatchInfo; +use frame_support::{ dispatch::{Dispatchable, Parameter}, codec::{Encode, Decode}, traits::{ChangeMembers, InitializeMembers}, decl_module, decl_event, decl_storage, ensure, }; -use system::{self, ensure_signed, ensure_root}; +use frame_system::{self as system, ensure_signed, ensure_root}; /// Simple index type for proposal counting. pub type ProposalIndex = u32; @@ -44,7 +44,7 @@ pub type ProposalIndex = u32; /// vote exactly once, therefore also the number of votes for any given motion. pub type MemberCount = u32; -pub trait Trait: system::Trait { +pub trait Trait: frame_system::Trait { /// The outer origin type. type Origin: From>; @@ -52,7 +52,7 @@ pub trait Trait: system::Trait { type Proposal: Parameter + Dispatchable>::Origin>; /// The outer event type. - type Event: From> + Into<::Event>; + type Event: From> + Into<::Event>; } /// Origin for the collective module. @@ -67,7 +67,7 @@ pub enum RawOrigin { } /// Origin for the collective module. -pub type Origin = RawOrigin<::AccountId, I>; +pub type Origin = RawOrigin<::AccountId, I>; #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)] /// Info for keeping track of a motion being voted on. @@ -104,8 +104,8 @@ decl_storage! { decl_event!( pub enum Event where - ::Hash, - ::AccountId, + ::Hash, + ::AccountId, { /// A motion (given hash) has been proposed (by given account) with a threshold (given /// `MemberCount`). @@ -128,7 +128,7 @@ decl_event!( // executed logic with other democracy function. Note that councillor operations are assigned to the // operational class. decl_module! { - pub struct Module, I: Instance=DefaultInstance> for enum Call where origin: ::Origin { + pub struct Module, I: Instance=DefaultInstance> for enum Call where origin: ::Origin { fn deposit_event() = default; /// Set the collective's membership manually to `new_members`. Be nice to the chain and @@ -379,10 +379,10 @@ impl< #[cfg(test)] mod tests { use super::*; - use support::{Hashable, assert_ok, assert_noop, parameter_types, weights::Weight}; - use system::{EventRecord, Phase}; + use frame_support::{Hashable, assert_ok, assert_noop, parameter_types, weights::Weight}; + use frame_system::{self as system, EventRecord, Phase}; use hex_literal::hex; - use primitives::H256; + use sp_core::H256; use sp_runtime::{ Perbill, traits::{BlakeTwo256, IdentityLookup, Block as BlockT}, testing::Header, BuildStorage, @@ -395,7 +395,7 @@ mod tests { pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } - impl system::Trait for Test { + impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -426,7 +426,7 @@ mod tests { pub type Block = sp_runtime::generic::Block; pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; - support::construct_runtime!( + frame_support::construct_runtime!( pub enum Test where Block = Block, NodeBlock = Block, @@ -458,7 +458,7 @@ mod tests { } fn make_proposal(value: u64) -> Call { - Call::System(system::Call::remark(value.encode())) + Call::System(frame_system::Call::remark(value.encode())) } #[test] diff --git a/substrate/frame/contracts/Cargo.toml b/substrate/frame/contracts/Cargo.toml index b5bd460dee..a55c6671b9 100644 --- a/substrate/frame/contracts/Cargo.toml +++ b/substrate/frame/contracts/Cargo.toml @@ -10,34 +10,34 @@ pwasm-utils = { version = "0.12.0", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } parity-wasm = { version = "0.41.0", default-features = false } wasmi-validation = { version = "0.3.0", default-features = false } -primitives = { package = "sp-core", path = "../../primitives/core", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } sp-io = { path = "../../primitives/io", default-features = false } sp-std = { path = "../../primitives/std", default-features = false } -sandbox = { package = "sp-sandbox", path = "../../primitives/sandbox", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } +sp-sandbox = { path = "../../primitives/sandbox", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } [dev-dependencies] wabt = "0.9.2" assert_matches = "1.3.0" hex-literal = "0.2.1" -balances = { package = "pallet-balances", path = "../balances" } -timestamp = { package = "pallet-timestamp", path = "../timestamp" } -randomness-collective-flip = { package = "pallet-randomness-collective-flip", path = "../randomness-collective-flip" } +pallet-balances = { path = "../balances" } +pallet-timestamp = { path = "../timestamp" } +pallet-randomness-collective-flip = { path = "../randomness-collective-flip" } [features] default = ["std"] std = [ "serde", "codec/std", - "primitives/std", + "sp-core/std", "sp-runtime/std", "sp-io/std", "sp-std/std", - "sandbox/std", - "support/std", - "system/std", + "sp-sandbox/std", + "frame-support/std", + "frame-system/std", "parity-wasm/std", "pwasm-utils/std", "wasmi-validation/std", diff --git a/substrate/frame/contracts/rpc/Cargo.toml b/substrate/frame/contracts/rpc/Cargo.toml index 8e69b4fb8e..bb2bbd5844 100644 --- a/substrate/frame/contracts/rpc/Cargo.toml +++ b/substrate/frame/contracts/rpc/Cargo.toml @@ -10,8 +10,8 @@ jsonrpc-core = "14.0.3" jsonrpc-core-client = "14.0.3" jsonrpc-derive = "14.0.3" sp-blockchain = { path = "../../../primitives/blockchain" } -primitives = { package = "sp-core", path = "../../../primitives/core" } -rpc-primitives = { package = "sp-rpc", path = "../../../primitives/rpc" } +sp-core = { path = "../../../primitives/core" } +sp-rpc = { path = "../../../primitives/rpc" } serde = { version = "1.0.101", features = ["derive"] } sp-runtime = { path = "../../../primitives/runtime" } pallet-contracts-rpc-runtime-api = { path = "./runtime-api" } diff --git a/substrate/frame/contracts/rpc/src/lib.rs b/substrate/frame/contracts/rpc/src/lib.rs index ab0f89bd56..01d346c66a 100644 --- a/substrate/frame/contracts/rpc/src/lib.rs +++ b/substrate/frame/contracts/rpc/src/lib.rs @@ -22,8 +22,8 @@ use sp_blockchain::HeaderBackend; use codec::Codec; use jsonrpc_core::{Error, ErrorCode, Result}; use jsonrpc_derive::rpc; -use primitives::{H256, Bytes}; -use rpc_primitives::number; +use sp_core::{H256, Bytes}; +use sp_rpc::number; use serde::{Deserialize, Serialize}; use sp_runtime::{ generic::BlockId, diff --git a/substrate/frame/contracts/src/account_db.rs b/substrate/frame/contracts/src/account_db.rs index 3f345f043f..866733cefa 100644 --- a/substrate/frame/contracts/src/account_db.rs +++ b/substrate/frame/contracts/src/account_db.rs @@ -26,9 +26,9 @@ use sp_std::collections::btree_map::{BTreeMap, Entry}; use sp_std::prelude::*; use sp_io::hashing::blake2_256; use sp_runtime::traits::{Bounded, Zero}; -use support::traits::{Currency, Get, Imbalance, SignedImbalance, UpdateBalanceOutcome}; -use support::{storage::child, StorageMap}; -use system; +use frame_support::traits::{Currency, Get, Imbalance, SignedImbalance, UpdateBalanceOutcome}; +use frame_support::{storage::child, StorageMap}; +use frame_system; // Note: we don't provide Option because we can't create // the trie_id in the overlay, thus we provide an overlay on the fields @@ -100,7 +100,7 @@ impl Default for ChangeEntry { } } -pub type ChangeSet = BTreeMap<::AccountId, ChangeEntry>; +pub type ChangeSet = BTreeMap<::AccountId, ChangeEntry>; pub trait AccountDb { /// Account is used when overlayed otherwise trie_id must be provided. @@ -184,7 +184,7 @@ impl AccountDb for DirectAccountDb { code_hash, storage_size: T::StorageSizeOffset::get(), trie_id: ::TrieIdGenerator::trie_id(&address), - deduct_block: >::block_number(), + deduct_block: >::block_number(), rent_allowance: >::max_value(), last_write: None, } @@ -195,7 +195,7 @@ impl AccountDb for DirectAccountDb { code_hash, storage_size: T::StorageSizeOffset::get(), trie_id: ::TrieIdGenerator::trie_id(&address), - deduct_block: >::block_number(), + deduct_block: >::block_number(), rent_allowance: >::max_value(), last_write: None, } @@ -213,7 +213,7 @@ impl AccountDb for DirectAccountDb { } if !changed.storage.is_empty() { - new_info.last_write = Some(>::block_number()); + new_info.last_write = Some(>::block_number()); } for (k, v) in changed.storage.into_iter() { diff --git a/substrate/frame/contracts/src/exec.rs b/substrate/frame/contracts/src/exec.rs index 9243d9f8c1..c2a20ec4a1 100644 --- a/substrate/frame/contracts/src/exec.rs +++ b/substrate/frame/contracts/src/exec.rs @@ -22,20 +22,20 @@ use crate::rent; use sp_std::prelude::*; use sp_runtime::traits::{Bounded, CheckedAdd, CheckedSub, Zero}; -use support::{ +use frame_support::{ storage::unhashed, traits::{WithdrawReason, Currency, Time, Randomness}, }; -pub type AccountIdOf = ::AccountId; +pub type AccountIdOf = ::AccountId; pub type CallOf = ::Call; pub type MomentOf = <::Time as Time>::Moment; -pub type SeedOf = ::Hash; -pub type BlockNumberOf = ::BlockNumber; +pub type SeedOf = ::Hash; +pub type BlockNumberOf = ::BlockNumber; pub type StorageKey = [u8; 32]; /// A type that represents a topic of an event. At the moment a hash is used. -pub type TopicOf = ::Hash; +pub type TopicOf = ::Hash; /// A status code return to the source of a contract call or instantiation indicating success or /// failure. A code of 0 indicates success and that changes are applied. All other codes indicate @@ -304,7 +304,7 @@ where vm: &vm, loader: &loader, timestamp: T::Time::now(), - block_number: >::block_number(), + block_number: >::block_number(), } } @@ -871,7 +871,7 @@ mod tests { fn insert(&mut self, f: impl Fn(MockCtx) -> ExecResult + 'a) -> CodeHash { // Generate code hashes as monotonically increasing values. - let code_hash = ::Hash::from_low_u64_be(self.counter); + let code_hash = ::Hash::from_low_u64_be(self.counter); self.counter += 1; self.map.insert(code_hash, MockExecutable::new(f)); diff --git a/substrate/frame/contracts/src/gas.rs b/substrate/frame/contracts/src/gas.rs index b9faaf298f..f914aaad1b 100644 --- a/substrate/frame/contracts/src/gas.rs +++ b/substrate/frame/contracts/src/gas.rs @@ -19,7 +19,7 @@ use sp_std::convert::TryFrom; use sp_runtime::traits::{ CheckedMul, Zero, SaturatedConversion, SimpleArithmetic, UniqueSaturatedInto, }; -use support::{ +use frame_support::{ traits::{Currency, ExistenceRequirement, Imbalance, OnUnbalanced, WithdrawReason}, StorageValue, }; diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index 0642049478..83f11b1d9f 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -108,7 +108,7 @@ pub use crate::exec::{ExecResult, ExecReturnValue, ExecError, StatusCode}; #[cfg(feature = "std")] use serde::{Serialize, Deserialize}; -use primitives::crypto::UncheckedFrom; +use sp_core::crypto::UncheckedFrom; use sp_std::{prelude::*, marker::PhantomData, fmt::Debug}; use codec::{Codec, Encode, Decode}; use sp_io::hashing::blake2_256; @@ -119,17 +119,17 @@ use sp_runtime::{ }, RuntimeDebug, }; -use support::dispatch::{Result, Dispatchable}; -use support::{ +use frame_support::dispatch::{Result, Dispatchable}; +use frame_support::{ Parameter, decl_module, decl_event, decl_storage, storage::child, parameter_types, IsSubType, weights::DispatchInfo, }; -use support::traits::{OnFreeBalanceZero, OnUnbalanced, Currency, Get, Time, Randomness}; -use system::{ensure_signed, RawOrigin, ensure_root}; -use primitives::storage::well_known_keys::CHILD_STORAGE_KEY_PREFIX; +use frame_support::traits::{OnFreeBalanceZero, OnUnbalanced, Currency, Get, Time, Randomness}; +use frame_system::{self as system, ensure_signed, RawOrigin, ensure_root}; +use sp_core::storage::well_known_keys::CHILD_STORAGE_KEY_PREFIX; -pub type CodeHash = ::Hash; +pub type CodeHash = ::Hash; pub type TrieId = Vec; /// A function that generates an `AccountId` for a contract upon instantiation. @@ -203,7 +203,7 @@ impl ContractInfo { } pub type AliveContractInfo = - RawAliveContractInfo, BalanceOf, ::BlockNumber>; + RawAliveContractInfo, BalanceOf, ::BlockNumber>; /// Information for managing an account and its sub trie abstraction. /// This is the required info to cache for an account. @@ -237,7 +237,7 @@ pub(crate) fn trie_unique_id(trie_id: &[u8]) -> child::ChildInfo { } pub type TombstoneContractInfo = - RawTombstoneContractInfo<::Hash, ::Hashing>; + RawTombstoneContractInfo<::Hash, ::Hashing>; #[derive(Encode, Decode, PartialEq, Eq, RuntimeDebug)] pub struct RawTombstoneContractInfo(H, PhantomData); @@ -303,9 +303,9 @@ where } } -pub type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; +pub type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; pub type NegativeImbalanceOf = - <::Currency as Currency<::AccountId>>::NegativeImbalance; + <::Currency as Currency<::AccountId>>::NegativeImbalance; parameter_types! { /// A reasonable default value for [`Trait::SignedClaimedHandicap`]. @@ -342,16 +342,16 @@ parameter_types! { pub const DefaultBlockGasLimit: u32 = 10_000_000; } -pub trait Trait: system::Trait { +pub trait Trait: frame_system::Trait { type Currency: Currency; type Time: Time; type Randomness: Randomness; /// The outer call dispatch type. - type Call: Parameter + Dispatchable::Origin> + IsSubType, Self>; + type Call: Parameter + Dispatchable::Origin> + IsSubType, Self>; /// The overarching event type. - type Event: From> + Into<::Event>; + type Event: From> + Into<::Event>; /// A function type to get the contract address given the instantiator. type DetermineContractAddress: ContractAddressFor, Self::AccountId>; @@ -469,7 +469,7 @@ impl ComputeDispatchFee<::Call, BalanceOf> for DefaultD decl_module! { /// Contracts module. - pub struct Module for enum Call where origin: ::Origin { + pub struct Module for enum Call where origin: ::Origin { /// Number of block delay an extrinsic claim surcharge has. /// /// When claim surcharge is called by an extrinsic the rent is checked @@ -630,10 +630,10 @@ decl_module! { fn claim_surcharge(origin, dest: T::AccountId, aux_sender: Option) { let origin = origin.into(); let (signed, rewarded) = match (origin, aux_sender) { - (Ok(system::RawOrigin::Signed(account)), None) => { + (Ok(frame_system::RawOrigin::Signed(account)), None) => { (true, account) }, - (Ok(system::RawOrigin::None), Some(aux_sender)) => { + (Ok(frame_system::RawOrigin::None), Some(aux_sender)) => { (false, aux_sender) }, _ => return Err( @@ -751,7 +751,7 @@ impl Module { DepositEvent { topics, event, - } => >::deposit_event_indexed( + } => >::deposit_event_indexed( &*topics, ::Event::from(event).into(), ), @@ -788,7 +788,7 @@ impl Module { .and_then(|c| c.get_alive()) .ok_or("Cannot restore from inexisting or tombstone contract")?; - let current_block = >::block_number(); + let current_block = >::block_number(); if origin_contract.last_write == Some(current_block) { return Err("Origin TrieId written in the current block"); @@ -870,8 +870,8 @@ decl_event! { pub enum Event where Balance = BalanceOf, - ::AccountId, - ::Hash + ::AccountId, + ::Hash { /// Transfer happened `from` to `to` with given `value` as part of a `call` or `instantiate`. Transfer(AccountId, AccountId, Balance), diff --git a/substrate/frame/contracts/src/rent.rs b/substrate/frame/contracts/src/rent.rs index d4ca5ec7f7..c75dd97ff3 100644 --- a/substrate/frame/contracts/src/rent.rs +++ b/substrate/frame/contracts/src/rent.rs @@ -17,9 +17,9 @@ use crate::{BalanceOf, ContractInfo, ContractInfoOf, TombstoneContractInfo, Trait, AliveContractInfo}; use sp_runtime::traits::{Bounded, CheckedDiv, CheckedMul, Saturating, Zero, SaturatedConversion}; -use support::traits::{Currency, ExistenceRequirement, Get, WithdrawReason, OnUnbalanced}; -use support::StorageMap; -use support::storage::child; +use frame_support::traits::{Currency, ExistenceRequirement, Get, WithdrawReason, OnUnbalanced}; +use frame_support::StorageMap; +use frame_support::storage::child; #[derive(PartialEq, Eq, Copy, Clone)] #[must_use] @@ -58,7 +58,7 @@ fn try_evict_or_and_pay_rent( Some(ContractInfo::Alive(contract)) => contract, }; - let current_block_number = >::block_number(); + let current_block_number = >::block_number(); // How much block has passed since the last deduction for the contract. let blocks_passed = { diff --git a/substrate/frame/contracts/src/tests.rs b/substrate/frame/contracts/src/tests.rs index 153a70d54b..160b1d74dc 100644 --- a/substrate/frame/contracts/src/tests.rs +++ b/substrate/frame/contracts/src/tests.rs @@ -32,29 +32,32 @@ use sp_runtime::{ traits::{BlakeTwo256, Hash, IdentityLookup, SignedExtension}, testing::{Digest, DigestItem, Header, UintAuthorityId, H256}, }; -use support::{ +use frame_support::{ assert_ok, assert_err, impl_outer_dispatch, impl_outer_event, impl_outer_origin, parameter_types, storage::child, StorageMap, StorageValue, traits::{Currency, Get}, weights::{DispatchInfo, DispatchClass, Weight}, }; use std::{cell::RefCell, sync::atomic::{AtomicUsize, Ordering}}; -use primitives::storage::well_known_keys; -use system::{self, EventRecord, Phase}; +use sp_core::storage::well_known_keys; +use frame_system::{self as system, EventRecord, Phase}; mod contract { // Re-export contents of the root. This basically // needs to give a name for the current crate. // This hack is required for `impl_outer_event!`. pub use super::super::*; - use support::impl_outer_event; + use frame_support::impl_outer_event; } + +use pallet_balances as balances; + impl_outer_event! { pub enum MetaEvent for Test { balances, contract, } } impl_outer_origin! { - pub enum Origin for Test { } + pub enum Origin for Test where system = frame_system { } } impl_outer_dispatch! { pub enum Call for Test where origin: Origin { @@ -98,7 +101,7 @@ parameter_types! { pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } -impl system::Trait for Test { +impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -115,7 +118,7 @@ impl system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type Version = (); } -impl balances::Trait for Test { +impl pallet_balances::Trait for Test { type Balance = u64; type OnFreeBalanceZero = Contract; type OnNewAccount = (); @@ -129,7 +132,7 @@ impl balances::Trait for Test { parameter_types! { pub const MinimumPeriod: u64 = 1; } -impl timestamp::Trait for Test { +impl pallet_timestamp::Trait for Test { type Moment = u64; type OnTimestampSet = (); type MinimumPeriod = MinimumPeriod; @@ -178,11 +181,11 @@ impl Trait for Test { type BlockGasLimit = BlockGasLimit; } -type Balances = balances::Module; -type Timestamp = timestamp::Module; +type Balances = pallet_balances::Module; +type Timestamp = pallet_timestamp::Module; type Contract = Module; -type System = system::Module; -type Randomness = randomness_collective_flip::Module; +type System = frame_system::Module; +type Randomness = pallet_randomness_collective_flip::Module; pub struct DummyContractAddressFor; impl ContractAddressFor for DummyContractAddressFor { @@ -194,7 +197,7 @@ impl ContractAddressFor for DummyContractAddressFor { pub struct DummyTrieIdGenerator; impl TrieIdGenerator for DummyTrieIdGenerator { fn trie_id(account_id: &u64) -> TrieId { - use primitives::storage::well_known_keys; + use sp_core::storage::well_known_keys; let new_seed = super::AccountCounter::mutate(|v| { *v = v.wrapping_add(1); @@ -270,8 +273,8 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { self.set_associated_consts(); - let mut t = system::GenesisConfig::default().build_storage::().unwrap(); - balances::GenesisConfig:: { + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + pallet_balances::GenesisConfig:: { balances: vec![], vesting: vec![], }.assimilate_storage(&mut t).unwrap(); @@ -289,7 +292,7 @@ impl ExtBuilder { /// Generate Wasm binary and code hash from wabt source. fn compile_module(wabt_module: &str) -> Result<(Vec, ::Output), wabt::Error> - where T: system::Trait + where T: frame_system::Trait { let wasm = wabt::wat2wasm(wabt_module)?; let code_hash = T::Hashing::hash(&wasm); @@ -426,7 +429,7 @@ fn instantiate_and_call_and_deposit_event() { assert_eq!(System::events(), vec![ EventRecord { phase: Phase::ApplyExtrinsic(0), - event: MetaEvent::balances(balances::RawEvent::NewAccount(1, 1_000_000)), + event: MetaEvent::balances(pallet_balances::RawEvent::NewAccount(1, 1_000_000)), topics: vec![], }, EventRecord { @@ -437,7 +440,7 @@ fn instantiate_and_call_and_deposit_event() { EventRecord { phase: Phase::ApplyExtrinsic(0), event: MetaEvent::balances( - balances::RawEvent::NewAccount(BOB, 100) + pallet_balances::RawEvent::NewAccount(BOB, 100) ), topics: vec![], }, @@ -484,7 +487,7 @@ const CODE_DISPATCH_CALL: &str = r#" fn dispatch_call() { // This test can fail due to the encoding changes. In case it becomes too annoying // let's rewrite so as we use this module controlled call or we serialize it in runtime. - let encoded = Encode::encode(&Call::Balances(balances::Call::transfer(CHARLIE, 50))); + let encoded = Encode::encode(&Call::Balances(pallet_balances::Call::transfer(CHARLIE, 50))); assert_eq!(&encoded[..], &hex!("00000300000000000000C8")[..]); let (wasm, code_hash) = compile_module::(CODE_DISPATCH_CALL).unwrap(); @@ -499,7 +502,7 @@ fn dispatch_call() { assert_eq!(System::events(), vec![ EventRecord { phase: Phase::ApplyExtrinsic(0), - event: MetaEvent::balances(balances::RawEvent::NewAccount(1, 1_000_000)), + event: MetaEvent::balances(pallet_balances::RawEvent::NewAccount(1, 1_000_000)), topics: vec![], }, EventRecord { @@ -528,7 +531,7 @@ fn dispatch_call() { assert_eq!(System::events(), vec![ EventRecord { phase: Phase::ApplyExtrinsic(0), - event: MetaEvent::balances(balances::RawEvent::NewAccount(1, 1_000_000)), + event: MetaEvent::balances(pallet_balances::RawEvent::NewAccount(1, 1_000_000)), topics: vec![], }, EventRecord { @@ -539,7 +542,7 @@ fn dispatch_call() { EventRecord { phase: Phase::ApplyExtrinsic(0), event: MetaEvent::balances( - balances::RawEvent::NewAccount(BOB, 100) + pallet_balances::RawEvent::NewAccount(BOB, 100) ), topics: vec![], }, @@ -558,14 +561,14 @@ fn dispatch_call() { EventRecord { phase: Phase::ApplyExtrinsic(0), event: MetaEvent::balances( - balances::RawEvent::NewAccount(CHARLIE, 50) + pallet_balances::RawEvent::NewAccount(CHARLIE, 50) ), topics: vec![], }, EventRecord { phase: Phase::ApplyExtrinsic(0), event: MetaEvent::balances( - balances::RawEvent::Transfer(BOB, CHARLIE, 50, 0) + pallet_balances::RawEvent::Transfer(BOB, CHARLIE, 50, 0) ), topics: vec![], }, @@ -602,7 +605,7 @@ const CODE_DISPATCH_CALL_THEN_TRAP: &str = r#" fn dispatch_call_not_dispatched_after_top_level_transaction_failure() { // This test can fail due to the encoding changes. In case it becomes too annoying // let's rewrite so as we use this module controlled call or we serialize it in runtime. - let encoded = Encode::encode(&Call::Balances(balances::Call::transfer(CHARLIE, 50))); + let encoded = Encode::encode(&Call::Balances(pallet_balances::Call::transfer(CHARLIE, 50))); assert_eq!(&encoded[..], &hex!("00000300000000000000C8")[..]); let (wasm, code_hash) = compile_module::(CODE_DISPATCH_CALL_THEN_TRAP).unwrap(); @@ -617,7 +620,7 @@ fn dispatch_call_not_dispatched_after_top_level_transaction_failure() { assert_eq!(System::events(), vec![ EventRecord { phase: Phase::ApplyExtrinsic(0), - event: MetaEvent::balances(balances::RawEvent::NewAccount(1, 1_000_000)), + event: MetaEvent::balances(pallet_balances::RawEvent::NewAccount(1, 1_000_000)), topics: vec![], }, EventRecord { @@ -650,7 +653,7 @@ fn dispatch_call_not_dispatched_after_top_level_transaction_failure() { assert_eq!(System::events(), vec![ EventRecord { phase: Phase::ApplyExtrinsic(0), - event: MetaEvent::balances(balances::RawEvent::NewAccount(1, 1_000_000)), + event: MetaEvent::balances(pallet_balances::RawEvent::NewAccount(1, 1_000_000)), topics: vec![], }, EventRecord { @@ -661,7 +664,7 @@ fn dispatch_call_not_dispatched_after_top_level_transaction_failure() { EventRecord { phase: Phase::ApplyExtrinsic(0), event: MetaEvent::balances( - balances::RawEvent::NewAccount(BOB, 100) + pallet_balances::RawEvent::NewAccount(BOB, 100) ), topics: vec![], }, @@ -802,7 +805,7 @@ mod call { fn test_set_rent_code_and_hash() { // This test can fail due to the encoding changes. In case it becomes too annoying // let's rewrite so as we use this module controlled call or we serialize it in runtime. - let encoded = Encode::encode(&Call::Balances(balances::Call::transfer(CHARLIE, 50))); + let encoded = Encode::encode(&Call::Balances(pallet_balances::Call::transfer(CHARLIE, 50))); assert_eq!(&encoded[..], &hex!("00000300000000000000C8")[..]); let (wasm, code_hash) = compile_module::(CODE_SET_RENT).unwrap(); @@ -816,7 +819,7 @@ fn test_set_rent_code_and_hash() { assert_eq!(System::events(), vec![ EventRecord { phase: Phase::ApplyExtrinsic(0), - event: MetaEvent::balances(balances::RawEvent::NewAccount(1, 1_000_000)), + event: MetaEvent::balances(pallet_balances::RawEvent::NewAccount(1, 1_000_000)), topics: vec![], }, EventRecord { @@ -841,7 +844,7 @@ fn storage_size() { Origin::signed(ALICE), 30_000, 100_000, code_hash.into(), - ::Balance::from(1_000u32).encode() // rent allowance + ::Balance::from(1_000u32).encode() // rent allowance )); let bob_contract = ContractInfoOf::::get(BOB).unwrap().get_alive().unwrap(); assert_eq!(bob_contract.storage_size, ::StorageSizeOffset::get() + 4); @@ -868,7 +871,7 @@ fn deduct_blocks() { Origin::signed(ALICE), 30_000, 100_000, code_hash.into(), - ::Balance::from(1_000u32).encode() // rent allowance + ::Balance::from(1_000u32).encode() // rent allowance )); // Check creation @@ -962,7 +965,7 @@ fn claim_surcharge(blocks: u64, trigger_call: impl Fn() -> bool, removes: bool) Origin::signed(ALICE), 100, 100_000, code_hash.into(), - ::Balance::from(1_000u32).encode() // rent allowance + ::Balance::from(1_000u32).encode() // rent allowance )); // Advance blocks @@ -995,7 +998,7 @@ fn removals(trigger_call: impl Fn() -> bool) { Origin::signed(ALICE), 100, 100_000, code_hash.into(), - ::Balance::from(1_000u32).encode() // rent allowance + ::Balance::from(1_000u32).encode() // rent allowance )); let subsistence_threshold = 50 /*existential_deposit*/ + 16 /*tombstone_deposit*/; @@ -1031,7 +1034,7 @@ fn removals(trigger_call: impl Fn() -> bool) { Origin::signed(ALICE), 1_000, 100_000, code_hash.into(), - ::Balance::from(100u32).encode() // rent allowance + ::Balance::from(100u32).encode() // rent allowance )); // Trigger rent must have no effect @@ -1066,7 +1069,7 @@ fn removals(trigger_call: impl Fn() -> bool) { Origin::signed(ALICE), 50+Balances::minimum_balance(), 100_000, code_hash.into(), - ::Balance::from(1_000u32).encode() // rent allowance + ::Balance::from(1_000u32).encode() // rent allowance )); // Trigger rent must have no effect @@ -1110,7 +1113,7 @@ fn call_removed_contract() { Origin::signed(ALICE), 100, 100_000, code_hash.into(), - ::Balance::from(1_000u32).encode() // rent allowance + ::Balance::from(1_000u32).encode() // rent allowance )); // Calling contract should succeed. @@ -1311,7 +1314,7 @@ fn restoration(test_different_storage: bool, test_restore_to_with_dirty_storage: assert_eq!(System::events(), vec![ EventRecord { phase: Phase::ApplyExtrinsic(0), - event: MetaEvent::balances(balances::RawEvent::NewAccount(1, 1_000_000)), + event: MetaEvent::balances(pallet_balances::RawEvent::NewAccount(1, 1_000_000)), topics: vec![], }, EventRecord { @@ -1333,7 +1336,7 @@ fn restoration(test_different_storage: bool, test_restore_to_with_dirty_storage: 30_000, 100_000, set_rent_code_hash.into(), - ::Balance::from(0u32).encode() + ::Balance::from(0u32).encode() )); // Check if `BOB` was created successfully and that the rent allowance is @@ -1370,7 +1373,7 @@ fn restoration(test_different_storage: bool, test_restore_to_with_dirty_storage: 30_000, 100_000, restoration_code_hash.into(), - ::Balance::from(0u32).encode() + ::Balance::from(0u32).encode() )); // Before performing a call to `DJANGO` save its original trie id. @@ -2425,7 +2428,7 @@ fn get_runtime_storage() { ExtBuilder::default().existential_deposit(50).build().execute_with(|| { Balances::deposit_creating(&ALICE, 1_000_000); - support::storage::unhashed::put_raw( + frame_support::storage::unhashed::put_raw( &[1, 2, 3, 4], 0x14144020u32.to_le_bytes().to_vec().as_ref() ); diff --git a/substrate/frame/contracts/src/wasm/code_cache.rs b/substrate/frame/contracts/src/wasm/code_cache.rs index 7264122397..ada28ffc15 100644 --- a/substrate/frame/contracts/src/wasm/code_cache.rs +++ b/substrate/frame/contracts/src/wasm/code_cache.rs @@ -31,7 +31,7 @@ use crate::wasm::{prepare, runtime::Env, PrefabWasmModule}; use crate::{CodeHash, CodeStorage, PristineCode, Schedule, Trait}; use sp_std::prelude::*; use sp_runtime::traits::{Hash, Bounded}; -use support::StorageMap; +use frame_support::StorageMap; /// Gas metering token that used for charging storing code into the code storage. /// diff --git a/substrate/frame/contracts/src/wasm/env_def/macros.rs b/substrate/frame/contracts/src/wasm/env_def/macros.rs index 0f36095048..e02be90b8e 100644 --- a/substrate/frame/contracts/src/wasm/env_def/macros.rs +++ b/substrate/frame/contracts/src/wasm/env_def/macros.rs @@ -96,7 +96,7 @@ macro_rules! unmarshall_then_body { #[inline(always)] pub fn constrain_closure(f: F) -> F where - F: FnOnce() -> Result, + F: FnOnce() -> Result, { f } @@ -110,14 +110,14 @@ macro_rules! unmarshall_then_body_then_marshall { unmarshall_then_body!($body, $ctx, $args_iter, $( $names : $params ),*) }); let r = body()?; - return Ok(sandbox::ReturnValue::Value({ use $crate::wasm::env_def::ConvertibleToWasm; r.to_typed_value() })) + return Ok(sp_sandbox::ReturnValue::Value({ use $crate::wasm::env_def::ConvertibleToWasm; r.to_typed_value() })) }); ( $args_iter:ident, $ctx:ident, ( $( $names:ident : $params:ty ),* ) => $body:tt ) => ({ let body = $crate::wasm::env_def::macros::constrain_closure::<(), _>(|| { unmarshall_then_body!($body, $ctx, $args_iter, $( $names : $params ),*) }); body()?; - return Ok(sandbox::ReturnValue::Unit) + return Ok(sp_sandbox::ReturnValue::Unit) }) } @@ -126,8 +126,8 @@ macro_rules! define_func { ( < E: $ext_ty:tt > $name:ident ( $ctx: ident $(, $names:ident : $params:ty)*) $(-> $returns:ty)* => $body:tt ) => { fn $name< E: $ext_ty >( $ctx: &mut $crate::wasm::Runtime, - args: &[sandbox::TypedValue], - ) -> Result { + args: &[sp_sandbox::TypedValue], + ) -> Result { #[allow(unused)] let mut args = args.iter(); @@ -196,7 +196,7 @@ mod tests { use parity_wasm::elements::FunctionType; use parity_wasm::elements::ValueType; use sp_runtime::traits::Zero; - use sandbox::{self, ReturnValue, TypedValue}; + use sp_sandbox::{self, ReturnValue, TypedValue}; use crate::wasm::tests::MockExt; use crate::wasm::Runtime; use crate::exec::Ext; @@ -206,15 +206,15 @@ mod tests { fn macro_unmarshall_then_body_then_marshall_value_or_trap() { fn test_value( _ctx: &mut u32, - args: &[sandbox::TypedValue], - ) -> Result { + args: &[sp_sandbox::TypedValue], + ) -> Result { let mut args = args.iter(); unmarshall_then_body_then_marshall!( args, _ctx, (a: u32, b: u32) -> u32 => { if b == 0 { - Err(sandbox::HostError) + Err(sp_sandbox::HostError) } else { Ok(a / b) } @@ -234,8 +234,8 @@ mod tests { fn macro_unmarshall_then_body_then_marshall_unit() { fn test_unit( ctx: &mut u32, - args: &[sandbox::TypedValue], - ) -> Result { + args: &[sp_sandbox::TypedValue], + ) -> Result { let mut args = args.iter(); unmarshall_then_body_then_marshall!( args, @@ -260,11 +260,11 @@ mod tests { if !amount.is_zero() { Ok(()) } else { - Err(sandbox::HostError) + Err(sp_sandbox::HostError) } }); - let _f: fn(&mut Runtime, &[sandbox::TypedValue]) - -> Result = ext_gas::; + let _f: fn(&mut Runtime, &[sp_sandbox::TypedValue]) + -> Result = ext_gas::; } #[test] @@ -312,7 +312,7 @@ mod tests { if !amount.is_zero() { Ok(()) } else { - Err(sandbox::HostError) + Err(sp_sandbox::HostError) } }, ); diff --git a/substrate/frame/contracts/src/wasm/env_def/mod.rs b/substrate/frame/contracts/src/wasm/env_def/mod.rs index d51a157910..30c1b5455d 100644 --- a/substrate/frame/contracts/src/wasm/env_def/mod.rs +++ b/substrate/frame/contracts/src/wasm/env_def/mod.rs @@ -17,7 +17,7 @@ use super::Runtime; use crate::exec::Ext; -use sandbox::{self, TypedValue}; +use sp_sandbox::{self, TypedValue}; use parity_wasm::elements::{FunctionType, ValueType}; #[macro_use] @@ -69,8 +69,8 @@ impl ConvertibleToWasm for u64 { pub(crate) type HostFunc = fn( &mut Runtime, - &[sandbox::TypedValue] - ) -> Result; + &[sp_sandbox::TypedValue] + ) -> Result; pub(crate) trait FunctionImplProvider { fn impls)>(f: &mut F); diff --git a/substrate/frame/contracts/src/wasm/mod.rs b/substrate/frame/contracts/src/wasm/mod.rs index 273b7fb037..472951efb5 100644 --- a/substrate/frame/contracts/src/wasm/mod.rs +++ b/substrate/frame/contracts/src/wasm/mod.rs @@ -24,7 +24,7 @@ use crate::gas::GasMeter; use sp_std::prelude::*; use codec::{Encode, Decode}; -use sandbox; +use sp_sandbox; #[macro_use] mod env_def; @@ -114,7 +114,7 @@ impl<'a, T: Trait> crate::exec::Vm for WasmVm<'a> { gas_meter: &mut GasMeter, ) -> ExecResult { let memory = - sandbox::Memory::new(exec.prefab_module.initial, Some(exec.prefab_module.maximum)) + sp_sandbox::Memory::new(exec.prefab_module.initial, Some(exec.prefab_module.maximum)) .unwrap_or_else(|_| { // unlike `.expect`, explicit panic preserves the source location. // Needed as we can't use `RUST_BACKTRACE` in here. @@ -125,7 +125,7 @@ impl<'a, T: Trait> crate::exec::Vm for WasmVm<'a> { ) }); - let mut imports = sandbox::EnvironmentDefinitionBuilder::new(); + let mut imports = sp_sandbox::EnvironmentDefinitionBuilder::new(); imports.add_memory("env", "memory", memory.clone()); runtime::Env::impls(&mut |name, func_ptr| { imports.add_host_func("env", name, func_ptr); @@ -141,7 +141,7 @@ impl<'a, T: Trait> crate::exec::Vm for WasmVm<'a> { // Instantiate the instance from the instrumented module code and invoke the contract // entrypoint. - let result = sandbox::Instance::new(&exec.prefab_module.code, &imports, &mut runtime) + let result = sp_sandbox::Instance::new(&exec.prefab_module.code, &imports, &mut runtime) .and_then(|mut instance| instance.invoke(exec.entrypoint_name, &[], &mut runtime)); to_execution_result(runtime, result) } @@ -152,7 +152,7 @@ mod tests { use super::*; use std::collections::HashMap; use std::cell::RefCell; - use primitives::H256; + use sp_core::H256; use crate::exec::{Ext, StorageKey, ExecError, ExecReturnValue, STATUS_SUCCESS}; use crate::gas::{Gas, GasMeter}; use crate::tests::{Test, Call}; @@ -1111,7 +1111,7 @@ mod tests { assert_eq!( &mock_ext.dispatches, &[DispatchEntry( - Call::Balances(balances::Call::set_balance(42, 1337, 0)), + Call::Balances(pallet_balances::Call::set_balance(42, 1337, 0)), )] ); } diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 0204d4eba0..98675aa0e4 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -21,8 +21,8 @@ use crate::exec::{ Ext, ExecResult, ExecError, ExecReturnValue, StorageKey, TopicOf, STATUS_SUCCESS, }; use crate::gas::{Gas, GasMeter, Token, GasMeterResult, approx_gas_for_balance}; -use sandbox; -use system; +use sp_sandbox; +use frame_system; use sp_std::prelude::*; use sp_std::convert::TryInto; use sp_std::mem; @@ -48,7 +48,7 @@ pub(crate) struct Runtime<'a, E: Ext + 'a> { ext: &'a mut E, scratch_buf: Vec, schedule: &'a Schedule, - memory: sandbox::Memory, + memory: sp_sandbox::Memory, gas_meter: &'a mut GasMeter, special_trap: Option, } @@ -57,7 +57,7 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { ext: &'a mut E, input_data: Vec, schedule: &'a Schedule, - memory: sandbox::Memory, + memory: sp_sandbox::Memory, gas_meter: &'a mut GasMeter, ) -> Self { Runtime { @@ -74,7 +74,7 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { pub(crate) fn to_execution_result( runtime: Runtime, - sandbox_result: Result, + sandbox_result: Result, ) -> ExecResult { // Special case. The trap was the result of the execution `return` host function. if let Some(SpecialTrap::Return(data)) = runtime.special_trap { @@ -84,12 +84,12 @@ pub(crate) fn to_execution_result( // Check the exact type of the error. match sandbox_result { // No traps were generated. Proceed normally. - Ok(sandbox::ReturnValue::Unit) => { + Ok(sp_sandbox::ReturnValue::Unit) => { let mut buffer = runtime.scratch_buf; buffer.clear(); Ok(ExecReturnValue { status: STATUS_SUCCESS, data: buffer }) } - Ok(sandbox::ReturnValue::Value(sandbox::TypedValue::I32(exit_code))) => { + Ok(sp_sandbox::ReturnValue::Value(sp_sandbox::TypedValue::I32(exit_code))) => { let status = (exit_code & 0xFF).try_into() .expect("exit_code is masked into the range of a u8; qed"); Ok(ExecReturnValue { status, data: runtime.scratch_buf }) @@ -105,10 +105,10 @@ pub(crate) fn to_execution_result( // // Because panics are really undesirable in the runtime code, we treat this as // a trap for now. Eventually, we might want to revisit this. - Err(sandbox::Error::Module) => + Err(sp_sandbox::Error::Module) => Err(ExecError { reason: "validation error", buffer: runtime.scratch_buf }), // Any other kind of a trap should result in a failure. - Err(sandbox::Error::Execution) | Err(sandbox::Error::OutOfBounds) => + Err(sp_sandbox::Error::Execution) | Err(sp_sandbox::Error::OutOfBounds) => Err(ExecError { reason: "during execution", buffer: runtime.scratch_buf }), } } @@ -182,10 +182,10 @@ fn charge_gas>( gas_meter: &mut GasMeter, metadata: &Tok::Metadata, token: Tok, -) -> Result<(), sandbox::HostError> { +) -> Result<(), sp_sandbox::HostError> { match gas_meter.charge(metadata, token) { GasMeterResult::Proceed => Ok(()), - GasMeterResult::OutOfGas => Err(sandbox::HostError), + GasMeterResult::OutOfGas => Err(sp_sandbox::HostError), } } @@ -201,11 +201,11 @@ fn read_sandbox_memory( ctx: &mut Runtime, ptr: u32, len: u32, -) -> Result, sandbox::HostError> { +) -> Result, sp_sandbox::HostError> { charge_gas(ctx.gas_meter, ctx.schedule, RuntimeToken::ReadMemory(len))?; let mut buf = vec![0u8; len as usize]; - ctx.memory.get(ptr, buf.as_mut_slice()).map_err(|_| sandbox::HostError)?; + ctx.memory.get(ptr, buf.as_mut_slice()).map_err(|_| sp_sandbox::HostError)?; Ok(buf) } @@ -221,11 +221,11 @@ fn read_sandbox_memory_into_scratch( ctx: &mut Runtime, ptr: u32, len: u32, -) -> Result<(), sandbox::HostError> { +) -> Result<(), sp_sandbox::HostError> { charge_gas(ctx.gas_meter, ctx.schedule, RuntimeToken::ReadMemory(len))?; ctx.scratch_buf.resize(len as usize, 0); - ctx.memory.get(ptr, ctx.scratch_buf.as_mut_slice()).map_err(|_| sandbox::HostError)?; + ctx.memory.get(ptr, ctx.scratch_buf.as_mut_slice()).map_err(|_| sp_sandbox::HostError)?; Ok(()) } @@ -241,7 +241,7 @@ fn read_sandbox_memory_into_buf( ctx: &mut Runtime, ptr: u32, buf: &mut [u8], -) -> Result<(), sandbox::HostError> { +) -> Result<(), sp_sandbox::HostError> { charge_gas(ctx.gas_meter, ctx.schedule, RuntimeToken::ReadMemory(buf.len() as u32))?; ctx.memory.get(ptr, buf).map_err(Into::into) @@ -260,9 +260,9 @@ fn read_sandbox_memory_as( ctx: &mut Runtime, ptr: u32, len: u32, -) -> Result { +) -> Result { let buf = read_sandbox_memory(ctx, ptr, len)?; - D::decode(&mut &buf[..]).map_err(|_| sandbox::HostError) + D::decode(&mut &buf[..]).map_err(|_| sp_sandbox::HostError) } /// Write the given buffer to the designated location in the sandbox memory, consuming @@ -276,10 +276,10 @@ fn read_sandbox_memory_as( fn write_sandbox_memory( schedule: &Schedule, gas_meter: &mut GasMeter, - memory: &sandbox::Memory, + memory: &sp_sandbox::Memory, ptr: u32, buf: &[u8], -) -> Result<(), sandbox::HostError> { +) -> Result<(), sp_sandbox::HostError> { charge_gas(gas_meter, schedule, RuntimeToken::WriteMemory(buf.len() as u32))?; memory.set(ptr, buf)?; @@ -318,7 +318,7 @@ define_env!(Env, , // - value_len: the length of the value. If `value_non_null` is set to 0, then this parameter is ignored. ext_set_storage(ctx, key_ptr: u32, value_non_null: u32, value_ptr: u32, value_len: u32) => { if value_non_null != 0 && ctx.ext.max_value_size() < value_len { - return Err(sandbox::HostError); + return Err(sp_sandbox::HostError); } let mut key: StorageKey = [0; 32]; read_sandbox_memory_into_buf(ctx, key_ptr, &mut key)?; @@ -328,7 +328,7 @@ define_env!(Env, , } else { None }; - ctx.ext.set_storage(key, value).map_err(|_| sandbox::HostError)?; + ctx.ext.set_storage(key, value).map_err(|_| sp_sandbox::HostError)?; Ok(()) }, @@ -382,7 +382,7 @@ define_env!(Env, , input_data_ptr: u32, input_data_len: u32 ) -> u32 => { - let callee: <::T as system::Trait>::AccountId = + let callee: <::T as frame_system::Trait>::AccountId = read_sandbox_memory_as(ctx, callee_ptr, callee_len)?; let value: BalanceOf<::T> = read_sandbox_memory_as(ctx, value_ptr, value_len)?; @@ -532,7 +532,7 @@ define_env!(Env, , // The trap mechanism is used to immediately terminate the execution. // This trap should be handled appropriately before returning the result // to the user of this crate. - Err(sandbox::HostError) + Err(sp_sandbox::HostError) }, // Stores the address of the caller into the scratch buffer. @@ -597,7 +597,7 @@ define_env!(Env, , ext_random(ctx, subject_ptr: u32, subject_len: u32) => { // The length of a subject can't exceed `max_subject_len`. if subject_len > ctx.schedule.max_subject_len { - return Err(sandbox::HostError); + return Err(sp_sandbox::HostError); } let subject_buf = read_sandbox_memory(ctx, subject_ptr, subject_len)?; @@ -675,7 +675,7 @@ define_env!(Env, , delta_ptr: u32, delta_count: u32 ) => { - let dest: <::T as system::Trait>::AccountId = + let dest: <::T as frame_system::Trait>::AccountId = read_sandbox_memory_as(ctx, dest_ptr, dest_len)?; let code_hash: CodeHash<::T> = read_sandbox_memory_as(ctx, code_hash_ptr, code_hash_len)?; @@ -696,7 +696,7 @@ define_env!(Env, , delta.push(delta_key); // Offset key_ptr to the next element. - key_ptr = key_ptr.checked_add(KEY_SIZE as u32).ok_or_else(|| sandbox::HostError)?; + key_ptr = key_ptr.checked_add(KEY_SIZE as u32).ok_or_else(|| sp_sandbox::HostError)?; } delta @@ -729,13 +729,13 @@ define_env!(Env, , let offset = offset as usize; if offset > ctx.scratch_buf.len() { // Offset can't be larger than scratch buffer length. - return Err(sandbox::HostError); + return Err(sp_sandbox::HostError); } // This can't panic since `offset <= ctx.scratch_buf.len()`. let src = &ctx.scratch_buf[offset..]; if src.len() != len as usize { - return Err(sandbox::HostError); + return Err(sp_sandbox::HostError); } // Finally, perform the write. @@ -775,12 +775,12 @@ define_env!(Env, , // If there are more than `max_event_topics`, then trap. if topics.len() > ctx.schedule.max_event_topics as usize { - return Err(sandbox::HostError); + return Err(sp_sandbox::HostError); } // Check for duplicate topics. If there are any, then trap. if has_duplicates(&mut topics) { - return Err(sandbox::HostError); + return Err(sp_sandbox::HostError); } let event_data = read_sandbox_memory(ctx, data_ptr, data_len)?; diff --git a/substrate/frame/democracy/Cargo.toml b/substrate/frame/democracy/Cargo.toml index 5772f11af1..7e0a9ad53d 100644 --- a/substrate/frame/democracy/Cargo.toml +++ b/substrate/frame/democracy/Cargo.toml @@ -11,12 +11,12 @@ codec = { package = "parity-scale-codec", version = "1.0.0", default-features = sp-std = { path = "../../primitives/std", default-features = false } sp-io = { path = "../../primitives/io", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } [dev-dependencies] -primitives = { package = "sp-core", path = "../../primitives/core" } -balances = { package = "pallet-balances", path = "../balances" } +sp-core = { path = "../../primitives/core" } +pallet-balances = { path = "../balances" } [features] default = ["std"] @@ -26,7 +26,7 @@ std = [ "codec/std", "sp-std/std", "sp-io/std", - "support/std", + "frame-support/std", "sp-runtime/std", - "system/std", + "frame-system/std", ] diff --git a/substrate/frame/democracy/src/lib.rs b/substrate/frame/democracy/src/lib.rs index 4b4c070cda..ea51c4e1d9 100644 --- a/substrate/frame/democracy/src/lib.rs +++ b/substrate/frame/democracy/src/lib.rs @@ -25,7 +25,7 @@ use sp_runtime::{ traits::{Zero, Bounded, CheckedMul, CheckedDiv, EnsureOrigin, Hash, Dispatchable, Saturating}, }; use codec::{Ref, Encode, Decode, Input, Output, Error}; -use support::{ +use frame_support::{ decl_module, decl_storage, decl_event, ensure, dispatch, Parameter, @@ -35,7 +35,7 @@ use support::{ OnFreeBalanceZero, OnUnbalanced } }; -use system::{ensure_signed, ensure_root}; +use frame_system::{self as system, ensure_signed, ensure_root}; mod vote_threshold; pub use vote_threshold::{Approved, VoteThreshold}; @@ -173,13 +173,13 @@ impl Decode for Vote { } } -type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; +type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; type NegativeImbalanceOf = -<::Currency as Currency<::AccountId>>::NegativeImbalance; +<::Currency as Currency<::AccountId>>::NegativeImbalance; -pub trait Trait: system::Trait + Sized { +pub trait Trait: frame_system::Trait + Sized { type Proposal: Parameter + Dispatchable; - type Event: From> + Into<::Event>; + type Event: From> + Into<::Event>; /// Currency type for this module. type Currency: ReservableCurrency @@ -281,7 +281,7 @@ decl_storage! { pub LowestUnbaked get(fn lowest_unbaked) build(|_| 0 as ReferendumIndex): ReferendumIndex; /// Information concerning any given referendum. pub ReferendumInfoOf get(fn referendum_info): - map ReferendumIndex => Option<(ReferendumInfo)>; + map ReferendumIndex => Option>; /// Queue of successful referenda to be dispatched. Stored ordered by block number. pub DispatchQueue get(fn dispatch_queue): Vec<(T::BlockNumber, T::Hash, ReferendumIndex)>; @@ -323,9 +323,9 @@ decl_storage! { decl_event!( pub enum Event where Balance = BalanceOf, - ::AccountId, - ::Hash, - ::BlockNumber, + ::AccountId, + ::Hash, + ::BlockNumber, { /// A motion has been proposed by a public account. Proposed(PropIndex, Balance), @@ -487,7 +487,7 @@ decl_module! { T::ExternalOrigin::ensure_origin(origin)?; ensure!(!>::exists(), "proposal already made"); if let Some((until, _)) = >::get(proposal_hash) { - ensure!(>::block_number() >= until, "proposal still blacklisted"); + ensure!(>::block_number() >= until, "proposal still blacklisted"); } >::put((proposal_hash, VoteThreshold::SuperMajorityApprove)); } @@ -538,7 +538,7 @@ decl_module! { ensure!(proposal_hash == e_proposal_hash, "invalid hash"); >::kill(); - let now = >::block_number(); + let now = >::block_number(); // We don't consider it an error if `vote_period` is too low, like `emergency_propose`. let period = voting_period.max(T::EmergencyVotingPeriod::get()); Self::inject_referendum(now + period, proposal_hash, threshold, delay); @@ -562,7 +562,7 @@ decl_module! { .err().ok_or("identity may not veto a proposal twice")?; existing_vetoers.insert(insert_position, who.clone()); - let until = >::block_number() + T::CooloffPeriod::get(); + let until = >::block_number() + T::CooloffPeriod::get(); >::insert(&proposal_hash, (until, existing_vetoers)); Self::deposit_event(RawEvent::Vetoed(who, proposal_hash, until)); @@ -659,7 +659,7 @@ decl_module! { ensure!(>::exists(&who), "not delegated"); let (_, conviction) = >::take(&who); // Indefinite lock is reduced to the maximum voting lock that could be possible. - let now = >::block_number(); + let now = >::block_number(); let locked_until = now + T::EnactmentPeriod::get() * conviction.lock_periods().into(); T::Currency::set_lock( DEMOCRACY_ID, @@ -691,7 +691,7 @@ decl_module! { .saturating_mul(T::PreimageByteDeposit::get()); T::Currency::reserve(&who, deposit)?; - let now = >::block_number(); + let now = >::block_number(); >::insert(proposal_hash, (encoded_proposal, who.clone(), deposit, now)); Self::deposit_event(RawEvent::PreimageNoted(proposal_hash, who, deposit)); @@ -707,7 +707,7 @@ decl_module! { let queue = >::get(); ensure!(queue.iter().any(|item| &item.1 == &proposal_hash), "not imminent"); - let now = >::block_number(); + let now = >::block_number(); let free = >::zero(); >::insert(proposal_hash, (encoded_proposal, who.clone(), free, now)); @@ -724,7 +724,7 @@ decl_module! { let who = ensure_signed(origin)?; let (_, old, deposit, then) = >::get(&proposal_hash).ok_or("not found")?; - let now = >::block_number(); + let now = >::block_number(); let (voting, enactment) = (T::VotingPeriod::get(), T::EnactmentPeriod::get()); let additional = if who == old { Zero::zero() } else { enactment }; ensure!(now >= then + voting + additional, "too early"); @@ -863,7 +863,7 @@ impl Module { delay: T::BlockNumber ) -> ReferendumIndex { >::inject_referendum( - >::block_number() + T::VotingPeriod::get(), + >::block_number() + T::VotingPeriod::get(), proposal_hash, threshold, delay @@ -927,7 +927,7 @@ impl Module { let _ = T::Currency::unreserve(&who, amount); Self::deposit_event(RawEvent::PreimageUsed(proposal_hash, who, amount)); - let ok = proposal.dispatch(system::RawOrigin::Root.into()).is_ok(); + let ok = proposal.dispatch(frame_system::RawOrigin::Root.into()).is_ok(); Self::deposit_event(RawEvent::Executed(index, ok)); Ok(()) @@ -1088,15 +1088,15 @@ impl OnFreeBalanceZero for Module { mod tests { use super::*; use std::cell::RefCell; - use support::{ + use frame_support::{ impl_outer_origin, impl_outer_dispatch, assert_noop, assert_ok, parameter_types, traits::Contains, weights::Weight, }; - use primitives::H256; + use sp_core::H256; use sp_runtime::{traits::{BlakeTwo256, IdentityLookup, Bounded}, testing::Header, Perbill}; - use balances::BalanceLock; - use system::EnsureSignedBy; + use pallet_balances::BalanceLock; + use frame_system::EnsureSignedBy; const AYE: Vote = Vote{ aye: true, conviction: Conviction::None }; const NAY: Vote = Vote{ aye: false, conviction: Conviction::None }; @@ -1104,12 +1104,12 @@ mod tests { const BIG_NAY: Vote = Vote{ aye: false, conviction: Conviction::Locked1x }; impl_outer_origin! { - pub enum Origin for Test {} + pub enum Origin for Test where system = frame_system {} } impl_outer_dispatch! { pub enum Call for Test where origin: Origin { - balances::Balances, + pallet_balances::Balances, democracy::Democracy, } } @@ -1123,7 +1123,7 @@ mod tests { pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } - impl system::Trait for Test { + impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -1145,7 +1145,7 @@ mod tests { pub const TransferFee: u64 = 0; pub const CreationFee: u64 = 0; } - impl balances::Trait for Test { + impl pallet_balances::Trait for Test { type Balance = u64; type OnFreeBalanceZero = (); type OnNewAccount = (); @@ -1185,7 +1185,7 @@ mod tests { impl super::Trait for Test { type Proposal = Call; type Event = (); - type Currency = balances::Module; + type Currency = pallet_balances::Module; type EnactmentPeriod = EnactmentPeriod; type LaunchPeriod = LaunchPeriod; type VotingPeriod = VotingPeriod; @@ -1203,8 +1203,8 @@ mod tests { } fn new_test_ext() -> sp_io::TestExternalities { - let mut t = system::GenesisConfig::default().build_storage::().unwrap(); - balances::GenesisConfig::{ + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + pallet_balances::GenesisConfig::{ balances: vec![(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)], vesting: vec![], }.assimilate_storage(&mut t).unwrap(); @@ -1212,8 +1212,8 @@ mod tests { sp_io::TestExternalities::new(t) } - type System = system::Module; - type Balances = balances::Module; + type System = frame_system::Module; + type Balances = pallet_balances::Module; type Democracy = Module; #[test] @@ -1226,7 +1226,7 @@ mod tests { } fn set_balance_proposal(value: u64) -> Vec { - Call::Balances(balances::Call::set_balance(42, value, 0)).encode() + Call::Balances(pallet_balances::Call::set_balance(42, value, 0)).encode() } fn set_balance_proposal_hash(value: u64) -> H256 { diff --git a/substrate/frame/elections-phragmen/Cargo.toml b/substrate/frame/elections-phragmen/Cargo.toml index 0778ef25fd..df253e0f02 100644 --- a/substrate/frame/elections-phragmen/Cargo.toml +++ b/substrate/frame/elections-phragmen/Cargo.toml @@ -7,16 +7,16 @@ edition = "2018" [dependencies] codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } sp-runtime = { path = "../../primitives/runtime", default-features = false } -phragmen = { package = "sp-phragmen", path = "../../primitives/phragmen", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } +sp-phragmen = { path = "../../primitives/phragmen", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } sp-std = { path = "../../primitives/std", default-features = false } [dev-dependencies] sp-io = { path = "../../primitives/io" } hex-literal = "0.2.1" -balances = { package = "pallet-balances", path = "../balances" } -primitives = { package = "sp-core", path = "../../primitives/core" } +pallet-balances = { path = "../balances" } +sp-core = { path = "../../primitives/core" } substrate-test-utils = { path = "../../test-utils" } serde = { version = "1.0.101" } @@ -24,9 +24,9 @@ serde = { version = "1.0.101" } default = ["std"] std = [ "codec/std", - "support/std", + "frame-support/std", "sp-runtime/std", - "phragmen/std", - "system/std", + "sp-phragmen/std", + "frame-system/std", "sp-std/std", ] diff --git a/substrate/frame/elections-phragmen/src/lib.rs b/substrate/frame/elections-phragmen/src/lib.rs index 0fa0515751..59856692b5 100644 --- a/substrate/frame/elections-phragmen/src/lib.rs +++ b/substrate/frame/elections-phragmen/src/lib.rs @@ -76,7 +76,7 @@ //! //! ### Module Information //! -//! - [`election_phragmen::Trait`](./trait.Trait.html) +//! - [`election_sp_phragmen::Trait`](./trait.Trait.html) //! - [`Call`](./enum.Call.html) //! - [`Module`](./struct.Module.html) @@ -84,28 +84,28 @@ use sp_std::prelude::*; use sp_runtime::{print, traits::{Zero, StaticLookup, Bounded, Convert}}; -use support::{ +use frame_support::{ decl_storage, decl_event, ensure, decl_module, dispatch, weights::SimpleDispatchInfo, traits::{ Currency, Get, LockableCurrency, LockIdentifier, ReservableCurrency, WithdrawReasons, ChangeMembers, OnUnbalanced, WithdrawReason } }; -use phragmen::ExtendedBalance; -use system::{self, ensure_signed, ensure_root}; +use sp_phragmen::ExtendedBalance; +use frame_system::{self as system, ensure_signed, ensure_root}; const MODULE_ID: LockIdentifier = *b"phrelect"; /// The maximum votes allowed per voter. pub const MAXIMUM_VOTE: usize = 16; -type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; +type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; type NegativeImbalanceOf = - <::Currency as Currency<::AccountId>>::NegativeImbalance; + <::Currency as Currency<::AccountId>>::NegativeImbalance; -pub trait Trait: system::Trait { +pub trait Trait: frame_system::Trait { /// The overarching event type.c - type Event: From> + Into<::Event>; + type Event: From> + Into<::Event>; /// The currency that people are electing with. type Currency: @@ -418,7 +418,7 @@ decl_module! { decl_event!( pub enum Event where Balance = BalanceOf, - ::AccountId, + ::AccountId, { /// A new term with new members. This indicates that enough candidates existed, not that /// enough have has been elected. The inner value must be examined for this purpose. @@ -602,7 +602,7 @@ impl Module { let voters_and_votes = >::enumerate() .map(|(v, i)| (v, i)) .collect::)>>(); - let maybe_phragmen_result = phragmen::elect::<_, _, _, T::CurrencyToVote>( + let maybe_phragmen_result = sp_phragmen::elect::<_, _, _, T::CurrencyToVote>( num_to_elect, 0, candidates, @@ -629,7 +629,7 @@ impl Module { .filter_map(|(m, a)| if a.is_zero() { None } else { Some(m) } ) .collect::>(); - let support_map = phragmen::build_support_map::<_, _, _, T::CurrencyToVote>( + let support_map = sp_phragmen::build_support_map::<_, _, _, T::CurrencyToVote>( &new_set, &phragmen_result.assignments, Self::locked_stake_of, @@ -735,14 +735,15 @@ impl Module { mod tests { use super::*; use std::cell::RefCell; - use support::{assert_ok, assert_noop, parameter_types, weights::Weight}; + use frame_support::{assert_ok, assert_noop, parameter_types, weights::Weight}; use substrate_test_utils::assert_eq_uvec; - use primitives::H256; + use sp_core::H256; use sp_runtime::{ Perbill, testing::Header, BuildStorage, traits::{BlakeTwo256, IdentityLookup, Block as BlockT}, }; use crate as elections; + use frame_system as system; parameter_types! { pub const BlockHashCount: u64 = 250; @@ -751,7 +752,7 @@ mod tests { pub const AvailableBlockRatio: Perbill = Perbill::one(); } - impl system::Trait for Test { + impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -775,7 +776,7 @@ mod tests { pub const CreationFee: u64 = 0; } - impl balances::Trait for Test { + impl pallet_balances::Trait for Test { type Balance = u64; type OnNewAccount = (); type OnFreeBalanceZero = (); @@ -886,14 +887,14 @@ mod tests { pub type Block = sp_runtime::generic::Block; pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; - support::construct_runtime!( + frame_support::construct_runtime!( pub enum Test where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { System: system::{Module, Call, Event}, - Balances: balances::{Module, Call, Event, Config}, + Balances: pallet_balances::{Module, Call, Event, Config}, Elections: elections::{Module, Call, Event}, } ); @@ -934,7 +935,7 @@ mod tests { TERM_DURATION.with(|v| *v.borrow_mut() = self.term_duration); DESIRED_RUNNERS_UP.with(|v| *v.borrow_mut() = self.desired_runners_up); GenesisConfig { - balances: Some(balances::GenesisConfig::{ + pallet_balances: Some(pallet_balances::GenesisConfig::{ balances: vec![ (1, 10 * self.balance_factor), (2, 20 * self.balance_factor), diff --git a/substrate/frame/elections/Cargo.toml b/substrate/frame/elections/Cargo.toml index 9a1216f38c..c1b845bd5a 100644 --- a/substrate/frame/elections/Cargo.toml +++ b/substrate/frame/elections/Cargo.toml @@ -8,27 +8,27 @@ edition = "2018" serde = { version = "1.0.101", optional = true } safe-mix = { version = "1.0.0", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } -primitives = { package = "sp-core", path = "../../primitives/core", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false } sp-std = { path = "../../primitives/std", default-features = false } sp-io = { path = "../../primitives/io", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } [dev-dependencies] hex-literal = "0.2.1" -balances = { package = "pallet-balances", path = "../balances" } +pallet-balances = { path = "../balances" } [features] default = ["std"] std = [ "safe-mix/std", "codec/std", - "primitives/std", + "sp-core/std", "sp-std/std", "serde", "sp-io/std", - "support/std", + "frame-support/std", "sp-runtime/std", - "system/std", + "frame-system/std", ] diff --git a/substrate/frame/elections/src/lib.rs b/substrate/frame/elections/src/lib.rs index 530ffad963..5b2bee253c 100644 --- a/substrate/frame/elections/src/lib.rs +++ b/substrate/frame/elections/src/lib.rs @@ -29,7 +29,7 @@ use sp_runtime::{ print, traits::{Zero, One, StaticLookup, Bounded, Saturating}, }; -use support::{ +use frame_support::{ dispatch::Result, decl_storage, decl_event, ensure, decl_module, weights::SimpleDispatchInfo, traits::{ @@ -38,7 +38,7 @@ use support::{ } }; use codec::{Encode, Decode}; -use system::{self, ensure_signed, ensure_root}; +use frame_system::{self as system, ensure_signed, ensure_root}; mod mock; mod tests; @@ -134,9 +134,9 @@ pub const VOTER_SET_SIZE: usize = 64; /// NUmber of approvals grouped in one chunk. pub const APPROVAL_SET_SIZE: usize = 8; -type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; +type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; type NegativeImbalanceOf = - <::Currency as Currency<::AccountId>>::NegativeImbalance; + <::Currency as Currency<::AccountId>>::NegativeImbalance; /// Index used to access chunks. type SetIndex = u32; @@ -147,8 +147,8 @@ type ApprovalFlag = u32; /// Number of approval flags that can fit into [`ApprovalFlag`] type. const APPROVAL_FLAG_LEN: usize = 32; -pub trait Trait: system::Trait { - type Event: From> + Into<::Event>; +pub trait Trait: frame_system::Trait { + type Event: From> + Into<::Event>; /// The currency that people are electing with. type Currency: @@ -643,7 +643,7 @@ decl_module! { } decl_event!( - pub enum Event where ::AccountId { + pub enum Event where ::AccountId { /// reaped voter, reaper VoterReaped(AccountId, AccountId), /// slashed reaper @@ -695,7 +695,7 @@ impl Module { // if there's a tally in progress, then next tally can begin immediately afterwards (tally_end, c.len() - leavers.len() + comers as usize, comers) } else { - (>::block_number(), c.len(), 0) + (>::block_number(), c.len(), 0) }; if count < desired_seats as usize { Some(next_possible) @@ -851,7 +851,7 @@ impl Module { fn start_tally() { let members = Self::members(); let desired_seats = Self::desired_seats() as usize; - let number = >::block_number(); + let number = >::block_number(); let expiring = members.iter().take_while(|i| i.1 <= number).map(|i| i.0.clone()).collect::>(); let retaining_seats = members.len() - expiring.len(); @@ -879,7 +879,7 @@ impl Module { .ok_or("finalize can only be called after a tally is started.")?; let leaderboard: Vec<(BalanceOf, T::AccountId)> = >::take() .unwrap_or_default(); - let new_expiry = >::block_number() + Self::term_duration(); + let new_expiry = >::block_number() + Self::term_duration(); // return bond to winners. let candidacy_bond = T::CandidacyBond::get(); diff --git a/substrate/frame/elections/src/mock.rs b/substrate/frame/elections/src/mock.rs index 7e3c762427..de4f263f0e 100644 --- a/substrate/frame/elections/src/mock.rs +++ b/substrate/frame/elections/src/mock.rs @@ -19,12 +19,12 @@ #![cfg(test)] use std::cell::RefCell; -use support::{ +use frame_support::{ StorageValue, StorageMap, parameter_types, assert_ok, traits::{Get, ChangeMembers, Currency}, weights::Weight, }; -use primitives::H256; +use sp_core::H256; use sp_runtime::{ Perbill, BuildStorage, testing::Header, traits::{BlakeTwo256, IdentityLookup, Block as BlockT}, }; @@ -37,7 +37,7 @@ parameter_types! { pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } -impl system::Trait for Test { +impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -60,7 +60,7 @@ parameter_types! { pub const TransferFee: u64 = 0; pub const CreationFee: u64 = 0; } -impl balances::Trait for Test { +impl pallet_balances::Trait for Test { type Balance = u64; type OnNewAccount = (); type OnFreeBalanceZero = (); @@ -145,14 +145,15 @@ impl elections::Trait for Test { pub type Block = sp_runtime::generic::Block; pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; -support::construct_runtime!( +use frame_system as system; +frame_support::construct_runtime!( pub enum Test where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { System: system::{Module, Call, Event}, - Balances: balances::{Module, Call, Event, Config, Error}, + Balances: pallet_balances::{Module, Call, Event, Config, Error}, Elections: elections::{Module, Call, Event, Config}, } ); @@ -210,7 +211,7 @@ impl ExtBuilder { PRESENT_SLASH_PER_VOTER.with(|v| *v.borrow_mut() = self.bad_presentation_punishment); DECAY_RATIO.with(|v| *v.borrow_mut() = self.decay_ratio); GenesisConfig { - balances: Some(balances::GenesisConfig::{ + pallet_balances: Some(pallet_balances::GenesisConfig::{ balances: vec![ (1, 10 * self.balance_factor), (2, 20 * self.balance_factor), diff --git a/substrate/frame/elections/src/tests.rs b/substrate/frame/elections/src/tests.rs index c9bb054ab2..b502c52f8f 100644 --- a/substrate/frame/elections/src/tests.rs +++ b/substrate/frame/elections/src/tests.rs @@ -21,7 +21,7 @@ use crate::mock::*; use crate::*; -use support::{assert_ok, assert_err, assert_noop}; +use frame_support::{assert_ok, assert_err, assert_noop}; #[test] fn params_should_work() { diff --git a/substrate/frame/evm/Cargo.toml b/substrate/frame/evm/Cargo.toml index c6a8083a2f..d26c6672d1 100644 --- a/substrate/frame/evm/Cargo.toml +++ b/substrate/frame/evm/Cargo.toml @@ -7,11 +7,11 @@ edition = "2018" [dependencies] serde = { version = "1.0.101", optional = true, features = ["derive"] } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } -timestamp = { package = "pallet-timestamp", path = "../timestamp", default-features = false } -balances = { package = "pallet-balances", path = "../balances", default-features = false } -primitives = { package = "sp-core", path = "../../primitives/core", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } +pallet-timestamp = { path = "../timestamp", default-features = false } +pallet-balances = { path = "../balances", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } sp-std = { path = "../../primitives/std", default-features = false } sp-io = { path = "../../primitives/io", default-features = false } @@ -25,16 +25,16 @@ default = ["std"] std = [ "serde", "codec/std", - "primitives/std", + "sp-core/std", "sp-runtime/std", - "support/std", - "system/std", - "balances/std", + "frame-support/std", + "frame-system/std", + "pallet-balances/std", "sp-io/std", "sp-std/std", "sha3/std", "rlp/std", "primitive-types/std", "evm/std", - "timestamp/std", + "pallet-timestamp/std", ] diff --git a/substrate/frame/evm/src/backend.rs b/substrate/frame/evm/src/backend.rs index aec3371f0b..b6c3078a33 100644 --- a/substrate/frame/evm/src/backend.rs +++ b/substrate/frame/evm/src/backend.rs @@ -3,9 +3,9 @@ use sp_std::vec::Vec; #[cfg(feature = "std")] use serde::{Serialize, Deserialize}; use codec::{Encode, Decode}; -use primitives::{U256, H256, H160}; +use sp_core::{U256, H256, H160}; use sp_runtime::traits::UniqueSaturatedInto; -use support::storage::{StorageMap, StorageDoubleMap}; +use frame_support::storage::{StorageMap, StorageDoubleMap}; use sha3::{Keccak256, Digest}; use evm::Config; use evm::backend::{Backend as BackendT, ApplyBackend, Apply}; @@ -69,12 +69,12 @@ impl<'vicinity, T: Trait> BackendT for Backend<'vicinity, T> { H256::default() } else { let number = T::BlockNumber::from(number.as_u32()); - H256::from_slice(system::Module::::block_hash(number).as_ref()) + H256::from_slice(frame_system::Module::::block_hash(number).as_ref()) } } fn block_number(&self) -> U256 { - let number: u128 = system::Module::::block_number().unique_saturated_into(); + let number: u128 = frame_system::Module::::block_number().unique_saturated_into(); U256::from(number) } @@ -83,7 +83,7 @@ impl<'vicinity, T: Trait> BackendT for Backend<'vicinity, T> { } fn block_timestamp(&self) -> U256 { - let now: u128 = timestamp::Module::::get().unique_saturated_into(); + let now: u128 = pallet_timestamp::Module::::get().unique_saturated_into(); U256::from(now) } diff --git a/substrate/frame/evm/src/lib.rs b/substrate/frame/evm/src/lib.rs index 4a62dae9ad..6215dfaab2 100644 --- a/substrate/frame/evm/src/lib.rs +++ b/substrate/frame/evm/src/lib.rs @@ -24,14 +24,14 @@ mod backend; pub use crate::backend::{Account, Log, Vicinity, Backend}; use sp_std::{vec::Vec, marker::PhantomData}; -use support::{dispatch, decl_module, decl_storage, decl_event}; -use support::weights::{Weight, WeighData, ClassifyDispatch, DispatchClass, PaysFee}; -use support::traits::{Currency, WithdrawReason, ExistenceRequirement}; -use system::ensure_signed; +use frame_support::{dispatch, decl_module, decl_storage, decl_event}; +use frame_support::weights::{Weight, WeighData, ClassifyDispatch, DispatchClass, PaysFee}; +use frame_support::traits::{Currency, WithdrawReason, ExistenceRequirement}; +use frame_system::{self as system, ensure_signed}; use sp_runtime::ModuleId; -use support::weights::SimpleDispatchInfo; +use frame_support::weights::SimpleDispatchInfo; use sp_runtime::traits::{UniqueSaturatedInto, AccountIdConversion, SaturatedConversion}; -use primitives::{U256, H256, H160}; +use sp_core::{U256, H256, H160}; use evm::{ExitReason, ExitSucceed, ExitError}; use evm::executor::StackExecutor; use evm::backend::ApplyBackend; @@ -39,7 +39,7 @@ use evm::backend::ApplyBackend; const MODULE_ID: ModuleId = ModuleId(*b"py/ethvm"); /// Type alias for currency balance. -pub type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; +pub type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; /// Trait that outputs the current transaction gas price. pub trait FeeCalculator { @@ -116,7 +116,7 @@ impl PaysFee for WeightForCallCreate { } /// EVM module trait -pub trait Trait: system::Trait + timestamp::Trait { +pub trait Trait: frame_system::Trait + pallet_timestamp::Trait { /// Calculator for current gas price. type FeeCalculator: FeeCalculator; /// Convert account ID to H160; @@ -124,7 +124,7 @@ pub trait Trait: system::Trait + timestamp::Trait { /// Currency type for deposit and withdraw. type Currency: Currency; /// The overarching event type. - type Event: From + Into<::Event>; + type Event: From + Into<::Event>; /// Precompiles associated with this EVM engine. type Precompiles: Precompiles; } diff --git a/substrate/frame/example/Cargo.toml b/substrate/frame/example/Cargo.toml index 496d4e64a5..2515604b3e 100644 --- a/substrate/frame/example/Cargo.toml +++ b/substrate/frame/example/Cargo.toml @@ -7,15 +7,15 @@ edition = "2018" [dependencies] serde = { version = "1.0.101", optional = true } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } -balances = { package = "pallet-balances", path = "../balances", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } +pallet-balances = { path = "../balances", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } sp-std = { path = "../../primitives/std", default-features = false } sp-io = { path = "../../primitives/io", default-features = false } [dev-dependencies] -primitives = { package = "sp-core", path = "../../primitives/core" } +sp-core = { path = "../../primitives/core" } [features] default = ["std"] @@ -23,9 +23,9 @@ std = [ "serde", "codec/std", "sp-runtime/std", - "support/std", - "system/std", - "balances/std", + "frame-support/std", + "frame-system/std", + "pallet-balances/std", "sp-io/std", "sp-std/std" ] diff --git a/substrate/frame/example/src/lib.rs b/substrate/frame/example/src/lib.rs index 10f075ec6d..d77998c85f 100644 --- a/substrate/frame/example/src/lib.rs +++ b/substrate/frame/example/src/lib.rs @@ -254,11 +254,11 @@ #![cfg_attr(not(feature = "std"), no_std)] use sp_std::marker::PhantomData; -use support::{ +use frame_support::{ dispatch::Result, decl_module, decl_storage, decl_event, weights::{SimpleDispatchInfo, DispatchInfo, DispatchClass, ClassifyDispatch, WeighData, Weight, PaysFee}, }; -use system::{ensure_signed, ensure_root}; +use frame_system::{self as system, ensure_signed, ensure_root}; use codec::{Encode, Decode}; use sp_runtime::{ traits::{SignedExtension, Bounded, SaturatedConversion}, @@ -281,9 +281,9 @@ use sp_runtime::{ // - The final weight of each dispatch is calculated as the argument of the call multiplied by the // parameter given to the `WeightForSetDummy`'s constructor. // - assigns a dispatch class `operational` if the argument of the call is more than 1000. -struct WeightForSetDummy(BalanceOf); +struct WeightForSetDummy(BalanceOf); -impl WeighData<(&BalanceOf,)> for WeightForSetDummy +impl WeighData<(&BalanceOf,)> for WeightForSetDummy { fn weigh_data(&self, target: (&BalanceOf,)) -> Weight { let multiplier = self.0; @@ -291,7 +291,7 @@ impl WeighData<(&BalanceOf,)> for WeightForSetDummy } } -impl ClassifyDispatch<(&BalanceOf,)> for WeightForSetDummy { +impl ClassifyDispatch<(&BalanceOf,)> for WeightForSetDummy { fn classify_dispatch(&self, target: (&BalanceOf,)) -> DispatchClass { if *target.0 > >::from(1000u32) { DispatchClass::Operational @@ -301,23 +301,23 @@ impl ClassifyDispatch<(&BalanceOf,)> for WeightForSetDumm } } -impl PaysFee for WeightForSetDummy { +impl PaysFee for WeightForSetDummy { fn pays_fee(&self) -> bool { true } } /// A type alias for the balance type from this module's point of view. -type BalanceOf = ::Balance; +type BalanceOf = ::Balance; /// Our module's configuration trait. All our types and constants go in here. If the /// module is dependent on specific other modules, then their configuration traits /// should be added to our implied traits list. /// -/// `system::Trait` should always be included in our implied traits. -pub trait Trait: balances::Trait { +/// `frame_system::Trait` should always be included in our implied traits. +pub trait Trait: pallet_balances::Trait { /// The overarching event type. - type Event: From> + Into<::Event>; + type Event: From> + Into<::Event>; } decl_storage! { @@ -342,8 +342,8 @@ decl_storage! { // e.g. pub Bar get(fn bar): map T::AccountId => Vec<(T::Balance, u64)>; // // For basic value items, you'll get a type which implements - // `support::StorageValue`. For map items, you'll get a type which - // implements `support::StorageMap`. + // `frame_support::StorageValue`. For map items, you'll get a type which + // implements `frame_support::StorageMap`. // // If they have a getter (`get(getter_name)`), then your module will come // equipped with `fn getter_name() -> Type` for basic value items or @@ -362,7 +362,7 @@ decl_event!( /// Events are a simple means of reporting specific conditions and /// circumstances that have happened that users, Dapps and/or chain explorers would find /// interesting and otherwise difficult to detect. - pub enum Event where B = ::Balance { + pub enum Event where B = ::Balance { // Just a normal `enum`, here's a dummy event to ensure it compiles. /// Dummy event, just here so there's a generic type that's used. Dummy(B), @@ -398,7 +398,7 @@ decl_event!( // // `fn foo(origin: T::Origin, bar: Bar, baz: Baz) { ... }` // -// There are three entries in the `system::Origin` enum that correspond +// There are three entries in the `frame_system::Origin` enum that correspond // to the above bullets: `::Signed(AccountId)`, `::Root` and `::None`. You should always match // against them as the first thing you do in your function. There are three convenience calls // in system that do the matching for you and return a convenient result: `ensure_signed`, @@ -605,7 +605,7 @@ impl sp_std::fmt::Debug for WatchDummy { impl SignedExtension for WatchDummy { type AccountId = T::AccountId; // Note that this could also be assigned to the top-level call enum. It is passed into the - // balances module directly and since `Trait: balances::Trait`, you could also use `T::Call`. + // balances module directly and since `Trait: pallet_balances::Trait`, you could also use `T::Call`. // In that case, you would have had access to all call variants and could match on variants from // other modules. type Call = Call; @@ -645,8 +645,8 @@ impl SignedExtension for WatchDummy { mod tests { use super::*; - use support::{assert_ok, impl_outer_origin, parameter_types, weights::GetDispatchInfo}; - use primitives::H256; + use frame_support::{assert_ok, impl_outer_origin, parameter_types, weights::GetDispatchInfo}; + use sp_core::H256; // The testing primitives are very useful for avoiding having to work with signatures // or public keys. `u64` is used as the `AccountId` and no `Signature`s are required. use sp_runtime::{ @@ -655,7 +655,7 @@ mod tests { }; impl_outer_origin! { - pub enum Origin for Test {} + pub enum Origin for Test where system = frame_system {} } // For testing the module, we construct most of a mock runtime. This means @@ -669,7 +669,7 @@ mod tests { pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } - impl system::Trait for Test { + impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -691,7 +691,7 @@ mod tests { pub const TransferFee: u64 = 0; pub const CreationFee: u64 = 0; } - impl balances::Trait for Test { + impl pallet_balances::Trait for Test { type Balance = u64; type OnFreeBalanceZero = (); type OnNewAccount = (); @@ -710,9 +710,9 @@ mod tests { // This function basically just builds a genesis storage key/value store according to // our desired mockup. fn new_test_ext() -> sp_io::TestExternalities { - let mut t = system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); // We use default for brevity, but you can configure as desired if needed. - balances::GenesisConfig::::default().assimilate_storage(&mut t).unwrap(); + pallet_balances::GenesisConfig::::default().assimilate_storage(&mut t).unwrap(); GenesisConfig::{ dummy: 42, // we configure the map with (key, value) pairs. diff --git a/substrate/frame/executive/Cargo.toml b/substrate/frame/executive/Cargo.toml index 3220e2ba49..de9a82643e 100644 --- a/substrate/frame/executive/Cargo.toml +++ b/substrate/frame/executive/Cargo.toml @@ -10,24 +10,24 @@ codec = { package = "parity-scale-codec", version = "1.0.0", default-features = sp-std = { path = "../../primitives/std", default-features = false } sp-io ={ path = "../../primitives/io", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } [dev-dependencies] hex-literal = "0.2.1" -primitives = { package = "sp-core", path = "../../primitives/core" } +sp-core = { path = "../../primitives/core" } pallet-indices = { path = "../indices" } -balances = { package = "pallet-balances", path = "../balances" } -transaction-payment = { package = "pallet-transaction-payment", path = "../transaction-payment" } +pallet-balances = { path = "../balances" } +pallet-transaction-payment = { path = "../transaction-payment" } [features] default = ["std"] std = [ "sp-std/std", - "support/std", + "frame-support/std", "serde", "codec/std", "sp-runtime/std", "sp-io/std", - "system/std", + "frame-system/std", ] diff --git a/substrate/frame/executive/src/lib.rs b/substrate/frame/executive/src/lib.rs index efe963a6d3..4dfa72f9c6 100644 --- a/substrate/frame/executive/src/lib.rs +++ b/substrate/frame/executive/src/lib.rs @@ -54,7 +54,7 @@ //! # use frame_executive as executive; //! # pub struct UncheckedExtrinsic {}; //! # pub struct Header {}; -//! # type Context = system::ChainContext; +//! # type Context = frame_system::ChainContext; //! # pub type Block = generic::Block; //! # pub type Balances = u64; //! # pub type AllModules = u64; @@ -77,7 +77,7 @@ #![cfg_attr(not(feature = "std"), no_std)] use sp_std::{prelude::*, marker::PhantomData}; -use support::weights::{GetDispatchInfo, WeighBlock, DispatchInfo}; +use frame_support::weights::{GetDispatchInfo, WeighBlock, DispatchInfo}; use sp_runtime::{ generic::Digest, ApplyExtrinsicResult, traits::{ @@ -89,7 +89,7 @@ use sp_runtime::{ #[allow(deprecated)] use sp_runtime::traits::ValidateUnsigned; use codec::{Codec, Encode}; -use system::{extrinsics_root, DigestOf}; +use frame_system::{extrinsics_root, DigestOf}; /// Trait that can be used to execute a block. pub trait ExecuteBlock { @@ -107,7 +107,7 @@ pub struct Executive( #[allow(deprecated)] // Allow ValidateUnsigned, remove the attribute when the trait is removed. impl< - System: system::Trait, + System: frame_system::Trait, Block: traits::Block, Context: Default, UnsignedValidator, @@ -133,7 +133,7 @@ where #[allow(deprecated)] // Allow ValidateUnsigned, remove the attribute when the trait is removed. impl< - System: system::Trait, + System: frame_system::Trait, Block: traits::Block, Context: Default, UnsignedValidator, @@ -165,12 +165,12 @@ where extrinsics_root: &System::Hash, digest: &Digest, ) { - >::initialize(block_number, parent_hash, extrinsics_root, digest); + >::initialize(block_number, parent_hash, extrinsics_root, digest); >::on_initialize(*block_number); - >::register_extra_weight_unchecked( + >::register_extra_weight_unchecked( >::on_initialize(*block_number) ); - >::register_extra_weight_unchecked( + >::register_extra_weight_unchecked( >::on_finalize(*block_number) ); } @@ -182,7 +182,7 @@ where let n = header.number().clone(); assert!( n > System::BlockNumber::zero() - && >::block_hash(n - System::BlockNumber::one()) == *header.parent_hash(), + && >::block_hash(n - System::BlockNumber::one()) == *header.parent_hash(), "Parent hash should be valid." ); @@ -213,19 +213,19 @@ where extrinsics.into_iter().for_each(Self::apply_extrinsic_no_note); // post-extrinsics book-keeping - >::note_finished_extrinsics(); + >::note_finished_extrinsics(); >::on_finalize(block_number); } /// Finalize the block - it is up the caller to ensure that all header fields are valid /// except state-root. pub fn finalize_block() -> System::Header { - >::note_finished_extrinsics(); - >::on_finalize(>::block_number()); + >::note_finished_extrinsics(); + >::on_finalize(>::block_number()); // set up extrinsics - >::derive_extrinsics(); - >::finalize() + >::derive_extrinsics(); + >::finalize() } /// Apply extrinsic outside of the block execution function. @@ -261,7 +261,7 @@ where // executed to prevent it from leaking in storage since at this point, it will either // execute or panic (and revert storage changes). if let Some(encoded) = to_note { - >::note_extrinsic(encoded); + >::note_extrinsic(encoded); } // AUDIT: Under no circumstances may this function panic from here onwards. @@ -270,14 +270,14 @@ where let dispatch_info = xt.get_dispatch_info(); let r = Applyable::apply::(xt, dispatch_info, encoded_len)?; - >::note_applied_extrinsic(&r, encoded_len as u32, dispatch_info); + >::note_applied_extrinsic(&r, encoded_len as u32, dispatch_info); Ok(r) } fn final_checks(header: &System::Header) { // remove temporaries - let new_header = >::finalize(); + let new_header = >::finalize(); // check digest assert_eq!( @@ -319,40 +319,40 @@ where #[cfg(test)] mod tests { use super::*; - use primitives::H256; + use sp_core::H256; use sp_runtime::{ generic::Era, Perbill, DispatchError, testing::{Digest, Header, Block}, traits::{Bounded, Header as HeaderT, BlakeTwo256, IdentityLookup, ConvertInto}, transaction_validity::{InvalidTransaction, UnknownTransaction, TransactionValidityError}, }; - use support::{ + use frame_support::{ impl_outer_event, impl_outer_origin, parameter_types, impl_outer_dispatch, weights::Weight, traits::{Currency, LockIdentifier, LockableCurrency, WithdrawReasons, WithdrawReason}, }; - use system::{Call as SystemCall, ChainContext}; - use balances::Call as BalancesCall; + use frame_system::{self as system, Call as SystemCall, ChainContext}; + use pallet_balances::Call as BalancesCall; use hex_literal::hex; mod custom { - use support::weights::SimpleDispatchInfo; + use frame_support::weights::SimpleDispatchInfo; - pub trait Trait: system::Trait {} + pub trait Trait: frame_system::Trait {} - support::decl_module! { + frame_support::decl_module! { pub struct Module for enum Call where origin: T::Origin { #[weight = SimpleDispatchInfo::FixedNormal(100)] fn some_function(origin) { // NOTE: does not make any different. - let _ = system::ensure_signed(origin); + let _ = frame_system::ensure_signed(origin); } #[weight = SimpleDispatchInfo::FixedOperational(200)] fn some_root_operation(origin) { - let _ = system::ensure_root(origin); + let _ = frame_system::ensure_root(origin); } #[weight = SimpleDispatchInfo::FreeNormal] fn some_unsigned_message(origin) { - let _ = system::ensure_none(origin); + let _ = frame_system::ensure_none(origin); } // module hooks. @@ -369,10 +369,12 @@ mod tests { } } - type System = system::Module; - type Balances = balances::Module; + type System = frame_system::Module; + type Balances = pallet_balances::Module; type Custom = custom::Module; + use pallet_balances as balances; + impl_outer_origin! { pub enum Origin for Runtime { } } @@ -384,8 +386,8 @@ mod tests { } impl_outer_dispatch! { pub enum Call for Runtime where origin: Origin { - system::System, - balances::Balances, + frame_system::System, + pallet_balances::Balances, } } @@ -397,12 +399,12 @@ mod tests { pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } - impl system::Trait for Runtime { + impl frame_system::Trait for Runtime { type Origin = Origin; type Index = u64; type Call = Call; type BlockNumber = u64; - type Hash = primitives::H256; + type Hash = sp_core::H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup; @@ -419,7 +421,7 @@ mod tests { pub const TransferFee: u64 = 0; pub const CreationFee: u64 = 0; } - impl balances::Trait for Runtime { + impl pallet_balances::Trait for Runtime { type Balance = u64; type OnFreeBalanceZero = (); type OnNewAccount = (); @@ -435,7 +437,7 @@ mod tests { pub const TransactionBaseFee: u64 = 10; pub const TransactionByteFee: u64 = 0; } - impl transaction_payment::Trait for Runtime { + impl pallet_transaction_payment::Trait for Runtime { type Currency = Balances; type OnTransactionPayment = (); type TransactionBaseFee = TransactionBaseFee; @@ -462,10 +464,10 @@ mod tests { } type SignedExtra = ( - system::CheckEra, - system::CheckNonce, - system::CheckWeight, - transaction_payment::ChargeTransactionPayment + frame_system::CheckEra, + frame_system::CheckNonce, + frame_system::CheckWeight, + pallet_transaction_payment::ChargeTransactionPayment ); type AllModules = (System, Balances, Custom); type TestXt = sp_runtime::testing::TestXt; @@ -473,10 +475,10 @@ mod tests { fn extra(nonce: u64, fee: u64) -> SignedExtra { ( - system::CheckEra::from(Era::Immortal), - system::CheckNonce::from(nonce), - system::CheckWeight::new(), - transaction_payment::ChargeTransactionPayment::from(fee) + frame_system::CheckEra::from(Era::Immortal), + frame_system::CheckNonce::from(nonce), + frame_system::CheckWeight::new(), + pallet_transaction_payment::ChargeTransactionPayment::from(fee) ) } @@ -486,8 +488,8 @@ mod tests { #[test] fn balance_transfer_dispatch_works() { - let mut t = system::GenesisConfig::default().build_storage::().unwrap(); - balances::GenesisConfig:: { + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + pallet_balances::GenesisConfig:: { balances: vec![(1, 211)], vesting: vec![], }.assimilate_storage(&mut t).unwrap(); @@ -504,14 +506,14 @@ mod tests { )); let r = Executive::apply_extrinsic(xt); assert!(r.is_ok()); - assert_eq!(>::total_balance(&1), 142 - 10 - weight); - assert_eq!(>::total_balance(&2), 69); + assert_eq!(>::total_balance(&1), 142 - 10 - weight); + assert_eq!(>::total_balance(&2), 69); }); } fn new_test_ext(balance_factor: u64) -> sp_io::TestExternalities { - let mut t = system::GenesisConfig::default().build_storage::().unwrap(); - balances::GenesisConfig:: { + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + pallet_balances::GenesisConfig:: { balances: vec![(1, 111 * balance_factor)], vesting: vec![], }.assimilate_storage(&mut t).unwrap(); @@ -582,7 +584,7 @@ mod tests { Digest::default(), )); assert!(Executive::apply_extrinsic(xt).is_err()); - assert_eq!(>::extrinsic_index(), Some(0)); + assert_eq!(>::extrinsic_index(), Some(0)); }); } @@ -604,7 +606,7 @@ mod tests { Digest::default(), )); // Initial block weight form the custom module. - assert_eq!(>::all_extrinsics_weight(), 175); + assert_eq!(>::all_extrinsics_weight(), 175); for nonce in 0..=num_to_exhaust_block { let xt = sp_runtime::testing::TestXt( @@ -614,10 +616,10 @@ mod tests { if nonce != num_to_exhaust_block { assert!(res.is_ok()); assert_eq!( - >::all_extrinsics_weight(), + >::all_extrinsics_weight(), encoded_len * (nonce + 1) + 175, ); - assert_eq!(>::extrinsic_index(), Some(nonce as u32 + 1)); + assert_eq!(>::extrinsic_index(), Some(nonce as u32 + 1)); } else { assert_eq!(res, Err(InvalidTransaction::ExhaustsResources.into())); } @@ -633,21 +635,21 @@ mod tests { let len = xt.clone().encode().len() as u32; let mut t = new_test_ext(1); t.execute_with(|| { - assert_eq!(>::all_extrinsics_weight(), 0); - assert_eq!(>::all_extrinsics_weight(), 0); + assert_eq!(>::all_extrinsics_weight(), 0); + assert_eq!(>::all_extrinsics_weight(), 0); assert!(Executive::apply_extrinsic(xt.clone()).unwrap().is_ok()); assert!(Executive::apply_extrinsic(x1.clone()).unwrap().is_ok()); assert!(Executive::apply_extrinsic(x2.clone()).unwrap().is_ok()); // default weight for `TestXt` == encoded length. - assert_eq!(>::all_extrinsics_weight(), (3 * len) as Weight); - assert_eq!(>::all_extrinsics_len(), 3 * len); + assert_eq!(>::all_extrinsics_weight(), (3 * len) as Weight); + assert_eq!(>::all_extrinsics_len(), 3 * len); - let _ = >::finalize(); + let _ = >::finalize(); - assert_eq!(>::all_extrinsics_weight(), 0); - assert_eq!(>::all_extrinsics_weight(), 0); + assert_eq!(>::all_extrinsics_weight(), 0); + assert_eq!(>::all_extrinsics_weight(), 0); }); } @@ -675,7 +677,7 @@ mod tests { let execute_with_lock = |lock: WithdrawReasons| { let mut t = new_test_ext(1); t.execute_with(|| { - as LockableCurrency>::set_lock( + as LockableCurrency>::set_lock( id, &1, 110, @@ -698,13 +700,13 @@ mod tests { if lock == WithdrawReasons::except(WithdrawReason::TransactionPayment) { assert!(Executive::apply_extrinsic(xt).unwrap().is_ok()); // tx fee has been deducted. - assert_eq!(>::total_balance(&1), 111 - 10 - weight); + assert_eq!(>::total_balance(&1), 111 - 10 - weight); } else { assert_eq!( Executive::apply_extrinsic(xt), Err(InvalidTransaction::Payment.into()), ); - assert_eq!(>::total_balance(&1), 111); + assert_eq!(>::total_balance(&1), 111); } }); }; @@ -720,7 +722,7 @@ mod tests { Executive::initialize_block(&Header::new_from_number(1)); // NOTE: might need updates over time if system and balance introduce new weights. For // now only accounts for the custom module. - assert_eq!(>::all_extrinsics_weight(), 150 + 25); + assert_eq!(>::all_extrinsics_weight(), 150 + 25); }) } } diff --git a/substrate/frame/finality-tracker/Cargo.toml b/substrate/frame/finality-tracker/Cargo.toml index 6169ba8c03..96aef70792 100644 --- a/substrate/frame/finality-tracker/Cargo.toml +++ b/substrate/frame/finality-tracker/Cargo.toml @@ -7,16 +7,16 @@ edition = "2018" [dependencies] serde = { version = "1.0.101", default-features = false, features = ["derive"] } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false } -inherents = { package = "sp-inherents", path = "../../primitives/inherents", default-features = false } +sp-inherents = { path = "../../primitives/inherents", default-features = false } sp-std = { path = "../../primitives/std", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } sp-finality-tracker = { path = "../../primitives/finality-tracker", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } +frame-support = { path = "../support", default-features = false } frame-system = { path = "../system", default-features = false } impl-trait-for-tuples = "0.1.3" [dev-dependencies] -primitives = { package = "sp-core", path = "../../primitives/core", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false } sp-io = { path = "../../primitives/io", default-features = false } [features] @@ -25,9 +25,9 @@ std = [ "serde/std", "codec/std", "sp-std/std", - "support/std", + "frame-support/std", "sp-runtime/std", "frame-system/std", "sp-finality-tracker/std", - "inherents/std", + "sp-inherents/std", ] diff --git a/substrate/frame/finality-tracker/src/lib.rs b/substrate/frame/finality-tracker/src/lib.rs index 14aba50834..4837a9cf78 100644 --- a/substrate/frame/finality-tracker/src/lib.rs +++ b/substrate/frame/finality-tracker/src/lib.rs @@ -18,11 +18,11 @@ #![cfg_attr(not(feature = "std"), no_std)] -use inherents::{InherentIdentifier, ProvideInherent, InherentData, MakeFatalError}; +use sp_inherents::{InherentIdentifier, ProvideInherent, InherentData, MakeFatalError}; use sp_runtime::traits::{One, Zero, SaturatedConversion}; use sp_std::{prelude::*, result, cmp, vec}; -use support::{decl_module, decl_storage}; -use support::traits::Get; +use frame_support::{decl_module, decl_storage}; +use frame_support::traits::Get; use frame_system::{ensure_none, Trait as SystemTrait}; use sp_finality_tracker::{INHERENT_IDENTIFIER, FinalizedInherentData}; @@ -194,12 +194,12 @@ mod tests { use super::*; use sp_io::TestExternalities; - use primitives::H256; + use sp_core::H256; use sp_runtime::{ testing::Header, Perbill, traits::{BlakeTwo256, IdentityLookup, OnFinalize, Header as HeaderT}, }; - use support::{assert_ok, impl_outer_origin, parameter_types, weights::Weight}; + use frame_support::{assert_ok, impl_outer_origin, parameter_types, weights::Weight}; use frame_system as system; use std::cell::RefCell; @@ -213,7 +213,7 @@ mod tests { pub struct Test; impl_outer_origin! { - pub enum Origin for Test {} + pub enum Origin for Test where system = frame_system {} } thread_local! { diff --git a/substrate/frame/generic-asset/Cargo.toml b/substrate/frame/generic-asset/Cargo.toml index 2b4b5e3ac0..fa05425d11 100644 --- a/substrate/frame/generic-asset/Cargo.toml +++ b/substrate/frame/generic-asset/Cargo.toml @@ -9,12 +9,12 @@ serde = { version = "1.0.101", optional = true } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } sp-std = { path = "../../primitives/std", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } [dev-dependencies] sp-io ={ path = "../../primitives/io" } -primitives = { package = "sp-core", path = "../../primitives/core" } +sp-core = { path = "../../primitives/core" } [features] default = ["std"] @@ -23,6 +23,6 @@ std =[ "codec/std", "sp-std/std", "sp-runtime/std", - "support/std", - "system/std", + "frame-support/std", + "frame-system/std", ] diff --git a/substrate/frame/generic-asset/src/lib.rs b/substrate/frame/generic-asset/src/lib.rs index 9315b36674..4ad61af4a7 100644 --- a/substrate/frame/generic-asset/src/lib.rs +++ b/substrate/frame/generic-asset/src/lib.rs @@ -114,14 +114,14 @@ //! The Fees module uses the `Currency` trait to handle fee charge/refund, and its types inherit from `Currency`: //! //! ``` -//! use support::{ +//! use frame_support::{ //! dispatch, //! traits::{Currency, ExistenceRequirement, WithdrawReason}, //! }; -//! # pub trait Trait: system::Trait { +//! # pub trait Trait: frame_system::Trait { //! # type Currency: Currency; //! # } -//! type AssetOf = <::Currency as Currency<::AccountId>>::Balance; +//! type AssetOf = <::Currency as Currency<::AccountId>>::Balance; //! //! fn charge_fee(transactor: &T::AccountId, amount: AssetOf) -> dispatch::Result { //! // ... @@ -161,7 +161,7 @@ use sp_runtime::traits::{ use sp_std::prelude::*; use sp_std::{cmp, result, fmt::Debug}; -use support::{ +use frame_support::{ decl_event, decl_module, decl_storage, ensure, dispatch, traits::{ Currency, ExistenceRequirement, Imbalance, LockIdentifier, LockableCurrency, ReservableCurrency, @@ -169,14 +169,14 @@ use support::{ }, Parameter, StorageMap, }; -use system::{ensure_signed, ensure_root}; +use frame_system::{self as system, ensure_signed, ensure_root}; mod mock; mod tests; pub use self::imbalances::{NegativeImbalance, PositiveImbalance}; -pub trait Trait: system::Trait { +pub trait Trait: frame_system::Trait { type Balance: Parameter + Member + SimpleArithmetic @@ -185,10 +185,10 @@ pub trait Trait: system::Trait { + MaybeSerializeDeserialize + Debug; type AssetId: Parameter + Member + SimpleArithmetic + Default + Copy; - type Event: From> + Into<::Event>; + type Event: From> + Into<::Event>; } -pub trait Subtrait: system::Trait { +pub trait Subtrait: frame_system::Trait { type Balance: Parameter + Member + SimpleArithmetic @@ -495,10 +495,10 @@ decl_storage! { decl_event!( pub enum Event where - ::AccountId, + ::AccountId, ::Balance, ::AssetId, - AssetOptions = AssetOptions<::Balance, ::AccountId> + AssetOptions = AssetOptions<::Balance, ::AccountId> { /// Asset created (asset_id, creator, asset_options). Created(AssetId, AccountId, AssetOptions), @@ -760,7 +760,7 @@ impl Module { if locks.is_empty() { return Ok(()); } - let now = >::block_number(); + let now = >::block_number(); if Self::locks(who) .into_iter() .all(|l| now >= l.until || new_balance >= l.amount || !l.reasons.intersects(reasons)) @@ -792,7 +792,7 @@ impl Module { until: T::BlockNumber, reasons: WithdrawReasons, ) { - let now = >::block_number(); + let now = >::block_number(); let mut new_lock = Some(BalanceLock { id, amount, @@ -824,7 +824,7 @@ impl Module { until: T::BlockNumber, reasons: WithdrawReasons, ) { - let now = >::block_number(); + let now = >::block_number(); let mut new_lock = Some(BalanceLock { id, amount, @@ -855,7 +855,7 @@ impl Module { } fn remove_lock(id: LockIdentifier, who: &T::AccountId) { - let now = >::block_number(); + let now = >::block_number(); let locks = >::locks(who) .into_iter() .filter_map(|l| if l.until > now && l.id != id { Some(l) } else { None }) @@ -1076,7 +1076,7 @@ impl PartialEq for ElevatedTrait { } } impl Eq for ElevatedTrait {} -impl system::Trait for ElevatedTrait { +impl frame_system::Trait for ElevatedTrait { type Origin = T::Origin; type Call = T::Call; type Index = T::Index; diff --git a/substrate/frame/generic-asset/src/mock.rs b/substrate/frame/generic-asset/src/mock.rs index 461fb0aeca..90426516c1 100644 --- a/substrate/frame/generic-asset/src/mock.rs +++ b/substrate/frame/generic-asset/src/mock.rs @@ -25,13 +25,13 @@ use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, }; -use primitives::H256; -use support::{parameter_types, impl_outer_event, impl_outer_origin, weights::Weight}; +use sp_core::H256; +use frame_support::{parameter_types, impl_outer_event, impl_outer_origin, weights::Weight}; use super::*; impl_outer_origin! { - pub enum Origin for Test {} + pub enum Origin for Test where system = frame_system {} } // For testing the module, we construct most of a mock runtime. This means @@ -45,7 +45,7 @@ parameter_types! { pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } -impl system::Trait for Test { +impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -73,6 +73,7 @@ mod generic_asset { pub use crate::Event; } +use frame_system as system; impl_outer_event! { pub enum TestEvent for Test { generic_asset, @@ -81,7 +82,7 @@ impl_outer_event! { pub type GenericAsset = Module; -pub type System = system::Module; +pub type System = frame_system::Module; pub struct ExtBuilder { asset_id: u32, @@ -118,7 +119,7 @@ impl ExtBuilder { // builds genesis config pub fn build(self) -> sp_io::TestExternalities { - let mut t = system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); GenesisConfig:: { assets: vec![self.asset_id], @@ -137,7 +138,7 @@ impl ExtBuilder { // This function basically just builds a genesis storage key/value store according to // our desired mockup. pub fn new_test_ext() -> sp_io::TestExternalities { - system::GenesisConfig::default() + frame_system::GenesisConfig::default() .build_storage::() .unwrap() .into() diff --git a/substrate/frame/generic-asset/src/tests.rs b/substrate/frame/generic-asset/src/tests.rs index 165936d021..1f9f458b2c 100644 --- a/substrate/frame/generic-asset/src/tests.rs +++ b/substrate/frame/generic-asset/src/tests.rs @@ -22,7 +22,7 @@ use super::*; use crate::mock::{new_test_ext, ExtBuilder, GenericAsset, Origin, System, Test, TestEvent}; -use support::{assert_noop, assert_ok}; +use frame_support::{assert_noop, assert_ok}; #[test] fn issuing_asset_units_to_issuer_should_work() { @@ -906,7 +906,7 @@ fn update_permission_should_throw_error_when_lack_of_permissions() { fn create_asset_works_with_given_asset_id_and_from_account() { ExtBuilder::default().next_asset_id(10).build().execute_with(|| { let origin = 1; - let from_account: Option<::AccountId> = Some(1); + let from_account: Option<::AccountId> = Some(1); let default_permission = PermissionLatest { update: Owner::Address(origin), @@ -943,7 +943,7 @@ fn create_asset_works_with_given_asset_id_and_from_account() { fn create_asset_with_non_reserved_asset_id_should_not_work() { ExtBuilder::default().next_asset_id(10).build().execute_with(|| { let origin = 1; - let from_account: Option<::AccountId> = Some(1); + let from_account: Option<::AccountId> = Some(1); let default_permission = PermissionLatest { update: Owner::Address(origin), @@ -977,7 +977,7 @@ fn create_asset_with_non_reserved_asset_id_should_not_work() { fn create_asset_with_a_taken_asset_id_should_not_work() { ExtBuilder::default().next_asset_id(10).build().execute_with(|| { let origin = 1; - let from_account: Option<::AccountId> = Some(1); + let from_account: Option<::AccountId> = Some(1); let default_permission = PermissionLatest { update: Owner::Address(origin), @@ -1022,7 +1022,7 @@ fn create_asset_with_a_taken_asset_id_should_not_work() { fn create_asset_should_create_a_reserved_asset_when_from_account_is_none() { ExtBuilder::default().next_asset_id(10).build().execute_with(|| { let origin = 1; - let from_account: Option<::AccountId> = None; + let from_account: Option<::AccountId> = None; let default_permission = PermissionLatest { update: Owner::Address(origin), @@ -1065,7 +1065,7 @@ fn create_asset_should_create_a_reserved_asset_when_from_account_is_none() { fn create_asset_should_create_a_user_asset() { ExtBuilder::default().next_asset_id(10).build().execute_with(|| { let origin = 1; - let from_account: Option<::AccountId> = None; + let from_account: Option<::AccountId> = None; let default_permission = PermissionLatest { update: Owner::Address(origin), diff --git a/substrate/frame/grandpa/Cargo.toml b/substrate/frame/grandpa/Cargo.toml index 49cb393315..bfb330fcee 100644 --- a/substrate/frame/grandpa/Cargo.toml +++ b/substrate/frame/grandpa/Cargo.toml @@ -7,15 +7,15 @@ edition = "2018" [dependencies] serde = { version = "1.0.101", optional = true, features = ["derive"] } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } -primitives = { package = "sp-core", path = "../../primitives/core", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false } sp-finality-grandpa = { path = "../../primitives/finality-grandpa", default-features = false } sp-std = { path = "../../primitives/std", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } sp-staking = { path = "../../primitives/staking", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } -session = { package = "pallet-session", path = "../session", default-features = false } -finality-tracker = { package = "pallet-finality-tracker", path = "../finality-tracker", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } +pallet-session = { path = "../session", default-features = false } +pallet-finality-tracker = { path = "../finality-tracker", default-features = false } [dev-dependencies] sp-io ={ path = "../../primitives/io" } @@ -25,14 +25,14 @@ default = ["std"] std = [ "serde", "codec/std", - "primitives/std", + "sp-core/std", "sp-finality-grandpa/std", "sp-std/std", - "support/std", + "frame-support/std", "sp-runtime/std", "sp-staking/std", - "system/std", - "session/std", - "finality-tracker/std", + "frame-system/std", + "pallet-session/std", + "pallet-finality-tracker/std", ] migrate-authorities = [] diff --git a/substrate/frame/grandpa/src/lib.rs b/substrate/frame/grandpa/src/lib.rs index 301a09d107..8c017acc91 100644 --- a/substrate/frame/grandpa/src/lib.rs +++ b/substrate/frame/grandpa/src/lib.rs @@ -32,7 +32,7 @@ pub use sp_finality_grandpa as fg_primitives; use sp_std::prelude::*; use codec::{self as codec, Encode, Decode, Error}; -use support::{decl_event, decl_storage, decl_module, dispatch, storage}; +use frame_support::{decl_event, decl_storage, decl_module, dispatch, storage}; use sp_runtime::{ generic::{DigestItem, OpaqueDigestItemId}, traits::Zero, Perbill, }; @@ -44,14 +44,14 @@ use fg_primitives::{ GRANDPA_AUTHORITIES_KEY, GRANDPA_ENGINE_ID, ScheduledChange, ConsensusLog, SetId, RoundNumber, }; pub use fg_primitives::{AuthorityId, AuthorityList, AuthorityWeight, VersionedAuthorityList}; -use system::{ensure_signed, DigestOf}; +use frame_system::{self as system, ensure_signed, DigestOf}; mod mock; mod tests; -pub trait Trait: system::Trait { +pub trait Trait: frame_system::Trait { /// The event type of this module. - type Event: From + Into<::Event>; + type Event: From + Into<::Event>; } /// A stored pending change, old format. @@ -266,7 +266,7 @@ impl Module { /// Cannot be done when already paused. pub fn schedule_pause(in_blocks: T::BlockNumber) -> dispatch::Result { if let StoredState::Live = >::get() { - let scheduled_at = >::block_number(); + let scheduled_at = >::block_number(); >::put(StoredState::PendingPause { delay: in_blocks, scheduled_at, @@ -282,7 +282,7 @@ impl Module { /// Schedule a resume of GRANDPA after pausing. pub fn schedule_resume(in_blocks: T::BlockNumber) -> dispatch::Result { if let StoredState::Paused = >::get() { - let scheduled_at = >::block_number(); + let scheduled_at = >::block_number(); >::put(StoredState::PendingResume { delay: in_blocks, scheduled_at, @@ -315,7 +315,7 @@ impl Module { forced: Option, ) -> dispatch::Result { if !>::exists() { - let scheduled_at = >::block_number(); + let scheduled_at = >::block_number(); if let Some(_) = forced { if Self::next_forced().map_or(false, |next| next > scheduled_at) { @@ -343,7 +343,7 @@ impl Module { /// Deposit one of this module's logs. fn deposit_log(log: ConsensusLog) { let log: DigestItem = DigestItem::Consensus(GRANDPA_ENGINE_ID, log.encode()); - >::deposit_log(log.into()); + >::deposit_log(log.into()); } fn initialize_authorities(authorities: &AuthorityList) { @@ -404,8 +404,8 @@ impl sp_runtime::BoundToRuntimeAppPublic for Module { type Public = AuthorityId; } -impl session::OneSessionHandler for Module - where T: session::Trait +impl pallet_session::OneSessionHandler for Module + where T: pallet_session::Trait { type Key = AuthorityId; @@ -438,7 +438,7 @@ impl session::OneSessionHandler for Module // if we didn't issue a change, we update the mapping to note that the current // set corresponds to the latest equivalent session (i.e. now). - let session_index = >::current_index(); + let session_index = >::current_index(); SetIdSession::insert(current_set_id, &session_index); } @@ -447,9 +447,9 @@ impl session::OneSessionHandler for Module } } -impl finality_tracker::OnFinalizationStalled for Module { +impl pallet_finality_tracker::OnFinalizationStalled for Module { fn on_stalled(further_wait: T::BlockNumber, median: T::BlockNumber) { - // when we record old authority sets, we can use `finality_tracker::median` + // when we record old authority sets, we can use `pallet_finality_tracker::median` // to figure out _who_ failed. until then, we can't meaningfully guard // against `next == last` the way that normal session changes do. >::put((further_wait, median)); diff --git a/substrate/frame/grandpa/src/mock.rs b/substrate/frame/grandpa/src/mock.rs index 8826414cfc..20701b11aa 100644 --- a/substrate/frame/grandpa/src/mock.rs +++ b/substrate/frame/grandpa/src/mock.rs @@ -20,14 +20,15 @@ use sp_runtime::{Perbill, DigestItem, traits::IdentityLookup, testing::{Header, UintAuthorityId}}; use sp_io; -use support::{impl_outer_origin, impl_outer_event, parameter_types, weights::Weight}; -use primitives::H256; +use frame_support::{impl_outer_origin, impl_outer_event, parameter_types, weights::Weight}; +use sp_core::H256; use codec::{Encode, Decode}; use crate::{AuthorityId, AuthorityList, GenesisConfig, Trait, Module, ConsensusLog}; use sp_finality_grandpa::GRANDPA_ENGINE_ID; +use frame_system as system; impl_outer_origin!{ - pub enum Origin for Test {} + pub enum Origin for Test where system = frame_system {} } pub fn grandpa_log(log: ConsensusLog) -> DigestItem { @@ -47,7 +48,7 @@ parameter_types! { pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } -impl system::Trait for Test { +impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -82,12 +83,12 @@ pub fn to_authorities(vec: Vec<(u64, u64)>) -> AuthorityList { } pub fn new_test_ext(authorities: Vec<(u64, u64)>) -> sp_io::TestExternalities { - let mut t = system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); GenesisConfig { authorities: to_authorities(authorities), }.assimilate_storage::(&mut t).unwrap(); t.into() } -pub type System = system::Module; +pub type System = frame_system::Module; pub type Grandpa = Module; diff --git a/substrate/frame/grandpa/src/tests.rs b/substrate/frame/grandpa/src/tests.rs index 9ca00fd169..5ad26d22f4 100644 --- a/substrate/frame/grandpa/src/tests.rs +++ b/substrate/frame/grandpa/src/tests.rs @@ -20,7 +20,7 @@ use sp_runtime::{testing::Digest, traits::{Header, OnFinalize}}; use crate::mock::*; -use system::{EventRecord, Phase}; +use frame_system::{EventRecord, Phase}; use codec::{Decode, Encode}; use fg_primitives::ScheduledChange; use super::*; diff --git a/substrate/frame/identity/Cargo.toml b/substrate/frame/identity/Cargo.toml index c1518bfcfc..74979dec5d 100644 --- a/substrate/frame/identity/Cargo.toml +++ b/substrate/frame/identity/Cargo.toml @@ -11,12 +11,12 @@ enumflags2 = { version = "0.6.2" } sp-std = { path = "../../primitives/std", default-features = false } sp-io = { path = "../../primitives/io", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } [dev-dependencies] -primitives = { package = "sp-core", path = "../../primitives/core" } -balances = { package = "pallet-balances", path = "../balances" } +sp-core = { path = "../../primitives/core" } +pallet-balances = { path = "../balances" } [features] default = ["std"] @@ -26,6 +26,6 @@ std = [ "sp-std/std", "sp-io/std", "sp-runtime/std", - "support/std", - "system/std", + "frame-support/std", + "frame-system/std", ] diff --git a/substrate/frame/identity/src/lib.rs b/substrate/frame/identity/src/lib.rs index 904ab8cf2e..2813d6c83b 100644 --- a/substrate/frame/identity/src/lib.rs +++ b/substrate/frame/identity/src/lib.rs @@ -70,19 +70,19 @@ use sp_std::{fmt::Debug, ops::Add, iter::once}; use enumflags2::BitFlags; use codec::{Encode, Decode}; use sp_runtime::{traits::{StaticLookup, EnsureOrigin, Zero}, RuntimeDebug}; -use support::{ +use frame_support::{ decl_module, decl_event, decl_storage, ensure, dispatch::Result, traits::{Currency, ReservableCurrency, OnUnbalanced, Get}, weights::SimpleDispatchInfo, }; -use system::{ensure_signed, ensure_root}; +use frame_system::{self as system, ensure_signed, ensure_root}; -type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; -type NegativeImbalanceOf = <::Currency as Currency<::AccountId>>::NegativeImbalance; +type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; +type NegativeImbalanceOf = <::Currency as Currency<::AccountId>>::NegativeImbalance; -pub trait Trait: system::Trait { +pub trait Trait: frame_system::Trait { /// The overarching event type. - type Event: From> + Into<::Event>; + type Event: From> + Into<::Event>; /// The currency trait. type Currency: ReservableCurrency; @@ -383,7 +383,7 @@ decl_storage! { } decl_event!( - pub enum Event where AccountId = ::AccountId, Balance = BalanceOf { + pub enum Event where AccountId = ::AccountId, Balance = BalanceOf { /// A name was set or reset (which will remove all judgements). IdentitySet(AccountId), /// A name was cleared, and the given balance returned. @@ -822,9 +822,9 @@ decl_module! { mod tests { use super::*; - use support::{assert_ok, assert_noop, impl_outer_origin, parameter_types, weights::Weight}; - use primitives::H256; - use system::EnsureSignedBy; + use frame_support::{assert_ok, assert_noop, impl_outer_origin, parameter_types, weights::Weight}; + use sp_core::H256; + use frame_system::EnsureSignedBy; // The testing primitives are very useful for avoiding having to work with signatures // or public keys. `u64` is used as the `AccountId` and no `Signature`s are required. use sp_runtime::{ @@ -832,7 +832,7 @@ mod tests { }; impl_outer_origin! { - pub enum Origin for Test {} + pub enum Origin for Test where system = frame_system {} } // For testing the module, we construct most of a mock runtime. This means @@ -846,7 +846,7 @@ mod tests { pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } - impl system::Trait for Test { + impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -868,7 +868,7 @@ mod tests { pub const TransferFee: u64 = 0; pub const CreationFee: u64 = 0; } - impl balances::Trait for Test { + impl pallet_balances::Trait for Test { type Balance = u64; type OnFreeBalanceZero = (); type OnNewAccount = (); @@ -898,15 +898,15 @@ mod tests { type RegistrarOrigin = EnsureSignedBy; type ForceOrigin = EnsureSignedBy; } - type Balances = balances::Module; + type Balances = pallet_balances::Module; type Identity = Module; // This function basically just builds a genesis storage key/value store according to // our desired mockup. fn new_test_ext() -> sp_io::TestExternalities { - let mut t = system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); // We use default for brevity, but you can configure as desired if needed. - balances::GenesisConfig:: { + pallet_balances::GenesisConfig:: { balances: vec![ (1, 10), (2, 10), diff --git a/substrate/frame/im-online/Cargo.toml b/substrate/frame/im-online/Cargo.toml index e71a2f41c4..2b498c2ae9 100644 --- a/substrate/frame/im-online/Cargo.toml +++ b/substrate/frame/im-online/Cargo.toml @@ -5,32 +5,32 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -app-crypto = { package = "sp-application-crypto", path = "../../primitives/application-crypto", default-features = false } -authorship = { package = "pallet-authorship", path = "../authorship", default-features = false } +sp-application-crypto = { path = "../../primitives/application-crypto", default-features = false } +pallet-authorship = { path = "../authorship", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } -primitives = { package="sp-core", path = "../../primitives/core", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false } sp-std = { path = "../../primitives/std", default-features = false } serde = { version = "1.0.101", optional = true } -session = { package = "pallet-session", path = "../session", default-features = false } +pallet-session = { path = "../session", default-features = false } sp-io = { path = "../../primitives/io", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } sp-staking = { path = "../../primitives/staking", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } [features] -default = ["std", "session/historical"] +default = ["std", "pallet-session/historical"] std = [ - "app-crypto/std", - "authorship/std", + "sp-application-crypto/std", + "pallet-authorship/std", "codec/std", - "primitives/std", + "sp-core/std", "sp-std/std", "serde", - "session/std", + "pallet-session/std", "sp-io/std", "sp-runtime/std", "sp-staking/std", - "support/std", - "system/std", + "frame-support/std", + "frame-system/std", ] diff --git a/substrate/frame/im-online/src/lib.rs b/substrate/frame/im-online/src/lib.rs index c9991cf690..64d23dbb5d 100644 --- a/substrate/frame/im-online/src/lib.rs +++ b/substrate/frame/im-online/src/lib.rs @@ -42,8 +42,8 @@ //! ## Usage //! //! ``` -//! use support::{decl_module, dispatch}; -//! use system::ensure_signed; +//! use frame_support::{decl_module, dispatch}; +//! use frame_system::{self as system, ensure_signed}; //! use pallet_im_online::{self as im_online}; //! //! pub trait Trait: im_online::Trait {} @@ -70,12 +70,12 @@ mod mock; mod tests; -use app_crypto::RuntimeAppPublic; +use sp_application_crypto::RuntimeAppPublic; use codec::{Encode, Decode}; -use primitives::offchain::{OpaqueNetworkState, StorageKind}; +use sp_core::offchain::{OpaqueNetworkState, StorageKind}; use sp_std::prelude::*; use sp_std::convert::TryInto; -use session::historical::IdentificationTuple; +use pallet_session::historical::IdentificationTuple; use sp_runtime::{ RuntimeDebug, traits::{Convert, Member, Printable, Saturating}, Perbill, @@ -88,16 +88,16 @@ use sp_staking::{ SessionIndex, offence::{ReportOffence, Offence, Kind}, }; -use support::{ +use frame_support::{ decl_module, decl_event, decl_storage, print, Parameter, debug, traits::Get, }; -use system::ensure_none; -use system::offchain::SubmitUnsignedTransaction; +use frame_system::{self as system, ensure_none}; +use frame_system::offchain::SubmitUnsignedTransaction; pub mod sr25519 { mod app_sr25519 { - use app_crypto::{app_crypto, key_types::IM_ONLINE, sr25519}; + use sp_application_crypto::{app_crypto, key_types::IM_ONLINE, sr25519}; app_crypto!(sr25519, IM_ONLINE); } @@ -114,7 +114,7 @@ pub mod sr25519 { pub mod ed25519 { mod app_ed25519 { - use app_crypto::{app_crypto, key_types::IM_ONLINE, ed25519}; + use sp_application_crypto::{app_crypto, key_types::IM_ONLINE, ed25519}; app_crypto!(ed25519, IM_ONLINE); } @@ -177,12 +177,12 @@ pub struct Heartbeat authority_index: AuthIndex, } -pub trait Trait: system::Trait + session::historical::Trait { +pub trait Trait: frame_system::Trait + pallet_session::historical::Trait { /// The identifier type for an authority. type AuthorityId: Member + Parameter + RuntimeAppPublic + Default + Ord; /// The overarching event type. - type Event: From> + Into<::Event>; + type Event: From> + Into<::Event>; /// A dispatchable call type. type Call: From>; @@ -257,7 +257,7 @@ decl_module! { ) { ensure_none(origin)?; - let current_session = >::current_index(); + let current_session = >::current_index(); let exists = ::exists( ¤t_session, &heartbeat.authority_index @@ -294,7 +294,7 @@ decl_module! { /// Keep track of number of authored blocks per authority, uncles are counted as /// well since they're a valid proof of onlineness. -impl authorship::EventHandler for Module { +impl pallet_authorship::EventHandler for Module { fn note_author(author: T::ValidatorId) { Self::note_authorship(author); } @@ -310,7 +310,7 @@ impl Module { /// authored at least one block, during the current session. Otherwise /// `false`. pub fn is_online(authority_index: AuthIndex) -> bool { - let current_validators = >::validators(); + let current_validators = >::validators(); if authority_index >= current_validators.len() as u32 { return false; @@ -322,7 +322,7 @@ impl Module { } fn is_online_aux(authority_index: AuthIndex, authority: &T::ValidatorId) -> bool { - let current_session = >::current_index(); + let current_session = >::current_index(); ::exists(¤t_session, &authority_index) || >::get( @@ -334,13 +334,13 @@ impl Module { /// Returns `true` if a heartbeat has been received for the authority at `authority_index` in /// the authorities series, during the current session. Otherwise `false`. pub fn received_heartbeat_in_current_session(authority_index: AuthIndex) -> bool { - let current_session = >::current_index(); + let current_session = >::current_index(); ::exists(¤t_session, &authority_index) } /// Note that the given authority has authored a block in the current session. fn note_authorship(author: T::ValidatorId) { - let current_session = >::current_index(); + let current_session = >::current_index(); >::mutate( ¤t_session, @@ -413,7 +413,7 @@ impl Module { let heartbeat_data = Heartbeat { block_number, network_state, - session_index: >::current_index(), + session_index: >::current_index(), authority_index, }; @@ -513,7 +513,7 @@ impl sp_runtime::BoundToRuntimeAppPublic for Module { type Public = T::AuthorityId; } -impl session::OneSessionHandler for Module { +impl pallet_session::OneSessionHandler for Module { type Key = T::AuthorityId; fn on_genesis_session<'a, I: 'a>(validators: I) @@ -529,7 +529,7 @@ impl session::OneSessionHandler for Module { // Tell the offchain worker to start making the next session's heartbeats. // Since we consider producing blocks as being online, // the hearbeat is defered a bit to prevent spaming. - let block_number = >::block_number(); + let block_number = >::block_number(); let half_session = T::SessionDuration::get() / 2.into(); >::put(block_number + half_session); @@ -538,9 +538,9 @@ impl session::OneSessionHandler for Module { } fn on_before_session_ending() { - let session_index = >::current_index(); + let session_index = >::current_index(); let keys = Keys::::get(); - let current_validators = >::validators(); + let current_validators = >::validators(); let offenders = current_validators.into_iter().enumerate() .filter(|(index, id)| @@ -552,8 +552,8 @@ impl session::OneSessionHandler for Module { // Remove all received heartbeats and number of authored blocks from the // current session, they have already been processed and won't be needed // anymore. - ::remove_prefix(&>::current_index()); - >::remove_prefix(&>::current_index()); + ::remove_prefix(&>::current_index()); + >::remove_prefix(&>::current_index()); if offenders.is_empty() { Self::deposit_event(RawEvent::AllGood); @@ -572,7 +572,7 @@ impl session::OneSessionHandler for Module { } #[allow(deprecated)] -impl support::unsigned::ValidateUnsigned for Module { +impl frame_support::unsigned::ValidateUnsigned for Module { type Call = Call; fn validate_unsigned(call: &Self::Call) -> TransactionValidity { @@ -583,7 +583,7 @@ impl support::unsigned::ValidateUnsigned for Module { } // check if session index from heartbeat is recent - let current_session = >::current_index(); + let current_session = >::current_index(); if heartbeat.session_index != current_session { return InvalidTransaction::Stale.into(); } diff --git a/substrate/frame/im-online/src/mock.rs b/substrate/frame/im-online/src/mock.rs index 48af849195..94f91ddc2e 100644 --- a/substrate/frame/im-online/src/mock.rs +++ b/substrate/frame/im-online/src/mock.rs @@ -25,10 +25,10 @@ use sp_runtime::Perbill; use sp_staking::{SessionIndex, offence::ReportOffence}; use sp_runtime::testing::{Header, UintAuthorityId, TestXt}; use sp_runtime::traits::{IdentityLookup, BlakeTwo256, ConvertInto}; -use primitives::H256; -use support::{impl_outer_origin, impl_outer_dispatch, parameter_types, weights::Weight}; -use {sp_io, system}; +use sp_core::H256; +use frame_support::{impl_outer_origin, impl_outer_dispatch, parameter_types, weights::Weight}; +use frame_system as system; impl_outer_origin!{ pub enum Origin for Runtime {} } @@ -44,7 +44,7 @@ thread_local! { } pub struct TestOnSessionEnding; -impl session::OnSessionEnding for TestOnSessionEnding { +impl pallet_session::OnSessionEnding for TestOnSessionEnding { fn on_session_ending(_ending_index: SessionIndex, _will_apply_at: SessionIndex) -> Option> { @@ -52,7 +52,7 @@ impl session::OnSessionEnding for TestOnSessionEnding { } } -impl session::historical::OnSessionEnding for TestOnSessionEnding { +impl pallet_session::historical::OnSessionEnding for TestOnSessionEnding { fn on_session_ending(_ending_index: SessionIndex, _will_apply_at: SessionIndex) -> Option<(Vec, Vec<(u64, u64)>)> { @@ -69,7 +69,7 @@ impl session::historical::OnSessionEnding for TestOnSessionEnding { /// An extrinsic type used for tests. pub type Extrinsic = TestXt; -type SubmitTransaction = system::offchain::TransactionSubmitter<(), Call, Extrinsic>; +type SubmitTransaction = frame_system::offchain::TransactionSubmitter<(), Call, Extrinsic>; type IdentificationTuple = (u64, u64); type Offence = crate::UnresponsivenessOffence; @@ -86,7 +86,7 @@ impl ReportOffence for OffenceHandler { } pub fn new_test_ext() -> sp_io::TestExternalities { - let t = system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); t.into() } @@ -101,7 +101,7 @@ parameter_types! { pub const AvailableBlockRatio: Perbill = Perbill::one(); } -impl system::Trait for Runtime { +impl frame_system::Trait for Runtime { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -128,9 +128,9 @@ parameter_types! { pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(33); } -impl session::Trait for Runtime { - type ShouldEndSession = session::PeriodicSessions; - type OnSessionEnding = session::historical::NoteHistoricalRoot; +impl pallet_session::Trait for Runtime { + type ShouldEndSession = pallet_session::PeriodicSessions; + type OnSessionEnding = pallet_session::historical::NoteHistoricalRoot; type SessionHandler = (ImOnline, ); type ValidatorId = u64; type ValidatorIdOf = ConvertInto; @@ -140,7 +140,7 @@ impl session::Trait for Runtime { type DisabledValidatorsThreshold = DisabledValidatorsThreshold; } -impl session::historical::Trait for Runtime { +impl pallet_session::historical::Trait for Runtime { type FullIdentification = u64; type FullIdentificationOf = ConvertInto; } @@ -149,7 +149,7 @@ parameter_types! { pub const UncleGenerations: u32 = 5; } -impl authorship::Trait for Runtime { +impl pallet_authorship::Trait for Runtime { type FindAuthor = (); type UncleGenerations = UncleGenerations; type FilterUncle = (); @@ -167,8 +167,8 @@ impl Trait for Runtime { /// Im Online module. pub type ImOnline = Module; -pub type System = system::Module; -pub type Session = session::Module; +pub type System = frame_system::Module; +pub type Session = pallet_session::Module; pub fn advance_session() { let now = System::block_number(); diff --git a/substrate/frame/im-online/src/tests.rs b/substrate/frame/im-online/src/tests.rs index db91a215de..3fbd424421 100644 --- a/substrate/frame/im-online/src/tests.rs +++ b/substrate/frame/im-online/src/tests.rs @@ -20,13 +20,13 @@ use super::*; use crate::mock::*; -use primitives::offchain::{ +use sp_core::offchain::{ OpaquePeerId, OffchainExt, TransactionPoolExt, testing::{TestOffchainExt, TestTransactionPoolExt}, }; -use support::{dispatch, assert_noop}; +use frame_support::{dispatch, assert_noop}; use sp_runtime::testing::UintAuthorityId; #[test] @@ -113,7 +113,7 @@ fn heartbeat( id: UintAuthorityId, ) -> dispatch::Result { #[allow(deprecated)] - use support::unsigned::ValidateUnsigned; + use frame_support::unsigned::ValidateUnsigned; let heartbeat = Heartbeat { block_number, @@ -129,7 +129,7 @@ fn heartbeat( #[allow(deprecated)] // Allow ValidateUnsigned ImOnline::pre_dispatch(&crate::Call::heartbeat(heartbeat.clone(), signature.clone()))?; ImOnline::heartbeat( - Origin::system(system::RawOrigin::None), + Origin::system(frame_system::RawOrigin::None), heartbeat, signature ) @@ -262,7 +262,7 @@ fn should_cleanup_received_heartbeats_on_session_end() { #[test] fn should_mark_online_validator_when_block_is_authored() { - use authorship::EventHandler; + use pallet_authorship::EventHandler; new_test_ext().execute_with(|| { advance_session(); @@ -292,7 +292,7 @@ fn should_mark_online_validator_when_block_is_authored() { #[test] fn should_not_send_a_report_if_already_online() { - use authorship::EventHandler; + use pallet_authorship::EventHandler; let mut ext = new_test_ext(); let (offchain, _state) = TestOffchainExt::new(); @@ -313,7 +313,7 @@ fn should_not_send_a_report_if_already_online() { ImOnline::note_uncle(3, 0); // when - UintAuthorityId::set_all_keys(vec![0]); // all authorities use session key 0 + UintAuthorityId::set_all_keys(vec![0]); // all authorities use pallet_session key 0 ImOnline::offchain(4); // then diff --git a/substrate/frame/indices/Cargo.toml b/substrate/frame/indices/Cargo.toml index 2503d0ea60..24609622f3 100644 --- a/substrate/frame/indices/Cargo.toml +++ b/substrate/frame/indices/Cargo.toml @@ -12,9 +12,9 @@ sp-keyring = { path = "../../primitives/keyring", optional = true } sp-std = { path = "../../primitives/std", default-features = false } sp-io = { path = "../../primitives/io", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } -primitives = { package = "sp-core", path = "../../primitives/core", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } [dev-dependencies] ref_thread_local = "0.0.0" @@ -26,10 +26,10 @@ std = [ "safe-mix/std", "sp-keyring", "codec/std", - "primitives/std", + "sp-core/std", "sp-std/std", "sp-io/std", - "support/std", + "frame-support/std", "sp-runtime/std", - "system/std", + "frame-system/std", ] diff --git a/substrate/frame/indices/src/lib.rs b/substrate/frame/indices/src/lib.rs index f74991e4ac..af30d5297e 100644 --- a/substrate/frame/indices/src/lib.rs +++ b/substrate/frame/indices/src/lib.rs @@ -21,9 +21,9 @@ use sp_std::{prelude::*, marker::PhantomData, convert::TryInto}; use codec::{Encode, Codec}; -use support::{Parameter, decl_module, decl_event, decl_storage}; +use frame_support::{Parameter, decl_module, decl_event, decl_storage}; use sp_runtime::traits::{One, SimpleArithmetic, StaticLookup, Member, LookupError}; -use system::{IsDeadAccount, OnNewAccount}; +use frame_system::{IsDeadAccount, OnNewAccount}; use self::address::Address as RawAddress; @@ -35,7 +35,7 @@ mod tests; /// Number of account IDs stored per enum set. const ENUM_SET_SIZE: u32 = 64; -pub type Address = RawAddress<::AccountId, ::AccountIndex>; +pub type Address = RawAddress<::AccountId, ::AccountIndex>; /// Turn an Id into an Index, or None for the purpose of getting /// a hint at a possibly desired index. @@ -56,7 +56,7 @@ impl> } /// The module's config trait. -pub trait Trait: system::Trait { +pub trait Trait: frame_system::Trait { /// Type used for storing an account's index; implies the maximum number of accounts the system /// can hold. type AccountIndex: Parameter + Member + Codec + Default + SimpleArithmetic + Copy; @@ -68,18 +68,18 @@ pub trait Trait: system::Trait { type ResolveHint: ResolveHint; /// The overarching event type. - type Event: From> + Into<::Event>; + type Event: From> + Into<::Event>; } decl_module! { - pub struct Module for enum Call where origin: T::Origin { + pub struct Module for enum Call where origin: T::Origin, system = frame_system { fn deposit_event() = default; } } decl_event!( pub enum Event where - ::AccountId, + ::AccountId, ::AccountIndex { /// A new account index was assigned. diff --git a/substrate/frame/indices/src/mock.rs b/substrate/frame/indices/src/mock.rs index ea24f46e13..e4ff3d2d77 100644 --- a/substrate/frame/indices/src/mock.rs +++ b/substrate/frame/indices/src/mock.rs @@ -22,13 +22,12 @@ use std::collections::HashSet; use ref_thread_local::{ref_thread_local, RefThreadLocal}; use sp_runtime::testing::Header; use sp_runtime::Perbill; -use primitives::H256; -use support::{impl_outer_origin, parameter_types, weights::Weight}; -use {sp_io, system}; +use sp_core::H256; +use frame_support::{impl_outer_origin, parameter_types, weights::Weight}; use crate::{GenesisConfig, Module, Trait, IsDeadAccount, OnNewAccount, ResolveHint}; impl_outer_origin!{ - pub enum Origin for Runtime {} + pub enum Origin for Runtime where system = frame_system {} } ref_thread_local! { @@ -71,7 +70,7 @@ parameter_types! { pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } -impl system::Trait for Runtime { +impl frame_system::Trait for Runtime { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -102,7 +101,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities { for i in 1..5 { h.insert(i); } } - let mut t = system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); GenesisConfig:: { ids: vec![1, 2, 3, 4] }.assimilate_storage(&mut t).unwrap(); diff --git a/substrate/frame/membership/Cargo.toml b/substrate/frame/membership/Cargo.toml index 13c6fba9f9..c5ffc8ce81 100644 --- a/substrate/frame/membership/Cargo.toml +++ b/substrate/frame/membership/Cargo.toml @@ -9,12 +9,12 @@ serde = { version = "1.0.101", optional = true } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false } sp-std = { path = "../../primitives/std", default-features = false } sp-io = { path = "../../primitives/io", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } [dev-dependencies] -primitives = { package = "sp-core", path = "../../primitives/core" } +sp-core = { path = "../../primitives/core" } [features] default = ["std"] @@ -24,6 +24,6 @@ std = [ "sp-runtime/std", "sp-std/std", "sp-io/std", - "support/std", - "system/std", + "frame-support/std", + "frame-system/std", ] diff --git a/substrate/frame/membership/src/lib.rs b/substrate/frame/membership/src/lib.rs index 2c441f2d72..93fcb479c7 100644 --- a/substrate/frame/membership/src/lib.rs +++ b/substrate/frame/membership/src/lib.rs @@ -23,17 +23,17 @@ #![cfg_attr(not(feature = "std"), no_std)] use sp_std::prelude::*; -use support::{ +use frame_support::{ decl_module, decl_storage, decl_event, traits::{ChangeMembers, InitializeMembers}, weights::SimpleDispatchInfo, }; -use system::{ensure_root, ensure_signed}; +use frame_system::{self as system, ensure_root, ensure_signed}; use sp_runtime::traits::EnsureOrigin; -pub trait Trait: system::Trait { +pub trait Trait: frame_system::Trait { /// The overarching event type. - type Event: From> + Into<::Event>; + type Event: From> + Into<::Event>; /// Required origin for adding a member (though can always be Root). type AddOrigin: EnsureOrigin; @@ -75,7 +75,7 @@ decl_storage! { decl_event!( pub enum Event where - ::AccountId, + ::AccountId, >::Event, { /// The given member was added; see the transaction for who. @@ -221,15 +221,15 @@ mod tests { use super::*; use std::cell::RefCell; - use support::{assert_ok, assert_noop, impl_outer_origin, parameter_types, weights::Weight}; - use primitives::H256; + use frame_support::{assert_ok, assert_noop, impl_outer_origin, parameter_types, weights::Weight}; + use sp_core::H256; // The testing primitives are very useful for avoiding having to work with signatures // or public keys. `u64` is used as the `AccountId` and no `Signature`s are requried. use sp_runtime::{Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header}; - use system::EnsureSignedBy; + use frame_system::EnsureSignedBy; impl_outer_origin! { - pub enum Origin for Test {} + pub enum Origin for Test where system = frame_system {} } // For testing the module, we construct most of a mock runtime. This means @@ -243,7 +243,7 @@ mod tests { pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } - impl system::Trait for Test { + impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -307,7 +307,7 @@ mod tests { // This function basically just builds a genesis storage key/value store according to // our desired mockup. fn new_test_ext() -> sp_io::TestExternalities { - let mut t = system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); // We use default for brevity, but you can configure as desired if needed. GenesisConfig::{ members: vec![10, 20, 30], diff --git a/substrate/frame/metadata/Cargo.toml b/substrate/frame/metadata/Cargo.toml index 0feeb14d59..b29193ec20 100644 --- a/substrate/frame/metadata/Cargo.toml +++ b/substrate/frame/metadata/Cargo.toml @@ -8,13 +8,13 @@ edition = "2018" codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } serde = { version = "1.0.101", optional = true, features = ["derive"] } sp-std = { path = "../../primitives/std", default-features = false } -primitives = { package = "sp-core", path = "../../primitives/core", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false } [features] default = ["std"] std = [ "codec/std", "sp-std/std", - "primitives/std", + "sp-core/std", "serde", ] diff --git a/substrate/frame/metadata/src/lib.rs b/substrate/frame/metadata/src/lib.rs index e37733fc9d..d47e0c75cf 100644 --- a/substrate/frame/metadata/src/lib.rs +++ b/substrate/frame/metadata/src/lib.rs @@ -28,7 +28,7 @@ use serde::Serialize; use codec::{Decode, Input, Error}; use codec::{Encode, Output}; use sp_std::vec::Vec; -use primitives::RuntimeDebug; +use sp_core::RuntimeDebug; #[cfg(feature = "std")] type StringBuf = String; @@ -391,9 +391,9 @@ pub struct ModuleMetadata { type ODFnA = Option>; type DFnA = DecodeDifferent, Vec>; -impl Into for RuntimeMetadataPrefixed { - fn into(self) -> primitives::OpaqueMetadata { - primitives::OpaqueMetadata::new(self.encode()) +impl Into for RuntimeMetadataPrefixed { + fn into(self) -> sp_core::OpaqueMetadata { + sp_core::OpaqueMetadata::new(self.encode()) } } diff --git a/substrate/frame/nicks/Cargo.toml b/substrate/frame/nicks/Cargo.toml index 924d706d51..55c1afe1b9 100644 --- a/substrate/frame/nicks/Cargo.toml +++ b/substrate/frame/nicks/Cargo.toml @@ -10,12 +10,12 @@ codec = { package = "parity-scale-codec", version = "1.0.0", default-features = sp-std = { path = "../../primitives/std", default-features = false } sp-io = { path = "../../primitives/io", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } [dev-dependencies] -primitives = { package = "sp-core", path = "../../primitives/core" } -balances = { package = "pallet-balances", path = "../balances" } +sp-core = { path = "../../primitives/core" } +pallet-balances = { path = "../balances" } [features] default = ["std"] @@ -25,6 +25,6 @@ std = [ "sp-std/std", "sp-io/std", "sp-runtime/std", - "support/std", - "system/std", + "frame-support/std", + "frame-system/std", ] diff --git a/substrate/frame/nicks/src/lib.rs b/substrate/frame/nicks/src/lib.rs index 95fd6f5b82..1c28146edb 100644 --- a/substrate/frame/nicks/src/lib.rs +++ b/substrate/frame/nicks/src/lib.rs @@ -42,19 +42,19 @@ use sp_std::prelude::*; use sp_runtime::{ traits::{StaticLookup, EnsureOrigin, Zero} }; -use support::{ +use frame_support::{ decl_module, decl_event, decl_storage, ensure, traits::{Currency, ReservableCurrency, OnUnbalanced, Get}, weights::SimpleDispatchInfo, }; -use system::{ensure_signed, ensure_root}; +use frame_system::{self as system, ensure_signed, ensure_root}; -type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; -type NegativeImbalanceOf = <::Currency as Currency<::AccountId>>::NegativeImbalance; +type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; +type NegativeImbalanceOf = <::Currency as Currency<::AccountId>>::NegativeImbalance; -pub trait Trait: system::Trait { +pub trait Trait: frame_system::Trait { /// The overarching event type. - type Event: From> + Into<::Event>; + type Event: From> + Into<::Event>; /// The currency trait. type Currency: ReservableCurrency; @@ -83,7 +83,7 @@ decl_storage! { } decl_event!( - pub enum Event where AccountId = ::AccountId, Balance = BalanceOf { + pub enum Event where AccountId = ::AccountId, Balance = BalanceOf { /// A name was set. NameSet(AccountId), /// A name was forcibly set. @@ -229,9 +229,9 @@ decl_module! { mod tests { use super::*; - use support::{assert_ok, assert_noop, impl_outer_origin, parameter_types, weights::Weight}; - use primitives::H256; - use system::EnsureSignedBy; + use frame_support::{assert_ok, assert_noop, impl_outer_origin, parameter_types, weights::Weight}; + use sp_core::H256; + use frame_system::EnsureSignedBy; // The testing primitives are very useful for avoiding having to work with signatures // or public keys. `u64` is used as the `AccountId` and no `Signature`s are required. use sp_runtime::{ @@ -239,7 +239,7 @@ mod tests { }; impl_outer_origin! { - pub enum Origin for Test {} + pub enum Origin for Test where system = frame_system {} } // For testing the module, we construct most of a mock runtime. This means @@ -253,7 +253,7 @@ mod tests { pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } - impl system::Trait for Test { + impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -275,7 +275,7 @@ mod tests { pub const TransferFee: u64 = 0; pub const CreationFee: u64 = 0; } - impl balances::Trait for Test { + impl pallet_balances::Trait for Test { type Balance = u64; type OnFreeBalanceZero = (); type OnNewAccount = (); @@ -301,15 +301,15 @@ mod tests { type MinLength = MinLength; type MaxLength = MaxLength; } - type Balances = balances::Module; + type Balances = pallet_balances::Module; type Nicks = Module; // This function basically just builds a genesis storage key/value store according to // our desired mockup. fn new_test_ext() -> sp_io::TestExternalities { - let mut t = system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); // We use default for brevity, but you can configure as desired if needed. - balances::GenesisConfig:: { + pallet_balances::GenesisConfig:: { balances: vec![ (1, 10), (2, 10), diff --git a/substrate/frame/offences/Cargo.toml b/substrate/frame/offences/Cargo.toml index db60c463a0..72e1f15c56 100644 --- a/substrate/frame/offences/Cargo.toml +++ b/substrate/frame/offences/Cargo.toml @@ -5,14 +5,14 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -balances = { package = "pallet-balances", path = "../balances", default-features = false } +pallet-balances = { path = "../balances", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } sp-std = { path = "../../primitives/std", default-features = false } serde = { version = "1.0.101", optional = true } sp-runtime = { path = "../../primitives/runtime", default-features = false } sp-staking = { path = "../../primitives/staking", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } [dev-dependencies] sp-io = { path = "../../primitives/io" } @@ -21,12 +21,12 @@ sp-core = { path = "../../primitives/core" } [features] default = ["std"] std = [ - "balances/std", + "pallet-balances/std", "codec/std", "sp-std/std", "serde", "sp-runtime/std", "sp-staking/std", - "support/std", - "system/std", + "frame-support/std", + "frame-system/std", ] diff --git a/substrate/frame/offences/src/lib.rs b/substrate/frame/offences/src/lib.rs index 6d83de3652..0dc66c72d4 100644 --- a/substrate/frame/offences/src/lib.rs +++ b/substrate/frame/offences/src/lib.rs @@ -25,7 +25,7 @@ mod mock; mod tests; use sp_std::vec::Vec; -use support::{ +use frame_support::{ decl_module, decl_event, decl_storage, Parameter, }; use sp_runtime::traits::Hash; @@ -33,17 +33,18 @@ use sp_staking::{ offence::{Offence, ReportOffence, Kind, OnOffenceHandler, OffenceDetails}, }; use codec::{Encode, Decode}; +use frame_system as system; /// A binary blob which represents a SCALE codec-encoded `O::TimeSlot`. type OpaqueTimeSlot = Vec; /// A type alias for a report identifier. -type ReportIdOf = ::Hash; +type ReportIdOf = ::Hash; /// Offences trait -pub trait Trait: system::Trait { +pub trait Trait: frame_system::Trait { /// The overarching event type. - type Event: From + Into<::Event>; + type Event: From + Into<::Event>; /// Full identification of the validator. type IdentificationTuple: Parameter + Ord; /// A handler called for every offence report. diff --git a/substrate/frame/offences/src/mock.rs b/substrate/frame/offences/src/mock.rs index abe84fe5f5..1175ebaeee 100644 --- a/substrate/frame/offences/src/mock.rs +++ b/substrate/frame/offences/src/mock.rs @@ -29,11 +29,11 @@ use sp_staking::{ use sp_runtime::testing::Header; use sp_runtime::traits::{IdentityLookup, BlakeTwo256}; use sp_core::H256; -use support::{ +use frame_support::{ impl_outer_origin, impl_outer_event, parameter_types, StorageMap, StorageDoubleMap, weights::Weight, }; -use {sp_io, system}; +use frame_system as system; impl_outer_origin!{ pub enum Origin for Runtime {} @@ -72,7 +72,7 @@ parameter_types! { pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } -impl system::Trait for Runtime { +impl frame_system::Trait for Runtime { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -107,13 +107,13 @@ impl_outer_event! { } pub fn new_test_ext() -> sp_io::TestExternalities { - let t = system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); t.into() } /// Offences module. pub type Offences = Module; -pub type System = system::Module; +pub type System = frame_system::Module; pub const KIND: [u8; 16] = *b"test_report_1234"; diff --git a/substrate/frame/offences/src/tests.rs b/substrate/frame/offences/src/tests.rs index 134c7a3cb0..2cbadf96b5 100644 --- a/substrate/frame/offences/src/tests.rs +++ b/substrate/frame/offences/src/tests.rs @@ -24,7 +24,7 @@ use crate::mock::{ offence_reports, }; use sp_runtime::Perbill; -use system::{EventRecord, Phase}; +use frame_system::{EventRecord, Phase}; #[test] fn should_report_an_authority_and_trigger_on_offence() { diff --git a/substrate/frame/randomness-collective-flip/Cargo.toml b/substrate/frame/randomness-collective-flip/Cargo.toml index 1840e795f5..131b20c28b 100644 --- a/substrate/frame/randomness-collective-flip/Cargo.toml +++ b/substrate/frame/randomness-collective-flip/Cargo.toml @@ -8,21 +8,21 @@ edition = "2018" safe-mix = { version = "1.0", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } sp-runtime = { path = "../../primitives/runtime", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } sp-std = { path = "../../primitives/std", default-features = false } [dev-dependencies] -primitives = { package = "sp-core", path = "../../primitives/core" } +sp-core = { path = "../../primitives/core" } sp-io = { path = "../../primitives/io" } [features] default = ["std"] std = [ "safe-mix/std", - "system/std", + "frame-system/std", "codec/std", - "support/std", + "frame-support/std", "sp-runtime/std", "sp-std/std", ] diff --git a/substrate/frame/randomness-collective-flip/src/lib.rs b/substrate/frame/randomness-collective-flip/src/lib.rs index 17b681d2e0..ff75d6b9b8 100644 --- a/substrate/frame/randomness-collective-flip/src/lib.rs +++ b/substrate/frame/randomness-collective-flip/src/lib.rs @@ -35,9 +35,9 @@ //! ### Example - Get random seed for the current block //! //! ``` -//! use support::{decl_module, dispatch, traits::Randomness}; +//! use frame_support::{decl_module, dispatch, traits::Randomness}; //! -//! pub trait Trait: system::Trait {} +//! pub trait Trait: frame_system::Trait {} //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { @@ -54,10 +54,10 @@ use sp_std::{prelude::*, convert::TryInto}; use sp_runtime::traits::Hash; -use support::{decl_module, decl_storage, traits::Randomness}; +use frame_support::{decl_module, decl_storage, traits::Randomness}; use safe_mix::TripletMix; use codec::Encode; -use system::Trait; +use frame_system::Trait; const RANDOM_MATERIAL_LEN: u32 = 81; @@ -70,7 +70,7 @@ fn block_number_to_index(block_number: T::BlockNumber) -> usize { decl_module! { pub struct Module for enum Call where origin: T::Origin { fn on_initialize(block_number: T::BlockNumber) { - let parent_hash = >::parent_hash(); + let parent_hash = >::parent_hash(); >::mutate(|ref mut values| if values.len() < RANDOM_MATERIAL_LEN as usize { values.push(parent_hash) @@ -130,7 +130,7 @@ impl Randomness for Module { /// and mean that all bits of the resulting value are entirely manipulatable by the author of /// the parent block, who can determine the value of `parent_hash`. fn random(subject: &[u8]) -> T::Hash { - let block_number = >::block_number(); + let block_number = >::block_number(); let index = block_number_to_index::(block_number); let hash_series = >::get(); @@ -152,17 +152,17 @@ impl Randomness for Module { #[cfg(test)] mod tests { use super::*; - use primitives::H256; + use sp_core::H256; use sp_runtime::{ Perbill, traits::{BlakeTwo256, OnInitialize, Header as _, IdentityLookup}, testing::Header, }; - use support::{impl_outer_origin, parameter_types, weights::Weight, traits::Randomness}; + use frame_support::{impl_outer_origin, parameter_types, weights::Weight, traits::Randomness}; #[derive(Clone, PartialEq, Eq)] pub struct Test; impl_outer_origin! { - pub enum Origin for Test {} + pub enum Origin for Test where system = frame_system {} } parameter_types! { @@ -172,7 +172,7 @@ mod tests { pub const AvailableBlockRatio: Perbill = Perbill::one(); } - impl system::Trait for Test { + impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -190,11 +190,11 @@ mod tests { type Version = (); } - type System = system::Module; + type System = frame_system::Module; type CollectiveFlip = Module; fn new_test_ext() -> sp_io::TestExternalities { - let t = system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); t.into() } diff --git a/substrate/frame/scored-pool/Cargo.toml b/substrate/frame/scored-pool/Cargo.toml index 5ac049d1e2..ebc5417659 100644 --- a/substrate/frame/scored-pool/Cargo.toml +++ b/substrate/frame/scored-pool/Cargo.toml @@ -10,12 +10,12 @@ serde = { version = "1.0.101", optional = true } sp-io = { path = "../../primitives/io", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } sp-std = { path = "../../primitives/std", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } [dev-dependencies] -balances = { package = "pallet-balances", path = "../balances" } -primitives = { package = "sp-core", path = "../../primitives/core" } +pallet-balances = { path = "../balances" } +sp-core = { path = "../../primitives/core" } [features] default = ["std"] @@ -25,6 +25,6 @@ std = [ "sp-io/std", "sp-runtime/std", "sp-std/std", - "support/std", - "system/std", + "frame-support/std", + "frame-system/std", ] diff --git a/substrate/frame/scored-pool/src/lib.rs b/substrate/frame/scored-pool/src/lib.rs index 30dfbbbccf..9703d041d7 100644 --- a/substrate/frame/scored-pool/src/lib.rs +++ b/substrate/frame/scored-pool/src/lib.rs @@ -53,8 +53,8 @@ //! ## Usage //! //! ``` -//! use support::{decl_module, dispatch}; -//! use system::ensure_signed; +//! use frame_support::{decl_module, dispatch}; +//! use frame_system::{self as system, ensure_signed}; //! use pallet_scored_pool::{self as scored_pool}; //! //! pub trait Trait: scored_pool::Trait {} @@ -93,17 +93,17 @@ use sp_std::{ fmt::Debug, prelude::*, }; -use support::{ +use frame_support::{ decl_module, decl_storage, decl_event, ensure, traits::{ChangeMembers, InitializeMembers, Currency, Get, ReservableCurrency}, }; -use system::{self, ensure_root, ensure_signed}; +use frame_system::{self as system, ensure_root, ensure_signed}; use sp_runtime::{ traits::{EnsureOrigin, SimpleArithmetic, MaybeSerializeDeserialize, Zero, StaticLookup}, }; -type BalanceOf = <>::Currency as Currency<::AccountId>>::Balance; -type PoolT = Vec<(::AccountId, Option<>::Score>)>; +type BalanceOf = <>::Currency as Currency<::AccountId>>::Balance; +type PoolT = Vec<(::AccountId, Option<>::Score>)>; /// The enum is supplied when refreshing the members set. /// Depending on the enum variant the corresponding associated @@ -115,7 +115,7 @@ enum ChangeReceiver { MembershipChanged, } -pub trait Trait: system::Trait { +pub trait Trait: frame_system::Trait { /// The currency used for deposits. type Currency: Currency + ReservableCurrency; @@ -124,7 +124,7 @@ pub trait Trait: system::Trait { SimpleArithmetic + Clone + Copy + Default + FullCodec + MaybeSerializeDeserialize + Debug; /// The overarching event type. - type Event: From> + Into<::Event>; + type Event: From> + Into<::Event>; // The deposit which is reserved from candidates if they want to // start a candidacy. The deposit gets returned when the candidacy is @@ -203,7 +203,7 @@ decl_storage! { decl_event!( pub enum Event where - ::AccountId, + ::AccountId, { /// The given member was removed. See the transaction for who. MemberRemoved, diff --git a/substrate/frame/scored-pool/src/mock.rs b/substrate/frame/scored-pool/src/mock.rs index 06e11e62eb..097d7bc33f 100644 --- a/substrate/frame/scored-pool/src/mock.rs +++ b/substrate/frame/scored-pool/src/mock.rs @@ -19,17 +19,17 @@ use super::*; use std::cell::RefCell; -use support::{impl_outer_origin, parameter_types, weights::Weight}; -use primitives::H256; +use frame_support::{impl_outer_origin, parameter_types, weights::Weight}; +use sp_core::H256; // The testing primitives are very useful for avoiding having to work with signatures // or public keys. `u64` is used as the `AccountId` and no `Signature`s are requried. use sp_runtime::{ Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header, }; -use system::EnsureSignedBy; +use frame_system::EnsureSignedBy; impl_outer_origin! { - pub enum Origin for Test {} + pub enum Origin for Test where system = frame_system {} } // For testing the module, we construct most of a mock runtime. This means @@ -54,7 +54,7 @@ parameter_types! { pub const CreationFee: u64 = 0; } -impl system::Trait for Test { +impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -72,7 +72,7 @@ impl system::Trait for Test { type Version = (); } -impl balances::Trait for Test { +impl pallet_balances::Trait for Test { type Balance = u64; type OnFreeBalanceZero = (); type OnNewAccount = (); @@ -116,7 +116,7 @@ impl Trait for Test { type KickOrigin = EnsureSignedBy; type MembershipInitialized = TestChangeMembers; type MembershipChanged = TestChangeMembers; - type Currency = balances::Module; + type Currency = pallet_balances::Module; type CandidateDeposit = CandidateDeposit; type Period = Period; type Score = u64; @@ -126,9 +126,9 @@ impl Trait for Test { // This function basically just builds a genesis storage key/value store according to // our desired mockup. pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); // We use default for brevity, but you can configure as desired if needed. - balances::GenesisConfig:: { + pallet_balances::GenesisConfig:: { balances: vec![ (5, 500_000), (10, 500_000), diff --git a/substrate/frame/scored-pool/src/tests.rs b/substrate/frame/scored-pool/src/tests.rs index 20aff6618a..0b3ede9ee0 100644 --- a/substrate/frame/scored-pool/src/tests.rs +++ b/substrate/frame/scored-pool/src/tests.rs @@ -19,12 +19,12 @@ use super::*; use mock::*; -use support::{assert_ok, assert_noop}; +use frame_support::{assert_ok, assert_noop}; use sp_runtime::traits::OnInitialize; type ScoredPool = Module; -type System = system::Module; -type Balances = balances::Module; +type System = frame_system::Module; +type Balances = pallet_balances::Module; const OOB_ERR: &str = "index out of bounds"; const INDEX_ERR: &str = "index does not match requested account"; diff --git a/substrate/frame/session/Cargo.toml b/substrate/frame/session/Cargo.toml index 98f5221cf1..d82b8ef144 100644 --- a/substrate/frame/session/Cargo.toml +++ b/substrate/frame/session/Cargo.toml @@ -11,16 +11,16 @@ codec = { package = "parity-scale-codec", version = "1.0.0", default-features = sp-std = { path = "../../primitives/std", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } sp-staking = { path = "../../primitives/staking", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } -timestamp = { package = "pallet-timestamp", path = "../timestamp", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } +pallet-timestamp = { path = "../timestamp", default-features = false } sp-trie = { path = "../../primitives/trie", default-features = false, optional = true } sp-io ={ path = "../../primitives/io", default-features = false } impl-trait-for-tuples = "0.1.3" [dev-dependencies] -primitives = { package = "sp-core", path = "../../primitives/core" } -app-crypto = { package = "sp-application-crypto", path = "../../primitives/application-crypto" } +sp-core = { path = "../../primitives/core" } +sp-application-crypto = { path = "../../primitives/application-crypto" } lazy_static = "1.4.0" [features] @@ -31,10 +31,10 @@ std = [ "safe-mix/std", "codec/std", "sp-std/std", - "support/std", + "frame-support/std", "sp-runtime/std", "sp-staking/std", - "timestamp/std", + "pallet-timestamp/std", "sp-trie/std", "sp-io/std", ] diff --git a/substrate/frame/session/src/historical.rs b/substrate/frame/session/src/historical.rs index e116e6ac34..1298111e93 100644 --- a/substrate/frame/session/src/historical.rs +++ b/substrate/frame/session/src/historical.rs @@ -29,8 +29,8 @@ use sp_std::prelude::*; use codec::{Encode, Decode}; use sp_runtime::KeyTypeId; use sp_runtime::traits::{Convert, OpaqueKeys, Hash as HashT}; -use support::{decl_module, decl_storage}; -use support::{Parameter, print}; +use frame_support::{decl_module, decl_storage}; +use frame_support::{Parameter, print}; use sp_trie::{MemoryDB, Trie, TrieMut, Recorder, EMPTY_PREFIX}; use sp_trie::trie_types::{TrieDBMut, TrieDB}; use super::{SessionIndex, Module as SessionModule}; @@ -146,7 +146,7 @@ impl crate::OnSessionEnding for NoteHistoricalRoot< } } -type HasherOf = <::Hashing as HashT>::Hasher; +type HasherOf = <::Hashing as HashT>::Hasher; /// A tuple of the validator's ID and their full identification. pub type IdentificationTuple = (::ValidatorId, ::FullIdentification); @@ -273,7 +273,7 @@ pub struct Proof { trie_nodes: Vec>, } -impl> support::traits::KeyOwnerProofSystem<(KeyTypeId, D)> +impl> frame_support::traits::KeyOwnerProofSystem<(KeyTypeId, D)> for Module { type Proof = Proof; @@ -310,18 +310,18 @@ impl> support::traits::KeyOwnerProofSystem<(KeyTypeId, #[cfg(test)] mod tests { use super::*; - use primitives::crypto::key_types::DUMMY; + use sp_core::crypto::key_types::DUMMY; use sp_runtime::{traits::OnInitialize, testing::UintAuthorityId}; use crate::mock::{ NEXT_VALIDATORS, force_new_session, set_next_validators, Test, System, Session, }; - use support::traits::KeyOwnerProofSystem; + use frame_support::traits::KeyOwnerProofSystem; type Historical = Module; fn new_test_ext() -> sp_io::TestExternalities { - let mut t = system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); crate::GenesisConfig:: { keys: NEXT_VALIDATORS.with(|l| l.borrow().iter().cloned().map(|i| (i, UintAuthorityId(i).into())).collect() diff --git a/substrate/frame/session/src/lib.rs b/substrate/frame/session/src/lib.rs index 2fb08540c0..aee01dc37f 100644 --- a/substrate/frame/session/src/lib.rs +++ b/substrate/frame/session/src/lib.rs @@ -122,12 +122,12 @@ use sp_std::{prelude::*, marker::PhantomData, ops::{Sub, Rem}}; use codec::Decode; use sp_runtime::{KeyTypeId, Perbill, RuntimeAppPublic, BoundToRuntimeAppPublic}; -use support::weights::SimpleDispatchInfo; +use frame_support::weights::SimpleDispatchInfo; use sp_runtime::traits::{Convert, Zero, Member, OpaqueKeys}; use sp_staking::SessionIndex; -use support::{dispatch, ConsensusEngineId, decl_module, decl_event, decl_storage}; -use support::{ensure, traits::{OnFreeBalanceZero, Get, FindAuthor, ValidatorRegistration}, Parameter}; -use system::{self, ensure_signed}; +use frame_support::{dispatch, ConsensusEngineId, decl_module, decl_event, decl_storage}; +use frame_support::{ensure, traits::{OnFreeBalanceZero, Get, FindAuthor, ValidatorRegistration}, Parameter}; +use frame_system::{self as system, ensure_signed}; #[cfg(test)] mod mock; @@ -339,9 +339,9 @@ impl ValidatorRegistration for Module { } } -pub trait Trait: system::Trait { +pub trait Trait: frame_system::Trait { /// The overarching event type. - type Event: From + Into<::Event>; + type Event: From + Into<::Event>; /// A stable ID for a validator. type ValidatorId: Member + Parameter; @@ -720,8 +720,8 @@ impl> FindAuthor #[cfg(test)] mod tests { use super::*; - use support::assert_ok; - use primitives::crypto::key_types::DUMMY; + use frame_support::assert_ok; + use sp_core::crypto::key_types::DUMMY; use sp_runtime::{traits::OnInitialize, testing::UintAuthorityId}; use mock::{ NEXT_VALIDATORS, SESSION_CHANGED, TEST_SESSION_CHANGED, authorities, force_new_session, @@ -730,7 +730,7 @@ mod tests { }; fn new_test_ext() -> sp_io::TestExternalities { - let mut t = system::GenesisConfig::default().build_storage::().unwrap(); + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); GenesisConfig:: { keys: NEXT_VALIDATORS.with(|l| l.borrow().iter().cloned().map(|i| (i, UintAuthorityId(i).into())).collect() diff --git a/substrate/frame/session/src/mock.rs b/substrate/frame/session/src/mock.rs index 9ee95d208b..14fbc46c82 100644 --- a/substrate/frame/session/src/mock.rs +++ b/substrate/frame/session/src/mock.rs @@ -18,8 +18,8 @@ use super::*; use std::cell::RefCell; -use support::{impl_outer_origin, parameter_types, weights::Weight}; -use primitives::{crypto::key_types::DUMMY, H256}; +use frame_support::{impl_outer_origin, parameter_types, weights::Weight}; +use sp_core::{crypto::key_types::DUMMY, H256}; use sp_runtime::{ Perbill, impl_opaque_keys, traits::{BlakeTwo256, IdentityLookup, ConvertInto}, testing::{Header, UintAuthorityId} @@ -39,7 +39,7 @@ impl From for MockSessionKeys { } impl_outer_origin! { - pub enum Origin for Test {} + pub enum Origin for Test where system = frame_system {} } thread_local! { @@ -158,7 +158,7 @@ parameter_types! { pub const AvailableBlockRatio: Perbill = Perbill::one(); } -impl system::Trait for Test { +impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -176,7 +176,7 @@ impl system::Trait for Test { type Version = (); } -impl timestamp::Trait for Test { +impl pallet_timestamp::Trait for Test { type Moment = u64; type OnTimestampSet = (); type MinimumPeriod = MinimumPeriod; @@ -207,5 +207,5 @@ impl crate::historical::Trait for Test { type FullIdentificationOf = sp_runtime::traits::ConvertInto; } -pub type System = system::Module; +pub type System = frame_system::Module; pub type Session = Module; diff --git a/substrate/frame/staking/Cargo.toml b/substrate/frame/staking/Cargo.toml index c82a0c13e2..878acdbce6 100644 --- a/substrate/frame/staking/Cargo.toml +++ b/substrate/frame/staking/Cargo.toml @@ -10,19 +10,19 @@ safe-mix = { version = "1.0.0", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } sp-keyring = { path = "../../primitives/keyring", optional = true } sp-std = { path = "../../primitives/std", default-features = false } -phragmen = { package = "sp-phragmen", path = "../../primitives/phragmen", default-features = false } +sp-phragmen = { path = "../../primitives/phragmen", default-features = false } sp-io ={ path = "../../primitives/io", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } sp-staking = { path = "../../primitives/staking", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } -session = { package = "pallet-session", path = "../session", default-features = false, features = ["historical"] } -authorship = { package = "pallet-authorship", path = "../authorship", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } +pallet-session = { path = "../session", default-features = false, features = ["historical"] } +pallet-authorship = { path = "../authorship", default-features = false } [dev-dependencies] -primitives = { package = "sp-core", path = "../../primitives/core" } -balances = { package = "pallet-balances", path = "../balances" } -timestamp = { package = "pallet-timestamp", path = "../timestamp" } +sp-core = { path = "../../primitives/core" } +pallet-balances = { path = "../balances" } +pallet-timestamp = { path = "../timestamp" } pallet-staking-reward-curve = { path = "../staking/reward-curve"} substrate-test-utils = { path = "../../test-utils" } @@ -36,12 +36,12 @@ std = [ "sp-keyring", "codec/std", "sp-std/std", - "phragmen/std", + "sp-phragmen/std", "sp-io/std", - "support/std", + "frame-support/std", "sp-runtime/std", "sp-staking/std", - "session/std", - "system/std", - "authorship/std", + "pallet-session/std", + "frame-system/std", + "pallet-authorship/std", ] diff --git a/substrate/frame/staking/src/lib.rs b/substrate/frame/staking/src/lib.rs index d2a6ec7c13..3d641e24a5 100644 --- a/substrate/frame/staking/src/lib.rs +++ b/substrate/frame/staking/src/lib.rs @@ -138,8 +138,8 @@ //! ### Example: Rewarding a validator by id. //! //! ``` -//! use support::{decl_module, dispatch}; -//! use system::ensure_signed; +//! use frame_support::{decl_module, dispatch}; +//! use frame_system::{self as system, ensure_signed}; //! use pallet_staking::{self as staking}; //! //! pub trait Trait: staking::Trait {} @@ -181,7 +181,7 @@ //! [`reward_by_indices`](./enum.Call.html#variant.reward_by_indices). //! //! [`Module`](./struct.Module.html) implements -//! [`authorship::EventHandler`](../pallet_authorship/trait.EventHandler.html) to add reward points +//! [`pallet_authorship::EventHandler`](../pallet_authorship/trait.EventHandler.html) to add reward points //! to block producer and block producer of referenced uncles. //! //! The validator and its nominator split their reward as following: @@ -257,7 +257,7 @@ pub mod inflation; use sp_std::{prelude::*, result}; use codec::{HasCompact, Encode, Decode}; -use support::{ +use frame_support::{ decl_module, decl_event, decl_storage, ensure, weights::SimpleDispatchInfo, traits::{ @@ -265,7 +265,7 @@ use support::{ WithdrawReasons, OnUnbalanced, Imbalance, Get, Time } }; -use session::{historical::OnSessionEnding, SelectInitialValidators}; +use pallet_session::{historical::OnSessionEnding, SelectInitialValidators}; use sp_runtime::{ Perbill, RuntimeDebug, @@ -281,9 +281,9 @@ use sp_staking::{ }; #[cfg(feature = "std")] use sp_runtime::{Serialize, Deserialize}; -use system::{ensure_signed, ensure_root}; +use frame_system::{self as system, ensure_signed, ensure_root}; -use phragmen::{ExtendedBalance, PhragmenStakedAssignment}; +use sp_phragmen::{ExtendedBalance, PhragmenStakedAssignment}; const DEFAULT_MINIMUM_VALIDATOR_COUNT: u32 = 4; const MAX_NOMINATIONS: usize = 16; @@ -521,17 +521,17 @@ pub struct UnappliedSlash { } pub type BalanceOf = - <::Currency as Currency<::AccountId>>::Balance; + <::Currency as Currency<::AccountId>>::Balance; type PositiveImbalanceOf = - <::Currency as Currency<::AccountId>>::PositiveImbalance; + <::Currency as Currency<::AccountId>>::PositiveImbalance; type NegativeImbalanceOf = - <::Currency as Currency<::AccountId>>::NegativeImbalance; + <::Currency as Currency<::AccountId>>::NegativeImbalance; type MomentOf = <::Time as Time>::Moment; /// Means for interacting with a specialized version of the `session` trait. /// -/// This is needed because `Staking` sets the `ValidatorIdOf` of the `session::Trait` -pub trait SessionInterface: system::Trait { +/// This is needed because `Staking` sets the `ValidatorIdOf` of the `pallet_session::Trait` +pub trait SessionInterface: frame_system::Trait { /// Disable a given validator by stash ID. /// /// Returns `true` if new era should be forced at the end of this session. @@ -544,31 +544,31 @@ pub trait SessionInterface: system::Trait { fn prune_historical_up_to(up_to: SessionIndex); } -impl SessionInterface<::AccountId> for T where - T: session::Trait::AccountId>, - T: session::historical::Trait< - FullIdentification = Exposure<::AccountId, BalanceOf>, +impl SessionInterface<::AccountId> for T where + T: pallet_session::Trait::AccountId>, + T: pallet_session::historical::Trait< + FullIdentification = Exposure<::AccountId, BalanceOf>, FullIdentificationOf = ExposureOf, >, - T::SessionHandler: session::SessionHandler<::AccountId>, - T::OnSessionEnding: session::OnSessionEnding<::AccountId>, - T::SelectInitialValidators: session::SelectInitialValidators<::AccountId>, - T::ValidatorIdOf: Convert<::AccountId, Option<::AccountId>> + T::SessionHandler: pallet_session::SessionHandler<::AccountId>, + T::OnSessionEnding: pallet_session::OnSessionEnding<::AccountId>, + T::SelectInitialValidators: pallet_session::SelectInitialValidators<::AccountId>, + T::ValidatorIdOf: Convert<::AccountId, Option<::AccountId>> { - fn disable_validator(validator: &::AccountId) -> Result { - >::disable(validator) + fn disable_validator(validator: &::AccountId) -> Result { + >::disable(validator) } - fn validators() -> Vec<::AccountId> { - >::validators() + fn validators() -> Vec<::AccountId> { + >::validators() } fn prune_historical_up_to(up_to: SessionIndex) { - >::prune_up_to(up_to); + >::prune_up_to(up_to); } } -pub trait Trait: system::Trait { +pub trait Trait: frame_system::Trait { /// The staking balance. type Currency: LockableCurrency; @@ -586,7 +586,7 @@ pub trait Trait: system::Trait { type RewardRemainder: OnUnbalanced>; /// The overarching event type. - type Event: From> + Into<::Event>; + type Event: From> + Into<::Event>; /// Handler for the unbalanced reduction when slashing a staker. type Slash: OnUnbalanced>; @@ -771,7 +771,7 @@ decl_storage! { } decl_event!( - pub enum Event where Balance = BalanceOf, ::AccountId { + pub enum Event where Balance = BalanceOf, ::AccountId { /// All validators have been rewarded by the first balance; the second is the remainder /// from the maximum amount of reward. Reward(Balance, Balance), @@ -1423,7 +1423,7 @@ impl Module { }); all_nominators.extend(nominator_votes); - let maybe_phragmen_result = phragmen::elect::<_, _, _, T::CurrencyToVote>( + let maybe_phragmen_result = sp_phragmen::elect::<_, _, _, T::CurrencyToVote>( Self::validator_count() as usize, Self::minimum_validator_count().max(1) as usize, all_validators, @@ -1442,7 +1442,7 @@ impl Module { let to_balance = |e: ExtendedBalance| >>::convert(e); - let mut supports = phragmen::build_support_map::<_, _, _, T::CurrencyToVote>( + let mut supports = sp_phragmen::build_support_map::<_, _, _, T::CurrencyToVote>( &elected_stashes, &assignments, Self::slashable_balance_of, @@ -1473,7 +1473,7 @@ impl Module { let tolerance = 0_u128; let iterations = 2_usize; - phragmen::equalize::<_, _, T::CurrencyToVote, _>( + sp_phragmen::equalize::<_, _, T::CurrencyToVote, _>( staked_assignments, &mut supports, tolerance, @@ -1600,7 +1600,7 @@ impl Module { } } -impl session::OnSessionEnding for Module { +impl pallet_session::OnSessionEnding for Module { fn on_session_ending(_ending: SessionIndex, start_session: SessionIndex) -> Option> { Self::ensure_storage_upgraded(); Self::new_session(start_session - 1).map(|(new, _old)| new) @@ -1627,13 +1627,13 @@ impl OnFreeBalanceZero for Module { /// * 20 points to the block producer for producing a (non-uncle) block in the relay chain, /// * 2 points to the block producer for each reference to a previously unreferenced uncle, and /// * 1 point to the producer of each referenced uncle block. -impl authorship::EventHandler for Module { +impl pallet_authorship::EventHandler for Module { fn note_author(author: T::AccountId) { Self::reward_by_ids(vec![(author, 20)]); } fn note_uncle(author: T::AccountId, _age: T::BlockNumber) { Self::reward_by_ids(vec![ - (>::author(), 2), + (>::author(), 2), (author, 1) ]) } @@ -1668,19 +1668,19 @@ impl SelectInitialValidators for Module { } /// This is intended to be used with `FilterHistoricalOffences`. -impl OnOffenceHandler> for Module where - T: session::Trait::AccountId>, - T: session::historical::Trait< - FullIdentification = Exposure<::AccountId, BalanceOf>, +impl OnOffenceHandler> for Module where + T: pallet_session::Trait::AccountId>, + T: pallet_session::historical::Trait< + FullIdentification = Exposure<::AccountId, BalanceOf>, FullIdentificationOf = ExposureOf, >, - T::SessionHandler: session::SessionHandler<::AccountId>, - T::OnSessionEnding: session::OnSessionEnding<::AccountId>, - T::SelectInitialValidators: session::SelectInitialValidators<::AccountId>, - T::ValidatorIdOf: Convert<::AccountId, Option<::AccountId>> + T::SessionHandler: pallet_session::SessionHandler<::AccountId>, + T::OnSessionEnding: pallet_session::OnSessionEnding<::AccountId>, + T::SelectInitialValidators: pallet_session::SelectInitialValidators<::AccountId>, + T::ValidatorIdOf: Convert<::AccountId, Option<::AccountId>> { fn on_offence( - offenders: &[OffenceDetails>], + offenders: &[OffenceDetails>], slash_fraction: &[Perbill], slash_session: SessionIndex, ) { diff --git a/substrate/frame/staking/src/migration.rs b/substrate/frame/staking/src/migration.rs index 4c4306253e..0ee52dc337 100644 --- a/substrate/frame/staking/src/migration.rs +++ b/substrate/frame/staking/src/migration.rs @@ -25,7 +25,7 @@ pub const CURRENT_VERSION: VersionNumber = 1; #[cfg(any(test, feature = "migrate"))] mod inner { use crate::{Store, Module, Trait}; - use support::{StorageLinkedMap, StorageValue}; + use frame_support::{StorageLinkedMap, StorageValue}; use sp_std::vec::Vec; use super::{CURRENT_VERSION, VersionNumber}; @@ -51,21 +51,21 @@ mod inner { ); if let Err(e) = res { - support::print("Encountered error in migration of Staking::Nominators map."); + frame_support::print("Encountered error in migration of Staking::Nominators map."); if e.is_none() { - support::print("Staking::Nominators map reinitialized"); + frame_support::print("Staking::Nominators map reinitialized"); } } - support::print("Finished migrating Staking storage to v1."); + frame_support::print("Finished migrating Staking storage to v1."); } pub(super) fn perform_migrations() { as Store>::StorageVersion::mutate(|version| { if *version < MIN_SUPPORTED_VERSION { - support::print("Cannot migrate staking storage because version is less than\ + frame_support::print("Cannot migrate staking storage because version is less than\ minimum."); - support::print(*version); + frame_support::print(*version); return } diff --git a/substrate/frame/staking/src/mock.rs b/substrate/frame/staking/src/mock.rs index 91c6b3c2a1..16c587f9be 100644 --- a/substrate/frame/staking/src/mock.rs +++ b/substrate/frame/staking/src/mock.rs @@ -22,9 +22,9 @@ use sp_runtime::curve::PiecewiseLinear; use sp_runtime::traits::{IdentityLookup, Convert, OpaqueKeys, OnInitialize, SaturatedConversion}; use sp_runtime::testing::{Header, UintAuthorityId}; use sp_staking::{SessionIndex, offence::{OffenceDetails, OnOffenceHandler}}; -use primitives::{H256, crypto::key_types}; +use sp_core::{H256, crypto::key_types}; use sp_io; -use support::{ +use frame_support::{ assert_ok, impl_outer_origin, parameter_types, StorageLinkedMap, StorageValue, traits::{Currency, Get, FindAuthor}, weights::Weight, @@ -55,7 +55,7 @@ thread_local! { } pub struct TestSessionHandler; -impl session::SessionHandler for TestSessionHandler { +impl pallet_session::SessionHandler for TestSessionHandler { const KEY_TYPE_IDS: &'static [KeyTypeId] = &[key_types::DUMMY]; fn on_genesis_session(_validators: &[(AccountId, Ks)]) {} @@ -99,14 +99,14 @@ impl Get for SlashDeferDuration { } impl_outer_origin!{ - pub enum Origin for Test {} + pub enum Origin for Test where system = frame_system {} } /// Author of block is always 11 pub struct Author11; impl FindAuthor for Author11 { fn find_author<'a, I>(_digests: I) -> Option - where I: 'a + IntoIterator + where I: 'a + IntoIterator { Some(11) } @@ -121,7 +121,7 @@ parameter_types! { pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } -impl system::Trait for Test { +impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = BlockNumber; @@ -142,7 +142,7 @@ parameter_types! { pub const TransferFee: Balance = 0; pub const CreationFee: Balance = 0; } -impl balances::Trait for Test { +impl pallet_balances::Trait for Test { type Balance = Balance; type OnFreeBalanceZero = Staking; type OnNewAccount = (); @@ -159,10 +159,10 @@ parameter_types! { pub const UncleGenerations: u64 = 0; pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(25); } -impl session::Trait for Test { - type OnSessionEnding = session::historical::NoteHistoricalRoot; +impl pallet_session::Trait for Test { + type OnSessionEnding = pallet_session::historical::NoteHistoricalRoot; type Keys = UintAuthorityId; - type ShouldEndSession = session::PeriodicSessions; + type ShouldEndSession = pallet_session::PeriodicSessions; type SessionHandler = TestSessionHandler; type Event = (); type ValidatorId = AccountId; @@ -171,11 +171,11 @@ impl session::Trait for Test { type DisabledValidatorsThreshold = DisabledValidatorsThreshold; } -impl session::historical::Trait for Test { +impl pallet_session::historical::Trait for Test { type FullIdentification = crate::Exposure; type FullIdentificationOf = crate::ExposureOf; } -impl authorship::Trait for Test { +impl pallet_authorship::Trait for Test { type FindAuthor = Author11; type UncleGenerations = UncleGenerations; type FilterUncle = (); @@ -184,7 +184,7 @@ impl authorship::Trait for Test { parameter_types! { pub const MinimumPeriod: u64 = 5; } -impl timestamp::Trait for Test { +impl pallet_timestamp::Trait for Test { type Moment = u64; type OnTimestampSet = (); type MinimumPeriod = MinimumPeriod; @@ -205,8 +205,8 @@ parameter_types! { pub const RewardCurve: &'static PiecewiseLinear<'static> = &I_NPOS; } impl Trait for Test { - type Currency = balances::Module; - type Time = timestamp::Module; + type Currency = pallet_balances::Module; + type Time = pallet_timestamp::Module; type CurrencyToVote = CurrencyToVoteHandler; type RewardRemainder = (); type Event = (); @@ -214,7 +214,7 @@ impl Trait for Test { type Reward = (); type SessionsPerEra = SessionsPerEra; type SlashDeferDuration = SlashDeferDuration; - type SlashCancelOrigin = system::EnsureRoot; + type SlashCancelOrigin = frame_system::EnsureRoot; type BondingDuration = BondingDuration; type SessionInterface = Self; type RewardCurve = RewardCurve; @@ -291,7 +291,7 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { self.set_associated_consts(); - let mut storage = system::GenesisConfig::default().build_storage::().unwrap(); + let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); let balance_factor = if self.existential_deposit > 0 { 256 } else { @@ -303,7 +303,7 @@ impl ExtBuilder { .map(|x| ((x + 1) * 10 + 1) as u64) .collect::>(); - let _ = balances::GenesisConfig::{ + let _ = pallet_balances::GenesisConfig::{ balances: vec![ (1, 10 * balance_factor), (2, 20 * balance_factor), @@ -351,7 +351,7 @@ impl ExtBuilder { ..Default::default() }.assimilate_storage(&mut storage); - let _ = session::GenesisConfig:: { + let _ = pallet_session::GenesisConfig:: { keys: validators.iter().map(|x| (*x, UintAuthorityId(*x))).collect(), }.assimilate_storage(&mut storage); @@ -366,10 +366,10 @@ impl ExtBuilder { } } -pub type System = system::Module; -pub type Balances = balances::Module; -pub type Session = session::Module; -pub type Timestamp = timestamp::Module; +pub type System = frame_system::Module; +pub type Balances = pallet_balances::Module; +pub type Session = pallet_session::Module; +pub type Timestamp = pallet_timestamp::Module; pub type Staking = Module; pub fn check_exposure_all() { @@ -481,7 +481,7 @@ pub fn validator_controllers() -> Vec { } pub fn on_offence_in_era( - offenders: &[OffenceDetails>], + offenders: &[OffenceDetails>], slash_fraction: &[Perbill], era: EraIndex, ) { @@ -503,7 +503,7 @@ pub fn on_offence_in_era( } pub fn on_offence_now( - offenders: &[OffenceDetails>], + offenders: &[OffenceDetails>], slash_fraction: &[Perbill], ) { let now = Staking::current_era(); diff --git a/substrate/frame/staking/src/slashing.rs b/substrate/frame/staking/src/slashing.rs index 54b14a0cf8..b4ef364cb3 100644 --- a/substrate/frame/staking/src/slashing.rs +++ b/substrate/frame/staking/src/slashing.rs @@ -53,7 +53,7 @@ use super::{ NegativeImbalanceOf, UnappliedSlash, }; use sp_runtime::traits::{Zero, Saturating}; -use support::{ +use frame_support::{ StorageMap, StorageDoubleMap, traits::{Currency, OnUnbalanced, Imbalance}, }; diff --git a/substrate/frame/staking/src/tests.rs b/substrate/frame/staking/src/tests.rs index 0f0dbb4eba..c31cdf7611 100644 --- a/substrate/frame/staking/src/tests.rs +++ b/substrate/frame/staking/src/tests.rs @@ -20,7 +20,7 @@ use super::*; use mock::*; use sp_runtime::{assert_eq_error_rate, traits::OnInitialize}; use sp_staking::offence::OffenceDetails; -use support::{assert_ok, assert_noop, traits::{Currency, ReservableCurrency}}; +use frame_support::{assert_ok, assert_noop, traits::{Currency, ReservableCurrency}}; use substrate_test_utils::assert_eq_uvec; #[test] @@ -1688,9 +1688,9 @@ fn reward_validator_slashing_validator_doesnt_overflow() { #[test] fn reward_from_authorship_event_handler_works() { ExtBuilder::default().build().execute_with(|| { - use authorship::EventHandler; + use pallet_authorship::EventHandler; - assert_eq!(>::author(), 11); + assert_eq!(>::author(), 11); >::note_author(11); >::note_uncle(21, 1); diff --git a/substrate/frame/sudo/Cargo.toml b/substrate/frame/sudo/Cargo.toml index 1487df43b5..733e9a7084 100644 --- a/substrate/frame/sudo/Cargo.toml +++ b/substrate/frame/sudo/Cargo.toml @@ -10,11 +10,11 @@ codec = { package = "parity-scale-codec", version = "1.0.0", default-features = sp-std = { path = "../../primitives/std", default-features = false } sp-io = { path = "../../primitives/io", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } [dev-dependencies] -primitives = { package = "sp-core", path = "../../primitives/core" } +sp-core = { path = "../../primitives/core" } [features] default = ["std"] @@ -24,6 +24,6 @@ std = [ "sp-std/std", "sp-io/std", "sp-runtime/std", - "support/std", - "system/std", + "frame-support/std", + "frame-system/std", ] diff --git a/substrate/frame/sudo/src/lib.rs b/substrate/frame/sudo/src/lib.rs index 95ff953904..3a80c2e946 100644 --- a/substrate/frame/sudo/src/lib.rs +++ b/substrate/frame/sudo/src/lib.rs @@ -51,10 +51,10 @@ //! This is an example of a module that exposes a privileged function: //! //! ``` -//! use support::{decl_module, dispatch}; -//! use system::ensure_root; +//! use frame_support::{decl_module, dispatch}; +//! use frame_system::{self as system, ensure_root}; //! -//! pub trait Trait: system::Trait {} +//! pub trait Trait: frame_system::Trait {} //! //! decl_module! { //! pub struct Module for enum Call where origin: T::Origin { @@ -90,15 +90,15 @@ use sp_std::prelude::*; use sp_runtime::{ traits::{StaticLookup, Dispatchable}, DispatchError, }; -use support::{ +use frame_support::{ Parameter, decl_module, decl_event, decl_storage, ensure, weights::SimpleDispatchInfo, }; -use system::ensure_signed; +use frame_system::{self as system, ensure_signed}; -pub trait Trait: system::Trait { +pub trait Trait: frame_system::Trait { /// The overarching event type. - type Event: From> + Into<::Event>; + type Event: From> + Into<::Event>; /// A sudo-able call. type Proposal: Parameter + Dispatchable; @@ -125,7 +125,7 @@ decl_module! { let sender = ensure_signed(origin)?; ensure!(sender == Self::key(), "only the current sudo key can sudo"); - let res = match proposal.dispatch(system::RawOrigin::Root.into()) { + let res = match proposal.dispatch(frame_system::RawOrigin::Root.into()) { Ok(_) => true, Err(e) => { let e: DispatchError = e.into(); @@ -175,7 +175,7 @@ decl_module! { let who = T::Lookup::lookup(who)?; - let res = match proposal.dispatch(system::RawOrigin::Signed(who).into()) { + let res = match proposal.dispatch(frame_system::RawOrigin::Signed(who).into()) { Ok(_) => true, Err(e) => { let e: DispatchError = e.into(); @@ -190,7 +190,7 @@ decl_module! { } decl_event!( - pub enum Event where AccountId = ::AccountId { + pub enum Event where AccountId = ::AccountId { /// A sudo just took place. Sudid(bool), /// The sudoer just switched identity; the old key is supplied. diff --git a/substrate/frame/support/Cargo.toml b/substrate/frame/support/Cargo.toml index 4312cbceeb..ad04964b12 100644 --- a/substrate/frame/support/Cargo.toml +++ b/substrate/frame/support/Cargo.toml @@ -12,13 +12,13 @@ frame-metadata = { path = "../metadata", default-features = false } sp-std = { path = "../../primitives/std", default-features = false } sp-io ={ path = "../../primitives/io", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } -primitives = { package = "sp-core", path = "../../primitives/core", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false } sp-arithmetic = { path = "../../primitives/arithmetic", default-features = false } -inherents = { package = "sp-inherents", path = "../../primitives/inherents", default-features = false } -frame-support-procedural = { package = "frame-support-procedural", path = "./procedural" } +sp-inherents = { path = "../../primitives/inherents", default-features = false } +frame-support-procedural = { path = "./procedural" } paste = "0.1.6" once_cell = { version = "0.2.4", default-features = false, optional = true } -state-machine = { package = "sp-state-machine", path = "../../primitives/state-machine", optional = true } +sp-state-machine = { path = "../../primitives/state-machine", optional = true } bitmask = { version = "0.5.0", default-features = false } impl-trait-for-tuples = "0.1.3" tracing = { version = "0.1.10", optional = true } @@ -40,8 +40,8 @@ std = [ "sp-runtime/std", "sp-arithmetic/std", "frame-metadata/std", - "inherents/std", - "state-machine", + "sp-inherents/std", + "sp-state-machine", ] nightly = [] strict = [] diff --git a/substrate/frame/support/procedural/Cargo.toml b/substrate/frame/support/procedural/Cargo.toml index 2231cf67db..220aea5028 100644 --- a/substrate/frame/support/procedural/Cargo.toml +++ b/substrate/frame/support/procedural/Cargo.toml @@ -8,7 +8,7 @@ edition = "2018" proc-macro = true [dependencies] -frame-support-procedural-tools = { package = "frame-support-procedural-tools", path = "./tools" } +frame-support-procedural-tools = { path = "./tools" } proc-macro2 = "1.0.6" quote = "1.0.2" diff --git a/substrate/frame/support/procedural/src/construct_runtime/mod.rs b/substrate/frame/support/procedural/src/construct_runtime/mod.rs index 184cb4d49d..07b7f2cefe 100644 --- a/substrate/frame/support/procedural/src/construct_runtime/mod.rs +++ b/substrate/frame/support/procedural/src/construct_runtime/mod.rs @@ -79,7 +79,7 @@ fn construct_runtime_parsed(definition: RuntimeDefinition) -> Result( fn decl_all_modules<'a>( runtime: &'a Ident, + system_name: &'a Ident, module_declarations: impl Iterator, ) -> TokenStream2 { let mut types = TokenStream2::new(); @@ -335,7 +336,7 @@ fn decl_all_modules<'a>( ); quote!( - pub type System = system::Module<#runtime>; + pub type System = #system_name::Module<#runtime>; #types type AllModules = ( #all_modules ); ) diff --git a/substrate/frame/support/procedural/src/construct_runtime/parse.rs b/substrate/frame/support/procedural/src/construct_runtime/parse.rs index a5338bb8af..84ac6573c6 100644 --- a/substrate/frame/support/procedural/src/construct_runtime/parse.rs +++ b/substrate/frame/support/procedural/src/construct_runtime/parse.rs @@ -243,7 +243,7 @@ impl ModuleDeclaration { .collect(); res.extend( ["Event", "Config"] - .into_iter() + .iter() .map(|name| ModulePart::with_generics(name, span)), ); res @@ -345,7 +345,7 @@ impl ModulePart { pub fn is_included_in_default(&self) -> bool { ["Module", "Call", "Storage", "Event", "Config"] - .into_iter() + .iter() .any(|name| self.name == name) } diff --git a/substrate/frame/support/procedural/tools/Cargo.toml b/substrate/frame/support/procedural/tools/Cargo.toml index 8a9f87116b..00ac787c57 100644 --- a/substrate/frame/support/procedural/tools/Cargo.toml +++ b/substrate/frame/support/procedural/tools/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -frame-support-procedural-tools-derive = { package = "frame-support-procedural-tools-derive", path = "./derive" } +frame-support-procedural-tools-derive = { path = "./derive" } proc-macro2 = "1.0.6" quote = "1.0.2" syn = { version = "1.0.7", features = ["full", "visit"] } diff --git a/substrate/frame/support/src/debug.rs b/substrate/frame/support/src/debug.rs index 0609148092..2e64b67c1b 100644 --- a/substrate/frame/support/src/debug.rs +++ b/substrate/frame/support/src/debug.rs @@ -25,7 +25,7 @@ //! this that are described below. //! //! First component to utilize debug-printing and loggin is actually -//! located in `primitives` crate: `primitives::RuntimeDebug`. +//! located in `primitives` crate: `sp_core::RuntimeDebug`. //! This custom-derive generates `core::fmt::Debug` implementation, //! just like regular `derive(Debug)`, however it does not generate //! any code when the code is compiled to WASM. This means that @@ -37,7 +37,7 @@ //! ```rust,no_run //! use frame_support::debug; //! -//! #[derive(primitives::RuntimeDebug)] +//! #[derive(sp_core::RuntimeDebug)] //! struct MyStruct { //! a: u64, //! } @@ -68,7 +68,7 @@ //! ```rust,no_run //! use frame_support::debug::native; //! -//! #[derive(primitives::RuntimeDebug)] +//! #[derive(sp_core::RuntimeDebug)] //! struct MyStruct { //! a: u64, //! } diff --git a/substrate/frame/support/src/event.rs b/substrate/frame/support/src/event.rs index 5b8ce1830e..3453adf796 100644 --- a/substrate/frame/support/src/event.rs +++ b/substrate/frame/support/src/event.rs @@ -530,7 +530,7 @@ macro_rules! __impl_outer_event_json_metadata { $crate::event::OuterEventMetadata { name: $crate::event::DecodeDifferent::Encode(stringify!($event_name)), events: $crate::event::DecodeDifferent::Encode(&[ - ("system", $crate::event::FnEncode(system::Event::metadata)) + ("system", $crate::event::FnEncode($system::Event::metadata)) $( , ( stringify!($module_name), @@ -542,6 +542,7 @@ macro_rules! __impl_outer_event_json_metadata { ]) } } + #[allow(dead_code)] pub fn __module_events_system() -> &'static [$crate::event::EventMetadata] { system::Event::metadata() diff --git a/substrate/frame/support/src/inherent.rs b/substrate/frame/support/src/inherent.rs index 5dfb1bade8..fc11cd0a2e 100644 --- a/substrate/frame/support/src/inherent.rs +++ b/substrate/frame/support/src/inherent.rs @@ -19,7 +19,7 @@ pub use crate::sp_std::vec::Vec; #[doc(hidden)] pub use crate::sp_runtime::traits::{Block as BlockT, Extrinsic}; #[doc(hidden)] -pub use inherents::{InherentData, ProvideInherent, CheckInherentsResult, IsFatalError}; +pub use sp_inherents::{InherentData, ProvideInherent, CheckInherentsResult, IsFatalError}; /// Implement the outer inherent. diff --git a/substrate/frame/support/src/lib.rs b/substrate/frame/support/src/lib.rs index 1ddc6db65c..cf6b2472f0 100644 --- a/substrate/frame/support/src/lib.rs +++ b/substrate/frame/support/src/lib.rs @@ -39,7 +39,7 @@ pub use once_cell; pub use paste; #[cfg(feature = "std")] #[doc(hidden)] -pub use state_machine::BasicExternalities; +pub use sp_state_machine::BasicExternalities; #[doc(hidden)] pub use sp_io::storage::root as storage_root; #[doc(hidden)] diff --git a/substrate/frame/support/src/storage/child.rs b/substrate/frame/support/src/storage/child.rs index abd1a208c6..5aca2d3125 100644 --- a/substrate/frame/support/src/storage/child.rs +++ b/substrate/frame/support/src/storage/child.rs @@ -27,7 +27,7 @@ use crate::sp_std::prelude::*; use codec::{Codec, Encode, Decode}; -pub use primitives::storage::ChildInfo; +pub use sp_core::storage::ChildInfo; /// Return the value of the item in storage under `key`, or `None` if there is no explicit entry. pub fn get( diff --git a/substrate/frame/support/src/storage/mod.rs b/substrate/frame/support/src/storage/mod.rs index 4a392affbd..7c0ee4c8e4 100644 --- a/substrate/frame/support/src/storage/mod.rs +++ b/substrate/frame/support/src/storage/mod.rs @@ -423,7 +423,7 @@ pub trait StoragePrefixedMap { #[cfg(test)] mod test { - use primitives::hashing::twox_128; + use sp_core::hashing::twox_128; use sp_io::TestExternalities; use crate::storage::{unhashed, StoragePrefixedMap}; diff --git a/substrate/frame/support/src/traits.rs b/substrate/frame/support/src/traits.rs index ae1695b3d3..afc4a4e4f4 100644 --- a/substrate/frame/support/src/traits.rs +++ b/substrate/frame/support/src/traits.rs @@ -20,7 +20,7 @@ use sp_std::{prelude::*, result, marker::PhantomData, ops::Div, fmt::Debug}; use codec::{FullCodec, Codec, Encode, Decode}; -use primitives::u32_trait::Value as U32; +use sp_core::u32_trait::Value as U32; use sp_runtime::{ ConsensusEngineId, traits::{MaybeSerializeDeserialize, SimpleArithmetic, Saturating}, diff --git a/substrate/frame/support/test/Cargo.toml b/substrate/frame/support/test/Cargo.toml index abd44f7a95..8637a582bf 100644 --- a/substrate/frame/support/test/Cargo.toml +++ b/substrate/frame/support/test/Cargo.toml @@ -8,11 +8,11 @@ edition = "2018" serde = { version = "1.0.101", default-features = false, features = ["derive"] } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } sp-io ={ path = "../../../primitives/io", default-features = false } -state-machine ={ package = "sp-state-machine", path = "../../../primitives/state-machine", optional = true } -support = { package = "frame-support", version = "2", path = "../", default-features = false } -inherents = { package = "sp-inherents", path = "../../../primitives/inherents", default-features = false } -sp-runtime = { package = "sp-runtime", path = "../../../primitives/runtime", default-features = false } -primitives = { package = "sp-core", path = "../../../primitives/core", default-features = false } +sp-state-machine = { path = "../../../primitives/state-machine", optional = true } +frame-support = { version = "2", path = "../", default-features = false } +sp-inherents = { path = "../../../primitives/inherents", default-features = false } +sp-runtime = { path = "../../../primitives/runtime", default-features = false } +sp-core = { path = "../../../primitives/core", default-features = false } trybuild = "1.0.17" pretty_assertions = "0.6.1" @@ -22,9 +22,9 @@ std = [ "serde/std", "codec/std", "sp-io/std", - "support/std", - "inherents/std", - "primitives/std", + "frame-support/std", + "sp-inherents/std", + "sp-core/std", "sp-runtime/std", - "state-machine", + "sp-state-machine", ] diff --git a/substrate/frame/support/test/src/lib.rs b/substrate/frame/support/test/src/lib.rs index 95fa5c6e95..c6a93e1b77 100644 --- a/substrate/frame/support/test/src/lib.rs +++ b/substrate/frame/support/test/src/lib.rs @@ -14,5 +14,5 @@ // You should have received a copy of the GNU General Public License // along with Substrate. If not, see . -//! Test crate for frame_support. Allow to make use of `support::decl_storage`. +//! Test crate for frame_support. Allow to make use of `frame_support::decl_storage`. //! See tests directory. diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/abundant_where_param.rs b/substrate/frame/support/test/tests/construct_runtime_ui/abundant_where_param.rs index 4d5b40d7c9..d5e9f22521 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/abundant_where_param.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/abundant_where_param.rs @@ -1,4 +1,4 @@ -use support::construct_runtime; +use frame_support::construct_runtime; construct_runtime! { pub enum Runtime where diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/double_module_parts.rs b/substrate/frame/support/test/tests/construct_runtime_ui/double_module_parts.rs index b741b316e1..0907f0bfb3 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/double_module_parts.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/double_module_parts.rs @@ -1,4 +1,4 @@ -use support::construct_runtime; +use frame_support::construct_runtime; construct_runtime! { pub enum Runtime where diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/double_module_parts_default.rs b/substrate/frame/support/test/tests/construct_runtime_ui/double_module_parts_default.rs index d259389460..3d61abebe8 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/double_module_parts_default.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/double_module_parts_default.rs @@ -1,4 +1,4 @@ -use support::construct_runtime; +use frame_support::construct_runtime; construct_runtime! { pub enum Runtime where diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.rs b/substrate/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.rs index 16e3696195..5a9a4612ed 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.rs @@ -1,4 +1,4 @@ -use support::construct_runtime; +use frame_support::construct_runtime; construct_runtime! { pub enum Runtime where diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/invalid_module_details.rs b/substrate/frame/support/test/tests/construct_runtime_ui/invalid_module_details.rs index bfaeca6a42..336e27e915 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/invalid_module_details.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/invalid_module_details.rs @@ -1,4 +1,4 @@ -use support::construct_runtime; +use frame_support::construct_runtime; construct_runtime! { pub enum Runtime where diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.rs b/substrate/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.rs index 87e802f4bc..0891483c92 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.rs @@ -1,4 +1,4 @@ -use support::construct_runtime; +use frame_support::construct_runtime; construct_runtime! { pub enum Runtime where diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/invalid_token_after_module.rs b/substrate/frame/support/test/tests/construct_runtime_ui/invalid_token_after_module.rs index d7307c2548..448ae913f3 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/invalid_token_after_module.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/invalid_token_after_module.rs @@ -1,4 +1,4 @@ -use support::construct_runtime; +use frame_support::construct_runtime; construct_runtime! { pub enum Runtime where diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/invalid_token_after_name.rs b/substrate/frame/support/test/tests/construct_runtime_ui/invalid_token_after_name.rs index f0fb296c73..43538789f1 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/invalid_token_after_name.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/invalid_token_after_name.rs @@ -1,4 +1,4 @@ -use support::construct_runtime; +use frame_support::construct_runtime; construct_runtime! { pub enum Runtime where diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/invalid_where_param.rs b/substrate/frame/support/test/tests/construct_runtime_ui/invalid_where_param.rs index 000af42715..13536338e0 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/invalid_where_param.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/invalid_where_param.rs @@ -1,4 +1,4 @@ -use support::construct_runtime; +use frame_support::construct_runtime; construct_runtime! { pub enum Runtime where diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/missing_event_generic_on_module_with_instance.rs b/substrate/frame/support/test/tests/construct_runtime_ui/missing_event_generic_on_module_with_instance.rs index 224ec65ee3..928871fab2 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/missing_event_generic_on_module_with_instance.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/missing_event_generic_on_module_with_instance.rs @@ -1,4 +1,4 @@ -use support::construct_runtime; +use frame_support::construct_runtime; construct_runtime! { pub enum Runtime where diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/missing_module_instance.rs b/substrate/frame/support/test/tests/construct_runtime_ui/missing_module_instance.rs index 9171827d16..fbc4b60db8 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/missing_module_instance.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/missing_module_instance.rs @@ -1,4 +1,4 @@ -use support::construct_runtime; +use frame_support::construct_runtime; construct_runtime! { pub enum Runtime where diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/missing_origin_generic_on_module_with_instance.rs b/substrate/frame/support/test/tests/construct_runtime_ui/missing_origin_generic_on_module_with_instance.rs index 6eadbbf3e0..35a5c8201b 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/missing_origin_generic_on_module_with_instance.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/missing_origin_generic_on_module_with_instance.rs @@ -1,4 +1,4 @@ -use support::construct_runtime; +use frame_support::construct_runtime; construct_runtime! { pub enum Runtime where diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/missing_system_module.rs b/substrate/frame/support/test/tests/construct_runtime_ui/missing_system_module.rs index 409ee2b8ba..71dabf91c1 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/missing_system_module.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/missing_system_module.rs @@ -1,4 +1,4 @@ -use support::construct_runtime; +use frame_support::construct_runtime; construct_runtime! { pub enum Runtime where diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/missing_where_block.rs b/substrate/frame/support/test/tests/construct_runtime_ui/missing_where_block.rs index 8d43c58140..5148330ae5 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/missing_where_block.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/missing_where_block.rs @@ -1,4 +1,4 @@ -use support::construct_runtime; +use frame_support::construct_runtime; construct_runtime! { pub enum Runtime {} diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/missing_where_param.rs b/substrate/frame/support/test/tests/construct_runtime_ui/missing_where_param.rs index 7ec6409124..2e311c5ea0 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/missing_where_param.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/missing_where_param.rs @@ -1,4 +1,4 @@ -use support::construct_runtime; +use frame_support::construct_runtime; construct_runtime! { pub enum Runtime where diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/no_comma_after_where.rs b/substrate/frame/support/test/tests/construct_runtime_ui/no_comma_after_where.rs index 096d5fd376..954fadefa1 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/no_comma_after_where.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/no_comma_after_where.rs @@ -1,4 +1,4 @@ -use support::construct_runtime; +use frame_support::construct_runtime; construct_runtime! { pub enum Runtime where diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/params_in_invalid_module.rs b/substrate/frame/support/test/tests/construct_runtime_ui/params_in_invalid_module.rs index f493371bb3..a739277d62 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/params_in_invalid_module.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/params_in_invalid_module.rs @@ -1,4 +1,4 @@ -use support::construct_runtime; +use frame_support::construct_runtime; construct_runtime! { pub enum Runtime where diff --git a/substrate/frame/support/test/tests/decl_storage.rs b/substrate/frame/support/test/tests/decl_storage.rs index 1c7ff1ce0a..e12799f479 100644 --- a/substrate/frame/support/test/tests/decl_storage.rs +++ b/substrate/frame/support/test/tests/decl_storage.rs @@ -18,12 +18,12 @@ // Do not complain about unused `dispatch` and `dispatch_aux`. #[allow(dead_code)] mod tests { - use support::metadata::*; + use frame_support::metadata::*; use sp_io::TestExternalities; use std::marker::PhantomData; use codec::{Encode, Decode, EncodeLike}; - support::decl_module! { + frame_support::decl_module! { pub struct Module for enum Call where origin: T::Origin {} } @@ -32,7 +32,7 @@ mod tests { type BlockNumber; } - support::decl_storage! { + frame_support::decl_storage! { trait Store for Module as TestStorage { // non-getters: pub / $default @@ -478,13 +478,13 @@ mod test2 { type BlockNumber; } - support::decl_module! { + frame_support::decl_module! { pub struct Module for enum Call where origin: T::Origin {} } type PairOf = (T, T); - support::decl_storage! { + frame_support::decl_storage! { trait Store for Module as TestStorage { SingleDef : u32; PairDef : PairOf; @@ -513,10 +513,10 @@ mod test3 { type Origin; type BlockNumber; } - support::decl_module! { + frame_support::decl_module! { pub struct Module for enum Call where origin: T::Origin {} } - support::decl_storage! { + frame_support::decl_storage! { trait Store for Module as Test { Foo get(fn foo) config(initial_foo): u32; } @@ -543,14 +543,14 @@ mod test_append_and_len { type BlockNumber; } - support::decl_module! { + frame_support::decl_module! { pub struct Module for enum Call where origin: T::Origin {} } #[derive(PartialEq, Eq, Clone, Encode, Decode)] struct NoDef(u32); - support::decl_storage! { + frame_support::decl_storage! { trait Store for Module as Test { NoDefault: Option; diff --git a/substrate/frame/support/test/tests/decl_storage_ui/config_duplicate.rs b/substrate/frame/support/test/tests/decl_storage_ui/config_duplicate.rs index bdd7da7449..e00f9a8f4c 100644 --- a/substrate/frame/support/test/tests/decl_storage_ui/config_duplicate.rs +++ b/substrate/frame/support/test/tests/decl_storage_ui/config_duplicate.rs @@ -19,11 +19,11 @@ pub trait Trait { type BlockNumber: codec::Codec + codec::EncodeLike + Default + Clone; } -support::decl_module! { +frame_support::decl_module! { pub struct Module for enum Call where origin: T::Origin {} } -support::decl_storage!{ +frame_support::decl_storage!{ trait Store for Module as FinalKeysNone { pub Value config(value): u32; pub Value2 config(value): u32; diff --git a/substrate/frame/support/test/tests/decl_storage_ui/config_get_duplicate.rs b/substrate/frame/support/test/tests/decl_storage_ui/config_get_duplicate.rs index 2bf8df4532..6ce8194b57 100644 --- a/substrate/frame/support/test/tests/decl_storage_ui/config_get_duplicate.rs +++ b/substrate/frame/support/test/tests/decl_storage_ui/config_get_duplicate.rs @@ -19,11 +19,11 @@ pub trait Trait { type BlockNumber: codec::Codec + codec::EncodeLike + Default + Clone; } -support::decl_module! { +frame_support::decl_module! { pub struct Module for enum Call where origin: T::Origin {} } -support::decl_storage!{ +frame_support::decl_storage!{ trait Store for Module as FinalKeysNone { pub Value get(fn value) config(): u32; pub Value2 config(value): u32; diff --git a/substrate/frame/support/test/tests/decl_storage_ui/get_duplicate.rs b/substrate/frame/support/test/tests/decl_storage_ui/get_duplicate.rs index 41ca708352..d593ddc477 100644 --- a/substrate/frame/support/test/tests/decl_storage_ui/get_duplicate.rs +++ b/substrate/frame/support/test/tests/decl_storage_ui/get_duplicate.rs @@ -19,11 +19,11 @@ pub trait Trait { type BlockNumber: codec::Codec + codec::EncodeLike + Default + Clone; } -support::decl_module! { +frame_support::decl_module! { pub struct Module for enum Call where origin: T::Origin {} } -support::decl_storage!{ +frame_support::decl_storage!{ trait Store for Module as FinalKeysNone { pub Value get(fn value) config(): u32; pub Value2 get(fn value) config(): u32; diff --git a/substrate/frame/support/test/tests/final_keys.rs b/substrate/frame/support/test/tests/final_keys.rs index 21f91e4f78..3d4c3f5060 100644 --- a/substrate/frame/support/test/tests/final_keys.rs +++ b/substrate/frame/support/test/tests/final_keys.rs @@ -14,9 +14,9 @@ // You should have received a copy of the GNU General Public License // along with Substrate. If not, see . -use support::storage::unhashed; +use frame_support::storage::unhashed; use codec::Encode; -use support::{StorageDoubleMap, StorageLinkedMap, StorageMap, StorageValue, StoragePrefixedMap}; +use frame_support::{StorageDoubleMap, StorageLinkedMap, StorageMap, StorageValue, StoragePrefixedMap}; use sp_io::{TestExternalities, hashing::{twox_128, blake2_128, blake2_256}}; mod no_instance { @@ -27,11 +27,11 @@ mod no_instance { type BlockNumber: Encode + Decode + EncodeLike + Default + Clone; } - support::decl_module! { + frame_support::decl_module! { pub struct Module for enum Call where origin: T::Origin {} } - support::decl_storage!{ + frame_support::decl_storage!{ trait Store for Module as FinalKeysNone { pub Value config(value): u32; @@ -54,12 +54,12 @@ mod no_instance { mod instance { pub trait Trait: super::no_instance::Trait {} - support::decl_module! { + frame_support::decl_module! { pub struct Module, I: Instantiable = DefaultInstance> for enum Call where origin: T::Origin {} } - support::decl_storage!{ + frame_support::decl_storage!{ trait Store for Module, I: Instantiable = DefaultInstance> as FinalKeysSome { diff --git a/substrate/frame/support/test/tests/genesisconfig.rs b/substrate/frame/support/test/tests/genesisconfig.rs index e945c774c0..1b5a935983 100644 --- a/substrate/frame/support/test/tests/genesisconfig.rs +++ b/substrate/frame/support/test/tests/genesisconfig.rs @@ -19,11 +19,11 @@ pub trait Trait { type Origin; } -support::decl_module! { +frame_support::decl_module! { pub struct Module for enum Call where origin: T::Origin {} } -support::decl_storage! { +frame_support::decl_storage! { trait Store for Module as Example { pub AppendableDM config(t): double_map u32, blake2_256(T::BlockNumber) => Vec; } diff --git a/substrate/frame/support/test/tests/instance.rs b/substrate/frame/support/test/tests/instance.rs index 0525589afa..835c082a66 100644 --- a/substrate/frame/support/test/tests/instance.rs +++ b/substrate/frame/support/test/tests/instance.rs @@ -17,7 +17,7 @@ #![recursion_limit="128"] use sp_runtime::{generic, BuildStorage, traits::{BlakeTwo256, Block as _, Verify}}; -use support::{ +use frame_support::{ Parameter, traits::Get, parameter_types, metadata::{ DecodeDifferent, StorageMetadata, StorageEntryModifier, StorageEntryType, DefaultByteGetter, @@ -25,8 +25,8 @@ use support::{ }, StorageValue, StorageMap, StorageLinkedMap, StorageDoubleMap, }; -use inherents::{ProvideInherent, InherentData, InherentIdentifier, MakeFatalError}; -use primitives::{H256, sr25519}; +use sp_inherents::{ProvideInherent, InherentData, InherentIdentifier, MakeFatalError}; +use sp_core::{H256, sr25519}; mod system; @@ -46,7 +46,7 @@ mod module1 { type GenericType: Default + Clone + codec::Codec + codec::EncodeLike; } - support::decl_module! { + frame_support::decl_module! { pub struct Module, I: InstantiableThing> for enum Call where origin: ::Origin, T::BlockNumber: From @@ -62,7 +62,7 @@ mod module1 { } } - support::decl_storage! { + frame_support::decl_storage! { trait Store for Module, I: InstantiableThing> as Module1 where T::BlockNumber: From + std::fmt::Display { @@ -79,7 +79,7 @@ mod module1 { } } - support::decl_event! { + frame_support::decl_event! { pub enum Event where Phantom = std::marker::PhantomData { _Phantom(Phantom), AnotherVariant(u32), @@ -98,7 +98,7 @@ mod module1 { T::BlockNumber: From { type Call = Call; - type Error = MakeFatalError; + type Error = MakeFatalError; const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER; fn create_inherent(_data: &InherentData) -> Option { @@ -125,7 +125,7 @@ mod module2 { impl, I: Instance> Currency for Module {} - support::decl_module! { + frame_support::decl_module! { pub struct Module, I: Instance=DefaultInstance> for enum Call where origin: ::Origin { @@ -133,7 +133,7 @@ mod module2 { } } - support::decl_storage! { + frame_support::decl_storage! { trait Store for Module, I: Instance=DefaultInstance> as Module2 { pub Value config(value): T::Amount; pub Map config(map): map u64 => u64; @@ -142,7 +142,7 @@ mod module2 { } } - support::decl_event! { + frame_support::decl_event! { pub enum Event where Amount = >::Amount { Variant(Amount), } @@ -158,7 +158,7 @@ mod module2 { impl, I: Instance> ProvideInherent for Module { type Call = Call; - type Error = MakeFatalError; + type Error = MakeFatalError; const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER; fn create_inherent(_data: &InherentData) -> Option { @@ -181,7 +181,7 @@ mod module3 { type Currency2: Currency; } - support::decl_module! { + frame_support::decl_module! { pub struct Module for enum Call where origin: ::Origin {} } } @@ -240,7 +240,7 @@ impl system::Trait for Runtime { type Event = Event; } -support::construct_runtime!( +frame_support::construct_runtime!( pub enum Runtime where Block = Block, NodeBlock = Block, @@ -300,11 +300,11 @@ fn new_test_ext() -> sp_io::TestExternalities { #[test] fn storage_instance_independance() { - let mut storage = primitives::storage::Storage { + let mut storage = sp_core::storage::Storage { top: std::collections::BTreeMap::new(), children: std::collections::HashMap::new() }; - state_machine::BasicExternalities::execute_with_storage(&mut storage, || { + sp_state_machine::BasicExternalities::execute_with_storage(&mut storage, || { module2::Value::::put(0); module2::Value::::put(0); module2::Value::::put(0); diff --git a/substrate/frame/support/test/tests/issue2219.rs b/substrate/frame/support/test/tests/issue2219.rs index c5c7f77935..4c9731b498 100644 --- a/substrate/frame/support/test/tests/issue2219.rs +++ b/substrate/frame/support/test/tests/issue2219.rs @@ -14,10 +14,10 @@ // You should have received a copy of the GNU General Public License // along with Substrate. If not, see . -use support::sp_runtime::generic; -use support::sp_runtime::traits::{BlakeTwo256, Block as _, Verify}; -use support::codec::{Encode, Decode}; -use primitives::{H256, sr25519}; +use frame_support::sp_runtime::generic; +use frame_support::sp_runtime::traits::{BlakeTwo256, Block as _, Verify}; +use frame_support::codec::{Encode, Decode}; +use sp_core::{H256, sr25519}; use serde::{Serialize, Deserialize}; mod system; @@ -82,7 +82,7 @@ mod module { pub trait Trait: system::Trait {} - support::decl_module! { + frame_support::decl_module! { pub struct Module for enum Call where origin: T::Origin {} } @@ -99,7 +99,7 @@ mod module { } } - support::decl_storage! { + frame_support::decl_storage! { trait Store for Module as Actors { /// requirements to enter and maintain status in roles pub Parameters get(fn parameters) build(|config: &GenesisConfig| { @@ -164,7 +164,7 @@ impl system::Trait for Runtime { impl module::Trait for Runtime {} -support::construct_runtime!( +frame_support::construct_runtime!( pub enum Runtime where Block = Block, NodeBlock = Block, diff --git a/substrate/frame/support/test/tests/reserved_keyword/on_initialize.rs b/substrate/frame/support/test/tests/reserved_keyword/on_initialize.rs index 80ee52a982..9a7ffcf067 100644 --- a/substrate/frame/support/test/tests/reserved_keyword/on_initialize.rs +++ b/substrate/frame/support/test/tests/reserved_keyword/on_initialize.rs @@ -2,7 +2,7 @@ macro_rules! reserved { ($($reserved:ident)*) => { $( mod $reserved { - pub use support::dispatch; + pub use frame_support::dispatch; pub trait Trait { type Origin; @@ -10,14 +10,14 @@ macro_rules! reserved { } pub mod system { - use support::dispatch; + use frame_support::dispatch; pub fn ensure_root(_: R) -> dispatch::Result { Ok(()) } } - support::decl_module! { + frame_support::decl_module! { pub struct Module for enum Call where origin: T::Origin { fn $reserved(_origin) -> dispatch::Result { unreachable!() } } diff --git a/substrate/frame/support/test/tests/system.rs b/substrate/frame/support/test/tests/system.rs index fe977392dd..e7da24bbab 100644 --- a/substrate/frame/support/test/tests/system.rs +++ b/substrate/frame/support/test/tests/system.rs @@ -1,4 +1,4 @@ -use support::codec::{Encode, Decode, EncodeLike}; +use frame_support::codec::{Encode, Decode, EncodeLike}; pub trait Trait: 'static + Eq + Clone { type Origin: Into, Self::Origin>> @@ -10,7 +10,7 @@ pub trait Trait: 'static + Eq + Clone { type Event: From; } -support::decl_module! { +frame_support::decl_module! { pub struct Module for enum Call where origin: T::Origin { } } @@ -20,14 +20,14 @@ impl Module { } } -support::decl_event!( +frame_support::decl_event!( pub enum Event { ExtrinsicSuccess, ExtrinsicFailed, } ); -support::decl_error! { +frame_support::decl_error! { pub enum Error { /// Test error documentation TestError, diff --git a/substrate/frame/system/Cargo.toml b/substrate/frame/system/Cargo.toml index 78c8884e42..1bd0f60d51 100644 --- a/substrate/frame/system/Cargo.toml +++ b/substrate/frame/system/Cargo.toml @@ -8,12 +8,12 @@ edition = "2018" serde = { version = "1.0.101", optional = true, features = ["derive"] } safe-mix = { version = "1.0.0", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } -primitives = { package = "sp-core", path = "../../primitives/core", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false } sp-std = { path = "../../primitives/std", default-features = false } sp-io ={ path = "../../primitives/io", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } sp-version = { path = "../../primitives/version", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } +frame-support = { path = "../support", default-features = false } impl-trait-for-tuples = "0.1.3" [dev-dependencies] @@ -25,10 +25,10 @@ std = [ "serde", "safe-mix/std", "codec/std", - "primitives/std", + "sp-core/std", "sp-std/std", "sp-io/std", - "support/std", + "frame-support/std", "sp-runtime/std", "sp-version/std", ] diff --git a/substrate/frame/system/benches/bench.rs b/substrate/frame/system/benches/bench.rs index 731cadb579..5102c56adf 100644 --- a/substrate/frame/system/benches/bench.rs +++ b/substrate/frame/system/benches/bench.rs @@ -16,8 +16,8 @@ use criterion::{Criterion, criterion_group, criterion_main, black_box}; use frame_system as system; -use support::{decl_module, decl_event, impl_outer_origin, impl_outer_event, weights::Weight}; -use primitives::H256; +use frame_support::{decl_module, decl_event, impl_outer_origin, impl_outer_event, weights::Weight}; +use sp_core::H256; use sp_runtime::{Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header}; mod module { @@ -50,7 +50,7 @@ impl_outer_event! { } } -support::parameter_types! { +frame_support::parameter_types! { pub const BlockHashCount: u64 = 250; pub const MaximumBlockWeight: Weight = 4 * 1024 * 1024; pub const MaximumBlockLength: u32 = 4 * 1024 * 1024; diff --git a/substrate/frame/system/src/lib.rs b/substrate/frame/system/src/lib.rs index b8786e59a5..cf008101ed 100644 --- a/substrate/frame/system/src/lib.rs +++ b/substrate/frame/system/src/lib.rs @@ -68,7 +68,7 @@ //! ### Example - Get extrinsic count and parent hash for the current block //! //! ``` -//! use support::{decl_module, dispatch}; +//! use frame_support::{decl_module, dispatch}; //! use frame_system::{self as system, ensure_signed}; //! //! pub trait Trait: system::Trait {} @@ -110,8 +110,8 @@ use sp_runtime::{ }, }; -use primitives::storage::well_known_keys; -use support::{ +use sp_core::storage::well_known_keys; +use frame_support::{ decl_module, decl_event, decl_storage, decl_error, storage, Parameter, traits::{Contains, Get}, weights::{Weight, DispatchInfo, DispatchClass, SimpleDispatchInfo}, @@ -122,7 +122,7 @@ use codec::{Encode, Decode}; use sp_io::TestExternalities; #[cfg(any(feature = "std", test))] -use primitives::ChangesTrieConfiguration; +use sp_core::ChangesTrieConfiguration; pub mod offchain; @@ -416,7 +416,7 @@ decl_storage! { } add_extra_genesis { config(changes_trie_config): Option; - #[serde(with = "primitives::bytes")] + #[serde(with = "sp_core::bytes")] config(code): Vec; build(|config: &GenesisConfig| { @@ -703,7 +703,7 @@ impl Module { /// Get the basic externalities for this module, useful for tests. #[cfg(any(feature = "std", test))] pub fn externalities() -> TestExternalities { - TestExternalities::new(primitives::storage::Storage { + TestExternalities::new(sp_core::storage::Storage { top: map![ >::hashed_key_for(T::BlockNumber::zero()) => [69u8; 32].encode(), >::hashed_key().to_vec() => T::BlockNumber::one().encode(), @@ -1141,9 +1141,9 @@ impl Lookup for ChainContext { #[cfg(test)] mod tests { use super::*; - use primitives::H256; + use sp_core::H256; use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, testing::Header, DispatchError}; - use support::{impl_outer_origin, parameter_types}; + use frame_support::{impl_outer_origin, parameter_types}; impl_outer_origin! { pub enum Origin for Test where system = super {} diff --git a/substrate/frame/timestamp/Cargo.toml b/substrate/frame/timestamp/Cargo.toml index ab2e40d021..675efe37b0 100644 --- a/substrate/frame/timestamp/Cargo.toml +++ b/substrate/frame/timestamp/Cargo.toml @@ -9,25 +9,25 @@ serde = { version = "1.0.101", optional = true } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } sp-std = { path = "../../primitives/std", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } -inherents = { package = "sp-inherents", path = "../../primitives/inherents", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } +sp-inherents = { path = "../../primitives/inherents", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } sp-timestamp = { path = "../../primitives/timestamp", default-features = false } impl-trait-for-tuples = "0.1.3" [dev-dependencies] sp-io ={ path = "../../primitives/io" } -primitives = { package = "sp-core", path = "../../primitives/core" } +sp-core = { path = "../../primitives/core" } [features] default = ["std"] std = [ - "inherents/std", + "sp-inherents/std", "codec/std", "sp-std/std", "sp-runtime/std", - "support/std", + "frame-support/std", "serde", - "system/std", + "frame-system/std", "sp-timestamp/std" ] diff --git a/substrate/frame/timestamp/src/lib.rs b/substrate/frame/timestamp/src/lib.rs index 90c9f9ef6c..f15c0ed627 100644 --- a/substrate/frame/timestamp/src/lib.rs +++ b/substrate/frame/timestamp/src/lib.rs @@ -61,9 +61,9 @@ //! ### Get current timestamp //! //! ``` -//! use support::{decl_module, dispatch}; +//! use frame_support::{decl_module, dispatch}; //! # use pallet_timestamp as timestamp; -//! use system::ensure_signed; +//! use frame_system::{self as system, ensure_signed}; //! //! pub trait Trait: timestamp::Trait {} //! @@ -91,24 +91,24 @@ #![cfg_attr(not(feature = "std"), no_std)] use sp_std::{result, cmp}; -use inherents::{ProvideInherent, InherentData, InherentIdentifier}; -use support::{Parameter, decl_storage, decl_module}; -use support::traits::{Time, Get}; +use sp_inherents::{ProvideInherent, InherentData, InherentIdentifier}; +use frame_support::{Parameter, decl_storage, decl_module}; +use frame_support::traits::{Time, Get}; use sp_runtime::{ RuntimeString, traits::{ SimpleArithmetic, Zero, SaturatedConversion, Scale } }; -use support::weights::SimpleDispatchInfo; -use system::ensure_none; +use frame_support::weights::SimpleDispatchInfo; +use frame_system::ensure_none; use sp_timestamp::{ InherentError, INHERENT_IDENTIFIER, InherentType, OnTimestampSet, }; /// The module configuration trait -pub trait Trait: system::Trait { +pub trait Trait: frame_system::Trait { /// Type used for expressing timestamp. type Moment: Parameter + Default + SimpleArithmetic + Scale + Copy; @@ -240,13 +240,13 @@ impl Time for Module { mod tests { use super::*; - use support::{impl_outer_origin, assert_ok, parameter_types, weights::Weight}; + use frame_support::{impl_outer_origin, assert_ok, parameter_types, weights::Weight}; use sp_io::TestExternalities; - use primitives::H256; + use sp_core::H256; use sp_runtime::{Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header}; impl_outer_origin! { - pub enum Origin for Test {} + pub enum Origin for Test where system = frame_system {} } #[derive(Clone, Eq, PartialEq)] @@ -257,7 +257,7 @@ mod tests { pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } - impl system::Trait for Test { + impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -286,7 +286,7 @@ mod tests { #[test] fn timestamp_works() { - let t = system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); TestExternalities::new(t).execute_with(|| { Timestamp::set_timestamp(42); assert_ok!(Timestamp::dispatch(Call::set(69), Origin::NONE)); @@ -297,7 +297,7 @@ mod tests { #[test] #[should_panic(expected = "Timestamp must be updated only once in the block")] fn double_timestamp_should_fail() { - let t = system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); TestExternalities::new(t).execute_with(|| { Timestamp::set_timestamp(42); assert_ok!(Timestamp::dispatch(Call::set(69), Origin::NONE)); @@ -308,7 +308,7 @@ mod tests { #[test] #[should_panic(expected = "Timestamp must increment by at least between sequential blocks")] fn block_period_minimum_enforced() { - let t = system::GenesisConfig::default().build_storage::().unwrap(); + let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); TestExternalities::new(t).execute_with(|| { Timestamp::set_timestamp(42); let _ = Timestamp::dispatch(Call::set(46), Origin::NONE); diff --git a/substrate/frame/transaction-payment/Cargo.toml b/substrate/frame/transaction-payment/Cargo.toml index e8c163fb34..379dfc8d65 100644 --- a/substrate/frame/transaction-payment/Cargo.toml +++ b/substrate/frame/transaction-payment/Cargo.toml @@ -8,14 +8,14 @@ edition = "2018" codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } sp-std = { path = "../../primitives/std", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } -transaction-payment-rpc-runtime-api = { package = "pallet-transaction-payment-rpc-runtime-api", path = "./rpc/runtime-api", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } +pallet-transaction-payment-rpc-runtime-api = { path = "./rpc/runtime-api", default-features = false } [dev-dependencies] sp-io = { path = "../../primitives/io" } -primitives = { package = "sp-core", path = "../../primitives/core" } -balances = { package = "pallet-balances", path = "../balances" } +sp-core = { path = "../../primitives/core" } +pallet-balances = { path = "../balances" } [features] default = ["std"] @@ -23,7 +23,7 @@ std = [ "codec/std", "sp-std/std", "sp-runtime/std", - "support/std", - "system/std", - "transaction-payment-rpc-runtime-api/std" + "frame-support/std", + "frame-system/std", + "pallet-transaction-payment-rpc-runtime-api/std" ] diff --git a/substrate/frame/transaction-payment/rpc/Cargo.toml b/substrate/frame/transaction-payment/rpc/Cargo.toml index 71817ab05e..087333e80e 100644 --- a/substrate/frame/transaction-payment/rpc/Cargo.toml +++ b/substrate/frame/transaction-payment/rpc/Cargo.toml @@ -9,8 +9,8 @@ codec = { package = "parity-scale-codec", version = "1.0.0" } jsonrpc-core = "14.0.3" jsonrpc-core-client = "14.0.3" jsonrpc-derive = "14.0.3" -primitives = { package = "sp-core", path = "../../../primitives/core" } -rpc-primitives = { package = "sp-rpc", path = "../../../primitives/rpc" } +sp-core = { path = "../../../primitives/core" } +sp-rpc = { path = "../../../primitives/rpc" } serde = { version = "1.0.101", features = ["derive"] } sp-runtime = { path = "../../../primitives/runtime" } sp-blockchain = { path = "../../../primitives/blockchain" } diff --git a/substrate/frame/transaction-payment/rpc/runtime-api/Cargo.toml b/substrate/frame/transaction-payment/rpc/runtime-api/Cargo.toml index 076bd2afc7..b5f8c8e876 100644 --- a/substrate/frame/transaction-payment/rpc/runtime-api/Cargo.toml +++ b/substrate/frame/transaction-payment/rpc/runtime-api/Cargo.toml @@ -10,7 +10,7 @@ sp-api = { path = "../../../../primitives/api", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.6", default-features = false, features = ["derive"] } sp-std = { path = "../../../../primitives/std", default-features = false } sp-runtime = { path = "../../../../primitives/runtime", default-features = false } -support = { package = "frame-support", path = "../../../support", default-features = false } +frame-support = { path = "../../../support", default-features = false } [dev-dependencies] serde_json = "1.0.41" @@ -23,5 +23,5 @@ std = [ "codec/std", "sp-std/std", "sp-runtime/std", - "support/std", + "frame-support/std", ] diff --git a/substrate/frame/transaction-payment/rpc/runtime-api/src/lib.rs b/substrate/frame/transaction-payment/rpc/runtime-api/src/lib.rs index 8de2e847ac..ea2b7c2677 100644 --- a/substrate/frame/transaction-payment/rpc/runtime-api/src/lib.rs +++ b/substrate/frame/transaction-payment/rpc/runtime-api/src/lib.rs @@ -19,7 +19,7 @@ #![cfg_attr(not(feature = "std"), no_std)] use sp_std::prelude::*; -use support::weights::{Weight, DispatchClass}; +use frame_support::weights::{Weight, DispatchClass}; use codec::{Encode, Codec, Decode}; #[cfg(feature = "std")] use serde::{Serialize, Deserialize}; diff --git a/substrate/frame/transaction-payment/rpc/src/lib.rs b/substrate/frame/transaction-payment/rpc/src/lib.rs index 63a6b1827b..e7f4638113 100644 --- a/substrate/frame/transaction-payment/rpc/src/lib.rs +++ b/substrate/frame/transaction-payment/rpc/src/lib.rs @@ -25,7 +25,7 @@ use sp_runtime::{ generic::BlockId, traits::{Block as BlockT, ProvideRuntimeApi, UniqueSaturatedInto}, }; -use primitives::Bytes; +use sp_core::Bytes; use pallet_transaction_payment_rpc_runtime_api::CappedDispatchInfo; pub use pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi as TransactionPaymentRuntimeApi; pub use self::gen_client::Client as TransactionPaymentClient; diff --git a/substrate/frame/transaction-payment/src/lib.rs b/substrate/frame/transaction-payment/src/lib.rs index 6f35f79f14..562e7fe21f 100644 --- a/substrate/frame/transaction-payment/src/lib.rs +++ b/substrate/frame/transaction-payment/src/lib.rs @@ -33,7 +33,7 @@ use sp_std::prelude::*; use codec::{Encode, Decode}; -use support::{ +use frame_support::{ decl_storage, decl_module, traits::{Currency, Get, OnUnbalanced, ExistenceRequirement, WithdrawReason}, weights::{Weight, DispatchInfo, GetDispatchInfo}, @@ -46,15 +46,15 @@ use sp_runtime::{ }, traits::{Zero, Saturating, SignedExtension, SaturatedConversion, Convert}, }; -use transaction_payment_rpc_runtime_api::RuntimeDispatchInfo; +use pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo; type Multiplier = Fixed64; type BalanceOf = - <::Currency as Currency<::AccountId>>::Balance; + <::Currency as Currency<::AccountId>>::Balance; type NegativeImbalanceOf = - <::Currency as Currency<::AccountId>>::NegativeImbalance; + <::Currency as Currency<::AccountId>>::NegativeImbalance; -pub trait Trait: system::Trait { +pub trait Trait: frame_system::Trait { /// The currency type in which fees will be paid. type Currency: Currency + Send + Sync; @@ -163,7 +163,7 @@ impl ChargeTransactionPayment { let weight_fee = { // cap the weight to the maximum defined in runtime, otherwise it will be the `Bounded` // maximum of its data type, which is not desired. - let capped_weight = info.weight.min(::MaximumBlockWeight::get()); + let capped_weight = info.weight.min(::MaximumBlockWeight::get()); T::WeightToFee::convert(capped_weight) }; @@ -237,32 +237,33 @@ impl SignedExtension for ChargeTransactionPayment mod tests { use super::*; use codec::Encode; - use support::{ + use frame_support::{ parameter_types, impl_outer_origin, impl_outer_dispatch, weights::{DispatchClass, DispatchInfo, GetDispatchInfo, Weight}, }; - use primitives::H256; + use sp_core::H256; use sp_runtime::{ Perbill, testing::{Header, TestXt}, traits::{BlakeTwo256, IdentityLookup, Extrinsic}, }; - use balances::Call as BalancesCall; + use pallet_balances::Call as BalancesCall; use sp_std::cell::RefCell; - use transaction_payment_rpc_runtime_api::RuntimeDispatchInfo; + use pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo; - const CALL: &::Call = &Call::Balances(BalancesCall::transfer(2, 69)); + const CALL: &::Call = &Call::Balances(BalancesCall::transfer(2, 69)); impl_outer_dispatch! { pub enum Call for Runtime where origin: Origin { - balances::Balances, - system::System, + pallet_balances::Balances, + frame_system::System, } } #[derive(Clone, PartialEq, Eq, Debug)] pub struct Runtime; + use frame_system as system; impl_outer_origin!{ pub enum Origin for Runtime {} } @@ -274,7 +275,7 @@ mod tests { pub const AvailableBlockRatio: Perbill = Perbill::one(); } - impl system::Trait for Runtime { + impl frame_system::Trait for Runtime { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -298,7 +299,7 @@ mod tests { pub const ExistentialDeposit: u64 = 0; } - impl balances::Trait for Runtime { + impl pallet_balances::Trait for Runtime { type Balance = u64; type OnFreeBalanceZero = (); type OnNewAccount = (); @@ -334,7 +335,7 @@ mod tests { } impl Trait for Runtime { - type Currency = balances::Module; + type Currency = pallet_balances::Module; type OnTransactionPayment = (); type TransactionBaseFee = TransactionBaseFee; type TransactionByteFee = TransactionByteFee; @@ -342,8 +343,8 @@ mod tests { type FeeMultiplierUpdate = (); } - type Balances = balances::Module; - type System = system::Module; + type Balances = pallet_balances::Module; + type System = frame_system::Module; type TransactionPayment = Module; pub struct ExtBuilder { @@ -382,8 +383,8 @@ mod tests { } pub fn build(self) -> sp_io::TestExternalities { self.set_constants(); - let mut t = system::GenesisConfig::default().build_storage::().unwrap(); - balances::GenesisConfig:: { + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + pallet_balances::GenesisConfig:: { balances: vec![ (1, 10 * self.balance_factor), (2, 20 * self.balance_factor), @@ -445,7 +446,7 @@ mod tests { // fee will be proportional to what is the actual maximum weight in the runtime. assert_eq!( Balances::free_balance(&1), - (10000 - ::MaximumBlockWeight::get()) as u64 + (10000 - ::MaximumBlockWeight::get()) as u64 ); }); } diff --git a/substrate/frame/treasury/Cargo.toml b/substrate/frame/treasury/Cargo.toml index 0f588e910e..bd79b4d038 100644 --- a/substrate/frame/treasury/Cargo.toml +++ b/substrate/frame/treasury/Cargo.toml @@ -9,13 +9,13 @@ serde = { version = "1.0.101", optional = true, features = ["derive"] } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } sp-std = { path = "../../primitives/std", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } -balances = { package = "pallet-balances", path = "../balances", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } +pallet-balances = { path = "../balances", default-features = false } [dev-dependencies] sp-io ={ path = "../../primitives/io" } -primitives = { package = "sp-core", path = "../../primitives/core" } +sp-core = { path = "../../primitives/core" } [features] default = ["std"] @@ -24,7 +24,7 @@ std = [ "codec/std", "sp-std/std", "sp-runtime/std", - "support/std", - "system/std", - "balances/std", + "frame-support/std", + "frame-system/std", + "pallet-balances/std", ] diff --git a/substrate/frame/treasury/src/lib.rs b/substrate/frame/treasury/src/lib.rs index 92749d5eee..210761d87e 100644 --- a/substrate/frame/treasury/src/lib.rs +++ b/substrate/frame/treasury/src/lib.rs @@ -60,8 +60,8 @@ #[cfg(feature = "std")] use serde::{Serialize, Deserialize}; use sp_std::prelude::*; -use support::{decl_module, decl_storage, decl_event, ensure, print}; -use support::traits::{ +use frame_support::{decl_module, decl_storage, decl_event, ensure, print}; +use frame_support::traits::{ Currency, ExistenceRequirement, Get, Imbalance, OnUnbalanced, ReservableCurrency, WithdrawReason }; @@ -69,17 +69,17 @@ use sp_runtime::{Permill, ModuleId}; use sp_runtime::traits::{ Zero, EnsureOrigin, StaticLookup, AccountIdConversion, Saturating }; -use support::weights::SimpleDispatchInfo; +use frame_support::weights::SimpleDispatchInfo; use codec::{Encode, Decode}; -use system::ensure_signed; +use frame_system::{self as system, ensure_signed}; -type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; -type PositiveImbalanceOf = <::Currency as Currency<::AccountId>>::PositiveImbalance; -type NegativeImbalanceOf = <::Currency as Currency<::AccountId>>::NegativeImbalance; +type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; +type PositiveImbalanceOf = <::Currency as Currency<::AccountId>>::PositiveImbalance; +type NegativeImbalanceOf = <::Currency as Currency<::AccountId>>::NegativeImbalance; const MODULE_ID: ModuleId = ModuleId(*b"py/trsry"); -pub trait Trait: system::Trait { +pub trait Trait: frame_system::Trait { /// The staking balance. type Currency: Currency + ReservableCurrency; @@ -90,7 +90,7 @@ pub trait Trait: system::Trait { type RejectOrigin: EnsureOrigin; /// The overarching event type. - type Event: From> + Into<::Event>; + type Event: From> + Into<::Event>; /// Handler for the unbalanced decrease when slashing for a rejected proposal. type ProposalRejection: OnUnbalanced>; @@ -235,7 +235,7 @@ decl_event!( pub enum Event where Balance = BalanceOf, - ::AccountId + ::AccountId { /// New proposal. Proposed(ProposalIndex), @@ -351,14 +351,14 @@ impl OnUnbalanced> for Module { mod tests { use super::*; - use support::{assert_noop, assert_ok, impl_outer_origin, parameter_types, weights::Weight}; - use primitives::H256; + use frame_support::{assert_noop, assert_ok, impl_outer_origin, parameter_types, weights::Weight}; + use sp_core::H256; use sp_runtime::{ traits::{BlakeTwo256, OnFinalize, IdentityLookup}, testing::Header, Perbill }; impl_outer_origin! { - pub enum Origin for Test {} + pub enum Origin for Test where system = frame_system {} } #[derive(Clone, Eq, PartialEq)] @@ -369,7 +369,7 @@ mod tests { pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } - impl system::Trait for Test { + impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -391,7 +391,7 @@ mod tests { pub const TransferFee: u64 = 0; pub const CreationFee: u64 = 0; } - impl balances::Trait for Test { + impl pallet_balances::Trait for Test { type Balance = u64; type OnNewAccount = (); type OnFreeBalanceZero = (); @@ -409,9 +409,9 @@ mod tests { pub const Burn: Permill = Permill::from_percent(50); } impl Trait for Test { - type Currency = balances::Module; - type ApproveOrigin = system::EnsureRoot; - type RejectOrigin = system::EnsureRoot; + type Currency = pallet_balances::Module; + type ApproveOrigin = frame_system::EnsureRoot; + type RejectOrigin = frame_system::EnsureRoot; type Event = (); type ProposalRejection = (); type ProposalBond = ProposalBond; @@ -419,12 +419,12 @@ mod tests { type SpendPeriod = SpendPeriod; type Burn = Burn; } - type Balances = balances::Module; + type Balances = pallet_balances::Module; type Treasury = Module; fn new_test_ext() -> sp_io::TestExternalities { - let mut t = system::GenesisConfig::default().build_storage::().unwrap(); - balances::GenesisConfig::{ + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + pallet_balances::GenesisConfig::{ // Total issuance will be 200 with treasury account initialized at ED. balances: vec![(0, 100), (1, 98), (2, 1)], vesting: vec![], @@ -614,8 +614,8 @@ mod tests { // This is usefull for chain that will just update runtime. #[test] fn inexisting_account_works() { - let mut t = system::GenesisConfig::default().build_storage::().unwrap(); - balances::GenesisConfig::{ + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + pallet_balances::GenesisConfig::{ balances: vec![(0, 100), (1, 99), (2, 1)], vesting: vec![], }.assimilate_storage(&mut t).unwrap(); diff --git a/substrate/frame/utility/Cargo.toml b/substrate/frame/utility/Cargo.toml index 3341fd50ec..e4bcd1f84b 100644 --- a/substrate/frame/utility/Cargo.toml +++ b/substrate/frame/utility/Cargo.toml @@ -7,15 +7,15 @@ edition = "2018" [dependencies] serde = { version = "1.0.101", optional = true } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false } -support = { package = "frame-support", path = "../support", default-features = false } -system = { package = "frame-system", path = "../system", default-features = false } +frame-support = { path = "../support", default-features = false } +frame-system = { path = "../system", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } sp-std = { path = "../../primitives/std", default-features = false } sp-io = { path = "../../primitives/io", default-features = false } [dev-dependencies] -primitives = { package = "sp-core", path = "../../primitives/core" } -balances = { package = "pallet-balances", path = "../balances" } +sp-core = { path = "../../primitives/core" } +pallet-balances = { path = "../balances" } [features] default = ["std"] @@ -23,8 +23,8 @@ std = [ "serde", "codec/std", "sp-runtime/std", - "support/std", - "system/std", + "frame-support/std", + "frame-system/std", "sp-io/std", "sp-std/std" ] diff --git a/substrate/frame/utility/src/lib.rs b/substrate/frame/utility/src/lib.rs index 7639d0c77a..c5400b891e 100644 --- a/substrate/frame/utility/src/lib.rs +++ b/substrate/frame/utility/src/lib.rs @@ -21,14 +21,14 @@ #![cfg_attr(not(feature = "std"), no_std)] use sp_std::prelude::*; -use support::{decl_module, decl_event, Parameter, weights::SimpleDispatchInfo}; -use system::ensure_root; +use frame_support::{decl_module, decl_event, Parameter, weights::SimpleDispatchInfo}; +use frame_system::{self as system, ensure_root}; use sp_runtime::{traits::Dispatchable, DispatchError}; /// Configuration trait. -pub trait Trait: system::Trait { +pub trait Trait: frame_system::Trait { /// The overarching event type. - type Event: From + Into<::Event>; + type Event: From + Into<::Event>; /// The overarching call type. type Call: Parameter + Dispatchable; @@ -51,7 +51,7 @@ decl_module! { fn batch(origin, calls: Vec<::Call>) { ensure_root(origin)?; let results = calls.into_iter() - .map(|call| call.dispatch(system::RawOrigin::Root.into())) + .map(|call| call.dispatch(frame_system::RawOrigin::Root.into())) .map(|res| res.map_err(Into::into)) .collect::>(); Self::deposit_event(Event::BatchExecuted(results)); @@ -63,20 +63,20 @@ decl_module! { mod tests { use super::*; - use support::{ + use frame_support::{ assert_ok, assert_noop, impl_outer_origin, parameter_types, impl_outer_dispatch, weights::Weight }; - use primitives::H256; + use sp_core::H256; use sp_runtime::{Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header}; impl_outer_origin! { - pub enum Origin for Test {} + pub enum Origin for Test where system = frame_system {} } impl_outer_dispatch! { pub enum Call for Test where origin: Origin { - balances::Balances, + pallet_balances::Balances, utility::Utility, } } @@ -92,7 +92,7 @@ mod tests { pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } - impl system::Trait for Test { + impl frame_system::Trait for Test { type Origin = Origin; type Index = u64; type BlockNumber = u64; @@ -114,7 +114,7 @@ mod tests { pub const TransferFee: u64 = 0; pub const CreationFee: u64 = 0; } - impl balances::Trait for Test { + impl pallet_balances::Trait for Test { type Balance = u64; type OnFreeBalanceZero = (); type OnNewAccount = (); @@ -129,12 +129,12 @@ mod tests { type Event = (); type Call = Call; } - type Balances = balances::Module; + type Balances = pallet_balances::Module; type Utility = Module; fn new_test_ext() -> sp_io::TestExternalities { - let mut t = system::GenesisConfig::default().build_storage::().unwrap(); - balances::GenesisConfig:: { + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + pallet_balances::GenesisConfig:: { balances: vec![(1, 10), (2, 0)], vesting: vec![], }.assimilate_storage(&mut t).unwrap(); @@ -147,12 +147,12 @@ mod tests { assert_eq!(Balances::free_balance(1), 10); assert_eq!(Balances::free_balance(2), 0); assert_noop!(Utility::batch(Origin::signed(1), vec![ - Call::Balances(balances::Call::force_transfer(1, 2, 5)), - Call::Balances(balances::Call::force_transfer(1, 2, 5)) + Call::Balances(pallet_balances::Call::force_transfer(1, 2, 5)), + Call::Balances(pallet_balances::Call::force_transfer(1, 2, 5)) ]), "RequireRootOrigin"); assert_ok!(Utility::batch(Origin::ROOT, vec![ - Call::Balances(balances::Call::force_transfer(1, 2, 5)), - Call::Balances(balances::Call::force_transfer(1, 2, 5)) + Call::Balances(pallet_balances::Call::force_transfer(1, 2, 5)), + Call::Balances(pallet_balances::Call::force_transfer(1, 2, 5)) ])); assert_eq!(Balances::free_balance(1), 0); assert_eq!(Balances::free_balance(2), 10); diff --git a/substrate/primitives/api/Cargo.toml b/substrate/primitives/api/Cargo.toml index ef36a7b47a..0b3a1f2cf9 100644 --- a/substrate/primitives/api/Cargo.toml +++ b/substrate/primitives/api/Cargo.toml @@ -7,11 +7,11 @@ edition = "2018" [dependencies] codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false } sp-api-proc-macro = { path = "proc-macro" } -primitives = { package = "sp-core", path = "../core", default-features = false } +sp-core = { path = "../core", default-features = false } sp-std = { path = "../std", default-features = false } sp-runtime = { path = "../runtime", default-features = false } sp-version = { path = "../version", default-features = false } -state-machine = { package = "sp-state-machine", path = "../../primitives/state-machine", optional = true } +sp-state-machine = { path = "../../primitives/state-machine", optional = true } [dev-dependencies] sp-test-primitives = { path = "../test-primitives" } @@ -20,9 +20,9 @@ sp-test-primitives = { path = "../test-primitives" } default = [ "std" ] std = [ "codec/std", - "primitives/std", + "sp-core/std", "sp-std/std", "sp-runtime/std", - "state-machine", + "sp-state-machine", "sp-version/std", ] diff --git a/substrate/primitives/api/src/lib.rs b/substrate/primitives/api/src/lib.rs index 7d1f91e339..b655cf0939 100644 --- a/substrate/primitives/api/src/lib.rs +++ b/substrate/primitives/api/src/lib.rs @@ -35,13 +35,13 @@ extern crate self as sp_api; #[doc(hidden)] #[cfg(feature = "std")] -pub use state_machine::{OverlayedChanges, StorageProof}; +pub use sp_state_machine::{OverlayedChanges, StorageProof}; #[doc(hidden)] #[cfg(feature = "std")] -pub use primitives::NativeOrEncoded; +pub use sp_core::NativeOrEncoded; #[doc(hidden)] #[cfg(not(feature = "std"))] -pub use primitives::to_substrate_wasm_fn_return_value; +pub use sp_core::to_substrate_wasm_fn_return_value; #[doc(hidden)] pub use sp_runtime::{ traits::{ @@ -51,7 +51,7 @@ pub use sp_runtime::{ generic::BlockId, transaction_validity::TransactionValidity, }; #[doc(hidden)] -pub use primitives::{offchain, ExecutionContext}; +pub use sp_core::{offchain, ExecutionContext}; #[doc(hidden)] pub use sp_version::{ApiId, RuntimeVersion, ApisVec, create_apis_vec}; #[doc(hidden)] @@ -60,7 +60,7 @@ pub use sp_std::{slice, mem}; use sp_std::result; #[doc(hidden)] pub use codec::{Encode, Decode}; -use primitives::OpaqueMetadata; +use sp_core::OpaqueMetadata; #[cfg(feature = "std")] use std::{panic::UnwindSafe, cell::RefCell}; @@ -223,7 +223,7 @@ pub use sp_api_proc_macro::impl_runtime_apis; #[cfg(feature = "std")] /// A type that records all accessed trie nodes and generates a proof out of it. -pub type ProofRecorder = state_machine::ProofRecorder< +pub type ProofRecorder = sp_state_machine::ProofRecorder< <<::Header as HeaderT>::Hashing as HashT>::Hasher >; diff --git a/substrate/primitives/api/test/Cargo.toml b/substrate/primitives/api/test/Cargo.toml index 497790f2d6..8fdfcc98f1 100644 --- a/substrate/primitives/api/test/Cargo.toml +++ b/substrate/primitives/api/test/Cargo.toml @@ -6,19 +6,19 @@ edition = "2018" [dependencies] sp-api = { path = "../" } -test-client = { package = "substrate-test-runtime-client", path = "../../../test-utils/runtime/client" } +substrate-test-runtime-client = { path = "../../../test-utils/runtime/client" } sp-version = { path = "../../version" } sp-runtime = { path = "../../runtime" } sp-blockchain = { path = "../../blockchain" } -consensus_common = { package = "sp-consensus", path = "../../../primitives/consensus/common" } +sp-consensus = { path = "../../../primitives/consensus/common" } codec = { package = "parity-scale-codec", version = "1.0.0" } -state-machine = { package = "sp-state-machine", path = "../../../primitives/state-machine" } +sp-state-machine = { path = "../../../primitives/state-machine" } trybuild = "1.0.17" rustversion = "1.0.0" [dev-dependencies] criterion = "0.3.0" -test-client = { package = "substrate-test-runtime-client", path = "../../../test-utils/runtime/client" } +substrate-test-runtime-client = { path = "../../../test-utils/runtime/client" } [[bench]] name = "bench" diff --git a/substrate/primitives/api/test/benches/bench.rs b/substrate/primitives/api/test/benches/bench.rs index 59bac57f13..9b41834097 100644 --- a/substrate/primitives/api/test/benches/bench.rs +++ b/substrate/primitives/api/test/benches/bench.rs @@ -15,16 +15,16 @@ // along with Substrate. If not, see . use criterion::{Criterion, criterion_group, criterion_main}; -use test_client::{ +use substrate_test_runtime_client::{ DefaultTestClientBuilderExt, TestClientBuilder, TestClientBuilderExt, runtime::TestAPI, }; use sp_runtime::{generic::BlockId, traits::ProvideRuntimeApi}; -use state_machine::ExecutionStrategy; +use sp_state_machine::ExecutionStrategy; fn sp_api_benchmark(c: &mut Criterion) { c.bench_function("add one with same runtime api", |b| { - let client = test_client::new(); + let client = substrate_test_runtime_client::new(); let runtime_api = client.runtime_api(); let block_id = BlockId::Number(client.info().chain.best_number); @@ -32,14 +32,14 @@ fn sp_api_benchmark(c: &mut Criterion) { }); c.bench_function("add one with recreating runtime api", |b| { - let client = test_client::new(); + let client = substrate_test_runtime_client::new(); let block_id = BlockId::Number(client.info().chain.best_number); b.iter(|| client.runtime_api().benchmark_add_one(&block_id, &1)) }); c.bench_function("vector add one with same runtime api", |b| { - let client = test_client::new(); + let client = substrate_test_runtime_client::new(); let runtime_api = client.runtime_api(); let block_id = BlockId::Number(client.info().chain.best_number); let data = vec![0; 1000]; @@ -48,7 +48,7 @@ fn sp_api_benchmark(c: &mut Criterion) { }); c.bench_function("vector add one with recreating runtime api", |b| { - let client = test_client::new(); + let client = substrate_test_runtime_client::new(); let block_id = BlockId::Number(client.info().chain.best_number); let data = vec![0; 1000]; diff --git a/substrate/primitives/api/test/tests/decl_and_impl.rs b/substrate/primitives/api/test/tests/decl_and_impl.rs index d52b5b4070..b25c8c2710 100644 --- a/substrate/primitives/api/test/tests/decl_and_impl.rs +++ b/substrate/primitives/api/test/tests/decl_and_impl.rs @@ -18,7 +18,7 @@ use sp_api::{RuntimeApiInfo, decl_runtime_apis, impl_runtime_apis}; use sp_runtime::{traits::{GetNodeBlockType, Block as BlockT}, generic::BlockId}; -use test_client::runtime::Block; +use substrate_test_runtime_client::runtime::Block; use sp_blockchain::Result; /// The declaration of the `Runtime` type and the implementation of the `GetNodeBlockType` @@ -81,8 +81,11 @@ impl_runtime_apis! { } } -type TestClient = test_client::client::Client< - test_client::Backend, test_client::Executor, Block, RuntimeApi +type TestClient = substrate_test_runtime_client::sc_client::Client< + substrate_test_runtime_client::Backend, + substrate_test_runtime_client::Executor, + Block, + RuntimeApi, >; #[test] diff --git a/substrate/primitives/api/test/tests/runtime_calls.rs b/substrate/primitives/api/test/tests/runtime_calls.rs index 3b09d67a2c..34184c936a 100644 --- a/substrate/primitives/api/test/tests/runtime_calls.rs +++ b/substrate/primitives/api/test/tests/runtime_calls.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Substrate. If not, see . -use test_client::{ +use substrate_test_runtime_client::{ prelude::*, DefaultTestClientBuilderExt, TestClientBuilder, runtime::{TestAPI, DecodeFails, Transfer, Header}, @@ -23,12 +23,12 @@ use sp_runtime::{ generic::BlockId, traits::{ProvideRuntimeApi, Header as HeaderT, Hash as HashT}, }; -use state_machine::{ +use sp_state_machine::{ ExecutionStrategy, create_proof_check_backend, execution_proof_check_on_trie_backend, }; -use consensus_common::SelectChain; +use sp_consensus::SelectChain; use codec::Encode; fn calling_function_with_strat(strat: ExecutionStrategy) { diff --git a/substrate/primitives/api/test/tests/ui/changed_in_unknown_version.rs b/substrate/primitives/api/test/tests/ui/changed_in_unknown_version.rs index 818b504860..151f3e5f4d 100644 --- a/substrate/primitives/api/test/tests/ui/changed_in_unknown_version.rs +++ b/substrate/primitives/api/test/tests/ui/changed_in_unknown_version.rs @@ -1,5 +1,5 @@ use sp_runtime::traits::GetNodeBlockType; -use test_client::runtime::Block; +use substrate_test_runtime_client::runtime::Block; /// The declaration of the `Runtime` type and the implementation of the `GetNodeBlockType` /// trait are done by the `construct_runtime!` macro in a real runtime. diff --git a/substrate/primitives/api/test/tests/ui/empty_impl_runtime_apis_call.rs b/substrate/primitives/api/test/tests/ui/empty_impl_runtime_apis_call.rs index 6275979de2..93343fb72a 100644 --- a/substrate/primitives/api/test/tests/ui/empty_impl_runtime_apis_call.rs +++ b/substrate/primitives/api/test/tests/ui/empty_impl_runtime_apis_call.rs @@ -1,5 +1,5 @@ use sp_runtime::traits::GetNodeBlockType; -use test_client::runtime::Block; +use substrate_test_runtime_client::runtime::Block; /// The declaration of the `Runtime` type and the implementation of the `GetNodeBlockType` /// trait are done by the `construct_runtime!` macro in a real runtime. diff --git a/substrate/primitives/api/test/tests/ui/impl_incorrect_method_signature.rs b/substrate/primitives/api/test/tests/ui/impl_incorrect_method_signature.rs index cdc1dacb6a..e4eba99d9e 100644 --- a/substrate/primitives/api/test/tests/ui/impl_incorrect_method_signature.rs +++ b/substrate/primitives/api/test/tests/ui/impl_incorrect_method_signature.rs @@ -1,5 +1,5 @@ use sp_runtime::traits::{GetNodeBlockType, Block as BlockT}; -use test_client::runtime::Block; +use substrate_test_runtime_client::runtime::Block; /// The declaration of the `Runtime` type and the implementation of the `GetNodeBlockType` /// trait are done by the `construct_runtime!` macro in a real runtime. diff --git a/substrate/primitives/api/test/tests/ui/impl_two_traits_with_same_name.rs b/substrate/primitives/api/test/tests/ui/impl_two_traits_with_same_name.rs index 4c3ee6b27d..9c01dc0e92 100644 --- a/substrate/primitives/api/test/tests/ui/impl_two_traits_with_same_name.rs +++ b/substrate/primitives/api/test/tests/ui/impl_two_traits_with_same_name.rs @@ -1,5 +1,5 @@ use sp_runtime::traits::GetNodeBlockType; -use test_client::runtime::Block; +use substrate_test_runtime_client::runtime::Block; /// The declaration of the `Runtime` type and the implementation of the `GetNodeBlockType` /// trait are done by the `construct_runtime!` macro in a real runtime. diff --git a/substrate/primitives/api/test/tests/ui/missing_block_generic_parameter.rs b/substrate/primitives/api/test/tests/ui/missing_block_generic_parameter.rs index 4639ae328c..e194fdbf4a 100644 --- a/substrate/primitives/api/test/tests/ui/missing_block_generic_parameter.rs +++ b/substrate/primitives/api/test/tests/ui/missing_block_generic_parameter.rs @@ -1,5 +1,5 @@ use sp_runtime::traits::GetNodeBlockType; -use test_client::runtime::Block; +use substrate_test_runtime_client::runtime::Block; /// The declaration of the `Runtime` type and the implementation of the `GetNodeBlockType` /// trait are done by the `construct_runtime!` macro in a real runtime. diff --git a/substrate/primitives/api/test/tests/ui/missing_path_for_trait.rs b/substrate/primitives/api/test/tests/ui/missing_path_for_trait.rs index d90756ce1b..d7540ce88a 100644 --- a/substrate/primitives/api/test/tests/ui/missing_path_for_trait.rs +++ b/substrate/primitives/api/test/tests/ui/missing_path_for_trait.rs @@ -1,5 +1,5 @@ use sp_runtime::traits::GetNodeBlockType; -use test_client::runtime::Block; +use substrate_test_runtime_client::runtime::Block; /// The declaration of the `Runtime` type and the implementation of the `GetNodeBlockType` /// trait are done by the `construct_runtime!` macro in a real runtime. diff --git a/substrate/primitives/api/test/tests/ui/type_reference_in_impl_runtime_apis_call.rs b/substrate/primitives/api/test/tests/ui/type_reference_in_impl_runtime_apis_call.rs index 809444cb30..f45f0844c6 100644 --- a/substrate/primitives/api/test/tests/ui/type_reference_in_impl_runtime_apis_call.rs +++ b/substrate/primitives/api/test/tests/ui/type_reference_in_impl_runtime_apis_call.rs @@ -1,5 +1,5 @@ use sp_runtime::traits::{GetNodeBlockType, Block as BlockT}; -use test_client::runtime::Block; +use substrate_test_runtime_client::runtime::Block; /// The declaration of the `Runtime` type and the implementation of the `GetNodeBlockType` /// trait are done by the `construct_runtime!` macro in a real runtime. diff --git a/substrate/primitives/application-crypto/Cargo.toml b/substrate/primitives/application-crypto/Cargo.toml index 79b3f35f6b..549c0a5891 100644 --- a/substrate/primitives/application-crypto/Cargo.toml +++ b/substrate/primitives/application-crypto/Cargo.toml @@ -6,7 +6,7 @@ edition = "2018" description = "Provides facilities for generating application specific crypto wrapper types." [dependencies] -primitives = { package = "sp-core", path = "../core", default-features = false } +sp-core = { path = "../core", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } serde = { version = "1.0.101", optional = true, features = ["derive"] } sp-std = { path = "../std", default-features = false } @@ -14,11 +14,11 @@ sp-io = { path = "../../primitives/io", default-features = false } [features] default = [ "std" ] -std = [ "full_crypto", "primitives/std", "codec/std", "serde", "sp-std/std", "sp-io/std" ] +std = [ "full_crypto", "sp-core/std", "codec/std", "serde", "sp-std/std", "sp-io/std" ] # This feature enables all crypto primitives for `no_std` builds like microcontrollers # or Intel SGX. # For the regular wasm runtime builds this should not be used. full_crypto = [ - "primitives/full_crypto" + "sp-core/full_crypto" ] diff --git a/substrate/primitives/application-crypto/src/ed25519.rs b/substrate/primitives/application-crypto/src/ed25519.rs index 2ac94ac423..14796a4b55 100644 --- a/substrate/primitives/application-crypto/src/ed25519.rs +++ b/substrate/primitives/application-crypto/src/ed25519.rs @@ -20,10 +20,10 @@ use crate::{RuntimePublic, KeyTypeId}; use sp_std::vec::Vec; -pub use primitives::ed25519::*; +pub use sp_core::ed25519::*; mod app { - use primitives::testing::ED25519; + use sp_core::testing::ED25519; crate::app_crypto!(super, ED25519); impl crate::traits::BoundToRuntimeAppPublic for Public { diff --git a/substrate/primitives/application-crypto/src/lib.rs b/substrate/primitives/application-crypto/src/lib.rs index 12972b4707..0d8df56535 100644 --- a/substrate/primitives/application-crypto/src/lib.rs +++ b/substrate/primitives/application-crypto/src/lib.rs @@ -21,11 +21,11 @@ #![cfg_attr(not(feature = "std"), no_std)] #[doc(hidden)] -pub use primitives::{self, crypto::{CryptoType, Public, Derive, IsWrappedBy, Wraps}, RuntimeDebug}; +pub use sp_core::{self, crypto::{CryptoType, Public, Derive, IsWrappedBy, Wraps}, RuntimeDebug}; #[doc(hidden)] #[cfg(feature = "full_crypto")] -pub use primitives::crypto::{SecretStringError, DeriveJunction, Ss58Codec, Pair}; -pub use primitives::{crypto::{KeyTypeId, key_types}}; +pub use sp_core::crypto::{SecretStringError, DeriveJunction, Ss58Codec, Pair}; +pub use sp_core::{crypto::{KeyTypeId, key_types}}; #[doc(hidden)] pub use codec; diff --git a/substrate/primitives/application-crypto/src/sr25519.rs b/substrate/primitives/application-crypto/src/sr25519.rs index d49fc46cc2..f3d2a84843 100644 --- a/substrate/primitives/application-crypto/src/sr25519.rs +++ b/substrate/primitives/application-crypto/src/sr25519.rs @@ -20,10 +20,10 @@ use crate::{RuntimePublic, KeyTypeId}; use sp_std::vec::Vec; -pub use primitives::sr25519::*; +pub use sp_core::sr25519::*; mod app { - use primitives::testing::SR25519; + use sp_core::testing::SR25519; crate::app_crypto!(super, SR25519); impl crate::traits::BoundToRuntimeAppPublic for Public { diff --git a/substrate/primitives/application-crypto/src/traits.rs b/substrate/primitives/application-crypto/src/traits.rs index 741bbc48c9..917ec3b0e9 100644 --- a/substrate/primitives/application-crypto/src/traits.rs +++ b/substrate/primitives/application-crypto/src/traits.rs @@ -15,10 +15,10 @@ // along with Substrate. If not, see . #[cfg(feature = "full_crypto")] -use primitives::crypto::Pair; +use sp_core::crypto::Pair; use codec::Codec; -use primitives::crypto::{KeyTypeId, CryptoType, IsWrappedBy, Public}; +use sp_core::crypto::{KeyTypeId, CryptoType, IsWrappedBy, Public}; use sp_std::{fmt::Debug, vec::Vec}; /// An application-specific key. diff --git a/substrate/primitives/application-crypto/test/Cargo.toml b/substrate/primitives/application-crypto/test/Cargo.toml index 2a599e9638..85cb5d1163 100644 --- a/substrate/primitives/application-crypto/test/Cargo.toml +++ b/substrate/primitives/application-crypto/test/Cargo.toml @@ -7,6 +7,7 @@ description = "Integration tests for application-crypto" publish = false [dependencies] -primitives = { package = "sp-core", path = "../../core", default-features = false } -test-client = { package = "substrate-test-runtime-client", path = "../../../test-utils/runtime/client" } -sp-runtime = { path = "../../runtime" } \ No newline at end of file +sp-core = { path = "../../core", default-features = false } +substrate-test-runtime-client = { path = "../../../test-utils/runtime/client" } +sp-runtime = { path = "../../runtime" } +sp-application-crypto = { path = "../" } diff --git a/substrate/primitives/application-crypto/test/src/ed25519.rs b/substrate/primitives/application-crypto/test/src/ed25519.rs index 0e66e5b3ff..40f318509e 100644 --- a/substrate/primitives/application-crypto/test/src/ed25519.rs +++ b/substrate/primitives/application-crypto/test/src/ed25519.rs @@ -17,11 +17,12 @@ //! Integration tests for ed25519 use sp_runtime::{generic::BlockId, traits::ProvideRuntimeApi}; -use primitives::{testing::{KeyStore, ED25519}, crypto::Pair}; -use test_client::{ +use sp_core::{testing::{KeyStore, ED25519}, crypto::Pair}; +use substrate_test_runtime_client::{ TestClientBuilder, DefaultTestClientBuilderExt, TestClientBuilderExt, - runtime::{TestAPI, app_crypto::ed25519::{AppPair, AppPublic}}, + runtime::TestAPI, }; +use sp_application_crypto::ed25519::{AppPair, AppPublic}; #[test] fn ed25519_works_in_runtime() { @@ -35,4 +36,4 @@ fn ed25519_works_in_runtime() { .expect("There should be at a `ed25519` key in the keystore for the given public key."); assert!(AppPair::verify(&signature, "ed25519", &AppPublic::from(key_pair.public()))); -} \ No newline at end of file +} diff --git a/substrate/primitives/application-crypto/test/src/sr25519.rs b/substrate/primitives/application-crypto/test/src/sr25519.rs index 50981f4677..f0bc3e09b2 100644 --- a/substrate/primitives/application-crypto/test/src/sr25519.rs +++ b/substrate/primitives/application-crypto/test/src/sr25519.rs @@ -18,11 +18,12 @@ use sp_runtime::{generic::BlockId, traits::ProvideRuntimeApi}; -use primitives::{testing::{KeyStore, SR25519}, crypto::Pair}; -use test_client::{ +use sp_core::{testing::{KeyStore, SR25519}, crypto::Pair}; +use substrate_test_runtime_client::{ TestClientBuilder, DefaultTestClientBuilderExt, TestClientBuilderExt, - runtime::{TestAPI, app_crypto::sr25519::{AppPair, AppPublic}}, + runtime::TestAPI, }; +use sp_application_crypto::sr25519::{AppPair, AppPublic}; #[test] fn sr25519_works_in_runtime() { @@ -36,4 +37,4 @@ fn sr25519_works_in_runtime() { .expect("There should be at a `sr25519` key in the keystore for the given public key."); assert!(AppPair::verify(&signature, "sr25519", &AppPublic::from(key_pair.public()))); -} \ No newline at end of file +} diff --git a/substrate/primitives/authority-discovery/Cargo.toml b/substrate/primitives/authority-discovery/Cargo.toml index aa8fa926ca..241891a48b 100644 --- a/substrate/primitives/authority-discovery/Cargo.toml +++ b/substrate/primitives/authority-discovery/Cargo.toml @@ -6,7 +6,7 @@ description = "Authority discovery primitives" edition = "2018" [dependencies] -app-crypto = { package = "sp-application-crypto", path = "../application-crypto", default-features = false } +sp-application-crypto = { path = "../application-crypto", default-features = false } codec = { package = "parity-scale-codec", default-features = false, version = "1.0.3" } sp-std = { path = "../std", default-features = false } sp-api = { path = "../api", default-features = false } @@ -15,7 +15,7 @@ sp-runtime = { path = "../runtime", default-features = false } [features] default = ["std"] std = [ - "app-crypto/std", + "sp-application-crypto/std", "codec/std", "sp-std/std", "sp-api/std", diff --git a/substrate/primitives/authority-discovery/src/lib.rs b/substrate/primitives/authority-discovery/src/lib.rs index b208727148..41ad384f91 100644 --- a/substrate/primitives/authority-discovery/src/lib.rs +++ b/substrate/primitives/authority-discovery/src/lib.rs @@ -21,7 +21,7 @@ use sp_std::vec::Vec; mod app { - use app_crypto::{app_crypto, key_types::AUTHORITY_DISCOVERY, sr25519}; + use sp_application_crypto::{app_crypto, key_types::AUTHORITY_DISCOVERY, sr25519}; app_crypto!(sr25519, AUTHORITY_DISCOVERY); } diff --git a/substrate/primitives/block-builder/Cargo.toml b/substrate/primitives/block-builder/Cargo.toml index c454a1516d..41bedb2fa5 100644 --- a/substrate/primitives/block-builder/Cargo.toml +++ b/substrate/primitives/block-builder/Cargo.toml @@ -9,14 +9,14 @@ sp-runtime = { path = "../runtime", default-features = false } sp-api = { path = "../api", default-features = false } sp-std = { path = "../std", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.6", default-features = false } -inherents = { package = "sp-inherents", path = "../inherents", default-features = false } +sp-inherents = { path = "../inherents", default-features = false } [features] default = [ "std" ] std = [ "sp-runtime/std", "codec/std", - "inherents/std", + "sp-inherents/std", "sp-api/std", "sp-std/std", ] diff --git a/substrate/primitives/block-builder/src/lib.rs b/substrate/primitives/block-builder/src/lib.rs index 3b0a615ae5..95f187da9a 100644 --- a/substrate/primitives/block-builder/src/lib.rs +++ b/substrate/primitives/block-builder/src/lib.rs @@ -20,7 +20,7 @@ use sp_runtime::{traits::Block as BlockT, ApplyExtrinsicResult}; -use inherents::{InherentData, CheckInherentsResult}; +use sp_inherents::{InherentData, CheckInherentsResult}; /// Definitions for supporting the older version of API: v3 /// diff --git a/substrate/primitives/blockchain/Cargo.toml b/substrate/primitives/blockchain/Cargo.toml index 598af8153e..9326ad6e0b 100644 --- a/substrate/primitives/blockchain/Cargo.toml +++ b/substrate/primitives/blockchain/Cargo.toml @@ -9,8 +9,8 @@ log = "0.4.8" lru = "0.4.0" parking_lot = "0.9.0" derive_more = "0.99.2" -parity-scale-codec = { version = "1.0.0", default-features = false, features = ["derive"] } -sp_consensus = { package = "sp-consensus", path = "../consensus/common" } +codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } +sp-consensus = { path = "../consensus/common" } sp-runtime = { path = "../runtime" } -sp-block-builder-runtime-api = { package = "sp-block-builder", path = "../block-builder" } -sp-state-machine = { package = "sp-state-machine", path = "../state-machine" } +sp-block-builder = { path = "../block-builder" } +sp-state-machine = { path = "../state-machine" } diff --git a/substrate/primitives/blockchain/src/error.rs b/substrate/primitives/blockchain/src/error.rs index 68a916b7d8..ec60533a50 100644 --- a/substrate/primitives/blockchain/src/error.rs +++ b/substrate/primitives/blockchain/src/error.rs @@ -20,10 +20,10 @@ use std::{self, error, result}; use sp_state_machine; use sp_runtime::transaction_validity::TransactionValidityError; #[allow(deprecated)] -use sp_block_builder_runtime_api::compatability_v3; +use sp_block_builder::compatability_v3; use sp_consensus; use derive_more::{Display, From}; -use parity_scale_codec::Error as CodecError; +use codec::Error as CodecError; /// Client Result type alias pub type Result = result::Result; diff --git a/substrate/primitives/consensus/aura/Cargo.toml b/substrate/primitives/consensus/aura/Cargo.toml index 2a46cf015c..c84a943779 100644 --- a/substrate/primitives/consensus/aura/Cargo.toml +++ b/substrate/primitives/consensus/aura/Cargo.toml @@ -6,22 +6,22 @@ description = "Primitives for Aura consensus" edition = "2018" [dependencies] -app-crypto = { package = "sp-application-crypto", path = "../../application-crypto", default-features = false } +sp-application-crypto = { path = "../../application-crypto", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false } sp-std = { path = "../../std", default-features = false } sp-api = { path = "../../api", default-features = false } sp-runtime = { path = "../../runtime", default-features = false } -inherents = { package = "sp-inherents", path = "../../inherents", default-features = false } +sp-inherents = { path = "../../inherents", default-features = false } sp-timestamp = { path = "../../timestamp", default-features = false } [features] default = ["std"] std = [ - "app-crypto/std", + "sp-application-crypto/std", "codec/std", "sp-std/std", "sp-api/std", "sp-runtime/std", - "inherents/std", + "sp-inherents/std", "sp-timestamp/std", ] diff --git a/substrate/primitives/consensus/aura/src/inherents.rs b/substrate/primitives/consensus/aura/src/inherents.rs index 9a7c7c0c5b..566ed6ccc4 100644 --- a/substrate/primitives/consensus/aura/src/inherents.rs +++ b/substrate/primitives/consensus/aura/src/inherents.rs @@ -16,10 +16,10 @@ /// Contains the inherents for the AURA module -use inherents::{InherentIdentifier, InherentData, Error}; +use sp_inherents::{InherentIdentifier, InherentData, Error}; #[cfg(feature = "std")] -use inherents::{InherentDataProviders, ProvideInherentData}; +use sp_inherents::{InherentDataProviders, ProvideInherentData}; /// The Aura inherent identifier. pub const INHERENT_IDENTIFIER: InherentIdentifier = *b"auraslot"; @@ -93,6 +93,6 @@ impl ProvideInherentData for InherentDataProvider { fn error_to_string(&self, error: &[u8]) -> Option { use codec::Decode; - inherents::Error::decode(&mut &error[..]).map(|e| e.into_string()).ok() + sp_inherents::Error::decode(&mut &error[..]).map(|e| e.into_string()).ok() } } diff --git a/substrate/primitives/consensus/aura/src/lib.rs b/substrate/primitives/consensus/aura/src/lib.rs index 1ed1da96ec..770ed47319 100644 --- a/substrate/primitives/consensus/aura/src/lib.rs +++ b/substrate/primitives/consensus/aura/src/lib.rs @@ -26,7 +26,7 @@ pub mod inherents; pub mod sr25519 { mod app_sr25519 { - use app_crypto::{app_crypto, key_types::AURA, sr25519}; + use sp_application_crypto::{app_crypto, key_types::AURA, sr25519}; app_crypto!(sr25519, AURA); } @@ -43,7 +43,7 @@ pub mod sr25519 { pub mod ed25519 { mod app_ed25519 { - use app_crypto::{app_crypto, key_types::AURA, ed25519}; + use sp_application_crypto::{app_crypto, key_types::AURA, ed25519}; app_crypto!(ed25519, AURA); } diff --git a/substrate/primitives/consensus/babe/Cargo.toml b/substrate/primitives/consensus/babe/Cargo.toml index 0889f6f639..f994c69671 100644 --- a/substrate/primitives/consensus/babe/Cargo.toml +++ b/substrate/primitives/consensus/babe/Cargo.toml @@ -6,20 +6,20 @@ description = "Primitives for BABE consensus" edition = "2018" [dependencies] -app-crypto = { package = "sp-application-crypto", path = "../../application-crypto", default-features = false } +sp-application-crypto = { path = "../../application-crypto", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false } sp-std = { path = "../../std", default-features = false } schnorrkel = { version = "0.8.5", features = ["preaudit_deprecated"], optional = true } sp-api = { path = "../../api", default-features = false } sp-consensus = { path = "../common", optional = true } -sp-inherents = { package = "sp-inherents", path = "../../inherents", default-features = false } +sp-inherents = { path = "../../inherents", default-features = false } sp-runtime = { path = "../../runtime", default-features = false } sp-timestamp = { path = "../../timestamp", default-features = false } [features] default = ["std"] std = [ - "app-crypto/std", + "sp-application-crypto/std", "codec/std", "sp-std/std", "schnorrkel", diff --git a/substrate/primitives/consensus/babe/src/lib.rs b/substrate/primitives/consensus/babe/src/lib.rs index 90e8855b57..196f1be1a6 100644 --- a/substrate/primitives/consensus/babe/src/lib.rs +++ b/substrate/primitives/consensus/babe/src/lib.rs @@ -31,7 +31,7 @@ pub use digest::{BabePreDigest, CompatibleDigestItem}; pub use digest::{BABE_VRF_PREFIX, RawBabePreDigest, NextEpochDescriptor}; mod app { - use app_crypto::{app_crypto, key_types::BABE, sr25519}; + use sp_application_crypto::{app_crypto, key_types::BABE, sr25519}; app_crypto!(sr25519, BABE); } diff --git a/substrate/primitives/consensus/common/Cargo.toml b/substrate/primitives/consensus/common/Cargo.toml index 17aec7bca2..9fde4e3df9 100644 --- a/substrate/primitives/consensus/common/Cargo.toml +++ b/substrate/primitives/consensus/common/Cargo.toml @@ -9,12 +9,12 @@ edition = "2018" derive_more = "0.99.2" libp2p = { version = "0.13.0", default-features = false } log = "0.4.8" -primitives = { package = "sp-core", path= "../../core" } -inherents = { package = "sp-inherents", path = "../../inherents" } +sp-core = { path= "../../core" } +sp-inherents = { path = "../../inherents" } futures = { version = "0.3.1", features = ["thread-pool"] } futures-timer = "0.4.0" sp-std = { path = "../../std" } -runtime_version = { package = "sp-version", path = "../../version" } +sp-version = { path = "../../version" } sp-runtime = { path = "../../runtime" } codec = { package = "parity-scale-codec", version = "1.0.0", features = ["derive"] } parking_lot = "0.9.0" diff --git a/substrate/primitives/consensus/common/src/error.rs b/substrate/primitives/consensus/common/src/error.rs index 0455a553cc..29e9a3ee92 100644 --- a/substrate/primitives/consensus/common/src/error.rs +++ b/substrate/primitives/consensus/common/src/error.rs @@ -15,8 +15,8 @@ // along with Substrate. If not, see . //! Error types in Consensus -use runtime_version::RuntimeVersion; -use primitives::ed25519::{Public, Signature}; +use sp_version::RuntimeVersion; +use sp_core::ed25519::{Public, Signature}; use std::error; /// Result type alias. @@ -36,7 +36,7 @@ pub enum Error { FaultyTimer(std::io::Error), /// Error while working with inherent data. #[display(fmt="InherentData error: {}", _0)] - InherentData(inherents::Error), + InherentData(sp_inherents::Error), /// Unable to propose a block. #[display(fmt="Unable to create block proposal.")] CannotPropose, diff --git a/substrate/primitives/consensus/common/src/lib.rs b/substrate/primitives/consensus/common/src/lib.rs index cc5d0105ad..413f541340 100644 --- a/substrate/primitives/consensus/common/src/lib.rs +++ b/substrate/primitives/consensus/common/src/lib.rs @@ -33,7 +33,7 @@ use std::time::Duration; use sp_runtime::{traits::{Block as BlockT, DigestFor}, generic::BlockId}; use futures::prelude::*; -pub use inherents::InherentData; +pub use sp_inherents::InherentData; pub mod block_validation; pub mod offline_tracker; @@ -146,7 +146,7 @@ pub trait CanAuthorWith { } /// Checks if the node can author blocks by using -/// [`NativeVersion::can_author_with`](runtime_version::NativeVersion::can_author_with). +/// [`NativeVersion::can_author_with`](sp_version::NativeVersion::can_author_with). pub struct CanAuthorWithNativeVersion(T); impl CanAuthorWithNativeVersion { @@ -156,7 +156,7 @@ impl CanAuthorWithNativeVersion { } } -impl, Block: BlockT> CanAuthorWith +impl, Block: BlockT> CanAuthorWith for CanAuthorWithNativeVersion { fn can_author_with(&self, at: &BlockId) -> Result<(), String> { diff --git a/substrate/primitives/consensus/pow/Cargo.toml b/substrate/primitives/consensus/pow/Cargo.toml index 0baff76a9b..73efe40ec5 100644 --- a/substrate/primitives/consensus/pow/Cargo.toml +++ b/substrate/primitives/consensus/pow/Cargo.toml @@ -9,7 +9,7 @@ edition = "2018" sp-api = { path = "../../api", default-features = false } sp-std = { path = "../../std", default-features = false } sp-runtime = { path = "../../runtime", default-features = false } -primitives = { package = "sp-core", path = "../../core", default-features = false } +sp-core = { path = "../../core", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } [features] @@ -18,6 +18,6 @@ std = [ "sp-std/std", "sp-api/std", "sp-runtime/std", - "primitives/std", + "sp-core/std", "codec/std", ] diff --git a/substrate/primitives/consensus/pow/src/lib.rs b/substrate/primitives/consensus/pow/src/lib.rs index 005e2f5325..6a1c1179ed 100644 --- a/substrate/primitives/consensus/pow/src/lib.rs +++ b/substrate/primitives/consensus/pow/src/lib.rs @@ -33,7 +33,7 @@ pub trait TotalDifficulty { fn increment(&mut self, other: Self); } -impl TotalDifficulty for primitives::U256 { +impl TotalDifficulty for sp_core::U256 { fn increment(&mut self, other: Self) { let ret = self.saturating_add(other); *self = ret; diff --git a/substrate/primitives/core/Cargo.toml b/substrate/primitives/core/Cargo.toml index bde9d37ee0..d9e4619fa1 100644 --- a/substrate/primitives/core/Cargo.toml +++ b/substrate/primitives/core/Cargo.toml @@ -26,8 +26,8 @@ zeroize = { version = "1.0.0", default-features = false } lazy_static = { version = "1.4.0", default-features = false, optional = true } parking_lot = { version = "0.9.0", optional = true } sp-debug-derive = { version = "2.0.0", path = "../debug-derive" } -externalities = { package = "sp-externalities", path = "../externalities", optional = true } -primitives-storage = { package = "sp-storage", path = "../storage", default-features = false } +sp-externalities = { path = "../externalities", optional = true } +sp-storage = { path = "../storage", default-features = false } # full crypto ed25519-dalek = { version = "1.0.0-pre.3", default-features = false, features = ["u64_backend", "alloc"], optional = true } @@ -39,7 +39,7 @@ sha2 = { version = "0.8.0", default-features = false, optional = true } hex = { version = "0.4", default-features = false, optional = true } twox-hash = { version = "1.5.0", default-features = false, optional = true } -runtime-interface = { package = "sp-runtime-interface", path = "../runtime-interface", default-features = false } +sp-runtime-interface = { path = "../runtime-interface", default-features = false } [dev-dependencies] sp-serializer = { path = "../serializer" } @@ -93,9 +93,9 @@ std = [ "libsecp256k1", "tiny-keccak", "sp-debug-derive/std", - "externalities", - "primitives-storage/std", - "runtime-interface/std", + "sp-externalities", + "sp-storage/std", + "sp-runtime-interface/std", "zeroize/alloc" ] @@ -111,5 +111,5 @@ full_crypto = [ "hex", "sha2", "twox-hash", - "runtime-interface/disable_target_static_assertions", + "sp-runtime-interface/disable_target_static_assertions", ] diff --git a/substrate/primitives/core/benches/bench.rs b/substrate/primitives/core/benches/bench.rs index bac7eb41ca..d03407de5f 100644 --- a/substrate/primitives/core/benches/bench.rs +++ b/substrate/primitives/core/benches/bench.rs @@ -16,11 +16,10 @@ #[macro_use] extern crate criterion; -use sp_core as primitives; use criterion::{Criterion, black_box, Bencher, Fun}; use std::time::Duration; -use primitives::crypto::Pair as _; -use primitives::hashing::{twox_128, blake2_128}; +use sp_core::crypto::Pair as _; +use sp_core::hashing::{twox_128, blake2_128}; const MAX_KEY_SIZE: u32 = 32; @@ -72,7 +71,7 @@ fn bench_ed25519(c: &mut Criterion) { let msg = (0..msg_size) .map(|_| rand::random::()) .collect::>(); - let key = primitives::ed25519::Pair::generate().0; + let key = sp_core::ed25519::Pair::generate().0; b.iter(|| key.sign(&msg)) }, vec![32, 1024, 1024 * 1024]); @@ -80,10 +79,10 @@ fn bench_ed25519(c: &mut Criterion) { let msg = (0..msg_size) .map(|_| rand::random::()) .collect::>(); - let key = primitives::ed25519::Pair::generate().0; + let key = sp_core::ed25519::Pair::generate().0; let sig = key.sign(&msg); let public = key.public(); - b.iter(|| primitives::ed25519::Pair::verify(&sig, &msg, &public)) + b.iter(|| sp_core::ed25519::Pair::verify(&sig, &msg, &public)) }, vec![32, 1024, 1024 * 1024]); } diff --git a/substrate/primitives/core/src/crypto.rs b/substrate/primitives/core/src/crypto.rs index 2f7574bee3..5119203a08 100644 --- a/substrate/primitives/core/src/crypto.rs +++ b/substrate/primitives/core/src/crypto.rs @@ -37,7 +37,7 @@ use base58::{FromBase58, ToBase58}; use zeroize::Zeroize; #[doc(hidden)] pub use sp_std::ops::Deref; -use runtime_interface::pass_by::PassByInner; +use sp_runtime_interface::pass_by::PassByInner; /// The root phrase for our publicly known keys. pub const DEV_PHRASE: &str = "bottom drive obey lake curtain smoke basket hold race lonely fit walk"; diff --git a/substrate/primitives/core/src/ed25519.rs b/substrate/primitives/core/src/ed25519.rs index 0b40ea8bb6..180e3b0ccb 100644 --- a/substrate/primitives/core/src/ed25519.rs +++ b/substrate/primitives/core/src/ed25519.rs @@ -39,7 +39,7 @@ use crate::crypto::Ss58Codec; #[cfg(feature = "std")] use serde::{de, Serializer, Serialize, Deserializer, Deserialize}; use crate::{crypto::{Public as TraitPublic, UncheckedFrom, CryptoType, Derive}}; -use runtime_interface::pass_by::PassByInner; +use sp_runtime_interface::pass_by::PassByInner; use sp_std::ops::Deref; /// A secret seed. It's not called a "secret key" because ring doesn't expose the secret keys diff --git a/substrate/primitives/core/src/lib.rs b/substrate/primitives/core/src/lib.rs index 3241f9b4ff..00343c0e7f 100644 --- a/substrate/primitives/core/src/lib.rs +++ b/substrate/primitives/core/src/lib.rs @@ -84,7 +84,7 @@ pub use hash_db::Hasher; // pub use self::hasher::blake::BlakeHasher; pub use self::hasher::blake2::Blake2Hasher; -pub use primitives_storage as storage; +pub use sp_storage as storage; #[doc(hidden)] pub use sp_std; @@ -236,7 +236,7 @@ pub trait TypeId { /// A log level matching the one from `log` crate. /// /// Used internally by `sp_io::log` method. -#[derive(Encode, Decode, runtime_interface::pass_by::PassByEnum, Copy, Clone)] +#[derive(Encode, Decode, sp_runtime_interface::pass_by::PassByEnum, Copy, Clone)] pub enum LogLevel { /// `Error` log level. Error = 1, diff --git a/substrate/primitives/core/src/offchain/mod.rs b/substrate/primitives/core/src/offchain/mod.rs index 4b7423c253..9c33abb7c1 100644 --- a/substrate/primitives/core/src/offchain/mod.rs +++ b/substrate/primitives/core/src/offchain/mod.rs @@ -19,7 +19,7 @@ use codec::{Encode, Decode}; use sp_std::{prelude::{Vec, Box}, convert::TryFrom}; use crate::RuntimeDebug; -use runtime_interface::pass_by::{PassByCodec, PassByInner, PassByEnum}; +use sp_runtime_interface::pass_by::{PassByCodec, PassByInner, PassByEnum}; pub use crate::crypto::KeyTypeId; @@ -669,7 +669,7 @@ impl Externalities for LimitedExternalities { } #[cfg(feature = "std")] -externalities::decl_extension! { +sp_externalities::decl_extension! { /// The offchain extension that will be registered at the Substrate externalities. pub struct OffchainExt(Box); } @@ -696,7 +696,7 @@ pub trait TransactionPool { } #[cfg(feature = "std")] -externalities::decl_extension! { +sp_externalities::decl_extension! { /// An externalities extension to submit transactions to the pool. pub struct TransactionPoolExt(Box); } diff --git a/substrate/primitives/core/src/sr25519.rs b/substrate/primitives/core/src/sr25519.rs index 05b128d288..c0f71ea83b 100644 --- a/substrate/primitives/core/src/sr25519.rs +++ b/substrate/primitives/core/src/sr25519.rs @@ -48,7 +48,7 @@ use sp_std::ops::Deref; use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; #[cfg(feature = "full_crypto")] use schnorrkel::keys::{MINI_SECRET_KEY_LENGTH, SECRET_KEY_LENGTH}; -use runtime_interface::pass_by::PassByInner; +use sp_runtime_interface::pass_by::PassByInner; // signing context #[cfg(feature = "full_crypto")] diff --git a/substrate/primitives/core/src/traits.rs b/substrate/primitives/core/src/traits.rs index f1b13408d1..2f78c8a708 100644 --- a/substrate/primitives/core/src/traits.rs +++ b/substrate/primitives/core/src/traits.rs @@ -24,7 +24,7 @@ use std::{ sync::Arc, }; -pub use externalities::{Externalities, ExternalitiesExt}; +pub use sp_externalities::{Externalities, ExternalitiesExt}; /// Something that generates, stores and provides access to keys. pub trait BareCryptoStore: Send + Sync { @@ -74,7 +74,7 @@ pub trait BareCryptoStore: Send + Sync { /// A pointer to the key store. pub type BareCryptoStorePtr = Arc>; -externalities::decl_extension! { +sp_externalities::decl_extension! { /// The keystore extension to register/retrieve from the externalities. pub struct KeystoreExt(BareCryptoStorePtr); } diff --git a/substrate/primitives/externalities/Cargo.toml b/substrate/primitives/externalities/Cargo.toml index d64d104baa..e9c826a8fe 100644 --- a/substrate/primitives/externalities/Cargo.toml +++ b/substrate/primitives/externalities/Cargo.toml @@ -6,6 +6,6 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -primitives-storage = { package = "sp-storage", path = "../storage" } +sp-storage = { path = "../storage" } sp-std = { path = "../std" } environmental = { version = "1.0.2" } diff --git a/substrate/primitives/externalities/src/lib.rs b/substrate/primitives/externalities/src/lib.rs index e79d6a2e3d..52be547e25 100644 --- a/substrate/primitives/externalities/src/lib.rs +++ b/substrate/primitives/externalities/src/lib.rs @@ -24,7 +24,7 @@ use std::any::{Any, TypeId}; -use primitives_storage::{ChildStorageKey, ChildInfo}; +use sp_storage::{ChildStorageKey, ChildInfo}; pub use scope_limited::{set_and_run_with_externalities, with_externalities}; pub use extensions::{Extension, Extensions, ExtensionStore}; diff --git a/substrate/primitives/finality-tracker/Cargo.toml b/substrate/primitives/finality-tracker/Cargo.toml index 919fc0bab4..24681bbd1e 100644 --- a/substrate/primitives/finality-tracker/Cargo.toml +++ b/substrate/primitives/finality-tracker/Cargo.toml @@ -6,7 +6,7 @@ edition = "2018" [dependencies] codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false } -inherents = { package = "sp-inherents", path = "../../primitives/inherents", default-features = false } +sp-inherents = { path = "../../primitives/inherents", default-features = false } sp-std = { path = "../../primitives/std", default-features = false } [features] @@ -14,5 +14,5 @@ default = ["std"] std = [ "codec/std", "sp-std/std", - "inherents/std", + "sp-inherents/std", ] diff --git a/substrate/primitives/finality-tracker/src/lib.rs b/substrate/primitives/finality-tracker/src/lib.rs index 7b81a300c4..677be24ef5 100644 --- a/substrate/primitives/finality-tracker/src/lib.rs +++ b/substrate/primitives/finality-tracker/src/lib.rs @@ -18,7 +18,7 @@ #![cfg_attr(not(feature = "std"), no_std)] -use inherents::{InherentIdentifier, InherentData, Error}; +use sp_inherents::{InherentIdentifier, InherentData, Error}; use codec::Decode; #[cfg(feature = "std")] @@ -55,7 +55,7 @@ impl InherentDataProvider { } #[cfg(feature = "std")] -impl inherents::ProvideInherentData for InherentDataProvider +impl sp_inherents::ProvideInherentData for InherentDataProvider where F: Fn() -> Result { fn inherent_identifier(&self) -> &'static InherentIdentifier { diff --git a/substrate/primitives/inherents/Cargo.toml b/substrate/primitives/inherents/Cargo.toml index d8f67031f9..f40cf8c7f5 100644 --- a/substrate/primitives/inherents/Cargo.toml +++ b/substrate/primitives/inherents/Cargo.toml @@ -7,7 +7,7 @@ edition = "2018" [dependencies] parking_lot = { version = "0.9.0", optional = true } sp-std = { path = "../std", default-features = false } -primitives = { package = "sp-core", path = "../core", default-features = false } +sp-core = { path = "../core", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.6", default-features = false, features = ["derive"] } derive_more = { version = "0.99.2", optional = true } @@ -17,6 +17,6 @@ std = [ "parking_lot", "sp-std/std", "codec/std", - "primitives/std", + "sp-core/std", "derive_more", ] diff --git a/substrate/primitives/inherents/src/lib.rs b/substrate/primitives/inherents/src/lib.rs index 8f26a50822..b777b64e5e 100644 --- a/substrate/primitives/inherents/src/lib.rs +++ b/substrate/primitives/inherents/src/lib.rs @@ -64,7 +64,7 @@ impl Error { } /// An error that can occur within the inherent data system. -#[derive(Encode, primitives::RuntimeDebug)] +#[derive(Encode, sp_core::RuntimeDebug)] #[cfg(not(feature = "std"))] pub struct Error(&'static str); diff --git a/substrate/primitives/io/Cargo.toml b/substrate/primitives/io/Cargo.toml index b124ef7843..b72a6adb8c 100644 --- a/substrate/primitives/io/Cargo.toml +++ b/substrate/primitives/io/Cargo.toml @@ -7,27 +7,27 @@ edition = "2018" [dependencies] codec = { package = "parity-scale-codec", version = "1.0.6", default-features = false } hash-db = { version = "0.15.2", default-features = false } -primitives = { package = "sp-core", path = "../core", default-features = false } +sp-core = { path = "../core", default-features = false } sp-std = { path = "../std", default-features = false } libsecp256k1 = { version = "0.3.0", optional = true } sp-state-machine = { path = "../../primitives/state-machine", optional = true } -runtime-interface = { package = "sp-runtime-interface", path = "../runtime-interface", default-features = false } -trie = { package = "sp-trie", path = "../../primitives/trie", optional = true } -externalities = { package = "sp-externalities", path = "../externalities", optional = true } +sp-runtime-interface = { path = "../runtime-interface", default-features = false } +sp-trie = { path = "../../primitives/trie", optional = true } +sp-externalities = { path = "../externalities", optional = true } log = { version = "0.4.8", optional = true } [features] default = ["std"] std = [ - "primitives/std", + "sp-core/std", "codec/std", "sp-std/std", "hash-db/std", - "trie", + "sp-trie", "sp-state-machine", "libsecp256k1", - "runtime-interface/std", - "externalities", + "sp-runtime-interface/std", + "sp-externalities", "log", ] diff --git a/substrate/primitives/io/src/lib.rs b/substrate/primitives/io/src/lib.rs index 5941a8fff8..be88907cde 100644 --- a/substrate/primitives/io/src/lib.rs +++ b/substrate/primitives/io/src/lib.rs @@ -34,7 +34,7 @@ use sp_std::vec::Vec; use sp_std::ops::Deref; #[cfg(feature = "std")] -use primitives::{ +use sp_core::{ crypto::Pair, traits::KeystoreExt, offchain::{OffchainExt, TransactionPoolExt}, @@ -42,7 +42,7 @@ use primitives::{ storage::{ChildStorageKey, ChildInfo}, }; -use primitives::{ +use sp_core::{ crypto::KeyTypeId, ed25519, sr25519, H256, LogLevel, offchain::{ Timestamp, HttpRequestId, HttpRequestStatus, HttpError, StorageKind, OpaqueNetworkState, @@ -50,14 +50,14 @@ use primitives::{ }; #[cfg(feature = "std")] -use ::trie::{TrieConfiguration, trie_types::Layout}; +use ::sp_trie::{TrieConfiguration, trie_types::Layout}; -use runtime_interface::{runtime_interface, Pointer}; +use sp_runtime_interface::{runtime_interface, Pointer}; use codec::{Encode, Decode}; #[cfg(feature = "std")] -use externalities::{ExternalitiesExt, Externalities}; +use sp_externalities::{ExternalitiesExt, Externalities}; /// Error verifying ECDSA signature #[derive(Encode, Decode)] @@ -318,12 +318,12 @@ pub trait Storage { pub trait Trie { /// A trie root formed from the iterated items. fn blake2_256_root(input: Vec<(Vec, Vec)>) -> H256 { - Layout::::trie_root(input) + Layout::::trie_root(input) } /// A trie root formed from the enumerated items. fn blake2_256_ordered_root(input: Vec>) -> H256 { - Layout::::ordered_trie_root(input) + Layout::::ordered_trie_root(input) } } @@ -332,7 +332,7 @@ pub trait Trie { pub trait Misc { /// The current relay chain identifier. fn chain_id(&self) -> u64 { - externalities::Externalities::chain_id(*self) + sp_externalities::Externalities::chain_id(*self) } /// Print a number. @@ -496,37 +496,37 @@ pub trait Crypto { pub trait Hashing { /// Conduct a 256-bit Keccak hash. fn keccak_256(data: &[u8]) -> [u8; 32] { - primitives::hashing::keccak_256(data) + sp_core::hashing::keccak_256(data) } /// Conduct a 256-bit Sha2 hash. fn sha2_256(data: &[u8]) -> [u8; 32] { - primitives::hashing::sha2_256(data) + sp_core::hashing::sha2_256(data) } /// Conduct a 128-bit Blake2 hash. fn blake2_128(data: &[u8]) -> [u8; 16] { - primitives::hashing::blake2_128(data) + sp_core::hashing::blake2_128(data) } /// Conduct a 256-bit Blake2 hash. fn blake2_256(data: &[u8]) -> [u8; 32] { - primitives::hashing::blake2_256(data) + sp_core::hashing::blake2_256(data) } /// Conduct four XX hashes to give a 256-bit result. fn twox_256(data: &[u8]) -> [u8; 32] { - primitives::hashing::twox_256(data) + sp_core::hashing::twox_256(data) } /// Conduct two XX hashes to give a 128-bit result. fn twox_128(data: &[u8]) -> [u8; 16] { - primitives::hashing::twox_128(data) + sp_core::hashing::twox_128(data) } /// Conduct two XX hashes to give a 64-bit result. fn twox_64(data: &[u8]) -> [u8; 8] { - primitives::hashing::twox_64(data) + sp_core::hashing::twox_64(data) } } @@ -881,7 +881,7 @@ pub fn oom(_: core::alloc::Layout) -> ! { /// Type alias for Externalities implementation used in tests. #[cfg(feature = "std")] -pub type TestExternalities = sp_state_machine::TestExternalities; +pub type TestExternalities = sp_state_machine::TestExternalities; /// The host functions Substrate provides for the Wasm runtime environment. /// @@ -902,9 +902,9 @@ pub type SubstrateHostFunctions = ( #[cfg(test)] mod tests { use super::*; - use primitives::map; + use sp_core::map; use sp_state_machine::BasicExternalities; - use primitives::storage::Storage; + use sp_core::storage::Storage; #[test] fn storage_works() { diff --git a/substrate/primitives/keyring/Cargo.toml b/substrate/primitives/keyring/Cargo.toml index 9053266184..7db87f3391 100644 --- a/substrate/primitives/keyring/Cargo.toml +++ b/substrate/primitives/keyring/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -primitives = { package = "sp-core", path = "../core" } +sp-core = { path = "../core" } sp-runtime = { path = "../runtime" } lazy_static = "1.4.0" strum = { version = "0.16.0", features = ["derive"] } diff --git a/substrate/primitives/keyring/src/ed25519.rs b/substrate/primitives/keyring/src/ed25519.rs index 7174d1cc43..3b882bfea8 100644 --- a/substrate/primitives/keyring/src/ed25519.rs +++ b/substrate/primitives/keyring/src/ed25519.rs @@ -18,8 +18,8 @@ use std::{collections::HashMap, ops::Deref}; use lazy_static::lazy_static; -use primitives::{ed25519::{Pair, Public, Signature}, Pair as PairT, Public as PublicT, H256}; -pub use primitives::ed25519; +use sp_core::{ed25519::{Pair, Public, Signature}, Pair as PairT, Public as PublicT, H256}; +pub use sp_core::ed25519; use sp_runtime::AccountId32; /// Set of test accounts. @@ -180,7 +180,7 @@ impl Deref for Keyring { #[cfg(test)] mod tests { use super::*; - use primitives::{ed25519::Pair, Pair as PairT}; + use sp_core::{ed25519::Pair, Pair as PairT}; #[test] fn should_work() { diff --git a/substrate/primitives/keyring/src/sr25519.rs b/substrate/primitives/keyring/src/sr25519.rs index a14566bbab..533a21f55a 100644 --- a/substrate/primitives/keyring/src/sr25519.rs +++ b/substrate/primitives/keyring/src/sr25519.rs @@ -19,8 +19,8 @@ use std::collections::HashMap; use std::ops::Deref; use lazy_static::lazy_static; -use primitives::{sr25519::{Pair, Public, Signature}, Pair as PairT, Public as PublicT, H256}; -pub use primitives::sr25519; +use sp_core::{sr25519::{Pair, Public, Signature}, Pair as PairT, Public as PublicT, H256}; +pub use sp_core::sr25519; use sp_runtime::AccountId32; /// Set of test accounts. @@ -181,7 +181,7 @@ impl Deref for Keyring { #[cfg(test)] mod tests { use super::*; - use primitives::{sr25519::Pair, Pair as PairT}; + use sp_core::{sr25519::Pair, Pair as PairT}; #[test] fn should_work() { diff --git a/substrate/primitives/rpc/Cargo.toml b/substrate/primitives/rpc/Cargo.toml index 9e44f407d0..09ce69e0c5 100644 --- a/substrate/primitives/rpc/Cargo.toml +++ b/substrate/primitives/rpc/Cargo.toml @@ -6,7 +6,7 @@ edition = "2018" [dependencies] serde = { version = "1.0.101", features = ["derive"] } -primitives = { package = "sp-core", path = "../core" } +sp-core = { path = "../core" } [dev-dependencies] serde_json = "1.0.41" diff --git a/substrate/primitives/rpc/src/number.rs b/substrate/primitives/rpc/src/number.rs index 9c3312e6cc..220b221b66 100644 --- a/substrate/primitives/rpc/src/number.rs +++ b/substrate/primitives/rpc/src/number.rs @@ -18,7 +18,7 @@ use serde::{Serialize, Deserialize}; use std::{convert::TryFrom, fmt::Debug}; -use primitives::U256; +use sp_core::U256; /// RPC Block number type /// diff --git a/substrate/primitives/runtime-interface/Cargo.toml b/substrate/primitives/runtime-interface/Cargo.toml index c451407681..5874e66237 100644 --- a/substrate/primitives/runtime-interface/Cargo.toml +++ b/substrate/primitives/runtime-interface/Cargo.toml @@ -5,19 +5,19 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -wasm-interface = { package = "sp-wasm-interface", path = "../wasm-interface", optional = true } +sp-wasm-interface = { path = "../wasm-interface", optional = true } sp-std = { path = "../std", default-features = false } sp-runtime-interface-proc-macro = { path = "proc-macro" } -externalities = { package = "sp-externalities", path = "../externalities", optional = true } +sp-externalities = { path = "../externalities", optional = true } codec = { package = "parity-scale-codec", version = "1.0.6", default-features = false } environmental = { version = "1.0.2", optional = true } static_assertions = "1.0.0" primitive-types = { version = "0.6.1", default-features = false } [dev-dependencies] -test-wasm = { package = "sp-runtime-interface-test-wasm", path = "test-wasm" } -state_machine = { package = "sp-state-machine", path = "../../primitives/state-machine" } -primitives = { package = "sp-core", path = "../core" } +sp-runtime-interface-test-wasm = { path = "test-wasm" } +sp-state-machine = { path = "../../primitives/state-machine" } +sp-core = { path = "../core" } sp-io = { path = "../io" } rustversion = "1.0.0" trybuild = "1.0.17" @@ -25,10 +25,10 @@ trybuild = "1.0.17" [features] default = [ "std" ] std = [ - "wasm-interface", + "sp-wasm-interface", "sp-std/std", "codec/std", - "externalities", + "sp-externalities", "environmental", "primitive-types/std", ] diff --git a/substrate/primitives/runtime-interface/proc-macro/src/runtime_interface/bare_function_interface.rs b/substrate/primitives/runtime-interface/proc-macro/src/runtime_interface/bare_function_interface.rs index dbedba000e..1c662f8802 100644 --- a/substrate/primitives/runtime-interface/proc-macro/src/runtime_interface/bare_function_interface.rs +++ b/substrate/primitives/runtime-interface/proc-macro/src/runtime_interface/bare_function_interface.rs @@ -106,7 +106,7 @@ fn function_std_impl( if is_wasm_only { Some( parse_quote!( - mut __function_context__: &mut dyn #crate_::wasm_interface::FunctionContext + mut __function_context__: &mut dyn #crate_::sp_wasm_interface::FunctionContext ) ) } else { @@ -164,7 +164,7 @@ fn generate_call_to_trait( } else { // The name of the trait the interface trait is implemented for let impl_trait_name = if is_wasm_only { - quote!( #crate_::wasm_interface::FunctionContext ) + quote!( #crate_::sp_wasm_interface::FunctionContext ) } else { quote!( #crate_::Externalities ) }; diff --git a/substrate/primitives/runtime-interface/proc-macro/src/runtime_interface/host_function_interface.rs b/substrate/primitives/runtime-interface/proc-macro/src/runtime_interface/host_function_interface.rs index f710e9b60c..63cb75f667 100644 --- a/substrate/primitives/runtime-interface/proc-macro/src/runtime_interface/host_function_interface.rs +++ b/substrate/primitives/runtime-interface/proc-macro/src/runtime_interface/host_function_interface.rs @@ -174,8 +174,8 @@ fn generate_host_functions_struct(trait_def: &ItemTrait, is_wasm_only: bool) -> pub struct HostFunctions; #[cfg(feature = "std")] - impl #crate_::wasm_interface::HostFunctions for HostFunctions { - fn host_functions() -> Vec<&'static dyn #crate_::wasm_interface::Function> { + impl #crate_::sp_wasm_interface::HostFunctions for HostFunctions { + fn host_functions() -> Vec<&'static dyn #crate_::sp_wasm_interface::Function> { vec![ #( #host_functions ),* ] } } @@ -212,20 +212,20 @@ fn generate_host_function_implementation( struct #struct_name; #[allow(unused)] - impl #crate_::wasm_interface::Function for #struct_name { + impl #crate_::sp_wasm_interface::Function for #struct_name { fn name(&self) -> &str { #name } - fn signature(&self) -> #crate_::wasm_interface::Signature { + fn signature(&self) -> #crate_::sp_wasm_interface::Signature { #signature } fn execute( &self, - __function_context__: &mut dyn #crate_::wasm_interface::FunctionContext, - args: &mut dyn Iterator, - ) -> std::result::Result, String> { + __function_context__: &mut dyn #crate_::sp_wasm_interface::FunctionContext, + args: &mut dyn Iterator, + ) -> std::result::Result, String> { #( #wasm_to_ffi_values )* #( #ffi_to_host_values )* #host_function_call @@ -234,7 +234,7 @@ fn generate_host_function_implementation( } } - &#struct_name as &dyn #crate_::wasm_interface::Function + &#struct_name as &dyn #crate_::sp_wasm_interface::Function } } ) @@ -246,18 +246,18 @@ fn generate_wasm_interface_signature_for_host_function(sig: &Signature) -> Resul let return_value = match &sig.output { ReturnType::Type(_, ty) => quote! { - Some( <<#ty as #crate_::RIType>::FFIType as #crate_::wasm_interface::IntoValue>::VALUE_TYPE ) + Some( <<#ty as #crate_::RIType>::FFIType as #crate_::sp_wasm_interface::IntoValue>::VALUE_TYPE ) }, ReturnType::Default => quote!( None ), }; let arg_types = get_function_argument_types_without_ref(sig) .map(|ty| quote! { - <<#ty as #crate_::RIType>::FFIType as #crate_::wasm_interface::IntoValue>::VALUE_TYPE + <<#ty as #crate_::RIType>::FFIType as #crate_::sp_wasm_interface::IntoValue>::VALUE_TYPE }); Ok( quote! { - #crate_::wasm_interface::Signature { + #crate_::sp_wasm_interface::Signature { args: std::borrow::Cow::Borrowed(&[ #( #arg_types ),* ][..]), return_value: #return_value, } @@ -292,7 +292,7 @@ fn generate_wasm_to_ffi_values<'a>( Ok(quote! { let val = args.next().ok_or_else(|| #error_message)?; let #var_name = < - <#ty as #crate_::RIType>::FFIType as #crate_::wasm_interface::TryFromValue + <#ty as #crate_::RIType>::FFIType as #crate_::sp_wasm_interface::TryFromValue >::try_from_value(val).ok_or_else(|| #try_from_error)?; }) }) @@ -408,7 +408,7 @@ fn generate_return_value_into_wasm_value(sig: &Signature) -> TokenStream { <#ty as #crate_::host::IntoFFIValue>::into_ffi_value( #result_var_name, __function_context__, - ).map(#crate_::wasm_interface::IntoValue::into_value).map(Some) + ).map(#crate_::sp_wasm_interface::IntoValue::into_value).map(Some) } } } diff --git a/substrate/primitives/runtime-interface/proc-macro/src/runtime_interface/trait_decl_impl.rs b/substrate/primitives/runtime-interface/proc-macro/src/runtime_interface/trait_decl_impl.rs index 0e5ae906ab..e76daf71bd 100644 --- a/substrate/primitives/runtime-interface/proc-macro/src/runtime_interface/trait_decl_impl.rs +++ b/substrate/primitives/runtime-interface/proc-macro/src/runtime_interface/trait_decl_impl.rs @@ -130,7 +130,7 @@ fn impl_trait_for_externalities(trait_def: &ItemTrait, is_wasm_only: bool) -> Re }); let impl_type = if is_wasm_only { - quote!( &mut dyn #crate_::wasm_interface::FunctionContext ) + quote!( &mut dyn #crate_::sp_wasm_interface::FunctionContext ) } else { quote!( &mut dyn #crate_::Externalities ) }; diff --git a/substrate/primitives/runtime-interface/src/host.rs b/substrate/primitives/runtime-interface/src/host.rs index 313aba3d85..10ebd1beec 100644 --- a/substrate/primitives/runtime-interface/src/host.rs +++ b/substrate/primitives/runtime-interface/src/host.rs @@ -18,7 +18,7 @@ use crate::RIType; -use wasm_interface::{FunctionContext, Result}; +use sp_wasm_interface::{FunctionContext, Result}; /// Something that can be converted into a ffi value. pub trait IntoFFIValue: RIType { diff --git a/substrate/primitives/runtime-interface/src/impls.rs b/substrate/primitives/runtime-interface/src/impls.rs index 0410d15321..97dfcb769a 100644 --- a/substrate/primitives/runtime-interface/src/impls.rs +++ b/substrate/primitives/runtime-interface/src/impls.rs @@ -26,7 +26,7 @@ use crate::wasm::*; use static_assertions::assert_eq_size; #[cfg(feature = "std")] -use wasm_interface::{FunctionContext, Result}; +use sp_wasm_interface::{FunctionContext, Result}; use codec::{Encode, Decode}; @@ -448,7 +448,7 @@ impl IntoFFIValue for str { } #[cfg(feature = "std")] -impl RIType for Pointer { +impl RIType for Pointer { type FFIType = u32; } @@ -475,7 +475,7 @@ impl FromFFIValue for Pointer { } #[cfg(feature = "std")] -impl FromFFIValue for Pointer { +impl FromFFIValue for Pointer { type SelfInstance = Self; fn from_ffi_value(_: &mut dyn FunctionContext, arg: u32) -> Result { @@ -484,7 +484,7 @@ impl FromFFIValue for Pointer { } #[cfg(feature = "std")] -impl IntoFFIValue for Pointer { +impl IntoFFIValue for Pointer { fn into_ffi_value(self, _: &mut dyn FunctionContext) -> Result { Ok(self.into()) } diff --git a/substrate/primitives/runtime-interface/src/lib.rs b/substrate/primitives/runtime-interface/src/lib.rs index 9baf47df27..b02ccc6ab2 100644 --- a/substrate/primitives/runtime-interface/src/lib.rs +++ b/substrate/primitives/runtime-interface/src/lib.rs @@ -76,7 +76,7 @@ extern crate self as sp_runtime_interface; #[doc(hidden)] #[cfg(feature = "std")] -pub use wasm_interface; +pub use sp_wasm_interface; #[doc(hidden)] pub use sp_std; @@ -130,7 +130,7 @@ pub use sp_std; /// fn set_or_clear(&mut self, optional: Option>); /// } /// -/// impl Interface for &mut dyn externalities::Externalities { +/// impl Interface for &mut dyn sp_externalities::Externalities { /// fn call_some_complex_code(data: &[u8]) -> Vec { Vec::new() } /// fn set_or_clear(&mut self, optional: Option>) { /// match optional { @@ -141,11 +141,11 @@ pub use sp_std; /// } /// /// pub fn call_some_complex_code(data: &[u8]) -> Vec { -/// <&mut dyn externalities::Externalities as Interface>::call_some_complex_code(data) +/// <&mut dyn sp_externalities::Externalities as Interface>::call_some_complex_code(data) /// } /// /// pub fn set_or_clear(optional: Option>) { -/// externalities::with_externalities(|mut ext| Interface::set_or_clear(&mut ext, optional)) +/// sp_externalities::with_externalities(|mut ext| Interface::set_or_clear(&mut ext, optional)) /// .expect("`set_or_clear` called outside of an Externalities-provided environment.") /// } /// @@ -227,7 +227,7 @@ pub use sp_runtime_interface_proc_macro::runtime_interface; #[doc(hidden)] #[cfg(feature = "std")] -pub use externalities::{ +pub use sp_externalities::{ set_and_run_with_externalities, with_externalities, Externalities, ExternalitiesExt, ExtensionStore, }; @@ -249,7 +249,7 @@ pub mod pass_by; pub trait RIType { /// The ffi type that is used to represent `Self`. #[cfg(feature = "std")] - type FFIType: wasm_interface::IntoValue + wasm_interface::TryFromValue; + type FFIType: sp_wasm_interface::IntoValue + sp_wasm_interface::TryFromValue; #[cfg(not(feature = "std"))] type FFIType; } @@ -260,4 +260,4 @@ pub type Pointer = *mut T; /// A pointer that can be used in a runtime interface function signature. #[cfg(feature = "std")] -pub type Pointer = wasm_interface::Pointer; \ No newline at end of file +pub type Pointer = sp_wasm_interface::Pointer; \ No newline at end of file diff --git a/substrate/primitives/runtime-interface/src/pass_by.rs b/substrate/primitives/runtime-interface/src/pass_by.rs index 5d5b98244e..dd38a4f80f 100644 --- a/substrate/primitives/runtime-interface/src/pass_by.rs +++ b/substrate/primitives/runtime-interface/src/pass_by.rs @@ -28,7 +28,7 @@ use crate::host::*; use crate::wasm::*; #[cfg(feature = "std")] -use wasm_interface::{FunctionContext, Pointer, Result}; +use sp_wasm_interface::{FunctionContext, Pointer, Result}; use sp_std::{marker::PhantomData, convert::TryFrom}; diff --git a/substrate/primitives/runtime-interface/test-wasm/Cargo.toml b/substrate/primitives/runtime-interface/test-wasm/Cargo.toml index 9c3ac0a7f0..d8ed272aa8 100644 --- a/substrate/primitives/runtime-interface/test-wasm/Cargo.toml +++ b/substrate/primitives/runtime-interface/test-wasm/Cargo.toml @@ -6,14 +6,14 @@ edition = "2018" build = "build.rs" [dependencies] -runtime-interface = { package = "sp-runtime-interface", path = "../", default-features = false } +sp-runtime-interface = { path = "../", default-features = false } sp-std = { path = "../../std", default-features = false } sp-io = { path = "../../io", default-features = false } -primitives = { package = "sp-core", path = "../../core", default-features = false } +sp-core = { path = "../../core", default-features = false } [build-dependencies] wasm-builder-runner = { package = "substrate-wasm-builder-runner", version = "1.0.3", path = "../../../utils/wasm-builder-runner" } [features] default = [ "std" ] -std = [ "runtime-interface/std", "sp-std/std", "primitives/std", "sp-io/std" ] +std = [ "sp-runtime-interface/std", "sp-std/std", "sp-core/std", "sp-io/std" ] diff --git a/substrate/primitives/runtime-interface/test-wasm/src/lib.rs b/substrate/primitives/runtime-interface/test-wasm/src/lib.rs index dd75a9cb8a..f353518019 100644 --- a/substrate/primitives/runtime-interface/test-wasm/src/lib.rs +++ b/substrate/primitives/runtime-interface/test-wasm/src/lib.rs @@ -18,12 +18,12 @@ #![cfg_attr(not(feature = "std"), no_std)] -use runtime_interface::runtime_interface; +use sp_runtime_interface::runtime_interface; #[cfg(not(feature = "std"))] use sp_std::{vec, vec::Vec, mem, convert::TryFrom}; -use primitives::{sr25519::Public, wasm_export_functions}; +use sp_core::{sr25519::Public, wasm_export_functions}; // Inlucde the WASM binary #[cfg(feature = "std")] diff --git a/substrate/primitives/runtime-interface/test/Cargo.toml b/substrate/primitives/runtime-interface/test/Cargo.toml index 269e8bc4aa..1e9aea910e 100644 --- a/substrate/primitives/runtime-interface/test/Cargo.toml +++ b/substrate/primitives/runtime-interface/test/Cargo.toml @@ -7,8 +7,8 @@ publish = false [dependencies] sp-runtime-interface = { path = "../" } -executor = { package = "sc-executor", path = "../../../client/executor" } -test-wasm = { package = "sp-runtime-interface-test-wasm", path = "../test-wasm" } -state_machine = { package = "sp-state-machine", path = "../../../primitives/state-machine" } -primitives = { package = "sp-core", path = "../../core" } +sc-executor = { path = "../../../client/executor" } +sp-runtime-interface-test-wasm = { path = "../test-wasm" } +sp-state-machine = { path = "../../../primitives/state-machine" } +sp-core = { path = "../../core" } sp-io = { path = "../../io" } diff --git a/substrate/primitives/runtime-interface/test/src/lib.rs b/substrate/primitives/runtime-interface/test/src/lib.rs index 3de5e1ddc1..a791442fc4 100644 --- a/substrate/primitives/runtime-interface/test/src/lib.rs +++ b/substrate/primitives/runtime-interface/test/src/lib.rs @@ -17,26 +17,26 @@ //! Integration tests for runtime interface primitives use sp_runtime_interface::*; -use test_wasm::{WASM_BINARY, test_api::HostFunctions}; -use wasm_interface::HostFunctions as HostFunctionsT; +use sp_runtime_interface_test_wasm::{WASM_BINARY, test_api::HostFunctions}; +use sp_wasm_interface::HostFunctions as HostFunctionsT; -type TestExternalities = state_machine::TestExternalities; +type TestExternalities = sp_state_machine::TestExternalities; fn call_wasm_method(method: &str) -> TestExternalities { let mut ext = TestExternalities::default(); let mut ext_ext = ext.ext(); - executor::call_in_wasm::< + sc_executor::call_in_wasm::< _, ( HF, sp_io::SubstrateHostFunctions, - executor::deprecated_host_interface::SubstrateExternals + sc_executor::deprecated_host_interface::SubstrateExternals ) >( method, &[], - executor::WasmExecutionMethod::Interpreted, + sc_executor::WasmExecutionMethod::Interpreted, &mut ext_ext, &WASM_BINARY[..], 8, diff --git a/substrate/primitives/runtime/Cargo.toml b/substrate/primitives/runtime/Cargo.toml index 3c8377666a..78cbcad6dc 100644 --- a/substrate/primitives/runtime/Cargo.toml +++ b/substrate/primitives/runtime/Cargo.toml @@ -7,16 +7,16 @@ edition = "2018" [dependencies] serde = { version = "1.0.101", optional = true, features = ["derive"] } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } -primitives = { package = "sp-core", path = "../core", default-features = false } -app-crypto = { package = "sp-application-crypto", path = "../application-crypto", default-features = false } -arithmetic = { package = "sp-arithmetic", path = "../arithmetic", default-features = false } +sp-core = { path = "../core", default-features = false } +sp-application-crypto = { path = "../application-crypto", default-features = false } +sp-arithmetic = { path = "../arithmetic", default-features = false } sp-std = { path = "../std", default-features = false } sp-io = { path = "../io", default-features = false } log = { version = "0.4.8", optional = true } paste = "0.1.6" rand = { version = "0.7.2", optional = true } impl-trait-for-tuples = "0.1.3" -inherents = { package = "sp-inherents", path = "../inherents", default-features = false } +sp-inherents = { path = "../inherents", default-features = false } [dev-dependencies] serde_json = "1.0.41" @@ -26,14 +26,14 @@ rand = "0.7.2" bench = [] default = ["std"] std = [ - "app-crypto/std", - "arithmetic/std", + "sp-application-crypto/std", + "sp-arithmetic/std", "codec/std", "log", - "primitives/std", + "sp-core/std", "rand", "sp-std/std", "sp-io/std", "serde", - "inherents/std", + "sp-inherents/std", ] diff --git a/substrate/primitives/runtime/src/curve.rs b/substrate/primitives/runtime/src/curve.rs index 52a6ddd33b..f2e1a8b7d5 100644 --- a/substrate/primitives/runtime/src/curve.rs +++ b/substrate/primitives/runtime/src/curve.rs @@ -20,7 +20,7 @@ use crate::{Perbill, traits::{SimpleArithmetic, SaturatedConversion}}; use core::ops::Sub; /// Piecewise Linear function in [0, 1] -> [0, 1]. -#[derive(PartialEq, Eq, primitives::RuntimeDebug)] +#[derive(PartialEq, Eq, sp_core::RuntimeDebug)] pub struct PiecewiseLinear<'a> { /// Array of points. Must be in order from the lowest abscissas to the highest. pub points: &'a [(Perbill, Perbill)], diff --git a/substrate/primitives/runtime/src/generic/block.rs b/substrate/primitives/runtime/src/generic/block.rs index 12b2f82eac..cad166e80c 100644 --- a/substrate/primitives/runtime/src/generic/block.rs +++ b/substrate/primitives/runtime/src/generic/block.rs @@ -23,7 +23,7 @@ use std::fmt; use serde::{Deserialize, Serialize}; use sp_std::prelude::*; -use primitives::RuntimeDebug; +use sp_core::RuntimeDebug; use crate::codec::{Codec, Encode, Decode}; use crate::traits::{self, Member, Block as BlockT, Header as HeaderT, MaybeSerialize}; use crate::Justification; diff --git a/substrate/primitives/runtime/src/generic/checked_extrinsic.rs b/substrate/primitives/runtime/src/generic/checked_extrinsic.rs index 929d702661..3940943a59 100644 --- a/substrate/primitives/runtime/src/generic/checked_extrinsic.rs +++ b/substrate/primitives/runtime/src/generic/checked_extrinsic.rs @@ -27,7 +27,7 @@ use crate::transaction_validity::TransactionValidity; /// Definition of something that the external world might want to say; its /// existence implies that it has been checked and is good, particularly with /// regards to the signature. -#[derive(PartialEq, Eq, Clone, primitives::RuntimeDebug)] +#[derive(PartialEq, Eq, Clone, sp_core::RuntimeDebug)] pub struct CheckedExtrinsic { /// Who this purports to be from and the number of extrinsics have come before /// from the same signer, if anyone (note this is not a signature). diff --git a/substrate/primitives/runtime/src/generic/digest.rs b/substrate/primitives/runtime/src/generic/digest.rs index c74d09076b..9e241d9a48 100644 --- a/substrate/primitives/runtime/src/generic/digest.rs +++ b/substrate/primitives/runtime/src/generic/digest.rs @@ -23,7 +23,7 @@ use sp_std::prelude::*; use crate::ConsensusEngineId; use crate::codec::{Decode, Encode, Input, Error}; -use primitives::RuntimeDebug; +use sp_core::RuntimeDebug; /// Generic header digest. #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)] @@ -105,7 +105,7 @@ pub enum DigestItem { impl serde::Serialize for DigestItem { fn serialize(&self, seq: S) -> Result where S: serde::Serializer { self.using_encoded(|bytes| { - primitives::bytes::serialize(bytes, seq) + sp_core::bytes::serialize(bytes, seq) }) } } @@ -115,7 +115,7 @@ impl<'a, Hash: Decode> serde::Deserialize<'a> for DigestItem { fn deserialize(de: D) -> Result where D: serde::Deserializer<'a>, { - let r = primitives::bytes::deserialize(de)?; + let r = sp_core::bytes::deserialize(de)?; Decode::decode(&mut &r[..]) .map_err(|e| serde::de::Error::custom(format!("Decode error: {}", e))) } diff --git a/substrate/primitives/runtime/src/generic/era.rs b/substrate/primitives/runtime/src/generic/era.rs index 305951b1ee..c72e8f8b0f 100644 --- a/substrate/primitives/runtime/src/generic/era.rs +++ b/substrate/primitives/runtime/src/generic/era.rs @@ -28,7 +28,7 @@ pub type Period = u64; pub type Phase = u64; /// An era to describe the longevity of a transaction. -#[derive(PartialEq, Eq, Clone, Copy, primitives::RuntimeDebug)] +#[derive(PartialEq, Eq, Clone, Copy, sp_core::RuntimeDebug)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub enum Era { /// The transaction is valid forever. The genesis hash must be present in the signed content. diff --git a/substrate/primitives/runtime/src/generic/header.rs b/substrate/primitives/runtime/src/generic/header.rs index aa47966956..c095490bc9 100644 --- a/substrate/primitives/runtime/src/generic/header.rs +++ b/substrate/primitives/runtime/src/generic/header.rs @@ -24,14 +24,14 @@ use crate::traits::{ MaybeSerializeDeserialize, MaybeSerialize, MaybeDisplay, }; use crate::generic::Digest; -use primitives::U256; +use sp_core::U256; use sp_std::{ convert::TryFrom, fmt::Debug, }; /// Abstraction over a block header for a substrate chain. -#[derive(PartialEq, Eq, Clone, primitives::RuntimeDebug)] +#[derive(PartialEq, Eq, Clone, sp_core::RuntimeDebug)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] #[cfg_attr(feature = "std", serde(deny_unknown_fields))] diff --git a/substrate/primitives/runtime/src/generic/tests.rs b/substrate/primitives/runtime/src/generic/tests.rs index 67e85da374..fed9f6ec60 100644 --- a/substrate/primitives/runtime/src/generic/tests.rs +++ b/substrate/primitives/runtime/src/generic/tests.rs @@ -17,7 +17,7 @@ //! Tests for the generic implementations of Extrinsic/Header/Block. use crate::codec::{Decode, Encode}; -use primitives::H256; +use sp_core::H256; use super::DigestItem; #[test] diff --git a/substrate/primitives/runtime/src/lib.rs b/substrate/primitives/runtime/src/lib.rs index 8bfd4834c5..db039d5b75 100644 --- a/substrate/primitives/runtime/src/lib.rs +++ b/substrate/primitives/runtime/src/lib.rs @@ -35,14 +35,14 @@ pub use sp_std; pub use paste; #[doc(hidden)] -pub use app_crypto; +pub use sp_application_crypto as app_crypto; #[cfg(feature = "std")] -pub use primitives::storage::{Storage, StorageChild}; +pub use sp_core::storage::{Storage, StorageChild}; use sp_std::prelude::*; use sp_std::convert::TryFrom; -use primitives::{crypto, ed25519, sr25519, ecdsa, hash::{H256, H512}}; +use sp_core::{crypto, ed25519, sr25519, ecdsa, hash::{H256, H512}}; use codec::{Encode, Decode}; pub mod curve; @@ -58,18 +58,18 @@ pub mod random_number_generator; pub use generic::{DigestItem, Digest}; /// Re-export this since it's part of the API of this crate. -pub use primitives::{TypeId, crypto::{key_types, KeyTypeId, CryptoType, AccountId32}}; -pub use app_crypto::{RuntimeAppPublic, BoundToRuntimeAppPublic}; +pub use sp_core::{TypeId, crypto::{key_types, KeyTypeId, CryptoType, AccountId32}}; +pub use sp_application_crypto::{RuntimeAppPublic, BoundToRuntimeAppPublic}; /// Re-export `RuntimeDebug`, to avoid dependency clutter. -pub use primitives::RuntimeDebug; +pub use sp_core::RuntimeDebug; /// Re-export top-level arithmetic stuff. -pub use arithmetic::{Perquintill, Perbill, Permill, Percent, Rational128, Fixed64}; +pub use sp_arithmetic::{Perquintill, Perbill, Permill, Percent, Rational128, Fixed64}; /// Re-export 128 bit helpers. -pub use arithmetic::helpers_128bit; +pub use sp_arithmetic::helpers_128bit; /// Re-export big_uint stuff. -pub use arithmetic::biguint; +pub use sp_arithmetic::biguint; pub use random_number_generator::RandomNumberGenerator; @@ -121,7 +121,7 @@ use crate::traits::IdentifyAccount; #[cfg(feature = "std")] pub trait BuildStorage: Sized { /// Build the storage out of this builder. - fn build_storage(&self) -> Result { + fn build_storage(&self) -> Result { let mut storage = Default::default(); self.assimilate_storage(&mut storage)?; Ok(storage) @@ -129,7 +129,7 @@ pub trait BuildStorage: Sized { /// Assimilate the storage for this module into pre-existing overlays. fn assimilate_storage( &self, - storage: &mut primitives::storage::Storage, + storage: &mut sp_core::storage::Storage, ) -> Result<(), String>; } @@ -139,15 +139,15 @@ pub trait BuildModuleGenesisStorage: Sized { /// Create the module genesis storage into the given `storage` and `child_storage`. fn build_module_genesis_storage( &self, - storage: &mut primitives::storage::Storage, + storage: &mut sp_core::storage::Storage, ) -> Result<(), String>; } #[cfg(feature = "std")] -impl BuildStorage for primitives::storage::Storage { +impl BuildStorage for sp_core::storage::Storage { fn assimilate_storage( &self, - storage: &mut primitives::storage::Storage, + storage: &mut sp_core::storage::Storage, )-> Result<(), String> { storage.top.extend(self.top.iter().map(|(k, v)| (k.clone(), v.clone()))); for (k, other_map) in self.children.iter() { @@ -304,7 +304,7 @@ impl std::fmt::Display for MultiSigner { impl Verify for MultiSignature { type Signer = MultiSigner; fn verify>(&self, mut msg: L, signer: &AccountId32) -> bool { - use primitives::crypto::Public; + use sp_core::crypto::Public; match (self, signer) { (MultiSignature::Ed25519(ref sig), who) => sig.verify(msg, &ed25519::Public::from_slice(who.as_ref())), (MultiSignature::Sr25519(ref sig), who) => sig.verify(msg, &sr25519::Public::from_slice(who.as_ref())), @@ -329,7 +329,7 @@ pub struct AnySignature(H512); impl Verify for AnySignature { type Signer = sr25519::Public; fn verify>(&self, mut msg: L, signer: &sr25519::Public) -> bool { - use primitives::crypto::Public; + use sp_core::crypto::Public; let msg = msg.get(); sr25519::Signature::try_from(self.0.as_fixed_bytes().as_ref()) .map(|s| s.verify(msg, signer)) @@ -619,7 +619,7 @@ pub struct OpaqueExtrinsic(pub Vec); impl sp_std::fmt::Debug for OpaqueExtrinsic { #[cfg(feature = "std")] fn fmt(&self, fmt: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { - write!(fmt, "{}", primitives::hexdisplay::HexDisplay::from(&self.0)) + write!(fmt, "{}", sp_core::hexdisplay::HexDisplay::from(&self.0)) } #[cfg(not(feature = "std"))] @@ -632,14 +632,14 @@ impl sp_std::fmt::Debug for OpaqueExtrinsic { #[cfg(feature = "std")] impl ::serde::Serialize for OpaqueExtrinsic { fn serialize(&self, seq: S) -> Result where S: ::serde::Serializer { - codec::Encode::using_encoded(&self.0, |bytes| ::primitives::bytes::serialize(bytes, seq)) + codec::Encode::using_encoded(&self.0, |bytes| ::sp_core::bytes::serialize(bytes, seq)) } } #[cfg(feature = "std")] impl<'a> ::serde::Deserialize<'a> for OpaqueExtrinsic { fn deserialize(de: D) -> Result where D: ::serde::Deserializer<'a> { - let r = ::primitives::bytes::deserialize(de)?; + let r = ::sp_core::bytes::deserialize(de)?; Decode::decode(&mut &r[..]) .map_err(|e| ::serde::de::Error::custom(format!("Decode error: {}", e))) } diff --git a/substrate/primitives/runtime/src/offchain/http.rs b/substrate/primitives/runtime/src/offchain/http.rs index 5110aede13..968d50daee 100644 --- a/substrate/primitives/runtime/src/offchain/http.rs +++ b/substrate/primitives/runtime/src/offchain/http.rs @@ -51,8 +51,8 @@ use sp_std::str; use sp_std::prelude::Vec; #[cfg(not(feature = "std"))] use sp_std::prelude::vec; -use primitives::RuntimeDebug; -use primitives::offchain::{ +use sp_core::RuntimeDebug; +use sp_core::offchain::{ Timestamp, HttpRequestId as RequestId, HttpRequestStatus as RequestStatus, @@ -516,7 +516,7 @@ impl<'a> HeadersIterator<'a> { mod tests { use super::*; use sp_io::TestExternalities; - use primitives::offchain::{ + use sp_core::offchain::{ OffchainExt, testing, }; diff --git a/substrate/primitives/runtime/src/testing.rs b/substrate/primitives/runtime/src/testing.rs index e77b7c23b4..4fb7ccade7 100644 --- a/substrate/primitives/runtime/src/testing.rs +++ b/substrate/primitives/runtime/src/testing.rs @@ -26,8 +26,8 @@ use crate::traits::{ #[allow(deprecated)] use crate::traits::ValidateUnsigned; use crate::{generic, KeyTypeId, ApplyExtrinsicResult}; -pub use primitives::{H256, sr25519}; -use primitives::{crypto::{CryptoType, Dummy, key_types, Public}, U256}; +pub use sp_core::{H256, sr25519}; +use sp_core::{crypto::{CryptoType, Dummy, key_types, Public}, U256}; use crate::transaction_validity::{TransactionValidity, TransactionValidityError}; /// Authority Id @@ -80,7 +80,7 @@ impl UintAuthorityId { } } -impl app_crypto::RuntimeAppPublic for UintAuthorityId { +impl sp_application_crypto::RuntimeAppPublic for UintAuthorityId { const ID: KeyTypeId = key_types::DUMMY; type Signature = u64; diff --git a/substrate/primitives/runtime/src/traits.rs b/substrate/primitives/runtime/src/traits.rs index de74c949db..0001690b38 100644 --- a/substrate/primitives/runtime/src/traits.rs +++ b/substrate/primitives/runtime/src/traits.rs @@ -23,18 +23,18 @@ use sp_io; use std::fmt::Display; #[cfg(feature = "std")] use serde::{Serialize, Deserialize, de::DeserializeOwned}; -use primitives::{self, Hasher, Blake2Hasher, TypeId}; +use sp_core::{self, Hasher, Blake2Hasher, TypeId}; use crate::codec::{Codec, Encode, Decode}; use crate::transaction_validity::{ ValidTransaction, TransactionValidity, TransactionValidityError, UnknownTransaction, }; use crate::generic::{Digest, DigestItem}; -pub use arithmetic::traits::{ +pub use sp_arithmetic::traits::{ SimpleArithmetic, UniqueSaturatedInto, UniqueSaturatedFrom, Saturating, SaturatedConversion, Zero, One, Bounded, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv, CheckedShl, CheckedShr, IntegerSquareRoot }; -use app_crypto::AppKey; +use sp_application_crypto::AppKey; use impl_trait_for_tuples::impl_for_tuples; /// A lazy value. @@ -58,17 +58,17 @@ pub trait IdentifyAccount { fn into_account(self) -> Self::AccountId; } -impl IdentifyAccount for primitives::ed25519::Public { +impl IdentifyAccount for sp_core::ed25519::Public { type AccountId = Self; fn into_account(self) -> Self { self } } -impl IdentifyAccount for primitives::sr25519::Public { +impl IdentifyAccount for sp_core::sr25519::Public { type AccountId = Self; fn into_account(self) -> Self { self } } -impl IdentifyAccount for primitives::ecdsa::Public { +impl IdentifyAccount for sp_core::ecdsa::Public { type AccountId = Self; fn into_account(self) -> Self { self } } @@ -81,23 +81,23 @@ pub trait Verify { fn verify>(&self, msg: L, signer: &::AccountId) -> bool; } -impl Verify for primitives::ed25519::Signature { - type Signer = primitives::ed25519::Public; - fn verify>(&self, mut msg: L, signer: &primitives::ed25519::Public) -> bool { +impl Verify for sp_core::ed25519::Signature { + type Signer = sp_core::ed25519::Public; + fn verify>(&self, mut msg: L, signer: &sp_core::ed25519::Public) -> bool { sp_io::crypto::ed25519_verify(self, msg.get(), signer) } } -impl Verify for primitives::sr25519::Signature { - type Signer = primitives::sr25519::Public; - fn verify>(&self, mut msg: L, signer: &primitives::sr25519::Public) -> bool { +impl Verify for sp_core::sr25519::Signature { + type Signer = sp_core::sr25519::Public; + fn verify>(&self, mut msg: L, signer: &sp_core::sr25519::Public) -> bool { sp_io::crypto::sr25519_verify(self, msg.get(), signer) } } -impl Verify for primitives::ecdsa::Signature { - type Signer = primitives::ecdsa::Public; - fn verify>(&self, mut msg: L, signer: &primitives::ecdsa::Public) -> bool { +impl Verify for sp_core::ecdsa::Signature { + type Signer = sp_core::ecdsa::Public; + fn verify>(&self, mut msg: L, signer: &sp_core::ecdsa::Public) -> bool { match sp_io::crypto::secp256k1_ecdsa_recover_compressed( self.as_ref(), &sp_io::hashing::blake2_256(msg.get()), @@ -117,19 +117,19 @@ pub trait AppVerify { } impl< - S: Verify::Public as app_crypto::AppPublic>::Generic> + From, - T: app_crypto::Wraps + app_crypto::AppKey + app_crypto::AppSignature + + S: Verify::Public as sp_application_crypto::AppPublic>::Generic> + From, + T: sp_application_crypto::Wraps + sp_application_crypto::AppKey + sp_application_crypto::AppSignature + AsRef + AsMut + From, > AppVerify for T where ::Signer: IdentifyAccount::Signer>, - <::Public as app_crypto::AppPublic>::Generic: - IdentifyAccount::Public as app_crypto::AppPublic>::Generic>, + <::Public as sp_application_crypto::AppPublic>::Generic: + IdentifyAccount::Public as sp_application_crypto::AppPublic>::Generic>, { type AccountId = ::Public; fn verify>(&self, msg: L, signer: &::Public) -> bool { - use app_crypto::IsWrappedBy; + use sp_application_crypto::IsWrappedBy; let inner: &S = self.as_ref(); - let inner_pubkey = <::Public as app_crypto::AppPublic>::Generic::from_ref(&signer); + let inner_pubkey = <::Public as sp_application_crypto::AppPublic>::Generic::from_ref(&signer); Verify::verify(inner, msg, inner_pubkey) } } @@ -391,12 +391,12 @@ pub trait Hash: 'static + MaybeSerializeDeserialize + Debug + Clone + Eq + Parti } /// Blake2-256 Hash implementation. -#[derive(PartialEq, Eq, Clone, primitives::RuntimeDebug)] +#[derive(PartialEq, Eq, Clone, sp_core::RuntimeDebug)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub struct BlakeTwo256; impl Hash for BlakeTwo256 { - type Output = primitives::H256; + type Output = sp_core::H256; type Hasher = Blake2Hasher; fn hash(s: &[u8]) -> Self::Output { sp_io::hashing::blake2_256(s).into() @@ -417,10 +417,10 @@ pub trait CheckEqual { fn check_equal(&self, other: &Self); } -impl CheckEqual for primitives::H256 { +impl CheckEqual for sp_core::H256 { #[cfg(feature = "std")] fn check_equal(&self, other: &Self) { - use primitives::hexdisplay::HexDisplay; + use sp_core::hexdisplay::HexDisplay; if self != other { println!( "Hash: given={}, expected={}", @@ -1281,8 +1281,8 @@ mod tests { use crate::codec::{Encode, Decode, Input}; mod t { - use primitives::crypto::KeyTypeId; - use app_crypto::{app_crypto, sr25519}; + use sp_core::crypto::KeyTypeId; + use sp_application_crypto::{app_crypto, sr25519}; app_crypto!(sr25519, KeyTypeId(*b"test")); } diff --git a/substrate/primitives/sandbox/Cargo.toml b/substrate/primitives/sandbox/Cargo.toml index 6f8d518c49..d02c115501 100755 --- a/substrate/primitives/sandbox/Cargo.toml +++ b/substrate/primitives/sandbox/Cargo.toml @@ -6,7 +6,7 @@ edition = "2018" [dependencies] wasmi = { version = "0.6.2", optional = true } -primitives = { package = "sp-core", path = "../core", default-features = false } +sp-core = { path = "../core", default-features = false } sp-std = { path = "../std", default-features = false } sp-io = { path = "../io", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false } @@ -19,7 +19,7 @@ assert_matches = "1.3.0" default = ["std"] std = [ "wasmi", - "primitives/std", + "sp-core/std", "sp-std/std", "codec/std", "sp-io/std", diff --git a/substrate/primitives/sandbox/src/lib.rs b/substrate/primitives/sandbox/src/lib.rs index a006655c78..448cadfe80 100755 --- a/substrate/primitives/sandbox/src/lib.rs +++ b/substrate/primitives/sandbox/src/lib.rs @@ -40,7 +40,7 @@ use sp_std::prelude::*; -pub use primitives::sandbox::{TypedValue, ReturnValue, HostError}; +pub use sp_core::sandbox::{TypedValue, ReturnValue, HostError}; mod imp { #[cfg(feature = "std")] @@ -51,7 +51,7 @@ mod imp { } /// Error that can occur while using this crate. -#[derive(primitives::RuntimeDebug)] +#[derive(sp_core::RuntimeDebug)] pub enum Error { /// Module is not valid, couldn't be instantiated. Module, diff --git a/substrate/primitives/sandbox/without_std.rs b/substrate/primitives/sandbox/without_std.rs index 68956db8bf..e76bbe7285 100755 --- a/substrate/primitives/sandbox/without_std.rs +++ b/substrate/primitives/sandbox/without_std.rs @@ -14,11 +14,11 @@ // You should have received a copy of the GNU General Public License // along with Substrate. If not, see . -use sp_std::{prelude::*, slice, marker, mem, vec, rc::Rc}; use codec::{Decode, Encode}; -use primitives::sandbox as sandbox_primitives; -use super::{Error, TypedValue, ReturnValue, HostFuncType}; +use sp_core::sandbox as sandbox_primitives; use sp_io::sandbox; +use sp_std::{prelude::*, slice, marker, mem, vec, rc::Rc}; +use super::{Error, TypedValue, ReturnValue, HostFuncType}; mod ffi { use sp_std::mem; diff --git a/substrate/primitives/state-machine/Cargo.toml b/substrate/primitives/state-machine/Cargo.toml index cd721c17fd..73e943011c 100644 --- a/substrate/primitives/state-machine/Cargo.toml +++ b/substrate/primitives/state-machine/Cargo.toml @@ -11,13 +11,13 @@ parking_lot = "0.9.0" hash-db = "0.15.2" trie-db = "0.16.0" trie-root = "0.15.2" -trie = { package = "sp-trie", path = "../trie" } -primitives = { package = "sp-core", path = "../core" } -panic-handler = { package = "sp-panic-handler", path = "../panic-handler" } +sp-trie = { path = "../trie" } +sp-core = { path = "../core" } +sp-panic-handler = { path = "../panic-handler" } codec = { package = "parity-scale-codec", version = "1.0.0" } num-traits = "0.2.8" rand = "0.7.2" -externalities = { package = "sp-externalities", path = "../externalities" } +sp-externalities = { path = "../externalities" } [dev-dependencies] hex-literal = "0.2.1" diff --git a/substrate/primitives/state-machine/src/backend.rs b/substrate/primitives/state-machine/src/backend.rs index 8a6ba25731..7a5357c398 100644 --- a/substrate/primitives/state-machine/src/backend.rs +++ b/substrate/primitives/state-machine/src/backend.rs @@ -21,12 +21,12 @@ use log::warn; use hash_db::Hasher; use crate::trie_backend::TrieBackend; use crate::trie_backend_essence::TrieBackendStorage; -use trie::{ +use sp_trie::{ TrieMut, MemoryDB, child_trie_root, default_child_trie_root, TrieConfiguration, trie_types::{TrieDBMut, Layout}, }; use codec::{Encode, Codec}; -use primitives::storage::{ChildInfo, OwnedChildInfo, Storage}; +use sp_core::storage::{ChildInfo, OwnedChildInfo, Storage}; /// A state backend is used to read state data and can have changes committed /// to it. @@ -311,9 +311,9 @@ impl Consolidate for Vec<( } } -impl> Consolidate for trie::GenericMemoryDB { +impl> Consolidate for sp_trie::GenericMemoryDB { fn consolidate(&mut self, other: Self) { - trie::GenericMemoryDB::consolidate(self, other) + sp_trie::GenericMemoryDB::consolidate(self, other) } } @@ -564,7 +564,7 @@ impl Backend for InMemory where H::Out: Codec { let storage_key = storage_key.to_vec(); let child_info = Some((storage_key.clone(), child_info.to_owned())); - + let existing_pairs = self.inner.get(&child_info) .into_iter() .flat_map(|map| map.iter().map(|(k, v)| (k.clone(), Some(v.clone())))); @@ -667,7 +667,7 @@ mod tests { /// Assert in memory backend with only child trie keys works as trie backend. #[test] fn in_memory_with_child_trie_only() { - let storage = InMemory::::default(); + let storage = InMemory::::default(); let child_info = OwnedChildInfo::new_default(b"unique_id_1".to_vec()); let mut storage = storage.update( vec![( diff --git a/substrate/primitives/state-machine/src/basic.rs b/substrate/primitives/state-machine/src/basic.rs index 62503bdee1..641d3b531c 100644 --- a/substrate/primitives/state-machine/src/basic.rs +++ b/substrate/primitives/state-machine/src/basic.rs @@ -21,9 +21,9 @@ use std::{ }; use crate::backend::{Backend, InMemory}; use hash_db::Hasher; -use trie::{TrieConfiguration, default_child_trie_root}; -use trie::trie_types::Layout; -use primitives::{ +use sp_trie::{TrieConfiguration, default_child_trie_root}; +use sp_trie::trie_types::Layout; +use sp_core::{ storage::{ well_known_keys::is_child_storage_key, ChildStorageKey, Storage, ChildInfo, StorageChild, @@ -59,7 +59,7 @@ impl BasicExternalities { /// /// Returns the result of the closure and updates `storage` with all changes. pub fn execute_with_storage( - storage: &mut primitives::storage::Storage, + storage: &mut sp_core::storage::Storage, f: impl FnOnce() -> R, ) -> R { let mut ext = Self { inner: Storage { @@ -78,7 +78,7 @@ impl BasicExternalities { /// /// Returns the result of the given closure. pub fn execute_with(&mut self, f: impl FnOnce() -> R) -> R { - externalities::set_and_run_with_externalities(self, f) + sp_externalities::set_and_run_with_externalities(self, f) } } @@ -300,7 +300,7 @@ impl Externalities for BasicExternalities { } } -impl externalities::ExtensionStore for BasicExternalities { +impl sp_externalities::ExtensionStore for BasicExternalities { fn extension_by_type_id(&mut self, _: TypeId) -> Option<&mut dyn Any> { warn!("Extensions are not supported by `BasicExternalities`."); None @@ -310,9 +310,9 @@ impl externalities::ExtensionStore for BasicExternalities { #[cfg(test)] mod tests { use super::*; - use primitives::map; - use primitives::storage::{Storage, StorageChild}; - use primitives::storage::well_known_keys::CODE; + use sp_core::map; + use sp_core::storage::{Storage, StorageChild}; + use sp_core::storage::well_known_keys::CODE; use hex_literal::hex; const CHILD_INFO_1: ChildInfo<'static> = ChildInfo::new_default(b"unique_id_1"); diff --git a/substrate/primitives/state-machine/src/changes_trie/build.rs b/substrate/primitives/state-machine/src/changes_trie/build.rs index 4bb7b6c0aa..356c8614e2 100644 --- a/substrate/primitives/state-machine/src/changes_trie/build.rs +++ b/substrate/primitives/state-machine/src/changes_trie/build.rs @@ -153,7 +153,7 @@ fn prepare_extrinsics_input_inner<'a, B, H, Number>( // AND are not in storage at the beginning of operation if let Some(sk) = storage_key.as_ref() { if !changes.child_storage(sk, k).map(|v| v.is_some()).unwrap_or_default() { - if let Some(child_info) = child_info.as_ref() { + if let Some(child_info) = child_info.as_ref() { if !backend.exists_child_storage(sk, child_info.as_ref(), k) .map_err(|e| format!("{}", e))? { return Ok(map); @@ -338,9 +338,9 @@ fn prepare_digest_input<'a, H, Number>( #[cfg(test)] mod test { use codec::Encode; - use primitives::Blake2Hasher; - use primitives::storage::well_known_keys::{EXTRINSIC_INDEX}; - use primitives::storage::ChildInfo; + use sp_core::Blake2Hasher; + use sp_core::storage::well_known_keys::{EXTRINSIC_INDEX}; + use sp_core::storage::ChildInfo; use crate::backend::InMemory; use crate::changes_trie::{RootsStorage, Configuration, storage::InMemoryStorage}; use crate::changes_trie::build_cache::{IncompleteCacheAction, IncompleteCachedBuildData}; diff --git a/substrate/primitives/state-machine/src/changes_trie/changes_iterator.rs b/substrate/primitives/state-machine/src/changes_trie/changes_iterator.rs index 017eb33d52..f62575f451 100644 --- a/substrate/primitives/state-machine/src/changes_trie/changes_iterator.rs +++ b/substrate/primitives/state-machine/src/changes_trie/changes_iterator.rs @@ -22,7 +22,7 @@ use std::collections::VecDeque; use codec::{Decode, Encode, Codec}; use hash_db::Hasher; use num_traits::Zero; -use trie::Recorder; +use sp_trie::Recorder; use crate::changes_trie::{AnchorBlockId, ConfigurationRange, RootsStorage, Storage, BlockNumber}; use crate::changes_trie::input::{DigestIndex, ExtrinsicIndex, DigestIndexValue, ExtrinsicIndexValue}; use crate::changes_trie::storage::{TrieBackendAdapter, InMemoryStorage}; @@ -376,7 +376,7 @@ impl<'a, H, Number> Iterator for ProvingDrilldownIterator<'a, H, Number> #[cfg(test)] mod tests { use std::iter::FromIterator; - use primitives::Blake2Hasher; + use sp_core::Blake2Hasher; use crate::changes_trie::Configuration; use crate::changes_trie::input::InputPair; use crate::changes_trie::storage::InMemoryStorage; diff --git a/substrate/primitives/state-machine/src/changes_trie/mod.rs b/substrate/primitives/state-machine/src/changes_trie/mod.rs index 0542ec6268..54eaa967c7 100644 --- a/substrate/primitives/state-machine/src/changes_trie/mod.rs +++ b/substrate/primitives/state-machine/src/changes_trie/mod.rs @@ -71,12 +71,12 @@ use hash_db::{Hasher, Prefix}; use crate::backend::Backend; use num_traits::{One, Zero}; use codec::{Decode, Encode}; -use primitives; +use sp_core; use crate::changes_trie::build::prepare_input; use crate::changes_trie::build_cache::{IncompleteCachedBuildData, IncompleteCacheAction}; use crate::overlayed_changes::OverlayedChanges; -use trie::{MemoryDB, DBValue, TrieMut}; -use trie::trie_types::TrieDBMut; +use sp_trie::{MemoryDB, DBValue, TrieMut}; +use sp_trie::trie_types::TrieDBMut; /// Changes that are made outside of extrinsics are marked with this index; pub const NO_EXTRINSIC_INDEX: u32 = 0xffffffff; @@ -149,7 +149,7 @@ pub trait Storage: RootsStorage { pub struct TrieBackendStorageAdapter<'a, H: Hasher, Number: BlockNumber>(pub &'a dyn Storage); impl<'a, H: Hasher, N: BlockNumber> crate::TrieBackendStorage for TrieBackendStorageAdapter<'a, H, N> { - type Overlay = trie::MemoryDB; + type Overlay = sp_trie::MemoryDB; fn get(&self, key: &H::Out, prefix: Prefix) -> Result, String> { self.0.get(key, prefix) @@ -157,7 +157,7 @@ impl<'a, H: Hasher, N: BlockNumber> crate::TrieBackendStorage for TrieBackend } /// Changes trie configuration. -pub type Configuration = primitives::ChangesTrieConfiguration; +pub type Configuration = sp_core::ChangesTrieConfiguration; /// Blocks range where configuration has been constant. #[derive(Clone)] diff --git a/substrate/primitives/state-machine/src/changes_trie/prune.rs b/substrate/primitives/state-machine/src/changes_trie/prune.rs index 2f39f9162c..c6d305ddf9 100644 --- a/substrate/primitives/state-machine/src/changes_trie/prune.rs +++ b/substrate/primitives/state-machine/src/changes_trie/prune.rs @@ -17,7 +17,7 @@ //! Changes trie pruning-related functions. use hash_db::Hasher; -use trie::Recorder; +use sp_trie::Recorder; use log::warn; use num_traits::{One, Zero}; use crate::proving_backend::ProvingBackendRecorder; @@ -202,8 +202,8 @@ fn max_digest_intervals_to_keep( #[cfg(test)] mod tests { use std::collections::HashSet; - use trie::MemoryDB; - use primitives::Blake2Hasher; + use sp_trie::MemoryDB; + use sp_core::Blake2Hasher; use crate::backend::insert_into_memory_db; use crate::changes_trie::storage::InMemoryStorage; use codec::Encode; diff --git a/substrate/primitives/state-machine/src/changes_trie/storage.rs b/substrate/primitives/state-machine/src/changes_trie/storage.rs index a82477bdc3..f9a03b6c2e 100644 --- a/substrate/primitives/state-machine/src/changes_trie/storage.rs +++ b/substrate/primitives/state-machine/src/changes_trie/storage.rs @@ -18,8 +18,8 @@ use std::collections::{BTreeMap, HashSet, HashMap}; use hash_db::{Hasher, Prefix, EMPTY_PREFIX}; -use trie::DBValue; -use trie::MemoryDB; +use sp_trie::DBValue; +use sp_trie::MemoryDB; use parking_lot::RwLock; use crate::changes_trie::{BuildCache, RootsStorage, Storage, AnchorBlockId, BlockNumber}; use crate::trie_backend_essence::TrieBackendStorage; diff --git a/substrate/primitives/state-machine/src/ext.rs b/substrate/primitives/state-machine/src/ext.rs index 9e7baea45e..32dcba634e 100644 --- a/substrate/primitives/state-machine/src/ext.rs +++ b/substrate/primitives/state-machine/src/ext.rs @@ -24,12 +24,12 @@ use crate::{ }; use hash_db::Hasher; -use primitives::{ +use sp_core::{ storage::{ChildStorageKey, well_known_keys::is_child_storage_key, ChildInfo}, traits::Externalities, hexdisplay::HexDisplay, hash::H256, }; -use trie::{trie_types::Layout, MemoryDB, default_child_trie_root}; -use externalities::Extensions; +use sp_trie::{trie_types::Layout, MemoryDB, default_child_trie_root}; +use sp_externalities::Extensions; use codec::{Decode, Encode}; use std::{error, fmt, any::{Any, TypeId}}; @@ -179,7 +179,7 @@ where N: crate::changes_trie::BlockNumber, { fn storage(&self, key: &[u8]) -> Option> { - let _guard = panic_handler::AbortGuard::force_abort(); + let _guard = sp_panic_handler::AbortGuard::force_abort(); let result = self.overlay.storage(key).map(|x| x.map(|x| x.to_vec())).unwrap_or_else(|| self.backend.storage(key).expect(EXT_NOT_ALLOWED_TO_FAIL)); trace!(target: "state-trace", "{:04x}: Get {}={:?}", @@ -191,7 +191,7 @@ where } fn storage_hash(&self, key: &[u8]) -> Option> { - let _guard = panic_handler::AbortGuard::force_abort(); + let _guard = sp_panic_handler::AbortGuard::force_abort(); let result = self.overlay .storage(key) .map(|x| x.map(|x| H::hash(x))) @@ -206,7 +206,7 @@ where } fn original_storage(&self, key: &[u8]) -> Option> { - let _guard = panic_handler::AbortGuard::force_abort(); + let _guard = sp_panic_handler::AbortGuard::force_abort(); let result = self.backend.storage(key).expect(EXT_NOT_ALLOWED_TO_FAIL); trace!(target: "state-trace", "{:04x}: GetOriginal {}={:?}", @@ -218,7 +218,7 @@ where } fn original_storage_hash(&self, key: &[u8]) -> Option> { - let _guard = panic_handler::AbortGuard::force_abort(); + let _guard = sp_panic_handler::AbortGuard::force_abort(); let result = self.backend.storage_hash(key).expect(EXT_NOT_ALLOWED_TO_FAIL); trace!(target: "state-trace", "{:04x}: GetOriginalHash {}={:?}", @@ -235,7 +235,7 @@ where child_info: ChildInfo, key: &[u8], ) -> Option> { - let _guard = panic_handler::AbortGuard::force_abort(); + let _guard = sp_panic_handler::AbortGuard::force_abort(); let result = self.overlay .child_storage(storage_key.as_ref(), key) .map(|x| x.map(|x| x.to_vec())) @@ -260,7 +260,7 @@ where _child_info: ChildInfo, key: &[u8], ) -> Option> { - let _guard = panic_handler::AbortGuard::force_abort(); + let _guard = sp_panic_handler::AbortGuard::force_abort(); let result = self.overlay .child_storage(storage_key.as_ref(), key) .map(|x| x.map(|x| H::hash(x))) @@ -284,7 +284,7 @@ where child_info: ChildInfo, key: &[u8], ) -> Option> { - let _guard = panic_handler::AbortGuard::force_abort(); + let _guard = sp_panic_handler::AbortGuard::force_abort(); let result = self.backend .child_storage(storage_key.as_ref(), child_info, key) .expect(EXT_NOT_ALLOWED_TO_FAIL); @@ -304,7 +304,7 @@ where child_info: ChildInfo, key: &[u8], ) -> Option> { - let _guard = panic_handler::AbortGuard::force_abort(); + let _guard = sp_panic_handler::AbortGuard::force_abort(); let result = self.backend .child_storage_hash(storage_key.as_ref(), child_info, key) .expect(EXT_NOT_ALLOWED_TO_FAIL); @@ -319,7 +319,7 @@ where } fn exists_storage(&self, key: &[u8]) -> bool { - let _guard = panic_handler::AbortGuard::force_abort(); + let _guard = sp_panic_handler::AbortGuard::force_abort(); let result = match self.overlay.storage(key) { Some(x) => x.is_some(), _ => self.backend.exists_storage(key).expect(EXT_NOT_ALLOWED_TO_FAIL), @@ -340,7 +340,7 @@ where child_info: ChildInfo, key: &[u8], ) -> bool { - let _guard = panic_handler::AbortGuard::force_abort(); + let _guard = sp_panic_handler::AbortGuard::force_abort(); let result = match self.overlay.child_storage(storage_key.as_ref(), key) { Some(x) => x.is_some(), @@ -408,7 +408,7 @@ where HexDisplay::from(&key), value.as_ref().map(HexDisplay::from) ); - let _guard = panic_handler::AbortGuard::force_abort(); + let _guard = sp_panic_handler::AbortGuard::force_abort(); if is_child_storage_key(&key) { warn!(target: "trie", "Refuse to directly set child storage key"); return; @@ -431,7 +431,7 @@ where HexDisplay::from(&key), value.as_ref().map(HexDisplay::from) ); - let _guard = panic_handler::AbortGuard::force_abort(); + let _guard = sp_panic_handler::AbortGuard::force_abort(); self.mark_dirty(); self.overlay.set_child_storage(storage_key.into_owned(), child_info, key, value); @@ -446,7 +446,7 @@ where self.id, HexDisplay::from(&storage_key.as_ref()), ); - let _guard = panic_handler::AbortGuard::force_abort(); + let _guard = sp_panic_handler::AbortGuard::force_abort(); self.mark_dirty(); self.overlay.clear_child_storage(storage_key.as_ref(), child_info); @@ -460,7 +460,7 @@ where self.id, HexDisplay::from(&prefix), ); - let _guard = panic_handler::AbortGuard::force_abort(); + let _guard = sp_panic_handler::AbortGuard::force_abort(); if is_child_storage_key(prefix) { warn!(target: "trie", "Refuse to directly clear prefix that is part of child storage key"); return; @@ -484,7 +484,7 @@ where HexDisplay::from(&storage_key.as_ref()), HexDisplay::from(&prefix), ); - let _guard = panic_handler::AbortGuard::force_abort(); + let _guard = sp_panic_handler::AbortGuard::force_abort(); self.mark_dirty(); self.overlay.clear_child_prefix(storage_key.as_ref(), child_info, prefix); @@ -498,7 +498,7 @@ where } fn storage_root(&mut self) -> Vec { - let _guard = panic_handler::AbortGuard::force_abort(); + let _guard = sp_panic_handler::AbortGuard::force_abort(); if let Some((_, ref root)) = self.storage_transaction { trace!(target: "state-trace", "{:04x}: Root (cached) {}", self.id, @@ -543,7 +543,7 @@ where &mut self, storage_key: ChildStorageKey, ) -> Vec { - let _guard = panic_handler::AbortGuard::force_abort(); + let _guard = sp_panic_handler::AbortGuard::force_abort(); if self.storage_transaction.is_some() { let root = self .storage(storage_key.as_ref()) @@ -611,7 +611,7 @@ where } fn storage_changes_root(&mut self, parent_hash: &[u8]) -> Result>, ()> { - let _guard = panic_handler::AbortGuard::force_abort(); + let _guard = sp_panic_handler::AbortGuard::force_abort(); self.changes_trie_transaction = build_changes_trie::<_, T, H, N>( self.backend, @@ -638,7 +638,7 @@ where } } -impl<'a, H, B, T, N> externalities::ExtensionStore for Ext<'a, H, N, B, T> +impl<'a, H, B, T, N> sp_externalities::ExtensionStore for Ext<'a, H, N, B, T> where H: Hasher, B: 'a + Backend, @@ -655,14 +655,14 @@ mod tests { use super::*; use hex_literal::hex; use codec::Encode; - use primitives::{Blake2Hasher, storage::well_known_keys::EXTRINSIC_INDEX, map}; + use sp_core::{Blake2Hasher, storage::well_known_keys::EXTRINSIC_INDEX, map}; use crate::{ changes_trie::{ Configuration as ChangesTrieConfiguration, InMemoryStorage as InMemoryChangesTrieStorage, }, backend::InMemory, overlayed_changes::OverlayedValue, }; - use primitives::storage::{Storage, StorageChild}; + use sp_core::storage::{Storage, StorageChild}; type TestBackend = InMemory; type TestChangesTrieStorage = InMemoryChangesTrieStorage; diff --git a/substrate/primitives/state-machine/src/lib.rs b/substrate/primitives/state-machine/src/lib.rs index e8043829e7..86cae2dfbb 100644 --- a/substrate/primitives/state-machine/src/lib.rs +++ b/substrate/primitives/state-machine/src/lib.rs @@ -22,12 +22,12 @@ use std::{fmt, result, collections::HashMap, panic::UnwindSafe, marker::PhantomD use log::{warn, trace}; use hash_db::Hasher; use codec::{Decode, Encode, Codec}; -use primitives::{ +use sp_core::{ storage::{well_known_keys, ChildInfo}, NativeOrEncoded, NeverNativeValue, traits::CodeExecutor, hexdisplay::HexDisplay, hash::H256, }; use overlayed_changes::OverlayedChangeSet; -use externalities::Extensions; +use sp_externalities::Extensions; pub mod backend; mod changes_trie; @@ -40,7 +40,7 @@ mod proving_backend; mod trie_backend; mod trie_backend_essence; -pub use trie::{trie_types::{Layout, TrieDBMut}, TrieMut, DBValue, MemoryDB}; +pub use sp_trie::{trie_types::{Layout, TrieDBMut}, TrieMut, DBValue, MemoryDB}; pub use testing::TestExternalities; pub use basic::BasicExternalities; pub use ext::Ext; @@ -424,7 +424,7 @@ impl<'a, B, H, N, T, Exec> StateMachine<'a, B, H, N, T, Exec> where ExecutionManager::AlwaysWasm(trust_level) => { let _abort_guard = match trust_level { BackendTrustLevel::Trusted => None, - BackendTrustLevel::Untrusted => Some(panic_handler::AbortGuard::never_abort()), + BackendTrustLevel::Untrusted => Some(sp_panic_handler::AbortGuard::never_abort()), }; let res = self.execute_aux(compute_tx, false, native_call); (res.0, res.2, res.3) @@ -745,7 +745,7 @@ mod tests { InMemoryStorage as InMemoryChangesTrieStorage, Configuration as ChangesTrieConfig, }; - use primitives::{Blake2Hasher, map, traits::Externalities, storage::ChildStorageKey}; + use sp_core::{Blake2Hasher, map, traits::Externalities, storage::ChildStorageKey}; struct DummyCodeExecutor { change_changes_trie_config: bool, diff --git a/substrate/primitives/state-machine/src/overlayed_changes.rs b/substrate/primitives/state-machine/src/overlayed_changes.rs index 0714120ae3..f4e0de5045 100644 --- a/substrate/primitives/state-machine/src/overlayed_changes.rs +++ b/substrate/primitives/state-machine/src/overlayed_changes.rs @@ -21,7 +21,7 @@ use std::iter::FromIterator; use std::collections::{HashMap, BTreeMap, BTreeSet}; use codec::Decode; use crate::changes_trie::{NO_EXTRINSIC_INDEX, Configuration as ChangesTrieConfig}; -use primitives::storage::{well_known_keys::EXTRINSIC_INDEX, OwnedChildInfo, ChildInfo}; +use sp_core::storage::{well_known_keys::EXTRINSIC_INDEX, OwnedChildInfo, ChildInfo}; use std::{mem, ops}; /// The overlayed changes to state to be queried on top of the backend. @@ -442,7 +442,7 @@ impl From>> for OverlayedValue { #[cfg(test)] mod tests { use hex_literal::hex; - use primitives::{ + use sp_core::{ Blake2Hasher, traits::Externalities, storage::well_known_keys::EXTRINSIC_INDEX, }; use crate::backend::InMemory; diff --git a/substrate/primitives/state-machine/src/proving_backend.rs b/substrate/primitives/state-machine/src/proving_backend.rs index 3809ac8446..92ad2047a5 100644 --- a/substrate/primitives/state-machine/src/proving_backend.rs +++ b/substrate/primitives/state-machine/src/proving_backend.rs @@ -21,18 +21,18 @@ use parking_lot::RwLock; use codec::{Decode, Encode, Codec}; use log::debug; use hash_db::{Hasher, HashDB, EMPTY_PREFIX, Prefix}; -use trie::{ +use sp_trie::{ MemoryDB, PrefixedMemoryDB, default_child_trie_root, read_trie_value_with, read_child_trie_value_with, record_all_keys }; -pub use trie::Recorder; -pub use trie::trie_types::{Layout, TrieError}; +pub use sp_trie::Recorder; +pub use sp_trie::trie_types::{Layout, TrieError}; use crate::trie_backend::TrieBackend; use crate::trie_backend_essence::{Ephemeral, TrieBackendEssence, TrieBackendStorage}; use crate::{Error, ExecutionError, Backend}; use std::collections::{HashMap, HashSet}; use crate::DBValue; -use primitives::storage::ChildInfo; +use sp_core::storage::ChildInfo; /// Patricia trie-based backend specialized in get value proofs. pub struct ProvingBackendRecorder<'a, S: 'a + TrieBackendStorage, H: 'a + Hasher> { @@ -394,7 +394,7 @@ mod tests { use crate::backend::{InMemory}; use crate::trie_backend::tests::test_trie; use super::*; - use primitives::{Blake2Hasher, storage::ChildStorageKey}; + use sp_core::{Blake2Hasher, storage::ChildStorageKey}; use crate::proving_backend::create_proof_check_backend; const CHILD_INFO_1: ChildInfo<'static> = ChildInfo::new_default(b"unique_id_1"); @@ -422,7 +422,7 @@ mod tests { #[test] fn proof_is_invalid_when_does_not_contains_root() { - use primitives::H256; + use sp_core::H256; let result = create_proof_check_backend::( H256::from_low_u64_be(1), StorageProof::empty() diff --git a/substrate/primitives/state-machine/src/testing.rs b/substrate/primitives/state-machine/src/testing.rs index a37cd8caef..7bb7e7320b 100644 --- a/substrate/primitives/state-machine/src/testing.rs +++ b/substrate/primitives/state-machine/src/testing.rs @@ -26,7 +26,7 @@ use crate::{ }, ext::Ext, }; -use primitives::{ +use sp_core::{ storage::{ well_known_keys::{CHANGES_TRIE_CONFIG, CODE, HEAP_PAGES, is_child_storage_key}, Storage, @@ -34,7 +34,7 @@ use primitives::{ hash::H256, Blake2Hasher, }; use codec::Encode; -use externalities::{Extensions, Extension}; +use sp_externalities::{Extensions, Extension}; /// Simple HashMap-based Externalities impl. pub struct TestExternalities=Blake2Hasher, N: ChangesTrieBlockNumber=u64> { @@ -125,7 +125,7 @@ impl, N: ChangesTrieBlockNumber> TestExternalities { /// Returns the result of the given closure. pub fn execute_with(&mut self, execute: impl FnOnce() -> R) -> R { let mut ext = self.ext(); - externalities::set_and_run_with_externalities(&mut ext, execute) + sp_externalities::set_and_run_with_externalities(&mut ext, execute) } } @@ -153,7 +153,7 @@ impl, N: ChangesTrieBlockNumber> From for TestExter } } -impl externalities::ExtensionStore for TestExternalities where +impl sp_externalities::ExtensionStore for TestExternalities where H: Hasher, N: ChangesTrieBlockNumber, { @@ -165,7 +165,7 @@ impl externalities::ExtensionStore for TestExternalities where #[cfg(test)] mod tests { use super::*; - use primitives::traits::Externalities; + use sp_core::traits::Externalities; use hex_literal::hex; #[test] diff --git a/substrate/primitives/state-machine/src/trie_backend.rs b/substrate/primitives/state-machine/src/trie_backend.rs index 5286f0e505..4b48bec31b 100644 --- a/substrate/primitives/state-machine/src/trie_backend.rs +++ b/substrate/primitives/state-machine/src/trie_backend.rs @@ -18,11 +18,11 @@ use log::{warn, debug}; use hash_db::Hasher; -use trie::{Trie, delta_trie_root, default_child_trie_root, child_delta_trie_root}; -use trie::trie_types::{TrieDB, TrieError, Layout}; +use sp_trie::{Trie, delta_trie_root, default_child_trie_root, child_delta_trie_root}; +use sp_trie::trie_types::{TrieDB, TrieError, Layout}; use crate::trie_backend_essence::{TrieBackendEssence, TrieBackendStorage, Ephemeral}; use crate::Backend; -use primitives::storage::ChildInfo; +use sp_core::storage::ChildInfo; use codec::{Codec, Decode}; /// Patricia trie-based backend. Transaction type is an overlay of changes to commit. @@ -243,9 +243,9 @@ impl, H: Hasher> Backend for TrieBackend where #[cfg(test)] pub mod tests { use std::collections::HashSet; - use primitives::{Blake2Hasher, H256}; + use sp_core::{Blake2Hasher, H256}; use codec::Encode; - use trie::{TrieMut, PrefixedMemoryDB, trie_types::TrieDBMut, KeySpacedDBMut}; + use sp_trie::{TrieMut, PrefixedMemoryDB, trie_types::TrieDBMut, KeySpacedDBMut}; use super::*; const CHILD_KEY_1: &[u8] = b":child_storage:default:sub1"; diff --git a/substrate/primitives/state-machine/src/trie_backend_essence.rs b/substrate/primitives/state-machine/src/trie_backend_essence.rs index cd8f686a92..75601373ed 100644 --- a/substrate/primitives/state-machine/src/trie_backend_essence.rs +++ b/substrate/primitives/state-machine/src/trie_backend_essence.rs @@ -21,12 +21,12 @@ use std::ops::Deref; use std::sync::Arc; use log::{debug, warn}; use hash_db::{self, Hasher, EMPTY_PREFIX, Prefix}; -use trie::{Trie, MemoryDB, PrefixedMemoryDB, DBValue, +use sp_trie::{Trie, MemoryDB, PrefixedMemoryDB, DBValue, default_child_trie_root, read_trie_value, read_child_trie_value, for_keys_in_child_trie, KeySpacedDB}; -use trie::trie_types::{TrieDB, TrieError, Layout}; +use sp_trie::trie_types::{TrieDB, TrieError, Layout}; use crate::backend::Consolidate; -use primitives::storage::ChildInfo; +use sp_core::storage::ChildInfo; use codec::Encode; /// Patricia trie-based storage trait. @@ -250,7 +250,7 @@ impl, H: Hasher> TrieBackendEssence where H::Out: storage: &self.storage, overlay: &mut read_overlay, }; - + let mut iter = move |db| -> Result<(), Box>> { let trie = TrieDB::::new(db, root)?; let mut iter = trie.iter()?; @@ -448,8 +448,8 @@ impl TrieBackendStorage for MemoryDB { #[cfg(test)] mod test { - use primitives::{Blake2Hasher, H256}; - use trie::{TrieMut, PrefixedMemoryDB, trie_types::TrieDBMut, KeySpacedDBMut}; + use sp_core::{Blake2Hasher, H256}; + use sp_trie::{TrieMut, PrefixedMemoryDB, trie_types::TrieDBMut, KeySpacedDBMut}; use super::*; #[test] diff --git a/substrate/primitives/test-primitives/Cargo.toml b/substrate/primitives/test-primitives/Cargo.toml index d8d66e91c4..1301887241 100644 --- a/substrate/primitives/test-primitives/Cargo.toml +++ b/substrate/primitives/test-primitives/Cargo.toml @@ -5,9 +5,9 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -app-crypto = { package = "sp-application-crypto", path = "../application-crypto", default-features = false } +sp-application-crypto = { path = "../application-crypto", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } -primitives = { package = "sp-core", path = "../core", default-features = false } +sp-core = { path = "../core", default-features = false } serde = { version = "1.0.101", optional = true, features = ["derive"] } sp-runtime = { path = "../runtime", default-features = false } @@ -16,6 +16,6 @@ default = [ "std", ] std = [ - "app-crypto/std", + "sp-application-crypto/std", "serde", ] diff --git a/substrate/primitives/test-primitives/src/lib.rs b/substrate/primitives/test-primitives/src/lib.rs index 4acf10bbdf..d95b9cb3e2 100644 --- a/substrate/primitives/test-primitives/src/lib.rs +++ b/substrate/primitives/test-primitives/src/lib.rs @@ -20,10 +20,10 @@ use codec::{Encode, Decode}; -use app_crypto::sr25519; -pub use app_crypto; +use sp_application_crypto::sr25519; +pub use sp_application_crypto; -pub use primitives::{hash::H256, RuntimeDebug}; +pub use sp_core::{hash::H256, RuntimeDebug}; use sp_runtime::traits::{BlakeTwo256, Verify, Extrinsic as ExtrinsicT,}; /// Extrinsic for test-runtime. @@ -79,8 +79,8 @@ pub type Header = sp_runtime::generic::Header; /// Changes trie configuration (optionally) used in tests. -pub fn changes_trie_config() -> primitives::ChangesTrieConfiguration { - primitives::ChangesTrieConfiguration { +pub fn changes_trie_config() -> sp_core::ChangesTrieConfiguration { + sp_core::ChangesTrieConfiguration { digest_interval: 4, digest_levels: 2, } diff --git a/substrate/primitives/timestamp/Cargo.toml b/substrate/primitives/timestamp/Cargo.toml index 8661a44a44..a11e4bce40 100644 --- a/substrate/primitives/timestamp/Cargo.toml +++ b/substrate/primitives/timestamp/Cargo.toml @@ -9,7 +9,7 @@ sp-api = { path = "../api", default-features = false } sp-std = { path = "../std", default-features = false } sp-runtime = { path = "../runtime", default-features = false } codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } -inherents = { package = "sp-inherents", path = "../inherents", default-features = false } +sp-inherents = { path = "../inherents", default-features = false } impl-trait-for-tuples = "0.1.3" [features] @@ -19,5 +19,5 @@ std = [ "sp-std/std", "sp-runtime/std", "codec/std", - "inherents/std", + "sp-inherents/std", ] diff --git a/substrate/primitives/timestamp/src/lib.rs b/substrate/primitives/timestamp/src/lib.rs index 6b20e11ef4..9306e14ca8 100644 --- a/substrate/primitives/timestamp/src/lib.rs +++ b/substrate/primitives/timestamp/src/lib.rs @@ -22,8 +22,8 @@ use codec::Encode; #[cfg(feature = "std")] use codec::Decode; #[cfg(feature = "std")] -use inherents::ProvideInherentData; -use inherents::{InherentIdentifier, IsFatalError, InherentData}; +use sp_inherents::ProvideInherentData; +use sp_inherents::{InherentIdentifier, IsFatalError, InherentData}; use sp_runtime::RuntimeString; @@ -67,11 +67,11 @@ impl InherentError { /// Auxiliary trait to extract timestamp inherent data. pub trait TimestampInherentData { /// Get timestamp inherent data. - fn timestamp_inherent_data(&self) -> Result; + fn timestamp_inherent_data(&self) -> Result; } impl TimestampInherentData for InherentData { - fn timestamp_inherent_data(&self) -> Result { + fn timestamp_inherent_data(&self) -> Result { self.get_data(&INHERENT_IDENTIFIER) .and_then(|r| r.ok_or_else(|| "Timestamp inherent data not found".into())) } @@ -89,7 +89,7 @@ impl ProvideInherentData for InherentDataProvider { fn provide_inherent_data( &self, inherent_data: &mut InherentData, - ) -> Result<(), inherents::Error> { + ) -> Result<(), sp_inherents::Error> { use std::time::SystemTime; let now = SystemTime::now(); diff --git a/substrate/primitives/trie/Cargo.toml b/substrate/primitives/trie/Cargo.toml index e77d5665b4..974246b0e4 100644 --- a/substrate/primitives/trie/Cargo.toml +++ b/substrate/primitives/trie/Cargo.toml @@ -18,7 +18,7 @@ hash-db = { version = "0.15.2", default-features = false } trie-db = { version = "0.16.0", default-features = false } trie-root = { version = "0.15.2", default-features = false } memory-db = { version = "0.15.2", default-features = false } -primitives = { package = "sp-core", path = "../core", default-features = false } +sp-core = { path = "../core", default-features = false } [dev-dependencies] trie-bench = "0.17.0" @@ -35,5 +35,5 @@ std = [ "memory-db/std", "trie-db/std", "trie-root/std", - "primitives/std", + "sp-core/std", ] diff --git a/substrate/primitives/trie/benches/bench.rs b/substrate/primitives/trie/benches/bench.rs index 347426d0c5..353644ee1e 100644 --- a/substrate/primitives/trie/benches/bench.rs +++ b/substrate/primitives/trie/benches/bench.rs @@ -20,11 +20,11 @@ criterion_main!(benches); fn benchmark(c: &mut Criterion) { trie_bench::standard_benchmark::< - sp_trie::Layout, + sp_trie::Layout, sp_trie::TrieStream, >(c, "substrate-blake2"); trie_bench::standard_benchmark::< - sp_trie::Layout, + sp_trie::Layout, sp_trie::TrieStream, >(c, "substrate-keccak"); } diff --git a/substrate/primitives/trie/src/lib.rs b/substrate/primitives/trie/src/lib.rs index 244752f44b..08f26e0063 100644 --- a/substrate/primitives/trie/src/lib.rs +++ b/substrate/primitives/trie/src/lib.rs @@ -425,7 +425,7 @@ mod trie_constants { mod tests { use super::*; use codec::{Encode, Compact}; - use primitives::Blake2Hasher; + use sp_core::Blake2Hasher; use hash_db::{HashDB, Hasher}; use trie_db::{DBValue, TrieMut, Trie, NodeCodec as NodeCodecT}; use trie_standardmap::{Alphabet, ValueMode, StandardMap}; diff --git a/substrate/primitives/trie/src/node_header.rs b/substrate/primitives/trie/src/node_header.rs index 34586d8b52..43d71e33b3 100644 --- a/substrate/primitives/trie/src/node_header.rs +++ b/substrate/primitives/trie/src/node_header.rs @@ -22,7 +22,7 @@ use sp_std::iter::once; /// A node header #[derive(Copy, Clone, PartialEq, Eq)] -#[derive(primitives::RuntimeDebug)] +#[derive(sp_core::RuntimeDebug)] pub(crate) enum NodeHeader { Null, Branch(bool, usize), diff --git a/substrate/test-utils/client/Cargo.toml b/substrate/test-utils/client/Cargo.toml index d89a75d137..df0bb1738a 100644 --- a/substrate/test-utils/client/Cargo.toml +++ b/substrate/test-utils/client/Cargo.toml @@ -5,16 +5,16 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -client-api = { package = "sc-client-api", path = "../../client/api" } -client = { package = "sc-client", path = "../../client/" } -client-db = { package = "sc-client-db", path = "../../client//db", features = ["test-helpers"] } -consensus = { package = "sp-consensus", path = "../../primitives/consensus/common" } -executor = { package = "sc-executor", path = "../../client/executor" } +sc-client-api = { path = "../../client/api" } +sc-client = { path = "../../client/" } +sc-client-db = { path = "../../client/db", features = ["test-helpers"] } +sp-consensus = { path = "../../primitives/consensus/common" } +sc-executor = { path = "../../client/executor" } futures = "0.3.1" hash-db = "0.15.2" -keyring = { package = "sp-keyring", path = "../../primitives/keyring" } +sp-keyring = { path = "../../primitives/keyring" } codec = { package = "parity-scale-codec", version = "1.0.0" } -primitives = { package = "sp-core", path = "../../primitives/core" } +sp-core = { path = "../../primitives/core" } sp-runtime = { path = "../../primitives/runtime" } sp-blockchain = { path = "../../primitives/blockchain" } -state_machine = { package = "sp-state-machine", path = "../../primitives/state-machine" } +sp-state-machine = { path = "../../primitives/state-machine" } diff --git a/substrate/test-utils/client/src/client_ext.rs b/substrate/test-utils/client/src/client_ext.rs index 961d8570d8..f560d0f97b 100644 --- a/substrate/test-utils/client/src/client_ext.rs +++ b/substrate/test-utils/client/src/client_ext.rs @@ -16,9 +16,9 @@ //! Client extension for tests. -use client::{self, Client}; -use client_api::backend::Finalizer; -use consensus::{ +use sc_client::{self, Client}; +use sc_client_api::backend::Finalizer; +use sp_consensus::{ BlockImportParams, BlockImport, BlockOrigin, Error as ConsensusError, ForkChoiceStrategy, }; @@ -26,7 +26,7 @@ use hash_db::Hasher; use sp_runtime::Justification; use sp_runtime::traits::{Block as BlockT}; use sp_runtime::generic::BlockId; -use primitives::Blake2Hasher; +use sp_core::Blake2Hasher; use codec::alloc::collections::hash_map::HashMap; /// Extension trait for a test client. @@ -64,8 +64,8 @@ pub trait ClientExt: Sized { impl ClientExt for Client where - B: client_api::backend::Backend, - E: client::CallExecutor, + B: sc_client_api::backend::Backend, + E: sc_client::CallExecutor, for<'r> &'r Self: BlockImport, Block: BlockT::Out>, { diff --git a/substrate/test-utils/client/src/lib.rs b/substrate/test-utils/client/src/lib.rs index c6067e5d7c..2496409f87 100644 --- a/substrate/test-utils/client/src/lib.rs +++ b/substrate/test-utils/client/src/lib.rs @@ -20,31 +20,32 @@ pub mod client_ext; -pub use client::{blockchain, self}; -pub use client_api::execution_extensions::{ExecutionStrategies, ExecutionExtensions}; -pub use client_db::{Backend, self}; -pub use client_ext::ClientExt; -pub use consensus; -pub use executor::{NativeExecutor, WasmExecutionMethod, self}; -pub use keyring::{ +pub use sc_client::{blockchain, self}; +pub use sc_client_api::execution_extensions::{ExecutionStrategies, ExecutionExtensions}; +pub use sc_client_db::{Backend, self}; +pub use sp_consensus; +pub use sc_executor::{NativeExecutor, WasmExecutionMethod, self}; +pub use sp_keyring::{ AccountKeyring, ed25519::Keyring as Ed25519Keyring, sr25519::Keyring as Sr25519Keyring, }; -pub use primitives::{Blake2Hasher, traits::BareCryptoStorePtr}; +pub use sp_core::{Blake2Hasher, traits::BareCryptoStorePtr}; pub use sp_runtime::{Storage, StorageChild}; -pub use state_machine::ExecutionStrategy; +pub use sp_state_machine::ExecutionStrategy; + +pub use self::client_ext::ClientExt; use std::sync::Arc; use std::collections::HashMap; use hash_db::Hasher; -use primitives::storage::{well_known_keys, ChildInfo}; +use sp_core::storage::{well_known_keys, ChildInfo}; use sp_runtime::traits::Block as BlockT; -use client::LocalCallExecutor; +use sc_client::LocalCallExecutor; /// Test client light database backend. -pub type LightBackend = client::light::backend::Backend< - client_db::light::LightStorage, +pub type LightBackend = sc_client::light::backend::Backend< + sc_client_db::light::LightStorage, Blake2Hasher, >; @@ -168,16 +169,16 @@ impl TestClientBuilder self, executor: Executor, ) -> ( - client::Client< + sc_client::Client< Backend, Executor, Block, RuntimeApi, >, - client::LongestChain, + sc_client::LongestChain, ) where - Executor: client::CallExecutor, - Backend: client_api::backend::Backend, + Executor: sc_client::CallExecutor, + Backend: sc_client_api::backend::Backend, Block: BlockT::Out>, { @@ -198,7 +199,7 @@ impl TestClientBuilder storage }; - let client = client::Client::new( + let client = sc_client::Client::new( self.backend.clone(), executor, storage, @@ -209,14 +210,14 @@ impl TestClientBuilder ) ).expect("Creates new client"); - let longest_chain = client::LongestChain::new(self.backend); + let longest_chain = sc_client::LongestChain::new(self.backend); (client, longest_chain) } } impl TestClientBuilder< - client::LocalCallExecutor>, + sc_client::LocalCallExecutor>, Backend, G, > { @@ -225,17 +226,17 @@ impl TestClientBuilder< self, executor: I, ) -> ( - client::Client< + sc_client::Client< Backend, - client::LocalCallExecutor>, + sc_client::LocalCallExecutor>, Block, RuntimeApi >, - client::LongestChain, + sc_client::LongestChain, ) where I: Into>>, - E: executor::NativeExecutionDispatch, - Backend: client_api::backend::Backend, + E: sc_executor::NativeExecutionDispatch, + Backend: sc_client_api::backend::Backend, Block: BlockT::Out>, { let executor = executor.into().unwrap_or_else(|| diff --git a/substrate/test-utils/runtime/Cargo.toml b/substrate/test-utils/runtime/Cargo.toml index c669cd4141..66b97ac78e 100644 --- a/substrate/test-utils/runtime/Cargo.toml +++ b/substrate/test-utils/runtime/Cargo.toml @@ -6,26 +6,26 @@ edition = "2018" build = "build.rs" [dependencies] -app-crypto = { package = "sp-application-crypto", path = "../../primitives/application-crypto", default-features = false } -aura-primitives = { package = "sp-consensus-aura", path = "../../primitives/consensus/aura", default-features = false } -babe-primitives = { package = "sp-consensus-babe", path = "../../primitives/consensus/babe", default-features = false } -block-builder-api = { package = "sp-block-builder", path = "../../primitives/block-builder", default-features = false } +sp-application-crypto = { path = "../../primitives/application-crypto", default-features = false } +sp-consensus-aura = { path = "../../primitives/consensus/aura", default-features = false } +sp-consensus-babe = { path = "../../primitives/consensus/babe", default-features = false } +sp-block-builder = { path = "../../primitives/block-builder", default-features = false } cfg-if = "0.1.10" codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } -executive = { package = "frame-executive", path = "../../frame/executive", default-features = false } -inherents = { package = "sp-inherents", path = "../../primitives/inherents", default-features = false } -keyring = { package = "sp-keyring", path = "../../primitives/keyring", optional = true } +frame-executive = { path = "../../frame/executive", default-features = false } +sp-inherents = { path = "../../primitives/inherents", default-features = false } +sp-keyring = { path = "../../primitives/keyring", optional = true } log = { version = "0.4.8", optional = true } memory-db = { version = "0.15.2", default-features = false } -offchain-primitives = { package = "sp-offchain", path = "../../primitives/offchain", default-features = false} -primitives = { package = "sp-core", path = "../../primitives/core", default-features = false } +sp-offchain = { path = "../../primitives/offchain", default-features = false} +sp-core = { path = "../../primitives/core", default-features = false } sp-std = { path = "../../primitives/std", default-features = false } -runtime-interface = { package = "sp-runtime-interface", path = "../../primitives/runtime-interface", default-features = false} +sp-runtime-interface = { path = "../../primitives/runtime-interface", default-features = false} sp-io = { path = "../../primitives/io", default-features = false } -runtime_support = { package = "frame-support", path = "../../frame/support", default-features = false } -runtime_version = { package = "sp-version", path = "../../primitives/version", default-features = false } +frame-support = { path = "../../frame/support", default-features = false } +sp-version = { path = "../../primitives/version", default-features = false } serde = { version = "1.0.101", optional = true, features = ["derive"] } -session = { package = "sp-session", path = "../../primitives/session", default-features = false } +sp-session = { path = "../../primitives/session", default-features = false } sp-api = { path = "../../primitives/api", default-features = false } sp-runtime = { path = "../../primitives/runtime", default-features = false } pallet-babe = { path = "../../frame/babe", default-features = false } @@ -34,13 +34,13 @@ frame-system-rpc-runtime-api = { path = "../../frame/system/rpc/runtime-api", de pallet-timestamp = { path = "../../frame/timestamp", default-features = false } sc-client = { path = "../../client", optional = true } sp-trie = { path = "../../primitives/trie", default-features = false } -sp-transaction-pool = { package = "sp-transaction-pool", path = "../../primitives/transaction-pool", default-features = false } +sp-transaction-pool = { path = "../../primitives/transaction-pool", default-features = false } trie-db = { version = "0.16.0", default-features = false } [dev-dependencies] sc-executor = { path = "../../client/executor" } substrate-test-runtime-client = { path = "./client" } -state_machine = { package = "sp-state-machine", path = "../../primitives/state-machine" } +sp-state-machine = { path = "../../primitives/state-machine" } [build-dependencies] wasm-builder-runner = { package = "substrate-wasm-builder-runner", path = "../../utils/wasm-builder-runner", version = "1.0.4" } @@ -50,26 +50,26 @@ default = [ "std", ] std = [ - "app-crypto/std", - "aura-primitives/std", - "babe-primitives/std", - "block-builder-api/std", + "sp-application-crypto/std", + "sp-consensus-aura/std", + "sp-consensus-babe/std", + "sp-block-builder/std", "codec/std", - "executive/std", - "inherents/std", - "keyring", + "frame-executive/std", + "sp-inherents/std", + "sp-keyring", "log", "memory-db/std", - "offchain-primitives/std", - "primitives/std", - "primitives/std", + "sp-offchain/std", + "sp-core/std", + "sp-core/std", "sp-std/std", - "runtime-interface/std", + "sp-runtime-interface/std", "sp-io/std", - "runtime_support/std", - "runtime_version/std", + "frame-support/std", + "sp-version/std", "serde", - "session/std", + "sp-session/std", "sp-api/std", "sp-runtime/std", "pallet-babe/std", diff --git a/substrate/test-utils/runtime/client/Cargo.toml b/substrate/test-utils/runtime/client/Cargo.toml index 85b9928234..2ba3fab8d1 100644 --- a/substrate/test-utils/runtime/client/Cargo.toml +++ b/substrate/test-utils/runtime/client/Cargo.toml @@ -5,13 +5,13 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -block-builder = { package = "sc-block-builder", path = "../../../client/block-builder" } -generic-test-client = { package = "substrate-test-client", path = "../../client" } -primitives = { package = "sp-core", path = "../../../primitives/core" } -runtime = { package = "substrate-test-runtime", path = "../../runtime" } +sc-block-builder = { path = "../../../client/block-builder" } +substrate-test-client = { path = "../../client" } +sp-core = { path = "../../../primitives/core" } +substrate-test-runtime = { path = "../../runtime" } sp-runtime = { path = "../../../primitives/runtime" } sp-blockchain = { path = "../../../primitives/blockchain" } codec = { package = "parity-scale-codec", version = "1.0.0" } -client-api = { package = "sc-client-api", path = "../../../client/api" } -client = { package = "sc-client", path = "../../../client/" } +sc-client-api = { path = "../../../client/api" } +sc-client = { path = "../../../client/" } futures = "0.3.1" diff --git a/substrate/test-utils/runtime/client/src/block_builder_ext.rs b/substrate/test-utils/runtime/client/src/block_builder_ext.rs index a1065c82a0..5b98b1deb3 100644 --- a/substrate/test-utils/runtime/client/src/block_builder_ext.rs +++ b/substrate/test-utils/runtime/client/src/block_builder_ext.rs @@ -16,15 +16,15 @@ //! Block Builder extensions for tests. -use runtime; +use substrate_test_runtime; use sp_runtime::traits::ProvideRuntimeApi; -use block_builder::BlockBuilderApi; +use sc_block_builder::BlockBuilderApi; /// Extension trait for test block builder. pub trait BlockBuilderExt { /// Add transfer extrinsic to the block. - fn push_transfer(&mut self, transfer: runtime::Transfer) -> Result<(), sp_blockchain::Error>; + fn push_transfer(&mut self, transfer: substrate_test_runtime::Transfer) -> Result<(), sp_blockchain::Error>; /// Add storage change extrinsic to the block. fn push_storage_change( &mut self, @@ -33,11 +33,11 @@ pub trait BlockBuilderExt { ) -> Result<(), sp_blockchain::Error>; } -impl<'a, A> BlockBuilderExt for block_builder::BlockBuilder<'a, runtime::Block, A> where +impl<'a, A> BlockBuilderExt for sc_block_builder::BlockBuilder<'a, substrate_test_runtime::Block, A> where A: ProvideRuntimeApi + 'a, - A::Api: BlockBuilderApi, + A::Api: BlockBuilderApi, { - fn push_transfer(&mut self, transfer: runtime::Transfer) -> Result<(), sp_blockchain::Error> { + fn push_transfer(&mut self, transfer: substrate_test_runtime::Transfer) -> Result<(), sp_blockchain::Error> { self.push(transfer.into_signed_tx()) } @@ -46,6 +46,6 @@ impl<'a, A> BlockBuilderExt for block_builder::BlockBuilder<'a, runtime::Block, key: Vec, value: Option>, ) -> Result<(), sp_blockchain::Error> { - self.push(runtime::Extrinsic::StorageChange(key, value)) + self.push(substrate_test_runtime::Extrinsic::StorageChange(key, value)) } } diff --git a/substrate/test-utils/runtime/client/src/lib.rs b/substrate/test-utils/runtime/client/src/lib.rs index 13d9b19553..988fa56678 100644 --- a/substrate/test-utils/runtime/client/src/lib.rs +++ b/substrate/test-utils/runtime/client/src/lib.rs @@ -24,15 +24,16 @@ mod block_builder_ext; use std::sync::Arc; use std::collections::HashMap; -pub use block_builder_ext::BlockBuilderExt; -pub use generic_test_client::*; -pub use runtime; +pub use substrate_test_client::*; +pub use substrate_test_runtime as runtime; -use primitives::sr25519; -use primitives::storage::{ChildInfo, Storage, StorageChild}; -use runtime::genesismap::{GenesisConfig, additional_storage_with_genesis}; +pub use self::block_builder_ext::BlockBuilderExt; + +use sp_core::sr25519; +use sp_core::storage::{ChildInfo, Storage, StorageChild}; +use substrate_test_runtime::genesismap::{GenesisConfig, additional_storage_with_genesis}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT, Hash as HashT, NumberFor}; -use client::{ +use sc_client::{ light::fetcher::{ Fetcher, RemoteHeaderRequest, RemoteReadRequest, RemoteReadChildRequest, @@ -56,37 +57,37 @@ pub mod prelude { mod local_executor { #![allow(missing_docs)] - use runtime; - use crate::executor::native_executor_instance; + use substrate_test_runtime; + use crate::sc_executor::native_executor_instance; // FIXME #1576 change the macro and pass in the `BlakeHasher` that dispatch needs from here instead native_executor_instance!( pub LocalExecutor, - runtime::api::dispatch, - runtime::native_version + substrate_test_runtime::api::dispatch, + substrate_test_runtime::native_version ); } /// Native executor used for tests. -pub use local_executor::LocalExecutor; +pub use self::local_executor::LocalExecutor; /// Test client database backend. -pub type Backend = generic_test_client::Backend; +pub type Backend = substrate_test_client::Backend; /// Test client executor. -pub type Executor = client::LocalCallExecutor< +pub type Executor = sc_client::LocalCallExecutor< Backend, NativeExecutor, >; /// Test client light database backend. -pub type LightBackend = generic_test_client::LightBackend; +pub type LightBackend = substrate_test_client::LightBackend; /// Test client light executor. -pub type LightExecutor = client::light::call_executor::GenesisCallExecutor< +pub type LightExecutor = sc_client::light::call_executor::GenesisCallExecutor< LightBackend, - client::LocalCallExecutor< - client::light::backend::Backend< - client_db::light::LightStorage, + sc_client::LocalCallExecutor< + sc_client::light::backend::Backend< + sc_client_db::light::LightStorage, Blake2Hasher, >, NativeExecutor @@ -122,9 +123,10 @@ impl GenesisParameters { } } -impl generic_test_client::GenesisInit for GenesisParameters { +impl substrate_test_client::GenesisInit for GenesisParameters { fn genesis_storage(&self) -> Storage { use codec::Encode; + let mut storage = self.genesis_config().genesis_map(); let child_roots = storage.children.iter().map(|(sk, child_content)| { @@ -136,7 +138,7 @@ impl generic_test_client::GenesisInit for GenesisParameters { let state_root = <<::Header as HeaderT>::Hashing as HashT>::trie_root( storage.top.clone().into_iter().chain(child_roots).collect() ); - let block: runtime::Block = client::genesis::construct_genesis_block(state_root); + let block: runtime::Block = sc_client::genesis::construct_genesis_block(state_root); storage.top.extend(additional_storage_with_genesis(&block)); storage @@ -144,14 +146,14 @@ impl generic_test_client::GenesisInit for GenesisParameters { } /// A `TestClient` with `test-runtime` builder. -pub type TestClientBuilder = generic_test_client::TestClientBuilder; +pub type TestClientBuilder = substrate_test_client::TestClientBuilder; /// Test client type with `LocalExecutor` and generic Backend. -pub type Client = client::Client< +pub type Client = sc_client::Client< B, - client::LocalCallExecutor>, - runtime::Block, - runtime::RuntimeApi, + sc_client::LocalCallExecutor>, + substrate_test_runtime::Block, + substrate_test_runtime::RuntimeApi, >; /// A test client with default backend. @@ -206,14 +208,14 @@ pub trait TestClientBuilderExt: Sized { } /// Build the test client and longest chain selector. - fn build_with_longest_chain(self) -> (Client, client::LongestChain); + fn build_with_longest_chain(self) -> (Client, sc_client::LongestChain); } impl TestClientBuilderExt for TestClientBuilder< - client::LocalCallExecutor>, + sc_client::LocalCallExecutor>, B > where - B: client_api::backend::Backend, + B: sc_client_api::backend::Backend, { fn set_heap_pages(mut self, heap_pages: u64) -> Self { self.genesis_init_mut().heap_pages_override = Some(heap_pages); @@ -253,7 +255,7 @@ impl TestClientBuilderExt for TestClientBuilder< } - fn build_with_longest_chain(self) -> (Client, client::LongestChain) { + fn build_with_longest_chain(self) -> (Client, sc_client::LongestChain) { self.build_with_native_executor(None) } } @@ -267,15 +269,15 @@ type FetcherFutureResult = futures::future::Ready, Vec>, - body: MaybeFetcherCallback, Vec>, + call: MaybeFetcherCallback, Vec>, + body: MaybeFetcherCallback, Vec>, } impl LightFetcher { /// Sets remote call callback. pub fn with_remote_call( self, - call: MaybeFetcherCallback, Vec>, + call: MaybeFetcherCallback, Vec>, ) -> Self { LightFetcher { call, @@ -286,7 +288,7 @@ impl LightFetcher { /// Sets remote body callback. pub fn with_remote_body( self, - body: MaybeFetcherCallback, Vec>, + body: MaybeFetcherCallback, Vec>, ) -> Self { LightFetcher { call: self.call, @@ -295,37 +297,37 @@ impl LightFetcher { } } -impl Fetcher for LightFetcher { - type RemoteHeaderResult = FetcherFutureResult; +impl Fetcher for LightFetcher { + type RemoteHeaderResult = FetcherFutureResult; type RemoteReadResult = FetcherFutureResult, Option>>>; type RemoteCallResult = FetcherFutureResult>; - type RemoteChangesResult = FetcherFutureResult, u32)>>; - type RemoteBodyResult = FetcherFutureResult>; + type RemoteChangesResult = FetcherFutureResult, u32)>>; + type RemoteBodyResult = FetcherFutureResult>; - fn remote_header(&self, _: RemoteHeaderRequest) -> Self::RemoteHeaderResult { + fn remote_header(&self, _: RemoteHeaderRequest) -> Self::RemoteHeaderResult { unimplemented!() } - fn remote_read(&self, _: RemoteReadRequest) -> Self::RemoteReadResult { + fn remote_read(&self, _: RemoteReadRequest) -> Self::RemoteReadResult { unimplemented!() } - fn remote_read_child(&self, _: RemoteReadChildRequest) -> Self::RemoteReadResult { + fn remote_read_child(&self, _: RemoteReadChildRequest) -> Self::RemoteReadResult { unimplemented!() } - fn remote_call(&self, req: RemoteCallRequest) -> Self::RemoteCallResult { + fn remote_call(&self, req: RemoteCallRequest) -> Self::RemoteCallResult { match self.call { Some(ref call) => futures::future::ready(call(req)), None => unimplemented!(), } } - fn remote_changes(&self, _: RemoteChangesRequest) -> Self::RemoteChangesResult { + fn remote_changes(&self, _: RemoteChangesRequest) -> Self::RemoteChangesResult { unimplemented!() } - fn remote_body(&self, req: RemoteBodyRequest) -> Self::RemoteBodyResult { + fn remote_body(&self, req: RemoteBodyRequest) -> Self::RemoteBodyResult { match self.body { Some(ref body) => futures::future::ready(body(req)), None => unimplemented!(), @@ -340,15 +342,15 @@ pub fn new() -> Client { /// Creates new light client instance used for tests. pub fn new_light() -> ( - client::Client, + sc_client::Client, Arc, ) { - let storage = client_db::light::LightStorage::new_test(); - let blockchain = Arc::new(client::light::blockchain::Blockchain::new(storage)); + let storage = sc_client_db::light::LightStorage::new_test(); + let blockchain = Arc::new(sc_client::light::blockchain::Blockchain::new(storage)); let backend = Arc::new(LightBackend::new(blockchain.clone())); let executor = NativeExecutor::new(WasmExecutionMethod::Interpreted, None); - let local_call_executor = client::LocalCallExecutor::new(backend.clone(), executor); + let local_call_executor = sc_client::LocalCallExecutor::new(backend.clone(), executor); let call_executor = LightExecutor::new( backend.clone(), local_call_executor, diff --git a/substrate/test-utils/runtime/client/src/trait_tests.rs b/substrate/test-utils/runtime/client/src/trait_tests.rs index 108924c4dd..9217cff801 100644 --- a/substrate/test-utils/runtime/client/src/trait_tests.rs +++ b/substrate/test-utils/runtime/client/src/trait_tests.rs @@ -21,19 +21,19 @@ use std::sync::Arc; -use client_api::backend::LocalBackend; +use sc_client_api::backend::LocalBackend; use crate::block_builder_ext::BlockBuilderExt; -use client_api::blockchain::{Backend as BlockChainBackendT, HeaderBackend}; +use sc_client_api::blockchain::{Backend as BlockChainBackendT, HeaderBackend}; use crate::{AccountKeyring, ClientExt, TestClientBuilder, TestClientBuilderExt}; -use generic_test_client::consensus::BlockOrigin; -use primitives::Blake2Hasher; -use runtime::{self, Transfer}; +use substrate_test_client::sp_consensus::BlockOrigin; +use sp_core::Blake2Hasher; +use substrate_test_runtime::{self, Transfer}; use sp_runtime::generic::BlockId; use sp_runtime::traits::Block as BlockT; /// helper to test the `leaves` implementation for various backends pub fn test_leaves_for_backend(backend: Arc) where - B: LocalBackend, + B: LocalBackend, { // block tree: // G -> A1 -> A2 -> A3 -> A4 -> A5 @@ -149,7 +149,7 @@ pub fn test_leaves_for_backend(backend: Arc) where /// helper to test the `children` implementation for various backends pub fn test_children_for_backend(backend: Arc) where - B: LocalBackend, + B: LocalBackend, { // block tree: // G -> A1 -> A2 -> A3 -> A4 -> A5 @@ -240,7 +240,7 @@ pub fn test_children_for_backend(backend: Arc) where } pub fn test_blockchain_query_by_number_gets_canonical(backend: Arc) where - B: LocalBackend, + B: LocalBackend, { // block tree: // G -> A1 -> A2 -> A3 -> A4 -> A5 diff --git a/substrate/test-utils/runtime/src/genesismap.rs b/substrate/test-utils/runtime/src/genesismap.rs index 85d513c2cf..62d9b160b9 100644 --- a/substrate/test-utils/runtime/src/genesismap.rs +++ b/substrate/test-utils/runtime/src/genesismap.rs @@ -20,8 +20,8 @@ use std::collections::BTreeMap; use sp_io::hashing::{blake2_256, twox_128}; use super::{AuthorityId, AccountId, WASM_BINARY, system}; use codec::{Encode, KeyedVec, Joiner}; -use primitives::{ChangesTrieConfiguration, map}; -use primitives::storage::{well_known_keys, Storage}; +use sp_core::{ChangesTrieConfiguration, map}; +use sp_core::storage::{well_known_keys, Storage}; use sp_runtime::traits::{Block as BlockT, Hash as HashT, Header as HeaderT}; /// Configuration of a general Substrate test genesis block. @@ -41,7 +41,7 @@ impl GenesisConfig { endowed_accounts: Vec, balance: u64, heap_pages_override: Option, - extra_storage: Storage, + extra_storage: Storage, ) -> Self { GenesisConfig { changes_trie_config: match support_changes_trie { @@ -87,7 +87,7 @@ impl GenesisConfig { pub fn insert_genesis_block( storage: &mut Storage, -) -> primitives::hash::H256 { +) -> sp_core::hash::H256 { let child_roots = storage.children.iter().map(|(sk, child_content)| { let state_root = <<::Header as HeaderT>::Hashing as HashT>::trie_root( child_content.data.clone().into_iter().collect(), diff --git a/substrate/test-utils/runtime/src/lib.rs b/substrate/test-utils/runtime/src/lib.rs index 785d8dec5b..2a0cfe454f 100644 --- a/substrate/test-utils/runtime/src/lib.rs +++ b/substrate/test-utils/runtime/src/lib.rs @@ -25,9 +25,8 @@ pub mod system; use sp_std::{prelude::*, marker::PhantomData}; use codec::{Encode, Decode, Input, Error}; -use primitives::{Blake2Hasher, OpaqueMetadata, RuntimeDebug}; -use app_crypto::{ed25519, sr25519, RuntimeAppPublic}; -pub use app_crypto; +use sp_core::{Blake2Hasher, OpaqueMetadata, RuntimeDebug}; +use sp_application_crypto::{ed25519, sr25519, RuntimeAppPublic}; use trie_db::{TrieMut, Trie}; use sp_trie::PrefixedMemoryDB; use sp_trie::trie_types::{TrieDB, TrieDBMut}; @@ -43,18 +42,18 @@ use sp_runtime::{ GetNodeBlockType, GetRuntimeBlockType, Verify, IdentityLookup, }, }; -use runtime_version::RuntimeVersion; -pub use primitives::{hash::H256}; +use sp_version::RuntimeVersion; +pub use sp_core::{hash::H256}; #[cfg(any(feature = "std", test))] -use runtime_version::NativeVersion; -use runtime_support::{impl_outer_origin, parameter_types, weights::Weight}; -use inherents::{CheckInherentsResult, InherentData}; +use sp_version::NativeVersion; +use frame_support::{impl_outer_origin, parameter_types, weights::Weight}; +use sp_inherents::{CheckInherentsResult, InherentData}; use cfg_if::cfg_if; -use primitives::storage::ChildType; +use sp_core::storage::ChildType; // Ensure Babe and Aura use the same crypto to simplify things a bit. -pub use babe_primitives::AuthorityId; -pub type AuraId = aura_primitives::sr25519::AuthorityId; +pub use sp_consensus_babe::AuthorityId; +pub type AuraId = sp_consensus_aura::sr25519::AuthorityId; // Inlucde the WASM binary #[cfg(feature = "std")] @@ -96,7 +95,7 @@ impl Transfer { /// Convert into a signed extrinsic. #[cfg(feature = "std")] pub fn into_signed_tx(self) -> Extrinsic { - let signature = keyring::AccountKeyring::from_public(&self.from) + let signature = sp_keyring::AccountKeyring::from_public(&self.from) .expect("Creates keyring from public key.").sign(&self.encode()).into(); Extrinsic::Transfer(self, signature) } @@ -195,8 +194,8 @@ pub fn run_tests(mut input: &[u8]) -> Vec { } /// Changes trie configuration (optionally) used in tests. -pub fn changes_trie_config() -> primitives::ChangesTrieConfiguration { - primitives::ChangesTrieConfiguration { +pub fn changes_trie_config() -> sp_core::ChangesTrieConfiguration { + sp_core::ChangesTrieConfiguration { digest_interval: 4, digest_levels: 2, } @@ -406,8 +405,8 @@ fn benchmark_add_one(i: u64) -> u64 { /// The `benchmark_add_one` function as function pointer. #[cfg(not(feature = "std"))] -static BENCHMARK_ADD_ONE: runtime_interface::wasm::ExchangeableFunction u64> = - runtime_interface::wasm::ExchangeableFunction::new(benchmark_add_one); +static BENCHMARK_ADD_ONE: sp_runtime_interface::wasm::ExchangeableFunction u64> = + sp_runtime_interface::wasm::ExchangeableFunction::new(benchmark_add_one); fn code_using_trie() -> u64 { let pairs = [ @@ -494,7 +493,7 @@ cfg_if! { } } - impl block_builder_api::BlockBuilder for Runtime { + impl sp_block_builder::BlockBuilder for Runtime { fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { system::execute_transaction(extrinsic) } @@ -598,7 +597,7 @@ cfg_if! { } } - impl aura_primitives::AuraApi for Runtime { + impl sp_consensus_aura::AuraApi for Runtime { fn slot_duration() -> u64 { 1000 } fn authorities() -> Vec { system::authorities().into_iter().map(|a| { @@ -608,9 +607,9 @@ cfg_if! { } } - impl babe_primitives::BabeApi for Runtime { - fn configuration() -> babe_primitives::BabeConfiguration { - babe_primitives::BabeConfiguration { + impl sp_consensus_babe::BabeApi for Runtime { + fn configuration() -> sp_consensus_babe::BabeConfiguration { + sp_consensus_babe::BabeConfiguration { slot_duration: 1000, epoch_length: EpochDuration::get(), c: (3, 10), @@ -622,14 +621,14 @@ cfg_if! { } } - impl offchain_primitives::OffchainWorkerApi for Runtime { + impl sp_offchain::OffchainWorkerApi for Runtime { fn offchain_worker(block: u64) { let ex = Extrinsic::IncludeData(block.encode()); sp_io::offchain::submit_transaction(ex.encode()).unwrap(); } } - impl session::SessionKeys for Runtime { + impl sp_session::SessionKeys for Runtime { fn generate_session_keys(_: Option>) -> Vec { SessionKeys::generate(None) } @@ -679,7 +678,7 @@ cfg_if! { } } - impl block_builder_api::BlockBuilder for Runtime { + impl sp_block_builder::BlockBuilder for Runtime { fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { system::execute_transaction(extrinsic) } @@ -814,7 +813,7 @@ cfg_if! { } } - impl aura_primitives::AuraApi for Runtime { + impl sp_consensus_aura::AuraApi for Runtime { fn slot_duration() -> u64 { 1000 } fn authorities() -> Vec { system::authorities().into_iter().map(|a| { @@ -824,9 +823,9 @@ cfg_if! { } } - impl babe_primitives::BabeApi for Runtime { - fn configuration() -> babe_primitives::BabeConfiguration { - babe_primitives::BabeConfiguration { + impl sp_consensus_babe::BabeApi for Runtime { + fn configuration() -> sp_consensus_babe::BabeConfiguration { + sp_consensus_babe::BabeConfiguration { slot_duration: 1000, epoch_length: EpochDuration::get(), c: (3, 10), @@ -838,14 +837,14 @@ cfg_if! { } } - impl offchain_primitives::OffchainWorkerApi for Runtime { + impl sp_offchain::OffchainWorkerApi for Runtime { fn offchain_worker(block: u64) { let ex = Extrinsic::IncludeData(block.encode()); sp_io::offchain::submit_transaction(ex.encode()).unwrap() } } - impl session::SessionKeys for Runtime { + impl sp_session::SessionKeys for Runtime { fn generate_session_keys(_: Option>) -> Vec { SessionKeys::generate(None) } @@ -950,7 +949,7 @@ fn test_read_child_storage() { mod tests { use substrate_test_runtime_client::{ prelude::*, - consensus::BlockOrigin, + sp_consensus::BlockOrigin, DefaultTestClientBuilderExt, TestClientBuilder, runtime::TestAPI, }; @@ -958,8 +957,8 @@ mod tests { generic::BlockId, traits::ProvideRuntimeApi, }; - use primitives::storage::well_known_keys::HEAP_PAGES; - use state_machine::ExecutionStrategy; + use sp_core::storage::well_known_keys::HEAP_PAGES; + use sp_state_machine::ExecutionStrategy; use codec::Encode; #[test] diff --git a/substrate/test-utils/runtime/src/system.rs b/substrate/test-utils/runtime/src/system.rs index aec909f8da..162f9a8ad6 100644 --- a/substrate/test-utils/runtime/src/system.rs +++ b/substrate/test-utils/runtime/src/system.rs @@ -22,8 +22,8 @@ use sp_io::{ storage::root as storage_root, storage::changes_root as storage_changes_root, hashing::blake2_256, }; -use runtime_support::storage; -use runtime_support::{decl_storage, decl_module}; +use frame_support::storage; +use frame_support::{decl_storage, decl_module}; use sp_runtime::{ traits::{Hash as HashT, BlakeTwo256, Header as _}, generic, ApplyExtrinsicResult, transaction_validity::{ @@ -35,7 +35,7 @@ use frame_system::Trait; use crate::{ AccountId, BlockNumber, Extrinsic, Transfer, H256 as Hash, Block, Header, Digest, AuthorityId }; -use primitives::storage::well_known_keys; +use sp_core::storage::well_known_keys; const NONCE_OF: &[u8] = b"nonce:"; const BALANCE_OF: &[u8] = b"balance:"; @@ -169,7 +169,7 @@ fn execute_block_with_state_root_handler( /// The block executor. pub struct BlockExecutor; -impl executive::ExecuteBlock for BlockExecutor { +impl frame_executive::ExecuteBlock for BlockExecutor { fn execute_block(block: Block) { execute_block(block); } @@ -312,7 +312,7 @@ fn execute_storage_change(key: &[u8], value: Option<&[u8]>) -> ApplyExtrinsicRes #[cfg(feature = "std")] fn info_expect_equal_hash(given: &Hash, expected: &Hash) { - use primitives::hexdisplay::HexDisplay; + use sp_core::hexdisplay::HexDisplay; if given != expected { println!( "Hash: given={}, expected={}", @@ -338,7 +338,7 @@ mod tests { use sp_io::TestExternalities; use substrate_test_runtime_client::{AccountKeyring, Sr25519Keyring}; use crate::{Header, Transfer, WASM_BINARY}; - use primitives::{NeverNativeValue, map, traits::CodeExecutor}; + use sp_core::{NeverNativeValue, map, traits::CodeExecutor}; use sc_executor::{NativeExecutor, WasmExecutionMethod, native_executor_instance}; use sp_io::hashing::twox_128; @@ -361,7 +361,7 @@ mod tests { ]; TestExternalities::new_with_code( WASM_BINARY, - primitives::storage::Storage { + sp_core::storage::Storage { top: map![ twox_128(b"latest").to_vec() => vec![69u8; 32], twox_128(b"sys:auth").to_vec() => authorities.encode(), diff --git a/substrate/utils/frame/rpc/support/Cargo.toml b/substrate/utils/frame/rpc/support/Cargo.toml index cc5a860470..272fdb5642 100644 --- a/substrate/utils/frame/rpc/support/Cargo.toml +++ b/substrate/utils/frame/rpc/support/Cargo.toml @@ -8,7 +8,7 @@ edition = "2018" futures = { version = "0.3.0", features = ["compat"] } jsonrpc-client-transports = "14" jsonrpc-core = "14" -parity-scale-codec = "1" +codec = { package = "parity-scale-codec", version = "1" } serde = "1" frame-support = { path = "../../../../frame/support" } sp-storage = { path = "../../../../primitives/storage" } diff --git a/substrate/utils/frame/rpc/support/src/lib.rs b/substrate/utils/frame/rpc/support/src/lib.rs index 396c521501..80c0658086 100644 --- a/substrate/utils/frame/rpc/support/src/lib.rs +++ b/substrate/utils/frame/rpc/support/src/lib.rs @@ -22,7 +22,7 @@ use core::marker::PhantomData; use futures::compat::Future01CompatExt; use jsonrpc_client_transports::RpcError; -use parity_scale_codec::{DecodeAll, FullCodec, FullEncode}; +use codec::{DecodeAll, FullCodec, FullEncode}; use serde::{de::DeserializeOwned, Serialize}; use frame_support::storage::generator::{ StorageDoubleMap, StorageLinkedMap, StorageMap, StorageValue @@ -38,7 +38,7 @@ use sc_rpc_api::state::StateClient; /// # use futures::future::FutureExt; /// # use jsonrpc_client_transports::RpcError; /// # use jsonrpc_client_transports::transports::http; -/// # use parity_scale_codec::Encode; +/// # use codec::Encode; /// # use frame_support::{decl_storage, decl_module}; /// # use substrate_frame_rpc_support::StorageQuery; /// # use frame_system::Trait; diff --git a/substrate/utils/frame/rpc/system/Cargo.toml b/substrate/utils/frame/rpc/system/Cargo.toml index a501891749..c904bceae0 100644 --- a/substrate/utils/frame/rpc/system/Cargo.toml +++ b/substrate/utils/frame/rpc/system/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -client = { package = "sc-client", path = "../../../../client/" } +sc-client = { path = "../../../../client/" } codec = { package = "parity-scale-codec", version = "1.0.0" } futures = "0.3.1" jsonrpc-core = "14.0.3" @@ -17,9 +17,9 @@ sp-runtime = { path = "../../../../primitives/runtime" } frame-system-rpc-runtime-api = { path = "../../../../frame/system/rpc/runtime-api" } sp-core = { path = "../../../../primitives/core" } sp-blockchain = { path = "../../../../primitives/blockchain" } -txpool-api = { package = "sp-transaction-pool", path = "../../../../primitives/transaction-pool" } +sp-transaction-pool = { path = "../../../../primitives/transaction-pool" } [dev-dependencies] -test-client = { package = "substrate-test-runtime-client", path = "../../../../test-utils/runtime/client" } +substrate-test-runtime-client = { path = "../../../../test-utils/runtime/client" } env_logger = "0.7.0" -txpool = { package = "sc-transaction-pool", path = "../../../../client/transaction-pool" } +sc-transaction-pool = { path = "../../../../client/transaction-pool" } diff --git a/substrate/utils/frame/rpc/system/src/lib.rs b/substrate/utils/frame/rpc/system/src/lib.rs index 675965729d..c1d9b1f4f6 100644 --- a/substrate/utils/frame/rpc/system/src/lib.rs +++ b/substrate/utils/frame/rpc/system/src/lib.rs @@ -19,7 +19,7 @@ use std::sync::Arc; use codec::{self, Codec, Decode, Encode}; -use client::{ +use sc_client::{ light::blockchain::{future_header, RemoteBlockchain}, light::fetcher::{Fetcher, RemoteCallRequest}, }; @@ -38,7 +38,7 @@ use sp_runtime::{ traits, }; use sp_core::hexdisplay::HexDisplay; -use txpool_api::{TransactionPool, InPoolTransaction}; +use sp_transaction_pool::{TransactionPool, InPoolTransaction}; pub use frame_system_rpc_runtime_api::AccountNonceApi; pub use self::gen_client::Client as SystemClient; @@ -224,17 +224,17 @@ mod tests { use super::*; use futures::executor::block_on; - use test_client::{ + use substrate_test_runtime_client::{ runtime::Transfer, AccountKeyring, }; - use txpool::{BasicPool, FullChainApi}; + use sc_transaction_pool::{BasicPool, FullChainApi}; #[test] fn should_return_next_nonce_for_some_account() { // given let _ = env_logger::try_init(); - let client = Arc::new(test_client::new()); + let client = Arc::new(substrate_test_runtime_client::new()); let pool = Arc::new(BasicPool::new(Default::default(), FullChainApi::new(client.clone()))); let new_transaction = |nonce: u64| {