Implement pallet-bags-list and its interfaces with pallet-staking (#9507)

* 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>
This commit is contained in:
Zeke Mostov
2021-09-16 19:25:21 -07:00
committed by GitHub
parent 867cf27bbd
commit 669972a171
36 changed files with 4601 additions and 339 deletions
+201 -52
View File
@@ -17,7 +17,10 @@
//! Implementations for the Staking FRAME Pallet.
use frame_election_provider_support::{data_provider, ElectionProvider, Supports, VoteWeight};
use frame_election_provider_support::{
data_provider, ElectionDataProvider, ElectionProvider, SortedListProvider, Supports,
VoteWeight, VoteWeightProvider,
};
use frame_support::{
pallet_prelude::*,
traits::{
@@ -26,6 +29,7 @@ use frame_support::{
},
weights::{Weight, WithPostDispatchInfo},
};
use frame_system::pallet_prelude::BlockNumberFor;
use pallet_session::historical;
use sp_runtime::{
traits::{Bounded, Convert, SaturatedConversion, Saturating, Zero},
@@ -64,7 +68,7 @@ impl<T: Config> Pallet<T> {
///
/// This prevents call sites from repeatedly requesting `total_issuance` from backend. But it is
/// important to be only used while the total issuance is not changing.
pub fn slashable_balance_of_fn() -> Box<dyn Fn(&T::AccountId) -> VoteWeight> {
pub fn weight_of_fn() -> Box<dyn Fn(&T::AccountId) -> VoteWeight> {
// NOTE: changing this to unboxed `impl Fn(..)` return type and the pallet will still
// compile, while some types in mock fail to resolve.
let issuance = T::Currency::total_issuance();
@@ -73,6 +77,12 @@ impl<T: Config> Pallet<T> {
})
}
/// Same as `weight_of_fn`, but made for one time use.
pub fn weight_of(who: &T::AccountId) -> VoteWeight {
let issuance = T::Currency::total_issuance();
Self::slashable_balance_of_vote_weight(who, issuance)
}
pub(super) fn do_payout_stakers(
validator_stash: T::AccountId,
era: EraIndex,
@@ -629,54 +639,92 @@ impl<T: Config> Pallet<T> {
/// Get all of the voters that are eligible for the npos election.
///
/// This will use all on-chain nominators, and all the validators will inject a self vote.
/// `maybe_max_len` can imposes a cap on the number of voters returned; First all the validator
/// are included in no particular order, then remainder is taken from the nominators, as
/// returned by [`Config::SortedListProvider`].
///
/// This will use nominators, and all the validators will inject a self vote.
///
/// This function is self-weighing as [`DispatchClass::Mandatory`].
///
/// ### Slashing
///
/// All nominations that have been submitted before the last non-zero slash of the validator are
/// auto-chilled.
pub fn get_npos_voters() -> Vec<(T::AccountId, VoteWeight, Vec<T::AccountId>)> {
let weight_of = Self::slashable_balance_of_fn();
let mut all_voters = Vec::new();
/// auto-chilled, but still count towards the limit imposed by `maybe_max_len`.
pub fn get_npos_voters(
maybe_max_len: Option<usize>,
) -> Vec<(T::AccountId, VoteWeight, Vec<T::AccountId>)> {
let max_allowed_len = {
let nominator_count = CounterForNominators::<T>::get() as usize;
let validator_count = CounterForValidators::<T>::get() as usize;
let all_voter_count = validator_count.saturating_add(nominator_count);
maybe_max_len.unwrap_or(all_voter_count).min(all_voter_count)
};
let mut validator_count = 0u32;
for (validator, _) in <Validators<T>>::iter() {
let mut all_voters = Vec::<_>::with_capacity(max_allowed_len);
// first, grab all validators in no particular order, capped by the maximum allowed length.
let mut validators_taken = 0u32;
for (validator, _) in <Validators<T>>::iter().take(max_allowed_len) {
// Append self vote.
let self_vote = (validator.clone(), weight_of(&validator), vec![validator.clone()]);
let self_vote =
(validator.clone(), Self::weight_of(&validator), vec![validator.clone()]);
all_voters.push(self_vote);
validator_count.saturating_inc();
validators_taken.saturating_inc();
}
// Collect all slashing spans into a BTreeMap for further queries.
// .. and grab whatever we have left from nominators.
let nominators_quota = (max_allowed_len as u32).saturating_sub(validators_taken);
let slashing_spans = <SlashingSpans<T>>::iter().collect::<BTreeMap<_, _>>();
let mut nominator_count = 0u32;
for (nominator, nominations) in Nominators::<T>::iter() {
let Nominations { submitted_in, mut targets, suppressed: _ } = nominations;
// track the count of nominators added to `all_voters
let mut nominators_taken = 0u32;
// track every nominator iterated over, but not necessarily added to `all_voters`
let mut nominators_seen = 0u32;
// Filter out nomination targets which were nominated before the most recent
// slashing span.
targets.retain(|stash| {
slashing_spans
.get(stash)
.map_or(true, |spans| submitted_in >= spans.last_nonzero_slash())
});
let mut nominators_iter = T::SortedListProvider::iter();
while nominators_taken < nominators_quota && nominators_seen < nominators_quota * 2 {
let nominator = match nominators_iter.next() {
Some(nominator) => {
nominators_seen.saturating_inc();
nominator
},
None => break,
};
if !targets.is_empty() {
let vote_weight = weight_of(&nominator);
all_voters.push((nominator, vote_weight, targets));
nominator_count.saturating_inc();
if let Some(Nominations { submitted_in, mut targets, suppressed: _ }) =
<Nominators<T>>::get(&nominator)
{
targets.retain(|stash| {
slashing_spans
.get(stash)
.map_or(true, |spans| submitted_in >= spans.last_nonzero_slash())
});
if !targets.len().is_zero() {
all_voters.push((nominator.clone(), Self::weight_of(&nominator), targets));
nominators_taken.saturating_inc();
}
} else {
log!(error, "invalid item in `SortedListProvider`: {:?}", nominator)
}
}
// all_voters should have not re-allocated.
debug_assert!(all_voters.capacity() == max_allowed_len);
Self::register_weight(T::WeightInfo::get_npos_voters(
validator_count,
nominator_count,
validators_taken,
nominators_taken,
slashing_spans.len() as u32,
));
log!(
info,
"generated {} npos voters, {} from validators and {} nominators",
all_voters.len(),
validators_taken,
nominators_taken
);
all_voters
}
@@ -698,34 +746,59 @@ impl<T: Config> Pallet<T> {
}
/// This function will add a nominator to the `Nominators` storage map,
/// and keep track of the `CounterForNominators`.
/// [`SortedListProvider`] and keep track of the `CounterForNominators`.
///
/// If the nominator already exists, their nominations will be updated.
///
/// NOTE: you must ALWAYS use this function to add nominator or update their targets. Any access
/// to `Nominators`, its counter, or `VoterList` outside of this function is almost certainly
/// wrong.
pub fn do_add_nominator(who: &T::AccountId, nominations: Nominations<T::AccountId>) {
if !Nominators::<T>::contains_key(who) {
CounterForNominators::<T>::mutate(|x| x.saturating_inc())
// maybe update the counter.
CounterForNominators::<T>::mutate(|x| x.saturating_inc());
// maybe update sorted list. Error checking is defensive-only - this should never fail.
if T::SortedListProvider::on_insert(who.clone(), Self::weight_of(who)).is_err() {
log!(warn, "attempt to insert duplicate nominator ({:#?})", who);
debug_assert!(false, "attempt to insert duplicate nominator");
};
debug_assert_eq!(T::SortedListProvider::sanity_check(), Ok(()));
}
Nominators::<T>::insert(who, nominations);
}
/// This function will remove a nominator from the `Nominators` storage map,
/// and keep track of the `CounterForNominators`.
/// [`SortedListProvider`] and keep track of the `CounterForNominators`.
///
/// Returns true if `who` was removed from `Nominators`, otherwise false.
///
/// NOTE: you must ALWAYS use this function to remove a nominator from the system. Any access to
/// `Nominators`, its counter, or `VoterList` outside of this function is almost certainly
/// wrong.
pub fn do_remove_nominator(who: &T::AccountId) -> bool {
if Nominators::<T>::contains_key(who) {
Nominators::<T>::remove(who);
CounterForNominators::<T>::mutate(|x| x.saturating_dec());
T::SortedListProvider::on_remove(who);
debug_assert_eq!(T::SortedListProvider::sanity_check(), Ok(()));
debug_assert_eq!(CounterForNominators::<T>::get(), T::SortedListProvider::count());
true
} else {
false
}
}
/// This function will add a validator to the `Validators` storage map,
/// and keep track of the `CounterForValidators`.
/// This function will add a validator to the `Validators` storage map, and keep track of the
/// `CounterForValidators`.
///
/// If the validator already exists, their preferences will be updated.
///
/// NOTE: you must ALWAYS use this function to add a validator to the system. Any access to
/// `Validators`, its counter, or `VoterList` outside of this function is almost certainly
/// wrong.
pub fn do_add_validator(who: &T::AccountId, prefs: ValidatorPrefs) {
if !Validators::<T>::contains_key(who) {
CounterForValidators::<T>::mutate(|x| x.saturating_inc())
@@ -737,6 +810,10 @@ impl<T: Config> Pallet<T> {
/// and keep track of the `CounterForValidators`.
///
/// Returns true if `who` was removed from `Validators`, otherwise false.
///
/// NOTE: you must ALWAYS use this function to remove a validator from the system. Any access to
/// `Validators`, its counter, or `VoterList` outside of this function is almost certainly
/// wrong.
pub fn do_remove_validator(who: &T::AccountId) -> bool {
if Validators::<T>::contains_key(who) {
Validators::<T>::remove(who);
@@ -758,10 +835,9 @@ impl<T: Config> Pallet<T> {
}
}
impl<T: Config> frame_election_provider_support::ElectionDataProvider<T::AccountId, T::BlockNumber>
for Pallet<T>
{
impl<T: Config> ElectionDataProvider<T::AccountId, BlockNumberFor<T>> for Pallet<T> {
const MAXIMUM_VOTES_PER_VOTER: u32 = T::MAX_NOMINATIONS;
fn desired_targets() -> data_provider::Result<u32> {
Self::register_weight(T::DbWeight::get().reads(1));
Ok(Self::validator_count())
@@ -770,30 +846,26 @@ impl<T: Config> frame_election_provider_support::ElectionDataProvider<T::Account
fn voters(
maybe_max_len: Option<usize>,
) -> data_provider::Result<Vec<(T::AccountId, VoteWeight, Vec<T::AccountId>)>> {
let nominator_count = CounterForNominators::<T>::get();
let validator_count = CounterForValidators::<T>::get();
let voter_count = nominator_count.saturating_add(validator_count) as usize;
debug_assert!(<Nominators<T>>::iter().count() as u32 == CounterForNominators::<T>::get());
debug_assert!(<Validators<T>>::iter().count() as u32 == CounterForValidators::<T>::get());
debug_assert_eq!(
CounterForNominators::<T>::get(),
T::SortedListProvider::count(),
"voter_count must be accurate",
);
// register the extra 2 reads
Self::register_weight(T::DbWeight::get().reads(2));
// 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));
if maybe_max_len.map_or(false, |max_len| voter_count > max_len) {
return Err("Voter snapshot too big")
}
Ok(Self::get_npos_voters())
Ok(voters)
}
fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<Vec<T::AccountId>> {
let target_count = CounterForValidators::<T>::get() as usize;
let target_count = CounterForValidators::<T>::get();
// register the extra 1 read
Self::register_weight(T::DbWeight::get().reads(1));
if maybe_max_len.map_or(false, |max_len| target_count > max_len) {
// We can't handle this case yet -- return an error.
if maybe_max_len.map_or(false, |max_len| target_count > max_len as u32) {
return Err("Target snapshot too big")
}
@@ -879,6 +951,9 @@ impl<T: Config> frame_election_provider_support::ElectionDataProvider<T::Account
<Ledger<T>>::remove_all(None);
<Validators<T>>::remove_all(None);
<Nominators<T>>::remove_all(None);
<CounterForNominators<T>>::kill();
<CounterForValidators<T>>::kill();
let _ = T::SortedListProvider::clear(None);
}
#[cfg(feature = "runtime-benchmarks")]
@@ -1152,3 +1227,77 @@ where
consumed_weight
}
}
impl<T: Config> VoteWeightProvider<T::AccountId> for Pallet<T> {
fn vote_weight(who: &T::AccountId) -> VoteWeight {
Self::weight_of(who)
}
#[cfg(feature = "runtime-benchmarks")]
fn set_vote_weight_of(who: &T::AccountId, weight: VoteWeight) {
// this will clearly results in an inconsistent state, but it should not matter for a
// benchmark.
use sp_std::convert::TryInto;
let active: BalanceOf<T> = weight.try_into().map_err(|_| ()).unwrap();
let mut ledger = Self::ledger(who).unwrap_or_default();
ledger.active = active;
<Ledger<T>>::insert(who, ledger);
<Bonded<T>>::insert(who, who);
// also, we play a trick to make sure that a issuance based-`CurrencyToVote` behaves well:
// This will make sure that total issuance is zero, thus the currency to vote will be a 1-1
// conversion.
let imbalance = T::Currency::burn(T::Currency::total_issuance());
// kinda ugly, but gets the job done. The fact that this works here is a HUGE exception.
// Don't try this pattern in other places.
sp_std::mem::forget(imbalance);
}
}
/// A simple voter list implementation that does not require any additional pallets. Note, this
/// does not provided nominators in sorted ordered. If you desire nominators in a sorted order take
/// a look at [`pallet-bags-list].
pub struct UseNominatorsMap<T>(sp_std::marker::PhantomData<T>);
impl<T: Config> SortedListProvider<T::AccountId> for UseNominatorsMap<T> {
type Error = ();
/// Returns iterator over voter list, which can have `take` called on it.
fn iter() -> Box<dyn Iterator<Item = T::AccountId>> {
Box::new(Nominators::<T>::iter().map(|(n, _)| n))
}
fn count() -> u32 {
CounterForNominators::<T>::get()
}
fn contains(id: &T::AccountId) -> bool {
Nominators::<T>::contains_key(id)
}
fn on_insert(_: T::AccountId, _weight: VoteWeight) -> Result<(), Self::Error> {
// nothing to do on insert.
Ok(())
}
fn on_update(_: &T::AccountId, _weight: VoteWeight) {
// nothing to do on update.
}
fn on_remove(_: &T::AccountId) {
// nothing to do on remove.
}
fn regenerate(
_: impl IntoIterator<Item = T::AccountId>,
_: Box<dyn Fn(&T::AccountId) -> VoteWeight>,
) -> u32 {
// nothing to do upon regenerate.
0
}
fn sanity_check() -> Result<(), &'static str> {
Ok(())
}
fn clear(maybe_count: Option<u32>) -> u32 {
Nominators::<T>::remove_all(maybe_count);
if let Some(count) = maybe_count {
CounterForNominators::<T>::mutate(|noms| *noms - count);
count
} else {
CounterForNominators::<T>::take()
}
}
}