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
@@ -48,7 +48,7 @@
//!
//! ### Signed Phase
//!
//! In the signed phase, solutions (of type [`RawSolution`]) are submitted and queued on chain. A
//! In the signed phase, solutions (of type [`RawSolution`]) are submitted and queued on chain. A
//! deposit is reserved, based on the size of the solution, for the cost of keeping this solution
//! on-chain for a number of blocks, and the potential weight of the solution upon being checked. A
//! maximum of `pallet::Config::MaxSignedSubmissions` solutions are stored. The queue is always
@@ -228,34 +228,31 @@
#![cfg_attr(not(feature = "std"), no_std)]
use codec::{Decode, Encode};
use frame_election_provider_support::{onchain, ElectionDataProvider, ElectionProvider};
use frame_support::{
dispatch::DispatchResultWithPostInfo,
ensure,
traits::{Currency, Get, ReservableCurrency, OnUnbalanced},
traits::{Currency, Get, OnUnbalanced, ReservableCurrency},
weights::Weight,
};
use frame_system::{ensure_none, offchain::SendTransactionTypes};
use frame_election_provider_support::{ElectionDataProvider, ElectionProvider, onchain};
use sp_arithmetic::{
traits::{CheckedAdd, Zero},
UpperOf,
};
use sp_npos_elections::{
assignment_ratio_to_staked_normalized, CompactSolution, ElectionScore,
EvaluateSupport, PerThing128, Supports, VoteWeight,
assignment_ratio_to_staked_normalized, CompactSolution, ElectionScore, EvaluateSupport,
PerThing128, Supports, VoteWeight,
};
use sp_runtime::{
traits::Bounded,
transaction_validity::{
InvalidTransaction, TransactionPriority, TransactionSource, TransactionValidity,
TransactionValidityError, ValidTransaction,
},
DispatchError, PerThing, Perbill, RuntimeDebug, SaturatedConversion,
traits::Bounded,
};
use sp_std::{
convert::TryInto,
prelude::*,
};
use sp_arithmetic::{
UpperOf,
traits::{Zero, CheckedAdd},
};
use sp_std::{convert::TryInto, prelude::*};
#[cfg(any(feature = "runtime-benchmarks", test))]
mod benchmarking;
@@ -562,7 +559,9 @@ pub mod pallet {
#[pallet::config]
pub trait Config: frame_system::Config + SendTransactionTypes<Call<Self>> {
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event> + TryInto<Event<Self>>;
type Event: From<Event<Self>>
+ IsType<<Self as frame_system::Config>::Event>
+ TryInto<Event<Self>>;
/// Currency type.
type Currency: ReservableCurrency<Self::AccountId> + Currency<Self::AccountId>;
@@ -701,21 +700,22 @@ pub mod pallet {
Ok(snap_weight) => {
log!(info, "Starting signed phase round {}.", Self::round());
T::WeightInfo::on_initialize_open_signed().saturating_add(snap_weight)
}
},
Err(why) => {
// Not much we can do about this at this point.
log!(warn, "failed to open signed phase due to {:?}", why);
T::WeightInfo::on_initialize_nothing()
// NOTE: ^^ The trait specifies that this is a noop in terms of weight
// in case of error.
}
},
}
}
},
Phase::Signed | Phase::Off
if remaining <= unsigned_deadline && remaining > Zero::zero() =>
{
// our needs vary according to whether or not the unsigned phase follows a signed phase
let (need_snapshot, enabled, signed_weight) = if current_phase == Phase::Signed {
let (need_snapshot, enabled, signed_weight) = if current_phase == Phase::Signed
{
// there was previously a signed phase: close the signed phase, no need for snapshot.
//
// Notes:
@@ -744,14 +744,14 @@ pub mod pallet {
};
base_weight.saturating_add(snap_weight).saturating_add(signed_weight)
}
},
Err(why) => {
// Not much we can do about this at this point.
log!(warn, "failed to open unsigned phase due to {:?}", why);
T::WeightInfo::on_initialize_nothing()
// NOTE: ^^ The trait specifies that this is a noop in terms of weight
// in case of error.
}
},
}
}
_ => T::WeightInfo::on_initialize_nothing(),
@@ -759,15 +759,16 @@ pub mod pallet {
}
fn offchain_worker(now: T::BlockNumber) {
use sp_runtime::offchain::storage_lock::{StorageLock, BlockAndTime};
use sp_runtime::offchain::storage_lock::{BlockAndTime, StorageLock};
// Create a lock with the maximum deadline of number of blocks in the unsigned phase.
// This should only come useful in an **abrupt** termination of execution, otherwise the
// guard will be dropped upon successful execution.
let mut lock = StorageLock::<BlockAndTime<frame_system::Pallet::<T>>>::with_block_deadline(
unsigned::OFFCHAIN_LOCK,
T::UnsignedPhase::get().saturated_into(),
);
let mut lock =
StorageLock::<BlockAndTime<frame_system::Pallet<T>>>::with_block_deadline(
unsigned::OFFCHAIN_LOCK,
T::UnsignedPhase::get().saturated_into(),
);
match lock.try_lock() {
Ok(_guard) => {
@@ -775,7 +776,7 @@ pub mod pallet {
},
Err(deadline) => {
log!(debug, "offchain worker lock not released, deadline is {:?}", deadline);
}
},
};
}
@@ -857,8 +858,7 @@ pub mod pallet {
witness: SolutionOrSnapshotSize,
) -> DispatchResultWithPostInfo {
ensure_none(origin)?;
let error_message =
"Invalid unsigned submission must produce invalid block and \
let error_message = "Invalid unsigned submission must produce invalid block and \
deprive validator from their authoring reward.";
// Check score being an improvement, phase, and desired targets.
@@ -921,11 +921,8 @@ pub mod pallet {
// Note: we don't `rotate_round` at this point; the next call to
// `ElectionProvider::elect` will succeed and take care of that.
let solution = ReadySolution {
supports,
score: [0, 0, 0],
compute: ElectionCompute::Emergency,
};
let solution =
ReadySolution { supports, score: [0, 0, 0], compute: ElectionCompute::Emergency };
<QueuedSolution<T>>::put(solution);
Ok(())
@@ -954,7 +951,8 @@ pub mod pallet {
// ensure witness data is correct.
ensure!(
num_signed_submissions >= <SignedSubmissions<T>>::decode_len().unwrap_or_default() as u32,
num_signed_submissions >=
<SignedSubmissions<T>>::decode_len().unwrap_or_default() as u32,
Error::<T>::SignedInvalidWitness,
);
@@ -989,8 +987,7 @@ pub mod pallet {
};
// collect deposit. Thereafter, the function cannot fail.
T::Currency::reserve(&who, deposit)
.map_err(|_| Error::<T>::SignedCannotPayDeposit)?;
T::Currency::reserve(&who, deposit).map_err(|_| Error::<T>::SignedCannotPayDeposit)?;
let ejected_a_solution = maybe_removed.is_some();
// if we had to remove the weakest solution, unreserve its deposit
@@ -1068,10 +1065,8 @@ pub mod pallet {
if let Call::submit_unsigned(solution, _) = call {
// Discard solution not coming from the local OCW.
match source {
TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ }
_ => {
return InvalidTransaction::Call.into();
}
TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ },
_ => return InvalidTransaction::Call.into(),
}
let _ = Self::unsigned_pre_dispatch_checks(solution)
@@ -1084,9 +1079,8 @@ pub mod pallet {
ValidTransaction::with_tag_prefix("OffchainElection")
// The higher the score[0], the better a solution is.
.priority(
T::MinerTxPriority::get().saturating_add(
solution.score[0].saturated_into()
),
T::MinerTxPriority::get()
.saturating_add(solution.score[0].saturated_into()),
)
// Used to deduplicate unsigned solutions: each validator should produce one
// solution per round at most, and solutions are not propagate.
@@ -1219,20 +1213,18 @@ impl<T: Config> Pallet<T> {
match current_phase {
Phase::Unsigned((true, opened)) if opened == now => {
// Mine a new solution, cache it, and attempt to submit it
let initial_output = Self::ensure_offchain_repeat_frequency(now).and_then(|_| {
Self::mine_check_save_submit()
});
let initial_output = Self::ensure_offchain_repeat_frequency(now)
.and_then(|_| Self::mine_check_save_submit());
log!(debug, "initial offchain thread output: {:?}", initial_output);
}
},
Phase::Unsigned((true, opened)) if opened < now => {
// Try and resubmit the cached solution, and recompute ONLY if it is not
// feasible.
let resubmit_output = Self::ensure_offchain_repeat_frequency(now).and_then(|_| {
Self::restore_or_compute_then_maybe_submit()
});
let resubmit_output = Self::ensure_offchain_repeat_frequency(now)
.and_then(|_| Self::restore_or_compute_then_maybe_submit());
log!(debug, "resubmit offchain thread output: {:?}", resubmit_output);
}
_ => {}
},
_ => {},
}
// After election finalization, clear OCW solution storage.
@@ -1242,9 +1234,7 @@ impl<T: Config> Pallet<T> {
let local_event = <T as Config>::Event::from(event_record.event);
local_event.try_into().ok()
})
.any(|event| {
matches!(event, Event::ElectionFinalized(_))
})
.any(|event| matches!(event, Event::ElectionFinalized(_)))
{
unsigned::kill_ocw_solution::<T>();
}
@@ -1308,14 +1298,12 @@ impl<T: Config> Pallet<T> {
// Defensive-only.
if targets.len() > target_limit || voters.len() > voter_limit {
debug_assert!(false, "Snapshot limit has not been respected.");
return Err(ElectionError::DataProvider("Snapshot too big for submission."));
return Err(ElectionError::DataProvider("Snapshot too big for submission."))
}
// Only write snapshot if all existed.
let metadata = SolutionOrSnapshotSize {
voters: voters.len() as u32,
targets: targets.len() as u32,
};
let metadata =
SolutionOrSnapshotSize { voters: voters.len() as u32, targets: targets.len() as u32 };
log!(debug, "creating a snapshot with metadata {:?}", metadata);
<SnapshotMetadata<T>>::put(metadata);
@@ -1335,7 +1323,10 @@ impl<T: Config> Pallet<T> {
debug_assert!(buffer.len() == size && size == buffer.capacity());
sp_io::storage::set(&<Snapshot<T>>::hashed_key(), &buffer);
Ok(w1.saturating_add(w2).saturating_add(w3).saturating_add(T::DbWeight::get().writes(3)))
Ok(w1
.saturating_add(w2)
.saturating_add(w3)
.saturating_add(T::DbWeight::get().writes(3)))
}
/// Kill everything created by [`Pallet::create_snapshot`].
@@ -1369,9 +1360,9 @@ impl<T: Config> Pallet<T> {
// Ensure that the solution's score can pass absolute min-score.
let submitted_score = solution.score.clone();
ensure!(
Self::minimum_untrusted_score().map_or(true, |min_score|
Self::minimum_untrusted_score().map_or(true, |min_score| {
sp_npos_elections::is_score_better(submitted_score, min_score, Perbill::zero())
),
}),
FeasibilityError::UntrustedScoreTooLow
);
@@ -1418,7 +1409,7 @@ impl<T: Config> Pallet<T> {
// Check that all of the targets are valid based on the snapshot.
if assignment.distribution.iter().any(|(d, _)| !targets.contains(d)) {
return Err(FeasibilityError::InvalidVote);
return Err(FeasibilityError::InvalidVote)
}
Ok(())
})
@@ -1494,8 +1485,13 @@ impl<T: Config> Pallet<T> {
.fold(Zero::zero(), |acc, next| acc + next.voters.len() as u32);
Ok((
supports,
T::WeightInfo::elect_queued(metadata.voters, metadata.targets, active_voters, desired),
compute
T::WeightInfo::elect_queued(
metadata.voters,
metadata.targets,
active_voters,
desired,
),
compute,
))
},
)
@@ -1526,12 +1522,12 @@ impl<T: Config> ElectionProvider<T::AccountId, T::BlockNumber> for Pallet<T> {
// All went okay, put sign to be Off, clean snapshot, etc.
Self::rotate_round();
Ok((supports, weight))
}
},
Err(why) => {
log!(error, "Entering emergency mode: {:?}", why);
<CurrentPhase<T>>::put(Phase::Emergency);
Err(why)
}
},
}
}
}
@@ -1553,11 +1549,9 @@ mod feasibility_check {
//! that is invalid, but gets through the system as valid.
use super::*;
use crate::{
mock::{
MultiPhase, Runtime, roll_to, TargetIndex, raw_solution, EpochLength, UnsignedPhase,
SignedPhase, VoterIndex, ExtBuilder,
},
use crate::mock::{
raw_solution, roll_to, EpochLength, ExtBuilder, MultiPhase, Runtime, SignedPhase,
TargetIndex, UnsignedPhase, VoterIndex,
};
use frame_support::assert_noop;
@@ -1728,11 +1722,11 @@ mod feasibility_check {
mod tests {
use super::*;
use crate::{
Phase,
mock::{
ExtBuilder, MultiPhase, Runtime, roll_to, MockWeightInfo, AccountId, TargetIndex,
Targets, multi_phase_events, System, SignedMaxSubmissions,
multi_phase_events, roll_to, AccountId, ExtBuilder, MockWeightInfo, MultiPhase,
Runtime, SignedMaxSubmissions, System, TargetIndex, Targets,
},
Phase,
};
use frame_election_provider_support::ElectionProvider;
use frame_support::{assert_noop, assert_ok};
@@ -2002,7 +1996,6 @@ mod tests {
roll_to(15);
assert_eq!(MultiPhase::current_phase(), Phase::Signed);
let (solution, _) = MultiPhase::mine_solution(2).unwrap();
// Default solution has a score of [50, 100, 5000].
assert_eq!(solution.score, [50, 100, 5000]);
@@ -2012,10 +2005,7 @@ mod tests {
<MinimumUntrustedScore<Runtime>>::put([51, 0, 0]);
assert_noop!(
MultiPhase::feasibility_check(
solution,
ElectionCompute::Signed
),
MultiPhase::feasibility_check(solution, ElectionCompute::Signed),
FeasibilityError::UntrustedScoreTooLow,
);
})
@@ -2039,9 +2029,9 @@ mod tests {
};
let mut active = 1;
while weight_with(active)
<= <Runtime as frame_system::Config>::BlockWeights::get().max_block
|| active == all_voters
while weight_with(active) <=
<Runtime as frame_system::Config>::BlockWeights::get().max_block ||
active == all_voters
{
active += 1;
}