Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Generate storage info for pallet authority_discovery #9428

Merged
20 commits merged into from
Aug 30, 2021
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion bin/node-template/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ parameter_types! {
pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength
::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
pub const SS58Prefix: u8 = 42;
pub const MaxAuthorities: u32 = 100;
}

// Configure FRAME pallets to include in runtime.
Expand Down Expand Up @@ -197,6 +198,7 @@ impl pallet_randomness_collective_flip::Config for Runtime {}

impl pallet_aura::Config for Runtime {
type AuthorityId = AuraId;
type MaxAuthorities = MaxAuthorities;
}

impl pallet_grandpa::Config for Runtime {
Expand Down Expand Up @@ -381,7 +383,7 @@ impl_runtime_apis! {
}

fn authorities() -> Vec<AuraId> {
Aura::authorities()
Aura::authorities().to_vec()
}
}

Expand Down
5 changes: 4 additions & 1 deletion bin/node/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -883,6 +883,7 @@ parameter_types! {
pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::max_value();
/// We prioritize im-online heartbeats over election solution submission.
pub const StakingUnsignedPriority: TransactionPriority = TransactionPriority::max_value() / 2;
pub const MaxAuthorities: u32 = 100;
georgesdib marked this conversation as resolved.
Show resolved Hide resolved
}

impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime
Expand Down Expand Up @@ -955,7 +956,9 @@ impl pallet_offences::Config for Runtime {
type OnOffenceHandler = Staking;
}

impl pallet_authority_discovery::Config for Runtime {}
impl pallet_authority_discovery::Config for Runtime {
type MaxAuthorities = MaxAuthorities;
}

impl pallet_grandpa::Config for Runtime {
type Event = Event;
Expand Down
36 changes: 28 additions & 8 deletions frame/aura/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,10 @@
#![cfg_attr(not(feature = "std"), no_std)]

use codec::{Decode, Encode};
use core::convert::TryFrom;
use frame_support::{
traits::{FindAuthor, Get, OnTimestampSet, OneSessionHandler},
ConsensusEngineId, Parameter,
BoundedVec, ConsensusEngineId, Parameter,
};
use sp_consensus_aura::{AuthorityIndex, ConsensusLog, Slot, AURA_ENGINE_ID};
use sp_runtime::{
Expand Down Expand Up @@ -69,10 +70,15 @@ pub mod pallet {
+ Parameter
+ RuntimeAppPublic
+ Default
+ MaybeSerializeDeserialize;
+ MaybeSerializeDeserialize
+ MaxEncodedLen;

/// The maximum number of authorities that can be added.
type MaxAuthorities: Get<u32>;
}

#[pallet::pallet]
#[pallet::generate_storage_info]
pub struct Pallet<T>(sp_std::marker::PhantomData<T>);

#[pallet::hooks]
Expand All @@ -96,7 +102,8 @@ pub mod pallet {
/// The current authority set.
#[pallet::storage]
#[pallet::getter(fn authorities)]
pub(super) type Authorities<T: Config> = StorageValue<_, Vec<T::AuthorityId>, ValueQuery>;
pub(super) type Authorities<T: Config> =
StorageValue<_, BoundedVec<T::AuthorityId, T::MaxAuthorities>, ValueQuery>;

/// The current slot of this block.
///
Expand All @@ -113,7 +120,7 @@ pub mod pallet {
#[cfg(feature = "std")]
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
Self { authorities: Vec::new() }
Self { authorities: Vec::<T::AuthorityId>::new() }
}
}

Expand All @@ -126,18 +133,31 @@ pub mod pallet {
}

impl<T: Config> Pallet<T> {
fn to_bounded_vec(
authorities: Vec<T::AuthorityId>,
) -> BoundedVec<T::AuthorityId, T::MaxAuthorities> {
let bounded_authorities =
BoundedVec::<T::AuthorityId, T::MaxAuthorities>::try_from(authorities);
assert!(
bounded_authorities.is_ok(),
"More than the maximum number of authorities provided"
);
georgesdib marked this conversation as resolved.
Show resolved Hide resolved
bounded_authorities.unwrap()
}

fn change_authorities(new: Vec<T::AuthorityId>) {
<Authorities<T>>::put(&new);
<Authorities<T>>::put(&Self::to_bounded_vec(new.clone()));

let log: DigestItem<T::Hash> =
DigestItem::Consensus(AURA_ENGINE_ID, ConsensusLog::AuthoritiesChange(new).encode());
<frame_system::Pallet<T>>::deposit_log(log.into());
}

fn initialize_authorities(authorities: &[T::AuthorityId]) {
fn initialize_authorities(authorities: &Vec<T::AuthorityId>) {
if !authorities.is_empty() {
assert!(<Authorities<T>>::get().is_empty(), "Authorities are already initialized!");
<Authorities<T>>::put(authorities);
let bounded_authorities = Self::to_bounded_vec((*authorities).clone());
<Authorities<T>>::put(bounded_authorities);
}
}

Expand Down Expand Up @@ -185,7 +205,7 @@ impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
if changed {
let next_authorities = validators.map(|(_, k)| k).collect::<Vec<_>>();
let last_authorities = Self::authorities();
if next_authorities != last_authorities {
if next_authorities != last_authorities.into_inner() {
Self::change_authorities(next_authorities);
}
}
Expand Down
2 changes: 2 additions & 0 deletions frame/aura/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ parameter_types! {
pub BlockWeights: frame_system::limits::BlockWeights =
frame_system::limits::BlockWeights::simple_max(1024);
pub const MinimumPeriod: u64 = 1;
pub const MaxAuthorities: u32 = 100;
}

impl frame_system::Config for Test {
Expand Down Expand Up @@ -85,6 +86,7 @@ impl pallet_timestamp::Config for Test {

impl pallet_aura::Config for Test {
type AuthorityId = AuthorityId;
type MaxAuthorities = MaxAuthorities;
}

pub fn new_test_ext(authorities: Vec<u64>) -> sp_io::TestExternalities {
Expand Down
56 changes: 38 additions & 18 deletions frame/authority-discovery/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@
// Ensure we're `no_std` when compiling for Wasm.
#![cfg_attr(not(feature = "std"), no_std)]

use frame_support::traits::OneSessionHandler;
use frame_support::{traits::OneSessionHandler, BoundedVec};
use sp_authority_discovery::AuthorityId;
use sp_std::prelude::*;

use core::convert::TryFrom;

pub use pallet::*;

#[frame_support::pallet]
Expand All @@ -36,21 +38,27 @@ pub mod pallet {

#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
#[pallet::generate_storage_info]
pub struct Pallet<T>(_);

#[pallet::config]
/// The pallet's config trait.
pub trait Config: frame_system::Config + pallet_session::Config {}
pub trait Config: frame_system::Config + pallet_session::Config {
/// The maximum number of authorities that can be added.
type MaxAuthorities: Get<u32>;
}

#[pallet::storage]
#[pallet::getter(fn keys)]
/// Keys of the current authority set.
pub(super) type Keys<T: Config> = StorageValue<_, Vec<AuthorityId>, ValueQuery>;
pub(super) type Keys<T: Config> =
StorageValue<_, BoundedVec<AuthorityId, T::MaxAuthorities>, ValueQuery>;

#[pallet::storage]
#[pallet::getter(fn next_keys)]
/// Keys of the next authority set.
pub(super) type NextKeys<T: Config> = StorageValue<_, Vec<AuthorityId>, ValueQuery>;
pub(super) type NextKeys<T: Config> =
StorageValue<_, BoundedVec<AuthorityId, T::MaxAuthorities>, ValueQuery>;

#[pallet::genesis_config]
pub struct GenesisConfig {
Expand All @@ -75,33 +83,40 @@ impl<T: Config> Pallet<T> {
/// Retrieve authority identifiers of the current and next authority set
/// sorted and deduplicated.
pub fn authorities() -> Vec<AuthorityId> {
let mut keys = Keys::<T>::get();
let next = NextKeys::<T>::get();
let mut keys = Keys::<T>::get().to_vec();
let next = NextKeys::<T>::get().to_vec();

keys.extend(next);
keys.sort();
keys.dedup();

keys
keys.to_vec()
}

/// Retrieve authority identifiers of the current authority set in the original order.
pub fn current_authorities() -> Vec<AuthorityId> {
pub fn current_authorities() -> BoundedVec<AuthorityId, T::MaxAuthorities> {
Keys::<T>::get()
}

/// Retrieve authority identifiers of the next authority set in the original order.
pub fn next_authorities() -> Vec<AuthorityId> {
pub fn next_authorities() -> BoundedVec<AuthorityId, T::MaxAuthorities> {
NextKeys::<T>::get()
}

fn initialize_keys(keys: &[AuthorityId]) {
fn initialize_keys(keys: &Vec<AuthorityId>) {
if !keys.is_empty() {
assert!(Keys::<T>::get().is_empty(), "Keys are already initialized!");
Keys::<T>::put(keys);
NextKeys::<T>::put(keys);
let bounded_keys = Self::to_bounded_vec((*keys).clone());
Keys::<T>::put(bounded_keys.clone());
gui1117 marked this conversation as resolved.
Show resolved Hide resolved
NextKeys::<T>::put(bounded_keys);
}
}

fn to_bounded_vec(keys: Vec<AuthorityId>) -> BoundedVec<AuthorityId, T::MaxAuthorities> {
let bounded_keys = BoundedVec::<AuthorityId, T::MaxAuthorities>::try_from(keys);
assert!(bounded_keys.is_ok(), "More than the maximum number of authorities provided");
georgesdib marked this conversation as resolved.
Show resolved Hide resolved
bounded_keys.unwrap()
}
}

impl<T: Config> sp_runtime::BoundToRuntimeAppPublic for Pallet<T> {
Expand All @@ -124,10 +139,12 @@ impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
{
// Remember who the authorities are for the new and next session.
if changed {
let keys = validators.map(|x| x.1);
Keys::<T>::put(keys.collect::<Vec<_>>());
let next_keys = queued_validators.map(|x| x.1);
NextKeys::<T>::put(next_keys.collect::<Vec<_>>());
let keys = validators.map(|x| x.1).collect::<Vec<_>>();
let bounded_keys = Self::to_bounded_vec(keys);
Keys::<T>::put(bounded_keys);
let next_keys = queued_validators.map(|x| x.1).collect::<Vec<_>>();
let next_bounded_keys = Self::to_bounded_vec(next_keys);
NextKeys::<T>::put(next_bounded_keys);
}
}

Expand Down Expand Up @@ -166,10 +183,13 @@ mod tests {
}
);

impl Config for Test {}

parameter_types! {
pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(33);
pub const MaxAuthorities: u32 = 100;
}

impl Config for Test {
type MaxAuthorities = MaxAuthorities;
}

impl pallet_session::Config for Test {
Expand Down
1 change: 1 addition & 0 deletions primitives/application-crypto/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@ macro_rules! app_crypto_public_not_full_crypto {
$crate::codec::Encode,
$crate::codec::Decode,
$crate::RuntimeDebug,
$crate::codec::MaxEncodedLen,
)]
pub struct Public($public);
}
Expand Down
4 changes: 2 additions & 2 deletions primitives/consensus/slots/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@

#![cfg_attr(not(feature = "std"), no_std)]

use codec::{Decode, Encode};
use codec::{Decode, Encode, MaxEncodedLen};

/// Unit type wrapper that represents a slot.
#[derive(Debug, Encode, Decode, Eq, Clone, Copy, Default, Ord)]
#[derive(Debug, Encode, MaxEncodedLen, Decode, Eq, Clone, Copy, Default, Ord)]
pub struct Slot(u64);

impl core::ops::Deref for Slot {
Expand Down