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

Commit

Permalink
Incorporate the new electing/electable naming into the code (#10956)
Browse files Browse the repository at this point in the history
* Incorporate the new electing/electable naming into the code

* Update frame/election-provider-support/src/lib.rs

Co-authored-by: Zeke Mostov <[email protected]>

* Update frame/election-provider-support/src/lib.rs

Co-authored-by: Zeke Mostov <[email protected]>

* Some additional changes

* fmt

* update codec

* revert lock file to master

* fix doc test

Co-authored-by: Zeke Mostov <[email protected]>
  • Loading branch information
kianenigma and emostov authored Mar 19, 2022
1 parent 4c9bf00 commit 8cbda80
Show file tree
Hide file tree
Showing 9 changed files with 82 additions and 70 deletions.
16 changes: 7 additions & 9 deletions bin/node/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,12 @@ use frame_system::{
pub use node_primitives::{AccountId, Signature};
use node_primitives::{AccountIndex, Balance, BlockNumber, Hash, Index, Moment};
use pallet_contracts::weights::WeightInfo;
use pallet_election_provider_multi_phase::SolutionAccuracyOf;
use pallet_grandpa::{
fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList,
};
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
use pallet_session::historical as pallet_session_historical;
use pallet_session::historical::{self as pallet_session_historical};
pub use pallet_transaction_payment::{CurrencyAdapter, Multiplier, TargetedFeeAdjustment};
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
use sp_api::impl_runtime_apis;
Expand Down Expand Up @@ -668,20 +669,17 @@ impl pallet_election_provider_multi_phase::Config for Runtime {
type DataProvider = Staking;
type Solution = NposSolution16;
type Fallback = pallet_election_provider_multi_phase::NoFallback<Self>;
type GovernanceFallback =
frame_election_provider_support::onchain::OnChainSequentialPhragmen<Self>;
type GovernanceFallback = onchain::OnChainSequentialPhragmen<Self>;
type Solver = frame_election_provider_support::SequentialPhragmen<
AccountId,
pallet_election_provider_multi_phase::SolutionAccuracyOf<Self>,
SolutionAccuracyOf<Self>,
OffchainRandomBalancing,
>;
type WeightInfo = pallet_election_provider_multi_phase::weights::SubstrateWeight<Self>;
type ForceOrigin = EnsureRootOrHalfCouncil;
type MaxElectableTargets = ConstU16<{ u16::MAX }>;
type MaxElectingVoters = ConstU32<10_000>;
type BenchmarkingConfig = ElectionProviderBenchmarkConfig;
// BagsList allows a practically unbounded count of nominators to participate in NPoS elections.
// To ensure we respect memory limits when using the BagsList this must be set to a number of
// voters we know can fit into a single vec allocation.
type VoterSnapshotPerBlock = ConstU32<10_000>;
type WeightInfo = pallet_election_provider_multi_phase::weights::SubstrateWeight<Self>;
}

parameter_types! {
Expand Down
3 changes: 2 additions & 1 deletion frame/bags-list/remote-tests/src/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ pub async fn execute<Runtime: crate::RuntimeT, Block: BlockT + DeserializeOwned>
);

let voters =
<pallet_staking::Pallet<Runtime> as ElectionDataProvider>::voters(voter_limit).unwrap();
<pallet_staking::Pallet<Runtime> as ElectionDataProvider>::electing_voters(voter_limit)
.unwrap();

let mut voters_nominator_only = voters
.iter()
Expand Down
4 changes: 2 additions & 2 deletions frame/election-provider-multi-phase/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,8 +260,8 @@ frame_benchmarking::benchmarks! {

// we don't directly need the data-provider to be populated, but it is just easy to use it.
set_up_data_provider::<T>(v, t);
let targets = T::DataProvider::targets(None)?;
let voters = T::DataProvider::voters(None)?;
let targets = T::DataProvider::electable_targets(None)?;
let voters = T::DataProvider::electing_voters(None)?;
let desired_targets = T::DataProvider::desired_targets()?;
assert!(<MultiPhase<T>>::snapshot().is_none());
}: {
Expand Down
37 changes: 18 additions & 19 deletions frame/election-provider-multi-phase/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
//! Upon the end of the signed phase, the solutions are examined from best to worse (i.e. `pop()`ed
//! until drained). Each solution undergoes an expensive `Pallet::feasibility_check`, which ensures
//! the score claimed by this score was correct, and it is valid based on the election data (i.e.
//! votes and candidates). At each step, if the current best solution passes the feasibility check,
//! votes and targets). At each step, if the current best solution passes the feasibility check,
//! it is considered to be the best one. The sender of the origin is rewarded, and the rest of the
//! queued solutions get their deposit back and are discarded, without being checked.
//!
Expand Down Expand Up @@ -249,7 +249,6 @@ use sp_npos_elections::{
assignment_ratio_to_staked_normalized, ElectionScore, EvaluateSupport, Supports, VoteWeight,
};
use sp_runtime::{
traits::Bounded,
transaction_validity::{
InvalidTransaction, TransactionPriority, TransactionSource, TransactionValidity,
TransactionValidityError, ValidTransaction,
Expand Down Expand Up @@ -643,14 +642,15 @@ pub mod pallet {
#[pallet::constant]
type SignedDepositWeight: Get<BalanceOf<Self>>;

/// The maximum number of voters to put in the snapshot. At the moment, snapshots are only
/// over a single block, but once multi-block elections are introduced they will take place
/// over multiple blocks.
///
/// Also, note the data type: If the voters are represented by a `u32` in `type
/// CompactSolution`, the same `u32` is used here to ensure bounds are respected.
/// The maximum number of electing voters to put in the snapshot. At the moment, snapshots
/// are only over a single block, but once multi-block elections are introduced they will
/// take place over multiple blocks.
#[pallet::constant]
type MaxElectingVoters: Get<SolutionVoterIndexOf<Self>>;

/// The maximum number of electable targets to put in the snapshot.
#[pallet::constant]
type VoterSnapshotPerBlock: Get<SolutionVoterIndexOf<Self>>;
type MaxElectableTargets: Get<SolutionTargetIndexOf<Self>>;

/// Handler for the slashed deposits.
type SlashHandler: OnUnbalanced<NegativeImbalanceOf<Self>>;
Expand Down Expand Up @@ -817,7 +817,7 @@ pub mod pallet {
fn integrity_test() {
use sp_std::mem::size_of;
// The index type of both voters and targets need to be smaller than that of usize (very
// unlikely to be the case, but anyhow).
// unlikely to be the case, but anyhow)..
assert!(size_of::<SolutionVoterIndexOf<T>>() <= size_of::<usize>());
assert!(size_of::<SolutionTargetIndexOf<T>>() <= size_of::<usize>());

Expand Down Expand Up @@ -1338,14 +1338,13 @@ impl<T: Config> Pallet<T> {
/// Extracted for easier weight calculation.
fn create_snapshot_external(
) -> Result<(Vec<T::AccountId>, Vec<VoterOf<T>>, u32), ElectionError<T>> {
let target_limit = <SolutionTargetIndexOf<T>>::max_value().saturated_into::<usize>();
// for now we have just a single block snapshot.
let voter_limit = T::VoterSnapshotPerBlock::get().saturated_into::<usize>();

let targets =
T::DataProvider::targets(Some(target_limit)).map_err(ElectionError::DataProvider)?;
let voters =
T::DataProvider::voters(Some(voter_limit)).map_err(ElectionError::DataProvider)?;
let target_limit = T::MaxElectableTargets::get().saturated_into::<usize>();
let voter_limit = T::MaxElectingVoters::get().saturated_into::<usize>();

let targets = T::DataProvider::electable_targets(Some(target_limit))
.map_err(ElectionError::DataProvider)?;
let voters = T::DataProvider::electing_voters(Some(voter_limit))
.map_err(ElectionError::DataProvider)?;
let mut desired_targets =
T::DataProvider::desired_targets().map_err(ElectionError::DataProvider)?;

Expand Down Expand Up @@ -2090,7 +2089,7 @@ mod tests {
// we have 8 voters in total.
assert_eq!(crate::mock::Voters::get().len(), 8);
// but we want to take 2.
crate::mock::VoterSnapshotPerBlock::set(2);
crate::mock::MaxElectingVoters::set(2);

// Signed phase opens just fine.
roll_to(15);
Expand Down
13 changes: 9 additions & 4 deletions frame/election-provider-multi-phase/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,8 @@ parameter_types! {
pub static MinerMaxWeight: Weight = BlockWeights::get().max_block;
pub static MinerMaxLength: u32 = 256;
pub static MockWeightInfo: bool = false;
pub static VoterSnapshotPerBlock: VoterIndex = u32::max_value();
pub static MaxElectingVoters: VoterIndex = u32::max_value();
pub static MaxElectableTargets: TargetIndex = TargetIndex::max_value();

pub static EpochLength: u64 = 30;
pub static OnChianFallback: bool = true;
Expand Down Expand Up @@ -413,7 +414,8 @@ impl crate::Config for Runtime {
type GovernanceFallback = NoFallback<Self>;
type ForceOrigin = frame_system::EnsureRoot<AccountId>;
type Solution = TestNposSolution;
type VoterSnapshotPerBlock = VoterSnapshotPerBlock;
type MaxElectingVoters = MaxElectingVoters;
type MaxElectableTargets = MaxElectableTargets;
type Solver = SequentialPhragmen<AccountId, SolutionAccuracyOf<Runtime>, Balancing>;
}

Expand All @@ -439,7 +441,8 @@ impl ElectionDataProvider for StakingMock {
type AccountId = AccountId;
type BlockNumber = u64;
type MaxVotesPerVoter = MaxNominations;
fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<AccountId>> {

fn electable_targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<AccountId>> {
let targets = Targets::get();

if maybe_max_len.map_or(false, |max_len| targets.len() > max_len) {
Expand All @@ -449,7 +452,9 @@ impl ElectionDataProvider for StakingMock {
Ok(targets)
}

fn voters(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<VoterOf<Runtime>>> {
fn electing_voters(
maybe_max_len: Option<usize>,
) -> data_provider::Result<Vec<VoterOf<Runtime>>> {
let mut voters = Voters::get();
if let Some(max_len) = maybe_max_len {
voters.truncate(max_len)
Expand Down
17 changes: 10 additions & 7 deletions frame/election-provider-support/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,12 +107,12 @@
//! fn desired_targets() -> data_provider::Result<u32> {
//! Ok(1)
//! }
//! fn voters(maybe_max_len: Option<usize>)
//! fn electing_voters(maybe_max_len: Option<usize>)
//! -> data_provider::Result<Vec<VoterOf<Self>>>
//! {
//! Ok(Default::default())
//! }
//! fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<AccountId>> {
//! fn electable_targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<AccountId>> {
//! Ok(vec![10, 20, 30])
//! }
//! fn next_election_prediction(now: BlockNumber) -> BlockNumber {
Expand All @@ -138,7 +138,7 @@
//! type DataProvider = T::DataProvider;
//!
//! fn elect() -> Result<Supports<AccountId>, Self::Error> {
//! Self::DataProvider::targets(None)
//! Self::DataProvider::electable_targets(None)
//! .map_err(|_| "failed to elect")
//! .map(|t| vec![(t[0], Support::default())])
//! }
Expand Down Expand Up @@ -265,16 +265,19 @@ pub trait ElectionDataProvider {
/// Maximum number of votes per voter that this data provider is providing.
type MaxVotesPerVoter: Get<u32>;

/// All possible targets for the election, i.e. the candidates.
/// All possible targets for the election, i.e. the targets that could become elected, thus
/// "electable".
///
/// If `maybe_max_len` is `Some(v)` then the resulting vector MUST NOT be longer than `v` items
/// long.
///
/// This should be implemented as a self-weighing function. The implementor should register its
/// appropriate weight at the end of execution with the system pallet directly.
fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<Self::AccountId>>;
fn electable_targets(
maybe_max_len: Option<usize>,
) -> data_provider::Result<Vec<Self::AccountId>>;

/// All possible voters for the election.
/// All the voters that participate in the election, thus "electing".
///
/// Note that if a notion of self-vote exists, it should be represented here.
///
Expand All @@ -283,7 +286,7 @@ pub trait ElectionDataProvider {
///
/// This should be implemented as a self-weighing function. The implementor should register its
/// appropriate weight at the end of execution with the system pallet directly.
fn voters(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<VoterOf<Self>>>;
fn electing_voters(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<VoterOf<Self>>>;

/// The number of targets to elect.
///
Expand Down
11 changes: 6 additions & 5 deletions frame/election-provider-support/src/onchain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,11 @@ impl<T: Config> OnChainSequentialPhragmen<T> {
maybe_max_voters: Option<usize>,
maybe_max_targets: Option<usize>,
) -> Result<Supports<T::AccountId>, Error> {
let voters = <Self as ElectionProvider>::DataProvider::voters(maybe_max_voters)
.map_err(Error::DataProvider)?;
let targets = <Self as ElectionProvider>::DataProvider::targets(maybe_max_targets)
let voters = <Self as ElectionProvider>::DataProvider::electing_voters(maybe_max_voters)
.map_err(Error::DataProvider)?;
let targets =
<Self as ElectionProvider>::DataProvider::electable_targets(maybe_max_targets)
.map_err(Error::DataProvider)?;
let desired_targets = <Self as ElectionProvider>::DataProvider::desired_targets()
.map_err(Error::DataProvider)?;

Expand Down Expand Up @@ -197,15 +198,15 @@ mod tests {
type AccountId = AccountId;
type BlockNumber = BlockNumber;
type MaxVotesPerVoter = ConstU32<2>;
fn voters(_: Option<usize>) -> data_provider::Result<Vec<VoterOf<Self>>> {
fn electing_voters(_: Option<usize>) -> data_provider::Result<Vec<VoterOf<Self>>> {
Ok(vec![
(1, 10, bounded_vec![10, 20]),
(2, 20, bounded_vec![30, 20]),
(3, 30, bounded_vec![10, 30]),
])
}

fn targets(_: Option<usize>) -> data_provider::Result<Vec<AccountId>> {
fn electable_targets(_: Option<usize>) -> data_provider::Result<Vec<AccountId>> {
Ok(vec![10, 20, 30])
}

Expand Down
4 changes: 2 additions & 2 deletions frame/staking/src/pallet/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -860,15 +860,15 @@ impl<T: Config> ElectionDataProvider for Pallet<T> {
Ok(Self::validator_count())
}

fn voters(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<VoterOf<Self>>> {
fn electing_voters(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<VoterOf<Self>>> {
// This can never fail -- if `maybe_max_len` is `Some(_)` we handle it.
let voters = Self::get_npos_voters(maybe_max_len);
debug_assert!(maybe_max_len.map_or(true, |max| voters.len() <= max));

Ok(voters)
}

fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<T::AccountId>> {
fn electable_targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<T::AccountId>> {
let target_count = Validators::<T>::count();

// We can't handle this case yet -- return an error.
Expand Down
Loading

0 comments on commit 8cbda80

Please sign in to comment.