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" name = "sp-keystore"
version = "0.13.0" version = "0.13.0"
dependencies = [ dependencies = [
"async-trait",
"futures", "futures",
"merlin", "merlin",
"parity-scale-codec", "parity-scale-codec",
@@ -150,7 +150,7 @@ pub fn new_partial(
fn remote_keystore(_url: &String) -> Result<Arc<LocalKeystore>, &'static str> { fn remote_keystore(_url: &String) -> Result<Arc<LocalKeystore>, &'static str> {
// FIXME: here would the concrete keystore be built, // FIXME: here would the concrete keystore be built,
// must return a concrete type (NOT `LocalKeystore`) that // must return a concrete type (NOT `LocalKeystore`) that
// implements `CryptoStore` and `SyncCryptoStore` // implements `Keystore`
Err("Remote Keystore not supported.") 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 { let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
network: network.clone(), network: network.clone(),
client: client.clone(), client: client.clone(),
keystore: keystore_container.sync_keystore(), keystore: keystore_container.keystore(),
task_manager: &mut task_manager, task_manager: &mut task_manager,
transaction_pool: transaction_pool.clone(), transaction_pool: transaction_pool.clone(),
rpc_builder: rpc_extensions_builder, rpc_builder: rpc_extensions_builder,
@@ -276,7 +276,7 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
}, },
force_authoring, force_authoring,
backoff_authoring_blocks, backoff_authoring_blocks,
keystore: keystore_container.sync_keystore(), keystore: keystore_container.keystore(),
sync_oracle: sync_service.clone(), sync_oracle: sync_service.clone(),
justification_sync_link: sync_service.clone(), justification_sync_link: sync_service.clone(),
block_proposal_slot_portion: SlotProportion::new(2f32 / 3f32), 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 enable_grandpa {
// if the node isn't actively participating in consensus then it doesn't // if the node isn't actively participating in consensus then it doesn't
// need a keystore, regardless of which protocol we use below. // need a keystore, regardless of which protocol we use below.
let keystore = let keystore = if role.is_authority() { Some(keystore_container.keystore()) } else { None };
if role.is_authority() { Some(keystore_container.sync_keystore()) } else { None };
let grandpa_config = sc_consensus_grandpa::Config { let grandpa_config = sc_consensus_grandpa::Config {
// FIXME #1578 make this available through chainspec // FIXME #1578 make this available through chainspec
+8 -9
View File
@@ -251,7 +251,7 @@ pub fn new_partial(
let client = client.clone(); let client = client.clone();
let pool = transaction_pool.clone(); let pool = transaction_pool.clone();
let select_chain = select_chain.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 chain_spec = config.chain_spec.cloned_box();
let rpc_backend = backend.clone(); let rpc_backend = backend.clone();
@@ -386,7 +386,7 @@ pub fn new_full_base(
config, config,
backend, backend,
client: client.clone(), client: client.clone(),
keystore: keystore_container.sync_keystore(), keystore: keystore_container.keystore(),
network: network.clone(), network: network.clone(),
rpc_builder: Box::new(rpc_builder), rpc_builder: Box::new(rpc_builder),
transaction_pool: transaction_pool.clone(), transaction_pool: transaction_pool.clone(),
@@ -431,7 +431,7 @@ pub fn new_full_base(
let client_clone = client.clone(); let client_clone = client.clone();
let slot_duration = babe_link.config().slot_duration(); let slot_duration = babe_link.config().slot_duration();
let babe_config = sc_consensus_babe::BabeParams { let babe_config = sc_consensus_babe::BabeParams {
keystore: keystore_container.sync_keystore(), keystore: keystore_container.keystore(),
client: client.clone(), client: client.clone(),
select_chain, select_chain,
env: proposer, env: proposer,
@@ -507,8 +507,7 @@ pub fn new_full_base(
// if the node isn't actively participating in consensus then it doesn't // if the node isn't actively participating in consensus then it doesn't
// need a keystore, regardless of which protocol we use below. // need a keystore, regardless of which protocol we use below.
let keystore = let keystore = if role.is_authority() { Some(keystore_container.keystore()) } else { None };
if role.is_authority() { Some(keystore_container.sync_keystore()) } else { None };
let config = grandpa::Config { let config = grandpa::Config {
// FIXME #1578 make this available through chainspec // FIXME #1578 make this available through chainspec
@@ -596,7 +595,7 @@ mod tests {
use sp_core::{crypto::Pair as CryptoPair, Public}; use sp_core::{crypto::Pair as CryptoPair, Public};
use sp_inherents::InherentDataProvider; use sp_inherents::InherentDataProvider;
use sp_keyring::AccountKeyring; use sp_keyring::AccountKeyring;
use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; use sp_keystore::{Keystore, KeystorePtr};
use sp_runtime::{ use sp_runtime::{
generic::{Digest, Era, SignedPayload}, generic::{Digest, Era, SignedPayload},
key_types::BABE, key_types::BABE,
@@ -616,10 +615,10 @@ mod tests {
sp_tracing::try_init_simple(); sp_tracing::try_init_simple();
let keystore_path = tempfile::tempdir().expect("Creates keystore path"); 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")); Arc::new(LocalKeystore::open(keystore_path.path(), None).expect("Creates keystore"));
let alice: sp_consensus_babe::AuthorityId = 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") .expect("Creates authority pair")
.into(); .into();
@@ -736,7 +735,7 @@ mod tests {
// sign the pre-sealed hash of the block and then // sign the pre-sealed hash of the block and then
// add it to a digest item. // add it to a digest item.
let to_sign = pre_hash.encode(); let to_sign = pre_hash.encode();
let signature = SyncCryptoStore::sign_with( let signature = Keystore::sign_with(
&*keystore, &*keystore,
sp_consensus_babe::AuthorityId::ID, sp_consensus_babe::AuthorityId::ID,
&alice.to_public_crypto_pair(), &alice.to_public_crypto_pair(),
@@ -21,7 +21,7 @@ use kitchensink_runtime::{Executive, Indices, Runtime, UncheckedExtrinsic};
use sp_application_crypto::AppKey; use sp_application_crypto::AppKey;
use sp_core::offchain::{testing::TestTransactionPoolExt, TransactionPoolExt}; use sp_core::offchain::{testing::TestTransactionPoolExt, TransactionPoolExt};
use sp_keyring::sr25519::Keyring::Alice; use sp_keyring::sr25519::Keyring::Alice;
use sp_keystore::{testing::KeyStore, KeystoreExt, SyncCryptoStore}; use sp_keystore::{testing::MemoryKeystore, Keystore, KeystoreExt};
use std::sync::Arc; use std::sync::Arc;
pub mod common; pub mod common;
@@ -62,20 +62,20 @@ fn should_submit_signed_transaction() {
let (pool, state) = TestTransactionPoolExt::new(); let (pool, state) = TestTransactionPoolExt::new();
t.register_extension(TransactionPoolExt::new(pool)); t.register_extension(TransactionPoolExt::new(pool));
let keystore = KeyStore::new(); let keystore = MemoryKeystore::new();
SyncCryptoStore::sr25519_generate_new( Keystore::sr25519_generate_new(
&keystore, &keystore,
sr25519::AuthorityId::ID, sr25519::AuthorityId::ID,
Some(&format!("{}/hunter1", PHRASE)), Some(&format!("{}/hunter1", PHRASE)),
) )
.unwrap(); .unwrap();
SyncCryptoStore::sr25519_generate_new( Keystore::sr25519_generate_new(
&keystore, &keystore,
sr25519::AuthorityId::ID, sr25519::AuthorityId::ID,
Some(&format!("{}/hunter2", PHRASE)), Some(&format!("{}/hunter2", PHRASE)),
) )
.unwrap(); .unwrap();
SyncCryptoStore::sr25519_generate_new( Keystore::sr25519_generate_new(
&keystore, &keystore,
sr25519::AuthorityId::ID, sr25519::AuthorityId::ID,
Some(&format!("{}/hunter3", PHRASE)), Some(&format!("{}/hunter3", PHRASE)),
@@ -105,14 +105,14 @@ fn should_submit_signed_twice_from_the_same_account() {
let (pool, state) = TestTransactionPoolExt::new(); let (pool, state) = TestTransactionPoolExt::new();
t.register_extension(TransactionPoolExt::new(pool)); t.register_extension(TransactionPoolExt::new(pool));
let keystore = KeyStore::new(); let keystore = MemoryKeystore::new();
SyncCryptoStore::sr25519_generate_new( Keystore::sr25519_generate_new(
&keystore, &keystore,
sr25519::AuthorityId::ID, sr25519::AuthorityId::ID,
Some(&format!("{}/hunter1", PHRASE)), Some(&format!("{}/hunter1", PHRASE)),
) )
.unwrap(); .unwrap();
SyncCryptoStore::sr25519_generate_new( Keystore::sr25519_generate_new(
&keystore, &keystore,
sr25519::AuthorityId::ID, sr25519::AuthorityId::ID,
Some(&format!("{}/hunter2", PHRASE)), Some(&format!("{}/hunter2", PHRASE)),
@@ -162,7 +162,7 @@ fn should_submit_signed_twice_from_all_accounts() {
let (pool, state) = TestTransactionPoolExt::new(); let (pool, state) = TestTransactionPoolExt::new();
t.register_extension(TransactionPoolExt::new(pool)); t.register_extension(TransactionPoolExt::new(pool));
let keystore = KeyStore::new(); let keystore = MemoryKeystore::new();
keystore keystore
.sr25519_generate_new(sr25519::AuthorityId::ID, Some(&format!("{}/hunter1", PHRASE))) .sr25519_generate_new(sr25519::AuthorityId::ID, Some(&format!("{}/hunter1", PHRASE)))
.unwrap(); .unwrap();
@@ -226,8 +226,8 @@ fn submitted_transaction_should_be_valid() {
let (pool, state) = TestTransactionPoolExt::new(); let (pool, state) = TestTransactionPoolExt::new();
t.register_extension(TransactionPoolExt::new(pool)); t.register_extension(TransactionPoolExt::new(pool));
let keystore = KeyStore::new(); let keystore = MemoryKeystore::new();
SyncCryptoStore::sr25519_generate_new( Keystore::sr25519_generate_new(
&keystore, &keystore,
sr25519::AuthorityId::ID, sr25519::AuthorityId::ID,
Some(&format!("{}/hunter1", PHRASE)), 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_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata};
use sp_consensus::SelectChain; use sp_consensus::SelectChain;
use sp_consensus_babe::BabeApi; use sp_consensus_babe::BabeApi;
use sp_keystore::SyncCryptoStorePtr; use sp_keystore::KeystorePtr;
/// Extra dependencies for BABE. /// Extra dependencies for BABE.
pub struct BabeDeps { pub struct BabeDeps {
@@ -58,7 +58,7 @@ pub struct BabeDeps {
/// BABE pending epoch changes. /// BABE pending epoch changes.
pub shared_epoch_changes: SharedEpochChanges<Block, Epoch>, pub shared_epoch_changes: SharedEpochChanges<Block, Epoch>,
/// The keystore that manages the keys of the node. /// The keystore that manages the keys of the node.
pub keystore: SyncCryptoStorePtr, pub keystore: KeystorePtr,
} }
/// Extra dependencies for GRANDPA /// Extra dependencies for GRANDPA
@@ -32,7 +32,7 @@ use sp_core::{
crypto::{ByteArray, Ss58Codec}, crypto::{ByteArray, Ss58Codec},
sr25519, 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 /// A utility to easily create a testnet chain spec definition with a given set
/// of authorities and endowed accounts and/or generate random accounts. /// 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> { fn generate_authority_keys_and_store(seeds: &[String], keystore_path: &Path) -> Result<(), String> {
for (n, seed) in seeds.iter().enumerate() { 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) LocalKeystore::open(keystore_path.join(format!("auth-{}", n)), None)
.map_err(|err| err.to_string())?, .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); chain_spec::authority_keys_from_seed(seed);
let insert_key = |key_type, public| { 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)) .map_err(|_| format!("Failed to insert key: {}", grandpa))
}; };
@@ -30,7 +30,7 @@ use sp_core::{
ExecutionContext, ExecutionContext,
}; };
use sp_externalities::{Extension, Extensions}; use sp_externalities::{Extension, Extensions};
use sp_keystore::{KeystoreExt, SyncCryptoStorePtr}; use sp_keystore::{KeystoreExt, KeystorePtr};
use sp_runtime::{ use sp_runtime::{
generic::BlockId, generic::BlockId,
traits::{Block as BlockT, NumberFor}, 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`. /// for each call, based on required `Capabilities`.
pub struct ExecutionExtensions<Block: BlockT> { pub struct ExecutionExtensions<Block: BlockT> {
strategies: ExecutionStrategies, strategies: ExecutionStrategies,
keystore: Option<SyncCryptoStorePtr>, keystore: Option<KeystorePtr>,
offchain_db: Option<Box<dyn DbExternalitiesFactory>>, offchain_db: Option<Box<dyn DbExternalitiesFactory>>,
// FIXME: these two are only RwLock because of https://github.com/paritytech/substrate/issues/4587 // FIXME: these two are only RwLock because of https://github.com/paritytech/substrate/issues/4587
// remove when fixed. // remove when fixed.
@@ -191,7 +191,7 @@ impl<Block: BlockT> ExecutionExtensions<Block> {
/// Create new `ExecutionExtensions` given a `keystore` and `ExecutionStrategies`. /// Create new `ExecutionExtensions` given a `keystore` and `ExecutionStrategies`.
pub fn new( pub fn new(
strategies: ExecutionStrategies, strategies: ExecutionStrategies,
keystore: Option<SyncCryptoStorePtr>, keystore: Option<KeystorePtr>,
offchain_db: Option<Box<dyn DbExternalitiesFactory>>, offchain_db: Option<Box<dyn DbExternalitiesFactory>>,
) -> Self { ) -> Self {
let transaction_pool = RwLock::new(None); let transaction_pool = RwLock::new(None);
@@ -33,7 +33,7 @@ use std::{collections::HashSet, sync::Arc};
use sp_authority_discovery::AuthorityId; use sp_authority_discovery::AuthorityId;
use sp_core::crypto::key_types; use sp_core::crypto::key_types;
use sp_keystore::{testing::KeyStore, CryptoStore}; use sp_keystore::{testing::MemoryKeystore, Keystore};
#[test] #[test]
fn get_addresses_and_authority_id() { fn get_addresses_and_authority_id() {
@@ -42,12 +42,11 @@ fn get_addresses_and_authority_id() {
let mut pool = LocalPool::new(); let mut pool = LocalPool::new();
let key_store = KeyStore::new(); let key_store = MemoryKeystore::new();
let remote_authority_id: AuthorityId = pool.run_until(async { let remote_authority_id: AuthorityId = pool.run_until(async {
key_store key_store
.sr25519_generate_new(key_types::AUTHORITY_DISCOVERY, None) .sr25519_generate_new(key_types::AUTHORITY_DISCOVERY, None)
.await
.unwrap() .unwrap()
.into() .into()
}); });
@@ -53,7 +53,7 @@ use sp_authority_discovery::{
use sp_blockchain::HeaderBackend; use sp_blockchain::HeaderBackend;
use sp_core::crypto::{key_types, CryptoTypePublicPair, Pair}; use sp_core::crypto::{key_types, CryptoTypePublicPair, Pair};
use sp_keystore::CryptoStore; use sp_keystore::{Keystore, KeystorePtr};
use sp_runtime::traits::Block as BlockT; use sp_runtime::traits::Block as BlockT;
mod addr_cache; mod addr_cache;
@@ -78,7 +78,7 @@ const MAX_IN_FLIGHT_LOOKUPS: usize = 8;
/// Role an authority discovery [`Worker`] can run as. /// Role an authority discovery [`Worker`] can run as.
pub enum Role { pub enum Role {
/// Publish own addresses and discover addresses of others. /// Publish own addresses and discover addresses of others.
PublishAndDiscover(Arc<dyn CryptoStore>), PublishAndDiscover(KeystorePtr),
/// Discover addresses of others. /// Discover addresses of others.
Discover, Discover,
} }
@@ -364,8 +364,7 @@ where
Some(peer_signature), Some(peer_signature),
key_store.as_ref(), key_store.as_ref(),
keys_vec, keys_vec,
) )?;
.await?;
for (key, value) in kv_pairs.into_iter() { for (key, value) in kv_pairs.into_iter() {
self.network.put_value(key, value); self.network.put_value(key, value);
@@ -382,7 +381,6 @@ where
let local_keys = match &self.role { let local_keys = match &self.role {
Role::PublishAndDiscover(key_store) => key_store Role::PublishAndDiscover(key_store) => key_store
.sr25519_public_keys(key_types::AUTHORITY_DISCOVERY) .sr25519_public_keys(key_types::AUTHORITY_DISCOVERY)
.await
.into_iter() .into_iter()
.collect::<HashSet<_>>(), .collect::<HashSet<_>>(),
Role::Discover => HashSet::new(), 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 // 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. // discovery public keys, but only the ones intersecting with the current or next authority set.
async fn get_own_public_keys_within_authority_set( async fn get_own_public_keys_within_authority_set(
key_store: Arc<dyn CryptoStore>, key_store: KeystorePtr,
client: &Client, client: &Client,
) -> Result<HashSet<AuthorityId>> { ) -> Result<HashSet<AuthorityId>> {
let local_pub_keys = key_store let local_pub_keys = key_store
.sr25519_public_keys(key_types::AUTHORITY_DISCOVERY) .sr25519_public_keys(key_types::AUTHORITY_DISCOVERY)
.await
.into_iter() .into_iter()
.collect::<HashSet<_>>(); .collect::<HashSet<_>>();
@@ -663,33 +660,28 @@ fn sign_record_with_peer_id(
Ok(schema::PeerSignature { signature, public_key }) Ok(schema::PeerSignature { signature, public_key })
} }
async fn sign_record_with_authority_ids( fn sign_record_with_authority_ids(
serialized_record: Vec<u8>, serialized_record: Vec<u8>,
peer_signature: Option<schema::PeerSignature>, peer_signature: Option<schema::PeerSignature>,
key_store: &dyn CryptoStore, key_store: &dyn Keystore,
keys: Vec<CryptoTypePublicPair>, keys: Vec<CryptoTypePublicPair>,
) -> Result<Vec<(KademliaKey, Vec<u8>)>> { ) -> Result<Vec<(KademliaKey, Vec<u8>)>> {
let signatures = key_store let mut result = Vec::with_capacity(keys.len());
.sign_with_all(key_types::AUTHORITY_DISCOVERY, keys.clone(), &serialized_record)
.await
.map_err(|_| Error::Signing)?;
let mut result = vec![]; for key in keys.iter() {
for (sign_result, key) in signatures.into_iter().zip(keys.iter()) { let auth_signature = key_store
let mut signed_record = vec![]; .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 signed_record = schema::SignedAuthorityRecord {
let auth_signature =
sign_result.ok().flatten().ok_or_else(|| Error::MissingSignature(key.clone()))?;
schema::SignedAuthorityRecord {
record: serialized_record.clone(), record: serialized_record.clone(),
auth_signature, auth_signature,
peer_signature: peer_signature.clone(), peer_signature: peer_signature.clone(),
} }
.encode(&mut signed_record) .encode_to_vec();
.map_err(Error::EncodingProto)?;
result.push((hash_authority_id(key.1.as_ref()), signed_record)); result.push((hash_authority_id(&key.1), signed_record));
} }
Ok(result) Ok(result)
@@ -40,7 +40,7 @@ use prometheus_endpoint::prometheus::default_registry;
use sc_client_api::HeaderBackend; use sc_client_api::HeaderBackend;
use sc_network::Signature; use sc_network::Signature;
use sp_api::{ApiRef, ProvideRuntimeApi}; 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 sp_runtime::traits::{Block as BlockT, NumberFor, Zero};
use substrate_test_runtime_client::runtime::Block; 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>, addresses: Vec<Multiaddr>,
public_key: AuthorityId, public_key: AuthorityId,
key_store: &dyn CryptoStore, key_store: &MemoryKeystore,
network: Option<&Signer>, network: Option<&Signer>,
) -> Vec<(KademliaKey, Vec<u8>)> { ) -> Vec<(KademliaKey, Vec<u8>)> {
let serialized_record = let serialized_record =
@@ -224,7 +224,6 @@ async fn build_dht_event<Signer: NetworkSigner>(
key_store, key_store,
vec![public_key.into()], vec![public_key.into()],
) )
.await
.unwrap(); .unwrap();
// There is always a single item in it, because we signed it with a single key // There is always a single item in it, because we signed it with a single key
kv_pairs kv_pairs
@@ -234,7 +233,7 @@ async fn build_dht_event<Signer: NetworkSigner>(
fn new_registers_metrics() { fn new_registers_metrics() {
let (_dht_event_tx, dht_event_rx) = mpsc::channel(1000); let (_dht_event_tx, dht_event_rx) = mpsc::channel(1000);
let network: Arc<TestNetwork> = Arc::new(Default::default()); 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 test_api = Arc::new(TestApi { authorities: vec![] });
let registry = prometheus_endpoint::Registry::new(); 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 test_api = Arc::new(TestApi { authorities: authorities.clone() });
let network = Arc::new(TestNetwork::default()); 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 (_to_worker, from_service) = mpsc::channel(0);
let mut worker = Worker::new( let mut worker = Worker::new(
@@ -298,14 +297,12 @@ fn publish_discover_cycle() {
let network: Arc<TestNetwork> = Arc::new(Default::default()); let network: Arc<TestNetwork> = Arc::new(Default::default());
let key_store = KeyStore::new(); let key_store = MemoryKeystore::new();
let _ = pool.spawner().spawn_local_obj( let _ = pool.spawner().spawn_local_obj(
async move { async move {
let node_a_public = key_store let node_a_public =
.sr25519_generate_new(key_types::AUTHORITY_DISCOVERY, None) key_store.sr25519_generate_new(key_types::AUTHORITY_DISCOVERY, None).unwrap();
.await
.unwrap();
let test_api = Arc::new(TestApi { authorities: vec![node_a_public.into()] }); let test_api = Arc::new(TestApi { authorities: vec![node_a_public.into()] });
let (_to_worker, from_service) = mpsc::channel(0); let (_to_worker, from_service) = mpsc::channel(0);
@@ -337,7 +334,7 @@ fn publish_discover_cycle() {
authorities: vec![node_a_public.into()], authorities: vec![node_a_public.into()],
}); });
let network: Arc<TestNetwork> = Arc::new(Default::default()); 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 (_to_worker, from_service) = mpsc::channel(0);
let mut worker = Worker::new( let mut worker = Worker::new(
@@ -371,7 +368,7 @@ fn publish_discover_cycle() {
fn terminate_when_event_stream_terminates() { fn terminate_when_event_stream_terminates() {
let (dht_event_tx, dht_event_rx) = channel(1000); let (dht_event_tx, dht_event_rx) = channel(1000);
let network: Arc<TestNetwork> = Arc::new(Default::default()); 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 test_api = Arc::new(TestApi { authorities: vec![] });
let (to_worker, from_service) = mpsc::channel(0); 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())) address.with(multiaddr::Protocol::P2p(peer_id.into()))
}; };
let remote_key_store = KeyStore::new(); let remote_key_store = MemoryKeystore::new();
let remote_public_key: AuthorityId = let remote_public_key: AuthorityId = remote_key_store
block_on(remote_key_store.sr25519_generate_new(key_types::AUTHORITY_DISCOVERY, None)) .sr25519_generate_new(key_types::AUTHORITY_DISCOVERY, None)
.unwrap() .unwrap()
.into(); .into();
let (mut dht_event_tx, dht_event_rx) = channel(1); let (mut dht_event_tx, dht_event_rx) = channel(1);
let (network, mut network_events) = { let (network, mut network_events) = {
@@ -433,7 +430,7 @@ fn dont_stop_polling_dht_event_stream_after_bogus_event() {
(Arc::new(n), r) (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 test_api = Arc::new(TestApi { authorities: vec![remote_public_key.clone()] });
let mut pool = LocalPool::new(); let mut pool = LocalPool::new();
@@ -480,8 +477,7 @@ fn dont_stop_polling_dht_event_stream_after_bogus_event() {
remote_public_key.clone(), remote_public_key.clone(),
&remote_key_store, &remote_key_store,
None, None,
) );
.await;
DhtEvent::ValueFound(kv_pairs) DhtEvent::ValueFound(kv_pairs)
}; };
dht_event_tx.send(dht_event).await.expect("Channel has capacity of 1."); 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 { struct DhtValueFoundTester {
pub remote_key_store: KeyStore, pub remote_key_store: MemoryKeystore,
pub remote_authority_public: sp_core::sr25519::Public, pub remote_authority_public: sp_core::sr25519::Public,
pub remote_node_key: Keypair, pub remote_node_key: Keypair,
pub local_worker: Option< pub local_worker: Option<
@@ -516,10 +512,10 @@ struct DhtValueFoundTester {
impl DhtValueFoundTester { impl DhtValueFoundTester {
fn new() -> Self { fn new() -> Self {
let remote_key_store = KeyStore::new(); let remote_key_store = MemoryKeystore::new();
let remote_authority_public = let remote_authority_public = remote_key_store
block_on(remote_key_store.sr25519_generate_new(key_types::AUTHORITY_DISCOVERY, None)) .sr25519_generate_new(key_types::AUTHORITY_DISCOVERY, None)
.unwrap(); .unwrap();
let remote_node_key = Keypair::generate_ed25519(); let remote_node_key = Keypair::generate_ed25519();
Self { remote_key_store, remote_authority_public, remote_node_key, local_worker: None } Self { remote_key_store, remote_authority_public, remote_node_key, local_worker: None }
@@ -542,7 +538,7 @@ impl DhtValueFoundTester {
let local_test_api = let local_test_api =
Arc::new(TestApi { authorities: vec![self.remote_authority_public.into()] }); Arc::new(TestApi { authorities: vec![self.remote_authority_public.into()] });
let local_network: Arc<TestNetwork> = Arc::new(Default::default()); 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 (_to_worker, from_service) = mpsc::channel(0);
let mut local_worker = Worker::new( 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(); let mut tester = DhtValueFoundTester::new();
assert!(MAX_ADDRESSES_PER_AUTHORITY < 100); assert!(MAX_ADDRESSES_PER_AUTHORITY < 100);
let addresses = (1..100).map(|i| tester.multiaddr_with_peer_id(i)).collect(); 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, addresses,
tester.remote_authority_public.into(), tester.remote_authority_public.into(),
&tester.remote_key_store, &tester.remote_key_store,
None, None,
)); );
let cached_remote_addresses = tester.process_value_found(false, kv_pairs); let cached_remote_addresses = tester.process_value_found(false, kv_pairs);
assert_eq!(MAX_ADDRESSES_PER_AUTHORITY, cached_remote_addresses.unwrap().len()); 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() { fn strict_accept_address_with_peer_signature() {
let mut tester = DhtValueFoundTester::new(); let mut tester = DhtValueFoundTester::new();
let addr = tester.multiaddr_with_peer_id(1); 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()], vec![addr.clone()],
tester.remote_authority_public.into(), tester.remote_authority_public.into(),
&tester.remote_key_store, &tester.remote_key_store,
Some(&TestSigner { keypair: &tester.remote_node_key }), Some(&TestSigner { keypair: &tester.remote_node_key }),
)); );
let cached_remote_addresses = tester.process_value_found(true, kv_pairs); 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() { fn reject_address_with_rogue_peer_signature() {
let mut tester = DhtValueFoundTester::new(); let mut tester = DhtValueFoundTester::new();
let rogue_remote_node_key = Keypair::generate_ed25519(); 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)], vec![tester.multiaddr_with_peer_id(1)],
tester.remote_authority_public.into(), tester.remote_authority_public.into(),
&tester.remote_key_store, &tester.remote_key_store,
Some(&TestSigner { keypair: &rogue_remote_node_key }), Some(&TestSigner { keypair: &rogue_remote_node_key }),
)); );
let cached_remote_addresses = tester.process_value_found(false, kv_pairs); let cached_remote_addresses = tester.process_value_found(false, kv_pairs);
@@ -629,12 +625,12 @@ fn reject_address_with_rogue_peer_signature() {
#[test] #[test]
fn reject_address_with_invalid_peer_signature() { fn reject_address_with_invalid_peer_signature() {
let mut tester = DhtValueFoundTester::new(); 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)], vec![tester.multiaddr_with_peer_id(1)],
tester.remote_authority_public.into(), tester.remote_authority_public.into(),
&tester.remote_key_store, &tester.remote_key_store,
Some(&TestSigner { keypair: &tester.remote_node_key }), Some(&TestSigner { keypair: &tester.remote_node_key }),
)); );
// tamper with the signature // tamper with the signature
let mut record = schema::SignedAuthorityRecord::decode(kv_pairs[0].1.as_slice()).unwrap(); 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]); 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] #[test]
fn reject_address_without_peer_signature() { fn reject_address_without_peer_signature() {
let mut tester = DhtValueFoundTester::new(); 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)], vec![tester.multiaddr_with_peer_id(1)],
tester.remote_authority_public.into(), tester.remote_authority_public.into(),
&tester.remote_key_store, &tester.remote_key_store,
None, None,
)); );
let cached_remote_addresses = tester.process_value_found(true, kv_pairs); 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_with_peer_id = tester.multiaddr_with_peer_id(1);
let multiaddr_without_peer_id: Multiaddr = let multiaddr_without_peer_id: Multiaddr =
"/ip6/2001:db8:0:0:0:0:0:2/tcp/30333".parse().unwrap(); "/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], vec![multiaddr_with_peer_id.clone(), multiaddr_without_peer_id],
tester.remote_authority_public.into(), tester.remote_authority_public.into(),
&tester.remote_key_store, &tester.remote_key_store,
None, None,
)); );
let cached_remote_addresses = tester.process_value_found(false, kv_pairs); 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![] }), Arc::new(TestApi { authorities: vec![] }),
network.clone(), network.clone(),
Box::pin(dht_event_rx), Box::pin(dht_event_rx),
Role::PublishAndDiscover(Arc::new(KeyStore::new())), Role::PublishAndDiscover(Arc::new(MemoryKeystore::new())),
Some(prometheus_endpoint::Registry::new()), Some(prometheus_endpoint::Registry::new()),
Default::default(), Default::default(),
); );
@@ -735,7 +731,7 @@ fn addresses_to_publish_respects_existing_p2p_protocol() {
Arc::new(TestApi { authorities: vec![] }), Arc::new(TestApi { authorities: vec![] }),
network.clone(), network.clone(),
Box::pin(dht_event_rx), Box::pin(dht_event_rx),
Role::PublishAndDiscover(Arc::new(KeyStore::new())), Role::PublishAndDiscover(Arc::new(MemoryKeystore::new())),
Some(prometheus_endpoint::Registry::new()), Some(prometheus_endpoint::Registry::new()),
Default::default(), Default::default(),
); );
@@ -755,10 +751,11 @@ fn lookup_throttling() {
address.with(multiaddr::Protocol::P2p(peer_id.into())) 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) let remote_public_keys: Vec<AuthorityId> = (0..20)
.map(|_| { .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() .unwrap()
.into() .into()
}) })
@@ -818,8 +815,7 @@ fn lookup_throttling() {
remote_key, remote_key,
&remote_key_store, &remote_key_store,
None, None,
) );
.await;
DhtEvent::ValueFound(kv_pairs) DhtEvent::ValueFound(kv_pairs)
}; };
dht_event_tx.send(dht_event).await.expect("Channel has capacity of 1."); 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_keystore::LocalKeystore;
use sc_service::config::{BasePath, KeystoreConfig}; use sc_service::config::{BasePath, KeystoreConfig};
use sp_core::crypto::{KeyTypeId, SecretString}; use sp_core::crypto::{KeyTypeId, SecretString};
use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; use sp_keystore::{Keystore, KeystorePtr};
use std::sync::Arc; use std::sync::Arc;
/// The `insert` command /// The `insert` command
@@ -69,7 +69,7 @@ impl InsertKeyCmd {
let (keystore, public) = match self.keystore_params.keystore_config(&config_dir)? { let (keystore, public) = match self.keystore_params.keystore_config(&config_dir)? {
(_, KeystoreConfig::Path { path, password }) => { (_, KeystoreConfig::Path { path, password }) => {
let public = with_crypto_scheme!(self.scheme, to_vec(&suri, password.clone()))?; let 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) (keystore, public)
}, },
_ => unreachable!("keystore_config always returns path and password; qed"), _ => unreachable!("keystore_config always returns path and password; qed"),
@@ -78,8 +78,8 @@ impl InsertKeyCmd {
let key_type = let key_type =
KeyTypeId::try_from(self.key_type.as_str()).map_err(|_| Error::KeyTypeInvalid)?; KeyTypeId::try_from(self.key_type.as_str()).map_err(|_| Error::KeyTypeInvalid)?;
SyncCryptoStore::insert_unknown(&*keystore, key_type, &suri, &public[..]) Keystore::insert(&*keystore, key_type, &suri, &public[..])
.map_err(|_| Error::KeyStoreOperation)?; .map_err(|_| Error::KeystoreOperation)?;
Ok(()) Ok(())
} }
+1 -1
View File
@@ -64,7 +64,7 @@ pub enum Error {
SignatureInvalid, SignatureInvalid,
#[error("Key store operation failed")] #[error("Key store operation failed")]
KeyStoreOperation, KeystoreOperation,
#[error("Key storage issue encountered")] #[error("Key storage issue encountered")]
KeyStorage(#[from] sc_keystore::Error), 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_consensus_slots::Slot;
use sp_core::crypto::{ByteArray, Pair, Public}; use sp_core::crypto::{ByteArray, Pair, Public};
use sp_inherents::CreateInherentDataProviders; use sp_inherents::CreateInherentDataProviders;
use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; use sp_keystore::{Keystore, KeystorePtr};
use sp_runtime::{ use sp_runtime::{
traits::{Block as BlockT, Header, Member, NumberFor, Zero}, traits::{Block as BlockT, Header, Member, NumberFor, Zero},
DigestItem, DigestItem,
@@ -168,7 +168,7 @@ pub struct StartAuraParams<C, SC, I, PF, SO, L, CIDP, BS, N> {
/// The backoff strategy when we miss slots. /// The backoff strategy when we miss slots.
pub backoff_authoring_blocks: Option<BS>, pub backoff_authoring_blocks: Option<BS>,
/// The keystore used by the node. /// The keystore used by the node.
pub keystore: SyncCryptoStorePtr, pub keystore: KeystorePtr,
/// The proportion of the slot dedicated to proposing. /// 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 /// 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. /// The backoff strategy when we miss slots.
pub backoff_authoring_blocks: Option<BS>, pub backoff_authoring_blocks: Option<BS>,
/// The keystore used by the node. /// The keystore used by the node.
pub keystore: SyncCryptoStorePtr, pub keystore: KeystorePtr,
/// The proportion of the slot dedicated to proposing. /// 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 /// 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>, client: Arc<C>,
block_import: I, block_import: I,
env: E, env: E,
keystore: SyncCryptoStorePtr, keystore: KeystorePtr,
sync_oracle: SO, sync_oracle: SO,
justification_sync_link: L, justification_sync_link: L,
force_authoring: bool, force_authoring: bool,
@@ -418,7 +418,7 @@ where
) -> Option<Self::Claim> { ) -> Option<Self::Claim> {
let expected_author = slot_author::<P>(slot, epoch_data); let expected_author = slot_author::<P>(slot, epoch_data);
expected_author.and_then(|p| { expected_author.and_then(|p| {
if SyncCryptoStore::has_keys( if Keystore::has_keys(
&*self.keystore, &*self.keystore,
&[(p.to_raw_vec(), sp_application_crypto::key_types::AURA)], &[(p.to_raw_vec(), sp_application_crypto::key_types::AURA)],
) { ) {
@@ -449,7 +449,7 @@ where
// add it to a digest item. // add it to a digest item.
let public_type_pair = public.to_public_crypto_pair(); let public_type_pair = public.to_public_crypto_pair();
let public = public.to_raw_vec(); let public = public.to_raw_vec();
let signature = SyncCryptoStore::sign_with( let signature = Keystore::sign_with(
&*self.keystore, &*self.keystore,
<AuthorityId<P> as AppKey>::ID, <AuthorityId<P> as AppKey>::ID,
&public_type_pair, &public_type_pair,
@@ -798,7 +798,7 @@ mod tests {
LocalKeystore::open(keystore_path.path(), None).expect("Creates keystore."), 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"); .expect("Creates authority key");
keystore_paths.push(keystore_path); keystore_paths.push(keystore_path);
@@ -883,7 +883,7 @@ mod tests {
let keystore_path = tempfile::tempdir().expect("Creates keystore path"); let keystore_path = tempfile::tempdir().expect("Creates keystore path");
let keystore = LocalKeystore::open(keystore_path.path(), None).expect("Creates keystore."); 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"); .expect("Key should be created");
authorities.push(public.into()); authorities.push(public.into());
@@ -933,7 +933,7 @@ mod tests {
let keystore_path = tempfile::tempdir().expect("Creates keystore path"); let keystore_path = tempfile::tempdir().expect("Creates keystore path");
let keystore = LocalKeystore::open(keystore_path.path(), None).expect("Creates keystore."); let keystore = LocalKeystore::open(keystore_path.path(), None).expect("Creates keystore.");
SyncCryptoStore::sr25519_generate_new( Keystore::sr25519_generate_new(
&keystore, &keystore,
AuthorityPair::ID, AuthorityPair::ID,
Some(&Keyring::Alice.to_seed()), Some(&Keyring::Alice.to_seed()),
+7 -10
View File
@@ -37,7 +37,7 @@ use sp_consensus_babe::{
digests::PreDigest, AuthorityId, BabeApi as BabeRuntimeApi, BabeConfiguration, digests::PreDigest, AuthorityId, BabeApi as BabeRuntimeApi, BabeConfiguration,
}; };
use sp_core::crypto::ByteArray; 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 sp_runtime::traits::{Block as BlockT, Header as _};
use std::{collections::HashMap, sync::Arc}; use std::{collections::HashMap, sync::Arc};
@@ -57,7 +57,7 @@ pub struct Babe<B: BlockT, C, SC> {
/// shared reference to EpochChanges /// shared reference to EpochChanges
shared_epoch_changes: SharedEpochChanges<B, Epoch>, shared_epoch_changes: SharedEpochChanges<B, Epoch>,
/// shared reference to the Keystore /// shared reference to the Keystore
keystore: SyncCryptoStorePtr, keystore: KeystorePtr,
/// config (actually holds the slot duration) /// config (actually holds the slot duration)
babe_config: BabeConfiguration, babe_config: BabeConfiguration,
/// The SelectChain strategy /// The SelectChain strategy
@@ -71,7 +71,7 @@ impl<B: BlockT, C, SC> Babe<B, C, SC> {
pub fn new( pub fn new(
client: Arc<C>, client: Arc<C>,
shared_epoch_changes: SharedEpochChanges<B, Epoch>, shared_epoch_changes: SharedEpochChanges<B, Epoch>,
keystore: SyncCryptoStorePtr, keystore: KeystorePtr,
babe_config: BabeConfiguration, babe_config: BabeConfiguration,
select_chain: SC, select_chain: SC,
deny_unsafe: DenyUnsafe, deny_unsafe: DenyUnsafe,
@@ -117,10 +117,7 @@ where
.iter() .iter()
.enumerate() .enumerate()
.filter_map(|(i, a)| { .filter_map(|(i, a)| {
if SyncCryptoStore::has_keys( if Keystore::has_keys(&*self.keystore, &[(a.0.to_raw_vec(), AuthorityId::ID)]) {
&*self.keystore,
&[(a.0.to_raw_vec(), AuthorityId::ID)],
) {
Some((a.0.clone(), i)) Some((a.0.clone(), i))
} else { } else {
None None
@@ -217,7 +214,7 @@ mod tests {
use sp_application_crypto::AppPair; use sp_application_crypto::AppPair;
use sp_core::crypto::key_types::BABE; use sp_core::crypto::key_types::BABE;
use sp_keyring::Sr25519Keyring; use sp_keyring::Sr25519Keyring;
use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; use sp_keystore::{Keystore, KeystorePtr};
use substrate_test_runtime_client::{ use substrate_test_runtime_client::{
runtime::Block, Backend, DefaultTestClientBuilderExt, TestClient, TestClientBuilder, runtime::Block, Backend, DefaultTestClientBuilderExt, TestClient, TestClientBuilder,
TestClientBuilderExt, TestClientBuilderExt,
@@ -229,11 +226,11 @@ mod tests {
/// creates keystore backed by a temp file /// creates keystore backed by a temp file
fn create_temp_keystore<P: AppPair>( fn create_temp_keystore<P: AppPair>(
authority: Sr25519Keyring, authority: Sr25519Keyring,
) -> (SyncCryptoStorePtr, tempfile::TempDir) { ) -> (KeystorePtr, tempfile::TempDir) {
let keystore_path = tempfile::tempdir().expect("Creates keystore path"); let keystore_path = tempfile::tempdir().expect("Creates keystore path");
let keystore = let keystore =
Arc::new(LocalKeystore::open(keystore_path.path(), None).expect("Creates 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"); .expect("Creates authority key");
(keystore, keystore_path) (keystore, keystore_path)
@@ -29,7 +29,7 @@ use sp_consensus_babe::{
}; };
use sp_consensus_vrf::schnorrkel::{VRFOutput, VRFProof}; use sp_consensus_vrf::schnorrkel::{VRFOutput, VRFProof};
use sp_core::{blake2_256, crypto::ByteArray, U256}; 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 /// Calculates the primary selection threshold for a given authority, taking
/// into account `c` (`1 - c` represents the probability of a slot being empty). /// into account `c` (`1 - c` represents the probability of a slot being empty).
@@ -133,7 +133,7 @@ fn claim_secondary_slot(
slot: Slot, slot: Slot,
epoch: &Epoch, epoch: &Epoch,
keys: &[(AuthorityId, usize)], keys: &[(AuthorityId, usize)],
keystore: &SyncCryptoStorePtr, keystore: &KeystorePtr,
author_secondary_vrf: bool, author_secondary_vrf: bool,
) -> Option<(PreDigest, AuthorityId)> { ) -> Option<(PreDigest, AuthorityId)> {
let Epoch { authorities, randomness, mut epoch_index, .. } = epoch; let Epoch { authorities, randomness, mut epoch_index, .. } = epoch;
@@ -153,7 +153,7 @@ fn claim_secondary_slot(
if authority_id == expected_author { if authority_id == expected_author {
let pre_digest = if author_secondary_vrf { let pre_digest = if author_secondary_vrf {
let transcript_data = make_transcript_data(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, &**keystore,
AuthorityId::ID, AuthorityId::ID,
authority_id.as_ref(), authority_id.as_ref(),
@@ -169,7 +169,7 @@ fn claim_secondary_slot(
} else { } else {
None None
} }
} else if SyncCryptoStore::has_keys( } else if Keystore::has_keys(
&**keystore, &**keystore,
&[(authority_id.to_raw_vec(), AuthorityId::ID)], &[(authority_id.to_raw_vec(), AuthorityId::ID)],
) { ) {
@@ -197,7 +197,7 @@ fn claim_secondary_slot(
pub fn claim_slot( pub fn claim_slot(
slot: Slot, slot: Slot,
epoch: &Epoch, epoch: &Epoch,
keystore: &SyncCryptoStorePtr, keystore: &KeystorePtr,
) -> Option<(PreDigest, AuthorityId)> { ) -> Option<(PreDigest, AuthorityId)> {
let authorities = epoch let authorities = epoch
.authorities .authorities
@@ -213,7 +213,7 @@ pub fn claim_slot(
pub fn claim_slot_using_keys( pub fn claim_slot_using_keys(
slot: Slot, slot: Slot,
epoch: &Epoch, epoch: &Epoch,
keystore: &SyncCryptoStorePtr, keystore: &KeystorePtr,
keys: &[(AuthorityId, usize)], keys: &[(AuthorityId, usize)],
) -> Option<(PreDigest, AuthorityId)> { ) -> Option<(PreDigest, AuthorityId)> {
claim_primary_slot(slot, epoch, epoch.config.c, keystore, keys).or_else(|| { claim_primary_slot(slot, epoch, epoch.config.c, keystore, keys).or_else(|| {
@@ -241,7 +241,7 @@ fn claim_primary_slot(
slot: Slot, slot: Slot,
epoch: &Epoch, epoch: &Epoch,
c: (u64, u64), c: (u64, u64),
keystore: &SyncCryptoStorePtr, keystore: &KeystorePtr,
keys: &[(AuthorityId, usize)], keys: &[(AuthorityId, usize)],
) -> Option<(PreDigest, AuthorityId)> { ) -> Option<(PreDigest, AuthorityId)> {
let Epoch { authorities, randomness, mut epoch_index, .. } = epoch; let Epoch { authorities, randomness, mut epoch_index, .. } = epoch;
@@ -254,7 +254,7 @@ fn claim_primary_slot(
for (authority_id, authority_index) in keys { for (authority_id, authority_index) in keys {
let transcript = make_transcript(randomness, slot, epoch_index); let transcript = make_transcript(randomness, slot, epoch_index);
let transcript_data = make_transcript_data(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, &**keystore,
AuthorityId::ID, AuthorityId::ID,
authority_id.as_ref(), authority_id.as_ref(),
@@ -294,8 +294,8 @@ mod tests {
#[test] #[test]
fn claim_secondary_plain_slot_works() { fn claim_secondary_plain_slot_works() {
let keystore: SyncCryptoStorePtr = Arc::new(LocalKeystore::in_memory()); let keystore: KeystorePtr = Arc::new(LocalKeystore::in_memory());
let valid_public_key = SyncCryptoStore::sr25519_generate_new( let valid_public_key = Keystore::sr25519_generate_new(
&*keystore, &*keystore,
AuthorityId::ID, AuthorityId::ID,
Some(sp_core::crypto::DEV_PHRASE), 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_consensus_slots::Slot;
use sp_core::{crypto::ByteArray, ExecutionContext}; use sp_core::{crypto::ByteArray, ExecutionContext};
use sp_inherents::{CreateInherentDataProviders, InherentData, InherentDataProvider}; use sp_inherents::{CreateInherentDataProviders, InherentData, InherentDataProvider};
use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; use sp_keystore::{Keystore, KeystorePtr};
use sp_runtime::{ use sp_runtime::{
generic::OpaqueDigestItemId, generic::OpaqueDigestItemId,
traits::{Block as BlockT, Header, NumberFor, SaturatedConversion, Zero}, traits::{Block as BlockT, Header, NumberFor, SaturatedConversion, Zero},
@@ -404,7 +404,7 @@ where
/// Parameters for BABE. /// Parameters for BABE.
pub struct BabeParams<B: BlockT, C, SC, E, I, SO, L, CIDP, BS> { pub struct BabeParams<B: BlockT, C, SC, E, I, SO, L, CIDP, BS> {
/// The keystore that manages the keys of the node. /// The keystore that manages the keys of the node.
pub keystore: SyncCryptoStorePtr, pub keystore: KeystorePtr,
/// The client to use /// The client to use
pub client: Arc<C>, pub client: Arc<C>,
@@ -711,7 +711,7 @@ struct BabeSlotWorker<B: BlockT, C, E, I, SO, L, BS> {
justification_sync_link: L, justification_sync_link: L,
force_authoring: bool, force_authoring: bool,
backoff_authoring_blocks: Option<BS>, backoff_authoring_blocks: Option<BS>,
keystore: SyncCryptoStorePtr, keystore: KeystorePtr,
epoch_changes: SharedEpochChanges<B, Epoch>, epoch_changes: SharedEpochChanges<B, Epoch>,
slot_notification_sinks: SlotNotificationSinks<B>, slot_notification_sinks: SlotNotificationSinks<B>,
config: BabeConfiguration, config: BabeConfiguration,
@@ -834,7 +834,7 @@ where
// add it to a digest item. // add it to a digest item.
let public_type_pair = public.clone().into(); let public_type_pair = public.clone().into();
let public = public.to_raw_vec(); let public = public.to_raw_vec();
let signature = SyncCryptoStore::sign_with( let signature = Keystore::sign_with(
&*self.keystore, &*self.keystore,
<AuthorityId as AppKey>::ID, <AuthorityId as AppKey>::ID,
&public_type_pair, &public_type_pair,
+8 -9
View File
@@ -41,8 +41,7 @@ use sp_consensus_vrf::schnorrkel::VRFOutput;
use sp_core::crypto::Pair; use sp_core::crypto::Pair;
use sp_keyring::Sr25519Keyring; use sp_keyring::Sr25519Keyring;
use sp_keystore::{ use sp_keystore::{
testing::KeyStore as TestKeyStore, vrf::make_transcript as transcript_from_data, testing::MemoryKeystore, vrf::make_transcript as transcript_from_data, Keystore,
SyncCryptoStore,
}; };
use sp_runtime::{ use sp_runtime::{
generic::{Digest, DigestItem}, generic::{Digest, DigestItem},
@@ -369,9 +368,9 @@ async fn rejects_empty_block() {
}) })
} }
fn create_keystore(authority: Sr25519Keyring) -> SyncCryptoStorePtr { fn create_keystore(authority: Sr25519Keyring) -> KeystorePtr {
let keystore = Arc::new(TestKeyStore::new()); let keystore = Arc::new(MemoryKeystore::new());
SyncCryptoStore::sr25519_generate_new(&*keystore, BABE, Some(&authority.to_seed())) Keystore::sr25519_generate_new(&*keystore, BABE, Some(&authority.to_seed()))
.expect("Generates authority key"); .expect("Generates authority key");
keystore keystore
} }
@@ -638,7 +637,7 @@ fn claim_vrf_check() {
v => panic!("Unexpected pre-digest variant {:?}", v), v => panic!("Unexpected pre-digest variant {:?}", v),
}; };
let transcript = make_transcript_data(&epoch.randomness.clone(), 0.into(), epoch.epoch_index); 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()
.unwrap(); .unwrap();
assert_eq!(pre_digest.vrf_output, VRFOutput(sign.output)); assert_eq!(pre_digest.vrf_output, VRFOutput(sign.output));
@@ -649,7 +648,7 @@ fn claim_vrf_check() {
v => panic!("Unexpected pre-digest variant {:?}", v), v => panic!("Unexpected pre-digest variant {:?}", v),
}; };
let transcript = make_transcript_data(&epoch.randomness.clone(), 1.into(), epoch.epoch_index); 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()
.unwrap(); .unwrap();
assert_eq!(pre_digest.vrf_output, VRFOutput(sign.output)); 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 fixed_epoch = epoch.clone_for_slot(slot);
let transcript = make_transcript_data(&epoch.randomness.clone(), slot, fixed_epoch.epoch_index); 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()
.unwrap(); .unwrap();
assert_eq!(fixed_epoch.epoch_index, 11); assert_eq!(fixed_epoch.epoch_index, 11);
@@ -676,7 +675,7 @@ fn claim_vrf_check() {
}; };
let fixed_epoch = epoch.clone_for_slot(slot); let fixed_epoch = epoch.clone_for_slot(slot);
let transcript = make_transcript_data(&epoch.randomness.clone(), slot, fixed_epoch.epoch_index); 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()
.unwrap(); .unwrap();
assert_eq!(fixed_epoch.epoch_index, 11); assert_eq!(fixed_epoch.epoch_index, 11);
@@ -245,7 +245,7 @@ where
mod tests { mod tests {
use sc_keystore::LocalKeystore; use sc_keystore::LocalKeystore;
use sc_network_test::Block; use sc_network_test::Block;
use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; use sp_keystore::{Keystore, KeystorePtr};
use crate::keystore::BeefyKeystore; use crate::keystore::BeefyKeystore;
use sp_consensus_beefy::{ use sp_consensus_beefy::{
@@ -306,8 +306,8 @@ mod tests {
} }
fn sign_commitment<BN: Encode>(who: &Keyring, commitment: &Commitment<BN>) -> Signature { fn sign_commitment<BN: Encode>(who: &Keyring, commitment: &Commitment<BN>) -> Signature {
let store: SyncCryptoStorePtr = std::sync::Arc::new(LocalKeystore::in_memory()); let store: KeystorePtr = std::sync::Arc::new(LocalKeystore::in_memory());
SyncCryptoStore::ecdsa_generate_new(&*store, KEY_TYPE, Some(&who.to_seed())).unwrap(); Keystore::ecdsa_generate_new(&*store, KEY_TYPE, Some(&who.to_seed())).unwrap();
let beefy_keystore: BeefyKeystore = Some(store).into(); let beefy_keystore: BeefyKeystore = Some(store).into();
beefy_keystore.sign(&who.public(), &commitment.encode()).unwrap() beefy_keystore.sign(&who.public(), &commitment.encode()).unwrap()
@@ -18,7 +18,7 @@
use sp_application_crypto::RuntimeAppPublic; use sp_application_crypto::RuntimeAppPublic;
use sp_core::keccak_256; use sp_core::keccak_256;
use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; use sp_keystore::{Keystore, KeystorePtr};
use log::warn; use log::warn;
@@ -33,9 +33,9 @@ use crate::{error, LOG_TARGET};
pub(crate) type BeefySignatureHasher = sp_runtime::traits::Keccak256; pub(crate) type BeefySignatureHasher = sp_runtime::traits::Keccak256;
/// A BEEFY specific keystore implemented as a `Newtype`. This is basically a /// 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. /// common cryptographic functionality.
pub(crate) struct BeefyKeystore(Option<SyncCryptoStorePtr>); pub(crate) struct BeefyKeystore(Option<KeystorePtr>);
impl BeefyKeystore { impl BeefyKeystore {
/// Check if the keystore contains a private key for one of the public keys /// 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. // we do check for multiple private keys as a key store sanity check.
let public: Vec<Public> = keys let public: Vec<Public> = keys
.iter() .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() .cloned()
.collect(); .collect();
@@ -77,7 +77,7 @@ impl BeefyKeystore {
let msg = keccak_256(message); let msg = keccak_256(message);
let public = public.as_ref(); 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()))? .map_err(|e| error::Error::Keystore(e.to_string()))?
.ok_or_else(|| error::Error::Signature("ecdsa_sign_prehashed() failed".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> { 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 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(..) .drain(..)
.map(Public::from) .map(Public::from)
.collect(); .collect();
@@ -110,8 +110,8 @@ impl BeefyKeystore {
} }
} }
impl From<Option<SyncCryptoStorePtr>> for BeefyKeystore { impl From<Option<KeystorePtr>> for BeefyKeystore {
fn from(store: Option<SyncCryptoStorePtr>) -> BeefyKeystore { fn from(store: Option<KeystorePtr>) -> BeefyKeystore {
BeefyKeystore(store) BeefyKeystore(store)
} }
} }
@@ -128,7 +128,7 @@ pub mod tests {
use super::*; use super::*;
use crate::error::Error; use crate::error::Error;
fn keystore() -> SyncCryptoStorePtr { fn keystore() -> KeystorePtr {
Arc::new(LocalKeystore::in_memory()) Arc::new(LocalKeystore::in_memory())
} }
@@ -198,7 +198,7 @@ pub mod tests {
let store = keystore(); let store = keystore();
let alice: crypto::Public = 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() .ok()
.unwrap() .unwrap()
.into(); .into();
@@ -224,7 +224,7 @@ pub mod tests {
let store = keystore(); let store = keystore();
let alice: crypto::Public = 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() .ok()
.unwrap() .unwrap()
.into(); .into();
@@ -243,10 +243,9 @@ pub mod tests {
fn sign_error() { fn sign_error() {
let store = keystore(); let store = keystore();
let _ = let _ = Keystore::ecdsa_generate_new(&*store, KEY_TYPE, Some(&Keyring::Bob.to_seed()))
SyncCryptoStore::ecdsa_generate_new(&*store, KEY_TYPE, Some(&Keyring::Bob.to_seed())) .ok()
.ok() .unwrap();
.unwrap();
let store: BeefyKeystore = Some(store).into(); let store: BeefyKeystore = Some(store).into();
@@ -276,7 +275,7 @@ pub mod tests {
let store = keystore(); let store = keystore();
let alice: crypto::Public = 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() .ok()
.unwrap() .unwrap()
.into(); .into();
@@ -302,7 +301,7 @@ pub mod tests {
let store = keystore(); let store = keystore();
let add_key = |key_type, seed: Option<&str>| { 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 // test keys
+2 -2
View File
@@ -49,7 +49,7 @@ use sp_consensus_beefy::{
crypto::AuthorityId, BeefyApi, MmrRootHash, PayloadProvider, ValidatorSet, BEEFY_ENGINE_ID, crypto::AuthorityId, BeefyApi, MmrRootHash, PayloadProvider, ValidatorSet, BEEFY_ENGINE_ID,
GENESIS_AUTHORITY_SET_ID, GENESIS_AUTHORITY_SET_ID,
}; };
use sp_keystore::SyncCryptoStorePtr; use sp_keystore::KeystorePtr;
use sp_mmr_primitives::MmrApi; use sp_mmr_primitives::MmrApi;
use sp_runtime::traits::{Block, Zero}; use sp_runtime::traits::{Block, Zero};
use std::{collections::VecDeque, marker::PhantomData, sync::Arc}; 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 /// Runtime Api Provider
pub runtime: Arc<R>, pub runtime: Arc<R>,
/// Local key store /// Local key store
pub key_store: Option<SyncCryptoStorePtr>, pub key_store: Option<KeystorePtr>,
/// BEEFY voter network params /// BEEFY voter network params
pub network_params: BeefyNetworkParams<B, N, S>, pub network_params: BeefyNetworkParams<B, N, S>,
/// Minimal delta between blocks, BEEFY should vote for /// Minimal delta between blocks, BEEFY should vote for
@@ -54,7 +54,7 @@ use sp_consensus_beefy::{
VersionedFinalityProof, BEEFY_ENGINE_ID, KEY_TYPE as BeefyKeyType, VersionedFinalityProof, BEEFY_ENGINE_ID, KEY_TYPE as BeefyKeyType,
}; };
use sp_core::H256; 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_mmr_primitives::{Error as MmrError, MmrApi};
use sp_runtime::{ use sp_runtime::{
codec::Encode, codec::Encode,
@@ -339,9 +339,9 @@ pub(crate) fn make_beefy_ids(keys: &[BeefyKeyring]) -> Vec<AuthorityId> {
keys.iter().map(|&key| key.public().into()).collect() keys.iter().map(|&key| key.public().into()).collect()
} }
pub(crate) fn create_beefy_keystore(authority: BeefyKeyring) -> SyncCryptoStorePtr { pub(crate) fn create_beefy_keystore(authority: BeefyKeyring) -> KeystorePtr {
let keystore = Arc::new(TestKeystore::new()); let keystore = Arc::new(MemoryKeystore::new());
SyncCryptoStore::ecdsa_generate_new(&*keystore, BeefyKeyType, Some(&authority.to_seed())) Keystore::ecdsa_generate_new(&*keystore, BeefyKeyType, Some(&authority.to_seed()))
.expect("Creates authority key"); .expect("Creates authority key");
keystore keystore
} }
@@ -49,7 +49,7 @@ use parity_scale_codec::{Decode, Encode};
use sc_network::{NetworkBlock, NetworkSyncForkRequest, ReputationChange}; use sc_network::{NetworkBlock, NetworkSyncForkRequest, ReputationChange};
use sc_network_gossip::{GossipEngine, Network as GossipNetwork}; use sc_network_gossip::{GossipEngine, Network as GossipNetwork};
use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_DEBUG, CONSENSUS_INFO}; 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 sp_runtime::traits::{Block as BlockT, Hash as HashT, Header as HeaderT, NumberFor};
use crate::{ use crate::{
@@ -136,7 +136,7 @@ mod benefit {
/// A type that ties together our local authority id and a keystore where it is /// A type that ties together our local authority id and a keystore where it is
/// available for signing. /// available for signing.
pub struct LocalIdKeystore((AuthorityId, SyncCryptoStorePtr)); pub struct LocalIdKeystore((AuthorityId, KeystorePtr));
impl LocalIdKeystore { impl LocalIdKeystore {
/// Returns a reference to our local authority id. /// Returns a reference to our local authority id.
@@ -145,13 +145,13 @@ impl LocalIdKeystore {
} }
/// Returns a reference to the keystore. /// Returns a reference to the keystore.
fn keystore(&self) -> SyncCryptoStorePtr { fn keystore(&self) -> KeystorePtr {
(self.0).1.clone() (self.0).1.clone()
} }
} }
impl From<(AuthorityId, SyncCryptoStorePtr)> for LocalIdKeystore { impl From<(AuthorityId, KeystorePtr)> for LocalIdKeystore {
fn from(inner: (AuthorityId, SyncCryptoStorePtr)) -> LocalIdKeystore { fn from(inner: (AuthorityId, KeystorePtr)) -> LocalIdKeystore {
LocalIdKeystore(inner) LocalIdKeystore(inner)
} }
} }
@@ -79,7 +79,7 @@ use sp_consensus_grandpa::{
AuthorityList, AuthoritySignature, SetId, CLIENT_LOG_TARGET as LOG_TARGET, AuthorityList, AuthoritySignature, SetId, CLIENT_LOG_TARGET as LOG_TARGET,
}; };
use sp_core::{crypto::ByteArray, traits::CallContext}; use sp_core::{crypto::ByteArray, traits::CallContext};
use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; use sp_keystore::{Keystore, KeystorePtr};
use sp_runtime::{ use sp_runtime::{
generic::BlockId, generic::BlockId,
traits::{Block as BlockT, NumberFor, Zero}, traits::{Block as BlockT, NumberFor, Zero},
@@ -228,7 +228,7 @@ pub struct Config {
/// Some local identifier of the voter. /// Some local identifier of the voter.
pub name: Option<String>, pub name: Option<String>,
/// The keystore that manages the keys of this node. /// The keystore that manages the keys of this node.
pub keystore: Option<SyncCryptoStorePtr>, pub keystore: Option<KeystorePtr>,
/// TelemetryHandle instance. /// TelemetryHandle instance.
pub telemetry: Option<TelemetryHandle>, pub telemetry: Option<TelemetryHandle>,
/// Chain specific GRANDPA protocol name. See [`crate::protocol_standard_name`]. /// 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>>, voters: &Arc<VoterSet<AuthorityId>>,
client: Arc<C>, client: Arc<C>,
network: &NetworkBridge<Block, N, S>, network: &NetworkBridge<Block, N, S>,
keystore: Option<&SyncCryptoStorePtr>, keystore: Option<&KeystorePtr>,
metrics: Option<until_imported::Metrics>, metrics: Option<until_imported::Metrics>,
) -> ( ) -> (
impl Stream< impl Stream<
@@ -1136,14 +1136,12 @@ where
/// available. /// available.
fn local_authority_id( fn local_authority_id(
voters: &VoterSet<AuthorityId>, voters: &VoterSet<AuthorityId>,
keystore: Option<&SyncCryptoStorePtr>, keystore: Option<&KeystorePtr>,
) -> Option<AuthorityId> { ) -> Option<AuthorityId> {
keystore.and_then(|keystore| { keystore.and_then(|keystore| {
voters voters
.iter() .iter()
.find(|(p, _)| { .find(|(p, _)| Keystore::has_keys(&**keystore, &[(p.to_raw_vec(), AuthorityId::ID)]))
SyncCryptoStore::has_keys(&**keystore, &[(p.to_raw_vec(), AuthorityId::ID)])
})
.map(|(p, _)| p.clone()) .map(|(p, _)| p.clone())
}) })
} }
@@ -33,7 +33,7 @@ use sc_utils::mpsc::TracingUnboundedReceiver;
use sp_blockchain::HeaderMetadata; use sp_blockchain::HeaderMetadata;
use sp_consensus::SelectChain; use sp_consensus::SelectChain;
use sp_consensus_grandpa::AuthorityId; use sp_consensus_grandpa::AuthorityId;
use sp_keystore::SyncCryptoStorePtr; use sp_keystore::KeystorePtr;
use sp_runtime::traits::{Block as BlockT, NumberFor}; use sp_runtime::traits::{Block as BlockT, NumberFor};
use crate::{ use crate::{
@@ -220,7 +220,7 @@ struct ObserverWork<B: BlockT, BE, Client, N: NetworkT<B>, S: SyncingT<B>> {
client: Arc<Client>, client: Arc<Client>,
network: NetworkBridge<B, N, S>, network: NetworkBridge<B, N, S>,
persistent_data: PersistentData<B>, persistent_data: PersistentData<B>,
keystore: Option<SyncCryptoStorePtr>, keystore: Option<KeystorePtr>,
voter_commands_rx: TracingUnboundedReceiver<VoterCommand<B::Hash, NumberFor<B>>>, voter_commands_rx: TracingUnboundedReceiver<VoterCommand<B::Hash, NumberFor<B>>>,
justification_sender: Option<GrandpaJustificationSender<B>>, justification_sender: Option<GrandpaJustificationSender<B>>,
telemetry: Option<TelemetryHandle>, telemetry: Option<TelemetryHandle>,
@@ -240,7 +240,7 @@ where
client: Arc<Client>, client: Arc<Client>,
network: NetworkBridge<B, Network, Syncing>, network: NetworkBridge<B, Network, Syncing>,
persistent_data: PersistentData<B>, persistent_data: PersistentData<B>,
keystore: Option<SyncCryptoStorePtr>, keystore: Option<KeystorePtr>,
voter_commands_rx: TracingUnboundedReceiver<VoterCommand<B::Hash, NumberFor<B>>>, voter_commands_rx: TracingUnboundedReceiver<VoterCommand<B::Hash, NumberFor<B>>>,
justification_sender: Option<GrandpaJustificationSender<B>>, justification_sender: Option<GrandpaJustificationSender<B>>,
telemetry: Option<TelemetryHandle>, telemetry: Option<TelemetryHandle>,
@@ -40,7 +40,7 @@ use sp_consensus_grandpa::{
}; };
use sp_core::H256; use sp_core::H256;
use sp_keyring::Ed25519Keyring; use sp_keyring::Ed25519Keyring;
use sp_keystore::{testing::KeyStore as TestKeyStore, SyncCryptoStore, SyncCryptoStorePtr}; use sp_keystore::{testing::MemoryKeystore, Keystore, KeystorePtr};
use sp_runtime::{ use sp_runtime::{
codec::Encode, codec::Encode,
generic::{BlockId, DigestItem}, 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() keys.iter().map(|&key| key.public().into()).map(|id| (id, 1)).collect()
} }
fn create_keystore(authority: Ed25519Keyring) -> SyncCryptoStorePtr { fn create_keystore(authority: Ed25519Keyring) -> KeystorePtr {
let keystore = Arc::new(TestKeyStore::new()); let keystore = Arc::new(MemoryKeystore::new());
SyncCryptoStore::ed25519_generate_new(&*keystore, GRANDPA, Some(&authority.to_seed())) Keystore::ed25519_generate_new(&*keystore, GRANDPA, Some(&authority.to_seed()))
.expect("Creates authority key"); .expect("Creates authority key");
keystore keystore
} }
@@ -1376,7 +1376,7 @@ type TestEnvironment<N, S, SC, VR> =
fn test_environment_with_select_chain<N, S, VR, SC>( fn test_environment_with_select_chain<N, S, VR, SC>(
link: &TestLinkHalf, link: &TestLinkHalf,
keystore: Option<SyncCryptoStorePtr>, keystore: Option<KeystorePtr>,
network_service: N, network_service: N,
sync_service: S, sync_service: S,
select_chain: SC, select_chain: SC,
@@ -1428,7 +1428,7 @@ where
fn test_environment<N, S, VR>( fn test_environment<N, S, VR>(
link: &TestLinkHalf, link: &TestLinkHalf,
keystore: Option<SyncCryptoStorePtr>, keystore: Option<KeystorePtr>,
network_service: N, network_service: N,
sync_service: S, sync_service: S,
voting_rule: VR, voting_rule: VR,
@@ -29,7 +29,7 @@ use sc_consensus_babe::{
use sc_consensus_epochs::{ use sc_consensus_epochs::{
descendent_query, EpochHeader, SharedEpochChanges, ViableEpochDescriptor, descendent_query, EpochHeader, SharedEpochChanges, ViableEpochDescriptor,
}; };
use sp_keystore::SyncCryptoStorePtr; use sp_keystore::KeystorePtr;
use std::{marker::PhantomData, sync::Arc}; use std::{marker::PhantomData, sync::Arc};
use sc_consensus::{BlockImportParams, ForkChoiceStrategy, Verifier}; use sc_consensus::{BlockImportParams, ForkChoiceStrategy, Verifier};
@@ -53,7 +53,7 @@ use sp_timestamp::TimestampInherentData;
/// Intended for use with BABE runtimes. /// Intended for use with BABE runtimes.
pub struct BabeConsensusDataProvider<B: BlockT, C, P> { pub struct BabeConsensusDataProvider<B: BlockT, C, P> {
/// shared reference to keystore /// shared reference to keystore
keystore: SyncCryptoStorePtr, keystore: KeystorePtr,
/// Shared reference to the client. /// Shared reference to the client.
client: Arc<C>, client: Arc<C>,
@@ -143,7 +143,7 @@ where
{ {
pub fn new( pub fn new(
client: Arc<C>, client: Arc<C>,
keystore: SyncCryptoStorePtr, keystore: KeystorePtr,
epoch_changes: SharedEpochChanges<B, Epoch>, epoch_changes: SharedEpochChanges<B, Epoch>,
authorities: Vec<(AuthorityId, BabeAuthorityWeight)>, authorities: Vec<(AuthorityId, BabeAuthorityWeight)>,
) -> Result<Self, Error> { ) -> Result<Self, Error> {
+21 -137
View File
@@ -17,7 +17,6 @@
// //
//! Local keystore implementation //! Local keystore implementation
use async_trait::async_trait;
use parking_lot::RwLock; use parking_lot::RwLock;
use sp_application_crypto::{ecdsa, ed25519, sr25519, AppKey, AppPair, IsWrappedBy}; use sp_application_crypto::{ecdsa, ed25519, sr25519, AppKey, AppPair, IsWrappedBy};
use sp_core::{ use sp_core::{
@@ -29,10 +28,10 @@ use sp_core::{
}; };
use sp_keystore::{ use sp_keystore::{
vrf::{make_transcript, VRFSignature, VRFTranscriptData}, vrf::{make_transcript, VRFSignature, VRFTranscriptData},
CryptoStore, Error as TraitError, SyncCryptoStore, SyncCryptoStorePtr, Error as TraitError, Keystore, KeystorePtr,
}; };
use std::{ use std::{
collections::{HashMap, HashSet}, collections::HashMap,
fs::{self, File}, fs::{self, File},
io::Write, io::Write,
path::PathBuf, path::PathBuf,
@@ -69,101 +68,7 @@ impl LocalKeystore {
} }
} }
#[async_trait] impl Keystore for LocalKeystore {
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 {
fn keys(&self, id: KeyTypeId) -> std::result::Result<Vec<CryptoTypePublicPair>, TraitError> { fn keys(&self, id: KeyTypeId) -> std::result::Result<Vec<CryptoTypePublicPair>, TraitError> {
let raw_keys = self.0.read().raw_public_keys(id)?; let raw_keys = self.0.read().raw_public_keys(id)?;
Ok(raw_keys.into_iter().fold(Vec::new(), |mut v, k| { 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( fn sign_with(
&self, &self,
id: KeyTypeId, id: KeyTypeId,
@@ -308,13 +204,13 @@ impl SyncCryptoStore for LocalKeystore {
Ok(pair.public()) Ok(pair.public())
} }
fn insert_unknown( fn insert(
&self, &self,
key_type: KeyTypeId, key_type: KeyTypeId,
suri: &str, suri: &str,
public: &[u8], public: &[u8],
) -> std::result::Result<(), ()> { ) -> 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 { fn has_keys(&self, public_keys: &[(Vec<u8>, KeyTypeId)]) -> bool {
@@ -352,14 +248,8 @@ impl SyncCryptoStore for LocalKeystore {
} }
} }
impl Into<SyncCryptoStorePtr> for LocalKeystore { impl Into<KeystorePtr> for LocalKeystore {
fn into(self) -> SyncCryptoStorePtr { fn into(self) -> KeystorePtr {
Arc::new(self)
}
}
impl Into<Arc<dyn CryptoStore>> for LocalKeystore {
fn into(self) -> Arc<dyn CryptoStore> {
Arc::new(self) Arc::new(self)
} }
} }
@@ -414,7 +304,7 @@ impl KeystoreInner {
/// Insert a new key with anonymous crypto. /// Insert a new key with anonymous crypto.
/// ///
/// Places it into the file system store, if a path is configured. /// 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) { if let Some(path) = self.key_file_path(public, key_type) {
Self::write_to_file(path, suri)?; Self::write_to_file(path, suri)?;
} }
@@ -614,12 +504,9 @@ mod tests {
let key: ed25519::AppPair = store.0.write().generate().unwrap(); let key: ed25519::AppPair = store.0.write().generate().unwrap();
let key2 = ed25519::Pair::generate().0; let key2 = ed25519::Pair::generate().0;
assert!(!SyncCryptoStore::has_keys( assert!(!Keystore::has_keys(&store, &[(key2.public().to_vec(), ed25519::AppPublic::ID)]));
&store,
&[(key2.public().to_vec(), ed25519::AppPublic::ID)]
));
assert!(!SyncCryptoStore::has_keys( assert!(!Keystore::has_keys(
&store, &store,
&[ &[
(key2.public().to_vec(), ed25519::AppPublic::ID), (key2.public().to_vec(), ed25519::AppPublic::ID),
@@ -627,10 +514,7 @@ mod tests {
], ],
)); ));
assert!(SyncCryptoStore::has_keys( assert!(Keystore::has_keys(&store, &[(key.public().to_raw_vec(), ed25519::AppPublic::ID)]));
&store,
&[(key.public().to_raw_vec(), ed25519::AppPublic::ID)]
));
} }
#[test] #[test]
@@ -723,7 +607,7 @@ mod tests {
let key_pair = sr25519::AppPair::from_string(secret_uri, None).expect("Generates key pair"); let key_pair = sr25519::AppPair::from_string(secret_uri, None).expect("Generates key pair");
store store
.insert_unknown(SR25519, secret_uri, key_pair.public().as_ref()) .insert(SR25519, secret_uri, key_pair.public().as_ref())
.expect("Inserts unknown key"); .expect("Inserts unknown key");
let store_key_pair = store let store_key_pair = store
@@ -742,7 +626,7 @@ mod tests {
let file_name = temp_dir.path().join(array_bytes::bytes2hex("", &SR25519.0[..2])); let file_name = temp_dir.path().join(array_bytes::bytes2hex("", &SR25519.0[..2]));
fs::write(file_name, "test").expect("Invalid file is written"); 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] #[test]
@@ -750,23 +634,23 @@ mod tests {
let temp_dir = TempDir::new().unwrap(); let temp_dir = TempDir::new().unwrap();
let store = LocalKeystore::open(temp_dir.path(), None).unwrap(); let store = LocalKeystore::open(temp_dir.path(), None).unwrap();
let _alice_tmp_key = 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); drop(store);
let store = LocalKeystore::open(temp_dir.path(), None).unwrap(); 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] #[test]
fn generate_can_be_fetched_in_memory() { fn generate_can_be_fetched_in_memory() {
let store = LocalKeystore::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); assert_eq!(Keystore::sr25519_public_keys(&store, TEST_KEY_TYPE).len(), 1);
SyncCryptoStore::sr25519_generate_new(&store, TEST_KEY_TYPE, None).unwrap(); Keystore::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(), 2);
} }
#[test] #[test]
@@ -777,7 +661,7 @@ mod tests {
let temp_dir = TempDir::new().unwrap(); let temp_dir = TempDir::new().unwrap();
let store = LocalKeystore::open(temp_dir.path(), None).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 path = store.0.read().key_file_path(public.as_ref(), TEST_KEY_TYPE).unwrap();
let permissions = File::open(path).unwrap().metadata().unwrap().permissions(); let permissions = File::open(path).unwrap().metadata().unwrap().permissions();
+1 -1
View File
@@ -47,7 +47,7 @@ pub enum Error {
BadKeyType, BadKeyType,
/// Some random issue with the key store. Shouldn't happen. /// Some random issue with the key store. Shouldn't happen.
#[error("The key store is unavailable")] #[error("The key store is unavailable")]
KeyStoreUnavailable, KeystoreUnavailable,
/// Invalid session keys encoding. /// Invalid session keys encoding.
#[error("Session keys are not encoded correctly")] #[error("Session keys are not encoded correctly")]
InvalidSessionKeys, InvalidSessionKeys,
+7 -7
View File
@@ -40,7 +40,7 @@ use sc_transaction_pool_api::{
use sp_api::ProvideRuntimeApi; use sp_api::ProvideRuntimeApi;
use sp_blockchain::HeaderBackend; use sp_blockchain::HeaderBackend;
use sp_core::Bytes; use sp_core::Bytes;
use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; use sp_keystore::{Keystore, KeystorePtr};
use sp_runtime::{generic, traits::Block as BlockT}; use sp_runtime::{generic, traits::Block as BlockT};
use sp_session::SessionKeys; use sp_session::SessionKeys;
@@ -55,7 +55,7 @@ pub struct Author<P, Client> {
/// Transactions pool /// Transactions pool
pool: Arc<P>, pool: Arc<P>,
/// The key store. /// The key store.
keystore: SyncCryptoStorePtr, keystore: KeystorePtr,
/// Whether to deny unsafe calls /// Whether to deny unsafe calls
deny_unsafe: DenyUnsafe, deny_unsafe: DenyUnsafe,
/// Executor to spawn subscriptions. /// Executor to spawn subscriptions.
@@ -67,7 +67,7 @@ impl<P, Client> Author<P, Client> {
pub fn new( pub fn new(
client: Arc<Client>, client: Arc<Client>,
pool: Arc<P>, pool: Arc<P>,
keystore: SyncCryptoStorePtr, keystore: KeystorePtr,
deny_unsafe: DenyUnsafe, deny_unsafe: DenyUnsafe,
executor: SubscriptionTaskExecutor, executor: SubscriptionTaskExecutor,
) -> Self { ) -> Self {
@@ -112,8 +112,8 @@ where
self.deny_unsafe.check_if_safe()?; self.deny_unsafe.check_if_safe()?;
let key_type = key_type.as_str().try_into().map_err(|_| Error::BadKeyType)?; let key_type = key_type.as_str().try_into().map_err(|_| Error::BadKeyType)?;
SyncCryptoStore::insert_unknown(&*self.keystore, key_type, &suri, &public[..]) Keystore::insert(&*self.keystore, key_type, &suri, &public[..])
.map_err(|_| Error::KeyStoreUnavailable)?; .map_err(|_| Error::KeystoreUnavailable)?;
Ok(()) Ok(())
} }
@@ -139,14 +139,14 @@ where
.map_err(|e| Error::Client(Box::new(e)))? .map_err(|e| Error::Client(Box::new(e)))?
.ok_or(Error::InvalidSessionKeys)?; .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> { fn has_key(&self, public_key: Bytes, key_type: String) -> RpcResult<bool> {
self.deny_unsafe.check_if_safe()?; self.deny_unsafe.check_if_safe()?;
let key_type = key_type.as_str().try_into().map_err(|_| Error::BadKeyType)?; 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>> { fn pending_extrinsics(&self) -> RpcResult<Vec<Bytes>> {
+6 -6
View File
@@ -36,7 +36,7 @@ use sp_core::{
testing::{ED25519, SR25519}, testing::{ED25519, SR25519},
H256, H256,
}; };
use sp_keystore::testing::KeyStore; use sp_keystore::testing::MemoryKeystore;
use std::sync::Arc; use std::sync::Arc;
use substrate_test_runtime_client::{ use substrate_test_runtime_client::{
self, self,
@@ -58,13 +58,13 @@ type FullTransactionPool = BasicPool<FullChainApi<Client<Backend>, Block>, Block
struct TestSetup { struct TestSetup {
pub client: Arc<Client<Backend>>, pub client: Arc<Client<Backend>>,
pub keystore: Arc<KeyStore>, pub keystore: Arc<MemoryKeystore>,
pub pool: Arc<FullTransactionPool>, pub pool: Arc<FullTransactionPool>,
} }
impl Default for TestSetup { impl Default for TestSetup {
fn default() -> Self { 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_builder = substrate_test_runtime_client::TestClientBuilder::new();
let client = Arc::new(client_builder.set_keystore(keystore.clone()).build()); 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(), keypair.public().0.to_vec().into(),
); );
api.call::<_, ()>("author_insertKey", params).await.unwrap(); api.call::<_, ()>("author_insertKey", params).await.unwrap();
let pubkeys = SyncCryptoStore::keys(&*setup.keystore, ED25519).unwrap(); let pubkeys = Keystore::keys(&*setup.keystore, ED25519).unwrap();
assert!( assert!(
pubkeys.contains(&CryptoTypePublicPair(ed25519::CRYPTO_ID, keypair.public().to_raw_vec())) 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 new_pubkeys: Bytes = api.call("author_rotateKeys", EmptyParams::new()).await.unwrap();
let session_keys = let session_keys =
SessionKeys::decode(&mut &new_pubkeys[..]).expect("SessionKeys decode successfully"); SessionKeys::decode(&mut &new_pubkeys[..]).expect("SessionKeys decode successfully");
let ed25519_pubkeys = SyncCryptoStore::keys(&*setup.keystore, ED25519).unwrap(); let ed25519_pubkeys = Keystore::keys(&*setup.keystore, ED25519).unwrap();
let sr25519_pubkeys = SyncCryptoStore::keys(&*setup.keystore, SR25519).unwrap(); let sr25519_pubkeys = Keystore::keys(&*setup.keystore, SR25519).unwrap();
assert!(ed25519_pubkeys assert!(ed25519_pubkeys
.contains(&CryptoTypePublicPair(ed25519::CRYPTO_ID, session_keys.ed25519.to_raw_vec()))); .contains(&CryptoTypePublicPair(ed25519::CRYPTO_ID, session_keys.ed25519.to_raw_vec())));
assert!(sr25519_pubkeys assert!(sr25519_pubkeys
+13 -26
View File
@@ -67,7 +67,7 @@ use sp_consensus::block_validation::{
BlockAnnounceValidator, Chain, DefaultBlockAnnounceValidator, BlockAnnounceValidator, Chain, DefaultBlockAnnounceValidator,
}; };
use sp_core::traits::{CodeExecutor, SpawnNamed}; 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 sp_runtime::traits::{Block as BlockT, BlockIdTo, NumberFor, Zero};
use std::{str::FromStr, sync::Arc, time::SystemTime}; use std::{str::FromStr, sync::Arc, time::SystemTime};
@@ -85,26 +85,22 @@ pub type TFullCallExecutor<TBl, TExec> =
type TFullParts<TBl, TRtApi, TExec> = type TFullParts<TBl, TRtApi, TExec> =
(TFullClient<TBl, TRtApi, TExec>, Arc<TFullBackend<TBl>>, KeystoreContainer, TaskManager); (TFullClient<TBl, TRtApi, TExec>, Arc<TFullBackend<TBl>>, KeystoreContainer, TaskManager);
trait AsCryptoStoreRef { trait AsKeystoreRef {
fn keystore_ref(&self) -> Arc<dyn CryptoStore>; fn keystore_ref(&self) -> Arc<dyn Keystore>;
fn sync_keystore_ref(&self) -> Arc<dyn SyncCryptoStore>;
} }
impl<T> AsCryptoStoreRef for Arc<T> impl<T> AsKeystoreRef for Arc<T>
where where
T: CryptoStore + SyncCryptoStore + 'static, T: Keystore + 'static,
{ {
fn keystore_ref(&self) -> Arc<dyn CryptoStore> { fn keystore_ref(&self) -> Arc<dyn Keystore> {
self.clone()
}
fn sync_keystore_ref(&self) -> Arc<dyn SyncCryptoStore> {
self.clone() self.clone()
} }
} }
/// Construct and hold different layers of Keystore wrappers /// Construct and hold different layers of Keystore wrappers
pub struct KeystoreContainer { pub struct KeystoreContainer {
remote: Option<Box<dyn AsCryptoStoreRef>>, remote: Option<Box<dyn AsKeystoreRef>>,
local: Arc<LocalKeystore>, local: Arc<LocalKeystore>,
} }
@@ -127,13 +123,13 @@ impl KeystoreContainer {
/// stick around. /// stick around.
pub fn set_remote_keystore<T>(&mut self, remote: Arc<T>) pub fn set_remote_keystore<T>(&mut self, remote: Arc<T>)
where where
T: CryptoStore + SyncCryptoStore + 'static, T: Keystore + 'static,
{ {
self.remote = Some(Box::new(remote)) self.remote = Some(Box::new(remote))
} }
/// Returns an adapter to the asynchronous keystore that implements `CryptoStore` /// Returns an adapter to a `Keystore` implementation.
pub fn keystore(&self) -> Arc<dyn CryptoStore> { pub fn keystore(&self) -> Arc<dyn Keystore> {
if let Some(c) = self.remote.as_ref() { if let Some(c) = self.remote.as_ref() {
c.keystore_ref() c.keystore_ref()
} else { } 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 /// Returns the local keystore if available
/// ///
/// The function will return None if the available keystore is not a local keystore. /// The function will return None if the available keystore is not a local keystore.
@@ -234,7 +221,7 @@ where
let client = { let client = {
let extensions = sc_client_api::execution_extensions::ExecutionExtensions::new( let extensions = sc_client_api::execution_extensions::ExecutionExtensions::new(
config.execution_strategies.clone(), config.execution_strategies.clone(),
Some(keystore_container.sync_keystore()), Some(keystore_container.keystore()),
sc_offchain::OffchainDb::factory_from_backend(&*backend), 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`. /// A task manager returned by `new_full_parts`.
pub task_manager: &'a mut TaskManager, pub task_manager: &'a mut TaskManager,
/// A shared keystore returned by `new_full_parts`. /// A shared keystore returned by `new_full_parts`.
pub keystore: SyncCryptoStorePtr, pub keystore: KeystorePtr,
/// A shared transaction pool. /// A shared transaction pool.
pub transaction_pool: Arc<TExPool>, pub transaction_pool: Arc<TExPool>,
/// Builds additional [`RpcModule`]s that should be added to the server /// 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, spawn_handle: SpawnTaskHandle,
client: Arc<TCl>, client: Arc<TCl>,
transaction_pool: Arc<TExPool>, transaction_pool: Arc<TExPool>,
keystore: SyncCryptoStorePtr, keystore: KeystorePtr,
system_rpc_tx: TracingUnboundedSender<sc_rpc::system::Request<TBl>>, system_rpc_tx: TracingUnboundedSender<sc_rpc::system::Request<TBl>>,
config: &Configuration, config: &Configuration,
backend: Arc<TBackend>, backend: Arc<TBackend>,
@@ -65,7 +65,7 @@ use sp_core::{
traits::SpawnNamed, traits::SpawnNamed,
}; };
#[cfg(feature = "test-helpers")] #[cfg(feature = "test-helpers")]
use sp_keystore::SyncCryptoStorePtr; use sp_keystore::KeystorePtr;
use sp_runtime::{ use sp_runtime::{
generic::{BlockId, SignedBlock}, generic::{BlockId, SignedBlock},
traits::{ traits::{
@@ -161,7 +161,7 @@ pub fn new_in_mem<E, Block, G, RA>(
backend: Arc<in_mem::Backend<Block>>, backend: Arc<in_mem::Backend<Block>>,
executor: E, executor: E,
genesis_block_builder: G, genesis_block_builder: G,
keystore: Option<SyncCryptoStorePtr>, keystore: Option<KeystorePtr>,
prometheus_registry: Option<Registry>, prometheus_registry: Option<Registry>,
telemetry: Option<TelemetryHandle>, telemetry: Option<TelemetryHandle>,
spawn_handle: Box<dyn SpawnNamed>, spawn_handle: Box<dyn SpawnNamed>,
@@ -224,7 +224,7 @@ pub fn new_with_backend<B, E, Block, G, RA>(
backend: Arc<B>, backend: Arc<B>,
executor: E, executor: E,
genesis_block_builder: G, genesis_block_builder: G,
keystore: Option<SyncCryptoStorePtr>, keystore: Option<KeystorePtr>,
spawn_handle: Box<dyn SpawnNamed>, spawn_handle: Box<dyn SpawnNamed>,
prometheus_registry: Option<Registry>, prometheus_registry: Option<Registry>,
telemetry: Option<TelemetryHandle>, telemetry: Option<TelemetryHandle>,
+2 -2
View File
@@ -160,12 +160,12 @@ pub mod mock {
impl super::Config for Test {} impl super::Config for Test {}
pub fn new_test_ext() -> sp_io::TestExternalities { 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; use sp_std::sync::Arc;
let t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap(); let t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
let mut ext = sp_io::TestExternalities::new(t); 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 ext
} }
+2 -2
View File
@@ -44,7 +44,7 @@ use frame_support::{
use frame_system::{self as system, EventRecord, Phase}; use frame_system::{self as system, EventRecord, Phase};
use pretty_assertions::{assert_eq, assert_ne}; use pretty_assertions::{assert_eq, assert_ne};
use sp_io::hashing::blake2_256; use sp_io::hashing::blake2_256;
use sp_keystore::{testing::KeyStore, KeystoreExt}; use sp_keystore::{testing::MemoryKeystore, KeystoreExt};
use sp_runtime::{ use sp_runtime::{
testing::{Header, H256}, testing::{Header, H256},
traits::{BlakeTwo256, Convert, Hash, IdentityLookup}, traits::{BlakeTwo256, Convert, Hash, IdentityLookup},
@@ -440,7 +440,7 @@ impl ExtBuilder {
.assimilate_storage(&mut t) .assimilate_storage(&mut t)
.unwrap(); .unwrap();
let mut ext = sp_io::TestExternalities::new(t); 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.execute_with(|| System::set_block_number(1));
ext ext
} }
@@ -29,7 +29,7 @@ use sp_core::{
}; };
use std::sync::Arc; use std::sync::Arc;
use sp_keystore::{testing::KeyStore, KeystoreExt, SyncCryptoStore}; use sp_keystore::{testing::MemoryKeystore, Keystore, KeystoreExt};
use sp_runtime::{ use sp_runtime::{
testing::{Header, TestXt}, testing::{Header, TestXt},
traits::{BlakeTwo256, Extrinsic as ExtrinsicT, IdentifyAccount, IdentityLookup, Verify}, 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 (offchain, offchain_state) = testing::TestOffchainExt::new();
let (pool, pool_state) = testing::TestTransactionPoolExt::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, &keystore,
crate::crypto::Public::ID, crate::crypto::Public::ID,
Some(&format!("{}/hunter1", PHRASE)), 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 (offchain, offchain_state) = testing::TestOffchainExt::new();
let (pool, pool_state) = testing::TestTransactionPoolExt::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, &keystore,
crate::crypto::Public::ID, crate::crypto::Public::ID,
Some(&format!("{}/hunter1", PHRASE)), Some(&format!("{}/hunter1", PHRASE)),
) )
.unwrap(); .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) .get(0)
.unwrap(); .unwrap();
@@ -298,16 +298,16 @@ fn should_submit_unsigned_transaction_on_chain_for_all_accounts() {
let (offchain, offchain_state) = testing::TestOffchainExt::new(); let (offchain, offchain_state) = testing::TestOffchainExt::new();
let (pool, pool_state) = testing::TestTransactionPoolExt::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, &keystore,
crate::crypto::Public::ID, crate::crypto::Public::ID,
Some(&format!("{}/hunter1", PHRASE)), Some(&format!("{}/hunter1", PHRASE)),
) )
.unwrap(); .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) .get(0)
.unwrap(); .unwrap();
@@ -355,7 +355,7 @@ fn should_submit_raw_unsigned_transaction_on_chain() {
let (offchain, offchain_state) = testing::TestOffchainExt::new(); let (offchain, offchain_state) = testing::TestOffchainExt::new();
let (pool, pool_state) = testing::TestTransactionPoolExt::new(); let (pool, pool_state) = testing::TestTransactionPoolExt::new();
let keystore = KeyStore::new(); let keystore = MemoryKeystore::new();
let mut t = sp_io::TestExternalities::default(); let mut t = sp_io::TestExternalities::default();
t.register_extension(OffchainWorkerExt::new(offchain)); t.register_extension(OffchainWorkerExt::new(offchain));
+2 -2
View File
@@ -25,7 +25,7 @@ use frame_support::{
traits::{AsEnsureOriginWithArg, ConstU32, ConstU64}, traits::{AsEnsureOriginWithArg, ConstU32, ConstU64},
}; };
use sp_core::H256; use sp_core::H256;
use sp_keystore::{testing::KeyStore, KeystoreExt}; use sp_keystore::{testing::MemoryKeystore, KeystoreExt};
use sp_runtime::{ use sp_runtime::{
testing::Header, testing::Header,
traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify},
@@ -130,7 +130,7 @@ impl Config for Test {
pub(crate) fn new_test_ext() -> sp_io::TestExternalities { pub(crate) fn new_test_ext() -> sp_io::TestExternalities {
let t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap(); 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); let mut ext = sp_io::TestExternalities::new(t);
ext.register_extension(KeystoreExt(Arc::new(keystore))); ext.register_extension(KeystoreExt(Arc::new(keystore)));
ext.execute_with(|| System::set_block_number(1)); ext.execute_with(|| System::set_block_number(1));
@@ -19,7 +19,7 @@
use sp_api::ProvideRuntimeApi; use sp_api::ProvideRuntimeApi;
use sp_application_crypto::ecdsa::{AppPair, AppPublic}; use sp_application_crypto::ecdsa::{AppPair, AppPublic};
use sp_core::{crypto::Pair, testing::ECDSA}; use sp_core::{crypto::Pair, testing::ECDSA};
use sp_keystore::{testing::KeyStore, SyncCryptoStore}; use sp_keystore::{testing::MemoryKeystore, Keystore};
use std::sync::Arc; use std::sync::Arc;
use substrate_test_runtime_client::{ use substrate_test_runtime_client::{
runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, TestClientBuilderExt, runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, TestClientBuilderExt,
@@ -27,14 +27,14 @@ use substrate_test_runtime_client::{
#[test] #[test]
fn ecdsa_works_in_runtime() { 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 test_client = TestClientBuilder::new().set_keystore(keystore.clone()).build();
let (signature, public) = test_client let (signature, public) = test_client
.runtime_api() .runtime_api()
.test_ecdsa_crypto(test_client.chain_info().genesis_hash) .test_ecdsa_crypto(test_client.chain_info().genesis_hash)
.expect("Tests `ecdsa` crypto."); .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!(supported_keys.contains(&public.clone().into()));
assert!(AppPair::verify(&signature, "ecdsa", &AppPublic::from(public))); assert!(AppPair::verify(&signature, "ecdsa", &AppPublic::from(public)));
} }
@@ -20,7 +20,7 @@
use sp_api::ProvideRuntimeApi; use sp_api::ProvideRuntimeApi;
use sp_application_crypto::ed25519::{AppPair, AppPublic}; use sp_application_crypto::ed25519::{AppPair, AppPublic};
use sp_core::{crypto::Pair, testing::ED25519}; use sp_core::{crypto::Pair, testing::ED25519};
use sp_keystore::{testing::KeyStore, SyncCryptoStore}; use sp_keystore::{testing::MemoryKeystore, Keystore};
use std::sync::Arc; use std::sync::Arc;
use substrate_test_runtime_client::{ use substrate_test_runtime_client::{
runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, TestClientBuilderExt, runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, TestClientBuilderExt,
@@ -28,14 +28,14 @@ use substrate_test_runtime_client::{
#[test] #[test]
fn ed25519_works_in_runtime() { 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 test_client = TestClientBuilder::new().set_keystore(keystore.clone()).build();
let (signature, public) = test_client let (signature, public) = test_client
.runtime_api() .runtime_api()
.test_ed25519_crypto(test_client.chain_info().genesis_hash) .test_ed25519_crypto(test_client.chain_info().genesis_hash)
.expect("Tests `ed25519` crypto."); .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!(supported_keys.contains(&public.clone().into()));
assert!(AppPair::verify(&signature, "ed25519", &AppPublic::from(public))); assert!(AppPair::verify(&signature, "ed25519", &AppPublic::from(public)));
} }
@@ -20,7 +20,7 @@
use sp_api::ProvideRuntimeApi; use sp_api::ProvideRuntimeApi;
use sp_application_crypto::sr25519::{AppPair, AppPublic}; use sp_application_crypto::sr25519::{AppPair, AppPublic};
use sp_core::{crypto::Pair, testing::SR25519}; use sp_core::{crypto::Pair, testing::SR25519};
use sp_keystore::{testing::KeyStore, SyncCryptoStore}; use sp_keystore::{testing::MemoryKeystore, Keystore};
use std::sync::Arc; use std::sync::Arc;
use substrate_test_runtime_client::{ use substrate_test_runtime_client::{
runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, TestClientBuilderExt, runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, TestClientBuilderExt,
@@ -28,14 +28,14 @@ use substrate_test_runtime_client::{
#[test] #[test]
fn sr25519_works_in_runtime() { 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 test_client = TestClientBuilder::new().set_keystore(keystore.clone()).build();
let (signature, public) = test_client let (signature, public) = test_client
.runtime_api() .runtime_api()
.test_sr25519_crypto(test_client.chain_info().genesis_hash) .test_sr25519_crypto(test_client.chain_info().genesis_hash)
.expect("Tests `sr25519` crypto."); .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!(supported_keys.contains(&public.clone().into()));
assert!(AppPair::verify(&signature, "sr25519", &AppPublic::from(public))); assert!(AppPair::verify(&signature, "sr25519", &AppPublic::from(public)));
} }
@@ -253,7 +253,7 @@ mod tests {
use crate::{crypto, known_payloads, KEY_TYPE}; use crate::{crypto, known_payloads, KEY_TYPE};
use codec::Decode; use codec::Decode;
use sp_core::{keccak_256, Pair}; 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 TestCommitment = Commitment<u128>;
type TestSignedCommitment = SignedCommitment<u128, crypto::Signature>; 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 // The mock signatures are equivalent to the ones produced by the BEEFY keystore
fn mock_signatures() -> (crypto::Signature, crypto::Signature) { 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 alice = sp_core::ecdsa::Pair::from_string("//Alice", None).unwrap();
let _ = let _ = Keystore::insert(&*store, KEY_TYPE, "//Alice", alice.public().as_ref()).unwrap();
SyncCryptoStore::insert_unknown(&*store, KEY_TYPE, "//Alice", alice.public().as_ref())
.unwrap();
let msg = keccak_256(b"This is the first message"); 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()
.unwrap(); .unwrap();
let msg = keccak_256(b"This is the second message"); 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()
.unwrap(); .unwrap();
@@ -76,7 +76,7 @@ impl<TBlockNumber, TMerkleRoot> SignedCommitmentWitness<TBlockNumber, TMerkleRoo
mod tests { mod tests {
use sp_core::{keccak_256, Pair}; use sp_core::{keccak_256, Pair};
use sp_keystore::{testing::KeyStore, SyncCryptoStore, SyncCryptoStorePtr}; use sp_keystore::{testing::MemoryKeystore, Keystore, KeystorePtr};
use super::*; use super::*;
use codec::Decode; use codec::Decode;
@@ -90,20 +90,18 @@ mod tests {
// The mock signatures are equivalent to the ones produced by the BEEFY keystore // The mock signatures are equivalent to the ones produced by the BEEFY keystore
fn mock_signatures() -> (crypto::Signature, crypto::Signature) { 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 alice = sp_core::ecdsa::Pair::from_string("//Alice", None).unwrap();
let _ = let _ = Keystore::insert(&*store, KEY_TYPE, "//Alice", alice.public().as_ref()).unwrap();
SyncCryptoStore::insert_unknown(&*store, KEY_TYPE, "//Alice", alice.public().as_ref())
.unwrap();
let msg = keccak_256(b"This is the first message"); 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()
.unwrap(); .unwrap();
let msg = keccak_256(b"This is the second message"); 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()
.unwrap(); .unwrap();
@@ -28,7 +28,7 @@ use serde::Serialize;
use codec::{Codec, Decode, Encode, Input}; use codec::{Codec, Decode, Encode, Input};
use scale_info::TypeInfo; use scale_info::TypeInfo;
#[cfg(feature = "std")] #[cfg(feature = "std")]
use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; use sp_keystore::{Keystore, KeystorePtr};
use sp_runtime::{ use sp_runtime::{
traits::{Header as HeaderT, NumberFor}, traits::{Header as HeaderT, NumberFor},
ConsensusEngineId, RuntimeDebug, ConsensusEngineId, RuntimeDebug,
@@ -444,7 +444,7 @@ where
/// Localizes the message to the given set and round and signs the payload. /// Localizes the message to the given set and round and signs the payload.
#[cfg(feature = "std")] #[cfg(feature = "std")]
pub fn sign_message<H, N>( pub fn sign_message<H, N>(
keystore: SyncCryptoStorePtr, keystore: KeystorePtr,
message: grandpa::Message<H, N>, message: grandpa::Message<H, N>,
public: AuthorityId, public: AuthorityId,
round: RoundNumber, round: RoundNumber,
@@ -458,7 +458,7 @@ where
use sp_core::crypto::Public; use sp_core::crypto::Public;
let encoded = localized_payload(round, set_id, &message); let encoded = localized_payload(round, set_id, &message);
let signature = SyncCryptoStore::sign_with( let signature = Keystore::sign_with(
&*keystore, &*keystore,
AuthorityId::ID, AuthorityId::ID,
&public.to_public_crypto_pair(), &public.to_public_crypto_pair(),
+11 -13
View File
@@ -43,7 +43,7 @@ use sp_core::{
traits::TaskExecutorExt, traits::TaskExecutorExt,
}; };
#[cfg(feature = "std")] #[cfg(feature = "std")]
use sp_keystore::{KeystoreExt, SyncCryptoStore}; use sp_keystore::{Keystore, KeystoreExt};
use sp_core::{ use sp_core::{
crypto::KeyTypeId, crypto::KeyTypeId,
@@ -734,7 +734,7 @@ pub trait Crypto {
let keystore = &***self let keystore = &***self
.extension::<KeystoreExt>() .extension::<KeystoreExt>()
.expect("No `keystore` associated for the current context!"); .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 /// Generate an `ed22519` key for the given key type using an optional `seed` and
@@ -748,8 +748,7 @@ pub trait Crypto {
let keystore = &***self let keystore = &***self
.extension::<KeystoreExt>() .extension::<KeystoreExt>()
.expect("No `keystore` associated for the current context!"); .expect("No `keystore` associated for the current context!");
SyncCryptoStore::ed25519_generate_new(keystore, id, seed) Keystore::ed25519_generate_new(keystore, id, seed).expect("`ed25519_generate` failed")
.expect("`ed25519_generate` failed")
} }
/// Sign the given `msg` with the `ed25519` key that corresponds to the given public key and /// 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 let keystore = &***self
.extension::<KeystoreExt>() .extension::<KeystoreExt>()
.expect("No `keystore` associated for the current context!"); .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() .ok()
.flatten() .flatten()
.and_then(|sig| ed25519::Signature::from_slice(&sig)) .and_then(|sig| ed25519::Signature::from_slice(&sig))
@@ -877,7 +876,7 @@ pub trait Crypto {
let keystore = &***self let keystore = &***self
.extension::<KeystoreExt>() .extension::<KeystoreExt>()
.expect("No `keystore` associated for the current context!"); .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 /// Generate an `sr22519` key for the given key type using an optional seed and
@@ -891,8 +890,7 @@ pub trait Crypto {
let keystore = &***self let keystore = &***self
.extension::<KeystoreExt>() .extension::<KeystoreExt>()
.expect("No `keystore` associated for the current context!"); .expect("No `keystore` associated for the current context!");
SyncCryptoStore::sr25519_generate_new(keystore, id, seed) Keystore::sr25519_generate_new(keystore, id, seed).expect("`sr25519_generate` failed")
.expect("`sr25519_generate` failed")
} }
/// Sign the given `msg` with the `sr25519` key that corresponds to the given public key and /// 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 let keystore = &***self
.extension::<KeystoreExt>() .extension::<KeystoreExt>()
.expect("No `keystore` associated for the current context!"); .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() .ok()
.flatten() .flatten()
.and_then(|sig| sr25519::Signature::from_slice(&sig)) .and_then(|sig| sr25519::Signature::from_slice(&sig))
@@ -927,7 +925,7 @@ pub trait Crypto {
let keystore = &***self let keystore = &***self
.extension::<KeystoreExt>() .extension::<KeystoreExt>()
.expect("No `keystore` associated for the current context!"); .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 /// Generate an `ecdsa` key for the given key type using an optional `seed` and
@@ -941,7 +939,7 @@ pub trait Crypto {
let keystore = &***self let keystore = &***self
.extension::<KeystoreExt>() .extension::<KeystoreExt>()
.expect("No `keystore` associated for the current context!"); .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 /// 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 let keystore = &***self
.extension::<KeystoreExt>() .extension::<KeystoreExt>()
.expect("No `keystore` associated for the current context!"); .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() .ok()
.flatten() .flatten()
.and_then(|sig| ecdsa::Signature::from_slice(&sig)) .and_then(|sig| ecdsa::Signature::from_slice(&sig))
@@ -976,7 +974,7 @@ pub trait Crypto {
let keystore = &***self let keystore = &***self
.extension::<KeystoreExt>() .extension::<KeystoreExt>()
.expect("No `keystore` associated for the current context!"); .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. /// Verify `ecdsa` signature.
-1
View File
@@ -13,7 +13,6 @@ documentation = "https://docs.rs/sp-core"
targets = ["x86_64-unknown-linux-gnu"] targets = ["x86_64-unknown-linux-gnu"]
[dependencies] [dependencies]
async-trait = "0.1.57"
codec = { package = "parity-scale-codec", version = "3.2.2", default-features = false, features = ["derive"] } codec = { package = "parity-scale-codec", version = "3.2.2", default-features = false, features = ["derive"] }
futures = "0.3.21" futures = "0.3.21"
merlin = { version = "2.0", default-features = false } merlin = { version = "2.0", default-features = false }
+8 -242
View File
@@ -20,15 +20,13 @@ pub mod testing;
pub mod vrf; pub mod vrf;
use crate::vrf::{VRFSignature, VRFTranscriptData}; use crate::vrf::{VRFSignature, VRFTranscriptData};
use async_trait::async_trait;
use futures::{executor::block_on, future::join_all};
use sp_core::{ use sp_core::{
crypto::{CryptoTypePublicPair, KeyTypeId}, crypto::{CryptoTypePublicPair, KeyTypeId},
ecdsa, ed25519, sr25519, ecdsa, ed25519, sr25519,
}; };
use std::sync::Arc; use std::sync::Arc;
/// CryptoStore error /// Keystore error
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum Error { pub enum Error {
/// Public key type is not supported /// Public key type is not supported
@@ -45,179 +43,8 @@ pub enum Error {
Other(String), Other(String),
} }
/// Something that generates, stores and provides access to keys. /// Something that generates, stores and provides access to secret keys.
#[async_trait] pub trait Keystore: Send + Sync {
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 {
/// Returns all sr25519 public keys for the given key type. /// Returns all sr25519 public keys for the given key type.
fn sr25519_public_keys(&self, id: KeyTypeId) -> Vec<sr25519::Public>; 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>) fn ecdsa_generate_new(&self, id: KeyTypeId, seed: Option<&str>)
-> Result<ecdsa::Public, Error>; -> Result<ecdsa::Public, Error>;
/// Insert a new key. This doesn't require any known of the crypto; but a public key must be /// Insert a new secret key.
/// manually provided. fn insert(&self, key_type: KeyTypeId, suri: &str, public: &[u8]) -> Result<(), ()>;
///
/// 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>;
/// List all supported keys /// List all supported keys
/// ///
/// Returns a set of public keys the signer supports. /// Returns a set of public keys the signer supports.
fn keys(&self, id: KeyTypeId) -> Result<Vec<CryptoTypePublicPair>, Error> { fn keys(&self, id: KeyTypeId) -> Result<Vec<CryptoTypePublicPair>, Error>;
block_on(CryptoStore::keys(self, id))
}
/// Checks if the private keys for the given public key and key type combinations exist. /// 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], msg: &[u8],
) -> Result<Option<Vec<u8>>, Error>; ) -> 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. /// Generate VRF signature for given transcript data.
/// ///
/// Receives KeyTypeId and Public key to be able to map /// 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. /// A pointer to a keystore.
pub type SyncCryptoStorePtr = Arc<dyn SyncCryptoStore>; pub type KeystorePtr = Arc<dyn Keystore>;
sp_externalities::decl_extension! { sp_externalities::decl_extension! {
/// The keystore extension to register/retrieve from the externalities. /// 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::{ use crate::{
vrf::{make_transcript, VRFSignature, VRFTranscriptData}, vrf::{make_transcript, VRFSignature, VRFTranscriptData},
CryptoStore, Error, SyncCryptoStore, SyncCryptoStorePtr, Error, Keystore, KeystorePtr,
}; };
use async_trait::async_trait;
use parking_lot::RwLock; use parking_lot::RwLock;
use std::{ use std::{collections::HashMap, sync::Arc};
collections::{HashMap, HashSet},
sync::Arc,
};
/// A keystore implementation usable in tests. /// A keystore implementation usable in tests.
#[derive(Default)] #[derive(Default)]
pub struct KeyStore { pub struct MemoryKeystore {
/// `KeyTypeId` maps to public keys and public keys map to private keys. /// `KeyTypeId` maps to public keys and public keys map to private keys.
keys: Arc<RwLock<HashMap<KeyTypeId, HashMap<Vec<u8>, String>>>>, keys: Arc<RwLock<HashMap<KeyTypeId, HashMap<Vec<u8>, String>>>>,
} }
impl KeyStore { impl MemoryKeystore {
/// Creates a new instance of `Self`. /// Creates a new instance of `Self`.
pub fn new() -> Self { pub fn new() -> Self {
Self::default() Self::default()
@@ -71,93 +67,7 @@ impl KeyStore {
} }
} }
#[async_trait] impl Keystore for MemoryKeystore {
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 {
fn keys(&self, id: KeyTypeId) -> Result<Vec<CryptoTypePublicPair>, Error> { fn keys(&self, id: KeyTypeId) -> Result<Vec<CryptoTypePublicPair>, Error> {
self.keys self.keys
.read() .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 self.keys
.write() .write()
.entry(id) .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()) .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( fn sign_with(
&self, &self,
id: KeyTypeId, id: KeyTypeId,
@@ -386,14 +285,8 @@ impl SyncCryptoStore for KeyStore {
} }
} }
impl Into<SyncCryptoStorePtr> for KeyStore { impl Into<KeystorePtr> for MemoryKeystore {
fn into(self) -> SyncCryptoStorePtr { fn into(self) -> KeystorePtr {
Arc::new(self)
}
}
impl Into<Arc<dyn CryptoStore>> for KeyStore {
fn into(self) -> Arc<dyn CryptoStore> {
Arc::new(self) Arc::new(self)
} }
} }
@@ -401,7 +294,7 @@ impl Into<Arc<dyn CryptoStore>> for KeyStore {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::{vrf::VRFTranscriptValue, SyncCryptoStore}; use crate::vrf::VRFTranscriptValue;
use sp_core::{ use sp_core::{
sr25519, sr25519,
testing::{ECDSA, ED25519, SR25519}, testing::{ECDSA, ED25519, SR25519},
@@ -409,34 +302,33 @@ mod tests {
#[test] #[test]
fn store_key_and_extract() { fn store_key_and_extract() {
let store = KeyStore::new(); let store = MemoryKeystore::new();
let public = let public = Keystore::ed25519_generate_new(&store, ED25519, None).expect("Generates key");
SyncCryptoStore::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())); assert!(public_keys.contains(&public.into()));
} }
#[test] #[test]
fn store_unknown_and_extract_it() { fn store_unknown_and_extract_it() {
let store = KeyStore::new(); let store = MemoryKeystore::new();
let secret_uri = "//Alice"; let secret_uri = "//Alice";
let key_pair = sr25519::Pair::from_string(secret_uri, None).expect("Generates key pair"); 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"); .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())); assert!(public_keys.contains(&key_pair.public().into()));
} }
#[test] #[test]
fn vrf_sign() { fn vrf_sign() {
let store = KeyStore::new(); let store = MemoryKeystore::new();
let secret_uri = "//Alice"; let secret_uri = "//Alice";
let key_pair = sr25519::Pair::from_string(secret_uri, None).expect("Generates key pair"); 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, &store,
SR25519, SR25519,
&key_pair.public(), &key_pair.public(),
@@ -458,18 +350,18 @@ mod tests {
); );
assert!(result.unwrap().is_none()); 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"); .expect("Inserts unknown key");
let result = 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()); assert!(result.unwrap().is_some());
} }
#[test] #[test]
fn ecdsa_sign_prehashed_works() { fn ecdsa_sign_prehashed_works() {
let store = KeyStore::new(); let store = MemoryKeystore::new();
let suri = "//Alice"; let suri = "//Alice";
let pair = ecdsa::Pair::from_string(suri, None).unwrap(); 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"); let msg = sp_core::keccak_256(b"this should be a hashed message");
// no key in key store // no key in key store
let res = let res = Keystore::ecdsa_sign_prehashed(&store, ECDSA, &pair.public(), &msg).unwrap();
SyncCryptoStore::ecdsa_sign_prehashed(&store, ECDSA, &pair.public(), &msg).unwrap();
assert!(res.is_none()); assert!(res.is_none());
// insert key, sign again // 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 = let res = Keystore::ecdsa_sign_prehashed(&store, ECDSA, &pair.public(), &msg).unwrap();
SyncCryptoStore::ecdsa_sign_prehashed(&store, ECDSA, &pair.public(), &msg).unwrap();
assert!(res.is_some()); assert!(res.is_some());
} }
} }
+3 -3
View File
@@ -33,7 +33,7 @@ pub use sp_consensus;
pub use sp_keyring::{ pub use sp_keyring::{
ed25519::Keyring as Ed25519Keyring, sr25519::Keyring as Sr25519Keyring, AccountKeyring, 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_runtime::{Storage, StorageChild};
pub use sp_state_machine::ExecutionStrategy; 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>, child_storage_extension: HashMap<Vec<u8>, StorageChild>,
backend: Arc<Backend>, backend: Arc<Backend>,
_executor: std::marker::PhantomData<ExecutorDispatch>, _executor: std::marker::PhantomData<ExecutorDispatch>,
keystore: Option<SyncCryptoStorePtr>, keystore: Option<KeystorePtr>,
fork_blocks: ForkBlocks<Block>, fork_blocks: ForkBlocks<Block>,
bad_blocks: BadBlocks<Block>, bad_blocks: BadBlocks<Block>,
enable_offchain_indexing_api: bool, 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. /// 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.keystore = Some(keystore);
self self
} }
@@ -38,7 +38,7 @@ use sp_core::{
traits::CallContext, traits::CallContext,
}; };
use sp_externalities::Extensions; 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_runtime::traits::{Block as BlockT, Header as HeaderT};
use sp_state_machine::StateMachine; use sp_state_machine::StateMachine;
use std::{collections::HashMap, fmt::Debug, fs, str::FromStr, sync::Arc, time}; use std::{collections::HashMap, fmt::Debug, fs, str::FromStr, sync::Arc, time};
@@ -218,7 +218,7 @@ impl PalletCmd {
let extensions = || -> Extensions { let extensions = || -> Extensions {
let mut extensions = Extensions::default(); 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 (offchain, _) = TestOffchainExt::new();
let (pool, _) = TestTransactionPoolExt::new(); let (pool, _) = TestTransactionPoolExt::new();
extensions.register(OffchainWorkerExt::new(offchain.clone())); extensions.register(OffchainWorkerExt::new(offchain.clone()));
@@ -383,7 +383,7 @@ use sp_core::{
}; };
use sp_externalities::Extensions; use sp_externalities::Extensions;
use sp_inherents::InherentData; use sp_inherents::InherentData;
use sp_keystore::{testing::KeyStore, KeystoreExt}; use sp_keystore::{testing::MemoryKeystore, KeystoreExt};
use sp_runtime::{ use sp_runtime::{
traits::{BlakeTwo256, Block as BlockT, NumberFor}, traits::{BlakeTwo256, Block as BlockT, NumberFor},
DeserializeOwned, Digest, DeserializeOwned, Digest,
@@ -820,7 +820,7 @@ pub(crate) fn full_extensions() -> Extensions {
let (pool, _pool_state) = TestTransactionPoolExt::new(); let (pool, _pool_state) = TestTransactionPoolExt::new();
extensions.register(OffchainDbExt::new(offchain.clone())); extensions.register(OffchainDbExt::new(offchain.clone()));
extensions.register(OffchainWorkerExt::new(offchain)); 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.register(TransactionPoolExt::new(pool));
extensions extensions