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:
2025-12-14 00:04:10 +03:00
parent 286de54384
commit 1c0e57d984
9084 changed files with 997839 additions and 997557 deletions
@@ -0,0 +1,62 @@
[package]
name = "pezframe-election-provider-support"
version = "28.0.0"
authors.workspace = true
edition.workspace = true
license = "Apache-2.0"
homepage.workspace = true
repository.workspace = true
description = "election provider supporting traits"
[lints]
workspace = true
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { features = ["derive"], workspace = true }
pezframe-election-provider-solution-type = { workspace = true, default-features = true }
pezframe-support = { workspace = true }
pezframe-system = { workspace = true }
scale-info = { features = ["derive"], workspace = true }
pezsp-arithmetic = { workspace = true }
pezsp-core = { workspace = true }
pezsp-npos-elections = { workspace = true }
pezsp-runtime = { workspace = true }
pezsp-std = { workspace = true }
[dev-dependencies]
rand = { features = ["small_rng"], workspace = true, default-features = true }
pezsp-io = { workspace = true, default-features = true }
pezsp-npos-elections = { workspace = true, default-features = true }
[features]
default = ["std"]
fuzz = ["default"]
std = [
"codec/std",
"pezframe-support/std",
"pezframe-system/std",
"scale-info/std",
"pezsp-arithmetic/std",
"pezsp-core/std",
"pezsp-io/std",
"pezsp-npos-elections/std",
"pezsp-runtime/std",
"pezsp-std/std",
]
runtime-benchmarks = [
"pezframe-election-provider-solution-type/runtime-benchmarks",
"pezframe-support/runtime-benchmarks",
"pezframe-system/runtime-benchmarks",
"pezsp-io/runtime-benchmarks",
"pezsp-npos-elections/runtime-benchmarks",
"pezsp-runtime/runtime-benchmarks",
]
try-runtime = [
"pezframe-support/try-runtime",
"pezframe-system/try-runtime",
"pezsp-runtime/try-runtime",
]
@@ -0,0 +1,41 @@
[package]
name = "pezpallet-election-provider-support-benchmarking"
version = "27.0.0"
authors.workspace = true
edition.workspace = true
license = "Apache-2.0"
homepage.workspace = true
repository.workspace = true
description = "Benchmarking for election provider support onchain config trait"
[lints]
workspace = true
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
codec = { features = ["derive"], workspace = true }
pezframe-benchmarking = { optional = true, workspace = true }
pezframe-election-provider-support = { workspace = true }
pezframe-system = { workspace = true }
pezsp-npos-elections = { workspace = true }
pezsp-runtime = { workspace = true }
[features]
default = ["std"]
std = [
"codec/std",
"pezframe-benchmarking?/std",
"pezframe-election-provider-support/std",
"pezframe-system/std",
"pezsp-npos-elections/std",
"pezsp-runtime/std",
]
runtime-benchmarks = [
"pezframe-benchmarking/runtime-benchmarks",
"pezframe-election-provider-support/runtime-benchmarks",
"pezframe-system/runtime-benchmarks",
"pezsp-npos-elections/runtime-benchmarks",
"pezsp-runtime/runtime-benchmarks",
]
@@ -0,0 +1,102 @@
// 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.
//! Election provider support pallet benchmarking.
//! This is separated into its own crate to avoid bloating the size of the runtime.
use alloc::vec::Vec;
use codec::Decode;
use pezframe_benchmarking::v2::*;
use pezframe_election_provider_support::{NposSolver, PhragMMS, SequentialPhragmen};
use pezsp_runtime::Perbill;
const VOTERS: [u32; 2] = [1_000, 2_000];
const TARGETS: [u32; 2] = [500, 1_000];
const VOTES_PER_VOTER: [u32; 2] = [5, 16];
const SEED: u32 = 999;
pub trait Config: pezframe_system::Config {}
pub struct Pallet<T: Config>(pezframe_system::Pallet<T>);
fn set_up_voters_targets<AccountId: Decode + Clone>(
voters_len: u32,
targets_len: u32,
degree: usize,
) -> (Vec<(AccountId, u64, impl Clone + IntoIterator<Item = AccountId>)>, Vec<AccountId>) {
// fill targets.
let mut targets = (0..targets_len)
.map(|i| pezframe_benchmarking::account::<AccountId>("Target", i, SEED))
.collect::<Vec<_>>();
assert!(targets.len() > degree, "we should always have enough voters to fill");
targets.truncate(degree);
// fill voters.
let voters = (0..voters_len)
.map(|i| {
let voter = pezframe_benchmarking::account::<AccountId>("Voter", i, SEED);
(voter, 1_000, targets.clone())
})
.collect::<Vec<_>>();
(voters, targets)
}
#[benchmarks]
mod benchmarks {
use super::*;
#[benchmark]
fn phragmen(
// Number of votes in snapshot.
v: Linear<{ VOTERS[0] }, { VOTERS[1] }>,
// Number of targets in snapshot.
t: Linear<{ TARGETS[0] }, { TARGETS[1] }>,
// Number of votes per voter (ie the degree).
d: Linear<{ VOTES_PER_VOTER[0] }, { VOTES_PER_VOTER[1] }>,
) {
let (voters, targets) = set_up_voters_targets::<T::AccountId>(v, t, d as _);
let result;
#[block]
{
result = SequentialPhragmen::<T::AccountId, Perbill>::solve(d as _, targets, voters);
}
assert!(result.is_ok());
}
#[benchmark]
fn phragmms(
// Number of votes in snapshot.
v: Linear<{ VOTERS[0] }, { VOTERS[1] }>,
// Number of targets in snapshot.
t: Linear<{ TARGETS[0] }, { TARGETS[1] }>,
// Number of votes per voter (ie the degree).
d: Linear<{ VOTES_PER_VOTER[0] }, { VOTES_PER_VOTER[1] }>,
) {
let (voters, targets) = set_up_voters_targets::<T::AccountId>(v, t, d as _);
let result;
#[block]
{
result = PhragMMS::<T::AccountId, Perbill>::solve(d as _, targets, voters);
}
assert!(result.is_ok());
}
}
@@ -0,0 +1,28 @@
// 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.
//! Election provider support pallet benchmarking.
#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;
#[cfg(feature = "runtime-benchmarks")]
pub mod inner;
#[cfg(feature = "runtime-benchmarks")]
pub use inner::*;
@@ -0,0 +1,142 @@
// 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.
// 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 32.0.0
//! DATE: 2025-02-21, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `4563561839a5`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz`
//! WASM-EXECUTION: `Compiled`, CHAIN: `None`, DB CACHE: `1024`
// Executed Command:
// frame-omni-bencher
// v1
// benchmark
// pallet
// --extrinsic=*
// --runtime=target/production/wbuild/kitchensink-runtime/kitchensink_runtime.wasm
// --pallet=pezpallet_election_provider_support_benchmarking
// --header=/__w/pezkuwi-sdk/pezkuwi-sdk/bizinikiwi/HEADER-APACHE2
// --output=/__w/pezkuwi-sdk/pezkuwi-sdk/bizinikiwi/pezframe/election-provider-support/benchmarking/src/weights.rs
// --wasm-execution=compiled
// --steps=50
// --repeat=20
// --heap-pages=4096
// --template=bizinikiwi/.maintain/frame-weight-template.hbs
// --no-storage-info
// --no-min-squares
// --no-median-slopes
// --genesis-builder-policy=none
// --exclude-pallets=pezpallet_xcm,pezpallet_xcm_benchmarks::fungible,pezpallet_xcm_benchmarks::generic,pezpallet_nomination_pools,pezpallet_remark,pezpallet_transaction_storage,pezpallet_election_provider_multi_block,pezpallet_election_provider_multi_block::signed,pezpallet_election_provider_multi_block::unsigned,pezpallet_election_provider_multi_block::verifier
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]
#![allow(missing_docs)]
#![allow(dead_code)]
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> {
/// The range of component `v` is `[1000, 2000]`.
/// The range of component `t` is `[500, 1000]`.
/// The range of component `d` is `[5, 16]`.
fn phragmen(v: u32, _t: u32, d: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `0`
// Estimated: `0`
// Minimum execution time: 7_323_617_000 picoseconds.
Weight::from_parts(7_363_714_000, 0)
// Standard Error: 161_363
.saturating_add(Weight::from_parts(6_572_858, 0).saturating_mul(v.into()))
// Standard Error: 16_497_213
.saturating_add(Weight::from_parts(1_676_706_522, 0).saturating_mul(d.into()))
}
/// The range of component `v` is `[1000, 2000]`.
/// The range of component `t` is `[500, 1000]`.
/// The range of component `d` is `[5, 16]`.
fn phragmms(v: u32, _t: u32, d: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `0`
// Estimated: `0`
// Minimum execution time: 5_200_392_000 picoseconds.
Weight::from_parts(5_252_995_000, 0)
// Standard Error: 150_087
.saturating_add(Weight::from_parts(5_632_837, 0).saturating_mul(v.into()))
// Standard Error: 15_344_440
.saturating_add(Weight::from_parts(1_672_952_586, 0).saturating_mul(d.into()))
}
}
// For backwards compatibility and tests.
impl WeightInfo for () {
/// The range of component `v` is `[1000, 2000]`.
/// The range of component `t` is `[500, 1000]`.
/// The range of component `d` is `[5, 16]`.
fn phragmen(v: u32, _t: u32, d: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `0`
// Estimated: `0`
// Minimum execution time: 7_323_617_000 picoseconds.
Weight::from_parts(7_363_714_000, 0)
// Standard Error: 161_363
.saturating_add(Weight::from_parts(6_572_858, 0).saturating_mul(v.into()))
// Standard Error: 16_497_213
.saturating_add(Weight::from_parts(1_676_706_522, 0).saturating_mul(d.into()))
}
/// The range of component `v` is `[1000, 2000]`.
/// The range of component `t` is `[500, 1000]`.
/// The range of component `d` is `[5, 16]`.
fn phragmms(v: u32, _t: u32, d: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `0`
// Estimated: `0`
// Minimum execution time: 5_200_392_000 picoseconds.
Weight::from_parts(5_252_995_000, 0)
// Standard Error: 150_087
.saturating_add(Weight::from_parts(5_632_837, 0).saturating_mul(v.into()))
// Standard Error: 15_344_440
.saturating_add(Weight::from_parts(1_672_952_586, 0).saturating_mul(d.into()))
}
}
@@ -0,0 +1,42 @@
[package]
name = "pezframe-election-provider-solution-type"
version = "13.0.0"
authors.workspace = true
edition.workspace = true
license = "Apache-2.0"
homepage.workspace = true
repository.workspace = true
description = "NPoS Solution Type"
[lints]
workspace = true
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
[lib]
proc-macro = true
[dependencies]
proc-macro-crate = { workspace = true }
proc-macro2 = { workspace = true }
quote = { workspace = true }
syn = { features = ["full", "visit"], workspace = true }
[dev-dependencies]
codec = { workspace = true, default-features = true }
scale-info = { workspace = true, default-features = true }
pezsp-arithmetic = { workspace = true, default-features = true }
# used by generate_solution_type:
# NOTE: we have to explicitly specify `std` because of trybuild
pezframe-election-provider-support = { workspace = true, default-features = true, features = [
"std",
] }
pezframe-support = { workspace = true, default-features = true }
trybuild = { workspace = true }
[features]
runtime-benchmarks = [
"pezframe-election-provider-support/runtime-benchmarks",
"pezframe-support/runtime-benchmarks",
]
@@ -0,0 +1,39 @@
[package]
name = "frame-election-solution-type-fuzzer"
version = "2.0.0-alpha.5"
authors.workspace = true
edition.workspace = true
license = "Apache-2.0"
homepage.workspace = true
repository.workspace = true
description = "Fuzzer for phragmén solution type implementation."
publish = false
[lints]
workspace = true
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
[[bin]]
name = "compact"
path = "src/compact.rs"
[dependencies]
honggfuzz = { workspace = true }
codec = { features = ["derive"], workspace = true }
pezframe-election-provider-solution-type = { workspace = true, default-features = true }
pezframe-election-provider-support = { workspace = true, default-features = true }
pezsp-arithmetic = { workspace = true, default-features = true }
pezsp-runtime = { workspace = true, default-features = true }
# used by generate_solution_type:
pezframe-support = { workspace = true, default-features = true }
[features]
runtime-benchmarks = [
"pezframe-election-provider-solution-type/runtime-benchmarks",
"pezframe-election-provider-support/runtime-benchmarks",
"pezframe-support/runtime-benchmarks",
"pezsp-runtime/runtime-benchmarks",
]
@@ -0,0 +1,58 @@
// 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.
use pezframe_election_provider_solution_type::generate_solution_type;
use honggfuzz::fuzz;
use pezsp_arithmetic::Percent;
use pezsp_runtime::codec::{Encode, Error};
fn main() {
generate_solution_type!(
#[compact] pub struct InnerTestSolutionCompact::<
VoterIndex = u32,
TargetIndex = u32,
Accuracy = Percent,
MaxVoters = pezframe_support::traits::ConstU32::<100_000>,
>(16));
loop {
fuzz!(|fuzzer_data: &[u8]| {
let result_decoded: Result<InnerTestSolutionCompact, Error> =
<InnerTestSolutionCompact as codec::Decode>::decode(&mut &*fuzzer_data);
// Ignore errors as not every random sequence of bytes can be decoded as
// InnerTestSolutionCompact
if let Ok(decoded) = result_decoded {
// Decoding works, let's re-encode it and compare results.
let reencoded: std::vec::Vec<u8> = decoded.encode();
// The reencoded value may or may not be equal to the original fuzzer output.
// However, the original decoder should be optimal (in the sense that there is no
// shorter encoding of the same object). So let's see if the fuzzer can find
// something shorter:
if fuzzer_data.len() < reencoded.len() {
panic!("fuzzer_data.len() < reencoded.len()");
}
// The reencoded value should definitely be decodable (if unwrap() fails that is a
// valid panic/finding for the fuzzer):
let decoded2: InnerTestSolutionCompact =
<InnerTestSolutionCompact as codec::Decode>::decode(&mut reencoded.as_slice())
.unwrap();
// And it should be equal to the original decoded object (resulting from directly
// decoding fuzzer_data):
assert_eq!(decoded, decoded2);
}
});
}
}
@@ -0,0 +1,243 @@
// 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.
//! Code generation for the ratio assignment type' encode/decode/info impl.
use crate::vote_field;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
pub(crate) fn codec_and_info_impl(
ident: syn::Ident,
voter_type: syn::Type,
target_type: syn::Type,
weight_type: syn::Type,
count: usize,
) -> TokenStream2 {
let encode = encode_impl(&ident, count);
let decode = decode_impl(&ident, &voter_type, &target_type, &weight_type, count);
let scale_info = scale_info_impl(&ident, &voter_type, &target_type, &weight_type, count);
quote! {
impl _fepsp::codec::EncodeLike for #ident {}
#encode
#decode
#scale_info
}
}
fn decode_impl(
ident: &syn::Ident,
voter_type: &syn::Type,
target_type: &syn::Type,
weight_type: &syn::Type,
count: usize,
) -> TokenStream2 {
let decode_impl_single = {
let name = vote_field(1);
quote! {
let #name =
<
_fepsp::Vec<(_fepsp::codec::Compact<#voter_type>, _fepsp::codec::Compact<#target_type>)>
as
_fepsp::codec::Decode
>::decode(value)?;
let #name = #name
.into_iter()
.map(|(v, t)| (v.0, t.0))
.collect::<_fepsp::Vec<_>>();
}
};
let decode_impl_rest = (2..=count)
.map(|c| {
let name = vote_field(c);
let inner_impl = (0..c - 1)
.map(|i| quote! { ( (inner[#i].0).0, (inner[#i].1).0 ), })
.collect::<TokenStream2>();
quote! {
let #name =
<
_fepsp::Vec<(
_fepsp::codec::Compact<#voter_type>,
[(_fepsp::codec::Compact<#target_type>, _fepsp::codec::Compact<#weight_type>); #c-1],
_fepsp::codec::Compact<#target_type>,
)>
as _fepsp::codec::Decode
>::decode(value)?;
let #name = #name
.into_iter()
.map(|(v, inner, t_last)| (
v.0,
[ #inner_impl ],
t_last.0,
))
.collect::<_fepsp::Vec<_>>();
}
})
.collect::<TokenStream2>();
let all_field_names = (1..=count)
.map(|c| {
let name = vote_field(c);
quote! { #name, }
})
.collect::<TokenStream2>();
quote!(
impl _fepsp::codec::Decode for #ident {
fn decode<I: _fepsp::codec::Input>(value: &mut I) -> Result<Self, _fepsp::codec::Error> {
#decode_impl_single
#decode_impl_rest
// The above code generates variables with the decoded value with the same name as
// filed names of the struct, i.e. `let votes4 = decode_value_of_votes4`. All we
// have to do is collect them into the main struct now.
Ok(#ident { #all_field_names })
}
}
)
}
// General attitude is that we will convert inner values to `Compact` and then use the normal
// `Encode` implementation.
fn encode_impl(ident: &syn::Ident, count: usize) -> TokenStream2 {
let encode_impl_single = {
let name = vote_field(1);
quote! {
let #name = self.#name
.iter()
.map(|(v, t)| (
_fepsp::codec::Compact(v.clone()),
_fepsp::codec::Compact(t.clone()),
))
.collect::<_fepsp::Vec<_>>();
#name.encode_to(&mut r);
}
};
let encode_impl_rest = (2..=count)
.map(|c| {
let name = vote_field(c);
// we use the knowledge of the length to avoid copy_from_slice.
let inners_solution_array = (0..c - 1)
.map(|i| {
quote! {(
_fepsp::codec::Compact(inner[#i].0.clone()),
_fepsp::codec::Compact(inner[#i].1.clone()),
),}
})
.collect::<TokenStream2>();
quote! {
let #name = self.#name
.iter()
.map(|(v, inner, t_last)| (
_fepsp::codec::Compact(v.clone()),
[ #inners_solution_array ],
_fepsp::codec::Compact(t_last.clone()),
))
.collect::<_fepsp::Vec<_>>();
#name.encode_to(&mut r);
}
})
.collect::<TokenStream2>();
quote!(
impl _fepsp::codec::Encode for #ident {
fn encode(&self) -> _fepsp::Vec<u8> {
let mut r = vec![];
#encode_impl_single
#encode_impl_rest
r
}
}
)
}
fn scale_info_impl(
ident: &syn::Ident,
voter_type: &syn::Type,
target_type: &syn::Type,
weight_type: &syn::Type,
count: usize,
) -> TokenStream2 {
let scale_info_impl_single = {
let name = format!("{}", vote_field(1));
quote! {
.field(|f|
f.ty::<_fepsp::Vec<
(_fepsp::codec::Compact<#voter_type>, _fepsp::codec::Compact<#target_type>)
>>()
.name(#name)
)
}
};
let scale_info_impl_double = {
let name = format!("{}", vote_field(2));
quote! {
.field(|f|
f.ty::<_fepsp::Vec<(
_fepsp::codec::Compact<#voter_type>,
(_fepsp::codec::Compact<#target_type>, _fepsp::codec::Compact<#weight_type>),
_fepsp::codec::Compact<#target_type>
)>>()
.name(#name)
)
}
};
let scale_info_impl_rest = (3..=count)
.map(|c| {
let name = format!("{}", vote_field(c));
quote! {
.field(|f|
f.ty::<_fepsp::Vec<(
_fepsp::codec::Compact<#voter_type>,
[
(_fepsp::codec::Compact<#target_type>, _fepsp::codec::Compact<#weight_type>);
#c - 1
],
_fepsp::codec::Compact<#target_type>
)>>()
.name(#name)
)
}
})
.collect::<TokenStream2>();
quote!(
impl _fepsp::scale_info::TypeInfo for #ident {
type Identity = Self;
fn type_info() -> _fepsp::scale_info::Type<_fepsp::scale_info::form::MetaForm> {
_fepsp::scale_info::Type::builder()
.path(_fepsp::scale_info::Path::new(stringify!(#ident), module_path!()))
.composite(
_fepsp::scale_info::build::Fields::named()
#scale_info_impl_single
#scale_info_impl_double
#scale_info_impl_rest
)
}
}
)
}
@@ -0,0 +1,56 @@
// 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.
//! Helpers to generate the push code for `from_assignment` implementations. This can be shared
//! between both single_page and double_page, thus extracted here.
//!
//! All of the code in this helper module assumes some variable names, namely `who` and
//! `distribution`.
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
pub(crate) fn from_impl_single_push_code() -> TokenStream2 {
quote!(push((
voter_index(&who).or_invalid_index()?,
target_index(&distribution[0].0).or_invalid_index()?,
)))
}
pub(crate) fn from_impl_rest_push_code(count: usize) -> TokenStream2 {
let inner = (0..count - 1).map(|i| {
quote!(
(
target_index(&distribution[#i].0).or_invalid_index()?,
distribution[#i].1
)
)
});
let last_index = count - 1;
let last = quote!(target_index(&distribution[#last_index].0).or_invalid_index()?);
quote!(
push(
(
voter_index(&who).or_invalid_index()?,
[ #( #inner ),* ],
#last,
)
)
)
}
@@ -0,0 +1,61 @@
// 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.
//! Code generation for getting the solution representation from the `IndexAssignment` type.
use crate::vote_field;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
pub(crate) fn from_impl(struct_name: &syn::Ident, count: usize) -> TokenStream2 {
let from_impl_single = {
let name = vote_field(1);
quote!(1 => #struct_name.#name.push(
(
*who,
distribution[0].0,
)
),)
};
let from_impl_rest = (2..=count)
.map(|c| {
let inner = (0..c - 1)
.map(|i| quote!((distribution[#i].0, distribution[#i].1),))
.collect::<TokenStream2>();
let field_name = vote_field(c);
let last_index = c - 1;
let last = quote!(distribution[#last_index].0);
quote!(
#c => #struct_name.#field_name.push(
(
*who,
[#inner],
#last,
)
),
)
})
.collect::<TokenStream2>();
quote!(
#from_impl_single
#from_impl_rest
)
}
@@ -0,0 +1,291 @@
// 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.
//! Proc macro for a npos solution type.
use proc_macro::TokenStream;
use proc_macro2::{Ident, Span, TokenStream as TokenStream2};
use proc_macro_crate::{crate_name, FoundCrate};
use quote::quote;
use syn::parse::{Parse, ParseStream, Result};
mod codec;
mod from_assignment_helpers;
mod index_assignment;
mod single_page;
/// Get the name of a filed based on voter count.
pub(crate) fn vote_field(n: usize) -> Ident {
quote::format_ident!("votes{}", n)
}
/// Generate a `syn::Error`.
pub(crate) fn syn_err(message: &'static str) -> syn::Error {
syn::Error::new(Span::call_site(), message)
}
/// Generates a struct to store the election result in a small/compact way. This can encode a
/// structure which is the equivalent of a `pezsp_npos_elections::Assignment<_>`.
///
/// The following data types can be configured by the macro.
///
/// - The identifier of the voter. This can be any type that supports `parity-scale-codec`'s compact
/// encoding.
/// - The identifier of the target. This can be any type that supports `parity-scale-codec`'s
/// compact encoding.
/// - The accuracy of the ratios. This must be one of the `PerThing` types defined in
/// `sp-arithmetic`.
/// - The maximum number of voters. This must be of type `Get<u32>`. Check <https://github.com/pezkuwichain/kurdistan-sdk/issues/5>
/// for more details. This is used to bound the struct, by leveraging the fact that `votes1.len()
/// < votes2.len() < ... < votesn.len()` (the details of the struct is explained further below).
/// We know that `sum_i votes_i.len() <= MaxVoters`, and we know that the maximum size of the
/// struct would be achieved if all voters fall in the last bucket. One can also check the tests
/// and more specifically `max_encoded_len_exact` for a concrete example.
///
/// Moreover, the maximum number of edges per voter (distribution per assignment) also need to be
/// specified. Attempting to convert from/to an assignment with more distributions will fail.
///
/// For example, the following generates a public struct with name `TestSolution` with `u16` voter
/// type, `u8` target type and `Perbill` accuracy with maximum of 4 edges per voter.
///
/// ```
/// # use pezframe_election_provider_solution_type::generate_solution_type;
/// # use pezsp_arithmetic::per_things::Perbill;
/// # use pezframe_support::traits::ConstU32;
/// generate_solution_type!(pub struct TestSolution::<
/// VoterIndex = u16,
/// TargetIndex = u8,
/// Accuracy = Perbill,
/// MaxVoters = ConstU32::<10>,
/// >(4));
/// ```
///
/// The output of this macro will roughly look like:
///
/// ```ignore
/// struct TestSolution {
/// voters1: vec![(u16 /* voter */, u8 /* target */)]
/// voters2: vec![
/// (u16 /* voter */, [u8 /* first target*/, Perbill /* proportion for first target */], u8 /* last target */)
/// ]
/// voters3: vec![
/// (u16 /* voter */, [
/// (u8 /* first target*/, Perbill /* proportion for first target */ ),
/// (u8 /* second target */, Perbill /* proportion for second target*/)
/// ], u8 /* last target */)
/// ],
/// voters4: ...,
/// }
///
/// impl NposSolution for TestSolution {};
/// impl Solution for TestSolution {};
/// ```
///
/// The given struct provides function to convert from/to `Assignment` as part of
/// `pezframe_election_provider_support::NposSolution` trait:
///
/// - `fn from_assignment<..>(..)`
/// - `fn into_assignment<..>(..)`
///
/// ## Compact Encoding
///
/// The generated struct is by default deriving both `Encode` and `Decode`. This is okay but could
/// lead to many `0`s in the solution. If prefixed with `#[compact]`, then a custom compact encoding
/// for numbers will be used, similar to how `parity-scale-codec`'s `Compact` works.
///
/// ```
/// # use pezframe_election_provider_solution_type::generate_solution_type;
/// # use pezframe_election_provider_support::NposSolution;
/// # use pezsp_arithmetic::per_things::Perbill;
/// # use pezframe_support::traits::ConstU32;
/// generate_solution_type!(
/// #[compact]
/// pub struct TestSolutionCompact::<
/// VoterIndex = u16,
/// TargetIndex = u8,
/// Accuracy = Perbill,
/// MaxVoters = ConstU32::<10>,
/// >(8)
/// );
/// ```
#[proc_macro]
pub fn generate_solution_type(item: TokenStream) -> TokenStream {
let solution_def = syn::parse_macro_input!(item as SolutionDef);
let imports = imports().unwrap_or_else(|e| e.to_compile_error());
let def = single_page::generate(solution_def).unwrap_or_else(|e| e.to_compile_error());
quote!(
#imports
#def
)
.into()
}
struct SolutionDef {
vis: syn::Visibility,
ident: syn::Ident,
voter_type: syn::Type,
target_type: syn::Type,
weight_type: syn::Type,
max_voters: syn::Type,
count: usize,
compact_encoding: bool,
}
fn check_attributes(input: ParseStream) -> syn::Result<bool> {
let mut attrs = input.call(syn::Attribute::parse_outer).unwrap_or_default();
if attrs.len() > 1 {
let extra_attr = attrs.pop().expect("attributes vec with len > 1 can be popped");
return Err(syn::Error::new_spanned(
extra_attr,
"compact solution can accept only #[compact]",
));
}
if attrs.is_empty() {
return Ok(false);
}
let attr = attrs.pop().expect("attributes vec with len 1 can be popped.");
if attr.path().is_ident("compact") {
Ok(true)
} else {
Err(syn::Error::new_spanned(attr, "compact solution can accept only #[compact]"))
}
}
impl Parse for SolutionDef {
fn parse(input: ParseStream) -> syn::Result<Self> {
// optional #[compact]
let compact_encoding = check_attributes(input)?;
// <vis> struct <name>
let vis: syn::Visibility = input.parse()?;
<syn::Token![struct]>::parse(input)?;
let ident: syn::Ident = input.parse()?;
// ::<V, T, W>
<syn::Token![::]>::parse(input)?;
let generics: syn::AngleBracketedGenericArguments = input.parse()?;
if generics.args.len() != 4 {
return Err(syn_err("Must provide 4 generic args."));
}
let expected_types = ["VoterIndex", "TargetIndex", "Accuracy", "MaxVoters"];
let mut types: Vec<syn::Type> = generics
.args
.iter()
.zip(expected_types.iter())
.map(|(t, expected)| match t {
syn::GenericArgument::Type(ty) => {
// this is now an error
Err(syn::Error::new_spanned(
ty,
format!("Expected binding: `{} = ...`", expected),
))
},
syn::GenericArgument::AssocType(syn::AssocType { ident, ty, .. }) => {
// check that we have the right keyword for this position in the argument list
if ident == expected {
Ok(ty.clone())
} else {
Err(syn::Error::new_spanned(ident, format!("Expected `{}`", expected)))
}
},
_ => Err(syn_err("Wrong type of generic provided. Must be a `type`.")),
})
.collect::<Result<_>>()?;
let max_voters = types.pop().expect("Vector of length 4 can be popped; qed");
let weight_type = types.pop().expect("Vector of length 3 can be popped; qed");
let target_type = types.pop().expect("Vector of length 2 can be popped; qed");
let voter_type = types.pop().expect("Vector of length 1 can be popped; qed");
// (<count>)
let count_expr: syn::ExprParen = input.parse()?;
let count = parse_parenthesized_number::<usize>(count_expr)?;
Ok(Self {
vis,
ident,
voter_type,
target_type,
weight_type,
max_voters,
count,
compact_encoding,
})
}
}
fn parse_parenthesized_number<N: std::str::FromStr>(input_expr: syn::ExprParen) -> syn::Result<N>
where
<N as std::str::FromStr>::Err: std::fmt::Display,
{
let expr = input_expr.expr;
let expr_lit = match *expr {
syn::Expr::Lit(count_lit) => count_lit.lit,
_ => return Err(syn_err("Count must be literal.")),
};
let int_lit = match expr_lit {
syn::Lit::Int(int_lit) => int_lit,
_ => return Err(syn_err("Count must be int literal.")),
};
int_lit.base10_parse::<N>()
}
fn imports() -> Result<TokenStream2> {
match crate_name("pezframe-election-provider-support") {
Ok(FoundCrate::Itself) => Ok(quote! {
use crate as _feps;
use _feps::private as _fepsp;
}),
Ok(FoundCrate::Name(pezframe_election_provider_support)) => {
let ident = syn::Ident::new(&pezframe_election_provider_support, Span::call_site());
Ok(quote!(
use #ident as _feps;
use _feps::private as _fepsp;
))
},
Err(e) => match crate_name("pezkuwi-sdk") {
Ok(FoundCrate::Name(pezkuwi_sdk)) => {
let ident = syn::Ident::new(&pezkuwi_sdk, Span::call_site());
Ok(quote!(
use #ident::pezframe_election_provider_support as _feps;
use _feps::private as _fepsp;
))
},
_ => Err(syn::Error::new(Span::call_site(), e)),
},
}
}
#[cfg(test)]
mod tests {
#[test]
fn ui_fail() {
// Only run the ui tests when `RUN_UI_TESTS` is set.
if std::env::var("RUN_UI_TESTS").is_err() {
return;
}
let cases = trybuild::TestCases::new();
cases.compile_fail("tests/ui/fail/*.rs");
}
}
@@ -0,0 +1,506 @@
// 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.
use crate::{from_assignment_helpers::*, syn_err, vote_field};
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::parse::Result;
pub(crate) fn generate(def: crate::SolutionDef) -> Result<TokenStream2> {
let crate::SolutionDef {
vis,
ident,
count,
voter_type,
target_type,
weight_type,
max_voters,
compact_encoding,
} = def;
if count <= 2 {
return Err(syn_err("cannot build solution struct with capacity less than 3."));
}
let single = {
let name = vote_field(1);
// NOTE: we use the visibility of the struct for the fields as well.. could be made better.
quote!(
#vis #name: _fepsp::Vec<(#voter_type, #target_type)>,
)
};
let rest = (2..=count)
.map(|c| {
let field_name = vote_field(c);
let array_len = c - 1;
quote!(
#vis #field_name: _fepsp::Vec<(
#voter_type,
[(#target_type, #weight_type); #array_len],
#target_type
)>,
)
})
.collect::<TokenStream2>();
let len_impl = len_impl(count);
let edge_count_impl = edge_count_impl(count);
let unique_targets_impl = unique_targets_impl(count);
let remove_voter_impl = remove_voter_impl(count);
let derives_and_maybe_compact_encoding = if compact_encoding {
// custom compact encoding.
let compact_impl = crate::codec::codec_and_info_impl(
ident.clone(),
voter_type.clone(),
target_type.clone(),
weight_type.clone(),
count,
);
quote! {
#compact_impl
#[derive(Default, PartialEq, Eq, Clone, Debug, PartialOrd, Ord, _fepsp::codec::DecodeWithMemTracking)]
}
} else {
// automatically derived.
quote!(#[derive(
Default,
PartialEq,
Eq,
Clone,
Debug,
Ord,
PartialOrd,
_fepsp::codec::Encode,
_fepsp::codec::Decode,
_fepsp::codec::DecodeWithMemTracking,
_fepsp::scale_info::TypeInfo,
)])
};
let struct_name = syn::Ident::new("solution", proc_macro2::Span::call_site());
let assignment_name = syn::Ident::new("all_assignments", proc_macro2::Span::call_site());
let from_impl = from_impl(&struct_name, count);
let into_impl = into_impl(&assignment_name, count, weight_type.clone());
let from_index_impl = crate::index_assignment::from_impl(&struct_name, count);
let sort_impl = sort_impl(count);
let remove_weakest_sorted_impl = remove_weakest_sorted_impl(count);
Ok(quote! (
/// A struct to encode a election assignment in a compact way.
#derives_and_maybe_compact_encoding
#vis struct #ident { #single #rest }
use _fepsp::__OrInvalidIndex;
impl _feps::NposSolution for #ident {
const LIMIT: usize = #count;
type VoterIndex = #voter_type;
type TargetIndex = #target_type;
type Accuracy = #weight_type;
fn remove_voter(&mut self, to_remove: Self::VoterIndex) -> bool {
#remove_voter_impl
return false
}
fn from_assignment<FV, FT, A>(
assignments: &[_feps::Assignment<A, #weight_type>],
voter_index: FV,
target_index: FT,
) -> Result<Self, _feps::Error>
where
A: _feps::IdentifierT,
for<'r> FV: Fn(&'r A) -> Option<Self::VoterIndex>,
for<'r> FT: Fn(&'r A) -> Option<Self::TargetIndex>,
{
// Make sure that the voter bound is binding.
// `assignments.len()` actually represents the number of voters
if assignments.len() as u32 > <#max_voters as _feps::Get<u32>>::get() {
return Err(_feps::Error::TooManyVoters);
}
let mut #struct_name: #ident = Default::default();
for _feps::Assignment { who, distribution } in assignments {
match distribution.len() {
0 => continue,
#from_impl
_ => {
return Err(_feps::Error::SolutionTargetOverflow);
}
}
};
Ok(#struct_name)
}
fn into_assignment<A: _feps::IdentifierT>(
self,
voter_at: impl Fn(Self::VoterIndex) -> Option<A>,
target_at: impl Fn(Self::TargetIndex) -> Option<A>,
) -> Result<_fepsp::Vec<_feps::Assignment<A, #weight_type>>, _feps::Error> {
let mut #assignment_name: _fepsp::BTreeMap<Self::VoterIndex, _feps::Assignment<A, #weight_type>> = Default::default();
#into_impl
Ok(#assignment_name.into_values().collect())
}
fn voter_count(&self) -> usize {
let mut all_len = 0usize;
#len_impl
all_len
}
fn edge_count(&self) -> usize {
let mut all_edges = 0usize;
#edge_count_impl
all_edges
}
fn unique_targets(&self) -> _fepsp::Vec<Self::TargetIndex> {
// NOTE: this implementation returns the targets sorted, but we don't use it yet per
// se, nor is the API enforcing it.
use _fepsp::BTreeSet;
let mut all_targets: BTreeSet<Self::TargetIndex> = BTreeSet::new();
let mut maybe_insert_target = |t: Self::TargetIndex| {
all_targets.insert(t);
};
#unique_targets_impl
all_targets.into_iter().collect()
}
fn sort<F>(&mut self, mut voter_stake: F)
where
F: FnMut(&Self::VoterIndex) -> _feps::VoteWeight
{
#sort_impl
}
fn remove_weakest_sorted<F>(&mut self, mut voter_stake: F) -> Option<Self::VoterIndex>
where
F: FnMut(&Self::VoterIndex) -> _feps::VoteWeight
{
#remove_weakest_sorted_impl
}
fn corrupt(&mut self) {
self.votes1.push(
(
_fepsp::pezsp_arithmetic::traits::Bounded::max_value(),
_fepsp::pezsp_arithmetic::traits::Bounded::max_value()
)
)
}
}
type __IndexAssignment = _feps::IndexAssignment<
<#ident as _feps::NposSolution>::VoterIndex,
<#ident as _feps::NposSolution>::TargetIndex,
<#ident as _feps::NposSolution>::Accuracy,
>;
impl _fepsp::codec::MaxEncodedLen for #ident {
fn max_encoded_len() -> usize {
use pezframe_support::traits::Get;
use _fepsp::codec::Encode;
let s: u32 = <#max_voters as _feps::Get<u32>>::get();
let max_element_size =
// the first voter..
#voter_type::max_encoded_len()
// #count - 1 tuples..
.saturating_add(
(#count - 1).saturating_mul(
#target_type::max_encoded_len().saturating_add(#weight_type::max_encoded_len())))
// and the last target.
.saturating_add(#target_type::max_encoded_len());
// The assumption is that it contains #count-1 empty elements
// and then last element with full size
#count
.saturating_mul(_fepsp::codec::Compact(0u32).encoded_size())
.saturating_add((s as usize).saturating_mul(max_element_size))
}
}
impl<'a> core::convert::TryFrom<&'a [__IndexAssignment]> for #ident {
type Error = _feps::Error;
fn try_from(index_assignments: &'a [__IndexAssignment]) -> Result<Self, Self::Error> {
let mut #struct_name = #ident::default();
for _feps::IndexAssignment { who, distribution } in index_assignments {
match distribution.len() {
0 => {}
#from_index_impl
_ => {
return Err(_feps::Error::SolutionTargetOverflow);
}
}
};
Ok(#struct_name)
}
}
))
}
fn sort_impl(count: usize) -> TokenStream2 {
(1..=count)
.map(|c| {
let field = vote_field(c);
quote! {
// NOTE: self.filed here is sometimes `Vec<(voter, weight)>` and sometimes
// `Vec<(voter, weights, last_weight)>`, but Rust's great patter matching makes it
// all work super nice.
self.#field.sort_by(|(a, ..), (b, ..)| voter_stake(&b).cmp(&voter_stake(&a)));
// ---------------------------------^^ in all fields, the index 0 is the voter id.
}
})
.collect::<TokenStream2>()
}
fn remove_weakest_sorted_impl(count: usize) -> TokenStream2 {
// check minium from field 2 onwards. We assume 0 is minimum
let check_minimum = (2..=count).map(|c| {
let filed = vote_field(c);
quote! {
let filed_value = self.#filed
.last()
.map(|(x, ..)| voter_stake(x))
.unwrap_or_else(|| _fepsp::pezsp_arithmetic::traits::Bounded::max_value());
if filed_value < minimum {
minimum = filed_value;
minimum_filed = #c
}
}
});
let remove_minimum_match = (1..=count).map(|c| {
let filed = vote_field(c);
quote! {
#c => self.#filed.pop().map(|(x, ..)| x),
}
});
let first_filed = vote_field(1);
quote! {
// we assume first one is the minimum. No problem if it is empty.
let mut minimum_filed = 1;
let mut minimum = self.#first_filed
.last()
.map(|(x, ..)| voter_stake(x))
.unwrap_or_else(|| _fepsp::pezsp_arithmetic::traits::Bounded::max_value());
#( #check_minimum )*
match minimum_filed {
#( #remove_minimum_match )*
_ => {
debug_assert!(false);
None
}
}
}
}
fn remove_voter_impl(count: usize) -> TokenStream2 {
let field_name = vote_field(1);
let single = quote! {
if let Some(idx) = self.#field_name.iter().position(|(x, _)| *x == to_remove) {
self.#field_name.remove(idx);
return true
}
};
let rest = (2..=count)
.map(|c| {
let field_name = vote_field(c);
quote! {
if let Some(idx) = self.#field_name.iter().position(|(x, _, _)| *x == to_remove) {
self.#field_name.remove(idx);
return true
}
}
})
.collect::<TokenStream2>();
quote! {
#single
#rest
}
}
fn len_impl(count: usize) -> TokenStream2 {
(1..=count)
.map(|c| {
let field_name = vote_field(c);
quote!(
all_len = all_len.saturating_add(self.#field_name.len());
)
})
.collect::<TokenStream2>()
}
fn edge_count_impl(count: usize) -> TokenStream2 {
(1..=count)
.map(|c| {
let field_name = vote_field(c);
quote!(
all_edges = all_edges.saturating_add(
self.#field_name.len().saturating_mul(#c as usize)
);
)
})
.collect::<TokenStream2>()
}
fn unique_targets_impl(count: usize) -> TokenStream2 {
let unique_targets_impl_single = {
let field_name = vote_field(1);
quote! {
self.#field_name.iter().for_each(|(_, t)| {
maybe_insert_target(*t);
});
}
};
let unique_targets_impl_rest = (2..=count)
.map(|c| {
let field_name = vote_field(c);
quote! {
self.#field_name.iter().for_each(|(_, inners, t_last)| {
inners.iter().for_each(|(t, _)| {
maybe_insert_target(*t);
});
maybe_insert_target(*t_last);
});
}
})
.collect::<TokenStream2>();
quote! {
#unique_targets_impl_single
#unique_targets_impl_rest
}
}
pub(crate) fn from_impl(struct_name: &syn::Ident, count: usize) -> TokenStream2 {
let from_impl_single = {
let field = vote_field(1);
let push_code = from_impl_single_push_code();
quote!(1 => #struct_name.#field.#push_code,)
};
let from_impl_rest = (2..=count)
.map(|c| {
let field = vote_field(c);
let push_code = from_impl_rest_push_code(c);
quote!(#c => #struct_name.#field.#push_code,)
})
.collect::<TokenStream2>();
quote!(
#from_impl_single
#from_impl_rest
)
}
pub(crate) fn into_impl(
assignments: &syn::Ident,
count: usize,
per_thing: syn::Type,
) -> TokenStream2 {
let into_impl_single = {
let name = vote_field(1);
quote!(
for (voter_index, target_index) in self.#name {;
if #assignments.contains_key(&voter_index) {
return Err(_feps::Error::DuplicateVoter);
} else {
#assignments.insert(
voter_index,
_feps::Assignment {
who: voter_at(voter_index).or_invalid_index()?,
distribution: vec![(target_at(target_index).or_invalid_index()?, #per_thing::one())],
}
);
}
}
)
};
let into_impl_rest = (2..=count)
.map(|c| {
let name = vote_field(c);
quote!(
for (voter_index, inners, t_last_idx) in self.#name {
if #assignments.contains_key(&voter_index) {
return Err(_feps::Error::DuplicateVoter);
}
let mut targets_seen = _fepsp::BTreeSet::new();
let mut sum = #per_thing::zero();
let mut inners_parsed = inners
.iter()
.map(|(ref t_idx, p)| {
if targets_seen.contains(t_idx) {
return Err(_feps::Error::DuplicateTarget);
} else {
targets_seen.insert(t_idx);
}
sum = _fepsp::pezsp_arithmetic::traits::Saturating::saturating_add(sum, *p);
let target = target_at(*t_idx).or_invalid_index()?;
Ok((target, *p))
})
.collect::<Result<_fepsp::Vec<(A, #per_thing)>, _feps::Error>>()?;
if sum >= #per_thing::one() {
return Err(_feps::Error::SolutionWeightOverflow);
}
// check that the last target index is also unique.
if targets_seen.contains(&t_last_idx) {
return Err(_feps::Error::DuplicateTarget);
} else {
// no need to insert, we are done.
}
// defensive only. Since Percent doesn't have `Sub`.
let p_last = _fepsp::pezsp_arithmetic::traits::Saturating::saturating_sub(
#per_thing::one(),
sum,
);
inners_parsed.push((target_at(t_last_idx).or_invalid_index()?, p_last));
#assignments.insert(
voter_index,
_feps::Assignment {
who: voter_at(voter_index).or_invalid_index()?,
distribution: inners_parsed,
}
);
}
)
})
.collect::<TokenStream2>();
quote!(
#into_impl_single
#into_impl_rest
)
}
@@ -0,0 +1,27 @@
// 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.
use pezframe_election_provider_solution_type::generate_solution_type;
generate_solution_type!(pub struct TestSolution::<
VoterIndex = u16,
TargetIndex = u8,
Perbill,
MaxVoters = ConstU32::<10>,
>(8));
fn main() {}
@@ -0,0 +1,5 @@
error: Expected binding: `Accuracy = ...`
--> tests/ui/fail/missing_accuracy.rs:23:2
|
23 | Perbill,
| ^^^^^^^
@@ -0,0 +1,27 @@
// 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.
use pezframe_election_provider_solution_type::generate_solution_type;
generate_solution_type!(pub struct TestSolution::<
VoterIndex = u16,
TargetIndex = u8,
Accuracy = Perbill,
ConstU32::<10>,
>(8));
fn main() {}
@@ -0,0 +1,5 @@
error: Expected binding: `MaxVoters = ...`
--> tests/ui/fail/missing_size_bound.rs:24:2
|
24 | ConstU32::<10>,
| ^^^^^^^^^^^^^^
@@ -0,0 +1,27 @@
// 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.
use pezframe_election_provider_solution_type::generate_solution_type;
generate_solution_type!(pub struct TestSolution::<
VoterIndex = u16,
u8,
Accuracy = Perbill,
MaxVoters = ConstU32::<10>,
>(8));
fn main() {}
@@ -0,0 +1,5 @@
error: Expected binding: `TargetIndex = ...`
--> tests/ui/fail/missing_target.rs:22:2
|
22 | u8,
| ^^
@@ -0,0 +1,27 @@
// 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.
use pezframe_election_provider_solution_type::generate_solution_type;
generate_solution_type!(pub struct TestSolution::<
u16,
TargetIndex = u8,
Accuracy = Perbill,
MaxVoters = ConstU32::<10>,
>(8));
fn main() {}
@@ -0,0 +1,5 @@
error: Expected binding: `VoterIndex = ...`
--> tests/ui/fail/missing_voter.rs:21:2
|
21 | u16,
| ^^^
@@ -0,0 +1,27 @@
// 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.
use pezframe_election_provider_solution_type::generate_solution_type;
generate_solution_type!(pub struct TestSolution::<
u16,
u8,
Perbill,
MaxVoters = ConstU32::<10>,
>(8));
fn main() {}
@@ -0,0 +1,5 @@
error: Expected binding: `VoterIndex = ...`
--> tests/ui/fail/no_annotations.rs:21:2
|
21 | u16,
| ^^^
@@ -0,0 +1,27 @@
// 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.
use pezframe_election_provider_solution_type::generate_solution_type;
generate_solution_type!(pub struct TestSolution::<
TargetIndex = u16,
VoterIndex = u8,
Accuracy = Perbill,
MaxVoters = ConstU32::<10>,
>(8));
fn main() {}
@@ -0,0 +1,5 @@
error: Expected `VoterIndex`
--> tests/ui/fail/swap_voter_target.rs:21:2
|
21 | TargetIndex = u16,
| ^^^^^^^^^^^
@@ -0,0 +1,29 @@
// 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.
use pezframe_election_provider_solution_type::generate_solution_type;
generate_solution_type!(
#[pages(1)] pub struct TestSolution::<
VoterIndex = u8,
TargetIndex = u16,
Accuracy = Perbill,
MaxVoters = ConstU32::<10>,
>(8)
);
fn main() {}
@@ -0,0 +1,5 @@
error: compact solution can accept only #[compact]
--> tests/ui/fail/wrong_attribute.rs:21:2
|
21 | #[pages(1)] pub struct TestSolution::<
| ^^^^^^^^^^^
@@ -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))
}
}