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
@@ -16,12 +16,14 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use std::collections::{BTreeMap, HashMap};
use std::iter::FromIterator;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use std::{
collections::{BTreeMap, HashMap},
iter::FromIterator,
marker::PhantomData,
pin::Pin,
sync::Arc,
time::Duration,
};
use finality_grandpa::{
round::State as RoundState, voter, voter_set::VoterSet, BlockNumberOps, Error as GrandpaError,
@@ -44,8 +46,10 @@ use sp_finality_grandpa::{
AuthorityId, AuthoritySignature, Equivocation, EquivocationProof, GrandpaApi, RoundNumber,
SetId, GRANDPA_ENGINE_ID,
};
use sp_runtime::generic::BlockId;
use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor, Zero};
use sp_runtime::{
generic::BlockId,
traits::{Block as BlockT, Header as HeaderT, NumberFor, Zero},
};
use crate::{
authorities::{AuthoritySet, SharedAuthoritySet},
@@ -105,13 +109,11 @@ impl<Block: BlockT> Encode for CompletedRounds<Block> {
impl<Block: BlockT> parity_scale_codec::EncodeLike for CompletedRounds<Block> {}
impl<Block: BlockT> Decode for CompletedRounds<Block> {
fn decode<I: parity_scale_codec::Input>(value: &mut I) -> Result<Self, parity_scale_codec::Error> {
fn decode<I: parity_scale_codec::Input>(
value: &mut I,
) -> Result<Self, parity_scale_codec::Error> {
<(Vec<CompletedRound<Block>>, SetId, Vec<AuthorityId>)>::decode(value)
.map(|(rounds, set_id, voters)| CompletedRounds {
rounds,
set_id,
voters,
})
.map(|(rounds, set_id, voters)| CompletedRounds { rounds, set_id, voters })
}
}
@@ -121,9 +123,7 @@ impl<Block: BlockT> CompletedRounds<Block> {
genesis: CompletedRound<Block>,
set_id: SetId,
voters: &AuthoritySet<Block::Hash, NumberFor<Block>>,
)
-> CompletedRounds<Block>
{
) -> CompletedRounds<Block> {
let mut rounds = Vec::with_capacity(NUM_LAST_COMPLETED_ROUNDS);
rounds.push(genesis);
@@ -137,13 +137,14 @@ impl<Block: BlockT> CompletedRounds<Block> {
}
/// Iterate over all completed rounds.
pub fn iter(&self) -> impl Iterator<Item=&CompletedRound<Block>> {
pub fn iter(&self) -> impl Iterator<Item = &CompletedRound<Block>> {
self.rounds.iter().rev()
}
/// Returns the last (latest) completed round.
pub fn last(&self) -> &CompletedRound<Block> {
self.rounds.first()
self.rounds
.first()
.expect("inner is never empty; always contains at least genesis; qed")
}
@@ -152,10 +153,11 @@ impl<Block: BlockT> CompletedRounds<Block> {
pub fn push(&mut self, completed_round: CompletedRound<Block>) {
use std::cmp::Reverse;
match self.rounds.binary_search_by_key(
&Reverse(completed_round.number),
|completed_round| Reverse(completed_round.number),
) {
match self
.rounds
.binary_search_by_key(&Reverse(completed_round.number), |completed_round| {
Reverse(completed_round.number)
}) {
Ok(idx) => self.rounds[idx] = completed_round,
Err(idx) => self.rounds.insert(idx, completed_round),
};
@@ -215,37 +217,31 @@ impl<Block: BlockT> VoterSetState<Block> {
let mut current_rounds = CurrentRounds::new();
current_rounds.insert(1, HasVoted::No);
VoterSetState::Live {
completed_rounds,
current_rounds,
}
VoterSetState::Live { completed_rounds, current_rounds }
}
/// Returns the last completed rounds.
pub(crate) fn completed_rounds(&self) -> CompletedRounds<Block> {
match self {
VoterSetState::Live { completed_rounds, .. } =>
completed_rounds.clone(),
VoterSetState::Paused { completed_rounds } =>
completed_rounds.clone(),
VoterSetState::Live { completed_rounds, .. } => completed_rounds.clone(),
VoterSetState::Paused { completed_rounds } => completed_rounds.clone(),
}
}
/// Returns the last completed round.
pub(crate) fn last_completed_round(&self) -> CompletedRound<Block> {
match self {
VoterSetState::Live { completed_rounds, .. } =>
completed_rounds.last().clone(),
VoterSetState::Paused { completed_rounds } =>
completed_rounds.last().clone(),
VoterSetState::Live { completed_rounds, .. } => completed_rounds.last().clone(),
VoterSetState::Paused { completed_rounds } => completed_rounds.last().clone(),
}
}
/// Returns the voter set state validating that it includes the given round
/// in current rounds and that the voter isn't paused.
pub fn with_current_round(&self, round: RoundNumber)
-> Result<(&CompletedRounds<Block>, &CurrentRounds<Block>), Error>
{
pub fn with_current_round(
&self,
round: RoundNumber,
) -> Result<(&CompletedRounds<Block>, &CurrentRounds<Block>), Error> {
if let VoterSetState::Live { completed_rounds, current_rounds } = self {
if current_rounds.contains_key(&round) {
Ok((completed_rounds, current_rounds))
@@ -284,10 +280,9 @@ impl<Block: BlockT> HasVoted<Block> {
/// Returns the proposal we should vote with (if any.)
pub fn propose(&self) -> Option<&PrimaryPropose<Block>> {
match self {
HasVoted::Yes(_, Vote::Propose(propose)) =>
Some(propose),
HasVoted::Yes(_, Vote::Prevote(propose, _)) | HasVoted::Yes(_, Vote::Precommit(propose, _, _)) =>
propose.as_ref(),
HasVoted::Yes(_, Vote::Propose(propose)) => Some(propose),
HasVoted::Yes(_, Vote::Prevote(propose, _)) |
HasVoted::Yes(_, Vote::Precommit(propose, _, _)) => propose.as_ref(),
_ => None,
}
}
@@ -295,8 +290,8 @@ impl<Block: BlockT> HasVoted<Block> {
/// Returns the prevote we should vote with (if any.)
pub fn prevote(&self) -> Option<&Prevote<Block>> {
match self {
HasVoted::Yes(_, Vote::Prevote(_, prevote)) | HasVoted::Yes(_, Vote::Precommit(_, prevote, _)) =>
Some(prevote),
HasVoted::Yes(_, Vote::Prevote(_, prevote)) |
HasVoted::Yes(_, Vote::Precommit(_, prevote, _)) => Some(prevote),
_ => None,
}
}
@@ -304,8 +299,7 @@ impl<Block: BlockT> HasVoted<Block> {
/// Returns the precommit we should vote with (if any.)
pub fn precommit(&self) -> Option<&Precommit<Block>> {
match self {
HasVoted::Yes(_, Vote::Precommit(_, _, precommit)) =>
Some(precommit),
HasVoted::Yes(_, Vote::Precommit(_, _, precommit)) => Some(precommit),
_ => None,
}
}
@@ -376,21 +370,21 @@ impl<Block: BlockT> SharedVoterSetState<Block> {
/// Return vote status information for the current round.
pub(crate) fn has_voted(&self, round: RoundNumber) -> HasVoted<Block> {
match &*self.inner.read() {
VoterSetState::Live { current_rounds, .. } => {
current_rounds.get(&round).and_then(|has_voted| match has_voted {
HasVoted::Yes(id, vote) =>
Some(HasVoted::Yes(id.clone(), vote.clone())),
VoterSetState::Live { current_rounds, .. } => current_rounds
.get(&round)
.and_then(|has_voted| match has_voted {
HasVoted::Yes(id, vote) => Some(HasVoted::Yes(id.clone(), vote.clone())),
_ => None,
})
.unwrap_or(HasVoted::No)
},
.unwrap_or(HasVoted::No),
_ => HasVoted::No,
}
}
// NOTE: not exposed outside of this module intentionally.
fn with<F, R>(&self, f: F) -> R
where F: FnOnce(&mut VoterSetState<Block>) -> R
where
F: FnOnce(&mut VoterSetState<Block>) -> R,
{
f(&mut *self.inner.write())
}
@@ -452,8 +446,9 @@ impl<BE, Block: BlockT, C, N: NetworkT<Block>, SC, VR> Environment<BE, Block, C,
/// Updates the voter set state using the given closure. The write lock is
/// held during evaluation of the closure and the environment's voter set
/// state is set to its result if successful.
pub(crate) fn update_voter_set_state<F>(&self, f: F) -> Result<(), Error> where
F: FnOnce(&VoterSetState<Block>) -> Result<Option<VoterSetState<Block>>, Error>
pub(crate) fn update_voter_set_state<F>(&self, f: F) -> Result<(), Error>
where
F: FnOnce(&VoterSetState<Block>) -> Result<Option<VoterSetState<Block>>, Error>,
{
self.voter_set_state.with(|voter_set_state| {
if let Some(set_state) = f(&voter_set_state)? {
@@ -461,7 +456,9 @@ impl<BE, Block: BlockT, C, N: NetworkT<Block>, SC, VR> Environment<BE, Block, C,
if let Some(metrics) = self.metrics.as_ref() {
if let VoterSetState::Live { completed_rounds, .. } = voter_set_state {
let highest = completed_rounds.rounds.iter()
let highest = completed_rounds
.rounds
.iter()
.map(|round| round.number)
.max()
.expect("There is always one completed round (genesis); qed");
@@ -497,7 +494,7 @@ where
if *equivocation.offender() == local_id {
return Err(Error::Safety(
"Refraining from sending equivocation report for our own equivocation.".into(),
));
))
}
}
@@ -520,11 +517,8 @@ where
// find the hash of the latest block in the current set
let current_set_latest_hash = match next_change {
Some((_, n)) if n.is_zero() => {
return Err(Error::Safety(
"Authority set change signalled at genesis.".to_string(),
))
}
Some((_, n)) if n.is_zero() =>
return Err(Error::Safety("Authority set change signalled at genesis.".to_string())),
// the next set starts at `n` so the current one lasts until `n - 1`. if
// `n` is later than the best block, then the current set is still live
// at best block.
@@ -538,14 +532,15 @@ where
// its parent block is the last block in the current set
*header.parent_hash()
}
},
// there is no pending change, the latest block for the current set is
// the best block.
None => best_block_hash,
};
// generate key ownership proof at that block
let key_owner_proof = match self.client
let key_owner_proof = match self
.client
.runtime_api()
.generate_key_ownership_proof(
&BlockId::Hash(current_set_latest_hash),
@@ -557,15 +552,12 @@ where
Some(proof) => proof,
None => {
debug!(target: "afg", "Equivocation offender is not part of the authority set.");
return Ok(());
}
return Ok(())
},
};
// submit equivocation report at **best** block
let equivocation_proof = EquivocationProof::new(
authority_set.set_id,
equivocation,
);
let equivocation_proof = EquivocationProof::new(authority_set.set_id, equivocation);
self.client
.runtime_api()
@@ -608,7 +600,9 @@ pub(crate) fn ancestry<Block: BlockT, Client>(
where
Client: HeaderMetadata<Block, Error = sp_blockchain::Error>,
{
if base == block { return Err(GrandpaError::NotDescendent) }
if base == block {
return Err(GrandpaError::NotDescendent)
}
let tree_route_res = sp_blockchain::tree_route(&**client, block, base);
@@ -618,22 +612,17 @@ where
debug!(target: "afg", "Encountered error computing ancestry between block {:?} and base {:?}: {:?}",
block, base, e);
return Err(GrandpaError::NotDescendent);
}
return Err(GrandpaError::NotDescendent)
},
};
if tree_route.common_block().hash != base {
return Err(GrandpaError::NotDescendent);
return Err(GrandpaError::NotDescendent)
}
// skip one because our ancestry is meant to start from the parent of `block`,
// and `tree_route` includes it.
Ok(tree_route
.retracted()
.iter()
.skip(1)
.map(|e| e.hash)
.collect())
Ok(tree_route.retracted().iter().skip(1).map(|e| e.hash).collect())
}
impl<B, Block, C, N, SC, VR> voter::Environment<Block::Hash, NumberFor<Block>>
@@ -699,7 +688,7 @@ where
// before activating the new set. the `authority_set` is updated immediately thus
// we restrict the voter based on that.
if set_id != authority_set.set_id() {
return Ok(None);
return Ok(None)
}
best_chain_containing(block, client, authority_set, select_chain, voting_rule)
@@ -718,13 +707,12 @@ where
let local_id = local_authority_id(&self.voters, self.config.keystore.as_ref());
let has_voted = match self.voter_set_state.has_voted(round) {
HasVoted::Yes(id, vote) => {
HasVoted::Yes(id, vote) =>
if local_id.as_ref().map(|k| k == &id).unwrap_or(false) {
HasVoted::Yes(id, vote)
} else {
HasVoted::No
}
},
},
HasVoted::No => HasVoted::No,
};
@@ -756,14 +744,17 @@ where
// schedule incoming messages from the network to be held until
// corresponding blocks are imported.
let incoming = Box::pin(UntilVoteTargetImported::new(
self.client.import_notification_stream(),
self.network.clone(),
self.client.clone(),
incoming,
"round",
None,
).map_err(Into::into));
let incoming = Box::pin(
UntilVoteTargetImported::new(
self.client.import_notification_stream(),
self.network.clone(),
self.client.clone(),
incoming,
"round",
None,
)
.map_err(Into::into),
);
// schedule network message cleanup when sink drops.
let outgoing = Box::pin(outgoing.sink_err_into());
@@ -789,18 +780,20 @@ where
self.update_voter_set_state(|voter_set_state| {
let (completed_rounds, current_rounds) = voter_set_state.with_current_round(round)?;
let current_round = current_rounds.get(&round)
let current_round = current_rounds
.get(&round)
.expect("checked in with_current_round that key exists; qed.");
if !current_round.can_propose() {
// we've already proposed in this round (in a previous run),
// ignore the given vote and don't update the voter set
// state
return Ok(None);
return Ok(None)
}
let mut current_rounds = current_rounds.clone();
let current_round = current_rounds.get_mut(&round)
let current_round = current_rounds
.get_mut(&round)
.expect("checked previously that key exists; qed.");
*current_round = HasVoted::Yes(local_id, Vote::Propose(propose));
@@ -849,7 +842,7 @@ where
// we've already prevoted in this round (in a previous run),
// ignore the given vote and don't update the voter set
// state
return Ok(None);
return Ok(None)
}
// report to telemetry and prometheus
@@ -858,7 +851,8 @@ where
let propose = current_round.propose();
let mut current_rounds = current_rounds.clone();
let current_round = current_rounds.get_mut(&round)
let current_round = current_rounds
.get_mut(&round)
.expect("checked previously that key exists; qed.");
*current_round = HasVoted::Yes(local_id, Vote::Prevote(propose.cloned(), prevote));
@@ -911,7 +905,7 @@ where
// we've already precommitted in this round (in a previous run),
// ignore the given vote and don't update the voter set
// state
return Ok(None);
return Ok(None)
}
// report to telemetry and prometheus
@@ -922,12 +916,13 @@ where
HasVoted::Yes(_, Vote::Prevote(_, prevote)) => prevote,
_ => {
let msg = "Voter precommitting before prevoting.";
return Err(Error::Safety(msg.to_string()));
}
return Err(Error::Safety(msg.to_string()))
},
};
let mut current_rounds = current_rounds.clone();
let current_round = current_rounds.get_mut(&round)
let current_round = current_rounds
.get_mut(&round)
.expect("checked previously that key exists; qed.");
*current_round = HasVoted::Yes(
@@ -973,7 +968,7 @@ where
(completed_rounds, current_rounds)
} else {
let msg = "Voter acting while in paused state.";
return Err(Error::Safety(msg.to_string()));
return Err(Error::Safety(msg.to_string()))
};
let mut completed_rounds = completed_rounds.clone();
@@ -998,10 +993,7 @@ where
current_rounds.insert(round + 1, HasVoted::No);
}
let set_state = VoterSetState::<Block>::Live {
completed_rounds,
current_rounds,
};
let set_state = VoterSetState::<Block>::Live { completed_rounds, current_rounds };
crate::aux_schema::write_voter_set_state(&*self.client, &set_state)?;
@@ -1038,21 +1030,21 @@ where
(completed_rounds, current_rounds)
} else {
let msg = "Voter acting while in paused state.";
return Err(Error::Safety(msg.to_string()));
return Err(Error::Safety(msg.to_string()))
};
let mut completed_rounds = completed_rounds.clone();
if let Some(already_completed) = completed_rounds.rounds
.iter_mut().find(|r| r.number == round)
if let Some(already_completed) =
completed_rounds.rounds.iter_mut().find(|r| r.number == round)
{
let n_existing_votes = already_completed.votes.len();
// the interface of Environment guarantees that the previous `historical_votes`
// from `completable` is a prefix of what is passed to `concluded`.
already_completed.votes.extend(
historical_votes.seen().iter().skip(n_existing_votes).cloned()
);
already_completed
.votes
.extend(historical_votes.seen().iter().skip(n_existing_votes).cloned());
already_completed.state = state;
crate::aux_schema::write_concluded_round(&*self.client, &already_completed)?;
}
@@ -1161,8 +1153,8 @@ where
block,
);
return Ok(None);
}
return Ok(None)
},
};
// we refuse to vote beyond the current limit number where transitions are scheduled to occur.
@@ -1195,7 +1187,7 @@ where
}
if *target_header.number() == target_number {
break;
break
}
target_header = client
@@ -1230,15 +1222,15 @@ where
restricted_number < target_header.number()
})
.or_else(|| Some((target_header.hash(), *target_header.number())))
}
},
Ok(None) => {
debug!(target: "afg", "Encountered error finding best chain containing {:?}: couldn't find target block", block);
None
}
},
Err(e) => {
debug!(target: "afg", "Encountered error finding best chain containing {:?}: {:?}", block, e);
None
}
},
};
Ok(result)
@@ -1281,20 +1273,22 @@ where
status.finalized_number,
);
return Ok(());
return Ok(())
}
// FIXME #1483: clone only when changed
let old_authority_set = authority_set.clone();
let update_res: Result<_, Error> = client.lock_import_and_run(|import_op| {
let status = authority_set.apply_standard_changes(
hash,
number,
&is_descendent_of::<Block, _>(&*client, None),
initial_sync,
None,
).map_err(|e| Error::Safety(e.to_string()))?;
let status = authority_set
.apply_standard_changes(
hash,
number,
&is_descendent_of::<Block, _>(&*client, None),
initial_sync,
None,
)
.map_err(|e| Error::Safety(e.to_string()))?;
// send a justification notification if a sender exists and in case of error log it.
fn notify_justification<Block: BlockT>(
@@ -1327,17 +1321,15 @@ where
if !justification_required {
if let Some(justification_period) = justification_period {
let last_finalized_number = client.info().finalized_number;
justification_required =
(!last_finalized_number.is_zero() || number - last_finalized_number == justification_period) &&
(last_finalized_number / justification_period != number / justification_period);
justification_required = (!last_finalized_number.is_zero() ||
number - last_finalized_number == justification_period) &&
(last_finalized_number / justification_period !=
number / justification_period);
}
}
let justification = GrandpaJustification::from_commit(
&client,
round_number,
commit,
)?;
let justification =
GrandpaJustification::from_commit(&client, round_number, commit)?;
(justification_required, justification)
},
@@ -1369,25 +1361,22 @@ where
"number" => ?number, "hash" => ?hash,
);
crate::aux_schema::update_best_justification(
&justification,
|insert| apply_aux(import_op, insert, &[]),
)?;
crate::aux_schema::update_best_justification(&justification, |insert| {
apply_aux(import_op, insert, &[])
})?;
let new_authorities = if let Some((canon_hash, canon_number)) = status.new_set_block {
// the authority set has changed.
let (new_id, set_ref) = authority_set.current();
if set_ref.len() > 16 {
afg_log!(initial_sync,
afg_log!(
initial_sync,
"👴 Applying GRANDPA set change to new set with {} authorities",
set_ref.len(),
);
} else {
afg_log!(initial_sync,
"👴 Applying GRANDPA set change to new set {:?}",
set_ref,
);
afg_log!(initial_sync, "👴 Applying GRANDPA set change to new set {:?}", set_ref,);
}
telemetry!(
@@ -1419,7 +1408,7 @@ where
warn!(target: "afg", "Failed to write updated authority set to disk. Bailing.");
warn!(target: "afg", "Node is in a potentially inconsistent state.");
return Err(e.into());
return Err(e.into())
}
}
@@ -1433,6 +1422,6 @@ where
*authority_set = old_authority_set;
Err(CommandOrError::Error(e))
}
},
}
}