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
+1 -4
View File
@@ -95,10 +95,7 @@ mod tests {
);
println!("equivocation_proof: {:?}", equivocation_proof);
println!(
"equivocation_proof.encode(): {:?}",
equivocation_proof.encode()
);
println!("equivocation_proof.encode(): {:?}", equivocation_proof.encode());
});
}
}
+2 -1
View File
@@ -19,7 +19,8 @@
//! This file was not auto-generated.
use frame_support::weights::{
Weight, constants::{WEIGHT_PER_MICROS, WEIGHT_PER_NANOS, RocksDbWeight as DbWeight},
constants::{RocksDbWeight as DbWeight, WEIGHT_PER_MICROS, WEIGHT_PER_NANOS},
Weight,
};
impl crate::WeightInfo for () {
+15 -22
View File
@@ -15,7 +15,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//!
//! An opt-in utility module for reporting equivocations.
//!
//! This module defines an offence type for BABE equivocations
@@ -33,22 +32,23 @@
//! When using this module for enabling equivocation reporting it is required
//! that the `ValidateUnsigned` for the BABE pallet is used in the runtime
//! definition.
//!
use frame_support::traits::{Get, KeyOwnerProofSystem};
use sp_consensus_babe::{EquivocationProof, Slot};
use sp_runtime::transaction_validity::{
InvalidTransaction, TransactionPriority, TransactionSource, TransactionValidity,
TransactionValidityError, ValidTransaction,
use sp_runtime::{
transaction_validity::{
InvalidTransaction, TransactionPriority, TransactionSource, TransactionValidity,
TransactionValidityError, ValidTransaction,
},
DispatchResult, Perbill,
};
use sp_runtime::{DispatchResult, Perbill};
use sp_staking::{
offence::{Kind, Offence, OffenceError, ReportOffence},
SessionIndex,
};
use sp_std::prelude::*;
use crate::{Call, Pallet, Config};
use crate::{Call, Config, Pallet};
/// A trait with utility methods for handling equivocation reports in BABE.
/// The trait provides methods for reporting an offence triggered by a valid
@@ -115,9 +115,7 @@ pub struct EquivocationHandler<I, R, L> {
impl<I, R, L> Default for EquivocationHandler<I, R, L> {
fn default() -> Self {
Self {
_phantom: Default::default(),
}
Self { _phantom: Default::default() }
}
}
@@ -188,30 +186,28 @@ impl<T: Config> Pallet<T> {
if let Call::report_equivocation_unsigned(equivocation_proof, key_owner_proof) = call {
// discard equivocation report not coming from the local node
match source {
TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ }
TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ },
_ => {
log::warn!(
target: "runtime::babe",
"rejecting unsigned report equivocation transaction because it is not local/in-block.",
);
return InvalidTransaction::Call.into();
}
return InvalidTransaction::Call.into()
},
}
// check report staleness
is_known_offence::<T>(equivocation_proof, key_owner_proof)?;
let longevity = <T::HandleEquivocation as HandleEquivocation<T>>::ReportLongevity::get();
let longevity =
<T::HandleEquivocation as HandleEquivocation<T>>::ReportLongevity::get();
ValidTransaction::with_tag_prefix("BabeEquivocation")
// We assign the maximum priority for any equivocation report.
.priority(TransactionPriority::max_value())
// Only one equivocation report for the same offender at the same slot.
.and_provides((
equivocation_proof.offender.clone(),
*equivocation_proof.slot,
))
.and_provides((equivocation_proof.offender.clone(), *equivocation_proof.slot))
.longevity(longevity)
// We don't propagate this. This can never be included on a remote node.
.propagate(false)
@@ -235,10 +231,7 @@ fn is_known_offence<T: Config>(
key_owner_proof: &T::KeyOwnerProof,
) -> Result<(), TransactionValidityError> {
// check the membership proof to extract the offender's id
let key = (
sp_consensus_babe::KEY_TYPE,
equivocation_proof.offender.clone(),
);
let key = (sp_consensus_babe::KEY_TYPE, equivocation_proof.offender.clone());
let offender = T::KeyOwnerProofSystem::check_proof(key, key_owner_proof.clone())
.ok_or(InvalidTransaction::BadProof)?;
+85 -117
View File
@@ -24,7 +24,7 @@
use codec::{Decode, Encode};
use frame_support::{
dispatch::DispatchResultWithPostInfo,
traits::{FindAuthor, Get, KeyOwnerProofSystem, OneSessionHandler, OnTimestampSet},
traits::{FindAuthor, Get, KeyOwnerProofSystem, OnTimestampSet, OneSessionHandler},
weights::{Pays, Weight},
};
use sp_application_crypto::Public;
@@ -38,8 +38,8 @@ use sp_std::prelude::*;
use sp_consensus_babe::{
digests::{NextConfigDescriptor, NextEpochDescriptor, PreDigest},
BabeAuthorityWeight, BabeEpochConfiguration, ConsensusLog, Epoch,
EquivocationProof, Slot, BABE_ENGINE_ID,
BabeAuthorityWeight, BabeEpochConfiguration, ConsensusLog, Epoch, EquivocationProof, Slot,
BABE_ENGINE_ID,
};
use sp_consensus_vrf::schnorrkel;
@@ -80,7 +80,7 @@ pub trait EpochChangeTrigger {
pub struct ExternalTrigger;
impl EpochChangeTrigger for ExternalTrigger {
fn trigger<T: Config>(_: T::BlockNumber) { } // nothing - trigger is external.
fn trigger<T: Config>(_: T::BlockNumber) {} // nothing - trigger is external.
}
/// A type signifying to BABE that it should perform epoch changes
@@ -104,9 +104,9 @@ type MaybeRandomness = Option<schnorrkel::Randomness>;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
use super::*;
/// The BABE Pallet
#[pallet::pallet]
@@ -222,11 +222,8 @@ pub mod pallet {
/// Next epoch authorities.
#[pallet::storage]
pub(super) type NextAuthorities<T> = StorageValue<
_,
Vec<(AuthorityId, BabeAuthorityWeight)>,
ValueQuery,
>;
pub(super) type NextAuthorities<T> =
StorageValue<_, Vec<(AuthorityId, BabeAuthorityWeight)>, ValueQuery>;
/// Randomness under construction.
///
@@ -242,13 +239,8 @@ pub mod pallet {
/// TWOX-NOTE: `SegmentIndex` is an increasing integer, so this is okay.
#[pallet::storage]
pub(super) type UnderConstruction<T> = StorageMap<
_,
Twox64Concat,
u32,
Vec<schnorrkel::Randomness>,
ValueQuery,
>;
pub(super) type UnderConstruction<T> =
StorageMap<_, Twox64Concat, u32, Vec<schnorrkel::Randomness>, ValueQuery>;
/// Temporary value (cleared at block finalization) which is `Some`
/// if per-block initialization has already been called for current block.
@@ -270,11 +262,8 @@ pub mod pallet {
/// entropy was fixed (i.e. it was known to chain observers). Since epochs are defined in
/// slots, which may be skipped, the block numbers may not line up with the slot numbers.
#[pallet::storage]
pub(super) type EpochStart<T: Config> = StorageValue<
_,
(T::BlockNumber, T::BlockNumber),
ValueQuery,
>;
pub(super) type EpochStart<T: Config> =
StorageValue<_, (T::BlockNumber, T::BlockNumber), ValueQuery>;
/// How late the current block is compared to its parent.
///
@@ -303,10 +292,7 @@ pub mod pallet {
#[cfg(feature = "std")]
impl Default for GenesisConfig {
fn default() -> Self {
GenesisConfig {
authorities: Default::default(),
epoch_config: Default::default(),
}
GenesisConfig { authorities: Default::default(), epoch_config: Default::default() }
}
}
@@ -315,7 +301,9 @@ pub mod pallet {
fn build(&self) {
SegmentIndex::<T>::put(0);
Pallet::<T>::initialize_authorities(&self.authorities);
EpochConfig::<T>::put(self.epoch_config.clone().expect("epoch_config must not be None"));
EpochConfig::<T>::put(
self.epoch_config.clone().expect("epoch_config must not be None"),
);
}
}
@@ -359,11 +347,7 @@ pub mod pallet {
) -> DispatchResultWithPostInfo {
let reporter = ensure_signed(origin)?;
Self::do_report_equivocation(
Some(reporter),
equivocation_proof,
key_owner_proof,
)
Self::do_report_equivocation(Some(reporter), equivocation_proof, key_owner_proof)
}
/// Report authority equivocation/misbehavior. This method will verify
@@ -423,8 +407,9 @@ pub mod pallet {
pub type BabeKey = [u8; PUBLIC_KEY_LENGTH];
impl<T: Config> FindAuthor<u32> for Pallet<T> {
fn find_author<'a, I>(digests: I) -> Option<u32> where
I: 'a + IntoIterator<Item=(ConsensusEngineId, &'a [u8])>
fn find_author<'a, I>(digests: I) -> Option<u32>
where
I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
{
for (id, mut data) in digests.into_iter() {
if id == BABE_ENGINE_ID {
@@ -433,15 +418,13 @@ impl<T: Config> FindAuthor<u32> for Pallet<T> {
}
}
return None;
return None
}
}
impl<T: Config> IsMember<AuthorityId> for Pallet<T> {
fn is_member(authority_id: &AuthorityId) -> bool {
<Pallet<T>>::authorities()
.iter()
.any(|id| &id.0 == authority_id)
<Pallet<T>>::authorities().iter().any(|id| &id.0 == authority_id)
}
}
@@ -490,7 +473,6 @@ impl<T: Config> Pallet<T> {
/// In other word, this is only accurate if no slots are missed. Given missed slots, the slot
/// number will grow while the block number will not. Hence, the result can be interpreted as an
/// upper bound.
//
// ## IMPORTANT NOTE
//
// This implementation is linked to how [`should_epoch_change`] is working. This might need to
@@ -500,13 +482,11 @@ impl<T: Config> Pallet<T> {
// update this function, you must also update the corresponding weight.
pub fn next_expected_epoch_change(now: T::BlockNumber) -> Option<T::BlockNumber> {
let next_slot = Self::current_epoch_start().saturating_add(T::EpochDuration::get());
next_slot
.checked_sub(*CurrentSlot::<T>::get())
.map(|slots_remaining| {
// This is a best effort guess. Drifts in the slot/block ratio will cause errors here.
let blocks_remaining: T::BlockNumber = slots_remaining.saturated_into();
now.saturating_add(blocks_remaining)
})
next_slot.checked_sub(*CurrentSlot::<T>::get()).map(|slots_remaining| {
// This is a best effort guess. Drifts in the slot/block ratio will cause errors here.
let blocks_remaining: T::BlockNumber = slots_remaining.saturated_into();
now.saturating_add(blocks_remaining)
})
}
/// DANGEROUS: Enact an epoch change. Should be done on every block where `should_epoch_change` has returned `true`,
@@ -553,10 +533,8 @@ impl<T: Config> Pallet<T> {
// so that nodes can track changes.
let next_randomness = NextRandomness::<T>::get();
let next_epoch = NextEpochDescriptor {
authorities: next_authorities,
randomness: next_randomness,
};
let next_epoch =
NextEpochDescriptor { authorities: next_authorities, randomness: next_randomness };
Self::deposit_consensus(ConsensusLog::NextEpochData(next_epoch));
if let Some(next_config) = NextEpochConfig::<T>::get() {
@@ -587,7 +565,8 @@ impl<T: Config> Pallet<T> {
duration: T::EpochDuration::get(),
authorities: Self::authorities(),
randomness: Self::randomness(),
config: EpochConfig::<T>::get().expect("EpochConfig is initialized in genesis; we never `take` or `kill` it; qed"),
config: EpochConfig::<T>::get()
.expect("EpochConfig is initialized in genesis; we never `take` or `kill` it; qed"),
}
}
@@ -606,7 +585,9 @@ impl<T: Config> Pallet<T> {
authorities: NextAuthorities::<T>::get(),
randomness: NextRandomness::<T>::get(),
config: NextEpochConfig::<T>::get().unwrap_or_else(|| {
EpochConfig::<T>::get().expect("EpochConfig is initialized in genesis; we never `take` or `kill` it; qed")
EpochConfig::<T>::get().expect(
"EpochConfig is initialized in genesis; we never `take` or `kill` it; qed",
)
}),
}
}
@@ -617,9 +598,7 @@ impl<T: Config> Pallet<T> {
const PROOF: &str = "slot number is u64; it should relate in some way to wall clock time; \
if u64 is not enough we should crash for safety; qed.";
let epoch_start = epoch_index
.checked_mul(T::EpochDuration::get())
.expect(PROOF);
let epoch_start = epoch_index.checked_mul(T::EpochDuration::get()).expect(PROOF);
epoch_start.checked_add(*GenesisSlot::<T>::get()).expect(PROOF).into()
}
@@ -649,19 +628,22 @@ impl<T: Config> Pallet<T> {
// => let's ensure that we only modify the storage once per block
let initialized = Self::initialized().is_some();
if initialized {
return;
return
}
let maybe_pre_digest: Option<PreDigest> = <frame_system::Pallet<T>>::digest()
.logs
.iter()
.filter_map(|s| s.as_pre_runtime())
.filter_map(|(id, mut data)| if id == BABE_ENGINE_ID {
PreDigest::decode(&mut data).ok()
} else {
None
})
.next();
let maybe_pre_digest: Option<PreDigest> =
<frame_system::Pallet<T>>::digest()
.logs
.iter()
.filter_map(|s| s.as_pre_runtime())
.filter_map(|(id, mut data)| {
if id == BABE_ENGINE_ID {
PreDigest::decode(&mut data).ok()
} else {
None
}
})
.next();
let is_primary = matches!(maybe_pre_digest, Some(PreDigest::Primary(..)));
@@ -697,31 +679,22 @@ impl<T: Config> Pallet<T> {
let authority_index = digest.authority_index();
// Extract out the VRF output if we have it
digest
.vrf_output()
.and_then(|vrf_output| {
// Reconstruct the bytes of VRFInOut using the authority id.
Authorities::<T>::get()
.get(authority_index as usize)
.and_then(|author| {
schnorrkel::PublicKey::from_bytes(author.0.as_slice()).ok()
})
.and_then(|pubkey| {
let transcript = sp_consensus_babe::make_transcript(
&Self::randomness(),
current_slot,
EpochIndex::<T>::get(),
);
digest.vrf_output().and_then(|vrf_output| {
// Reconstruct the bytes of VRFInOut using the authority id.
Authorities::<T>::get()
.get(authority_index as usize)
.and_then(|author| schnorrkel::PublicKey::from_bytes(author.0.as_slice()).ok())
.and_then(|pubkey| {
let transcript = sp_consensus_babe::make_transcript(
&Self::randomness(),
current_slot,
EpochIndex::<T>::get(),
);
vrf_output.0.attach_input_hash(
&pubkey,
transcript
).ok()
})
.map(|inout| {
inout.make_bytes(&sp_consensus_babe::BABE_VRF_INOUT_CONTEXT)
})
})
vrf_output.0.attach_input_hash(&pubkey, transcript).ok()
})
.map(|inout| inout.make_bytes(&sp_consensus_babe::BABE_VRF_INOUT_CONTEXT))
})
});
// For primary VRF output we place it in the `Initialized` storage
@@ -774,7 +747,7 @@ impl<T: Config> Pallet<T> {
// validate the equivocation proof
if !sp_consensus_babe::check_equivocation_proof(equivocation_proof) {
return Err(Error::<T>::InvalidEquivocationProof.into());
return Err(Error::<T>::InvalidEquivocationProof.into())
}
let validator_set_count = key_owner_proof.validator_count();
@@ -786,7 +759,7 @@ impl<T: Config> Pallet<T> {
// check that the slot number is consistent with the session index
// in the key ownership proof (i.e. slot is for that epoch)
if epoch_index != session_index {
return Err(Error::<T>::InvalidKeyOwnershipProof.into());
return Err(Error::<T>::InvalidKeyOwnershipProof.into())
}
// check the membership proof and extract the offender's id
@@ -794,12 +767,8 @@ impl<T: Config> Pallet<T> {
let offender = T::KeyOwnerProofSystem::check_proof(key, key_owner_proof)
.ok_or(Error::<T>::InvalidKeyOwnershipProof)?;
let offence = BabeEquivocationOffence {
slot,
validator_set_count,
offender,
session_index,
};
let offence =
BabeEquivocationOffence { slot, validator_set_count, offender, session_index };
let reporters = match reporter {
Some(id) => vec![id],
@@ -837,7 +806,10 @@ impl<T: Config> OnTimestampSet<T::Moment> for Pallet<T> {
let timestamp_slot = moment / slot_duration;
let timestamp_slot = Slot::from(timestamp_slot.saturated_into::<u64>());
assert!(CurrentSlot::<T>::get() == timestamp_slot, "Timestamp slot must match `CurrentSlot`");
assert!(
CurrentSlot::<T>::get() == timestamp_slot,
"Timestamp slot must match `CurrentSlot`"
);
}
}
@@ -850,10 +822,7 @@ impl<T: Config> frame_support::traits::EstimateNextSessionRotation<T::BlockNumbe
let elapsed = CurrentSlot::<T>::get().saturating_sub(Self::current_epoch_start()) + 1;
(
Some(Permill::from_rational(
*elapsed,
T::EpochDuration::get(),
)),
Some(Permill::from_rational(*elapsed, T::EpochDuration::get())),
// Read: Current Slot, Epoch Index, Genesis Slot
T::DbWeight::get().reads(3),
)
@@ -882,22 +851,20 @@ impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
type Key = AuthorityId;
fn on_genesis_session<'a, I: 'a>(validators: I)
where I: Iterator<Item=(&'a T::AccountId, AuthorityId)>
where
I: Iterator<Item = (&'a T::AccountId, AuthorityId)>,
{
let authorities = validators.map(|(_, k)| (k, 1)).collect::<Vec<_>>();
Self::initialize_authorities(&authorities);
}
fn on_new_session<'a, I: 'a>(_changed: bool, validators: I, queued_validators: I)
where I: Iterator<Item=(&'a T::AccountId, AuthorityId)>
where
I: Iterator<Item = (&'a T::AccountId, AuthorityId)>,
{
let authorities = validators.map(|(_account, k)| {
(k, 1)
}).collect::<Vec<_>>();
let authorities = validators.map(|(_account, k)| (k, 1)).collect::<Vec<_>>();
let next_authorities = queued_validators.map(|(_account, k)| {
(k, 1)
}).collect::<Vec<_>>();
let next_authorities = queued_validators.map(|(_account, k)| (k, 1)).collect::<Vec<_>>();
Self::enact_epoch_change(authorities, next_authorities)
}
@@ -914,7 +881,7 @@ impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
fn compute_randomness(
last_epoch_randomness: schnorrkel::Randomness,
epoch_index: u64,
rho: impl Iterator<Item=schnorrkel::Randomness>,
rho: impl Iterator<Item = schnorrkel::Randomness>,
rho_size_hint: Option<usize>,
) -> schnorrkel::Randomness {
let mut s = Vec::with_capacity(40 + rho_size_hint.unwrap_or(0) * VRF_OUTPUT_LENGTH);
@@ -930,7 +897,7 @@ fn compute_randomness(
pub mod migrations {
use super::*;
use frame_support::pallet_prelude::{ValueQuery, StorageValue};
use frame_support::pallet_prelude::{StorageValue, ValueQuery};
/// Something that can return the storage prefix of the `Babe` pallet.
pub trait BabePalletPrefix: Config {
@@ -939,13 +906,14 @@ pub mod migrations {
struct __OldNextEpochConfig<T>(sp_std::marker::PhantomData<T>);
impl<T: BabePalletPrefix> frame_support::traits::StorageInstance for __OldNextEpochConfig<T> {
fn pallet_prefix() -> &'static str { T::pallet_prefix() }
fn pallet_prefix() -> &'static str {
T::pallet_prefix()
}
const STORAGE_PREFIX: &'static str = "NextEpochConfig";
}
type OldNextEpochConfig<T> = StorageValue<
__OldNextEpochConfig<T>, Option<NextConfigDescriptor>, ValueQuery
>;
type OldNextEpochConfig<T> =
StorageValue<__OldNextEpochConfig<T>, Option<NextConfigDescriptor>, ValueQuery>;
/// A storage migration that adds the current epoch configuration for Babe
/// to storage.
+35 -47
View File
@@ -17,27 +17,31 @@
//! Test utilities
use codec::Encode;
use crate::{self as pallet_babe, Config, CurrentSlot};
use sp_runtime::{
Perbill, impl_opaque_keys,
curve::PiecewiseLinear,
testing::{Digest, DigestItem, Header, TestXt,},
traits::{Header as _, IdentityLookup, OpaqueKeys},
};
use frame_system::InitKind;
use codec::Encode;
use frame_election_provider_support::onchain;
use frame_support::{
parameter_types,
traits::{KeyOwnerProofSystem, OnInitialize, GenesisBuild},
traits::{GenesisBuild, KeyOwnerProofSystem, OnInitialize},
};
use sp_io;
use sp_core::{H256, U256, crypto::{IsWrappedBy, KeyTypeId, Pair}};
use frame_system::InitKind;
use pallet_session::historical as pallet_session_historical;
use pallet_staking::EraIndex;
use sp_consensus_babe::{AuthorityId, AuthorityPair, Slot};
use sp_consensus_vrf::schnorrkel::{VRFOutput, VRFProof};
use sp_core::{
crypto::{IsWrappedBy, KeyTypeId, Pair},
H256, U256,
};
use sp_io;
use sp_runtime::{
curve::PiecewiseLinear,
impl_opaque_keys,
testing::{Digest, DigestItem, Header, TestXt},
traits::{Header as _, IdentityLookup, OpaqueKeys},
Perbill,
};
use sp_staking::SessionIndex;
use pallet_staking::EraIndex;
use frame_election_provider_support::onchain;
use pallet_session::historical as pallet_session_historical;
type DummyValidatorId = u64;
@@ -277,7 +281,7 @@ pub fn go_to_block(n: u64, s: u64) {
/// Slots will grow accordingly to blocks
pub fn progress_to_block(n: u64) {
let mut slot = u64::from(Babe::current_slot()) + 1;
for i in System::block_number() + 1 ..= n {
for i in System::block_number() + 1..=n {
go_to_block(i, slot);
slot += 1;
}
@@ -308,7 +312,7 @@ pub fn make_primary_pre_digest(
slot,
vrf_output,
vrf_proof,
}
},
);
let log = DigestItem::PreRuntime(sp_consensus_babe::BABE_ENGINE_ID, digest_data.encode());
Digest { logs: vec![log] }
@@ -319,10 +323,7 @@ pub fn make_secondary_plain_pre_digest(
slot: sp_consensus_babe::Slot,
) -> Digest {
let digest_data = sp_consensus_babe::digests::PreDigest::SecondaryPlain(
sp_consensus_babe::digests::SecondaryPlainPreDigest {
authority_index,
slot,
}
sp_consensus_babe::digests::SecondaryPlainPreDigest { authority_index, slot },
);
let log = DigestItem::PreRuntime(sp_consensus_babe::BABE_ENGINE_ID, digest_data.encode());
Digest { logs: vec![log] }
@@ -340,7 +341,7 @@ pub fn make_secondary_vrf_pre_digest(
slot,
vrf_output,
vrf_proof,
}
},
);
let log = DigestItem::PreRuntime(sp_consensus_babe::BABE_ENGINE_ID, digest_data.encode());
Digest { logs: vec![log] }
@@ -348,13 +349,13 @@ pub fn make_secondary_vrf_pre_digest(
pub fn make_vrf_output(
slot: Slot,
pair: &sp_consensus_babe::AuthorityPair
pair: &sp_consensus_babe::AuthorityPair,
) -> (VRFOutput, VRFProof, [u8; 32]) {
let pair = sp_core::sr25519::Pair::from_ref(pair).as_ref();
let transcript = sp_consensus_babe::make_transcript(&Babe::randomness(), slot, 0);
let vrf_inout = pair.vrf_sign(transcript);
let vrf_randomness: sp_consensus_vrf::schnorrkel::Randomness = vrf_inout.0
.make_bytes::<[u8; 32]>(&sp_consensus_babe::BABE_VRF_INOUT_CONTEXT);
let vrf_randomness: sp_consensus_vrf::schnorrkel::Randomness =
vrf_inout.0.make_bytes::<[u8; 32]>(&sp_consensus_babe::BABE_VRF_INOUT_CONTEXT);
let vrf_output = VRFOutput(vrf_inout.0.to_output());
let vrf_proof = VRFProof(vrf_inout.1);
@@ -365,10 +366,12 @@ pub fn new_test_ext(authorities_len: usize) -> sp_io::TestExternalities {
new_test_ext_with_pairs(authorities_len).1
}
pub fn new_test_ext_with_pairs(authorities_len: usize) -> (Vec<AuthorityPair>, sp_io::TestExternalities) {
let pairs = (0..authorities_len).map(|i| {
AuthorityPair::from_seed(&U256::from(i).into())
}).collect::<Vec<_>>();
pub fn new_test_ext_with_pairs(
authorities_len: usize,
) -> (Vec<AuthorityPair>, sp_io::TestExternalities) {
let pairs = (0..authorities_len)
.map(|i| AuthorityPair::from_seed(&U256::from(i).into()))
.collect::<Vec<_>>();
let public = pairs.iter().map(|p| p.public()).collect();
@@ -376,13 +379,9 @@ pub fn new_test_ext_with_pairs(authorities_len: usize) -> (Vec<AuthorityPair>, s
}
pub fn new_test_ext_raw_authorities(authorities: Vec<AuthorityId>) -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::default()
.build_storage::<Test>()
.unwrap();
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
let balances: Vec<_> = (0..authorities.len())
.map(|i| (i as u64, 10_000_000))
.collect();
let balances: Vec<_> = (0..authorities.len()).map(|i| (i as u64, 10_000_000)).collect();
pallet_balances::GenesisConfig::<Test> { balances }
.assimilate_storage(&mut t)
@@ -393,13 +392,7 @@ pub fn new_test_ext_raw_authorities(authorities: Vec<AuthorityId>) -> sp_io::Tes
.iter()
.enumerate()
.map(|(i, k)| {
(
i as u64,
i as u64,
MockSessionKeys {
babe_authority: AuthorityId::from(k.clone()),
},
)
(i as u64, i as u64, MockSessionKeys { babe_authority: AuthorityId::from(k.clone()) })
})
.collect();
@@ -412,12 +405,7 @@ pub fn new_test_ext_raw_authorities(authorities: Vec<AuthorityId>) -> sp_io::Tes
// controllers are the index + 1000
let stakers: Vec<_> = (0..authorities.len())
.map(|i| {
(
i as u64,
i as u64 + 1000,
10_000,
pallet_staking::StakerStatus::<u64>::Validator,
)
(i as u64, i as u64 + 1000, 10_000, pallet_staking::StakerStatus::<u64>::Validator)
})
.collect();
+1 -1
View File
@@ -21,7 +21,7 @@
use super::{
AuthorVrfRandomness, Config, EpochStart, NextRandomness, Randomness, VRF_OUTPUT_LENGTH,
};
use frame_support::{traits::Randomness as RandomnessT};
use frame_support::traits::Randomness as RandomnessT;
use sp_runtime::traits::Hash;
/// Randomness usable by consensus protocols that **depend** upon finality and take action
+69 -154
View File
@@ -19,7 +19,7 @@
use super::{Call, *};
use frame_support::{
assert_err, assert_ok, assert_noop,
assert_err, assert_noop, assert_ok,
traits::{Currency, EstimateNextSessionRotation, OnFinalize},
weights::{GetDispatchInfo, Pays},
};
@@ -29,10 +29,8 @@ use sp_consensus_babe::{AllowedSlots, BabeEpochConfiguration, Slot};
use sp_core::crypto::Pair;
const EMPTY_RANDOMNESS: [u8; 32] = [
74, 25, 49, 128, 53, 97, 244, 49,
222, 202, 176, 2, 231, 66, 95, 10,
133, 49, 213, 228, 86, 161, 164, 127,
217, 153, 138, 37, 48, 192, 248, 0,
74, 25, 49, 128, 53, 97, 244, 49, 222, 202, 176, 2, 231, 66, 95, 10, 133, 49, 213, 228, 86,
161, 164, 127, 217, 153, 138, 37, 48, 192, 248, 0,
];
#[test]
@@ -43,17 +41,17 @@ fn empty_randomness_is_correct() {
#[test]
fn initial_values() {
new_test_ext(4).execute_with(|| {
assert_eq!(Babe::authorities().len(), 4)
})
new_test_ext(4).execute_with(|| assert_eq!(Babe::authorities().len(), 4))
}
#[test]
fn check_module() {
new_test_ext(4).execute_with(|| {
assert!(!Babe::should_end_session(0), "Genesis does not change sessions");
assert!(!Babe::should_end_session(200000),
"BABE does not include the block number in epoch calculations");
assert!(
!Babe::should_end_session(200000),
"BABE does not include the block number in epoch calculations"
);
})
}
@@ -66,20 +64,10 @@ fn first_block_epoch_zero_start() {
let (vrf_output, vrf_proof, vrf_randomness) = make_vrf_output(genesis_slot, &pairs[0]);
let first_vrf = vrf_output;
let pre_digest = make_primary_pre_digest(
0,
genesis_slot,
first_vrf.clone(),
vrf_proof,
);
let pre_digest = make_primary_pre_digest(0, genesis_slot, first_vrf.clone(), vrf_proof);
assert_eq!(Babe::genesis_slot(), Slot::from(0));
System::initialize(
&1,
&Default::default(),
&pre_digest,
Default::default(),
);
System::initialize(&1, &Default::default(), &pre_digest, Default::default());
// see implementation of the function for details why: we issue an
// epoch-change digest but don't do it via the normal session mechanism.
@@ -106,7 +94,7 @@ fn first_block_epoch_zero_start() {
sp_consensus_babe::digests::NextEpochDescriptor {
authorities: Babe::authorities(),
randomness: Babe::randomness(),
}
},
);
let consensus_digest = DigestItem::Consensus(BABE_ENGINE_ID, consensus_log.encode());
@@ -124,12 +112,7 @@ fn author_vrf_output_for_primary() {
let (vrf_output, vrf_proof, vrf_randomness) = make_vrf_output(genesis_slot, &pairs[0]);
let primary_pre_digest = make_primary_pre_digest(0, genesis_slot, vrf_output, vrf_proof);
System::initialize(
&1,
&Default::default(),
&primary_pre_digest,
Default::default(),
);
System::initialize(&1, &Default::default(), &primary_pre_digest, Default::default());
Babe::do_initialize(1);
assert_eq!(Babe::author_vrf_randomness(), Some(vrf_randomness));
@@ -147,14 +130,10 @@ fn author_vrf_output_for_secondary_vrf() {
ext.execute_with(|| {
let genesis_slot = Slot::from(10);
let (vrf_output, vrf_proof, vrf_randomness) = make_vrf_output(genesis_slot, &pairs[0]);
let secondary_vrf_pre_digest = make_secondary_vrf_pre_digest(0, genesis_slot, vrf_output, vrf_proof);
let secondary_vrf_pre_digest =
make_secondary_vrf_pre_digest(0, genesis_slot, vrf_output, vrf_proof);
System::initialize(
&1,
&Default::default(),
&secondary_vrf_pre_digest,
Default::default(),
);
System::initialize(&1, &Default::default(), &secondary_vrf_pre_digest, Default::default());
Babe::do_initialize(1);
assert_eq!(Babe::author_vrf_randomness(), Some(vrf_randomness));
@@ -192,8 +171,10 @@ fn no_author_vrf_output_for_secondary_plain() {
fn authority_index() {
new_test_ext(4).execute_with(|| {
assert_eq!(
Babe::find_author((&[(BABE_ENGINE_ID, &[][..])]).into_iter().cloned()), None,
"Trivially invalid authorities are ignored")
Babe::find_author((&[(BABE_ENGINE_ID, &[][..])]).into_iter().cloned()),
None,
"Trivially invalid authorities are ignored"
)
})
}
@@ -237,7 +218,10 @@ fn can_estimate_current_epoch_progress() {
Permill::from_percent(100)
);
} else {
assert!(Babe::estimate_current_session_progress(i).0.unwrap() < Permill::from_percent(100));
assert!(
Babe::estimate_current_session_progress(i).0.unwrap() <
Permill::from_percent(100)
);
}
}
@@ -287,7 +271,8 @@ fn can_enact_next_config() {
c: next_next_config.c,
allowed_slots: next_next_config.allowed_slots,
},
).unwrap();
)
.unwrap();
progress_to_block(4);
Babe::on_finalize(9);
@@ -296,12 +281,11 @@ fn can_enact_next_config() {
assert_eq!(EpochConfig::<Test>::get(), Some(next_config));
assert_eq!(NextEpochConfig::<Test>::get(), Some(next_next_config.clone()));
let consensus_log = sp_consensus_babe::ConsensusLog::NextConfigData(
NextConfigDescriptor::V1 {
let consensus_log =
sp_consensus_babe::ConsensusLog::NextConfigData(NextConfigDescriptor::V1 {
c: next_next_config.c,
allowed_slots: next_next_config.allowed_slots,
}
);
});
let consensus_digest = DigestItem::Consensus(BABE_ENGINE_ID, consensus_log.encode());
assert_eq!(header.digest.logs[2], consensus_digest.clone())
@@ -313,29 +297,18 @@ fn only_root_can_enact_config_change() {
use sp_runtime::DispatchError;
new_test_ext(1).execute_with(|| {
let next_config = NextConfigDescriptor::V1 {
c: (1, 4),
allowed_slots: AllowedSlots::PrimarySlots,
};
let next_config =
NextConfigDescriptor::V1 { c: (1, 4), allowed_slots: AllowedSlots::PrimarySlots };
let res = Babe::plan_config_change(
Origin::none(),
next_config.clone(),
);
let res = Babe::plan_config_change(Origin::none(), next_config.clone());
assert_noop!(res, DispatchError::BadOrigin);
let res = Babe::plan_config_change(
Origin::signed(1),
next_config.clone(),
);
let res = Babe::plan_config_change(Origin::signed(1), next_config.clone());
assert_noop!(res, DispatchError::BadOrigin);
let res = Babe::plan_config_change(
Origin::root(),
next_config,
);
let res = Babe::plan_config_change(Origin::root(), next_config);
assert!(res.is_ok());
});
@@ -350,10 +323,7 @@ fn can_fetch_current_and_next_epoch_data() {
});
// genesis authorities should be used for the first and second epoch
assert_eq!(
Babe::current_epoch().authorities,
Babe::next_epoch().authorities,
);
assert_eq!(Babe::current_epoch().authorities, Babe::next_epoch().authorities,);
// 1 era = 3 epochs
// 1 epoch = 3 slots
// Eras start from 0.
@@ -420,11 +390,7 @@ fn report_equivocation_current_session_works() {
assert_eq!(
Staking::eras_stakers(1, validator),
pallet_staking::Exposure {
total: 10_000,
own: 10_000,
others: vec![],
},
pallet_staking::Exposure { total: 10_000, own: 10_000, others: vec![] },
);
}
@@ -445,10 +411,7 @@ fn report_equivocation_current_session_works() {
);
// create the key ownership proof
let key = (
sp_consensus_babe::KEY_TYPE,
&offending_authority_pair.public(),
);
let key = (sp_consensus_babe::KEY_TYPE, &offending_authority_pair.public());
let key_owner_proof = Historical::prove(key).unwrap();
// report the equivocation
@@ -460,35 +423,24 @@ fn report_equivocation_current_session_works() {
start_era(2);
// check that the balance of offending validator is slashed 100%.
assert_eq!(
Balances::total_balance(&offending_validator_id),
10_000_000 - 10_000
);
assert_eq!(Balances::total_balance(&offending_validator_id), 10_000_000 - 10_000);
assert_eq!(Staking::slashable_balance_of(&offending_validator_id), 0);
assert_eq!(
Staking::eras_stakers(2, offending_validator_id),
pallet_staking::Exposure {
total: 0,
own: 0,
others: vec![],
},
pallet_staking::Exposure { total: 0, own: 0, others: vec![] },
);
// check that the balances of all other validators are left intact.
for validator in &validators {
if *validator == offending_validator_id {
continue;
continue
}
assert_eq!(Balances::total_balance(validator), 10_000_000);
assert_eq!(Staking::slashable_balance_of(validator), 10_000);
assert_eq!(
Staking::eras_stakers(2, validator),
pallet_staking::Exposure {
total: 10_000,
own: 10_000,
others: vec![],
},
pallet_staking::Exposure { total: 10_000, own: 10_000, others: vec![] },
);
}
})
@@ -519,10 +471,7 @@ fn report_equivocation_old_session_works() {
);
// create the key ownership proof
let key = (
sp_consensus_babe::KEY_TYPE,
&offending_authority_pair.public(),
);
let key = (sp_consensus_babe::KEY_TYPE, &offending_authority_pair.public());
let key_owner_proof = Historical::prove(key).unwrap();
// start a new era and report the equivocation
@@ -531,10 +480,7 @@ fn report_equivocation_old_session_works() {
// check the balance of the offending validator
assert_eq!(Balances::total_balance(&offending_validator_id), 10_000_000);
assert_eq!(
Staking::slashable_balance_of(&offending_validator_id),
10_000
);
assert_eq!(Staking::slashable_balance_of(&offending_validator_id), 10_000);
// report the equivocation
Babe::report_equivocation_unsigned(Origin::none(), equivocation_proof, key_owner_proof)
@@ -545,18 +491,11 @@ fn report_equivocation_old_session_works() {
start_era(3);
// check that the balance of offending validator is slashed 100%.
assert_eq!(
Balances::total_balance(&offending_validator_id),
10_000_000 - 10_000
);
assert_eq!(Balances::total_balance(&offending_validator_id), 10_000_000 - 10_000);
assert_eq!(Staking::slashable_balance_of(&offending_validator_id), 0);
assert_eq!(
Staking::eras_stakers(3, offending_validator_id),
pallet_staking::Exposure {
total: 0,
own: 0,
others: vec![],
},
pallet_staking::Exposure { total: 0, own: 0, others: vec![] },
);
})
}
@@ -585,10 +524,7 @@ fn report_equivocation_invalid_key_owner_proof() {
);
// create the key ownership proof
let key = (
sp_consensus_babe::KEY_TYPE,
&offending_authority_pair.public(),
);
let key = (sp_consensus_babe::KEY_TYPE, &offending_authority_pair.public());
let mut key_owner_proof = Historical::prove(key).unwrap();
// we change the session index in the key ownership proof
@@ -640,10 +576,7 @@ fn report_equivocation_invalid_equivocation_proof() {
.unwrap();
// create the key ownership proof
let key = (
sp_consensus_babe::KEY_TYPE,
&offending_authority_pair.public(),
);
let key = (sp_consensus_babe::KEY_TYPE, &offending_authority_pair.public());
let key_owner_proof = Historical::prove(key).unwrap();
let assert_invalid_equivocation = |equivocation_proof| {
@@ -753,10 +686,7 @@ fn report_equivocation_validate_unsigned_prevents_duplicates() {
CurrentSlot::<Test>::get(),
);
let key = (
sp_consensus_babe::KEY_TYPE,
&offending_authority_pair.public(),
);
let key = (sp_consensus_babe::KEY_TYPE, &offending_authority_pair.public());
let key_owner_proof = Historical::prove(key).unwrap();
let inner =
@@ -815,23 +745,19 @@ fn report_equivocation_validate_unsigned_prevents_duplicates() {
fn report_equivocation_has_valid_weight() {
// the weight depends on the size of the validator set,
// but there's a lower bound of 100 validators.
assert!(
(1..=100)
.map(<Test as Config>::WeightInfo::report_equivocation)
.collect::<Vec<_>>()
.windows(2)
.all(|w| w[0] == w[1])
);
assert!((1..=100)
.map(<Test as Config>::WeightInfo::report_equivocation)
.collect::<Vec<_>>()
.windows(2)
.all(|w| w[0] == w[1]));
// after 100 validators the weight should keep increasing
// with every extra validator.
assert!(
(100..=1000)
.map(<Test as Config>::WeightInfo::report_equivocation)
.collect::<Vec<_>>()
.windows(2)
.all(|w| w[0] < w[1])
);
assert!((100..=1000)
.map(<Test as Config>::WeightInfo::report_equivocation)
.collect::<Vec<_>>()
.windows(2)
.all(|w| w[0] < w[1]));
}
#[test]
@@ -848,11 +774,9 @@ fn valid_equivocation_reports_dont_pay_fees() {
generate_equivocation_proof(0, &offending_authority_pair, CurrentSlot::<Test>::get());
// create the key ownership proof.
let key_owner_proof = Historical::prove((
sp_consensus_babe::KEY_TYPE,
&offending_authority_pair.public(),
))
.unwrap();
let key_owner_proof =
Historical::prove((sp_consensus_babe::KEY_TYPE, &offending_authority_pair.public()))
.unwrap();
// check the dispatch info for the call.
let info = Call::<Test>::report_equivocation_unsigned(
@@ -894,9 +818,7 @@ fn valid_equivocation_reports_dont_pay_fees() {
#[test]
fn add_epoch_configurations_migration_works() {
use frame_support::storage::migration::{
put_storage_value, get_storage_value,
};
use frame_support::storage::migration::{get_storage_value, put_storage_value};
impl crate::migrations::BabePalletPrefix for Test {
fn pallet_prefix() -> &'static str {
@@ -905,38 +827,31 @@ fn add_epoch_configurations_migration_works() {
}
new_test_ext(1).execute_with(|| {
let next_config_descriptor = NextConfigDescriptor::V1 {
c: (3, 4),
allowed_slots: AllowedSlots::PrimarySlots
};
let next_config_descriptor =
NextConfigDescriptor::V1 { c: (3, 4), allowed_slots: AllowedSlots::PrimarySlots };
put_storage_value(
b"Babe",
b"NextEpochConfig",
&[],
Some(next_config_descriptor.clone())
);
put_storage_value(b"Babe", b"NextEpochConfig", &[], Some(next_config_descriptor.clone()));
assert!(get_storage_value::<Option<NextConfigDescriptor>>(
b"Babe",
b"NextEpochConfig",
&[],
).is_some());
)
.is_some());
let current_epoch = BabeEpochConfiguration {
c: (1, 4),
allowed_slots: sp_consensus_babe::AllowedSlots::PrimarySlots,
};
crate::migrations::add_epoch_configuration::<Test>(
current_epoch.clone()
);
crate::migrations::add_epoch_configuration::<Test>(current_epoch.clone());
assert!(get_storage_value::<Option<NextConfigDescriptor>>(
b"Babe",
b"NextEpochConfig",
&[],
).is_none());
)
.is_none());
assert_eq!(EpochConfig::<Test>::get(), Some(current_epoch));
assert_eq!(PendingEpochConfigChange::<Test>::get(), Some(next_config_descriptor));