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
+25 -34
View File
@@ -19,30 +19,30 @@
pub mod testing;
pub mod vrf;
use std::sync::Arc;
use crate::vrf::{VRFSignature, VRFTranscriptData};
use async_trait::async_trait;
use futures::{executor::block_on, future::join_all};
use sp_core::{
crypto::{KeyTypeId, CryptoTypePublicPair},
ed25519, sr25519, ecdsa,
crypto::{CryptoTypePublicPair, KeyTypeId},
ecdsa, ed25519, sr25519,
};
use crate::vrf::{VRFTranscriptData, VRFSignature};
use std::sync::Arc;
/// CryptoStore error
#[derive(Debug, derive_more::Display)]
pub enum Error {
/// Public key type is not supported
#[display(fmt="Key not supported: {:?}", _0)]
#[display(fmt = "Key not supported: {:?}", _0)]
KeyNotSupported(KeyTypeId),
/// Validation error
#[display(fmt="Validation error: {}", _0)]
#[display(fmt = "Validation error: {}", _0)]
ValidationError(String),
/// Keystore unavailable
#[display(fmt="Keystore unavailable")]
#[display(fmt = "Keystore unavailable")]
Unavailable,
/// Programming errors
#[display(fmt="An unknown keystore error occurred: {}", _0)]
Other(String)
#[display(fmt = "An unknown keystore error occurred: {}", _0)]
Other(String),
}
/// Something that generates, stores and provides access to keys.
@@ -91,12 +91,7 @@ pub trait CryptoStore: Send + Sync {
/// 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<(), ()>;
async fn insert_unknown(&self, id: KeyTypeId, suri: &str, public: &[u8]) -> Result<(), ()>;
/// Find intersection between provided keys and supported keys
///
@@ -105,7 +100,7 @@ pub trait CryptoStore: Send + Sync {
async fn supported_keys(
&self,
id: KeyTypeId,
keys: Vec<CryptoTypePublicPair>
keys: Vec<CryptoTypePublicPair>,
) -> Result<Vec<CryptoTypePublicPair>, Error>;
/// List all supported keys
///
@@ -142,14 +137,14 @@ pub trait CryptoStore: Send + Sync {
&self,
id: KeyTypeId,
keys: Vec<CryptoTypePublicPair>,
msg: &[u8]
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)));
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)));
return Ok(Some((k, sign)))
}
}
}
@@ -170,8 +165,7 @@ pub trait CryptoStore: Send + Sync {
keys: Vec<CryptoTypePublicPair>,
msg: &[u8],
) -> Result<Vec<Result<Option<Vec<u8>>, Error>>, ()> {
let futs = keys.iter()
.map(|k| self.sign_with(id, k, msg));
let futs = keys.iter().map(|k| self.sign_with(id, k, msg));
Ok(join_all(futs).await)
}
@@ -202,8 +196,8 @@ pub trait CryptoStore: Send + Sync {
/// 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.
///
/// 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.
@@ -260,11 +254,8 @@ pub trait SyncCryptoStore: CryptoStore + Send + Sync {
/// If the given seed is `Some(_)`, the key pair will only be stored in memory.
///
/// Returns the public key of the generated key pair.
fn ecdsa_generate_new(
&self,
id: KeyTypeId,
seed: Option<&str>,
) -> Result<ecdsa::Public, Error>;
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.
@@ -281,7 +272,7 @@ pub trait SyncCryptoStore: CryptoStore + Send + Sync {
fn supported_keys(
&self,
id: KeyTypeId,
keys: Vec<CryptoTypePublicPair>
keys: Vec<CryptoTypePublicPair>,
) -> Result<Vec<CryptoTypePublicPair>, Error>;
/// List all supported keys
@@ -321,16 +312,16 @@ pub trait SyncCryptoStore: CryptoStore + Send + Sync {
&self,
id: KeyTypeId,
keys: Vec<CryptoTypePublicPair>,
msg: &[u8]
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)),
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)));
return Ok(Some((k, sign)))
}
}
}
@@ -380,8 +371,8 @@ pub trait SyncCryptoStore: CryptoStore + Send + Sync {
/// 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.
///
/// 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.
+138 -105
View File
@@ -17,19 +17,21 @@
//! Types that should only be used for testing!
use sp_core::crypto::KeyTypeId;
use sp_core::{
crypto::{Pair, Public, CryptoTypePublicPair},
ed25519, sr25519, ecdsa,
crypto::{CryptoTypePublicPair, KeyTypeId, Pair, Public},
ecdsa, ed25519, sr25519,
};
use crate::{
{CryptoStore, SyncCryptoStorePtr, Error, SyncCryptoStore},
vrf::{VRFTranscriptData, VRFSignature, make_transcript},
vrf::{make_transcript, VRFSignature, VRFTranscriptData},
CryptoStore, Error, SyncCryptoStore, SyncCryptoStorePtr,
};
use std::{collections::{HashMap, HashSet}, sync::Arc};
use parking_lot::RwLock;
use async_trait::async_trait;
use parking_lot::RwLock;
use std::{
collections::{HashMap, HashSet},
sync::Arc,
};
/// A keystore implementation usable in tests.
#[derive(Default)]
@@ -45,29 +47,28 @@ impl KeyStore {
}
fn sr25519_key_pair(&self, id: KeyTypeId, pub_key: &sr25519::Public) -> Option<sr25519::Pair> {
self.keys.read().get(&id)
.and_then(|inner|
inner.get(pub_key.as_slice())
.map(|s| sr25519::Pair::from_string(s, None).expect("`sr25519` seed slice is valid"))
)
self.keys.read().get(&id).and_then(|inner| {
inner.get(pub_key.as_slice()).map(|s| {
sr25519::Pair::from_string(s, None).expect("`sr25519` seed slice is valid")
})
})
}
fn ed25519_key_pair(&self, id: KeyTypeId, pub_key: &ed25519::Public) -> Option<ed25519::Pair> {
self.keys.read().get(&id)
.and_then(|inner|
inner.get(pub_key.as_slice())
.map(|s| ed25519::Pair::from_string(s, None).expect("`ed25519` seed slice is valid"))
)
self.keys.read().get(&id).and_then(|inner| {
inner.get(pub_key.as_slice()).map(|s| {
ed25519::Pair::from_string(s, None).expect("`ed25519` seed slice is valid")
})
})
}
fn ecdsa_key_pair(&self, id: KeyTypeId, pub_key: &ecdsa::Public) -> Option<ecdsa::Pair> {
self.keys.read().get(&id)
.and_then(|inner|
inner.get(pub_key.as_slice())
.map(|s| ecdsa::Pair::from_string(s, None).expect("`ecdsa` seed slice is valid"))
)
self.keys.read().get(&id).and_then(|inner| {
inner
.get(pub_key.as_slice())
.map(|s| ecdsa::Pair::from_string(s, None).expect("`ecdsa` seed slice is valid"))
})
}
}
#[async_trait]
@@ -158,28 +159,32 @@ impl CryptoStore for KeyStore {
impl SyncCryptoStore for KeyStore {
fn keys(&self, id: KeyTypeId) -> Result<Vec<CryptoTypePublicPair>, Error> {
self.keys.read()
self.keys
.read()
.get(&id)
.map(|map| {
Ok(map.keys()
.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.clone()));
v
}))
Ok(map.keys().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.clone()));
v
}))
})
.unwrap_or_else(|| Ok(vec![]))
}
fn sr25519_public_keys(&self, id: KeyTypeId) -> Vec<sr25519::Public> {
self.keys.read().get(&id)
.map(|keys|
self.keys
.read()
.get(&id)
.map(|keys| {
keys.values()
.map(|s| sr25519::Pair::from_string(s, None).expect("`sr25519` seed slice is valid"))
.map(|s| {
sr25519::Pair::from_string(s, None).expect("`sr25519` seed slice is valid")
})
.map(|p| p.public())
.collect()
)
})
.unwrap_or_default()
}
@@ -190,27 +195,40 @@ impl SyncCryptoStore for KeyStore {
) -> Result<sr25519::Public, Error> {
match seed {
Some(seed) => {
let pair = sr25519::Pair::from_string(seed, None)
.map_err(|_| Error::ValidationError("Generates an `sr25519` pair.".to_owned()))?;
self.keys.write().entry(id).or_default().insert(pair.public().to_raw_vec(), seed.into());
let pair = sr25519::Pair::from_string(seed, None).map_err(|_| {
Error::ValidationError("Generates an `sr25519` pair.".to_owned())
})?;
self.keys
.write()
.entry(id)
.or_default()
.insert(pair.public().to_raw_vec(), seed.into());
Ok(pair.public())
},
None => {
let (pair, phrase, _) = sr25519::Pair::generate_with_phrase(None);
self.keys.write().entry(id).or_default().insert(pair.public().to_raw_vec(), phrase);
self.keys
.write()
.entry(id)
.or_default()
.insert(pair.public().to_raw_vec(), phrase);
Ok(pair.public())
}
},
}
}
fn ed25519_public_keys(&self, id: KeyTypeId) -> Vec<ed25519::Public> {
self.keys.read().get(&id)
.map(|keys|
self.keys
.read()
.get(&id)
.map(|keys| {
keys.values()
.map(|s| ed25519::Pair::from_string(s, None).expect("`ed25519` seed slice is valid"))
.map(|s| {
ed25519::Pair::from_string(s, None).expect("`ed25519` seed slice is valid")
})
.map(|p| p.public())
.collect()
)
})
.unwrap_or_default()
}
@@ -221,27 +239,40 @@ impl SyncCryptoStore for KeyStore {
) -> Result<ed25519::Public, Error> {
match seed {
Some(seed) => {
let pair = ed25519::Pair::from_string(seed, None)
.map_err(|_| Error::ValidationError("Generates an `ed25519` pair.".to_owned()))?;
self.keys.write().entry(id).or_default().insert(pair.public().to_raw_vec(), seed.into());
let pair = ed25519::Pair::from_string(seed, None).map_err(|_| {
Error::ValidationError("Generates an `ed25519` pair.".to_owned())
})?;
self.keys
.write()
.entry(id)
.or_default()
.insert(pair.public().to_raw_vec(), seed.into());
Ok(pair.public())
},
None => {
let (pair, phrase, _) = ed25519::Pair::generate_with_phrase(None);
self.keys.write().entry(id).or_default().insert(pair.public().to_raw_vec(), phrase);
self.keys
.write()
.entry(id)
.or_default()
.insert(pair.public().to_raw_vec(), phrase);
Ok(pair.public())
}
},
}
}
fn ecdsa_public_keys(&self, id: KeyTypeId) -> Vec<ecdsa::Public> {
self.keys.read().get(&id)
.map(|keys|
self.keys
.read()
.get(&id)
.map(|keys| {
keys.values()
.map(|s| ecdsa::Pair::from_string(s, None).expect("`ecdsa` seed slice is valid"))
.map(|s| {
ecdsa::Pair::from_string(s, None).expect("`ecdsa` seed slice is valid")
})
.map(|p| p.public())
.collect()
)
})
.unwrap_or_default()
}
@@ -254,24 +285,38 @@ impl SyncCryptoStore for KeyStore {
Some(seed) => {
let pair = ecdsa::Pair::from_string(seed, None)
.map_err(|_| Error::ValidationError("Generates an `ecdsa` pair.".to_owned()))?;
self.keys.write().entry(id).or_default().insert(pair.public().to_raw_vec(), seed.into());
self.keys
.write()
.entry(id)
.or_default()
.insert(pair.public().to_raw_vec(), seed.into());
Ok(pair.public())
},
None => {
let (pair, phrase, _) = ecdsa::Pair::generate_with_phrase(None);
self.keys.write().entry(id).or_default().insert(pair.public().to_raw_vec(), phrase);
self.keys
.write()
.entry(id)
.or_default()
.insert(pair.public().to_raw_vec(), phrase);
Ok(pair.public())
}
},
}
}
fn insert_unknown(&self, id: KeyTypeId, suri: &str, public: &[u8]) -> Result<(), ()> {
self.keys.write().entry(id).or_default().insert(public.to_owned(), suri.to_string());
self.keys
.write()
.entry(id)
.or_default()
.insert(public.to_owned(), suri.to_string());
Ok(())
}
fn has_keys(&self, public_keys: &[(Vec<u8>, KeyTypeId)]) -> bool {
public_keys.iter().all(|(k, t)| self.keys.read().get(&t).and_then(|s| s.get(k)).is_some())
public_keys
.iter()
.all(|(k, t)| self.keys.read().get(&t).and_then(|s| s.get(k)).is_some())
}
fn supported_keys(
@@ -295,24 +340,24 @@ impl SyncCryptoStore for KeyStore {
match key.0 {
ed25519::CRYPTO_ID => {
let key_pair = self
.ed25519_key_pair(id, &ed25519::Public::from_slice(key.1.as_slice()));
let key_pair =
self.ed25519_key_pair(id, &ed25519::Public::from_slice(key.1.as_slice()));
key_pair.map(|k| k.sign(msg).encode()).map(Ok).transpose()
}
},
sr25519::CRYPTO_ID => {
let key_pair = self
.sr25519_key_pair(id, &sr25519::Public::from_slice(key.1.as_slice()));
let key_pair =
self.sr25519_key_pair(id, &sr25519::Public::from_slice(key.1.as_slice()));
key_pair.map(|k| k.sign(msg).encode()).map(Ok).transpose()
}
},
ecdsa::CRYPTO_ID => {
let key_pair = self
.ecdsa_key_pair(id, &ecdsa::Public::from_slice(key.1.as_slice()));
let key_pair =
self.ecdsa_key_pair(id, &ecdsa::Public::from_slice(key.1.as_slice()));
key_pair.map(|k| k.sign(msg).encode()).map(Ok).transpose()
}
_ => Err(Error::KeyNotSupported(id))
},
_ => Err(Error::KeyNotSupported(id)),
}
}
@@ -323,17 +368,11 @@ impl SyncCryptoStore for KeyStore {
transcript_data: VRFTranscriptData,
) -> Result<Option<VRFSignature>, Error> {
let transcript = make_transcript(transcript_data);
let pair = if let Some(k) = self.sr25519_key_pair(key_type, public) {
k
} else {
return Ok(None)
};
let pair =
if let Some(k) = self.sr25519_key_pair(key_type, public) { k } else { return Ok(None) };
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 }))
}
fn ecdsa_sign_prehashed(
@@ -362,15 +401,18 @@ impl Into<Arc<dyn CryptoStore>> for KeyStore {
#[cfg(test)]
mod tests {
use super::*;
use sp_core::{sr25519, testing::{ED25519, SR25519, ECDSA}};
use crate::{SyncCryptoStore, vrf::VRFTranscriptValue};
use crate::{vrf::VRFTranscriptValue, SyncCryptoStore};
use sp_core::{
sr25519,
testing::{ECDSA, ED25519, SR25519},
};
#[test]
fn store_key_and_extract() {
let store = KeyStore::new();
let public = SyncCryptoStore::ed25519_generate_new(&store, ED25519, None)
.expect("Generates key");
let public =
SyncCryptoStore::ed25519_generate_new(&store, ED25519, None).expect("Generates key");
let public_keys = SyncCryptoStore::keys(&store, ED25519).unwrap();
@@ -384,12 +426,8 @@ mod tests {
let secret_uri = "//Alice";
let key_pair = sr25519::Pair::from_string(secret_uri, None).expect("Generates key pair");
SyncCryptoStore::insert_unknown(
&store,
SR25519,
secret_uri,
key_pair.public().as_ref(),
).expect("Inserts unknown key");
SyncCryptoStore::insert_unknown(&store, SR25519, secret_uri, key_pair.public().as_ref())
.expect("Inserts unknown key");
let public_keys = SyncCryptoStore::keys(&store, SR25519).unwrap();
@@ -409,7 +447,7 @@ mod tests {
("one", VRFTranscriptValue::U64(1)),
("two", VRFTranscriptValue::U64(2)),
("three", VRFTranscriptValue::Bytes("test".as_bytes().to_vec())),
]
],
};
let result = SyncCryptoStore::sr25519_vrf_sign(
@@ -420,19 +458,11 @@ mod tests {
);
assert!(result.unwrap().is_none());
SyncCryptoStore::insert_unknown(
&store,
SR25519,
secret_uri,
key_pair.public().as_ref(),
).expect("Inserts unknown key");
SyncCryptoStore::insert_unknown(&store, SR25519, secret_uri, key_pair.public().as_ref())
.expect("Inserts unknown key");
let result = SyncCryptoStore::sr25519_vrf_sign(
&store,
SR25519,
&key_pair.public(),
transcript_data,
);
let result =
SyncCryptoStore::sr25519_vrf_sign(&store, SR25519, &key_pair.public(), transcript_data);
assert!(result.unwrap().is_some());
}
@@ -445,16 +475,19 @@ mod tests {
let pair = ecdsa::Pair::from_string(suri, None).unwrap();
let msg = sp_core::keccak_256(b"this should be a hashed message");
// no key in key store
let res = SyncCryptoStore::ecdsa_sign_prehashed(&store, ECDSA, &pair.public(), &msg).unwrap();
let res =
SyncCryptoStore::ecdsa_sign_prehashed(&store, ECDSA, &pair.public(), &msg).unwrap();
assert!(res.is_none());
// insert key, sign again
let res = SyncCryptoStore::insert_unknown(&store, ECDSA, suri, pair.public().as_ref()).unwrap();
let res =
SyncCryptoStore::insert_unknown(&store, ECDSA, suri, pair.public().as_ref()).unwrap();
assert_eq!((), res);
let res = SyncCryptoStore::ecdsa_sign_prehashed(&store, ECDSA, &pair.public(), &msg).unwrap();
assert!(res.is_some());
let res =
SyncCryptoStore::ecdsa_sign_prehashed(&store, ECDSA, &pair.public(), &msg).unwrap();
assert!(res.is_some());
}
}
+3 -9
View File
@@ -59,21 +59,17 @@ pub fn make_transcript(data: VRFTranscriptData) -> Transcript {
},
VRFTranscriptValue::U64(val) => {
transcript.append_u64(label.as_bytes(), val);
}
},
}
}
transcript
}
#[cfg(test)]
mod tests {
use super::*;
use rand::RngCore;
use rand_chacha::{
rand_core::SeedableRng,
ChaChaRng,
};
use rand_chacha::{rand_core::SeedableRng, ChaChaRng};
#[test]
fn transcript_creation_matches() {
@@ -90,9 +86,7 @@ mod tests {
});
let test = |t: Transcript| -> [u8; 16] {
let mut b = [0u8; 16];
t.build_rng()
.finalize(&mut ChaChaRng::from_seed([0u8;32]))
.fill_bytes(&mut b);
t.build_rng().finalize(&mut ChaChaRng::from_seed([0u8; 32])).fill_bytes(&mut b);
b
};
debug_assert!(test(orig_transcript) == test(new_transcript));