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
@@ -17,27 +17,31 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use std::{
collections::{HashSet, HashMap},
collections::{HashMap, HashSet},
hash,
sync::Arc,
};
use serde::Serialize;
use futures::channel::mpsc::{channel, Sender};
use parking_lot::{Mutex, RwLock};
use retain_mut::RetainMut;
use sc_transaction_pool_api::{error, PoolStatus};
use serde::Serialize;
use sp_runtime::{
generic::BlockId,
traits::{self, SaturatedConversion},
transaction_validity::{TransactionTag as Tag, ValidTransaction, TransactionSource},
transaction_validity::{TransactionSource, TransactionTag as Tag, ValidTransaction},
};
use sc_transaction_pool_api::{error, PoolStatus};
use wasm_timer::Instant;
use futures::channel::mpsc::{channel, Sender};
use retain_mut::RetainMut;
use super::{
base_pool::{self as base, PruneStatus}, watcher::Watcher,
listener::Listener, rotator::PoolRotator,
pool::{EventStream, Options, ChainApi, BlockHash, ExtrinsicHash, ExtrinsicFor, TransactionFor},
base_pool::{self as base, PruneStatus},
listener::Listener,
pool::{
BlockHash, ChainApi, EventStream, ExtrinsicFor, ExtrinsicHash, Options, TransactionFor,
},
rotator::PoolRotator,
watcher::Watcher,
};
/// Pre-validated transaction. Validated pool only accepts transactions wrapped in this enum.
@@ -72,19 +76,14 @@ impl<Hash, Ex, Error> ValidatedTransaction<Hash, Ex, Error> {
requires: validity.requires,
provides: validity.provides,
propagate: validity.propagate,
valid_till: at
.saturated_into::<u64>()
.saturating_add(validity.longevity),
valid_till: at.saturated_into::<u64>().saturating_add(validity.longevity),
})
}
}
/// A type of validated transaction stored in the pool.
pub type ValidatedTransactionFor<B> = ValidatedTransaction<
ExtrinsicHash<B>,
ExtrinsicFor<B>,
<B as ChainApi>::Error,
>;
pub type ValidatedTransactionFor<B> =
ValidatedTransaction<ExtrinsicHash<B>, ExtrinsicFor<B>, <B as ChainApi>::Error>;
/// A closure that returns true if the local node is a validator that can author blocks.
pub struct IsValidator(Box<dyn Fn() -> bool + Send + Sync>);
@@ -107,10 +106,7 @@ pub struct ValidatedPool<B: ChainApi> {
is_validator: IsValidator,
options: Options,
listener: RwLock<Listener<ExtrinsicHash<B>, B>>,
pool: RwLock<base::BasePool<
ExtrinsicHash<B>,
ExtrinsicFor<B>,
>>,
pool: RwLock<base::BasePool<ExtrinsicHash<B>, ExtrinsicFor<B>>>,
import_notification_sinks: Mutex<Vec<Sender<ExtrinsicHash<B>>>>,
rotator: PoolRotator<ExtrinsicHash<B>>,
}
@@ -142,7 +138,7 @@ impl<B: ChainApi> ValidatedPool<B> {
}
/// Bans given set of hashes.
pub fn ban(&self, now: &Instant, hashes: impl IntoIterator<Item=ExtrinsicHash<B>>) {
pub fn ban(&self, now: &Instant, hashes: impl IntoIterator<Item = ExtrinsicHash<B>>) {
self.rotator.ban(now, hashes)
}
@@ -173,9 +169,10 @@ impl<B: ChainApi> ValidatedPool<B> {
/// Imports a bunch of pre-validated transactions to the pool.
pub fn submit(
&self,
txs: impl IntoIterator<Item=ValidatedTransactionFor<B>>,
txs: impl IntoIterator<Item = ValidatedTransactionFor<B>>,
) -> Vec<Result<ExtrinsicHash<B>, B::Error>> {
let results = txs.into_iter()
let results = txs
.into_iter()
.map(|validated_tx| self.submit_one(validated_tx))
.collect::<Vec<_>>();
@@ -186,10 +183,14 @@ impl<B: ChainApi> ValidatedPool<B> {
Default::default()
};
results.into_iter().map(|res| match res {
Ok(ref hash) if removed.contains(hash) => Err(error::Error::ImmediatelyDropped.into()),
other => other,
}).collect()
results
.into_iter()
.map(|res| match res {
Ok(ref hash) if removed.contains(hash) =>
Err(error::Error::ImmediatelyDropped.into()),
other => other,
})
.collect()
}
/// Submit single pre-validated transaction to the pool.
@@ -197,30 +198,28 @@ impl<B: ChainApi> ValidatedPool<B> {
match tx {
ValidatedTransaction::Valid(tx) => {
if !tx.propagate && !(self.is_validator.0)() {
return Err(error::Error::Unactionable.into());
return Err(error::Error::Unactionable.into())
}
let imported = self.pool.write().import(tx)?;
if let base::Imported::Ready { ref hash, .. } = imported {
self.import_notification_sinks.lock()
.retain_mut(|sink| {
match sink.try_send(*hash) {
Ok(()) => true,
Err(e) => {
if e.is_full() {
log::warn!(
target: "txpool",
"[{:?}] Trying to notify an import but the channel is full",
hash,
);
true
} else {
false
}
self.import_notification_sinks.lock().retain_mut(|sink| {
match sink.try_send(*hash) {
Ok(()) => true,
Err(e) =>
if e.is_full() {
log::warn!(
target: "txpool",
"[{:?}] Trying to notify an import but the channel is full",
hash,
);
true
} else {
false
},
}
});
}
});
}
let mut listener = self.listener.write();
@@ -244,8 +243,8 @@ impl<B: ChainApi> ValidatedPool<B> {
let future_limit = &self.options.future;
log::debug!(target: "txpool", "Pool Status: {:?}", status);
if ready_limit.is_exceeded(status.ready, status.ready_bytes)
|| future_limit.is_exceeded(status.future, status.future_bytes)
if ready_limit.is_exceeded(status.ready, status.ready_bytes) ||
future_limit.is_exceeded(status.future, status.future_bytes)
{
log::debug!(
target: "txpool",
@@ -257,8 +256,11 @@ impl<B: ChainApi> ValidatedPool<B> {
// clean up the pool
let removed = {
let mut pool = self.pool.write();
let removed = pool.enforce_limits(ready_limit, future_limit)
.into_iter().map(|x| x.hash).collect::<HashSet<_>>();
let removed = pool
.enforce_limits(ready_limit, future_limit)
.into_iter()
.map(|x| x.hash)
.collect::<HashSet<_>>();
// ban all removed transactions
self.rotator.ban(&Instant::now(), removed.iter().copied());
removed
@@ -305,9 +307,17 @@ impl<B: ChainApi> ValidatedPool<B> {
///
/// Removes and then submits passed transactions and all dependent transactions.
/// Transactions that are missing from the pool are not submitted.
pub fn resubmit(&self, mut updated_transactions: HashMap<ExtrinsicHash<B>, ValidatedTransactionFor<B>>) {
pub fn resubmit(
&self,
mut updated_transactions: HashMap<ExtrinsicHash<B>, ValidatedTransactionFor<B>>,
) {
#[derive(Debug, Clone, Copy, PartialEq)]
enum Status { Future, Ready, Failed, Dropped }
enum Status {
Future,
Ready,
Failed,
Dropped,
}
let (mut initial_statuses, final_statuses) = {
let mut pool = self.pool.write();
@@ -322,7 +332,11 @@ impl<B: ChainApi> ValidatedPool<B> {
let mut initial_statuses = HashMap::new();
let mut txs_to_resubmit = Vec::with_capacity(updated_transactions.len());
while !updated_transactions.is_empty() {
let hash = updated_transactions.keys().next().cloned().expect("transactions is not empty; qed");
let hash = updated_transactions
.keys()
.next()
.cloned()
.expect("transactions is not empty; qed");
// note we are not considering tx with hash invalid here - we just want
// to remove it along with dependent transactions and `remove_subtree()`
@@ -390,7 +404,8 @@ impl<B: ChainApi> ValidatedPool<B> {
final_statuses.insert(hash, Status::Failed);
},
},
ValidatedTransaction::Invalid(_, _) | ValidatedTransaction::Unknown(_, _) => {
ValidatedTransaction::Invalid(_, _) |
ValidatedTransaction::Unknown(_, _) => {
final_statuses.insert(hash, Status::Failed);
},
}
@@ -425,12 +440,13 @@ impl<B: ChainApi> ValidatedPool<B> {
/// For each extrinsic, returns tags that it provides (if known), or None (if it is unknown).
pub fn extrinsics_tags(&self, hashes: &[ExtrinsicHash<B>]) -> Vec<Option<Vec<Tag>>> {
self.pool.read()
self.pool
.read()
.by_hashes(&hashes)
.into_iter()
.map(|existing_in_pool|
.map(|existing_in_pool| {
existing_in_pool.map(|transaction| transaction.provides.to_vec())
)
})
.collect()
}
@@ -442,7 +458,7 @@ impl<B: ChainApi> ValidatedPool<B> {
/// Prunes ready transactions that provide given list of tags.
pub fn prune_tags(
&self,
tags: impl IntoIterator<Item=Tag>,
tags: impl IntoIterator<Item = Tag>,
) -> Result<PruneStatus<ExtrinsicHash<B>, ExtrinsicFor<B>>, B::Error> {
// Perform tag-based pruning in the base pool
let status = self.pool.write().prune_tags(tags);
@@ -465,7 +481,7 @@ impl<B: ChainApi> ValidatedPool<B> {
pub fn resubmit_pruned(
&self,
at: &BlockId<B::Block>,
known_imported_hashes: impl IntoIterator<Item=ExtrinsicHash<B>> + Clone,
known_imported_hashes: impl IntoIterator<Item = ExtrinsicHash<B>> + Clone,
pruned_hashes: Vec<ExtrinsicHash<B>>,
pruned_xts: Vec<ValidatedTransactionFor<B>>,
) -> Result<(), B::Error> {
@@ -475,13 +491,12 @@ impl<B: ChainApi> ValidatedPool<B> {
let results = self.submit(pruned_xts);
// Collect the hashes of transactions that now became invalid (meaning that they are successfully pruned).
let hashes = results
.into_iter()
.enumerate()
.filter_map(|(idx, r)| match r.map_err(error::IntoPoolError::into_pool_error) {
let hashes = results.into_iter().enumerate().filter_map(|(idx, r)| {
match r.map_err(error::IntoPoolError::into_pool_error) {
Err(Ok(error::Error::InvalidTransaction(_))) => Some(pruned_hashes[idx]),
_ => None,
});
}
});
// Fire `pruned` notifications for collected hashes and make sure to include
// `known_imported_hashes` since they were just imported as part of the block.
let hashes = hashes.chain(known_imported_hashes.into_iter());
@@ -497,9 +512,11 @@ impl<B: ChainApi> ValidatedPool<B> {
pub fn fire_pruned(
&self,
at: &BlockId<B::Block>,
hashes: impl Iterator<Item=ExtrinsicHash<B>>,
hashes: impl Iterator<Item = ExtrinsicHash<B>>,
) -> Result<(), B::Error> {
let header_hash = self.api.block_id_to_hash(at)?
let header_hash = self
.api
.block_id_to_hash(at)?
.ok_or_else(|| error::Error::InvalidBlockId(format!("{:?}", at)))?;
let mut listener = self.listener.write();
let mut set = HashSet::with_capacity(hashes.size_hint().0);
@@ -520,7 +537,9 @@ impl<B: ChainApi> ValidatedPool<B> {
/// Note this function does not remove transactions that are already included in the chain.
/// See `prune_tags` if you want this.
pub fn clear_stale(&self, at: &BlockId<B::Block>) -> Result<(), B::Error> {
let block_number = self.api.block_id_to_number(at)?
let block_number = self
.api
.block_id_to_number(at)?
.ok_or_else(|| error::Error::InvalidBlockId(format!("{:?}", at)))?
.saturated_into::<u64>();
let now = Instant::now();
@@ -589,7 +608,7 @@ impl<B: ChainApi> ValidatedPool<B> {
pub fn remove_invalid(&self, hashes: &[ExtrinsicHash<B>]) -> Vec<TransactionFor<B>> {
// early exit in case there is no invalid transactions.
if hashes.is_empty() {
return vec![];
return vec![]
}
log::debug!(target: "txpool", "Removing invalid transactions: {:?}", hashes);
@@ -610,13 +629,15 @@ impl<B: ChainApi> ValidatedPool<B> {
}
/// Get an iterator for ready transactions ordered by priority
pub fn ready(&self) -> impl Iterator<Item=TransactionFor<B>> + Send {
pub fn ready(&self) -> impl Iterator<Item = TransactionFor<B>> + Send {
self.pool.read().ready()
}
/// Returns a Vec of hashes and extrinsics in the future pool.
pub fn futures(&self) -> Vec<(ExtrinsicHash<B>, ExtrinsicFor<B>)> {
self.pool.read().futures()
self.pool
.read()
.futures()
.map(|tx| (tx.hash.clone(), tx.data.clone()))
.collect()
}
@@ -639,10 +660,8 @@ impl<B: ChainApi> ValidatedPool<B> {
}
}
fn fire_events<H, B, Ex>(
listener: &mut Listener<H, B>,
imported: &base::Imported<H, Ex>,
) where
fn fire_events<H, B, Ex>(listener: &mut Listener<H, B>, imported: &base::Imported<H, Ex>)
where
H: hash::Hash + Eq + traits::Member + Serialize,
B: ChainApi,
{
@@ -653,8 +672,6 @@ fn fire_events<H, B, Ex>(
removed.into_iter().for_each(|r| listener.dropped(&r.hash, Some(hash)));
promoted.into_iter().for_each(|p| listener.ready(p, None));
},
base::Imported::Future { ref hash } => {
listener.future(hash)
},
base::Imported::Future { ref hash } => listener.future(hash),
}
}