From ec9929fbfb4d0c8182612ef70ddc7ed2baecfc1d Mon Sep 17 00:00:00 2001 From: Wei Tang Date: Thu, 16 Apr 2020 01:05:32 +0200 Subject: [PATCH 01/13] Generalize pallet-babe to be independent of BABE primitives --- Cargo.lock | 46 +++--- Cargo.toml | 3 +- bin/node/runtime/Cargo.toml | 4 +- frame/{babe => epoch-vrf}/Cargo.toml | 4 +- frame/{babe => epoch-vrf}/src/lib.rs | 192 ++++++++++++------------- frame/{babe => epoch-vrf}/src/mock.rs | 0 frame/{babe => epoch-vrf}/src/tests.rs | 0 primitives/consensus/babe/src/lib.rs | 3 + primitives/runtime/src/traits.rs | 3 + test-utils/runtime/Cargo.toml | 4 +- 10 files changed, 129 insertions(+), 130 deletions(-) rename frame/{babe => epoch-vrf}/Cargo.toml (92%) rename frame/{babe => epoch-vrf}/src/lib.rs (80%) rename frame/{babe => epoch-vrf}/src/mock.rs (100%) rename frame/{babe => epoch-vrf}/src/tests.rs (100%) diff --git a/Cargo.lock b/Cargo.lock index 57464914312ae..a1e5b8c74b53f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3568,7 +3568,6 @@ dependencies = [ "node-primitives", "pallet-authority-discovery", "pallet-authorship", - "pallet-babe", "pallet-balances", "pallet-collective", "pallet-contracts", @@ -3576,6 +3575,7 @@ dependencies = [ "pallet-contracts-rpc-runtime-api", "pallet-democracy", "pallet-elections-phragmen", + "pallet-epoch-vrf", "pallet-finality-tracker", "pallet-grandpa", "pallet-identity", @@ -3986,27 +3986,6 @@ dependencies = [ "sp-std", ] -[[package]] -name = "pallet-babe" -version = "2.0.0-dev" -dependencies = [ - "frame-support", - "frame-system", - "pallet-session", - "pallet-timestamp", - "parity-scale-codec", - "serde", - "sp-consensus-babe", - "sp-consensus-vrf", - "sp-core", - "sp-inherents", - "sp-io", - "sp-runtime", - "sp-staking", - "sp-std", - "sp-timestamp", -] - [[package]] name = "pallet-balances" version = "2.0.0-dev" @@ -4172,6 +4151,27 @@ dependencies = [ "substrate-test-utils", ] +[[package]] +name = "pallet-epoch-vrf" +version = "2.0.0-dev" +dependencies = [ + "frame-support", + "frame-system", + "pallet-session", + "pallet-timestamp", + "parity-scale-codec", + "serde", + "sp-consensus-babe", + "sp-consensus-vrf", + "sp-core", + "sp-inherents", + "sp-io", + "sp-runtime", + "sp-staking", + "sp-std", + "sp-timestamp", +] + [[package]] name = "pallet-evm" version = "2.0.0-dev" @@ -8037,7 +8037,7 @@ dependencies = [ "frame-system-rpc-runtime-api", "log", "memory-db", - "pallet-babe", + "pallet-epoch-vrf", "pallet-timestamp", "parity-scale-codec", "parity-util-mem", diff --git a/Cargo.toml b/Cargo.toml index ad05847f61f49..5dce9d5107541 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -60,7 +60,7 @@ members = [ "frame/aura", "frame/authority-discovery", "frame/authorship", - "frame/babe", + "frame/epoch-vrf", "frame/balances", "frame/benchmarking", "frame/benchmark", @@ -177,4 +177,3 @@ members = [ [profile.release] # Substrate runtime requires unwinding. panic = "unwind" - diff --git a/bin/node/runtime/Cargo.toml b/bin/node/runtime/Cargo.toml index 9c93c071c70d4..317908ef4c067 100644 --- a/bin/node/runtime/Cargo.toml +++ b/bin/node/runtime/Cargo.toml @@ -43,7 +43,7 @@ frame-system = { version = "2.0.0-dev", default-features = false, path = "../../ frame-system-rpc-runtime-api = { version = "2.0.0-dev", default-features = false, path = "../../../frame/system/rpc/runtime-api/" } pallet-authority-discovery = { version = "2.0.0-dev", default-features = false, path = "../../../frame/authority-discovery" } pallet-authorship = { version = "2.0.0-dev", default-features = false, path = "../../../frame/authorship" } -pallet-babe = { version = "2.0.0-dev", default-features = false, path = "../../../frame/babe" } +pallet-epoch-vrf = { version = "2.0.0-dev", default-features = false, path = "../../../frame/epoch-vrf" } pallet-balances = { version = "2.0.0-dev", default-features = false, path = "../../../frame/balances" } pallet-collective = { version = "2.0.0-dev", default-features = false, path = "../../../frame/collective" } pallet-contracts = { version = "2.0.0-dev", default-features = false, path = "../../../frame/contracts" } @@ -88,7 +88,7 @@ std = [ "pallet-authority-discovery/std", "pallet-authorship/std", "sp-consensus-babe/std", - "pallet-babe/std", + "pallet-epoch-vrf/std", "pallet-balances/std", "sp-block-builder/std", "codec/std", diff --git a/frame/babe/Cargo.toml b/frame/epoch-vrf/Cargo.toml similarity index 92% rename from frame/babe/Cargo.toml rename to frame/epoch-vrf/Cargo.toml index c94ec75b26ad3..955dcaefcd8b5 100644 --- a/frame/babe/Cargo.toml +++ b/frame/epoch-vrf/Cargo.toml @@ -1,12 +1,12 @@ [package] -name = "pallet-babe" +name = "pallet-epoch-vrf" version = "2.0.0-dev" authors = ["Parity Technologies "] edition = "2018" license = "GPL-3.0" homepage = "https://substrate.dev" repository = "https://github.com/paritytech/substrate/" -description = "Consensus extension module for BABE consensus. Collects on-chain randomness from VRF outputs and manages epoch transitions." +description = "Consensus extension module for VRF-based consensus. Collects on-chain randomness from VRF outputs and manages epoch transitions." [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/frame/babe/src/lib.rs b/frame/epoch-vrf/src/lib.rs similarity index 80% rename from frame/babe/src/lib.rs rename to frame/epoch-vrf/src/lib.rs index 5f85b91088067..07dd51aeb438b 100644 --- a/frame/babe/src/lib.rs +++ b/frame/epoch-vrf/src/lib.rs @@ -24,26 +24,26 @@ use pallet_timestamp; use sp_std::{result, prelude::*}; use frame_support::{ - decl_storage, decl_module, traits::{FindAuthor, Get, Randomness as RandomnessT}, + decl_storage, decl_module, traits::{Get, Randomness as RandomnessT}, weights::{Weight, SimpleDispatchInfo, WeighData}, }; use sp_timestamp::OnTimestampSet; -use sp_runtime::{generic::DigestItem, ConsensusEngineId, Perbill}; -use sp_runtime::traits::{IsMember, SaturatedConversion, Saturating, Hash, One}; +use sp_runtime::{Perbill, RuntimeAppPublic}; +use sp_runtime::traits::{ + IsMember, SaturatedConversion, Saturating, CheckedSub, Hash, One, UniqueSaturatedInto, + CheckedAdd, MaybeDisplay, MaybeDebug, +}; use sp_staking::{ SessionIndex, offence::{Offence, Kind}, }; -use codec::{Encode, Decode}; +use codec::{Encode, EncodeLike, Decode}; use sp_inherents::{InherentIdentifier, InherentData, ProvideInherent, MakeFatalError}; -use sp_consensus_babe::{ - BABE_ENGINE_ID, ConsensusLog, BabeAuthorityWeight, SlotNumber, - inherents::{INHERENT_IDENTIFIER, BabeInherentData}, - digests::{NextEpochDescriptor, RawPreDigest}, -}; -use sp_consensus_vrf::schnorrkel; -pub use sp_consensus_babe::{AuthorityId, VRF_OUTPUT_LENGTH, RANDOMNESS_LENGTH, PUBLIC_KEY_LENGTH}; +use sp_consensus_vrf::schnorrkel::{self, VRF_OUTPUT_LENGTH}; + +// TODO: Move those out of sp-consensus-babe. +use sp_consensus_babe::inherents::{INHERENT_IDENTIFIER, BabeInherentData}; #[cfg(all(feature = "std", test))] mod tests; @@ -51,9 +51,20 @@ mod tests; #[cfg(all(feature = "std", test))] mod mock; +/// Raw pre-digest for this block production engine. +pub trait RawPreDigest { + /// Type of slot number. + type SlotNumber; + + /// Primary VRF output. + fn vrf_output(&self) -> Option; + /// Slot number. + fn slot_number(&self) -> Self::SlotNumber; +} + pub trait Trait: pallet_timestamp::Trait { /// The amount of time, in slots, that each epoch should last. - type EpochDuration: Get; + type EpochDuration: Get; /// The expected average block time at which BABE should be creating /// blocks. Since BABE is probabilistic it is not trivial to figure out @@ -68,6 +79,32 @@ pub trait Trait: pallet_timestamp::Trait { /// Typically, the `ExternalTrigger` type should be used. An internal trigger should only be used /// when no other module is responsible for changing authority set. type EpochChangeTrigger: EpochChangeTrigger; + + /// Block production authority ID. + type AuthorityId: Default + RuntimeAppPublic + Encode + EncodeLike + Decode + Clone + Eq; + + /// Block production authority weight. + type AuthorityWeight: One + Encode + EncodeLike + Decode + Clone; + + /// Block production slot number. + type SlotNumber: Encode + EncodeLike + Decode + Clone + Copy + Default + Saturating + + CheckedSub + CheckedAdd + UniqueSaturatedInto + Ord + One + + MaybeDisplay + MaybeDebug + UniqueSaturatedInto; + + /// Type of raw pre-digest. + type RawPreDigest: RawPreDigest; + + /// Find the raw pre-digest in current block. + fn find_raw_pre_digest() -> Option; + + /// Deposit next epoch descriptor. + fn deposit_next_epoch_descriptor( + authorities: Vec<(Self::AuthorityId, Self::AuthorityWeight)>, + randomness: schnorrkel::Randomness, + ); + + /// Deposit disabled event. + fn deposit_disabled_event(i: u32); } /// Trigger an epoch change, if any should take place. @@ -107,17 +144,17 @@ type MaybeVrf = Option; decl_storage! { trait Store for Module as Babe { /// Current epoch index. - pub EpochIndex get(fn epoch_index): u64; + pub EpochIndex get(fn epoch_index): T::SlotNumber; /// Current epoch authorities. - pub Authorities get(fn authorities): Vec<(AuthorityId, BabeAuthorityWeight)>; + pub Authorities get(fn authorities): Vec<(T::AuthorityId, T::AuthorityWeight)>; /// The slot at which the first epoch actually started. This is 0 /// until the first block of the chain. - pub GenesisSlot get(fn genesis_slot): u64; + pub GenesisSlot get(fn genesis_slot): T::SlotNumber; /// Current slot number. - pub CurrentSlot get(fn current_slot): u64; + pub CurrentSlot get(fn current_slot): T::SlotNumber; /// The epoch randomness for the *current* epoch. /// @@ -161,7 +198,7 @@ decl_storage! { Lateness get(fn lateness): T::BlockNumber; } add_extra_genesis { - config(authorities): Vec<(AuthorityId, BabeAuthorityWeight)>; + config(authorities): Vec<(T::AuthorityId, T::AuthorityWeight)>; build(|config| Module::::initialize_authorities(&config.authorities)) } } @@ -171,7 +208,7 @@ decl_module! { pub struct Module for enum Call where origin: T::Origin { /// The number of **slots** that an epoch takes. We couple sessions to /// epochs, i.e. we start a new session once the new epoch begins. - const EpochDuration: u64 = T::EpochDuration::get(); + const EpochDuration: T::SlotNumber = T::EpochDuration::get(); /// The expected average block time at which BABE should be creating /// blocks. Since BABE is probabilistic it is not trivial to figure out @@ -214,26 +251,8 @@ impl RandomnessT<::Hash> for Module { } } -/// A BABE public key -pub type BabeKey = [u8; PUBLIC_KEY_LENGTH]; - -impl FindAuthor for Module { - fn find_author<'a, I>(digests: I) -> Option where - I: 'a + IntoIterator - { - for (id, mut data) in digests.into_iter() { - if id == BABE_ENGINE_ID { - let pre_digest: RawPreDigest = RawPreDigest::decode(&mut data).ok()?; - return Some(pre_digest.authority_index()) - } - } - - return None; - } -} - -impl IsMember for Module { - fn is_member(authority_id: &AuthorityId) -> bool { +impl IsMember for Module { + fn is_member(authority_id: &T::AuthorityId) -> bool { >::authorities() .iter() .any(|id| &id.0 == authority_id) @@ -318,7 +337,7 @@ impl Module { // the same randomness and validator set as signalled in the genesis, // so we don't rotate the epoch. now != One::one() && { - let diff = CurrentSlot::get().saturating_sub(Self::current_epoch_start()); + let diff = >::get().saturating_sub(Self::current_epoch_start()); diff >= T::EpochDuration::get() } } @@ -337,10 +356,10 @@ impl Module { pub fn next_expected_epoch_change(now: T::BlockNumber) -> Option { let next_slot = Self::current_epoch_start().saturating_add(T::EpochDuration::get()); next_slot - .checked_sub(CurrentSlot::get()) + .checked_sub(&>::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(); + let blocks_remaining = UniqueSaturatedInto::::unique_saturated_into(slots_remaining); now.saturating_add(blocks_remaining) }) } @@ -351,24 +370,24 @@ impl Module { /// Typically, this is not handled directly by the user, but by higher-level validator-set manager logic like /// `pallet-session`. pub fn enact_epoch_change( - authorities: Vec<(AuthorityId, BabeAuthorityWeight)>, - next_authorities: Vec<(AuthorityId, BabeAuthorityWeight)>, + authorities: Vec<(T::AuthorityId, T::AuthorityWeight)>, + next_authorities: Vec<(T::AuthorityId, T::AuthorityWeight)>, ) { // PRECONDITION: caller has done initialization and is guaranteed // by the session module to be called before this. debug_assert!(Self::initialized().is_some()); // Update epoch index - let epoch_index = EpochIndex::get() - .checked_add(1) + let epoch_index = >::get() + .checked_add(&One::one()) .expect("epoch indices will never reach 2^64 before the death of the universe; qed"); - EpochIndex::put(epoch_index); - Authorities::put(authorities); + >::put(epoch_index); + >::put(authorities); // Update epoch randomness. let next_epoch_index = epoch_index - .checked_add(1) + .checked_add(&One::one()) .expect("epoch indices will never reach 2^64 before the death of the universe; qed"); // Returns randomness for the current epoch and computes the *next* @@ -380,24 +399,14 @@ impl Module { // so that nodes can track changes. let next_randomness = NextRandomness::get(); - let next = NextEpochDescriptor { - authorities: next_authorities, - randomness: next_randomness, - }; - - Self::deposit_consensus(ConsensusLog::NextEpochData(next)) + T::deposit_next_epoch_descriptor(next_authorities, next_randomness); } // finds the start slot of the current epoch. only guaranteed to // give correct results after `do_initialize` of the first block // in the chain (as its result is based off of `GenesisSlot`). - pub fn current_epoch_start() -> SlotNumber { - (EpochIndex::get() * T::EpochDuration::get()) + GenesisSlot::get() - } - - fn deposit_consensus(new: U) { - let log: DigestItem = DigestItem::Consensus(BABE_ENGINE_ID, new.encode()); - >::deposit_log(log.into()) + pub fn current_epoch_start() -> T::SlotNumber { + (>::get() * T::EpochDuration::get()) + >::get() } fn deposit_vrf_output(vrf_output: &schnorrkel::RawVRFOutput) { @@ -423,51 +432,36 @@ impl Module { return; } - let maybe_pre_digest: Option = >::digest() - .logs - .iter() - .filter_map(|s| s.as_pre_runtime()) - .filter_map(|(id, mut data)| if id == BABE_ENGINE_ID { - RawPreDigest::decode(&mut data).ok() - } else { - None - }) - .next(); + let maybe_pre_digest: Option = T::find_raw_pre_digest(); let maybe_vrf = maybe_pre_digest.and_then(|digest| { // on the first non-zero block (i.e. block #1) // this is where the first epoch (epoch #0) actually starts. // we need to adjust internal storage accordingly. - if GenesisSlot::get() == 0 { - GenesisSlot::put(digest.slot_number()); - debug_assert_ne!(GenesisSlot::get(), 0); + if >::get() == Default::default() { + >::put(digest.slot_number()); + debug_assert_ne!(>::get(), Default::default()); // deposit a log because this is the first block in epoch #0 // we use the same values as genesis because we haven't collected any // randomness yet. - let next = NextEpochDescriptor { - authorities: Self::authorities(), - randomness: Self::randomness(), - }; - - Self::deposit_consensus(ConsensusLog::NextEpochData(next)) + T::deposit_next_epoch_descriptor(Self::authorities(), Self::randomness()); } // the slot number of the current block being initialized let current_slot = digest.slot_number(); // how many slots were skipped between current and last block - let lateness = current_slot.saturating_sub(CurrentSlot::get() + 1); - let lateness = T::BlockNumber::from(lateness as u32); + let lateness = current_slot.saturating_sub(>::get() + One::one()); - Lateness::::put(lateness); - CurrentSlot::put(current_slot); + Lateness::::put(UniqueSaturatedInto::::unique_saturated_into(lateness)); + CurrentSlot::::put(current_slot); - if let RawPreDigest::Primary(primary) = digest { + if let Some(vrf_output) = digest.vrf_output() { // place the VRF output into the `Initialized` storage item // and it'll be put onto the under-construction randomness // later, once we've decided which epoch this block is in. - Some(primary.vrf_output) + Some(vrf_output) } else { None } @@ -481,7 +475,7 @@ impl Module { /// Call this function exactly once when an epoch changes, to update the /// randomness. Returns the new randomness. - fn randomness_change_epoch(next_epoch_index: u64) -> schnorrkel::Randomness { + fn randomness_change_epoch(next_epoch_index: T::SlotNumber) -> schnorrkel::Randomness { let this_randomness = NextRandomness::get(); let segment_idx: u32 = ::mutate(|s| sp_std::mem::replace(s, 0)); @@ -490,7 +484,7 @@ impl Module { let next_randomness = compute_randomness( this_randomness, - next_epoch_index, + next_epoch_index.saturated_into(), (0..segment_idx).flat_map(|i| ::take(&i)), Some(rho_size), ); @@ -498,10 +492,10 @@ impl Module { this_randomness } - fn initialize_authorities(authorities: &[(AuthorityId, BabeAuthorityWeight)]) { + fn initialize_authorities(authorities: &[(T::AuthorityId, T::AuthorityWeight)]) { if !authorities.is_empty() { - assert!(Authorities::get().is_empty(), "Authorities are already initialized!"); - Authorities::put(authorities); + assert!(>::get().is_empty(), "Authorities are already initialized!"); + >::put(authorities); } } } @@ -523,35 +517,35 @@ impl frame_support::traits::Lateness for Module { } impl sp_runtime::BoundToRuntimeAppPublic for Module { - type Public = AuthorityId; + type Public = T::AuthorityId; } impl pallet_session::OneSessionHandler for Module { - type Key = AuthorityId; + type Key = T::AuthorityId; fn on_genesis_session<'a, I: 'a>(validators: I) - where I: Iterator + where I: Iterator { - let authorities = validators.map(|(_, k)| (k, 1)).collect::>(); + let authorities = validators.map(|(_, k)| (k, One::one())).collect::>(); Self::initialize_authorities(&authorities); } fn on_new_session<'a, I: 'a>(_changed: bool, validators: I, queued_validators: I) - where I: Iterator + where I: Iterator { let authorities = validators.map(|(_account, k)| { - (k, 1) + (k, One::one()) }).collect::>(); let next_authorities = queued_validators.map(|(_account, k)| { - (k, 1) + (k, One::one()) }).collect::>(); Self::enact_epoch_change(authorities, next_authorities) } fn on_disabled(i: usize) { - Self::deposit_consensus(ConsensusLog::OnDisabled(i as u32)) + T::deposit_disabled_event(i as u32); } } diff --git a/frame/babe/src/mock.rs b/frame/epoch-vrf/src/mock.rs similarity index 100% rename from frame/babe/src/mock.rs rename to frame/epoch-vrf/src/mock.rs diff --git a/frame/babe/src/tests.rs b/frame/epoch-vrf/src/tests.rs similarity index 100% rename from frame/babe/src/tests.rs rename to frame/epoch-vrf/src/tests.rs diff --git a/primitives/consensus/babe/src/lib.rs b/primitives/consensus/babe/src/lib.rs index 33701860d1f10..27b3d367372ee 100644 --- a/primitives/consensus/babe/src/lib.rs +++ b/primitives/consensus/babe/src/lib.rs @@ -36,6 +36,9 @@ mod app { app_crypto!(sr25519, BABE); } +/// A BABE public key +pub type BabeKey = [u8; PUBLIC_KEY_LENGTH]; + /// The prefix used by BABE for its VRF keys. pub const BABE_VRF_PREFIX: &[u8] = b"substrate-babe-vrf"; diff --git a/primitives/runtime/src/traits.rs b/primitives/runtime/src/traits.rs index fdf1d6396d26f..4d69409630d3a 100644 --- a/primitives/runtime/src/traits.rs +++ b/primitives/runtime/src/traits.rs @@ -422,6 +422,9 @@ sp_core::impl_maybe_marker!( /// A type that implements Display when in std environment. trait MaybeDisplay: Display; + /// A type that implements Debug when in std environment. + trait MaybeDebug: Debug; + /// A type that implements FromStr when in std environment. trait MaybeFromStr: FromStr; diff --git a/test-utils/runtime/Cargo.toml b/test-utils/runtime/Cargo.toml index 065a09c889aa0..d06db3fbb059c 100644 --- a/test-utils/runtime/Cargo.toml +++ b/test-utils/runtime/Cargo.toml @@ -35,7 +35,7 @@ serde = { version = "1.0.101", optional = true, features = ["derive"] } sp-session = { version = "2.0.0-dev", default-features = false, path = "../../primitives/session" } sp-api = { version = "2.0.0-dev", default-features = false, path = "../../primitives/api" } sp-runtime = { version = "2.0.0-dev", default-features = false, path = "../../primitives/runtime" } -pallet-babe = { version = "2.0.0-dev", default-features = false, path = "../../frame/babe" } +pallet-epoch-vrf = { version = "2.0.0-dev", default-features = false, path = "../../frame/epoch-vrf" } frame-system = { version = "2.0.0-dev", default-features = false, path = "../../frame/system" } frame-system-rpc-runtime-api = { version = "2.0.0-dev", default-features = false, path = "../../frame/system/rpc/runtime-api" } pallet-timestamp = { version = "2.0.0-dev", default-features = false, path = "../../frame/timestamp" } @@ -81,7 +81,7 @@ std = [ "sp-session/std", "sp-api/std", "sp-runtime/std", - "pallet-babe/std", + "pallet-epoch-vrf/std", "frame-system-rpc-runtime-api/std", "frame-system/std", "pallet-timestamp/std", From 84745c7701e6ec13452f24fba54c525ab04cabe5 Mon Sep 17 00:00:00 2001 From: Wei Tang Date: Thu, 16 Apr 2020 17:51:57 +0200 Subject: [PATCH 02/13] Implement BabeTrait for Babe-specific functionality --- Cargo.lock | 16 ++-- Cargo.toml | 2 +- client/consensus/babe/Cargo.toml | 2 +- frame/epoch-vrf/Cargo.toml | 4 +- frame/epoch-vrf/src/babe.rs | 87 +++++++++++++++++++ frame/epoch-vrf/src/lib.rs | 10 +-- primitives/consensus/babe/Cargo.toml | 4 +- primitives/consensus/babe/src/digests.rs | 4 +- primitives/consensus/babe/src/lib.rs | 3 +- .../consensus/{vrf => epoch-vrf}/Cargo.toml | 6 +- .../{babe => epoch-vrf}/src/inherents.rs | 20 ++--- .../consensus/{vrf => epoch-vrf}/src/lib.rs | 1 + .../{vrf => epoch-vrf}/src/schnorrkel.rs | 0 13 files changed, 125 insertions(+), 34 deletions(-) create mode 100644 frame/epoch-vrf/src/babe.rs rename primitives/consensus/{vrf => epoch-vrf}/Cargo.toml (77%) rename primitives/consensus/{babe => epoch-vrf}/src/inherents.rs (83%) rename primitives/consensus/{vrf => epoch-vrf}/src/lib.rs (97%) rename primitives/consensus/{vrf => epoch-vrf}/src/schnorrkel.rs (100%) diff --git a/Cargo.lock b/Cargo.lock index a1e5b8c74b53f..a620156890564 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4162,7 +4162,7 @@ dependencies = [ "parity-scale-codec", "serde", "sp-consensus-babe", - "sp-consensus-vrf", + "sp-consensus-epoch-vrf", "sp-core", "sp-inherents", "sp-io", @@ -6075,7 +6075,7 @@ dependencies = [ "sp-blockchain", "sp-consensus", "sp-consensus-babe", - "sp-consensus-vrf", + "sp-consensus-epoch-vrf", "sp-core", "sp-inherents", "sp-io", @@ -7320,7 +7320,7 @@ dependencies = [ "sp-api", "sp-application-crypto", "sp-consensus", - "sp-consensus-vrf", + "sp-consensus-epoch-vrf", "sp-inherents", "sp-runtime", "sp-std", @@ -7328,22 +7328,24 @@ dependencies = [ ] [[package]] -name = "sp-consensus-pow" +name = "sp-consensus-epoch-vrf" version = "0.8.0-dev" dependencies = [ "parity-scale-codec", - "sp-api", + "schnorrkel", "sp-core", + "sp-inherents", "sp-runtime", "sp-std", + "sp-timestamp", ] [[package]] -name = "sp-consensus-vrf" +name = "sp-consensus-pow" version = "0.8.0-dev" dependencies = [ "parity-scale-codec", - "schnorrkel", + "sp-api", "sp-core", "sp-runtime", "sp-std", diff --git a/Cargo.toml b/Cargo.toml index 5dce9d5107541..e5a4465b06b5d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -120,7 +120,7 @@ members = [ "primitives/consensus/babe", "primitives/consensus/common", "primitives/consensus/pow", - "primitives/consensus/vrf", + "primitives/consensus/epoch-vrf", "primitives/core", "primitives/chain-spec", "primitives/database", diff --git a/client/consensus/babe/Cargo.toml b/client/consensus/babe/Cargo.toml index 7ac3330b6ac51..ee12e34502a58 100644 --- a/client/consensus/babe/Cargo.toml +++ b/client/consensus/babe/Cargo.toml @@ -34,7 +34,7 @@ sp-api = { version = "2.0.0-dev", path = "../../../primitives/api" } sp-block-builder = { version = "2.0.0-dev", path = "../../../primitives/block-builder" } sp-blockchain = { version = "2.0.0-dev", path = "../../../primitives/blockchain" } sp-consensus = { version = "0.8.0-dev", path = "../../../primitives/consensus/common" } -sp-consensus-vrf = { version = "0.8.0-dev", path = "../../../primitives/consensus/vrf" } +sp-consensus-epoch-vrf = { version = "0.8.0-dev", path = "../../../primitives/consensus/epoch-vrf" } sc-consensus-uncles = { version = "0.8.0-dev", path = "../uncles" } sc-consensus-slots = { version = "0.8.0-dev", path = "../slots" } sp-runtime = { version = "2.0.0-dev", path = "../../../primitives/runtime" } diff --git a/frame/epoch-vrf/Cargo.toml b/frame/epoch-vrf/Cargo.toml index 955dcaefcd8b5..004a806c86415 100644 --- a/frame/epoch-vrf/Cargo.toml +++ b/frame/epoch-vrf/Cargo.toml @@ -24,7 +24,7 @@ pallet-timestamp = { version = "2.0.0-dev", default-features = false, path = ".. sp-timestamp = { version = "2.0.0-dev", default-features = false, path = "../../primitives/timestamp" } pallet-session = { version = "2.0.0-dev", default-features = false, path = "../session" } sp-consensus-babe = { version = "0.8.0-dev", default-features = false, path = "../../primitives/consensus/babe" } -sp-consensus-vrf = { version = "0.8.0-dev", default-features = false, path = "../../primitives/consensus/vrf" } +sp-consensus-epoch-vrf = { version = "0.8.0-dev", default-features = false, path = "../../primitives/consensus/epoch-vrf" } sp-io = { path = "../../primitives/io", default-features = false , version = "2.0.0-dev"} [dev-dependencies] @@ -44,7 +44,7 @@ std = [ "sp-timestamp/std", "sp-inherents/std", "sp-consensus-babe/std", - "sp-consensus-vrf/std", + "sp-consensus-epoch-vrf/std", "pallet-session/std", "sp-io/std", ] diff --git a/frame/epoch-vrf/src/babe.rs b/frame/epoch-vrf/src/babe.rs new file mode 100644 index 0000000000000..9000594a8142b --- /dev/null +++ b/frame/epoch-vrf/src/babe.rs @@ -0,0 +1,87 @@ +use codec::{Encode, Decode}; +use frame_support::traits::Get; +use sp_runtime::generic::DigestItem; +use sp_consensus_babe::{SlotNumber, AuthorityId, BabeAuthorityWeight, ConsensusLog, BABE_ENGINE_ID}; +use sp_consensus_babe::digests::{RawPreDigest, NextEpochDescriptor}; +use sp_consensus_epoch_vrf::schnorrkel; +use crate::{EpochChangeTrigger, Trait, RawPreDigest as RawPreDigestT}; + +pub trait BabeTrait: pallet_timestamp::Trait { + /// The amount of time, in slots, that each epoch should last. + type EpochDuration: Get; + + /// The expected average block time at which BABE should be creating + /// blocks. Since BABE is probabilistic it is not trivial to figure out + /// what the expected average block time should be based on the slot + /// duration and the security parameter `c` (where `1 - c` represents + /// the probability of a slot being empty). + type ExpectedBlockTime: Get; + + /// BABE requires some logic to be triggered on every block to query for whether an epoch + /// has ended and to perform the transition to the next epoch. + /// + /// Typically, the `ExternalTrigger` type should be used. An internal trigger should only be used + /// when no other module is responsible for changing authority set. + type EpochChangeTrigger: EpochChangeTrigger; +} + +impl Trait for T { + type EpochDuration = ::EpochDuration; + type ExpectedBlockTime = ::ExpectedBlockTime; + type EpochChangeTrigger = ::EpochChangeTrigger; + + type AuthorityId = AuthorityId; + type AuthorityWeight = BabeAuthorityWeight; + type SlotNumber = SlotNumber; + type RawPreDigest = RawPreDigest; + + fn find_raw_pre_digest() -> Option { + >::digest() + .logs + .iter() + .filter_map(|s| s.as_pre_runtime()) + .filter_map(|(id, mut data)| if id == BABE_ENGINE_ID { + RawPreDigest::decode(&mut data).ok() + } else { + None + }) + .next() + } + + fn deposit_next_epoch_descriptor( + next_authorities: Vec<(Self::AuthorityId, Self::AuthorityWeight)>, + next_randomness: schnorrkel::Randomness, + ) { + let next = NextEpochDescriptor { + authorities: next_authorities, + randomness: next_randomness, + }; + + let log: DigestItem = DigestItem::Consensus(BABE_ENGINE_ID, next.encode()); + >::deposit_log(log.into()); + } + + fn deposit_disabled_event(i: u32) { + let log: DigestItem = DigestItem::Consensus( + BABE_ENGINE_ID, + ConsensusLog::OnDisabled(i as u32).encode(), + ); + >::deposit_log(log.into()); + } +} + +impl RawPreDigestT for RawPreDigest { + type SlotNumber = SlotNumber; + + fn vrf_output(&self) -> Option { + if let RawPreDigest::Primary(ref primary) = self { + Some(primary.vrf_output.clone()) + } else { + None + } + } + + fn slot_number(&self) -> SlotNumber { + self.slot_number() + } +} diff --git a/frame/epoch-vrf/src/lib.rs b/frame/epoch-vrf/src/lib.rs index 07dd51aeb438b..e1a1a7ea442eb 100644 --- a/frame/epoch-vrf/src/lib.rs +++ b/frame/epoch-vrf/src/lib.rs @@ -40,14 +40,12 @@ use sp_staking::{ use codec::{Encode, EncodeLike, Decode}; use sp_inherents::{InherentIdentifier, InherentData, ProvideInherent, MakeFatalError}; -use sp_consensus_vrf::schnorrkel::{self, VRF_OUTPUT_LENGTH}; - -// TODO: Move those out of sp-consensus-babe. -use sp_consensus_babe::inherents::{INHERENT_IDENTIFIER, BabeInherentData}; +use sp_consensus_epoch_vrf::schnorrkel::{self, VRF_OUTPUT_LENGTH}; +use sp_consensus_epoch_vrf::inherents::{INHERENT_IDENTIFIER, SlotInherentData}; +pub mod babe; #[cfg(all(feature = "std", test))] mod tests; - #[cfg(all(feature = "std", test))] mod mock; @@ -586,7 +584,7 @@ impl ProvideInherent for Module { }; let timestamp_based_slot = (timestamp / Self::slot_duration()).saturated_into::(); - let seal_slot = data.babe_inherent_data()?; + let seal_slot = data.slot_inherent_data()?; if timestamp_based_slot == seal_slot { Ok(()) diff --git a/primitives/consensus/babe/Cargo.toml b/primitives/consensus/babe/Cargo.toml index ba7e7fffb623b..62785bc11b88f 100644 --- a/primitives/consensus/babe/Cargo.toml +++ b/primitives/consensus/babe/Cargo.toml @@ -17,7 +17,7 @@ codec = { package = "parity-scale-codec", version = "1.3.0", default-features = sp-std = { version = "2.0.0-dev", default-features = false, path = "../../std" } sp-api = { version = "2.0.0-dev", default-features = false, path = "../../api" } sp-consensus = { version = "0.8.0-dev", optional = true, path = "../common" } -sp-consensus-vrf = { version = "0.8.0-dev", path = "../vrf", default-features = false } +sp-consensus-epoch-vrf = { version = "0.8.0-dev", path = "../epoch-vrf", default-features = false } sp-inherents = { version = "2.0.0-dev", default-features = false, path = "../../inherents" } sp-runtime = { version = "2.0.0-dev", default-features = false, path = "../../runtime" } sp-timestamp = { version = "2.0.0-dev", default-features = false, path = "../../timestamp" } @@ -30,7 +30,7 @@ std = [ "sp-std/std", "sp-api/std", "sp-consensus", - "sp-consensus-vrf/std", + "sp-consensus-epoch-vrf/std", "sp-inherents/std", "sp-runtime/std", "sp-timestamp/std", diff --git a/primitives/consensus/babe/src/digests.rs b/primitives/consensus/babe/src/digests.rs index 6079aa88c8749..2c305e3b15a75 100644 --- a/primitives/consensus/babe/src/digests.rs +++ b/primitives/consensus/babe/src/digests.rs @@ -28,9 +28,9 @@ use codec::{Decode, Encode}; use codec::Codec; use sp_std::vec::Vec; use sp_runtime::RuntimeDebug; -use sp_consensus_vrf::schnorrkel::{self, Randomness}; +use sp_consensus_epoch_vrf::schnorrkel::{self, Randomness}; #[cfg(feature = "std")] -use sp_consensus_vrf::schnorrkel::SignatureError; +use sp_consensus_epoch_vrf::schnorrkel::SignatureError; /// Raw BABE primary slot assignment pre-digest. #[derive(Clone, RuntimeDebug, Encode, Decode)] diff --git a/primitives/consensus/babe/src/lib.rs b/primitives/consensus/babe/src/lib.rs index 27b3d367372ee..e4f30f19e63f0 100644 --- a/primitives/consensus/babe/src/lib.rs +++ b/primitives/consensus/babe/src/lib.rs @@ -20,9 +20,8 @@ #![cfg_attr(not(feature = "std"), no_std)] pub mod digests; -pub mod inherents; -pub use sp_consensus_vrf::schnorrkel::{ +pub use sp_consensus_epoch_vrf::schnorrkel::{ Randomness, VRF_PROOF_LENGTH, VRF_OUTPUT_LENGTH, RANDOMNESS_LENGTH }; diff --git a/primitives/consensus/vrf/Cargo.toml b/primitives/consensus/epoch-vrf/Cargo.toml similarity index 77% rename from primitives/consensus/vrf/Cargo.toml rename to primitives/consensus/epoch-vrf/Cargo.toml index 71b647df593d3..fcdc910d478a6 100644 --- a/primitives/consensus/vrf/Cargo.toml +++ b/primitives/consensus/epoch-vrf/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "sp-consensus-vrf" +name = "sp-consensus-epoch-vrf" version = "0.8.0-dev" authors = ["Parity Technologies "] description = "Primitives for VRF based consensus" @@ -17,6 +17,8 @@ schnorrkel = { version = "0.9.1", features = ["preaudit_deprecated"], optional = sp-std = { version = "2.0.0-dev", path = "../../std", default-features = false } sp-core = { version = "2.0.0-dev", path = "../../core", default-features = false } sp-runtime = { version = "2.0.0-dev", default-features = false, path = "../../runtime" } +sp-inherents = { version = "2.0.0-dev", default-features = false, path = "../../inherents" } +sp-timestamp = { version = "2.0.0-dev", default-features = false, path = "../../timestamp" } [features] default = ["std"] @@ -26,4 +28,6 @@ std = [ "sp-std/std", "sp-core/std", "sp-runtime/std", + "sp-inherents/std", + "sp-timestamp/std", ] diff --git a/primitives/consensus/babe/src/inherents.rs b/primitives/consensus/epoch-vrf/src/inherents.rs similarity index 83% rename from primitives/consensus/babe/src/inherents.rs rename to primitives/consensus/epoch-vrf/src/inherents.rs index 7c0744ac6e13a..2070c8e5d084e 100644 --- a/primitives/consensus/babe/src/inherents.rs +++ b/primitives/consensus/epoch-vrf/src/inherents.rs @@ -25,26 +25,26 @@ use sp_timestamp::TimestampInherentData; use codec::Decode; use sp_std::result::Result; -/// The BABE inherent identifier. +/// The Slot inherent identifier. pub const INHERENT_IDENTIFIER: InherentIdentifier = *b"babeslot"; /// The type of the BABE inherent. pub type InherentType = u64; /// Auxiliary trait to extract BABE inherent data. -pub trait BabeInherentData { - /// Get BABE inherent data. - fn babe_inherent_data(&self) -> Result; - /// Replace BABE inherent data. - fn babe_replace_inherent_data(&mut self, new: InherentType); +pub trait SlotInherentData { + /// Get Slot inherent data. + fn slot_inherent_data(&self) -> Result; + /// Replace Slot inherent data. + fn slot_replace_inherent_data(&mut self, new: InherentType); } -impl BabeInherentData for InherentData { - fn babe_inherent_data(&self) -> Result { +impl SlotInherentData for InherentData { + fn slot_inherent_data(&self) -> Result { self.get_data(&INHERENT_IDENTIFIER) - .and_then(|r| r.ok_or_else(|| "BABE inherent data not found".into())) + .and_then(|r| r.ok_or_else(|| "Slot inherent data not found".into())) } - fn babe_replace_inherent_data(&mut self, new: InherentType) { + fn slot_replace_inherent_data(&mut self, new: InherentType) { self.replace_data(INHERENT_IDENTIFIER, &new); } } diff --git a/primitives/consensus/vrf/src/lib.rs b/primitives/consensus/epoch-vrf/src/lib.rs similarity index 97% rename from primitives/consensus/vrf/src/lib.rs rename to primitives/consensus/epoch-vrf/src/lib.rs index 4ec6e376d6829..22b771da6b800 100644 --- a/primitives/consensus/vrf/src/lib.rs +++ b/primitives/consensus/epoch-vrf/src/lib.rs @@ -18,3 +18,4 @@ #![cfg_attr(not(feature = "std"), no_std)] pub mod schnorrkel; +pub mod inherents; diff --git a/primitives/consensus/vrf/src/schnorrkel.rs b/primitives/consensus/epoch-vrf/src/schnorrkel.rs similarity index 100% rename from primitives/consensus/vrf/src/schnorrkel.rs rename to primitives/consensus/epoch-vrf/src/schnorrkel.rs From 4d57f6955ef1b52bfaed7f7ba3e7bdc37e869e00 Mon Sep 17 00:00:00 2001 From: Wei Tang Date: Thu, 16 Apr 2020 17:54:47 +0200 Subject: [PATCH 03/13] Add back FindAuthor trait implementation for Babe --- frame/epoch-vrf/src/babe.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/frame/epoch-vrf/src/babe.rs b/frame/epoch-vrf/src/babe.rs index 9000594a8142b..187d40fc941c8 100644 --- a/frame/epoch-vrf/src/babe.rs +++ b/frame/epoch-vrf/src/babe.rs @@ -1,5 +1,6 @@ use codec::{Encode, Decode}; -use frame_support::traits::Get; +use frame_support::{ConsensusEngineId, traits::{Get, FindAuthor}}; +use sp_std::marker::PhantomData; use sp_runtime::generic::DigestItem; use sp_consensus_babe::{SlotNumber, AuthorityId, BabeAuthorityWeight, ConsensusLog, BABE_ENGINE_ID}; use sp_consensus_babe::digests::{RawPreDigest, NextEpochDescriptor}; @@ -85,3 +86,20 @@ impl RawPreDigestT for RawPreDigest { self.slot_number() } } + +pub struct BabeFindAuthor(PhantomData); + +impl FindAuthor for BabeFindAuthor { + fn find_author<'a, I>(digests: I) -> Option where + I: 'a + IntoIterator + { + for (id, mut data) in digests.into_iter() { + if id == BABE_ENGINE_ID { + let pre_digest: RawPreDigest = RawPreDigest::decode(&mut data).ok()?; + return Some(pre_digest.authority_index()) + } + } + + return None; + } +} From a287b0f254d492b3e2f1bc934f324ed0d6e5384b Mon Sep 17 00:00:00 2001 From: Wei Tang Date: Thu, 16 Apr 2020 18:34:48 +0200 Subject: [PATCH 04/13] Fix all frame-epoch-vrf tests --- frame/epoch-vrf/src/babe.rs | 7 +++++-- frame/epoch-vrf/src/mock.rs | 17 ++++++++++------- frame/epoch-vrf/src/tests.rs | 16 +++++++++++----- 3 files changed, 26 insertions(+), 14 deletions(-) diff --git a/frame/epoch-vrf/src/babe.rs b/frame/epoch-vrf/src/babe.rs index 187d40fc941c8..03e98104a3ac2 100644 --- a/frame/epoch-vrf/src/babe.rs +++ b/frame/epoch-vrf/src/babe.rs @@ -1,6 +1,6 @@ +use sp_std::{prelude::*, marker::PhantomData}; use codec::{Encode, Decode}; use frame_support::{ConsensusEngineId, traits::{Get, FindAuthor}}; -use sp_std::marker::PhantomData; use sp_runtime::generic::DigestItem; use sp_consensus_babe::{SlotNumber, AuthorityId, BabeAuthorityWeight, ConsensusLog, BABE_ENGINE_ID}; use sp_consensus_babe::digests::{RawPreDigest, NextEpochDescriptor}; @@ -58,7 +58,10 @@ impl Trait for T { randomness: next_randomness, }; - let log: DigestItem = DigestItem::Consensus(BABE_ENGINE_ID, next.encode()); + let log: DigestItem = DigestItem::Consensus( + BABE_ENGINE_ID, + ConsensusLog::NextEpochData(next).encode() + ); >::deposit_log(log.into()); } diff --git a/frame/epoch-vrf/src/mock.rs b/frame/epoch-vrf/src/mock.rs index ea802b268e399..f201da8a82f7b 100644 --- a/frame/epoch-vrf/src/mock.rs +++ b/frame/epoch-vrf/src/mock.rs @@ -17,7 +17,7 @@ //! Test utilities use codec::Encode; -use super::{Trait, Module, GenesisConfig, CurrentSlot}; +use super::{Module, GenesisConfig, CurrentSlot, babe::BabeTrait}; use sp_runtime::{ Perbill, impl_opaque_keys, testing::{Header, UintAuthorityId, Digest, DigestItem}, @@ -31,7 +31,7 @@ use frame_support::{ }; use sp_io; use sp_core::H256; -use sp_consensus_vrf::schnorrkel::{RawVRFOutput, RawVRFProof}; +use sp_consensus_epoch_vrf::schnorrkel::{RawVRFOutput, RawVRFProof}; impl_outer_origin!{ pub enum Origin for Test where system = frame_system {} @@ -100,7 +100,7 @@ impl pallet_timestamp::Trait for Test { type MinimumPeriod = MinimumPeriod; } -impl Trait for Test { +impl BabeTrait for Test { type EpochDuration = EpochDuration; type ExpectedBlockTime = ExpectedBlockTime; type EpochChangeTrigger = crate::ExternalTrigger; @@ -108,9 +108,12 @@ impl Trait for Test { pub fn new_test_ext(authorities: Vec) -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); - GenesisConfig { - authorities: authorities.into_iter().map(|a| (UintAuthorityId(a).to_public_key(), 1)).collect(), - }.assimilate_storage::(&mut t).unwrap(); + GenesisConfig:: { + authorities: authorities + .into_iter() + .map(|a| (UintAuthorityId(a).to_public_key(), 1)) + .collect(), + }.assimilate_storage(&mut t).unwrap(); t.into() } @@ -119,7 +122,7 @@ pub fn go_to_block(n: u64, s: u64) { System::initialize(&n, &Default::default(), &Default::default(), &pre_digest, InitKind::Full); System::set_block_number(n); if s > 1 { - CurrentSlot::put(s); + CurrentSlot::::put(s); } // includes a call into `Babe::do_initialize`. Session::on_initialize(n); diff --git a/frame/epoch-vrf/src/tests.rs b/frame/epoch-vrf/src/tests.rs index 24aba100178e0..d77af13658fcc 100644 --- a/frame/epoch-vrf/src/tests.rs +++ b/frame/epoch-vrf/src/tests.rs @@ -16,11 +16,13 @@ //! Consensus extension module tests for BABE consensus. -use super::*; +use super::{*, babe::*}; use mock::*; -use frame_support::traits::OnFinalize; +use sp_runtime::generic::DigestItem; +use frame_support::traits::{OnFinalize, FindAuthor}; use pallet_session::ShouldEndSession; -use sp_consensus_vrf::schnorrkel::{RawVRFOutput, RawVRFProof}; +use sp_consensus_babe::BABE_ENGINE_ID; +use sp_consensus_epoch_vrf::schnorrkel::{RawVRFOutput, RawVRFProof, RANDOMNESS_LENGTH}; const EMPTY_RANDOMNESS: [u8; 32] = [ 74, 25, 49, 128, 53, 97, 244, 49, @@ -109,8 +111,12 @@ fn first_block_epoch_zero_start() { fn authority_index() { new_test_ext(vec![0, 1, 2, 3]).execute_with(|| { assert_eq!( - Babe::find_author((&[(BABE_ENGINE_ID, &[][..])]).into_iter().cloned()), None, - "Trivially invalid authorities are ignored") + BabeFindAuthor::::find_author( + (&[(BABE_ENGINE_ID, &[][..])]).into_iter().cloned() + ), + None, + "Trivially invalid authorities are ignored" + ) }) } From cc75e49b1b275a896875c383c3d1f029a751892b Mon Sep 17 00:00:00 2001 From: Wei Tang Date: Thu, 16 Apr 2020 19:12:23 +0200 Subject: [PATCH 05/13] Fix tests in clients and nodes --- bin/node/runtime/src/lib.rs | 12 ++++++------ bin/node/testing/src/genesis.rs | 2 +- client/consensus/babe/src/authorship.rs | 2 +- client/consensus/babe/src/lib.rs | 12 ++++++------ frame/epoch-vrf/src/lib.rs | 4 +++- test-utils/runtime/src/lib.rs | 12 ++++++------ 6 files changed, 23 insertions(+), 21 deletions(-) diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index 1daad5c12ce19..a5dc4cc8a3b44 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -127,8 +127,8 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { // and set impl_version to 0. If only runtime // implementation changes and behavior does not, then leave spec_version as // is and increment impl_version. - spec_version: 240, - impl_version: 2, + spec_version: 241, + impl_version: 0, apis: RUNTIME_API_VERSIONS, }; @@ -222,10 +222,10 @@ parameter_types! { pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK; } -impl pallet_babe::Trait for Runtime { +impl pallet_epoch_vrf::babe::BabeTrait for Runtime { type EpochDuration = EpochDuration; type ExpectedBlockTime = ExpectedBlockTime; - type EpochChangeTrigger = pallet_babe::ExternalTrigger; + type EpochChangeTrigger = pallet_epoch_vrf::ExternalTrigger; } parameter_types! { @@ -284,7 +284,7 @@ parameter_types! { } impl pallet_authorship::Trait for Runtime { - type FindAuthor = pallet_session::FindAccountFromAuthorIndex; + type FindAuthor = pallet_session::FindAccountFromAuthorIndex>; type UncleGenerations = UncleGenerations; type FilterUncle = (); type EventHandler = (Staking, ImOnline); @@ -661,7 +661,7 @@ construct_runtime!( { System: frame_system::{Module, Call, Config, Storage, Event}, Utility: pallet_utility::{Module, Call, Storage, Event}, - Babe: pallet_babe::{Module, Call, Storage, Config, Inherent(Timestamp)}, + Babe: pallet_epoch_vrf::{Module, Call, Storage, Config, Inherent(Timestamp)}, Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent}, Authorship: pallet_authorship::{Module, Call, Storage, Inherent}, Indices: pallet_indices::{Module, Call, Storage, Config, Event}, diff --git a/bin/node/testing/src/genesis.rs b/bin/node/testing/src/genesis.rs index 8a57010770f3d..a1a96718d31c9 100644 --- a/bin/node/testing/src/genesis.rs +++ b/bin/node/testing/src/genesis.rs @@ -99,7 +99,7 @@ pub fn config_endowed( current_schedule: Default::default(), gas_price: 1 * MILLICENTS, }), - pallet_babe: Some(Default::default()), + pallet_epoch_vrf: Some(Default::default()), pallet_grandpa: Some(GrandpaConfig { authorities: vec![], }), diff --git a/client/consensus/babe/src/authorship.rs b/client/consensus/babe/src/authorship.rs index 074e582bff252..8d7f0d4043727 100644 --- a/client/consensus/babe/src/authorship.rs +++ b/client/consensus/babe/src/authorship.rs @@ -22,7 +22,7 @@ use sp_consensus_babe::{ SlotNumber, AuthorityPair, BabeConfiguration }; use sp_consensus_babe::digests::{PreDigest, PrimaryPreDigest, SecondaryPreDigest}; -use sp_consensus_vrf::schnorrkel::{VRFOutput, VRFProof}; +use sp_consensus_epoch_vrf::schnorrkel::{VRFOutput, VRFProof}; use sp_core::{U256, blake2_256}; use codec::Encode; use schnorrkel::vrf::VRFInOut; diff --git a/client/consensus/babe/src/lib.rs b/client/consensus/babe/src/lib.rs index 092bf8153b9bf..a4c49c5f42023 100644 --- a/client/consensus/babe/src/lib.rs +++ b/client/consensus/babe/src/lib.rs @@ -91,7 +91,7 @@ use sp_consensus::{ ForkChoiceStrategy, BlockImportParams, BlockOrigin, Error as ConsensusError, SelectChain, SlotData, }; -use sp_consensus_babe::inherents::BabeInherentData; +use sp_consensus_epoch_vrf::inherents::SlotInherentData; use sp_timestamp::{TimestampInherentData, InherentType as TimestampInherent}; use sp_consensus::import_queue::{Verifier, BasicQueue, CacheKeyId}; use sc_client_api::{ @@ -620,7 +620,7 @@ impl SlotCompatible for TimeSource { ) -> Result<(TimestampInherent, u64, std::time::Duration), sp_consensus::Error> { trace!(target: "babe", "extract timestamp"); data.timestamp_inherent_data() - .and_then(|t| data.babe_inherent_data().map(|a| (t, a))) + .and_then(|t| data.slot_inherent_data().map(|a| (t, a))) .map_err(Into::into) .map_err(sp_consensus::Error::InherentData) .map(|(x, y)| (x, y, self.0.lock().0.take().unwrap_or_default())) @@ -780,7 +780,7 @@ impl Verifier for BabeVerifier where // to check that the internally-set timestamp in the inherents // actually matches the slot set in the seal. if let Some(inner_body) = body.take() { - inherent_data.babe_replace_inherent_data(slot_number); + inherent_data.slot_replace_inherent_data(slot_number); let block = Block::new(pre_header.clone(), inner_body); self.check_inherents( @@ -831,9 +831,9 @@ fn register_babe_inherent_data_provider( slot_duration: u64, ) -> Result<(), sp_consensus::Error> { debug!(target: "babe", "Registering"); - if !inherent_data_providers.has_provider(&sp_consensus_babe::inherents::INHERENT_IDENTIFIER) { + if !inherent_data_providers.has_provider(&sp_consensus_epoch_vrf::inherents::INHERENT_IDENTIFIER) { inherent_data_providers - .register_provider(sp_consensus_babe::inherents::InherentDataProvider::new(slot_duration)) + .register_provider(sp_consensus_epoch_vrf::inherents::InherentDataProvider::new(slot_duration)) .map_err(Into::into) .map_err(sp_consensus::Error::InherentData) } else { @@ -1008,7 +1008,7 @@ impl BlockImport for BabeBlockImport= start slot {}).", viable_epoch.as_ref().epoch_index, hash, diff --git a/frame/epoch-vrf/src/lib.rs b/frame/epoch-vrf/src/lib.rs index e1a1a7ea442eb..02089955e3a92 100644 --- a/frame/epoch-vrf/src/lib.rs +++ b/frame/epoch-vrf/src/lib.rs @@ -438,7 +438,9 @@ impl Module { // we need to adjust internal storage accordingly. if >::get() == Default::default() { >::put(digest.slot_number()); - debug_assert_ne!(>::get(), Default::default()); + #[cfg(feature = "std")] { + debug_assert_ne!(>::get(), Default::default()); + } // deposit a log because this is the first block in epoch #0 // we use the same values as genesis because we haven't collected any diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index c0aea9a2ab599..881c3528c387f 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -418,13 +418,13 @@ parameter_types! { pub const ExpectedBlockTime: u64 = 10_000; } -impl pallet_babe::Trait for Runtime { +impl pallet_epoch_vrf::babe::BabeTrait for Runtime { type EpochDuration = EpochDuration; type ExpectedBlockTime = ExpectedBlockTime; // there is no actual runtime in this test-runtime, so testing crates // are manually adding the digests. normally in this situation you'd use // pallet_babe::SameAuthoritiesForever. - type EpochChangeTrigger = pallet_babe::ExternalTrigger; + type EpochChangeTrigger = pallet_epoch_vrf::ExternalTrigger; } /// Adds one to the given input and returns the final result. @@ -635,13 +635,13 @@ cfg_if! { c: (3, 10), genesis_authorities: system::authorities() .into_iter().map(|x|(x, 1)).collect(), - randomness: >::randomness(), + randomness: >::randomness(), secondary_slots: true, } } fn current_epoch_start() -> SlotNumber { - >::current_epoch_start() + >::current_epoch_start() } } @@ -829,13 +829,13 @@ cfg_if! { c: (3, 10), genesis_authorities: system::authorities() .into_iter().map(|x|(x, 1)).collect(), - randomness: >::randomness(), + randomness: >::randomness(), secondary_slots: true, } } fn current_epoch_start() -> SlotNumber { - >::current_epoch_start() + >::current_epoch_start() } } From 746b20bc709aa99b115d43abdccbe4798fd2b2f4 Mon Sep 17 00:00:00 2001 From: Wei Tang Date: Thu, 16 Apr 2020 19:15:45 +0200 Subject: [PATCH 06/13] Fix cli tests --- bin/node/cli/src/chain_spec.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/node/cli/src/chain_spec.rs b/bin/node/cli/src/chain_spec.rs index 6d67c61381270..0c5a6c15e89b1 100644 --- a/bin/node/cli/src/chain_spec.rs +++ b/bin/node/cli/src/chain_spec.rs @@ -297,7 +297,7 @@ pub fn testnet_genesis( pallet_sudo: Some(SudoConfig { key: root_key, }), - pallet_babe: Some(BabeConfig { + pallet_epoch_vrf: Some(BabeConfig { authorities: vec![], }), pallet_im_online: Some(ImOnlineConfig { From 9ed0c9eb207b97bad3b891022cadc43abb46fd56 Mon Sep 17 00:00:00 2001 From: Wei Tang Date: Tue, 12 May 2020 15:15:09 +0200 Subject: [PATCH 07/13] Fix epoch-vrf dependency and update cargo lock --- Cargo.lock | 4 +++- frame/offences/benchmarking/Cargo.toml | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 14ad35d728994..5bd8ee1af6ac5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4003,6 +4003,7 @@ dependencies = [ "sp-std", ] +[[package]] name = "pallet-balances" version = "2.0.0-dev" dependencies = [ @@ -4178,6 +4179,7 @@ dependencies = [ "pallet-timestamp", "parity-scale-codec", "serde", + "sp-application-crypto", "sp-consensus-babe", "sp-consensus-epoch-vrf", "sp-core", @@ -4402,8 +4404,8 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", - "pallet-babe", "pallet-balances", + "pallet-epoch-vrf", "pallet-grandpa", "pallet-im-online", "pallet-offences", diff --git a/frame/offences/benchmarking/Cargo.toml b/frame/offences/benchmarking/Cargo.toml index 7b998176eb0de..63b881ceb5a1f 100644 --- a/frame/offences/benchmarking/Cargo.toml +++ b/frame/offences/benchmarking/Cargo.toml @@ -16,7 +16,7 @@ codec = { package = "parity-scale-codec", version = "1.3.0", default-features = frame-benchmarking = { version = "2.0.0-dev", default-features = false, path = "../../benchmarking" } frame-support = { version = "2.0.0-dev", default-features = false, path = "../../support" } frame-system = { version = "2.0.0-dev", default-features = false, path = "../../system" } -pallet-babe = { version = "2.0.0-dev", default-features = false, path = "../../babe" } +pallet-epoch-vrf = { version = "2.0.0-dev", default-features = false, path = "../../epoch-vrf" } pallet-balances = { version = "2.0.0-dev", default-features = false, path = "../../balances" } pallet-grandpa = { version = "2.0.0-dev", default-features = false, path = "../../grandpa" } pallet-im-online = { version = "2.0.0-dev", default-features = false, path = "../../im-online" } @@ -42,7 +42,7 @@ std = [ "frame-benchmarking/std", "frame-support/std", "frame-system/std", - "pallet-babe/std", + "pallet-epoch-vrf/std", "pallet-balances/std", "pallet-grandpa/std", "pallet-im-online/std", From 0e724564e7bd7335dbd18f61e98c33495d2238f2 Mon Sep 17 00:00:00 2001 From: Wei Tang Date: Tue, 12 May 2020 15:49:54 +0200 Subject: [PATCH 08/13] Fix all build errors in frame-epoch-vrf --- frame/epoch-vrf/src/babe.rs | 74 ++++++++++++------------ frame/epoch-vrf/src/lib.rs | 28 ++++----- primitives/consensus/babe/src/digests.rs | 4 +- 3 files changed, 52 insertions(+), 54 deletions(-) diff --git a/frame/epoch-vrf/src/babe.rs b/frame/epoch-vrf/src/babe.rs index 1ab17ebdda403..fb87ef6865117 100644 --- a/frame/epoch-vrf/src/babe.rs +++ b/frame/epoch-vrf/src/babe.rs @@ -1,11 +1,15 @@ use sp_std::{prelude::*, marker::PhantomData}; use codec::{Encode, Decode}; -use frame_support::{ConsensusEngineId, traits::{Get, FindAuthor}}; +use frame_support::{ConsensusEngineId, traits::{Get, FindAuthor}, storage::StorageValue}; use sp_runtime::generic::DigestItem; -use sp_consensus_babe::{SlotNumber, AuthorityId, BabeAuthorityWeight, ConsensusLog, BABE_ENGINE_ID}; -use sp_consensus_babe::digests::{RawPreDigest, NextEpochDescriptor}; +use sp_consensus_babe::{ + SlotNumber, AuthorityId, BabeAuthorityWeight, + ConsensusLog, BABE_ENGINE_ID +}; +use sp_consensus_babe::digests::{PreDigest, NextEpochDescriptor}; use sp_consensus_epoch_vrf::schnorrkel; -use crate::{EpochChangeTrigger, Trait, RawPreDigest as RawPreDigestT}; +use sp_application_crypto::Public; +use crate::{EpochChangeTrigger, Trait, PreDigest as PreDigestT}; pub trait BabeTrait: pallet_timestamp::Trait { /// The amount of time, in slots, that each epoch should last. @@ -34,9 +38,9 @@ impl Trait for T { type AuthorityId = AuthorityId; type AuthorityWeight = BabeAuthorityWeight; type SlotNumber = SlotNumber; - type RawPreDigest = RawPreDigest; + type PreDigest = PreDigest; - fn find_raw_pre_digest() -> Option { + fn find_pre_digest() -> Option { >::digest() .logs .iter() @@ -73,41 +77,37 @@ impl Trait for T { >::deposit_log(log.into()); } - fn make_randomness(vrf_output: VRFOutput) { - // Reconstruct the bytes of VRFInOut using the authority id. - Authorities::get() - .get(primary.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::get(), - ); - - primary.vrf_output.0.attach_input_hash( - &pubkey, - transcript - ).ok() - }) - .map(|inout| { - inout.make_bytes(&sp_consensus_babe::BABE_VRF_INOUT_CONTEXT) - }) - } -} - -impl RawPreDigestT for RawPreDigest { - type SlotNumber = SlotNumber; - - fn vrf_output(&self) -> Option { - if let RawPreDigest::Primary(ref primary) = self { - Some(primary.vrf_output.clone()) + fn make_randomness(pre_digest: &Self::PreDigest) -> Option { + if let PreDigest::Primary(ref primary) = pre_digest { + // Reconstruct the bytes of VRFInOut using the authority id. + super::Authorities::::get() + .get(primary.authority_index as usize) + .and_then(|author: &(AuthorityId, BabeAuthorityWeight)| { + schnorrkel::PublicKey::from_bytes(author.0.as_slice()).ok() + }) + .and_then(|pubkey| { + let transcript = sp_consensus_babe::make_transcript( + &super::Randomness::get(), + primary.slot_number, + super::EpochIndex::::get(), + ); + + primary.vrf_output.0.attach_input_hash( + &pubkey, + transcript + ).ok() + }) + .map(|inout| { + inout.make_bytes(&sp_consensus_babe::BABE_VRF_INOUT_CONTEXT) + }) } else { None } } +} + +impl PreDigestT for PreDigest { + type SlotNumber = SlotNumber; fn slot_number(&self) -> SlotNumber { self.slot_number() diff --git a/frame/epoch-vrf/src/lib.rs b/frame/epoch-vrf/src/lib.rs index d92f563b022e1..3e19ae62b22b1 100644 --- a/frame/epoch-vrf/src/lib.rs +++ b/frame/epoch-vrf/src/lib.rs @@ -24,8 +24,8 @@ use pallet_timestamp; use sp_std::{result, prelude::*}; use frame_support::{ - decl_storage, decl_module, traits::{FindAuthor, Get, Randomness as RandomnessT}, - weights::{Weight, MINIMUM_WEIGHT}, + decl_storage, decl_module, traits::{Get, Randomness as RandomnessT}, + weights::Weight, }; use sp_timestamp::OnTimestampSet; use sp_runtime::{Perbill, RuntimeAppPublic}; @@ -37,7 +37,6 @@ use sp_staking::{ SessionIndex, offence::{Offence, Kind}, }; -use sp_application_crypto::Public; use codec::{Encode, EncodeLike, Decode}; use sp_inherents::{InherentIdentifier, InherentData, ProvideInherent, MakeFatalError}; @@ -50,13 +49,11 @@ mod tests; #[cfg(all(feature = "std", test))] mod mock; -/// Raw pre-digest for this block production engine. -pub trait RawPreDigest { +/// Pre-digest for this block production engine. +pub trait PreDigest { /// Type of slot number. type SlotNumber; - /// Primary VRF output. - fn vrf_output(&self) -> Option; /// Slot number. fn slot_number(&self) -> Self::SlotNumber; } @@ -90,11 +87,11 @@ pub trait Trait: pallet_timestamp::Trait { CheckedSub + CheckedAdd + UniqueSaturatedInto + Ord + One + MaybeDisplay + MaybeDebug + UniqueSaturatedInto; - /// Type of raw pre-digest. - type RawPreDigest: RawPreDigest; + /// Type of pre-digest. + type PreDigest: PreDigest; - /// Find the raw pre-digest in current block. - fn find_raw_pre_digest() -> Option; + /// Find the pre-digest in current block. + fn find_pre_digest() -> Option; /// Deposit next epoch descriptor. fn deposit_next_epoch_descriptor( @@ -104,6 +101,9 @@ pub trait Trait: pallet_timestamp::Trait { /// Deposit disabled event. fn deposit_disabled_event(i: u32); + + /// Make randomness from pre-digest. + fn make_randomness(pre_digest: &Self::PreDigest) -> Option; } /// Trigger an epoch change, if any should take place. @@ -445,7 +445,7 @@ impl Module { return; } - let maybe_pre_digest: Option = T::find_raw_pre_digest(); + let maybe_pre_digest: Option = T::find_pre_digest(); let maybe_randomness: Option = maybe_pre_digest.and_then(|digest| { // on the first non-zero block (i.e. block #1) @@ -472,11 +472,11 @@ impl Module { Lateness::::put(UniqueSaturatedInto::::unique_saturated_into(lateness)); CurrentSlot::::put(current_slot); - if let Some(vrf_output) = digest.vrf_output() { + if let Some(randomness) = T::make_randomness(&digest) { // place the VRF output into the `Initialized` storage item // and it'll be put onto the under-construction randomness // later, once we've decided which epoch this block is in. - Some(T::make_randomness(vrf_output)) + Some(randomness) } else { None } diff --git a/primitives/consensus/babe/src/digests.rs b/primitives/consensus/babe/src/digests.rs index c754dd15ab492..01ffb9fc8ae00 100644 --- a/primitives/consensus/babe/src/digests.rs +++ b/primitives/consensus/babe/src/digests.rs @@ -28,9 +28,7 @@ use codec::{Decode, Encode}; use codec::Codec; use sp_std::vec::Vec; use sp_runtime::RuntimeDebug; -use sp_consensus_epoch_vrf::schnorrkel::{self, Randomness}; -#[cfg(feature = "std")] -use sp_consensus_epoch_vrf::schnorrkel::SignatureError; +use sp_consensus_epoch_vrf::schnorrkel::{Randomness, VRFOutput, VRFProof}; /// Raw BABE primary slot assignment pre-digest. #[derive(Clone, RuntimeDebug, Encode, Decode)] From ce747e55e7fd3fa94c65f75887f68ababf9aa25e Mon Sep 17 00:00:00 2001 From: Wei Tang Date: Tue, 12 May 2020 16:43:02 +0200 Subject: [PATCH 09/13] Fix all epoch-vrf frame tests --- frame/epoch-vrf/src/mock.rs | 10 ++++++---- frame/epoch-vrf/src/tests.rs | 5 +++-- test-utils/runtime/src/lib.rs | 4 ++-- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/frame/epoch-vrf/src/mock.rs b/frame/epoch-vrf/src/mock.rs index 7034c1d103b9f..ae6a1946cb1e7 100644 --- a/frame/epoch-vrf/src/mock.rs +++ b/frame/epoch-vrf/src/mock.rs @@ -30,8 +30,10 @@ use frame_support::{ weights::Weight, }; use sp_io; -use sp_core::H256; -use sp_consensus_epoch_vrf::schnorrkel::{RawVRFOutput, RawVRFProof}; +use sp_core::{U256, H256}; +use sp_application_crypto::Pair; +use sp_consensus_babe::AuthorityPair; +use sp_consensus_epoch_vrf::schnorrkel::{VRFOutput, VRFProof}; impl_outer_origin!{ pub enum Origin for Test where system = frame_system {} @@ -115,9 +117,9 @@ pub fn new_test_ext(authorities_len: usize) -> (Vec, sp_io::TestE }).collect::>(); let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); - GenesisConfig { + GenesisConfig:: { authorities: pairs.iter().map(|a| (a.public(), 1)).collect(), - }.assimilate_storage::(&mut t).unwrap(); + }.assimilate_storage(&mut t).unwrap(); (pairs, t.into()) } diff --git a/frame/epoch-vrf/src/tests.rs b/frame/epoch-vrf/src/tests.rs index d68b1015c9f90..a672906b1e8c8 100644 --- a/frame/epoch-vrf/src/tests.rs +++ b/frame/epoch-vrf/src/tests.rs @@ -21,8 +21,9 @@ use mock::*; use sp_runtime::generic::DigestItem; use frame_support::traits::{OnFinalize, FindAuthor}; use pallet_session::ShouldEndSession; +use sp_application_crypto::IsWrappedBy; use sp_consensus_babe::BABE_ENGINE_ID; -use sp_consensus_epoch_vrf::schnorrkel::{RawVRFOutput, RawVRFProof, RANDOMNESS_LENGTH}; +use sp_consensus_epoch_vrf::schnorrkel::{VRFOutput, VRFProof, RANDOMNESS_LENGTH}; const EMPTY_RANDOMNESS: [u8; 32] = [ 74, 25, 49, 128, 53, 97, 244, 49, @@ -67,7 +68,7 @@ fn first_block_epoch_zero_start() { 0, ); let vrf_inout = pair.vrf_sign(transcript); - let vrf_randomness: sp_consensus_vrf::schnorrkel::Randomness = vrf_inout.0 + let vrf_randomness: sp_consensus_epoch_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); diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index 22027fae44456..070ffaf1a29f3 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -41,7 +41,7 @@ use sp_runtime::{ }, traits::{ BlindCheckable, BlakeTwo256, Block as BlockT, Extrinsic as ExtrinsicT, - GetNodeBlockType, GetRuntimeBlockType, NumberFor, Verify, IdentityLookup, + GetNodeBlockType, GetRuntimeBlockType, Verify, IdentityLookup, }, }; use sp_version::RuntimeVersion; @@ -860,7 +860,7 @@ cfg_if! { c: (3, 10), genesis_authorities: system::authorities() .into_iter().map(|x|(x, 1)).collect(), - randomness: >::randomness(), + randomness: >::randomness(), allowed_slots: AllowedSlots::PrimaryAndSecondaryPlainSlots, } } From 15d6586523daa003938ad285ba7c6cc527e6c9d5 Mon Sep 17 00:00:00 2001 From: Wei Tang Date: Tue, 12 May 2020 16:52:10 +0200 Subject: [PATCH 10/13] Fix consensus-babe compile --- client/consensus/babe/src/authorship.rs | 1 - frame/epoch-vrf/src/lib.rs | 6 +++--- frame/offences/benchmarking/src/lib.rs | 6 +++--- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/client/consensus/babe/src/authorship.rs b/client/consensus/babe/src/authorship.rs index a95f1b531a2c7..2f72a02cd3233 100644 --- a/client/consensus/babe/src/authorship.rs +++ b/client/consensus/babe/src/authorship.rs @@ -23,7 +23,6 @@ use sp_consensus_babe::{ use sp_consensus_babe::digests::{ PreDigest, PrimaryPreDigest, SecondaryPlainPreDigest, SecondaryVRFPreDigest, }; -use sp_consensus_babe::digests::{PreDigest, PrimaryPreDigest, SecondaryPreDigest}; use sp_consensus_epoch_vrf::schnorrkel::{VRFOutput, VRFProof}; use sp_core::{U256, blake2_256}; use codec::Encode; diff --git a/frame/epoch-vrf/src/lib.rs b/frame/epoch-vrf/src/lib.rs index 3e19ae62b22b1..fcb237f0db209 100644 --- a/frame/epoch-vrf/src/lib.rs +++ b/frame/epoch-vrf/src/lib.rs @@ -285,10 +285,10 @@ impl pallet_session::ShouldEndSession for Module { } } -/// A BABE equivocation offence report. +/// An equivocation offence report. /// /// When a validator released two or more blocks at the same slot. -pub struct BabeEquivocationOffence { +pub struct EquivocationOffence { /// A babe slot number in which this incident happened. pub slot: u64, /// The session index in which the incident happened. @@ -299,7 +299,7 @@ pub struct BabeEquivocationOffence { pub offender: FullIdentification, } -impl Offence for BabeEquivocationOffence { +impl Offence for EquivocationOffence { const ID: Kind = *b"babe:equivocatio"; type TimeSlot = u64; diff --git a/frame/offences/benchmarking/src/lib.rs b/frame/offences/benchmarking/src/lib.rs index a0e05a74d58db..7ddd784fe9673 100644 --- a/frame/offences/benchmarking/src/lib.rs +++ b/frame/offences/benchmarking/src/lib.rs @@ -31,7 +31,7 @@ use sp_runtime::{Perbill, traits::{Convert, StaticLookup, Saturating, UniqueSatu use sp_staking::offence::{ReportOffence, Offence, OffenceDetails}; use pallet_balances::{Trait as BalancesTrait}; -use pallet_babe::BabeEquivocationOffence; +use pallet_epoch_vrf::EquivocationOffence; use pallet_grandpa::{GrandpaEquivocationOffence, GrandpaTimeSlot}; use pallet_im_online::{Trait as ImOnlineTrait, Module as ImOnline, UnresponsivenessOffence}; use pallet_offences::{Trait as OffencesTrait, Module as Offences}; @@ -337,9 +337,9 @@ benchmarks! { Staking::::set_slash_reward_fraction(Perbill::one()); let (mut offenders, raw_offenders) = make_offenders::(o, n)?; - let keys = ImOnline::::keys(); + let keys = ImOnline::::keys(); - let offence = BabeEquivocationOffence { + let offence = EquivocationOffence { slot: 0, session_index: 0, validator_set_count: keys.len() as u32, From 0c1d6397e9014c30dd4d2d64f80abd257dac5bd4 Mon Sep 17 00:00:00 2001 From: Wei Tang Date: Tue, 12 May 2020 16:58:30 +0200 Subject: [PATCH 11/13] Add back NumberFor --- test-utils/runtime/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index 070ffaf1a29f3..396af1f12157a 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -41,7 +41,7 @@ use sp_runtime::{ }, traits::{ BlindCheckable, BlakeTwo256, Block as BlockT, Extrinsic as ExtrinsicT, - GetNodeBlockType, GetRuntimeBlockType, Verify, IdentityLookup, + GetNodeBlockType, GetRuntimeBlockType, NumberFor, Verify, IdentityLookup, }, }; use sp_version::RuntimeVersion; From 0f1739ea54005d67f436cf526e206442c42f16a5 Mon Sep 17 00:00:00 2001 From: Wei Tang Date: Tue, 12 May 2020 16:59:32 +0200 Subject: [PATCH 12/13] Fix test-utils epoch-vrf module name --- test-utils/runtime/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index 396af1f12157a..9bf3d1611b074 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -643,7 +643,7 @@ cfg_if! { c: (3, 10), genesis_authorities: system::authorities() .into_iter().map(|x|(x, 1)).collect(), - randomness: >::randomness(), + randomness: >::randomness(), allowed_slots: AllowedSlots::PrimaryAndSecondaryPlainSlots, } } From 1aadb44d9b90c0e527d9e36462b16f91832aff18 Mon Sep 17 00:00:00 2001 From: Wei Tang Date: Tue, 12 May 2020 17:04:47 +0200 Subject: [PATCH 13/13] Bump runtime version --- bin/node/runtime/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index 478dd76aa9783..3c425a5057c45 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -90,7 +90,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { // and set impl_version to 0. If only runtime // implementation changes and behavior does not, then leave spec_version as // is and increment impl_version. - spec_version: 247, + spec_version: 248, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1,