diff --git a/Cargo.lock b/Cargo.lock index d4e9476782fd1..a76a8a73c2861 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10658,7 +10658,6 @@ dependencies = [ name = "sp-keystore" version = "0.13.0" dependencies = [ - "async-trait", "futures", "merlin", "parity-scale-codec", diff --git a/bin/node-template/node/src/service.rs b/bin/node-template/node/src/service.rs index 34e4e566d92fc..40ad80c7b3b79 100644 --- a/bin/node-template/node/src/service.rs +++ b/bin/node-template/node/src/service.rs @@ -150,7 +150,7 @@ 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 `CryptoStore` and `SyncCryptoStore` + // implements `Keystore` Err("Remote Keystore not supported.") } @@ -233,7 +233,7 @@ pub fn new_full(mut config: Configuration) -> Result let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams { network: network.clone(), client: client.clone(), - keystore: keystore_container.sync_keystore(), + keystore: keystore_container.keystore(), task_manager: &mut task_manager, transaction_pool: transaction_pool.clone(), rpc_builder: rpc_extensions_builder, @@ -276,7 +276,7 @@ pub fn new_full(mut config: Configuration) -> Result }, force_authoring, backoff_authoring_blocks, - keystore: keystore_container.sync_keystore(), + keystore: keystore_container.keystore(), sync_oracle: sync_service.clone(), justification_sync_link: sync_service.clone(), block_proposal_slot_portion: SlotProportion::new(2f32 / 3f32), @@ -296,8 +296,7 @@ pub fn new_full(mut config: Configuration) -> Result if enable_grandpa { // if the node isn't actively participating in consensus then it doesn't // need a keystore, regardless of which protocol we use below. - let keystore = - if role.is_authority() { Some(keystore_container.sync_keystore()) } else { None }; + let keystore = if role.is_authority() { Some(keystore_container.keystore()) } else { None }; let grandpa_config = sc_consensus_grandpa::Config { // FIXME #1578 make this available through chainspec diff --git a/bin/node/cli/src/service.rs b/bin/node/cli/src/service.rs index 3c9716c08d1c0..a2d66cd6349de 100644 --- a/bin/node/cli/src/service.rs +++ b/bin/node/cli/src/service.rs @@ -251,7 +251,7 @@ pub fn new_partial( let client = client.clone(); let pool = transaction_pool.clone(); let select_chain = select_chain.clone(); - let keystore = keystore_container.sync_keystore(); + let keystore = keystore_container.keystore(); let chain_spec = config.chain_spec.cloned_box(); let rpc_backend = backend.clone(); @@ -386,7 +386,7 @@ pub fn new_full_base( config, backend, client: client.clone(), - keystore: keystore_container.sync_keystore(), + keystore: keystore_container.keystore(), network: network.clone(), rpc_builder: Box::new(rpc_builder), transaction_pool: transaction_pool.clone(), @@ -431,7 +431,7 @@ pub fn new_full_base( let client_clone = client.clone(); let slot_duration = babe_link.config().slot_duration(); let babe_config = sc_consensus_babe::BabeParams { - keystore: keystore_container.sync_keystore(), + keystore: keystore_container.keystore(), client: client.clone(), select_chain, env: proposer, @@ -507,8 +507,7 @@ pub fn new_full_base( // if the node isn't actively participating in consensus then it doesn't // need a keystore, regardless of which protocol we use below. - let keystore = - if role.is_authority() { Some(keystore_container.sync_keystore()) } else { None }; + let keystore = if role.is_authority() { Some(keystore_container.keystore()) } else { None }; let config = grandpa::Config { // FIXME #1578 make this available through chainspec @@ -596,7 +595,7 @@ mod tests { use sp_core::{crypto::Pair as CryptoPair, Public}; use sp_inherents::InherentDataProvider; use sp_keyring::AccountKeyring; - use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; + use sp_keystore::{Keystore, KeystorePtr}; use sp_runtime::{ generic::{Digest, Era, SignedPayload}, key_types::BABE, @@ -616,10 +615,10 @@ mod tests { sp_tracing::try_init_simple(); let keystore_path = tempfile::tempdir().expect("Creates keystore path"); - let keystore: SyncCryptoStorePtr = + let keystore: KeystorePtr = Arc::new(LocalKeystore::open(keystore_path.path(), None).expect("Creates keystore")); let alice: sp_consensus_babe::AuthorityId = - SyncCryptoStore::sr25519_generate_new(&*keystore, BABE, Some("//Alice")) + Keystore::sr25519_generate_new(&*keystore, BABE, Some("//Alice")) .expect("Creates authority pair") .into(); @@ -736,7 +735,7 @@ 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 = SyncCryptoStore::sign_with( + let signature = Keystore::sign_with( &*keystore, sp_consensus_babe::AuthorityId::ID, &alice.to_public_crypto_pair(), diff --git a/bin/node/executor/tests/submit_transaction.rs b/bin/node/executor/tests/submit_transaction.rs index ab5df62a2e714..32eacd78b78b7 100644 --- a/bin/node/executor/tests/submit_transaction.rs +++ b/bin/node/executor/tests/submit_transaction.rs @@ -21,7 +21,7 @@ use kitchensink_runtime::{Executive, Indices, Runtime, UncheckedExtrinsic}; use sp_application_crypto::AppKey; use sp_core::offchain::{testing::TestTransactionPoolExt, TransactionPoolExt}; use sp_keyring::sr25519::Keyring::Alice; -use sp_keystore::{testing::KeyStore, KeystoreExt, SyncCryptoStore}; +use sp_keystore::{testing::MemoryKeystore, Keystore, KeystoreExt}; use std::sync::Arc; pub mod common; @@ -62,20 +62,20 @@ fn should_submit_signed_transaction() { let (pool, state) = TestTransactionPoolExt::new(); t.register_extension(TransactionPoolExt::new(pool)); - let keystore = KeyStore::new(); - SyncCryptoStore::sr25519_generate_new( + let keystore = MemoryKeystore::new(); + Keystore::sr25519_generate_new( &keystore, sr25519::AuthorityId::ID, Some(&format!("{}/hunter1", PHRASE)), ) .unwrap(); - SyncCryptoStore::sr25519_generate_new( + Keystore::sr25519_generate_new( &keystore, sr25519::AuthorityId::ID, Some(&format!("{}/hunter2", PHRASE)), ) .unwrap(); - SyncCryptoStore::sr25519_generate_new( + Keystore::sr25519_generate_new( &keystore, sr25519::AuthorityId::ID, Some(&format!("{}/hunter3", PHRASE)), @@ -105,14 +105,14 @@ fn should_submit_signed_twice_from_the_same_account() { let (pool, state) = TestTransactionPoolExt::new(); t.register_extension(TransactionPoolExt::new(pool)); - let keystore = KeyStore::new(); - SyncCryptoStore::sr25519_generate_new( + let keystore = MemoryKeystore::new(); + Keystore::sr25519_generate_new( &keystore, sr25519::AuthorityId::ID, Some(&format!("{}/hunter1", PHRASE)), ) .unwrap(); - SyncCryptoStore::sr25519_generate_new( + Keystore::sr25519_generate_new( &keystore, sr25519::AuthorityId::ID, Some(&format!("{}/hunter2", PHRASE)), @@ -162,7 +162,7 @@ fn should_submit_signed_twice_from_all_accounts() { let (pool, state) = TestTransactionPoolExt::new(); t.register_extension(TransactionPoolExt::new(pool)); - let keystore = KeyStore::new(); + let keystore = MemoryKeystore::new(); keystore .sr25519_generate_new(sr25519::AuthorityId::ID, Some(&format!("{}/hunter1", PHRASE))) .unwrap(); @@ -226,8 +226,8 @@ fn submitted_transaction_should_be_valid() { let (pool, state) = TestTransactionPoolExt::new(); t.register_extension(TransactionPoolExt::new(pool)); - let keystore = KeyStore::new(); - SyncCryptoStore::sr25519_generate_new( + let keystore = MemoryKeystore::new(); + Keystore::sr25519_generate_new( &keystore, sr25519::AuthorityId::ID, Some(&format!("{}/hunter1", PHRASE)), diff --git a/bin/node/rpc/src/lib.rs b/bin/node/rpc/src/lib.rs index 7c2f7c15e05c8..9dcdf0f218923 100644 --- a/bin/node/rpc/src/lib.rs +++ b/bin/node/rpc/src/lib.rs @@ -49,7 +49,7 @@ use sp_block_builder::BlockBuilder; use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; use sp_consensus::SelectChain; use sp_consensus_babe::BabeApi; -use sp_keystore::SyncCryptoStorePtr; +use sp_keystore::KeystorePtr; /// Extra dependencies for BABE. pub struct BabeDeps { @@ -58,7 +58,7 @@ pub struct BabeDeps { /// BABE pending epoch changes. pub shared_epoch_changes: SharedEpochChanges, /// The keystore that manages the keys of the node. - pub keystore: SyncCryptoStorePtr, + pub keystore: KeystorePtr, } /// Extra dependencies for GRANDPA diff --git a/bin/utils/chain-spec-builder/src/main.rs b/bin/utils/chain-spec-builder/src/main.rs index b3f28b269fddd..f7b7d94c57d1c 100644 --- a/bin/utils/chain-spec-builder/src/main.rs +++ b/bin/utils/chain-spec-builder/src/main.rs @@ -32,7 +32,7 @@ use sp_core::{ crypto::{ByteArray, Ss58Codec}, sr25519, }; -use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; +use sp_keystore::{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,7 +164,7 @@ 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: SyncCryptoStorePtr = Arc::new( + let keystore: KeystorePtr = Arc::new( LocalKeystore::open(keystore_path.join(format!("auth-{}", n)), None) .map_err(|err| err.to_string())?, ); @@ -173,7 +173,7 @@ fn generate_authority_keys_and_store(seeds: &[String], keystore_path: &Path) -> chain_spec::authority_keys_from_seed(seed); let insert_key = |key_type, public| { - SyncCryptoStore::insert_unknown(&*keystore, key_type, &format!("//{}", seed), public) + Keystore::insert(&*keystore, key_type, &format!("//{}", seed), public) .map_err(|_| format!("Failed to insert key: {}", grandpa)) }; diff --git a/client/api/src/execution_extensions.rs b/client/api/src/execution_extensions.rs index b491d7672e8f0..ffa670f7bc628 100644 --- a/client/api/src/execution_extensions.rs +++ b/client/api/src/execution_extensions.rs @@ -30,7 +30,7 @@ use sp_core::{ ExecutionContext, }; use sp_externalities::{Extension, Extensions}; -use sp_keystore::{KeystoreExt, SyncCryptoStorePtr}; +use sp_keystore::{KeystoreExt, KeystorePtr}; use sp_runtime::{ generic::BlockId, traits::{Block as BlockT, NumberFor}, @@ -163,7 +163,7 @@ impl DbExternaliti /// for each call, based on required `Capabilities`. pub struct ExecutionExtensions { strategies: ExecutionStrategies, - keystore: Option, + keystore: Option, offchain_db: Option>, // FIXME: these two are only RwLock because of https://github.com/paritytech/substrate/issues/4587 // remove when fixed. @@ -191,7 +191,7 @@ impl ExecutionExtensions { /// Create new `ExecutionExtensions` given a `keystore` and `ExecutionStrategies`. pub fn new( strategies: ExecutionStrategies, - keystore: Option, + keystore: Option, offchain_db: Option>, ) -> Self { let transaction_pool = RwLock::new(None); diff --git a/client/authority-discovery/src/tests.rs b/client/authority-discovery/src/tests.rs index 982c3fc04c590..d354f6a963e73 100644 --- a/client/authority-discovery/src/tests.rs +++ b/client/authority-discovery/src/tests.rs @@ -33,7 +33,7 @@ use std::{collections::HashSet, sync::Arc}; use sp_authority_discovery::AuthorityId; use sp_core::crypto::key_types; -use sp_keystore::{testing::KeyStore, CryptoStore}; +use sp_keystore::{testing::MemoryKeystore, Keystore}; #[test] fn get_addresses_and_authority_id() { @@ -42,12 +42,11 @@ fn get_addresses_and_authority_id() { let mut pool = LocalPool::new(); - let key_store = KeyStore::new(); + let key_store = MemoryKeystore::new(); let remote_authority_id: AuthorityId = pool.run_until(async { key_store .sr25519_generate_new(key_types::AUTHORITY_DISCOVERY, None) - .await .unwrap() .into() }); diff --git a/client/authority-discovery/src/worker.rs b/client/authority-discovery/src/worker.rs index 0b2055c818a9b..a8b7e448d02f6 100644 --- a/client/authority-discovery/src/worker.rs +++ b/client/authority-discovery/src/worker.rs @@ -53,7 +53,7 @@ use sp_authority_discovery::{ use sp_blockchain::HeaderBackend; use sp_core::crypto::{key_types, CryptoTypePublicPair, Pair}; -use sp_keystore::CryptoStore; +use sp_keystore::{Keystore, KeystorePtr}; use sp_runtime::traits::Block as BlockT; mod addr_cache; @@ -78,7 +78,7 @@ const MAX_IN_FLIGHT_LOOKUPS: usize = 8; /// Role an authority discovery [`Worker`] can run as. pub enum Role { /// Publish own addresses and discover addresses of others. - PublishAndDiscover(Arc), + PublishAndDiscover(KeystorePtr), /// Discover addresses of others. Discover, } @@ -371,8 +371,7 @@ where Some(peer_signature), key_store.as_ref(), keys_vec, - ) - .await?; + )?; for (key, value) in kv_pairs.into_iter() { self.network.put_value(key, value); @@ -389,7 +388,6 @@ where let local_keys = match &self.role { Role::PublishAndDiscover(key_store) => key_store .sr25519_public_keys(key_types::AUTHORITY_DISCOVERY) - .await .into_iter() .collect::>(), Role::Discover => HashSet::new(), @@ -595,12 +593,11 @@ where // next authority set with two keys. The function does not return all of the local authority // discovery public keys, but only the ones intersecting with the current or next authority set. async fn get_own_public_keys_within_authority_set( - key_store: Arc, + key_store: KeystorePtr, client: &Client, ) -> Result> { let local_pub_keys = key_store .sr25519_public_keys(key_types::AUTHORITY_DISCOVERY) - .await .into_iter() .collect::>(); @@ -670,33 +667,28 @@ fn sign_record_with_peer_id( Ok(schema::PeerSignature { signature, public_key }) } -async fn sign_record_with_authority_ids( +fn sign_record_with_authority_ids( serialized_record: Vec, peer_signature: Option, - key_store: &dyn CryptoStore, + key_store: &dyn Keystore, keys: Vec, ) -> Result)>> { - let signatures = key_store - .sign_with_all(key_types::AUTHORITY_DISCOVERY, keys.clone(), &serialized_record) - .await - .map_err(|_| Error::Signing)?; + let mut result = Vec::with_capacity(keys.len()); - let mut result = vec![]; - for (sign_result, key) in signatures.into_iter().zip(keys.iter()) { - let mut signed_record = vec![]; + for key in keys.iter() { + let auth_signature = key_store + .sign_with(key_types::AUTHORITY_DISCOVERY, key, &serialized_record) + .map_err(|_| Error::Signing)? + .ok_or_else(|| Error::MissingSignature(key.clone()))?; - // Verify that all signatures exist for all provided keys. - let auth_signature = - sign_result.ok().flatten().ok_or_else(|| Error::MissingSignature(key.clone()))?; - schema::SignedAuthorityRecord { + let signed_record = schema::SignedAuthorityRecord { record: serialized_record.clone(), auth_signature, peer_signature: peer_signature.clone(), } - .encode(&mut signed_record) - .map_err(Error::EncodingProto)?; + .encode_to_vec(); - result.push((hash_authority_id(key.1.as_ref()), signed_record)); + result.push((hash_authority_id(&key.1), signed_record)); } Ok(result) diff --git a/client/authority-discovery/src/worker/tests.rs b/client/authority-discovery/src/worker/tests.rs index febe40657e06a..c918d79932624 100644 --- a/client/authority-discovery/src/worker/tests.rs +++ b/client/authority-discovery/src/worker/tests.rs @@ -40,7 +40,7 @@ use prometheus_endpoint::prometheus::default_registry; use sc_client_api::HeaderBackend; use sc_network::Signature; use sp_api::{ApiRef, ProvideRuntimeApi}; -use sp_keystore::{testing::KeyStore, CryptoStore}; +use sp_keystore::{testing::MemoryKeystore, Keystore}; use sp_runtime::traits::{Block as BlockT, NumberFor, Zero}; use substrate_test_runtime_client::runtime::Block; @@ -208,10 +208,10 @@ impl<'a> NetworkSigner for TestSigner<'a> { } } -async fn build_dht_event( +fn build_dht_event( addresses: Vec, public_key: AuthorityId, - key_store: &dyn CryptoStore, + key_store: &MemoryKeystore, network: Option<&Signer>, ) -> Vec<(KademliaKey, Vec)> { let serialized_record = @@ -224,7 +224,6 @@ async fn build_dht_event( key_store, vec![public_key.into()], ) - .await .unwrap(); // There is always a single item in it, because we signed it with a single key kv_pairs @@ -234,7 +233,7 @@ async fn build_dht_event( fn new_registers_metrics() { let (_dht_event_tx, dht_event_rx) = mpsc::channel(1000); let network: Arc = Arc::new(Default::default()); - let key_store = KeyStore::new(); + let key_store = MemoryKeystore::new(); let test_api = Arc::new(TestApi { authorities: vec![] }); let registry = prometheus_endpoint::Registry::new(); @@ -266,7 +265,7 @@ fn triggers_dht_get_query() { let test_api = Arc::new(TestApi { authorities: authorities.clone() }); let network = Arc::new(TestNetwork::default()); - let key_store = KeyStore::new(); + let key_store = MemoryKeystore::new(); let (_to_worker, from_service) = mpsc::channel(0); let mut worker = Worker::new( @@ -298,14 +297,12 @@ fn publish_discover_cycle() { let network: Arc = Arc::new(Default::default()); - let key_store = KeyStore::new(); + let key_store = MemoryKeystore::new(); let _ = pool.spawner().spawn_local_obj( async move { - let node_a_public = key_store - .sr25519_generate_new(key_types::AUTHORITY_DISCOVERY, None) - .await - .unwrap(); + let node_a_public = + key_store.sr25519_generate_new(key_types::AUTHORITY_DISCOVERY, None).unwrap(); let test_api = Arc::new(TestApi { authorities: vec![node_a_public.into()] }); let (_to_worker, from_service) = mpsc::channel(0); @@ -337,7 +334,7 @@ fn publish_discover_cycle() { authorities: vec![node_a_public.into()], }); let network: Arc = Arc::new(Default::default()); - let key_store = KeyStore::new(); + let key_store = MemoryKeystore::new(); let (_to_worker, from_service) = mpsc::channel(0); let mut worker = Worker::new( @@ -371,7 +368,7 @@ fn publish_discover_cycle() { fn terminate_when_event_stream_terminates() { let (dht_event_tx, dht_event_rx) = channel(1000); let network: Arc = Arc::new(Default::default()); - let key_store = KeyStore::new(); + let key_store = MemoryKeystore::new(); let test_api = Arc::new(TestApi { authorities: vec![] }); let (to_worker, from_service) = mpsc::channel(0); @@ -420,11 +417,11 @@ fn dont_stop_polling_dht_event_stream_after_bogus_event() { address.with(multiaddr::Protocol::P2p(peer_id.into())) }; - let remote_key_store = KeyStore::new(); - let remote_public_key: AuthorityId = - block_on(remote_key_store.sr25519_generate_new(key_types::AUTHORITY_DISCOVERY, None)) - .unwrap() - .into(); + let remote_key_store = MemoryKeystore::new(); + let remote_public_key: AuthorityId = remote_key_store + .sr25519_generate_new(key_types::AUTHORITY_DISCOVERY, None) + .unwrap() + .into(); let (mut dht_event_tx, dht_event_rx) = channel(1); let (network, mut network_events) = { @@ -433,7 +430,7 @@ fn dont_stop_polling_dht_event_stream_after_bogus_event() { (Arc::new(n), r) }; - let key_store = KeyStore::new(); + let key_store = MemoryKeystore::new(); let test_api = Arc::new(TestApi { authorities: vec![remote_public_key.clone()] }); let mut pool = LocalPool::new(); @@ -480,8 +477,7 @@ fn dont_stop_polling_dht_event_stream_after_bogus_event() { remote_public_key.clone(), &remote_key_store, None, - ) - .await; + ); DhtEvent::ValueFound(kv_pairs) }; dht_event_tx.send(dht_event).await.expect("Channel has capacity of 1."); @@ -498,7 +494,7 @@ fn dont_stop_polling_dht_event_stream_after_bogus_event() { } struct DhtValueFoundTester { - pub remote_key_store: KeyStore, + pub remote_key_store: MemoryKeystore, pub remote_authority_public: sp_core::sr25519::Public, pub remote_node_key: Keypair, pub local_worker: Option< @@ -516,10 +512,10 @@ struct DhtValueFoundTester { impl DhtValueFoundTester { fn new() -> Self { - let remote_key_store = KeyStore::new(); - let remote_authority_public = - block_on(remote_key_store.sr25519_generate_new(key_types::AUTHORITY_DISCOVERY, None)) - .unwrap(); + let remote_key_store = MemoryKeystore::new(); + let remote_authority_public = remote_key_store + .sr25519_generate_new(key_types::AUTHORITY_DISCOVERY, None) + .unwrap(); let remote_node_key = Keypair::generate_ed25519(); Self { remote_key_store, remote_authority_public, remote_node_key, local_worker: None } @@ -542,7 +538,7 @@ impl DhtValueFoundTester { let local_test_api = Arc::new(TestApi { authorities: vec![self.remote_authority_public.into()] }); let local_network: Arc = Arc::new(Default::default()); - let local_key_store = KeyStore::new(); + let local_key_store = MemoryKeystore::new(); let (_to_worker, from_service) = mpsc::channel(0); let mut local_worker = Worker::new( @@ -576,12 +572,12 @@ fn limit_number_of_addresses_added_to_cache_per_authority() { let mut tester = DhtValueFoundTester::new(); assert!(MAX_ADDRESSES_PER_AUTHORITY < 100); let addresses = (1..100).map(|i| tester.multiaddr_with_peer_id(i)).collect(); - let kv_pairs = block_on(build_dht_event::( + let kv_pairs = build_dht_event::( addresses, tester.remote_authority_public.into(), &tester.remote_key_store, None, - )); + ); let cached_remote_addresses = tester.process_value_found(false, kv_pairs); assert_eq!(MAX_ADDRESSES_PER_AUTHORITY, cached_remote_addresses.unwrap().len()); @@ -591,12 +587,12 @@ fn limit_number_of_addresses_added_to_cache_per_authority() { fn strict_accept_address_with_peer_signature() { let mut tester = DhtValueFoundTester::new(); let addr = tester.multiaddr_with_peer_id(1); - let kv_pairs = block_on(build_dht_event( + let kv_pairs = build_dht_event( vec![addr.clone()], tester.remote_authority_public.into(), &tester.remote_key_store, Some(&TestSigner { keypair: &tester.remote_node_key }), - )); + ); let cached_remote_addresses = tester.process_value_found(true, kv_pairs); @@ -611,12 +607,12 @@ fn strict_accept_address_with_peer_signature() { fn reject_address_with_rogue_peer_signature() { let mut tester = DhtValueFoundTester::new(); let rogue_remote_node_key = Keypair::generate_ed25519(); - let kv_pairs = block_on(build_dht_event( + let kv_pairs = build_dht_event( vec![tester.multiaddr_with_peer_id(1)], tester.remote_authority_public.into(), &tester.remote_key_store, Some(&TestSigner { keypair: &rogue_remote_node_key }), - )); + ); let cached_remote_addresses = tester.process_value_found(false, kv_pairs); @@ -629,12 +625,12 @@ fn reject_address_with_rogue_peer_signature() { #[test] fn reject_address_with_invalid_peer_signature() { let mut tester = DhtValueFoundTester::new(); - let mut kv_pairs = block_on(build_dht_event( + let mut kv_pairs = build_dht_event( vec![tester.multiaddr_with_peer_id(1)], tester.remote_authority_public.into(), &tester.remote_key_store, Some(&TestSigner { keypair: &tester.remote_node_key }), - )); + ); // tamper with the signature let mut record = schema::SignedAuthorityRecord::decode(kv_pairs[0].1.as_slice()).unwrap(); record.peer_signature.as_mut().map(|p| p.signature[1] = !p.signature[1]); @@ -651,12 +647,12 @@ fn reject_address_with_invalid_peer_signature() { #[test] fn reject_address_without_peer_signature() { let mut tester = DhtValueFoundTester::new(); - let kv_pairs = block_on(build_dht_event::( + let kv_pairs = build_dht_event::( vec![tester.multiaddr_with_peer_id(1)], tester.remote_authority_public.into(), &tester.remote_key_store, None, - )); + ); let cached_remote_addresses = tester.process_value_found(true, kv_pairs); @@ -669,12 +665,12 @@ fn do_not_cache_addresses_without_peer_id() { let multiaddr_with_peer_id = tester.multiaddr_with_peer_id(1); let multiaddr_without_peer_id: Multiaddr = "/ip6/2001:db8:0:0:0:0:0:2/tcp/30333".parse().unwrap(); - let kv_pairs = block_on(build_dht_event::( + let kv_pairs = build_dht_event::( vec![multiaddr_with_peer_id.clone(), multiaddr_without_peer_id], tester.remote_authority_public.into(), &tester.remote_key_store, None, - )); + ); let cached_remote_addresses = tester.process_value_found(false, kv_pairs); @@ -701,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(KeyStore::new())), + Role::PublishAndDiscover(Arc::new(MemoryKeystore::new())), Some(prometheus_endpoint::Registry::new()), Default::default(), ); @@ -735,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(KeyStore::new())), + Role::PublishAndDiscover(Arc::new(MemoryKeystore::new())), Some(prometheus_endpoint::Registry::new()), Default::default(), ); @@ -755,10 +751,11 @@ fn lookup_throttling() { address.with(multiaddr::Protocol::P2p(peer_id.into())) }; - let remote_key_store = KeyStore::new(); + let remote_key_store = MemoryKeystore::new(); let remote_public_keys: Vec = (0..20) .map(|_| { - block_on(remote_key_store.sr25519_generate_new(key_types::AUTHORITY_DISCOVERY, None)) + remote_key_store + .sr25519_generate_new(key_types::AUTHORITY_DISCOVERY, None) .unwrap() .into() }) @@ -818,8 +815,7 @@ fn lookup_throttling() { remote_key, &remote_key_store, None, - ) - .await; + ); DhtEvent::ValueFound(kv_pairs) }; dht_event_tx.send(dht_event).await.expect("Channel has capacity of 1."); diff --git a/client/cli/src/commands/insert_key.rs b/client/cli/src/commands/insert_key.rs index 77d0f57780a94..b02c0181d43a2 100644 --- a/client/cli/src/commands/insert_key.rs +++ b/client/cli/src/commands/insert_key.rs @@ -24,7 +24,7 @@ use clap::Parser; use sc_keystore::LocalKeystore; use sc_service::config::{BasePath, KeystoreConfig}; use sp_core::crypto::{KeyTypeId, SecretString}; -use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; +use sp_keystore::{Keystore, KeystorePtr}; use std::sync::Arc; /// The `insert` command @@ -69,7 +69,7 @@ impl InsertKeyCmd { let (keystore, public) = match self.keystore_params.keystore_config(&config_dir)? { (_, KeystoreConfig::Path { path, password }) => { let public = with_crypto_scheme!(self.scheme, to_vec(&suri, password.clone()))?; - let keystore: SyncCryptoStorePtr = Arc::new(LocalKeystore::open(path, password)?); + let keystore: KeystorePtr = Arc::new(LocalKeystore::open(path, password)?); (keystore, public) }, _ => unreachable!("keystore_config always returns path and password; qed"), @@ -78,8 +78,8 @@ impl InsertKeyCmd { let key_type = KeyTypeId::try_from(self.key_type.as_str()).map_err(|_| Error::KeyTypeInvalid)?; - SyncCryptoStore::insert_unknown(&*keystore, key_type, &suri, &public[..]) - .map_err(|_| Error::KeyStoreOperation)?; + Keystore::insert(&*keystore, key_type, &suri, &public[..]) + .map_err(|_| Error::KeystoreOperation)?; Ok(()) } diff --git a/client/cli/src/error.rs b/client/cli/src/error.rs index 3b30ccb3ed6b0..6c0cfca4932ef 100644 --- a/client/cli/src/error.rs +++ b/client/cli/src/error.rs @@ -64,7 +64,7 @@ pub enum Error { SignatureInvalid, #[error("Key store operation failed")] - KeyStoreOperation, + KeystoreOperation, #[error("Key storage issue encountered")] KeyStorage(#[from] sc_keystore::Error), diff --git a/client/consensus/aura/src/lib.rs b/client/consensus/aura/src/lib.rs index e90494ddfc177..8cdad148d6ef4 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::{SyncCryptoStore, SyncCryptoStorePtr}; +use sp_keystore::{Keystore, KeystorePtr}; use sp_runtime::{ traits::{Block as BlockT, Header, Member, NumberFor, Zero}, DigestItem, @@ -168,7 +168,7 @@ pub struct StartAuraParams { /// The backoff strategy when we miss slots. pub backoff_authoring_blocks: Option, /// The keystore used by the node. - pub keystore: SyncCryptoStorePtr, + pub keystore: KeystorePtr, /// The proportion of the slot dedicated to proposing. /// /// The block proposing will be limited to this proportion of the slot from the starting of the @@ -265,7 +265,7 @@ pub struct BuildAuraWorkerParams { /// The backoff strategy when we miss slots. pub backoff_authoring_blocks: Option, /// The keystore used by the node. - pub keystore: SyncCryptoStorePtr, + pub keystore: KeystorePtr, /// The proportion of the slot dedicated to proposing. /// /// The block proposing will be limited to this proportion of the slot from the starting of the @@ -346,7 +346,7 @@ struct AuraWorker { client: Arc, block_import: I, env: E, - keystore: SyncCryptoStorePtr, + keystore: KeystorePtr, sync_oracle: SO, justification_sync_link: L, force_authoring: bool, @@ -418,7 +418,7 @@ where ) -> Option { let expected_author = slot_author::

(slot, epoch_data); expected_author.and_then(|p| { - if SyncCryptoStore::has_keys( + if Keystore::has_keys( &*self.keystore, &[(p.to_raw_vec(), sp_application_crypto::key_types::AURA)], ) { @@ -449,7 +449,7 @@ where // add it to a digest item. let public_type_pair = public.to_public_crypto_pair(); let public = public.to_raw_vec(); - let signature = SyncCryptoStore::sign_with( + let signature = Keystore::sign_with( &*self.keystore, as AppKey>::ID, &public_type_pair, @@ -798,7 +798,7 @@ mod tests { LocalKeystore::open(keystore_path.path(), None).expect("Creates keystore."), ); - SyncCryptoStore::sr25519_generate_new(&*keystore, AURA, Some(&key.to_seed())) + Keystore::sr25519_generate_new(&*keystore, AURA, Some(&key.to_seed())) .expect("Creates authority key"); keystore_paths.push(keystore_path); @@ -883,7 +883,7 @@ mod tests { let keystore_path = tempfile::tempdir().expect("Creates keystore path"); let keystore = LocalKeystore::open(keystore_path.path(), None).expect("Creates keystore."); - let public = SyncCryptoStore::sr25519_generate_new(&keystore, AuthorityPair::ID, None) + let public = Keystore::sr25519_generate_new(&keystore, AuthorityPair::ID, None) .expect("Key should be created"); authorities.push(public.into()); @@ -933,7 +933,7 @@ mod tests { let keystore_path = tempfile::tempdir().expect("Creates keystore path"); let keystore = LocalKeystore::open(keystore_path.path(), None).expect("Creates keystore."); - SyncCryptoStore::sr25519_generate_new( + Keystore::sr25519_generate_new( &keystore, AuthorityPair::ID, Some(&Keyring::Alice.to_seed()), diff --git a/client/consensus/babe/rpc/src/lib.rs b/client/consensus/babe/rpc/src/lib.rs index 677a4ad92c9e1..bc4d1c17eb3f1 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::{SyncCryptoStore, SyncCryptoStorePtr}; +use sp_keystore::{Keystore, KeystorePtr}; use sp_runtime::traits::{Block as BlockT, Header as _}; use std::{collections::HashMap, sync::Arc}; @@ -57,7 +57,7 @@ pub struct Babe { /// shared reference to EpochChanges shared_epoch_changes: SharedEpochChanges, /// shared reference to the Keystore - keystore: SyncCryptoStorePtr, + keystore: KeystorePtr, /// config (actually holds the slot duration) babe_config: BabeConfiguration, /// The SelectChain strategy @@ -71,7 +71,7 @@ impl Babe { pub fn new( client: Arc, shared_epoch_changes: SharedEpochChanges, - keystore: SyncCryptoStorePtr, + keystore: KeystorePtr, babe_config: BabeConfiguration, select_chain: SC, deny_unsafe: DenyUnsafe, @@ -117,10 +117,7 @@ where .iter() .enumerate() .filter_map(|(i, a)| { - if SyncCryptoStore::has_keys( - &*self.keystore, - &[(a.0.to_raw_vec(), AuthorityId::ID)], - ) { + if Keystore::has_keys(&*self.keystore, &[(a.0.to_raw_vec(), AuthorityId::ID)]) { Some((a.0.clone(), i)) } else { None @@ -217,7 +214,7 @@ mod tests { use sp_application_crypto::AppPair; use sp_core::crypto::key_types::BABE; use sp_keyring::Sr25519Keyring; - use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; + use sp_keystore::{Keystore, KeystorePtr}; use substrate_test_runtime_client::{ runtime::Block, Backend, DefaultTestClientBuilderExt, TestClient, TestClientBuilder, TestClientBuilderExt, @@ -229,11 +226,11 @@ mod tests { /// creates keystore backed by a temp file fn create_temp_keystore( authority: Sr25519Keyring, - ) -> (SyncCryptoStorePtr, tempfile::TempDir) { + ) -> (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")); - SyncCryptoStore::sr25519_generate_new(&*keystore, BABE, Some(&authority.to_seed())) + Keystore::sr25519_generate_new(&*keystore, BABE, Some(&authority.to_seed())) .expect("Creates authority key"); (keystore, keystore_path) diff --git a/client/consensus/babe/src/authorship.rs b/client/consensus/babe/src/authorship.rs index 195a19b3d0f61..956e886d1254c 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::{SyncCryptoStore, SyncCryptoStorePtr}; +use sp_keystore::{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). @@ -133,7 +133,7 @@ fn claim_secondary_slot( slot: Slot, epoch: &Epoch, keys: &[(AuthorityId, usize)], - keystore: &SyncCryptoStorePtr, + keystore: &KeystorePtr, author_secondary_vrf: bool, ) -> Option<(PreDigest, AuthorityId)> { let Epoch { authorities, randomness, mut epoch_index, .. } = epoch; @@ -153,7 +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 = SyncCryptoStore::sr25519_vrf_sign( + let result = Keystore::sr25519_vrf_sign( &**keystore, AuthorityId::ID, authority_id.as_ref(), @@ -169,7 +169,7 @@ fn claim_secondary_slot( } else { None } - } else if SyncCryptoStore::has_keys( + } else if Keystore::has_keys( &**keystore, &[(authority_id.to_raw_vec(), AuthorityId::ID)], ) { @@ -197,7 +197,7 @@ fn claim_secondary_slot( pub fn claim_slot( slot: Slot, epoch: &Epoch, - keystore: &SyncCryptoStorePtr, + keystore: &KeystorePtr, ) -> Option<(PreDigest, AuthorityId)> { let authorities = epoch .authorities @@ -213,7 +213,7 @@ pub fn claim_slot( pub fn claim_slot_using_keys( slot: Slot, epoch: &Epoch, - keystore: &SyncCryptoStorePtr, + keystore: &KeystorePtr, keys: &[(AuthorityId, usize)], ) -> Option<(PreDigest, AuthorityId)> { claim_primary_slot(slot, epoch, epoch.config.c, keystore, keys).or_else(|| { @@ -241,7 +241,7 @@ fn claim_primary_slot( slot: Slot, epoch: &Epoch, c: (u64, u64), - keystore: &SyncCryptoStorePtr, + keystore: &KeystorePtr, keys: &[(AuthorityId, usize)], ) -> Option<(PreDigest, AuthorityId)> { let Epoch { authorities, randomness, mut epoch_index, .. } = epoch; @@ -254,7 +254,7 @@ 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 = SyncCryptoStore::sr25519_vrf_sign( + let result = Keystore::sr25519_vrf_sign( &**keystore, AuthorityId::ID, authority_id.as_ref(), @@ -294,8 +294,8 @@ mod tests { #[test] fn claim_secondary_plain_slot_works() { - let keystore: SyncCryptoStorePtr = Arc::new(LocalKeystore::in_memory()); - let valid_public_key = SyncCryptoStore::sr25519_generate_new( + 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), diff --git a/client/consensus/babe/src/lib.rs b/client/consensus/babe/src/lib.rs index 1d42057a36b23..621aac391630b 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::{SyncCryptoStore, SyncCryptoStorePtr}; +use sp_keystore::{Keystore, KeystorePtr}; use sp_runtime::{ generic::OpaqueDigestItemId, traits::{Block as BlockT, Header, NumberFor, SaturatedConversion, Zero}, @@ -404,7 +404,7 @@ where /// Parameters for BABE. pub struct BabeParams { /// The keystore that manages the keys of the node. - pub keystore: SyncCryptoStorePtr, + pub keystore: KeystorePtr, /// The client to use pub client: Arc, @@ -711,7 +711,7 @@ struct BabeSlotWorker { justification_sync_link: L, force_authoring: bool, backoff_authoring_blocks: Option, - keystore: SyncCryptoStorePtr, + keystore: KeystorePtr, epoch_changes: SharedEpochChanges, slot_notification_sinks: SlotNotificationSinks, config: BabeConfiguration, @@ -834,7 +834,7 @@ where // add it to a digest item. let public_type_pair = public.clone().into(); let public = public.to_raw_vec(); - let signature = SyncCryptoStore::sign_with( + let signature = Keystore::sign_with( &*self.keystore, ::ID, &public_type_pair, diff --git a/client/consensus/babe/src/tests.rs b/client/consensus/babe/src/tests.rs index 25f1f87235702..4ac15bf2634d7 100644 --- a/client/consensus/babe/src/tests.rs +++ b/client/consensus/babe/src/tests.rs @@ -41,8 +41,7 @@ use sp_consensus_vrf::schnorrkel::VRFOutput; use sp_core::crypto::Pair; use sp_keyring::Sr25519Keyring; use sp_keystore::{ - testing::KeyStore as TestKeyStore, vrf::make_transcript as transcript_from_data, - SyncCryptoStore, + testing::MemoryKeystore, vrf::make_transcript as transcript_from_data, Keystore, }; use sp_runtime::{ generic::{Digest, DigestItem}, @@ -369,9 +368,9 @@ async fn rejects_empty_block() { }) } -fn create_keystore(authority: Sr25519Keyring) -> SyncCryptoStorePtr { - let keystore = Arc::new(TestKeyStore::new()); - SyncCryptoStore::sr25519_generate_new(&*keystore, BABE, Some(&authority.to_seed())) +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"); keystore } @@ -638,7 +637,7 @@ 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 = SyncCryptoStore::sr25519_vrf_sign(&*keystore, AuthorityId::ID, &public, transcript) + let sign = Keystore::sr25519_vrf_sign(&*keystore, AuthorityId::ID, &public, transcript) .unwrap() .unwrap(); assert_eq!(pre_digest.vrf_output, VRFOutput(sign.output)); @@ -649,7 +648,7 @@ 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 = SyncCryptoStore::sr25519_vrf_sign(&*keystore, AuthorityId::ID, &public, transcript) + let sign = Keystore::sr25519_vrf_sign(&*keystore, AuthorityId::ID, &public, transcript) .unwrap() .unwrap(); assert_eq!(pre_digest.vrf_output, VRFOutput(sign.output)); @@ -662,7 +661,7 @@ 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 = SyncCryptoStore::sr25519_vrf_sign(&*keystore, AuthorityId::ID, &public, transcript) + let sign = Keystore::sr25519_vrf_sign(&*keystore, AuthorityId::ID, &public, transcript) .unwrap() .unwrap(); assert_eq!(fixed_epoch.epoch_index, 11); @@ -676,7 +675,7 @@ 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 = SyncCryptoStore::sr25519_vrf_sign(&*keystore, AuthorityId::ID, &public, transcript) + let sign = Keystore::sr25519_vrf_sign(&*keystore, 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 e49382251e846..4bbd7a7f68d5c 100644 --- a/client/consensus/beefy/src/communication/gossip.rs +++ b/client/consensus/beefy/src/communication/gossip.rs @@ -245,7 +245,7 @@ where mod tests { use sc_keystore::LocalKeystore; use sc_network_test::Block; - use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; + use sp_keystore::{Keystore, KeystorePtr}; use crate::keystore::BeefyKeystore; use sp_consensus_beefy::{ @@ -306,8 +306,8 @@ mod tests { } fn sign_commitment(who: &Keyring, commitment: &Commitment) -> Signature { - let store: SyncCryptoStorePtr = std::sync::Arc::new(LocalKeystore::in_memory()); - SyncCryptoStore::ecdsa_generate_new(&*store, KEY_TYPE, Some(&who.to_seed())).unwrap(); + 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(); 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 421f7149018c8..596e8f2eb9c6d 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::{SyncCryptoStore, SyncCryptoStorePtr}; +use sp_keystore::{Keystore, KeystorePtr}; use log::warn; @@ -33,9 +33,9 @@ use crate::{error, LOG_TARGET}; pub(crate) type BeefySignatureHasher = sp_runtime::traits::Keccak256; /// A BEEFY specific keystore implemented as a `Newtype`. This is basically a -/// wrapper around [`sp_keystore::SyncCryptoStore`] and allows to customize +/// wrapper around [`sp_keystore::Keystore`] and allows to customize /// common cryptographic functionality. -pub(crate) struct BeefyKeystore(Option); +pub(crate) struct BeefyKeystore(Option); impl BeefyKeystore { /// Check if the keystore contains a private key for one of the public keys @@ -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| SyncCryptoStore::has_keys(&*store, &[(k.to_raw_vec(), KEY_TYPE)])) + .filter(|k| Keystore::has_keys(&*store, &[(k.to_raw_vec(), KEY_TYPE)])) .cloned() .collect(); @@ -77,7 +77,7 @@ impl BeefyKeystore { let msg = keccak_256(message); let public = public.as_ref(); - let sig = SyncCryptoStore::ecdsa_sign_prehashed(&*store, KEY_TYPE, public, &msg) + let sig = Keystore::ecdsa_sign_prehashed(&*store, 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,7 +94,7 @@ 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 = SyncCryptoStore::ecdsa_public_keys(&*store, KEY_TYPE) + let pk: Vec = Keystore::ecdsa_public_keys(&*store, KEY_TYPE) .drain(..) .map(Public::from) .collect(); @@ -110,8 +110,8 @@ impl BeefyKeystore { } } -impl From> for BeefyKeystore { - fn from(store: Option) -> BeefyKeystore { +impl From> for BeefyKeystore { + fn from(store: Option) -> BeefyKeystore { BeefyKeystore(store) } } @@ -128,7 +128,7 @@ pub mod tests { use super::*; use crate::error::Error; - fn keystore() -> SyncCryptoStorePtr { + fn keystore() -> KeystorePtr { Arc::new(LocalKeystore::in_memory()) } @@ -198,7 +198,7 @@ pub mod tests { let store = keystore(); let alice: crypto::Public = - SyncCryptoStore::ecdsa_generate_new(&*store, KEY_TYPE, Some(&Keyring::Alice.to_seed())) + Keystore::ecdsa_generate_new(&*store, KEY_TYPE, Some(&Keyring::Alice.to_seed())) .ok() .unwrap() .into(); @@ -224,7 +224,7 @@ pub mod tests { let store = keystore(); let alice: crypto::Public = - SyncCryptoStore::ecdsa_generate_new(&*store, KEY_TYPE, Some(&Keyring::Alice.to_seed())) + Keystore::ecdsa_generate_new(&*store, KEY_TYPE, Some(&Keyring::Alice.to_seed())) .ok() .unwrap() .into(); @@ -243,10 +243,9 @@ pub mod tests { fn sign_error() { let store = keystore(); - let _ = - SyncCryptoStore::ecdsa_generate_new(&*store, KEY_TYPE, Some(&Keyring::Bob.to_seed())) - .ok() - .unwrap(); + let _ = Keystore::ecdsa_generate_new(&*store, KEY_TYPE, Some(&Keyring::Bob.to_seed())) + .ok() + .unwrap(); let store: BeefyKeystore = Some(store).into(); @@ -276,7 +275,7 @@ pub mod tests { let store = keystore(); let alice: crypto::Public = - SyncCryptoStore::ecdsa_generate_new(&*store, KEY_TYPE, Some(&Keyring::Alice.to_seed())) + Keystore::ecdsa_generate_new(&*store, KEY_TYPE, Some(&Keyring::Alice.to_seed())) .ok() .unwrap() .into(); @@ -302,7 +301,7 @@ pub mod tests { let store = keystore(); let add_key = |key_type, seed: Option<&str>| { - SyncCryptoStore::ecdsa_generate_new(&*store, key_type, seed).unwrap() + Keystore::ecdsa_generate_new(&*store, key_type, seed).unwrap() }; // test keys diff --git a/client/consensus/beefy/src/lib.rs b/client/consensus/beefy/src/lib.rs index d632f58332a77..b84fa45e7e2f3 100644 --- a/client/consensus/beefy/src/lib.rs +++ b/client/consensus/beefy/src/lib.rs @@ -49,7 +49,7 @@ use sp_consensus_beefy::{ crypto::AuthorityId, BeefyApi, MmrRootHash, PayloadProvider, ValidatorSet, BEEFY_ENGINE_ID, GENESIS_AUTHORITY_SET_ID, }; -use sp_keystore::SyncCryptoStorePtr; +use sp_keystore::KeystorePtr; use sp_mmr_primitives::MmrApi; use sp_runtime::traits::{Block, Zero}; use std::{collections::VecDeque, marker::PhantomData, sync::Arc}; @@ -197,7 +197,7 @@ pub struct BeefyParams { /// Runtime Api Provider pub runtime: Arc, /// Local key store - pub key_store: Option, + pub key_store: Option, /// BEEFY voter network params pub network_params: BeefyNetworkParams, /// Minimal delta between blocks, BEEFY should vote for diff --git a/client/consensus/beefy/src/tests.rs b/client/consensus/beefy/src/tests.rs index 629f144246d7f..9a3653f7cc549 100644 --- a/client/consensus/beefy/src/tests.rs +++ b/client/consensus/beefy/src/tests.rs @@ -54,7 +54,7 @@ use sp_consensus_beefy::{ VersionedFinalityProof, BEEFY_ENGINE_ID, KEY_TYPE as BeefyKeyType, }; use sp_core::H256; -use sp_keystore::{testing::KeyStore as TestKeystore, SyncCryptoStore, SyncCryptoStorePtr}; +use sp_keystore::{testing::MemoryKeystore, Keystore, KeystorePtr}; use sp_mmr_primitives::{Error as MmrError, MmrApi}; use sp_runtime::{ codec::Encode, @@ -339,9 +339,9 @@ pub(crate) fn make_beefy_ids(keys: &[BeefyKeyring]) -> Vec { keys.iter().map(|&key| key.public().into()).collect() } -pub(crate) fn create_beefy_keystore(authority: BeefyKeyring) -> SyncCryptoStorePtr { - let keystore = Arc::new(TestKeystore::new()); - SyncCryptoStore::ecdsa_generate_new(&*keystore, BeefyKeyType, Some(&authority.to_seed())) +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"); keystore } diff --git a/client/consensus/grandpa/src/communication/mod.rs b/client/consensus/grandpa/src/communication/mod.rs index 3896bc36031ba..81365c20b1ebe 100644 --- a/client/consensus/grandpa/src/communication/mod.rs +++ b/client/consensus/grandpa/src/communication/mod.rs @@ -49,7 +49,7 @@ use parity_scale_codec::{Decode, Encode}; use sc_network::{NetworkBlock, NetworkSyncForkRequest, ReputationChange}; use sc_network_gossip::{GossipEngine, Network as GossipNetwork}; use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_DEBUG, CONSENSUS_INFO}; -use sp_keystore::SyncCryptoStorePtr; +use sp_keystore::KeystorePtr; use sp_runtime::traits::{Block as BlockT, Hash as HashT, Header as HeaderT, NumberFor}; use crate::{ @@ -136,7 +136,7 @@ mod benefit { /// A type that ties together our local authority id and a keystore where it is /// available for signing. -pub struct LocalIdKeystore((AuthorityId, SyncCryptoStorePtr)); +pub struct LocalIdKeystore((AuthorityId, KeystorePtr)); impl LocalIdKeystore { /// Returns a reference to our local authority id. @@ -145,13 +145,13 @@ impl LocalIdKeystore { } /// Returns a reference to the keystore. - fn keystore(&self) -> SyncCryptoStorePtr { + fn keystore(&self) -> KeystorePtr { (self.0).1.clone() } } -impl From<(AuthorityId, SyncCryptoStorePtr)> for LocalIdKeystore { - fn from(inner: (AuthorityId, SyncCryptoStorePtr)) -> LocalIdKeystore { +impl From<(AuthorityId, KeystorePtr)> for LocalIdKeystore { + fn from(inner: (AuthorityId, KeystorePtr)) -> LocalIdKeystore { LocalIdKeystore(inner) } } diff --git a/client/consensus/grandpa/src/lib.rs b/client/consensus/grandpa/src/lib.rs index 2baa135081c55..6b3730fc7f476 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::{SyncCryptoStore, SyncCryptoStorePtr}; +use sp_keystore::{Keystore, KeystorePtr}; use sp_runtime::{ generic::BlockId, traits::{Block as BlockT, NumberFor, Zero}, @@ -228,7 +228,7 @@ pub struct Config { /// Some local identifier of the voter. pub name: Option, /// The keystore that manages the keys of this node. - pub keystore: Option, + pub keystore: Option, /// TelemetryHandle instance. pub telemetry: Option, /// Chain specific GRANDPA protocol name. See [`crate::protocol_standard_name`]. @@ -623,7 +623,7 @@ fn global_communication( voters: &Arc>, client: Arc, network: &NetworkBridge, - keystore: Option<&SyncCryptoStorePtr>, + keystore: Option<&KeystorePtr>, metrics: Option, ) -> ( impl Stream< @@ -1136,14 +1136,12 @@ where /// available. fn local_authority_id( voters: &VoterSet, - keystore: Option<&SyncCryptoStorePtr>, + keystore: Option<&KeystorePtr>, ) -> Option { keystore.and_then(|keystore| { voters .iter() - .find(|(p, _)| { - SyncCryptoStore::has_keys(&**keystore, &[(p.to_raw_vec(), AuthorityId::ID)]) - }) + .find(|(p, _)| Keystore::has_keys(&**keystore, &[(p.to_raw_vec(), AuthorityId::ID)])) .map(|(p, _)| p.clone()) }) } diff --git a/client/consensus/grandpa/src/observer.rs b/client/consensus/grandpa/src/observer.rs index 53672c1f02225..8541baa822bb4 100644 --- a/client/consensus/grandpa/src/observer.rs +++ b/client/consensus/grandpa/src/observer.rs @@ -33,7 +33,7 @@ use sc_utils::mpsc::TracingUnboundedReceiver; use sp_blockchain::HeaderMetadata; use sp_consensus::SelectChain; use sp_consensus_grandpa::AuthorityId; -use sp_keystore::SyncCryptoStorePtr; +use sp_keystore::KeystorePtr; use sp_runtime::traits::{Block as BlockT, NumberFor}; use crate::{ @@ -220,7 +220,7 @@ struct ObserverWork, S: SyncingT> { client: Arc, network: NetworkBridge, persistent_data: PersistentData, - keystore: Option, + keystore: Option, voter_commands_rx: TracingUnboundedReceiver>>, justification_sender: Option>, telemetry: Option, @@ -240,7 +240,7 @@ where client: Arc, network: NetworkBridge, persistent_data: PersistentData, - keystore: Option, + keystore: Option, voter_commands_rx: TracingUnboundedReceiver>>, justification_sender: Option>, telemetry: Option, diff --git a/client/consensus/grandpa/src/tests.rs b/client/consensus/grandpa/src/tests.rs index f5e5c45e74207..6f19ca7391e65 100644 --- a/client/consensus/grandpa/src/tests.rs +++ b/client/consensus/grandpa/src/tests.rs @@ -40,7 +40,7 @@ use sp_consensus_grandpa::{ }; use sp_core::H256; use sp_keyring::Ed25519Keyring; -use sp_keystore::{testing::KeyStore as TestKeyStore, SyncCryptoStore, SyncCryptoStorePtr}; +use sp_keystore::{testing::MemoryKeystore, Keystore, KeystorePtr}; use sp_runtime::{ codec::Encode, generic::{BlockId, DigestItem}, @@ -280,9 +280,9 @@ fn make_ids(keys: &[Ed25519Keyring]) -> AuthorityList { keys.iter().map(|&key| key.public().into()).map(|id| (id, 1)).collect() } -fn create_keystore(authority: Ed25519Keyring) -> SyncCryptoStorePtr { - let keystore = Arc::new(TestKeyStore::new()); - SyncCryptoStore::ed25519_generate_new(&*keystore, GRANDPA, Some(&authority.to_seed())) +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"); keystore } @@ -1376,7 +1376,7 @@ type TestEnvironment = fn test_environment_with_select_chain( link: &TestLinkHalf, - keystore: Option, + keystore: Option, network_service: N, sync_service: S, select_chain: SC, @@ -1428,7 +1428,7 @@ where fn test_environment( link: &TestLinkHalf, - keystore: Option, + keystore: Option, network_service: N, sync_service: S, voting_rule: VR, diff --git a/client/consensus/manual-seal/src/consensus/babe.rs b/client/consensus/manual-seal/src/consensus/babe.rs index 3d21fd73d95ae..2485bd603e785 100644 --- a/client/consensus/manual-seal/src/consensus/babe.rs +++ b/client/consensus/manual-seal/src/consensus/babe.rs @@ -29,7 +29,7 @@ use sc_consensus_babe::{ use sc_consensus_epochs::{ descendent_query, EpochHeader, SharedEpochChanges, ViableEpochDescriptor, }; -use sp_keystore::SyncCryptoStorePtr; +use sp_keystore::KeystorePtr; use std::{marker::PhantomData, sync::Arc}; use sc_consensus::{BlockImportParams, ForkChoiceStrategy, Verifier}; @@ -53,7 +53,7 @@ use sp_timestamp::TimestampInherentData; /// Intended for use with BABE runtimes. pub struct BabeConsensusDataProvider { /// shared reference to keystore - keystore: SyncCryptoStorePtr, + keystore: KeystorePtr, /// Shared reference to the client. client: Arc, @@ -143,7 +143,7 @@ where { pub fn new( client: Arc, - keystore: SyncCryptoStorePtr, + keystore: KeystorePtr, epoch_changes: SharedEpochChanges, authorities: Vec<(AuthorityId, BabeAuthorityWeight)>, ) -> Result { diff --git a/client/keystore/src/local.rs b/client/keystore/src/local.rs index cd55739a9fac3..18ee58b8719b9 100644 --- a/client/keystore/src/local.rs +++ b/client/keystore/src/local.rs @@ -17,7 +17,6 @@ // //! Local keystore implementation -use async_trait::async_trait; use parking_lot::RwLock; use sp_application_crypto::{ecdsa, ed25519, sr25519, AppKey, AppPair, IsWrappedBy}; use sp_core::{ @@ -29,10 +28,10 @@ use sp_core::{ }; use sp_keystore::{ vrf::{make_transcript, VRFSignature, VRFTranscriptData}, - CryptoStore, Error as TraitError, SyncCryptoStore, SyncCryptoStorePtr, + Error as TraitError, Keystore, KeystorePtr, }; use std::{ - collections::{HashMap, HashSet}, + collections::HashMap, fs::{self, File}, io::Write, path::PathBuf, @@ -69,101 +68,7 @@ impl LocalKeystore { } } -#[async_trait] -impl CryptoStore for LocalKeystore { - async fn keys( - &self, - id: KeyTypeId, - ) -> std::result::Result, TraitError> { - SyncCryptoStore::keys(self, id) - } - - async fn sr25519_public_keys(&self, id: KeyTypeId) -> Vec { - SyncCryptoStore::sr25519_public_keys(self, id) - } - - async fn sr25519_generate_new( - &self, - id: KeyTypeId, - seed: Option<&str>, - ) -> std::result::Result { - SyncCryptoStore::sr25519_generate_new(self, id, seed) - } - - async fn ed25519_public_keys(&self, id: KeyTypeId) -> Vec { - SyncCryptoStore::ed25519_public_keys(self, id) - } - - async fn ed25519_generate_new( - &self, - id: KeyTypeId, - seed: Option<&str>, - ) -> std::result::Result { - SyncCryptoStore::ed25519_generate_new(self, id, seed) - } - - async fn ecdsa_public_keys(&self, id: KeyTypeId) -> Vec { - SyncCryptoStore::ecdsa_public_keys(self, id) - } - - async fn ecdsa_generate_new( - &self, - id: KeyTypeId, - seed: Option<&str>, - ) -> std::result::Result { - SyncCryptoStore::ecdsa_generate_new(self, id, seed) - } - - async fn insert_unknown( - &self, - id: KeyTypeId, - suri: &str, - public: &[u8], - ) -> std::result::Result<(), ()> { - SyncCryptoStore::insert_unknown(self, id, suri, public) - } - - async fn has_keys(&self, public_keys: &[(Vec, KeyTypeId)]) -> bool { - SyncCryptoStore::has_keys(self, public_keys) - } - - async fn supported_keys( - &self, - id: KeyTypeId, - keys: Vec, - ) -> std::result::Result, TraitError> { - SyncCryptoStore::supported_keys(self, id, keys) - } - - async fn sign_with( - &self, - id: KeyTypeId, - key: &CryptoTypePublicPair, - msg: &[u8], - ) -> std::result::Result>, TraitError> { - SyncCryptoStore::sign_with(self, id, key, msg) - } - - async fn sr25519_vrf_sign( - &self, - key_type: KeyTypeId, - public: &sr25519::Public, - transcript_data: VRFTranscriptData, - ) -> std::result::Result, TraitError> { - SyncCryptoStore::sr25519_vrf_sign(self, key_type, public, transcript_data) - } - - async fn ecdsa_sign_prehashed( - &self, - id: KeyTypeId, - public: &ecdsa::Public, - msg: &[u8; 32], - ) -> std::result::Result, TraitError> { - SyncCryptoStore::ecdsa_sign_prehashed(self, id, public, msg) - } -} - -impl SyncCryptoStore for LocalKeystore { +impl Keystore for LocalKeystore { fn keys(&self, id: KeyTypeId) -> std::result::Result, TraitError> { let raw_keys = self.0.read().raw_public_keys(id)?; Ok(raw_keys.into_iter().fold(Vec::new(), |mut v, k| { @@ -174,15 +79,6 @@ impl SyncCryptoStore for LocalKeystore { })) } - fn supported_keys( - &self, - id: KeyTypeId, - keys: Vec, - ) -> std::result::Result, TraitError> { - let all_keys = SyncCryptoStore::keys(self, id)?.into_iter().collect::>(); - Ok(keys.into_iter().filter(|key| all_keys.contains(key)).collect::>()) - } - fn sign_with( &self, id: KeyTypeId, @@ -308,13 +204,13 @@ impl SyncCryptoStore for LocalKeystore { Ok(pair.public()) } - fn insert_unknown( + fn insert( &self, key_type: KeyTypeId, suri: &str, public: &[u8], ) -> std::result::Result<(), ()> { - self.0.write().insert_unknown(key_type, suri, public).map_err(|_| ()) + self.0.write().insert(key_type, suri, public).map_err(|_| ()) } fn has_keys(&self, public_keys: &[(Vec, KeyTypeId)]) -> bool { @@ -352,14 +248,8 @@ impl SyncCryptoStore for LocalKeystore { } } -impl Into for LocalKeystore { - fn into(self) -> SyncCryptoStorePtr { - Arc::new(self) - } -} - -impl Into> for LocalKeystore { - fn into(self) -> Arc { +impl Into for LocalKeystore { + fn into(self) -> KeystorePtr { Arc::new(self) } } @@ -414,7 +304,7 @@ impl KeystoreInner { /// Insert a new key with anonymous crypto. /// /// Places it into the file system store, if a path is configured. - fn insert_unknown(&self, key_type: KeyTypeId, suri: &str, public: &[u8]) -> Result<()> { + fn insert(&self, key_type: KeyTypeId, suri: &str, public: &[u8]) -> Result<()> { if let Some(path) = self.key_file_path(public, key_type) { Self::write_to_file(path, suri)?; } @@ -614,12 +504,9 @@ mod tests { let key: ed25519::AppPair = store.0.write().generate().unwrap(); let key2 = ed25519::Pair::generate().0; - assert!(!SyncCryptoStore::has_keys( - &store, - &[(key2.public().to_vec(), ed25519::AppPublic::ID)] - )); + assert!(!Keystore::has_keys(&store, &[(key2.public().to_vec(), ed25519::AppPublic::ID)])); - assert!(!SyncCryptoStore::has_keys( + assert!(!Keystore::has_keys( &store, &[ (key2.public().to_vec(), ed25519::AppPublic::ID), @@ -627,10 +514,7 @@ mod tests { ], )); - assert!(SyncCryptoStore::has_keys( - &store, - &[(key.public().to_raw_vec(), ed25519::AppPublic::ID)] - )); + assert!(Keystore::has_keys(&store, &[(key.public().to_raw_vec(), ed25519::AppPublic::ID)])); } #[test] @@ -723,7 +607,7 @@ mod tests { let key_pair = sr25519::AppPair::from_string(secret_uri, None).expect("Generates key pair"); store - .insert_unknown(SR25519, secret_uri, key_pair.public().as_ref()) + .insert(SR25519, secret_uri, key_pair.public().as_ref()) .expect("Inserts unknown key"); let store_key_pair = store @@ -742,7 +626,7 @@ 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!(SyncCryptoStore::sr25519_public_keys(&store, SR25519).is_empty()); + assert!(Keystore::sr25519_public_keys(&store, SR25519).is_empty()); } #[test] @@ -750,23 +634,23 @@ mod tests { let temp_dir = TempDir::new().unwrap(); let store = LocalKeystore::open(temp_dir.path(), None).unwrap(); let _alice_tmp_key = - SyncCryptoStore::sr25519_generate_new(&store, TEST_KEY_TYPE, Some("//Alice")).unwrap(); + Keystore::sr25519_generate_new(&store, TEST_KEY_TYPE, Some("//Alice")).unwrap(); - assert_eq!(SyncCryptoStore::sr25519_public_keys(&store, TEST_KEY_TYPE).len(), 1); + assert_eq!(Keystore::sr25519_public_keys(&store, TEST_KEY_TYPE).len(), 1); drop(store); let store = LocalKeystore::open(temp_dir.path(), None).unwrap(); - assert_eq!(SyncCryptoStore::sr25519_public_keys(&store, TEST_KEY_TYPE).len(), 0); + assert_eq!(Keystore::sr25519_public_keys(&store, TEST_KEY_TYPE).len(), 0); } #[test] fn generate_can_be_fetched_in_memory() { let store = LocalKeystore::in_memory(); - SyncCryptoStore::sr25519_generate_new(&store, TEST_KEY_TYPE, Some("//Alice")).unwrap(); + Keystore::sr25519_generate_new(&store, TEST_KEY_TYPE, Some("//Alice")).unwrap(); - assert_eq!(SyncCryptoStore::sr25519_public_keys(&store, TEST_KEY_TYPE).len(), 1); - SyncCryptoStore::sr25519_generate_new(&store, TEST_KEY_TYPE, None).unwrap(); - assert_eq!(SyncCryptoStore::sr25519_public_keys(&store, TEST_KEY_TYPE).len(), 2); + 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); } #[test] @@ -777,7 +661,7 @@ mod tests { let temp_dir = TempDir::new().unwrap(); let store = LocalKeystore::open(temp_dir.path(), None).unwrap(); - let public = SyncCryptoStore::sr25519_generate_new(&store, TEST_KEY_TYPE, None).unwrap(); + let public = Keystore::sr25519_generate_new(&store, 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-api/src/author/error.rs b/client/rpc-api/src/author/error.rs index 7ca96bbab7f19..8149a1f8d1afe 100644 --- a/client/rpc-api/src/author/error.rs +++ b/client/rpc-api/src/author/error.rs @@ -47,7 +47,7 @@ pub enum Error { BadKeyType, /// Some random issue with the key store. Shouldn't happen. #[error("The key store is unavailable")] - KeyStoreUnavailable, + KeystoreUnavailable, /// Invalid session keys encoding. #[error("Session keys are not encoded correctly")] InvalidSessionKeys, diff --git a/client/rpc/src/author/mod.rs b/client/rpc/src/author/mod.rs index 2bb88352eb2e5..9752a32b17c67 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::{SyncCryptoStore, SyncCryptoStorePtr}; +use sp_keystore::{Keystore, KeystorePtr}; use sp_runtime::{generic, traits::Block as BlockT}; use sp_session::SessionKeys; @@ -55,7 +55,7 @@ pub struct Author { /// Transactions pool pool: Arc

, /// The key store. - keystore: SyncCryptoStorePtr, + keystore: KeystorePtr, /// Whether to deny unsafe calls deny_unsafe: DenyUnsafe, /// Executor to spawn subscriptions. @@ -67,7 +67,7 @@ impl Author { pub fn new( client: Arc, pool: Arc

, - keystore: SyncCryptoStorePtr, + keystore: KeystorePtr, deny_unsafe: DenyUnsafe, executor: SubscriptionTaskExecutor, ) -> Self { @@ -112,8 +112,8 @@ where self.deny_unsafe.check_if_safe()?; let key_type = key_type.as_str().try_into().map_err(|_| Error::BadKeyType)?; - SyncCryptoStore::insert_unknown(&*self.keystore, key_type, &suri, &public[..]) - .map_err(|_| Error::KeyStoreUnavailable)?; + Keystore::insert(&*self.keystore, key_type, &suri, &public[..]) + .map_err(|_| Error::KeystoreUnavailable)?; Ok(()) } @@ -139,14 +139,14 @@ where .map_err(|e| Error::Client(Box::new(e)))? .ok_or(Error::InvalidSessionKeys)?; - Ok(SyncCryptoStore::has_keys(&*self.keystore, &keys)) + Ok(Keystore::has_keys(&*self.keystore, &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(SyncCryptoStore::has_keys(&*self.keystore, &[(public_key.to_vec(), key_type)])) + Ok(Keystore::has_keys(&*self.keystore, &[(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 bf880cfbcfe9b..209673fce2602 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::KeyStore; +use sp_keystore::testing::MemoryKeystore; use std::sync::Arc; use substrate_test_runtime_client::{ self, @@ -58,13 +58,13 @@ type FullTransactionPool = BasicPool, Block>, Block struct TestSetup { pub client: Arc>, - pub keystore: Arc, + pub keystore: Arc, pub pool: Arc, } impl Default for TestSetup { fn default() -> Self { - let keystore = Arc::new(KeyStore::new()); + let keystore = Arc::new(MemoryKeystore::new()); let client_builder = substrate_test_runtime_client::TestClientBuilder::new(); let client = Arc::new(client_builder.set_keystore(keystore.clone()).build()); @@ -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 = SyncCryptoStore::keys(&*setup.keystore, ED25519).unwrap(); + let pubkeys = Keystore::keys(&*setup.keystore, 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 = SyncCryptoStore::keys(&*setup.keystore, ED25519).unwrap(); - let sr25519_pubkeys = SyncCryptoStore::keys(&*setup.keystore, SR25519).unwrap(); + let ed25519_pubkeys = Keystore::keys(&*setup.keystore, ED25519).unwrap(); + let sr25519_pubkeys = Keystore::keys(&*setup.keystore, 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 1d8cbae004eee..efe4b010057c0 100644 --- a/client/service/src/builder.rs +++ b/client/service/src/builder.rs @@ -65,7 +65,7 @@ use sp_consensus::block_validation::{ BlockAnnounceValidator, Chain, DefaultBlockAnnounceValidator, }; use sp_core::traits::{CodeExecutor, SpawnNamed}; -use sp_keystore::{CryptoStore, SyncCryptoStore, SyncCryptoStorePtr}; +use sp_keystore::{Keystore, KeystorePtr}; use sp_runtime::traits::{Block as BlockT, BlockIdTo, NumberFor, Zero}; use std::{str::FromStr, sync::Arc, time::SystemTime}; @@ -83,26 +83,22 @@ pub type TFullCallExecutor = type TFullParts = (TFullClient, Arc>, KeystoreContainer, TaskManager); -trait AsCryptoStoreRef { - fn keystore_ref(&self) -> Arc; - fn sync_keystore_ref(&self) -> Arc; +trait AsKeystoreRef { + fn keystore_ref(&self) -> Arc; } -impl AsCryptoStoreRef for Arc +impl AsKeystoreRef for Arc where - T: CryptoStore + SyncCryptoStore + 'static, + T: Keystore + 'static, { - fn keystore_ref(&self) -> Arc { - self.clone() - } - fn sync_keystore_ref(&self) -> Arc { + fn keystore_ref(&self) -> Arc { self.clone() } } /// Construct and hold different layers of Keystore wrappers pub struct KeystoreContainer { - remote: Option>, + remote: Option>, local: Arc, } @@ -125,13 +121,13 @@ impl KeystoreContainer { /// stick around. pub fn set_remote_keystore(&mut self, remote: Arc) where - T: CryptoStore + SyncCryptoStore + 'static, + T: Keystore + 'static, { self.remote = Some(Box::new(remote)) } - /// Returns an adapter to the asynchronous keystore that implements `CryptoStore` - pub fn keystore(&self) -> Arc { + /// Returns an adapter to a `Keystore` implementation. + pub fn keystore(&self) -> Arc { if let Some(c) = self.remote.as_ref() { c.keystore_ref() } else { @@ -139,15 +135,6 @@ impl KeystoreContainer { } } - /// Returns the synchronous keystore wrapper - pub fn sync_keystore(&self) -> SyncCryptoStorePtr { - if let Some(c) = self.remote.as_ref() { - c.sync_keystore_ref() - } else { - self.local.clone() as SyncCryptoStorePtr - } - } - /// Returns the local keystore if available /// /// The function will return None if the available keystore is not a local keystore. @@ -232,7 +219,7 @@ where let client = { let extensions = sc_client_api::execution_extensions::ExecutionExtensions::new( config.execution_strategies.clone(), - Some(keystore_container.sync_keystore()), + Some(keystore_container.keystore()), sc_offchain::OffchainDb::factory_from_backend(&*backend), ); @@ -372,7 +359,7 @@ pub struct SpawnTasksParams<'a, TBl: BlockT, TCl, TExPool, TRpc, Backend> { /// A task manager returned by `new_full_parts`. pub task_manager: &'a mut TaskManager, /// A shared keystore returned by `new_full_parts`. - pub keystore: SyncCryptoStorePtr, + pub keystore: KeystorePtr, /// A shared transaction pool. pub transaction_pool: Arc, /// Builds additional [`RpcModule`]s that should be added to the server @@ -643,7 +630,7 @@ fn gen_rpc_module( spawn_handle: SpawnTaskHandle, client: Arc, transaction_pool: Arc, - keystore: SyncCryptoStorePtr, + keystore: KeystorePtr, system_rpc_tx: TracingUnboundedSender>, config: &Configuration, backend: Arc, diff --git a/client/service/src/client/client.rs b/client/service/src/client/client.rs index 3613cc760f569..d5212021f2d79 100644 --- a/client/service/src/client/client.rs +++ b/client/service/src/client/client.rs @@ -65,7 +65,7 @@ use sp_core::{ traits::SpawnNamed, }; #[cfg(feature = "test-helpers")] -use sp_keystore::SyncCryptoStorePtr; +use sp_keystore::KeystorePtr; use sp_runtime::{ generic::{BlockId, SignedBlock}, traits::{ @@ -161,7 +161,7 @@ pub fn new_in_mem( backend: Arc>, executor: E, genesis_block_builder: G, - keystore: Option, + keystore: Option, prometheus_registry: Option, telemetry: Option, spawn_handle: Box, @@ -224,7 +224,7 @@ pub fn new_with_backend( backend: Arc, executor: E, genesis_block_builder: G, - keystore: Option, + keystore: Option, spawn_handle: Box, prometheus_registry: Option, telemetry: Option, diff --git a/frame/benchmarking/src/baseline.rs b/frame/benchmarking/src/baseline.rs index 11d4ba5011a2f..1f6e9c5a68892 100644 --- a/frame/benchmarking/src/baseline.rs +++ b/frame/benchmarking/src/baseline.rs @@ -160,12 +160,12 @@ pub mod mock { impl super::Config for Test {} pub fn new_test_ext() -> sp_io::TestExternalities { - use sp_keystore::{testing::KeyStore, KeystoreExt, SyncCryptoStorePtr}; + use sp_keystore::{testing::MemoryKeystore, KeystoreExt, KeystorePtr}; use sp_std::sync::Arc; let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); let mut ext = sp_io::TestExternalities::new(t); - ext.register_extension(KeystoreExt(Arc::new(KeyStore::new()) as SyncCryptoStorePtr)); + ext.register_extension(KeystoreExt(Arc::new(MemoryKeystore::new()) as KeystorePtr)); ext } diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index d74b08243df4b..ba9873f07efee 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -44,7 +44,7 @@ use frame_support::{ use frame_system::{self as system, EventRecord, Phase}; use pretty_assertions::{assert_eq, assert_ne}; use sp_io::hashing::blake2_256; -use sp_keystore::{testing::KeyStore, KeystoreExt}; +use sp_keystore::{testing::MemoryKeystore, KeystoreExt}; use sp_runtime::{ testing::{Header, H256}, traits::{BlakeTwo256, Convert, Hash, IdentityLookup}, @@ -440,7 +440,7 @@ impl ExtBuilder { .assimilate_storage(&mut t) .unwrap(); let mut ext = sp_io::TestExternalities::new(t); - ext.register_extension(KeystoreExt(Arc::new(KeyStore::new()))); + ext.register_extension(KeystoreExt(Arc::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 75a42e872ae52..c513590435252 100644 --- a/frame/examples/offchain-worker/src/tests.rs +++ b/frame/examples/offchain-worker/src/tests.rs @@ -29,7 +29,7 @@ use sp_core::{ }; use std::sync::Arc; -use sp_keystore::{testing::KeyStore, KeystoreExt, SyncCryptoStore}; +use sp_keystore::{testing::MemoryKeystore, Keystore, KeystoreExt}; use sp_runtime::{ testing::{Header, TestXt}, traits::{BlakeTwo256, Extrinsic as ExtrinsicT, IdentifyAccount, IdentityLookup, Verify}, @@ -205,8 +205,8 @@ fn should_submit_signed_transaction_on_chain() { let (offchain, offchain_state) = testing::TestOffchainExt::new(); let (pool, pool_state) = testing::TestTransactionPoolExt::new(); - let keystore = KeyStore::new(); - SyncCryptoStore::sr25519_generate_new( + let keystore = MemoryKeystore::new(); + Keystore::sr25519_generate_new( &keystore, crate::crypto::Public::ID, Some(&format!("{}/hunter1", PHRASE)), @@ -239,16 +239,16 @@ fn should_submit_unsigned_transaction_on_chain_for_any_account() { let (offchain, offchain_state) = testing::TestOffchainExt::new(); let (pool, pool_state) = testing::TestTransactionPoolExt::new(); - let keystore = KeyStore::new(); + let keystore = MemoryKeystore::new(); - SyncCryptoStore::sr25519_generate_new( + Keystore::sr25519_generate_new( &keystore, crate::crypto::Public::ID, Some(&format!("{}/hunter1", PHRASE)), ) .unwrap(); - let public_key = *SyncCryptoStore::sr25519_public_keys(&keystore, crate::crypto::Public::ID) + let public_key = *Keystore::sr25519_public_keys(&keystore, crate::crypto::Public::ID) .get(0) .unwrap(); @@ -298,16 +298,16 @@ fn should_submit_unsigned_transaction_on_chain_for_all_accounts() { let (offchain, offchain_state) = testing::TestOffchainExt::new(); let (pool, pool_state) = testing::TestTransactionPoolExt::new(); - let keystore = KeyStore::new(); + let keystore = MemoryKeystore::new(); - SyncCryptoStore::sr25519_generate_new( + Keystore::sr25519_generate_new( &keystore, crate::crypto::Public::ID, Some(&format!("{}/hunter1", PHRASE)), ) .unwrap(); - let public_key = *SyncCryptoStore::sr25519_public_keys(&keystore, crate::crypto::Public::ID) + let public_key = *Keystore::sr25519_public_keys(&keystore, crate::crypto::Public::ID) .get(0) .unwrap(); @@ -355,7 +355,7 @@ fn should_submit_raw_unsigned_transaction_on_chain() { let (offchain, offchain_state) = testing::TestOffchainExt::new(); let (pool, pool_state) = testing::TestTransactionPoolExt::new(); - let keystore = KeyStore::new(); + let keystore = MemoryKeystore::new(); let mut t = sp_io::TestExternalities::default(); t.register_extension(OffchainWorkerExt::new(offchain)); diff --git a/frame/nfts/src/mock.rs b/frame/nfts/src/mock.rs index a9db1a62c9d67..f21547b720c34 100644 --- a/frame/nfts/src/mock.rs +++ b/frame/nfts/src/mock.rs @@ -25,7 +25,7 @@ use frame_support::{ traits::{AsEnsureOriginWithArg, ConstU32, ConstU64}, }; use sp_core::H256; -use sp_keystore::{testing::KeyStore, KeystoreExt}; +use sp_keystore::{testing::MemoryKeystore, KeystoreExt}; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, @@ -130,7 +130,7 @@ impl Config for Test { pub(crate) fn new_test_ext() -> sp_io::TestExternalities { let t = frame_system::GenesisConfig::default().build_storage::().unwrap(); - let keystore = KeyStore::new(); + let keystore = MemoryKeystore::new(); let mut ext = sp_io::TestExternalities::new(t); ext.register_extension(KeystoreExt(Arc::new(keystore))); ext.execute_with(|| System::set_block_number(1)); diff --git a/primitives/application-crypto/test/src/ecdsa.rs b/primitives/application-crypto/test/src/ecdsa.rs index df3be6f934304..7b96b42d5556b 100644 --- a/primitives/application-crypto/test/src/ecdsa.rs +++ b/primitives/application-crypto/test/src/ecdsa.rs @@ -19,7 +19,7 @@ use sp_api::ProvideRuntimeApi; use sp_application_crypto::ecdsa::{AppPair, AppPublic}; use sp_core::{crypto::Pair, testing::ECDSA}; -use sp_keystore::{testing::KeyStore, SyncCryptoStore}; +use sp_keystore::{testing::MemoryKeystore, Keystore}; use std::sync::Arc; use substrate_test_runtime_client::{ runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, TestClientBuilderExt, @@ -27,14 +27,14 @@ use substrate_test_runtime_client::{ #[test] fn ecdsa_works_in_runtime() { - let keystore = Arc::new(KeyStore::new()); + let keystore = Arc::new(MemoryKeystore::new()); let test_client = TestClientBuilder::new().set_keystore(keystore.clone()).build(); let (signature, public) = test_client .runtime_api() .test_ecdsa_crypto(test_client.chain_info().genesis_hash) .expect("Tests `ecdsa` crypto."); - let supported_keys = SyncCryptoStore::keys(&*keystore, ECDSA).unwrap(); + let supported_keys = Keystore::keys(&*keystore, 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 8ce08717a8947..1cf2b574b6bfb 100644 --- a/primitives/application-crypto/test/src/ed25519.rs +++ b/primitives/application-crypto/test/src/ed25519.rs @@ -20,7 +20,7 @@ use sp_api::ProvideRuntimeApi; use sp_application_crypto::ed25519::{AppPair, AppPublic}; use sp_core::{crypto::Pair, testing::ED25519}; -use sp_keystore::{testing::KeyStore, SyncCryptoStore}; +use sp_keystore::{testing::MemoryKeystore, Keystore}; use std::sync::Arc; use substrate_test_runtime_client::{ runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, TestClientBuilderExt, @@ -28,14 +28,14 @@ use substrate_test_runtime_client::{ #[test] fn ed25519_works_in_runtime() { - let keystore = Arc::new(KeyStore::new()); + let keystore = Arc::new(MemoryKeystore::new()); let test_client = TestClientBuilder::new().set_keystore(keystore.clone()).build(); let (signature, public) = test_client .runtime_api() .test_ed25519_crypto(test_client.chain_info().genesis_hash) .expect("Tests `ed25519` crypto."); - let supported_keys = SyncCryptoStore::keys(&*keystore, ED25519).unwrap(); + let supported_keys = Keystore::keys(&*keystore, 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 4c1d0f1ef7a97..aa8f75c0dc27a 100644 --- a/primitives/application-crypto/test/src/sr25519.rs +++ b/primitives/application-crypto/test/src/sr25519.rs @@ -20,7 +20,7 @@ use sp_api::ProvideRuntimeApi; use sp_application_crypto::sr25519::{AppPair, AppPublic}; use sp_core::{crypto::Pair, testing::SR25519}; -use sp_keystore::{testing::KeyStore, SyncCryptoStore}; +use sp_keystore::{testing::MemoryKeystore, Keystore}; use std::sync::Arc; use substrate_test_runtime_client::{ runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, TestClientBuilderExt, @@ -28,14 +28,14 @@ use substrate_test_runtime_client::{ #[test] fn sr25519_works_in_runtime() { - let keystore = Arc::new(KeyStore::new()); + let keystore = Arc::new(MemoryKeystore::new()); let test_client = TestClientBuilder::new().set_keystore(keystore.clone()).build(); let (signature, public) = test_client .runtime_api() .test_sr25519_crypto(test_client.chain_info().genesis_hash) .expect("Tests `sr25519` crypto."); - let supported_keys = SyncCryptoStore::keys(&*keystore, SR25519).unwrap(); + let supported_keys = Keystore::keys(&*keystore, 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 f824c90e27c46..6ae17b06d96a4 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::KeyStore, SyncCryptoStore, SyncCryptoStorePtr}; + use sp_keystore::{testing::MemoryKeystore, Keystore, KeystorePtr}; type TestCommitment = Commitment; type TestSignedCommitment = SignedCommitment; @@ -263,20 +263,18 @@ mod tests { // The mock signatures are equivalent to the ones produced by the BEEFY keystore fn mock_signatures() -> (crypto::Signature, crypto::Signature) { - let store: SyncCryptoStorePtr = KeyStore::new().into(); + let store: KeystorePtr = MemoryKeystore::new().into(); let alice = sp_core::ecdsa::Pair::from_string("//Alice", None).unwrap(); - let _ = - SyncCryptoStore::insert_unknown(&*store, KEY_TYPE, "//Alice", alice.public().as_ref()) - .unwrap(); + let _ = Keystore::insert(&*store, KEY_TYPE, "//Alice", alice.public().as_ref()).unwrap(); let msg = keccak_256(b"This is the first message"); - let sig1 = SyncCryptoStore::ecdsa_sign_prehashed(&*store, KEY_TYPE, &alice.public(), &msg) + let sig1 = Keystore::ecdsa_sign_prehashed(&*store, KEY_TYPE, &alice.public(), &msg) .unwrap() .unwrap(); let msg = keccak_256(b"This is the second message"); - let sig2 = SyncCryptoStore::ecdsa_sign_prehashed(&*store, KEY_TYPE, &alice.public(), &msg) + let sig2 = Keystore::ecdsa_sign_prehashed(&*store, KEY_TYPE, &alice.public(), &msg) .unwrap() .unwrap(); diff --git a/primitives/consensus/beefy/src/witness.rs b/primitives/consensus/beefy/src/witness.rs index 9cc31d54b4c1d..70b924c0a42fe 100644 --- a/primitives/consensus/beefy/src/witness.rs +++ b/primitives/consensus/beefy/src/witness.rs @@ -76,7 +76,7 @@ impl SignedCommitmentWitness (crypto::Signature, crypto::Signature) { - let store: SyncCryptoStorePtr = KeyStore::new().into(); + let store: KeystorePtr = MemoryKeystore::new().into(); let alice = sp_core::ecdsa::Pair::from_string("//Alice", None).unwrap(); - let _ = - SyncCryptoStore::insert_unknown(&*store, KEY_TYPE, "//Alice", alice.public().as_ref()) - .unwrap(); + let _ = Keystore::insert(&*store, KEY_TYPE, "//Alice", alice.public().as_ref()).unwrap(); let msg = keccak_256(b"This is the first message"); - let sig1 = SyncCryptoStore::ecdsa_sign_prehashed(&*store, KEY_TYPE, &alice.public(), &msg) + let sig1 = Keystore::ecdsa_sign_prehashed(&*store, KEY_TYPE, &alice.public(), &msg) .unwrap() .unwrap(); let msg = keccak_256(b"This is the second message"); - let sig2 = SyncCryptoStore::ecdsa_sign_prehashed(&*store, KEY_TYPE, &alice.public(), &msg) + let sig2 = Keystore::ecdsa_sign_prehashed(&*store, KEY_TYPE, &alice.public(), &msg) .unwrap() .unwrap(); diff --git a/primitives/consensus/grandpa/src/lib.rs b/primitives/consensus/grandpa/src/lib.rs index 26cee07b80be8..32fc563b1facd 100644 --- a/primitives/consensus/grandpa/src/lib.rs +++ b/primitives/consensus/grandpa/src/lib.rs @@ -28,7 +28,7 @@ use serde::Serialize; use codec::{Codec, Decode, Encode, Input}; use scale_info::TypeInfo; #[cfg(feature = "std")] -use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; +use sp_keystore::{Keystore, KeystorePtr}; use sp_runtime::{ traits::{Header as HeaderT, NumberFor}, ConsensusEngineId, RuntimeDebug, @@ -444,7 +444,7 @@ where /// Localizes the message to the given set and round and signs the payload. #[cfg(feature = "std")] pub fn sign_message( - keystore: SyncCryptoStorePtr, + keystore: KeystorePtr, message: grandpa::Message, public: AuthorityId, round: RoundNumber, @@ -458,7 +458,7 @@ where use sp_core::crypto::Public; let encoded = localized_payload(round, set_id, &message); - let signature = SyncCryptoStore::sign_with( + let signature = Keystore::sign_with( &*keystore, AuthorityId::ID, &public.to_public_crypto_pair(), diff --git a/primitives/io/src/lib.rs b/primitives/io/src/lib.rs index f1997abefbbbc..682697f75a185 100644 --- a/primitives/io/src/lib.rs +++ b/primitives/io/src/lib.rs @@ -45,7 +45,7 @@ use sp_core::{ traits::TaskExecutorExt, }; #[cfg(feature = "std")] -use sp_keystore::{KeystoreExt, SyncCryptoStore}; +use sp_keystore::{Keystore, KeystoreExt}; use sp_core::{ crypto::KeyTypeId, @@ -736,7 +736,7 @@ pub trait Crypto { let keystore = &***self .extension::() .expect("No `keystore` associated for the current context!"); - SyncCryptoStore::ed25519_public_keys(keystore, id) + Keystore::ed25519_public_keys(keystore, id) } /// Generate an `ed22519` key for the given key type using an optional `seed` and @@ -750,8 +750,7 @@ pub trait Crypto { let keystore = &***self .extension::() .expect("No `keystore` associated for the current context!"); - SyncCryptoStore::ed25519_generate_new(keystore, id, seed) - .expect("`ed25519_generate` failed") + Keystore::ed25519_generate_new(keystore, id, seed).expect("`ed25519_generate` failed") } /// Sign the given `msg` with the `ed25519` key that corresponds to the given public key and @@ -767,7 +766,7 @@ pub trait Crypto { let keystore = &***self .extension::() .expect("No `keystore` associated for the current context!"); - SyncCryptoStore::sign_with(keystore, id, &pub_key.into(), msg) + Keystore::sign_with(keystore, id, &pub_key.into(), msg) .ok() .flatten() .and_then(|sig| ed25519::Signature::from_slice(&sig)) @@ -879,7 +878,7 @@ pub trait Crypto { let keystore = &***self .extension::() .expect("No `keystore` associated for the current context!"); - SyncCryptoStore::sr25519_public_keys(keystore, id) + Keystore::sr25519_public_keys(keystore, id) } /// Generate an `sr22519` key for the given key type using an optional seed and @@ -893,8 +892,7 @@ pub trait Crypto { let keystore = &***self .extension::() .expect("No `keystore` associated for the current context!"); - SyncCryptoStore::sr25519_generate_new(keystore, id, seed) - .expect("`sr25519_generate` failed") + Keystore::sr25519_generate_new(keystore, id, seed).expect("`sr25519_generate` failed") } /// Sign the given `msg` with the `sr25519` key that corresponds to the given public key and @@ -910,7 +908,7 @@ pub trait Crypto { let keystore = &***self .extension::() .expect("No `keystore` associated for the current context!"); - SyncCryptoStore::sign_with(keystore, id, &pub_key.into(), msg) + Keystore::sign_with(keystore, id, &pub_key.into(), msg) .ok() .flatten() .and_then(|sig| sr25519::Signature::from_slice(&sig)) @@ -929,7 +927,7 @@ pub trait Crypto { let keystore = &***self .extension::() .expect("No `keystore` associated for the current context!"); - SyncCryptoStore::ecdsa_public_keys(keystore, id) + Keystore::ecdsa_public_keys(keystore, id) } /// Generate an `ecdsa` key for the given key type using an optional `seed` and @@ -943,7 +941,7 @@ pub trait Crypto { let keystore = &***self .extension::() .expect("No `keystore` associated for the current context!"); - SyncCryptoStore::ecdsa_generate_new(keystore, id, seed).expect("`ecdsa_generate` failed") + Keystore::ecdsa_generate_new(keystore, id, seed).expect("`ecdsa_generate` failed") } /// Sign the given `msg` with the `ecdsa` key that corresponds to the given public key and @@ -959,7 +957,7 @@ pub trait Crypto { let keystore = &***self .extension::() .expect("No `keystore` associated for the current context!"); - SyncCryptoStore::sign_with(keystore, id, &pub_key.into(), msg) + Keystore::sign_with(keystore, id, &pub_key.into(), msg) .ok() .flatten() .and_then(|sig| ecdsa::Signature::from_slice(&sig)) @@ -978,7 +976,7 @@ pub trait Crypto { let keystore = &***self .extension::() .expect("No `keystore` associated for the current context!"); - SyncCryptoStore::ecdsa_sign_prehashed(keystore, id, pub_key, msg).ok().flatten() + Keystore::ecdsa_sign_prehashed(keystore, id, pub_key, msg).ok().flatten() } /// Verify `ecdsa` signature. diff --git a/primitives/keystore/Cargo.toml b/primitives/keystore/Cargo.toml index 9386cb5d104d2..543f01059412e 100644 --- a/primitives/keystore/Cargo.toml +++ b/primitives/keystore/Cargo.toml @@ -13,7 +13,6 @@ documentation = "https://docs.rs/sp-core" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -async-trait = "0.1.57" codec = { package = "parity-scale-codec", version = "3.2.2", default-features = false, features = ["derive"] } futures = "0.3.21" merlin = { version = "2.0", default-features = false } diff --git a/primitives/keystore/src/lib.rs b/primitives/keystore/src/lib.rs index 17c435483bae5..e0c00967b6b5e 100644 --- a/primitives/keystore/src/lib.rs +++ b/primitives/keystore/src/lib.rs @@ -20,15 +20,13 @@ pub mod testing; pub mod vrf; use crate::vrf::{VRFSignature, VRFTranscriptData}; -use async_trait::async_trait; -use futures::{executor::block_on, future::join_all}; use sp_core::{ crypto::{CryptoTypePublicPair, KeyTypeId}, ecdsa, ed25519, sr25519, }; use std::sync::Arc; -/// CryptoStore error +/// Keystore error #[derive(Debug, thiserror::Error)] pub enum Error { /// Public key type is not supported @@ -45,179 +43,8 @@ pub enum Error { Other(String), } -/// Something that generates, stores and provides access to keys. -#[async_trait] -pub trait CryptoStore: Send + Sync { - /// Returns all sr25519 public keys for the given key type. - async fn sr25519_public_keys(&self, id: KeyTypeId) -> Vec; - /// Generate a new sr25519 key pair for the given key type and an optional seed. - /// - /// If the given seed is `Some(_)`, the key pair will only be stored in memory. - /// - /// Returns the public key of the generated key pair. - async fn sr25519_generate_new( - &self, - id: KeyTypeId, - seed: Option<&str>, - ) -> Result; - /// Returns all ed25519 public keys for the given key type. - async fn ed25519_public_keys(&self, id: KeyTypeId) -> Vec; - /// Generate a new ed25519 key pair for the given key type and an optional seed. - /// - /// If the given seed is `Some(_)`, the key pair will only be stored in memory. - /// - /// Returns the public key of the generated key pair. - async fn ed25519_generate_new( - &self, - id: KeyTypeId, - seed: Option<&str>, - ) -> Result; - /// Returns all ecdsa public keys for the given key type. - async fn ecdsa_public_keys(&self, id: KeyTypeId) -> Vec; - /// Generate a new ecdsa key pair for the given key type and an optional seed. - /// - /// If the given seed is `Some(_)`, the key pair will only be stored in memory. - /// - /// Returns the public key of the generated key pair. - async fn ecdsa_generate_new( - &self, - id: KeyTypeId, - seed: Option<&str>, - ) -> Result; - - /// Insert a new key. This doesn't require any known of the crypto; but a public key must be - /// manually provided. - /// - /// Places it into the file system store. - /// - /// `Err` if there's some sort of weird filesystem error, but should generally be `Ok`. - async fn insert_unknown(&self, id: KeyTypeId, suri: &str, public: &[u8]) -> Result<(), ()>; - - /// Find intersection between provided keys and supported keys - /// - /// Provided a list of (CryptoTypeId,[u8]) pairs, this would return - /// a filtered set of public keys which are supported by the keystore. - async fn supported_keys( - &self, - id: KeyTypeId, - keys: Vec, - ) -> Result, Error>; - /// List all supported keys - /// - /// Returns a set of public keys the signer supports. - async fn keys(&self, id: KeyTypeId) -> Result, Error>; - - /// Checks if the private keys for the given public key and key type combinations exist. - /// - /// Returns `true` iff all private keys could be found. - async fn has_keys(&self, public_keys: &[(Vec, KeyTypeId)]) -> bool; - - /// Sign with key - /// - /// Signs a message with the private key that matches - /// the public key passed. - /// - /// Returns the SCALE encoded signature if key is found and supported, `None` if the key doesn't - /// exist or an error when something failed. - async fn sign_with( - &self, - id: KeyTypeId, - key: &CryptoTypePublicPair, - msg: &[u8], - ) -> Result>, Error>; - - /// Sign with any key - /// - /// Given a list of public keys, find the first supported key and - /// sign the provided message with that key. - /// - /// Returns a tuple of the used key and the SCALE encoded signature or `None` if no key could - /// be found to sign. - async fn sign_with_any( - &self, - id: KeyTypeId, - keys: Vec, - msg: &[u8], - ) -> Result)>, Error> { - if keys.len() == 1 { - return Ok(self.sign_with(id, &keys[0], msg).await?.map(|s| (keys[0].clone(), s))) - } else { - for k in self.supported_keys(id, keys).await? { - if let Ok(Some(sign)) = self.sign_with(id, &k, msg).await { - return Ok(Some((k, sign))) - } - } - } - - Ok(None) - } - - /// Sign with all keys - /// - /// Provided a list of public keys, sign a message with - /// each key given that the key is supported. - /// - /// Returns a list of `Result`s each representing the SCALE encoded - /// signature of each key, `None` if the key doesn't exist or a error when something failed. - async fn sign_with_all( - &self, - id: KeyTypeId, - keys: Vec, - msg: &[u8], - ) -> Result>, Error>>, ()> { - let futs = keys.iter().map(|k| self.sign_with(id, k, msg)); - - Ok(join_all(futs).await) - } - - /// Generate VRF signature for given transcript data. - /// - /// Receives KeyTypeId and Public key to be able to map - /// them to a private key that exists in the keystore which - /// is, in turn, used for signing the provided transcript. - /// - /// Returns a result containing the signature data. - /// Namely, VRFOutput and VRFProof which are returned - /// inside the `VRFSignature` container struct. - /// - /// This function will return `None` if the given `key_type` and `public` combination - /// doesn't exist in the keystore or an `Err` when something failed. - async fn sr25519_vrf_sign( - &self, - key_type: KeyTypeId, - public: &sr25519::Public, - transcript_data: VRFTranscriptData, - ) -> Result, Error>; - - /// Generate an ECDSA signature for a given pre-hashed message. - /// - /// Receives [`KeyTypeId`] and an [`ecdsa::Public`] key to be able to map - /// them to a private key that exists in the keystore. This private key is, - /// in turn, used for signing the provided pre-hashed message. - /// - /// The `msg` argument provided should be a hashed message for which an - /// ECDSA signature should be generated. - /// - /// Returns an [`ecdsa::Signature`] or `None` in case the given `id` and - /// `public` combination doesn't exist in the keystore. An `Err` will be - /// returned if generating the signature itself failed. - async fn ecdsa_sign_prehashed( - &self, - id: KeyTypeId, - public: &ecdsa::Public, - msg: &[u8; 32], - ) -> Result, Error>; -} - -/// Sync version of the CryptoStore -/// -/// Some parts of Substrate still rely on a sync version of the `CryptoStore`. -/// To make the transition easier this auto trait wraps any async `CryptoStore` and -/// exposes a `sync` interface using `block_on`. Usage of this is deprecated and it -/// will be removed as soon as the internal usage has transitioned successfully. -/// If you are starting out building something new **do not use this**, -/// instead, use [`CryptoStore`]. -pub trait SyncCryptoStore: CryptoStore + Send + Sync { +/// Something that generates, stores and provides access to secret keys. +pub trait Keystore: Send + Sync { /// Returns all sr25519 public keys for the given key type. fn sr25519_public_keys(&self, id: KeyTypeId) -> Vec; @@ -257,30 +84,13 @@ pub trait SyncCryptoStore: CryptoStore + Send + Sync { fn ecdsa_generate_new(&self, id: KeyTypeId, seed: Option<&str>) -> Result; - /// Insert a new key. This doesn't require any known of the crypto; but a public key must be - /// manually provided. - /// - /// Places it into the file system store. - /// - /// `Err` if there's some sort of weird filesystem error, but should generally be `Ok`. - fn insert_unknown(&self, key_type: KeyTypeId, suri: &str, public: &[u8]) -> Result<(), ()>; - - /// Find intersection between provided keys and supported keys - /// - /// Provided a list of (CryptoTypeId,[u8]) pairs, this would return - /// a filtered set of public keys which are supported by the keystore. - fn supported_keys( - &self, - id: KeyTypeId, - keys: Vec, - ) -> Result, Error>; + /// Insert a new secret key. + fn insert(&self, key_type: KeyTypeId, suri: &str, public: &[u8]) -> Result<(), ()>; /// List all supported keys /// /// Returns a set of public keys the signer supports. - fn keys(&self, id: KeyTypeId) -> Result, Error> { - block_on(CryptoStore::keys(self, id)) - } + fn keys(&self, id: KeyTypeId) -> Result, Error>; /// Checks if the private keys for the given public key and key type combinations exist. /// @@ -301,50 +111,6 @@ pub trait SyncCryptoStore: CryptoStore + Send + Sync { msg: &[u8], ) -> Result>, Error>; - /// Sign with any key - /// - /// Given a list of public keys, find the first supported key and - /// sign the provided message with that key. - /// - /// Returns a tuple of the used key and the SCALE encoded signature or `None` if no key could - /// be found to sign. - fn sign_with_any( - &self, - id: KeyTypeId, - keys: Vec, - msg: &[u8], - ) -> Result)>, Error> { - if keys.len() == 1 { - return Ok( - SyncCryptoStore::sign_with(self, id, &keys[0], msg)?.map(|s| (keys[0].clone(), s)) - ) - } else { - for k in SyncCryptoStore::supported_keys(self, id, keys)? { - if let Ok(Some(sign)) = SyncCryptoStore::sign_with(self, id, &k, msg) { - return Ok(Some((k, sign))) - } - } - } - - Ok(None) - } - - /// Sign with all keys - /// - /// Provided a list of public keys, sign a message with - /// each key given that the key is supported. - /// - /// Returns a list of `Result`s each representing the SCALE encoded - /// signature of each key, `None` if the key doesn't exist or an error when something failed. - fn sign_with_all( - &self, - id: KeyTypeId, - keys: Vec, - msg: &[u8], - ) -> Result>, Error>>, ()> { - Ok(keys.iter().map(|k| SyncCryptoStore::sign_with(self, id, k, msg)).collect()) - } - /// Generate VRF signature for given transcript data. /// /// Receives KeyTypeId and Public key to be able to map @@ -385,9 +151,9 @@ pub trait SyncCryptoStore: CryptoStore + Send + Sync { } /// A pointer to a keystore. -pub type SyncCryptoStorePtr = Arc; +pub type KeystorePtr = Arc; sp_externalities::decl_extension! { /// The keystore extension to register/retrieve from the externalities. - pub struct KeystoreExt(SyncCryptoStorePtr); + pub struct KeystoreExt(KeystorePtr); } diff --git a/primitives/keystore/src/testing.rs b/primitives/keystore/src/testing.rs index 5058a06508eac..fecc11342c464 100644 --- a/primitives/keystore/src/testing.rs +++ b/primitives/keystore/src/testing.rs @@ -24,23 +24,19 @@ use sp_core::{ use crate::{ vrf::{make_transcript, VRFSignature, VRFTranscriptData}, - CryptoStore, Error, SyncCryptoStore, SyncCryptoStorePtr, + Error, Keystore, KeystorePtr, }; -use async_trait::async_trait; use parking_lot::RwLock; -use std::{ - collections::{HashMap, HashSet}, - sync::Arc, -}; +use std::{collections::HashMap, sync::Arc}; /// A keystore implementation usable in tests. #[derive(Default)] -pub struct KeyStore { +pub struct MemoryKeystore { /// `KeyTypeId` maps to public keys and public keys map to private keys. keys: Arc, String>>>>, } -impl KeyStore { +impl MemoryKeystore { /// Creates a new instance of `Self`. pub fn new() -> Self { Self::default() @@ -71,93 +67,7 @@ impl KeyStore { } } -#[async_trait] -impl CryptoStore for KeyStore { - async fn keys(&self, id: KeyTypeId) -> Result, Error> { - SyncCryptoStore::keys(self, id) - } - - async fn sr25519_public_keys(&self, id: KeyTypeId) -> Vec { - SyncCryptoStore::sr25519_public_keys(self, id) - } - - async fn sr25519_generate_new( - &self, - id: KeyTypeId, - seed: Option<&str>, - ) -> Result { - SyncCryptoStore::sr25519_generate_new(self, id, seed) - } - - async fn ed25519_public_keys(&self, id: KeyTypeId) -> Vec { - SyncCryptoStore::ed25519_public_keys(self, id) - } - - async fn ed25519_generate_new( - &self, - id: KeyTypeId, - seed: Option<&str>, - ) -> Result { - SyncCryptoStore::ed25519_generate_new(self, id, seed) - } - - async fn ecdsa_public_keys(&self, id: KeyTypeId) -> Vec { - SyncCryptoStore::ecdsa_public_keys(self, id) - } - - async fn ecdsa_generate_new( - &self, - id: KeyTypeId, - seed: Option<&str>, - ) -> Result { - SyncCryptoStore::ecdsa_generate_new(self, id, seed) - } - - async fn insert_unknown(&self, id: KeyTypeId, suri: &str, public: &[u8]) -> Result<(), ()> { - SyncCryptoStore::insert_unknown(self, id, suri, public) - } - - async fn has_keys(&self, public_keys: &[(Vec, KeyTypeId)]) -> bool { - SyncCryptoStore::has_keys(self, public_keys) - } - - async fn supported_keys( - &self, - id: KeyTypeId, - keys: Vec, - ) -> std::result::Result, Error> { - SyncCryptoStore::supported_keys(self, id, keys) - } - - async fn sign_with( - &self, - id: KeyTypeId, - key: &CryptoTypePublicPair, - msg: &[u8], - ) -> Result>, Error> { - SyncCryptoStore::sign_with(self, id, key, msg) - } - - async fn sr25519_vrf_sign( - &self, - key_type: KeyTypeId, - public: &sr25519::Public, - transcript_data: VRFTranscriptData, - ) -> Result, Error> { - SyncCryptoStore::sr25519_vrf_sign(self, key_type, public, transcript_data) - } - - async fn ecdsa_sign_prehashed( - &self, - id: KeyTypeId, - public: &ecdsa::Public, - msg: &[u8; 32], - ) -> Result, Error> { - SyncCryptoStore::ecdsa_sign_prehashed(self, id, public, msg) - } -} - -impl SyncCryptoStore for KeyStore { +impl Keystore for MemoryKeystore { fn keys(&self, id: KeyTypeId) -> Result, Error> { self.keys .read() @@ -304,7 +214,7 @@ impl SyncCryptoStore for KeyStore { } } - fn insert_unknown(&self, id: KeyTypeId, suri: &str, public: &[u8]) -> Result<(), ()> { + fn insert(&self, id: KeyTypeId, suri: &str, public: &[u8]) -> Result<(), ()> { self.keys .write() .entry(id) @@ -319,17 +229,6 @@ impl SyncCryptoStore for KeyStore { .all(|(k, t)| self.keys.read().get(t).and_then(|s| s.get(k)).is_some()) } - fn supported_keys( - &self, - id: KeyTypeId, - keys: Vec, - ) -> std::result::Result, Error> { - let provided_keys = keys.into_iter().collect::>(); - let all_keys = SyncCryptoStore::keys(self, id)?.into_iter().collect::>(); - - Ok(provided_keys.intersection(&all_keys).cloned().collect()) - } - fn sign_with( &self, id: KeyTypeId, @@ -386,14 +285,8 @@ impl SyncCryptoStore for KeyStore { } } -impl Into for KeyStore { - fn into(self) -> SyncCryptoStorePtr { - Arc::new(self) - } -} - -impl Into> for KeyStore { - fn into(self) -> Arc { +impl Into for MemoryKeystore { + fn into(self) -> KeystorePtr { Arc::new(self) } } @@ -401,7 +294,7 @@ impl Into> for KeyStore { #[cfg(test)] mod tests { use super::*; - use crate::{vrf::VRFTranscriptValue, SyncCryptoStore}; + use crate::vrf::VRFTranscriptValue; use sp_core::{ sr25519, testing::{ECDSA, ED25519, SR25519}, @@ -409,34 +302,33 @@ mod tests { #[test] fn store_key_and_extract() { - let store = KeyStore::new(); + let store = MemoryKeystore::new(); - let public = - SyncCryptoStore::ed25519_generate_new(&store, ED25519, None).expect("Generates key"); + let public = Keystore::ed25519_generate_new(&store, ED25519, None).expect("Generates key"); - let public_keys = SyncCryptoStore::keys(&store, ED25519).unwrap(); + let public_keys = Keystore::keys(&store, ED25519).unwrap(); assert!(public_keys.contains(&public.into())); } #[test] fn store_unknown_and_extract_it() { - let store = KeyStore::new(); + let store = MemoryKeystore::new(); let secret_uri = "//Alice"; let key_pair = sr25519::Pair::from_string(secret_uri, None).expect("Generates key pair"); - SyncCryptoStore::insert_unknown(&store, SR25519, secret_uri, key_pair.public().as_ref()) + Keystore::insert(&store, SR25519, secret_uri, key_pair.public().as_ref()) .expect("Inserts unknown key"); - let public_keys = SyncCryptoStore::keys(&store, SR25519).unwrap(); + let public_keys = Keystore::keys(&store, SR25519).unwrap(); assert!(public_keys.contains(&key_pair.public().into())); } #[test] fn vrf_sign() { - let store = KeyStore::new(); + let store = MemoryKeystore::new(); let secret_uri = "//Alice"; let key_pair = sr25519::Pair::from_string(secret_uri, None).expect("Generates key pair"); @@ -450,7 +342,7 @@ mod tests { ], }; - let result = SyncCryptoStore::sr25519_vrf_sign( + let result = Keystore::sr25519_vrf_sign( &store, SR25519, &key_pair.public(), @@ -458,18 +350,18 @@ mod tests { ); assert!(result.unwrap().is_none()); - SyncCryptoStore::insert_unknown(&store, SR25519, secret_uri, key_pair.public().as_ref()) + Keystore::insert(&store, SR25519, secret_uri, key_pair.public().as_ref()) .expect("Inserts unknown key"); let result = - SyncCryptoStore::sr25519_vrf_sign(&store, SR25519, &key_pair.public(), transcript_data); + Keystore::sr25519_vrf_sign(&store, SR25519, &key_pair.public(), transcript_data); assert!(result.unwrap().is_some()); } #[test] fn ecdsa_sign_prehashed_works() { - let store = KeyStore::new(); + let store = MemoryKeystore::new(); let suri = "//Alice"; let pair = ecdsa::Pair::from_string(suri, None).unwrap(); @@ -477,15 +369,13 @@ mod tests { let msg = sp_core::keccak_256(b"this should be a hashed message"); // no key in key store - let res = - SyncCryptoStore::ecdsa_sign_prehashed(&store, ECDSA, &pair.public(), &msg).unwrap(); + let res = Keystore::ecdsa_sign_prehashed(&store, ECDSA, &pair.public(), &msg).unwrap(); assert!(res.is_none()); // insert key, sign again - SyncCryptoStore::insert_unknown(&store, ECDSA, suri, pair.public().as_ref()).unwrap(); + Keystore::insert(&store, ECDSA, suri, pair.public().as_ref()).unwrap(); - let res = - SyncCryptoStore::ecdsa_sign_prehashed(&store, ECDSA, &pair.public(), &msg).unwrap(); + let res = Keystore::ecdsa_sign_prehashed(&store, ECDSA, &pair.public(), &msg).unwrap(); assert!(res.is_some()); } } diff --git a/test-utils/client/src/lib.rs b/test-utils/client/src/lib.rs index a27178792579a..a91aa99929e2f 100644 --- a/test-utils/client/src/lib.rs +++ b/test-utils/client/src/lib.rs @@ -33,7 +33,7 @@ pub use sp_consensus; pub use sp_keyring::{ ed25519::Keyring as Ed25519Keyring, sr25519::Keyring as Sr25519Keyring, AccountKeyring, }; -pub use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; +pub use sp_keystore::{Keystore, KeystorePtr}; pub use sp_runtime::{Storage, StorageChild}; pub use sp_state_machine::ExecutionStrategy; @@ -70,7 +70,7 @@ pub struct TestClientBuilder, StorageChild>, backend: Arc, _executor: std::marker::PhantomData, - keystore: Option, + keystore: Option, fork_blocks: ForkBlocks, bad_blocks: BadBlocks, enable_offchain_indexing_api: bool, @@ -128,7 +128,7 @@ impl } /// Set the keystore that should be used by the externalities. - pub fn set_keystore(mut self, keystore: SyncCryptoStorePtr) -> Self { + pub fn set_keystore(mut self, keystore: KeystorePtr) -> Self { self.keystore = Some(keystore); self } diff --git a/utils/frame/benchmarking-cli/src/pallet/command.rs b/utils/frame/benchmarking-cli/src/pallet/command.rs index 60f078142e17f..f11e6bd920abf 100644 --- a/utils/frame/benchmarking-cli/src/pallet/command.rs +++ b/utils/frame/benchmarking-cli/src/pallet/command.rs @@ -38,7 +38,7 @@ use sp_core::{ traits::CallContext, }; use sp_externalities::Extensions; -use sp_keystore::{testing::KeyStore, KeystoreExt, SyncCryptoStorePtr}; +use sp_keystore::{testing::MemoryKeystore, KeystoreExt, KeystorePtr}; 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}; @@ -218,7 +218,7 @@ impl PalletCmd { let extensions = || -> Extensions { let mut extensions = Extensions::default(); - extensions.register(KeystoreExt(Arc::new(KeyStore::new()) as SyncCryptoStorePtr)); + extensions.register(KeystoreExt(Arc::new(MemoryKeystore::new()) as KeystorePtr)); let (offchain, _) = TestOffchainExt::new(); let (pool, _) = TestTransactionPoolExt::new(); extensions.register(OffchainWorkerExt::new(offchain.clone())); diff --git a/utils/frame/try-runtime/cli/src/lib.rs b/utils/frame/try-runtime/cli/src/lib.rs index 6fb4b44392546..e1d75064ac87f 100644 --- a/utils/frame/try-runtime/cli/src/lib.rs +++ b/utils/frame/try-runtime/cli/src/lib.rs @@ -383,7 +383,7 @@ use sp_core::{ }; use sp_externalities::Extensions; use sp_inherents::InherentData; -use sp_keystore::{testing::KeyStore, KeystoreExt}; +use sp_keystore::{testing::MemoryKeystore, KeystoreExt}; use sp_runtime::{ traits::{BlakeTwo256, Block as BlockT, NumberFor}, DeserializeOwned, Digest, @@ -820,7 +820,7 @@ pub(crate) fn full_extensions() -> Extensions { let (pool, _pool_state) = TestTransactionPoolExt::new(); extensions.register(OffchainDbExt::new(offchain.clone())); extensions.register(OffchainWorkerExt::new(offchain)); - extensions.register(KeystoreExt(std::sync::Arc::new(KeyStore::new()))); + extensions.register(KeystoreExt(std::sync::Arc::new(MemoryKeystore::new()))); extensions.register(TransactionPoolExt::new(pool)); extensions