mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-07-07 01:27:22 +00:00
669972a171
* remove extra whitespace Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> * only emit rebag event on success * add doc explaining the term voter * revamp/simplify rebag test * ensure genesis accounts are placed into the correct nodes/bags * bond_extra implicitly rebags * types at top; doc public type * start sketching out adjustable thresholds * add integrity test for voter bag threshold requirements * get rid of BagIdx This reorganizes bag storage such that bags are always referred to by their upper threshold. This in turn means that adding and removing bags is cheaper; you only need to migrate certain voters, not all of them. * implement migration logic for when the threshold list changes * start sketching out threshold proc macros * further refine macro signatures * WIP: implement make_ratio macro * start rethinking the process of producing threshold lists The macro approach seems to be a non-starter; that only really works if we're throwing around numeric literals everywhere, and that's just not nice in this case. Instead, let's write helper functions and make it really easy to generate the tables in separate, permanent files, which humans can then edit. * write helper functions to emit voter bags module * WIP: demo generating voter bags for a realistic runtime This isn't yet done, becuase it seems to take a Very Long Time to run, and it really shouldn't. Need to look into that. Still, it's a lot closer than it was this morning. * rm unnecessary arg_enum * fix voter bags math Turns out that when you're working in exponential space, you need to divide, not subtract, in order to keep the math working properly. Also neaten up the output a little bit to make it easier to read. * add computed voter bags thresholds to node * fixup some docs * iter from large bags to small, fulfuilling the contract * make tests compile * add VoterBagThresholds to some configs * ensure that iteration covers all voters even with implied final bag * use sp_std::boxed::Box; * fix unused import * add some more voter bags tests * file_header.txt * integrity test to ensure min bag exceeds existential weight * add more debug assertions about node list length * rm unused imports * Kian enters * Update frame/election-provider-support/src/onchain.rs Co-authored-by: Zeke Mostov <32168567+emostov@users.noreply.github.com> * Suggestions for #9081 (Store voters in unsorted bags) (#9328) * Add some debug asserts to node::get and remove_node * Improve the debug asserts in remove_node * improve debug asserts * Space * Remove bad assertions * Tests: WIP take_works * Take test * Doc comment * Apply suggestions from code review Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> * Test storage is cleaned up; * formatting * Switch to simpler thresholds * Update the storage cleanup test * Remove hardcoded values from benchmark to make it more robust * Fix tests to acces bags properly * Sanity check WIP; tests failing * Update sanity checks to be more correct * Improve storage cleanup tests * WIP remote_ext_tests * Some notes on next steps * Remove some stuff that was for remote-ext tests * Some more cleanup to reduce diff * More :clean: * Mo cleanin * small fix * A lot of changes from kian Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> Co-authored-by: kianenigma <kian@parity.io> * merge fallout * Run cargo +nightly fmt * Fix a bunch of stuff, remove not needed runtime arg of make-bags * add logs * Glue the new staking bags to the election snapshot (#9415) * Glue the new staking bags to the election snapshot * add CheckedRem (#9412) * add CheckedRem * fix * Run fmt * Test comment Co-authored-by: Xiliang Chen <xlchen1291@gmail.com> Co-authored-by: emostov <32168567+emostov@users.noreply.github.com> * Update node runtime with VoterSnapshotPerBlock * Unit test for pallet-staking unsorted bags feature (targets #9081) (#9422) * impl notional_bag_for_works * Add tests: insert_as_works & insert_works * Impl test: remove_works * Trivial cleaning * Add test: update_position_for_works * Write out edge case; probably can delete later * Add test: bags::get_works * Add test: remove_node_happy_path_works * Add test: remove_node_bad_paths_documented * WIP: voting_data_works * done * Improve test voting_data_works * Add comment * Fill out test basic_setup_works * Update: iteration_is_semi_sorted * Improve remove_works * Update update_position_for_works; create set_ledger_and_free_balance * Improve get_works * Improve storage clean up checks in remove test * Test: impl rebag_works + insert_and_remove_works * forgot file - Test: impl rebag_works + insert_and_remove_works * Small tweak * Update voter_bags test to reflect unused bags are removed * Unbond & Rebond: do_rebag * Prevent infinite loops with duplicate tail insert * Check iter.count on voter list in pre-migrate * undo strang fmt comment stuff * Add in todo Co-authored-by: kianenigma <kian@parity.io> * Try prepare for master merge * Reduce diff * Add comment for test to add * Add in code TODO for update_position efficiency updates * Initial impl compiles * impl StakingVoterListStub * Sample impl<T: Config> VoterListProvider<T> for VoterList<T> * impl VoterListProvider for voter-bags * WIP integrate pallet-voter-bags to staking mock * the trait `pallet_staking::pallet::pallet::Config` is not implemented for `mock::Test` * random * pushing my stuff * Mock working * WIP voter list tests * Add bag insert, remove tests * Add test for bag insert and remove * Add remaining tests for VoterList * Add tests for node * Add rebag works * Add rebag extrinsic tests * Rename to bags-list and name the list .. list! * Rename VoterBagThresholds => BagThresholds * Add test count_works * Test on_update_works * test sanity check * a round of test fixes * push a lot of changes * my last changes * all bags-list test work; fmt * Beautify some tests * Doc comment for bags-list * Add insert warnings * Setup initial benchmark * Wire up WeightInfo * is_terminal wip; everything broken! * Is terminal working * add TODOs for remove_node * clean up remoe_node * Fix all staking tests * retire VoterBagFor * commit * bring in stashed changes * save * bench pipeline works now, but I can't run stuff * sabe * benchmarks now run, but we have a failure * WIP: Wire up make_bags * bags-thresholds compiles * Fix most build issues * This will fix all the tests * move bag thresholds to bags-list * Move bag-thresholds bin to within pallet-bags * Remove some unnescary TODOs * Impl tets wrong_rebag_is_noop * assert remove is a noop with bad data * Assert integrity test panics * Return an error when inserting duplicates * Update to handle error in staking pallet when inserting to list * Test contains and on_insert error * Test re-nominate does not mess up list or count * Everything builds and works, only the benchmark... * fuck yeah benchmarks * more cleanup, more hardening. * use the bags list again * fix benhc * Some questions and changs for List::migration * Fix migration removed_bags and new_bags usage * Some trivial aesthetic changes * Some more trivial changes * tiny changes/ * mega rename * fix all tests and ci build * nit * Test and fix migration * nit * fmt * cargo run --quiet --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_staking --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/staking/src/weights.rs --template=./.maintain/frame-weight-template.hbs * fmt * remove unused * make a few things pub * make node also pub.. for remote-ext test * Fix all tests again * Force bag changes in relevant benchmarks (targets #9507) (#9529) * force rebag for unbond, rebond, and bond_extra * nit * Improve utils * fmt * nits * Move generate_bags to its own pallet * Get runtime-benchmarks feature setup with prepare_on_update_benchmark * Withdraw unbonded kill working * Nominate bench working * some cleanup * WIP * update to check head pre & post conditions * Add some post condition verification stuff for on_remove * Update nominate * fmt * Improvements * Fix build * fix build with polkadot companion * Update frame/bags-list/src/list/tests.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> * move generate-bag from frame to utils * wip * refactor WIP * WIP save * Refactor working * some variable renaming * WIP: prepare to remove head checks * Finish MvP refactor * Some cleanup * Soem more cleanup * save * fix a lot of stuff * Update client/db/src/bench.rs Co-authored-by: Shawn Tabrizi <shawntabrizi@gmail.com> * Apply suggestions from code review * Apply suggestions from code review * Fix some issues that came from trying to merge comments on github * some small changes * simplify it Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> Co-authored-by: kianenigma <kian@parity.io> Co-authored-by: Shawn Tabrizi <shawntabrizi@gmail.com> * Build works * Apply suggestions from code review Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com> * Apply suggestions from code review Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com> * Remove commented out debug assert * Remove some unused deps and some unused benchmarking stuff * Fix stakings ElectionDataProvider clear * cargo run --quiet --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_bags_list --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/bags-list/src/weights.rs --template=./.maintain/frame-weight-template.hbs * cargo run --quiet --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_bags_list --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/bags-list/src/weights.rs --template=./.maintain/frame-weight-template.hbs * cargo run --quiet --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_bags_list --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/bags-list/src/weights.rs --template=./.maintain/frame-weight-template.hbs * cargo run --quiet --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_bags_list --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/bags-list/src/weights.rs --template=./.maintain/frame-weight-template.hbs * Improving staking pallet-bags-list migration * fix build and some comments; * comment * Reduce visibility in bags list components * make node.bag_upper only accesible to benchmarks * Address some feedback; comments updates * use nominator map comment * fix vec capacity debug assert * Apply suggestions from code review Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com> * clarify VoterSnapshotPerBlock * Reduce diff on create_validators by wrapping with_seed * Some small improvements to staking benches * Soem comment updates * fix vec capacity debug assert ... for real this time * Reduce ListBags viz * cargo run --quiet --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_staking --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/staking/src/weights.rs --template=./.maintain/frame-weight-template.hbs * cargo run --quiet --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_staking --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/staking/src/weights.rs --template=./.maintain/frame-weight-template.hbs * Remove supports_eq_unordered & Support eq_unordered * Update utils/frame/generate-bags/src/lib.rs Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com> * Make total-issuance & minimium-balance CLI args; Dont use emptry ext * Improve docs for generate bags CLI args * Apply suggestions from code review Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> * Apply suggestions from code review Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> * Don't use default bags weight in node runtime * Feature gating sanity_check not working * Feature gate sanity check by creating duplicate fns * Fix line wrapping * Document VoteWeightProvider * Make bags ext-builder not a module * Apply suggestions from code review Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> * use pallet_bags_list instead of crate in mock * Make get_bags test helper fn live in List * use remove_from_storage_unchecked for node removal * Remove count of ids removed in remove_many * Add node sanity check, improve list sanity check * Do a list sanity check after on_update * List::migrate: clean up debug assert, exit early when no change in thresholds * Improve public doc comments for pallet_bags_list::list::List * Improve public doc comments for pallet_bags_list::list::List * Update generate bags docs * Fix grammar in bags-list benchmark * Add benchmark case for `rebag` extrinsic * Add count parameter to List::clear; WIP adding MaxEncodedLen to list' * MaxEncodeLen + generate_storage_info not working for Bag or Node * Get MaxEncodeLen derive to work * Try to correctly feature gate SortedListProvider::clear * Use u32::MAX, not u32::max_value * Get up to nominators_quota noms * SortedListProvider::clear takes an Option * Eplicitly ignore SortedListProvider return value * Fix doc comment * Update node-runtime voter snapshot per block * Add test get_max_len_voters_even_if_some_nominators_are_slashed * Add test only_iterates_max_2_times_nominators_quota * Fix generate bags cargo.toml * use sp_std vec * Remove v8 migration hooks from pallet-staking * Update npos trait * Try respect line width * cargo run --quiet --release --features=runtime-benchmarks --manifest-path=bin/node/cli/Cargo.toml -- benchmark --chain=dev --steps=50 --repeat=20 --pallet=pallet_bags_list --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --output=./frame/bags-list/src/weights.rs --template=./.maintain/frame-weight-template.hbs * Update frame/bags-list/src/benchmarks.rs * Unwrap try-runtime error; remove sortedlistprovider pre upgrade len check * trigger ci * restore * trigger ci * restore * trigger ci * revert * trigger ci * revert Co-authored-by: Peter Goodspeed-Niklaus <coriolinus@users.noreply.github.com> Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> Co-authored-by: Peter Goodspeed-Niklaus <peter.r.goodspeedniklaus@gmail.com> Co-authored-by: kianenigma <kian@parity.io> Co-authored-by: Xiliang Chen <xlchen1291@gmail.com> Co-authored-by: Parity Benchmarking Bot <admin@parity.io> Co-authored-by: Shawn Tabrizi <shawntabrizi@gmail.com> Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com>
434 lines
17 KiB
Rust
434 lines
17 KiB
Rust
// This file is part of Substrate.
|
|
|
|
// Copyright (C) 2020 Parity Technologies (UK) Ltd.
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
|
|
//! Primitive traits for providing election functionality.
|
|
//!
|
|
//! This crate provides two traits that could interact to enable extensible election functionality
|
|
//! within FRAME pallets.
|
|
//!
|
|
//! Something that will provide the functionality of election will implement [`ElectionProvider`],
|
|
//! whilst needing an associated [`ElectionProvider::DataProvider`], which needs to be fulfilled by
|
|
//! an entity implementing [`ElectionDataProvider`]. Most often, *the data provider is* the receiver
|
|
//! of the election, resulting in a diagram as below:
|
|
//!
|
|
//! ```ignore
|
|
//! ElectionDataProvider
|
|
//! <------------------------------------------+
|
|
//! | |
|
|
//! v |
|
|
//! +-----+----+ +------+---+
|
|
//! | | | |
|
|
//! pallet-do-election | | | | pallet-needs-election
|
|
//! | | | |
|
|
//! | | | |
|
|
//! +-----+----+ +------+---+
|
|
//! | ^
|
|
//! | |
|
|
//! +------------------------------------------+
|
|
//! ElectionProvider
|
|
//! ```
|
|
//!
|
|
//! > It could also be possible that a third party pallet (C), provides the data of election to an
|
|
//! > election provider (B), which then passes the election result to another pallet (A).
|
|
//!
|
|
//! ## Election Types
|
|
//!
|
|
//! Typically, two types of elections exist:
|
|
//!
|
|
//! 1. **Stateless**: Election data is provided, and the election result is immediately ready.
|
|
//! 2. **Stateful**: Election data is is queried ahead of time, and the election result might be
|
|
//! ready some number of blocks in the future.
|
|
//!
|
|
//! To accommodate both type of elections in one trait, the traits lean toward **stateful
|
|
//! election**, as it is more general than the stateless. This is why [`ElectionProvider::elect`]
|
|
//! has no parameters. All value and type parameter must be provided by the [`ElectionDataProvider`]
|
|
//! trait, even if the election happens immediately.
|
|
//!
|
|
//! ## Election Data
|
|
//!
|
|
//! The data associated with an election, essentially what the [`ElectionDataProvider`] must convey
|
|
//! is as follows:
|
|
//!
|
|
//! 1. A list of voters, with their stake.
|
|
//! 2. A list of targets (i.e. _candidates_).
|
|
//! 3. A number of desired targets to be elected (i.e. _winners_)
|
|
//!
|
|
//! In addition to that, the [`ElectionDataProvider`] must also hint [`ElectionProvider`] at when
|
|
//! the next election might happen ([`ElectionDataProvider::next_election_prediction`]). A stateless
|
|
//! election provider would probably ignore this. A stateful election provider can use this to
|
|
//! prepare the election result in advance.
|
|
//!
|
|
//! Nonetheless, an [`ElectionProvider`] shan't rely on this and should preferably provide some
|
|
//! means of fallback election as well, in case the `elect` was called immaturely early.
|
|
//!
|
|
//! ## Example
|
|
//!
|
|
//! ```rust
|
|
//! # use frame_election_provider_support::{*, data_provider};
|
|
//! # use sp_npos_elections::{Support, Assignment};
|
|
//!
|
|
//! type AccountId = u64;
|
|
//! type Balance = u64;
|
|
//! type BlockNumber = u32;
|
|
//!
|
|
//! mod data_provider_mod {
|
|
//! use super::*;
|
|
//!
|
|
//! pub trait Config: Sized {
|
|
//! type ElectionProvider: ElectionProvider<
|
|
//! AccountId,
|
|
//! BlockNumber,
|
|
//! DataProvider = Module<Self>,
|
|
//! >;
|
|
//! }
|
|
//!
|
|
//! pub struct Module<T: Config>(std::marker::PhantomData<T>);
|
|
//!
|
|
//! impl<T: Config> ElectionDataProvider<AccountId, BlockNumber> for Module<T> {
|
|
//! const MAXIMUM_VOTES_PER_VOTER: u32 = 1;
|
|
//! fn desired_targets() -> data_provider::Result<u32> {
|
|
//! Ok(1)
|
|
//! }
|
|
//! fn voters(maybe_max_len: Option<usize>)
|
|
//! -> data_provider::Result<Vec<(AccountId, VoteWeight, Vec<AccountId>)>>
|
|
//! {
|
|
//! Ok(Default::default())
|
|
//! }
|
|
//! fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<AccountId>> {
|
|
//! Ok(vec![10, 20, 30])
|
|
//! }
|
|
//! fn next_election_prediction(now: BlockNumber) -> BlockNumber {
|
|
//! 0
|
|
//! }
|
|
//! }
|
|
//! }
|
|
//!
|
|
//!
|
|
//! mod generic_election_provider {
|
|
//! use super::*;
|
|
//!
|
|
//! pub struct GenericElectionProvider<T: Config>(std::marker::PhantomData<T>);
|
|
//!
|
|
//! pub trait Config {
|
|
//! type DataProvider: ElectionDataProvider<AccountId, BlockNumber>;
|
|
//! }
|
|
//!
|
|
//! impl<T: Config> ElectionProvider<AccountId, BlockNumber> for GenericElectionProvider<T> {
|
|
//! type Error = &'static str;
|
|
//! type DataProvider = T::DataProvider;
|
|
//!
|
|
//! fn elect() -> Result<Supports<AccountId>, Self::Error> {
|
|
//! Self::DataProvider::targets(None)
|
|
//! .map_err(|_| "failed to elect")
|
|
//! .map(|t| vec![(t[0], Support::default())])
|
|
//! }
|
|
//! }
|
|
//! }
|
|
//!
|
|
//! mod runtime {
|
|
//! use super::generic_election_provider;
|
|
//! use super::data_provider_mod;
|
|
//! use super::AccountId;
|
|
//!
|
|
//! struct Runtime;
|
|
//! impl generic_election_provider::Config for Runtime {
|
|
//! type DataProvider = data_provider_mod::Module<Runtime>;
|
|
//! }
|
|
//!
|
|
//! impl data_provider_mod::Config for Runtime {
|
|
//! type ElectionProvider = generic_election_provider::GenericElectionProvider<Runtime>;
|
|
//! }
|
|
//!
|
|
//! }
|
|
//!
|
|
//! # fn main() {}
|
|
//! ```
|
|
|
|
#![cfg_attr(not(feature = "std"), no_std)]
|
|
|
|
pub mod onchain;
|
|
use frame_support::traits::Get;
|
|
use sp_std::{fmt::Debug, prelude::*};
|
|
|
|
/// Re-export some type as they are used in the interface.
|
|
pub use sp_arithmetic::PerThing;
|
|
pub use sp_npos_elections::{
|
|
Assignment, ElectionResult, ExtendedBalance, IdentifierT, PerThing128, Support, Supports,
|
|
VoteWeight,
|
|
};
|
|
|
|
/// Types that are used by the data provider trait.
|
|
pub mod data_provider {
|
|
/// Alias for the result type of the election data provider.
|
|
pub type Result<T> = sp_std::result::Result<T, &'static str>;
|
|
}
|
|
|
|
/// Something that can provide the data to an [`ElectionProvider`].
|
|
pub trait ElectionDataProvider<AccountId, BlockNumber> {
|
|
/// Maximum number of votes per voter that this data provider is providing.
|
|
const MAXIMUM_VOTES_PER_VOTER: u32;
|
|
|
|
/// All possible targets for the election, i.e. the candidates.
|
|
///
|
|
/// 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<AccountId>>;
|
|
|
|
/// All possible voters for the election.
|
|
///
|
|
/// Note that if a notion of self-vote exists, it should be represented here.
|
|
///
|
|
/// 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 voters(
|
|
maybe_max_len: Option<usize>,
|
|
) -> data_provider::Result<Vec<(AccountId, VoteWeight, Vec<AccountId>)>>;
|
|
|
|
/// The number of targets to elect.
|
|
///
|
|
/// 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 desired_targets() -> data_provider::Result<u32>;
|
|
|
|
/// Provide a best effort prediction about when the next election is about to happen.
|
|
///
|
|
/// In essence, the implementor should predict with this function when it will trigger the
|
|
/// [`ElectionProvider::elect`].
|
|
///
|
|
/// This is only useful for stateful election providers.
|
|
fn next_election_prediction(now: BlockNumber) -> BlockNumber;
|
|
|
|
/// Utility function only to be used in benchmarking scenarios, to be implemented optionally,
|
|
/// else a noop.
|
|
#[cfg(any(feature = "runtime-benchmarks", test))]
|
|
fn put_snapshot(
|
|
_voters: Vec<(AccountId, VoteWeight, Vec<AccountId>)>,
|
|
_targets: Vec<AccountId>,
|
|
_target_stake: Option<VoteWeight>,
|
|
) {
|
|
}
|
|
|
|
/// Utility function only to be used in benchmarking scenarios, to be implemented optionally,
|
|
/// else a noop.
|
|
///
|
|
/// Same as `put_snapshot`, but can add a single voter one by one.
|
|
#[cfg(any(feature = "runtime-benchmarks", test))]
|
|
fn add_voter(_voter: AccountId, _weight: VoteWeight, _targets: Vec<AccountId>) {}
|
|
|
|
/// Utility function only to be used in benchmarking scenarios, to be implemented optionally,
|
|
/// else a noop.
|
|
///
|
|
/// Same as `put_snapshot`, but can add a single voter one by one.
|
|
#[cfg(any(feature = "runtime-benchmarks", test))]
|
|
fn add_target(_target: AccountId) {}
|
|
|
|
/// Clear all voters and targets.
|
|
#[cfg(any(feature = "runtime-benchmarks", test))]
|
|
fn clear() {}
|
|
}
|
|
|
|
#[cfg(feature = "std")]
|
|
impl<AccountId, BlockNumber> ElectionDataProvider<AccountId, BlockNumber> for () {
|
|
const MAXIMUM_VOTES_PER_VOTER: u32 = 0;
|
|
fn targets(_maybe_max_len: Option<usize>) -> data_provider::Result<Vec<AccountId>> {
|
|
Ok(Default::default())
|
|
}
|
|
fn voters(
|
|
_maybe_max_len: Option<usize>,
|
|
) -> data_provider::Result<Vec<(AccountId, VoteWeight, Vec<AccountId>)>> {
|
|
Ok(Default::default())
|
|
}
|
|
fn desired_targets() -> data_provider::Result<u32> {
|
|
Ok(Default::default())
|
|
}
|
|
fn next_election_prediction(now: BlockNumber) -> BlockNumber {
|
|
now
|
|
}
|
|
}
|
|
|
|
/// Something that can compute the result of an election and pass it back to the caller.
|
|
///
|
|
/// This trait only provides an interface to _request_ an election, i.e.
|
|
/// [`ElectionProvider::elect`]. That data required for the election need to be passed to the
|
|
/// implemented of this trait through [`ElectionProvider::DataProvider`].
|
|
pub trait ElectionProvider<AccountId, BlockNumber> {
|
|
/// The error type that is returned by the provider.
|
|
type Error: Debug;
|
|
|
|
/// The data provider of the election.
|
|
type DataProvider: ElectionDataProvider<AccountId, BlockNumber>;
|
|
|
|
/// Elect a new set of winners.
|
|
///
|
|
/// The result is returned in a target major format, namely as vector of supports.
|
|
///
|
|
/// 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 elect() -> Result<Supports<AccountId>, Self::Error>;
|
|
}
|
|
|
|
#[cfg(feature = "std")]
|
|
impl<AccountId, BlockNumber> ElectionProvider<AccountId, BlockNumber> for () {
|
|
type Error = &'static str;
|
|
type DataProvider = ();
|
|
|
|
fn elect() -> Result<Supports<AccountId>, Self::Error> {
|
|
Err("<() as ElectionProvider> cannot do anything.")
|
|
}
|
|
}
|
|
|
|
/// A utility trait for something to implement `ElectionDataProvider` in a sensible way.
|
|
///
|
|
/// This is generic over `AccountId` and it can represent a validator, a nominator, or any other
|
|
/// entity.
|
|
///
|
|
/// To simplify the trait, the `VoteWeight` is hardcoded as the weight of each entity. The weights
|
|
/// are ascending, the higher, the better. In the long term, if this trait ends up having use cases
|
|
/// outside of the election context, it is easy enough to make it generic over the `VoteWeight`.
|
|
///
|
|
/// Something that implements this trait will do a best-effort sort over ids, and thus can be
|
|
/// used on the implementing side of [`ElectionDataProvider`].
|
|
pub trait SortedListProvider<AccountId> {
|
|
/// The list's error type.
|
|
type Error;
|
|
|
|
/// An iterator over the list, which can have `take` called on it.
|
|
fn iter() -> Box<dyn Iterator<Item = AccountId>>;
|
|
|
|
/// The current count of ids in the list.
|
|
fn count() -> u32;
|
|
|
|
/// Return true if the list already contains `id`.
|
|
fn contains(id: &AccountId) -> bool;
|
|
|
|
/// Hook for inserting a new id.
|
|
fn on_insert(id: AccountId, weight: VoteWeight) -> Result<(), Self::Error>;
|
|
|
|
/// Hook for updating a single id.
|
|
fn on_update(id: &AccountId, weight: VoteWeight);
|
|
|
|
/// Hook for removing am id from the list.
|
|
fn on_remove(id: &AccountId);
|
|
|
|
/// Regenerate this list from scratch. Returns the count of items inserted.
|
|
///
|
|
/// This should typically only be used at a runtime upgrade.
|
|
fn regenerate(
|
|
all: impl IntoIterator<Item = AccountId>,
|
|
weight_of: Box<dyn Fn(&AccountId) -> VoteWeight>,
|
|
) -> u32;
|
|
|
|
/// Remove `maybe_count` number of items from the list. Returns the number of items actually
|
|
/// removed. WARNING: removes all items if `maybe_count` is `None`, which should never be done
|
|
/// in production settings because it can lead to an unbounded amount of storage accesses.
|
|
fn clear(maybe_count: Option<u32>) -> u32;
|
|
|
|
/// Sanity check internal state of list. Only meant for debug compilation.
|
|
fn sanity_check() -> Result<(), &'static str>;
|
|
|
|
/// If `who` changes by the returned amount they are guaranteed to have a worst case change
|
|
/// in their list position.
|
|
#[cfg(feature = "runtime-benchmarks")]
|
|
fn weight_update_worst_case(_who: &AccountId, _is_increase: bool) -> VoteWeight {
|
|
VoteWeight::MAX
|
|
}
|
|
}
|
|
|
|
/// Something that can provide the `VoteWeight` of an account. Similar to [`ElectionProvider`] and
|
|
/// [`ElectionDataProvider`], this should typically be implementing by whoever is supposed to *use*
|
|
/// `SortedListProvider`.
|
|
pub trait VoteWeightProvider<AccountId> {
|
|
/// Get the current `VoteWeight` of `who`.
|
|
fn vote_weight(who: &AccountId) -> VoteWeight;
|
|
|
|
/// For tests and benchmarks, set the `VoteWeight`.
|
|
#[cfg(any(feature = "runtime-benchmarks", test))]
|
|
fn set_vote_weight_of(_: &AccountId, _: VoteWeight) {}
|
|
}
|
|
|
|
/// Something that can compute the result to an NPoS solution.
|
|
pub trait NposSolver {
|
|
/// The account identifier type of this solver.
|
|
type AccountId: sp_npos_elections::IdentifierT;
|
|
/// The accuracy of this solver. This will affect the accuracy of the output.
|
|
type Accuracy: PerThing128;
|
|
/// The error type of this implementation.
|
|
type Error: sp_std::fmt::Debug + sp_std::cmp::PartialEq;
|
|
|
|
/// Solve an NPoS solution with the given `voters`, `targets`, and select `to_elect` count
|
|
/// of `targets`.
|
|
fn solve(
|
|
to_elect: usize,
|
|
targets: Vec<Self::AccountId>,
|
|
voters: Vec<(Self::AccountId, VoteWeight, Vec<Self::AccountId>)>,
|
|
) -> Result<ElectionResult<Self::AccountId, Self::Accuracy>, Self::Error>;
|
|
}
|
|
|
|
/// A wrapper for [`sp_npos_elections::seq_phragmen`] that implements [`super::NposSolver`]. See the
|
|
/// documentation of [`sp_npos_elections::seq_phragmen`] for more info.
|
|
pub struct SequentialPhragmen<AccountId, Accuracy, Balancing = ()>(
|
|
sp_std::marker::PhantomData<(AccountId, Accuracy, Balancing)>,
|
|
);
|
|
|
|
impl<
|
|
AccountId: IdentifierT,
|
|
Accuracy: PerThing128,
|
|
Balancing: Get<Option<(usize, ExtendedBalance)>>,
|
|
> NposSolver for SequentialPhragmen<AccountId, Accuracy, Balancing>
|
|
{
|
|
type AccountId = AccountId;
|
|
type Accuracy = Accuracy;
|
|
type Error = sp_npos_elections::Error;
|
|
fn solve(
|
|
winners: usize,
|
|
targets: Vec<Self::AccountId>,
|
|
voters: Vec<(Self::AccountId, VoteWeight, Vec<Self::AccountId>)>,
|
|
) -> Result<ElectionResult<Self::AccountId, Self::Accuracy>, Self::Error> {
|
|
sp_npos_elections::seq_phragmen(winners, targets, voters, Balancing::get())
|
|
}
|
|
}
|
|
|
|
/// A wrapper for [`sp_npos_elections::phragmms`] that implements [`NposSolver`]. See the
|
|
/// documentation of [`sp_npos_elections::phragmms`] for more info.
|
|
pub struct PhragMMS<AccountId, Accuracy, Balancing = ()>(
|
|
sp_std::marker::PhantomData<(AccountId, Accuracy, Balancing)>,
|
|
);
|
|
|
|
impl<
|
|
AccountId: IdentifierT,
|
|
Accuracy: PerThing128,
|
|
Balancing: Get<Option<(usize, ExtendedBalance)>>,
|
|
> NposSolver for PhragMMS<AccountId, Accuracy, Balancing>
|
|
{
|
|
type AccountId = AccountId;
|
|
type Accuracy = Accuracy;
|
|
type Error = sp_npos_elections::Error;
|
|
fn solve(
|
|
winners: usize,
|
|
targets: Vec<Self::AccountId>,
|
|
voters: Vec<(Self::AccountId, VoteWeight, Vec<Self::AccountId>)>,
|
|
) -> Result<ElectionResult<Self::AccountId, Self::Accuracy>, Self::Error> {
|
|
sp_npos_elections::phragmms(winners, targets, voters, Balancing::get())
|
|
}
|
|
}
|