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
+45 -45
View File
@@ -26,22 +26,27 @@
//! These roots and proofs of inclusion can be generated at any time during the current session.
//! Afterwards, the proofs can be fed to a consensus module when reporting misbehavior.
use sp_std::prelude::*;
use codec::{Encode, Decode};
use sp_runtime::KeyTypeId;
use sp_runtime::traits::{Convert, OpaqueKeys};
use sp_session::{MembershipProof, ValidatorCount};
use super::{Module as SessionModule, SessionIndex};
use codec::{Decode, Encode};
use frame_support::{
decl_module, decl_storage, Parameter, print,
decl_module, decl_storage, print,
traits::{ValidatorSet, ValidatorSetWithIdentification},
Parameter,
};
use sp_runtime::{
traits::{Convert, OpaqueKeys},
KeyTypeId,
};
use sp_session::{MembershipProof, ValidatorCount};
use sp_std::prelude::*;
use sp_trie::{
trie_types::{TrieDB, TrieDBMut},
MemoryDB, Recorder, Trie, TrieMut, EMPTY_PREFIX,
};
use sp_trie::{MemoryDB, Trie, TrieMut, Recorder, EMPTY_PREFIX};
use sp_trie::trie_types::{TrieDBMut, TrieDB};
use super::{SessionIndex, Module as SessionModule};
mod shared;
pub mod offchain;
pub mod onchain;
mod shared;
/// Config necessary for the historical module.
pub trait Config: super::Config {
@@ -165,7 +170,7 @@ impl<T: Config, I: SessionManager<T::ValidatorId, T::FullIdentification>> NoteHi
Err(reason) => {
print("Failed to generate historical ancestry-inclusion proof.");
print(reason);
}
},
};
} else {
let previous_index = new_index.saturating_sub(1);
@@ -201,7 +206,8 @@ where
}
/// A tuple of the validator's ID and their full identification.
pub type IdentificationTuple<T> = (<T as crate::Config>::ValidatorId, <T as Config>::FullIdentification);
pub type IdentificationTuple<T> =
(<T as crate::Config>::ValidatorId, <T as Config>::FullIdentification);
/// A trie instance for checking and generating proofs.
pub struct ProvingTrie<T: Config> {
@@ -211,7 +217,8 @@ pub struct ProvingTrie<T: Config> {
impl<T: Config> ProvingTrie<T> {
fn generate_for<I>(validators: I) -> Result<Self, &'static str>
where I: IntoIterator<Item=(T::ValidatorId, T::FullIdentification)>
where
I: IntoIterator<Item = (T::ValidatorId, T::FullIdentification)>,
{
let mut db = MemoryDB::default();
let mut root = Default::default();
@@ -230,23 +237,20 @@ impl<T: Config> ProvingTrie<T> {
// map each key to the owner index.
for key_id in T::Keys::key_ids() {
let key = keys.get_raw(*key_id);
let res = (key_id, key).using_encoded(|k|
i.using_encoded(|v| trie.insert(k, v))
);
let res =
(key_id, key).using_encoded(|k| i.using_encoded(|v| trie.insert(k, v)));
let _ = res.map_err(|_| "failed to insert into trie")?;
}
// map each owner index to the full identification.
let _ = i.using_encoded(|k| full_id.using_encoded(|v| trie.insert(k, v)))
let _ = i
.using_encoded(|k| full_id.using_encoded(|v| trie.insert(k, v)))
.map_err(|_| "failed to insert into trie")?;
}
}
Ok(ProvingTrie {
db,
root,
})
Ok(ProvingTrie { db, root })
}
fn from_nodes(root: T::Hash, nodes: &[Vec<u8>]) -> Self {
@@ -257,10 +261,7 @@ impl<T: Config> ProvingTrie<T> {
HashDBT::insert(&mut memory_db, EMPTY_PREFIX, &node[..]);
}
ProvingTrie {
db: memory_db,
root,
}
ProvingTrie { db: memory_db, root }
}
/// Prove the full verification data for a given key and key ID.
@@ -291,11 +292,13 @@ impl<T: Config> ProvingTrie<T> {
// nodes within the current `MemoryDB` are insufficient to query the item.
fn query(&self, key_id: KeyTypeId, key_data: &[u8]) -> Option<IdentificationTuple<T>> {
let trie = TrieDB::new(&self.db, &self.root).ok()?;
let val_idx = (key_id, key_data).using_encoded(|s| trie.get(s))
let val_idx = (key_id, key_data)
.using_encoded(|s| trie.get(s))
.ok()?
.and_then(|raw| u32::decode(&mut &*raw).ok())?;
val_idx.using_encoded(|s| trie.get(s))
val_idx
.using_encoded(|s| trie.get(s))
.ok()?
.and_then(|raw| <IdentificationTuple<T>>::decode(&mut &*raw).ok())
}
@@ -322,12 +325,11 @@ impl<T: Config, D: AsRef<[u8]>> frame_support::traits::KeyOwnerProofSystem<(KeyT
let trie = ProvingTrie::<T>::generate_for(validators).ok()?;
let (id, data) = key;
trie.prove(id, data.as_ref())
.map(|trie_nodes| MembershipProof {
session,
trie_nodes,
validator_count: count,
})
trie.prove(id, data.as_ref()).map(|trie_nodes| MembershipProof {
session,
trie_nodes,
validator_count: count,
})
}
fn check_proof(key: (KeyTypeId, D), proof: Self::Proof) -> Option<IdentificationTuple<T>> {
@@ -339,7 +341,7 @@ impl<T: Config, D: AsRef<[u8]>> frame_support::traits::KeyOwnerProofSystem<(KeyT
let count = <SessionModule<T>>::validators().len() as ValidatorCount;
if count != proof.validator_count {
return None;
return None
}
Some((owner, id))
@@ -349,7 +351,7 @@ impl<T: Config, D: AsRef<[u8]>> frame_support::traits::KeyOwnerProofSystem<(KeyT
let (root, count) = <HistoricalSessions<T>>::get(&proof.session)?;
if count != proof.validator_count {
return None;
return None
}
let trie = ProvingTrie::<T>::from_nodes(root, &proof.trie_nodes);
@@ -361,22 +363,22 @@ impl<T: Config, D: AsRef<[u8]>> frame_support::traits::KeyOwnerProofSystem<(KeyT
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use sp_runtime::key_types::DUMMY;
use sp_runtime::testing::UintAuthorityId;
use crate::mock::{
NEXT_VALIDATORS, force_new_session,
set_next_validators, Test, System, Session,
force_new_session, set_next_validators, Session, System, Test, NEXT_VALIDATORS,
};
use frame_support::traits::{KeyOwnerProofSystem, OnInitialize};
use frame_support::BasicExternalities;
use frame_support::{
traits::{KeyOwnerProofSystem, OnInitialize},
BasicExternalities,
};
use sp_runtime::{key_types::DUMMY, testing::UintAuthorityId};
type Historical = Module<Test>;
pub(crate) fn new_test_ext() -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
let keys: Vec<_> = NEXT_VALIDATORS.with(|l|
let keys: Vec<_> = NEXT_VALIDATORS.with(|l| {
l.borrow().iter().cloned().map(|i| (i, i, UintAuthorityId(i).into())).collect()
);
});
BasicExternalities::execute_with_storage(&mut t, || {
for (ref k, ..) in &keys {
frame_system::Pallet::<Test>::inc_providers(k);
@@ -430,7 +432,6 @@ pub(crate) mod tests {
System::set_block_number(i);
Session::on_initialize(i);
}
assert_eq!(StoredRange::get(), Some((0, 100)));
@@ -461,7 +462,6 @@ pub(crate) mod tests {
System::set_block_number(i);
Session::on_initialize(i);
}
assert_eq!(StoredRange::get(), Some((100, 200)));
@@ -27,17 +27,18 @@
use sp_runtime::{
offchain::storage::{MutateStorageError, StorageRetrievalError, StorageValueRef},
KeyTypeId
KeyTypeId,
};
use sp_session::MembershipProof;
use super::super::{Pallet as SessionModule, SessionIndex};
use super::{IdentificationTuple, ProvingTrie, Config};
use super::{
super::{Pallet as SessionModule, SessionIndex},
Config, IdentificationTuple, ProvingTrie,
};
use super::shared;
use sp_std::prelude::*;
/// A set of validators, which was used for a fixed session index.
struct ValidatorSet<T: Config> {
validator_set: Vec<IdentificationTuple<T>>,
@@ -87,15 +88,13 @@ pub fn prove_session_membership<T: Config, D: AsRef<[u8]>>(
let trie = ProvingTrie::<T>::generate_for(validators.into_iter()).ok()?;
let (id, data) = session_key;
trie.prove(id, data.as_ref())
.map(|trie_nodes| MembershipProof {
session: session_index,
trie_nodes,
validator_count: count,
})
trie.prove(id, data.as_ref()).map(|trie_nodes| MembershipProof {
session: session_index,
trie_nodes,
validator_count: count,
})
}
/// Attempt to prune anything that is older than `first_to_keep` session index.
///
/// Due to re-organisation it could be that the `first_to_keep` might be less
@@ -104,18 +103,20 @@ pub fn prove_session_membership<T: Config, D: AsRef<[u8]>>(
pub fn prune_older_than<T: Config>(first_to_keep: SessionIndex) {
let derived_key = shared::LAST_PRUNE.to_vec();
let entry = StorageValueRef::persistent(derived_key.as_ref());
match entry.mutate(|current: Result<Option<SessionIndex>, StorageRetrievalError>| -> Result<_, ()> {
match current {
Ok(Some(current)) if current < first_to_keep => Ok(first_to_keep),
// do not move the cursor, if the new one would be behind ours
Ok(Some(current)) => Ok(current),
Ok(None) => Ok(first_to_keep),
// if the storage contains undecodable data, overwrite with current anyways
// which might leak some entries being never purged, but that is acceptable
// in this context
Err(_) => Ok(first_to_keep),
}
}) {
match entry.mutate(
|current: Result<Option<SessionIndex>, StorageRetrievalError>| -> Result<_, ()> {
match current {
Ok(Some(current)) if current < first_to_keep => Ok(first_to_keep),
// do not move the cursor, if the new one would be behind ours
Ok(Some(current)) => Ok(current),
Ok(None) => Ok(first_to_keep),
// if the storage contains undecodable data, overwrite with current anyways
// which might leak some entries being never purged, but that is acceptable
// in this context
Err(_) => Ok(first_to_keep),
}
},
) {
Ok(new_value) => {
// on a re-org this is not necessarily true, with the above they might be equal
if new_value < first_to_keep {
@@ -124,9 +125,9 @@ pub fn prune_older_than<T: Config>(first_to_keep: SessionIndex) {
let _ = StorageValueRef::persistent(derived_key.as_ref()).clear();
}
}
}
Err(MutateStorageError::ConcurrentModification(_)) => {}
Err(MutateStorageError::ValueFunctionFailed(_)) => {}
},
Err(MutateStorageError::ConcurrentModification(_)) => {},
Err(MutateStorageError::ValueFunctionFailed(_)) => {},
}
}
@@ -141,23 +142,22 @@ pub fn keep_newest<T: Config>(n_to_keep: usize) {
#[cfg(test)]
mod tests {
use super::super::{onchain, Module};
use super::*;
use super::{
super::{onchain, Module},
*,
};
use crate::mock::{
force_new_session, set_next_validators, Session, System, Test, NEXT_VALIDATORS,
};
use codec::Encode;
use frame_support::traits::{KeyOwnerProofSystem, OnInitialize};
use sp_core::crypto::key_types::DUMMY;
use sp_core::offchain::{
testing::TestOffchainExt,
OffchainDbExt,
OffchainWorkerExt,
StorageKind,
use sp_core::{
crypto::key_types::DUMMY,
offchain::{testing::TestOffchainExt, OffchainDbExt, OffchainWorkerExt, StorageKind},
};
use sp_runtime::testing::UintAuthorityId;
use frame_support::BasicExternalities;
use sp_runtime::testing::UintAuthorityId;
type Historical = Module<Test>;
@@ -166,16 +166,16 @@ mod tests {
.build_storage::<Test>()
.expect("Failed to create test externalities.");
let keys: Vec<_> = NEXT_VALIDATORS.with(|l|
let keys: Vec<_> = NEXT_VALIDATORS.with(|l| {
l.borrow().iter().cloned().map(|i| (i, i, UintAuthorityId(i).into())).collect()
);
});
BasicExternalities::execute_with_storage(&mut t, || {
for (ref k, ..) in &keys {
frame_system::Pallet::<Test>::inc_providers(k);
}
});
crate::GenesisConfig::<Test>{ keys }.assimilate_storage(&mut t).unwrap();
crate::GenesisConfig::<Test> { keys }.assimilate_storage(&mut t).unwrap();
let mut ext = sp_io::TestExternalities::new(t);
@@ -193,13 +193,13 @@ mod tests {
#[test]
fn encode_decode_roundtrip() {
use super::super::{super::Config as SessionConfig, Config as HistoricalConfig};
use codec::{Decode, Encode};
use super::super::super::Config as SessionConfig;
use super::super::Config as HistoricalConfig;
let sample = (
22u32 as <Test as SessionConfig>::ValidatorId,
7_777_777 as <Test as HistoricalConfig>::FullIdentification);
22u32 as <Test as SessionConfig>::ValidatorId,
7_777_777 as <Test as HistoricalConfig>::FullIdentification,
);
let encoded = sample.encode();
let decoded = Decode::decode(&mut encoded.as_slice()).expect("Must decode");
@@ -210,7 +210,7 @@ mod tests {
fn onchain_to_offchain() {
let mut ext = new_test_ext();
const DATA: &[u8] = &[7,8,9,10,11];
const DATA: &[u8] = &[7, 8, 9, 10, 11];
ext.execute_with(|| {
b"alphaomega"[..].using_encoded(|key| sp_io::offchain_index::set(key, DATA));
});
@@ -218,15 +218,13 @@ mod tests {
ext.persist_offchain_overlay();
ext.execute_with(|| {
let data =
b"alphaomega"[..].using_encoded(|key| {
let data = b"alphaomega"[..].using_encoded(|key| {
sp_io::offchain::local_storage_get(StorageKind::PERSISTENT, key)
});
assert_eq!(data, Some(DATA.to_vec()));
});
}
#[test]
fn historical_proof_offchain() {
let mut ext = new_test_ext();
@@ -251,8 +249,6 @@ mod tests {
ext.persist_offchain_overlay();
ext.execute_with(|| {
System::set_block_number(2);
Session::on_initialize(2);
assert_eq!(<SessionModule<Test>>::current_index(), 2);
@@ -20,9 +20,10 @@
use codec::Encode;
use sp_runtime::traits::Convert;
use super::super::Config as SessionConfig;
use super::super::{Pallet as SessionModule, SessionIndex};
use super::Config as HistoricalConfig;
use super::{
super::{Config as SessionConfig, Pallet as SessionModule, SessionIndex},
Config as HistoricalConfig,
};
use super::shared;
use sp_std::prelude::*;
@@ -18,10 +18,9 @@
//! Shared logic between on-chain and off-chain components used for slashing using an off-chain
//! worker.
use super::SessionIndex;
use sp_std::prelude::*;
use codec::Encode;
use sp_std::prelude::*;
pub(super) const PREFIX: &[u8] = b"session_historical";
pub(super) const LAST_PRUNE: &[u8] = b"session_historical_last_prune";
@@ -30,10 +29,11 @@ pub(super) const LAST_PRUNE: &[u8] = b"session_historical_last_prune";
pub(super) fn derive_key<P: AsRef<[u8]>>(prefix: P, session_index: SessionIndex) -> Vec<u8> {
let prefix: &[u8] = prefix.as_ref();
session_index.using_encoded(|encoded_session_index| {
prefix.into_iter()
prefix
.into_iter()
.chain(b"/".into_iter())
.chain(encoded_session_index.into_iter())
.copied()
.collect::<Vec<u8>>()
})
}
}
+68 -60
View File
@@ -106,31 +106,37 @@
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "historical")]
pub mod historical;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
#[cfg(feature = "historical")]
pub mod historical;
pub mod weights;
use sp_std::{prelude::*, marker::PhantomData, ops::{Sub, Rem}};
use codec::Decode;
use frame_support::{
decl_error, decl_event, decl_module, decl_storage,
dispatch::{self, DispatchError, DispatchResult},
ensure,
traits::{
EstimateNextNewSession, EstimateNextSessionRotation, FindAuthor, Get, OneSessionHandler,
ValidatorRegistration, ValidatorSet,
},
weights::Weight,
ConsensusEngineId, Parameter,
};
use frame_system::ensure_signed;
use sp_runtime::{
traits::{AtLeast32BitUnsigned, Convert, Member, One, OpaqueKeys, Zero},
KeyTypeId, Perbill, Permill, RuntimeAppPublic,
};
use sp_staking::SessionIndex;
use frame_support::{
ensure, decl_module, decl_event, decl_storage, decl_error, ConsensusEngineId, Parameter,
traits::{
Get, FindAuthor, ValidatorRegistration, EstimateNextSessionRotation, EstimateNextNewSession,
OneSessionHandler, ValidatorSet,
},
dispatch::{self, DispatchResult, DispatchError},
weights::Weight,
use sp_std::{
marker::PhantomData,
ops::{Rem, Sub},
prelude::*,
};
use frame_system::ensure_signed;
pub use weights::WeightInfo;
/// Decides whether the session should be ended.
@@ -147,10 +153,10 @@ pub trait ShouldEndSession<BlockNumber> {
pub struct PeriodicSessions<Period, Offset>(PhantomData<(Period, Offset)>);
impl<
BlockNumber: Rem<Output = BlockNumber> + Sub<Output = BlockNumber> + Zero + PartialOrd,
Period: Get<BlockNumber>,
Offset: Get<BlockNumber>,
> ShouldEndSession<BlockNumber> for PeriodicSessions<Period, Offset>
BlockNumber: Rem<Output = BlockNumber> + Sub<Output = BlockNumber> + Zero + PartialOrd,
Period: Get<BlockNumber>,
Offset: Get<BlockNumber>,
> ShouldEndSession<BlockNumber> for PeriodicSessions<Period, Offset>
{
fn should_end_session(now: BlockNumber) -> bool {
let offset = Offset::get();
@@ -159,10 +165,10 @@ impl<
}
impl<
BlockNumber: AtLeast32BitUnsigned + Clone,
Period: Get<BlockNumber>,
Offset: Get<BlockNumber>
> EstimateNextSessionRotation<BlockNumber> for PeriodicSessions<Period, Offset>
BlockNumber: AtLeast32BitUnsigned + Clone,
Period: Get<BlockNumber>,
Offset: Get<BlockNumber>,
> EstimateNextSessionRotation<BlockNumber> for PeriodicSessions<Period, Offset>
{
fn average_session_length() -> BlockNumber {
Period::get()
@@ -177,15 +183,9 @@ impl<
// (0% is never returned).
let progress = if now >= offset {
let current = (now - offset) % period.clone() + One::one();
Some(Permill::from_rational(
current.clone(),
period.clone(),
))
Some(Permill::from_rational(current.clone(), period.clone()))
} else {
Some(Permill::from_rational(
now + One::one(),
offset,
))
Some(Permill::from_rational(now + One::one(), offset))
};
// Weight note: `estimate_current_session_progress` has no storage reads and trivial
@@ -257,7 +257,9 @@ pub trait SessionManager<ValidatorId> {
}
impl<A> SessionManager<A> for () {
fn new_session(_: SessionIndex) -> Option<Vec<A>> { None }
fn new_session(_: SessionIndex) -> Option<Vec<A>> {
None
}
fn start_session(_: SessionIndex) {}
fn end_session(_: SessionIndex) {}
}
@@ -591,9 +593,8 @@ impl<T: Config> Module<T> {
// Get queued session keys and validators.
let session_keys = <QueuedKeys<T>>::get();
let validators = session_keys.iter()
.map(|(validator, _)| validator.clone())
.collect::<Vec<_>>();
let validators =
session_keys.iter().map(|(validator, _)| validator.clone()).collect::<Vec<_>>();
<Validators<T>>::put(&validators);
if changed {
@@ -609,16 +610,15 @@ impl<T: Config> Module<T> {
// Get next validator set.
let maybe_next_validators = T::SessionManager::new_session(session_index + 1);
let (next_validators, next_identities_changed)
= if let Some(validators) = maybe_next_validators
{
// NOTE: as per the documentation on `OnSessionEnding`, we consider
// the validator set as having changed even if the validators are the
// same as before, as underlying economic conditions may have changed.
(validators, true)
} else {
(<Validators<T>>::get(), false)
};
let (next_validators, next_identities_changed) =
if let Some(validators) = maybe_next_validators {
// NOTE: as per the documentation on `OnSessionEnding`, we consider
// the validator set as having changed even if the validators are the
// same as before, as underlying economic conditions may have changed.
(validators, true)
} else {
(<Validators<T>>::get(), false)
};
// Queue next session keys.
let (queued_amalgamated, next_changed) = {
@@ -628,7 +628,9 @@ impl<T: Config> Module<T> {
let mut now_session_keys = session_keys.iter();
let mut check_next_changed = |keys: &T::Keys| {
if changed { return }
if changed {
return
}
// since a new validator set always leads to `changed` starting
// as true, we can ensure that `now_session_keys` and `next_validators`
// have the same length. this function is called once per iteration.
@@ -639,7 +641,8 @@ impl<T: Config> Module<T> {
}
}
};
let queued_amalgamated = next_validators.into_iter()
let queued_amalgamated = next_validators
.into_iter()
.map(|a| {
let k = Self::load_keys(&a).unwrap_or_default();
check_next_changed(&k);
@@ -657,11 +660,7 @@ impl<T: Config> Module<T> {
Self::deposit_event(Event::NewSession(session_index));
// Tell everyone about the new session keys.
T::SessionHandler::on_new_session::<T::Keys>(
changed,
&session_keys,
&queued_amalgamated,
);
T::SessionHandler::on_new_session::<T::Keys>(changed, &session_keys, &queued_amalgamated);
}
/// Disable the validator of index `i`.
@@ -695,7 +694,11 @@ impl<T: Config> Module<T> {
/// session is already disabled.
/// If used with the staking module it allows to force a new era in such case.
pub fn disable(c: &T::ValidatorId) -> sp_std::result::Result<bool, ()> {
Self::validators().iter().position(|i| i == c).map(Self::disable_index).ok_or(())
Self::validators()
.iter()
.position(|i| i == c)
.map(Self::disable_index)
.ok_or(())
}
/// Upgrade the key type from some old type to a new type. Supports adding
@@ -713,7 +716,8 @@ impl<T: Config> Module<T> {
/// it's recommended to initialize the keys to a (unique) dummy value with the expectation
/// that all validators should invoke `set_keys` before those keys are actually
/// required.
pub fn upgrade_keys<Old, F>(upgrade: F) where
pub fn upgrade_keys<Old, F>(upgrade: F)
where
Old: OpaqueKeys + Member + Decode,
F: Fn(T::ValidatorId, Old) -> T::Keys,
{
@@ -738,13 +742,13 @@ impl<T: Config> Module<T> {
Some(new_keys)
});
let _ = <QueuedKeys<T>>::translate::<Vec<(T::ValidatorId, Old)>, _>(
|k| {
k.map(|k| k.into_iter()
let _ = <QueuedKeys<T>>::translate::<Vec<(T::ValidatorId, Old)>, _>(|k| {
k.map(|k| {
k.into_iter()
.map(|(val, old_keys)| (val.clone(), upgrade(val, old_keys)))
.collect::<Vec<_>>())
}
);
.collect::<Vec<_>>()
})
});
}
/// Perform the set_key operation, checking for duplicates. Does not set `Changed`.
@@ -771,7 +775,10 @@ impl<T: Config> Module<T> {
///
/// This does not ensure that the reference counter in system is incremented appropriately, it
/// must be done by the caller or the keys will be leaked in storage.
fn inner_set_keys(who: &T::ValidatorId, keys: T::Keys) -> Result<Option<T::Keys>, DispatchError> {
fn inner_set_keys(
who: &T::ValidatorId,
keys: T::Keys,
) -> Result<Option<T::Keys>, DispatchError> {
let old_keys = Self::load_keys(who);
for id in T::Keys::key_ids() {
@@ -789,7 +796,7 @@ impl<T: Config> Module<T> {
if let Some(old) = old_keys.as_ref().map(|k| k.get_raw(*id)) {
if key == old {
continue;
continue
}
Self::clear_key_owner(*id, old);
@@ -864,7 +871,8 @@ impl<T: Config, Inner: FindAuthor<u32>> FindAuthor<T::ValidatorId>
for FindAccountFromAuthorIndex<T, Inner>
{
fn find_author<'a, I>(digests: I) -> Option<T::ValidatorId>
where I: 'a + IntoIterator<Item=(ConsensusEngineId, &'a [u8])>
where
I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
{
let i = Inner::find_author(digests)?;
+28 -22
View File
@@ -18,18 +18,19 @@
//! Mock helpers for Session.
use super::*;
use std::cell::RefCell;
use frame_support::{parameter_types, BasicExternalities};
use sp_core::{crypto::key_types::DUMMY, H256};
use sp_runtime::{
Perbill, impl_opaque_keys,
traits::{BlakeTwo256, IdentityLookup, ConvertInto},
testing::{Header, UintAuthorityId},
};
use sp_staking::SessionIndex;
use crate as pallet_session;
#[cfg(feature = "historical")]
use crate::historical as pallet_session_historical;
use frame_support::{parameter_types, BasicExternalities};
use sp_core::{crypto::key_types::DUMMY, H256};
use sp_runtime::{
impl_opaque_keys,
testing::{Header, UintAuthorityId},
traits::{BlakeTwo256, ConvertInto, IdentityLookup},
Perbill,
};
use sp_staking::SessionIndex;
use std::cell::RefCell;
impl_opaque_keys! {
pub struct MockSessionKeys {
@@ -114,7 +115,12 @@ pub struct TestShouldEndSession;
impl ShouldEndSession<u64> for TestShouldEndSession {
fn should_end_session(now: u64) -> bool {
let l = SESSION_LENGTH.with(|l| *l.borrow());
now % l == 0 || FORCE_SESSION_END.with(|l| { let r = *l.borrow(); *l.borrow_mut() = false; r })
now % l == 0 ||
FORCE_SESSION_END.with(|l| {
let r = *l.borrow();
*l.borrow_mut() = false;
r
})
}
}
@@ -128,11 +134,12 @@ impl SessionHandler<u64> for TestSessionHandler {
_queued_validators: &[(u64, T)],
) {
SESSION_CHANGED.with(|l| *l.borrow_mut() = changed);
AUTHORITIES.with(|l|
*l.borrow_mut() = validators.iter()
AUTHORITIES.with(|l| {
*l.borrow_mut() = validators
.iter()
.map(|(_, id)| id.get::<UintAuthorityId>(DUMMY).unwrap_or_default())
.collect()
);
});
}
fn on_disabled(_validator_index: usize) {
DISABLED.with(|l| *l.borrow_mut() = true)
@@ -167,9 +174,7 @@ impl SessionManager<u64> for TestSessionManager {
impl crate::historical::SessionManager<u64, u64> for TestSessionManager {
fn end_session(_: SessionIndex) {}
fn start_session(_: SessionIndex) {}
fn new_session(new_index: SessionIndex)
-> Option<Vec<(u64, u64)>>
{
fn new_session(new_index: SessionIndex) -> Option<Vec<(u64, u64)>> {
<Self as SessionManager<_>>::new_session(new_index)
.map(|vals| vals.into_iter().map(|val| (val, val)).collect())
}
@@ -180,11 +185,11 @@ pub fn authorities() -> Vec<UintAuthorityId> {
}
pub fn force_new_session() {
FORCE_SESSION_END.with(|l| *l.borrow_mut() = true )
FORCE_SESSION_END.with(|l| *l.borrow_mut() = true)
}
pub fn set_session_length(x: u64) {
SESSION_LENGTH.with(|l| *l.borrow_mut() = x )
SESSION_LENGTH.with(|l| *l.borrow_mut() = x)
}
pub fn session_changed() -> bool {
@@ -205,9 +210,8 @@ pub fn reset_before_session_end_called() {
pub fn new_test_ext() -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
let keys: Vec<_> = NEXT_VALIDATORS.with(|l|
l.borrow().iter().cloned().map(|i| (i, i, UintAuthorityId(i).into())).collect()
);
let keys: Vec<_> = NEXT_VALIDATORS
.with(|l| l.borrow().iter().cloned().map(|i| (i, i, UintAuthorityId(i).into())).collect());
BasicExternalities::execute_with_storage(&mut t, || {
for (ref k, ..) in &keys {
frame_system::Pallet::<Test>::inc_providers(k);
@@ -216,7 +220,9 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
// An additional identity that we use.
frame_system::Pallet::<Test>::inc_providers(&69);
});
pallet_session::GenesisConfig::<Test> { keys }.assimilate_storage(&mut t).unwrap();
pallet_session::GenesisConfig::<Test> { keys }
.assimilate_storage(&mut t)
.unwrap();
sp_io::TestExternalities::new(t)
}
+45 -70
View File
@@ -18,17 +18,16 @@
// Tests for the Session Pallet
use super::*;
use mock::Test;
use codec::Decode;
use frame_support::{traits::OnInitialize, assert_ok, assert_noop};
use frame_support::{assert_noop, assert_ok, traits::OnInitialize};
use mock::{
authorities, before_session_end_called, force_new_session, new_test_ext,
reset_before_session_end_called, session_changed, set_next_validators, set_session_length,
Origin, PreUpgradeMockSessionKeys, Session, System, Test, SESSION_CHANGED,
TEST_SESSION_CHANGED,
};
use sp_core::crypto::key_types::DUMMY;
use sp_runtime::testing::UintAuthorityId;
use mock::{
SESSION_CHANGED, TEST_SESSION_CHANGED, authorities, force_new_session,
set_next_validators, set_session_length, session_changed, Origin, System, Session,
reset_before_session_end_called, before_session_end_called, new_test_ext,
PreUpgradeMockSessionKeys,
};
fn initialize_block(block: u64) {
SESSION_CHANGED.with(|l| *l.borrow_mut() = false);
@@ -79,10 +78,10 @@ fn authorities_should_track_validators() {
set_next_validators(vec![1, 2]);
force_new_session();
initialize_block(1);
assert_eq!(Session::queued_keys(), vec![
(1, UintAuthorityId(1).into()),
(2, UintAuthorityId(2).into()),
]);
assert_eq!(
Session::queued_keys(),
vec![(1, UintAuthorityId(1).into()), (2, UintAuthorityId(2).into()),]
);
assert_eq!(Session::validators(), vec![1, 2, 3]);
assert_eq!(authorities(), vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)]);
assert!(before_session_end_called());
@@ -90,10 +89,10 @@ fn authorities_should_track_validators() {
force_new_session();
initialize_block(2);
assert_eq!(Session::queued_keys(), vec![
(1, UintAuthorityId(1).into()),
(2, UintAuthorityId(2).into()),
]);
assert_eq!(
Session::queued_keys(),
vec![(1, UintAuthorityId(1).into()), (2, UintAuthorityId(2).into()),]
);
assert_eq!(Session::validators(), vec![1, 2]);
assert_eq!(authorities(), vec![UintAuthorityId(1), UintAuthorityId(2)]);
assert!(before_session_end_called());
@@ -103,22 +102,28 @@ fn authorities_should_track_validators() {
assert_ok!(Session::set_keys(Origin::signed(4), UintAuthorityId(4).into(), vec![]));
force_new_session();
initialize_block(3);
assert_eq!(Session::queued_keys(), vec![
(1, UintAuthorityId(1).into()),
(2, UintAuthorityId(2).into()),
(4, UintAuthorityId(4).into()),
]);
assert_eq!(
Session::queued_keys(),
vec![
(1, UintAuthorityId(1).into()),
(2, UintAuthorityId(2).into()),
(4, UintAuthorityId(4).into()),
]
);
assert_eq!(Session::validators(), vec![1, 2]);
assert_eq!(authorities(), vec![UintAuthorityId(1), UintAuthorityId(2)]);
assert!(before_session_end_called());
force_new_session();
initialize_block(4);
assert_eq!(Session::queued_keys(), vec![
(1, UintAuthorityId(1).into()),
(2, UintAuthorityId(2).into()),
(4, UintAuthorityId(4).into()),
]);
assert_eq!(
Session::queued_keys(),
vec![
(1, UintAuthorityId(1).into()),
(2, UintAuthorityId(2).into()),
(4, UintAuthorityId(4).into()),
]
);
assert_eq!(Session::validators(), vec![1, 2, 4]);
assert_eq!(authorities(), vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(4)]);
});
@@ -288,10 +293,7 @@ fn periodic_session_works() {
// 1/10 of progress.
assert!(P::should_end_session(3u64));
assert_eq!(P::estimate_next_session_rotation(3u64).0.unwrap(), 3);
assert_eq!(
P::estimate_current_session_progress(3u64).0.unwrap(),
Permill::from_percent(10),
);
assert_eq!(P::estimate_current_session_progress(3u64).0.unwrap(), Permill::from_percent(10),);
for i in (1u64..10).map(|i| 3 + i) {
assert!(!P::should_end_session(i));
@@ -314,30 +316,22 @@ fn periodic_session_works() {
// the new session starts and we proceed in 1/10 increments.
assert!(P::should_end_session(13u64));
assert_eq!(P::estimate_next_session_rotation(13u64).0.unwrap(), 23);
assert_eq!(
P::estimate_current_session_progress(13u64).0.unwrap(),
Permill::from_percent(10)
);
assert_eq!(P::estimate_current_session_progress(13u64).0.unwrap(), Permill::from_percent(10));
assert!(!P::should_end_session(14u64));
assert_eq!(P::estimate_next_session_rotation(14u64).0.unwrap(), 23);
assert_eq!(
P::estimate_current_session_progress(14u64).0.unwrap(),
Permill::from_percent(20)
);
assert_eq!(P::estimate_current_session_progress(14u64).0.unwrap(), Permill::from_percent(20));
}
#[test]
fn session_keys_generate_output_works_as_set_keys_input() {
new_test_ext().execute_with(|| {
let new_keys = mock::MockSessionKeys::generate(None);
assert_ok!(
Session::set_keys(
Origin::signed(2),
<mock::Test as Config>::Keys::decode(&mut &new_keys[..]).expect("Decode keys"),
vec![],
)
);
assert_ok!(Session::set_keys(
Origin::signed(2),
<mock::Test as Config>::Keys::decode(&mut &new_keys[..]).expect("Decode keys"),
vec![],
));
});
}
@@ -368,26 +362,13 @@ fn upgrade_keys() {
assert_eq!(mock::VALIDATORS.with(|l| l.borrow().clone()), vec![1, 2, 3]);
new_test_ext().execute_with(|| {
let pre_one = PreUpgradeMockSessionKeys {
a: [1u8; 32],
b: [1u8; 64],
};
let pre_one = PreUpgradeMockSessionKeys { a: [1u8; 32], b: [1u8; 64] };
let pre_two = PreUpgradeMockSessionKeys {
a: [2u8; 32],
b: [2u8; 64],
};
let pre_two = PreUpgradeMockSessionKeys { a: [2u8; 32], b: [2u8; 64] };
let pre_three = PreUpgradeMockSessionKeys {
a: [3u8; 32],
b: [3u8; 64],
};
let pre_three = PreUpgradeMockSessionKeys { a: [3u8; 32], b: [3u8; 64] };
let val_keys = vec![
(1u64, pre_one),
(2u64, pre_two),
(3u64, pre_three),
];
let val_keys = vec![(1u64, pre_one), (2u64, pre_two), (3u64, pre_three)];
// Set `QueuedKeys`.
{
@@ -422,9 +403,7 @@ fn upgrade_keys() {
// Do the upgrade and check sanity.
let mock_keys_for = |val| mock::MockSessionKeys { dummy: UintAuthorityId(val) };
Session::upgrade_keys::<PreUpgradeMockSessionKeys, _>(
|val, _old_keys| mock_keys_for(val),
);
Session::upgrade_keys::<PreUpgradeMockSessionKeys, _>(|val, _old_keys| mock_keys_for(val));
// Check key ownership.
for (i, ref keys) in val_keys.iter() {
@@ -438,11 +417,7 @@ fn upgrade_keys() {
// Check queued keys.
assert_eq!(
Session::queued_keys(),
vec![
(1, mock_keys_for(1)),
(2, mock_keys_for(2)),
(3, mock_keys_for(3)),
],
vec![(1, mock_keys_for(1)), (2, mock_keys_for(2)), (3, mock_keys_for(3)),],
);
for i in 1u64..4 {
+1
View File
@@ -36,6 +36,7 @@
// --template=./.maintain/frame-weight-template.hbs
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]