diff --git a/substrate/Cargo.lock b/substrate/Cargo.lock index ba762f1393..a1f3ba2983 100644 --- a/substrate/Cargo.lock +++ b/substrate/Cargo.lock @@ -3801,12 +3801,12 @@ dependencies = [ name = "sr-io" version = "2.0.0" dependencies = [ - "environmental 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", "hash-db 0.15.2 (registry+https://github.com/rust-lang/crates.io-index)", "libsecp256k1 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", "rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", "sr-std 2.0.0", + "substrate-externalities 2.0.0", "substrate-primitives 2.0.0", "substrate-state-machine 2.0.0", "substrate-trie 2.0.0", @@ -3830,6 +3830,7 @@ dependencies = [ "sr-io 2.0.0", "sr-std 2.0.0", "substrate-application-crypto 2.0.0", + "substrate-externalities 2.0.0", "substrate-offchain 2.0.0", "substrate-primitives 2.0.0", ] @@ -4387,6 +4388,7 @@ dependencies = [ "pretty_assertions 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.101 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 2.0.0", + "sr-primitives 2.0.0", "srml-support 2.0.0", "substrate-inherents 2.0.0", "substrate-primitives 2.0.0", @@ -4974,6 +4976,7 @@ dependencies = [ "sr-io 2.0.0", "sr-version 2.0.0", "substrate-client 2.0.0", + "substrate-externalities 2.0.0", "substrate-offchain 2.0.0", "substrate-panic-handler 2.0.0", "substrate-primitives 2.0.0", @@ -4987,6 +4990,16 @@ dependencies = [ "wasmi 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "substrate-externalities" +version = "2.0.0" +dependencies = [ + "environmental 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "primitive-types 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", + "sr-std 2.0.0", + "substrate-primitives-storage 2.0.0", +] + [[package]] name = "substrate-finality-grandpa" version = "2.0.0" @@ -5224,6 +5237,8 @@ dependencies = [ "sha2 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "sr-std 2.0.0", "substrate-bip39 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "substrate-externalities 2.0.0", + "substrate-primitives-storage 2.0.0", "substrate-serializer 2.0.0", "tiny-bip39 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", "twox-hash 1.5.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -5231,6 +5246,15 @@ dependencies = [ "zeroize 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "substrate-primitives-storage" +version = "2.0.0" +dependencies = [ + "impl-serde 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.101 (registry+https://github.com/rust-lang/crates.io-index)", + "sr-std 2.0.0", +] + [[package]] name = "substrate-rpc" version = "2.0.0" @@ -5425,6 +5449,7 @@ dependencies = [ "parity-scale-codec 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", + "substrate-externalities 2.0.0", "substrate-panic-handler 2.0.0", "substrate-primitives 2.0.0", "substrate-trie 2.0.0", diff --git a/substrate/Cargo.toml b/substrate/Cargo.toml index 62993397fd..7e34a0bd6c 100644 --- a/substrate/Cargo.toml +++ b/substrate/Cargo.toml @@ -36,6 +36,7 @@ members = [ "core/consensus/pow", "core/executor", "core/executor/runtime-test", + "core/externalities", "core/finality-grandpa", "core/finality-grandpa/primitives", "core/inherents", diff --git a/substrate/core/application-crypto/src/ed25519.rs b/substrate/core/application-crypto/src/ed25519.rs index d5c4fd7bad..b0113718b5 100644 --- a/substrate/core/application-crypto/src/ed25519.rs +++ b/substrate/core/application-crypto/src/ed25519.rs @@ -53,14 +53,7 @@ impl RuntimePublic for Public { #[cfg(test)] mod tests { use sr_primitives::{generic::BlockId, traits::ProvideRuntimeApi}; - use primitives::{ - testing::{ - KeyStore, - ED25519, - }, - crypto::Pair, - traits::BareCryptoStore as _, - }; + use primitives::{testing::{KeyStore, ED25519}, crypto::Pair}; use test_client::{ TestClientBuilder, DefaultTestClientBuilderExt, TestClientBuilderExt, runtime::{TestAPI, app_crypto::ed25519::{AppPair, AppPublic}}, diff --git a/substrate/core/application-crypto/src/sr25519.rs b/substrate/core/application-crypto/src/sr25519.rs index 93565a628f..40f6c6b22e 100644 --- a/substrate/core/application-crypto/src/sr25519.rs +++ b/substrate/core/application-crypto/src/sr25519.rs @@ -53,14 +53,7 @@ impl RuntimePublic for Public { #[cfg(test)] mod tests { use sr_primitives::{generic::BlockId, traits::ProvideRuntimeApi}; - use primitives::{ - testing::{ - KeyStore, - SR25519, - }, - crypto::Pair, - traits::BareCryptoStore as _, - }; + use primitives::{testing::{KeyStore, SR25519}, crypto::Pair}; use test_client::{ TestClientBuilder, DefaultTestClientBuilderExt, TestClientBuilderExt, runtime::{TestAPI, app_crypto::sr25519::{AppPair, AppPublic}}, diff --git a/substrate/core/client/db/src/lib.rs b/substrate/core/client/db/src/lib.rs index 7061e9d29a..1f7fa604a4 100644 --- a/substrate/core/client/db/src/lib.rs +++ b/substrate/core/client/db/src/lib.rs @@ -224,7 +224,7 @@ pub fn new_client( > where Block: BlockT, - E: CodeExecutor + RuntimeInfo, + E: CodeExecutor + RuntimeInfo, S: BuildStorage, { let backend = Arc::new(Backend::new(settings, CANONICALIZATION_DELAY)?); @@ -456,8 +456,7 @@ impl BlockImportOperation { } impl client::backend::BlockImportOperation -for BlockImportOperation -where Block: BlockT, + for BlockImportOperation where Block: BlockT, { type State = CachingState, Block>; diff --git a/substrate/core/client/src/call_executor.rs b/substrate/core/client/src/call_executor.rs index ebb882709d..05a2a8eba1 100644 --- a/substrate/core/client/src/call_executor.rs +++ b/substrate/core/client/src/call_executor.rs @@ -26,8 +26,8 @@ use state_machine::{ use executor::{RuntimeVersion, RuntimeInfo, NativeVersion}; use hash_db::Hasher; use primitives::{ - offchain::{self, NeverOffchainExt}, H256, Blake2Hasher, NativeOrEncoded, NeverNativeValue, - traits::CodeExecutor, + offchain::OffchainExt, H256, Blake2Hasher, NativeOrEncoded, NeverNativeValue, + traits::{CodeExecutor, KeystoreExt}, }; use crate::runtime_api::{ProofRecorder, InitializeBlock}; @@ -47,15 +47,13 @@ where /// Execute a call to a contract on top of state in a block of given hash. /// /// No changes are made. - fn call< - O: offchain::Externalities, - >( + fn call( &self, id: &BlockId, method: &str, call_data: &[u8], strategy: ExecutionStrategy, - side_effects_handler: Option<&mut O>, + side_effects_handler: Option, ) -> Result, error::Error>; /// Execute a contextual call on top of state in a block of a given hash. @@ -65,7 +63,6 @@ where /// of the execution context. fn contextual_call< 'a, - O: offchain::Externalities, IB: Fn() -> error::Result<()>, EM: Fn( Result, Self::Error>, @@ -83,7 +80,7 @@ where initialize_block: InitializeBlock<'a, B>, execution_manager: ExecutionManager, native_call: Option, - side_effects_handler: Option<&mut O>, + side_effects_handler: Option, proof_recorder: &Option>>>, enable_keystore: bool, ) -> error::Result> where ExecutionManager: Clone; @@ -97,11 +94,10 @@ where /// /// No changes are made. fn call_at_state< - O: offchain::Externalities, S: state_machine::Backend, F: FnOnce( Result, Self::Error>, - Result, Self::Error> + Result, Self::Error>, ) -> Result, Self::Error>, R: Encode + Decode + PartialEq, NC: FnOnce() -> result::Result + UnwindSafe, @@ -112,7 +108,7 @@ where call_data: &[u8], manager: ExecutionManager, native_call: Option, - side_effects_handler: Option<&mut O>, + side_effects_handler: Option, ) -> Result< ( NativeOrEncoded, @@ -191,18 +187,18 @@ impl Clone for LocalCallExecutor where E: Clone { impl CallExecutor for LocalCallExecutor where B: backend::Backend, - E: CodeExecutor + RuntimeInfo, + E: CodeExecutor + RuntimeInfo, Block: BlockT, { type Error = E::Error; - fn call( + fn call( &self, id: &BlockId, method: &str, call_data: &[u8], strategy: ExecutionStrategy, - side_effects_handler: Option<&mut O>, + side_effects_handler: Option, ) -> error::Result> { let mut changes = OverlayedChanges::default(); let state = self.backend.state_at(*id)?; @@ -214,7 +210,7 @@ where &self.executor, method, call_data, - self.keystore.clone(), + self.keystore.clone().map(KeystoreExt), ).execute_using_consensus_failure_handler::<_, NeverNativeValue, fn() -> _>( strategy.get_manager(), false, @@ -227,7 +223,6 @@ where fn contextual_call< 'a, - O: offchain::Externalities, IB: Fn() -> error::Result<()>, EM: Fn( Result, Self::Error>, @@ -245,7 +240,7 @@ where initialize_block: InitializeBlock<'a, Block>, execution_manager: ExecutionManager, native_call: Option, - side_effects_handler: Option<&mut O>, + side_effects_handler: Option, recorder: &Option>>>, enable_keystore: bool, ) -> Result, error::Error> where ExecutionManager: Clone { @@ -259,7 +254,7 @@ where } let keystore = if enable_keystore { - self.keystore.clone() + self.keystore.clone().map(KeystoreExt) } else { None }; @@ -326,7 +321,6 @@ where &mut overlay, &state, self.backend.changes_trie_storage(), - NeverOffchainExt::new(), None, ); let version = self.executor.runtime_version(&mut ext); @@ -335,11 +329,10 @@ where } fn call_at_state< - O: offchain::Externalities, S: state_machine::Backend, F: FnOnce( Result, Self::Error>, - Result, Self::Error> + Result, Self::Error>, ) -> Result, Self::Error>, R: Encode + Decode + PartialEq, NC: FnOnce() -> result::Result + UnwindSafe, @@ -350,7 +343,7 @@ where call_data: &[u8], manager: ExecutionManager, native_call: Option, - side_effects_handler: Option<&mut O>, + side_effects_handler: Option, ) -> error::Result<( NativeOrEncoded, (S::Transaction, ::Out), @@ -364,7 +357,7 @@ where &self.executor, method, call_data, - self.keystore.clone(), + self.keystore.clone().map(KeystoreExt), ).execute_using_consensus_failure_handler( manager, true, @@ -391,7 +384,7 @@ where &self.executor, method, call_data, - self.keystore.clone(), + self.keystore.clone().map(KeystoreExt), ) .map_err(Into::into) } diff --git a/substrate/core/client/src/client.rs b/substrate/core/client/src/client.rs index aff099233a..34334b1388 100644 --- a/substrate/core/client/src/client.rs +++ b/substrate/core/client/src/client.rs @@ -28,7 +28,7 @@ use hash_db::{Hasher, Prefix}; use primitives::{ Blake2Hasher, H256, ChangesTrieConfiguration, convert_hash, NeverNativeValue, ExecutionContext, NativeOrEncoded, storage::{StorageKey, StorageData, well_known_keys}, - offchain::{NeverOffchainExt, self}, traits::CodeExecutor, + offchain::{OffchainExt, self}, traits::CodeExecutor, }; use substrate_telemetry::{telemetry, SUBSTRATE_INFO}; use sr_primitives::{ @@ -248,7 +248,7 @@ pub fn new_in_mem( Block, RA >> where - E: CodeExecutor + RuntimeInfo, + E: CodeExecutor + RuntimeInfo, S: BuildStorage, Block: BlockT, { @@ -264,7 +264,7 @@ pub fn new_with_backend( keystore: Option, ) -> error::Result, Block, RA>> where - E: CodeExecutor + RuntimeInfo, + E: CodeExecutor + RuntimeInfo, S: BuildStorage, Block: BlockT, B: backend::LocalBackend @@ -1058,18 +1058,27 @@ impl Client where }), } }; - let (_, storage_update, changes_update) = self.executor.call_at_state::<_, _, _, NeverNativeValue, fn() -> _>( - transaction_state, - &mut overlay, - "Core_execute_block", - &::new(import_headers.pre().clone(), body.unwrap_or_default()).encode(), - match origin { - BlockOrigin::NetworkInitialSync => get_execution_manager(self.execution_strategies().syncing), - _ => get_execution_manager(self.execution_strategies().importing), - }, - None, - NeverOffchainExt::new(), - )?; + + let encoded_block = ::new( + import_headers.pre().clone(), + body.unwrap_or_default(), + ).encode(); + + let (_, storage_update, changes_update) = self.executor + .call_at_state::<_, _, NeverNativeValue, fn() -> _>( + transaction_state, + &mut overlay, + "Core_execute_block", + &encoded_block, + match origin { + BlockOrigin::NetworkInitialSync => get_execution_manager( + self.execution_strategies().syncing, + ), + _ => get_execution_manager(self.execution_strategies().importing), + }, + None, + None, + )?; overlay.commit_prospective(); @@ -1460,12 +1469,13 @@ impl CallRuntimeAt for Client where }; let capabilities = context.capabilities(); - let mut offchain_extensions = match context { - ExecutionContext::OffchainCall(ext) => ext.map(|x| x.0), - _ => None, - }.map(|ext| offchain::LimitedExternalities::new(capabilities, ext)); + let offchain_extensions = if let ExecutionContext::OffchainCall(Some(ext)) = context { + Some(OffchainExt::new(offchain::LimitedExternalities::new(capabilities, ext.0))) + } else { + None + }; - self.executor.contextual_call::<_, _, fn(_,_) -> _,_,_>( + self.executor.contextual_call::<_, fn(_,_) -> _,_,_>( || core_api.initialize_block(at, &self.prepare_environment_block(at)?), at, function, @@ -1474,7 +1484,7 @@ impl CallRuntimeAt for Client where initialize_block, manager, native_call, - offchain_extensions.as_mut(), + offchain_extensions, recorder, capabilities.has(offchain::Capability::Keystore), ) diff --git a/substrate/core/client/src/genesis.rs b/substrate/core/client/src/genesis.rs index 51e0536613..031b2dc0ad 100644 --- a/substrate/core/client/src/genesis.rs +++ b/substrate/core/client/src/genesis.rs @@ -53,7 +53,7 @@ mod tests { runtime::{Hash, Transfer, Block, BlockNumber, Header, Digest}, AccountKeyring, Sr25519Keyring, }; - use primitives::{Blake2Hasher, map, offchain::NeverOffchainExt}; + use primitives::{Blake2Hasher, map}; use hex_literal::*; native_executor_instance!( @@ -93,7 +93,7 @@ mod tests { StateMachine::new( backend, Some(&InMemoryChangesTrieStorage::<_, u64>::new()), - NeverOffchainExt::new(), + None, &mut overlay, &executor(), "Core_initialize_block", @@ -107,7 +107,7 @@ mod tests { StateMachine::new( backend, Some(&InMemoryChangesTrieStorage::<_, u64>::new()), - NeverOffchainExt::new(), + None, &mut overlay, &executor(), "BlockBuilder_apply_extrinsic", @@ -121,7 +121,7 @@ mod tests { let (ret_data, _, _) = StateMachine::new( backend, Some(&InMemoryChangesTrieStorage::<_, u64>::new()), - NeverOffchainExt::new(), + None, &mut overlay, &executor(), "BlockBuilder_finalize_block", @@ -169,7 +169,7 @@ mod tests { let _ = StateMachine::new( &backend, Some(&InMemoryChangesTrieStorage::<_, u64>::new()), - NeverOffchainExt::new(), + None, &mut overlay, &executor(), "Core_execute_block", @@ -199,7 +199,7 @@ mod tests { let _ = StateMachine::new( &backend, Some(&InMemoryChangesTrieStorage::<_, u64>::new()), - NeverOffchainExt::new(), + None, &mut overlay, &executor(), "Core_execute_block", @@ -229,7 +229,7 @@ mod tests { let r = StateMachine::new( &backend, Some(&InMemoryChangesTrieStorage::<_, u64>::new()), - NeverOffchainExt::new(), + None, &mut overlay, &executor(), "Core_execute_block", diff --git a/substrate/core/client/src/light/call_executor.rs b/substrate/core/client/src/light/call_executor.rs index d969c39a5a..65776bcfe0 100644 --- a/substrate/core/client/src/light/call_executor.rs +++ b/substrate/core/client/src/light/call_executor.rs @@ -23,11 +23,12 @@ use std::{ use codec::{Encode, Decode}; use primitives::{ - offchain, H256, Blake2Hasher, convert_hash, NativeOrEncoded, + offchain::OffchainExt, H256, Blake2Hasher, convert_hash, NativeOrEncoded, traits::CodeExecutor, }; -use sr_primitives::generic::BlockId; -use sr_primitives::traits::{One, Block as BlockT, Header as HeaderT, NumberFor}; +use sr_primitives::{ + generic::BlockId, traits::{One, Block as BlockT, Header as HeaderT, NumberFor}, +}; use state_machine::{ self, Backend as StateBackend, OverlayedChanges, ExecutionStrategy, create_proof_check_backend, execution_proof_check_on_trie_backend, ExecutionManager, ChangesTrieTransaction, @@ -74,15 +75,13 @@ impl CallExecutor for { type Error = ClientError; - fn call< - O: offchain::Externalities, - >( + fn call( &self, id: &BlockId, method: &str, call_data: &[u8], strategy: ExecutionStrategy, - side_effects_handler: Option<&mut O>, + side_effects_handler: Option, ) -> ClientResult> { match self.backend.is_local_state_available(id) { true => self.local.call(id, method, call_data, strategy, side_effects_handler), @@ -92,7 +91,6 @@ impl CallExecutor for fn contextual_call< 'a, - O: offchain::Externalities, IB: Fn() -> ClientResult<()>, EM: Fn( Result, Self::Error>, @@ -110,7 +108,7 @@ impl CallExecutor for initialize_block: InitializeBlock<'a, Block>, _manager: ExecutionManager, native_call: Option, - side_effects_handler: Option<&mut O>, + side_effects_handler: Option, recorder: &Option>>>, enable_keystore: bool, ) -> ClientResult> where ExecutionManager: Clone { @@ -119,7 +117,6 @@ impl CallExecutor for match self.backend.is_local_state_available(at) { true => CallExecutor::contextual_call::< - _, _, fn( Result, Local::Error>, @@ -153,7 +150,6 @@ impl CallExecutor for } fn call_at_state< - O: offchain::Externalities, S: StateBackend, FF: FnOnce( Result, Self::Error>, @@ -168,7 +164,7 @@ impl CallExecutor for _call_data: &[u8], _manager: ExecutionManager, _native_call: Option, - _side_effects_handler: Option<&mut O>, + _side_effects_handler: Option, ) -> ClientResult<( NativeOrEncoded, (S::Transaction, ::Out), @@ -242,11 +238,10 @@ pub fn check_execution_proof( ) -> ClientResult> where Header: HeaderT, - E: CodeExecutor, - H: Hasher, - H::Out: Ord + 'static, + E: CodeExecutor, + H: Hasher, { - check_execution_proof_with_make_header( + check_execution_proof_with_make_header::( executor, request, remote_proof, @@ -268,9 +263,8 @@ fn check_execution_proof_with_make_header ClientResult> where Header: HeaderT, - E: CodeExecutor, - H: Hasher, - H::Out: Ord + 'static, + E: CodeExecutor, + H: Hasher, { let local_state_root = request.header.state_root(); let root: H::Out = convert_hash(&local_state_root); @@ -301,33 +295,32 @@ fn check_execution_proof_with_make_header for DummyCallExecutor { type Error = ClientError; - fn call( + fn call( &self, _id: &BlockId, _method: &str, _call_data: &[u8], _strategy: ExecutionStrategy, - _side_effects_handler: Option<&mut O>, + _side_effects_handler: Option, ) -> Result, ClientError> { Ok(vec![42]) } fn contextual_call< 'a, - O: offchain::Externalities, IB: Fn() -> ClientResult<()>, EM: Fn( Result, Self::Error>, @@ -345,7 +338,7 @@ mod tests { _initialize_block: InitializeBlock<'a, Block>, _execution_manager: ExecutionManager, _native_call: Option, - _side_effects_handler: Option<&mut O>, + _side_effects_handler: Option, _proof_recorder: &Option>>>, _enable_keystore: bool, ) -> ClientResult> where ExecutionManager: Clone { @@ -357,7 +350,6 @@ mod tests { } fn call_at_state< - O: offchain::Externalities, S: state_machine::Backend, F: FnOnce( Result, Self::Error>, @@ -372,7 +364,7 @@ mod tests { _call_data: &[u8], _manager: ExecutionManager, _native_call: Option, - _side_effects_handler: Option<&mut O>, + _side_effects_handler: Option, ) -> Result< ( NativeOrEncoded, @@ -417,13 +409,17 @@ mod tests { ).unwrap(); // check remote execution proof locally - let local_result = check_execution_proof(&local_executor(), &RemoteCallRequest { - block: test_client::runtime::Hash::default(), - header: remote_header, - method: method.into(), - call_data: vec![], - retry_count: None, - }, remote_execution_proof).unwrap(); + let local_result = check_execution_proof::<_, _, Blake2Hasher>( + &local_executor(), + &RemoteCallRequest { + block: test_client::runtime::Hash::default(), + header: remote_header, + method: method.into(), + call_data: vec![], + retry_count: None, + }, + remote_execution_proof, + ).unwrap(); (remote_result, local_result) } @@ -440,7 +436,7 @@ mod tests { ).unwrap(); // check remote execution proof locally - let execution_result = check_execution_proof_with_make_header( + let execution_result = check_execution_proof_with_make_header::<_, _, Blake2Hasher, _>( &local_executor(), &RemoteCallRequest { block: test_client::runtime::Hash::default(), @@ -518,7 +514,7 @@ mod tests { "test_method", &[], ExecutionStrategy::NativeElseWasm, - NeverOffchainExt::new(), + None, ).unwrap(), vec![42], ); @@ -528,7 +524,7 @@ mod tests { "test_method", &[], ExecutionStrategy::NativeElseWasm, - NeverOffchainExt::new(), + None, ); match call_on_unavailable { diff --git a/substrate/core/client/src/light/fetcher.rs b/substrate/core/client/src/light/fetcher.rs index 51e1ed3b81..dbf6d41c38 100644 --- a/substrate/core/client/src/light/fetcher.rs +++ b/substrate/core/client/src/light/fetcher.rs @@ -23,7 +23,7 @@ use std::future::Future; use hash_db::{HashDB, Hasher, EMPTY_PREFIX}; use codec::{Decode, Encode}; -use primitives::{ChangesTrieConfiguration, convert_hash, traits::CodeExecutor}; +use primitives::{ChangesTrieConfiguration, convert_hash, traits::CodeExecutor, H256}; use sr_primitives::traits::{ Block as BlockT, Header as HeaderT, Hash, HashFor, NumberFor, SimpleArithmetic, CheckedConversion, Zero, @@ -370,9 +370,8 @@ impl> LightDataChecker { impl FetchChecker for LightDataChecker where Block: BlockT, - E: CodeExecutor, - H: Hasher, - H::Out: Ord + 'static, + E: CodeExecutor, + H: Hasher, S: BlockchainStorage, { fn check_header_proof( diff --git a/substrate/core/client/src/light/mod.rs b/substrate/core/client/src/light/mod.rs index c9d2e6040b..d06a9ae9dd 100644 --- a/substrate/core/client/src/light/mod.rs +++ b/substrate/core/client/src/light/mod.rs @@ -63,7 +63,7 @@ pub fn new_light( B: BlockT, S: BlockchainStorage + 'static, GS: BuildStorage, - E: CodeExecutor + RuntimeInfo, + E: CodeExecutor + RuntimeInfo, { let local_executor = LocalCallExecutor::new(backend.clone(), code_executor, None); let executor = GenesisCallExecutor::new(backend.clone(), local_executor); @@ -76,7 +76,7 @@ pub fn new_fetch_checker>( executor: E, ) -> LightDataChecker where - E: CodeExecutor, + E: CodeExecutor, { LightDataChecker::new(blockchain, executor) } diff --git a/substrate/core/executor/Cargo.toml b/substrate/core/executor/Cargo.toml index 1f53cd4099..cf3ea4ff7a 100644 --- a/substrate/core/executor/Cargo.toml +++ b/substrate/core/executor/Cargo.toml @@ -17,6 +17,7 @@ wasmi = "0.5.1" parity-wasm = "0.40.3" lazy_static = "1.4.0" wasm-interface = { package = "substrate-wasm-interface", path = "../wasm-interface" } +externalities = { package = "substrate-externalities", path = "../externalities" } parking_lot = "0.9.0" log = "0.4.8" libsecp256k1 = "0.3.0" diff --git a/substrate/core/executor/src/lib.rs b/substrate/core/executor/src/lib.rs index 8b833c9b08..ccc78afdb4 100644 --- a/substrate/core/executor/src/lib.rs +++ b/substrate/core/executor/src/lib.rs @@ -45,7 +45,7 @@ pub use native_executor::{with_native_environment, NativeExecutor, NativeExecuti pub use runtime_version::{RuntimeVersion, NativeVersion}; pub use codec::Codec; #[doc(hidden)] -pub use primitives::{Blake2Hasher, traits::Externalities}; +pub use primitives::traits::Externalities; #[doc(hidden)] pub use wasm_interface; pub use wasm_runtime::WasmExecutionMethod; @@ -56,7 +56,7 @@ pub trait RuntimeInfo { fn native_version(&self) -> &NativeVersion; /// Extract RuntimeVersion of given :code block - fn runtime_version> ( + fn runtime_version ( &self, ext: &mut E, ) -> Option; diff --git a/substrate/core/executor/src/native_executor.rs b/substrate/core/executor/src/native_executor.rs index 5f4e91b16d..7323703ed9 100644 --- a/substrate/core/executor/src/native_executor.rs +++ b/substrate/core/executor/src/native_executor.rs @@ -20,7 +20,7 @@ use crate::wasm_runtime::{RuntimesCache, WasmExecutionMethod, WasmRuntime}; use crate::RuntimeInfo; use runtime_version::{NativeVersion, RuntimeVersion}; use codec::{Decode, Encode}; -use primitives::{Blake2Hasher, NativeOrEncoded, traits::{CodeExecutor, Externalities}}; +use primitives::{NativeOrEncoded, traits::{CodeExecutor, Externalities}}; use log::{trace, warn}; thread_local! { @@ -41,10 +41,10 @@ fn safe_call(f: F) -> Result /// Set up the externalities and safe calling environment to execute calls to a native runtime. /// /// If the inner closure panics, it will be caught and return an error. -pub fn with_native_environment(ext: &mut dyn Externalities, f: F) -> Result +pub fn with_native_environment(ext: &mut dyn Externalities, f: F) -> Result where F: UnwindSafe + FnOnce() -> U { - runtime_io::with_externalities(ext, move || safe_call(f)) + externalities::set_and_run_with_externalities(ext, move || safe_call(f)) } /// Delegate for dispatching a CodeExecutor call. @@ -54,7 +54,7 @@ pub trait NativeExecutionDispatch: Send + Sync { /// Dispatch a method in the runtime. /// /// If the method with the specified name doesn't exist then `Err` is returned. - fn dispatch(ext: &mut dyn Externalities, method: &str, data: &[u8]) -> Result>; + fn dispatch(ext: &mut dyn Externalities, method: &str, data: &[u8]) -> Result>; /// Provide native runtime version. fn native_version() -> NativeVersion; @@ -95,10 +95,8 @@ impl NativeExecutor { fn with_runtime( &self, ext: &mut E, - f: impl for <'a> FnOnce(&'a mut dyn WasmRuntime, &'a mut E) -> Result - ) -> Result - where E: Externalities - { + f: impl for <'a> FnOnce(&'a mut dyn WasmRuntime, &'a mut E) -> Result, + ) -> Result where E: Externalities { RUNTIMES_CACHE.with(|cache| { let mut cache = cache.borrow_mut(); let runtime = cache.fetch_runtime(ext, self.fallback_method, self.default_heap_pages)?; @@ -123,7 +121,7 @@ impl RuntimeInfo for NativeExecutor { &self.native_version } - fn runtime_version>( + fn runtime_version( &self, ext: &mut E, ) -> Option { @@ -137,12 +135,12 @@ impl RuntimeInfo for NativeExecutor { } } -impl CodeExecutor for NativeExecutor { +impl CodeExecutor for NativeExecutor { type Error = Error; fn call < - E: Externalities, + E: Externalities, R:Decode + Encode + PartialEq, NC: FnOnce() -> result::Result + UnwindSafe >( @@ -220,7 +218,7 @@ macro_rules! native_executor_instance { (IMPL $name:ident, $dispatcher:path, $version:path) => { impl $crate::NativeExecutionDispatch for $name { fn dispatch( - ext: &mut $crate::Externalities<$crate::Blake2Hasher>, + ext: &mut $crate::Externalities, method: &str, data: &[u8] ) -> $crate::error::Result> { diff --git a/substrate/core/executor/src/sandbox.rs b/substrate/core/executor/src/sandbox.rs index de49cc9f7c..3a213ccdf0 100644 --- a/substrate/core/executor/src/sandbox.rs +++ b/substrate/core/executor/src/sandbox.rs @@ -593,9 +593,9 @@ mod tests { use wabt; use runtime_test::WASM_BINARY; - type TestExternalities = CoreTestExternalities; + type TestExternalities = CoreTestExternalities; - fn call_wasm>( + fn call_wasm( ext: &mut E, heap_pages: u64, code: &[u8], @@ -609,7 +609,7 @@ mod tests { #[test] fn sandbox_should_work() { - let mut ext = TestExternalities::::default(); + let mut ext = TestExternalities::default(); let test_code = WASM_BINARY; let code = wabt::wat2wasm(r#" @@ -641,7 +641,7 @@ mod tests { #[test] fn sandbox_trap() { - let mut ext = TestExternalities::::default(); + let mut ext = TestExternalities::default(); let test_code = WASM_BINARY; let code = wabt::wat2wasm(r#" @@ -662,7 +662,7 @@ mod tests { #[test] fn sandbox_should_trap_when_heap_exhausted() { - let mut ext = TestExternalities::::default(); + let mut ext = TestExternalities::default(); let test_code = WASM_BINARY; let code = wabt::wat2wasm(r#" @@ -690,7 +690,7 @@ mod tests { #[test] fn start_called() { - let mut ext = TestExternalities::::default(); + let mut ext = TestExternalities::default(); let test_code = WASM_BINARY; let code = wabt::wat2wasm(r#" @@ -728,7 +728,7 @@ mod tests { #[test] fn invoke_args() { - let mut ext = TestExternalities::::default(); + let mut ext = TestExternalities::default(); let test_code = WASM_BINARY; let code = wabt::wat2wasm(r#" @@ -762,7 +762,7 @@ mod tests { #[test] fn return_val() { - let mut ext = TestExternalities::::default(); + let mut ext = TestExternalities::default(); let test_code = WASM_BINARY; let code = wabt::wat2wasm(r#" @@ -784,7 +784,7 @@ mod tests { #[test] fn unlinkable_module() { - let mut ext = TestExternalities::::default(); + let mut ext = TestExternalities::default(); let test_code = WASM_BINARY; let code = wabt::wat2wasm(r#" @@ -804,7 +804,7 @@ mod tests { #[test] fn corrupted_module() { - let mut ext = TestExternalities::::default(); + let mut ext = TestExternalities::default(); let test_code = WASM_BINARY; // Corrupted wasm file @@ -818,7 +818,7 @@ mod tests { #[test] fn start_fn_ok() { - let mut ext = TestExternalities::::default(); + let mut ext = TestExternalities::default(); let test_code = WASM_BINARY; let code = wabt::wat2wasm(r#" @@ -841,7 +841,7 @@ mod tests { #[test] fn start_fn_traps() { - let mut ext = TestExternalities::::default(); + let mut ext = TestExternalities::default(); let test_code = WASM_BINARY; let code = wabt::wat2wasm(r#" diff --git a/substrate/core/executor/src/wasm_runtime.rs b/substrate/core/executor/src/wasm_runtime.rs index 27b65d6551..d88ae7b9ed 100644 --- a/substrate/core/executor/src/wasm_runtime.rs +++ b/substrate/core/executor/src/wasm_runtime.rs @@ -23,7 +23,7 @@ use crate::error::{Error, WasmError}; use crate::wasmi_execution; use log::{trace, warn}; use codec::Decode; -use primitives::{storage::well_known_keys, Blake2Hasher, traits::Externalities}; +use primitives::{storage::well_known_keys, traits::Externalities}; use runtime_version::RuntimeVersion; use std::{collections::hash_map::{Entry, HashMap}}; @@ -36,8 +36,8 @@ pub trait WasmRuntime { fn update_heap_pages(&mut self, heap_pages: u64) -> bool; /// Call a method in the Substrate runtime by name. Returns the encoded result on success. - fn call(&mut self, ext: &mut dyn Externalities, method: &str, data: &[u8]) - -> Result, Error>; + fn call(&mut self, ext: &mut dyn Externalities, method: &str, data: &[u8]) + -> Result, Error>; /// Returns the version of this runtime. /// @@ -109,7 +109,7 @@ impl RuntimesCache { /// /// `Error::InvalidMemoryReference` is returned if no memory export with the /// identifier `memory` can be found in the runtime. - pub fn fetch_runtime>( + pub fn fetch_runtime( &mut self, ext: &mut E, wasm_method: WasmExecutionMethod, @@ -157,7 +157,7 @@ impl RuntimesCache { } } -fn create_wasm_runtime>( +fn create_wasm_runtime( ext: &mut E, wasm_method: WasmExecutionMethod, heap_pages: u64, diff --git a/substrate/core/executor/src/wasmi_execution.rs b/substrate/core/executor/src/wasmi_execution.rs index e228372bd3..0719ff4d40 100644 --- a/substrate/core/executor/src/wasmi_execution.rs +++ b/substrate/core/executor/src/wasmi_execution.rs @@ -23,7 +23,7 @@ use wasmi::{ }; use crate::error::{Error, WasmError}; use codec::{Encode, Decode}; -use primitives::{sandbox as sandbox_primitives, Blake2Hasher, traits::Externalities}; +use primitives::{sandbox as sandbox_primitives, traits::Externalities}; use crate::host_interface::SubstrateExternals; use crate::sandbox; use crate::allocator; @@ -342,7 +342,7 @@ fn get_heap_base(module: &ModuleRef) -> Result { /// Call a given method in the given wasm-module runtime. fn call_in_wasm_module( - ext: &mut dyn Externalities, + ext: &mut dyn Externalities, module_instance: &ModuleRef, method: &str, data: &[u8], @@ -373,7 +373,7 @@ fn call_in_wasm_module_with_custom_signature< FR: FnOnce(Option, &MemoryRef) -> Result, Error>, R, >( - ext: &mut dyn Externalities, + ext: &mut dyn Externalities, module_instance: &ModuleRef, method: &str, create_parameters: F, @@ -398,7 +398,7 @@ fn call_in_wasm_module_with_custom_signature< fec.write_memory(offset, data).map(|_| offset.into()).map_err(Into::into) })?; - let result = runtime_io::with_externalities( + let result = externalities::set_and_run_with_externalities( ext, || module_instance.invoke_export(method, ¶meters, &mut fec), ); @@ -588,7 +588,7 @@ impl WasmRuntime for WasmiRuntime { self.state_snapshot.heap_pages == heap_pages } - fn call(&mut self, ext: &mut dyn Externalities, method: &str, data: &[u8]) + fn call(&mut self, ext: &mut dyn Externalities, method: &str, data: &[u8]) -> Result, Error> { self.with(|module| { @@ -601,7 +601,7 @@ impl WasmRuntime for WasmiRuntime { } } -pub fn create_instance>(ext: &mut E, code: &[u8], heap_pages: u64) +pub fn create_instance(ext: &mut E, code: &[u8], heap_pages: u64) -> Result { let module = Module::from_buffer(&code).map_err(|_| WasmError::InvalidModule)?; @@ -656,14 +656,16 @@ mod tests { use state_machine::TestExternalities as CoreTestExternalities; use hex_literal::hex; - use primitives::{blake2_128, blake2_256, ed25519, sr25519, map, Pair}; + use primitives::{ + Blake2Hasher, blake2_128, blake2_256, ed25519, sr25519, map, Pair, offchain::OffchainExt, + }; use runtime_test::WASM_BINARY; use substrate_offchain::testing; use trie::{TrieConfiguration, trie_types::Layout}; - type TestExternalities = CoreTestExternalities; + type TestExternalities = CoreTestExternalities; - fn call>( + fn call( ext: &mut E, heap_pages: u64, code: &[u8], @@ -798,7 +800,7 @@ mod tests { #[test] fn ed25519_verify_should_work() { - let mut ext = TestExternalities::::default(); + let mut ext = TestExternalities::default(); let test_code = WASM_BINARY; let key = ed25519::Pair::from_seed(&blake2_256(b"test")); let sig = key.sign(b"all ok!"); @@ -824,7 +826,7 @@ mod tests { #[test] fn sr25519_verify_should_work() { - let mut ext = TestExternalities::::default(); + let mut ext = TestExternalities::default(); let test_code = WASM_BINARY; let key = sr25519::Pair::from_seed(&blake2_256(b"test")); let sig = key.sign(b"all ok!"); @@ -850,7 +852,7 @@ mod tests { #[test] fn ordered_trie_root_should_work() { - let mut ext = TestExternalities::::default(); + let mut ext = TestExternalities::default(); let trie_input = vec![b"zero".to_vec(), b"one".to_vec(), b"two".to_vec()]; let test_code = WASM_BINARY; assert_eq!( @@ -863,9 +865,9 @@ mod tests { fn offchain_local_storage_should_work() { use substrate_client::backend::OffchainStorage; - let mut ext = TestExternalities::::default(); + let mut ext = TestExternalities::default(); let (offchain, state) = testing::TestOffchainExt::new(); - ext.set_offchain_externalities(offchain); + ext.register_extension(OffchainExt::new(offchain)); let test_code = WASM_BINARY; assert_eq!( call(&mut ext, 8, &test_code[..], "test_offchain_local_storage", &[]).unwrap(), @@ -876,9 +878,9 @@ mod tests { #[test] fn offchain_http_should_work() { - let mut ext = TestExternalities::::default(); + let mut ext = TestExternalities::default(); let (offchain, state) = testing::TestOffchainExt::new(); - ext.set_offchain_externalities(offchain); + ext.register_extension(OffchainExt::new(offchain)); state.write().expect_request( 0, testing::PendingRequest { diff --git a/substrate/core/externalities/Cargo.toml b/substrate/core/externalities/Cargo.toml new file mode 100644 index 0000000000..97ece5439a --- /dev/null +++ b/substrate/core/externalities/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "substrate-externalities" +version = "2.0.0" +license = "GPL-3.0" +authors = ["Parity Technologies "] +edition = "2018" + +[dependencies] +primitive-types = { version = "0.5.1", features = ["codec"] } +primitives-storage = { package = "substrate-primitives-storage", path = "../primitives/storage" } +rstd = { package = "sr-std", path = "../sr-std" } +environmental = { version = "1.0.2" } diff --git a/substrate/core/externalities/src/extensions.rs b/substrate/core/externalities/src/extensions.rs new file mode 100644 index 0000000000..c7d7bc4853 --- /dev/null +++ b/substrate/core/externalities/src/extensions.rs @@ -0,0 +1,127 @@ +// Copyright 2017-2019 Parity Technologies (UK) Ltd. +// This file is part of Substrate. + +// Substrate is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Substrate is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Substrate. If not, see . + +//! Externalities extensions storage. +//! +//! Externalities support to register a wide variety custom extensions. The [`Extensions`] provides +//! some convenience functionality to store and retrieve these extensions. +//! +//! It is required that each extension implements the [`Extension`] trait. + +use std::{collections::HashMap, any::{Any, TypeId}, ops::DerefMut}; + +/// Marker trait for types that should be registered as [`Externalities`](crate::Externalities) extension. +/// +/// As extensions are stored as `Box`, this trait should give more confidence that the correct +/// type is registered and requested. +pub trait Extension: Sized {} + +/// Macro for declaring an extension that usable with [`Extensions`]. +/// +/// The extension will be an unit wrapper struct that implements [`Extension`], `Deref` and +/// `DerefMut`. The wrapped type is given by the user. +/// +/// # Example +/// ``` +/// # use substrate_externalities::decl_extension; +/// decl_extension! { +/// /// Some test extension +/// struct TestExt(String); +/// } +/// ``` +#[macro_export] +macro_rules! decl_extension { + ( + $( #[ $attr:meta ] )* + $vis:vis struct $ext_name:ident ($inner:ty); + ) => { + $( #[ $attr ] )* + $vis struct $ext_name (pub $inner); + + impl $crate::Extension for $ext_name {} + + impl std::ops::Deref for $ext_name { + type Target = $inner; + + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + impl std::ops::DerefMut for $ext_name { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } + } + } +} + +/// Something that provides access to the [`Extensions`] store. +/// +/// This is a super trait of the [`Externalities`](crate::Externalities). +pub trait ExtensionStore { + /// Tries to find a registered extension by the given `type_id` and returns it as a `&mut dyn Any`. + /// + /// It is advised to use [`ExternalitiesExt::extension`](crate::ExternalitiesExt::extension) + /// instead of this function to get type system support and automatic type downcasting. + fn extension_by_type_id(&mut self, type_id: TypeId) -> Option<&mut dyn Any>; +} + +/// Stores extensions that should be made available through the externalities. +#[derive(Default)] +pub struct Extensions { + extensions: HashMap>, +} + +impl Extensions { + /// Create new instance of `Self`. + pub fn new() -> Self { + Self::default() + } + + /// Register the given extension. + pub fn register(&mut self, ext: E) { + self.extensions.insert(ext.type_id(), Box::new(ext)); + } + + /// Return a mutable reference to the requested extension. + pub fn get_mut(&mut self, ext_type_id: TypeId) -> Option<&mut dyn Any> { + self.extensions.get_mut(&ext_type_id).map(DerefMut::deref_mut) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + struct DummyExt(u32); + impl Extension for DummyExt {} + + struct DummyExt2(u32); + impl Extension for DummyExt2 {} + + #[test] + fn register_and_retrieve_extension() { + let mut exts = Extensions::new(); + exts.register(DummyExt(1)); + exts.register(DummyExt2(2)); + + let ext = exts.get_mut(TypeId::of::()).expect("Extension is registered"); + let ext_ty = ext.downcast_mut::().expect("Downcasting works"); + + assert_eq!(ext_ty.0, 1); + } +} diff --git a/substrate/core/externalities/src/lib.rs b/substrate/core/externalities/src/lib.rs new file mode 100644 index 0000000000..ecd5f7a7a7 --- /dev/null +++ b/substrate/core/externalities/src/lib.rs @@ -0,0 +1,139 @@ +// Copyright 2017-2019 Parity Technologies (UK) Ltd. +// This file is part of Substrate. + +// Substrate is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Substrate is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Substrate. If not, see . + +//! Substrate externalities abstraction +//! +//! The externalities mainly provide access to storage and to registered extensions. Extensions +//! are for example the keystore or the offchain externalities. These externalities are used to +//! access the node from the runtime via the runtime interfaces. +//! +//! This crate exposes the main [`Externalities`] trait. + +use primitive_types::H256; + +use std::any::{Any, TypeId}; + +use primitives_storage::ChildStorageKey; + +pub use scope_limited::{set_and_run_with_externalities, with_externalities}; +pub use extensions::{Extension, Extensions, ExtensionStore}; + +mod extensions; +mod scope_limited; + +/// The Substrate externalities. +/// +/// Provides access to the storage and to other registered extensions. +pub trait Externalities: ExtensionStore { + /// Read runtime storage. + fn storage(&self, key: &[u8]) -> Option>; + + /// Get storage value hash. This may be optimized for large values. + fn storage_hash(&self, key: &[u8]) -> Option; + + /// Get child storage value hash. This may be optimized for large values. + fn child_storage_hash(&self, storage_key: ChildStorageKey, key: &[u8]) -> Option; + + /// Read original runtime storage, ignoring any overlayed changes. + fn original_storage(&self, key: &[u8]) -> Option>; + + /// Read original runtime child storage, ignoring any overlayed changes. + fn original_child_storage(&self, storage_key: ChildStorageKey, key: &[u8]) -> Option>; + + /// Get original storage value hash, ignoring any overlayed changes. + /// This may be optimized for large values. + fn original_storage_hash(&self, key: &[u8]) -> Option; + + /// Get original child storage value hash, ignoring any overlayed changes. + /// This may be optimized for large values. + fn original_child_storage_hash(&self, storage_key: ChildStorageKey, key: &[u8]) -> Option; + + /// Read child runtime storage. + fn child_storage(&self, storage_key: ChildStorageKey, key: &[u8]) -> Option>; + + /// Set storage entry `key` of current contract being called (effective immediately). + fn set_storage(&mut self, key: Vec, value: Vec) { + self.place_storage(key, Some(value)); + } + + /// Set child storage entry `key` of current contract being called (effective immediately). + fn set_child_storage(&mut self, storage_key: ChildStorageKey, key: Vec, value: Vec) { + self.place_child_storage(storage_key, key, Some(value)) + } + + /// Clear a storage entry (`key`) of current contract being called (effective immediately). + fn clear_storage(&mut self, key: &[u8]) { + self.place_storage(key.to_vec(), None); + } + + /// Clear a child storage entry (`key`) of current contract being called (effective immediately). + fn clear_child_storage(&mut self, storage_key: ChildStorageKey, key: &[u8]) { + self.place_child_storage(storage_key, key.to_vec(), None) + } + + /// Whether a storage entry exists. + fn exists_storage(&self, key: &[u8]) -> bool { + self.storage(key).is_some() + } + + /// Whether a child storage entry exists. + fn exists_child_storage(&self, storage_key: ChildStorageKey, key: &[u8]) -> bool { + self.child_storage(storage_key, key).is_some() + } + + /// Clear an entire child storage. + fn kill_child_storage(&mut self, storage_key: ChildStorageKey); + + /// Clear storage entries which keys are start with the given prefix. + fn clear_prefix(&mut self, prefix: &[u8]); + + /// Clear child storage entries which keys are start with the given prefix. + fn clear_child_prefix(&mut self, storage_key: ChildStorageKey, prefix: &[u8]); + + /// Set or clear a storage entry (`key`) of current contract being called (effective immediately). + fn place_storage(&mut self, key: Vec, value: Option>); + + /// Set or clear a child storage entry. Return whether the operation succeeds. + fn place_child_storage(&mut self, storage_key: ChildStorageKey, key: Vec, value: Option>); + + /// Get the identity of the chain. + fn chain_id(&self) -> u64; + + /// Get the trie root of the current storage map. This will also update all child storage keys + /// in the top-level storage map. + fn storage_root(&mut self) -> H256; + + /// Get the trie root of a child storage map. This will also update the value of the child + /// storage keys in the top-level storage map. + /// If the storage root equals the default hash as defined by the trie, the key in the top-level + /// storage map will be removed. + fn child_storage_root(&mut self, storage_key: ChildStorageKey) -> Vec; + + /// Get the change trie root of the current storage overlay at a block with given parent. + fn storage_changes_root(&mut self, parent: H256) -> Result, ()>; +} + +/// Extension for the [`Externalities`] trait. +pub trait ExternalitiesExt { + /// Tries to find a registered extension and returns a mutable reference. + fn extension(&mut self) -> Option<&mut T>; +} + +impl ExternalitiesExt for T { + fn extension(&mut self) -> Option<&mut A> { + self.extension_by_type_id(TypeId::of::()).and_then(Any::downcast_mut) + } +} diff --git a/substrate/core/externalities/src/scope_limited.rs b/substrate/core/externalities/src/scope_limited.rs new file mode 100644 index 0000000000..ae185449be --- /dev/null +++ b/substrate/core/externalities/src/scope_limited.rs @@ -0,0 +1,37 @@ +// Copyright 2019 Parity Technologies (UK) Ltd. +// This file is part of Substrate. + +// Substrate is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Substrate is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Substrate. If not, see . + +//! Stores the externalities in an `environmental` value to make it scope limited available. + +use crate::Externalities; + +environmental::environmental!(ext: trait Externalities); + +/// Set the given externalities while executing the given closure. To get access to the externalities +/// while executing the given closure [`with_externalities`] grants access to them. The externalities +/// are only set for the same thread this function was called from. +pub fn set_and_run_with_externalities(ext: &mut dyn Externalities, f: F) -> R + where F: FnOnce() -> R +{ + ext::using(ext, f) +} + +/// Execute the given closure with the currently set externalities. +/// +/// Returns `None` if no externalities are set or `Some(_)` with the result of the closure. +pub fn with_externalities R, R>(f: F) -> Option { + ext::with(f) +} diff --git a/substrate/core/finality-grandpa/src/finality_proof.rs b/substrate/core/finality-grandpa/src/finality_proof.rs index bae6c8ebc0..da5732f2f6 100644 --- a/substrate/core/finality-grandpa/src/finality_proof.rs +++ b/substrate/core/finality-grandpa/src/finality_proof.rs @@ -48,7 +48,7 @@ use sr_primitives::{ Justification, generic::BlockId, traits::{NumberFor, Block as BlockT, Header as HeaderT, One}, }; -use primitives::{H256, Blake2Hasher, offchain::NeverOffchainExt}; +use primitives::{H256, Blake2Hasher}; use substrate_telemetry::{telemetry, CONSENSUS_INFO}; use fg_primitives::AuthorityId; @@ -78,7 +78,7 @@ impl, RA> AuthoritySetForFinalityProver fo "GrandpaApi_grandpa_authorities", &[], ExecutionStrategy::NativeElseWasm, - NeverOffchainExt::new(), + None, ).and_then(|call_result| Decode::decode(&mut &call_result[..]) .map_err(|err| ClientError::CallResultDecode( "failed to decode GRANDPA authorities set proof".into(), err diff --git a/substrate/core/primitives/Cargo.toml b/substrate/core/primitives/Cargo.toml index 461a8fe7e3..a527f16c1c 100644 --- a/substrate/core/primitives/Cargo.toml +++ b/substrate/core/primitives/Cargo.toml @@ -31,6 +31,8 @@ num-traits = { version = "0.2.8", default-features = false } zeroize = "0.10.1" lazy_static = { version = "1.4.0", optional = true } parking_lot = { version = "0.9.0", optional = true } +externalities = { package = "substrate-externalities", path = "../externalities", optional = true } +primitives-storage = { package = "substrate-primitives-storage", path = "storage", default-features = false } [dev-dependencies] substrate-serializer = { path = "../serializer" } @@ -52,7 +54,7 @@ std = [ "log", "wasmi", "lazy_static", - "parking_lot", + "parking_lot", "primitive-types/std", "primitive-types/serde", "primitive-types/byteorder", @@ -79,4 +81,6 @@ std = [ "schnorrkel", "regex", "num-traits/std", + "externalities", + "primitives-storage/std", ] diff --git a/substrate/core/primitives/src/child_storage_key.rs b/substrate/core/primitives/src/child_storage_key.rs deleted file mode 100644 index eba34c1ef9..0000000000 --- a/substrate/core/primitives/src/child_storage_key.rs +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2019 Parity Technologies (UK) Ltd. -// This file is part of Substrate. - -// Substrate is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Substrate is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Substrate. If not, see . - -//! Provides a wrapper around a child storage key. - -use crate::storage::well_known_keys::is_child_trie_key_valid; -use rstd::{borrow::Cow, vec::Vec}; - -/// A wrapper around a child storage key. -/// -/// This wrapper ensures that the child storage key is correct and properly used. It is -/// impossible to create an instance of this struct without providing a correct `storage_key`. -pub struct ChildStorageKey<'a> { - storage_key: Cow<'a, [u8]>, -} - -impl<'a> ChildStorageKey<'a> { - fn new(storage_key: Cow<'a, [u8]>) -> Option { - if is_child_trie_key_valid(&storage_key) { - Some(ChildStorageKey { storage_key }) - } else { - None - } - } - - /// Create a new `ChildStorageKey` from a vector. - /// - /// `storage_key` need to start with `:child_storage:default:` - /// See `is_child_trie_key_valid` for more details. - pub fn from_vec(key: Vec) -> Option { - Self::new(Cow::Owned(key)) - } - - /// Create a new `ChildStorageKey` from a slice. - /// - /// `storage_key` need to start with `:child_storage:default:` - /// See `is_child_trie_key_valid` for more details. - pub fn from_slice(key: &'a [u8]) -> Option { - Self::new(Cow::Borrowed(key)) - } - - /// Get access to the byte representation of the storage key. - /// - /// This key is guaranteed to be correct. - pub fn as_ref(&self) -> &[u8] { - &*self.storage_key - } - - /// Destruct this instance into an owned vector that represents the storage key. - /// - /// This key is guaranteed to be correct. - pub fn into_owned(self) -> Vec { - self.storage_key.into_owned() - } -} diff --git a/substrate/core/primitives/src/lib.rs b/substrate/core/primitives/src/lib.rs index 310f0133ef..b1ce6e2f97 100644 --- a/substrate/core/primitives/src/lib.rs +++ b/substrate/core/primitives/src/lib.rs @@ -54,16 +54,15 @@ pub mod crypto; pub mod u32_trait; -pub mod child_storage_key; pub mod ed25519; pub mod sr25519; pub mod hash; mod hasher; pub mod offchain; pub mod sandbox; -pub mod storage; pub mod uint; mod changes_trie; +#[cfg(feature = "std")] pub mod traits; pub mod testing; @@ -81,6 +80,8 @@ pub use hash_db::Hasher; // pub use self::hasher::blake::BlakeHasher; pub use self::hasher::blake2::Blake2Hasher; +pub use primitives_storage as storage; + /// Context for executing a call into the runtime. pub enum ExecutionContext { /// Context for general importing (including own blocks). diff --git a/substrate/core/primitives/src/offchain.rs b/substrate/core/primitives/src/offchain.rs index 6403a20dbd..84fee530f6 100644 --- a/substrate/core/primitives/src/offchain.rs +++ b/substrate/core/primitives/src/offchain.rs @@ -17,8 +17,7 @@ //! Offchain workers types use codec::{Encode, Decode}; -use rstd::prelude::{Vec, Box}; -use rstd::convert::TryFrom; +use rstd::{prelude::{Vec, Box}, convert::TryFrom}; pub use crate::crypto::KeyTypeId; @@ -663,110 +662,17 @@ impl Externalities for LimitedExternalities { } } -/// An implementation of offchain extensions that should never be triggered. -pub enum NeverOffchainExt {} - -impl NeverOffchainExt { - /// Create new offchain extensions. - pub fn new<'a>() -> Option<&'a mut Self> { - None - } +#[cfg(feature = "std")] +externalities::decl_extension! { + /// The offchain extension that will be registered at the Substrate externalities. + pub struct OffchainExt(Box); } -impl Externalities for NeverOffchainExt { - fn is_validator(&self) -> bool { - unreachable!() - } - - fn submit_transaction(&mut self, _extrinsic: Vec) -> Result<(), ()> { - unreachable!() - } - - fn network_state( - &self, - ) -> Result { - unreachable!() - } - - fn timestamp(&mut self) -> Timestamp { - unreachable!() - } - - fn sleep_until(&mut self, _deadline: Timestamp) { - unreachable!() - } - - fn random_seed(&mut self) -> [u8; 32] { - unreachable!() - } - - fn local_storage_set(&mut self, _kind: StorageKind, _key: &[u8], _value: &[u8]) { - unreachable!() - } - - fn local_storage_compare_and_set( - &mut self, - _kind: StorageKind, - _key: &[u8], - _old_value: Option<&[u8]>, - _new_value: &[u8], - ) -> bool { - unreachable!() - } - - fn local_storage_get(&mut self, _kind: StorageKind, _key: &[u8]) -> Option> { - unreachable!() - } - - fn http_request_start( - &mut self, - _method: &str, - _uri: &str, - _meta: &[u8] - ) -> Result { - unreachable!() - } - - fn http_request_add_header( - &mut self, - _request_id: HttpRequestId, - _name: &str, - _value: &str - ) -> Result<(), ()> { - unreachable!() - } - - fn http_request_write_body( - &mut self, - _request_id: HttpRequestId, - _chunk: &[u8], - _deadline: Option - ) -> Result<(), HttpError> { - unreachable!() - } - - fn http_response_wait( - &mut self, - _ids: &[HttpRequestId], - _deadline: Option - ) -> Vec { - unreachable!() - } - - fn http_response_headers( - &mut self, - _request_id: HttpRequestId - ) -> Vec<(Vec, Vec)> { - unreachable!() - } - - fn http_response_read_body( - &mut self, - _request_id: HttpRequestId, - _buffer: &mut [u8], - _deadline: Option - ) -> Result { - unreachable!() +#[cfg(feature = "std")] +impl OffchainExt { + /// Create a new instance of `Self`. + pub fn new(offchain: O) -> Self { + Self(Box::new(offchain)) } } diff --git a/substrate/core/primitives/src/testing.rs b/substrate/core/primitives/src/testing.rs index ccfc36af73..7fdefd8fe0 100644 --- a/substrate/core/primitives/src/testing.rs +++ b/substrate/core/primitives/src/testing.rs @@ -18,8 +18,7 @@ #[cfg(feature = "std")] use crate::{ed25519, sr25519, crypto::{Public, Pair}}; -use crate::crypto::KeyTypeId; // No idea why this import had to move from - // the previous line, but now the compiler is happy +use crate::crypto::KeyTypeId; /// Key type for generic Ed25519 key. pub const ED25519: KeyTypeId = KeyTypeId(*b"ed25"); @@ -37,7 +36,7 @@ pub struct KeyStore { #[cfg(feature = "std")] impl KeyStore { /// Creates a new instance of `Self`. - pub fn new() -> std::sync::Arc> { + pub fn new() -> crate::traits::BareCryptoStorePtr { std::sync::Arc::new(parking_lot::RwLock::new(Self::default())) } } @@ -133,7 +132,7 @@ impl crate::traits::BareCryptoStore for KeyStore { #[cfg(test)] mod tests { use super::*; - use crate::{sr25519, traits::BareCryptoStore}; + use crate::sr25519; use crate::testing::{ED25519, SR25519}; diff --git a/substrate/core/primitives/src/traits.rs b/substrate/core/primitives/src/traits.rs index b173d8512c..1ef665032e 100644 --- a/substrate/core/primitives/src/traits.rs +++ b/substrate/core/primitives/src/traits.rs @@ -16,15 +16,13 @@ //! Shareable Substrate traits. -#[cfg(feature = "std")] -use crate::{crypto::KeyTypeId, ed25519, sr25519, child_storage_key::ChildStorageKey}; -#[cfg(feature = "std")] +use crate::{crypto::KeyTypeId, ed25519, sr25519}; + use std::{fmt::{Debug, Display}, panic::UnwindSafe}; -#[cfg(feature = "std")] -use hash_db::Hasher; + +pub use externalities::{Externalities, ExternalitiesExt}; /// Something that generates, stores and provides access to keys. -#[cfg(feature = "std")] pub trait BareCryptoStore: Send + Sync { /// Returns all sr25519 public keys for the given key type. fn sr25519_public_keys(&self, id: KeyTypeId) -> Vec; @@ -70,128 +68,22 @@ pub trait BareCryptoStore: Send + Sync { } /// A pointer to the key store. -#[cfg(feature = "std")] pub type BareCryptoStorePtr = std::sync::Arc>; -/// Externalities: pinned to specific active address. -#[cfg(feature = "std")] -pub trait Externalities { - /// Read runtime storage. - fn storage(&self, key: &[u8]) -> Option>; - - /// Get storage value hash. This may be optimized for large values. - fn storage_hash(&self, key: &[u8]) -> Option { - self.storage(key).map(|v| H::hash(&v)) - } - - /// Get child storage value hash. This may be optimized for large values. - fn child_storage_hash(&self, storage_key: ChildStorageKey, key: &[u8]) -> Option { - self.child_storage(storage_key, key).map(|v| H::hash(&v)) - } - - /// Read original runtime storage, ignoring any overlayed changes. - fn original_storage(&self, key: &[u8]) -> Option>; - - /// Read original runtime child storage, ignoring any overlayed changes. - fn original_child_storage(&self, storage_key: ChildStorageKey, key: &[u8]) -> Option>; - - /// Get original storage value hash, ignoring any overlayed changes. - /// This may be optimized for large values. - fn original_storage_hash(&self, key: &[u8]) -> Option { - self.original_storage(key).map(|v| H::hash(&v)) - } - - /// Get original child storage value hash, ignoring any overlayed changes. - /// This may be optimized for large values. - fn original_child_storage_hash( - &self, - storage_key: ChildStorageKey, - key: &[u8], - ) -> Option { - self.original_child_storage(storage_key, key).map(|v| H::hash(&v)) - } - - /// Read child runtime storage. - fn child_storage(&self, storage_key: ChildStorageKey, key: &[u8]) -> Option>; - - /// Set storage entry `key` of current contract being called (effective immediately). - fn set_storage(&mut self, key: Vec, value: Vec) { - self.place_storage(key, Some(value)); - } - - /// Set child storage entry `key` of current contract being called (effective immediately). - fn set_child_storage(&mut self, storage_key: ChildStorageKey, key: Vec, value: Vec) { - self.place_child_storage(storage_key, key, Some(value)) - } - - /// Clear a storage entry (`key`) of current contract being called (effective immediately). - fn clear_storage(&mut self, key: &[u8]) { - self.place_storage(key.to_vec(), None); - } - - /// Clear a child storage entry (`key`) of current contract being called (effective immediately). - fn clear_child_storage(&mut self, storage_key: ChildStorageKey, key: &[u8]) { - self.place_child_storage(storage_key, key.to_vec(), None) - } - - /// Whether a storage entry exists. - fn exists_storage(&self, key: &[u8]) -> bool { - self.storage(key).is_some() - } - - /// Whether a child storage entry exists. - fn exists_child_storage(&self, storage_key: ChildStorageKey, key: &[u8]) -> bool { - self.child_storage(storage_key, key).is_some() - } - - /// Clear an entire child storage. - fn kill_child_storage(&mut self, storage_key: ChildStorageKey); - - /// Clear storage entries which keys are start with the given prefix. - fn clear_prefix(&mut self, prefix: &[u8]); - - /// Clear child storage entries which keys are start with the given prefix. - fn clear_child_prefix(&mut self, storage_key: ChildStorageKey, prefix: &[u8]); - - /// Set or clear a storage entry (`key`) of current contract being called (effective immediately). - fn place_storage(&mut self, key: Vec, value: Option>); - - /// Set or clear a child storage entry. Return whether the operation succeeds. - fn place_child_storage(&mut self, storage_key: ChildStorageKey, key: Vec, value: Option>); - - /// Get the identity of the chain. - fn chain_id(&self) -> u64; - - /// Get the trie root of the current storage map. This will also update all child storage keys - /// in the top-level storage map. - fn storage_root(&mut self) -> H::Out where H::Out: Ord; - - /// Get the trie root of a child storage map. This will also update the value of the child - /// storage keys in the top-level storage map. - /// If the storage root equals the default hash as defined by the trie, the key in the top-level - /// storage map will be removed. - fn child_storage_root(&mut self, storage_key: ChildStorageKey) -> Vec; - - /// Get the change trie root of the current storage overlay at a block with given parent. - fn storage_changes_root(&mut self, parent: H::Out) -> Result, ()> where H::Out: Ord; - - /// Returns offchain externalities extension if present. - fn offchain(&mut self) -> Option<&mut dyn crate::offchain::Externalities>; - - /// Returns the keystore. - fn keystore(&self) -> Option; +externalities::decl_extension! { + /// The keystore extension to register/retrieve from the externalities. + pub struct KeystoreExt(BareCryptoStorePtr); } /// Code execution engine. -#[cfg(feature = "std")] -pub trait CodeExecutor: Sized + Send + Sync { +pub trait CodeExecutor: Sized + Send + Sync { /// Externalities error type. type Error: Display + Debug + Send + 'static; /// Call a given method in the runtime. Returns a tuple of the result (either the output data /// or an execution error) together with a `bool`, which is true if native execution was used. fn call< - E: Externalities, + E: Externalities, R: codec::Codec + PartialEq, NC: FnOnce() -> Result + UnwindSafe, >( diff --git a/substrate/core/primitives/storage/Cargo.toml b/substrate/core/primitives/storage/Cargo.toml new file mode 100644 index 0000000000..5b1ed37d6a --- /dev/null +++ b/substrate/core/primitives/storage/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "substrate-primitives-storage" +version = "2.0.0" +authors = ["Parity Technologies "] +edition = "2018" +description = "Storage related primitives" + +[dependencies] +rstd = { package = "sr-std", path = "../../sr-std", default-features = false } +serde = { version = "1.0.101", optional = true, features = ["derive"] } +impl-serde = { version = "0.2.1", optional = true } + +[features] +default = [ "std" ] +std = [ "rstd/std", "serde", "impl-serde" ] diff --git a/substrate/core/primitives/src/storage.rs b/substrate/core/primitives/storage/src/lib.rs similarity index 62% rename from substrate/core/primitives/src/storage.rs rename to substrate/core/primitives/storage/src/lib.rs index 14c49bfaa9..334779ed5f 100644 --- a/substrate/core/primitives/src/storage.rs +++ b/substrate/core/primitives/storage/src/lib.rs @@ -14,23 +14,30 @@ // You should have received a copy of the GNU General Public License // along with Substrate. If not, see . -//! Contract execution data. +//! Primitive types for storage related stuff. + +#![cfg_attr(not(feature = "std"), no_std)] #[cfg(feature = "std")] use serde::{Serialize, Deserialize}; -#[cfg(feature = "std")] -use crate::bytes; -use rstd::vec::Vec; -/// Contract storage key. +use rstd::{vec::Vec, borrow::Cow}; + +/// Storage key. #[derive(PartialEq, Eq)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug, Hash, PartialOrd, Ord, Clone))] -pub struct StorageKey(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec); +pub struct StorageKey( + #[cfg_attr(feature = "std", serde(with="impl_serde::serialize"))] + pub Vec, +); -/// Contract storage entry data. +/// Storage data associated to a [`StorageKey`]. #[derive(PartialEq, Eq)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug, Hash, PartialOrd, Ord, Clone))] -pub struct StorageData(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec); +pub struct StorageData( + #[cfg_attr(feature = "std", serde(with="impl_serde::serialize"))] + pub Vec, +); /// Storage change set #[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug, PartialEq, Eq))] @@ -39,15 +46,11 @@ pub struct StorageChangeSet { /// Block hash pub block: Hash, /// A list of changes - pub changes: Vec<( - StorageKey, - Option, - )>, + pub changes: Vec<(StorageKey, Option)>, } /// List of all well known keys and prefixes in storage. pub mod well_known_keys { - /// Wasm code of the runtime. /// /// Stored as a raw byte vector. Required by substrate. @@ -94,3 +97,52 @@ pub mod well_known_keys { has_right_prefix } } + +/// A wrapper around a child storage key. +/// +/// This wrapper ensures that the child storage key is correct and properly used. It is +/// impossible to create an instance of this struct without providing a correct `storage_key`. +pub struct ChildStorageKey<'a> { + storage_key: Cow<'a, [u8]>, +} + +impl<'a> ChildStorageKey<'a> { + /// Create new instance of `Self`. + fn new(storage_key: Cow<'a, [u8]>) -> Option { + if well_known_keys::is_child_trie_key_valid(&storage_key) { + Some(ChildStorageKey { storage_key }) + } else { + None + } + } + + /// Create a new `ChildStorageKey` from a vector. + /// + /// `storage_key` need to start with `:child_storage:default:` + /// See `is_child_trie_key_valid` for more details. + pub fn from_vec(key: Vec) -> Option { + Self::new(Cow::Owned(key)) + } + + /// Create a new `ChildStorageKey` from a slice. + /// + /// `storage_key` need to start with `:child_storage:default:` + /// See `is_child_trie_key_valid` for more details. + pub fn from_slice(key: &'a [u8]) -> Option { + Self::new(Cow::Borrowed(key)) + } + + /// Get access to the byte representation of the storage key. + /// + /// This key is guaranteed to be correct. + pub fn as_ref(&self) -> &[u8] { + &*self.storage_key + } + + /// Destruct this instance into an owned vector that represents the storage key. + /// + /// This key is guaranteed to be correct. + pub fn into_owned(self) -> Vec { + self.storage_key.into_owned() + } +} diff --git a/substrate/core/rpc/src/author/tests.rs b/substrate/core/rpc/src/author/tests.rs index 57d3929d92..202dab4940 100644 --- a/substrate/core/rpc/src/author/tests.rs +++ b/substrate/core/rpc/src/author/tests.rs @@ -24,8 +24,8 @@ use transaction_pool::{ FullChainApi, }; use primitives::{ - H256, blake2_256, hexdisplay::HexDisplay, traits::BareCryptoStore, - testing::{ED25519, SR25519, KeyStore}, ed25519, crypto::Pair + H256, blake2_256, hexdisplay::HexDisplay, testing::{ED25519, SR25519, KeyStore}, ed25519, + crypto::Pair, }; use test_client::{ self, AccountKeyring, runtime::{Extrinsic, Transfer, SessionKeys}, DefaultTestClientBuilderExt, @@ -212,7 +212,9 @@ fn should_insert_key() { fn should_rotate_keys() { let runtime = runtime::Runtime::new().unwrap(); let keystore = KeyStore::new(); - let client = Arc::new(test_client::TestClientBuilder::new().set_keystore(keystore.clone()).build()); + let client = Arc::new( + test_client::TestClientBuilder::new().set_keystore(keystore.clone()).build(), + ); let p = Author { client: client.clone(), pool: Arc::new(Pool::new(Default::default(), FullChainApi::new(client))), diff --git a/substrate/core/rpc/src/state/state_full.rs b/substrate/core/rpc/src/state/state_full.rs index 6f0472163f..cd05093c3a 100644 --- a/substrate/core/rpc/src/state/state_full.rs +++ b/substrate/core/rpc/src/state/state_full.rs @@ -33,8 +33,7 @@ use client::{ backend::Backend, error::Result as ClientResult, }; use primitives::{ - H256, Blake2Hasher, Bytes, offchain::NeverOffchainExt, - storage::{well_known_keys, StorageKey, StorageData, StorageChangeSet}, + H256, Blake2Hasher, Bytes, storage::{well_known_keys, StorageKey, StorageData, StorageChangeSet}, }; use runtime_version::RuntimeVersion; use state_machine::ExecutionStrategy; @@ -240,13 +239,16 @@ impl StateBackend for FullState FutureResult { Box::new(result( self.block_or_best(block) - .and_then(|block| self.client.executor() + .and_then(|block| + self + .client + .executor() .call( &BlockId::Hash(block), &method, &*call_data, ExecutionStrategy::NativeElseWasm, - NeverOffchainExt::new(), + None, ) .map(Into::into)) .map_err(client_err))) diff --git a/substrate/core/sr-io/Cargo.toml b/substrate/core/sr-io/Cargo.toml index 65b080b86d..e2b681b75b 100644 --- a/substrate/core/sr-io/Cargo.toml +++ b/substrate/core/sr-io/Cargo.toml @@ -15,9 +15,9 @@ codec = { package = "parity-scale-codec", version = "1.0.0", default-features = hash-db = { version = "0.15.2", default-features = false } libsecp256k1 = { version = "0.3.0", optional = true } tiny-keccak = { version = "1.5.0", optional = true } -environmental = { version = "1.0.2", optional = true } substrate-state-machine = { path = "../state-machine", optional = true } trie = { package = "substrate-trie", path = "../trie", optional = true } +externalities = { package = "substrate-externalities", path = "../externalities", optional = true } [features] default = ["std"] @@ -27,10 +27,10 @@ std = [ "rstd/std", "hash-db/std", "trie", - "environmental", "substrate-state-machine", "libsecp256k1", "tiny-keccak", + "externalities", ] nightly = [] strict = [] diff --git a/substrate/core/sr-io/src/lib.rs b/substrate/core/sr-io/src/lib.rs index 4b00a84231..24f964c7b5 100644 --- a/substrate/core/sr-io/src/lib.rs +++ b/substrate/core/sr-io/src/lib.rs @@ -368,13 +368,10 @@ mod imp { } #[cfg(feature = "std")] -pub use self::imp::{ - StorageOverlay, ChildrenStorageOverlay, with_storage, - with_externalities -}; +pub use self::imp::{StorageOverlay, ChildrenStorageOverlay, with_storage}; #[cfg(not(feature = "std"))] pub use self::imp::ext::*; /// Type alias for Externalities implementation used in tests. #[cfg(feature = "std")] -pub type TestExternalities = self::imp::TestExternalities; +pub type TestExternalities = self::imp::TestExternalities; diff --git a/substrate/core/sr-io/with_std.rs b/substrate/core/sr-io/with_std.rs index 919f4a913a..e431ae1f6e 100644 --- a/substrate/core/sr-io/with_std.rs +++ b/substrate/core/sr-io/with_std.rs @@ -16,19 +16,18 @@ use primitives::{ blake2_128, blake2_256, twox_128, twox_256, twox_64, ed25519, Blake2Hasher, sr25519, Pair, H256, - traits::Externalities, child_storage_key::ChildStorageKey, hexdisplay::HexDisplay, offchain, - Hasher, + traits::KeystoreExt, storage::ChildStorageKey, hexdisplay::HexDisplay, Hasher, + offchain::{self, OffchainExt}, }; // Switch to this after PoC-3 // pub use primitives::BlakeHasher; pub use substrate_state_machine::{BasicExternalities, TestExternalities}; -use environmental::environmental; use trie::{TrieConfiguration, trie_types::Layout}; use std::{collections::HashMap, convert::TryFrom}; -environmental!(ext: trait Externalities); +use externalities::{with_externalities, set_and_run_with_externalities, ExternalitiesExt}; /// Additional bounds for `Hasher` trait for with_std. pub trait HasherBounds {} @@ -48,12 +47,12 @@ fn child_storage_key_or_panic(storage_key: &[u8]) -> ChildStorageKey { impl StorageApi for () { fn storage(key: &[u8]) -> Option> { - ext::with(|ext| ext.storage(key).map(|s| s.to_vec())) + with_externalities(|ext| ext.storage(key).map(|s| s.to_vec())) .expect("storage cannot be called outside of an Externalities-provided environment.") } fn read_storage(key: &[u8], value_out: &mut [u8], value_offset: usize) -> Option { - ext::with(|ext| ext.storage(key).map(|value| { + with_externalities(|ext| ext.storage(key).map(|value| { let data = &value[value_offset.min(value.len())..]; let written = std::cmp::min(data.len(), value_out.len()); value_out[..written].copy_from_slice(&data[..written]); @@ -62,7 +61,7 @@ impl StorageApi for () { } fn child_storage(storage_key: &[u8], key: &[u8]) -> Option> { - ext::with(|ext| { + with_externalities(|ext| { let storage_key = child_storage_key_or_panic(storage_key); ext.child_storage(storage_key, key).map(|s| s.to_vec()) }) @@ -70,7 +69,7 @@ impl StorageApi for () { } fn set_storage(key: &[u8], value: &[u8]) { - ext::with(|ext| + with_externalities(|ext| ext.set_storage(key.to_vec(), value.to_vec()) ); } @@ -81,7 +80,7 @@ impl StorageApi for () { value_out: &mut [u8], value_offset: usize, ) -> Option { - ext::with(|ext| { + with_externalities(|ext| { let storage_key = child_storage_key_or_panic(storage_key); ext.child_storage(storage_key, key) .map(|value| { @@ -95,73 +94,71 @@ impl StorageApi for () { } fn set_child_storage(storage_key: &[u8], key: &[u8], value: &[u8]) { - ext::with(|ext| { + with_externalities(|ext| { let storage_key = child_storage_key_or_panic(storage_key); ext.set_child_storage(storage_key, key.to_vec(), value.to_vec()) }); } fn clear_storage(key: &[u8]) { - ext::with(|ext| + with_externalities(|ext| ext.clear_storage(key) ); } fn clear_child_storage(storage_key: &[u8], key: &[u8]) { - ext::with(|ext| { + with_externalities(|ext| { let storage_key = child_storage_key_or_panic(storage_key); ext.clear_child_storage(storage_key, key) }); } fn kill_child_storage(storage_key: &[u8]) { - ext::with(|ext| { + with_externalities(|ext| { let storage_key = child_storage_key_or_panic(storage_key); ext.kill_child_storage(storage_key) }); } fn exists_storage(key: &[u8]) -> bool { - ext::with(|ext| + with_externalities(|ext| ext.exists_storage(key) ).unwrap_or(false) } fn exists_child_storage(storage_key: &[u8], key: &[u8]) -> bool { - ext::with(|ext| { + with_externalities(|ext| { let storage_key = child_storage_key_or_panic(storage_key); ext.exists_child_storage(storage_key, key) }).unwrap_or(false) } fn clear_prefix(prefix: &[u8]) { - ext::with(|ext| - ext.clear_prefix(prefix) - ); + with_externalities(|ext| ext.clear_prefix(prefix)); } fn clear_child_prefix(storage_key: &[u8], prefix: &[u8]) { - ext::with(|ext| { + with_externalities(|ext| { let storage_key = child_storage_key_or_panic(storage_key); ext.clear_child_prefix(storage_key, prefix) }); } fn storage_root() -> [u8; 32] { - ext::with(|ext| + with_externalities(|ext| ext.storage_root() ).unwrap_or(H256::zero()).into() } fn child_storage_root(storage_key: &[u8]) -> Vec { - ext::with(|ext| { + with_externalities(|ext| { let storage_key = child_storage_key_or_panic(storage_key); ext.child_storage_root(storage_key) }).expect("child_storage_root cannot be called outside of an Externalities-provided environment.") } fn storage_changes_root(parent_hash: [u8; 32]) -> Option<[u8; 32]> { - ext::with(|ext| + with_externalities(|ext| ext.storage_changes_root(parent_hash.into()).map(|h| h.map(|h| h.into())) ).unwrap_or(Ok(None)).expect("Invalid parent hash passed to storage_changes_root") } @@ -177,7 +174,7 @@ impl StorageApi for () { impl OtherApi for () { fn chain_id() -> u64 { - ext::with(|ext| + with_externalities(|ext| ext.chain_id() ).unwrap_or(0) } @@ -199,8 +196,8 @@ impl OtherApi for () { impl CryptoApi for () { fn ed25519_public_keys(id: KeyTypeId) -> Vec { - ext::with(|ext| { - ext.keystore() + with_externalities(|ext| { + ext.extension::() .expect("No `keystore` associated for the current context!") .read() .ed25519_public_keys(id) @@ -208,8 +205,8 @@ impl CryptoApi for () { } fn ed25519_generate(id: KeyTypeId, seed: Option<&str>) -> ed25519::Public { - ext::with(|ext| { - ext.keystore() + with_externalities(|ext| { + ext.extension::() .expect("No `keystore` associated for the current context!") .write() .ed25519_generate_new(id, seed) @@ -224,8 +221,8 @@ impl CryptoApi for () { ) -> Option { let pub_key = ed25519::Public::try_from(pubkey.as_ref()).ok()?; - ext::with(|ext| { - ext.keystore() + with_externalities(|ext| { + ext.extension::() .expect("No `keystore` associated for the current context!") .read() .ed25519_key_pair(id, &pub_key) @@ -238,8 +235,8 @@ impl CryptoApi for () { } fn sr25519_public_keys(id: KeyTypeId) -> Vec { - ext::with(|ext| { - ext.keystore() + with_externalities(|ext| { + ext.extension::() .expect("No `keystore` associated for the current context!") .read() .sr25519_public_keys(id) @@ -247,8 +244,8 @@ impl CryptoApi for () { } fn sr25519_generate(id: KeyTypeId, seed: Option<&str>) -> sr25519::Public { - ext::with(|ext| { - ext.keystore() + with_externalities(|ext| { + ext.extension::() .expect("No `keystore` associated for the current context!") .write() .sr25519_generate_new(id, seed) @@ -263,8 +260,8 @@ impl CryptoApi for () { ) -> Option { let pub_key = sr25519::Public::try_from(pubkey.as_ref()).ok()?; - ext::with(|ext| { - ext.keystore() + with_externalities(|ext| { + ext.extension::() .expect("No `keystore` associated for the current context!") .read() .sr25519_key_pair(id, &pub_key) @@ -316,9 +313,9 @@ impl HashingApi for () { } fn with_offchain(f: impl FnOnce(&mut dyn offchain::Externalities) -> R, msg: &'static str) -> R { - ext::with(|ext| ext - .offchain() - .map(|ext| f(ext)) + with_externalities(|ext| ext + .extension::() + .map(|ext| f(&mut **ext)) .expect(msg) ).expect("offchain-worker functions cannot be called outside of an Externalities-provided environment.") } @@ -443,13 +440,6 @@ impl OffchainApi for () { impl Api for () {} -/// Execute the given closure with global function available whose functionality routes into the -/// externalities `ext`. Forwards the value that the closure returns. -// NOTE: need a concrete hasher here due to limitations of the `environmental!` macro, otherwise a type param would have been fine I think. -pub fn with_externalities R>(ext: &mut dyn Externalities, f: F) -> R { - ext::using(ext, f) -} - /// A set of key value pairs for storage. pub type StorageOverlay = HashMap, Vec>; @@ -467,7 +457,7 @@ pub fn with_storage R>( rstd::mem::swap(&mut alt_storage, storage); let mut ext = BasicExternalities::new(alt_storage.0, alt_storage.1); - let r = ext::using(&mut ext, f); + let r = set_and_run_with_externalities(&mut ext, f); *storage = ext.into_storages(); @@ -482,7 +472,7 @@ mod std_tests { #[test] fn storage_works() { let mut t = BasicExternalities::default(); - assert!(with_externalities(&mut t, || { + assert!(set_and_run_with_externalities(&mut t, || { assert_eq!(storage(b"hello"), None); set_storage(b"hello", b"world"); assert_eq!(storage(b"hello"), Some(b"world".to_vec())); @@ -493,7 +483,7 @@ mod std_tests { t = BasicExternalities::new(map![b"foo".to_vec() => b"bar".to_vec()], map![]); - assert!(!with_externalities(&mut t, || { + assert!(!set_and_run_with_externalities(&mut t, || { assert_eq!(storage(b"hello"), None); assert_eq!(storage(b"foo"), Some(b"bar".to_vec())); false @@ -506,7 +496,7 @@ mod std_tests { b":test".to_vec() => b"\x0b\0\0\0Hello world".to_vec() ], map![]); - with_externalities(&mut t, || { + set_and_run_with_externalities(&mut t, || { let mut v = [0u8; 4]; assert!(read_storage(b":test", &mut v[..], 0).unwrap() >= 4); assert_eq!(v, [11u8, 0, 0, 0]); @@ -525,7 +515,7 @@ mod std_tests { b":abdd".to_vec() => b"\x0b\0\0\0Hello world".to_vec() ], map![]); - with_externalities(&mut t, || { + set_and_run_with_externalities(&mut t, || { clear_prefix(b":abc"); assert!(storage(b":a").is_some()); diff --git a/substrate/core/sr-primitives/Cargo.toml b/substrate/core/sr-primitives/Cargo.toml index fc8b744d37..ab81df2b53 100644 --- a/substrate/core/sr-primitives/Cargo.toml +++ b/substrate/core/sr-primitives/Cargo.toml @@ -16,6 +16,7 @@ runtime_io = { package = "sr-io", path = "../sr-io", default-features = false } log = { version = "0.4.8", optional = true } paste = "0.1.6" rand = { version = "0.7.2", optional = true } +externalities = { package = "substrate-externalities", path = "../externalities", optional = true } impl-trait-for-tuples = "0.1.2" [dev-dependencies] @@ -36,4 +37,5 @@ std = [ "primitives/std", "app-crypto/std", "rand", + "externalities", ] diff --git a/substrate/core/sr-primitives/src/lib.rs b/substrate/core/sr-primitives/src/lib.rs index bdcbfb0b46..36d785f9a6 100644 --- a/substrate/core/sr-primitives/src/lib.rs +++ b/substrate/core/sr-primitives/src/lib.rs @@ -67,6 +67,9 @@ pub use sr_arithmetic::{ /// Re-export 128 bit helpers from sr_arithmetic pub use sr_arithmetic::helpers_128bit; +#[cfg(feature = "std")] +pub use externalities::set_and_run_with_externalities; + /// An abstraction over justification for a block's validity under a consensus algorithm. /// /// Essentially a finality proof. The exact formulation will vary between consensus diff --git a/substrate/core/sr-primitives/src/offchain/http.rs b/substrate/core/sr-primitives/src/offchain/http.rs index 6df18da83e..2d84f175d1 100644 --- a/substrate/core/sr-primitives/src/offchain/http.rs +++ b/substrate/core/sr-primitives/src/offchain/http.rs @@ -512,16 +512,18 @@ impl<'a> HeadersIterator<'a> { #[cfg(test)] mod tests { use super::*; - use runtime_io::{TestExternalities, with_externalities}; + use crate::set_and_run_with_externalities; + use runtime_io::TestExternalities; use substrate_offchain::testing; + use primitives::offchain::OffchainExt; #[test] fn should_send_a_basic_request_and_get_response() { let (offchain, state) = testing::TestOffchainExt::new(); let mut t = TestExternalities::default(); - t.set_offchain_externalities(offchain); + t.register_extension(OffchainExt::new(offchain)); - with_externalities(&mut t, || { + set_and_run_with_externalities(&mut t, || { let request: Request = Request::get("http://localhost:1234"); let pending = request .add_header("X-Auth", "hunter2") @@ -560,9 +562,9 @@ mod tests { fn should_send_a_post_request() { let (offchain, state) = testing::TestOffchainExt::new(); let mut t = TestExternalities::default(); - t.set_offchain_externalities(offchain); + t.register_extension(OffchainExt::new(offchain)); - with_externalities(&mut t, || { + set_and_run_with_externalities(&mut t, || { let pending = Request::default() .method(Method::Post) .url("http://localhost:1234") diff --git a/substrate/core/state-machine/Cargo.toml b/substrate/core/state-machine/Cargo.toml index 914fa04db8..7cd8601a3b 100644 --- a/substrate/core/state-machine/Cargo.toml +++ b/substrate/core/state-machine/Cargo.toml @@ -17,6 +17,7 @@ panic-handler = { package = "substrate-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 = "substrate-externalities", path = "../externalities" } [dev-dependencies] hex-literal = "0.2.1" diff --git a/substrate/core/state-machine/src/basic.rs b/substrate/core/state-machine/src/basic.rs index e45af45c9f..c2d1a0e395 100644 --- a/substrate/core/state-machine/src/basic.rs +++ b/substrate/core/state-machine/src/basic.rs @@ -16,15 +16,14 @@ //! Basic implementation for Externalities. -use std::collections::HashMap; -use std::iter::FromIterator; +use std::{collections::HashMap, any::{TypeId, Any}, iter::FromIterator}; use crate::backend::{Backend, InMemory}; use hash_db::Hasher; use trie::{TrieConfiguration, default_child_trie_root}; use trie::trie_types::Layout; use primitives::{ - storage::well_known_keys::is_child_storage_key, child_storage_key::ChildStorageKey, offchain, - traits::Externalities, + storage::{well_known_keys::is_child_storage_key, ChildStorageKey}, + traits::Externalities, Blake2Hasher, hash::H256, }; use log::warn; @@ -88,21 +87,37 @@ impl From, Vec>> for BasicExternalities { } } -impl Externalities for BasicExternalities where H::Out: Ord { +impl Externalities for BasicExternalities { fn storage(&self, key: &[u8]) -> Option> { self.top.get(key).cloned() } + fn storage_hash(&self, key: &[u8]) -> Option { + self.storage(key).map(|v| Blake2Hasher::hash(&v)) + } + fn original_storage(&self, key: &[u8]) -> Option> { - Externalities::::storage(self, key) + self.storage(key) + } + + fn original_storage_hash(&self, key: &[u8]) -> Option { + self.storage_hash(key) } fn child_storage(&self, storage_key: ChildStorageKey, key: &[u8]) -> Option> { self.children.get(storage_key.as_ref()).and_then(|child| child.get(key)).cloned() } + fn child_storage_hash(&self, storage_key: ChildStorageKey, key: &[u8]) -> Option { + self.child_storage(storage_key, key).map(|v| Blake2Hasher::hash(&v)) + } + + fn original_child_storage_hash(&self, storage_key: ChildStorageKey, key: &[u8]) -> Option { + self.child_storage_hash(storage_key, key) + } + fn original_child_storage(&self, storage_key: ChildStorageKey, key: &[u8]) -> Option> { - Externalities::::child_storage(self, storage_key, key) + Externalities::child_storage(self, storage_key, key) } fn place_storage(&mut self, key: Vec, maybe_value: Option>) { @@ -155,16 +170,15 @@ impl Externalities for BasicExternalities where H::Out: Ord { fn chain_id(&self) -> u64 { 42 } - fn storage_root(&mut self) -> H::Out { + fn storage_root(&mut self) -> H256 { let mut top = self.top.clone(); let keys: Vec<_> = self.children.keys().map(|k| k.to_vec()).collect(); // Single child trie implementation currently allows using the same child // empty root for all child trie. Using null storage key until multiple // type of child trie support. - let empty_hash = default_child_trie_root::>(&[]); + let empty_hash = default_child_trie_root::>(&[]); for storage_key in keys { - let child_root = Externalities::::child_storage_root( - self, + let child_root = self.child_storage_root( ChildStorageKey::from_slice(storage_key.as_slice()) .expect("Map only feed by valid keys; qed"), ); @@ -175,30 +189,27 @@ impl Externalities for BasicExternalities where H::Out: Ord { } } - Layout::::trie_root(self.top.clone()) + Layout::::trie_root(self.top.clone()) } fn child_storage_root(&mut self, storage_key: ChildStorageKey) -> Vec { if let Some(child) = self.children.get(storage_key.as_ref()) { let delta = child.clone().into_iter().map(|(k, v)| (k, Some(v))); - InMemory::::default().child_storage_root(storage_key.as_ref(), delta).0 + InMemory::::default().child_storage_root(storage_key.as_ref(), delta).0 } else { - default_child_trie_root::>(storage_key.as_ref()) + default_child_trie_root::>(storage_key.as_ref()) } } - fn storage_changes_root(&mut self, _parent: H::Out) -> Result, ()> { + fn storage_changes_root(&mut self, _parent: H256) -> Result, ()> { Ok(None) } +} - fn offchain(&mut self) -> Option<&mut dyn offchain::Externalities> { - warn!("Call to non-existent offchain externalities set."); - None - } - - fn keystore(&self) -> Option { - warn!("Call to non-existent keystore."); +impl externalities::ExtensionStore for BasicExternalities { + fn extension_by_type_id(&mut self, _: TypeId) -> Option<&mut dyn Any> { + warn!("Extensions are not supported by `BasicExternalities`."); None } } @@ -206,14 +217,13 @@ impl Externalities for BasicExternalities where H::Out: Ord { #[cfg(test)] mod tests { use super::*; - use primitives::{Blake2Hasher, H256, map}; + use primitives::{H256, map}; use primitives::storage::well_known_keys::CODE; use hex_literal::hex; #[test] fn commit_should_work() { let mut ext = BasicExternalities::default(); - let ext = &mut ext as &mut dyn Externalities; ext.set_storage(b"doe".to_vec(), b"reindeer".to_vec()); ext.set_storage(b"dog".to_vec(), b"puppy".to_vec()); ext.set_storage(b"dogglesworth".to_vec(), b"cat".to_vec()); @@ -225,7 +235,6 @@ mod tests { #[test] fn set_and_retrieve_code() { let mut ext = BasicExternalities::default(); - let ext = &mut ext as &mut dyn Externalities; let code = vec![1, 2, 3]; ext.set_storage(CODE.to_vec(), code.clone()); @@ -246,8 +255,6 @@ mod tests { ] ); - let ext = &mut ext as &mut dyn Externalities; - let child = || ChildStorageKey::from_vec(child_storage.clone()).unwrap(); assert_eq!(ext.child_storage(child(), b"doe"), Some(b"reindeer".to_vec())); diff --git a/substrate/core/state-machine/src/ext.rs b/substrate/core/state-machine/src/ext.rs index c4a2bd7f63..3433aee92c 100644 --- a/substrate/core/state-machine/src/ext.rs +++ b/substrate/core/state-machine/src/ext.rs @@ -16,22 +16,24 @@ //! Concrete externalities implementation. -use std::{error, fmt, cmp::Ord}; -use log::{warn, trace}; use crate::{ backend::Backend, OverlayedChanges, changes_trie::{ Storage as ChangesTrieStorage, CacheAction as ChangesTrieCacheAction, build_changes_trie, }, }; + use hash_db::Hasher; use primitives::{ - offchain, storage::well_known_keys::is_child_storage_key, - traits::{BareCryptoStorePtr, Externalities}, child_storage_key::ChildStorageKey, - hexdisplay::HexDisplay, + storage::{ChildStorageKey, well_known_keys::is_child_storage_key}, + traits::Externalities, hexdisplay::HexDisplay, hash::H256, }; -use trie::{MemoryDB, default_child_trie_root}; -use trie::trie_types::Layout; +use trie::{trie_types::Layout, MemoryDB, default_child_trie_root}; +use externalities::Extensions; + +use std::{error, fmt, any::{Any, TypeId}}; + +use log::{warn, trace}; const EXT_NOT_ALLOWED_TO_FAIL: &str = "Externalities not allowed to fail within runtime"; @@ -65,11 +67,7 @@ impl error::Error for Error { } /// Wraps a read-only backend, call executor, and current overlayed changes. -pub struct Ext<'a, H, N, B, T, O> -where - H: Hasher, - B: 'a + Backend, -{ +pub struct Ext<'a, H, N, B, T> where H: Hasher, B: 'a + Backend { /// The overlayed changes to write to. overlay: &'a mut OverlayedChanges, /// The storage backend to read from. @@ -86,25 +84,19 @@ where /// `storage_changes_root` is called matters + we need to remember additional /// data at this moment (block number). changes_trie_transaction: Option<(MemoryDB, H::Out, ChangesTrieCacheAction)>, - /// Additional externalities for offchain workers. - /// - /// If None, some methods from the trait might not be supported. - offchain_externalities: Option<&'a mut O>, - /// The keystore that manages the keys of the node. - keystore: Option, /// Pseudo-unique id used for tracing. pub id: u16, /// Dummy usage of N arg. - _phantom: ::std::marker::PhantomData, + _phantom: std::marker::PhantomData, + /// Extensions registered with this instance. + extensions: Option<&'a mut Extensions>, } -impl<'a, H, N, B, T, O> Ext<'a, H, N, B, T, O> +impl<'a, H, N, B, T> Ext<'a, H, N, B, T> where - H: Hasher, + H: Hasher, B: 'a + Backend, T: 'a + ChangesTrieStorage, - O: 'a + offchain::Externalities, - H::Out: Ord + 'static, N: crate::changes_trie::BlockNumber, { /// Create a new `Ext` from overlayed changes and read-only backend @@ -112,8 +104,7 @@ where overlay: &'a mut OverlayedChanges, backend: &'a B, changes_trie_storage: Option<&'a T>, - offchain_externalities: Option<&'a mut O>, - keystore: Option, + extensions: Option<&'a mut Extensions>, ) -> Self { Ext { overlay, @@ -121,21 +112,25 @@ where storage_transaction: None, changes_trie_storage, changes_trie_transaction: None, - offchain_externalities, - keystore, id: rand::random(), _phantom: Default::default(), + extensions, } } /// Get the transaction necessary to update the backend. - pub fn transaction(mut self) -> ((B::Transaction, H::Out), Option>) { + pub fn transaction(&mut self) -> ( + (B::Transaction, H256), + Option>, + ) { let _ = self.storage_root(); let (storage_transaction, changes_trie_transaction) = ( self.storage_transaction + .take() .expect("storage_transaction always set after calling storage root; qed"), self.changes_trie_transaction + .take() .map(|(tx, _, cache)| (tx, cache)), ); @@ -151,16 +146,14 @@ where fn mark_dirty(&mut self) { self.storage_transaction = None; } - } #[cfg(test)] -impl<'a, H, N, B, T, O> Ext<'a, H, N, B, T, O> +impl<'a, H, N, B, T> Ext<'a, H, N, B, T> where - H: Hasher, + H: Hasher, B: 'a + Backend, T: 'a + ChangesTrieStorage, - O: 'a + offchain::Externalities, N: crate::changes_trie::BlockNumber, { pub fn storage_pairs(&self) -> Vec<(Vec, Vec)> { @@ -177,13 +170,12 @@ where } } -impl<'a, B, T, H, N, O> Externalities for Ext<'a, H, N, B, T, O> -where H: Hasher, +impl<'a, H, B, T, N> Externalities for Ext<'a, H, N, B, T> +where + H: Hasher, B: 'a + Backend, T: 'a + ChangesTrieStorage, - H::Out: Ord + 'static, N: crate::changes_trie::BlockNumber, - O: 'a + offchain::Externalities, { fn storage(&self, key: &[u8]) -> Option> { let _guard = panic_handler::AbortGuard::force_abort(); @@ -197,10 +189,14 @@ where H: Hasher, result } - fn storage_hash(&self, key: &[u8]) -> Option { + fn storage_hash(&self, key: &[u8]) -> Option { let _guard = panic_handler::AbortGuard::force_abort(); - let result = self.overlay.storage(key).map(|x| x.map(|x| H::hash(x))).unwrap_or_else(|| - self.backend.storage_hash(key).expect(EXT_NOT_ALLOWED_TO_FAIL)); + let result = self.overlay + .storage(key) + .map(|x| x.map(|x| H::hash(x))) + .unwrap_or_else(|| + self.backend.storage_hash(key).expect(EXT_NOT_ALLOWED_TO_FAIL) + ); trace!(target: "state-trace", "{:04x}: Hash {}={:?}", self.id, HexDisplay::from(&key), @@ -220,7 +216,7 @@ where H: Hasher, result } - fn original_storage_hash(&self, key: &[u8]) -> Option { + fn original_storage_hash(&self, key: &[u8]) -> Option { let _guard = panic_handler::AbortGuard::force_abort(); let result = self.backend.storage_hash(key).expect(EXT_NOT_ALLOWED_TO_FAIL); trace!(target: "state-trace", "{:04x}: GetOriginalHash {}={:?}", @@ -233,33 +229,48 @@ where H: Hasher, fn child_storage(&self, storage_key: ChildStorageKey, key: &[u8]) -> Option> { let _guard = panic_handler::AbortGuard::force_abort(); - let result = self.overlay.child_storage(storage_key.as_ref(), key).map(|x| x.map(|x| x.to_vec())).unwrap_or_else(|| - self.backend.child_storage(storage_key.as_ref(), key).expect(EXT_NOT_ALLOWED_TO_FAIL)); + let result = self.overlay + .child_storage(storage_key.as_ref(), key) + .map(|x| x.map(|x| x.to_vec())) + .unwrap_or_else(|| + self.backend.child_storage(storage_key.as_ref(), key).expect(EXT_NOT_ALLOWED_TO_FAIL) + ); + trace!(target: "state-trace", "{:04x}: GetChild({}) {}={:?}", self.id, HexDisplay::from(&storage_key.as_ref()), HexDisplay::from(&key), result.as_ref().map(HexDisplay::from) ); + result } - fn child_storage_hash(&self, storage_key: ChildStorageKey, key: &[u8]) -> Option { + fn child_storage_hash(&self, storage_key: ChildStorageKey, key: &[u8]) -> Option { let _guard = panic_handler::AbortGuard::force_abort(); - let result = self.overlay.child_storage(storage_key.as_ref(), key).map(|x| x.map(|x| H::hash(x))).unwrap_or_else(|| - self.backend.storage_hash(key).expect(EXT_NOT_ALLOWED_TO_FAIL)); + let result = self.overlay + .child_storage(storage_key.as_ref(), key) + .map(|x| x.map(|x| H::hash(x))) + .unwrap_or_else(|| + self.backend.storage_hash(key).expect(EXT_NOT_ALLOWED_TO_FAIL) + ); + trace!(target: "state-trace", "{:04x}: ChildHash({}) {}={:?}", self.id, HexDisplay::from(&storage_key.as_ref()), HexDisplay::from(&key), result, ); + result } fn original_child_storage(&self, storage_key: ChildStorageKey, key: &[u8]) -> Option> { let _guard = panic_handler::AbortGuard::force_abort(); - let result = self.backend.child_storage(storage_key.as_ref(), key).expect(EXT_NOT_ALLOWED_TO_FAIL); + let result = self.backend + .child_storage(storage_key.as_ref(), key) + .expect(EXT_NOT_ALLOWED_TO_FAIL); + trace!(target: "state-trace", "{:04x}: ChildOriginal({}) {}={:?}", self.id, HexDisplay::from(&storage_key.as_ref()), @@ -269,9 +280,12 @@ where H: Hasher, result } - fn original_child_storage_hash(&self, storage_key: ChildStorageKey, key: &[u8]) -> Option { + fn original_child_storage_hash(&self, storage_key: ChildStorageKey, key: &[u8]) -> Option { let _guard = panic_handler::AbortGuard::force_abort(); - let result = self.backend.child_storage_hash(storage_key.as_ref(), key).expect(EXT_NOT_ALLOWED_TO_FAIL); + let result = self.backend + .child_storage_hash(storage_key.as_ref(), key) + .expect(EXT_NOT_ALLOWED_TO_FAIL); + trace!(target: "state-trace", "{}: ChildHashOriginal({}) {}={:?}", self.id, HexDisplay::from(&storage_key.as_ref()), @@ -287,6 +301,7 @@ where H: Hasher, Some(x) => x.is_some(), _ => self.backend.exists_storage(key).expect(EXT_NOT_ALLOWED_TO_FAIL), }; + trace!(target: "state-trace", "{:04x}: Exists {}={:?}", self.id, HexDisplay::from(&key), @@ -301,8 +316,11 @@ where H: Hasher, let result = match self.overlay.child_storage(storage_key.as_ref(), key) { Some(x) => x.is_some(), - _ => self.backend.exists_child_storage(storage_key.as_ref(), key).expect(EXT_NOT_ALLOWED_TO_FAIL), + _ => self.backend + .exists_child_storage(storage_key.as_ref(), key) + .expect(EXT_NOT_ALLOWED_TO_FAIL), }; + trace!(target: "state-trace", "{:04x}: ChildExists({}) {}={:?}", self.id, HexDisplay::from(&storage_key.as_ref()), @@ -328,7 +346,12 @@ where H: Hasher, self.overlay.set_storage(key, value); } - fn place_child_storage(&mut self, storage_key: ChildStorageKey, key: Vec, value: Option>) { + fn place_child_storage( + &mut self, + storage_key: ChildStorageKey, + key: Vec, + value: Option>, + ) { trace!(target: "state-trace", "{:04x}: PutChild({}) {}={:?}", self.id, HexDisplay::from(&storage_key.as_ref()), @@ -392,7 +415,7 @@ where H: Hasher, 42 } - fn storage_root(&mut self) -> H::Out { + fn storage_root(&mut self) -> H256 { let _guard = panic_handler::AbortGuard::force_abort(); if let Some((_, ref root)) = self.storage_transaction { trace!(target: "state-trace", "{:04x}: Root (cached) {}", @@ -465,7 +488,7 @@ where H: Hasher, } } - fn storage_changes_root(&mut self, parent_hash: H::Out) -> Result, ()> { + fn storage_changes_root(&mut self, parent_hash: H256) -> Result, ()> { let _guard = panic_handler::AbortGuard::force_abort(); self.changes_trie_transaction = build_changes_trie::<_, T, H, N>( self.backend, @@ -481,32 +504,36 @@ where H: Hasher, ); result } +} - fn offchain(&mut self) -> Option<&mut dyn offchain::Externalities> { - self.offchain_externalities.as_mut().map(|x| &mut **x as _) +impl<'a, H, B, T, N> externalities::ExtensionStore for Ext<'a, H, N, B, T> +where + H: Hasher, + B: 'a + Backend, + T: 'a + ChangesTrieStorage, + N: crate::changes_trie::BlockNumber, +{ + fn extension_by_type_id(&mut self, type_id: TypeId) -> Option<&mut dyn Any> { + self.extensions.as_mut().and_then(|exts| exts.get_mut(type_id)) } - - fn keystore(&self) -> Option { - self.keystore.clone() - } - } #[cfg(test)] mod tests { + use super::*; use hex_literal::hex; use codec::Encode; - use primitives::{Blake2Hasher}; - use primitives::storage::well_known_keys::EXTRINSIC_INDEX; - use crate::backend::InMemory; - use crate::changes_trie::{Configuration as ChangesTrieConfiguration, - InMemoryStorage as InMemoryChangesTrieStorage}; - use crate::overlayed_changes::OverlayedValue; - use super::*; + use primitives::{Blake2Hasher, storage::well_known_keys::EXTRINSIC_INDEX}; + use crate::{ + changes_trie::{ + Configuration as ChangesTrieConfiguration, + InMemoryStorage as InMemoryChangesTrieStorage, + }, backend::InMemory, overlayed_changes::OverlayedValue, + }; type TestBackend = InMemory; type TestChangesTrieStorage = InMemoryChangesTrieStorage; - type TestExt<'a> = Ext<'a, Blake2Hasher, u64, TestBackend, TestChangesTrieStorage, crate::NeverOffchainExt>; + type TestExt<'a> = Ext<'a, Blake2Hasher, u64, TestBackend, TestChangesTrieStorage>; fn prepare_overlay_with_changes() -> OverlayedChanges { OverlayedChanges { @@ -532,7 +559,7 @@ mod tests { fn storage_changes_root_is_none_when_storage_is_not_provided() { let mut overlay = prepare_overlay_with_changes(); let backend = TestBackend::default(); - let mut ext = TestExt::new(&mut overlay, &backend, None, None, None); + let mut ext = TestExt::new(&mut overlay, &backend, None, None); assert_eq!(ext.storage_changes_root(Default::default()).unwrap(), None); } @@ -542,7 +569,7 @@ mod tests { overlay.changes_trie_config = None; let storage = TestChangesTrieStorage::with_blocks(vec![(100, Default::default())]); let backend = TestBackend::default(); - let mut ext = TestExt::new(&mut overlay, &backend, Some(&storage), None, None); + let mut ext = TestExt::new(&mut overlay, &backend, Some(&storage), None); assert_eq!(ext.storage_changes_root(Default::default()).unwrap(), None); } @@ -551,7 +578,7 @@ mod tests { let mut overlay = prepare_overlay_with_changes(); let storage = TestChangesTrieStorage::with_blocks(vec![(99, Default::default())]); let backend = TestBackend::default(); - let mut ext = TestExt::new(&mut overlay, &backend, Some(&storage), None, None); + let mut ext = TestExt::new(&mut overlay, &backend, Some(&storage), None); assert_eq!( ext.storage_changes_root(Default::default()).unwrap(), Some(hex!("bb0c2ef6e1d36d5490f9766cfcc7dfe2a6ca804504c3bb206053890d6dd02376").into()), @@ -564,7 +591,7 @@ mod tests { overlay.prospective.top.get_mut(&vec![1]).unwrap().value = None; let storage = TestChangesTrieStorage::with_blocks(vec![(99, Default::default())]); let backend = TestBackend::default(); - let mut ext = TestExt::new(&mut overlay, &backend, Some(&storage), None, None); + let mut ext = TestExt::new(&mut overlay, &backend, Some(&storage), None); assert_eq!( ext.storage_changes_root(Default::default()).unwrap(), Some(hex!("96f5aae4690e7302737b6f9b7f8567d5bbb9eac1c315f80101235a92d9ec27f4").into()), diff --git a/substrate/core/state-machine/src/lib.rs b/substrate/core/state-machine/src/lib.rs index 5220b4b31d..c3092367f0 100644 --- a/substrate/core/state-machine/src/lib.rs +++ b/substrate/core/state-machine/src/lib.rs @@ -18,18 +18,16 @@ #![warn(missing_docs)] -use std::{ - fmt, result, collections::HashMap, - marker::PhantomData, panic::UnwindSafe, -}; +use std::{fmt, result, collections::HashMap, panic::UnwindSafe, marker::PhantomData}; use log::{warn, trace}; use hash_db::Hasher; use codec::{Decode, Encode}; use primitives::{ - storage::well_known_keys, NativeOrEncoded, NeverNativeValue, offchain::{self, NeverOffchainExt}, - traits::{BareCryptoStorePtr, CodeExecutor}, - hexdisplay::HexDisplay, + storage::well_known_keys, NativeOrEncoded, NeverNativeValue, offchain::OffchainExt, + traits::{KeystoreExt, CodeExecutor}, hexdisplay::HexDisplay, hash::H256, }; +use overlayed_changes::OverlayedChangeSet; +use externalities::Extensions; pub mod backend; mod changes_trie; @@ -42,9 +40,7 @@ mod proving_backend; mod trie_backend; mod trie_backend_essence; -use overlayed_changes::OverlayedChangeSet; -pub use trie::{TrieMut, DBValue, MemoryDB}; -pub use trie::trie_types::{Layout, TrieDBMut}; +pub use trie::{trie_types::{Layout, TrieDBMut}, TrieMut, DBValue, MemoryDB}; pub use testing::TestExternalities; pub use basic::BasicExternalities; pub use ext::Ext; @@ -167,48 +163,54 @@ fn always_untrusted_wasm() -> ExecutionManager { - backend: B, - changes_trie_storage: Option<&'a T>, - offchain_ext: Option<&'a mut O>, - overlay: &'a mut OverlayedChanges, +pub struct StateMachine<'a, B, H, N, T, Exec> where H: Hasher, B: Backend { + backend: &'a B, exec: &'a Exec, method: &'a str, call_data: &'a [u8], - keystore: Option, - _hasher: PhantomData<(H, N)>, + overlay: &'a mut OverlayedChanges, + extensions: Extensions, + changes_trie_storage: Option<&'a T>, + _marker: PhantomData<(H, N)>, } -impl<'a, B, H, N, T, O, Exec> StateMachine<'a, B, H, N, T, O, Exec> where - H: Hasher, - Exec: CodeExecutor, +impl<'a, B, H, N, T, Exec> StateMachine<'a, B, H, N, T, Exec> where + H: Hasher, + Exec: CodeExecutor, B: Backend, T: ChangesTrieStorage, - O: offchain::Externalities, - H::Out: Ord + 'static, N: crate::changes_trie::BlockNumber, { /// Creates new substrate state machine. pub fn new( - backend: B, + backend: &'a B, changes_trie_storage: Option<&'a T>, - offchain_ext: Option<&'a mut O>, + offchain_ext: Option, overlay: &'a mut OverlayedChanges, exec: &'a Exec, method: &'a str, call_data: &'a [u8], - keystore: Option, + keystore: Option, ) -> Self { + let mut extensions = Extensions::new(); + + if let Some(keystore) = keystore { + extensions.register(keystore); + } + + if let Some(offchain) = offchain_ext { + extensions.register(offchain); + } + Self { backend, - changes_trie_storage, - offchain_ext, - overlay, exec, method, call_data, - keystore, - _hasher: PhantomData, + extensions, + overlay, + changes_trie_storage, + _marker: PhantomData, } } @@ -220,10 +222,10 @@ impl<'a, B, H, N, T, O, Exec> StateMachine<'a, B, H, N, T, O, Exec> where /// /// Note: changes to code will be in place if this call is made again. For running partial /// blocks (e.g. a transaction at a time), ensure a different method is used. - pub fn execute( - &mut self, - strategy: ExecutionStrategy, - ) -> Result<(Vec, (B::Transaction, H::Out), Option>), Box> { + pub fn execute(&mut self, strategy: ExecutionStrategy) -> Result< + (Vec, (B::Transaction, H::Out), Option>), + Box, + > { // We are not giving a native call and thus we are sure that the result can never be a native // value. self.execute_using_consensus_failure_handler::<_, NeverNativeValue, fn() -> _>( @@ -252,38 +254,44 @@ impl<'a, B, H, N, T, O, Exec> StateMachine<'a, B, H, N, T, O, Exec> where R: Decode + Encode + PartialEq, NC: FnOnce() -> result::Result + UnwindSafe, { - let mut externalities = ext::Ext::new( + let mut ext = Ext::new( self.overlay, - &self.backend, - self.changes_trie_storage, - self.offchain_ext.as_mut().map(|x| &mut **x), - self.keystore.clone(), + self.backend, + self.changes_trie_storage.clone(), + Some(&mut self.extensions), ); - let id = externalities.id; - trace!(target: "state-trace", "{:04x}: Call {} at {:?}. Input={:?}", + + let id = ext.id; + trace!( + target: "state-trace", "{:04x}: Call {} at {:?}. Input={:?}", id, self.method, self.backend, HexDisplay::from(&self.call_data), ); + let (result, was_native) = self.exec.call( - &mut externalities, + &mut ext, self.method, self.call_data, use_native, native_call, ); + let (storage_delta, changes_delta) = if compute_tx { - let (storage_delta, changes_delta) = externalities.transaction(); + let (storage_delta, changes_delta) = ext.transaction(); (Some(storage_delta), changes_delta) } else { (None, None) }; - trace!(target: "state-trace", "{:04x}: Return. Native={:?}, Result={:?}", + + trace!( + target: "state-trace", "{:04x}: Return. Native={:?}, Result={:?}", id, was_native, result, ); + (result, was_native, storage_delta, changes_delta) } @@ -293,12 +301,16 @@ impl<'a, B, H, N, T, O, Exec> StateMachine<'a, B, H, N, T, O, Exec> where mut native_call: Option, orig_prospective: OverlayedChangeSet, on_consensus_failure: Handler, - ) -> (CallResult, Option<(B::Transaction, H::Out)>, Option>) where + ) -> ( + CallResult, + Option<(B::Transaction, H::Out)>, + Option>, + ) where R: Decode + Encode + PartialEq, NC: FnOnce() -> result::Result + UnwindSafe, Handler: FnOnce( CallResult, - CallResult + CallResult, ) -> CallResult { let (result, was_native, storage_delta, changes_delta) = self.execute_aux( @@ -317,7 +329,8 @@ impl<'a, B, H, N, T, O, Exec> StateMachine<'a, B, H, N, T, O, Exec> where if (result.is_ok() && wasm_result.is_ok() && result.as_ref().ok() == wasm_result.as_ref().ok()) - || result.is_err() && wasm_result.is_err() { + || result.is_err() && wasm_result.is_err() + { (result, storage_delta, changes_delta) } else { (on_consensus_failure(wasm_result, result), wasm_storage_delta, wasm_changes_delta) @@ -332,7 +345,11 @@ impl<'a, B, H, N, T, O, Exec> StateMachine<'a, B, H, N, T, O, Exec> where compute_tx: bool, mut native_call: Option, orig_prospective: OverlayedChangeSet, - ) -> (CallResult, Option<(B::Transaction, H::Out)>, Option>) where + ) -> ( + CallResult, + Option<(B::Transaction, H::Out)>, + Option>, + ) where R: Decode + Encode + PartialEq, NC: FnOnce() -> result::Result + UnwindSafe, { @@ -431,7 +448,7 @@ impl<'a, B, H, N, T, O, Exec> StateMachine<'a, B, H, N, T, O, Exec> where }; if result.is_ok() { - init_overlay(self.overlay, true, &self.backend)?; + init_overlay(self.overlay, true, self.backend)?; } result.map_err(|e| Box::new(e) as _) @@ -445,13 +462,12 @@ pub fn prove_execution( exec: &Exec, method: &str, call_data: &[u8], - keystore: Option, + keystore: Option, ) -> Result<(Vec, Vec>), Box> where B: Backend, - H: Hasher, - Exec: CodeExecutor, - H::Out: Ord + 'static, + H: Hasher, + Exec: CodeExecutor, { let trie_backend = backend.as_trie_backend() .ok_or_else(|| Box::new(ExecutionError::UnableToGenerateProof) as Box)?; @@ -473,17 +489,16 @@ pub fn prove_execution_on_trie_backend( exec: &Exec, method: &str, call_data: &[u8], - keystore: Option, + keystore: Option, ) -> Result<(Vec, Vec>), Box> where S: trie_backend_essence::TrieBackendStorage, - H: Hasher, - Exec: CodeExecutor, - H::Out: Ord + 'static, + H: Hasher, + Exec: CodeExecutor, { let proving_backend = proving_backend::ProvingBackend::new(trie_backend); - let mut sm = StateMachine::<_, H, _, InMemoryChangesTrieStorage, _, Exec>::new( - proving_backend, None, NeverOffchainExt::new(), overlay, exec, method, call_data, keystore, + let mut sm = StateMachine::<_, H, _, InMemoryChangesTrieStorage, Exec>::new( + &proving_backend, None, None, overlay, exec, method, call_data, keystore, ); let (result, _, _) = sm.execute_using_consensus_failure_handler::<_, NeverNativeValue, fn() -> _>( @@ -503,11 +518,11 @@ pub fn execution_proof_check( exec: &Exec, method: &str, call_data: &[u8], - keystore: Option, + keystore: Option, ) -> Result, Box> where - H: Hasher, - Exec: CodeExecutor, + H: Hasher, + Exec: CodeExecutor, H::Out: Ord + 'static, { let trie_backend = create_proof_check_backend::(root.into(), proof)?; @@ -521,15 +536,14 @@ pub fn execution_proof_check_on_trie_backend( exec: &Exec, method: &str, call_data: &[u8], - keystore: Option, + keystore: Option, ) -> Result, Box> where - H: Hasher, - Exec: CodeExecutor, - H::Out: Ord + 'static, + H: Hasher, + Exec: CodeExecutor, { - let mut sm = StateMachine::<_, H, _, InMemoryChangesTrieStorage, _, Exec>::new( - trie_backend, None, NeverOffchainExt::new(), overlay, exec, method, call_data, keystore, + let mut sm = StateMachine::<_, H, _, InMemoryChangesTrieStorage, Exec>::new( + trie_backend, None, None, overlay, exec, method, call_data, keystore, ); sm.execute_using_consensus_failure_handler::<_, NeverNativeValue, fn() -> _>( @@ -546,7 +560,7 @@ pub fn prove_read( ) -> Result>, Box> where B: Backend, - H: Hasher, + H: Hasher, H::Out: Ord, I: IntoIterator, I::Item: AsRef<[u8]>, @@ -741,7 +755,7 @@ mod tests { InMemoryStorage as InMemoryChangesTrieStorage, Configuration as ChangesTrieConfig, }; - use primitives::{Blake2Hasher, map, traits::Externalities, child_storage_key::ChildStorageKey}; + use primitives::{Blake2Hasher, map, traits::Externalities, storage::ChildStorageKey}; struct DummyCodeExecutor { change_changes_trie_config: bool, @@ -750,10 +764,14 @@ mod tests { fallback_succeeds: bool, } - impl CodeExecutor for DummyCodeExecutor { + impl CodeExecutor for DummyCodeExecutor { type Error = u8; - fn call, R: Encode + Decode + PartialEq, NC: FnOnce() -> result::Result>( + fn call< + E: Externalities, + R: Encode + Decode + PartialEq, + NC: FnOnce() -> result::Result, + >( &self, ext: &mut E, _method: &str, @@ -800,9 +818,9 @@ mod tests { let changes_trie_storage = InMemoryChangesTrieStorage::::new(); let mut state_machine = StateMachine::new( - backend, + &backend, Some(&changes_trie_storage), - NeverOffchainExt::new(), + None, &mut overlayed_changes, &DummyCodeExecutor { change_changes_trie_config: false, @@ -829,9 +847,9 @@ mod tests { let changes_trie_storage = InMemoryChangesTrieStorage::::new(); let mut state_machine = StateMachine::new( - backend, + &backend, Some(&changes_trie_storage), - NeverOffchainExt::new(), + None, &mut overlayed_changes, &DummyCodeExecutor { change_changes_trie_config: false, @@ -855,9 +873,9 @@ mod tests { let changes_trie_storage = InMemoryChangesTrieStorage::::new(); let mut state_machine = StateMachine::new( - backend, + &backend, Some(&changes_trie_storage), - NeverOffchainExt::new(), + None, &mut overlayed_changes, &DummyCodeExecutor { change_changes_trie_config: false, @@ -948,7 +966,6 @@ mod tests { &mut overlay, backend, Some(&changes_trie_storage), - NeverOffchainExt::new(), None, ); ext.clear_prefix(b"ab"); @@ -979,7 +996,6 @@ mod tests { &mut overlay, backend, Some(&changes_trie_storage), - NeverOffchainExt::new(), None, ); @@ -1067,9 +1083,9 @@ mod tests { let changes_trie_storage = InMemoryChangesTrieStorage::::new(); let mut state_machine = StateMachine::new( - backend, + &backend, Some(&changes_trie_storage), - NeverOffchainExt::new(), + None, &mut overlayed_changes, &DummyCodeExecutor { change_changes_trie_config: true, @@ -1092,9 +1108,9 @@ mod tests { let changes_trie_storage = InMemoryChangesTrieStorage::::new(); let mut state_machine = StateMachine::new( - backend, + &backend, Some(&changes_trie_storage), - NeverOffchainExt::new(), + None, &mut overlayed_changes, &DummyCodeExecutor { change_changes_trie_config: true, diff --git a/substrate/core/state-machine/src/overlayed_changes.rs b/substrate/core/state-machine/src/overlayed_changes.rs index a4952ddf73..53a66dc49e 100644 --- a/substrate/core/state-machine/src/overlayed_changes.rs +++ b/substrate/core/state-machine/src/overlayed_changes.rs @@ -420,7 +420,6 @@ mod tests { &mut overlay, &backend, Some(&changes_trie_storage), - crate::NeverOffchainExt::new(), None, ); const ROOT: [u8; 32] = hex!("39245109cef3758c2eed2ccba8d9b370a917850af3824bc8348d505df2c298fa"); @@ -432,9 +431,12 @@ mod tests { fn changes_trie_configuration_is_saved() { let mut overlay = OverlayedChanges::default(); assert!(overlay.changes_trie_config.is_none()); - assert_eq!(overlay.set_changes_trie_config(ChangesTrieConfig { - digest_interval: 4, digest_levels: 1, - }), true); + assert_eq!( + overlay.set_changes_trie_config( + ChangesTrieConfig { digest_interval: 4, digest_levels: 1, }, + ), + true, + ); assert!(overlay.changes_trie_config.is_some()); } diff --git a/substrate/core/state-machine/src/proving_backend.rs b/substrate/core/state-machine/src/proving_backend.rs index 3908f62eaa..c6c4ef1ec8 100644 --- a/substrate/core/state-machine/src/proving_backend.rs +++ b/substrate/core/state-machine/src/proving_backend.rs @@ -250,7 +250,7 @@ mod tests { use crate::backend::{InMemory}; use crate::trie_backend::tests::test_trie; use super::*; - use primitives::{Blake2Hasher, child_storage_key::ChildStorageKey}; + use primitives::{Blake2Hasher, storage::ChildStorageKey}; fn test_proving<'a>( trie_backend: &'a TrieBackend,Blake2Hasher>, diff --git a/substrate/core/state-machine/src/testing.rs b/substrate/core/state-machine/src/testing.rs index 160f7d2a47..ea63eac021 100644 --- a/substrate/core/state-machine/src/testing.rs +++ b/substrate/core/state-machine/src/testing.rs @@ -16,7 +16,7 @@ //! Test implementation for Externalities. -use std::collections::{HashMap}; +use std::{collections::HashMap, any::{Any, TypeId}}; use hash_db::Hasher; use crate::{ backend::{InMemory, Backend}, OverlayedChanges, @@ -26,25 +26,28 @@ use crate::{ }, }; use primitives::{ - storage::well_known_keys::{CHANGES_TRIE_CONFIG, CODE, HEAP_PAGES, is_child_storage_key}, - traits::{BareCryptoStorePtr, Externalities}, offchain, child_storage_key::ChildStorageKey, + storage::{ + ChildStorageKey, + well_known_keys::{CHANGES_TRIE_CONFIG, CODE, HEAP_PAGES, is_child_storage_key} + }, + traits::Externalities, hash::H256, Blake2Hasher, }; use codec::Encode; +use externalities::{Extensions, Extension}; const EXT_NOT_ALLOWED_TO_FAIL: &str = "Externalities not allowed to fail within runtime"; type StorageTuple = (HashMap, Vec>, HashMap, HashMap, Vec>>); /// Simple HashMap-based Externalities impl. -pub struct TestExternalities { +pub struct TestExternalities=Blake2Hasher, N: ChangesTrieBlockNumber=u64> { overlay: OverlayedChanges, backend: InMemory, changes_trie_storage: ChangesTrieInMemoryStorage, - offchain: Option>, - keystore: Option, + extensions: Extensions, } -impl TestExternalities { +impl, N: ChangesTrieBlockNumber> TestExternalities { /// Create a new instance of `TestExternalities` with storage. pub fn new(storage: StorageTuple) -> Self { Self::new_with_code(&[], storage) @@ -75,8 +78,7 @@ impl TestExternalities { overlay, changes_trie_storage: ChangesTrieInMemoryStorage::new(), backend: backend.into(), - offchain: None, - keystore: None, + extensions: Default::default(), } } @@ -85,14 +87,9 @@ impl TestExternalities { self.backend = self.backend.update(vec![(None, k, Some(v))]); } - /// Set offchain externaltiies. - pub fn set_offchain_externalities(&mut self, offchain: impl offchain::Externalities + 'static) { - self.offchain = Some(Box::new(offchain)); - } - - /// Set keystore. - pub fn set_keystore(&mut self, keystore: BareCryptoStorePtr) { - self.keystore = Some(keystore); + /// Registers the given extension for this instance. + pub fn register_extension(&mut self, ext: E) { + self.extensions.register(ext); } /// Get mutable reference to changes trie storage. @@ -118,13 +115,13 @@ impl TestExternalities { } } -impl std::fmt::Debug for TestExternalities { +impl, N: ChangesTrieBlockNumber> std::fmt::Debug for TestExternalities { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "overlay: {:?}\nbackend: {:?}", self.overlay, self.backend.pairs()) } } -impl PartialEq for TestExternalities { +impl, N: ChangesTrieBlockNumber> PartialEq for TestExternalities { /// This doesn't test if they are in the same state, only if they contains the /// same data at this state fn eq(&self, other: &TestExternalities) -> bool { @@ -132,30 +129,37 @@ impl PartialEq for TestExternalities } } -impl Default for TestExternalities { +impl, N: ChangesTrieBlockNumber> Default for TestExternalities { fn default() -> Self { Self::new(Default::default()) } } -impl From for TestExternalities { +impl, N: ChangesTrieBlockNumber> From for TestExternalities { fn from(storage: StorageTuple) -> Self { Self::new(storage) } } -impl Externalities for TestExternalities where - H: Hasher, +impl Externalities for TestExternalities where + H: Hasher, N: ChangesTrieBlockNumber, - H::Out: Ord + 'static, { fn storage(&self, key: &[u8]) -> Option> { 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)) } + fn storage_hash(&self, key: &[u8]) -> Option { + self.storage(key).map(|v| H::hash(&v)) + } + fn original_storage(&self, key: &[u8]) -> Option> { self.backend.storage(key).expect(EXT_NOT_ALLOWED_TO_FAIL) } + fn original_storage_hash(&self, key: &[u8]) -> Option { + self.storage_hash(key) + } + fn child_storage(&self, storage_key: ChildStorageKey, key: &[u8]) -> Option> { self.overlay .child_storage(storage_key.as_ref(), key) @@ -166,6 +170,10 @@ impl Externalities for TestExternalities where ) } + fn child_storage_hash(&self, storage_key: ChildStorageKey, key: &[u8]) -> Option { + self.child_storage(storage_key, key).map(|v| H::hash(&v)) + } + fn original_child_storage(&self, storage_key: ChildStorageKey, key: &[u8]) -> Option> { self.backend .child_storage(storage_key.as_ref(), key) @@ -173,6 +181,10 @@ impl Externalities for TestExternalities where .expect(EXT_NOT_ALLOWED_TO_FAIL) } + fn original_child_storage_hash(&self, storage_key: ChildStorageKey, key: &[u8]) -> Option { + self.child_storage_hash(storage_key, key) + } + fn place_storage(&mut self, key: Vec, maybe_value: Option>) { if is_child_storage_key(&key) { panic!("Refuse to directly set child storage key"); @@ -185,7 +197,7 @@ impl Externalities for TestExternalities where &mut self, storage_key: ChildStorageKey, key: Vec, - value: Option> + value: Option>, ) { self.overlay.set_child_storage(storage_key.into_owned(), key, value); } @@ -215,7 +227,6 @@ impl Externalities for TestExternalities where } fn clear_child_prefix(&mut self, storage_key: ChildStorageKey, prefix: &[u8]) { - self.overlay.clear_child_prefix(storage_key.as_ref(), prefix); let backend = &self.backend; @@ -227,8 +238,7 @@ impl Externalities for TestExternalities where fn chain_id(&self) -> u64 { 42 } - fn storage_root(&mut self) -> H::Out { - + fn storage_root(&mut self) -> H256 { let child_storage_keys = self.overlay.prospective.children.keys() .chain(self.overlay.committed.children.keys()); @@ -246,7 +256,6 @@ impl Externalities for TestExternalities where let delta = self.overlay.committed.top.iter().map(|(k, v)| (k.clone(), v.value.clone())) .chain(self.overlay.prospective.top.iter().map(|(k, v)| (k.clone(), v.value.clone()))); self.backend.full_storage_root(delta, child_delta_iter).0 - } fn child_storage_root(&mut self, storage_key: ChildStorageKey) -> Vec { @@ -270,7 +279,7 @@ impl Externalities for TestExternalities where root } - fn storage_changes_root(&mut self, parent: H::Out) -> Result, ()> { + fn storage_changes_root(&mut self, parent: H256) -> Result, ()> { Ok(build_changes_trie::<_, _, H, N>( &self.backend, Some(&self.changes_trie_storage), @@ -278,15 +287,14 @@ impl Externalities for TestExternalities where parent, )?.map(|(_, root, _)| root)) } +} - fn offchain(&mut self) -> Option<&mut dyn offchain::Externalities> { - self.offchain - .as_mut() - .map(|x| &mut **x as _) - } - - fn keystore(&self) -> Option { - self.keystore.clone() +impl externalities::ExtensionStore for TestExternalities where + H: Hasher, + N: ChangesTrieBlockNumber, +{ + fn extension_by_type_id(&mut self, type_id: TypeId) -> Option<&mut dyn Any> { + self.extensions.get_mut(type_id) } } diff --git a/substrate/core/test-runtime/src/system.rs b/substrate/core/test-runtime/src/system.rs index 12a656cf31..81bca2fad3 100644 --- a/substrate/core/test-runtime/src/system.rs +++ b/substrate/core/test-runtime/src/system.rs @@ -319,10 +319,11 @@ fn info_expect_equal_hash(given: &Hash, expected: &Hash) { mod tests { use super::*; - use runtime_io::{with_externalities, TestExternalities}; + use runtime_io::TestExternalities; use substrate_test_runtime_client::{AccountKeyring, Sr25519Keyring}; + use sr_primitives::set_and_run_with_externalities; use crate::{Header, Transfer, WASM_BINARY}; - use primitives::{Blake2Hasher, NeverNativeValue, map, traits::CodeExecutor}; + use primitives::{NeverNativeValue, map, traits::CodeExecutor}; use substrate_executor::{NativeExecutor, WasmExecutionMethod, native_executor_instance}; // Declare an instance of the native executor dispatch for the test runtime. @@ -336,7 +337,7 @@ mod tests { NativeExecutor::new(WasmExecutionMethod::Interpreted, None) } - fn new_test_ext() -> TestExternalities { + fn new_test_ext() -> TestExternalities { let authorities = vec![ Sr25519Keyring::Alice.to_raw_public(), Sr25519Keyring::Bob.to_raw_public(), @@ -357,7 +358,7 @@ mod tests { ) } - fn block_import_works(block_executor: F) where F: Fn(Block, &mut TestExternalities) { + fn block_import_works(block_executor: F) where F: Fn(Block, &mut TestExternalities) { let h = Header { parent_hash: [69u8; 32].into(), number: 1, @@ -370,7 +371,7 @@ mod tests { extrinsics: vec![], }; - with_externalities(&mut new_test_ext(), || polish_block(&mut b)); + set_and_run_with_externalities(&mut new_test_ext(), || polish_block(&mut b)); block_executor(b, &mut new_test_ext()); } @@ -378,7 +379,7 @@ mod tests { #[test] fn block_import_works_native() { block_import_works(|b, ext| { - with_externalities(ext, || { + set_and_run_with_externalities(ext, || { execute_block(b); }); }); @@ -397,7 +398,9 @@ mod tests { }) } - fn block_import_with_transaction_works(block_executor: F) where F: Fn(Block, &mut TestExternalities) { + fn block_import_with_transaction_works(block_executor: F) + where F: Fn(Block, &mut TestExternalities) + { let mut b1 = Block { header: Header { parent_hash: [69u8; 32].into(), @@ -417,7 +420,7 @@ mod tests { }; let mut dummy_ext = new_test_ext(); - with_externalities(&mut dummy_ext, || polish_block(&mut b1)); + set_and_run_with_externalities(&mut dummy_ext, || polish_block(&mut b1)); let mut b2 = Block { header: Header { @@ -443,26 +446,26 @@ mod tests { ], }; - with_externalities(&mut dummy_ext, || polish_block(&mut b2)); + set_and_run_with_externalities(&mut dummy_ext, || polish_block(&mut b2)); drop(dummy_ext); let mut t = new_test_ext(); - with_externalities(&mut t, || { + set_and_run_with_externalities(&mut t, || { assert_eq!(balance_of(AccountKeyring::Alice.into()), 111); assert_eq!(balance_of(AccountKeyring::Bob.into()), 0); }); block_executor(b1, &mut t); - with_externalities(&mut t, || { + set_and_run_with_externalities(&mut t, || { assert_eq!(balance_of(AccountKeyring::Alice.into()), 42); assert_eq!(balance_of(AccountKeyring::Bob.into()), 69); }); block_executor(b2, &mut t); - with_externalities(&mut t, || { + set_and_run_with_externalities(&mut t, || { assert_eq!(balance_of(AccountKeyring::Alice.into()), 0); assert_eq!(balance_of(AccountKeyring::Bob.into()), 42); assert_eq!(balance_of(AccountKeyring::Charlie.into()), 69); @@ -472,7 +475,7 @@ mod tests { #[test] fn block_import_with_transaction_works_native() { block_import_with_transaction_works(|b, ext| { - with_externalities(ext, || { + set_and_run_with_externalities(ext, || { execute_block(b); }); }); diff --git a/substrate/node-template/runtime/src/template.rs b/substrate/node-template/runtime/src/template.rs index 5a4225e63a..0266890dd8 100644 --- a/substrate/node-template/runtime/src/template.rs +++ b/substrate/node-template/runtime/src/template.rs @@ -69,12 +69,12 @@ decl_event!( mod tests { use super::*; - use runtime_io::with_externalities; - use primitives::{H256, Blake2Hasher}; + use primitives::H256; use support::{impl_outer_origin, assert_ok, parameter_types}; - use sr_primitives::{traits::{BlakeTwo256, IdentityLookup}, testing::Header}; - use sr_primitives::weights::Weight; - use sr_primitives::Perbill; + use sr_primitives::{ + set_and_run_with_externalities, traits::{BlakeTwo256, IdentityLookup}, testing::Header, + weights::Weight, Perbill, + }; impl_outer_origin! { pub enum Origin for Test {} @@ -116,13 +116,13 @@ mod tests { // This function basically just builds a genesis storage key/value store according to // our desired mockup. - fn new_test_ext() -> runtime_io::TestExternalities { + fn new_test_ext() -> runtime_io::TestExternalities { system::GenesisConfig::default().build_storage::().unwrap().into() } #[test] fn it_works_for_default_value() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // Just a dummy test for the dummy funtion `do_something` // calling the `do_something` function with a value 42 assert_ok!(TemplateModule::do_something(Origin::signed(1), 42)); diff --git a/substrate/node/executor/src/lib.rs b/substrate/node/executor/src/lib.rs index 38656b7bd4..40c1e08f9b 100644 --- a/substrate/node/executor/src/lib.rs +++ b/substrate/node/executor/src/lib.rs @@ -36,7 +36,6 @@ native_executor_instance!( mod tests { use super::Executor; use {balances, contracts, indices, system, timestamp}; - use runtime_io; use codec::{Encode, Decode, Joiner}; use runtime_support::{ Hashable, StorageValue, StorageMap, traits::Currency, @@ -121,7 +120,7 @@ mod tests { NativeExecutor::new(WasmExecutionMethod::Interpreted, None) } - fn set_heap_pages>(ext: &mut E, heap_pages: u64) { + fn set_heap_pages(ext: &mut E, heap_pages: u64) { ext.place_storage(well_known_keys::HEAP_PAGES.to_vec(), Some(heap_pages.encode())); } @@ -227,7 +226,7 @@ mod tests { ).0; assert!(r.is_ok()); - runtime_io::with_externalities(&mut t, || { + sr_primitives::set_and_run_with_externalities(&mut t, || { assert_eq!(Balances::total_balance(&alice()), 42 * DOLLARS - transfer_fee(&xt())); assert_eq!(Balances::total_balance(&bob()), 69 * DOLLARS); }); @@ -263,7 +262,7 @@ mod tests { ).0; assert!(r.is_ok()); - runtime_io::with_externalities(&mut t, || { + sr_primitives::set_and_run_with_externalities(&mut t, || { assert_eq!(Balances::total_balance(&alice()), 42 * DOLLARS - transfer_fee(&xt())); assert_eq!(Balances::total_balance(&bob()), 69 * DOLLARS); }); @@ -434,7 +433,7 @@ mod tests { None, ).0.unwrap(); - runtime_io::with_externalities(&mut t, || { + sr_primitives::set_and_run_with_externalities(&mut t, || { assert_eq!(Balances::total_balance(&alice()), 42 * DOLLARS - transfer_fee(&xt())); assert_eq!(Balances::total_balance(&bob()), 169 * DOLLARS); let events = vec![ @@ -469,7 +468,7 @@ mod tests { None, ).0.unwrap(); - runtime_io::with_externalities(&mut t, || { + sr_primitives::set_and_run_with_externalities(&mut t, || { // NOTE: fees differ slightly in tests that execute more than one block due to the // weight update. Hence, using `assert_eq_error_rate`. assert_eq_error_rate!( @@ -541,7 +540,7 @@ mod tests { None, ).0.unwrap(); - runtime_io::with_externalities(&mut t, || { + sr_primitives::set_and_run_with_externalities(&mut t, || { assert_eq!(Balances::total_balance(&alice()), 42 * DOLLARS - transfer_fee(&xt())); assert_eq!(Balances::total_balance(&bob()), 169 * DOLLARS); }); @@ -554,7 +553,7 @@ mod tests { None, ).0.unwrap(); - runtime_io::with_externalities(&mut t, || { + sr_primitives::set_and_run_with_externalities(&mut t, || { assert_eq_error_rate!( Balances::total_balance(&alice()), 32 * DOLLARS - 2 * transfer_fee(&xt()), @@ -716,7 +715,7 @@ mod tests { None, ).0.unwrap(); - runtime_io::with_externalities(&mut t, || { + sr_primitives::set_and_run_with_externalities(&mut t, || { // Verify that the contract constructor worked well and code of TRANSFER contract is actually deployed. assert_eq!( &contracts::ContractInfoOf::::get(addr) @@ -837,7 +836,7 @@ mod tests { .expect("Extrinsic could be applied") .expect("Extrinsic did not fail"); - runtime_io::with_externalities(&mut t, || { + sr_primitives::set_and_run_with_externalities(&mut t, || { assert_eq!(Balances::total_balance(&alice()), 42 * DOLLARS - 1 * transfer_fee(&xt())); assert_eq!(Balances::total_balance(&bob()), 69 * DOLLARS); }); @@ -896,7 +895,7 @@ mod tests { let mut prev_multiplier = WeightMultiplier::default(); - runtime_io::with_externalities(&mut t, || { + sr_primitives::set_and_run_with_externalities(&mut t, || { assert_eq!(System::next_weight_multiplier(), prev_multiplier); }); @@ -948,7 +947,7 @@ mod tests { ).0.unwrap(); // weight multiplier is increased for next block. - runtime_io::with_externalities(&mut t, || { + sr_primitives::set_and_run_with_externalities(&mut t, || { let fm = System::next_weight_multiplier(); println!("After a big block: {:?} -> {:?}", prev_multiplier, fm); assert!(fm > prev_multiplier); @@ -965,7 +964,7 @@ mod tests { ).0.unwrap(); // weight multiplier is increased for next block. - runtime_io::with_externalities(&mut t, || { + sr_primitives::set_and_run_with_externalities(&mut t, || { let fm = System::next_weight_multiplier(); println!("After a small block: {:?} -> {:?}", prev_multiplier, fm); assert!(fm < prev_multiplier); @@ -1019,7 +1018,7 @@ mod tests { ).0; assert!(r.is_ok()); - runtime_io::with_externalities(&mut t, || { + sr_primitives::set_and_run_with_externalities(&mut t, || { assert_eq!(Balances::total_balance(&bob()), (10 + 69) * DOLLARS); // Components deducted from alice's balances: // - Weight fee diff --git a/substrate/srml/assets/src/lib.rs b/substrate/srml/assets/src/lib.rs index 2a4245176a..e7f258483f 100644 --- a/substrate/srml/assets/src/lib.rs +++ b/substrate/srml/assets/src/lib.rs @@ -240,12 +240,14 @@ impl Module { mod tests { use super::*; - use runtime_io::with_externalities; use support::{impl_outer_origin, assert_ok, assert_noop, parameter_types}; - use primitives::{H256, Blake2Hasher}; + use primitives::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 sr_primitives::{Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header}; + use sr_primitives::{ + Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header, + set_and_run_with_externalities, + }; impl_outer_origin! { pub enum Origin for Test {} @@ -289,13 +291,13 @@ mod tests { // This function basically just builds a genesis storage key/value store according to // our desired mockup. - fn new_test_ext() -> runtime_io::TestExternalities { + fn new_test_ext() -> runtime_io::TestExternalities { system::GenesisConfig::default().build_storage::().unwrap().into() } #[test] fn issuing_asset_units_to_issuer_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_ok!(Assets::issue(Origin::signed(1), 100)); assert_eq!(Assets::balance(0, 1), 100); }); @@ -303,7 +305,7 @@ mod tests { #[test] fn querying_total_supply_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_ok!(Assets::issue(Origin::signed(1), 100)); assert_eq!(Assets::balance(0, 1), 100); assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 50)); @@ -320,7 +322,7 @@ mod tests { #[test] fn transferring_amount_above_available_balance_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_ok!(Assets::issue(Origin::signed(1), 100)); assert_eq!(Assets::balance(0, 1), 100); assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 50)); @@ -331,7 +333,7 @@ mod tests { #[test] fn transferring_amount_less_than_available_balance_should_not_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_ok!(Assets::issue(Origin::signed(1), 100)); assert_eq!(Assets::balance(0, 1), 100); assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 50)); @@ -345,7 +347,7 @@ mod tests { #[test] fn transferring_less_than_one_unit_should_not_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_ok!(Assets::issue(Origin::signed(1), 100)); assert_eq!(Assets::balance(0, 1), 100); assert_noop!(Assets::transfer(Origin::signed(1), 0, 2, 0), "transfer amount should be non-zero"); @@ -354,7 +356,7 @@ mod tests { #[test] fn transferring_more_units_than_total_supply_should_not_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_ok!(Assets::issue(Origin::signed(1), 100)); assert_eq!(Assets::balance(0, 1), 100); assert_noop!(Assets::transfer(Origin::signed(1), 0, 2, 101), "origin account balance must be greater than or equal to the transfer amount"); @@ -363,7 +365,7 @@ mod tests { #[test] fn destroying_asset_balance_with_positive_balance_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_ok!(Assets::issue(Origin::signed(1), 100)); assert_eq!(Assets::balance(0, 1), 100); assert_ok!(Assets::destroy(Origin::signed(1), 0)); @@ -372,7 +374,7 @@ mod tests { #[test] fn destroying_asset_balance_with_zero_balance_should_not_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_ok!(Assets::issue(Origin::signed(1), 100)); assert_eq!(Assets::balance(0, 2), 0); assert_noop!(Assets::destroy(Origin::signed(2), 0), "origin balance should be non-zero"); diff --git a/substrate/srml/aura/src/mock.rs b/substrate/srml/aura/src/mock.rs index 6dc8953e88..7ebfd2a533 100644 --- a/substrate/srml/aura/src/mock.rs +++ b/substrate/srml/aura/src/mock.rs @@ -26,7 +26,7 @@ use sr_primitives::{ }; use support::{impl_outer_origin, parameter_types}; use runtime_io; -use primitives::{H256, Blake2Hasher}; +use primitives::H256; impl_outer_origin!{ pub enum Origin for Test {} @@ -73,7 +73,7 @@ impl Trait for Test { type AuthorityId = AuthorityId; } -pub fn new_test_ext(authorities: Vec) -> runtime_io::TestExternalities { +pub fn new_test_ext(authorities: Vec) -> runtime_io::TestExternalities { let mut t = system::GenesisConfig::default().build_storage::().unwrap(); GenesisConfig::{ authorities: authorities.into_iter().map(|a| UintAuthorityId(a).to_public_key()).collect(), diff --git a/substrate/srml/aura/src/tests.rs b/substrate/srml/aura/src/tests.rs index a90eddf18f..0537fc8b64 100644 --- a/substrate/srml/aura/src/tests.rs +++ b/substrate/srml/aura/src/tests.rs @@ -18,12 +18,12 @@ #![cfg(test)] -use runtime_io::with_externalities; +use sr_primitives::set_and_run_with_externalities; use crate::mock::{Aura, new_test_ext}; #[test] fn initial_values() { - with_externalities(&mut new_test_ext(vec![0, 1, 2, 3]), || { + set_and_run_with_externalities(&mut new_test_ext(vec![0, 1, 2, 3]), || { assert_eq!(Aura::last(), 0u64); assert_eq!(Aura::authorities().len(), 4); }); diff --git a/substrate/srml/authority-discovery/src/lib.rs b/substrate/srml/authority-discovery/src/lib.rs index 2ec9e98835..38d587ba05 100644 --- a/substrate/srml/authority-discovery/src/lib.rs +++ b/substrate/srml/authority-discovery/src/lib.rs @@ -135,12 +135,12 @@ impl session::OneSessionHandler for Module { mod tests { use super::*; use app_crypto::Pair; - use primitives::testing::KeyStore; - use primitives::{crypto::key_types, sr25519, traits::BareCryptoStore, H256}; - use runtime_io::{with_externalities, TestExternalities}; - use sr_primitives::testing::{Header, UintAuthorityId}; - use sr_primitives::traits::{ConvertInto, IdentityLookup, OpaqueKeys}; - use sr_primitives::Perbill; + use primitives::{testing::KeyStore, crypto::key_types, sr25519, H256, traits::KeystoreExt}; + use runtime_io::TestExternalities; + use sr_primitives::{ + testing::{Header, UintAuthorityId}, traits::{ConvertInto, IdentityLookup, OpaqueKeys}, + Perbill, set_and_run_with_externalities, + }; use support::{impl_outer_origin, parameter_types}; type AuthorityDiscovery = Module; @@ -261,9 +261,9 @@ mod tests { // Create externalities. let mut externalities = TestExternalities::new(t); - externalities.set_keystore(key_store); + externalities.register_extension(KeystoreExt(key_store)); - with_externalities(&mut externalities, || { + set_and_run_with_externalities(&mut externalities, || { assert_eq!( authority_id, AuthorityDiscovery::authority_id().expect("Retrieving public key.") @@ -298,9 +298,9 @@ mod tests { // Create externalities. let mut externalities = TestExternalities::new(t); - externalities.set_keystore(key_store); + externalities.register_extension(KeystoreExt(key_store)); - with_externalities(&mut externalities, || { + set_and_run_with_externalities(&mut externalities, || { assert_eq!(None, AuthorityDiscovery::authority_id()); }); } @@ -335,9 +335,9 @@ mod tests { // Create externalities. let mut externalities = TestExternalities::new(t); - externalities.set_keystore(key_store); + externalities.register_extension(KeystoreExt(key_store)); - with_externalities(&mut externalities, || { + set_and_run_with_externalities(&mut externalities, || { let payload = String::from("test payload").into_bytes(); let (sig, authority_id) = AuthorityDiscovery::sign(&payload).expect("signature"); @@ -350,7 +350,7 @@ mod tests { assert!(!AuthorityDiscovery::verify( &String::from("other payload").into_bytes(), sig, - authority_id + authority_id, )) }); } diff --git a/substrate/srml/authorship/src/lib.rs b/substrate/srml/authorship/src/lib.rs index 490774c734..0033e53221 100644 --- a/substrate/srml/authorship/src/lib.rs +++ b/substrate/srml/authorship/src/lib.rs @@ -412,12 +412,11 @@ impl ProvideInherent for Module { #[cfg(test)] mod tests { use super::*; - use runtime_io::with_externalities; - use primitives::{H256, Blake2Hasher}; - use sr_primitives::traits::{BlakeTwo256, IdentityLookup}; - use sr_primitives::testing::Header; - use sr_primitives::generic::DigestItem; - use sr_primitives::Perbill; + use primitives::H256; + use sr_primitives::{ + set_and_run_with_externalities, traits::{BlakeTwo256, IdentityLookup}, testing::Header, + generic::DigestItem, Perbill, + }; use support::{parameter_types, impl_outer_origin, ConsensusEngineId}; impl_outer_origin!{ @@ -535,7 +534,7 @@ mod tests { ) } - fn new_test_ext() -> runtime_io::TestExternalities { + fn new_test_ext() -> runtime_io::TestExternalities { let t = system::GenesisConfig::default().build_storage::().unwrap(); t.into() } @@ -543,7 +542,7 @@ mod tests { #[test] fn prune_old_uncles_works() { use UncleEntryItem::*; - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { let hash = Default::default(); let author = Default::default(); let uncles = vec![ @@ -562,7 +561,7 @@ mod tests { #[test] fn rejects_bad_uncles() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { let author_a = 69; struct CanonChain { @@ -675,7 +674,7 @@ mod tests { #[test] fn sets_author_lazily() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { let author = 42; let mut header = seal_header( create_header(1, Default::default(), [1; 32].into()), diff --git a/substrate/srml/babe/src/mock.rs b/substrate/srml/babe/src/mock.rs index acc08c7a3b..582299f11c 100644 --- a/substrate/srml/babe/src/mock.rs +++ b/substrate/srml/babe/src/mock.rs @@ -101,7 +101,7 @@ impl Trait for Test { type EpochChangeTrigger = crate::ExternalTrigger; } -pub fn new_test_ext(authorities: Vec) -> runtime_io::TestExternalities { +pub fn new_test_ext(authorities: Vec) -> runtime_io::TestExternalities { let mut t = system::GenesisConfig::default().build_storage::().unwrap(); GenesisConfig { authorities: authorities.into_iter().map(|a| (UintAuthorityId(a).to_public_key(), 1)).collect(), diff --git a/substrate/srml/babe/src/tests.rs b/substrate/srml/babe/src/tests.rs index ef449485b7..0a165b3854 100644 --- a/substrate/srml/babe/src/tests.rs +++ b/substrate/srml/babe/src/tests.rs @@ -17,9 +17,10 @@ //! Consensus extension module tests for BABE consensus. use super::*; -use runtime_io::with_externalities; use mock::{new_test_ext, Babe, Test}; -use sr_primitives::{traits::OnFinalize, testing::{Digest, DigestItem}}; +use sr_primitives::{ + set_and_run_with_externalities, traits::OnFinalize, testing::{Digest, DigestItem}, +}; use session::ShouldEndSession; const EMPTY_RANDOMNESS: [u8; 32] = [ @@ -53,14 +54,14 @@ fn empty_randomness_is_correct() { #[test] fn initial_values() { - with_externalities(&mut new_test_ext(vec![0, 1, 2, 3]), || { + set_and_run_with_externalities(&mut new_test_ext(vec![0, 1, 2, 3]), || { assert_eq!(Babe::authorities().len(), 4) }) } #[test] fn check_module() { - with_externalities(&mut new_test_ext(vec![0, 1, 2, 3]), || { + set_and_run_with_externalities(&mut new_test_ext(vec![0, 1, 2, 3]), || { assert!(!Babe::should_end_session(0), "Genesis does not change sessions"); assert!(!Babe::should_end_session(200000), "BABE does not include the block number in epoch calculations"); @@ -71,7 +72,7 @@ type System = system::Module; #[test] fn first_block_epoch_zero_start() { - with_externalities(&mut new_test_ext(vec![0, 1, 2, 3]), || { + set_and_run_with_externalities(&mut new_test_ext(vec![0, 1, 2, 3]), || { let genesis_slot = 100; let first_vrf = [1; 32]; let pre_digest = make_pre_digest( @@ -119,7 +120,7 @@ fn first_block_epoch_zero_start() { #[test] fn authority_index() { - with_externalities(&mut new_test_ext(vec![0, 1, 2, 3]), || { + set_and_run_with_externalities(&mut new_test_ext(vec![0, 1, 2, 3]), || { assert_eq!( Babe::find_author((&[(BABE_ENGINE_ID, &[][..])]).into_iter().cloned()), None, "Trivially invalid authorities are ignored") diff --git a/substrate/srml/balances/src/mock.rs b/substrate/srml/balances/src/mock.rs index 12a49fc90d..a909795178 100644 --- a/substrate/srml/balances/src/mock.rs +++ b/substrate/srml/balances/src/mock.rs @@ -20,7 +20,7 @@ use sr_primitives::{Perbill, traits::{Convert, IdentityLookup}, testing::Header, weights::{DispatchInfo, Weight}}; -use primitives::{H256, Blake2Hasher}; +use primitives::H256; use runtime_io; use support::{impl_outer_origin, parameter_types}; use support::traits::Get; @@ -179,7 +179,7 @@ impl ExtBuilder { TRANSACTION_BYTE_FEE.with(|v| *v.borrow_mut() = self.transaction_byte_fee); WEIGHT_TO_FEE.with(|v| *v.borrow_mut() = self.weight_to_fee); } - pub fn build(self) -> runtime_io::TestExternalities { + pub fn build(self) -> runtime_io::TestExternalities { self.set_associated_consts(); let mut t = system::GenesisConfig::default().build_storage::().unwrap(); GenesisConfig:: { diff --git a/substrate/srml/balances/src/tests.rs b/substrate/srml/balances/src/tests.rs index 8e9f6acdd8..b4745c2253 100644 --- a/substrate/srml/balances/src/tests.rs +++ b/substrate/srml/balances/src/tests.rs @@ -20,7 +20,7 @@ use super::*; use mock::{Balances, ExtBuilder, Runtime, System, info_from_weight, CALL}; -use runtime_io::with_externalities; +use sr_primitives::set_and_run_with_externalities; use support::{ assert_noop, assert_ok, assert_err, traits::{LockableCurrency, LockIdentifier, WithdrawReason, WithdrawReasons, @@ -34,7 +34,7 @@ const ID_3: LockIdentifier = *b"3 "; #[test] fn basic_locking_should_work() { - with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || { assert_eq!(Balances::free_balance(&1), 10); Balances::set_lock(ID_1, &1, 9, u64::max_value(), WithdrawReasons::all()); assert_noop!( @@ -46,7 +46,7 @@ fn basic_locking_should_work() { #[test] fn partial_locking_should_work() { - with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || { Balances::set_lock(ID_1, &1, 5, u64::max_value(), WithdrawReasons::all()); assert_ok!(>::transfer(&1, &2, 1)); }); @@ -54,7 +54,7 @@ fn partial_locking_should_work() { #[test] fn lock_removal_should_work() { - with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || { Balances::set_lock(ID_1, &1, u64::max_value(), u64::max_value(), WithdrawReasons::all()); Balances::remove_lock(ID_1, &1); assert_ok!(>::transfer(&1, &2, 1)); @@ -63,7 +63,7 @@ fn lock_removal_should_work() { #[test] fn lock_replacement_should_work() { - with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || { Balances::set_lock(ID_1, &1, u64::max_value(), u64::max_value(), WithdrawReasons::all()); Balances::set_lock(ID_1, &1, 5, u64::max_value(), WithdrawReasons::all()); assert_ok!(>::transfer(&1, &2, 1)); @@ -72,7 +72,7 @@ fn lock_replacement_should_work() { #[test] fn double_locking_should_work() { - with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || { Balances::set_lock(ID_1, &1, 5, u64::max_value(), WithdrawReasons::all()); Balances::set_lock(ID_2, &1, 5, u64::max_value(), WithdrawReasons::all()); assert_ok!(>::transfer(&1, &2, 1)); @@ -81,7 +81,7 @@ fn double_locking_should_work() { #[test] fn combination_locking_should_work() { - with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || { Balances::set_lock(ID_1, &1, u64::max_value(), 0, WithdrawReasons::none()); Balances::set_lock(ID_2, &1, 0, u64::max_value(), WithdrawReasons::none()); Balances::set_lock(ID_3, &1, 0, 0, WithdrawReasons::all()); @@ -91,7 +91,7 @@ fn combination_locking_should_work() { #[test] fn lock_value_extension_should_work() { - with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || { Balances::set_lock(ID_1, &1, 5, u64::max_value(), WithdrawReasons::all()); assert_noop!( >::transfer(&1, &2, 6), @@ -112,7 +112,7 @@ fn lock_value_extension_should_work() { #[test] fn lock_reasons_should_work() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default() .existential_deposit(1) .monied(true).transaction_fees(0, 1, 0) @@ -163,7 +163,7 @@ fn lock_reasons_should_work() { #[test] fn lock_block_number_should_work() { - with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || { Balances::set_lock(ID_1, &1, 10, 2, WithdrawReasons::all()); assert_noop!( >::transfer(&1, &2, 1), @@ -177,7 +177,7 @@ fn lock_block_number_should_work() { #[test] fn lock_block_number_extension_should_work() { - with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || { Balances::set_lock(ID_1, &1, 10, 2, WithdrawReasons::all()); assert_noop!( >::transfer(&1, &2, 6), @@ -199,7 +199,7 @@ fn lock_block_number_extension_should_work() { #[test] fn lock_reasons_extension_should_work() { - with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || { Balances::set_lock(ID_1, &1, 10, 10, WithdrawReason::Transfer.into()); assert_noop!( >::transfer(&1, &2, 6), @@ -220,7 +220,7 @@ fn lock_reasons_extension_should_work() { #[test] fn default_indexing_on_new_accounts_should_not_work2() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default() .existential_deposit(10) .creation_fee(50) @@ -242,7 +242,7 @@ fn default_indexing_on_new_accounts_should_not_work2() { #[test] fn reserved_balance_should_prevent_reclaim_count() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default() .existential_deposit(256 * 1) .monied(true) @@ -281,7 +281,7 @@ fn reserved_balance_should_prevent_reclaim_count() { #[test] fn reward_should_work() { - with_externalities(&mut ExtBuilder::default().monied(true).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().monied(true).build(), || { assert_eq!(Balances::total_balance(&1), 10); assert_ok!(Balances::deposit_into_existing(&1, 10).map(drop)); assert_eq!(Balances::total_balance(&1), 20); @@ -291,7 +291,7 @@ fn reward_should_work() { #[test] fn dust_account_removal_should_work() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default() .existential_deposit(100) .monied(true) @@ -311,7 +311,7 @@ fn dust_account_removal_should_work() { #[test] fn dust_account_removal_should_work2() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default() .existential_deposit(100) .creation_fee(50) @@ -332,7 +332,7 @@ fn dust_account_removal_should_work2() { #[test] fn balance_works() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let _ = Balances::deposit_creating(&1, 42); assert_eq!(Balances::free_balance(&1), 42); assert_eq!(Balances::reserved_balance(&1), 0); @@ -345,7 +345,7 @@ fn balance_works() { #[test] fn balance_transfer_works() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let _ = Balances::deposit_creating(&1, 111); assert_ok!(Balances::transfer(Some(1).into(), 2, 69)); assert_eq!(Balances::total_balance(&1), 42); @@ -355,7 +355,7 @@ fn balance_transfer_works() { #[test] fn force_transfer_works() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let _ = Balances::deposit_creating(&1, 111); assert_noop!( Balances::force_transfer(Some(2).into(), 1, 2, 69), @@ -369,7 +369,7 @@ fn force_transfer_works() { #[test] fn reserving_balance_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let _ = Balances::deposit_creating(&1, 111); assert_eq!(Balances::total_balance(&1), 111); @@ -386,7 +386,7 @@ fn reserving_balance_should_work() { #[test] fn balance_transfer_when_reserved_should_not_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let _ = Balances::deposit_creating(&1, 111); assert_ok!(Balances::reserve(&1, 69)); assert_noop!( @@ -398,7 +398,7 @@ fn balance_transfer_when_reserved_should_not_work() { #[test] fn deducting_balance_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let _ = Balances::deposit_creating(&1, 111); assert_ok!(Balances::reserve(&1, 69)); assert_eq!(Balances::free_balance(&1), 42); @@ -407,7 +407,7 @@ fn deducting_balance_should_work() { #[test] fn refunding_balance_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let _ = Balances::deposit_creating(&1, 42); Balances::set_reserved_balance(&1, 69); Balances::unreserve(&1, 69); @@ -418,7 +418,7 @@ fn refunding_balance_should_work() { #[test] fn slashing_balance_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let _ = Balances::deposit_creating(&1, 111); assert_ok!(Balances::reserve(&1, 69)); assert!(Balances::slash(&1, 69).1.is_zero()); @@ -430,7 +430,7 @@ fn slashing_balance_should_work() { #[test] fn slashing_incomplete_balance_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let _ = Balances::deposit_creating(&1, 42); assert_ok!(Balances::reserve(&1, 21)); assert_eq!(Balances::slash(&1, 69).1, 27); @@ -442,7 +442,7 @@ fn slashing_incomplete_balance_should_work() { #[test] fn unreserving_balance_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let _ = Balances::deposit_creating(&1, 111); assert_ok!(Balances::reserve(&1, 111)); Balances::unreserve(&1, 42); @@ -453,7 +453,7 @@ fn unreserving_balance_should_work() { #[test] fn slashing_reserved_balance_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let _ = Balances::deposit_creating(&1, 111); assert_ok!(Balances::reserve(&1, 111)); assert_eq!(Balances::slash_reserved(&1, 42).1, 0); @@ -465,7 +465,7 @@ fn slashing_reserved_balance_should_work() { #[test] fn slashing_incomplete_reserved_balance_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let _ = Balances::deposit_creating(&1, 111); assert_ok!(Balances::reserve(&1, 42)); assert_eq!(Balances::slash_reserved(&1, 69).1, 27); @@ -477,7 +477,7 @@ fn slashing_incomplete_reserved_balance_should_work() { #[test] fn transferring_reserved_balance_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let _ = Balances::deposit_creating(&1, 110); let _ = Balances::deposit_creating(&2, 1); assert_ok!(Balances::reserve(&1, 110)); @@ -491,7 +491,7 @@ fn transferring_reserved_balance_should_work() { #[test] fn transferring_reserved_balance_to_nonexistent_should_fail() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let _ = Balances::deposit_creating(&1, 111); assert_ok!(Balances::reserve(&1, 111)); assert_noop!(Balances::repatriate_reserved(&1, &2, 42), "beneficiary account must pre-exist"); @@ -500,7 +500,7 @@ fn transferring_reserved_balance_to_nonexistent_should_fail() { #[test] fn transferring_incomplete_reserved_balance_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let _ = Balances::deposit_creating(&1, 110); let _ = Balances::deposit_creating(&2, 1); assert_ok!(Balances::reserve(&1, 41)); @@ -514,7 +514,7 @@ fn transferring_incomplete_reserved_balance_should_work() { #[test] fn transferring_too_high_value_should_not_panic() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { >::insert(1, u64::max_value()); >::insert(2, 1); @@ -530,7 +530,7 @@ fn transferring_too_high_value_should_not_panic() { #[test] fn account_create_on_free_too_low_with_other() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(100).build(), || { let _ = Balances::deposit_creating(&1, 100); @@ -547,7 +547,7 @@ fn account_create_on_free_too_low_with_other() { #[test] fn account_create_on_free_too_low() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(100).build(), || { // No-op. @@ -560,7 +560,7 @@ fn account_create_on_free_too_low() { #[test] fn account_removal_on_free_too_low() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(100).build(), || { assert_eq!(>::get(), 0); @@ -590,7 +590,7 @@ fn account_removal_on_free_too_low() { #[test] fn transfer_overflow_isnt_exploitable() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().creation_fee(50).build(), || { // Craft a value that will overflow if summed with `creation_fee`. @@ -606,7 +606,7 @@ fn transfer_overflow_isnt_exploitable() { #[test] fn check_vesting_status() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default() .existential_deposit(256) .monied(true) @@ -669,7 +669,7 @@ fn check_vesting_status() { #[test] fn unvested_balance_should_not_transfer() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default() .existential_deposit(10) .monied(true) @@ -691,7 +691,7 @@ fn unvested_balance_should_not_transfer() { #[test] fn vested_balance_should_transfer() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default() .existential_deposit(10) .monied(true) @@ -710,7 +710,7 @@ fn vested_balance_should_transfer() { #[test] fn extra_balance_should_transfer() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default() .existential_deposit(10) .monied(true) @@ -740,7 +740,7 @@ fn extra_balance_should_transfer() { #[test] fn liquid_funds_should_transfer_with_delayed_vesting() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default() .existential_deposit(256) .monied(true) @@ -770,7 +770,7 @@ fn liquid_funds_should_transfer_with_delayed_vesting() { #[test] fn signed_extension_take_fees_work() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default() .existential_deposit(10) .transaction_fees(10, 1, 5) @@ -788,7 +788,7 @@ fn signed_extension_take_fees_work() { #[test] fn signed_extension_take_fees_is_bounded() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default() .existential_deposit(1000) .transaction_fees(0, 0, 1) @@ -810,7 +810,7 @@ fn signed_extension_take_fees_is_bounded() { #[test] fn burn_must_work() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default() .monied(true) .build(), diff --git a/substrate/srml/collective/src/lib.rs b/substrate/srml/collective/src/lib.rs index 4a157569c0..7ae352266a 100644 --- a/substrate/srml/collective/src/lib.rs +++ b/substrate/srml/collective/src/lib.rs @@ -382,10 +382,10 @@ mod tests { use support::{Hashable, assert_ok, assert_noop, parameter_types}; use system::{EventRecord, Phase}; use hex_literal::hex; - use runtime_io::with_externalities; - use primitives::{H256, Blake2Hasher}; + use primitives::H256; use sr_primitives::{ - Perbill, traits::{BlakeTwo256, IdentityLookup, Block as BlockT}, testing::Header, BuildStorage + set_and_run_with_externalities, Perbill, + traits::{BlakeTwo256, IdentityLookup, Block as BlockT}, testing::Header, BuildStorage, }; use crate as collective; @@ -439,7 +439,7 @@ mod tests { } ); - fn make_ext() -> runtime_io::TestExternalities { + fn make_ext() -> runtime_io::TestExternalities { GenesisConfig { collective_Instance1: Some(collective::GenesisConfig { members: vec![1, 2, 3], @@ -451,7 +451,7 @@ mod tests { #[test] fn motions_basic_environment_works() { - with_externalities(&mut make_ext(), || { + set_and_run_with_externalities(&mut make_ext(), || { System::set_block_number(1); assert_eq!(Collective::members(), vec![1, 2, 3]); assert_eq!(Collective::proposals(), Vec::::new()); @@ -464,7 +464,7 @@ mod tests { #[test] fn removal_of_old_voters_votes_works() { - with_externalities(&mut make_ext(), || { + set_and_run_with_externalities(&mut make_ext(), || { System::set_block_number(1); let proposal = make_proposal(42); let hash = BlakeTwo256::hash_of(&proposal); @@ -498,7 +498,7 @@ mod tests { #[test] fn removal_of_old_voters_votes_works_with_set_members() { - with_externalities(&mut make_ext(), || { + set_and_run_with_externalities(&mut make_ext(), || { System::set_block_number(1); let proposal = make_proposal(42); let hash = BlakeTwo256::hash_of(&proposal); @@ -532,7 +532,7 @@ mod tests { #[test] fn propose_works() { - with_externalities(&mut make_ext(), || { + set_and_run_with_externalities(&mut make_ext(), || { System::set_block_number(1); let proposal = make_proposal(42); let hash = proposal.blake2_256().into(); @@ -561,7 +561,7 @@ mod tests { #[test] fn motions_ignoring_non_collective_proposals_works() { - with_externalities(&mut make_ext(), || { + set_and_run_with_externalities(&mut make_ext(), || { System::set_block_number(1); let proposal = make_proposal(42); assert_noop!( @@ -573,7 +573,7 @@ mod tests { #[test] fn motions_ignoring_non_collective_votes_works() { - with_externalities(&mut make_ext(), || { + set_and_run_with_externalities(&mut make_ext(), || { System::set_block_number(1); let proposal = make_proposal(42); let hash: H256 = proposal.blake2_256().into(); @@ -584,7 +584,7 @@ mod tests { #[test] fn motions_ignoring_bad_index_collective_vote_works() { - with_externalities(&mut make_ext(), || { + set_and_run_with_externalities(&mut make_ext(), || { System::set_block_number(3); let proposal = make_proposal(42); let hash: H256 = proposal.blake2_256().into(); @@ -595,7 +595,7 @@ mod tests { #[test] fn motions_revoting_works() { - with_externalities(&mut make_ext(), || { + set_and_run_with_externalities(&mut make_ext(), || { System::set_block_number(1); let proposal = make_proposal(42); let hash: H256 = proposal.blake2_256().into(); @@ -640,7 +640,7 @@ mod tests { #[test] fn motions_disapproval_works() { - with_externalities(&mut make_ext(), || { + set_and_run_with_externalities(&mut make_ext(), || { System::set_block_number(1); let proposal = make_proposal(42); let hash: H256 = proposal.blake2_256().into(); @@ -683,7 +683,7 @@ mod tests { #[test] fn motions_approval_works() { - with_externalities(&mut make_ext(), || { + set_and_run_with_externalities(&mut make_ext(), || { System::set_block_number(1); let proposal = make_proposal(42); let hash: H256 = proposal.blake2_256().into(); diff --git a/substrate/srml/contracts/src/exec.rs b/substrate/srml/contracts/src/exec.rs index e4c5539cec..0cb0ee2679 100644 --- a/substrate/srml/contracts/src/exec.rs +++ b/substrate/srml/contracts/src/exec.rs @@ -803,16 +803,12 @@ mod tests { BalanceOf, ExecFeeToken, ExecutionContext, Ext, Loader, TransferFeeKind, TransferFeeToken, Vm, ExecResult, RawEvent, DeferredAction, }; - use crate::account_db::AccountDb; - use crate::exec::{ExecReturnValue, ExecError, STATUS_SUCCESS}; - use crate::gas::GasMeter; - use crate::tests::{ExtBuilder, Test}; - use crate::{CodeHash, Config}; - use runtime_io::with_externalities; - use std::cell::RefCell; - use std::rc::Rc; - use std::collections::HashMap; - use std::marker::PhantomData; + use crate::{ + account_db::AccountDb, gas::GasMeter, tests::{ExtBuilder, Test}, + exec::{ExecReturnValue, ExecError, STATUS_SUCCESS}, CodeHash, Config, + }; + use sr_primitives::set_and_run_with_externalities; + use std::{cell::RefCell, rc::Rc, collections::HashMap, marker::PhantomData}; use assert_matches::assert_matches; const ALICE: u64 = 1; @@ -937,7 +933,7 @@ mod tests { exec_success() }); - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let cfg = Config::preload(); let mut ctx = ExecutionContext::top_level(ALICE, &cfg, &vm, &loader); ctx.overlay.instantiate_contract(&BOB, exec_ch).unwrap(); @@ -957,7 +953,7 @@ mod tests { let dest = BOB; // This test verifies that base fee for call is taken. - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let vm = MockVm::new(); let loader = MockLoader::empty(); let cfg = Config::preload(); @@ -975,7 +971,7 @@ mod tests { }); // This test verifies that base fee for instantiation is taken. - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let mut loader = MockLoader::empty(); let code = loader.insert(|_| exec_success()); @@ -1005,7 +1001,7 @@ mod tests { let vm = MockVm::new(); let loader = MockLoader::empty(); - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let cfg = Config::preload(); let mut ctx = ExecutionContext::top_level(origin, &cfg, &vm, &loader); ctx.overlay.set_balance(&origin, 100); @@ -1037,7 +1033,7 @@ mod tests { |_| Ok(ExecReturnValue { status: 1, data: Vec::new() }) ); - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let cfg = Config::preload(); let mut ctx = ExecutionContext::top_level(origin, &cfg, &vm, &loader); ctx.overlay.instantiate_contract(&BOB, return_ch).unwrap(); @@ -1065,7 +1061,7 @@ mod tests { // This test sends 50 units of currency to a non-existent account. // This should lead to creation of a new account thus // a fee should be charged. - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(15).build(), || { let vm = MockVm::new(); @@ -1094,7 +1090,7 @@ mod tests { // This one is similar to the previous one but transfer to an existing account. // In this test we expect that a regular transfer fee is charged. - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(15).build(), || { let vm = MockVm::new(); @@ -1123,7 +1119,7 @@ mod tests { // This test sends 50 units of currency as an endownment to a newly // instantiated contract. - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(15).build(), || { let mut loader = MockLoader::empty(); @@ -1164,7 +1160,7 @@ mod tests { let vm = MockVm::new(); let loader = MockLoader::empty(); - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let cfg = Config::preload(); let mut ctx = ExecutionContext::top_level(origin, &cfg, &vm, &loader); ctx.overlay.set_balance(&origin, 0); @@ -1198,7 +1194,7 @@ mod tests { |_| Ok(ExecReturnValue { status: STATUS_SUCCESS, data: vec![1, 2, 3, 4] }) ); - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let cfg = Config::preload(); let mut ctx = ExecutionContext::top_level(origin, &cfg, &vm, &loader); ctx.overlay.instantiate_contract(&BOB, return_ch).unwrap(); @@ -1229,7 +1225,7 @@ mod tests { |_| Ok(ExecReturnValue { status: 1, data: vec![1, 2, 3, 4] }) ); - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let cfg = Config::preload(); let mut ctx = ExecutionContext::top_level(origin, &cfg, &vm, &loader); ctx.overlay.instantiate_contract(&BOB, return_ch).unwrap(); @@ -1257,7 +1253,7 @@ mod tests { }); // This one tests passing the input data into a contract via call. - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let cfg = Config::preload(); let mut ctx = ExecutionContext::top_level(ALICE, &cfg, &vm, &loader); ctx.overlay.instantiate_contract(&BOB, input_data_ch).unwrap(); @@ -1282,7 +1278,7 @@ mod tests { }); // This one tests passing the input data into a contract via instantiate. - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let cfg = Config::preload(); let mut ctx = ExecutionContext::top_level(ALICE, &cfg, &vm, &loader); @@ -1326,7 +1322,7 @@ mod tests { exec_success() }); - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let cfg = Config::preload(); let mut ctx = ExecutionContext::top_level(ALICE, &cfg, &vm, &loader); ctx.overlay.instantiate_contract(&BOB, recurse_ch).unwrap(); @@ -1370,7 +1366,7 @@ mod tests { exec_success() }); - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let cfg = Config::preload(); let mut ctx = ExecutionContext::top_level(origin, &cfg, &vm, &loader); @@ -1412,7 +1408,7 @@ mod tests { exec_success() }); - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let cfg = Config::preload(); let mut ctx = ExecutionContext::top_level(ALICE, &cfg, &vm, &loader); ctx.overlay.instantiate_contract(&BOB, bob_ch).unwrap(); @@ -1436,7 +1432,7 @@ mod tests { let mut loader = MockLoader::empty(); let dummy_ch = loader.insert(|_| exec_success()); - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(15).build(), || { let cfg = Config::preload(); @@ -1464,7 +1460,7 @@ mod tests { |_| Ok(ExecReturnValue { status: STATUS_SUCCESS, data: vec![80, 65, 83, 83] }) ); - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(15).build(), || { let cfg = Config::preload(); @@ -1507,7 +1503,7 @@ mod tests { |_| Ok(ExecReturnValue { status: 1, data: vec![70, 65, 73, 76] }) ); - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(15).build(), || { let cfg = Config::preload(); @@ -1555,7 +1551,7 @@ mod tests { } }); - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(15).build(), || { let cfg = Config::preload(); @@ -1617,7 +1613,7 @@ mod tests { } }); - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(15).build(), || { let cfg = Config::preload(); @@ -1653,7 +1649,7 @@ mod tests { exec_success() }); - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let cfg = Config::preload(); let mut ctx = ExecutionContext::top_level(ALICE, &cfg, &vm, &loader); diff --git a/substrate/srml/contracts/src/tests.rs b/substrate/srml/contracts/src/tests.rs index f2ef8a275d..a92d11e4d4 100644 --- a/substrate/srml/contracts/src/tests.rs +++ b/substrate/srml/contracts/src/tests.rs @@ -19,21 +19,18 @@ #![allow(unused)] -use crate::account_db::{AccountDb, DirectAccountDb, OverlayAccountDb}; use crate::{ BalanceOf, ComputeDispatchFee, ContractAddressFor, ContractInfo, ContractInfoOf, GenesisConfig, Module, RawAliveContractInfo, RawEvent, Trait, TrieId, TrieIdFromParentCounter, Schedule, - TrieIdGenerator, CheckBlockGasLimit, + TrieIdGenerator, CheckBlockGasLimit, account_db::{AccountDb, DirectAccountDb, OverlayAccountDb}, }; use assert_matches::assert_matches; use hex_literal::*; use codec::{Decode, Encode, KeyedVec}; -use runtime_io; -use runtime_io::with_externalities; use sr_primitives::{ Perbill, BuildStorage, transaction_validity::{InvalidTransaction, ValidTransaction}, traits::{BlakeTwo256, Hash, IdentityLookup, SignedExtension}, - weights::{DispatchInfo, DispatchClass}, + weights::{DispatchInfo, DispatchClass}, set_and_run_with_externalities, testing::{Digest, DigestItem, Header, UintAuthorityId, H256}, }; use support::{ @@ -41,7 +38,7 @@ use support::{ storage::child, StorageMap, StorageValue, traits::{Currency, Get}, }; use std::{cell::RefCell, sync::atomic::{AtomicUsize, Ordering}}; -use primitives::{storage::well_known_keys, Blake2Hasher}; +use primitives::storage::well_known_keys; use system::{self, EventRecord, Phase}; mod contract { @@ -275,7 +272,7 @@ impl ExtBuilder { INSTANTIATION_FEE.with(|v| *v.borrow_mut() = self.instantiation_fee); BLOCK_GAS_LIMIT.with(|v| *v.borrow_mut() = self.block_gas_limit); } - pub fn build(self) -> runtime_io::TestExternalities { + pub fn build(self) -> runtime_io::TestExternalities { self.set_associated_consts(); let mut t = system::GenesisConfig::default().build_storage::().unwrap(); balances::GenesisConfig:: { @@ -307,7 +304,7 @@ fn compile_module(wabt_module: &str) // Then we check that the all unused gas is refunded. #[test] fn refunds_unused_gas() { - with_externalities(&mut ExtBuilder::default().gas_price(2).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().gas_price(2).build(), || { Balances::deposit_creating(&ALICE, 100_000_000); assert_ok!(Contract::call(Origin::signed(ALICE), BOB, 0, 100_000, Vec::new())); @@ -319,7 +316,7 @@ fn refunds_unused_gas() { #[test] fn account_removal_removes_storage() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(100).build(), || { let trie_id1 = ::TrieIdGenerator::trie_id(&1); @@ -419,7 +416,7 @@ const CODE_RETURN_FROM_START_FN: &str = r#" fn instantiate_and_call_and_deposit_event() { let (wasm, code_hash) = compile_module::(CODE_RETURN_FROM_START_FN).unwrap(); - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(100).build(), || { Balances::deposit_creating(&ALICE, 1_000_000); @@ -502,7 +499,7 @@ fn dispatch_call() { let (wasm, code_hash) = compile_module::(CODE_DISPATCH_CALL).unwrap(); - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(50).build(), || { Balances::deposit_creating(&ALICE, 1_000_000); @@ -623,7 +620,7 @@ fn dispatch_call_not_dispatched_after_top_level_transaction_failure() { let (wasm, code_hash) = compile_module::(CODE_DISPATCH_CALL_THEN_TRAP).unwrap(); - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(50).build(), || { Balances::deposit_creating(&ALICE, 1_000_000); @@ -826,7 +823,7 @@ fn test_set_rent_code_and_hash() { let (wasm, code_hash) = compile_module::(CODE_SET_RENT).unwrap(); - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(50).build(), || { Balances::deposit_creating(&ALICE, 1_000_000); @@ -855,7 +852,7 @@ fn storage_size() { let (wasm, code_hash) = compile_module::(CODE_SET_RENT).unwrap(); // Storage size - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(50).build(), || { // Create @@ -885,7 +882,7 @@ fn storage_size() { fn deduct_blocks() { let (wasm, code_hash) = compile_module::(CODE_SET_RENT).unwrap(); - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(50).build(), || { // Create @@ -982,7 +979,7 @@ fn claim_surcharge_malus() { fn claim_surcharge(blocks: u64, trigger_call: impl Fn() -> bool, removes: bool) { let (wasm, code_hash) = compile_module::(CODE_SET_RENT).unwrap(); - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(50).build(), || { // Create @@ -1018,7 +1015,7 @@ fn removals(trigger_call: impl Fn() -> bool) { let (wasm, code_hash) = compile_module::(CODE_SET_RENT).unwrap(); // Balance reached and superior to subsistence threshold - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(50).build(), || { // Create @@ -1057,7 +1054,7 @@ fn removals(trigger_call: impl Fn() -> bool) { ); // Allowance exceeded - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(50).build(), || { // Create @@ -1095,7 +1092,7 @@ fn removals(trigger_call: impl Fn() -> bool) { ); // Balance reached and inferior to subsistence threshold - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(50).build(), || { // Create @@ -1142,7 +1139,7 @@ fn call_removed_contract() { let (wasm, code_hash) = compile_module::(CODE_SET_RENT).unwrap(); // Balance reached and superior to subsistence threshold - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(50).build(), || { // Create @@ -1230,7 +1227,7 @@ const CODE_CHECK_DEFAULT_RENT_ALLOWANCE: &str = r#" fn default_rent_allowance_on_instantiate() { let (wasm, code_hash) = compile_module::(CODE_CHECK_DEFAULT_RENT_ALLOWANCE).unwrap(); - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(50).build(), || { // Create @@ -1347,7 +1344,7 @@ fn restoration(test_different_storage: bool, test_restore_to_with_dirty_storage: let (restoration_wasm, restoration_code_hash) = compile_module::(CODE_RESTORATION).unwrap(); - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(50).build(), || { Balances::deposit_creating(&ALICE, 1_000_000); @@ -1533,7 +1530,7 @@ const CODE_STORAGE_SIZE: &str = r#" fn storage_max_value_limit() { let (wasm, code_hash) = compile_module::(CODE_STORAGE_SIZE).unwrap(); - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(50).build(), || { // Create @@ -1900,7 +1897,7 @@ fn deploy_and_call_other_contract() { let (callee_wasm, callee_code_hash) = compile_module::(CODE_RETURN_WITH_DATA).unwrap(); let (caller_wasm, caller_code_hash) = compile_module::(CODE_CALLER_CONTRACT).unwrap(); - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(50).build(), || { // Create @@ -2031,7 +2028,7 @@ const CODE_SELF_DESTRUCT: &str = r#" #[test] fn self_destruct_by_draining_balance() { let (wasm, code_hash) = compile_module::(CODE_SELF_DESTRUCT).unwrap(); - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(50).build(), || { Balances::deposit_creating(&ALICE, 1_000_000); @@ -2070,7 +2067,7 @@ fn self_destruct_by_draining_balance() { #[test] fn cannot_self_destruct_while_live() { let (wasm, code_hash) = compile_module::(CODE_SELF_DESTRUCT).unwrap(); - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(50).build(), || { Balances::deposit_creating(&ALICE, 1_000_000); @@ -2272,7 +2269,7 @@ fn destroy_contract_and_transfer_funds() { let (callee_wasm, callee_code_hash) = compile_module::(CODE_SELF_DESTRUCT).unwrap(); let (caller_wasm, caller_code_hash) = compile_module::(CODE_DESTROY_AND_TRANSFER).unwrap(); - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(50).build(), || { // Create @@ -2371,7 +2368,7 @@ const CODE_SELF_DESTRUCTING_CONSTRUCTOR: &str = r#" #[test] fn cannot_self_destruct_in_constructor() { let (wasm, code_hash) = compile_module::(CODE_SELF_DESTRUCTING_CONSTRUCTOR).unwrap(); - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().existential_deposit(50).build(), || { Balances::deposit_creating(&ALICE, 1_000_000); @@ -2395,7 +2392,7 @@ fn cannot_self_destruct_in_constructor() { #[test] fn check_block_gas_limit_works() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().block_gas_limit(50).build(), || { let info = DispatchInfo { weight: 100, class: DispatchClass::Normal }; diff --git a/substrate/srml/council/src/lib.rs b/substrate/srml/council/src/lib.rs index aa27bcde21..e65cf9ace1 100644 --- a/substrate/srml/council/src/lib.rs +++ b/substrate/srml/council/src/lib.rs @@ -38,7 +38,6 @@ impl OnMembersChanged for () { mod tests { // These re-exports are here for a reason, edit with care pub use super::*; - pub use runtime_io::with_externalities; use support::{impl_outer_origin, impl_outer_event, impl_outer_dispatch, parameter_types}; use support::traits::Get; pub use primitives::{H256, Blake2Hasher, u32_trait::{_1, _2, _3, _4}}; diff --git a/substrate/srml/democracy/src/lib.rs b/substrate/srml/democracy/src/lib.rs index b93f6f893a..477e6818c9 100644 --- a/substrate/srml/democracy/src/lib.rs +++ b/substrate/srml/democracy/src/lib.rs @@ -971,14 +971,15 @@ impl OnFreeBalanceZero for Module { #[cfg(test)] mod tests { use super::*; - use runtime_io::with_externalities; use support::{ impl_outer_origin, impl_outer_dispatch, assert_noop, assert_ok, parameter_types, traits::Contains }; - use primitives::{H256, Blake2Hasher}; - use sr_primitives::{traits::{BlakeTwo256, IdentityLookup, Bounded}, testing::Header}; - use sr_primitives::Perbill; + use primitives::H256; + use sr_primitives::{ + set_and_run_with_externalities, traits::{BlakeTwo256, IdentityLookup, Bounded}, + testing::Header, Perbill, + }; use balances::BalanceLock; use system::EnsureSignedBy; @@ -1084,7 +1085,7 @@ mod tests { type CooloffPeriod = CooloffPeriod; } - fn new_test_ext() -> runtime_io::TestExternalities { + fn new_test_ext() -> runtime_io::TestExternalities { let mut t = system::GenesisConfig::default().build_storage::().unwrap(); balances::GenesisConfig::{ balances: vec![(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)], @@ -1100,7 +1101,7 @@ mod tests { #[test] fn params_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_eq!(Democracy::referendum_count(), 0); assert_eq!(Balances::free_balance(&42), 0); assert_eq!(Balances::total_issuance(), 210); @@ -1132,7 +1133,7 @@ mod tests { #[test] fn external_and_public_interleaving_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(0); assert_ok!(Democracy::external_propose( Origin::signed(2), @@ -1245,7 +1246,7 @@ mod tests { #[test] fn emergency_cancel_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(0); let r = Democracy::inject_referendum( 2, @@ -1274,7 +1275,7 @@ mod tests { #[test] fn veto_external_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(0); assert_ok!(Democracy::external_propose( Origin::signed(2), @@ -1334,7 +1335,7 @@ mod tests { #[test] fn external_referendum_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(0); assert_noop!(Democracy::external_propose( Origin::signed(1), @@ -1363,7 +1364,7 @@ mod tests { #[test] fn external_majority_referendum_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(0); assert_noop!(Democracy::external_propose_majority( Origin::signed(1), @@ -1388,7 +1389,7 @@ mod tests { #[test] fn external_default_referendum_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(0); assert_noop!(Democracy::external_propose_default( Origin::signed(3), @@ -1413,7 +1414,7 @@ mod tests { #[test] fn fast_track_referendum_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(0); let h = BlakeTwo256::hash_of(&set_balance_proposal(2)); assert_noop!(Democracy::fast_track(Origin::signed(5), h, 3, 2), "no proposal made"); @@ -1437,7 +1438,7 @@ mod tests { #[test] fn fast_track_referendum_fails_when_no_simple_majority() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(0); let h = BlakeTwo256::hash_of(&set_balance_proposal(2)); assert_ok!(Democracy::external_propose( @@ -1453,7 +1454,7 @@ mod tests { #[test] fn locked_for_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(1); assert_ok!(propose_set_balance(1, 2, 2)); assert_ok!(propose_set_balance(1, 4, 4)); @@ -1466,7 +1467,7 @@ mod tests { #[test] fn single_proposal_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(0); assert_ok!(propose_set_balance(1, 2, 1)); assert!(Democracy::referendum_info(0).is_none()); @@ -1513,7 +1514,7 @@ mod tests { #[test] fn cancel_queued_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(0); assert_ok!(propose_set_balance(1, 2, 1)); @@ -1537,7 +1538,7 @@ mod tests { #[test] fn proxy_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_eq!(Democracy::proxy(10), None); assert_ok!(Democracy::set_proxy(Origin::signed(1), 10)); assert_eq!(Democracy::proxy(10), Some(1)); @@ -1567,7 +1568,7 @@ mod tests { #[test] fn single_proposal_should_work_with_proxy() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(0); assert_ok!(propose_set_balance(1, 2, 1)); @@ -1587,7 +1588,7 @@ mod tests { #[test] fn single_proposal_should_work_with_delegation() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(0); assert_ok!(propose_set_balance(1, 2, 1)); @@ -1612,7 +1613,7 @@ mod tests { #[test] fn single_proposal_should_work_with_cyclic_delegation() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(0); assert_ok!(propose_set_balance(1, 2, 1)); @@ -1639,7 +1640,7 @@ mod tests { #[test] /// If transactor already voted, delegated vote is overwriten. fn single_proposal_should_work_with_vote_and_delegation() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(0); assert_ok!(propose_set_balance(1, 2, 1)); @@ -1665,7 +1666,7 @@ mod tests { #[test] fn single_proposal_should_work_with_undelegation() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(0); assert_ok!(propose_set_balance(1, 2, 1)); @@ -1694,7 +1695,7 @@ mod tests { #[test] /// If transactor voted, delegated vote is overwriten. fn single_proposal_should_work_with_delegation_and_vote() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(0); assert_ok!(propose_set_balance(1, 2, 1)); @@ -1725,7 +1726,7 @@ mod tests { #[test] fn deposit_for_proposals_should_be_taken() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(1); assert_ok!(propose_set_balance(1, 2, 5)); assert_ok!(Democracy::second(Origin::signed(2), 0)); @@ -1740,7 +1741,7 @@ mod tests { #[test] fn deposit_for_proposals_should_be_returned() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(1); assert_ok!(propose_set_balance(1, 2, 5)); assert_ok!(Democracy::second(Origin::signed(2), 0)); @@ -1756,7 +1757,7 @@ mod tests { #[test] fn proposal_with_deposit_below_minimum_should_not_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(1); assert_noop!(propose_set_balance(1, 2, 0), "value too low"); }); @@ -1764,7 +1765,7 @@ mod tests { #[test] fn poor_proposer_should_not_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(1); assert_noop!(propose_set_balance(1, 2, 11), "proposer\'s balance too low"); }); @@ -1772,7 +1773,7 @@ mod tests { #[test] fn poor_seconder_should_not_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(1); assert_ok!(propose_set_balance(2, 2, 11)); assert_noop!(Democracy::second(Origin::signed(1), 0), "seconder\'s balance too low"); @@ -1781,7 +1782,7 @@ mod tests { #[test] fn runners_up_should_come_after() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(0); assert_ok!(propose_set_balance(1, 2, 2)); assert_ok!(propose_set_balance(1, 4, 4)); @@ -1797,7 +1798,7 @@ mod tests { #[test] fn simple_passing_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(1); let r = Democracy::inject_referendum( 1, @@ -1820,7 +1821,7 @@ mod tests { #[test] fn cancel_referendum_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(1); let r = Democracy::inject_referendum( 1, @@ -1840,7 +1841,7 @@ mod tests { #[test] fn simple_failing_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(1); let r = Democracy::inject_referendum( 1, @@ -1863,7 +1864,7 @@ mod tests { #[test] fn controversial_voting_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(1); let r = Democracy::inject_referendum( 1, @@ -1889,7 +1890,7 @@ mod tests { #[test] fn delayed_enactment_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(1); let r = Democracy::inject_referendum( 1, @@ -1917,7 +1918,7 @@ mod tests { #[test] fn controversial_low_turnout_voting_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(1); let r = Democracy::inject_referendum( 1, @@ -1939,7 +1940,7 @@ mod tests { #[test] fn passing_low_turnout_voting_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_eq!(Balances::free_balance(&42), 0); assert_eq!(Balances::total_issuance(), 210); @@ -1965,7 +1966,7 @@ mod tests { #[test] fn lock_voting_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(0); let r = Democracy::inject_referendum( 1, @@ -2025,7 +2026,7 @@ mod tests { #[test] fn lock_voting_should_work_with_delegation() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(1); let r = Democracy::inject_referendum( 1, diff --git a/substrate/srml/elections-phragmen/src/lib.rs b/substrate/srml/elections-phragmen/src/lib.rs index 58c0f11340..1405536267 100644 --- a/substrate/srml/elections-phragmen/src/lib.rs +++ b/substrate/srml/elections-phragmen/src/lib.rs @@ -591,10 +591,10 @@ mod tests { use super::*; use std::cell::RefCell; use srml_support::{assert_ok, assert_noop, parameter_types, assert_eq_uvec}; - use runtime_io::with_externalities; - use primitives::{H256, Blake2Hasher}; - use sr_primitives::{Perbill, testing::Header, BuildStorage, - traits::{BlakeTwo256, IdentityLookup, Block as BlockT} + use primitives::H256; + use sr_primitives::{ + Perbill, testing::Header, BuildStorage, + traits::{BlakeTwo256, IdentityLookup, Block as BlockT}, set_and_run_with_externalities }; use crate as elections; @@ -730,7 +730,7 @@ mod tests { self.desired_runners_up = count; self } - pub fn build(self) -> runtime_io::TestExternalities { + pub fn build(self) -> runtime_io::TestExternalities { VOTING_BOND.with(|v| *v.borrow_mut() = self.voter_bond); GenesisConfig { balances: Some(balances::GenesisConfig::{ @@ -770,7 +770,7 @@ mod tests { #[test] fn params_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(1); assert_eq!(Elections::desired_members(), 2); assert_eq!(Elections::term_duration(), 5); @@ -790,7 +790,7 @@ mod tests { #[test] fn simple_candidate_submission_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_eq!(Elections::candidates(), Vec::::new()); assert!(Elections::is_candidate(&1).is_err()); assert!(Elections::is_candidate(&2).is_err()); @@ -817,7 +817,7 @@ mod tests { #[test] fn simple_candidate_submission_with_no_votes_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_eq!(Elections::candidates(), Vec::::new()); assert_ok!(Elections::submit_candidacy(Origin::signed(1))); @@ -844,7 +844,7 @@ mod tests { #[test] fn dupe_candidate_submission_should_not_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_eq!(Elections::candidates(), Vec::::new()); assert_ok!(Elections::submit_candidacy(Origin::signed(1))); assert_eq!(Elections::candidates(), vec![1]); @@ -858,7 +858,7 @@ mod tests { #[test] fn member_candidacy_submission_should_not_work() { // critically important to make sure that outgoing candidates and losers are not mixed up. - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); assert_ok!(Elections::vote(Origin::signed(2), vec![5], 20)); @@ -878,7 +878,7 @@ mod tests { #[test] fn poor_candidate_submission_should_not_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_eq!(Elections::candidates(), Vec::::new()); assert_noop!( Elections::submit_candidacy(Origin::signed(7)), @@ -889,7 +889,7 @@ mod tests { #[test] fn simple_voting_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_eq!(Elections::candidates(), Vec::::new()); assert_eq!(balances(&2), (20, 0)); @@ -903,7 +903,7 @@ mod tests { #[test] fn can_vote_with_custom_stake() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_eq!(Elections::candidates(), Vec::::new()); assert_eq!(balances(&2), (20, 0)); @@ -917,7 +917,7 @@ mod tests { #[test] fn can_update_votes_and_stake() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_eq!(balances(&2), (20, 0)); assert_ok!(Elections::submit_candidacy(Origin::signed(5))); @@ -938,7 +938,7 @@ mod tests { #[test] fn cannot_vote_for_no_candidate() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_noop!( Elections::vote(Origin::signed(2), vec![], 20), "cannot vote when no candidates or members exist" @@ -949,7 +949,7 @@ mod tests { #[test] fn can_vote_for_old_members_even_when_no_new_candidates() { // let allowed_votes = candidates_count as usize + Self::members().len() - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); assert_ok!(Elections::submit_candidacy(Origin::signed(4))); @@ -967,7 +967,7 @@ mod tests { #[test] fn cannot_vote_for_more_than_candidates() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); assert_ok!(Elections::submit_candidacy(Origin::signed(4))); @@ -980,7 +980,7 @@ mod tests { #[test] fn cannot_vote_for_less_than_ed() { - with_externalities(&mut ExtBuilder::default().voter_bond(8).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().voter_bond(8).build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); assert_ok!(Elections::submit_candidacy(Origin::signed(4))); @@ -993,7 +993,7 @@ mod tests { #[test] fn can_vote_for_more_than_total_balance_but_moot() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); assert_ok!(Elections::submit_candidacy(Origin::signed(4))); @@ -1006,7 +1006,7 @@ mod tests { #[test] fn remove_voter_should_work() { - with_externalities(&mut ExtBuilder::default().voter_bond(8).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().voter_bond(8).build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); assert_ok!(Elections::vote(Origin::signed(2), vec![5], 20)); @@ -1031,14 +1031,14 @@ mod tests { #[test] fn non_voter_remove_should_not_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_noop!(Elections::remove_voter(Origin::signed(3)), "must be a voter"); }); } #[test] fn dupe_remove_should_fail() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); assert_ok!(Elections::vote(Origin::signed(2), vec![5], 20)); @@ -1051,7 +1051,7 @@ mod tests { #[test] fn removed_voter_should_not_be_counted() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); assert_ok!(Elections::submit_candidacy(Origin::signed(4))); assert_ok!(Elections::submit_candidacy(Origin::signed(3))); @@ -1071,7 +1071,7 @@ mod tests { #[test] fn reporter_must_be_voter() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_noop!( Elections::report_defunct_voter(Origin::signed(1), 2), "reporter must be a voter", @@ -1081,7 +1081,7 @@ mod tests { #[test] fn can_detect_defunct_voter() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); assert_ok!(Elections::submit_candidacy(Origin::signed(4))); @@ -1116,7 +1116,7 @@ mod tests { #[test] fn report_voter_should_work_and_earn_reward() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); assert_ok!(Elections::submit_candidacy(Origin::signed(4))); @@ -1148,8 +1148,8 @@ mod tests { #[test] fn report_voter_should_slash_when_bad_report() { - with_externalities(&mut ExtBuilder::default().build(), || { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); assert_ok!(Elections::submit_candidacy(Origin::signed(4))); @@ -1180,7 +1180,7 @@ mod tests { #[test] fn simple_voting_rounds_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); assert_ok!(Elections::submit_candidacy(Origin::signed(4))); assert_ok!(Elections::submit_candidacy(Origin::signed(3))); @@ -1215,7 +1215,7 @@ mod tests { #[test] fn defunct_voter_will_be_counted() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); // This guy's vote is pointless for this round. @@ -1243,7 +1243,7 @@ mod tests { #[test] fn only_desired_seats_are_chosen() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); assert_ok!(Elections::submit_candidacy(Origin::signed(4))); assert_ok!(Elections::submit_candidacy(Origin::signed(3))); @@ -1264,7 +1264,7 @@ mod tests { #[test] fn phragmen_should_not_self_vote() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); assert_ok!(Elections::submit_candidacy(Origin::signed(4))); @@ -1279,7 +1279,7 @@ mod tests { #[test] fn runners_up_should_be_kept() { - with_externalities(&mut ExtBuilder::default().desired_runners_up(2).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().desired_runners_up(2).build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); assert_ok!(Elections::submit_candidacy(Origin::signed(4))); assert_ok!(Elections::submit_candidacy(Origin::signed(3))); @@ -1306,7 +1306,7 @@ mod tests { #[test] fn runners_up_should_be_next_candidates() { - with_externalities(&mut ExtBuilder::default().desired_runners_up(2).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().desired_runners_up(2).build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); assert_ok!(Elections::submit_candidacy(Origin::signed(4))); assert_ok!(Elections::submit_candidacy(Origin::signed(3))); @@ -1333,7 +1333,7 @@ mod tests { #[test] fn runners_up_lose_bond_once_outgoing() { - with_externalities(&mut ExtBuilder::default().desired_runners_up(1).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().desired_runners_up(1).build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); assert_ok!(Elections::submit_candidacy(Origin::signed(4))); assert_ok!(Elections::submit_candidacy(Origin::signed(2))); @@ -1364,7 +1364,7 @@ mod tests { #[test] fn current_members_are_always_implicitly_next_candidate() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); assert_ok!(Elections::submit_candidacy(Origin::signed(4))); @@ -1400,7 +1400,7 @@ mod tests { fn election_state_is_uninterrupted() { // what I mean by uninterrupted: // given no input or stimulants the same members are re-elected. - with_externalities(&mut ExtBuilder::default().desired_runners_up(2).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().desired_runners_up(2).build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); assert_ok!(Elections::submit_candidacy(Origin::signed(4))); assert_ok!(Elections::submit_candidacy(Origin::signed(3))); @@ -1433,7 +1433,7 @@ mod tests { #[test] fn remove_members_triggers_election() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); assert_ok!(Elections::submit_candidacy(Origin::signed(4))); @@ -1459,7 +1459,7 @@ mod tests { #[test] fn seats_should_be_released_when_no_vote() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); assert_ok!(Elections::submit_candidacy(Origin::signed(4))); assert_ok!(Elections::submit_candidacy(Origin::signed(3))); @@ -1493,7 +1493,7 @@ mod tests { #[test] fn outgoing_will_get_the_bond_back() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_eq!(balances(&5), (50, 0)); assert_ok!(Elections::submit_candidacy(Origin::signed(5))); @@ -1519,7 +1519,7 @@ mod tests { #[test] fn losers_will_lose_the_bond() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5))); assert_ok!(Elections::submit_candidacy(Origin::signed(3))); @@ -1542,7 +1542,7 @@ mod tests { #[test] fn incoming_outgoing_are_reported() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(4))); assert_ok!(Elections::submit_candidacy(Origin::signed(5))); @@ -1587,7 +1587,7 @@ mod tests { #[test] fn invalid_votes_are_moot() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(4))); assert_ok!(Elections::submit_candidacy(Origin::signed(3))); diff --git a/substrate/srml/elections/src/mock.rs b/substrate/srml/elections/src/mock.rs index 161da35e6a..b9e548e1ed 100644 --- a/substrate/srml/elections/src/mock.rs +++ b/substrate/srml/elections/src/mock.rs @@ -23,11 +23,9 @@ use support::{ StorageValue, StorageMap, parameter_types, assert_ok, traits::{Get, ChangeMembers, Currency} }; -use runtime_io::with_externalities; -use primitives::{H256, Blake2Hasher}; +use primitives::H256; use sr_primitives::{ - Perbill, BuildStorage, - testing::Header, + Perbill, BuildStorage, set_and_run_with_externalities, testing::Header, traits::{BlakeTwo256, IdentityLookup, Block as BlockT}, }; use crate as elections; @@ -213,7 +211,7 @@ impl ExtBuilder { self.desired_seats = seats; self } - pub fn build(self) -> runtime_io::TestExternalities { + pub fn build(self) -> runtime_io::TestExternalities { VOTER_BOND.with(|v| *v.borrow_mut() = self.voter_bond); VOTING_FEE.with(|v| *v.borrow_mut() = self.voting_fee); PRESENT_SLASH_PER_VOTER.with(|v| *v.borrow_mut() = self.bad_presentation_punishment); @@ -283,9 +281,9 @@ pub(crate) fn locks(who: &u64) -> Vec { Balances::locks(who).iter().map(|l| l.amount).collect::>() } -pub(crate) fn new_test_ext_with_candidate_holes() -> runtime_io::TestExternalities { +pub(crate) fn new_test_ext_with_candidate_holes() -> runtime_io::TestExternalities { let mut t = ExtBuilder::default().build(); - with_externalities(&mut t, || { + set_and_run_with_externalities(&mut t, || { >::put(vec![0, 0, 1]); elections::CandidateCount::put(1); >::insert(1, (0, 2)); diff --git a/substrate/srml/elections/src/tests.rs b/substrate/srml/elections/src/tests.rs index c6f4f9a0b3..149e534a2f 100644 --- a/substrate/srml/elections/src/tests.rs +++ b/substrate/srml/elections/src/tests.rs @@ -22,11 +22,11 @@ use crate::mock::*; use crate::*; use support::{assert_ok, assert_err, assert_noop}; -use runtime_io::with_externalities; +use sr_primitives::set_and_run_with_externalities; #[test] fn params_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(1); assert_eq!(Elections::next_vote_from(1), 4); assert_eq!(Elections::next_vote_from(4), 4); @@ -53,7 +53,7 @@ fn params_should_work() { #[test] fn chunking_bool_to_flag_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_eq!(Elections::bool_to_flag(vec![]), vec![]); assert_eq!(Elections::bool_to_flag(vec![false]), vec![0]); assert_eq!(Elections::bool_to_flag(vec![true]), vec![1]); @@ -98,7 +98,7 @@ fn chunking_bool_to_flag_should_work() { #[test] fn chunking_voter_set_growth_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0)); // create 65. 64 (set0) + 1 (set1) @@ -122,7 +122,7 @@ fn chunking_voter_set_growth_should_work() { #[test] fn chunking_voter_set_reclaim_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0)); (1..=129).for_each(|i| vote(i, 0)); @@ -159,7 +159,7 @@ fn chunking_voter_set_reclaim_should_work() { #[test] fn chunking_approvals_set_growth_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { // create candidates and voters. (1..=250).for_each(|i| create_candidate(i, (i-1) as u32)); (1..=250).for_each(|i| vote(i, i as usize)); @@ -221,7 +221,7 @@ fn chunking_approvals_set_growth_should_work() { #[test] fn chunking_cell_status_works() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0)); (1..=63).for_each(|i| vote(i, 0)); @@ -240,7 +240,7 @@ fn chunking_cell_status_works() { #[test] fn chunking_voter_index_does_not_take_holes_into_account() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0)); // create 65. 64 (set0) + 1 (set1) @@ -265,7 +265,7 @@ fn chunking_voter_index_does_not_take_holes_into_account() { #[test] fn chunking_approval_storage_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0)); assert_ok!(Elections::submit_candidacy(Origin::signed(3), 1)); @@ -285,7 +285,7 @@ fn chunking_approval_storage_should_work() { #[test] fn voting_initial_set_approvals_ignores_voter_index() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0)); // Last argument is essentially irrelevant. You might get or miss a tip. @@ -299,7 +299,7 @@ fn voting_initial_set_approvals_ignores_voter_index() { } #[test] fn voting_bad_approval_index_slashes_voters_and_bond_reduces_stake() { - with_externalities(&mut ExtBuilder::default().voting_fee(5).voter_bond(2).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().voting_fee(5).voter_bond(2).build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0)); (1..=63).for_each(|i| vote(i, 0)); @@ -329,7 +329,7 @@ fn voting_bad_approval_index_slashes_voters_and_bond_reduces_stake() { #[test] fn voting_subsequent_set_approvals_checks_voter_index() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0)); assert_ok!(Elections::set_approvals(Origin::signed(3), vec![], 0, 0, 30)); @@ -353,7 +353,7 @@ fn voting_subsequent_set_approvals_checks_voter_index() { #[test] fn voting_cannot_lock_less_than_limit() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0)); assert_noop!( @@ -366,7 +366,7 @@ fn voting_cannot_lock_less_than_limit() { #[test] fn voting_locking_more_than_total_balance_is_moot() { - with_externalities(&mut ExtBuilder::default().voter_bond(2).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().voter_bond(2).build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0)); assert_eq!(balances(&3), (30, 0)); @@ -382,7 +382,7 @@ fn voting_locking_more_than_total_balance_is_moot() { #[test] fn voting_locking_stake_and_reserving_bond_works() { - with_externalities(&mut ExtBuilder::default().voter_bond(2).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().voter_bond(2).build(), || { assert_ok!(Elections::submit_candidacy(Origin::signed(5), 0)); assert_eq!(balances(&2), (20, 0)); @@ -408,7 +408,7 @@ fn voting_locking_stake_and_reserving_bond_works() { #[test] fn voting_without_any_candidate_count_should_not_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(1); assert_eq!(Elections::candidates().len(), 0); @@ -422,7 +422,7 @@ fn voting_without_any_candidate_count_should_not_work() { #[test] fn voting_setting_an_approval_vote_count_more_than_candidate_count_should_not_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(1); assert_ok!(Elections::submit_candidacy(Origin::signed(5), 0)); @@ -437,7 +437,7 @@ fn voting_setting_an_approval_vote_count_more_than_candidate_count_should_not_wo #[test] fn voting_resubmitting_approvals_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(1); assert_ok!(Elections::submit_candidacy(Origin::signed(5), 0)); @@ -456,7 +456,7 @@ fn voting_resubmitting_approvals_should_work() { #[test] fn voting_retracting_voter_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(1); assert_ok!(Elections::submit_candidacy(Origin::signed(5), 0)); @@ -501,7 +501,7 @@ fn voting_retracting_voter_should_work() { #[test] fn voting_invalid_retraction_index_should_not_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(1); assert_ok!(Elections::submit_candidacy(Origin::signed(3), 0)); @@ -514,7 +514,7 @@ fn voting_invalid_retraction_index_should_not_work() { #[test] fn voting_overflow_retraction_index_should_not_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(1); assert_ok!(Elections::submit_candidacy(Origin::signed(3), 0)); @@ -525,7 +525,7 @@ fn voting_overflow_retraction_index_should_not_work() { #[test] fn voting_non_voter_retraction_should_not_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(1); assert_ok!(Elections::submit_candidacy(Origin::signed(3), 0)); @@ -536,7 +536,7 @@ fn voting_non_voter_retraction_should_not_work() { #[test] fn retracting_inactive_voter_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(4); assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0)); assert_ok!(Elections::set_approvals(Origin::signed(2), vec![true], 0, 0, 20)); @@ -570,7 +570,7 @@ fn retracting_inactive_voter_should_work() { #[test] fn retracting_inactive_voter_with_other_candidates_in_slots_should_work() { - with_externalities(&mut ExtBuilder::default().voter_bond(2).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().voter_bond(2).build(), || { System::set_block_number(4); assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0)); assert_ok!(Elections::set_approvals(Origin::signed(2), vec![true], 0, 0, 20)); @@ -605,7 +605,7 @@ fn retracting_inactive_voter_with_other_candidates_in_slots_should_work() { #[test] fn retracting_inactive_voter_with_bad_reporter_index_should_not_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(4); assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0)); assert_ok!(Elections::set_approvals(Origin::signed(2), vec![true], 0, 0, 20)); @@ -634,7 +634,7 @@ fn retracting_inactive_voter_with_bad_reporter_index_should_not_work() { #[test] fn retracting_inactive_voter_with_bad_target_index_should_not_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(4); assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0)); assert_ok!(Elections::set_approvals(Origin::signed(2), vec![true], 0, 0, 20)); @@ -663,7 +663,7 @@ fn retracting_inactive_voter_with_bad_target_index_should_not_work() { #[test] fn retracting_active_voter_should_slash_reporter() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(4); assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0)); assert_ok!(Elections::submit_candidacy(Origin::signed(3), 1)); @@ -711,7 +711,7 @@ fn retracting_active_voter_should_slash_reporter() { #[test] fn retracting_inactive_voter_by_nonvoter_should_not_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(4); assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0)); assert_ok!(Elections::set_approvals(Origin::signed(2), vec![true], 0, 0, 20)); @@ -740,7 +740,7 @@ fn retracting_inactive_voter_by_nonvoter_should_not_work() { #[test] fn candidacy_simple_candidate_submission_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(1); assert_eq!(Elections::candidates(), Vec::::new()); assert_eq!(Elections::candidate_reg_info(1), None); @@ -768,7 +768,7 @@ fn candidacy_simple_candidate_submission_should_work() { fn candidacy_submission_using_free_slot_should_work() { let mut t = new_test_ext_with_candidate_holes(); - with_externalities(&mut t, || { + set_and_run_with_externalities(&mut t, || { System::set_block_number(1); assert_eq!(Elections::candidates(), vec![0, 0, 1]); @@ -784,7 +784,7 @@ fn candidacy_submission_using_free_slot_should_work() { fn candidacy_submission_using_alternative_free_slot_should_work() { let mut t = new_test_ext_with_candidate_holes(); - with_externalities(&mut t, || { + set_and_run_with_externalities(&mut t, || { System::set_block_number(1); assert_eq!(Elections::candidates(), vec![0, 0, 1]); @@ -800,7 +800,7 @@ fn candidacy_submission_using_alternative_free_slot_should_work() { fn candidacy_submission_not_using_free_slot_should_not_work() { let mut t = new_test_ext_with_candidate_holes(); - with_externalities(&mut t, || { + set_and_run_with_externalities(&mut t, || { System::set_block_number(1); assert_noop!( Elections::submit_candidacy(Origin::signed(4), 3), @@ -811,7 +811,7 @@ fn candidacy_submission_not_using_free_slot_should_not_work() { #[test] fn candidacy_bad_candidate_slot_submission_should_not_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(1); assert_eq!(Elections::candidates(), Vec::::new()); assert_noop!( @@ -823,7 +823,7 @@ fn candidacy_bad_candidate_slot_submission_should_not_work() { #[test] fn candidacy_non_free_candidate_slot_submission_should_not_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(1); assert_eq!(Elections::candidates(), Vec::::new()); assert_ok!(Elections::submit_candidacy(Origin::signed(1), 0)); @@ -837,7 +837,7 @@ fn candidacy_non_free_candidate_slot_submission_should_not_work() { #[test] fn candidacy_dupe_candidate_submission_should_not_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(1); assert_eq!(Elections::candidates(), Vec::::new()); assert_ok!(Elections::submit_candidacy(Origin::signed(1), 0)); @@ -851,7 +851,7 @@ fn candidacy_dupe_candidate_submission_should_not_work() { #[test] fn candidacy_poor_candidate_submission_should_not_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(1); assert_eq!(Elections::candidates(), Vec::::new()); assert_noop!( @@ -863,7 +863,7 @@ fn candidacy_poor_candidate_submission_should_not_work() { #[test] fn election_voting_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(1); assert_ok!(Elections::submit_candidacy(Origin::signed(5), 0)); @@ -892,7 +892,7 @@ fn election_voting_should_work() { #[test] fn election_proxy_voting_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(1); assert_ok!(Elections::submit_candidacy(Origin::signed(5), 0)); @@ -933,7 +933,7 @@ fn election_proxy_voting_should_work() { #[test] fn election_simple_tally_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(4); assert!(!Elections::presentation_active()); @@ -972,7 +972,7 @@ fn election_simple_tally_should_work() { #[test] fn election_seats_should_be_released() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(4); assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0)); assert_ok!(Elections::submit_candidacy(Origin::signed(5), 1)); @@ -1006,7 +1006,7 @@ fn election_seats_should_be_released() { #[test] fn election_presentations_with_zero_staked_deposit_should_not_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(4); assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0)); assert_ok!(Elections::set_approvals(Origin::signed(2), vec![true], 0, 0, 20)); @@ -1022,7 +1022,7 @@ fn election_presentations_with_zero_staked_deposit_should_not_work() { #[test] fn election_double_presentations_should_be_punished() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert!(Balances::can_slash(&4, 10)); System::set_block_number(4); @@ -1045,7 +1045,7 @@ fn election_double_presentations_should_be_punished() { #[test] fn election_presenting_for_double_election_should_not_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(4); assert_eq!(Elections::submit_candidacy(Origin::signed(2), 0), Ok(())); assert_ok!(Elections::set_approvals(Origin::signed(2), vec![true], 0, 0, 20)); @@ -1072,7 +1072,7 @@ fn election_presenting_for_double_election_should_not_work() { #[test] fn election_presenting_loser_should_not_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(4); assert_ok!(Elections::submit_candidacy(Origin::signed(1), 0)); assert_ok!(Elections::set_approvals(Origin::signed(6), vec![true], 0, 0, 60)); @@ -1105,7 +1105,7 @@ fn election_presenting_loser_should_not_work() { #[test] fn election_presenting_loser_first_should_not_matter() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(4); assert_ok!(Elections::submit_candidacy(Origin::signed(1), 0)); assert_ok!(Elections::set_approvals(Origin::signed(6), vec![true], 0, 0, 60)); @@ -1137,7 +1137,7 @@ fn election_presenting_loser_first_should_not_matter() { #[test] fn election_present_outside_of_presentation_period_should_not_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(4); assert!(!Elections::presentation_active()); assert_noop!( @@ -1149,7 +1149,7 @@ fn election_present_outside_of_presentation_period_should_not_work() { #[test] fn election_present_with_invalid_vote_index_should_not_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(4); assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0)); assert_ok!(Elections::submit_candidacy(Origin::signed(5), 1)); @@ -1165,7 +1165,7 @@ fn election_present_with_invalid_vote_index_should_not_work() { #[test] fn election_present_when_presenter_is_poor_should_not_work() { let test_present = |p| { - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .voting_fee(5) .voter_bond(2) .bad_presentation_punishment(p) @@ -1199,7 +1199,7 @@ fn election_present_when_presenter_is_poor_should_not_work() { #[test] fn election_invalid_present_tally_should_slash() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(4); assert!(!Elections::presentation_active()); assert_eq!(Balances::total_balance(&4), 40); @@ -1219,7 +1219,7 @@ fn election_invalid_present_tally_should_slash() { #[test] fn election_runners_up_should_be_kept() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(4); assert!(!Elections::presentation_active()); @@ -1280,7 +1280,7 @@ fn election_runners_up_should_be_kept() { #[test] fn election_second_tally_should_use_runners_up() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { System::set_block_number(4); assert_ok!(Elections::submit_candidacy(Origin::signed(1), 0)); assert_ok!(Elections::set_approvals(Origin::signed(6), vec![true], 0, 0, 60)); @@ -1335,7 +1335,7 @@ fn election_second_tally_should_use_runners_up() { #[test] fn election_loser_candidates_bond_gets_slashed() { - with_externalities(&mut ExtBuilder::default().desired_seats(1).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().desired_seats(1).build(), || { System::set_block_number(4); assert!(!Elections::presentation_active()); @@ -1374,7 +1374,7 @@ fn election_loser_candidates_bond_gets_slashed() { #[test] fn pot_accumulating_weight_and_decaying_should_work() { - with_externalities(&mut ExtBuilder::default().balance_factor(10).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().balance_factor(10).build(), || { System::set_block_number(4); assert!(!Elections::presentation_active()); @@ -1502,7 +1502,7 @@ fn pot_accumulating_weight_and_decaying_should_work() { #[test] fn pot_winning_resets_accumulated_pot() { - with_externalities(&mut ExtBuilder::default().balance_factor(10).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().balance_factor(10).build(), || { System::set_block_number(4); assert!(!Elections::presentation_active()); @@ -1564,7 +1564,7 @@ fn pot_winning_resets_accumulated_pot() { #[test] fn pot_resubmitting_approvals_stores_pot() { - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .voter_bond(0) .voting_fee(0) .balance_factor(10) @@ -1629,7 +1629,7 @@ fn pot_resubmitting_approvals_stores_pot() { #[test] fn pot_get_offset_should_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_eq!(Elections::get_offset(100, 0), 0); assert_eq!(Elections::get_offset(100, 1), 96); assert_eq!(Elections::get_offset(100, 2), 96 + 93); @@ -1653,7 +1653,7 @@ fn pot_get_offset_should_work() { #[test] fn pot_get_offset_with_zero_decay() { - with_externalities(&mut ExtBuilder::default().decay_ratio(0).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().decay_ratio(0).build(), || { assert_eq!(Elections::get_offset(100, 0), 0); assert_eq!(Elections::get_offset(100, 1), 0); assert_eq!(Elections::get_offset(100, 2), 0); diff --git a/substrate/srml/example/src/lib.rs b/substrate/srml/example/src/lib.rs index ef8eead7ba..08adf9efa7 100644 --- a/substrate/srml/example/src/lib.rs +++ b/substrate/srml/example/src/lib.rs @@ -634,15 +634,12 @@ mod tests { use super::*; use support::{assert_ok, impl_outer_origin, parameter_types}; - use runtime_io::with_externalities; - use primitives::{H256, Blake2Hasher}; + use primitives::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 sr_primitives::{ - Perbill, + set_and_run_with_externalities, Perbill, weights::GetDispatchInfo, testing::Header, traits::{BlakeTwo256, OnInitialize, OnFinalize, IdentityLookup}, - weights::GetDispatchInfo, - testing::Header }; impl_outer_origin! { @@ -707,7 +704,7 @@ mod tests { // This function basically just builds a genesis storage key/value store according to // our desired mockup. - fn new_test_ext() -> runtime_io::TestExternalities { + fn new_test_ext() -> runtime_io::TestExternalities { let mut t = 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(); @@ -722,7 +719,7 @@ mod tests { #[test] fn it_works_for_optional_value() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // Check that GenesisBuilder works properly. assert_eq!(Example::dummy(), Some(42)); @@ -743,7 +740,7 @@ mod tests { #[test] fn it_works_for_default_value() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_eq!(Example::foo(), 24); assert_ok!(Example::accumulate_foo(Origin::signed(1), 1)); assert_eq!(Example::foo(), 25); @@ -752,7 +749,7 @@ mod tests { #[test] fn signed_ext_watch_dummy_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { let call = >::set_dummy(10); let info = DispatchInfo::default(); diff --git a/substrate/srml/executive/src/lib.rs b/substrate/srml/executive/src/lib.rs index ee11ffadf4..f1509f1760 100644 --- a/substrate/srml/executive/src/lib.rs +++ b/substrate/srml/executive/src/lib.rs @@ -293,12 +293,12 @@ where #[cfg(test)] mod tests { use super::*; - use runtime_io::with_externalities; - use primitives::{H256, Blake2Hasher}; + use primitives::H256; use sr_primitives::{ generic::Era, Perbill, DispatchError, weights::Weight, testing::{Digest, Header, Block}, traits::{Bounded, Header as HeaderT, BlakeTwo256, IdentityLookup, ConvertInto}, transaction_validity::{InvalidTransaction, UnknownTransaction}, ApplyError, + set_and_run_with_externalities, }; use support::{ impl_outer_event, impl_outer_origin, parameter_types, impl_outer_dispatch, @@ -419,8 +419,8 @@ mod tests { }.assimilate_storage(&mut t).unwrap(); let xt = sr_primitives::testing::TestXt(sign_extra(1, 0, 0), Call::Balances(BalancesCall::transfer(2, 69))); let weight = xt.get_dispatch_info().weight as u64; - let mut t = runtime_io::TestExternalities::::new(t); - with_externalities(&mut t, || { + let mut t = runtime_io::TestExternalities::new(t); + set_and_run_with_externalities(&mut t, || { Executive::initialize_block(&Header::new( 1, H256::default(), @@ -435,7 +435,7 @@ mod tests { }); } - fn new_test_ext(balance_factor: u64) -> runtime_io::TestExternalities { + fn new_test_ext(balance_factor: u64) -> runtime_io::TestExternalities { let mut t = system::GenesisConfig::default().build_storage::().unwrap(); balances::GenesisConfig:: { balances: vec![(1, 111 * balance_factor)], @@ -446,7 +446,7 @@ mod tests { #[test] fn block_import_works() { - with_externalities(&mut new_test_ext(1), || { + set_and_run_with_externalities(&mut new_test_ext(1), || { Executive::execute_block(Block { header: Header { parent_hash: [69u8; 32].into(), @@ -463,7 +463,7 @@ mod tests { #[test] #[should_panic] fn block_import_of_bad_state_root_fails() { - with_externalities(&mut new_test_ext(1), || { + set_and_run_with_externalities(&mut new_test_ext(1), || { Executive::execute_block(Block { header: Header { parent_hash: [69u8; 32].into(), @@ -480,7 +480,7 @@ mod tests { #[test] #[should_panic] fn block_import_of_bad_extrinsic_root_fails() { - with_externalities(&mut new_test_ext(1), || { + set_and_run_with_externalities(&mut new_test_ext(1), || { Executive::execute_block(Block { header: Header { parent_hash: [69u8; 32].into(), @@ -499,7 +499,7 @@ mod tests { let mut t = new_test_ext(1); // bad nonce check! let xt = sr_primitives::testing::TestXt(sign_extra(1, 30, 0), Call::Balances(BalancesCall::transfer(33, 69))); - with_externalities(&mut t, || { + set_and_run_with_externalities(&mut t, || { Executive::initialize_block(&Header::new( 1, H256::default(), @@ -521,7 +521,7 @@ mod tests { let encoded_len = encoded.len() as Weight; let limit = AvailableBlockRatio::get() * MaximumBlockWeight::get(); let num_to_exhaust_block = limit / encoded_len; - with_externalities(&mut t, || { + set_and_run_with_externalities(&mut t, || { Executive::initialize_block(&Header::new( 1, H256::default(), @@ -557,7 +557,7 @@ mod tests { let x2 = sr_primitives::testing::TestXt(sign_extra(1, 2, 0), Call::Balances(BalancesCall::transfer(33, 0))); let len = xt.clone().encode().len() as u32; let mut t = new_test_ext(1); - with_externalities(&mut t, || { + set_and_run_with_externalities(&mut t, || { assert_eq!(>::all_extrinsics_weight(), 0); assert_eq!(>::all_extrinsics_weight(), 0); @@ -581,7 +581,7 @@ mod tests { let xt = sr_primitives::testing::TestXt(None, Call::Balances(BalancesCall::set_balance(33, 69, 69))); let mut t = new_test_ext(1); - with_externalities(&mut t, || { + set_and_run_with_externalities(&mut t, || { assert_eq!(Executive::validate_transaction(xt.clone()), Ok(Default::default())); assert_eq!( Executive::apply_extrinsic(xt), @@ -599,7 +599,7 @@ mod tests { let id: LockIdentifier = *b"0 "; let execute_with_lock = |lock: WithdrawReasons| { let mut t = new_test_ext(1); - with_externalities(&mut t, || { + set_and_run_with_externalities(&mut t, || { as LockableCurrency>::set_lock( id, &1, diff --git a/substrate/srml/finality-tracker/src/lib.rs b/substrate/srml/finality-tracker/src/lib.rs index 1bf9754b0a..f00762fcdf 100644 --- a/substrate/srml/finality-tracker/src/lib.rs +++ b/substrate/srml/finality-tracker/src/lib.rs @@ -247,11 +247,12 @@ impl ProvideInherent for Module { mod tests { use super::*; - use runtime_io::{with_externalities, TestExternalities}; + use runtime_io::TestExternalities; use primitives::H256; - use sr_primitives::traits::{BlakeTwo256, IdentityLookup, OnFinalize, Header as HeaderT}; - use sr_primitives::testing::Header; - use sr_primitives::Perbill; + use sr_primitives::{ + set_and_run_with_externalities, testing::Header, Perbill, + traits::{BlakeTwo256, IdentityLookup, OnFinalize, Header as HeaderT}, + }; use support::{assert_ok, impl_outer_origin, parameter_types}; use srml_system as system; use std::cell::RefCell; @@ -321,7 +322,7 @@ mod tests { #[test] fn median_works() { let t = system::GenesisConfig::default().build_storage::().unwrap(); - with_externalities(&mut TestExternalities::new(t), || { + set_and_run_with_externalities(&mut TestExternalities::new(t), || { FinalityTracker::update_hint(Some(500)); assert_eq!(FinalityTracker::median(), 250); assert!(NOTIFICATIONS.with(|n| n.borrow().is_empty())); @@ -331,7 +332,7 @@ mod tests { #[test] fn notifies_when_stalled() { let t = system::GenesisConfig::default().build_storage::().unwrap(); - with_externalities(&mut TestExternalities::new(t), || { + set_and_run_with_externalities(&mut TestExternalities::new(t), || { let mut parent_hash = System::parent_hash(); for i in 2..106 { System::initialize(&i, &parent_hash, &Default::default(), &Default::default()); @@ -350,7 +351,7 @@ mod tests { #[test] fn recent_notifications_prevent_stalling() { let t = system::GenesisConfig::default().build_storage::().unwrap(); - with_externalities(&mut TestExternalities::new(t), || { + set_and_run_with_externalities(&mut TestExternalities::new(t), || { let mut parent_hash = System::parent_hash(); for i in 2..106 { System::initialize(&i, &parent_hash, &Default::default(), &Default::default()); diff --git a/substrate/srml/generic-asset/src/mock.rs b/substrate/srml/generic-asset/src/mock.rs index 7e47de0b36..c0f9f154b8 100644 --- a/substrate/srml/generic-asset/src/mock.rs +++ b/substrate/srml/generic-asset/src/mock.rs @@ -25,7 +25,7 @@ use sr_primitives::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, }; -use primitives::{Blake2Hasher, H256}; +use primitives::H256; use support::{parameter_types, impl_outer_event, impl_outer_origin}; use super::*; @@ -118,7 +118,7 @@ impl ExtBuilder { } // builds genesis config - pub fn build(self) -> runtime_io::TestExternalities { + pub fn build(self) -> runtime_io::TestExternalities { let mut t = system::GenesisConfig::default().build_storage::().unwrap(); GenesisConfig:: { @@ -137,7 +137,7 @@ impl ExtBuilder { // This function basically just builds a genesis storage key/value store according to // our desired mockup. -pub fn new_test_ext() -> runtime_io::TestExternalities { +pub fn new_test_ext() -> runtime_io::TestExternalities { system::GenesisConfig::default() .build_storage::() .unwrap() diff --git a/substrate/srml/generic-asset/src/tests.rs b/substrate/srml/generic-asset/src/tests.rs index 685e553c1c..90e5775828 100644 --- a/substrate/srml/generic-asset/src/tests.rs +++ b/substrate/srml/generic-asset/src/tests.rs @@ -22,14 +22,14 @@ use super::*; use crate::mock::{new_test_ext, ExtBuilder, GenericAsset, Origin, System, Test, TestEvent}; -use runtime_io::with_externalities; +use sr_primitives::set_and_run_with_externalities; use support::{assert_noop, assert_ok}; #[test] fn issuing_asset_units_to_issuer_should_work() { let balance = 100; - with_externalities(&mut ExtBuilder::default().free_balance((16000, 1, 100)).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().free_balance((16000, 1, 100)).build(), || { let default_permission = PermissionLatest { update: Owner::Address(1), mint: Owner::Address(1), @@ -51,7 +51,7 @@ fn issuing_asset_units_to_issuer_should_work() { #[test] fn issuing_with_next_asset_id_overflow_should_not_work() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().free_balance((16000, 1, 100000)).build(), || { NextAssetId::::put(u32::max_value()); @@ -79,7 +79,7 @@ fn issuing_with_next_asset_id_overflow_should_not_work() { fn querying_total_supply_should_work() { let asset_id = 1000; - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().free_balance((16000, 1, 100000)).build(), || { let default_permission = PermissionLatest { @@ -127,7 +127,7 @@ fn querying_total_supply_should_work() { fn transferring_amount_should_work() { let asset_id = 1000; let free_balance = 100; - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().free_balance((16000, 1, 100000)).build(), || { let default_permission = PermissionLatest { @@ -168,7 +168,7 @@ fn transferring_amount_should_work() { #[test] fn transferring_amount_should_fail_when_transferring_more_than_free_balance() { let asset_id = 1000; - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().free_balance((16000, 1, 100000)).build(), || { let default_permission = PermissionLatest { @@ -195,7 +195,7 @@ fn transferring_amount_should_fail_when_transferring_more_than_free_balance() { fn transferring_less_than_one_unit_should_not_work() { let asset_id = 1000; - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().free_balance((16000, 1, 100000)).build(), || { let default_permission = PermissionLatest { @@ -233,7 +233,7 @@ fn self_transfer_should_fail() { let asset_id = 1000; let balance = 100; - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().free_balance((16000, 1, 100000)).build(), || { let default_permission = PermissionLatest { @@ -259,7 +259,7 @@ fn self_transfer_should_fail() { #[test] fn transferring_more_units_than_total_supply_should_not_work() { let asset_id = 1000; - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().free_balance((16000, 1, 100000)).build(), || { let default_permission = PermissionLatest { @@ -286,7 +286,7 @@ fn transferring_more_units_than_total_supply_should_not_work() { // Ensures it uses fake money for staking asset id. #[test] fn staking_asset_id_should_return_0() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_eq!(GenericAsset::staking_asset_id(), 16000); }); } @@ -294,7 +294,7 @@ fn staking_asset_id_should_return_0() { // Ensures it uses fake money for spending asset id. #[test] fn spending_asset_id_should_return_10() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_eq!(GenericAsset::spending_asset_id(), 16001); }); } @@ -305,7 +305,7 @@ fn spending_asset_id_should_return_10() { // -Â total_balance should return 0 #[test] fn total_balance_should_be_zero() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_eq!(GenericAsset::total_balance(&0, &0), 0); }); } @@ -323,7 +323,7 @@ fn total_balance_should_be_equal_to_account_balance() { mint: Owner::Address(1), burn: Owner::Address(1), }; - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().free_balance((16000, 1, 100000)).build(), || { assert_ok!(GenericAsset::create( @@ -348,7 +348,7 @@ fn total_balance_should_be_equal_to_account_balance() { // -Â free_balance should return 50. #[test] fn free_balance_should_only_return_account_free_balance() { - with_externalities(&mut ExtBuilder::default().free_balance((1, 0, 50)).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().free_balance((1, 0, 50)).build(), || { GenericAsset::set_reserved_balance(&1, &0, 70); assert_eq!(GenericAsset::free_balance(&1, &0), 50); }); @@ -363,7 +363,7 @@ fn free_balance_should_only_return_account_free_balance() { // -Â total_balance should equals to account balance + free balance. #[test] fn total_balance_should_be_equal_to_sum_of_account_balance_and_free_balance() { - with_externalities(&mut ExtBuilder::default().free_balance((1, 0, 50)).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().free_balance((1, 0, 50)).build(), || { GenericAsset::set_reserved_balance(&1, &0, 70); assert_eq!(GenericAsset::total_balance(&1, &0), 120); }); @@ -378,7 +378,7 @@ fn total_balance_should_be_equal_to_sum_of_account_balance_and_free_balance() { // - reserved_balance should return 70. #[test] fn reserved_balance_should_only_return_account_reserved_balance() { - with_externalities(&mut ExtBuilder::default().free_balance((1, 0, 50)).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().free_balance((1, 0, 50)).build(), || { GenericAsset::set_reserved_balance(&1, &0, 70); assert_eq!(GenericAsset::reserved_balance(&1, &0), 70); }); @@ -394,7 +394,7 @@ fn reserved_balance_should_only_return_account_reserved_balance() { // - reserved_balance = amount #[test] fn set_reserved_balance_should_add_balance_as_reserved() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { GenericAsset::set_reserved_balance(&1, &0, 50); assert_eq!(GenericAsset::reserved_balance(&1, &0), 50); }); @@ -410,7 +410,7 @@ fn set_reserved_balance_should_add_balance_as_reserved() { // - New free_balance should replace older free_balance. #[test] fn set_free_balance_should_add_amount_as_free_balance() { - with_externalities(&mut ExtBuilder::default().free_balance((1, 0, 100)).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().free_balance((1, 0, 100)).build(), || { GenericAsset::set_free_balance(&1, &0, 50); assert_eq!(GenericAsset::free_balance(&1, &0), 50); }); @@ -429,7 +429,7 @@ fn set_free_balance_should_add_amount_as_free_balance() { // - new reserved_balance = original free balance + reserved amount #[test] fn reserve_should_moves_amount_from_balance_to_reserved_balance() { - with_externalities(&mut ExtBuilder::default().free_balance((1, 0, 100)).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().free_balance((1, 0, 100)).build(), || { assert_ok!(GenericAsset::reserve(&1, &0, 70)); assert_eq!(GenericAsset::free_balance(&1, &0), 30); assert_eq!(GenericAsset::reserved_balance(&1, &0), 70); @@ -448,7 +448,7 @@ fn reserve_should_moves_amount_from_balance_to_reserved_balance() { // - Should throw an error. #[test] fn reserve_should_not_moves_amount_from_balance_to_reserved_balance() { - with_externalities(&mut ExtBuilder::default().free_balance((1, 0, 100)).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().free_balance((1, 0, 100)).build(), || { assert_noop!(GenericAsset::reserve(&1, &0, 120), "not enough free funds"); assert_eq!(GenericAsset::free_balance(&1, &0), 100); assert_eq!(GenericAsset::reserved_balance(&1, &0), 0); @@ -466,7 +466,7 @@ fn reserve_should_not_moves_amount_from_balance_to_reserved_balance() { // - unreserved should return 20. #[test] fn unreserve_should_return_substratced_value_from_unreserved_amount_by_actual_acount_balance() { - with_externalities(&mut ExtBuilder::default().free_balance((1, 0, 100)).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().free_balance((1, 0, 100)).build(), || { GenericAsset::set_reserved_balance(&1, &0, 100); assert_eq!(GenericAsset::unreserve(&1, &0, 120), 20); }); @@ -483,7 +483,7 @@ fn unreserve_should_return_substratced_value_from_unreserved_amount_by_actual_ac // - unreserved should return None. #[test] fn unreserve_should_return_none() { - with_externalities(&mut ExtBuilder::default().free_balance((1, 0, 100)).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().free_balance((1, 0, 100)).build(), || { GenericAsset::set_reserved_balance(&1, &0, 100); assert_eq!(GenericAsset::unreserve(&1, &0, 50), 0); }); @@ -500,7 +500,7 @@ fn unreserve_should_return_none() { // - free_balance should be 200. #[test] fn unreserve_should_increase_free_balance_by_reserved_balance() { - with_externalities(&mut ExtBuilder::default().free_balance((1, 0, 100)).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().free_balance((1, 0, 100)).build(), || { GenericAsset::set_reserved_balance(&1, &0, 100); GenericAsset::unreserve(&1, &0, 120); assert_eq!(GenericAsset::free_balance(&1, &0), 200); @@ -518,7 +518,7 @@ fn unreserve_should_increase_free_balance_by_reserved_balance() { // - reserved_balance should be 0. #[test] fn unreserve_should_deduct_reserved_balance_by_reserved_amount() { - with_externalities(&mut ExtBuilder::default().free_balance((1, 0, 100)).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().free_balance((1, 0, 100)).build(), || { GenericAsset::set_free_balance(&1, &0, 100); GenericAsset::unreserve(&1, &0, 120); assert_eq!(GenericAsset::reserved_balance(&1, &0), 0); @@ -536,7 +536,7 @@ fn unreserve_should_deduct_reserved_balance_by_reserved_amount() { // - slash should return None. #[test] fn slash_should_return_slash_reserved_amount() { - with_externalities(&mut ExtBuilder::default().free_balance((1, 0, 100)).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().free_balance((1, 0, 100)).build(), || { GenericAsset::set_reserved_balance(&1, &0, 100); assert_eq!(GenericAsset::slash(&1, &0, 70), None); }); @@ -550,7 +550,7 @@ fn slash_should_return_slash_reserved_amount() { // - Should return slashed_reserved - reserved_balance. #[test] fn slash_reserved_should_deducts_up_to_amount_from_reserved_balance() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { GenericAsset::set_reserved_balance(&1, &0, 100); assert_eq!(GenericAsset::slash_reserved(&1, &0, 150), Some(50)); }); @@ -564,7 +564,7 @@ fn slash_reserved_should_deducts_up_to_amount_from_reserved_balance() { // - Should return None. #[test] fn slash_reserved_should_return_none() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { GenericAsset::set_reserved_balance(&1, &0, 100); assert_eq!(GenericAsset::slash_reserved(&1, &0, 100), None); }); @@ -579,7 +579,7 @@ fn slash_reserved_should_return_none() { // - Should not return None. #[test] fn repatriate_reserved_return_amount_substracted_by_slash_amount() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { GenericAsset::set_reserved_balance(&1, &0, 100); assert_eq!(GenericAsset::repatriate_reserved(&1, &0, &1, 130), 30); }); @@ -594,7 +594,7 @@ fn repatriate_reserved_return_amount_substracted_by_slash_amount() { // - Should return None. #[test] fn repatriate_reserved_return_none() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { GenericAsset::set_reserved_balance(&1, &0, 100); assert_eq!(GenericAsset::repatriate_reserved(&1, &0, &1, 90), 0); }); @@ -608,7 +608,7 @@ fn repatriate_reserved_return_none() { // - Should create a new reserved asset. #[test] fn create_reserved_should_create_a_default_account_with_the_balance_given() { - with_externalities(&mut ExtBuilder::default().next_asset_id(10).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().next_asset_id(10).build(), || { let default_permission = PermissionLatest { update: Owner::Address(1), mint: Owner::Address(1), @@ -643,7 +643,7 @@ fn create_reserved_should_create_a_default_account_with_the_balance_given() { // - Should throw a permission error #[test] fn mint_should_throw_permission_error() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { let origin = 1; let asset_id = 4; let to_account = 2; @@ -666,7 +666,7 @@ fn mint_should_throw_permission_error() { // - Should not change `origins` free_balance. #[test] fn mint_should_increase_asset() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().free_balance((16000, 1, 100000)).build(), || { let origin = 1; @@ -707,7 +707,7 @@ fn mint_should_increase_asset() { // - Should throw a permission error. #[test] fn burn_should_throw_permission_error() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().free_balance((16000, 1, 100000)).build(), || { let origin = 1; @@ -733,7 +733,7 @@ fn burn_should_throw_permission_error() { // - Should not change `origin`'s free_balance. #[test] fn burn_should_burn_an_asset() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().free_balance((16000, 1, 100000)).build(), || { let origin = 1; @@ -779,7 +779,7 @@ fn burn_should_burn_an_asset() { // - The account origin should have burn, mint and update permissions. #[test] fn check_permission_should_return_correct_permission() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().free_balance((16000, 1, 100000)).build(), || { let origin = 1; @@ -825,7 +825,7 @@ fn check_permission_should_return_correct_permission() { // - The account origin should not have burn, mint and update permissions. #[test] fn check_permission_should_return_false_for_no_permission() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().free_balance((16000, 1, 100000)).build(), || { let origin = 1; @@ -871,7 +871,7 @@ fn check_permission_should_return_false_for_no_permission() { // - The account origin should have update and mint permissions. #[test] fn update_permission_should_change_permission() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().free_balance((16000, 1, 100000)).build(), || { let origin = 1; @@ -923,7 +923,7 @@ fn update_permission_should_change_permission() { // - Should throw an error stating "Origin does not have enough permission to update permissions." #[test] fn update_permission_should_throw_error_when_lack_of_permissions() { - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().free_balance((16000, 1, 100000)).build(), || { let origin = 1; @@ -974,7 +974,7 @@ fn update_permission_should_throw_error_when_lack_of_permissions() { // - Permissions must have burn, mint and updatePermission for the given asset_id. #[test] fn create_asset_works_with_given_asset_id_and_from_account() { - with_externalities(&mut ExtBuilder::default().next_asset_id(10).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().next_asset_id(10).build(), || { let origin = 1; let from_account: Option<::AccountId> = Some(1); @@ -1011,7 +1011,7 @@ fn create_asset_works_with_given_asset_id_and_from_account() { // - `create_asset` should not work. #[test] fn create_asset_with_non_reserved_asset_id_should_not_work() { - with_externalities(&mut ExtBuilder::default().next_asset_id(10).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().next_asset_id(10).build(), || { let origin = 1; let from_account: Option<::AccountId> = Some(1); @@ -1045,7 +1045,7 @@ fn create_asset_with_non_reserved_asset_id_should_not_work() { // - `create_asset` should not work. #[test] fn create_asset_with_a_taken_asset_id_should_not_work() { - with_externalities(&mut ExtBuilder::default().next_asset_id(10).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().next_asset_id(10).build(), || { let origin = 1; let from_account: Option<::AccountId> = Some(1); @@ -1090,7 +1090,7 @@ fn create_asset_with_a_taken_asset_id_should_not_work() { // - Should create a reserved token. #[test] fn create_asset_should_create_a_reserved_asset_when_from_account_is_none() { - with_externalities(&mut ExtBuilder::default().next_asset_id(10).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().next_asset_id(10).build(), || { let origin = 1; let from_account: Option<::AccountId> = None; @@ -1133,7 +1133,7 @@ fn create_asset_should_create_a_reserved_asset_when_from_account_is_none() { // - Should not create a `reserved_asset`. #[test] fn create_asset_should_create_a_user_asset() { - with_externalities(&mut ExtBuilder::default().next_asset_id(10).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().next_asset_id(10).build(), || { let origin = 1; let from_account: Option<::AccountId> = None; @@ -1180,7 +1180,7 @@ fn update_permission_should_raise_event() { burn: Owner::Address(origin), }; - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default() .next_asset_id(asset_id) .free_balance((staking_asset_id, origin, initial_balance)) @@ -1223,7 +1223,7 @@ fn mint_should_raise_event() { let to = 2; let amount = 100; - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default() .next_asset_id(asset_id) .free_balance((staking_asset_id, origin, initial_balance)) @@ -1262,7 +1262,7 @@ fn burn_should_raise_event() { }; let amount = 100; - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default() .next_asset_id(asset_id) .free_balance((staking_asset_id, origin, initial_balance)) diff --git a/substrate/srml/grandpa/src/mock.rs b/substrate/srml/grandpa/src/mock.rs index af2fedf42f..8d585e4b46 100644 --- a/substrate/srml/grandpa/src/mock.rs +++ b/substrate/srml/grandpa/src/mock.rs @@ -21,7 +21,7 @@ use sr_primitives::{Perbill, DigestItem, traits::IdentityLookup, testing::{Header, UintAuthorityId}}; use runtime_io; use support::{impl_outer_origin, impl_outer_event, parameter_types}; -use primitives::{H256, Blake2Hasher}; +use primitives::H256; use codec::{Encode, Decode}; use crate::{AuthorityId, GenesisConfig, Trait, Module, ConsensusLog}; use substrate_finality_grandpa_primitives::GRANDPA_ENGINE_ID; @@ -82,7 +82,7 @@ pub fn to_authorities(vec: Vec<(u64, u64)>) -> Vec<(AuthorityId, u64)> { .collect() } -pub fn new_test_ext(authorities: Vec<(u64, u64)>) -> runtime_io::TestExternalities { +pub fn new_test_ext(authorities: Vec<(u64, u64)>) -> runtime_io::TestExternalities { let mut t = system::GenesisConfig::default().build_storage::().unwrap(); GenesisConfig { authorities: to_authorities(authorities), diff --git a/substrate/srml/grandpa/src/tests.rs b/substrate/srml/grandpa/src/tests.rs index 41229a5136..aec75d274c 100644 --- a/substrate/srml/grandpa/src/tests.rs +++ b/substrate/srml/grandpa/src/tests.rs @@ -18,9 +18,7 @@ #![cfg(test)] -use sr_primitives::testing::Digest; -use sr_primitives::traits::{Header, OnFinalize}; -use runtime_io::with_externalities; +use sr_primitives::{set_and_run_with_externalities, testing::Digest, traits::{Header, OnFinalize}}; use crate::mock::*; use system::{EventRecord, Phase}; use codec::{Decode, Encode}; @@ -29,7 +27,7 @@ use super::*; #[test] fn authorities_change_logged() { - with_externalities(&mut new_test_ext(vec![(1, 1), (2, 1), (3, 1)]), || { + set_and_run_with_externalities(&mut new_test_ext(vec![(1, 1), (2, 1), (3, 1)]), || { System::initialize(&1, &Default::default(), &Default::default(), &Default::default()); Grandpa::schedule_change(to_authorities(vec![(4, 1), (5, 1), (6, 1)]), 0, None).unwrap(); @@ -57,7 +55,7 @@ fn authorities_change_logged() { #[test] fn authorities_change_logged_after_delay() { - with_externalities(&mut new_test_ext(vec![(1, 1), (2, 1), (3, 1)]), || { + set_and_run_with_externalities(&mut new_test_ext(vec![(1, 1), (2, 1), (3, 1)]), || { System::initialize(&1, &Default::default(), &Default::default(), &Default::default()); Grandpa::schedule_change(to_authorities(vec![(4, 1), (5, 1), (6, 1)]), 1, None).unwrap(); Grandpa::on_finalize(1); @@ -90,7 +88,7 @@ fn authorities_change_logged_after_delay() { #[test] fn cannot_schedule_change_when_one_pending() { - with_externalities(&mut new_test_ext(vec![(1, 1), (2, 1), (3, 1)]), || { + set_and_run_with_externalities(&mut new_test_ext(vec![(1, 1), (2, 1), (3, 1)]), || { System::initialize(&1, &Default::default(), &Default::default(), &Default::default()); Grandpa::schedule_change(to_authorities(vec![(4, 1), (5, 1), (6, 1)]), 1, None).unwrap(); assert!(>::exists()); @@ -133,7 +131,7 @@ fn new_decodes_from_old() { #[test] fn dispatch_forced_change() { - with_externalities(&mut new_test_ext(vec![(1, 1), (2, 1), (3, 1)]), || { + set_and_run_with_externalities(&mut new_test_ext(vec![(1, 1), (2, 1), (3, 1)]), || { System::initialize(&1, &Default::default(), &Default::default(), &Default::default()); Grandpa::schedule_change( to_authorities(vec![(4, 1), (5, 1), (6, 1)]), @@ -205,7 +203,7 @@ fn dispatch_forced_change() { #[test] fn schedule_pause_only_when_live() { - with_externalities(&mut new_test_ext(vec![(1, 1), (2, 1), (3, 1)]), || { + set_and_run_with_externalities(&mut new_test_ext(vec![(1, 1), (2, 1), (3, 1)]), || { // we schedule a pause at block 1 with delay of 1 System::initialize(&1, &Default::default(), &Default::default(), &Default::default()); Grandpa::schedule_pause(1).unwrap(); @@ -240,7 +238,7 @@ fn schedule_pause_only_when_live() { #[test] fn schedule_resume_only_when_paused() { - with_externalities(&mut new_test_ext(vec![(1, 1), (2, 1), (3, 1)]), || { + set_and_run_with_externalities(&mut new_test_ext(vec![(1, 1), (2, 1), (3, 1)]), || { System::initialize(&1, &Default::default(), &Default::default(), &Default::default()); // the set is currently live, resuming it is an error diff --git a/substrate/srml/im-online/src/mock.rs b/substrate/srml/im-online/src/mock.rs index a7b669ddb8..c2869136dc 100644 --- a/substrate/srml/im-online/src/mock.rs +++ b/substrate/srml/im-online/src/mock.rs @@ -25,7 +25,7 @@ use sr_primitives::Perbill; use sr_staking_primitives::{SessionIndex, offence::ReportOffence}; use sr_primitives::testing::{Header, UintAuthorityId, TestXt}; use sr_primitives::traits::{IdentityLookup, BlakeTwo256, ConvertInto}; -use primitives::{H256, Blake2Hasher}; +use primitives::H256; use support::{impl_outer_origin, impl_outer_dispatch, parameter_types}; use {runtime_io, system}; @@ -85,7 +85,7 @@ impl ReportOffence for OffenceHandler { } } -pub fn new_test_ext() -> runtime_io::TestExternalities { +pub fn new_test_ext() -> runtime_io::TestExternalities { let t = system::GenesisConfig::default().build_storage::().unwrap(); t.into() } diff --git a/substrate/srml/im-online/src/tests.rs b/substrate/srml/im-online/src/tests.rs index c6405c34fa..d57b9f59cb 100644 --- a/substrate/srml/im-online/src/tests.rs +++ b/substrate/srml/im-online/src/tests.rs @@ -21,10 +21,9 @@ use super::*; use crate::mock::*; use offchain::testing::TestOffchainExt; -use primitives::offchain::OpaquePeerId; -use runtime_io::with_externalities; +use primitives::offchain::{OpaquePeerId, OffchainExt}; use support::{dispatch, assert_noop}; -use sr_primitives::testing::UintAuthorityId; +use sr_primitives::{set_and_run_with_externalities, testing::UintAuthorityId}; #[test] @@ -49,7 +48,7 @@ fn test_unresponsiveness_slash_fraction() { #[test] fn should_report_offline_validators() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // given let block = 1; System::set_block_number(block); @@ -125,7 +124,7 @@ fn heartbeat( #[test] fn should_mark_online_validator_when_heartbeat_is_received() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { advance_session(); // given VALIDATORS.with(|l| *l.borrow_mut() = Some(vec![1, 2, 3, 4, 5, 6])); @@ -160,7 +159,7 @@ fn should_mark_online_validator_when_heartbeat_is_received() { #[test] fn late_heartbeat_should_fail() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { advance_session(); // given VALIDATORS.with(|l| *l.borrow_mut() = Some(vec![1, 2, 4, 4, 5, 6])); @@ -181,9 +180,9 @@ fn late_heartbeat_should_fail() { fn should_generate_heartbeats() { let mut ext = new_test_ext(); let (offchain, state) = TestOffchainExt::new(); - ext.set_offchain_externalities(offchain); + ext.register_extension(OffchainExt::new(offchain)); - with_externalities(&mut ext, || { + set_and_run_with_externalities(&mut ext, || { // given let block = 1; System::set_block_number(block); @@ -219,7 +218,7 @@ fn should_generate_heartbeats() { #[test] fn should_cleanup_received_heartbeats_on_session_end() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { advance_session(); VALIDATORS.with(|l| *l.borrow_mut() = Some(vec![1, 2, 3])); diff --git a/substrate/srml/indices/src/mock.rs b/substrate/srml/indices/src/mock.rs index 65a0193b5a..59d84279a9 100644 --- a/substrate/srml/indices/src/mock.rs +++ b/substrate/srml/indices/src/mock.rs @@ -22,7 +22,7 @@ use std::collections::HashSet; use ref_thread_local::{ref_thread_local, RefThreadLocal}; use sr_primitives::testing::Header; use sr_primitives::Perbill; -use primitives::{H256, Blake2Hasher}; +use primitives::H256; use support::{impl_outer_origin, parameter_types}; use {runtime_io, system}; use crate::{GenesisConfig, Module, Trait, IsDeadAccount, OnNewAccount, ResolveHint}; @@ -96,7 +96,7 @@ impl Trait for Runtime { type Event = (); } -pub fn new_test_ext() -> runtime_io::TestExternalities { +pub fn new_test_ext() -> runtime_io::TestExternalities { { let mut h = ALIVE.borrow_mut(); h.clear(); diff --git a/substrate/srml/indices/src/tests.rs b/substrate/srml/indices/src/tests.rs index 7b60e30527..4b8f1822b4 100644 --- a/substrate/srml/indices/src/tests.rs +++ b/substrate/srml/indices/src/tests.rs @@ -20,11 +20,11 @@ use super::*; use crate::mock::{Indices, new_test_ext, make_account, kill_account, TestIsDeadAccount}; -use runtime_io::with_externalities; +use sr_primitives::set_and_run_with_externalities; #[test] fn indexing_lookup_should_work() { - with_externalities( + set_and_run_with_externalities( &mut new_test_ext(), || { assert_eq!(Indices::lookup_index(0), Some(1)); @@ -38,7 +38,7 @@ fn indexing_lookup_should_work() { #[test] fn default_indexing_on_new_accounts_should_work() { - with_externalities( + set_and_run_with_externalities( &mut new_test_ext(), || { assert_eq!(Indices::lookup_index(4), None); @@ -50,7 +50,7 @@ fn default_indexing_on_new_accounts_should_work() { #[test] fn reclaim_indexing_on_new_accounts_should_work() { - with_externalities( + set_and_run_with_externalities( &mut new_test_ext(), || { assert_eq!(Indices::lookup_index(1), Some(2)); @@ -66,7 +66,7 @@ fn reclaim_indexing_on_new_accounts_should_work() { #[test] fn alive_account_should_prevent_reclaim() { - with_externalities( + set_and_run_with_externalities( &mut new_test_ext(), || { assert!(!TestIsDeadAccount::is_dead_account(&2)); diff --git a/substrate/srml/membership/src/lib.rs b/substrate/srml/membership/src/lib.rs index 87e9268bd9..1a6ca82986 100644 --- a/substrate/srml/membership/src/lib.rs +++ b/substrate/srml/membership/src/lib.rs @@ -193,12 +193,12 @@ mod tests { use std::cell::RefCell; use support::{assert_ok, assert_noop, impl_outer_origin, parameter_types}; - use runtime_io::with_externalities; - use primitives::{H256, Blake2Hasher}; + use primitives::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 sr_primitives::{ - Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header + Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header, + set_and_run_with_externalities, }; use system::EnsureSignedBy; @@ -281,7 +281,7 @@ mod tests { // This function basically just builds a genesis storage key/value store according to // our desired mockup. - fn new_test_ext() -> runtime_io::TestExternalities { + fn new_test_ext() -> runtime_io::TestExternalities { let mut t = system::GenesisConfig::default().build_storage::().unwrap(); // We use default for brevity, but you can configure as desired if needed. GenesisConfig::{ @@ -293,7 +293,7 @@ mod tests { #[test] fn query_membership_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_eq!(Membership::members(), vec![10, 20, 30]); assert_eq!(MEMBERS.with(|m| m.borrow().clone()), vec![10, 20, 30]); }); @@ -301,7 +301,7 @@ mod tests { #[test] fn add_member_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_noop!(Membership::add_member(Origin::signed(5), 15), "bad origin"); assert_noop!(Membership::add_member(Origin::signed(1), 10), "already a member"); assert_ok!(Membership::add_member(Origin::signed(1), 15)); @@ -312,7 +312,7 @@ mod tests { #[test] fn remove_member_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_noop!(Membership::remove_member(Origin::signed(5), 20), "bad origin"); assert_noop!(Membership::remove_member(Origin::signed(2), 15), "not a member"); assert_ok!(Membership::remove_member(Origin::signed(2), 20)); @@ -323,7 +323,7 @@ mod tests { #[test] fn swap_member_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_noop!(Membership::swap_member(Origin::signed(5), 10, 25), "bad origin"); assert_noop!(Membership::swap_member(Origin::signed(3), 15, 25), "not a member"); assert_noop!(Membership::swap_member(Origin::signed(3), 10, 30), "already a member"); @@ -337,7 +337,7 @@ mod tests { #[test] fn reset_members_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_noop!(Membership::reset_members(Origin::signed(1), vec![20, 40, 30]), "bad origin"); assert_ok!(Membership::reset_members(Origin::signed(4), vec![20, 40, 30])); assert_eq!(Membership::members(), vec![20, 30, 40]); diff --git a/substrate/srml/offences/src/mock.rs b/substrate/srml/offences/src/mock.rs index e7280c34e9..01891ce32b 100644 --- a/substrate/srml/offences/src/mock.rs +++ b/substrate/srml/offences/src/mock.rs @@ -28,7 +28,7 @@ use sr_staking_primitives::{ }; use sr_primitives::testing::Header; use sr_primitives::traits::{IdentityLookup, BlakeTwo256}; -use substrate_primitives::{H256, Blake2Hasher}; +use substrate_primitives::H256; use support::{impl_outer_origin, impl_outer_event, parameter_types, StorageMap, StorageDoubleMap}; use {runtime_io, system}; @@ -103,7 +103,7 @@ impl_outer_event! { } } -pub fn new_test_ext() -> runtime_io::TestExternalities { +pub fn new_test_ext() -> runtime_io::TestExternalities { let t = system::GenesisConfig::default().build_storage::().unwrap(); t.into() } diff --git a/substrate/srml/offences/src/tests.rs b/substrate/srml/offences/src/tests.rs index 17f933b8e8..7604533ba5 100644 --- a/substrate/srml/offences/src/tests.rs +++ b/substrate/srml/offences/src/tests.rs @@ -24,11 +24,11 @@ use crate::mock::{ offence_reports, }; use system::{EventRecord, Phase}; -use runtime_io::with_externalities; +use sr_primitives::set_and_run_with_externalities; #[test] fn should_report_an_authority_and_trigger_on_offence() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // given let time_slot = 42; assert_eq!(offence_reports(KIND, time_slot), vec![]); @@ -51,7 +51,7 @@ fn should_report_an_authority_and_trigger_on_offence() { #[test] fn should_calculate_the_fraction_correctly() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // given let time_slot = 42; assert_eq!(offence_reports(KIND, time_slot), vec![]); @@ -83,7 +83,7 @@ fn should_calculate_the_fraction_correctly() { #[test] fn should_not_report_the_same_authority_twice_in_the_same_slot() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // given let time_slot = 42; assert_eq!(offence_reports(KIND, time_slot), vec![]); @@ -113,7 +113,7 @@ fn should_not_report_the_same_authority_twice_in_the_same_slot() { #[test] fn should_report_in_different_time_slot() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // given let time_slot = 42; assert_eq!(offence_reports(KIND, time_slot), vec![]); @@ -143,7 +143,7 @@ fn should_report_in_different_time_slot() { #[test] fn should_deposit_event() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // given let time_slot = 42; assert_eq!(offence_reports(KIND, time_slot), vec![]); @@ -171,7 +171,7 @@ fn should_deposit_event() { #[test] fn doesnt_deposit_event_for_dups() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // given let time_slot = 42; assert_eq!(offence_reports(KIND, time_slot), vec![]); @@ -208,7 +208,7 @@ fn doesnt_deposit_event_for_dups() { fn should_properly_count_offences() { // We report two different authorities for the same issue. Ultimately, the 1st authority // should have `count` equal 2 and the count of the 2nd one should be equal to 1. - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // given let time_slot = 42; assert_eq!(offence_reports(KIND, time_slot), vec![]); diff --git a/substrate/srml/randomness-collective-flip/src/lib.rs b/substrate/srml/randomness-collective-flip/src/lib.rs index 39dcf15ab4..e5110c5d21 100644 --- a/substrate/srml/randomness-collective-flip/src/lib.rs +++ b/substrate/srml/randomness-collective-flip/src/lib.rs @@ -161,10 +161,12 @@ impl Module { #[cfg(test)] mod tests { use super::*; - use primitives::{H256, Blake2Hasher}; - use sr_primitives::{Perbill, traits::{BlakeTwo256, OnInitialize, Header as _, IdentityLookup}, testing::Header}; + use primitives::H256; + use sr_primitives::{ + Perbill, traits::{BlakeTwo256, OnInitialize, Header as _, IdentityLookup}, testing::Header, + set_and_run_with_externalities, + }; use support::{impl_outer_origin, parameter_types}; - use runtime_io::with_externalities; #[derive(Clone, PartialEq, Eq)] pub struct Test; @@ -202,7 +204,7 @@ mod tests { type System = system::Module; type Randomness = Module; - fn new_test_ext() -> runtime_io::TestExternalities { + fn new_test_ext() -> runtime_io::TestExternalities { let t = system::GenesisConfig::default().build_storage::().unwrap(); t.into() } @@ -229,7 +231,7 @@ mod tests { #[test] fn test_random_material_parital() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { let genesis_hash = System::parent_hash(); setup_blocks(38); @@ -243,7 +245,7 @@ mod tests { #[test] fn test_random_material_filled() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { let genesis_hash = System::parent_hash(); setup_blocks(81); @@ -258,7 +260,7 @@ mod tests { #[test] fn test_random_material_filled_twice() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { let genesis_hash = System::parent_hash(); setup_blocks(162); @@ -273,7 +275,7 @@ mod tests { #[test] fn test_random() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { setup_blocks(162); assert_eq!(System::block_number(), 162); diff --git a/substrate/srml/scored-pool/src/mock.rs b/substrate/srml/scored-pool/src/mock.rs index fd14abd617..92a16bf25d 100644 --- a/substrate/srml/scored-pool/src/mock.rs +++ b/substrate/srml/scored-pool/src/mock.rs @@ -20,7 +20,7 @@ use super::*; use std::cell::RefCell; use support::{impl_outer_origin, parameter_types}; -use primitives::{H256, Blake2Hasher}; +use primitives::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 sr_primitives::{ @@ -132,7 +132,7 @@ 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() -> runtime_io::TestExternalities { +pub fn new_test_ext() -> runtime_io::TestExternalities { let mut t = system::GenesisConfig::default().build_storage::().unwrap(); // We use default for brevity, but you can configure as desired if needed. balances::GenesisConfig:: { diff --git a/substrate/srml/scored-pool/src/tests.rs b/substrate/srml/scored-pool/src/tests.rs index 740e707ce0..cd3efb0ceb 100644 --- a/substrate/srml/scored-pool/src/tests.rs +++ b/substrate/srml/scored-pool/src/tests.rs @@ -20,8 +20,7 @@ use super::*; use mock::*; use support::{assert_ok, assert_noop}; -use runtime_io::with_externalities; -use sr_primitives::traits::OnInitialize; +use sr_primitives::{set_and_run_with_externalities, traits::OnInitialize}; type ScoredPool = Module; type System = system::Module; @@ -32,7 +31,7 @@ const INDEX_ERR: &str = "index does not match requested account"; #[test] fn query_membership_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_eq!(ScoredPool::members(), vec![20, 40]); assert_eq!(Balances::reserved_balance(&31), CandidateDeposit::get()); assert_eq!(Balances::reserved_balance(&40), CandidateDeposit::get()); @@ -42,7 +41,7 @@ fn query_membership_works() { #[test] fn submit_candidacy_must_not_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_noop!( ScoredPool::submit_candidacy(Origin::signed(99)), "balance too low to submit candidacy" @@ -56,7 +55,7 @@ fn submit_candidacy_must_not_work() { #[test] fn submit_candidacy_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // given let who = 15; @@ -71,7 +70,7 @@ fn submit_candidacy_works() { #[test] fn scoring_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // given let who = 15; let score = 99; @@ -89,7 +88,7 @@ fn scoring_works() { #[test] fn scoring_same_element_with_same_score_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // given let who = 31; let index = find_in_pool(who).expect("entity must be in pool") as u32; @@ -109,7 +108,7 @@ fn scoring_same_element_with_same_score_works() { #[test] fn kicking_works_only_for_authorized() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { let who = 40; let index = find_in_pool(who).expect("entity must be in pool") as u32; assert_noop!(ScoredPool::kick(Origin::signed(99), who, index), "bad origin"); @@ -118,7 +117,7 @@ fn kicking_works_only_for_authorized() { #[test] fn kicking_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // given let who = 40; assert_eq!(Balances::reserved_balance(&who), CandidateDeposit::get()); @@ -138,7 +137,7 @@ fn kicking_works() { #[test] fn unscored_entities_must_not_be_used_for_filling_members() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // given // we submit a candidacy, score will be `None` assert_ok!(ScoredPool::submit_candidacy(Origin::signed(15))); @@ -163,7 +162,7 @@ fn unscored_entities_must_not_be_used_for_filling_members() { #[test] fn refreshing_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // given let who = 15; assert_ok!(ScoredPool::submit_candidacy(Origin::signed(who))); @@ -181,7 +180,7 @@ fn refreshing_works() { #[test] fn refreshing_happens_every_period() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // given System::set_block_number(1); assert_ok!(ScoredPool::submit_candidacy(Origin::signed(15))); @@ -201,7 +200,7 @@ fn refreshing_happens_every_period() { #[test] fn withdraw_candidacy_must_only_work_for_members() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { let who = 77; let index = 0; assert_noop!( ScoredPool::withdraw_candidacy(Origin::signed(who), index), INDEX_ERR); @@ -210,7 +209,7 @@ fn withdraw_candidacy_must_only_work_for_members() { #[test] fn oob_index_should_abort() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { let who = 40; let oob_index = ScoredPool::pool().len() as u32; assert_noop!(ScoredPool::withdraw_candidacy(Origin::signed(who), oob_index), OOB_ERR); @@ -221,7 +220,7 @@ fn oob_index_should_abort() { #[test] fn index_mismatches_should_abort() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { let who = 40; let index = 3; assert_noop!(ScoredPool::withdraw_candidacy(Origin::signed(who), index), INDEX_ERR); @@ -232,7 +231,7 @@ fn index_mismatches_should_abort() { #[test] fn withdraw_unscored_candidacy_must_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // given let who = 5; @@ -247,7 +246,7 @@ fn withdraw_unscored_candidacy_must_work() { #[test] fn withdraw_scored_candidacy_must_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // given let who = 40; assert_eq!(Balances::reserved_balance(&who), CandidateDeposit::get()); @@ -265,7 +264,7 @@ fn withdraw_scored_candidacy_must_work() { #[test] fn candidacy_resubmitting_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // given let who = 15; diff --git a/substrate/srml/session/src/historical.rs b/substrate/srml/session/src/historical.rs index 24821a0393..af9447eb7e 100644 --- a/substrate/srml/session/src/historical.rs +++ b/substrate/srml/session/src/historical.rs @@ -312,9 +312,10 @@ impl> support::traits::KeyOwnerProofSystem<(KeyTypeId, #[cfg(test)] mod tests { use super::*; - use runtime_io::with_externalities; - use primitives::{Blake2Hasher, crypto::key_types::DUMMY}; - use sr_primitives::{traits::OnInitialize, testing::UintAuthorityId}; + use primitives::crypto::key_types::DUMMY; + use sr_primitives::{ + traits::OnInitialize, testing::UintAuthorityId, set_and_run_with_externalities, + }; use crate::mock::{ NEXT_VALIDATORS, force_new_session, set_next_validators, Test, System, Session, @@ -323,7 +324,7 @@ mod tests { type Historical = Module; - fn new_test_ext() -> runtime_io::TestExternalities { + fn new_test_ext() -> runtime_io::TestExternalities { let mut t = system::GenesisConfig::default().build_storage::().unwrap(); crate::GenesisConfig:: { keys: NEXT_VALIDATORS.with(|l| @@ -335,7 +336,7 @@ mod tests { #[test] fn generated_proof_is_good() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { set_next_validators(vec![1, 2]); force_new_session(); @@ -376,7 +377,7 @@ mod tests { #[test] fn prune_up_to_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { for i in 1..101u64 { set_next_validators(vec![i]); force_new_session(); diff --git a/substrate/srml/session/src/lib.rs b/substrate/srml/session/src/lib.rs index 208be4664a..df311f5081 100644 --- a/substrate/srml/session/src/lib.rs +++ b/substrate/srml/session/src/lib.rs @@ -680,11 +680,9 @@ impl> FindAuthor mod tests { use super::*; use support::assert_ok; - use runtime_io::with_externalities; - use primitives::{Blake2Hasher, crypto::key_types::DUMMY}; + use primitives::crypto::key_types::DUMMY; use sr_primitives::{ - traits::OnInitialize, - testing::UintAuthorityId, + traits::OnInitialize, set_and_run_with_externalities, testing::UintAuthorityId, }; use mock::{ NEXT_VALIDATORS, SESSION_CHANGED, TEST_SESSION_CHANGED, authorities, force_new_session, @@ -692,7 +690,7 @@ mod tests { reset_before_session_end_called, before_session_end_called, }; - fn new_test_ext() -> runtime_io::TestExternalities { + fn new_test_ext() -> runtime_io::TestExternalities { let mut t = system::GenesisConfig::default().build_storage::().unwrap(); GenesisConfig:: { keys: NEXT_VALIDATORS.with(|l| @@ -710,7 +708,7 @@ mod tests { #[test] fn simple_setup_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_eq!(authorities(), vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)]); assert_eq!(Session::validators(), vec![1, 2, 3]); }); @@ -718,7 +716,7 @@ mod tests { #[test] fn put_get_keys() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { Session::put_keys(&10, &UintAuthorityId(10).into()); assert_eq!(Session::load_keys(&10), Some(UintAuthorityId(10).into())); }) @@ -727,7 +725,7 @@ mod tests { #[test] fn keys_cleared_on_kill() { let mut ext = new_test_ext(); - with_externalities(&mut ext, || { + set_and_run_with_externalities(&mut ext, || { assert_eq!(Session::validators(), vec![1, 2, 3]); assert_eq!(Session::load_keys(&1), Some(UintAuthorityId(1).into())); @@ -744,7 +742,7 @@ mod tests { fn authorities_should_track_validators() { reset_before_session_end_called(); - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { set_next_validators(vec![1, 2]); force_new_session(); initialize_block(1); @@ -795,7 +793,7 @@ mod tests { #[test] fn should_work_with_early_exit() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { set_session_length(10); initialize_block(1); @@ -818,7 +816,7 @@ mod tests { #[test] fn session_change_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // Block 1: No change initialize_block(1); assert_eq!(authorities(), vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)]); @@ -848,7 +846,7 @@ mod tests { #[test] fn duplicates_are_not_allowed() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::set_block_number(1); Session::on_initialize(1); assert!(Session::set_keys(Origin::signed(4), UintAuthorityId(1).into(), vec![]).is_err()); @@ -863,7 +861,7 @@ mod tests { fn session_changed_flag_works() { reset_before_session_end_called(); - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { TEST_SESSION_CHANGED.with(|l| *l.borrow_mut() = true); force_new_session(); @@ -952,7 +950,7 @@ mod tests { #[test] fn session_keys_generate_output_works_as_set_keys_input() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { let new_keys = mock::MockSessionKeys::generate(None); assert_ok!( Session::set_keys( @@ -966,7 +964,7 @@ mod tests { #[test] fn return_true_if_more_than_third_is_disabled() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { set_next_validators(vec![1, 2, 3, 4, 5, 6, 7]); force_new_session(); initialize_block(1); diff --git a/substrate/srml/staking/src/mock.rs b/substrate/srml/staking/src/mock.rs index d8d3656142..9055d7db87 100644 --- a/substrate/srml/staking/src/mock.rs +++ b/substrate/srml/staking/src/mock.rs @@ -22,7 +22,7 @@ use sr_primitives::curve::PiecewiseLinear; use sr_primitives::traits::{IdentityLookup, Convert, OpaqueKeys, OnInitialize, SaturatedConversion}; use sr_primitives::testing::{Header, UintAuthorityId}; use sr_staking_primitives::SessionIndex; -use primitives::{H256, Blake2Hasher}; +use primitives::H256; use runtime_io; use support::{assert_ok, impl_outer_origin, parameter_types, StorageLinkedMap}; use support::traits::{Currency, Get, FindAuthor}; @@ -274,7 +274,7 @@ impl ExtBuilder { pub fn set_associated_consts(&self) { EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = self.existential_deposit); } - pub fn build(self) -> runtime_io::TestExternalities { + pub fn build(self) -> runtime_io::TestExternalities { self.set_associated_consts(); let mut storage = system::GenesisConfig::default().build_storage::().unwrap(); let balance_factor = if self.existential_deposit > 0 { @@ -341,7 +341,7 @@ impl ExtBuilder { }.assimilate_storage(&mut storage); let mut ext = storage.into(); - runtime_io::with_externalities(&mut ext, || { + sr_primitives::set_and_run_with_externalities(&mut ext, || { let validators = Session::validators(); SESSION.with(|x| *x.borrow_mut() = (validators.clone(), HashSet::new()) diff --git a/substrate/srml/staking/src/tests.rs b/substrate/srml/staking/src/tests.rs index 6b51fb9b3f..48218f9eb7 100644 --- a/substrate/srml/staking/src/tests.rs +++ b/substrate/srml/staking/src/tests.rs @@ -18,16 +18,14 @@ use super::*; use mock::*; -use runtime_io::with_externalities; -use sr_primitives::{assert_eq_error_rate, traits::OnInitialize}; +use sr_primitives::{assert_eq_error_rate, traits::OnInitialize, set_and_run_with_externalities}; use sr_staking_primitives::offence::{OffenceDetails, OnOffenceHandler}; -use support::{assert_ok, assert_noop, assert_eq_uvec}; -use support::traits::{Currency, ReservableCurrency}; +use support::{assert_ok, assert_noop, assert_eq_uvec, traits::{Currency, ReservableCurrency}}; #[test] fn basic_setup_works() { // Verifies initial conditions of mock - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .build(), || { // Account 11 is stashed and locked, and account 10 is the controller @@ -109,7 +107,7 @@ fn basic_setup_works() { #[test] fn change_controller_works() { - with_externalities(&mut ExtBuilder::default().build(), + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_eq!(Staking::bonded(&11), Some(10)); @@ -136,7 +134,7 @@ fn rewards_should_work() { // * rewards get recorded per session // * rewards get paid per Era // * Check that nominators are also rewarded - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .nominate(false) .build(), || { @@ -217,7 +215,7 @@ fn multi_era_reward_should_work() { // Should check that: // The value of current_session_reward is set at the end of each era, based on // slot_stake and session_reward. - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .nominate(false) .build(), || { @@ -260,7 +258,7 @@ fn staking_should_work() { // * new validators can be added to the default set // * new ones will be chosen per era // * either one can unlock the stash and back-down from being a validator via `chill`ing. - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .nominate(false) .fair(false) // to give 20 more staked value .build(), @@ -322,7 +320,7 @@ fn staking_should_work() { #[test] fn less_than_needed_candidates_works() { - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .minimum_validator_count(1) .validator_count(4) .nominate(false) @@ -349,7 +347,7 @@ fn less_than_needed_candidates_works() { #[test] fn no_candidate_emergency_condition() { - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .minimum_validator_count(10) .validator_count(15) .num_validators(4) @@ -415,7 +413,7 @@ fn nominating_and_rewards_should_work() { // 10 with stake 400.0 20 with stake 600.0 30 with stake 0 // 4 has load 0.0005555555555555556 and supported // 10 with stake 600.0 20 with stake 400.0 40 with stake 0.0 - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .nominate(false) .validator_pool(true) .build(), @@ -599,7 +597,7 @@ fn nominators_also_get_slashed() { // 10 - is the controller of 11 // 11 - is the stash. // 2 - is the nominator of 20, 10 - with_externalities(&mut ExtBuilder::default().nominate(false).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().nominate(false).build(), || { assert_eq!(Staking::validator_count(), 2); // Set payee to controller @@ -659,7 +657,7 @@ fn double_staking_should_fail() { // * an account already bonded as stash cannot be be stashed again. // * an account already bonded as stash cannot nominate. // * an account already bonded as controller can nominate. - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .build(), || { let arbitrary_value = 5; @@ -684,7 +682,7 @@ fn double_staking_should_fail() { fn double_controlling_should_fail() { // should test (in the same order): // * an account already bonded as controller CANNOT be reused as the controller of another account. - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .build(), || { let arbitrary_value = 5; @@ -703,7 +701,7 @@ fn double_controlling_should_fail() { #[test] fn session_and_eras_work() { - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .build(), || { assert_eq!(Staking::current_era(), 0); @@ -747,7 +745,7 @@ fn session_and_eras_work() { #[test] fn forcing_new_era_works() { - with_externalities(&mut ExtBuilder::default().build(),|| { + set_and_run_with_externalities(&mut ExtBuilder::default().build(),|| { // normal flow of session. assert_eq!(Staking::current_era(), 0); start_session(0); @@ -786,7 +784,7 @@ fn forcing_new_era_works() { #[test] fn cannot_transfer_staked_balance() { // Tests that a stash account cannot transfer funds - with_externalities(&mut ExtBuilder::default().nominate(false).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().nominate(false).build(), || { // Confirm account 11 is stashed assert_eq!(Staking::bonded(&11), Some(10)); // Confirm account 11 has some free balance @@ -811,7 +809,7 @@ fn cannot_transfer_staked_balance_2() { // Tests that a stash account cannot transfer funds // Same test as above but with 20, and more accurate. // 21 has 2000 free balance but 1000 at stake - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .nominate(false) .fair(true) .build(), @@ -834,7 +832,7 @@ fn cannot_transfer_staked_balance_2() { #[test] fn cannot_reserve_staked_balance() { // Checks that a bonded account cannot reserve balance from free balance - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { // Confirm account 11 is stashed assert_eq!(Staking::bonded(&11), Some(10)); // Confirm account 11 has some free balance @@ -854,7 +852,7 @@ fn cannot_reserve_staked_balance() { #[test] fn reward_destination_works() { // Rewards go to the correct destination as determined in Payee - with_externalities(&mut ExtBuilder::default().nominate(false).build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().nominate(false).build(), || { // Check that account 11 is a validator assert!(Staking::current_elected().contains(&11)); // Check the balance of the validator account @@ -946,7 +944,7 @@ fn validator_payment_prefs_work() { // Test that validator preferences are correctly honored // Note: unstake threshold is being directly tested in slashing tests. // This test will focus on validator payment. - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .build(), || { // Initial config @@ -998,7 +996,7 @@ fn bond_extra_works() { // Tests that extra `free_balance` in the stash can be added to stake // NOTE: this tests only verifies `StakingLedger` for correct updates // See `bond_extra_and_withdraw_unbonded_works` for more details and updates on `Exposure`. - with_externalities(&mut ExtBuilder::default().build(), + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { // Check that account 10 is a validator assert!(>::exists(11)); @@ -1044,7 +1042,7 @@ fn bond_extra_and_withdraw_unbonded_works() { // * It can add extra funds to the bonded account. // * it can unbond a portion of its funds from the stash account. // * Once the unbonding period is done, it can actually take the funds out of the stash. - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .nominate(false) .build(), || { @@ -1131,7 +1129,7 @@ fn bond_extra_and_withdraw_unbonded_works() { #[test] fn too_many_unbond_calls_should_not_work() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { // locked at era 0 until 3 for _ in 0..MAX_UNLOCKING_CHUNKS-1 { assert_ok!(Staking::unbond(Origin::signed(10), 1)); @@ -1160,7 +1158,7 @@ fn too_many_unbond_calls_should_not_work() { fn slot_stake_is_least_staked_validator_and_exposure_defines_maximum_punishment() { // Test that slot_stake is determined by the least staked validator // Test that slot_stake is the maximum punishment that can happen to a validator - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .nominate(false) .fair(false) .build(), @@ -1213,7 +1211,7 @@ fn slot_stake_is_least_staked_validator_and_exposure_defines_maximum_punishment( fn on_free_balance_zero_stash_removes_validator() { // Tests that validator storage items are cleaned up when stash is empty // Tests that storage items are untouched when controller is empty - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .existential_deposit(10) .build(), || { @@ -1266,7 +1264,7 @@ fn on_free_balance_zero_stash_removes_validator() { fn on_free_balance_zero_stash_removes_nominator() { // Tests that nominator storage items are cleaned up when stash is empty // Tests that storage items are untouched when controller is empty - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .existential_deposit(10) .build(), || { @@ -1322,7 +1320,7 @@ fn on_free_balance_zero_stash_removes_nominator() { #[test] fn switching_roles() { // Test that it should be possible to switch between roles (nominator, validator, idle) with minimal overhead. - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .nominate(false) .build(), || { @@ -1391,7 +1389,7 @@ fn switching_roles() { #[test] fn wrong_vote_is_null() { - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .nominate(false) .validator_pool(true) .build(), @@ -1419,7 +1417,7 @@ fn wrong_vote_is_null() { fn bond_with_no_staked_value() { // Behavior when someone bonds with no staked value. // Particularly when she votes and the candidate is elected. - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .validator_count(3) .existential_deposit(5) .nominate(false) @@ -1467,7 +1465,7 @@ fn bond_with_no_staked_value() { fn bond_with_little_staked_value_bounded_by_slot_stake() { // Behavior when someone bonds with little staked value. // Particularly when she votes and the candidate is elected. - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .validator_count(3) .nominate(false) .minimum_validator_count(1) @@ -1517,7 +1515,7 @@ fn bond_with_little_staked_value_bounded_by_slot_stake() { #[cfg(feature = "equalize")] #[test] fn phragmen_linear_worse_case_equalize() { - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .nominate(false) .validator_pool(true) .fair(true) @@ -1562,7 +1560,7 @@ fn phragmen_linear_worse_case_equalize() { #[test] fn new_era_elects_correct_number_of_validators() { - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .nominate(true) .validator_pool(true) .fair(true) @@ -1583,7 +1581,7 @@ fn new_era_elects_correct_number_of_validators() { #[test] fn phragmen_should_not_overflow_validators() { - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .nominate(false) .build(), || { @@ -1609,7 +1607,7 @@ fn phragmen_should_not_overflow_validators() { #[test] fn phragmen_should_not_overflow_nominators() { - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .nominate(false) .build(), || { @@ -1634,7 +1632,7 @@ fn phragmen_should_not_overflow_nominators() { #[test] fn phragmen_should_not_overflow_ultimate() { - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .nominate(false) .build(), || { @@ -1656,7 +1654,7 @@ fn phragmen_should_not_overflow_ultimate() { #[test] fn reward_validator_slashing_validator_doesnt_overflow() { - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .build(), || { let stake = u32::max_value() as u64 * 2; @@ -1689,7 +1687,7 @@ fn reward_validator_slashing_validator_doesnt_overflow() { #[test] fn reward_from_authorship_event_handler_works() { - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .build(), || { use authorship::EventHandler; @@ -1716,7 +1714,7 @@ fn reward_from_authorship_event_handler_works() { #[test] fn add_reward_points_fns_works() { - with_externalities(&mut ExtBuilder::default() + set_and_run_with_externalities(&mut ExtBuilder::default() .build(), || { let validators = >::current_elected(); @@ -1744,7 +1742,7 @@ fn add_reward_points_fns_works() { #[test] fn unbonded_balance_is_not_slashable() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { // total amount staked is slashable. assert_eq!(Staking::slashable_balance_of(&11), 1000); @@ -1759,7 +1757,7 @@ fn unbonded_balance_is_not_slashable() { fn era_is_always_same_length() { // This ensures that the sessions is always of the same length if there is no forcing no // session changes. - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { start_era(1); assert_eq!(Staking::current_era_start_session_index(), SessionsPerEra::get()); @@ -1779,7 +1777,7 @@ fn era_is_always_same_length() { #[test] fn offence_forces_new_era() { - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { Staking::on_offence( &[OffenceDetails { offender: ( @@ -1799,7 +1797,7 @@ fn offence_forces_new_era() { fn slashing_performed_according_exposure() { // This test checks that slashing is performed according the exposure (or more precisely, // historical exposure), not the current balance. - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_eq!(Staking::stakers(&11).own, 1000); // Handle an offence with a historical exposure. @@ -1827,7 +1825,7 @@ fn slashing_performed_according_exposure() { fn reporters_receive_their_slice() { // This test verifies that the reporters of the offence receive their slice from the slashed // amount. - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { // The reporters' reward is calculated from the total exposure. #[cfg(feature = "equalize")] let initial_balance = 1250; @@ -1857,7 +1855,7 @@ fn reporters_receive_their_slice() { #[test] fn invulnerables_are_not_slashed() { // For invulnerable validators no slashing is performed. - with_externalities( + set_and_run_with_externalities( &mut ExtBuilder::default().invulnerables(vec![11]).build(), || { #[cfg(feature = "equalize")] @@ -1894,7 +1892,7 @@ fn invulnerables_are_not_slashed() { #[test] fn dont_slash_if_fraction_is_zero() { // Don't slash if the fraction is zero. - with_externalities(&mut ExtBuilder::default().build(), || { + set_and_run_with_externalities(&mut ExtBuilder::default().build(), || { assert_eq!(Balances::free_balance(&11), 1000); Staking::on_offence( diff --git a/substrate/srml/support/src/lib.rs b/substrate/srml/support/src/lib.rs index b88d86761c..675e5b6ea8 100644 --- a/substrate/srml/support/src/lib.rs +++ b/substrate/srml/support/src/lib.rs @@ -236,13 +236,12 @@ pub use serde::{Serialize, Deserialize}; mod tests { use super::*; use codec::{Codec, EncodeLike}; - use runtime_io::with_externalities; - use primitives::Blake2Hasher; - pub use srml_metadata::{ + use sr_primitives::set_and_run_with_externalities; + use srml_metadata::{ DecodeDifferent, StorageEntryMetadata, StorageMetadata, StorageEntryType, - StorageEntryModifier, DefaultByte, DefaultByteGetter, StorageHasher + StorageEntryModifier, DefaultByteGetter, StorageHasher, }; - pub use rstd::marker::PhantomData; + use rstd::marker::PhantomData; pub trait Trait { type BlockNumber: Codec + EncodeLike + Default; @@ -281,7 +280,7 @@ mod tests { type Origin = u32; } - fn new_test_ext() -> runtime_io::TestExternalities { + fn new_test_ext() -> runtime_io::TestExternalities { GenesisConfig::default().build_storage().unwrap().into() } @@ -289,7 +288,7 @@ mod tests { #[test] fn linked_map_issue_3318() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { OptionLinkedMap::insert(1, 1); assert_eq!(OptionLinkedMap::get(1), Some(1)); OptionLinkedMap::insert(1, 2); @@ -299,7 +298,7 @@ mod tests { #[test] fn linked_map_swap_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { OptionLinkedMap::insert(0, 0); OptionLinkedMap::insert(1, 1); OptionLinkedMap::insert(2, 2); @@ -328,7 +327,7 @@ mod tests { #[test] fn linked_map_basic_insert_remove_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // initialized during genesis assert_eq!(Map::get(&15u32), 42u64); @@ -354,7 +353,7 @@ mod tests { #[test] fn linked_map_enumeration_and_head_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_eq!(Map::head(), Some(15)); assert_eq!(Map::enumerate().collect::>(), vec![(15, 42)]); // insert / remove @@ -406,7 +405,7 @@ mod tests { #[test] fn double_map_basic_insert_remove_remove_prefix_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { type DoubleMap = DataDM; // initialized during genesis assert_eq!(DoubleMap::get(&15u32, &16u32), 42u64); @@ -446,7 +445,7 @@ mod tests { #[test] fn double_map_append_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { type DoubleMap = AppendableDM; let key1 = 17u32; diff --git a/substrate/srml/support/src/storage/storage_items.rs b/substrate/srml/support/src/storage/storage_items.rs index 24a7f3984a..4f8f194795 100644 --- a/substrate/srml/support/src/storage/storage_items.rs +++ b/substrate/srml/support/src/storage/storage_items.rs @@ -758,8 +758,8 @@ mod test3 { #[cfg(test)] #[allow(dead_code)] mod test_append_and_len { - use crate::storage::{StorageValue}; - use runtime_io::{with_externalities, TestExternalities}; + use runtime_io::TestExternalities; + use sr_primitives::set_and_run_with_externalities; use codec::{Encode, Decode}; pub trait Trait { @@ -801,7 +801,7 @@ mod test_append_and_len { #[test] fn default_for_option() { - with_externalities(&mut TestExternalities::default(), || { + set_and_run_with_externalities(&mut TestExternalities::default(), || { assert_eq!(OptionVec::get(), None); assert_eq!(JustVec::get(), vec![]); }); @@ -809,7 +809,7 @@ mod test_append_and_len { #[test] fn append_works() { - with_externalities(&mut TestExternalities::default(), || { + set_and_run_with_externalities(&mut TestExternalities::default(), || { let _ = MapVec::append(1, [1, 2, 3].iter()); let _ = MapVec::append(1, [4, 5].iter()); assert_eq!(MapVec::get(1), vec![1, 2, 3, 4, 5]); @@ -822,7 +822,7 @@ mod test_append_and_len { #[test] fn append_works_for_default() { - with_externalities(&mut TestExternalities::default(), || { + set_and_run_with_externalities(&mut TestExternalities::default(), || { assert_eq!(JustVecWithDefault::get(), vec![6, 9]); let _ = JustVecWithDefault::append([1].iter()); assert_eq!(JustVecWithDefault::get(), vec![6, 9, 1]); @@ -839,7 +839,7 @@ mod test_append_and_len { #[test] fn append_or_put_works() { - with_externalities(&mut TestExternalities::default(), || { + set_and_run_with_externalities(&mut TestExternalities::default(), || { let _ = MapVec::append_or_insert(1, &[1, 2, 3][..]); let _ = MapVec::append_or_insert(1, &[4, 5][..]); assert_eq!(MapVec::get(1), vec![1, 2, 3, 4, 5]); @@ -856,7 +856,7 @@ mod test_append_and_len { #[test] fn len_works() { - with_externalities(&mut TestExternalities::default(), || { + set_and_run_with_externalities(&mut TestExternalities::default(), || { JustVec::put(&vec![1, 2, 3, 4]); OptionVec::put(&vec![1, 2, 3, 4, 5]); MapVec::insert(1, &vec![1, 2, 3, 4, 5, 6]); @@ -871,7 +871,7 @@ mod test_append_and_len { #[test] fn len_works_for_default() { - with_externalities(&mut TestExternalities::default(), || { + set_and_run_with_externalities(&mut TestExternalities::default(), || { // vec assert_eq!(JustVec::get(), vec![]); assert_eq!(JustVec::decode_len(), Ok(0)); diff --git a/substrate/srml/support/test/Cargo.toml b/substrate/srml/support/test/Cargo.toml index bb1b3749e9..f40fef9ead 100644 --- a/substrate/srml/support/test/Cargo.toml +++ b/substrate/srml/support/test/Cargo.toml @@ -10,6 +10,7 @@ codec = { package = "parity-scale-codec", version = "1.0.0", default-features = runtime-io ={ package = "sr-io", path = "../../../core/sr-io", default-features = false } support = { package = "srml-support", version = "2", path = "../", default-features = false } inherents = { package = "substrate-inherents", path = "../../../core/inherents", default-features = false } +sr-primitives = { package = "sr-primitives", path = "../../../core/sr-primitives", default-features = false } primitives = { package = "substrate-primitives", path = "../../../core/primitives", default-features = false } trybuild = "1.0.14" pretty_assertions = "0.6.1" @@ -23,4 +24,5 @@ std = [ "support/std", "inherents/std", "primitives/std", + "sr-primitives/std", ] diff --git a/substrate/srml/support/test/tests/instance.rs b/substrate/srml/support/test/tests/instance.rs index da4e73e710..c7a2d25eed 100644 --- a/substrate/srml/support/test/tests/instance.rs +++ b/substrate/srml/support/test/tests/instance.rs @@ -15,20 +15,22 @@ // along with Substrate. If not, see . #![recursion_limit="128"] -use runtime_io::with_externalities; +use sr_primitives::{ + generic, BuildStorage, traits::{BlakeTwo256, Block as _, Verify}, + set_and_run_with_externalities, +}; use support::{ Parameter, traits::Get, parameter_types, - sr_primitives::{generic, BuildStorage, traits::{BlakeTwo256, Block as _, Verify}}, metadata::{ DecodeDifferent, StorageMetadata, StorageEntryModifier, StorageEntryType, DefaultByteGetter, - StorageEntryMetadata, StorageHasher + StorageEntryMetadata, StorageHasher, }, StorageValue, StorageMap, StorageLinkedMap, StorageDoubleMap, }; use inherents::{ ProvideInherent, InherentData, InherentIdentifier, RuntimeString, MakeFatalError }; -use primitives::{H256, sr25519, Blake2Hasher}; +use primitives::{H256, sr25519}; mod system; @@ -275,7 +277,7 @@ pub type Header = generic::Header; pub type Block = generic::Block; pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; -fn new_test_ext() -> runtime_io::TestExternalities { +fn new_test_ext() -> runtime_io::TestExternalities { GenesisConfig{ module1_Instance1: Some(module1::GenesisConfig { value: 3, @@ -329,7 +331,7 @@ fn storage_instance_independance() { #[test] fn storage_with_instance_basic_operation() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { type Value = module2::Value; type Map = module2::Map; type LinkedMap = module2::LinkedMap; diff --git a/substrate/srml/system/benches/bench.rs b/substrate/srml/system/benches/bench.rs index b24e52f457..89e9af9525 100644 --- a/substrate/srml/system/benches/bench.rs +++ b/substrate/srml/system/benches/bench.rs @@ -17,9 +17,10 @@ use criterion::{Criterion, criterion_group, criterion_main, black_box}; use srml_system as system; use support::{decl_module, decl_event, impl_outer_origin, impl_outer_event}; -use runtime_io::with_externalities; -use primitives::{H256, Blake2Hasher}; -use sr_primitives::{Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header}; +use primitives::H256; +use sr_primitives::{ + set_and_run_with_externalities, Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header, +}; mod module { use super::*; @@ -82,13 +83,13 @@ impl module::Trait for Runtime { type Event = Event; } -fn new_test_ext() -> runtime_io::TestExternalities { +fn new_test_ext() -> runtime_io::TestExternalities { system::GenesisConfig::default().build_storage::().unwrap().into() } fn deposit_events(n: usize) { let mut t = new_test_ext(); - with_externalities(&mut t, || { + set_and_run_with_externalities(&mut t, || { for _ in 0..n { module::Module::::deposit_event( module::Event::Complex(vec![1, 2, 3], 2, 3, 899) diff --git a/substrate/srml/system/src/lib.rs b/substrate/srml/system/src/lib.rs index 79782d5af4..065b23bda1 100644 --- a/substrate/srml/system/src/lib.rs +++ b/substrate/srml/system/src/lib.rs @@ -120,7 +120,7 @@ use codec::{Encode, Decode}; use runtime_io::TestExternalities; #[cfg(any(feature = "std", test))] -use primitives::{ChangesTrieConfiguration, Blake2Hasher}; +use primitives::ChangesTrieConfiguration; pub mod offchain; @@ -695,7 +695,7 @@ impl Module { /// Get the basic externalities for this module, useful for tests. #[cfg(any(feature = "std", test))] - pub fn externalities() -> TestExternalities { + pub fn externalities() -> TestExternalities { TestExternalities::new((map![ >::hashed_key_for(T::BlockNumber::zero()) => [69u8; 32].encode(), >::hashed_key().to_vec() => T::BlockNumber::one().encode(), @@ -1090,9 +1090,11 @@ impl Lookup for ChainContext { #[cfg(test)] mod tests { use super::*; - use runtime_io::with_externalities; use primitives::H256; - use sr_primitives::{traits::{BlakeTwo256, IdentityLookup}, testing::Header, DispatchError}; + use sr_primitives::{ + traits::{BlakeTwo256, IdentityLookup}, testing::Header, DispatchError, + set_and_run_with_externalities, + }; use support::{impl_outer_origin, parameter_types}; impl_outer_origin! { @@ -1141,7 +1143,7 @@ mod tests { const CALL: &::Call = &(); - fn new_test_ext() -> runtime_io::TestExternalities { + fn new_test_ext() -> runtime_io::TestExternalities { GenesisConfig::default().build_storage::().unwrap().into() } @@ -1162,7 +1164,7 @@ mod tests { #[test] fn deposit_event_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { System::initialize(&1, &[0u8; 32].into(), &[0u8; 32].into(), &Default::default()); System::note_finished_extrinsics(); System::deposit_event(1u16); @@ -1199,7 +1201,7 @@ mod tests { #[test] fn deposit_event_topics() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { const BLOCK_NUMBER: u64 = 1; System::initialize(&BLOCK_NUMBER, &[0u8; 32].into(), &[0u8; 32].into(), &Default::default()); @@ -1259,7 +1261,7 @@ mod tests { #[test] fn prunes_block_hash_mappings() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // simulate import of 15 blocks for n in 1..=15 { System::initialize( @@ -1292,7 +1294,7 @@ mod tests { #[test] fn signed_ext_check_nonce_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { >::insert(1, 1); let info = DispatchInfo::default(); let len = 0_usize; @@ -1310,7 +1312,7 @@ mod tests { #[test] fn signed_ext_check_weight_works_normal_tx() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { let normal_limit = normal_weight_limit(); let small = DispatchInfo { weight: 100, ..Default::default() }; let medium = DispatchInfo { @@ -1337,7 +1339,7 @@ mod tests { #[test] fn signed_ext_check_weight_fee_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { let free = DispatchInfo { weight: 0, ..Default::default() }; let len = 0_usize; @@ -1350,7 +1352,7 @@ mod tests { #[test] fn signed_ext_check_weight_max_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { let max = DispatchInfo { weight: Weight::max_value(), ..Default::default() }; let len = 0_usize; let normal_limit = normal_weight_limit(); @@ -1364,7 +1366,7 @@ mod tests { #[test] fn signed_ext_check_weight_works_operational_tx() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { let normal = DispatchInfo { weight: 100, ..Default::default() }; let op = DispatchInfo { weight: 100, class: DispatchClass::Operational }; let len = 0_usize; @@ -1387,7 +1389,7 @@ mod tests { #[test] fn signed_ext_check_weight_priority_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { let normal = DispatchInfo { weight: 100, class: DispatchClass::Normal }; let op = DispatchInfo { weight: 100, class: DispatchClass::Operational }; let len = 0_usize; @@ -1408,7 +1410,7 @@ mod tests { #[test] fn signed_ext_check_weight_block_size_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { let normal = DispatchInfo::default(); let normal_limit = normal_weight_limit() as usize; let reset_check_weight = |tx, s, f| { @@ -1432,7 +1434,7 @@ mod tests { #[test] fn signed_ext_check_era_should_work() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // future assert_eq!( CheckEra::::from(Era::mortal(4, 2)).additional_signed().err().unwrap(), @@ -1448,7 +1450,7 @@ mod tests { #[test] fn signed_ext_check_era_should_change_longevity() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { let normal = DispatchInfo { weight: 100, class: DispatchClass::Normal }; let len = 0_usize; let ext = ( diff --git a/substrate/srml/timestamp/src/lib.rs b/substrate/srml/timestamp/src/lib.rs index 4af0de8bd1..8ed3aa8dc0 100644 --- a/substrate/srml/timestamp/src/lib.rs +++ b/substrate/srml/timestamp/src/lib.rs @@ -322,9 +322,12 @@ mod tests { use super::*; use support::{impl_outer_origin, assert_ok, parameter_types}; - use runtime_io::{with_externalities, TestExternalities}; + use runtime_io::TestExternalities; use primitives::H256; - use sr_primitives::{Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header}; + use sr_primitives::{ + Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header, + set_and_run_with_externalities, + }; impl_outer_origin! { pub enum Origin for Test {} @@ -369,7 +372,7 @@ mod tests { #[test] fn timestamp_works() { let t = system::GenesisConfig::default().build_storage::().unwrap(); - with_externalities(&mut TestExternalities::new(t), || { + set_and_run_with_externalities(&mut TestExternalities::new(t), || { Timestamp::set_timestamp(42); assert_ok!(Timestamp::dispatch(Call::set(69), Origin::NONE)); assert_eq!(Timestamp::now(), 69); @@ -380,7 +383,7 @@ mod tests { #[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(); - with_externalities(&mut TestExternalities::new(t), || { + set_and_run_with_externalities(&mut TestExternalities::new(t), || { Timestamp::set_timestamp(42); assert_ok!(Timestamp::dispatch(Call::set(69), Origin::NONE)); let _ = Timestamp::dispatch(Call::set(70), Origin::NONE); @@ -391,7 +394,7 @@ mod tests { #[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(); - with_externalities(&mut TestExternalities::new(t), || { + set_and_run_with_externalities(&mut TestExternalities::new(t), || { Timestamp::set_timestamp(42); let _ = Timestamp::dispatch(Call::set(46), Origin::NONE); }); diff --git a/substrate/srml/treasury/src/lib.rs b/substrate/srml/treasury/src/lib.rs index db8b0f34c9..8ccc260fa7 100644 --- a/substrate/srml/treasury/src/lib.rs +++ b/substrate/srml/treasury/src/lib.rs @@ -355,13 +355,11 @@ impl OnDilution> for Module { mod tests { use super::*; - use runtime_io::with_externalities; use support::{assert_noop, assert_ok, impl_outer_origin, parameter_types}; - use primitives::{H256, Blake2Hasher}; + use primitives::H256; use sr_primitives::{ - traits::{BlakeTwo256, OnFinalize, IdentityLookup}, - testing::Header, - assert_eq_error_rate, + traits::{BlakeTwo256, OnFinalize, IdentityLookup}, set_and_run_with_externalities, + testing::Header, assert_eq_error_rate, }; impl_outer_origin! { @@ -437,7 +435,7 @@ mod tests { type Balances = balances::Module; type Treasury = Module; - fn new_test_ext() -> runtime_io::TestExternalities { + fn new_test_ext() -> runtime_io::TestExternalities { let mut t = system::GenesisConfig::default().build_storage::().unwrap(); balances::GenesisConfig::{ balances: vec![(0, 100), (1, 99), (2, 1)], @@ -448,7 +446,7 @@ mod tests { #[test] fn genesis_config_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_eq!(Treasury::pot(), 0); assert_eq!(Treasury::proposal_count(), 0); }); @@ -456,7 +454,7 @@ mod tests { #[test] fn minting_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { // Check that accumulate works when we have Some value in Dummy already. Treasury::on_dilution(100, 100); assert_eq!(Treasury::pot(), 100); @@ -467,7 +465,7 @@ mod tests { fn minting_works_2() { let tests = [(1, 10), (1, 20), (40, 130), (2, 66), (2, 67), (2, 100), (2, 101), (2, 134)]; for &(minted, portion) in &tests { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { let init_total_issuance = Balances::total_issuance(); Treasury::on_dilution(minted, portion); @@ -491,7 +489,7 @@ mod tests { #[test] fn spend_proposal_takes_min_deposit() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_ok!(Treasury::propose_spend(Origin::signed(0), 1, 3)); assert_eq!(Balances::free_balance(&0), 99); assert_eq!(Balances::reserved_balance(&0), 1); @@ -500,7 +498,7 @@ mod tests { #[test] fn spend_proposal_takes_proportional_deposit() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3)); assert_eq!(Balances::free_balance(&0), 95); assert_eq!(Balances::reserved_balance(&0), 5); @@ -509,14 +507,14 @@ mod tests { #[test] fn spend_proposal_fails_when_proposer_poor() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_noop!(Treasury::propose_spend(Origin::signed(2), 100, 3), "Proposer's balance too low"); }); } #[test] fn accepted_spend_proposal_ignored_outside_spend_period() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { Treasury::on_dilution(100, 100); assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3)); @@ -530,7 +528,7 @@ mod tests { #[test] fn unused_pot_should_diminish() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { let init_total_issuance = Balances::total_issuance(); Treasury::on_dilution(100, 100); assert_eq!(Balances::total_issuance(), init_total_issuance + 100); @@ -543,7 +541,7 @@ mod tests { #[test] fn rejected_spend_proposal_ignored_on_spend_period() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { Treasury::on_dilution(100, 100); assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3)); @@ -557,7 +555,7 @@ mod tests { #[test] fn reject_already_rejected_spend_proposal_fails() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { Treasury::on_dilution(100, 100); assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3)); @@ -568,21 +566,21 @@ mod tests { #[test] fn reject_non_existant_spend_proposal_fails() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_noop!(Treasury::reject_proposal(Origin::ROOT, 0), "No proposal at that index"); }); } #[test] fn accept_non_existant_spend_proposal_fails() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_noop!(Treasury::approve_proposal(Origin::ROOT, 0), "No proposal at that index"); }); } #[test] fn accept_already_rejected_spend_proposal_fails() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { Treasury::on_dilution(100, 100); assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3)); @@ -593,7 +591,7 @@ mod tests { #[test] fn accepted_spend_proposal_enacted_on_spend_period() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { Treasury::on_dilution(100, 100); assert_eq!(Treasury::pot(), 100); @@ -608,7 +606,7 @@ mod tests { #[test] fn pot_underflow_should_not_diminish() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { Treasury::on_dilution(100, 100); assert_ok!(Treasury::propose_spend(Origin::signed(0), 150, 3)); diff --git a/substrate/srml/utility/src/lib.rs b/substrate/srml/utility/src/lib.rs index c0b1954da9..a9009a3a7e 100644 --- a/substrate/srml/utility/src/lib.rs +++ b/substrate/srml/utility/src/lib.rs @@ -64,10 +64,10 @@ mod tests { use super::*; use support::{assert_ok, assert_noop, impl_outer_origin, parameter_types, impl_outer_dispatch}; - use runtime_io::with_externalities; - use primitives::{H256, Blake2Hasher}; + use primitives::H256; use sr_primitives::{ - Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header + Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header, + set_and_run_with_externalities, }; impl_outer_origin! { @@ -139,7 +139,7 @@ mod tests { type Balances = balances::Module; type Utility = Module; - fn new_test_ext() -> runtime_io::TestExternalities { + fn new_test_ext() -> runtime_io::TestExternalities { let mut t = system::GenesisConfig::default().build_storage::().unwrap(); balances::GenesisConfig:: { balances: vec![(1, 10), (2, 0)], @@ -150,7 +150,7 @@ mod tests { #[test] fn batch_works() { - with_externalities(&mut new_test_ext(), || { + set_and_run_with_externalities(&mut new_test_ext(), || { assert_eq!(Balances::free_balance(1), 10); assert_eq!(Balances::free_balance(2), 0); assert_noop!(Utility::batch(Origin::signed(1), vec![