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
@@ -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>,