ci: add quick-check with rustfmt (#615)

* ci: add quick-check with clippy and rustfmt

* chore: rustfmt round

* chore: set the same rustfmt config than substrate

* chore: fix formatting

* cI: remove clippy

* ci: switch to nightly for the checks

* ci: fix toolchains and naming

* ci: Limit the check to formatting

* chore: fix formatting

* Update .rustfmt.toml

* Update .rustfmt.toml

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>
This commit is contained in:
Chevdor
2021-09-16 16:57:52 +02:00
committed by GitHub
parent e3eb3a0a12
commit 6b20f7a2c5
98 changed files with 1244 additions and 1872 deletions
@@ -19,15 +19,15 @@ use super::*;
#[allow(unused)]
use crate::Pallet as CollatorSelection;
use sp_std::prelude::*;
use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller, account};
use frame_system::{RawOrigin, EventRecord};
use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite, whitelisted_caller};
use frame_support::{
assert_ok,
traits::{Currency, Get, EnsureOrigin},
traits::{Currency, EnsureOrigin, Get},
};
use frame_system::{EventRecord, RawOrigin};
use pallet_authorship::EventHandler;
use pallet_session::SessionManager;
use sp_std::prelude::*;
pub type BalanceOf<T> =
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
@@ -38,7 +38,7 @@ const SEED: u32 = 0;
macro_rules! whitelist {
($acc:ident) => {
frame_benchmarking::benchmarking::add_to_whitelist(
frame_system::Account::<T>::hashed_key_for(&$acc).into()
frame_system::Account::<T>::hashed_key_for(&$acc).into(),
);
};
}
+82 -60
View File
@@ -74,29 +74,27 @@ pub mod weights;
#[frame_support::pallet]
pub mod pallet {
pub use crate::weights::WeightInfo;
use core::ops::Div;
use frame_support::{
dispatch::DispatchResultWithPostInfo,
pallet_prelude::*,
inherent::Vec,
traits::{
Currency, ReservableCurrency, EnsureOrigin, ExistenceRequirement::KeepAlive, ValidatorRegistration
},
PalletId,
};
use frame_system::pallet_prelude::*;
use frame_system::Config as SystemConfig;
use frame_support::{
pallet_prelude::*,
sp_runtime::{
traits::{AccountIdConversion, CheckedSub, Saturating, Zero},
RuntimeDebug,
traits::{AccountIdConversion, CheckedSub, Zero, Saturating},
},
traits::{
Currency, EnsureOrigin, ExistenceRequirement::KeepAlive, ReservableCurrency,
ValidatorRegistration,
},
weights::DispatchClass,
PalletId,
};
use sp_runtime::traits::Convert;
use core::ops::Div;
use frame_system::{pallet_prelude::*, Config as SystemConfig};
use pallet_session::SessionManager;
use sp_runtime::traits::Convert;
use sp_staking::SessionIndex;
pub use crate::weights::WeightInfo;
type BalanceOf<T> =
<<T as Config>::Currency as Currency<<T as SystemConfig>::AccountId>>::Balance;
@@ -136,7 +134,6 @@ pub mod pallet {
/// This does not take into account the invulnerables.
type MinCandidates: Get<u32>;
/// Maximum number of invulnerables.
///
/// Used only for benchmarking.
@@ -156,7 +153,6 @@ pub mod pallet {
/// Validate a user is registered
type ValidatorRegistration: ValidatorRegistration<Self::ValidatorId>;
/// The weight information of this pallet.
type WeightInfo: WeightInfo;
}
@@ -182,16 +178,14 @@ pub mod pallet {
/// The (community, limited) collation candidates.
#[pallet::storage]
#[pallet::getter(fn candidates)]
pub type Candidates<T: Config> = StorageValue<
_,
Vec<CandidateInfo<T::AccountId, BalanceOf<T>>>,
ValueQuery,
>;
pub type Candidates<T: Config> =
StorageValue<_, Vec<CandidateInfo<T::AccountId, BalanceOf<T>>>, ValueQuery>;
/// Last block authored by collator.
#[pallet::storage]
#[pallet::getter(fn last_authored_block)]
pub type LastAuthoredBlock<T: Config> = StorageMap<_, Twox64Concat, T::AccountId, T::BlockNumber, ValueQuery>;
pub type LastAuthoredBlock<T: Config> =
StorageMap<_, Twox64Concat, T::AccountId, T::BlockNumber, ValueQuery>;
/// Desired number of candidates.
///
@@ -205,7 +199,6 @@ pub mod pallet {
#[pallet::getter(fn candidacy_bond)]
pub type CandidacyBond<T> = StorageValue<_, BalanceOf<T>, ValueQuery>;
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
pub invulnerables: Vec<T::AccountId>,
@@ -227,9 +220,12 @@ pub mod pallet {
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
fn build(&self) {
let duplicate_invulnerables = self.invulnerables.iter().collect::<std::collections::BTreeSet<_>>();
assert!(duplicate_invulnerables.len() == self.invulnerables.len(), "duplicate invulnerables in genesis.");
let duplicate_invulnerables =
self.invulnerables.iter().collect::<std::collections::BTreeSet<_>>();
assert!(
duplicate_invulnerables.len() == self.invulnerables.len(),
"duplicate invulnerables in genesis."
);
assert!(
T::MaxInvulnerables::get() >= (self.invulnerables.len() as u32),
@@ -276,7 +272,7 @@ pub mod pallet {
/// Account has no associated validator ID
NoAssociatedValidatorId,
/// Validator ID is not yet registered
ValidatorNotRegistered
ValidatorNotRegistered,
}
#[pallet::hooks]
@@ -302,13 +298,14 @@ pub mod pallet {
}
#[pallet::weight(T::WeightInfo::set_desired_candidates())]
pub fn set_desired_candidates(origin: OriginFor<T>, max: u32) -> DispatchResultWithPostInfo {
pub fn set_desired_candidates(
origin: OriginFor<T>,
max: u32,
) -> DispatchResultWithPostInfo {
T::UpdateOrigin::ensure_origin(origin)?;
// we trust origin calls, this is just a for more accurate benchmarking
if max > T::MaxCandidates::get() {
log::warn!(
"max > T::MaxCandidates; you might need to run benchmarks again"
);
log::warn!("max > T::MaxCandidates; you might need to run benchmarks again");
}
<DesiredCandidates<T>>::put(&max);
Self::deposit_event(Event::NewDesiredCandidates(max));
@@ -316,7 +313,10 @@ pub mod pallet {
}
#[pallet::weight(T::WeightInfo::set_candidacy_bond())]
pub fn set_candidacy_bond(origin: OriginFor<T>, bond: BalanceOf<T>) -> DispatchResultWithPostInfo {
pub fn set_candidacy_bond(
origin: OriginFor<T>,
bond: BalanceOf<T>,
) -> DispatchResultWithPostInfo {
T::UpdateOrigin::ensure_origin(origin)?;
<CandidacyBond<T>>::put(&bond);
Self::deposit_event(Event::NewCandidacyBond(bond));
@@ -332,8 +332,12 @@ pub mod pallet {
ensure!((length as u32) < Self::desired_candidates(), Error::<T>::TooManyCandidates);
ensure!(!Self::invulnerables().contains(&who), Error::<T>::AlreadyInvulnerable);
let validator_key = T::ValidatorIdOf::convert(who.clone()).ok_or(Error::<T>::NoAssociatedValidatorId)?;
ensure!(T::ValidatorRegistration::is_registered(&validator_key), Error::<T>::ValidatorNotRegistered);
let validator_key = T::ValidatorIdOf::convert(who.clone())
.ok_or(Error::<T>::NoAssociatedValidatorId)?;
ensure!(
T::ValidatorRegistration::is_registered(&validator_key),
Error::<T>::ValidatorNotRegistered
);
let deposit = Self::candidacy_bond();
// First authored block is current block plus kick threshold to handle session delay
@@ -346,7 +350,10 @@ pub mod pallet {
} else {
T::Currency::reserve(&who, deposit)?;
candidates.push(incoming);
<LastAuthoredBlock<T>>::insert(who.clone(), frame_system::Pallet::<T>::block_number() + T::KickThreshold::get());
<LastAuthoredBlock<T>>::insert(
who.clone(),
frame_system::Pallet::<T>::block_number() + T::KickThreshold::get(),
);
Ok(candidates.len())
}
})?;
@@ -358,7 +365,10 @@ pub mod pallet {
#[pallet::weight(T::WeightInfo::leave_intent(T::MaxCandidates::get()))]
pub fn leave_intent(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
let who = ensure_signed(origin)?;
ensure!(Self::candidates().len() as u32 > T::MinCandidates::get(), Error::<T>::TooFewCandidates);
ensure!(
Self::candidates().len() as u32 > T::MinCandidates::get(),
Error::<T>::TooFewCandidates
);
let current_count = Self::try_remove_candidate(&who)?;
Ok(Some(T::WeightInfo::leave_intent(current_count as u32)).into())
@@ -372,13 +382,17 @@ pub mod pallet {
}
/// Removes a candidate if they exist and sends them back their deposit
fn try_remove_candidate(who: &T::AccountId) -> Result<usize, DispatchError> {
let current_count = <Candidates<T>>::try_mutate(|candidates| -> Result<usize, DispatchError> {
let index = candidates.iter().position(|candidate| candidate.who == *who).ok_or(Error::<T>::NotCandidate)?;
T::Currency::unreserve(&who, candidates[index].deposit);
candidates.remove(index);
<LastAuthoredBlock<T>>::remove(who.clone());
Ok(candidates.len())
})?;
let current_count =
<Candidates<T>>::try_mutate(|candidates| -> Result<usize, DispatchError> {
let index = candidates
.iter()
.position(|candidate| candidate.who == *who)
.ok_or(Error::<T>::NotCandidate)?;
T::Currency::unreserve(&who, candidates[index].deposit);
candidates.remove(index);
<LastAuthoredBlock<T>>::remove(who.clone());
Ok(candidates.len())
})?;
Self::deposit_event(Event::CandidateRemoved(who.clone()));
Ok(current_count)
}
@@ -388,29 +402,34 @@ pub mod pallet {
/// This is done on the fly, as frequent as we are told to do so, as the session manager.
pub fn assemble_collators(candidates: Vec<T::AccountId>) -> Vec<T::AccountId> {
let mut collators = Self::invulnerables();
collators.extend(
candidates.into_iter().collect::<Vec<_>>(),
);
collators.extend(candidates.into_iter().collect::<Vec<_>>());
collators
}
/// Kicks out and candidates that did not produce a block in the kick threshold.
pub fn kick_stale_candidates(candidates: Vec<CandidateInfo<T::AccountId, BalanceOf<T>>>) -> Vec<T::AccountId> {
pub fn kick_stale_candidates(
candidates: Vec<CandidateInfo<T::AccountId, BalanceOf<T>>>,
) -> Vec<T::AccountId> {
let now = frame_system::Pallet::<T>::block_number();
let kick_threshold = T::KickThreshold::get();
let new_candidates = candidates.into_iter().filter_map(|c| {
let last_block = <LastAuthoredBlock<T>>::get(c.who.clone());
let since_last = now.saturating_sub(last_block);
if since_last < kick_threshold || Self::candidates().len() as u32 <= T::MinCandidates::get() {
Some(c.who)
} else {
let outcome = Self::try_remove_candidate(&c.who);
if let Err(why) = outcome {
log::warn!("Failed to remove candidate {:?}", why);
debug_assert!(false, "failed to remove candidate {:?}", why);
let new_candidates = candidates
.into_iter()
.filter_map(|c| {
let last_block = <LastAuthoredBlock<T>>::get(c.who.clone());
let since_last = now.saturating_sub(last_block);
if since_last < kick_threshold ||
Self::candidates().len() as u32 <= T::MinCandidates::get()
{
Some(c.who)
} else {
let outcome = Self::try_remove_candidate(&c.who);
if let Err(why) = outcome {
log::warn!("Failed to remove candidate {:?}", why);
debug_assert!(false, "failed to remove candidate {:?}", why);
}
None
}
None
}
}).collect::<Vec<_>>();
})
.collect::<Vec<_>>();
new_candidates
}
}
@@ -423,7 +442,10 @@ pub mod pallet {
fn note_author(author: T::AccountId) {
let pot = Self::account_id();
// assumes an ED will be sent to pot.
let reward = T::Currency::free_balance(&pot).checked_sub(&T::Currency::minimum_balance()).unwrap_or_else(Zero::zero).div(2u32.into());
let reward = T::Currency::free_balance(&pot)
.checked_sub(&T::Currency::minimum_balance())
.unwrap_or_else(Zero::zero)
.div(2u32.into());
// `reward` is half of pot account minus ED, this should never fail.
let _success = T::Currency::transfer(&pot, &author, reward, KeepAlive);
debug_assert!(_success.is_ok());
+17 -25
View File
@@ -15,19 +15,19 @@
use super::*;
use crate as collator_selection;
use sp_core::H256;
use frame_support::{
parameter_types, ord_parameter_types,
ord_parameter_types, parameter_types,
traits::{FindAuthor, GenesisBuild, ValidatorRegistration},
PalletId
PalletId,
};
use sp_runtime::{
RuntimeAppPublic,
traits::{BlakeTwo256, IdentityLookup, OpaqueKeys},
testing::{Header, UintAuthorityId},
};
use frame_system::{EnsureSignedBy};
use frame_system as system;
use frame_system::EnsureSignedBy;
use sp_core::H256;
use sp_runtime::{
testing::{Header, UintAuthorityId},
traits::{BlakeTwo256, IdentityLookup, OpaqueKeys},
RuntimeAppPublic,
};
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
@@ -100,7 +100,8 @@ impl pallet_balances::Config for Test {
pub struct Author4;
impl FindAuthor<u64> for Author4 {
fn find_author<'a, I>(_digests: I) -> Option<u64>
where I: 'a + IntoIterator<Item = (frame_support::ConsensusEngineId, &'a [u8])>,
where
I: 'a + IntoIterator<Item = (frame_support::ConsensusEngineId, &'a [u8])>,
{
Some(4)
}
@@ -224,22 +225,13 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
sp_tracing::try_init_simple();
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
let invulnerables = vec![1, 2];
let keys = invulnerables.iter().map(|i|
(
*i,
*i,
MockSessionKeys { aura: UintAuthorityId(*i) },
)
).collect::<Vec<_>>();
let keys = invulnerables
.iter()
.map(|i| (*i, *i, MockSessionKeys { aura: UintAuthorityId(*i) }))
.collect::<Vec<_>>();
let balances = pallet_balances::GenesisConfig::<Test> {
balances: vec![
(1, 100),
(2, 100),
(3, 100),
(4, 100),
(5, 100),
],
balances: vec![(1, 100), (2, 100), (3, 100), (4, 100), (5, 100)],
};
let collator_selection = collator_selection::GenesisConfig::<Test> {
desired_candidates: 2,
@@ -256,7 +248,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
}
pub fn initialize_to_block(n: u64) {
for i in System::block_number()+1..=n {
for i in System::block_number() + 1..=n {
System::set_block_number(i);
<AllPallets as frame_support::traits::OnInitialize<u64>>::on_initialize(i);
}
+11 -25
View File
@@ -13,15 +13,14 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use crate as collator_selection;
use crate::{mock::*, Error, CandidateInfo};
use crate::{mock::*, CandidateInfo, Error};
use frame_support::{
assert_noop, assert_ok,
traits::{OnInitialize, Currency, GenesisBuild},
traits::{Currency, GenesisBuild, OnInitialize},
};
use sp_runtime::traits::BadOrigin;
use pallet_balances::Error as BalancesError;
use sp_runtime::traits::BadOrigin;
#[test]
fn basic_setup_works() {
@@ -59,7 +58,10 @@ fn set_desired_candidates_works() {
assert_eq!(CollatorSelection::desired_candidates(), 2);
// can set
assert_ok!(CollatorSelection::set_desired_candidates(Origin::signed(RootAccount::get()), 7));
assert_ok!(CollatorSelection::set_desired_candidates(
Origin::signed(RootAccount::get()),
7
));
assert_eq!(CollatorSelection::desired_candidates(), 7);
// rejects bad origin
@@ -239,11 +241,7 @@ fn authorship_event_handler() {
// triggers `note_author`
Authorship::on_initialize(1);
let collator = CandidateInfo {
who: 4,
deposit: 10,
};
let collator = CandidateInfo { who: 4, deposit: 10 };
assert_eq!(CollatorSelection::candidates(), vec![collator]);
assert_eq!(CollatorSelection::last_authored_block(4), 0);
@@ -268,11 +266,7 @@ fn fees_edgecases() {
// triggers `note_author`
Authorship::on_initialize(1);
let collator = CandidateInfo {
who: 4,
deposit: 10,
};
let collator = CandidateInfo { who: 4, deposit: 10 };
assert_eq!(CollatorSelection::candidates(), vec![collator]);
assert_eq!(CollatorSelection::last_authored_block(4), 0);
@@ -334,10 +328,7 @@ fn kick_mechanism() {
assert_eq!(CollatorSelection::candidates().len(), 1);
// 3 will be kicked after 1 session delay
assert_eq!(SessionHandlerCollators::get(), vec![1, 2, 3, 4]);
let collator = CandidateInfo {
who: 4,
deposit: 10,
};
let collator = CandidateInfo { who: 4, deposit: 10 };
assert_eq!(CollatorSelection::candidates(), vec![collator]);
assert_eq!(CollatorSelection::last_authored_block(4), 20);
initialize_to_block(30);
@@ -362,10 +353,7 @@ fn should_not_kick_mechanism_too_few() {
assert_eq!(CollatorSelection::candidates().len(), 1);
// 3 will be kicked after 1 session delay
assert_eq!(SessionHandlerCollators::get(), vec![1, 2, 3, 5]);
let collator = CandidateInfo {
who: 5,
deposit: 10,
};
let collator = CandidateInfo { who: 5, deposit: 10 };
assert_eq!(CollatorSelection::candidates(), vec![collator]);
assert_eq!(CollatorSelection::last_authored_block(4), 20);
initialize_to_block(30);
@@ -376,7 +364,6 @@ fn should_not_kick_mechanism_too_few() {
});
}
#[test]
#[should_panic = "duplicate invulnerables in genesis."]
fn cannot_set_genesis_value_twice() {
@@ -391,5 +378,4 @@ fn cannot_set_genesis_value_twice() {
};
// collator selection must be initialized before session.
collator_selection.assimilate_storage(&mut t).unwrap();
}
@@ -18,7 +18,10 @@
#![allow(unused_parens)]
#![allow(unused_imports)]
use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
use frame_support::{
traits::Get,
weights::{constants::RocksDbWeight, Weight},
};
use sp_std::marker::PhantomData;
// The weight info trait for `pallet_collator_selection`.
@@ -35,28 +38,26 @@ pub trait WeightInfo {
/// Weights for pallet_collator_selection using the Substrate node and recommended hardware.
pub struct SubstrateWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
fn set_invulnerables(b: u32, ) -> Weight {
fn set_invulnerables(b: u32) -> Weight {
(18_563_000 as Weight)
// Standard Error: 0
.saturating_add((68_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn set_desired_candidates() -> Weight {
(16_363_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
(16_363_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn set_candidacy_bond() -> Weight {
(16_840_000 as Weight)
.saturating_add(T::DbWeight::get().writes(1 as Weight))
(16_840_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight))
}
fn register_as_candidate(c: u32, ) -> Weight {
fn register_as_candidate(c: u32) -> Weight {
(71_196_000 as Weight)
// Standard Error: 0
.saturating_add((198_000 as Weight).saturating_mul(c as Weight))
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
fn leave_intent(c: u32, ) -> Weight {
fn leave_intent(c: u32) -> Weight {
(55_336_000 as Weight)
// Standard Error: 0
.saturating_add((151_000 as Weight).saturating_mul(c as Weight))
@@ -68,7 +69,7 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
}
fn new_session(r: u32, c: u32, ) -> Weight {
fn new_session(r: u32, c: u32) -> Weight {
(0 as Weight)
// Standard Error: 1_010_000
.saturating_add((109_961_000 as Weight).saturating_mul(r as Weight))
@@ -81,31 +82,28 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
}
}
// For backwards compatibility and tests
impl WeightInfo for () {
fn set_invulnerables(b: u32, ) -> Weight {
fn set_invulnerables(b: u32) -> Weight {
(18_563_000 as Weight)
// Standard Error: 0
.saturating_add((68_000 as Weight).saturating_mul(b as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
fn set_desired_candidates() -> Weight {
(16_363_000 as Weight)
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
(16_363_000 as Weight).saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
fn set_candidacy_bond() -> Weight {
(16_840_000 as Weight)
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
(16_840_000 as Weight).saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
fn register_as_candidate(c: u32, ) -> Weight {
fn register_as_candidate(c: u32) -> Weight {
(71_196_000 as Weight)
// Standard Error: 0
.saturating_add((198_000 as Weight).saturating_mul(c as Weight))
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
}
fn leave_intent(c: u32, ) -> Weight {
fn leave_intent(c: u32) -> Weight {
(55_336_000 as Weight)
// Standard Error: 0
.saturating_add((151_000 as Weight).saturating_mul(c as Weight))
@@ -117,7 +115,7 @@ impl WeightInfo for () {
.saturating_add(RocksDbWeight::get().reads(3 as Weight))
.saturating_add(RocksDbWeight::get().writes(4 as Weight))
}
fn new_session(r: u32, c: u32, ) -> Weight {
fn new_session(r: u32, c: u32) -> Weight {
(0 as Weight)
// Standard Error: 1_010_000
.saturating_add((109_961_000 as Weight).saturating_mul(r as Weight))