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
+69 -67
View File
@@ -21,30 +21,33 @@
#[cfg(test)]
mod tests;
use std::{sync::Arc, convert::TryInto};
use log::warn;
use std::{convert::TryInto, sync::Arc};
use sp_blockchain::HeaderBackend;
use rpc::futures::{Sink, Future, future::result};
use futures::{StreamExt as _, compat::Compat};
use futures::future::{ready, FutureExt, TryFutureExt};
use sc_rpc_api::DenyUnsafe;
use jsonrpc_pubsub::{typed::Subscriber, SubscriptionId, manager::SubscriptionManager};
use codec::{Encode, Decode};
use sp_core::Bytes;
use sp_keystore::{SyncCryptoStorePtr, SyncCryptoStore};
use sp_api::ProvideRuntimeApi;
use sp_runtime::generic;
use sc_transaction_pool_api::{
TransactionPool, InPoolTransaction, TransactionStatus, TransactionSource,
BlockHash, TxHash, TransactionFor, error::IntoPoolError,
use codec::{Decode, Encode};
use futures::{
compat::Compat,
future::{ready, FutureExt, TryFutureExt},
StreamExt as _,
};
use jsonrpc_pubsub::{manager::SubscriptionManager, typed::Subscriber, SubscriptionId};
use rpc::futures::{future::result, Future, Sink};
use sc_rpc_api::DenyUnsafe;
use sc_transaction_pool_api::{
error::IntoPoolError, BlockHash, InPoolTransaction, TransactionFor, TransactionPool,
TransactionSource, TransactionStatus, TxHash,
};
use sp_api::ProvideRuntimeApi;
use sp_core::Bytes;
use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr};
use sp_runtime::generic;
use sp_session::SessionKeys;
use self::error::{Error, FutureResult, Result};
/// Re-export the API for backward compatibility.
pub use sc_rpc_api::author::*;
use self::error::{Error, FutureResult, Result};
/// Authoring API
pub struct Author<P, Client> {
@@ -69,13 +72,7 @@ impl<P, Client> Author<P, Client> {
keystore: SyncCryptoStorePtr,
deny_unsafe: DenyUnsafe,
) -> Self {
Author {
client,
pool,
subscriptions,
keystore,
deny_unsafe,
}
Author { client, pool, subscriptions, keystore, deny_unsafe }
}
}
@@ -87,19 +84,14 @@ impl<P, Client> Author<P, Client> {
const TX_SOURCE: TransactionSource = TransactionSource::External;
impl<P, Client> AuthorApi<TxHash<P>, BlockHash<P>> for Author<P, Client>
where
P: TransactionPool + Sync + Send + 'static,
Client: HeaderBackend<P::Block> + ProvideRuntimeApi<P::Block> + Send + Sync + 'static,
Client::Api: SessionKeys<P::Block>,
where
P: TransactionPool + Sync + Send + 'static,
Client: HeaderBackend<P::Block> + ProvideRuntimeApi<P::Block> + Send + Sync + 'static,
Client::Api: SessionKeys<P::Block>,
{
type Metadata = crate::Metadata;
fn insert_key(
&self,
key_type: String,
suri: String,
public: Bytes,
) -> Result<()> {
fn insert_key(&self, key_type: String, suri: String, public: Bytes) -> Result<()> {
self.deny_unsafe.check_if_safe()?;
let key_type = key_type.as_str().try_into().map_err(|_| Error::BadKeyType)?;
@@ -112,20 +104,22 @@ impl<P, Client> AuthorApi<TxHash<P>, BlockHash<P>> for Author<P, Client>
self.deny_unsafe.check_if_safe()?;
let best_block_hash = self.client.info().best_hash;
self.client.runtime_api().generate_session_keys(
&generic::BlockId::Hash(best_block_hash),
None,
).map(Into::into).map_err(|e| Error::Client(Box::new(e)))
self.client
.runtime_api()
.generate_session_keys(&generic::BlockId::Hash(best_block_hash), None)
.map(Into::into)
.map_err(|e| Error::Client(Box::new(e)))
}
fn has_session_keys(&self, session_keys: Bytes) -> Result<bool> {
self.deny_unsafe.check_if_safe()?;
let best_block_hash = self.client.info().best_hash;
let keys = self.client.runtime_api().decode_session_keys(
&generic::BlockId::Hash(best_block_hash),
session_keys.to_vec(),
).map_err(|e| Error::Client(Box::new(e)))?
let keys = self
.client
.runtime_api()
.decode_session_keys(&generic::BlockId::Hash(best_block_hash), session_keys.to_vec())
.map_err(|e| Error::Client(Box::new(e)))?
.ok_or_else(|| Error::InvalidSessionKeys)?;
Ok(SyncCryptoStore::has_keys(&*self.keystore, &keys))
@@ -144,12 +138,15 @@ impl<P, Client> AuthorApi<TxHash<P>, BlockHash<P>> for Author<P, Client>
Err(err) => return Box::new(result(Err(err.into()))),
};
let best_block_hash = self.client.info().best_hash;
Box::new(self.pool
.submit_one(&generic::BlockId::hash(best_block_hash), TX_SOURCE, xt)
.compat()
.map_err(|e| e.into_pool_error()
.map(Into::into)
.unwrap_or_else(|e| error::Error::Verification(Box::new(e)).into()))
Box::new(
self.pool
.submit_one(&generic::BlockId::hash(best_block_hash), TX_SOURCE, xt)
.compat()
.map_err(|e| {
e.into_pool_error()
.map(Into::into)
.unwrap_or_else(|e| error::Error::Verification(Box::new(e)).into())
}),
)
}
@@ -163,7 +160,8 @@ impl<P, Client> AuthorApi<TxHash<P>, BlockHash<P>> for Author<P, Client>
) -> Result<Vec<TxHash<P>>> {
self.deny_unsafe.check_if_safe()?;
let hashes = bytes_or_hash.into_iter()
let hashes = bytes_or_hash
.into_iter()
.map(|x| match x {
hash::ExtrinsicOrHash::Hash(h) => Ok(h),
hash::ExtrinsicOrHash::Extrinsic(bytes) => {
@@ -173,32 +171,31 @@ impl<P, Client> AuthorApi<TxHash<P>, BlockHash<P>> for Author<P, Client>
})
.collect::<Result<Vec<_>>>()?;
Ok(
self.pool
.remove_invalid(&hashes)
.into_iter()
.map(|tx| tx.hash().clone())
.collect()
)
Ok(self
.pool
.remove_invalid(&hashes)
.into_iter()
.map(|tx| tx.hash().clone())
.collect())
}
fn watch_extrinsic(&self,
fn watch_extrinsic(
&self,
_metadata: Self::Metadata,
subscriber: Subscriber<TransactionStatus<TxHash<P>, BlockHash<P>>>,
xt: Bytes,
) {
let submit = || -> Result<_> {
let best_block_hash = self.client.info().best_hash;
let dxt = TransactionFor::<P>::decode(&mut &xt[..])
.map_err(error::Error::from)?;
Ok(
self.pool
.submit_and_watch(&generic::BlockId::hash(best_block_hash), TX_SOURCE, dxt)
.map_err(|e| e.into_pool_error()
let dxt = TransactionFor::<P>::decode(&mut &xt[..]).map_err(error::Error::from)?;
Ok(self
.pool
.submit_and_watch(&generic::BlockId::hash(best_block_hash), TX_SOURCE, dxt)
.map_err(|e| {
e.into_pool_error()
.map(error::Error::from)
.unwrap_or_else(|e| error::Error::Verification(Box::new(e)).into())
)
)
}))
};
let subscriptions = self.subscriptions.clone();
@@ -211,8 +208,7 @@ impl<P, Client> AuthorApi<TxHash<P>, BlockHash<P>> for Author<P, Client>
.map(move |result| match result {
Ok(watcher) => {
subscriptions.add(subscriber, move |sink| {
sink
.sink_map_err(|e| log::debug!("Subscription sink failed: {:?}", e))
sink.sink_map_err(|e| log::debug!("Subscription sink failed: {:?}", e))
.send_all(Compat::new(watcher))
.map(|_| ())
});
@@ -224,14 +220,20 @@ impl<P, Client> AuthorApi<TxHash<P>, BlockHash<P>> for Author<P, Client>
},
});
let res = self.subscriptions.executor()
let res = self
.subscriptions
.executor()
.execute(Box::new(Compat::new(future.map(|_| Ok(())))));
if res.is_err() {
warn!("Error spawning subscription RPC task.");
}
}
fn unwatch_extrinsic(&self, _metadata: Option<Self::Metadata>, id: SubscriptionId) -> Result<bool> {
fn unwatch_extrinsic(
&self,
_metadata: Option<Self::Metadata>,
id: SubscriptionId,
) -> Result<bool> {
Ok(self.subscriptions.cancel(id))
}
}
+51 -56
View File
@@ -18,37 +18,35 @@
use super::*;
use std::{mem, sync::Arc};
use assert_matches::assert_matches;
use codec::Encode;
use futures::{compat::Future01CompatExt, executor};
use rpc::futures::Stream as _;
use sc_transaction_pool::{BasicPool, FullChainApi};
use sp_core::{
ed25519, sr25519,
H256, blake2_256, hexdisplay::HexDisplay, testing::{ED25519, SR25519},
blake2_256,
crypto::{CryptoTypePublicPair, Pair, Public},
ed25519,
hexdisplay::HexDisplay,
sr25519,
testing::{ED25519, SR25519},
H256,
};
use sp_keystore::testing::KeyStore;
use rpc::futures::Stream as _;
use std::{mem, sync::Arc};
use substrate_test_runtime_client::{
self, AccountKeyring, runtime::{Extrinsic, Transfer, SessionKeys, Block},
DefaultTestClientBuilderExt, TestClientBuilderExt, Backend, Client,
self,
runtime::{Block, Extrinsic, SessionKeys, Transfer},
AccountKeyring, Backend, Client, DefaultTestClientBuilderExt, TestClientBuilderExt,
};
use sc_transaction_pool::{BasicPool, FullChainApi};
use futures::{executor, compat::Future01CompatExt};
fn uxt(sender: AccountKeyring, nonce: u64) -> Extrinsic {
let tx = Transfer {
amount: Default::default(),
nonce,
from: sender.into(),
to: Default::default(),
};
let tx =
Transfer { amount: Default::default(), nonce, from: sender.into(), to: Default::default() };
tx.into_signed_tx()
}
type FullTransactionPool = BasicPool<
FullChainApi<Client<Backend>, Block>,
Block,
>;
type FullTransactionPool = BasicPool<FullChainApi<Client<Backend>, Block>, Block>;
struct TestSetup {
pub client: Arc<Client<Backend>>,
@@ -63,18 +61,9 @@ impl Default for TestSetup {
let client = Arc::new(client_builder.set_keystore(keystore.clone()).build());
let spawner = sp_core::testing::TaskExecutor::new();
let pool = BasicPool::new_full(
Default::default(),
true.into(),
None,
spawner,
client.clone(),
);
TestSetup {
client,
keystore,
pool,
}
let pool =
BasicPool::new_full(Default::default(), true.into(), None, spawner, client.clone());
TestSetup { client, keystore, pool }
}
}
@@ -100,9 +89,7 @@ fn submit_transaction_should_not_cause_error() {
AuthorApi::submit_extrinsic(&p, xt.clone().into()).wait(),
Ok(h2) if h == h2
);
assert!(
AuthorApi::submit_extrinsic(&p, xt.into()).wait().is_err()
);
assert!(AuthorApi::submit_extrinsic(&p, xt.into()).wait().is_err());
}
#[test]
@@ -115,14 +102,12 @@ fn submit_rich_transaction_should_not_cause_error() {
AuthorApi::submit_extrinsic(&p, xt.clone().into()).wait(),
Ok(h2) if h == h2
);
assert!(
AuthorApi::submit_extrinsic(&p, xt.into()).wait().is_err()
);
assert!(AuthorApi::submit_extrinsic(&p, xt.into()).wait().is_err());
}
#[test]
fn should_watch_extrinsic() {
//given
// given
let setup = TestSetup::default();
let p = setup.author();
@@ -175,14 +160,18 @@ fn should_watch_extrinsic() {
#[test]
fn should_return_watch_validation_error() {
//given
// given
let setup = TestSetup::default();
let p = setup.author();
let (subscriber, id_rx, _data) = jsonrpc_pubsub::typed::Subscriber::new_test("test");
// when
p.watch_extrinsic(Default::default(), subscriber, uxt(AccountKeyring::Alice, 179).encode().into());
p.watch_extrinsic(
Default::default(),
subscriber,
uxt(AccountKeyring::Alice, 179).encode().into(),
);
// then
let res = executor::block_on(id_rx.compat()).unwrap();
@@ -215,11 +204,13 @@ fn should_remove_extrinsics() {
assert_eq!(setup.pool.status().ready, 3);
// now remove all 3
let removed = p.remove_extrinsic(vec![
hash::ExtrinsicOrHash::Hash(hash3),
// Removing this one will also remove ex2
hash::ExtrinsicOrHash::Extrinsic(ex1.encode().into()),
]).unwrap();
let removed = p
.remove_extrinsic(vec![
hash::ExtrinsicOrHash::Hash(hash3),
// Removing this one will also remove ex2
hash::ExtrinsicOrHash::Extrinsic(ex1.encode().into()),
])
.unwrap();
assert_eq!(removed.len(), 3);
}
@@ -235,11 +226,13 @@ fn should_insert_key() {
String::from_utf8(ED25519.0.to_vec()).expect("Keytype is a valid string"),
suri.to_string(),
key_pair.public().0.to_vec().into(),
).expect("Insert key");
)
.expect("Insert key");
let public_keys = SyncCryptoStore::keys(&*setup.keystore, ED25519).unwrap();
assert!(public_keys.contains(&CryptoTypePublicPair(ed25519::CRYPTO_ID, key_pair.public().to_raw_vec())));
assert!(public_keys
.contains(&CryptoTypePublicPair(ed25519::CRYPTO_ID, key_pair.public().to_raw_vec())));
}
#[test]
@@ -249,14 +242,16 @@ fn should_rotate_keys() {
let new_public_keys = p.rotate_keys().expect("Rotates the keys");
let session_keys = SessionKeys::decode(&mut &new_public_keys[..])
.expect("SessionKeys decode successfully");
let session_keys =
SessionKeys::decode(&mut &new_public_keys[..]).expect("SessionKeys decode successfully");
let ed25519_public_keys = SyncCryptoStore::keys(&*setup.keystore, ED25519).unwrap();
let sr25519_public_keys = SyncCryptoStore::keys(&*setup.keystore, SR25519).unwrap();
assert!(ed25519_public_keys.contains(&CryptoTypePublicPair(ed25519::CRYPTO_ID, session_keys.ed25519.to_raw_vec())));
assert!(sr25519_public_keys.contains(&CryptoTypePublicPair(sr25519::CRYPTO_ID, session_keys.sr25519.to_raw_vec())));
assert!(ed25519_public_keys
.contains(&CryptoTypePublicPair(ed25519::CRYPTO_ID, session_keys.ed25519.to_raw_vec())));
assert!(sr25519_public_keys
.contains(&CryptoTypePublicPair(sr25519::CRYPTO_ID, session_keys.sr25519.to_raw_vec())));
}
#[test]
@@ -264,10 +259,8 @@ fn test_has_session_keys() {
let setup = TestSetup::default();
let p = setup.author();
let non_existent_public_keys = TestSetup::default()
.author()
.rotate_keys()
.expect("Rotates the keys");
let non_existent_public_keys =
TestSetup::default().author().rotate_keys().expect("Rotates the keys");
let public_keys = p.rotate_keys().expect("Rotates the keys");
let test_vectors = vec![
@@ -295,7 +288,8 @@ fn test_has_key() {
String::from_utf8(ED25519.0.to_vec()).expect("Keytype is a valid string"),
suri.to_string(),
alice_key_pair.public().0.to_vec().into(),
).expect("Insert key");
)
.expect("Insert key");
let bob_key_pair = ed25519::Pair::from_string("//Bob", None).expect("Generates keypair");
let test_vectors = vec![
@@ -310,7 +304,8 @@ fn test_has_key() {
p.has_key(
key,
String::from_utf8(key_type.0.to_vec()).expect("Keytype is a valid string"),
).map_err(|e| mem::discriminant(&e)),
)
.map_err(|e| mem::discriminant(&e)),
);
}
}