#![cfg_attr(not(feature = "std"), no_std)]
#![warn(unused_must_use, unsafe_code, unused_variables, unused_must_use)]
use codec::{Decode, Encode};
use fabric_support::{
decl_error, decl_module, decl_storage,
dispatch::DispatchResultWithPostInfo,
traits::{FindAuthor, Get, KeyOwnerProofSystem, Randomness as RandomnessT},
weights::{Pays, Weight},
Parameter,
};
use fabric_system::{ensure_none, ensure_signed};
use tet_application_crypto::Public;
use tp_runtime::{
generic::DigestItem,
traits::{Hash, IsMember, One, SaturatedConversion, Saturating},
ConsensusEngineId, KeyTypeId,
};
use tp_session::{GetSessionNumber, GetValidatorCount};
use tetcore_std::{prelude::*, result};
use tp_timestamp::OnTimestampSet;
use tp_consensus_babe::{
digests::{NextConfigDescriptor, NextEpochDescriptor, PreDigest},
inherents::{BabeInherentData, INHERENT_IDENTIFIER},
BabeAuthorityWeight, ConsensusLog, Epoch, EquivocationProof, Slot, BABE_ENGINE_ID,
};
use tp_consensus_vrf::schnorrkel;
use tp_inherents::{InherentData, InherentIdentifier, MakeFatalError, ProvideInherent};
pub use tp_consensus_babe::{AuthorityId, PUBLIC_KEY_LENGTH, RANDOMNESS_LENGTH, VRF_OUTPUT_LENGTH};
mod equivocation;
mod default_weights;
#[cfg(any(feature = "runtime-benchmarks", test))]
mod benchmarking;
#[cfg(all(feature = "std", test))]
mod mock;
#[cfg(all(feature = "std", test))]
mod tests;
pub use equivocation::{BabeEquivocationOffence, EquivocationHandler, HandleEquivocation};
pub trait Config: noble_timestamp::Config {
type EpochDuration: Get<u64>;
type ExpectedBlockTime: Get<Self::Moment>;
type EpochChangeTrigger: EpochChangeTrigger;
type KeyOwnerProof: Parameter + GetSessionNumber + GetValidatorCount;
type KeyOwnerIdentification: Parameter;
type KeyOwnerProofSystem: KeyOwnerProofSystem<
(KeyTypeId, AuthorityId),
Proof = Self::KeyOwnerProof,
IdentificationTuple = Self::KeyOwnerIdentification,
>;
type HandleEquivocation: HandleEquivocation<Self>;
type WeightInfo: WeightInfo;
}
pub trait WeightInfo {
fn report_equivocation(validator_count: u32) -> Weight;
}
pub trait EpochChangeTrigger {
fn trigger<T: Config>(now: T::BlockNumber);
}
pub struct ExternalTrigger;
impl EpochChangeTrigger for ExternalTrigger {
fn trigger<T: Config>(_: T::BlockNumber) { } }
pub struct SameAuthoritiesForever;
impl EpochChangeTrigger for SameAuthoritiesForever {
fn trigger<T: Config>(now: T::BlockNumber) {
if <Module<T>>::should_epoch_change(now) {
let authorities = <Module<T>>::authorities();
let next_authorities = authorities.clone();
<Module<T>>::enact_epoch_change(authorities, next_authorities);
}
}
}
const UNDER_CONSTRUCTION_SEGMENT_LENGTH: usize = 256;
type MaybeRandomness = Option<schnorrkel::Randomness>;
decl_error! {
pub enum Error for Module<T: Config> {
InvalidEquivocationProof,
InvalidKeyOwnershipProof,
DuplicateOffenceReport,
}
}
decl_storage! {
trait Store for Module<T: Config> as Babe {
pub EpochIndex get(fn epoch_index): u64;
pub Authorities get(fn authorities): Vec<(AuthorityId, BabeAuthorityWeight)>;
pub GenesisSlot get(fn genesis_slot): Slot;
pub CurrentSlot get(fn current_slot): Slot;
pub Randomness get(fn randomness): schnorrkel::Randomness;
NextEpochConfig: Option<NextConfigDescriptor>;
NextRandomness: schnorrkel::Randomness;
NextAuthorities: Vec<(AuthorityId, BabeAuthorityWeight)>;
SegmentIndex build(|_| 0): u32;
UnderConstruction: map hasher(twox_64_concat) u32 => Vec<schnorrkel::Randomness>;
Initialized get(fn initialized): Option<MaybeRandomness>;
AuthorVrfRandomness get(fn author_vrf_randomness): MaybeRandomness;
Lateness get(fn lateness): T::BlockNumber;
}
add_extra_genesis {
config(authorities): Vec<(AuthorityId, BabeAuthorityWeight)>;
build(|config| Module::<T>::initialize_authorities(&config.authorities))
}
}
decl_module! {
pub struct Module<T: Config> for enum Call where origin: T::Origin {
const EpochDuration: u64 = T::EpochDuration::get();
const ExpectedBlockTime: T::Moment = T::ExpectedBlockTime::get();
fn on_initialize(now: T::BlockNumber) -> Weight {
Self::do_initialize(now);
0
}
fn on_finalize() {
if let Some(Some(randomness)) = Initialized::take() {
Self::deposit_randomness(&randomness);
}
AuthorVrfRandomness::kill();
Lateness::<T>::kill();
}
#[weight = <T as Config>::WeightInfo::report_equivocation(key_owner_proof.validator_count())]
fn report_equivocation(
origin,
equivocation_proof: EquivocationProof<T::Header>,
key_owner_proof: T::KeyOwnerProof,
) -> DispatchResultWithPostInfo {
let reporter = ensure_signed(origin)?;
Self::do_report_equivocation(
Some(reporter),
equivocation_proof,
key_owner_proof,
)
}
#[weight = <T as Config>::WeightInfo::report_equivocation(key_owner_proof.validator_count())]
fn report_equivocation_unsigned(
origin,
equivocation_proof: EquivocationProof<T::Header>,
key_owner_proof: T::KeyOwnerProof,
) -> DispatchResultWithPostInfo {
ensure_none(origin)?;
Self::do_report_equivocation(
T::HandleEquivocation::block_author(),
equivocation_proof,
key_owner_proof,
)
}
}
}
impl<T: Config> RandomnessT<<T as fabric_system::Config>::Hash> for Module<T> {
fn random(subject: &[u8]) -> T::Hash {
let mut subject = subject.to_vec();
subject.reserve(VRF_OUTPUT_LENGTH);
subject.extend_from_slice(&Self::randomness()[..]);
<T as fabric_system::Config>::Hashing::hash(&subject[..])
}
}
pub type BabeKey = [u8; PUBLIC_KEY_LENGTH];
impl<T: Config> FindAuthor<u32> for Module<T> {
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 {
let pre_digest: PreDigest = PreDigest::decode(&mut data).ok()?;
return Some(pre_digest.authority_index())
}
}
return None;
}
}
impl<T: Config> IsMember<AuthorityId> for Module<T> {
fn is_member(authority_id: &AuthorityId) -> bool {
<Module<T>>::authorities()
.iter()
.any(|id| &id.0 == authority_id)
}
}
impl<T: Config> noble_session::ShouldEndSession<T::BlockNumber> for Module<T> {
fn should_end_session(now: T::BlockNumber) -> bool {
Self::do_initialize(now);
Self::should_epoch_change(now)
}
}
impl<T: Config> Module<T> {
pub fn slot_duration() -> T::Moment {
<T as noble_timestamp::Config>::MinimumPeriod::get().saturating_mul(2u32.into())
}
pub fn should_epoch_change(now: T::BlockNumber) -> bool {
now != One::one() && {
let diff = CurrentSlot::get().saturating_sub(Self::current_epoch_start());
*diff >= T::EpochDuration::get()
}
}
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::get())
.map(|slots_remaining| {
let blocks_remaining: T::BlockNumber = slots_remaining.saturated_into();
now.saturating_add(blocks_remaining)
})
}
pub fn plan_config_change(
config: NextConfigDescriptor,
) {
NextEpochConfig::put(config);
}
pub fn enact_epoch_change(
authorities: Vec<(AuthorityId, BabeAuthorityWeight)>,
next_authorities: Vec<(AuthorityId, BabeAuthorityWeight)>,
) {
debug_assert!(Self::initialized().is_some());
let epoch_index = EpochIndex::get()
.checked_add(1)
.expect("epoch indices will never reach 2^64 before the death of the universe; qed");
EpochIndex::put(epoch_index);
Authorities::put(authorities);
let next_epoch_index = epoch_index
.checked_add(1)
.expect("epoch indices will never reach 2^64 before the death of the universe; qed");
let randomness = Self::randomness_change_epoch(next_epoch_index);
Randomness::put(randomness);
NextAuthorities::put(&next_authorities);
let next_randomness = NextRandomness::get();
let next_epoch = NextEpochDescriptor {
authorities: next_authorities,
randomness: next_randomness,
};
Self::deposit_consensus(ConsensusLog::NextEpochData(next_epoch));
if let Some(next_config) = NextEpochConfig::take() {
Self::deposit_consensus(ConsensusLog::NextConfigData(next_config));
}
}
pub fn current_epoch_start() -> Slot {
Self::epoch_start(EpochIndex::get())
}
pub fn current_epoch() -> Epoch {
Epoch {
epoch_index: EpochIndex::get(),
start_slot: Self::current_epoch_start(),
duration: T::EpochDuration::get(),
authorities: Self::authorities(),
randomness: Self::randomness(),
}
}
pub fn next_epoch() -> Epoch {
let next_epoch_index = EpochIndex::get().checked_add(1).expect(
"epoch index is u64; it is always only incremented by one; \
if u64 is not enough we should crash for safety; qed.",
);
Epoch {
epoch_index: next_epoch_index,
start_slot: Self::epoch_start(next_epoch_index),
duration: T::EpochDuration::get(),
authorities: NextAuthorities::get(),
randomness: NextRandomness::get(),
}
}
fn epoch_start(epoch_index: u64) -> Slot {
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);
epoch_start.checked_add(*GenesisSlot::get()).expect(PROOF).into()
}
fn deposit_consensus<U: Encode>(new: U) {
let log: DigestItem<T::Hash> = DigestItem::Consensus(BABE_ENGINE_ID, new.encode());
<fabric_system::Module<T>>::deposit_log(log.into())
}
fn deposit_randomness(randomness: &schnorrkel::Randomness) {
let segment_idx = <SegmentIndex>::get();
let mut segment = <UnderConstruction>::get(&segment_idx);
if segment.len() < UNDER_CONSTRUCTION_SEGMENT_LENGTH {
segment.push(*randomness);
<UnderConstruction>::insert(&segment_idx, &segment);
} else {
let segment_idx = segment_idx + 1;
<UnderConstruction>::insert(&segment_idx, &vec![randomness.clone()]);
<SegmentIndex>::put(&segment_idx);
}
}
fn do_initialize(now: T::BlockNumber) {
let initialized = Self::initialized().is_some();
if initialized {
return;
}
let maybe_pre_digest: Option<PreDigest> = <fabric_system::Module<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(..)));
let maybe_randomness: MaybeRandomness = maybe_pre_digest.and_then(|digest| {
if *GenesisSlot::get() == 0 {
GenesisSlot::put(digest.slot());
debug_assert_ne!(*GenesisSlot::get(), 0);
let next = NextEpochDescriptor {
authorities: Self::authorities(),
randomness: Self::randomness(),
};
Self::deposit_consensus(ConsensusLog::NextEpochData(next))
}
let current_slot = digest.slot();
let lateness = current_slot.saturating_sub(CurrentSlot::get() + 1);
let lateness = T::BlockNumber::from(*lateness as u32);
Lateness::<T>::put(lateness);
CurrentSlot::put(current_slot);
let authority_index = digest.authority_index();
digest
.vrf_output()
.and_then(|vrf_output| {
Authorities::get()
.get(authority_index as usize)
.and_then(|author| {
schnorrkel::PublicKey::from_bytes(author.0.as_slice()).ok()
})
.and_then(|pubkey| {
let transcript = tp_consensus_babe::make_transcript(
&Self::randomness(),
current_slot,
EpochIndex::get(),
);
vrf_output.0.attach_input_hash(
&pubkey,
transcript
).ok()
})
.map(|inout| {
inout.make_bytes(&tp_consensus_babe::BABE_VRF_INOUT_CONTEXT)
})
})
});
Initialized::put(if is_primary { maybe_randomness } else { None });
AuthorVrfRandomness::put(maybe_randomness);
T::EpochChangeTrigger::trigger::<T>(now)
}
fn randomness_change_epoch(next_epoch_index: u64) -> schnorrkel::Randomness {
let this_randomness = NextRandomness::get();
let segment_idx: u32 = <SegmentIndex>::mutate(|s| tetcore_std::mem::replace(s, 0));
let rho_size = segment_idx.saturating_add(1) as usize * UNDER_CONSTRUCTION_SEGMENT_LENGTH;
let next_randomness = compute_randomness(
this_randomness,
next_epoch_index,
(0..segment_idx).flat_map(|i| <UnderConstruction>::take(&i)),
Some(rho_size),
);
NextRandomness::put(&next_randomness);
this_randomness
}
fn initialize_authorities(authorities: &[(AuthorityId, BabeAuthorityWeight)]) {
if !authorities.is_empty() {
assert!(Authorities::get().is_empty(), "Authorities are already initialized!");
Authorities::put(authorities);
NextAuthorities::put(authorities);
}
}
fn do_report_equivocation(
reporter: Option<T::AccountId>,
equivocation_proof: EquivocationProof<T::Header>,
key_owner_proof: T::KeyOwnerProof,
) -> DispatchResultWithPostInfo {
let offender = equivocation_proof.offender.clone();
let slot = equivocation_proof.slot;
if !tp_consensus_babe::check_equivocation_proof(equivocation_proof) {
return Err(Error::<T>::InvalidEquivocationProof.into());
}
let validator_set_count = key_owner_proof.validator_count();
let session_index = key_owner_proof.session();
let epoch_index = (*slot.saturating_sub(GenesisSlot::get()) / T::EpochDuration::get())
.saturated_into::<u32>();
if epoch_index != session_index {
return Err(Error::<T>::InvalidKeyOwnershipProof.into());
}
let key = (tp_consensus_babe::KEY_TYPE, offender);
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 reporters = match reporter {
Some(id) => vec![id],
None => vec![],
};
T::HandleEquivocation::report_offence(reporters, offence)
.map_err(|_| Error::<T>::DuplicateOffenceReport)?;
Ok(Pays::No.into())
}
pub fn submit_unsigned_equivocation_report(
equivocation_proof: EquivocationProof<T::Header>,
key_owner_proof: T::KeyOwnerProof,
) -> Option<()> {
T::HandleEquivocation::submit_unsigned_equivocation_report(
equivocation_proof,
key_owner_proof,
)
.ok()
}
}
impl<T: Config> OnTimestampSet<T::Moment> for Module<T> {
fn on_timestamp_set(_moment: T::Moment) { }
}
impl<T: Config> fabric_support::traits::EstimateNextSessionRotation<T::BlockNumber> for Module<T> {
fn estimate_next_session_rotation(now: T::BlockNumber) -> Option<T::BlockNumber> {
Self::next_expected_epoch_change(now)
}
fn weight(_now: T::BlockNumber) -> Weight {
T::DbWeight::get().reads(3)
}
}
impl<T: Config> fabric_support::traits::Lateness<T::BlockNumber> for Module<T> {
fn lateness(&self) -> T::BlockNumber {
Self::lateness()
}
}
impl<T: Config> tp_runtime::BoundToRuntimeAppPublic for Module<T> {
type Public = AuthorityId;
}
impl<T: Config> noble_session::OneSessionHandler<T::AccountId> for Module<T> {
type Key = AuthorityId;
fn on_genesis_session<'a, I: 'a>(validators: I)
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)>
{
let authorities = 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)
}
fn on_disabled(i: usize) {
Self::deposit_consensus(ConsensusLog::OnDisabled(i as u32))
}
}
fn compute_randomness(
last_epoch_randomness: schnorrkel::Randomness,
epoch_index: u64,
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);
s.extend_from_slice(&last_epoch_randomness);
s.extend_from_slice(&epoch_index.to_le_bytes());
for vrf_output in rho {
s.extend_from_slice(&vrf_output[..]);
}
tet_io::hashing::blake2_256(&s)
}
impl<T: Config> ProvideInherent for Module<T> {
type Call = noble_timestamp::Call<T>;
type Error = MakeFatalError<tp_inherents::Error>;
const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER;
fn create_inherent(_: &InherentData) -> Option<Self::Call> {
None
}
fn check_inherent(call: &Self::Call, data: &InherentData) -> result::Result<(), Self::Error> {
let timestamp = match call {
noble_timestamp::Call::set(ref timestamp) => timestamp.clone(),
_ => return Ok(()),
};
let timestamp_based_slot = (timestamp / Self::slot_duration()).saturated_into::<u64>();
let seal_slot = data.babe_inherent_data()?;
if timestamp_based_slot == *seal_slot {
Ok(())
} else {
Err(tp_inherents::Error::from("timestamp set in block doesn't match slot in seal").into())
}
}
}