Run cargo fmt on the whole code base (#9394)

* Run cargo fmt on the whole code base

* Second run

* Add CI check

* Fix compilation

* More unnecessary braces

* Handle weights

* Use --all

* Use correct attributes...

* Fix UI tests

* AHHHHHHHHH

* 🤦

* Docs

* Fix compilation

* 🤷

* Please stop

* 🤦 x 2

* More

* make rustfmt.toml consistent with polkadot

Co-authored-by: André Silva <andrerfosilva@gmail.com>
This commit is contained in:
Bastian Köcher
2021-07-21 16:32:32 +02:00
committed by GitHub
parent d451c38c1c
commit 7b56ab15b4
1010 changed files with 53339 additions and 51208 deletions
+8 -10
View File
@@ -19,9 +19,9 @@
//! Keystore (and session key management) for ed25519 based chains like Polkadot.
#![warn(missing_docs)]
use std::io;
use sp_core::crypto::KeyTypeId;
use sp_keystore::Error as TraitError;
use std::io;
/// Local keystore implementation
mod local;
@@ -35,19 +35,19 @@ pub enum Error {
/// JSON error.
Json(serde_json::Error),
/// Invalid password.
#[display(fmt="Invalid password")]
#[display(fmt = "Invalid password")]
InvalidPassword,
/// Invalid BIP39 phrase
#[display(fmt="Invalid recovery phrase (BIP39) data")]
#[display(fmt = "Invalid recovery phrase (BIP39) data")]
InvalidPhrase,
/// Invalid seed
#[display(fmt="Invalid seed")]
#[display(fmt = "Invalid seed")]
InvalidSeed,
/// Public key type is not supported
#[display(fmt="Key crypto type is not supported")]
#[display(fmt = "Key crypto type is not supported")]
KeyNotSupported(KeyTypeId),
/// Keystore unavailable
#[display(fmt="Keystore unavailable")]
#[display(fmt = "Keystore unavailable")]
Unavailable,
}
@@ -58,9 +58,8 @@ impl From<Error> for TraitError {
fn from(error: Error) -> Self {
match error {
Error::KeyNotSupported(id) => TraitError::KeyNotSupported(id),
Error::InvalidSeed | Error::InvalidPhrase | Error::InvalidPassword => {
TraitError::ValidationError(error.to_string())
},
Error::InvalidSeed | Error::InvalidPhrase | Error::InvalidPassword =>
TraitError::ValidationError(error.to_string()),
Error::Unavailable => TraitError::Unavailable,
Error::Io(e) => TraitError::Other(e.to_string()),
Error::Json(e) => TraitError::Other(e.to_string()),
@@ -77,4 +76,3 @@ impl std::error::Error for Error {
}
}
}
+146 -150
View File
@@ -17,6 +17,18 @@
//
//! Local keystore implementation
use async_trait::async_trait;
use parking_lot::RwLock;
use sp_application_crypto::{ecdsa, ed25519, sr25519, AppKey, AppPair, IsWrappedBy};
use sp_core::{
crypto::{CryptoTypePublicPair, ExposeSecret, KeyTypeId, Pair as PairT, Public, SecretString},
sr25519::{Pair as Sr25519Pair, Public as Sr25519Public},
Encode,
};
use sp_keystore::{
vrf::{make_transcript, VRFSignature, VRFTranscriptData},
CryptoStore, Error as TraitError, SyncCryptoStore, SyncCryptoStorePtr,
};
use std::{
collections::{HashMap, HashSet},
fs::{self, File},
@@ -24,23 +36,8 @@ use std::{
path::PathBuf,
sync::Arc,
};
use async_trait::async_trait;
use parking_lot::RwLock;
use sp_core::{
crypto::{CryptoTypePublicPair, KeyTypeId, Pair as PairT, ExposeSecret, SecretString, Public},
sr25519::{Public as Sr25519Public, Pair as Sr25519Pair},
Encode,
};
use sp_keystore::{
CryptoStore,
SyncCryptoStorePtr,
Error as TraitError,
SyncCryptoStore,
vrf::{VRFTranscriptData, VRFSignature, make_transcript},
};
use sp_application_crypto::{ed25519, sr25519, ecdsa, AppPair, AppKey, IsWrappedBy};
use crate::{Result, Error};
use crate::{Error, Result};
/// A local based keystore that is either memory-based or filesystem-based.
pub struct LocalKeystore(RwLock<KeystoreInner>);
@@ -62,14 +59,20 @@ impl LocalKeystore {
///
/// Returns `Ok(None)` if the key doesn't exist, `Ok(Some(_))` if the key exists and
/// `Err(_)` when something failed.
pub fn key_pair<Pair: AppPair>(&self, public: &<Pair as AppKey>::Public) -> Result<Option<Pair>> {
pub fn key_pair<Pair: AppPair>(
&self,
public: &<Pair as AppKey>::Public,
) -> Result<Option<Pair>> {
self.0.read().key_pair::<Pair>(public)
}
}
#[async_trait]
impl CryptoStore for LocalKeystore {
async fn keys(&self, id: KeyTypeId) -> std::result::Result<Vec<CryptoTypePublicPair>, TraitError> {
async fn keys(
&self,
id: KeyTypeId,
) -> std::result::Result<Vec<CryptoTypePublicPair>, TraitError> {
SyncCryptoStore::keys(self, id)
}
@@ -109,7 +112,12 @@ impl CryptoStore for LocalKeystore {
SyncCryptoStore::ecdsa_generate_new(self, id, seed)
}
async fn insert_unknown(&self, id: KeyTypeId, suri: &str, public: &[u8]) -> std::result::Result<(), ()> {
async fn insert_unknown(
&self,
id: KeyTypeId,
suri: &str,
public: &[u8],
) -> std::result::Result<(), ()> {
SyncCryptoStore::insert_unknown(self, id, suri, public)
}
@@ -154,28 +162,22 @@ impl CryptoStore for LocalKeystore {
}
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)?;
Ok(raw_keys.into_iter()
.fold(Vec::new(), |mut v, k| {
v.push(CryptoTypePublicPair(sr25519::CRYPTO_ID, k.clone()));
v.push(CryptoTypePublicPair(ed25519::CRYPTO_ID, k.clone()));
v.push(CryptoTypePublicPair(ecdsa::CRYPTO_ID, k));
v
}))
Ok(raw_keys.into_iter().fold(Vec::new(), |mut v, k| {
v.push(CryptoTypePublicPair(sr25519::CRYPTO_ID, k.clone()));
v.push(CryptoTypePublicPair(ed25519::CRYPTO_ID, k.clone()));
v.push(CryptoTypePublicPair(ecdsa::CRYPTO_ID, k));
v
}))
}
fn supported_keys(
&self,
id: KeyTypeId,
keys: Vec<CryptoTypePublicPair>
keys: Vec<CryptoTypePublicPair>,
) -> std::result::Result<Vec<CryptoTypePublicPair>, TraitError> {
let all_keys = SyncCryptoStore::keys(self, id)?
.into_iter()
.collect::<HashSet<_>>();
let all_keys = SyncCryptoStore::keys(self, id)?.into_iter().collect::<HashSet<_>>();
Ok(keys.into_iter().filter(|key| all_keys.contains(key)).collect::<Vec<_>>())
}
@@ -188,36 +190,40 @@ impl SyncCryptoStore for LocalKeystore {
match key.0 {
ed25519::CRYPTO_ID => {
let pub_key = ed25519::Public::from_slice(key.1.as_slice());
let key_pair = self.0.read()
let key_pair = self
.0
.read()
.key_pair_by_type::<ed25519::Pair>(&pub_key, id)
.map_err(|e| TraitError::from(e))?;
key_pair.map(|k| k.sign(msg).encode()).map(Ok).transpose()
}
},
sr25519::CRYPTO_ID => {
let pub_key = sr25519::Public::from_slice(key.1.as_slice());
let key_pair = self.0.read()
let key_pair = self
.0
.read()
.key_pair_by_type::<sr25519::Pair>(&pub_key, id)
.map_err(|e| TraitError::from(e))?;
key_pair.map(|k| k.sign(msg).encode()).map(Ok).transpose()
},
ecdsa::CRYPTO_ID => {
let pub_key = ecdsa::Public::from_slice(key.1.as_slice());
let key_pair = self.0.read()
let key_pair = self
.0
.read()
.key_pair_by_type::<ecdsa::Pair>(&pub_key, id)
.map_err(|e| TraitError::from(e))?;
key_pair.map(|k| k.sign(msg).encode()).map(Ok).transpose()
}
_ => Err(TraitError::KeyNotSupported(id))
},
_ => Err(TraitError::KeyNotSupported(id)),
}
}
fn sr25519_public_keys(&self, key_type: KeyTypeId) -> Vec<sr25519::Public> {
self.0.read().raw_public_keys(key_type)
.map(|v| {
v.into_iter()
.map(|k| sr25519::Public::from_slice(k.as_slice()))
.collect()
})
self.0
.read()
.raw_public_keys(key_type)
.map(|v| v.into_iter().map(|k| sr25519::Public::from_slice(k.as_slice())).collect())
.unwrap_or_default()
}
@@ -227,20 +233,20 @@ impl SyncCryptoStore for LocalKeystore {
seed: Option<&str>,
) -> std::result::Result<sr25519::Public, TraitError> {
let pair = match seed {
Some(seed) => self.0.write().insert_ephemeral_from_seed_by_type::<sr25519::Pair>(seed, id),
Some(seed) =>
self.0.write().insert_ephemeral_from_seed_by_type::<sr25519::Pair>(seed, id),
None => self.0.write().generate_by_type::<sr25519::Pair>(id),
}.map_err(|e| -> TraitError { e.into() })?;
}
.map_err(|e| -> TraitError { e.into() })?;
Ok(pair.public())
}
fn ed25519_public_keys(&self, key_type: KeyTypeId) -> Vec<ed25519::Public> {
self.0.read().raw_public_keys(key_type)
.map(|v| {
v.into_iter()
.map(|k| ed25519::Public::from_slice(k.as_slice()))
.collect()
})
self.0
.read()
.raw_public_keys(key_type)
.map(|v| v.into_iter().map(|k| ed25519::Public::from_slice(k.as_slice())).collect())
.unwrap_or_default()
}
@@ -250,20 +256,20 @@ impl SyncCryptoStore for LocalKeystore {
seed: Option<&str>,
) -> std::result::Result<ed25519::Public, TraitError> {
let pair = match seed {
Some(seed) => self.0.write().insert_ephemeral_from_seed_by_type::<ed25519::Pair>(seed, id),
Some(seed) =>
self.0.write().insert_ephemeral_from_seed_by_type::<ed25519::Pair>(seed, id),
None => self.0.write().generate_by_type::<ed25519::Pair>(id),
}.map_err(|e| -> TraitError { e.into() })?;
}
.map_err(|e| -> TraitError { e.into() })?;
Ok(pair.public())
}
fn ecdsa_public_keys(&self, key_type: KeyTypeId) -> Vec<ecdsa::Public> {
self.0.read().raw_public_keys(key_type)
.map(|v| {
v.into_iter()
.map(|k| ecdsa::Public::from_slice(k.as_slice()))
.collect()
})
self.0
.read()
.raw_public_keys(key_type)
.map(|v| v.into_iter().map(|k| ecdsa::Public::from_slice(k.as_slice())).collect())
.unwrap_or_default()
}
@@ -273,21 +279,27 @@ impl SyncCryptoStore for LocalKeystore {
seed: Option<&str>,
) -> std::result::Result<ecdsa::Public, TraitError> {
let pair = match seed {
Some(seed) => self.0.write().insert_ephemeral_from_seed_by_type::<ecdsa::Pair>(seed, id),
Some(seed) =>
self.0.write().insert_ephemeral_from_seed_by_type::<ecdsa::Pair>(seed, id),
None => self.0.write().generate_by_type::<ecdsa::Pair>(id),
}.map_err(|e| -> TraitError { e.into() })?;
}
.map_err(|e| -> TraitError { e.into() })?;
Ok(pair.public())
}
fn insert_unknown(&self, key_type: KeyTypeId, suri: &str, public: &[u8])
-> std::result::Result<(), ()>
{
fn insert_unknown(
&self,
key_type: KeyTypeId,
suri: &str,
public: &[u8],
) -> std::result::Result<(), ()> {
self.0.write().insert_unknown(key_type, suri, public).map_err(|_| ())
}
fn has_keys(&self, public_keys: &[(Vec<u8>, KeyTypeId)]) -> bool {
public_keys.iter()
public_keys
.iter()
.all(|(p, t)| self.0.read().key_phrase_by_type(&p, *t).ok().flatten().is_some())
}
@@ -302,10 +314,7 @@ impl SyncCryptoStore for LocalKeystore {
if let Some(pair) = pair {
let (inout, proof, _) = pair.as_ref().vrf_sign(transcript);
Ok(Some(VRFSignature {
output: inout.to_output(),
proof,
}))
Ok(Some(VRFSignature { output: inout.to_output(), proof }))
} else {
Ok(None)
}
@@ -317,9 +326,8 @@ impl SyncCryptoStore for LocalKeystore {
public: &ecdsa::Public,
msg: &[u8; 32],
) -> std::result::Result<Option<ecdsa::Signature>, TraitError> {
let pair = self.0.read()
.key_pair_by_type::<ecdsa::Pair>(public, id)?;
let pair = self.0.read().key_pair_by_type::<ecdsa::Pair>(public, id)?;
pair.map(|k| k.sign_prehashed(msg)).map(Ok).transpose()
}
}
@@ -362,26 +370,16 @@ impl KeystoreInner {
/// Get the password for this store.
fn password(&self) -> Option<&str> {
self.password.as_ref()
.map(|p| p.expose_secret())
.map(|p| p.as_str())
self.password.as_ref().map(|p| p.expose_secret()).map(|p| p.as_str())
}
/// Create a new in-memory store.
fn new_in_memory() -> Self {
Self {
path: None,
additional: HashMap::new(),
password: None
}
Self { path: None, additional: HashMap::new(), password: None }
}
/// Get the key phrase for the given public key and key type from the in-memory store.
fn get_additional_pair(
&self,
public: &[u8],
key_type: KeyTypeId,
) -> Option<&String> {
fn get_additional_pair(&self, public: &[u8], key_type: KeyTypeId) -> Option<&String> {
let key = (key_type, public.to_vec());
self.additional.get(&key)
}
@@ -444,7 +442,7 @@ impl KeystoreInner {
let path = if let Some(path) = self.key_file_path(public, key_type) {
path
} else {
return Ok(None);
return Ok(None)
};
if path.exists() {
@@ -468,10 +466,7 @@ impl KeystoreInner {
return Ok(None)
};
let pair = Pair::from_string(
&phrase,
self.password(),
).map_err(|_| Error::InvalidPhrase)?;
let pair = Pair::from_string(&phrase, self.password()).map_err(|_| Error::InvalidPhrase)?;
if &pair.public() == public {
Ok(Some(pair))
@@ -493,7 +488,9 @@ impl KeystoreInner {
/// Returns a list of raw public keys filtered by `KeyTypeId`
fn raw_public_keys(&self, id: KeyTypeId) -> Result<Vec<Vec<u8>>> {
let mut public_keys: Vec<Vec<u8>> = self.additional.keys()
let mut public_keys: Vec<Vec<u8>> = self
.additional
.keys()
.into_iter()
.filter_map(|k| if k.0 == id { Some(k.1.clone()) } else { None })
.collect();
@@ -508,11 +505,11 @@ impl KeystoreInner {
match hex::decode(name) {
Ok(ref hex) if hex.len() > 4 => {
if &hex[0..4] != &id.0 {
continue;
continue
}
let public = hex[4..].to_vec();
public_keys.push(public);
}
},
_ => continue,
}
}
@@ -526,42 +523,34 @@ impl KeystoreInner {
///
/// Returns `Ok(None)` if the key doesn't exist, `Ok(Some(_))` if the key exists or `Err(_)` when
/// something failed.
pub fn key_pair<Pair: AppPair>(&self, public: &<Pair as AppKey>::Public) -> Result<Option<Pair>> {
pub fn key_pair<Pair: AppPair>(
&self,
public: &<Pair as AppKey>::Public,
) -> Result<Option<Pair>> {
self.key_pair_by_type::<Pair::Generic>(IsWrappedBy::from_ref(public), Pair::ID)
.map(|v| v.map(Into::into))
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
use sp_core::{
Pair,
crypto::Ss58Codec,
testing::SR25519,
};
use sp_application_crypto::{ed25519, sr25519, AppPublic};
use std::{
fs,
str::FromStr,
};
use sp_core::{crypto::Ss58Codec, testing::SR25519, Pair};
use std::{fs, str::FromStr};
use tempfile::TempDir;
const TEST_KEY_TYPE: KeyTypeId = KeyTypeId(*b"test");
impl KeystoreInner {
fn insert_ephemeral_from_seed<Pair: AppPair>(&mut self, seed: &str) -> Result<Pair> {
self.insert_ephemeral_from_seed_by_type::<Pair::Generic>(seed, Pair::ID).map(Into::into)
self.insert_ephemeral_from_seed_by_type::<Pair::Generic>(seed, Pair::ID)
.map(Into::into)
}
fn public_keys<Public: AppPublic>(&self) -> Result<Vec<Public>> {
self.raw_public_keys(Public::ID)
.map(|v| {
v.into_iter()
.map(|k| Public::from_slice(k.as_slice()))
.collect()
})
.map(|v| v.into_iter().map(|k| Public::from_slice(k.as_slice())).collect())
}
fn generate<Pair: AppPair>(&mut self) -> Result<Pair> {
@@ -592,23 +581,23 @@ mod tests {
let key: ed25519::AppPair = store.0.write().generate().unwrap();
let key2 = ed25519::Pair::generate().0;
assert!(
!SyncCryptoStore::has_keys(&store, &[(key2.public().to_vec(), ed25519::AppPublic::ID)])
);
assert!(!SyncCryptoStore::has_keys(
&store,
&[(key2.public().to_vec(), ed25519::AppPublic::ID)]
));
assert!(
!SyncCryptoStore::has_keys(
&store,
&[
(key2.public().to_vec(), ed25519::AppPublic::ID),
(key.public().to_raw_vec(), ed25519::AppPublic::ID),
],
)
);
assert!(!SyncCryptoStore::has_keys(
&store,
&[
(key2.public().to_vec(), ed25519::AppPublic::ID),
(key.public().to_raw_vec(), ed25519::AppPublic::ID),
],
));
assert!(
SyncCryptoStore::has_keys(&store, &[(key.public().to_raw_vec(), ed25519::AppPublic::ID)])
);
assert!(SyncCryptoStore::has_keys(
&store,
&[(key.public().to_raw_vec(), ed25519::AppPublic::ID)]
));
}
#[test]
@@ -616,9 +605,11 @@ mod tests {
let temp_dir = TempDir::new().unwrap();
let mut store = KeystoreInner::open(temp_dir.path(), None).unwrap();
let pair: ed25519::AppPair = store.insert_ephemeral_from_seed(
"0x3d97c819d68f9bafa7d6e79cb991eebcd77d966c5334c0b94d9e1fa7ad0869dc"
).unwrap();
let pair: ed25519::AppPair = store
.insert_ephemeral_from_seed(
"0x3d97c819d68f9bafa7d6e79cb991eebcd77d966c5334c0b94d9e1fa7ad0869dc",
)
.unwrap();
assert_eq!(
"5DKUrgFqCPV8iAXx9sjy1nyBygQCeiUYRFWurZGhnrn3HJCA",
pair.public().to_ss58check()
@@ -637,7 +628,8 @@ mod tests {
let mut store = KeystoreInner::open(
temp_dir.path(),
Some(FromStr::from_str(password.as_str()).unwrap()),
).unwrap();
)
.unwrap();
let pair: ed25519::AppPair = store.generate().unwrap();
assert_eq!(
@@ -652,7 +644,8 @@ mod tests {
let store = KeystoreInner::open(
temp_dir.path(),
Some(FromStr::from_str(password.as_str()).unwrap()),
).unwrap();
)
.unwrap();
assert_eq!(
pair.public(),
store.key_pair::<ed25519::AppPair>(&pair.public()).unwrap().unwrap().public(),
@@ -667,9 +660,15 @@ mod tests {
let mut keys = Vec::new();
for i in 0..10 {
keys.push(store.generate::<ed25519::AppPair>().unwrap().public());
keys.push(store.insert_ephemeral_from_seed::<ed25519::AppPair>(
&format!("0x3d97c819d68f9bafa7d6e79cb991eebcd7{}d966c5334c0b94d9e1fa7ad0869dc", i),
).unwrap().public());
keys.push(
store
.insert_ephemeral_from_seed::<ed25519::AppPair>(&format!(
"0x3d97c819d68f9bafa7d6e79cb991eebcd7{}d966c5334c0b94d9e1fa7ad0869dc",
i
))
.unwrap()
.public(),
);
}
// Generate a key of a different type
@@ -690,16 +689,14 @@ mod tests {
let secret_uri = "//Alice";
let key_pair = sr25519::AppPair::from_string(secret_uri, None).expect("Generates key pair");
store.insert_unknown(
SR25519,
secret_uri,
key_pair.public().as_ref(),
).expect("Inserts unknown key");
store
.insert_unknown(SR25519, secret_uri, key_pair.public().as_ref())
.expect("Inserts unknown key");
let store_key_pair = store.key_pair_by_type::<sr25519::AppPair>(
&key_pair.public(),
SR25519,
).expect("Gets key pair from keystore").unwrap();
let store_key_pair = store
.key_pair_by_type::<sr25519::AppPair>(&key_pair.public(), SR25519)
.expect("Gets key pair from keystore")
.unwrap();
assert_eq!(key_pair.public(), store_key_pair.public());
}
@@ -712,16 +709,15 @@ mod tests {
let file_name = temp_dir.path().join(hex::encode(&SR25519.0[..2]));
fs::write(file_name, "test").expect("Invalid file is written");
assert!(
SyncCryptoStore::sr25519_public_keys(&store, SR25519).is_empty(),
);
assert!(SyncCryptoStore::sr25519_public_keys(&store, SR25519).is_empty(),);
}
#[test]
fn generate_with_seed_is_not_stored() {
let temp_dir = TempDir::new().unwrap();
let store = LocalKeystore::open(temp_dir.path(), None).unwrap();
let _alice_tmp_key = SyncCryptoStore::sr25519_generate_new(&store, TEST_KEY_TYPE, Some("//Alice")).unwrap();
let _alice_tmp_key =
SyncCryptoStore::sr25519_generate_new(&store, TEST_KEY_TYPE, Some("//Alice")).unwrap();
assert_eq!(SyncCryptoStore::sr25519_public_keys(&store, TEST_KEY_TYPE).len(), 1);