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
@@ -21,19 +21,18 @@ use crate::{
helpers, Call, CompactAccuracyOf, CompactOf, Config, ElectionCompute, Error, FeasibilityError,
Pallet, RawSolution, ReadySolution, RoundSnapshot, SolutionOrSnapshotSize, Weight, WeightInfo,
};
use codec::{Encode, Decode};
use codec::{Decode, Encode};
use frame_support::{dispatch::DispatchResult, ensure, traits::Get};
use frame_system::offchain::SubmitTransaction;
use sp_arithmetic::Perbill;
use sp_npos_elections::{
CompactSolution, ElectionResult, assignment_ratio_to_staked_normalized,
assignment_staked_to_ratio_normalized, is_score_better, seq_phragmen,
assignment_ratio_to_staked_normalized, assignment_staked_to_ratio_normalized, is_score_better,
seq_phragmen, CompactSolution, ElectionResult,
};
use sp_runtime::{
DispatchError,
SaturatedConversion,
offchain::storage::{MutateStorageError, StorageValueRef},
traits::TrailingZeroInput,
DispatchError, SaturatedConversion,
};
use sp_std::{cmp::Ordering, convert::TryFrom, vec::Vec};
@@ -54,10 +53,8 @@ pub type Voter<T> = (
);
/// The relative distribution of a voter's stake among the winning targets.
pub type Assignment<T> = sp_npos_elections::Assignment<
<T as frame_system::Config>::AccountId,
CompactAccuracyOf<T>,
>;
pub type Assignment<T> =
sp_npos_elections::Assignment<<T as frame_system::Config>::AccountId, CompactAccuracyOf<T>>;
/// The [`IndexAssignment`][sp_npos_elections::IndexAssignment] type specialized for a particular
/// runtime `T`.
@@ -105,7 +102,8 @@ fn save_solution<T: Config>(call: &Call<T>) -> Result<(), MinerError> {
let storage = StorageValueRef::persistent(&OFFCHAIN_CACHED_CALL);
match storage.mutate::<_, (), _>(|_| Ok(call.clone())) {
Ok(_) => Ok(()),
Err(MutateStorageError::ConcurrentModification(_)) => Err(MinerError::FailedToStoreSolution),
Err(MutateStorageError::ConcurrentModification(_)) =>
Err(MinerError::FailedToStoreSolution),
Err(MutateStorageError::ValueFunctionFailed(_)) => {
// this branch should be unreachable according to the definition of
// `StorageValueRef::mutate`: that function should only ever `Err` if the closure we
@@ -151,44 +149,45 @@ impl<T: Config> Pallet<T> {
/// Attempt to restore a solution from cache. Otherwise, compute it fresh. Either way, submit
/// if our call's score is greater than that of the cached solution.
pub fn restore_or_compute_then_maybe_submit() -> Result<(), MinerError> {
log!(debug,"miner attempting to restore or compute an unsigned solution.");
log!(debug, "miner attempting to restore or compute an unsigned solution.");
let call = restore_solution::<T>()
.and_then(|call| {
// ensure the cached call is still current before submitting
if let Call::submit_unsigned(solution, _) = &call {
// prevent errors arising from state changes in a forkful chain
Self::basic_checks(solution, "restored")?;
Ok(call)
} else {
Err(MinerError::SolutionCallInvalid)
}
}).or_else::<MinerError, _>(|error| {
log!(debug, "restoring solution failed due to {:?}", error);
match error {
MinerError::NoStoredSolution => {
log!(trace, "mining a new solution.");
// if not present or cache invalidated due to feasibility, regenerate.
// note that failing `Feasibility` can only mean that the solution was
// computed over a snapshot that has changed due to a fork.
let call = Self::mine_checked_call()?;
save_solution(&call)?;
.and_then(|call| {
// ensure the cached call is still current before submitting
if let Call::submit_unsigned(solution, _) = &call {
// prevent errors arising from state changes in a forkful chain
Self::basic_checks(solution, "restored")?;
Ok(call)
} else {
Err(MinerError::SolutionCallInvalid)
}
MinerError::Feasibility(_) => {
log!(trace, "wiping infeasible solution.");
// kill the infeasible solution, hopefully in the next runs (whenever they
// may be) we mine a new one.
kill_ocw_solution::<T>();
clear_offchain_repeat_frequency();
Err(error)
},
_ => {
// nothing to do. Return the error as-is.
Err(error)
})
.or_else::<MinerError, _>(|error| {
log!(debug, "restoring solution failed due to {:?}", error);
match error {
MinerError::NoStoredSolution => {
log!(trace, "mining a new solution.");
// if not present or cache invalidated due to feasibility, regenerate.
// note that failing `Feasibility` can only mean that the solution was
// computed over a snapshot that has changed due to a fork.
let call = Self::mine_checked_call()?;
save_solution(&call)?;
Ok(call)
},
MinerError::Feasibility(_) => {
log!(trace, "wiping infeasible solution.");
// kill the infeasible solution, hopefully in the next runs (whenever they
// may be) we mine a new one.
kill_ocw_solution::<T>();
clear_offchain_repeat_frequency();
Err(error)
},
_ => {
// nothing to do. Return the error as-is.
Err(error)
},
}
}
})?;
})?;
Self::submit_call(call)
}
@@ -240,10 +239,12 @@ impl<T: Config> Pallet<T> {
MinerError::PreDispatchChecksFailed(err)
})?;
Self::feasibility_check(raw_solution.clone(), ElectionCompute::Unsigned).map_err(|err| {
log!(debug, "feasibility check failed for {} solution: {:?}", solution_type, err);
err
})?;
Self::feasibility_check(raw_solution.clone(), ElectionCompute::Unsigned).map_err(
|err| {
log!(debug, "feasibility check failed for {} solution: {:?}", solution_type, err);
err
},
)?;
Ok(())
}
@@ -347,11 +348,7 @@ impl<T: Config> Pallet<T> {
// converting to `Compact`.
let mut index_assignments = sorted_assignments
.into_iter()
.map(|assignment| IndexAssignmentOf::<T>::new(
&assignment,
&voter_index,
&target_index,
))
.map(|assignment| IndexAssignmentOf::<T>::new(&assignment, &voter_index, &target_index))
.collect::<Result<Vec<_>, _>>()?;
// trim assignments list for weight and length.
@@ -390,10 +387,10 @@ impl<T: Config> Pallet<T> {
max @ _ => {
let seed = sp_io::offchain::random_seed();
let random = <u32>::decode(&mut TrailingZeroInput::new(seed.as_ref()))
.expect("input is padded with zeroes; qed")
% max.saturating_add(1);
.expect("input is padded with zeroes; qed") %
max.saturating_add(1);
random as usize
}
},
}
}
@@ -418,18 +415,16 @@ impl<T: Config> Pallet<T> {
max_weight: Weight,
assignments: &mut Vec<IndexAssignmentOf<T>>,
) {
let maximum_allowed_voters = Self::maximum_voter_for_weight::<T::WeightInfo>(
desired_targets,
size,
max_weight,
);
let removing: usize = assignments.len().saturating_sub(
maximum_allowed_voters.saturated_into(),
);
let maximum_allowed_voters =
Self::maximum_voter_for_weight::<T::WeightInfo>(desired_targets, size, max_weight);
let removing: usize =
assignments.len().saturating_sub(maximum_allowed_voters.saturated_into());
log!(
debug,
"from {} assignments, truncating to {} for weight, removing {}",
assignments.len(), maximum_allowed_voters, removing,
assignments.len(),
maximum_allowed_voters,
removing,
);
assignments.truncate(maximum_allowed_voters as usize);
}
@@ -461,7 +456,7 @@ impl<T: Config> Pallet<T> {
// not much we can do if assignments are already empty.
if high == low {
return Ok(());
return Ok(())
}
while high - low > 1 {
@@ -472,22 +467,21 @@ impl<T: Config> Pallet<T> {
high = test;
}
}
let maximum_allowed_voters =
if low < assignments.len() &&
encoded_size_of(&assignments[..low + 1])? <= max_allowed_length
{
low + 1
} else {
low
};
let maximum_allowed_voters = if low < assignments.len() &&
encoded_size_of(&assignments[..low + 1])? <= max_allowed_length
{
low + 1
} else {
low
};
// ensure our post-conditions are correct
debug_assert!(
encoded_size_of(&assignments[..maximum_allowed_voters]).unwrap() <= max_allowed_length
);
debug_assert!(if maximum_allowed_voters < assignments.len() {
encoded_size_of(&assignments[..maximum_allowed_voters + 1]).unwrap()
> max_allowed_length
encoded_size_of(&assignments[..maximum_allowed_voters + 1]).unwrap() >
max_allowed_length
} else {
true
});
@@ -517,7 +511,7 @@ impl<T: Config> Pallet<T> {
max_weight: Weight,
) -> u32 {
if size.voters < 1 {
return size.voters;
return size.voters
}
let max_voters = size.voters.max(1);
@@ -536,7 +530,7 @@ impl<T: Config> Pallet<T> {
Some(voters) if voters < max_voters => Ok(voters),
_ => Err(()),
}
}
},
Ordering::Greater => voters.checked_sub(step).ok_or(()),
Ordering::Equal => Ok(voters),
}
@@ -551,11 +545,9 @@ impl<T: Config> Pallet<T> {
// proceed with the binary search
Ok(next) if next != voters => {
voters = next;
}
},
// we are out of bounds, break out of the loop.
Err(()) => {
break;
}
Err(()) => break,
// we found the right value - early exit the function.
Ok(next) => return next,
}
@@ -599,17 +591,16 @@ impl<T: Config> Pallet<T> {
|maybe_head: Result<Option<T::BlockNumber>, _>| {
match maybe_head {
Ok(Some(head)) if now < head => Err("fork."),
Ok(Some(head)) if now >= head && now <= head + threshold => {
Err("recently executed.")
}
Ok(Some(head)) if now >= head && now <= head + threshold =>
Err("recently executed."),
Ok(Some(head)) if now > head + threshold => {
// we can run again now. Write the new head.
Ok(now)
}
},
_ => {
// value doesn't exists. Probably this node just booted up. Write, and run
Ok(now)
}
},
}
},
);
@@ -632,9 +623,7 @@ impl<T: Config> Pallet<T> {
///
/// NOTE: Ideally, these tests should move more and more outside of this and more to the miner's
/// code, so that we do less and less storage reads here.
pub fn unsigned_pre_dispatch_checks(
solution: &RawSolution<CompactOf<T>>,
) -> DispatchResult {
pub fn unsigned_pre_dispatch_checks(solution: &RawSolution<CompactOf<T>>) -> DispatchResult {
// ensure solution is timely. Don't panic yet. This is a cheap check.
ensure!(Self::current_phase().is_unsigned_open(), Error::<T>::PreDispatchEarlySubmission);
@@ -643,8 +632,8 @@ impl<T: Config> Pallet<T> {
// ensure correct number of winners.
ensure!(
Self::desired_targets().unwrap_or_default()
== solution.compact.unique_targets().len() as u32,
Self::desired_targets().unwrap_or_default() ==
solution.compact.unique_targets().len() as u32,
Error::<T>::PreDispatchWrongWinnerCount,
);
@@ -761,19 +750,22 @@ mod max_weight {
mod tests {
use super::*;
use crate::{
mock::{
roll_to, roll_to_with_ocw, trim_helpers, witness, BlockNumber, Call as OuterCall,
ExtBuilder, Extrinsic, MinerMaxWeight, MultiPhase, Origin, Runtime, System,
TestCompact, TrimHelpers, UnsignedPhase,
},
CurrentPhase, InvalidTransaction, Phase, QueuedSolution, TransactionSource,
TransactionValidityError,
mock::{
Call as OuterCall, ExtBuilder, Extrinsic, MinerMaxWeight, MultiPhase, Origin, Runtime,
TestCompact, TrimHelpers, roll_to, roll_to_with_ocw, trim_helpers, witness,
UnsignedPhase, BlockNumber, System,
},
};
use frame_benchmarking::Zero;
use frame_support::{assert_noop, assert_ok, dispatch::Dispatchable, traits::OffchainWorker};
use sp_npos_elections::IndexAssignment;
use sp_runtime::offchain::storage_lock::{StorageLock, BlockAndTime};
use sp_runtime::{traits::ValidateUnsigned, PerU16};
use sp_runtime::{
offchain::storage_lock::{BlockAndTime, StorageLock},
traits::ValidateUnsigned,
PerU16,
};
type Assignment = crate::unsigned::Assignment<Runtime>;
@@ -786,8 +778,11 @@ mod tests {
// initial
assert_eq!(MultiPhase::current_phase(), Phase::Off);
assert!(matches!(
<MultiPhase as ValidateUnsigned>::validate_unsigned(TransactionSource::Local, &call)
.unwrap_err(),
<MultiPhase as ValidateUnsigned>::validate_unsigned(
TransactionSource::Local,
&call
)
.unwrap_err(),
TransactionValidityError::Invalid(InvalidTransaction::Custom(0))
));
assert!(matches!(
@@ -799,8 +794,11 @@ mod tests {
roll_to(15);
assert_eq!(MultiPhase::current_phase(), Phase::Signed);
assert!(matches!(
<MultiPhase as ValidateUnsigned>::validate_unsigned(TransactionSource::Local, &call)
.unwrap_err(),
<MultiPhase as ValidateUnsigned>::validate_unsigned(
TransactionSource::Local,
&call
)
.unwrap_err(),
TransactionValidityError::Invalid(InvalidTransaction::Custom(0))
));
assert!(matches!(
@@ -823,8 +821,11 @@ mod tests {
<CurrentPhase<Runtime>>::put(Phase::Unsigned((false, 25)));
assert!(MultiPhase::current_phase().is_unsigned());
assert!(matches!(
<MultiPhase as ValidateUnsigned>::validate_unsigned(TransactionSource::Local, &call)
.unwrap_err(),
<MultiPhase as ValidateUnsigned>::validate_unsigned(
TransactionSource::Local,
&call
)
.unwrap_err(),
TransactionValidityError::Invalid(InvalidTransaction::Custom(0))
));
assert!(matches!(
@@ -895,23 +896,27 @@ mod tests {
#[test]
fn priority_is_set() {
ExtBuilder::default().miner_tx_priority(20).desired_targets(0).build_and_execute(|| {
roll_to(25);
assert!(MultiPhase::current_phase().is_unsigned());
ExtBuilder::default()
.miner_tx_priority(20)
.desired_targets(0)
.build_and_execute(|| {
roll_to(25);
assert!(MultiPhase::current_phase().is_unsigned());
let solution = RawSolution::<TestCompact> { score: [5, 0, 0], ..Default::default() };
let call = Call::submit_unsigned(solution.clone(), witness());
let solution =
RawSolution::<TestCompact> { score: [5, 0, 0], ..Default::default() };
let call = Call::submit_unsigned(solution.clone(), witness());
assert_eq!(
<MultiPhase as ValidateUnsigned>::validate_unsigned(
TransactionSource::Local,
&call
)
.unwrap()
.priority,
25
);
})
assert_eq!(
<MultiPhase as ValidateUnsigned>::validate_unsigned(
TransactionSource::Local,
&call
)
.unwrap()
.priority,
25
);
})
}
#[test]
@@ -974,35 +979,38 @@ mod tests {
#[test]
fn miner_trims_weight() {
ExtBuilder::default().miner_weight(100).mock_weight_info(true).build_and_execute(|| {
roll_to(25);
assert!(MultiPhase::current_phase().is_unsigned());
ExtBuilder::default()
.miner_weight(100)
.mock_weight_info(true)
.build_and_execute(|| {
roll_to(25);
assert!(MultiPhase::current_phase().is_unsigned());
let (solution, witness) = MultiPhase::mine_solution(2).unwrap();
let solution_weight = <Runtime as Config>::WeightInfo::submit_unsigned(
witness.voters,
witness.targets,
solution.compact.voter_count() as u32,
solution.compact.unique_targets().len() as u32,
);
// default solution will have 5 edges (5 * 5 + 10)
assert_eq!(solution_weight, 35);
assert_eq!(solution.compact.voter_count(), 5);
let (solution, witness) = MultiPhase::mine_solution(2).unwrap();
let solution_weight = <Runtime as Config>::WeightInfo::submit_unsigned(
witness.voters,
witness.targets,
solution.compact.voter_count() as u32,
solution.compact.unique_targets().len() as u32,
);
// default solution will have 5 edges (5 * 5 + 10)
assert_eq!(solution_weight, 35);
assert_eq!(solution.compact.voter_count(), 5);
// now reduce the max weight
<MinerMaxWeight>::set(25);
// now reduce the max weight
<MinerMaxWeight>::set(25);
let (solution, witness) = MultiPhase::mine_solution(2).unwrap();
let solution_weight = <Runtime as Config>::WeightInfo::submit_unsigned(
witness.voters,
witness.targets,
solution.compact.voter_count() as u32,
solution.compact.unique_targets().len() as u32,
);
// default solution will have 5 edges (5 * 5 + 10)
assert_eq!(solution_weight, 25);
assert_eq!(solution.compact.voter_count(), 3);
})
let (solution, witness) = MultiPhase::mine_solution(2).unwrap();
let solution_weight = <Runtime as Config>::WeightInfo::submit_unsigned(
witness.voters,
witness.targets,
solution.compact.voter_count() as u32,
solution.compact.unique_targets().len() as u32,
);
// default solution will have 5 edges (5 * 5 + 10)
assert_eq!(solution_weight, 25);
assert_eq!(solution.compact.voter_count(), 3);
})
}
#[test]
@@ -1014,7 +1022,7 @@ mod tests {
assert_eq!(
MultiPhase::mine_check_save_submit().unwrap_err(),
MinerError::PreDispatchChecksFailed(DispatchError::Module{
MinerError::PreDispatchChecksFailed(DispatchError::Module {
index: 2,
error: 1,
message: Some("PreDispatchWrongWinnerCount"),
@@ -1360,15 +1368,14 @@ mod tests {
};
// Custom(7) maps to PreDispatchChecksFailed
let pre_dispatch_check_error = TransactionValidityError::Invalid(
InvalidTransaction::Custom(7),
);
let pre_dispatch_check_error =
TransactionValidityError::Invalid(InvalidTransaction::Custom(7));
assert_eq!(
<MultiPhase as ValidateUnsigned>::validate_unsigned(
TransactionSource::Local,
&call,
)
.unwrap_err(),
.unwrap_err(),
pre_dispatch_check_error,
);
assert_eq!(
@@ -1384,21 +1391,14 @@ mod tests {
roll_to(25);
// given
let TrimHelpers {
mut assignments,
encoded_size_of,
..
} = trim_helpers();
let TrimHelpers { mut assignments, encoded_size_of, .. } = trim_helpers();
let compact = CompactOf::<Runtime>::try_from(assignments.as_slice()).unwrap();
let encoded_len = compact.encoded_size() as u32;
let compact_clone = compact.clone();
// when
MultiPhase::trim_assignments_length(
encoded_len,
&mut assignments,
encoded_size_of,
).unwrap();
MultiPhase::trim_assignments_length(encoded_len, &mut assignments, encoded_size_of)
.unwrap();
// then
let compact = CompactOf::<Runtime>::try_from(assignments.as_slice()).unwrap();
@@ -1412,11 +1412,7 @@ mod tests {
roll_to(25);
// given
let TrimHelpers {
mut assignments,
encoded_size_of,
..
} = trim_helpers();
let TrimHelpers { mut assignments, encoded_size_of, .. } = trim_helpers();
let compact = CompactOf::<Runtime>::try_from(assignments.as_slice()).unwrap();
let encoded_len = compact.encoded_size();
let compact_clone = compact.clone();
@@ -1426,7 +1422,8 @@ mod tests {
encoded_len as u32 - 1,
&mut assignments,
encoded_size_of,
).unwrap();
)
.unwrap();
// then
let compact = CompactOf::<Runtime>::try_from(assignments.as_slice()).unwrap();
@@ -1441,33 +1438,26 @@ mod tests {
roll_to(25);
// given
let TrimHelpers {
voters,
mut assignments,
encoded_size_of,
voter_index,
} = trim_helpers();
let TrimHelpers { voters, mut assignments, encoded_size_of, voter_index } =
trim_helpers();
let compact = CompactOf::<Runtime>::try_from(assignments.as_slice()).unwrap();
let encoded_len = compact.encoded_size() as u32;
let count = assignments.len();
let min_stake_voter = voters.iter()
let min_stake_voter = voters
.iter()
.map(|(id, weight, _)| (weight, id))
.min()
.and_then(|(_, id)| voter_index(id))
.unwrap();
// when
MultiPhase::trim_assignments_length(
encoded_len - 1,
&mut assignments,
encoded_size_of,
).unwrap();
MultiPhase::trim_assignments_length(encoded_len - 1, &mut assignments, encoded_size_of)
.unwrap();
// then
assert_eq!(assignments.len(), count - 1, "we must have removed exactly one assignment");
assert!(
assignments.iter()
.all(|IndexAssignment{ who, ..}| *who != min_stake_voter),
assignments.iter().all(|IndexAssignment { who, .. }| *who != min_stake_voter),
"min_stake_voter must no longer be in the set of voters",
);
});