diff --git a/Cargo.lock b/Cargo.lock index 3145d736f8e2f..4928873566627 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8438,7 +8438,6 @@ dependencies = [ "sp-keystore", "sp-runtime", "substrate-test-runtime-client", - "tempfile", "thiserror", "tokio", ] diff --git a/bin/node-template/node/src/service.rs b/bin/node-template/node/src/service.rs index 40ad80c7b3b79..dfbb5e96354e4 100644 --- a/bin/node-template/node/src/service.rs +++ b/bin/node-template/node/src/service.rs @@ -5,7 +5,6 @@ use sc_client_api::BlockBackend; use sc_consensus_aura::{ImportQueueParams, SlotProportion, StartAuraParams}; use sc_consensus_grandpa::SharedVoterState; pub use sc_executor::NativeElseWasmExecutor; -use sc_keystore::LocalKeystore; use sc_service::{error::Error as ServiceError, Configuration, TaskManager, WarpSyncParams}; use sc_telemetry::{Telemetry, TelemetryWorker}; use sp_consensus_aura::sr25519::AuthorityPair as AuraPair; @@ -58,10 +57,6 @@ pub fn new_partial( >, ServiceError, > { - if config.keystore_remote.is_some() { - return Err(ServiceError::Other("Remote Keystores are not supported.".into())) - } - let telemetry = config .telemetry_endpoints .clone() @@ -147,13 +142,6 @@ pub fn new_partial( }) } -fn remote_keystore(_url: &String) -> Result, &'static str> { - // FIXME: here would the concrete keystore be built, - // must return a concrete type (NOT `LocalKeystore`) that - // implements `Keystore` - Err("Remote Keystore not supported.") -} - /// Builds a new service for a full client. pub fn new_full(mut config: Configuration) -> Result { let sc_service::PartialComponents { @@ -161,22 +149,12 @@ pub fn new_full(mut config: Configuration) -> Result backend, mut task_manager, import_queue, - mut keystore_container, + keystore_container, select_chain, transaction_pool, other: (block_import, grandpa_link, mut telemetry), } = new_partial(&config)?; - if let Some(url) = &config.keystore_remote { - match remote_keystore(url) { - Ok(k) => keystore_container.set_remote_keystore(k), - Err(e) => - return Err(ServiceError::Other(format!( - "Error hooking up remote keystore for {}: {}", - url, e - ))), - }; - } let grandpa_protocol_name = sc_consensus_grandpa::protocol_standard_name( &client.block_hash(0).ok().flatten().expect("Genesis block exists; qed"), &config.chain_spec, diff --git a/bin/node/cli/benches/block_production.rs b/bin/node/cli/benches/block_production.rs index f1c65955eaef8..c7f0cd20efd5b 100644 --- a/bin/node/cli/benches/block_production.rs +++ b/bin/node/cli/benches/block_production.rs @@ -69,7 +69,6 @@ fn new_node(tokio_handle: Handle) -> node_cli::service::NewFullBase { transaction_pool: Default::default(), network: network_config, keystore: KeystoreConfig::InMemory, - keystore_remote: Default::default(), database: DatabaseSource::RocksDb { path: root.join("db"), cache_size: 128 }, trie_cache_maximum_size: Some(64 * 1024 * 1024), state_pruning: Some(PruningMode::ArchiveAll), diff --git a/bin/node/cli/benches/transaction_pool.rs b/bin/node/cli/benches/transaction_pool.rs index 72c1c81608e13..7488ec03363e7 100644 --- a/bin/node/cli/benches/transaction_pool.rs +++ b/bin/node/cli/benches/transaction_pool.rs @@ -64,7 +64,6 @@ fn new_node(tokio_handle: Handle) -> node_cli::service::NewFullBase { }, network: network_config, keystore: KeystoreConfig::InMemory, - keystore_remote: Default::default(), database: DatabaseSource::RocksDb { path: root.join("db"), cache_size: 128 }, trie_cache_maximum_size: Some(64 * 1024 * 1024), state_pruning: Some(PruningMode::ArchiveAll), diff --git a/bin/node/cli/src/service.rs b/bin/node/cli/src/service.rs index d32223339dc4a..be8553b7b3a98 100644 --- a/bin/node/cli/src/service.rs +++ b/bin/node/cli/src/service.rs @@ -595,7 +595,7 @@ mod tests { use sp_core::{crypto::Pair as CryptoPair, Public}; use sp_inherents::InherentDataProvider; use sp_keyring::AccountKeyring; - use sp_keystore::{Keystore, KeystorePtr}; + use sp_keystore::KeystorePtr; use sp_runtime::{ generic::{Digest, Era, SignedPayload}, key_types::BABE, @@ -615,12 +615,13 @@ mod tests { sp_tracing::try_init_simple(); let keystore_path = tempfile::tempdir().expect("Creates keystore path"); - let keystore: KeystorePtr = - Arc::new(LocalKeystore::open(keystore_path.path(), None).expect("Creates keystore")); - let alice: sp_consensus_babe::AuthorityId = - Keystore::sr25519_generate_new(&*keystore, BABE, Some("//Alice")) - .expect("Creates authority pair") - .into(); + let keystore: KeystorePtr = LocalKeystore::open(keystore_path.path(), None) + .expect("Creates keystore") + .into(); + let alice: sp_consensus_babe::AuthorityId = keystore + .sr25519_generate_new(BABE, Some("//Alice")) + .expect("Creates authority pair") + .into(); let chain_spec = crate::chain_spec::tests::integration_test_config_with_single_authority(); @@ -735,16 +736,16 @@ mod tests { // sign the pre-sealed hash of the block and then // add it to a digest item. let to_sign = pre_hash.encode(); - let signature = Keystore::sign_with( - &*keystore, - sp_consensus_babe::AuthorityId::ID, - &alice.to_public_crypto_pair(), - &to_sign, - ) - .unwrap() - .unwrap() - .try_into() - .unwrap(); + let signature = keystore + .sign_with( + sp_consensus_babe::AuthorityId::ID, + &alice.to_public_crypto_pair(), + &to_sign, + ) + .unwrap() + .unwrap() + .try_into() + .unwrap(); let item = ::babe_seal(signature); slot += 1; diff --git a/bin/node/executor/tests/submit_transaction.rs b/bin/node/executor/tests/submit_transaction.rs index a3d6681fb6928..9bff415d27e45 100644 --- a/bin/node/executor/tests/submit_transaction.rs +++ b/bin/node/executor/tests/submit_transaction.rs @@ -22,7 +22,6 @@ use sp_application_crypto::AppKey; use sp_core::offchain::{testing::TestTransactionPoolExt, TransactionPoolExt}; use sp_keyring::sr25519::Keyring::Alice; use sp_keystore::{testing::MemoryKeystore, Keystore, KeystoreExt}; -use std::sync::Arc; pub mod common; use self::common::*; @@ -63,25 +62,16 @@ fn should_submit_signed_transaction() { t.register_extension(TransactionPoolExt::new(pool)); let keystore = MemoryKeystore::new(); - Keystore::sr25519_generate_new( - &keystore, - sr25519::AuthorityId::ID, - Some(&format!("{}/hunter1", PHRASE)), - ) - .unwrap(); - Keystore::sr25519_generate_new( - &keystore, - sr25519::AuthorityId::ID, - Some(&format!("{}/hunter2", PHRASE)), - ) - .unwrap(); - Keystore::sr25519_generate_new( - &keystore, - sr25519::AuthorityId::ID, - Some(&format!("{}/hunter3", PHRASE)), - ) - .unwrap(); - t.register_extension(KeystoreExt(Arc::new(keystore))); + keystore + .sr25519_generate_new(sr25519::AuthorityId::ID, Some(&format!("{}/hunter1", PHRASE))) + .unwrap(); + keystore + .sr25519_generate_new(sr25519::AuthorityId::ID, Some(&format!("{}/hunter2", PHRASE))) + .unwrap(); + keystore + .sr25519_generate_new(sr25519::AuthorityId::ID, Some(&format!("{}/hunter3", PHRASE))) + .unwrap(); + t.register_extension(KeystoreExt::new(keystore)); t.execute_with(|| { let results = @@ -106,19 +96,13 @@ fn should_submit_signed_twice_from_the_same_account() { t.register_extension(TransactionPoolExt::new(pool)); let keystore = MemoryKeystore::new(); - Keystore::sr25519_generate_new( - &keystore, - sr25519::AuthorityId::ID, - Some(&format!("{}/hunter1", PHRASE)), - ) - .unwrap(); - Keystore::sr25519_generate_new( - &keystore, - sr25519::AuthorityId::ID, - Some(&format!("{}/hunter2", PHRASE)), - ) - .unwrap(); - t.register_extension(KeystoreExt(Arc::new(keystore))); + keystore + .sr25519_generate_new(sr25519::AuthorityId::ID, Some(&format!("{}/hunter1", PHRASE))) + .unwrap(); + keystore + .sr25519_generate_new(sr25519::AuthorityId::ID, Some(&format!("{}/hunter2", PHRASE))) + .unwrap(); + t.register_extension(KeystoreExt::new(keystore)); t.execute_with(|| { let result = @@ -169,7 +153,7 @@ fn should_submit_signed_twice_from_all_accounts() { keystore .sr25519_generate_new(sr25519::AuthorityId::ID, Some(&format!("{}/hunter2", PHRASE))) .unwrap(); - t.register_extension(KeystoreExt(Arc::new(keystore))); + t.register_extension(KeystoreExt::new(keystore)); t.execute_with(|| { let results = Signer::::all_accounts() @@ -227,13 +211,10 @@ fn submitted_transaction_should_be_valid() { t.register_extension(TransactionPoolExt::new(pool)); let keystore = MemoryKeystore::new(); - Keystore::sr25519_generate_new( - &keystore, - sr25519::AuthorityId::ID, - Some(&format!("{}/hunter1", PHRASE)), - ) - .unwrap(); - t.register_extension(KeystoreExt(Arc::new(keystore))); + keystore + .sr25519_generate_new(sr25519::AuthorityId::ID, Some(&format!("{}/hunter1", PHRASE))) + .unwrap(); + t.register_extension(KeystoreExt::new(keystore)); t.execute_with(|| { let results = diff --git a/bin/utils/chain-spec-builder/src/main.rs b/bin/utils/chain-spec-builder/src/main.rs index f7b7d94c57d1c..f94fca1c1638d 100644 --- a/bin/utils/chain-spec-builder/src/main.rs +++ b/bin/utils/chain-spec-builder/src/main.rs @@ -19,7 +19,6 @@ use std::{ fs, path::{Path, PathBuf}, - sync::Arc, }; use ansi_term::Style; @@ -32,7 +31,7 @@ use sp_core::{ crypto::{ByteArray, Ss58Codec}, sr25519, }; -use sp_keystore::{Keystore, KeystorePtr}; +use sp_keystore::KeystorePtr; /// A utility to easily create a testnet chain spec definition with a given set /// of authorities and endowed accounts and/or generate random accounts. @@ -164,16 +163,17 @@ fn generate_chain_spec( fn generate_authority_keys_and_store(seeds: &[String], keystore_path: &Path) -> Result<(), String> { for (n, seed) in seeds.iter().enumerate() { - let keystore: KeystorePtr = Arc::new( + let keystore: KeystorePtr = LocalKeystore::open(keystore_path.join(format!("auth-{}", n)), None) - .map_err(|err| err.to_string())?, - ); + .map_err(|err| err.to_string())? + .into(); let (_, _, grandpa, babe, im_online, authority_discovery) = chain_spec::authority_keys_from_seed(seed); let insert_key = |key_type, public| { - Keystore::insert(&*keystore, key_type, &format!("//{}", seed), public) + keystore + .insert(key_type, &format!("//{}", seed), public) .map_err(|_| format!("Failed to insert key: {}", grandpa)) }; diff --git a/client/authority-discovery/src/worker/tests.rs b/client/authority-discovery/src/worker/tests.rs index c918d79932624..49055fec51611 100644 --- a/client/authority-discovery/src/worker/tests.rs +++ b/client/authority-discovery/src/worker/tests.rs @@ -697,7 +697,7 @@ fn addresses_to_publish_adds_p2p() { Arc::new(TestApi { authorities: vec![] }), network.clone(), Box::pin(dht_event_rx), - Role::PublishAndDiscover(Arc::new(MemoryKeystore::new())), + Role::PublishAndDiscover(MemoryKeystore::new().into()), Some(prometheus_endpoint::Registry::new()), Default::default(), ); @@ -731,7 +731,7 @@ fn addresses_to_publish_respects_existing_p2p_protocol() { Arc::new(TestApi { authorities: vec![] }), network.clone(), Box::pin(dht_event_rx), - Role::PublishAndDiscover(Arc::new(MemoryKeystore::new())), + Role::PublishAndDiscover(MemoryKeystore::new().into()), Some(prometheus_endpoint::Registry::new()), Default::default(), ); diff --git a/client/cli/src/commands/insert_key.rs b/client/cli/src/commands/insert_key.rs index b02c0181d43a2..e80058d44a5af 100644 --- a/client/cli/src/commands/insert_key.rs +++ b/client/cli/src/commands/insert_key.rs @@ -24,8 +24,7 @@ use clap::Parser; use sc_keystore::LocalKeystore; use sc_service::config::{BasePath, KeystoreConfig}; use sp_core::crypto::{KeyTypeId, SecretString}; -use sp_keystore::{Keystore, KeystorePtr}; -use std::sync::Arc; +use sp_keystore::KeystorePtr; /// The `insert` command #[derive(Debug, Clone, Parser)] @@ -67,9 +66,9 @@ impl InsertKeyCmd { let config_dir = base_path.config_dir(chain_spec.id()); let (keystore, public) = match self.keystore_params.keystore_config(&config_dir)? { - (_, KeystoreConfig::Path { path, password }) => { + KeystoreConfig::Path { path, password } => { let public = with_crypto_scheme!(self.scheme, to_vec(&suri, password.clone()))?; - let keystore: KeystorePtr = Arc::new(LocalKeystore::open(path, password)?); + let keystore: KeystorePtr = LocalKeystore::open(path, password)?.into(); (keystore, public) }, _ => unreachable!("keystore_config always returns path and password; qed"), @@ -78,7 +77,8 @@ impl InsertKeyCmd { let key_type = KeyTypeId::try_from(self.key_type.as_str()).map_err(|_| Error::KeyTypeInvalid)?; - Keystore::insert(&*keystore, key_type, &suri, &public[..]) + keystore + .insert(key_type, &suri, &public[..]) .map_err(|_| Error::KeystoreOperation)?; Ok(()) @@ -95,6 +95,7 @@ mod tests { use super::*; use sc_service::{ChainSpec, ChainType, GenericChainSpec, NoExtension}; use sp_core::{sr25519::Pair, ByteArray, Pair as _}; + use sp_keystore::Keystore; use tempfile::TempDir; struct Cli; diff --git a/client/cli/src/config.rs b/client/cli/src/config.rs index 5fedcf99a12ef..063b2c39839f4 100644 --- a/client/cli/src/config.rs +++ b/client/cli/src/config.rs @@ -185,10 +185,10 @@ pub trait CliConfiguration: Sized { /// /// By default this is retrieved from `KeystoreParams` if it is available. Otherwise it uses /// `KeystoreConfig::InMemory`. - fn keystore_config(&self, config_dir: &PathBuf) -> Result<(Option, KeystoreConfig)> { + fn keystore_config(&self, config_dir: &PathBuf) -> Result { self.keystore_params() .map(|x| x.keystore_config(config_dir)) - .unwrap_or_else(|| Ok((None, KeystoreConfig::InMemory))) + .unwrap_or_else(|| Ok(KeystoreConfig::InMemory)) } /// Get the database cache size. @@ -505,7 +505,7 @@ pub trait CliConfiguration: Sized { let role = self.role(is_dev)?; let max_runtime_instances = self.max_runtime_instances()?.unwrap_or(8); let is_validator = role.is_authority(); - let (keystore_remote, keystore) = self.keystore_config(&config_dir)?; + let keystore = self.keystore_config(&config_dir)?; let telemetry_endpoints = self.telemetry_endpoints(&chain_spec)?; let runtime_cache_size = self.runtime_cache_size()?; @@ -524,7 +524,6 @@ pub trait CliConfiguration: Sized { node_key, DCV::p2p_listen_port(), )?, - keystore_remote, keystore, database: self.database_config(&config_dir, database_cache_size, database)?, trie_cache_maximum_size: self.trie_cache_maximum_size()?, diff --git a/client/cli/src/params/keystore_params.rs b/client/cli/src/params/keystore_params.rs index e6e6fd9eb47ed..8933110c400b7 100644 --- a/client/cli/src/params/keystore_params.rs +++ b/client/cli/src/params/keystore_params.rs @@ -68,9 +68,7 @@ pub fn secret_string_from_str(s: &str) -> std::result::Result Result<(Option, KeystoreConfig)> { + pub fn keystore_config(&self, config_dir: &Path) -> Result { let password = if self.password_interactive { Some(SecretString::new(input_keystore_password()?)) } else if let Some(ref file) = self.password_filename { @@ -85,7 +83,7 @@ impl KeystoreParams { .clone() .unwrap_or_else(|| config_dir.join(DEFAULT_KEYSTORE_CONFIG_PATH)); - Ok((self.keystore_uri.clone(), KeystoreConfig::Path { path, password })) + Ok(KeystoreConfig::Path { path, password }) } /// helper method to fetch password from `KeyParams` or read from stdin diff --git a/client/cli/src/runner.rs b/client/cli/src/runner.rs index 47adfcf89fe99..3d216aef4a75c 100644 --- a/client/cli/src/runner.rs +++ b/client/cli/src/runner.rs @@ -345,7 +345,6 @@ mod tests { transaction_pool: Default::default(), network: NetworkConfiguration::new_memory(), keystore: sc_service::config::KeystoreConfig::InMemory, - keystore_remote: None, database: sc_client_db::DatabaseSource::ParityDb { path: PathBuf::from("db") }, trie_cache_maximum_size: None, state_pruning: None, diff --git a/client/consensus/aura/src/lib.rs b/client/consensus/aura/src/lib.rs index 8cdad148d6ef4..d06a6016a2297 100644 --- a/client/consensus/aura/src/lib.rs +++ b/client/consensus/aura/src/lib.rs @@ -51,7 +51,7 @@ use sp_consensus::{BlockOrigin, Environment, Error as ConsensusError, Proposer, use sp_consensus_slots::Slot; use sp_core::crypto::{ByteArray, Pair, Public}; use sp_inherents::CreateInherentDataProviders; -use sp_keystore::{Keystore, KeystorePtr}; +use sp_keystore::KeystorePtr; use sp_runtime::{ traits::{Block as BlockT, Header, Member, NumberFor, Zero}, DigestItem, @@ -418,10 +418,10 @@ where ) -> Option { let expected_author = slot_author::

(slot, epoch_data); expected_author.and_then(|p| { - if Keystore::has_keys( - &*self.keystore, - &[(p.to_raw_vec(), sp_application_crypto::key_types::AURA)], - ) { + if self + .keystore + .has_keys(&[(p.to_raw_vec(), sp_application_crypto::key_types::AURA)]) + { Some(p.clone()) } else { None @@ -449,19 +449,16 @@ where // add it to a digest item. let public_type_pair = public.to_public_crypto_pair(); let public = public.to_raw_vec(); - let signature = Keystore::sign_with( - &*self.keystore, - as AppKey>::ID, - &public_type_pair, - header_hash.as_ref(), - ) - .map_err(|e| sp_consensus::Error::CannotSign(public.clone(), e.to_string()))? - .ok_or_else(|| { - sp_consensus::Error::CannotSign( - public.clone(), - "Could not find key in keystore.".into(), - ) - })?; + let signature = self + .keystore + .sign_with( as AppKey>::ID, &public_type_pair, header_hash.as_ref()) + .map_err(|e| sp_consensus::Error::CannotSign(public.clone(), e.to_string()))? + .ok_or_else(|| { + sp_consensus::Error::CannotSign( + public.clone(), + "Could not find key in keystore.".into(), + ) + })?; let signature = signature .clone() .try_into() @@ -648,6 +645,7 @@ mod tests { use sp_consensus_aura::sr25519::AuthorityPair; use sp_inherents::InherentData; use sp_keyring::sr25519::Keyring; + use sp_keystore::Keystore; use sp_runtime::{ traits::{Block as BlockT, Header as _}, Digest, @@ -798,7 +796,8 @@ mod tests { LocalKeystore::open(keystore_path.path(), None).expect("Creates keystore."), ); - Keystore::sr25519_generate_new(&*keystore, AURA, Some(&key.to_seed())) + keystore + .sr25519_generate_new(AURA, Some(&key.to_seed())) .expect("Creates authority key"); keystore_paths.push(keystore_path); @@ -883,7 +882,8 @@ mod tests { let keystore_path = tempfile::tempdir().expect("Creates keystore path"); let keystore = LocalKeystore::open(keystore_path.path(), None).expect("Creates keystore."); - let public = Keystore::sr25519_generate_new(&keystore, AuthorityPair::ID, None) + let public = keystore + .sr25519_generate_new(AuthorityPair::ID, None) .expect("Key should be created"); authorities.push(public.into()); @@ -933,12 +933,9 @@ mod tests { let keystore_path = tempfile::tempdir().expect("Creates keystore path"); let keystore = LocalKeystore::open(keystore_path.path(), None).expect("Creates keystore."); - Keystore::sr25519_generate_new( - &keystore, - AuthorityPair::ID, - Some(&Keyring::Alice.to_seed()), - ) - .expect("Key should be created"); + keystore + .sr25519_generate_new(AuthorityPair::ID, Some(&Keyring::Alice.to_seed())) + .expect("Key should be created"); let net = Arc::new(Mutex::new(net)); diff --git a/client/consensus/babe/rpc/Cargo.toml b/client/consensus/babe/rpc/Cargo.toml index 4f5aaf85494b9..f81a14a97c758 100644 --- a/client/consensus/babe/rpc/Cargo.toml +++ b/client/consensus/babe/rpc/Cargo.toml @@ -31,7 +31,6 @@ sp-runtime = { version = "7.0.0", path = "../../../../primitives/runtime" } [dev-dependencies] serde_json = "1.0.85" -tempfile = "3.1.0" tokio = "1.22.0" sc-consensus = { version = "0.10.0-dev", path = "../../../consensus/common" } sc-keystore = { version = "4.0.0-dev", path = "../../../keystore" } diff --git a/client/consensus/babe/rpc/src/lib.rs b/client/consensus/babe/rpc/src/lib.rs index bc4d1c17eb3f1..005d84938e28e 100644 --- a/client/consensus/babe/rpc/src/lib.rs +++ b/client/consensus/babe/rpc/src/lib.rs @@ -37,7 +37,7 @@ use sp_consensus_babe::{ digests::PreDigest, AuthorityId, BabeApi as BabeRuntimeApi, BabeConfiguration, }; use sp_core::crypto::ByteArray; -use sp_keystore::{Keystore, KeystorePtr}; +use sp_keystore::KeystorePtr; use sp_runtime::traits::{Block as BlockT, Header as _}; use std::{collections::HashMap, sync::Arc}; @@ -117,7 +117,7 @@ where .iter() .enumerate() .filter_map(|(i, a)| { - if Keystore::has_keys(&*self.keystore, &[(a.0.to_raw_vec(), AuthorityId::ID)]) { + if self.keystore.has_keys(&[(a.0.to_raw_vec(), AuthorityId::ID)]) { Some((a.0.clone(), i)) } else { None @@ -210,30 +210,21 @@ where #[cfg(test)] mod tests { use super::*; - use sc_keystore::LocalKeystore; - use sp_application_crypto::AppPair; + use sc_consensus_babe::block_import; use sp_core::crypto::key_types::BABE; use sp_keyring::Sr25519Keyring; - use sp_keystore::{Keystore, KeystorePtr}; + use sp_keystore::{testing::MemoryKeystore, Keystore}; use substrate_test_runtime_client::{ runtime::Block, Backend, DefaultTestClientBuilderExt, TestClient, TestClientBuilder, TestClientBuilderExt, }; - use sc_consensus_babe::{block_import, AuthorityPair}; - use std::sync::Arc; - - /// creates keystore backed by a temp file - fn create_temp_keystore( - authority: Sr25519Keyring, - ) -> (KeystorePtr, tempfile::TempDir) { - let keystore_path = tempfile::tempdir().expect("Creates keystore path"); - let keystore = - Arc::new(LocalKeystore::open(keystore_path.path(), None).expect("Creates keystore")); - Keystore::sr25519_generate_new(&*keystore, BABE, Some(&authority.to_seed())) + fn create_keystore(authority: Sr25519Keyring) -> KeystorePtr { + let keystore = MemoryKeystore::new(); + keystore + .sr25519_generate_new(BABE, Some(&authority.to_seed())) .expect("Creates authority key"); - - (keystore, keystore_path) + keystore.into() } fn test_babe_rpc_module( @@ -247,7 +238,7 @@ mod tests { .expect("can initialize block-import"); let epoch_changes = link.epoch_changes().clone(); - let keystore = create_temp_keystore::(Sr25519Keyring::Alice).0; + let keystore = create_keystore(Sr25519Keyring::Alice); Babe::new(client.clone(), epoch_changes, keystore, config, longest_chain, deny_unsafe) } diff --git a/client/consensus/babe/src/authorship.rs b/client/consensus/babe/src/authorship.rs index 956e886d1254c..c4b43b0d074b9 100644 --- a/client/consensus/babe/src/authorship.rs +++ b/client/consensus/babe/src/authorship.rs @@ -29,7 +29,7 @@ use sp_consensus_babe::{ }; use sp_consensus_vrf::schnorrkel::{VRFOutput, VRFProof}; use sp_core::{blake2_256, crypto::ByteArray, U256}; -use sp_keystore::{Keystore, KeystorePtr}; +use sp_keystore::KeystorePtr; /// Calculates the primary selection threshold for a given authority, taking /// into account `c` (`1 - c` represents the probability of a slot being empty). @@ -153,8 +153,7 @@ fn claim_secondary_slot( if authority_id == expected_author { let pre_digest = if author_secondary_vrf { let transcript_data = make_transcript_data(randomness, slot, epoch_index); - let result = Keystore::sr25519_vrf_sign( - &**keystore, + let result = keystore.sr25519_vrf_sign( AuthorityId::ID, authority_id.as_ref(), transcript_data, @@ -169,10 +168,7 @@ fn claim_secondary_slot( } else { None } - } else if Keystore::has_keys( - &**keystore, - &[(authority_id.to_raw_vec(), AuthorityId::ID)], - ) { + } else if keystore.has_keys(&[(authority_id.to_raw_vec(), AuthorityId::ID)]) { Some(PreDigest::SecondaryPlain(SecondaryPlainPreDigest { slot, authority_index: *authority_index as u32, @@ -254,12 +250,8 @@ fn claim_primary_slot( for (authority_id, authority_index) in keys { let transcript = make_transcript(randomness, slot, epoch_index); let transcript_data = make_transcript_data(randomness, slot, epoch_index); - let result = Keystore::sr25519_vrf_sign( - &**keystore, - AuthorityId::ID, - authority_id.as_ref(), - transcript_data, - ); + let result = + keystore.sr25519_vrf_sign(AuthorityId::ID, authority_id.as_ref(), transcript_data); if let Ok(Some(signature)) = result { let public = PublicKey::from_bytes(&authority_id.to_raw_vec()).ok()?; let inout = match signature.output.attach_input_hash(&public, transcript) { @@ -287,20 +279,16 @@ fn claim_primary_slot( #[cfg(test)] mod tests { use super::*; - use sc_keystore::LocalKeystore; use sp_consensus_babe::{AllowedSlots, AuthorityId, BabeEpochConfiguration}; use sp_core::{crypto::Pair as _, sr25519::Pair}; - use std::sync::Arc; + use sp_keystore::testing::MemoryKeystore; #[test] fn claim_secondary_plain_slot_works() { - let keystore: KeystorePtr = Arc::new(LocalKeystore::in_memory()); - let valid_public_key = Keystore::sr25519_generate_new( - &*keystore, - AuthorityId::ID, - Some(sp_core::crypto::DEV_PHRASE), - ) - .unwrap(); + let keystore: KeystorePtr = MemoryKeystore::new().into(); + let valid_public_key = keystore + .sr25519_generate_new(AuthorityId::ID, Some(sp_core::crypto::DEV_PHRASE)) + .unwrap(); let authorities = vec![ (AuthorityId::from(Pair::generate().0.public()), 5), diff --git a/client/consensus/babe/src/lib.rs b/client/consensus/babe/src/lib.rs index 621aac391630b..e2c2793b11c9d 100644 --- a/client/consensus/babe/src/lib.rs +++ b/client/consensus/babe/src/lib.rs @@ -119,7 +119,7 @@ use sp_consensus_babe::inherents::BabeInherentData; use sp_consensus_slots::Slot; use sp_core::{crypto::ByteArray, ExecutionContext}; use sp_inherents::{CreateInherentDataProviders, InherentData, InherentDataProvider}; -use sp_keystore::{Keystore, KeystorePtr}; +use sp_keystore::KeystorePtr; use sp_runtime::{ generic::OpaqueDigestItemId, traits::{Block as BlockT, Header, NumberFor, SaturatedConversion, Zero}, @@ -834,19 +834,16 @@ where // add it to a digest item. let public_type_pair = public.clone().into(); let public = public.to_raw_vec(); - let signature = Keystore::sign_with( - &*self.keystore, - ::ID, - &public_type_pair, - header_hash.as_ref(), - ) - .map_err(|e| sp_consensus::Error::CannotSign(public.clone(), e.to_string()))? - .ok_or_else(|| { - sp_consensus::Error::CannotSign( - public.clone(), - "Could not find key in keystore.".into(), - ) - })?; + let signature = self + .keystore + .sign_with(::ID, &public_type_pair, header_hash.as_ref()) + .map_err(|e| sp_consensus::Error::CannotSign(public.clone(), e.to_string()))? + .ok_or_else(|| { + sp_consensus::Error::CannotSign( + public.clone(), + "Could not find key in keystore.".into(), + ) + })?; let signature: AuthoritySignature = signature .clone() .try_into() diff --git a/client/consensus/babe/src/tests.rs b/client/consensus/babe/src/tests.rs index 4ac15bf2634d7..7f8448d91991c 100644 --- a/client/consensus/babe/src/tests.rs +++ b/client/consensus/babe/src/tests.rs @@ -369,10 +369,11 @@ async fn rejects_empty_block() { } fn create_keystore(authority: Sr25519Keyring) -> KeystorePtr { - let keystore = Arc::new(MemoryKeystore::new()); - Keystore::sr25519_generate_new(&*keystore, BABE, Some(&authority.to_seed())) - .expect("Generates authority key"); + let keystore = MemoryKeystore::new(); keystore + .sr25519_generate_new(BABE, Some(&authority.to_seed())) + .expect("Generates authority key"); + keystore.into() } async fn run_one_test(mutator: impl Fn(&mut TestHeader, Stage) + Send + Sync + 'static) { @@ -637,7 +638,8 @@ fn claim_vrf_check() { v => panic!("Unexpected pre-digest variant {:?}", v), }; let transcript = make_transcript_data(&epoch.randomness.clone(), 0.into(), epoch.epoch_index); - let sign = Keystore::sr25519_vrf_sign(&*keystore, AuthorityId::ID, &public, transcript) + let sign = keystore + .sr25519_vrf_sign(AuthorityId::ID, &public, transcript) .unwrap() .unwrap(); assert_eq!(pre_digest.vrf_output, VRFOutput(sign.output)); @@ -648,7 +650,8 @@ fn claim_vrf_check() { v => panic!("Unexpected pre-digest variant {:?}", v), }; let transcript = make_transcript_data(&epoch.randomness.clone(), 1.into(), epoch.epoch_index); - let sign = Keystore::sr25519_vrf_sign(&*keystore, AuthorityId::ID, &public, transcript) + let sign = keystore + .sr25519_vrf_sign(AuthorityId::ID, &public, transcript) .unwrap() .unwrap(); assert_eq!(pre_digest.vrf_output, VRFOutput(sign.output)); @@ -661,7 +664,8 @@ fn claim_vrf_check() { }; let fixed_epoch = epoch.clone_for_slot(slot); let transcript = make_transcript_data(&epoch.randomness.clone(), slot, fixed_epoch.epoch_index); - let sign = Keystore::sr25519_vrf_sign(&*keystore, AuthorityId::ID, &public, transcript) + let sign = keystore + .sr25519_vrf_sign(AuthorityId::ID, &public, transcript) .unwrap() .unwrap(); assert_eq!(fixed_epoch.epoch_index, 11); @@ -675,7 +679,8 @@ fn claim_vrf_check() { }; let fixed_epoch = epoch.clone_for_slot(slot); let transcript = make_transcript_data(&epoch.randomness.clone(), slot, fixed_epoch.epoch_index); - let sign = Keystore::sr25519_vrf_sign(&*keystore, AuthorityId::ID, &public, transcript) + let sign = keystore + .sr25519_vrf_sign(AuthorityId::ID, &public, transcript) .unwrap() .unwrap(); assert_eq!(fixed_epoch.epoch_index, 11); diff --git a/client/consensus/beefy/src/communication/gossip.rs b/client/consensus/beefy/src/communication/gossip.rs index 4bbd7a7f68d5c..2b5e772c0578f 100644 --- a/client/consensus/beefy/src/communication/gossip.rs +++ b/client/consensus/beefy/src/communication/gossip.rs @@ -243,17 +243,14 @@ where #[cfg(test)] mod tests { - use sc_keystore::LocalKeystore; - use sc_network_test::Block; - use sp_keystore::{Keystore, KeystorePtr}; - + use super::*; use crate::keystore::BeefyKeystore; + use sc_network_test::Block; use sp_consensus_beefy::{ crypto::Signature, known_payloads, Commitment, Keyring, MmrRootHash, Payload, VoteMessage, KEY_TYPE, }; - - use super::*; + use sp_keystore::{testing::MemoryKeystore, Keystore}; #[test] fn known_votes_insert_remove() { @@ -306,10 +303,9 @@ mod tests { } fn sign_commitment(who: &Keyring, commitment: &Commitment) -> Signature { - let store: KeystorePtr = std::sync::Arc::new(LocalKeystore::in_memory()); - Keystore::ecdsa_generate_new(&*store, KEY_TYPE, Some(&who.to_seed())).unwrap(); - let beefy_keystore: BeefyKeystore = Some(store).into(); - + let store = MemoryKeystore::new(); + store.ecdsa_generate_new(KEY_TYPE, Some(&who.to_seed())).unwrap(); + let beefy_keystore: BeefyKeystore = Some(store.into()).into(); beefy_keystore.sign(&who.public(), &commitment.encode()).unwrap() } diff --git a/client/consensus/beefy/src/keystore.rs b/client/consensus/beefy/src/keystore.rs index 596e8f2eb9c6d..795d4cc8ade10 100644 --- a/client/consensus/beefy/src/keystore.rs +++ b/client/consensus/beefy/src/keystore.rs @@ -18,7 +18,7 @@ use sp_application_crypto::RuntimeAppPublic; use sp_core::keccak_256; -use sp_keystore::{Keystore, KeystorePtr}; +use sp_keystore::KeystorePtr; use log::warn; @@ -50,7 +50,7 @@ impl BeefyKeystore { // we do check for multiple private keys as a key store sanity check. let public: Vec = keys .iter() - .filter(|k| Keystore::has_keys(&*store, &[(k.to_raw_vec(), KEY_TYPE)])) + .filter(|k| store.has_keys(&[(k.to_raw_vec(), KEY_TYPE)])) .cloned() .collect(); @@ -77,7 +77,8 @@ impl BeefyKeystore { let msg = keccak_256(message); let public = public.as_ref(); - let sig = Keystore::ecdsa_sign_prehashed(&*store, KEY_TYPE, public, &msg) + let sig = store + .ecdsa_sign_prehashed(KEY_TYPE, public, &msg) .map_err(|e| error::Error::Keystore(e.to_string()))? .ok_or_else(|| error::Error::Signature("ecdsa_sign_prehashed() failed".to_string()))?; @@ -94,10 +95,8 @@ impl BeefyKeystore { pub fn public_keys(&self) -> Result, error::Error> { let store = self.0.clone().ok_or_else(|| error::Error::Keystore("no Keystore".into()))?; - let pk: Vec = Keystore::ecdsa_public_keys(&*store, KEY_TYPE) - .drain(..) - .map(Public::from) - .collect(); + let pk: Vec = + store.ecdsa_public_keys(KEY_TYPE).drain(..).map(Public::from).collect(); Ok(pk) } @@ -118,18 +117,15 @@ impl From> for BeefyKeystore { #[cfg(test)] pub mod tests { - use std::sync::Arc; - - use sc_keystore::LocalKeystore; - use sp_core::{ecdsa, Pair}; - use sp_consensus_beefy::{crypto, Keyring}; + use sp_core::{ecdsa, Pair}; + use sp_keystore::testing::MemoryKeystore; use super::*; use crate::error::Error; fn keystore() -> KeystorePtr { - Arc::new(LocalKeystore::in_memory()) + MemoryKeystore::new().into() } #[test] @@ -197,11 +193,11 @@ pub mod tests { fn authority_id_works() { let store = keystore(); - let alice: crypto::Public = - Keystore::ecdsa_generate_new(&*store, KEY_TYPE, Some(&Keyring::Alice.to_seed())) - .ok() - .unwrap() - .into(); + let alice: crypto::Public = store + .ecdsa_generate_new(KEY_TYPE, Some(&Keyring::Alice.to_seed())) + .ok() + .unwrap() + .into(); let bob = Keyring::Bob.public(); let charlie = Keyring::Charlie.public(); @@ -223,11 +219,11 @@ pub mod tests { fn sign_works() { let store = keystore(); - let alice: crypto::Public = - Keystore::ecdsa_generate_new(&*store, KEY_TYPE, Some(&Keyring::Alice.to_seed())) - .ok() - .unwrap() - .into(); + let alice: crypto::Public = store + .ecdsa_generate_new(KEY_TYPE, Some(&Keyring::Alice.to_seed())) + .ok() + .unwrap() + .into(); let store: BeefyKeystore = Some(store).into(); @@ -243,9 +239,7 @@ pub mod tests { fn sign_error() { let store = keystore(); - let _ = Keystore::ecdsa_generate_new(&*store, KEY_TYPE, Some(&Keyring::Bob.to_seed())) - .ok() - .unwrap(); + store.ecdsa_generate_new(KEY_TYPE, Some(&Keyring::Bob.to_seed())).ok().unwrap(); let store: BeefyKeystore = Some(store).into(); @@ -274,11 +268,11 @@ pub mod tests { fn verify_works() { let store = keystore(); - let alice: crypto::Public = - Keystore::ecdsa_generate_new(&*store, KEY_TYPE, Some(&Keyring::Alice.to_seed())) - .ok() - .unwrap() - .into(); + let alice: crypto::Public = store + .ecdsa_generate_new(KEY_TYPE, Some(&Keyring::Alice.to_seed())) + .ok() + .unwrap() + .into(); let store: BeefyKeystore = Some(store).into(); @@ -300,9 +294,8 @@ pub mod tests { let store = keystore(); - let add_key = |key_type, seed: Option<&str>| { - Keystore::ecdsa_generate_new(&*store, key_type, seed).unwrap() - }; + let add_key = + |key_type, seed: Option<&str>| store.ecdsa_generate_new(key_type, seed).unwrap(); // test keys let _ = add_key(TEST_TYPE, Some(Keyring::Alice.to_seed().as_str())); diff --git a/client/consensus/beefy/src/tests.rs b/client/consensus/beefy/src/tests.rs index 9a3653f7cc549..0ad5f10886093 100644 --- a/client/consensus/beefy/src/tests.rs +++ b/client/consensus/beefy/src/tests.rs @@ -340,10 +340,11 @@ pub(crate) fn make_beefy_ids(keys: &[BeefyKeyring]) -> Vec { } pub(crate) fn create_beefy_keystore(authority: BeefyKeyring) -> KeystorePtr { - let keystore = Arc::new(MemoryKeystore::new()); - Keystore::ecdsa_generate_new(&*keystore, BeefyKeyType, Some(&authority.to_seed())) - .expect("Creates authority key"); + let keystore = MemoryKeystore::new(); keystore + .ecdsa_generate_new(BeefyKeyType, Some(&authority.to_seed())) + .expect("Creates authority key"); + keystore.into() } async fn voter_init_setup( diff --git a/client/consensus/grandpa/src/lib.rs b/client/consensus/grandpa/src/lib.rs index 6b3730fc7f476..cf98e17920d5d 100644 --- a/client/consensus/grandpa/src/lib.rs +++ b/client/consensus/grandpa/src/lib.rs @@ -79,7 +79,7 @@ use sp_consensus_grandpa::{ AuthorityList, AuthoritySignature, SetId, CLIENT_LOG_TARGET as LOG_TARGET, }; use sp_core::{crypto::ByteArray, traits::CallContext}; -use sp_keystore::{Keystore, KeystorePtr}; +use sp_keystore::KeystorePtr; use sp_runtime::{ generic::BlockId, traits::{Block as BlockT, NumberFor, Zero}, @@ -1141,7 +1141,7 @@ fn local_authority_id( keystore.and_then(|keystore| { voters .iter() - .find(|(p, _)| Keystore::has_keys(&**keystore, &[(p.to_raw_vec(), AuthorityId::ID)])) + .find(|(p, _)| keystore.has_keys(&[(p.to_raw_vec(), AuthorityId::ID)])) .map(|(p, _)| p.clone()) }) } diff --git a/client/consensus/grandpa/src/tests.rs b/client/consensus/grandpa/src/tests.rs index 6f19ca7391e65..7a3f862d3602b 100644 --- a/client/consensus/grandpa/src/tests.rs +++ b/client/consensus/grandpa/src/tests.rs @@ -281,10 +281,11 @@ fn make_ids(keys: &[Ed25519Keyring]) -> AuthorityList { } fn create_keystore(authority: Ed25519Keyring) -> KeystorePtr { - let keystore = Arc::new(MemoryKeystore::new()); - Keystore::ed25519_generate_new(&*keystore, GRANDPA, Some(&authority.to_seed())) - .expect("Creates authority key"); + let keystore = MemoryKeystore::new(); keystore + .ed25519_generate_new(GRANDPA, Some(&authority.to_seed())) + .expect("Creates authority key"); + keystore.into() } async fn run_until_complete(future: impl Future + Unpin, net: &Arc>) { diff --git a/client/keystore/src/local.rs b/client/keystore/src/local.rs index 18ee58b8719b9..a4af7811721ce 100644 --- a/client/keystore/src/local.rs +++ b/client/keystore/src/local.rs @@ -135,6 +135,9 @@ impl Keystore for LocalKeystore { .unwrap_or_default() } + /// Generate a new pair compatible with the 'ed25519' signature scheme. + /// + /// If the `[seed]` is `Some` then the key will be ephemeral and stored in memory. fn sr25519_generate_new( &self, id: KeyTypeId, @@ -162,6 +165,9 @@ impl Keystore for LocalKeystore { .unwrap_or_default() } + /// Generate a new pair compatible with the 'sr25519' signature scheme. + /// + /// If the `[seed]` is `Some` then the key will be ephemeral and stored in memory. fn ed25519_generate_new( &self, id: KeyTypeId, @@ -189,6 +195,9 @@ impl Keystore for LocalKeystore { .unwrap_or_default() } + /// Generate a new pair compatible with the 'ecdsa' signature scheme. + /// + /// If the `[seed]` is `Some` then the key will be ephemeral and stored in memory. fn ecdsa_generate_new( &self, id: KeyTypeId, @@ -504,17 +513,14 @@ mod tests { let key: ed25519::AppPair = store.0.write().generate().unwrap(); let key2 = ed25519::Pair::generate().0; - assert!(!Keystore::has_keys(&store, &[(key2.public().to_vec(), ed25519::AppPublic::ID)])); + assert!(!store.has_keys(&[(key2.public().to_vec(), ed25519::AppPublic::ID)])); - assert!(!Keystore::has_keys( - &store, - &[ - (key2.public().to_vec(), ed25519::AppPublic::ID), - (key.public().to_raw_vec(), ed25519::AppPublic::ID), - ], - )); + assert!(!store.has_keys(&[ + (key2.public().to_vec(), ed25519::AppPublic::ID), + (key.public().to_raw_vec(), ed25519::AppPublic::ID), + ],)); - assert!(Keystore::has_keys(&store, &[(key.public().to_raw_vec(), ed25519::AppPublic::ID)])); + assert!(store.has_keys(&[(key.public().to_raw_vec(), ed25519::AppPublic::ID)])); } #[test] @@ -626,31 +632,30 @@ mod tests { let file_name = temp_dir.path().join(array_bytes::bytes2hex("", &SR25519.0[..2])); fs::write(file_name, "test").expect("Invalid file is written"); - assert!(Keystore::sr25519_public_keys(&store, SR25519).is_empty()); + assert!(store.sr25519_public_keys(SR25519).is_empty()); } #[test] fn generate_with_seed_is_not_stored() { let temp_dir = TempDir::new().unwrap(); let store = LocalKeystore::open(temp_dir.path(), None).unwrap(); - let _alice_tmp_key = - Keystore::sr25519_generate_new(&store, TEST_KEY_TYPE, Some("//Alice")).unwrap(); + let _alice_tmp_key = store.sr25519_generate_new(TEST_KEY_TYPE, Some("//Alice")).unwrap(); - assert_eq!(Keystore::sr25519_public_keys(&store, TEST_KEY_TYPE).len(), 1); + assert_eq!(store.sr25519_public_keys(TEST_KEY_TYPE).len(), 1); drop(store); let store = LocalKeystore::open(temp_dir.path(), None).unwrap(); - assert_eq!(Keystore::sr25519_public_keys(&store, TEST_KEY_TYPE).len(), 0); + assert_eq!(store.sr25519_public_keys(TEST_KEY_TYPE).len(), 0); } #[test] fn generate_can_be_fetched_in_memory() { let store = LocalKeystore::in_memory(); - Keystore::sr25519_generate_new(&store, TEST_KEY_TYPE, Some("//Alice")).unwrap(); + store.sr25519_generate_new(TEST_KEY_TYPE, Some("//Alice")).unwrap(); - assert_eq!(Keystore::sr25519_public_keys(&store, TEST_KEY_TYPE).len(), 1); - Keystore::sr25519_generate_new(&store, TEST_KEY_TYPE, None).unwrap(); - assert_eq!(Keystore::sr25519_public_keys(&store, TEST_KEY_TYPE).len(), 2); + assert_eq!(store.sr25519_public_keys(TEST_KEY_TYPE).len(), 1); + store.sr25519_generate_new(TEST_KEY_TYPE, None).unwrap(); + assert_eq!(store.sr25519_public_keys(TEST_KEY_TYPE).len(), 2); } #[test] @@ -661,7 +666,7 @@ mod tests { let temp_dir = TempDir::new().unwrap(); let store = LocalKeystore::open(temp_dir.path(), None).unwrap(); - let public = Keystore::sr25519_generate_new(&store, TEST_KEY_TYPE, None).unwrap(); + let public = store.sr25519_generate_new(TEST_KEY_TYPE, None).unwrap(); let path = store.0.read().key_file_path(public.as_ref(), TEST_KEY_TYPE).unwrap(); let permissions = File::open(path).unwrap().metadata().unwrap().permissions(); diff --git a/client/rpc/src/author/mod.rs b/client/rpc/src/author/mod.rs index 9752a32b17c67..00a126500e26d 100644 --- a/client/rpc/src/author/mod.rs +++ b/client/rpc/src/author/mod.rs @@ -40,7 +40,7 @@ use sc_transaction_pool_api::{ use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; use sp_core::Bytes; -use sp_keystore::{Keystore, KeystorePtr}; +use sp_keystore::KeystorePtr; use sp_runtime::{generic, traits::Block as BlockT}; use sp_session::SessionKeys; @@ -112,7 +112,8 @@ where self.deny_unsafe.check_if_safe()?; let key_type = key_type.as_str().try_into().map_err(|_| Error::BadKeyType)?; - Keystore::insert(&*self.keystore, key_type, &suri, &public[..]) + self.keystore + .insert(key_type, &suri, &public[..]) .map_err(|_| Error::KeystoreUnavailable)?; Ok(()) } @@ -139,14 +140,14 @@ where .map_err(|e| Error::Client(Box::new(e)))? .ok_or(Error::InvalidSessionKeys)?; - Ok(Keystore::has_keys(&*self.keystore, &keys)) + Ok(self.keystore.has_keys(&keys)) } fn has_key(&self, public_key: Bytes, key_type: String) -> RpcResult { self.deny_unsafe.check_if_safe()?; let key_type = key_type.as_str().try_into().map_err(|_| Error::BadKeyType)?; - Ok(Keystore::has_keys(&*self.keystore, &[(public_key.to_vec(), key_type)])) + Ok(self.keystore.has_keys(&[(public_key.to_vec(), key_type)])) } fn pending_extrinsics(&self) -> RpcResult> { diff --git a/client/rpc/src/author/tests.rs b/client/rpc/src/author/tests.rs index 209673fce2602..75b6390c83cc7 100644 --- a/client/rpc/src/author/tests.rs +++ b/client/rpc/src/author/tests.rs @@ -36,7 +36,7 @@ use sp_core::{ testing::{ED25519, SR25519}, H256, }; -use sp_keystore::testing::MemoryKeystore; +use sp_keystore::{testing::MemoryKeystore, Keystore}; use std::sync::Arc; use substrate_test_runtime_client::{ self, @@ -225,7 +225,7 @@ async fn author_should_insert_key() { keypair.public().0.to_vec().into(), ); api.call::<_, ()>("author_insertKey", params).await.unwrap(); - let pubkeys = Keystore::keys(&*setup.keystore, ED25519).unwrap(); + let pubkeys = setup.keystore.keys(ED25519).unwrap(); assert!( pubkeys.contains(&CryptoTypePublicPair(ed25519::CRYPTO_ID, keypair.public().to_raw_vec())) @@ -240,8 +240,8 @@ async fn author_should_rotate_keys() { let new_pubkeys: Bytes = api.call("author_rotateKeys", EmptyParams::new()).await.unwrap(); let session_keys = SessionKeys::decode(&mut &new_pubkeys[..]).expect("SessionKeys decode successfully"); - let ed25519_pubkeys = Keystore::keys(&*setup.keystore, ED25519).unwrap(); - let sr25519_pubkeys = Keystore::keys(&*setup.keystore, SR25519).unwrap(); + let ed25519_pubkeys = setup.keystore.keys(ED25519).unwrap(); + let sr25519_pubkeys = setup.keystore.keys(SR25519).unwrap(); assert!(ed25519_pubkeys .contains(&CryptoTypePublicPair(ed25519::CRYPTO_ID, session_keys.ed25519.to_raw_vec()))); assert!(sr25519_pubkeys diff --git a/client/service/src/builder.rs b/client/service/src/builder.rs index 034d056d6f66f..bee40e9a3da0c 100644 --- a/client/service/src/builder.rs +++ b/client/service/src/builder.rs @@ -67,7 +67,7 @@ use sp_consensus::block_validation::{ BlockAnnounceValidator, Chain, DefaultBlockAnnounceValidator, }; use sp_core::traits::{CodeExecutor, SpawnNamed}; -use sp_keystore::{Keystore, KeystorePtr}; +use sp_keystore::KeystorePtr; use sp_runtime::traits::{Block as BlockT, BlockIdTo, NumberFor, Zero}; use std::{str::FromStr, sync::Arc, time::SystemTime}; @@ -85,24 +85,8 @@ pub type TFullCallExecutor = type TFullParts = (TFullClient, Arc>, KeystoreContainer, TaskManager); -trait AsKeystoreRef { - fn keystore_ref(&self) -> Arc; -} - -impl AsKeystoreRef for Arc -where - T: Keystore + 'static, -{ - fn keystore_ref(&self) -> Arc { - self.clone() - } -} - -/// Construct and hold different layers of Keystore wrappers -pub struct KeystoreContainer { - remote: Option>, - local: Arc, -} +/// Construct a local keystore shareable container +pub struct KeystoreContainer(Arc); impl KeystoreContainer { /// Construct KeystoreContainer @@ -113,41 +97,17 @@ impl KeystoreContainer { KeystoreConfig::InMemory => LocalKeystore::in_memory(), }); - Ok(Self { remote: Default::default(), local: keystore }) + Ok(Self(keystore)) } - /// Set the remote keystore. - /// Should be called right away at startup and not at runtime: - /// even though this overrides any previously set remote store, it - /// does not reset any references previously handed out - they will - /// stick around. - pub fn set_remote_keystore(&mut self, remote: Arc) - where - T: Keystore + 'static, - { - self.remote = Some(Box::new(remote)) + /// Returns a shared reference to a dynamic `Keystore` trait implementation. + pub fn keystore(&self) -> KeystorePtr { + self.0.clone() } - /// Returns an adapter to a `Keystore` implementation. - pub fn keystore(&self) -> Arc { - if let Some(c) = self.remote.as_ref() { - c.keystore_ref() - } else { - self.local.clone() - } - } - - /// Returns the local keystore if available - /// - /// The function will return None if the available keystore is not a local keystore. - /// - /// # Note - /// - /// Using the [`LocalKeystore`] will result in loosing the ability to use any other keystore - /// implementation, like a remote keystore for example. Only use this if you a certain that you - /// require it! - pub fn local_keystore(&self) -> Option> { - Some(self.local.clone()) + /// Returns a shared reference to the local keystore . + pub fn local_keystore(&self) -> Arc { + self.0.clone() } } diff --git a/client/service/src/config.rs b/client/service/src/config.rs index c7d98a4533436..6550fcdd8ef4f 100644 --- a/client/service/src/config.rs +++ b/client/service/src/config.rs @@ -61,8 +61,6 @@ pub struct Configuration { pub network: NetworkConfiguration, /// Configuration for the keystore. pub keystore: KeystoreConfig, - /// Remote URI to connect to for async keystore support - pub keystore_remote: Option, /// Configuration for the database. pub database: DatabaseSource, /// Maximum size of internal trie cache in bytes. diff --git a/client/service/test/src/lib.rs b/client/service/test/src/lib.rs index f80446a4d43eb..8a2e5050bd5d3 100644 --- a/client/service/test/src/lib.rs +++ b/client/service/test/src/lib.rs @@ -242,7 +242,6 @@ fn node_config< tokio_handle, transaction_pool: Default::default(), network: network_config, - keystore_remote: Default::default(), keystore: KeystoreConfig::Path { path: root.join("key"), password: None }, database: DatabaseSource::RocksDb { path: root.join("db"), cache_size: 128 }, trie_cache_maximum_size: Some(16 * 1024 * 1024), diff --git a/frame/benchmarking/src/baseline.rs b/frame/benchmarking/src/baseline.rs index 1f6e9c5a68892..25336b6974d9f 100644 --- a/frame/benchmarking/src/baseline.rs +++ b/frame/benchmarking/src/baseline.rs @@ -160,12 +160,11 @@ pub mod mock { impl super::Config for Test {} pub fn new_test_ext() -> sp_io::TestExternalities { - use sp_keystore::{testing::MemoryKeystore, KeystoreExt, KeystorePtr}; - use sp_std::sync::Arc; + use sp_keystore::{testing::MemoryKeystore, KeystoreExt}; let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); let mut ext = sp_io::TestExternalities::new(t); - ext.register_extension(KeystoreExt(Arc::new(MemoryKeystore::new()) as KeystorePtr)); + ext.register_extension(KeystoreExt::new(MemoryKeystore::new())); ext } diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index 185945b71e5be..915a56a3f056c 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -50,7 +50,7 @@ use sp_runtime::{ traits::{BlakeTwo256, Convert, Hash, IdentityLookup}, AccountId32, TokenError, }; -use std::{ops::Deref, sync::Arc}; +use std::ops::Deref; use crate as pallet_contracts; @@ -444,7 +444,7 @@ impl ExtBuilder { .assimilate_storage(&mut t) .unwrap(); let mut ext = sp_io::TestExternalities::new(t); - ext.register_extension(KeystoreExt(Arc::new(MemoryKeystore::new()))); + ext.register_extension(KeystoreExt::new(MemoryKeystore::new())); ext.execute_with(|| System::set_block_number(1)); ext } diff --git a/frame/examples/offchain-worker/src/tests.rs b/frame/examples/offchain-worker/src/tests.rs index c513590435252..3df7f4a8d5439 100644 --- a/frame/examples/offchain-worker/src/tests.rs +++ b/frame/examples/offchain-worker/src/tests.rs @@ -27,7 +27,6 @@ use sp_core::{ sr25519::Signature, H256, }; -use std::sync::Arc; use sp_keystore::{testing::MemoryKeystore, Keystore, KeystoreExt}; use sp_runtime::{ @@ -206,17 +205,14 @@ fn should_submit_signed_transaction_on_chain() { let (offchain, offchain_state) = testing::TestOffchainExt::new(); let (pool, pool_state) = testing::TestTransactionPoolExt::new(); let keystore = MemoryKeystore::new(); - Keystore::sr25519_generate_new( - &keystore, - crate::crypto::Public::ID, - Some(&format!("{}/hunter1", PHRASE)), - ) - .unwrap(); + keystore + .sr25519_generate_new(crate::crypto::Public::ID, Some(&format!("{}/hunter1", PHRASE))) + .unwrap(); let mut t = sp_io::TestExternalities::default(); t.register_extension(OffchainWorkerExt::new(offchain)); t.register_extension(TransactionPoolExt::new(pool)); - t.register_extension(KeystoreExt(Arc::new(keystore))); + t.register_extension(KeystoreExt::new(keystore)); price_oracle_response(&mut offchain_state.write()); @@ -241,21 +237,16 @@ fn should_submit_unsigned_transaction_on_chain_for_any_account() { let keystore = MemoryKeystore::new(); - Keystore::sr25519_generate_new( - &keystore, - crate::crypto::Public::ID, - Some(&format!("{}/hunter1", PHRASE)), - ) - .unwrap(); - - let public_key = *Keystore::sr25519_public_keys(&keystore, crate::crypto::Public::ID) - .get(0) + keystore + .sr25519_generate_new(crate::crypto::Public::ID, Some(&format!("{}/hunter1", PHRASE))) .unwrap(); + let public_key = *keystore.sr25519_public_keys(crate::crypto::Public::ID).get(0).unwrap(); + let mut t = sp_io::TestExternalities::default(); t.register_extension(OffchainWorkerExt::new(offchain)); t.register_extension(TransactionPoolExt::new(pool)); - t.register_extension(KeystoreExt(Arc::new(keystore))); + t.register_extension(KeystoreExt::new(keystore)); price_oracle_response(&mut offchain_state.write()); @@ -300,21 +291,16 @@ fn should_submit_unsigned_transaction_on_chain_for_all_accounts() { let keystore = MemoryKeystore::new(); - Keystore::sr25519_generate_new( - &keystore, - crate::crypto::Public::ID, - Some(&format!("{}/hunter1", PHRASE)), - ) - .unwrap(); - - let public_key = *Keystore::sr25519_public_keys(&keystore, crate::crypto::Public::ID) - .get(0) + keystore + .sr25519_generate_new(crate::crypto::Public::ID, Some(&format!("{}/hunter1", PHRASE))) .unwrap(); + let public_key = *keystore.sr25519_public_keys(crate::crypto::Public::ID).get(0).unwrap(); + let mut t = sp_io::TestExternalities::default(); t.register_extension(OffchainWorkerExt::new(offchain)); t.register_extension(TransactionPoolExt::new(pool)); - t.register_extension(KeystoreExt(Arc::new(keystore))); + t.register_extension(KeystoreExt::new(keystore)); price_oracle_response(&mut offchain_state.write()); @@ -360,7 +346,7 @@ fn should_submit_raw_unsigned_transaction_on_chain() { let mut t = sp_io::TestExternalities::default(); t.register_extension(OffchainWorkerExt::new(offchain)); t.register_extension(TransactionPoolExt::new(pool)); - t.register_extension(KeystoreExt(Arc::new(keystore))); + t.register_extension(KeystoreExt::new(keystore)); price_oracle_response(&mut offchain_state.write()); diff --git a/frame/nfts/src/mock.rs b/frame/nfts/src/mock.rs index 91ac5d6a72203..e2856a07b994c 100644 --- a/frame/nfts/src/mock.rs +++ b/frame/nfts/src/mock.rs @@ -31,7 +31,6 @@ use sp_runtime::{ traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, MultiSignature, }; -use std::sync::Arc; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; @@ -134,9 +133,8 @@ impl Config for Test { pub(crate) fn new_test_ext() -> sp_io::TestExternalities { let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); - let keystore = MemoryKeystore::new(); let mut ext = sp_io::TestExternalities::new(t); - ext.register_extension(KeystoreExt(Arc::new(keystore))); + ext.register_extension(KeystoreExt::new(MemoryKeystore::new())); ext.execute_with(|| System::set_block_number(1)); ext } diff --git a/primitives/application-crypto/test/src/ecdsa.rs b/primitives/application-crypto/test/src/ecdsa.rs index 7b96b42d5556b..fe9e17a65b1a7 100644 --- a/primitives/application-crypto/test/src/ecdsa.rs +++ b/primitives/application-crypto/test/src/ecdsa.rs @@ -34,7 +34,7 @@ fn ecdsa_works_in_runtime() { .test_ecdsa_crypto(test_client.chain_info().genesis_hash) .expect("Tests `ecdsa` crypto."); - let supported_keys = Keystore::keys(&*keystore, ECDSA).unwrap(); + let supported_keys = keystore.keys(ECDSA).unwrap(); assert!(supported_keys.contains(&public.clone().into())); assert!(AppPair::verify(&signature, "ecdsa", &AppPublic::from(public))); } diff --git a/primitives/application-crypto/test/src/ed25519.rs b/primitives/application-crypto/test/src/ed25519.rs index 1cf2b574b6bfb..5687bd013970a 100644 --- a/primitives/application-crypto/test/src/ed25519.rs +++ b/primitives/application-crypto/test/src/ed25519.rs @@ -35,7 +35,7 @@ fn ed25519_works_in_runtime() { .test_ed25519_crypto(test_client.chain_info().genesis_hash) .expect("Tests `ed25519` crypto."); - let supported_keys = Keystore::keys(&*keystore, ED25519).unwrap(); + let supported_keys = keystore.keys(ED25519).unwrap(); assert!(supported_keys.contains(&public.clone().into())); assert!(AppPair::verify(&signature, "ed25519", &AppPublic::from(public))); } diff --git a/primitives/application-crypto/test/src/sr25519.rs b/primitives/application-crypto/test/src/sr25519.rs index aa8f75c0dc27a..92886b80cbfb3 100644 --- a/primitives/application-crypto/test/src/sr25519.rs +++ b/primitives/application-crypto/test/src/sr25519.rs @@ -35,7 +35,7 @@ fn sr25519_works_in_runtime() { .test_sr25519_crypto(test_client.chain_info().genesis_hash) .expect("Tests `sr25519` crypto."); - let supported_keys = Keystore::keys(&*keystore, SR25519).unwrap(); + let supported_keys = keystore.keys(SR25519).unwrap(); assert!(supported_keys.contains(&public.clone().into())); assert!(AppPair::verify(&signature, "sr25519", &AppPublic::from(public))); } diff --git a/primitives/consensus/beefy/src/commitment.rs b/primitives/consensus/beefy/src/commitment.rs index 6ae17b06d96a4..8ad3cc3721a00 100644 --- a/primitives/consensus/beefy/src/commitment.rs +++ b/primitives/consensus/beefy/src/commitment.rs @@ -253,7 +253,7 @@ mod tests { use crate::{crypto, known_payloads, KEY_TYPE}; use codec::Decode; use sp_core::{keccak_256, Pair}; - use sp_keystore::{testing::MemoryKeystore, Keystore, KeystorePtr}; + use sp_keystore::{testing::MemoryKeystore, KeystorePtr}; type TestCommitment = Commitment; type TestSignedCommitment = SignedCommitment; @@ -266,17 +266,13 @@ mod tests { let store: KeystorePtr = MemoryKeystore::new().into(); let alice = sp_core::ecdsa::Pair::from_string("//Alice", None).unwrap(); - let _ = Keystore::insert(&*store, KEY_TYPE, "//Alice", alice.public().as_ref()).unwrap(); + store.insert(KEY_TYPE, "//Alice", alice.public().as_ref()).unwrap(); let msg = keccak_256(b"This is the first message"); - let sig1 = Keystore::ecdsa_sign_prehashed(&*store, KEY_TYPE, &alice.public(), &msg) - .unwrap() - .unwrap(); + let sig1 = store.ecdsa_sign_prehashed(KEY_TYPE, &alice.public(), &msg).unwrap().unwrap(); let msg = keccak_256(b"This is the second message"); - let sig2 = Keystore::ecdsa_sign_prehashed(&*store, KEY_TYPE, &alice.public(), &msg) - .unwrap() - .unwrap(); + let sig2 = store.ecdsa_sign_prehashed(KEY_TYPE, &alice.public(), &msg).unwrap().unwrap(); (sig1.into(), sig2.into()) } diff --git a/primitives/consensus/beefy/src/witness.rs b/primitives/consensus/beefy/src/witness.rs index 70b924c0a42fe..ff9a0401dc632 100644 --- a/primitives/consensus/beefy/src/witness.rs +++ b/primitives/consensus/beefy/src/witness.rs @@ -74,9 +74,8 @@ impl SignedCommitmentWitness Vec { - let keystore = &***self - .extension::() - .expect("No `keystore` associated for the current context!"); - Keystore::ed25519_public_keys(keystore, id) + self.extension::() + .expect("No `keystore` associated for the current context!") + .ed25519_public_keys(id) } /// Generate an `ed22519` key for the given key type using an optional `seed` and @@ -745,10 +744,10 @@ pub trait Crypto { /// Returns the public key. fn ed25519_generate(&mut self, id: KeyTypeId, seed: Option>) -> ed25519::Public { let seed = seed.as_ref().map(|s| std::str::from_utf8(s).expect("Seed is valid utf8!")); - let keystore = &***self - .extension::() - .expect("No `keystore` associated for the current context!"); - Keystore::ed25519_generate_new(keystore, id, seed).expect("`ed25519_generate` failed") + self.extension::() + .expect("No `keystore` associated for the current context!") + .ed25519_generate_new(id, seed) + .expect("`ed25519_generate` failed") } /// Sign the given `msg` with the `ed25519` key that corresponds to the given public key and @@ -761,10 +760,9 @@ pub trait Crypto { pub_key: &ed25519::Public, msg: &[u8], ) -> Option { - let keystore = &***self - .extension::() - .expect("No `keystore` associated for the current context!"); - Keystore::sign_with(keystore, id, &pub_key.into(), msg) + self.extension::() + .expect("No `keystore` associated for the current context!") + .sign_with(id, &pub_key.into(), msg) .ok() .flatten() .and_then(|sig| ed25519::Signature::from_slice(&sig)) @@ -873,10 +871,9 @@ pub trait Crypto { /// Returns all `sr25519` public keys for the given key id from the keystore. fn sr25519_public_keys(&mut self, id: KeyTypeId) -> Vec { - let keystore = &***self - .extension::() - .expect("No `keystore` associated for the current context!"); - Keystore::sr25519_public_keys(keystore, id) + self.extension::() + .expect("No `keystore` associated for the current context!") + .sr25519_public_keys(id) } /// Generate an `sr22519` key for the given key type using an optional seed and @@ -887,10 +884,10 @@ pub trait Crypto { /// Returns the public key. fn sr25519_generate(&mut self, id: KeyTypeId, seed: Option>) -> sr25519::Public { let seed = seed.as_ref().map(|s| std::str::from_utf8(s).expect("Seed is valid utf8!")); - let keystore = &***self - .extension::() - .expect("No `keystore` associated for the current context!"); - Keystore::sr25519_generate_new(keystore, id, seed).expect("`sr25519_generate` failed") + self.extension::() + .expect("No `keystore` associated for the current context!") + .sr25519_generate_new(id, seed) + .expect("`sr25519_generate` failed") } /// Sign the given `msg` with the `sr25519` key that corresponds to the given public key and @@ -903,10 +900,9 @@ pub trait Crypto { pub_key: &sr25519::Public, msg: &[u8], ) -> Option { - let keystore = &***self - .extension::() - .expect("No `keystore` associated for the current context!"); - Keystore::sign_with(keystore, id, &pub_key.into(), msg) + self.extension::() + .expect("No `keystore` associated for the current context!") + .sign_with(id, &pub_key.into(), msg) .ok() .flatten() .and_then(|sig| sr25519::Signature::from_slice(&sig)) @@ -922,10 +918,9 @@ pub trait Crypto { /// Returns all `ecdsa` public keys for the given key id from the keystore. fn ecdsa_public_keys(&mut self, id: KeyTypeId) -> Vec { - let keystore = &***self - .extension::() - .expect("No `keystore` associated for the current context!"); - Keystore::ecdsa_public_keys(keystore, id) + self.extension::() + .expect("No `keystore` associated for the current context!") + .ecdsa_public_keys(id) } /// Generate an `ecdsa` key for the given key type using an optional `seed` and @@ -936,10 +931,10 @@ pub trait Crypto { /// Returns the public key. fn ecdsa_generate(&mut self, id: KeyTypeId, seed: Option>) -> ecdsa::Public { let seed = seed.as_ref().map(|s| std::str::from_utf8(s).expect("Seed is valid utf8!")); - let keystore = &***self - .extension::() - .expect("No `keystore` associated for the current context!"); - Keystore::ecdsa_generate_new(keystore, id, seed).expect("`ecdsa_generate` failed") + self.extension::() + .expect("No `keystore` associated for the current context!") + .ecdsa_generate_new(id, seed) + .expect("`ecdsa_generate` failed") } /// Sign the given `msg` with the `ecdsa` key that corresponds to the given public key and @@ -952,10 +947,9 @@ pub trait Crypto { pub_key: &ecdsa::Public, msg: &[u8], ) -> Option { - let keystore = &***self - .extension::() - .expect("No `keystore` associated for the current context!"); - Keystore::sign_with(keystore, id, &pub_key.into(), msg) + self.extension::() + .expect("No `keystore` associated for the current context!") + .sign_with(id, &pub_key.into(), msg) .ok() .flatten() .and_then(|sig| ecdsa::Signature::from_slice(&sig)) @@ -971,10 +965,11 @@ pub trait Crypto { pub_key: &ecdsa::Public, msg: &[u8; 32], ) -> Option { - let keystore = &***self - .extension::() - .expect("No `keystore` associated for the current context!"); - Keystore::ecdsa_sign_prehashed(keystore, id, pub_key, msg).ok().flatten() + self.extension::() + .expect("No `keystore` associated for the current context!") + .ecdsa_sign_prehashed(id, pub_key, msg) + .ok() + .flatten() } /// Verify `ecdsa` signature. diff --git a/primitives/keystore/src/lib.rs b/primitives/keystore/src/lib.rs index e0c00967b6b5e..d1cbe227ed551 100644 --- a/primitives/keystore/src/lib.rs +++ b/primitives/keystore/src/lib.rs @@ -150,10 +150,17 @@ pub trait Keystore: Send + Sync { ) -> Result, Error>; } -/// A pointer to a keystore. +/// A shared pointer to a keystore implementation. pub type KeystorePtr = Arc; sp_externalities::decl_extension! { /// The keystore extension to register/retrieve from the externalities. pub struct KeystoreExt(KeystorePtr); } + +impl KeystoreExt { + /// Create a new instance of `KeystoreExt` + pub fn new(keystore: T) -> Self { + Self(Arc::new(keystore)) + } +} diff --git a/primitives/keystore/src/testing.rs b/primitives/keystore/src/testing.rs index fecc11342c464..73b560d563a17 100644 --- a/primitives/keystore/src/testing.rs +++ b/primitives/keystore/src/testing.rs @@ -304,9 +304,9 @@ mod tests { fn store_key_and_extract() { let store = MemoryKeystore::new(); - let public = Keystore::ed25519_generate_new(&store, ED25519, None).expect("Generates key"); + let public = store.ed25519_generate_new(ED25519, None).expect("Generates key"); - let public_keys = Keystore::keys(&store, ED25519).unwrap(); + let public_keys = store.keys(ED25519).unwrap(); assert!(public_keys.contains(&public.into())); } @@ -318,10 +318,11 @@ mod tests { let secret_uri = "//Alice"; let key_pair = sr25519::Pair::from_string(secret_uri, None).expect("Generates key pair"); - Keystore::insert(&store, SR25519, secret_uri, key_pair.public().as_ref()) + store + .insert(SR25519, secret_uri, key_pair.public().as_ref()) .expect("Inserts unknown key"); - let public_keys = Keystore::keys(&store, SR25519).unwrap(); + let public_keys = store.keys(SR25519).unwrap(); assert!(public_keys.contains(&key_pair.public().into())); } @@ -342,19 +343,14 @@ mod tests { ], }; - let result = Keystore::sr25519_vrf_sign( - &store, - SR25519, - &key_pair.public(), - transcript_data.clone(), - ); + let result = store.sr25519_vrf_sign(SR25519, &key_pair.public(), transcript_data.clone()); assert!(result.unwrap().is_none()); - Keystore::insert(&store, SR25519, secret_uri, key_pair.public().as_ref()) + store + .insert(SR25519, secret_uri, key_pair.public().as_ref()) .expect("Inserts unknown key"); - let result = - Keystore::sr25519_vrf_sign(&store, SR25519, &key_pair.public(), transcript_data); + let result = store.sr25519_vrf_sign(SR25519, &key_pair.public(), transcript_data); assert!(result.unwrap().is_some()); } @@ -369,13 +365,13 @@ mod tests { let msg = sp_core::keccak_256(b"this should be a hashed message"); // no key in key store - let res = Keystore::ecdsa_sign_prehashed(&store, ECDSA, &pair.public(), &msg).unwrap(); + let res = store.ecdsa_sign_prehashed(ECDSA, &pair.public(), &msg).unwrap(); assert!(res.is_none()); // insert key, sign again - Keystore::insert(&store, ECDSA, suri, pair.public().as_ref()).unwrap(); + store.insert(ECDSA, suri, pair.public().as_ref()).unwrap(); - let res = Keystore::ecdsa_sign_prehashed(&store, ECDSA, &pair.public(), &msg).unwrap(); + let res = store.ecdsa_sign_prehashed(ECDSA, &pair.public(), &msg).unwrap(); assert!(res.is_some()); } } diff --git a/utils/frame/benchmarking-cli/src/pallet/command.rs b/utils/frame/benchmarking-cli/src/pallet/command.rs index f11e6bd920abf..15ebc668ff4fb 100644 --- a/utils/frame/benchmarking-cli/src/pallet/command.rs +++ b/utils/frame/benchmarking-cli/src/pallet/command.rs @@ -38,10 +38,10 @@ use sp_core::{ traits::CallContext, }; use sp_externalities::Extensions; -use sp_keystore::{testing::MemoryKeystore, KeystoreExt, KeystorePtr}; +use sp_keystore::{testing::MemoryKeystore, KeystoreExt}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; use sp_state_machine::StateMachine; -use std::{collections::HashMap, fmt::Debug, fs, str::FromStr, sync::Arc, time}; +use std::{collections::HashMap, fmt::Debug, fs, str::FromStr, time}; /// Logging target const LOG_TARGET: &'static str = "frame::benchmark::pallet"; @@ -218,9 +218,10 @@ impl PalletCmd { let extensions = || -> Extensions { let mut extensions = Extensions::default(); - extensions.register(KeystoreExt(Arc::new(MemoryKeystore::new()) as KeystorePtr)); let (offchain, _) = TestOffchainExt::new(); let (pool, _) = TestTransactionPoolExt::new(); + let keystore = MemoryKeystore::new(); + extensions.register(KeystoreExt::new(keystore)); extensions.register(OffchainWorkerExt::new(offchain.clone())); extensions.register(OffchainDbExt::new(offchain)); extensions.register(TransactionPoolExt::new(pool)); diff --git a/utils/frame/try-runtime/cli/src/lib.rs b/utils/frame/try-runtime/cli/src/lib.rs index bd914d3a2e017..34966fc2a1197 100644 --- a/utils/frame/try-runtime/cli/src/lib.rs +++ b/utils/frame/try-runtime/cli/src/lib.rs @@ -816,9 +816,10 @@ pub(crate) fn full_extensions() -> Extensions { extensions.register(TaskExecutorExt::new(TaskExecutor::new())); let (offchain, _offchain_state) = TestOffchainExt::new(); let (pool, _pool_state) = TestTransactionPoolExt::new(); + let keystore = MemoryKeystore::new(); extensions.register(OffchainDbExt::new(offchain.clone())); extensions.register(OffchainWorkerExt::new(offchain)); - extensions.register(KeystoreExt(std::sync::Arc::new(MemoryKeystore::new()))); + extensions.register(KeystoreExt::new(keystore)); extensions.register(TransactionPoolExt::new(pool)); extensions