feat: Rebrand Polkadot/Substrate references to PezkuwiChain
This commit systematically rebrands various references from Parity Technologies' Polkadot/Substrate ecosystem to PezkuwiChain within the kurdistan-sdk. Key changes include: - Updated external repository URLs (zombienet-sdk, parity-db, parity-scale-codec, wasm-instrument) to point to pezkuwichain forks. - Modified internal documentation and code comments to reflect PezkuwiChain naming and structure. - Replaced direct references to with or specific paths within the for XCM, Pezkuwi, and other modules. - Cleaned up deprecated issue and PR references in various and files, particularly in and modules. - Adjusted image and logo URLs in documentation to point to PezkuwiChain assets. - Removed or rephrased comments related to external Polkadot/Substrate PRs and issues. This is a significant step towards fully customizing the SDK for the PezkuwiChain ecosystem.
This commit is contained in:
@@ -0,0 +1,470 @@
|
||||
// This file is part of Bizinikiwi.
|
||||
|
||||
// Copyright (C) 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.
|
||||
|
||||
//! Types and helpers to define and handle election bounds.
|
||||
//!
|
||||
//! ### Overview
|
||||
//!
|
||||
//! This module defines and implements types that help creating and handling election bounds.
|
||||
//! [`DataProviderBounds`] encapsulates the upper limits for the results provided by `DataProvider`
|
||||
//! implementors. Those limits can be defined over two axis: number of elements returned (`count`)
|
||||
//! and/or the size of the returned SCALE encoded structure (`size`).
|
||||
//!
|
||||
//! [`ElectionBoundsBuilder`] is a helper to construct data election bounds and it aims at
|
||||
//! preventing the caller from mistake the order of size and count limits.
|
||||
//!
|
||||
//! ### Examples
|
||||
//!
|
||||
//! [`ElectionBoundsBuilder`] helps defining the size and count bounds for both voters and targets.
|
||||
//!
|
||||
//! ```
|
||||
//! use pezframe_election_provider_support::bounds::*;
|
||||
//!
|
||||
//! // unbounded limits are never exhausted.
|
||||
//! let unbounded = ElectionBoundsBuilder::default().build();
|
||||
//! assert!(!unbounded.targets.exhausted(SizeBound(1_000_000_000).into(), None));
|
||||
//!
|
||||
//! let bounds = ElectionBoundsBuilder::default()
|
||||
//! .voters_count(100.into())
|
||||
//! .voters_size(1_000.into())
|
||||
//! .targets_count(200.into())
|
||||
//! .targets_size(2_000.into())
|
||||
//! .build();
|
||||
//!
|
||||
//! assert!(!bounds.targets.exhausted(SizeBound(1).into(), CountBound(1).into()));
|
||||
//! assert!(bounds.targets.exhausted(SizeBound(1).into(), CountBound(100_000).into()));
|
||||
//! ```
|
||||
//!
|
||||
//! ### Implementation details
|
||||
//!
|
||||
//! A default or `None` bound means that no bounds are enforced (i.e. unlimited result size). In
|
||||
//! general, be careful when using unbounded election bounds in production.
|
||||
|
||||
use codec::Encode;
|
||||
use core::ops::Add;
|
||||
use pezsp_runtime::traits::Zero;
|
||||
|
||||
/// Count type for data provider bounds.
|
||||
///
|
||||
/// Encapsulates the counting of things that can be bounded in an election, such as voters,
|
||||
/// targets or anything else.
|
||||
///
|
||||
/// This struct is defined mostly to prevent callers from mistakenly using `CountBound` instead of
|
||||
/// `SizeBound` and vice-versa.
|
||||
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||||
pub struct CountBound(pub u32);
|
||||
|
||||
impl From<u32> for CountBound {
|
||||
fn from(value: u32) -> Self {
|
||||
CountBound(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl Add for CountBound {
|
||||
type Output = Self;
|
||||
fn add(self, rhs: Self) -> Self::Output {
|
||||
CountBound(self.0.saturating_add(rhs.0))
|
||||
}
|
||||
}
|
||||
|
||||
impl Zero for CountBound {
|
||||
fn is_zero(&self) -> bool {
|
||||
self.0 == 0u32
|
||||
}
|
||||
fn zero() -> Self {
|
||||
CountBound(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Size type for data provider bounds.
|
||||
///
|
||||
/// Encapsulates the size limit of things that can be bounded in an election, such as voters,
|
||||
/// targets or anything else. The size unit can represent anything depending on the election
|
||||
/// logic and implementation, but it most likely will represent bytes in SCALE encoding in this
|
||||
/// context.
|
||||
///
|
||||
/// This struct is defined mostly to prevent callers from mistakenly using `CountBound` instead of
|
||||
/// `SizeBound` and vice-versa.
|
||||
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||||
pub struct SizeBound(pub u32);
|
||||
|
||||
impl From<u32> for SizeBound {
|
||||
fn from(value: u32) -> Self {
|
||||
SizeBound(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl Zero for SizeBound {
|
||||
fn is_zero(&self) -> bool {
|
||||
self.0 == 0u32
|
||||
}
|
||||
fn zero() -> Self {
|
||||
SizeBound(0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Add for SizeBound {
|
||||
type Output = Self;
|
||||
fn add(self, rhs: Self) -> Self::Output {
|
||||
SizeBound(self.0.saturating_add(rhs.0))
|
||||
}
|
||||
}
|
||||
|
||||
/// Data bounds for election data.
|
||||
///
|
||||
/// Limits the data returned by `DataProvider` implementors, defined over two axis: `count`,
|
||||
/// defining the maximum number of elements returned, and `size`, defining the limit in size
|
||||
/// (bytes) of the SCALE encoded result.
|
||||
///
|
||||
/// `None` represents unlimited bounds in both `count` and `size` axis.
|
||||
#[derive(Clone, Copy, Default, Debug, Eq, PartialEq)]
|
||||
pub struct DataProviderBounds {
|
||||
pub count: Option<CountBound>,
|
||||
pub size: Option<SizeBound>,
|
||||
}
|
||||
|
||||
impl DataProviderBounds {
|
||||
/// Returns true if `given_count` exhausts `self.count`.
|
||||
pub fn count_exhausted(self, given_count: CountBound) -> bool {
|
||||
self.count.map_or(false, |count| given_count > count)
|
||||
}
|
||||
|
||||
/// Returns true if `given_size` exhausts `self.size`.
|
||||
pub fn size_exhausted(self, given_size: SizeBound) -> bool {
|
||||
self.size.map_or(false, |size| given_size > size)
|
||||
}
|
||||
|
||||
/// Returns true if `given_size` or `given_count` exhausts `self.size` or `self_count`,
|
||||
/// respectively.
|
||||
pub fn exhausted(self, given_size: Option<SizeBound>, given_count: Option<CountBound>) -> bool {
|
||||
self.count_exhausted(given_count.unwrap_or(CountBound::zero())) ||
|
||||
self.size_exhausted(given_size.unwrap_or(SizeBound::zero()))
|
||||
}
|
||||
|
||||
/// Ensures the given encode-able slice meets both the length and count bounds.
|
||||
///
|
||||
/// Same as `exhausted` but a better syntax.
|
||||
pub fn slice_exhausted<T: Encode>(self, input: &[T]) -> bool {
|
||||
let size = Some((input.encoded_size() as u32).into());
|
||||
let count = Some((input.len() as u32).into());
|
||||
self.exhausted(size, count)
|
||||
}
|
||||
|
||||
/// Returns an instance of `Self` that is constructed by capping both the `count` and `size`
|
||||
/// fields. If `self` is None, overwrite it with the provided bounds.
|
||||
pub fn max(self, bounds: DataProviderBounds) -> Self {
|
||||
DataProviderBounds {
|
||||
count: self
|
||||
.count
|
||||
.map(|c| {
|
||||
c.clamp(CountBound::zero(), bounds.count.unwrap_or(CountBound(u32::MAX))).into()
|
||||
})
|
||||
.or(bounds.count),
|
||||
size: self
|
||||
.size
|
||||
.map(|c| {
|
||||
c.clamp(SizeBound::zero(), bounds.size.unwrap_or(SizeBound(u32::MAX))).into()
|
||||
})
|
||||
.or(bounds.size),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The voter and target bounds of an election.
|
||||
///
|
||||
/// The bounds are defined over two axis: `count` of element of the election (voters or targets) and
|
||||
/// the `size` of the SCALE encoded result snapshot.
|
||||
#[derive(Clone, Debug, Copy)]
|
||||
pub struct ElectionBounds {
|
||||
pub voters: DataProviderBounds,
|
||||
pub targets: DataProviderBounds,
|
||||
}
|
||||
|
||||
impl ElectionBounds {
|
||||
/// Returns an error if the provided `count` and `size` do not fit in the voter's election
|
||||
/// bounds.
|
||||
pub fn ensure_voters_limits(
|
||||
self,
|
||||
count: CountBound,
|
||||
size: SizeBound,
|
||||
) -> Result<(), &'static str> {
|
||||
match self.voters.exhausted(Some(size), Some(count)) {
|
||||
true => Err("Ensure voters bounds: bounds exceeded."),
|
||||
false => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an error if the provided `count` and `size` do not fit in the target's election
|
||||
/// bounds.
|
||||
pub fn ensure_targets_limits(
|
||||
self,
|
||||
count: CountBound,
|
||||
size: SizeBound,
|
||||
) -> Result<(), &'static str> {
|
||||
match self.targets.exhausted(Some(size), Some(count).into()) {
|
||||
true => Err("Ensure targets bounds: bounds exceeded."),
|
||||
false => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Utility builder for [`ElectionBounds`].
|
||||
#[derive(Copy, Clone, Default)]
|
||||
pub struct ElectionBoundsBuilder {
|
||||
voters: Option<DataProviderBounds>,
|
||||
targets: Option<DataProviderBounds>,
|
||||
}
|
||||
|
||||
impl From<ElectionBounds> for ElectionBoundsBuilder {
|
||||
fn from(bounds: ElectionBounds) -> Self {
|
||||
ElectionBoundsBuilder { voters: Some(bounds.voters), targets: Some(bounds.targets) }
|
||||
}
|
||||
}
|
||||
|
||||
impl ElectionBoundsBuilder {
|
||||
/// Sets the voters count bounds.
|
||||
pub fn voters_count(mut self, count: CountBound) -> Self {
|
||||
self.voters = self.voters.map_or(
|
||||
Some(DataProviderBounds { count: Some(count), size: None }),
|
||||
|mut bounds| {
|
||||
bounds.count = Some(count);
|
||||
Some(bounds)
|
||||
},
|
||||
);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the voters size bounds.
|
||||
pub fn voters_size(mut self, size: SizeBound) -> Self {
|
||||
self.voters = self.voters.map_or(
|
||||
Some(DataProviderBounds { count: None, size: Some(size) }),
|
||||
|mut bounds| {
|
||||
bounds.size = Some(size);
|
||||
Some(bounds)
|
||||
},
|
||||
);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the targets count bounds.
|
||||
pub fn targets_count(mut self, count: CountBound) -> Self {
|
||||
self.targets = self.targets.map_or(
|
||||
Some(DataProviderBounds { count: Some(count), size: None }),
|
||||
|mut bounds| {
|
||||
bounds.count = Some(count);
|
||||
Some(bounds)
|
||||
},
|
||||
);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the targets size bounds.
|
||||
pub fn targets_size(mut self, size: SizeBound) -> Self {
|
||||
self.targets = self.targets.map_or(
|
||||
Some(DataProviderBounds { count: None, size: Some(size) }),
|
||||
|mut bounds| {
|
||||
bounds.size = Some(size);
|
||||
Some(bounds)
|
||||
},
|
||||
);
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the voters bounds.
|
||||
pub fn voters(mut self, bounds: Option<DataProviderBounds>) -> Self {
|
||||
self.voters = bounds;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the targets bounds.
|
||||
pub fn targets(mut self, bounds: Option<DataProviderBounds>) -> Self {
|
||||
self.targets = bounds;
|
||||
self
|
||||
}
|
||||
|
||||
/// Caps the number of the voters bounds in self to `voters` bounds. If `voters` bounds are
|
||||
/// higher than the self bounds, keeps it. Note that `None` bounds are equivalent to maximum
|
||||
/// and should be treated as such.
|
||||
pub fn voters_or_lower(mut self, voters: DataProviderBounds) -> Self {
|
||||
self.voters = match self.voters {
|
||||
None => Some(voters),
|
||||
Some(v) => Some(v.max(voters)),
|
||||
};
|
||||
self
|
||||
}
|
||||
|
||||
/// Caps the number of the target bounds in self to `voters` bounds. If `voters` bounds are
|
||||
/// higher than the self bounds, keeps it. Note that `None` bounds are equivalent to maximum
|
||||
/// and should be treated as such.
|
||||
pub fn targets_or_lower(mut self, targets: DataProviderBounds) -> Self {
|
||||
self.targets = match self.targets {
|
||||
None => Some(targets),
|
||||
Some(t) => Some(t.max(targets)),
|
||||
};
|
||||
self
|
||||
}
|
||||
|
||||
/// Returns an instance of `ElectionBounds` from the current state.
|
||||
pub fn build(self) -> ElectionBounds {
|
||||
ElectionBounds {
|
||||
voters: self.voters.unwrap_or_default(),
|
||||
targets: self.targets.unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
use pezframe_support::{assert_err, assert_ok};
|
||||
|
||||
#[test]
|
||||
fn data_provider_bounds_unbounded_works() {
|
||||
let bounds = DataProviderBounds::default();
|
||||
assert!(!bounds.exhausted(None, None));
|
||||
assert!(!bounds.exhausted(SizeBound(u32::MAX).into(), CountBound(u32::MAX).into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn election_bounds_builder_and_exhausted_bounds_work() {
|
||||
// voter bounds exhausts if count > 100 or size > 1_000; target bounds exhausts if count >
|
||||
// 200 or size > 2_000.
|
||||
let bounds = ElectionBoundsBuilder::default()
|
||||
.voters_count(100.into())
|
||||
.voters_size(1_000.into())
|
||||
.targets_count(200.into())
|
||||
.targets_size(2_000.into())
|
||||
.build();
|
||||
|
||||
assert!(!bounds.voters.exhausted(None, None));
|
||||
assert!(!bounds.voters.exhausted(SizeBound(10).into(), CountBound(10).into()));
|
||||
assert!(!bounds.voters.exhausted(None, CountBound(100).into()));
|
||||
assert!(!bounds.voters.exhausted(SizeBound(1_000).into(), None));
|
||||
// exhausts bounds.
|
||||
assert!(bounds.voters.exhausted(None, CountBound(101).into()));
|
||||
assert!(bounds.voters.exhausted(SizeBound(1_001).into(), None));
|
||||
|
||||
assert!(!bounds.targets.exhausted(None, None));
|
||||
assert!(!bounds.targets.exhausted(SizeBound(20).into(), CountBound(20).into()));
|
||||
assert!(!bounds.targets.exhausted(None, CountBound(200).into()));
|
||||
assert!(!bounds.targets.exhausted(SizeBound(2_000).into(), None));
|
||||
// exhausts bounds.
|
||||
assert!(bounds.targets.exhausted(None, CountBound(201).into()));
|
||||
assert!(bounds.targets.exhausted(SizeBound(2_001).into(), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn election_bounds_ensure_limits_works() {
|
||||
let bounds = ElectionBounds {
|
||||
voters: DataProviderBounds { count: Some(CountBound(10)), size: Some(SizeBound(10)) },
|
||||
targets: DataProviderBounds { count: Some(CountBound(10)), size: Some(SizeBound(10)) },
|
||||
};
|
||||
|
||||
assert_ok!(bounds.ensure_voters_limits(CountBound(1), SizeBound(1)));
|
||||
assert_ok!(bounds.ensure_voters_limits(CountBound(1), SizeBound(1)));
|
||||
assert_ok!(bounds.ensure_voters_limits(CountBound(10), SizeBound(10)));
|
||||
assert_err!(
|
||||
bounds.ensure_voters_limits(CountBound(1), SizeBound(11)),
|
||||
"Ensure voters bounds: bounds exceeded."
|
||||
);
|
||||
assert_err!(
|
||||
bounds.ensure_voters_limits(CountBound(11), SizeBound(10)),
|
||||
"Ensure voters bounds: bounds exceeded."
|
||||
);
|
||||
|
||||
assert_ok!(bounds.ensure_targets_limits(CountBound(1), SizeBound(1)));
|
||||
assert_ok!(bounds.ensure_targets_limits(CountBound(1), SizeBound(1)));
|
||||
assert_ok!(bounds.ensure_targets_limits(CountBound(10), SizeBound(10)));
|
||||
assert_err!(
|
||||
bounds.ensure_targets_limits(CountBound(1), SizeBound(11)),
|
||||
"Ensure targets bounds: bounds exceeded."
|
||||
);
|
||||
assert_err!(
|
||||
bounds.ensure_targets_limits(CountBound(11), SizeBound(10)),
|
||||
"Ensure targets bounds: bounds exceeded."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_provider_max_unbounded_works() {
|
||||
let unbounded = DataProviderBounds::default();
|
||||
|
||||
// max of some bounds with unbounded data provider bounds will always return the defined
|
||||
// bounds.
|
||||
let bounds = DataProviderBounds { count: CountBound(5).into(), size: SizeBound(10).into() };
|
||||
assert_eq!(unbounded.max(bounds), bounds);
|
||||
|
||||
let bounds = DataProviderBounds { count: None, size: SizeBound(10).into() };
|
||||
assert_eq!(unbounded.max(bounds), bounds);
|
||||
|
||||
let bounds = DataProviderBounds { count: CountBound(5).into(), size: None };
|
||||
assert_eq!(unbounded.max(bounds), bounds);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_provider_max_bounded_works() {
|
||||
let bounds_one =
|
||||
DataProviderBounds { count: CountBound(10).into(), size: SizeBound(100).into() };
|
||||
let bounds_two =
|
||||
DataProviderBounds { count: CountBound(100).into(), size: SizeBound(10).into() };
|
||||
let max_bounds_expected =
|
||||
DataProviderBounds { count: CountBound(10).into(), size: SizeBound(10).into() };
|
||||
|
||||
assert_eq!(bounds_one.max(bounds_two), max_bounds_expected);
|
||||
assert_eq!(bounds_two.max(bounds_one), max_bounds_expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn election_bounds_clamp_works() {
|
||||
let bounds = ElectionBoundsBuilder::default()
|
||||
.voters_count(10.into())
|
||||
.voters_size(10.into())
|
||||
.voters_or_lower(DataProviderBounds {
|
||||
count: CountBound(5).into(),
|
||||
size: SizeBound(20).into(),
|
||||
})
|
||||
.targets_count(20.into())
|
||||
.targets_or_lower(DataProviderBounds {
|
||||
count: CountBound(30).into(),
|
||||
size: SizeBound(30).into(),
|
||||
})
|
||||
.build();
|
||||
|
||||
assert_eq!(bounds.voters.count.unwrap(), CountBound(5));
|
||||
assert_eq!(bounds.voters.size.unwrap(), SizeBound(10));
|
||||
assert_eq!(bounds.targets.count.unwrap(), CountBound(20));
|
||||
assert_eq!(bounds.targets.size.unwrap(), SizeBound(30));
|
||||
|
||||
// note that unbounded bounds (None) are equivalent to maximum value.
|
||||
let bounds = ElectionBoundsBuilder::default()
|
||||
.voters_or_lower(DataProviderBounds {
|
||||
count: CountBound(5).into(),
|
||||
size: SizeBound(20).into(),
|
||||
})
|
||||
.targets_or_lower(DataProviderBounds {
|
||||
count: CountBound(10).into(),
|
||||
size: SizeBound(10).into(),
|
||||
})
|
||||
.build();
|
||||
|
||||
assert_eq!(bounds.voters.count.unwrap(), CountBound(5));
|
||||
assert_eq!(bounds.voters.size.unwrap(), SizeBound(20));
|
||||
assert_eq!(bounds.targets.count.unwrap(), CountBound(10));
|
||||
assert_eq!(bounds.targets.size.unwrap(), SizeBound(10));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,184 @@
|
||||
// This file is part of Bizinikiwi.
|
||||
|
||||
// Copyright (C) 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.
|
||||
|
||||
//! Mock file for solution-type.
|
||||
|
||||
#![cfg(test)]
|
||||
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
hash::Hash,
|
||||
};
|
||||
|
||||
use rand::{seq::SliceRandom, Rng};
|
||||
|
||||
pub type AccountId = u64;
|
||||
|
||||
/// The candidate mask allows easy disambiguation between voters and candidates: accounts
|
||||
/// for which this bit is set are candidates, and without it, are voters.
|
||||
pub const CANDIDATE_MASK: AccountId = 1 << ((std::mem::size_of::<AccountId>() * 8) - 1);
|
||||
|
||||
pub type TestAccuracy = pezsp_runtime::Perbill;
|
||||
|
||||
pub fn p(p: u8) -> TestAccuracy {
|
||||
TestAccuracy::from_percent(p.into())
|
||||
}
|
||||
|
||||
pub type MockAssignment = crate::Assignment<AccountId, TestAccuracy>;
|
||||
pub type Voter = (AccountId, crate::VoteWeight, Vec<AccountId>);
|
||||
|
||||
crate::generate_solution_type! {
|
||||
pub struct TestSolution::<
|
||||
VoterIndex = u32,
|
||||
TargetIndex = u16,
|
||||
Accuracy = TestAccuracy,
|
||||
MaxVoters = pezframe_support::traits::ConstU32::<2_500>,
|
||||
>(16)
|
||||
}
|
||||
|
||||
/// Generate voter and assignment lists. Makes no attempt to be realistic about winner or assignment
|
||||
/// fairness.
|
||||
///
|
||||
/// Maintains these invariants:
|
||||
///
|
||||
/// - candidate ids have `CANDIDATE_MASK` bit set
|
||||
/// - voter ids do not have `CANDIDATE_MASK` bit set
|
||||
/// - assignments have the same ordering as voters
|
||||
/// - `assignments.distribution.iter().map(|(_, frac)| frac).sum() == One::one()`
|
||||
/// - a coherent set of winners is chosen.
|
||||
/// - the winner set is a subset of the candidate set.
|
||||
/// - `assignments.distribution.iter().all(|(who, _)| winners.contains(who))`
|
||||
pub fn generate_random_votes(
|
||||
candidate_count: usize,
|
||||
voter_count: usize,
|
||||
mut rng: impl Rng,
|
||||
) -> (Vec<Voter>, Vec<MockAssignment>, Vec<AccountId>) {
|
||||
// cache for fast generation of unique candidate and voter ids
|
||||
let mut used_ids = HashSet::with_capacity(candidate_count + voter_count);
|
||||
|
||||
// candidates are easy: just a completely random set of IDs
|
||||
let mut candidates: Vec<AccountId> = Vec::with_capacity(candidate_count);
|
||||
while candidates.len() < candidate_count {
|
||||
let mut new = || rng.gen::<AccountId>() | CANDIDATE_MASK;
|
||||
let mut id = new();
|
||||
// insert returns `false` when the value was already present
|
||||
while !used_ids.insert(id) {
|
||||
id = new();
|
||||
}
|
||||
candidates.push(id);
|
||||
}
|
||||
|
||||
// voters are random ids, random weights, random selection from the candidates
|
||||
let mut voters = Vec::with_capacity(voter_count);
|
||||
while voters.len() < voter_count {
|
||||
let mut new = || rng.gen::<AccountId>() & !CANDIDATE_MASK;
|
||||
let mut id = new();
|
||||
// insert returns `false` when the value was already present
|
||||
while !used_ids.insert(id) {
|
||||
id = new();
|
||||
}
|
||||
|
||||
let vote_weight = rng.gen();
|
||||
|
||||
// it's not interesting if a voter chooses 0 or all candidates, so rule those cases out.
|
||||
// also, let's not generate any cases which result in a compact overflow.
|
||||
let n_candidates_chosen =
|
||||
rng.gen_range(1..candidates.len().min(<TestSolution as crate::NposSolution>::LIMIT));
|
||||
|
||||
let mut chosen_candidates = Vec::with_capacity(n_candidates_chosen);
|
||||
chosen_candidates.extend(candidates.choose_multiple(&mut rng, n_candidates_chosen));
|
||||
voters.push((id, vote_weight, chosen_candidates));
|
||||
}
|
||||
|
||||
// always generate a sensible number of winners: elections are uninteresting if nobody wins,
|
||||
// or everybody wins
|
||||
let num_winners = rng.gen_range(1..candidate_count);
|
||||
let mut winners: HashSet<AccountId> = HashSet::with_capacity(num_winners);
|
||||
winners.extend(candidates.choose_multiple(&mut rng, num_winners));
|
||||
assert_eq!(winners.len(), num_winners);
|
||||
|
||||
let mut assignments = Vec::with_capacity(voters.len());
|
||||
for (voter_id, _, votes) in voters.iter() {
|
||||
let chosen_winners = votes.iter().filter(|vote| winners.contains(vote)).cloned();
|
||||
let num_chosen_winners = chosen_winners.clone().count();
|
||||
|
||||
// distribute the available stake randomly
|
||||
let stake_distribution = if num_chosen_winners == 0 {
|
||||
continue;
|
||||
} else {
|
||||
let mut available_stake = 1000;
|
||||
let mut stake_distribution = Vec::with_capacity(num_chosen_winners);
|
||||
for _ in 0..num_chosen_winners - 1 {
|
||||
let stake = rng.gen_range(0..available_stake).min(1);
|
||||
stake_distribution.push(TestAccuracy::from_perthousand(stake));
|
||||
available_stake -= stake;
|
||||
}
|
||||
stake_distribution.push(TestAccuracy::from_perthousand(available_stake));
|
||||
stake_distribution.shuffle(&mut rng);
|
||||
stake_distribution
|
||||
};
|
||||
|
||||
assignments.push(MockAssignment {
|
||||
who: *voter_id,
|
||||
distribution: chosen_winners.zip(stake_distribution).collect(),
|
||||
});
|
||||
}
|
||||
|
||||
(voters, assignments, candidates)
|
||||
}
|
||||
|
||||
fn generate_cache<Voters, Item>(voters: Voters) -> HashMap<Item, usize>
|
||||
where
|
||||
Voters: Iterator<Item = Item>,
|
||||
Item: Hash + Eq + Copy,
|
||||
{
|
||||
let mut cache = HashMap::new();
|
||||
for (idx, voter_id) in voters.enumerate() {
|
||||
cache.insert(voter_id, idx);
|
||||
}
|
||||
cache
|
||||
}
|
||||
|
||||
/// Create a function that returns the index of a voter in the voters list.
|
||||
pub fn make_voter_fn<VoterIndex>(voters: &[Voter]) -> impl Fn(&AccountId) -> Option<VoterIndex>
|
||||
where
|
||||
usize: TryInto<VoterIndex>,
|
||||
{
|
||||
let cache = generate_cache(voters.iter().map(|(id, _, _)| *id));
|
||||
move |who| {
|
||||
if cache.get(who).is_none() {
|
||||
println!("WARNING: voter {} will raise InvalidIndex", who);
|
||||
}
|
||||
cache.get(who).cloned().and_then(|i| i.try_into().ok())
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a function that returns the index of a candidate in the candidates list.
|
||||
pub fn make_target_fn<TargetIndex>(
|
||||
candidates: &[AccountId],
|
||||
) -> impl Fn(&AccountId) -> Option<TargetIndex>
|
||||
where
|
||||
usize: TryInto<TargetIndex>,
|
||||
{
|
||||
let cache = generate_cache(candidates.iter().cloned());
|
||||
move |who| {
|
||||
if cache.get(who).is_none() {
|
||||
println!("WARNING: target {} will raise InvalidIndex", who);
|
||||
}
|
||||
cache.get(who).cloned().and_then(|i| i.try_into().ok())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
// This file is part of Bizinikiwi.
|
||||
|
||||
// Copyright (C) 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.
|
||||
|
||||
//! An implementation of [`ElectionProvider`] that uses an `NposSolver` to do the election. As the
|
||||
//! name suggests, this is meant to be used onchain. Given how heavy the calculations are, please be
|
||||
//! careful when using it onchain.
|
||||
|
||||
use crate::{
|
||||
bounds::{ElectionBounds, ElectionBoundsBuilder},
|
||||
BoundedSupportsOf, Debug, ElectionDataProvider, ElectionProvider, InstantElectionProvider,
|
||||
NposSolver, PageIndex, VoterOf, WeightInfo,
|
||||
};
|
||||
use alloc::{collections::btree_map::BTreeMap, vec::Vec};
|
||||
use core::marker::PhantomData;
|
||||
use pezframe_support::{dispatch::DispatchClass, traits::Get};
|
||||
use pezframe_system::pezpallet_prelude::BlockNumberFor;
|
||||
use pezsp_npos_elections::{
|
||||
assignment_ratio_to_staked_normalized, to_supports, ElectionResult, VoteWeight,
|
||||
};
|
||||
|
||||
/// Errors of the on-chain election.
|
||||
#[derive(Eq, PartialEq, Debug, Clone)]
|
||||
pub enum Error {
|
||||
/// An internal error in the NPoS elections crate.
|
||||
NposElections(pezsp_npos_elections::Error),
|
||||
/// Errors from the data provider.
|
||||
DataProvider(&'static str),
|
||||
/// Results failed to meet the bounds.
|
||||
FailedToBound,
|
||||
}
|
||||
|
||||
impl From<pezsp_npos_elections::Error> for Error {
|
||||
fn from(e: pezsp_npos_elections::Error) -> Self {
|
||||
Error::NposElections(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// A simple on-chain implementation of the election provider trait.
|
||||
///
|
||||
/// This implements both `ElectionProvider` and `InstantElectionProvider`.
|
||||
///
|
||||
/// This type has some utilities to make it safe. Nonetheless, it should be used with utmost care. A
|
||||
/// thoughtful value must be set as [`Config::Bounds`] to ensure the size of the input is sensible.
|
||||
pub struct OnChainExecution<T: Config>(PhantomData<T>);
|
||||
|
||||
#[deprecated(note = "use OnChainExecution, which is bounded by default")]
|
||||
pub type BoundedExecution<T> = OnChainExecution<T>;
|
||||
|
||||
/// Configuration trait for an onchain election execution.
|
||||
pub trait Config {
|
||||
/// Whether to try and sort or not.
|
||||
///
|
||||
/// If `true`, the supports will be sorted by descending total support to meet the bounds. If
|
||||
/// `false`, `FailedToBound` error may be returned.
|
||||
type Sort: Get<bool>;
|
||||
|
||||
/// Needed for weight registration.
|
||||
type System: pezframe_system::Config;
|
||||
|
||||
/// `NposSolver` that should be used, an example would be `PhragMMS`.
|
||||
type Solver: NposSolver<
|
||||
AccountId = <Self::System as pezframe_system::Config>::AccountId,
|
||||
Error = pezsp_npos_elections::Error,
|
||||
>;
|
||||
|
||||
/// Maximum number of backers allowed per target.
|
||||
///
|
||||
/// If the bounds are exceeded due to the data returned by the data provider, the election will
|
||||
/// fail.
|
||||
type MaxBackersPerWinner: Get<u32>;
|
||||
|
||||
/// Maximum number of winners in an election.
|
||||
///
|
||||
/// If the bounds are exceeded due to the data returned by the data provider, the election will
|
||||
/// fail.
|
||||
type MaxWinnersPerPage: Get<u32>;
|
||||
|
||||
/// Something that provides the data for election.
|
||||
type DataProvider: ElectionDataProvider<
|
||||
AccountId = <Self::System as pezframe_system::Config>::AccountId,
|
||||
BlockNumber = pezframe_system::pezpallet_prelude::BlockNumberFor<Self::System>,
|
||||
>;
|
||||
|
||||
/// Weight information for extrinsics in this pallet.
|
||||
type WeightInfo: WeightInfo;
|
||||
|
||||
/// Elections bounds, to use when calling into [`Config::DataProvider`]. It might be overwritten
|
||||
/// in the `InstantElectionProvider` impl.
|
||||
type Bounds: Get<ElectionBounds>;
|
||||
}
|
||||
|
||||
impl<T: Config> OnChainExecution<T> {
|
||||
fn elect_with_snapshot(
|
||||
voters: Vec<VoterOf<T::DataProvider>>,
|
||||
targets: Vec<<T::System as pezframe_system::Config>::AccountId>,
|
||||
desired_targets: u32,
|
||||
) -> Result<BoundedSupportsOf<Self>, Error> {
|
||||
if (desired_targets > T::MaxWinnersPerPage::get()) && !T::Sort::get() {
|
||||
// early exit what will fail in the last line anyways.
|
||||
return Err(Error::FailedToBound);
|
||||
}
|
||||
|
||||
let voters_len = voters.len() as u32;
|
||||
let targets_len = targets.len() as u32;
|
||||
|
||||
let stake_map: BTreeMap<_, _> = voters
|
||||
.iter()
|
||||
.map(|(validator, vote_weight, _)| (validator.clone(), *vote_weight))
|
||||
.collect();
|
||||
|
||||
let stake_of = |w: &<T::System as pezframe_system::Config>::AccountId| -> VoteWeight {
|
||||
stake_map.get(w).cloned().unwrap_or_default()
|
||||
};
|
||||
|
||||
let ElectionResult { winners: _, assignments } =
|
||||
T::Solver::solve(desired_targets as usize, targets, voters).map_err(Error::from)?;
|
||||
|
||||
let staked = assignment_ratio_to_staked_normalized(assignments, &stake_of)?;
|
||||
|
||||
let weight = T::Solver::weight::<T::WeightInfo>(
|
||||
voters_len,
|
||||
targets_len,
|
||||
<T::DataProvider as ElectionDataProvider>::MaxVotesPerVoter::get(),
|
||||
);
|
||||
pezframe_system::Pallet::<T::System>::register_extra_weight_unchecked(
|
||||
weight,
|
||||
DispatchClass::Mandatory,
|
||||
);
|
||||
|
||||
let unbounded = to_supports(&staked);
|
||||
let bounded = if T::Sort::get() {
|
||||
let (bounded, _winners_removed, _backers_removed) =
|
||||
BoundedSupportsOf::<Self>::sorted_truncate_from(unbounded);
|
||||
bounded
|
||||
} else {
|
||||
unbounded.try_into().map_err(|_| Error::FailedToBound)?
|
||||
};
|
||||
Ok(bounded)
|
||||
}
|
||||
|
||||
fn elect_with(
|
||||
bounds: ElectionBounds,
|
||||
page: PageIndex,
|
||||
) -> Result<BoundedSupportsOf<Self>, Error> {
|
||||
let (voters, targets) = T::DataProvider::electing_voters(bounds.voters, page)
|
||||
.and_then(|voters| {
|
||||
Ok((voters, T::DataProvider::electable_targets(bounds.targets, page)?))
|
||||
})
|
||||
.map_err(Error::DataProvider)?;
|
||||
let desired_targets = T::DataProvider::desired_targets().map_err(Error::DataProvider)?;
|
||||
Self::elect_with_snapshot(voters, targets, desired_targets)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Config> InstantElectionProvider for OnChainExecution<T> {
|
||||
fn instant_elect(
|
||||
voters: Vec<VoterOf<T::DataProvider>>,
|
||||
targets: Vec<<T::System as pezframe_system::Config>::AccountId>,
|
||||
desired_targets: u32,
|
||||
) -> Result<BoundedSupportsOf<Self>, Self::Error> {
|
||||
Self::elect_with_snapshot(voters, targets, desired_targets)
|
||||
}
|
||||
|
||||
fn bother() -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Config> ElectionProvider for OnChainExecution<T> {
|
||||
type AccountId = <T::System as pezframe_system::Config>::AccountId;
|
||||
type BlockNumber = BlockNumberFor<T::System>;
|
||||
type Error = Error;
|
||||
type MaxWinnersPerPage = T::MaxWinnersPerPage;
|
||||
type MaxBackersPerWinnerFinal = T::MaxWinnersPerPage;
|
||||
type MaxBackersPerWinner = T::MaxBackersPerWinner;
|
||||
// can support any number of pages, as this is meant to be called "instantly". We don't care
|
||||
// about this value here.
|
||||
type Pages = pezsp_core::ConstU32<1>;
|
||||
type DataProvider = T::DataProvider;
|
||||
|
||||
fn elect(page: PageIndex) -> Result<BoundedSupportsOf<Self>, Self::Error> {
|
||||
let election_bounds = ElectionBoundsBuilder::from(T::Bounds::get()).build();
|
||||
Self::elect_with(election_bounds, page)
|
||||
}
|
||||
|
||||
fn start() -> Result<(), Self::Error> {
|
||||
// noop, we are always ready!
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn duration() -> Self::BlockNumber {
|
||||
pezsp_runtime::traits::Zero::zero()
|
||||
}
|
||||
|
||||
fn status() -> Result<bool, ()> {
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{ElectionProvider, PhragMMS, SequentialPhragmen};
|
||||
use pezframe_support::{assert_noop, derive_impl, parameter_types};
|
||||
use pezsp_io::TestExternalities;
|
||||
use pezsp_npos_elections::Support;
|
||||
use pezsp_runtime::Perbill;
|
||||
type AccountId = u64;
|
||||
type Nonce = u64;
|
||||
type BlockNumber = u64;
|
||||
|
||||
pub type Header = pezsp_runtime::generic::Header<BlockNumber, pezsp_runtime::traits::BlakeTwo256>;
|
||||
pub type UncheckedExtrinsic = pezsp_runtime::generic::UncheckedExtrinsic<AccountId, (), (), ()>;
|
||||
pub type Block = pezsp_runtime::generic::Block<Header, UncheckedExtrinsic>;
|
||||
|
||||
pezframe_support::construct_runtime!(
|
||||
pub enum Runtime {
|
||||
System: pezframe_system,
|
||||
}
|
||||
);
|
||||
|
||||
#[derive_impl(pezframe_system::config_preludes::TestDefaultConfig)]
|
||||
impl pezframe_system::Config for Runtime {
|
||||
type SS58Prefix = ();
|
||||
type BaseCallFilter = pezframe_support::traits::Everything;
|
||||
type RuntimeOrigin = RuntimeOrigin;
|
||||
type Nonce = Nonce;
|
||||
type RuntimeCall = RuntimeCall;
|
||||
type Hash = pezsp_core::H256;
|
||||
type Hashing = pezsp_runtime::traits::BlakeTwo256;
|
||||
type AccountId = AccountId;
|
||||
type Lookup = pezsp_runtime::traits::IdentityLookup<Self::AccountId>;
|
||||
type Block = Block;
|
||||
type RuntimeEvent = ();
|
||||
type BlockHashCount = ();
|
||||
type DbWeight = ();
|
||||
type BlockLength = ();
|
||||
type BlockWeights = ();
|
||||
type Version = ();
|
||||
type PalletInfo = PalletInfo;
|
||||
type AccountData = ();
|
||||
type OnNewAccount = ();
|
||||
type OnKilledAccount = ();
|
||||
type SystemWeightInfo = ();
|
||||
type OnSetCode = ();
|
||||
type MaxConsumers = pezframe_support::traits::ConstU32<16>;
|
||||
}
|
||||
|
||||
struct PhragmenParams;
|
||||
struct PhragMMSParams;
|
||||
|
||||
parameter_types! {
|
||||
pub static MaxWinnersPerPage: u32 = 10;
|
||||
pub static MaxBackersPerWinner: u32 = 20;
|
||||
pub static DesiredTargets: u32 = 2;
|
||||
pub static Sort: bool = false;
|
||||
pub static Bounds: ElectionBounds = ElectionBoundsBuilder::default().voters_count(600.into()).targets_count(400.into()).build();
|
||||
}
|
||||
|
||||
impl Config for PhragmenParams {
|
||||
type Sort = Sort;
|
||||
type System = Runtime;
|
||||
type Solver = SequentialPhragmen<AccountId, Perbill>;
|
||||
type DataProvider = mock_data_provider::DataProvider;
|
||||
type MaxWinnersPerPage = MaxWinnersPerPage;
|
||||
type MaxBackersPerWinner = MaxBackersPerWinner;
|
||||
type Bounds = Bounds;
|
||||
type WeightInfo = ();
|
||||
}
|
||||
|
||||
impl Config for PhragMMSParams {
|
||||
type Sort = Sort;
|
||||
type System = Runtime;
|
||||
type Solver = PhragMMS<AccountId, Perbill>;
|
||||
type DataProvider = mock_data_provider::DataProvider;
|
||||
type MaxWinnersPerPage = MaxWinnersPerPage;
|
||||
type MaxBackersPerWinner = MaxBackersPerWinner;
|
||||
type WeightInfo = ();
|
||||
type Bounds = Bounds;
|
||||
}
|
||||
|
||||
mod mock_data_provider {
|
||||
use super::*;
|
||||
use crate::{data_provider, DataProviderBounds, PageIndex, VoterOf};
|
||||
use pezframe_support::traits::ConstU32;
|
||||
use pezsp_runtime::bounded_vec;
|
||||
|
||||
pub struct DataProvider;
|
||||
impl ElectionDataProvider for DataProvider {
|
||||
type AccountId = AccountId;
|
||||
type BlockNumber = BlockNumber;
|
||||
type MaxVotesPerVoter = ConstU32<2>;
|
||||
fn electing_voters(
|
||||
_: DataProviderBounds,
|
||||
_page: PageIndex,
|
||||
) -> 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 electable_targets(
|
||||
_: DataProviderBounds,
|
||||
_page: PageIndex,
|
||||
) -> data_provider::Result<Vec<AccountId>> {
|
||||
Ok(vec![10, 20, 30])
|
||||
}
|
||||
|
||||
fn desired_targets() -> data_provider::Result<u32> {
|
||||
Ok(DesiredTargets::get())
|
||||
}
|
||||
|
||||
fn next_election_prediction(_: BlockNumber) -> BlockNumber {
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn onchain_seq_phragmen_works() {
|
||||
TestExternalities::new_empty().execute_with(|| {
|
||||
let expected_supports = vec![
|
||||
(
|
||||
10 as AccountId,
|
||||
Support { total: 25, voters: vec![(1 as AccountId, 10), (3, 15)] },
|
||||
),
|
||||
(30, Support { total: 35, voters: vec![(2, 20), (3, 15)] }),
|
||||
]
|
||||
.try_into()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
<OnChainExecution::<PhragmenParams> as ElectionProvider>::elect(0).unwrap(),
|
||||
expected_supports,
|
||||
);
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sorting_false_works() {
|
||||
TestExternalities::new_empty().execute_with(|| {
|
||||
// Default results would have 3 targets, but we allow for only 2.
|
||||
DesiredTargets::set(3);
|
||||
MaxWinnersPerPage::set(2);
|
||||
|
||||
assert_noop!(
|
||||
<OnChainExecution::<PhragmenParams> as ElectionProvider>::elect(0),
|
||||
Error::FailedToBound,
|
||||
);
|
||||
});
|
||||
|
||||
TestExternalities::new_empty().execute_with(|| {
|
||||
// Default results would have 2 backers per winner
|
||||
MaxBackersPerWinner::set(1);
|
||||
|
||||
assert_noop!(
|
||||
<OnChainExecution::<PhragmenParams> as ElectionProvider>::elect(0),
|
||||
Error::FailedToBound,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sorting_true_works_winners() {
|
||||
Sort::set(true);
|
||||
|
||||
TestExternalities::new_empty().execute_with(|| {
|
||||
let expected_supports =
|
||||
vec![(30, Support { total: 35, voters: vec![(2, 20), (3, 15)] })]
|
||||
.try_into()
|
||||
.unwrap();
|
||||
|
||||
// we want to allow 1 winner only, and allow sorting.
|
||||
MaxWinnersPerPage::set(1);
|
||||
|
||||
assert_eq!(
|
||||
<OnChainExecution::<PhragmenParams> as ElectionProvider>::elect(0).unwrap(),
|
||||
expected_supports,
|
||||
);
|
||||
});
|
||||
|
||||
MaxWinnersPerPage::set(10);
|
||||
|
||||
TestExternalities::new_empty().execute_with(|| {
|
||||
let expected_supports = vec![
|
||||
(30, Support { total: 20, voters: vec![(2, 20)] }),
|
||||
(10 as AccountId, Support { total: 15, voters: vec![(3 as AccountId, 15)] }),
|
||||
]
|
||||
.try_into()
|
||||
.unwrap();
|
||||
|
||||
// we want to allow 2 winners only but 1 backer each, and allow sorting.
|
||||
MaxBackersPerWinner::set(1);
|
||||
|
||||
assert_eq!(
|
||||
<OnChainExecution::<PhragmenParams> as ElectionProvider>::elect(0).unwrap(),
|
||||
expected_supports,
|
||||
);
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn onchain_phragmms_works() {
|
||||
TestExternalities::new_empty().execute_with(|| {
|
||||
assert_eq!(
|
||||
<OnChainExecution::<PhragMMSParams> as ElectionProvider>::elect(0).unwrap(),
|
||||
vec![
|
||||
(
|
||||
10 as AccountId,
|
||||
Support { total: 25, voters: vec![(1 as AccountId, 10), (3, 15)] }
|
||||
),
|
||||
(30, Support { total: 35, voters: vec![(2, 20), (3, 15)] })
|
||||
]
|
||||
.try_into()
|
||||
.unwrap()
|
||||
);
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,612 @@
|
||||
// This file is part of Bizinikiwi.
|
||||
|
||||
// Copyright (C) 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.
|
||||
|
||||
//! Tests for solution-type.
|
||||
|
||||
#![cfg(test)]
|
||||
use crate::{
|
||||
mock::*, BoundedSupport, BoundedSupports, IndexAssignment, NposSolution, TryFromOtherBounds,
|
||||
};
|
||||
use pezframe_support::traits::ConstU32;
|
||||
use rand::SeedableRng;
|
||||
use pezsp_npos_elections::{Support, Supports};
|
||||
|
||||
mod solution_type {
|
||||
use super::*;
|
||||
use codec::{Decode, Encode, MaxEncodedLen};
|
||||
// these need to come from the same dev-dependency `pezframe-election-provider-support`, not from
|
||||
// the crate.
|
||||
use crate::{generate_solution_type, Assignment, Error as NposError, NposSolution};
|
||||
use core::fmt::Debug;
|
||||
|
||||
#[allow(dead_code)]
|
||||
mod __private {
|
||||
// This is just to make sure that the solution can be generated in a scope without any
|
||||
// imports.
|
||||
use crate::generate_solution_type;
|
||||
generate_solution_type!(
|
||||
#[compact]
|
||||
struct InnerTestSolutionIsolated::<
|
||||
VoterIndex = u32,
|
||||
TargetIndex = u8,
|
||||
Accuracy = pezsp_runtime::Percent,
|
||||
MaxVoters = crate::tests::ConstU32::<20>,
|
||||
>(12)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn solution_struct_works_with_and_without_compact() {
|
||||
// we use u32 size to make sure compact is smaller.
|
||||
let without_compact = {
|
||||
generate_solution_type!(
|
||||
pub struct InnerTestSolution::<
|
||||
VoterIndex = u32,
|
||||
TargetIndex = u32,
|
||||
Accuracy = TestAccuracy,
|
||||
MaxVoters = ConstU32::<20>,
|
||||
>(16)
|
||||
);
|
||||
let solution = InnerTestSolution {
|
||||
votes1: vec![(2, 20), (4, 40)],
|
||||
votes2: vec![(1, [(10, p(80))], 11), (5, [(50, p(85))], 51)],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
solution.encode().len()
|
||||
};
|
||||
|
||||
let with_compact = {
|
||||
generate_solution_type!(
|
||||
#[compact]
|
||||
pub struct InnerTestSolutionCompact::<
|
||||
VoterIndex = u32,
|
||||
TargetIndex = u32,
|
||||
Accuracy = TestAccuracy,
|
||||
MaxVoters = ConstU32::<20>,
|
||||
>(16)
|
||||
);
|
||||
let compact = InnerTestSolutionCompact {
|
||||
votes1: vec![(2, 20), (4, 40)],
|
||||
votes2: vec![(1, [(10, p(80))], 11), (5, [(50, p(85))], 51)],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
compact.encode().len()
|
||||
};
|
||||
|
||||
assert!(with_compact < without_compact);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_assignment_fail_too_many_voters() {
|
||||
let rng = rand::rngs::SmallRng::seed_from_u64(1);
|
||||
|
||||
// This will produce 24 voters..
|
||||
let (voters, assignments, candidates) = generate_random_votes(10, 25, rng);
|
||||
let voter_index = make_voter_fn(&voters);
|
||||
let target_index = make_target_fn(&candidates);
|
||||
|
||||
// Limit the voters to 20..
|
||||
generate_solution_type!(
|
||||
pub struct InnerTestSolution::<
|
||||
VoterIndex = u32,
|
||||
TargetIndex = u16,
|
||||
Accuracy = TestAccuracy,
|
||||
MaxVoters = pezframe_support::traits::ConstU32::<20>,
|
||||
>(16)
|
||||
);
|
||||
|
||||
// 24 > 20, so this should fail.
|
||||
assert_eq!(
|
||||
InnerTestSolution::from_assignment(&assignments, &voter_index, &target_index)
|
||||
.unwrap_err(),
|
||||
NposError::TooManyVoters,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_encoded_len_too_small() {
|
||||
generate_solution_type!(
|
||||
pub struct InnerTestSolution::<
|
||||
VoterIndex = u32,
|
||||
TargetIndex = u32,
|
||||
Accuracy = TestAccuracy,
|
||||
MaxVoters = ConstU32::<1>,
|
||||
>(3)
|
||||
);
|
||||
let solution = InnerTestSolution {
|
||||
votes1: vec![(2, 20), (4, 40)],
|
||||
votes2: vec![(1, [(10, p(80))], 11), (5, [(50, p(85))], 51)],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// We actually have 4 voters, but the bound is 1 voter, so the implemented bound is too
|
||||
// small.
|
||||
assert!(solution.encode().len() > InnerTestSolution::max_encoded_len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_encoded_len_upper_bound() {
|
||||
generate_solution_type!(
|
||||
pub struct InnerTestSolution::<
|
||||
VoterIndex = u32,
|
||||
TargetIndex = u32,
|
||||
Accuracy = TestAccuracy,
|
||||
MaxVoters = ConstU32::<4>,
|
||||
>(3)
|
||||
);
|
||||
let solution = InnerTestSolution {
|
||||
votes1: vec![(2, 20), (4, 40)],
|
||||
votes2: vec![(1, [(10, p(80))], 11), (5, [(50, p(85))], 51)],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// We actually have 4 voters, and the bound is 4 voters, so the implemented bound should be
|
||||
// larger than the encoded len.
|
||||
assert!(solution.encode().len() < InnerTestSolution::max_encoded_len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_encoded_len_exact() {
|
||||
generate_solution_type!(
|
||||
pub struct InnerTestSolution::<
|
||||
VoterIndex = u32,
|
||||
TargetIndex = u32,
|
||||
Accuracy = TestAccuracy,
|
||||
MaxVoters = ConstU32::<4>,
|
||||
>(3)
|
||||
);
|
||||
let solution = InnerTestSolution {
|
||||
votes1: vec![],
|
||||
votes2: vec![],
|
||||
votes3: vec![
|
||||
(1, [(10, p(50)), (11, p(20))], 12),
|
||||
(2, [(20, p(50)), (21, p(20))], 22),
|
||||
(3, [(30, p(50)), (31, p(20))], 32),
|
||||
(4, [(40, p(50)), (41, p(20))], 42),
|
||||
],
|
||||
};
|
||||
|
||||
// We have 4 voters, the bound is 4 voters, and all the voters voted for 3 targets, which is
|
||||
// the max number of targets. This should represent the upper bound that `max_encoded_len`
|
||||
// represents.
|
||||
assert_eq!(solution.encode().len(), InnerTestSolution::max_encoded_len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn solution_struct_is_codec() {
|
||||
let solution = TestSolution {
|
||||
votes1: vec![(2, 20), (4, 40)],
|
||||
votes2: vec![(1, [(10, p(80))], 11), (5, [(50, p(85))], 51)],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let encoded = solution.encode();
|
||||
|
||||
assert_eq!(solution, Decode::decode(&mut &encoded[..]).unwrap());
|
||||
assert_eq!(solution.voter_count(), 4);
|
||||
assert_eq!(solution.edge_count(), 2 + 4);
|
||||
assert_eq!(solution.unique_targets(), vec![10, 11, 20, 40, 50, 51]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_voter_works() {
|
||||
let mut solution = TestSolution {
|
||||
votes1: vec![(0, 2), (1, 6)],
|
||||
votes2: vec![(2, [(0, p(80))], 1), (3, [(7, p(85))], 8)],
|
||||
votes3: vec![(4, [(3, p(50)), (4, p(25))], 5)],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(!solution.remove_voter(11));
|
||||
assert!(solution.remove_voter(2));
|
||||
assert_eq!(
|
||||
solution,
|
||||
TestSolution {
|
||||
votes1: vec![(0, 2), (1, 6)],
|
||||
votes2: vec![(3, [(7, p(85))], 8)],
|
||||
votes3: vec![(4, [(3, p(50)), (4, p(25))], 5,)],
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
assert!(solution.remove_voter(4));
|
||||
assert_eq!(
|
||||
solution,
|
||||
TestSolution {
|
||||
votes1: vec![(0, 2), (1, 6)],
|
||||
votes2: vec![(3, [(7, p(85))], 8)],
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
assert!(solution.remove_voter(1));
|
||||
assert_eq!(
|
||||
solution,
|
||||
TestSolution {
|
||||
votes1: vec![(0, 2)],
|
||||
votes2: vec![(3, [(7, p(85))], 8),],
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prevents_target_duplicate_into_assignment() {
|
||||
let voter_at = |a: u32| -> Option<AccountId> { Some(a as AccountId) };
|
||||
let target_at = |a: u16| -> Option<AccountId> { Some(a as AccountId) };
|
||||
|
||||
// case 1: duplicate target in votes2.
|
||||
let solution = TestSolution { votes2: vec![(0, [(1, p(50))], 1)], ..Default::default() };
|
||||
assert_eq!(
|
||||
solution.into_assignment(&voter_at, &target_at).unwrap_err(),
|
||||
NposError::DuplicateTarget,
|
||||
);
|
||||
|
||||
// case 2: duplicate target in votes3.
|
||||
let solution =
|
||||
TestSolution { votes3: vec![(0, [(1, p(25)), (2, p(50))], 1)], ..Default::default() };
|
||||
assert_eq!(
|
||||
solution.into_assignment(&voter_at, &target_at).unwrap_err(),
|
||||
NposError::DuplicateTarget,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prevents_voter_duplicate_into_assignment() {
|
||||
let voter_at = |a: u32| -> Option<AccountId> { Some(a as AccountId) };
|
||||
let target_at = |a: u16| -> Option<AccountId> { Some(a as AccountId) };
|
||||
|
||||
// case 1: there is a duplicate among two different fields
|
||||
let solution = TestSolution {
|
||||
// voter index 0 is present here
|
||||
votes1: vec![(0, 0), (1, 0)],
|
||||
// voter index 0 is also present here
|
||||
votes2: vec![(0, [(1, p(50))], 2)],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
solution.into_assignment(&voter_at, &target_at).unwrap_err(),
|
||||
NposError::DuplicateVoter,
|
||||
);
|
||||
|
||||
// case 2: there is a duplicate in the same field
|
||||
let solution = TestSolution { votes1: vec![(0, 0), (0, 1)], ..Default::default() };
|
||||
assert_eq!(
|
||||
solution.into_assignment(&voter_at, &target_at).unwrap_err(),
|
||||
NposError::DuplicateVoter,
|
||||
);
|
||||
|
||||
// case 2.1: there is a duplicate in the same fieild, a bit more complex
|
||||
let solution = TestSolution {
|
||||
votes1: vec![(0, 0)],
|
||||
votes2: vec![(1, [(1, p(50))], 2), (1, [(3, p(50))], 4)],
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
solution.into_assignment(&voter_at, &target_at).unwrap_err(),
|
||||
NposError::DuplicateVoter,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_and_into_assignment_works() {
|
||||
let voters = vec![2 as AccountId, 4, 1, 5, 3];
|
||||
let targets = vec![
|
||||
10 as AccountId,
|
||||
11,
|
||||
20, // 2
|
||||
30,
|
||||
31, // 4
|
||||
32,
|
||||
40, // 6
|
||||
50,
|
||||
51, // 8
|
||||
];
|
||||
|
||||
let assignments = vec![
|
||||
Assignment { who: 2 as AccountId, distribution: vec![(20u64, p(100))] },
|
||||
Assignment { who: 4, distribution: vec![(40, p(100))] },
|
||||
Assignment { who: 1, distribution: vec![(10, p(80)), (11, p(20))] },
|
||||
Assignment { who: 5, distribution: vec![(50, p(85)), (51, p(15))] },
|
||||
Assignment { who: 3, distribution: vec![(30, p(50)), (31, p(25)), (32, p(25))] },
|
||||
];
|
||||
|
||||
let voter_index = |a: &AccountId| -> Option<u32> {
|
||||
voters.iter().position(|x| x == a).map(TryInto::try_into).unwrap().ok()
|
||||
};
|
||||
let target_index = |a: &AccountId| -> Option<u16> {
|
||||
targets.iter().position(|x| x == a).map(TryInto::try_into).unwrap().ok()
|
||||
};
|
||||
|
||||
let solution =
|
||||
TestSolution::from_assignment(&assignments, voter_index, target_index).unwrap();
|
||||
|
||||
// basically number of assignments that it is encoding.
|
||||
assert_eq!(solution.voter_count(), assignments.len());
|
||||
assert_eq!(
|
||||
solution.edge_count(),
|
||||
assignments.iter().fold(0, |a, b| a + b.distribution.len()),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
solution,
|
||||
TestSolution {
|
||||
votes1: vec![(0, 2), (1, 6)],
|
||||
votes2: vec![(2, [(0, p(80))], 1), (3, [(7, p(85))], 8)],
|
||||
votes3: vec![(4, [(3, p(50)), (4, p(25))], 5)],
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
|
||||
assert_eq!(solution.unique_targets(), vec![0, 1, 2, 3, 4, 5, 6, 7, 8]);
|
||||
|
||||
let voter_at = |a: u32| -> Option<AccountId> {
|
||||
voters.get(<u32 as TryInto<usize>>::try_into(a).unwrap()).cloned()
|
||||
};
|
||||
let target_at = |a: u16| -> Option<AccountId> {
|
||||
targets.get(<u16 as TryInto<usize>>::try_into(a).unwrap()).cloned()
|
||||
};
|
||||
|
||||
assert_eq!(solution.into_assignment(voter_at, target_at).unwrap(), assignments);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unique_targets_len_edge_count_works() {
|
||||
// we don't really care about voters here so all duplicates. This is not invalid per se.
|
||||
let solution = TestSolution {
|
||||
votes1: vec![(99, 1), (99, 2)],
|
||||
votes2: vec![(99, [(3, p(10))], 7), (99, [(4, p(10))], 8)],
|
||||
votes3: vec![(99, [(11, p(10)), (12, p(10))], 13)],
|
||||
// ensure the last one is also counted.
|
||||
votes16: vec![(
|
||||
99,
|
||||
[
|
||||
(66, p(10)),
|
||||
(66, p(10)),
|
||||
(66, p(10)),
|
||||
(66, p(10)),
|
||||
(66, p(10)),
|
||||
(66, p(10)),
|
||||
(66, p(10)),
|
||||
(66, p(10)),
|
||||
(66, p(10)),
|
||||
(66, p(10)),
|
||||
(66, p(10)),
|
||||
(66, p(10)),
|
||||
(66, p(10)),
|
||||
(66, p(10)),
|
||||
(66, p(10)),
|
||||
],
|
||||
67,
|
||||
)],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert_eq!(solution.unique_targets(), vec![1, 2, 3, 4, 7, 8, 11, 12, 13, 66, 67]);
|
||||
assert_eq!(solution.edge_count(), 2 + (2 * 2) + 3 + 16);
|
||||
assert_eq!(solution.voter_count(), 6);
|
||||
|
||||
// this one has some duplicates.
|
||||
let solution = TestSolution {
|
||||
votes1: vec![(99, 1), (99, 1)],
|
||||
votes2: vec![(99, [(3, p(10))], 7), (99, [(4, p(10))], 8)],
|
||||
votes3: vec![(99, [(11, p(10)), (11, p(10))], 13)],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert_eq!(solution.unique_targets(), vec![1, 3, 4, 7, 8, 11, 13]);
|
||||
assert_eq!(solution.edge_count(), 2 + (2 * 2) + 3);
|
||||
assert_eq!(solution.voter_count(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn solution_into_assignment_must_report_overflow() {
|
||||
// in votes2
|
||||
let solution = TestSolution {
|
||||
votes1: Default::default(),
|
||||
votes2: vec![(0, [(1, p(100))], 2)],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let voter_at = |a: u32| -> Option<AccountId> { Some(a as AccountId) };
|
||||
let target_at = |a: u16| -> Option<AccountId> { Some(a as AccountId) };
|
||||
|
||||
assert_eq!(
|
||||
solution.into_assignment(&voter_at, &target_at).unwrap_err(),
|
||||
NposError::SolutionWeightOverflow,
|
||||
);
|
||||
|
||||
// in votes3 onwards
|
||||
let solution = TestSolution {
|
||||
votes1: Default::default(),
|
||||
votes2: Default::default(),
|
||||
votes3: vec![(0, [(1, p(70)), (2, p(80))], 3)],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
solution.into_assignment(&voter_at, &target_at).unwrap_err(),
|
||||
NposError::SolutionWeightOverflow,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_count_overflow_is_detected() {
|
||||
let voter_index = |a: &AccountId| -> Option<u32> { Some(*a as u32) };
|
||||
let target_index = |a: &AccountId| -> Option<u16> { Some(*a as u16) };
|
||||
|
||||
let assignments = vec![Assignment {
|
||||
who: 1 as AccountId,
|
||||
distribution: (10..27).map(|i| (i as AccountId, p(i as u8))).collect::<Vec<_>>(),
|
||||
}];
|
||||
|
||||
let solution = TestSolution::from_assignment(&assignments, voter_index, target_index);
|
||||
assert_eq!(solution.unwrap_err(), NposError::SolutionTargetOverflow);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_target_count_is_ignored() {
|
||||
let voters = vec![1 as AccountId, 2];
|
||||
let targets = vec![10 as AccountId, 11];
|
||||
|
||||
let assignments = vec![
|
||||
Assignment { who: 1 as AccountId, distribution: vec![(10, p(50)), (11, p(50))] },
|
||||
Assignment { who: 2, distribution: vec![] },
|
||||
];
|
||||
|
||||
let voter_index = |a: &AccountId| -> Option<u32> {
|
||||
voters.iter().position(|x| x == a).map(TryInto::try_into).unwrap().ok()
|
||||
};
|
||||
let target_index = |a: &AccountId| -> Option<u16> {
|
||||
targets.iter().position(|x| x == a).map(TryInto::try_into).unwrap().ok()
|
||||
};
|
||||
|
||||
let solution =
|
||||
TestSolution::from_assignment(&assignments, voter_index, target_index).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
solution,
|
||||
TestSolution {
|
||||
votes1: Default::default(),
|
||||
votes2: vec![(0, [(0, p(50))], 1)],
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_assignments_generate_same_solution_as_plain_assignments() {
|
||||
let rng = rand::rngs::SmallRng::seed_from_u64(0);
|
||||
|
||||
let (voters, assignments, candidates) = generate_random_votes(1000, 2500, rng);
|
||||
let voter_index = make_voter_fn(&voters);
|
||||
let target_index = make_target_fn(&candidates);
|
||||
|
||||
let solution =
|
||||
TestSolution::from_assignment(&assignments, &voter_index, &target_index).unwrap();
|
||||
|
||||
let index_assignments = assignments
|
||||
.into_iter()
|
||||
.map(|assignment| IndexAssignment::new(&assignment, &voter_index, &target_index))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.unwrap();
|
||||
|
||||
let index_compact = index_assignments.as_slice().try_into().unwrap();
|
||||
|
||||
assert_eq!(solution, index_compact);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn try_from_other_bounds_works() {
|
||||
let bounded: BoundedSupports<u32, ConstU32<2>, ConstU32<2>> = vec![
|
||||
(1, Support { total: 100, voters: vec![(1, 50), (2, 50)] }),
|
||||
(2, Support { total: 100, voters: vec![(1, 50), (2, 50)] }),
|
||||
]
|
||||
.try_into()
|
||||
.unwrap();
|
||||
|
||||
// either of the bounds are smaller, won't convert
|
||||
assert!(BoundedSupports::<u32, ConstU32<1>, ConstU32<2>>::try_from_other_bounds(
|
||||
bounded.clone()
|
||||
)
|
||||
.is_err());
|
||||
assert!(BoundedSupports::<u32, ConstU32<2>, ConstU32<1>>::try_from_other_bounds(
|
||||
bounded.clone()
|
||||
)
|
||||
.is_err());
|
||||
|
||||
// bounds are equal, will convert
|
||||
assert!(BoundedSupports::<u32, ConstU32<2>, ConstU32<2>>::try_from_other_bounds(
|
||||
bounded.clone()
|
||||
)
|
||||
.is_ok());
|
||||
|
||||
// bounds are larger, will convert
|
||||
assert!(BoundedSupports::<u32, ConstU32<3>, ConstU32<2>>::try_from_other_bounds(
|
||||
bounded.clone()
|
||||
)
|
||||
.is_ok());
|
||||
assert!(BoundedSupports::<u32, ConstU32<3>, ConstU32<3>>::try_from_other_bounds(
|
||||
bounded.clone()
|
||||
)
|
||||
.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn support_sorted_truncate_from_works() {
|
||||
let support = Support { total: 100, voters: vec![(1, 50), (2, 30), (3, 20)] };
|
||||
|
||||
let (bounded, backers_removed) =
|
||||
BoundedSupport::<u32, ConstU32<1>>::sorted_truncate_from(support.clone());
|
||||
assert_eq!(bounded, Support { total: 50, voters: vec![(1, 50)] }.try_into().unwrap());
|
||||
assert_eq!(backers_removed, 2);
|
||||
|
||||
let (bounded, backers_removed) =
|
||||
BoundedSupport::<u32, ConstU32<2>>::sorted_truncate_from(support.clone());
|
||||
assert_eq!(bounded, Support { total: 80, voters: vec![(1, 50), (2, 30)] }.try_into().unwrap());
|
||||
assert_eq!(backers_removed, 1);
|
||||
|
||||
let (bounded, backers_removed) =
|
||||
BoundedSupport::<u32, ConstU32<3>>::sorted_truncate_from(support.clone());
|
||||
assert_eq!(
|
||||
bounded,
|
||||
Support { total: 100, voters: vec![(1, 50), (2, 30), (3, 20)] }
|
||||
.try_into()
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(backers_removed, 0);
|
||||
|
||||
let (bounded, backers_removed) =
|
||||
BoundedSupport::<u32, ConstU32<4>>::sorted_truncate_from(support.clone());
|
||||
assert_eq!(
|
||||
bounded,
|
||||
Support { total: 100, voters: vec![(1, 50), (2, 30), (3, 20)] }
|
||||
.try_into()
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(backers_removed, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supports_sorted_truncate_from_works() {
|
||||
let supports: Supports<u32> = vec![
|
||||
(1, Support { total: 303, voters: vec![(100, 100), (101, 101), (102, 102)] }),
|
||||
(2, Support { total: 201, voters: vec![(100, 100), (101, 101)] }),
|
||||
(3, Support { total: 406, voters: vec![(100, 100), (101, 101), (102, 102), (103, 103)] }),
|
||||
];
|
||||
|
||||
let (bounded, winners_removed, backers_removed) =
|
||||
BoundedSupports::<u32, ConstU32<2>, ConstU32<2>>::sorted_truncate_from(supports);
|
||||
// we trim 2 as it has least total support, and trim backers based on stake.
|
||||
assert_eq!(
|
||||
bounded
|
||||
.clone()
|
||||
.into_iter()
|
||||
.map(|(k, v)| (k, Support { total: v.total, voters: v.voters.into_inner() }))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
(3, Support { total: 205, voters: vec![(103, 103), (102, 102)] }),
|
||||
(1, Support { total: 203, voters: vec![(102, 102), (101, 101)] })
|
||||
]
|
||||
);
|
||||
assert_eq!(winners_removed, 1);
|
||||
assert_eq!(backers_removed, 3);
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
// This file is part of Bizinikiwi.
|
||||
|
||||
// Copyright (C) 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
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Traits for the election operations.
|
||||
|
||||
use crate::{Assignment, IdentifierT, IndexAssignmentOf, PerThing128, VoteWeight};
|
||||
use alloc::vec::Vec;
|
||||
use codec::Encode;
|
||||
use core::fmt::Debug;
|
||||
use scale_info::TypeInfo;
|
||||
use pezsp_arithmetic::traits::{Bounded, UniqueSaturatedInto};
|
||||
use pezsp_npos_elections::{ElectionScore, Error, EvaluateSupport};
|
||||
|
||||
/// An opaque index-based, NPoS solution type.
|
||||
pub trait NposSolution
|
||||
where
|
||||
Self: Sized + for<'a> TryFrom<&'a [IndexAssignmentOf<Self>], Error = Error>,
|
||||
{
|
||||
/// The maximum number of votes that are allowed.
|
||||
const LIMIT: usize;
|
||||
|
||||
/// The voter type. Needs to be an index (convert to usize).
|
||||
type VoterIndex: UniqueSaturatedInto<usize>
|
||||
+ TryInto<usize>
|
||||
+ TryFrom<usize>
|
||||
+ Debug
|
||||
+ Copy
|
||||
+ Clone
|
||||
+ Bounded
|
||||
+ Encode
|
||||
+ Ord
|
||||
+ PartialOrd
|
||||
+ TypeInfo;
|
||||
|
||||
/// The target type. Needs to be an index (convert to usize).
|
||||
type TargetIndex: UniqueSaturatedInto<usize>
|
||||
+ TryInto<usize>
|
||||
+ TryFrom<usize>
|
||||
+ Debug
|
||||
+ Copy
|
||||
+ Clone
|
||||
+ Bounded
|
||||
+ Encode
|
||||
+ Ord
|
||||
+ PartialOrd
|
||||
+ TypeInfo;
|
||||
|
||||
/// The weight/accuracy type of each vote.
|
||||
type Accuracy: PerThing128;
|
||||
|
||||
/// Get the length of all the voters that this type is encoding.
|
||||
///
|
||||
/// This is basically the same as the number of assignments, or number of active voters.
|
||||
fn voter_count(&self) -> usize;
|
||||
|
||||
/// Get the total count of edges.
|
||||
///
|
||||
/// This is effectively in the range of {[`Self::voter_count`], [`Self::voter_count`] *
|
||||
/// [`Self::LIMIT`]}.
|
||||
fn edge_count(&self) -> usize;
|
||||
|
||||
/// Get the number of unique targets in the whole struct.
|
||||
///
|
||||
/// Once presented with a list of winners, this set and the set of winners must be
|
||||
/// equal.
|
||||
fn unique_targets(&self) -> Vec<Self::TargetIndex>;
|
||||
|
||||
/// Get the average edge count.
|
||||
fn average_edge_count(&self) -> usize {
|
||||
self.edge_count().checked_div(self.voter_count()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Compute the score of this solution type.
|
||||
fn score<A, FS>(
|
||||
self,
|
||||
stake_of: FS,
|
||||
voter_at: impl Fn(Self::VoterIndex) -> Option<A>,
|
||||
target_at: impl Fn(Self::TargetIndex) -> Option<A>,
|
||||
) -> Result<ElectionScore, Error>
|
||||
where
|
||||
for<'r> FS: Fn(&'r A) -> VoteWeight,
|
||||
A: IdentifierT,
|
||||
{
|
||||
let ratio = self.into_assignment(voter_at, target_at)?;
|
||||
let staked =
|
||||
pezsp_npos_elections::helpers::assignment_ratio_to_staked_normalized(ratio, stake_of)?;
|
||||
let supports = pezsp_npos_elections::to_supports(&staked);
|
||||
Ok(supports.evaluate())
|
||||
}
|
||||
|
||||
/// Remove a certain voter.
|
||||
///
|
||||
/// This will only search until the first instance of `to_remove`, and return true. If
|
||||
/// no instance is found (no-op), then it returns false.
|
||||
///
|
||||
/// In other words, if this return true, exactly **one** element must have been removed self.
|
||||
fn remove_voter(&mut self, to_remove: Self::VoterIndex) -> bool;
|
||||
|
||||
/// Build self from a list of assignments.
|
||||
fn from_assignment<FV, FT, A>(
|
||||
assignments: &[Assignment<A, Self::Accuracy>],
|
||||
voter_index: FV,
|
||||
target_index: FT,
|
||||
) -> Result<Self, Error>
|
||||
where
|
||||
A: IdentifierT,
|
||||
for<'r> FV: Fn(&'r A) -> Option<Self::VoterIndex>,
|
||||
for<'r> FT: Fn(&'r A) -> Option<Self::TargetIndex>;
|
||||
|
||||
/// Convert self into a `Vec<Assignment<A, Self::Accuracy>>`
|
||||
fn into_assignment<A: IdentifierT>(
|
||||
self,
|
||||
voter_at: impl Fn(Self::VoterIndex) -> Option<A>,
|
||||
target_at: impl Fn(Self::TargetIndex) -> Option<A>,
|
||||
) -> Result<Vec<Assignment<A, Self::Accuracy>>, Error>;
|
||||
|
||||
/// Sort self by the means of the given function.
|
||||
///
|
||||
/// This might be helpful to allow for easier trimming.
|
||||
fn sort<F>(&mut self, voter_stake: F)
|
||||
where
|
||||
F: FnMut(&Self::VoterIndex) -> VoteWeight;
|
||||
|
||||
/// Remove the least staked voter.
|
||||
///
|
||||
/// This is ONLY sensible to do if [`Self::sort`] has been called on the struct at least once.
|
||||
fn remove_weakest_sorted<F>(&mut self, voter_stake: F) -> Option<Self::VoterIndex>
|
||||
where
|
||||
F: FnMut(&Self::VoterIndex) -> VoteWeight;
|
||||
|
||||
/// Make this solution corrupt. This should set the index of a voter to `Bounded::max_value()`.
|
||||
///
|
||||
/// Obviously, this is only useful for testing.
|
||||
fn corrupt(&mut self);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
// This file is part of Bizinikiwi.
|
||||
|
||||
// Copyright (C) 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.
|
||||
|
||||
//! Autogenerated weights for pezpallet_election_provider_support_benchmarking
|
||||
//!
|
||||
//! THIS FILE WAS AUTO-GENERATED USING THE BIZINIKIWI BENCHMARK CLI VERSION 4.0.0-dev
|
||||
//! DATE: 2022-04-23, STEPS: `1`, REPEAT: 1, LOW RANGE: `[]`, HIGH RANGE: `[]`
|
||||
//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024
|
||||
|
||||
// Executed Command:
|
||||
// target/release/bizinikiwi
|
||||
// benchmark
|
||||
// pallet
|
||||
// --chain=dev
|
||||
// --steps=1
|
||||
// --repeat=1
|
||||
// --pallet=pezpallet_election_provider_support_benchmarking
|
||||
// --extrinsic=*
|
||||
// --execution=wasm
|
||||
// --wasm-execution=compiled
|
||||
// --heap-pages=4096
|
||||
// --output=frame/election-provider-support/src/weights.rs
|
||||
// --template=./.maintain/frame-weight-template.hbs
|
||||
|
||||
#![cfg_attr(rustfmt, rustfmt_skip)]
|
||||
#![allow(unused_parens)]
|
||||
#![allow(unused_imports)]
|
||||
|
||||
use pezframe_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
|
||||
use core::marker::PhantomData;
|
||||
|
||||
/// Weight functions needed for pezpallet_election_provider_support_benchmarking.
|
||||
pub trait WeightInfo {
|
||||
fn phragmen(v: u32, t: u32, d: u32, ) -> Weight;
|
||||
fn phragmms(v: u32, t: u32, d: u32, ) -> Weight;
|
||||
}
|
||||
|
||||
/// Weights for pezpallet_election_provider_support_benchmarking using the Bizinikiwi node and recommended hardware.
|
||||
pub struct BizinikiwiWeight<T>(PhantomData<T>);
|
||||
impl<T: pezframe_system::Config> WeightInfo for BizinikiwiWeight<T> {
|
||||
fn phragmen(v: u32, t: u32, d: u32, ) -> Weight {
|
||||
Weight::from_parts(0 as u64, 0)
|
||||
// Standard Error: 667_000
|
||||
.saturating_add(Weight::from_parts(32_973_000 as u64, 0).saturating_mul(v as u64))
|
||||
// Standard Error: 1_334_000
|
||||
.saturating_add(Weight::from_parts(1_334_000 as u64, 0).saturating_mul(t as u64))
|
||||
// Standard Error: 60_644_000
|
||||
.saturating_add(Weight::from_parts(2_636_364_000 as u64, 0).saturating_mul(d as u64))
|
||||
}
|
||||
fn phragmms(v: u32, t: u32, d: u32, ) -> Weight {
|
||||
Weight::from_parts(0 as u64, 0)
|
||||
// Standard Error: 73_000
|
||||
.saturating_add(Weight::from_parts(21_073_000 as u64, 0).saturating_mul(v as u64))
|
||||
// Standard Error: 146_000
|
||||
.saturating_add(Weight::from_parts(65_000 as u64, 0).saturating_mul(t as u64))
|
||||
// Standard Error: 6_649_000
|
||||
.saturating_add(Weight::from_parts(1_711_424_000 as u64, 0).saturating_mul(d as u64))
|
||||
}
|
||||
}
|
||||
|
||||
// For backwards compatibility and tests
|
||||
impl WeightInfo for () {
|
||||
fn phragmen(v: u32, t: u32, d: u32, ) -> Weight {
|
||||
Weight::from_parts(0 as u64, 0)
|
||||
// Standard Error: 667_000
|
||||
.saturating_add(Weight::from_parts(32_973_000 as u64, 0).saturating_mul(v as u64))
|
||||
// Standard Error: 1_334_000
|
||||
.saturating_add(Weight::from_parts(1_334_000 as u64, 0).saturating_mul(t as u64))
|
||||
// Standard Error: 60_644_000
|
||||
.saturating_add(Weight::from_parts(2_636_364_000 as u64, 0).saturating_mul(d as u64))
|
||||
}
|
||||
fn phragmms(v: u32, t: u32, d: u32, ) -> Weight {
|
||||
Weight::from_parts(0 as u64, 0)
|
||||
// Standard Error: 73_000
|
||||
.saturating_add(Weight::from_parts(21_073_000 as u64, 0).saturating_mul(v as u64))
|
||||
// Standard Error: 146_000
|
||||
.saturating_add(Weight::from_parts(65_000 as u64, 0).saturating_mul(t as u64))
|
||||
// Standard Error: 6_649_000
|
||||
.saturating_add(Weight::from_parts(1_711_424_000 as u64, 0).saturating_mul(d as u64))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user