Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
simplify and unificate authorities api
  • Loading branch information
kostekIV committed Jan 17, 2023
commit ed2448da70593c9e74e131ae12978d070dcc4d10
37 changes: 22 additions & 15 deletions bin/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ use sp_runtime::{
OpaqueKeys, Verify,
},
transaction_validity::{TransactionSource, TransactionValidity},
ApplyExtrinsicResult, FixedU128, MultiSignature, RuntimeAppPublic,
ApplyExtrinsicResult, FixedU128, MultiSignature,
};
pub use sp_runtime::{FixedPointNumber, Perbill, Permill};
use sp_staking::EraIndex;
Expand Down Expand Up @@ -104,7 +104,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("aleph-node"),
impl_name: create_runtime_str!("aleph-node"),
authoring_version: 1,
spec_version: 45,
spec_version: 46,
impl_version: 1,
apis: RUNTIME_API_VERSIONS,
transaction_version: 14,
Expand Down Expand Up @@ -220,7 +220,7 @@ impl pallet_authorship::Config for Runtime {
type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Aura>;
type UncleGenerations = UncleGenerations;
type FilterUncle = ();
type EventHandler = (Elections,);
type EventHandler = (Elections, );
}

parameter_types! {
Expand All @@ -247,7 +247,7 @@ type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;
pub struct EverythingToTheTreasury;

impl OnUnbalanced<NegativeImbalance> for EverythingToTheTreasury {
fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {
fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item=NegativeImbalance>) {
if let Some(fees) = fees_then_tips.next() {
Treasury::on_unbalanced(fees);
if let Some(tips) = fees_then_tips.next() {
Expand Down Expand Up @@ -372,13 +372,17 @@ parameter_types! {
}

use sp_runtime::traits::Convert;

pub struct BalanceToU256;

impl Convert<Balance, sp_core::U256> for BalanceToU256 {
fn convert(balance: Balance) -> sp_core::U256 {
sp_core::U256::from(balance)
}
}

pub struct U256ToBalance;

impl Convert<sp_core::U256, Balance> for U256ToBalance {
fn convert(n: sp_core::U256) -> Balance {
n.try_into().unwrap_or(Balance::max_value())
Expand Down Expand Up @@ -423,6 +427,7 @@ impl pallet_staking::EraPayout<Balance> for UniformEraPayout {
type SubstrateStakingWeights = pallet_staking::weights::SubstrateWeight<Runtime>;

pub struct PayoutStakersDecreasedWeightInfo;

impl pallet_staking::WeightInfo for PayoutStakersDecreasedWeightInfo {
// To make possible to change nominators per validator we need to decrease weight for payout_stakers
fn payout_stakers_alive_staked(n: u32) -> Weight {
Expand Down Expand Up @@ -493,6 +498,7 @@ impl pallet_staking::WeightInfo for PayoutStakersDecreasedWeightInfo {
}

pub struct StakingBenchmarkingConfig;

impl pallet_staking::BenchmarkingConfig for StakingBenchmarkingConfig {
type MaxValidators = ConstU32<1000>;
type MaxNominators = ConstU32<1000>;
Expand Down Expand Up @@ -542,8 +548,8 @@ impl pallet_timestamp::Config for Runtime {
}

impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime
where
RuntimeCall: From<C>,
where
RuntimeCall: From<C>,
{
type Extrinsic = UncheckedExtrinsic;
type OverarchingCall = RuntimeCall;
Expand Down Expand Up @@ -609,6 +615,7 @@ parameter_types! {
}

pub struct TreasuryGovernance;

impl SortedMembers<AccountId> for TreasuryGovernance {
fn sorted_members() -> Vec<AccountId> {
pallet_sudo::Pallet::<Runtime>::key().into_iter().collect()
Expand Down Expand Up @@ -757,7 +764,7 @@ pub type SignedExtra = (
);
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic =
generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
/// Extrinsic type that has already been checked.
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra>;
/// Executive: handles dispatch to the various modules.
Expand Down Expand Up @@ -884,21 +891,21 @@ impl_runtime_apis! {
}

fn next_session_authorities() -> Result<Vec<AlephId>, AlephApiError> {
Session::queued_keys()
.iter()
.map(|(_, key)| key.get(AlephId::ID).ok_or(AlephApiError::DecodeKey))
.collect::<Result<Vec<AlephId>, AlephApiError>>()
let next_authorities = Aleph::next_authorities();
if next_authorities.is_empty() {
return Err(AlephApiError::MissingAuthoritiesForNextSession)
}

Ok(next_authorities)
}

fn authority_data() -> SessionAuthorityData {
SessionAuthorityData::new(Aleph::authorities(), Aleph::emergency_finalizer())
}

fn next_session_authority_data() -> Result<SessionAuthorityData, AlephApiError> {
Ok(SessionAuthorityData::new(Session::queued_keys()
.iter()
.map(|(_, key)| key.get(AlephId::ID).ok_or(AlephApiError::DecodeKey))
.collect::<Result<Vec<AlephId>, AlephApiError>>()?,
Ok(SessionAuthorityData::new(
Self::next_session_authorities()?,
Aleph::queued_emergency_finalizer(),
))
}
Expand Down
27 changes: 22 additions & 5 deletions pallets/aleph/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,10 @@ pub mod pallet {
#[pallet::getter(fn authorities)]
pub(super) type Authorities<T: Config> = StorageValue<_, Vec<T::AuthorityId>, ValueQuery>;

#[pallet::storage]
#[pallet::getter(fn next_authorities)]
pub(super) type NextAuthorities<T: Config> = StorageValue<_, Vec<T::AuthorityId>, ValueQuery>;

#[pallet::storage]
#[pallet::getter(fn emergency_finalizer)]
pub(super) type EmergencyFinalizer<T: Config> = StorageValue<_, T::AuthorityId, OptionQuery>;
Expand All @@ -134,18 +138,29 @@ pub mod pallet {
StorageValue<_, VersionChange, OptionQuery>;

impl<T: Config> Pallet<T> {
pub(crate) fn initialize_authorities(authorities: &[T::AuthorityId]) {
pub(crate) fn initialize_authorities(authorities: &[T::AuthorityId], next_authorities: &[T::AuthorityId]) {
if !authorities.is_empty() {
assert!(
<Authorities<T>>::get().is_empty(),
"Authorities are already initialized!"
);
<Authorities<T>>::put(authorities);
}
if !next_authorities.is_empty() {
assert!(
<NextAuthorities<T>>::get().is_empty(),
"NextAuthorities are already initialized!"
);
<NextAuthorities<T>>::put(next_authorities);
}
}

pub(crate) fn update_authorities(authorities: &[T::AuthorityId]) {
pub(crate) fn update_authorities(
authorities: &[T::AuthorityId],
next_authorities: &[T::AuthorityId],
) {
<Authorities<T>>::put(authorities);
<NextAuthorities<T>>::put(next_authorities);
}

pub(crate) fn update_emergency_finalizer() {
Expand Down Expand Up @@ -262,18 +277,20 @@ pub mod pallet {
T::AccountId: 'a,
{
let (_, authorities): (Vec<_>, Vec<_>) = validators.unzip();
Self::initialize_authorities(authorities.as_slice());
// it is guaranteed that the first validator set will also be used in the next session
Self::initialize_authorities(authorities.as_slice(), authorities.as_slice());
}

fn on_new_session<'a, I: 'a>(changed: bool, validators: I, _queued_validators: I)
fn on_new_session<'a, I: 'a>(changed: bool, validators: I, queued_validators: I)
where
I: Iterator<Item = (&'a T::AccountId, T::AuthorityId)>,
T::AccountId: 'a,
{
Self::update_emergency_finalizer();
if changed {
let (_, authorities): (Vec<_>, Vec<_>) = validators.unzip();
Self::update_authorities(authorities.as_slice());
let (_, next_authorities): (Vec<_>, Vec<_>) = queued_validators.unzip();
Self::update_authorities(authorities.as_slice(), next_authorities.as_slice());
}
}

Expand Down
2 changes: 1 addition & 1 deletion primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ impl<AccountId> Default for EraValidators<AccountId> {

#[derive(Encode, Decode, PartialEq, Eq, Debug)]
pub enum ApiError {
DecodeKey,
MissingAuthoritiesForNextSession,
}

/// All the data needed to verify block finalization justifications.
Expand Down