Keystore overhaul (#13615)

* Remove 'supported_keys' 'sign_with_any' and 'sign_with_all' from keystore trait

* Remove the aync keystore

* Renaming:
- SyncCryptoStore -> Keystore
- SyncCryptoStorePtr -> KeystorePtr
- KeyStore -> MemoryKeystore

* Fix authority discovery worker and tests

* Rename 'insert_unknown' to 'insert'

* Remove leftover
This commit is contained in:
Davide Galassi
2023-03-17 12:24:14 +01:00
committed by GitHub
parent 91bb2d29ca
commit f110941b7f
49 changed files with 317 additions and 820 deletions
-1
View File
@@ -10339,7 +10339,6 @@ dependencies = [
name = "sp-keystore"
version = "0.13.0"
dependencies = [
"async-trait",
"futures",
"merlin",
"parity-scale-codec",
@@ -150,7 +150,7 @@ pub fn new_partial(
fn remote_keystore(_url: &String) -> Result<Arc<LocalKeystore>, &'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<TaskManager, ServiceError>
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<TaskManager, ServiceError>
},
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<TaskManager, ServiceError>
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
+8 -9
View File
@@ -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(),
@@ -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)),
+2 -2
View File
@@ -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<Block, Epoch>,
/// The keystore that manages the keys of the node.
pub keystore: SyncCryptoStorePtr,
pub keystore: KeystorePtr,
}
/// Extra dependencies for GRANDPA
@@ -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))
};
@@ -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<T: offchain::DbExternalities + Clone + Sync + Send + 'static> DbExternaliti
/// for each call, based on required `Capabilities`.
pub struct ExecutionExtensions<Block: BlockT> {
strategies: ExecutionStrategies,
keystore: Option<SyncCryptoStorePtr>,
keystore: Option<KeystorePtr>,
offchain_db: Option<Box<dyn DbExternalitiesFactory>>,
// FIXME: these two are only RwLock because of https://github.com/paritytech/substrate/issues/4587
// remove when fixed.
@@ -191,7 +191,7 @@ impl<Block: BlockT> ExecutionExtensions<Block> {
/// Create new `ExecutionExtensions` given a `keystore` and `ExecutionStrategies`.
pub fn new(
strategies: ExecutionStrategies,
keystore: Option<SyncCryptoStorePtr>,
keystore: Option<KeystorePtr>,
offchain_db: Option<Box<dyn DbExternalitiesFactory>>,
) -> Self {
let transaction_pool = RwLock::new(None);
@@ -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()
});
@@ -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<dyn CryptoStore>),
PublishAndDiscover(KeystorePtr),
/// Discover addresses of others.
Discover,
}
@@ -364,8 +364,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);
@@ -382,7 +381,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::<HashSet<_>>(),
Role::Discover => HashSet::new(),
@@ -588,12 +586,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<dyn CryptoStore>,
key_store: KeystorePtr,
client: &Client,
) -> Result<HashSet<AuthorityId>> {
let local_pub_keys = key_store
.sr25519_public_keys(key_types::AUTHORITY_DISCOVERY)
.await
.into_iter()
.collect::<HashSet<_>>();
@@ -663,33 +660,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<u8>,
peer_signature: Option<schema::PeerSignature>,
key_store: &dyn CryptoStore,
key_store: &dyn Keystore,
keys: Vec<CryptoTypePublicPair>,
) -> Result<Vec<(KademliaKey, Vec<u8>)>> {
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)
@@ -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<Signer: NetworkSigner>(
fn build_dht_event<Signer: NetworkSigner>(
addresses: Vec<Multiaddr>,
public_key: AuthorityId,
key_store: &dyn CryptoStore,
key_store: &MemoryKeystore,
network: Option<&Signer>,
) -> Vec<(KademliaKey, Vec<u8>)> {
let serialized_record =
@@ -224,7 +224,6 @@ async fn build_dht_event<Signer: NetworkSigner>(
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<Signer: NetworkSigner>(
fn new_registers_metrics() {
let (_dht_event_tx, dht_event_rx) = mpsc::channel(1000);
let network: Arc<TestNetwork> = 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<TestNetwork> = 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<TestNetwork> = 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<TestNetwork> = 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<TestNetwork> = 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::<TestNetwork>(
let kv_pairs = build_dht_event::<TestNetwork>(
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::<TestNetwork>(
let kv_pairs = build_dht_event::<TestNetwork>(
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::<TestNetwork>(
let kv_pairs = build_dht_event::<TestNetwork>(
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<AuthorityId> = (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.");
@@ -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(())
}
+1 -1
View File
@@ -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),
+9 -9
View File
@@ -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<C, SC, I, PF, SO, L, CIDP, BS, N> {
/// The backoff strategy when we miss slots.
pub backoff_authoring_blocks: Option<BS>,
/// 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<C, I, PF, SO, L, BS, N> {
/// The backoff strategy when we miss slots.
pub backoff_authoring_blocks: Option<BS>,
/// 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<C, E, I, P, SO, L, BS, N> {
client: Arc<C>,
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<Self::Claim> {
let expected_author = slot_author::<P>(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,
<AuthorityId<P> 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()),
+7 -10
View File
@@ -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<B: BlockT, C, SC> {
/// shared reference to EpochChanges
shared_epoch_changes: SharedEpochChanges<B, Epoch>,
/// 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<B: BlockT, C, SC> Babe<B, C, SC> {
pub fn new(
client: Arc<C>,
shared_epoch_changes: SharedEpochChanges<B, Epoch>,
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<P: AppPair>(
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)
@@ -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),
+4 -4
View File
@@ -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<B: BlockT, C, SC, E, I, SO, L, CIDP, BS> {
/// The keystore that manages the keys of the node.
pub keystore: SyncCryptoStorePtr,
pub keystore: KeystorePtr,
/// The client to use
pub client: Arc<C>,
@@ -711,7 +711,7 @@ struct BabeSlotWorker<B: BlockT, C, E, I, SO, L, BS> {
justification_sync_link: L,
force_authoring: bool,
backoff_authoring_blocks: Option<BS>,
keystore: SyncCryptoStorePtr,
keystore: KeystorePtr,
epoch_changes: SharedEpochChanges<B, Epoch>,
slot_notification_sinks: SlotNotificationSinks<B>,
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,
<AuthorityId as AppKey>::ID,
&public_type_pair,
+8 -9
View File
@@ -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);
@@ -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<BN: Encode>(who: &Keyring, commitment: &Commitment<BN>) -> 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()
@@ -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<SyncCryptoStorePtr>);
pub(crate) struct BeefyKeystore(Option<KeystorePtr>);
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<Public> = 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<Vec<Public>, error::Error> {
let store = self.0.clone().ok_or_else(|| error::Error::Keystore("no Keystore".into()))?;
let pk: Vec<Public> = SyncCryptoStore::ecdsa_public_keys(&*store, KEY_TYPE)
let pk: Vec<Public> = Keystore::ecdsa_public_keys(&*store, KEY_TYPE)
.drain(..)
.map(Public::from)
.collect();
@@ -110,8 +110,8 @@ impl BeefyKeystore {
}
}
impl From<Option<SyncCryptoStorePtr>> for BeefyKeystore {
fn from(store: Option<SyncCryptoStorePtr>) -> BeefyKeystore {
impl From<Option<KeystorePtr>> for BeefyKeystore {
fn from(store: Option<KeystorePtr>) -> 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
+2 -2
View File
@@ -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<B: Block, BE, C, N, P, R, S> {
/// Runtime Api Provider
pub runtime: Arc<R>,
/// Local key store
pub key_store: Option<SyncCryptoStorePtr>,
pub key_store: Option<KeystorePtr>,
/// BEEFY voter network params
pub network_params: BeefyNetworkParams<B, N, S>,
/// Minimal delta between blocks, BEEFY should vote for
@@ -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<AuthorityId> {
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
}
@@ -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)
}
}
@@ -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<String>,
/// The keystore that manages the keys of this node.
pub keystore: Option<SyncCryptoStorePtr>,
pub keystore: Option<KeystorePtr>,
/// TelemetryHandle instance.
pub telemetry: Option<TelemetryHandle>,
/// Chain specific GRANDPA protocol name. See [`crate::protocol_standard_name`].
@@ -623,7 +623,7 @@ fn global_communication<BE, Block: BlockT, C, N, S>(
voters: &Arc<VoterSet<AuthorityId>>,
client: Arc<C>,
network: &NetworkBridge<Block, N, S>,
keystore: Option<&SyncCryptoStorePtr>,
keystore: Option<&KeystorePtr>,
metrics: Option<until_imported::Metrics>,
) -> (
impl Stream<
@@ -1136,14 +1136,12 @@ where
/// available.
fn local_authority_id(
voters: &VoterSet<AuthorityId>,
keystore: Option<&SyncCryptoStorePtr>,
keystore: Option<&KeystorePtr>,
) -> Option<AuthorityId> {
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())
})
}
@@ -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<B: BlockT, BE, Client, N: NetworkT<B>, S: SyncingT<B>> {
client: Arc<Client>,
network: NetworkBridge<B, N, S>,
persistent_data: PersistentData<B>,
keystore: Option<SyncCryptoStorePtr>,
keystore: Option<KeystorePtr>,
voter_commands_rx: TracingUnboundedReceiver<VoterCommand<B::Hash, NumberFor<B>>>,
justification_sender: Option<GrandpaJustificationSender<B>>,
telemetry: Option<TelemetryHandle>,
@@ -240,7 +240,7 @@ where
client: Arc<Client>,
network: NetworkBridge<B, Network, Syncing>,
persistent_data: PersistentData<B>,
keystore: Option<SyncCryptoStorePtr>,
keystore: Option<KeystorePtr>,
voter_commands_rx: TracingUnboundedReceiver<VoterCommand<B::Hash, NumberFor<B>>>,
justification_sender: Option<GrandpaJustificationSender<B>>,
telemetry: Option<TelemetryHandle>,
@@ -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<N, S, SC, VR> =
fn test_environment_with_select_chain<N, S, VR, SC>(
link: &TestLinkHalf,
keystore: Option<SyncCryptoStorePtr>,
keystore: Option<KeystorePtr>,
network_service: N,
sync_service: S,
select_chain: SC,
@@ -1428,7 +1428,7 @@ where
fn test_environment<N, S, VR>(
link: &TestLinkHalf,
keystore: Option<SyncCryptoStorePtr>,
keystore: Option<KeystorePtr>,
network_service: N,
sync_service: S,
voting_rule: VR,
@@ -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<B: BlockT, C, P> {
/// shared reference to keystore
keystore: SyncCryptoStorePtr,
keystore: KeystorePtr,
/// Shared reference to the client.
client: Arc<C>,
@@ -143,7 +143,7 @@ where
{
pub fn new(
client: Arc<C>,
keystore: SyncCryptoStorePtr,
keystore: KeystorePtr,
epoch_changes: SharedEpochChanges<B, Epoch>,
authorities: Vec<(AuthorityId, BabeAuthorityWeight)>,
) -> Result<Self, Error> {
+21 -137
View File
@@ -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<Vec<CryptoTypePublicPair>, TraitError> {
SyncCryptoStore::keys(self, id)
}
async fn sr25519_public_keys(&self, id: KeyTypeId) -> Vec<sr25519::Public> {
SyncCryptoStore::sr25519_public_keys(self, id)
}
async fn sr25519_generate_new(
&self,
id: KeyTypeId,
seed: Option<&str>,
) -> std::result::Result<sr25519::Public, TraitError> {
SyncCryptoStore::sr25519_generate_new(self, id, seed)
}
async fn ed25519_public_keys(&self, id: KeyTypeId) -> Vec<ed25519::Public> {
SyncCryptoStore::ed25519_public_keys(self, id)
}
async fn ed25519_generate_new(
&self,
id: KeyTypeId,
seed: Option<&str>,
) -> std::result::Result<ed25519::Public, TraitError> {
SyncCryptoStore::ed25519_generate_new(self, id, seed)
}
async fn ecdsa_public_keys(&self, id: KeyTypeId) -> Vec<ecdsa::Public> {
SyncCryptoStore::ecdsa_public_keys(self, id)
}
async fn ecdsa_generate_new(
&self,
id: KeyTypeId,
seed: Option<&str>,
) -> std::result::Result<ecdsa::Public, TraitError> {
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<u8>, KeyTypeId)]) -> bool {
SyncCryptoStore::has_keys(self, public_keys)
}
async fn supported_keys(
&self,
id: KeyTypeId,
keys: Vec<CryptoTypePublicPair>,
) -> std::result::Result<Vec<CryptoTypePublicPair>, TraitError> {
SyncCryptoStore::supported_keys(self, id, keys)
}
async fn sign_with(
&self,
id: KeyTypeId,
key: &CryptoTypePublicPair,
msg: &[u8],
) -> std::result::Result<Option<Vec<u8>>, 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<Option<VRFSignature>, 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<Option<ecdsa::Signature>, 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<Vec<CryptoTypePublicPair>, 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<CryptoTypePublicPair>,
) -> std::result::Result<Vec<CryptoTypePublicPair>, TraitError> {
let all_keys = SyncCryptoStore::keys(self, id)?.into_iter().collect::<HashSet<_>>();
Ok(keys.into_iter().filter(|key| all_keys.contains(key)).collect::<Vec<_>>())
}
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<u8>, KeyTypeId)]) -> bool {
@@ -352,14 +248,8 @@ impl SyncCryptoStore for LocalKeystore {
}
}
impl Into<SyncCryptoStorePtr> for LocalKeystore {
fn into(self) -> SyncCryptoStorePtr {
Arc::new(self)
}
}
impl Into<Arc<dyn CryptoStore>> for LocalKeystore {
fn into(self) -> Arc<dyn CryptoStore> {
impl Into<KeystorePtr> 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();
+1 -1
View File
@@ -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,
+7 -7
View File
@@ -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<P, Client> {
/// Transactions pool
pool: Arc<P>,
/// The key store.
keystore: SyncCryptoStorePtr,
keystore: KeystorePtr,
/// Whether to deny unsafe calls
deny_unsafe: DenyUnsafe,
/// Executor to spawn subscriptions.
@@ -67,7 +67,7 @@ impl<P, Client> Author<P, Client> {
pub fn new(
client: Arc<Client>,
pool: Arc<P>,
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<bool> {
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<Vec<Bytes>> {
+6 -6
View File
@@ -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<FullChainApi<Client<Backend>, Block>, Block
struct TestSetup {
pub client: Arc<Client<Backend>>,
pub keystore: Arc<KeyStore>,
pub keystore: Arc<MemoryKeystore>,
pub pool: Arc<FullTransactionPool>,
}
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
+13 -26
View File
@@ -67,7 +67,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};
@@ -85,26 +85,22 @@ pub type TFullCallExecutor<TBl, TExec> =
type TFullParts<TBl, TRtApi, TExec> =
(TFullClient<TBl, TRtApi, TExec>, Arc<TFullBackend<TBl>>, KeystoreContainer, TaskManager);
trait AsCryptoStoreRef {
fn keystore_ref(&self) -> Arc<dyn CryptoStore>;
fn sync_keystore_ref(&self) -> Arc<dyn SyncCryptoStore>;
trait AsKeystoreRef {
fn keystore_ref(&self) -> Arc<dyn Keystore>;
}
impl<T> AsCryptoStoreRef for Arc<T>
impl<T> AsKeystoreRef for Arc<T>
where
T: CryptoStore + SyncCryptoStore + 'static,
T: Keystore + 'static,
{
fn keystore_ref(&self) -> Arc<dyn CryptoStore> {
self.clone()
}
fn sync_keystore_ref(&self) -> Arc<dyn SyncCryptoStore> {
fn keystore_ref(&self) -> Arc<dyn Keystore> {
self.clone()
}
}
/// Construct and hold different layers of Keystore wrappers
pub struct KeystoreContainer {
remote: Option<Box<dyn AsCryptoStoreRef>>,
remote: Option<Box<dyn AsKeystoreRef>>,
local: Arc<LocalKeystore>,
}
@@ -127,13 +123,13 @@ impl KeystoreContainer {
/// stick around.
pub fn set_remote_keystore<T>(&mut self, remote: Arc<T>)
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<dyn CryptoStore> {
/// Returns an adapter to a `Keystore` implementation.
pub fn keystore(&self) -> Arc<dyn Keystore> {
if let Some(c) = self.remote.as_ref() {
c.keystore_ref()
} else {
@@ -141,15 +137,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.
@@ -234,7 +221,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),
);
@@ -374,7 +361,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<TExPool>,
/// Builds additional [`RpcModule`]s that should be added to the server
@@ -645,7 +632,7 @@ fn gen_rpc_module<TBl, TBackend, TCl, TRpc, TExPool>(
spawn_handle: SpawnTaskHandle,
client: Arc<TCl>,
transaction_pool: Arc<TExPool>,
keystore: SyncCryptoStorePtr,
keystore: KeystorePtr,
system_rpc_tx: TracingUnboundedSender<sc_rpc::system::Request<TBl>>,
config: &Configuration,
backend: Arc<TBackend>,
@@ -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<E, Block, G, RA>(
backend: Arc<in_mem::Backend<Block>>,
executor: E,
genesis_block_builder: G,
keystore: Option<SyncCryptoStorePtr>,
keystore: Option<KeystorePtr>,
prometheus_registry: Option<Registry>,
telemetry: Option<TelemetryHandle>,
spawn_handle: Box<dyn SpawnNamed>,
@@ -224,7 +224,7 @@ pub fn new_with_backend<B, E, Block, G, RA>(
backend: Arc<B>,
executor: E,
genesis_block_builder: G,
keystore: Option<SyncCryptoStorePtr>,
keystore: Option<KeystorePtr>,
spawn_handle: Box<dyn SpawnNamed>,
prometheus_registry: Option<Registry>,
telemetry: Option<TelemetryHandle>,
+2 -2
View File
@@ -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::<Test>().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
}
+2 -2
View File
@@ -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
}
@@ -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));
+2 -2
View File
@@ -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::<Test>().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));
@@ -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)));
}
@@ -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)));
}
@@ -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)));
}
@@ -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<u128>;
type TestSignedCommitment = SignedCommitment<u128, crypto::Signature>;
@@ -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();
@@ -76,7 +76,7 @@ impl<TBlockNumber, TMerkleRoot> SignedCommitmentWitness<TBlockNumber, TMerkleRoo
mod tests {
use sp_core::{keccak_256, Pair};
use sp_keystore::{testing::KeyStore, SyncCryptoStore, SyncCryptoStorePtr};
use sp_keystore::{testing::MemoryKeystore, Keystore, KeystorePtr};
use super::*;
use codec::Decode;
@@ -90,20 +90,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();
@@ -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<H, N>(
keystore: SyncCryptoStorePtr,
keystore: KeystorePtr,
message: grandpa::Message<H, N>,
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(),
+11 -13
View File
@@ -43,7 +43,7 @@ use sp_core::{
traits::TaskExecutorExt,
};
#[cfg(feature = "std")]
use sp_keystore::{KeystoreExt, SyncCryptoStore};
use sp_keystore::{Keystore, KeystoreExt};
use sp_core::{
crypto::KeyTypeId,
@@ -734,7 +734,7 @@ pub trait Crypto {
let keystore = &***self
.extension::<KeystoreExt>()
.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
@@ -748,8 +748,7 @@ pub trait Crypto {
let keystore = &***self
.extension::<KeystoreExt>()
.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
@@ -765,7 +764,7 @@ pub trait Crypto {
let keystore = &***self
.extension::<KeystoreExt>()
.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))
@@ -877,7 +876,7 @@ pub trait Crypto {
let keystore = &***self
.extension::<KeystoreExt>()
.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
@@ -891,8 +890,7 @@ pub trait Crypto {
let keystore = &***self
.extension::<KeystoreExt>()
.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
@@ -908,7 +906,7 @@ pub trait Crypto {
let keystore = &***self
.extension::<KeystoreExt>()
.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))
@@ -927,7 +925,7 @@ pub trait Crypto {
let keystore = &***self
.extension::<KeystoreExt>()
.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
@@ -941,7 +939,7 @@ pub trait Crypto {
let keystore = &***self
.extension::<KeystoreExt>()
.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
@@ -957,7 +955,7 @@ pub trait Crypto {
let keystore = &***self
.extension::<KeystoreExt>()
.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))
@@ -976,7 +974,7 @@ pub trait Crypto {
let keystore = &***self
.extension::<KeystoreExt>()
.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.
-1
View File
@@ -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 }
+8 -242
View File
@@ -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<sr25519::Public>;
/// 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<sr25519::Public, Error>;
/// Returns all ed25519 public keys for the given key type.
async fn ed25519_public_keys(&self, id: KeyTypeId) -> Vec<ed25519::Public>;
/// 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<ed25519::Public, Error>;
/// Returns all ecdsa public keys for the given key type.
async fn ecdsa_public_keys(&self, id: KeyTypeId) -> Vec<ecdsa::Public>;
/// 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<ecdsa::Public, Error>;
/// 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<CryptoTypePublicPair>,
) -> Result<Vec<CryptoTypePublicPair>, Error>;
/// List all supported keys
///
/// Returns a set of public keys the signer supports.
async fn keys(&self, id: KeyTypeId) -> Result<Vec<CryptoTypePublicPair>, 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<u8>, 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<Option<Vec<u8>>, 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<CryptoTypePublicPair>,
msg: &[u8],
) -> Result<Option<(CryptoTypePublicPair, Vec<u8>)>, 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<CryptoTypePublicPair>,
msg: &[u8],
) -> Result<Vec<Result<Option<Vec<u8>>, 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<Option<VRFSignature>, 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<Option<ecdsa::Signature>, 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<sr25519::Public>;
@@ -257,30 +84,13 @@ pub trait SyncCryptoStore: CryptoStore + Send + Sync {
fn ecdsa_generate_new(&self, id: KeyTypeId, seed: Option<&str>)
-> Result<ecdsa::Public, Error>;
/// 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<CryptoTypePublicPair>,
) -> Result<Vec<CryptoTypePublicPair>, 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<Vec<CryptoTypePublicPair>, Error> {
block_on(CryptoStore::keys(self, id))
}
fn keys(&self, id: KeyTypeId) -> Result<Vec<CryptoTypePublicPair>, 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<Option<Vec<u8>>, 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<CryptoTypePublicPair>,
msg: &[u8],
) -> Result<Option<(CryptoTypePublicPair, Vec<u8>)>, 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<CryptoTypePublicPair>,
msg: &[u8],
) -> Result<Vec<Result<Option<Vec<u8>>, 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<dyn SyncCryptoStore>;
pub type KeystorePtr = Arc<dyn Keystore>;
sp_externalities::decl_extension! {
/// The keystore extension to register/retrieve from the externalities.
pub struct KeystoreExt(SyncCryptoStorePtr);
pub struct KeystoreExt(KeystorePtr);
}
+23 -133
View File
@@ -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<RwLock<HashMap<KeyTypeId, HashMap<Vec<u8>, 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<Vec<CryptoTypePublicPair>, Error> {
SyncCryptoStore::keys(self, id)
}
async fn sr25519_public_keys(&self, id: KeyTypeId) -> Vec<sr25519::Public> {
SyncCryptoStore::sr25519_public_keys(self, id)
}
async fn sr25519_generate_new(
&self,
id: KeyTypeId,
seed: Option<&str>,
) -> Result<sr25519::Public, Error> {
SyncCryptoStore::sr25519_generate_new(self, id, seed)
}
async fn ed25519_public_keys(&self, id: KeyTypeId) -> Vec<ed25519::Public> {
SyncCryptoStore::ed25519_public_keys(self, id)
}
async fn ed25519_generate_new(
&self,
id: KeyTypeId,
seed: Option<&str>,
) -> Result<ed25519::Public, Error> {
SyncCryptoStore::ed25519_generate_new(self, id, seed)
}
async fn ecdsa_public_keys(&self, id: KeyTypeId) -> Vec<ecdsa::Public> {
SyncCryptoStore::ecdsa_public_keys(self, id)
}
async fn ecdsa_generate_new(
&self,
id: KeyTypeId,
seed: Option<&str>,
) -> Result<ecdsa::Public, Error> {
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<u8>, KeyTypeId)]) -> bool {
SyncCryptoStore::has_keys(self, public_keys)
}
async fn supported_keys(
&self,
id: KeyTypeId,
keys: Vec<CryptoTypePublicPair>,
) -> std::result::Result<Vec<CryptoTypePublicPair>, Error> {
SyncCryptoStore::supported_keys(self, id, keys)
}
async fn sign_with(
&self,
id: KeyTypeId,
key: &CryptoTypePublicPair,
msg: &[u8],
) -> Result<Option<Vec<u8>>, Error> {
SyncCryptoStore::sign_with(self, id, key, msg)
}
async fn sr25519_vrf_sign(
&self,
key_type: KeyTypeId,
public: &sr25519::Public,
transcript_data: VRFTranscriptData,
) -> Result<Option<VRFSignature>, 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<Option<ecdsa::Signature>, Error> {
SyncCryptoStore::ecdsa_sign_prehashed(self, id, public, msg)
}
}
impl SyncCryptoStore for KeyStore {
impl Keystore for MemoryKeystore {
fn keys(&self, id: KeyTypeId) -> Result<Vec<CryptoTypePublicPair>, 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<CryptoTypePublicPair>,
) -> std::result::Result<Vec<CryptoTypePublicPair>, Error> {
let provided_keys = keys.into_iter().collect::<HashSet<_>>();
let all_keys = SyncCryptoStore::keys(self, id)?.into_iter().collect::<HashSet<_>>();
Ok(provided_keys.intersection(&all_keys).cloned().collect())
}
fn sign_with(
&self,
id: KeyTypeId,
@@ -386,14 +285,8 @@ impl SyncCryptoStore for KeyStore {
}
}
impl Into<SyncCryptoStorePtr> for KeyStore {
fn into(self) -> SyncCryptoStorePtr {
Arc::new(self)
}
}
impl Into<Arc<dyn CryptoStore>> for KeyStore {
fn into(self) -> Arc<dyn CryptoStore> {
impl Into<KeystorePtr> for MemoryKeystore {
fn into(self) -> KeystorePtr {
Arc::new(self)
}
}
@@ -401,7 +294,7 @@ impl Into<Arc<dyn CryptoStore>> 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());
}
}
+3 -3
View File
@@ -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<Block: BlockT, ExecutorDispatch, Backend: 'static,
child_storage_extension: HashMap<Vec<u8>, StorageChild>,
backend: Arc<Backend>,
_executor: std::marker::PhantomData<ExecutorDispatch>,
keystore: Option<SyncCryptoStorePtr>,
keystore: Option<KeystorePtr>,
fork_blocks: ForkBlocks<Block>,
bad_blocks: BadBlocks<Block>,
enable_offchain_indexing_api: bool,
@@ -128,7 +128,7 @@ impl<Block: BlockT, ExecutorDispatch, Backend, G: GenesisInit>
}
/// 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
}
@@ -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()));
@@ -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