Multi-Block Election part 0: preparation and some cleanup. (#9442)

* Partially applied

* Everything builds, need to implement compact encoding as well.

* Fix some tests, add a ui test as well.

* Fix everything and everything.

* small nits

* a bunch more rename

* more reorg

* more reorg

* last nit of self-review

* Seemingly fixed the build now

* Fix build

* make it work again

* Update primitives/npos-elections/solution-type/src/lib.rs

Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com>

* Update primitives/npos-elections/solution-type/src/lib.rs

Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com>

* nits

* factor out double type

* fix try-build

Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com>
This commit is contained in:
Kian Paimani
2021-08-11 17:45:53 +02:00
committed by GitHub
parent abd08e29ce
commit f7bcbdd261
36 changed files with 1327 additions and 1364 deletions
@@ -16,7 +16,7 @@ targets = ["x86_64-unknown-linux-gnu"]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] }
serde = { version = "1.0.126", optional = true, features = ["derive"] }
sp-std = { version = "4.0.0-dev", default-features = false, path = "../std" }
sp-npos-elections-compact = { version = "4.0.0-dev", path = "./compact" }
sp-npos-elections-solution-type = { version = "4.0.0-dev", path = "./solution-type" }
sp-arithmetic = { version = "4.0.0-dev", default-features = false, path = "../arithmetic" }
sp-core = { version = "4.0.0-dev", default-features = false, path = "../core" }
@@ -28,7 +28,6 @@ sp-runtime = { version = "4.0.0-dev", path = "../runtime" }
[features]
default = ["std"]
bench = []
mocks = []
std = [
"codec/std",
"serde",
@@ -1,161 +0,0 @@
// This file is part of Substrate.
// Copyright (C) 2020-2021 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' compact representation.
use crate::field_name_for;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
pub(crate) fn from_impl(count: usize) -> TokenStream2 {
let from_impl_single = {
let name = field_name_for(1);
quote!(1 => compact.#name.push(
(
index_of_voter(&who).or_invalid_index()?,
index_of_target(&distribution[0].0).or_invalid_index()?,
)
),)
};
let from_impl_double = {
let name = field_name_for(2);
quote!(2 => compact.#name.push(
(
index_of_voter(&who).or_invalid_index()?,
(
index_of_target(&distribution[0].0).or_invalid_index()?,
distribution[0].1,
),
index_of_target(&distribution[1].0).or_invalid_index()?,
)
),)
};
let from_impl_rest = (3..=count)
.map(|c| {
let inner = (0..c - 1)
.map(
|i| quote!((index_of_target(&distribution[#i].0).or_invalid_index()?, distribution[#i].1),),
)
.collect::<TokenStream2>();
let field_name = field_name_for(c);
let last_index = c - 1;
let last = quote!(index_of_target(&distribution[#last_index].0).or_invalid_index()?);
quote!(
#c => compact.#field_name.push(
(
index_of_voter(&who).or_invalid_index()?,
[#inner],
#last,
)
),
)
})
.collect::<TokenStream2>();
quote!(
#from_impl_single
#from_impl_double
#from_impl_rest
)
}
pub(crate) fn into_impl(count: usize, per_thing: syn::Type) -> TokenStream2 {
let into_impl_single = {
let name = field_name_for(1);
quote!(
for (voter_index, target_index) in self.#name {
assignments.push(_npos::Assignment {
who: voter_at(voter_index).or_invalid_index()?,
distribution: vec![
(target_at(target_index).or_invalid_index()?, #per_thing::one())
],
})
}
)
};
let into_impl_double = {
let name = field_name_for(2);
quote!(
for (voter_index, (t1_idx, p1), t2_idx) in self.#name {
if p1 >= #per_thing::one() {
return Err(_npos::Error::CompactStakeOverflow);
}
// defensive only. Since Percent doesn't have `Sub`.
let p2 = _npos::sp_arithmetic::traits::Saturating::saturating_sub(
#per_thing::one(),
p1,
);
assignments.push( _npos::Assignment {
who: voter_at(voter_index).or_invalid_index()?,
distribution: vec![
(target_at(t1_idx).or_invalid_index()?, p1),
(target_at(t2_idx).or_invalid_index()?, p2),
]
});
}
)
};
let into_impl_rest = (3..=count)
.map(|c| {
let name = field_name_for(c);
quote!(
for (voter_index, inners, t_last_idx) in self.#name {
let mut sum = #per_thing::zero();
let mut inners_parsed = inners
.iter()
.map(|(ref t_idx, p)| {
sum = _npos::sp_arithmetic::traits::Saturating::saturating_add(sum, *p);
let target = target_at(*t_idx).or_invalid_index()?;
Ok((target, *p))
})
.collect::<Result<_npos::sp_std::prelude::Vec<(A, #per_thing)>, _npos::Error>>()?;
if sum >= #per_thing::one() {
return Err(_npos::Error::CompactStakeOverflow);
}
// defensive only. Since Percent doesn't have `Sub`.
let p_last = _npos::sp_arithmetic::traits::Saturating::saturating_sub(
#per_thing::one(),
sum,
);
inners_parsed.push((target_at(t_last_idx).or_invalid_index()?, p_last));
assignments.push(_npos::Assignment {
who: voter_at(voter_index).or_invalid_index()?,
distribution: inners_parsed,
});
}
)
})
.collect::<TokenStream2>();
quote!(
#into_impl_single
#into_impl_double
#into_impl_rest
)
}
@@ -1,499 +0,0 @@
// This file is part of Substrate.
// Copyright (C) 2020-2021 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 compact assignment.
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 assignment;
mod codec;
mod index_assignment;
// prefix used for struct fields in compact.
const PREFIX: &'static str = "votes";
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 way. This can encode a structure
/// which is the equivalent of a `sp_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`.
///
/// 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 8 edges per voter.
///
/// ```
/// # use sp_npos_elections_compact::generate_solution_type;
/// # use sp_arithmetic::per_things::Perbill;
/// generate_solution_type!(pub struct TestSolution::<
/// VoterIndex = u16,
/// TargetIndex = u8,
/// Accuracy = Perbill,
/// >(8));
/// ```
///
/// The given struct provides function to convert from/to Assignment:
///
/// - `fn from_assignment<..>(..)`
/// - `fn into_assignment<..>(..)`
///
/// The generated struct is by default deriving both `Encode` and `Decode`. This is okay but could
/// lead to many 0s 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 sp_npos_elections_compact::generate_solution_type;
/// # use sp_arithmetic::per_things::Perbill;
/// generate_solution_type!(
/// #[compact]
/// pub struct TestSolutionCompact::<VoterIndex = u16, TargetIndex = u8, Accuracy = Perbill>(8)
/// );
/// ```
#[proc_macro]
pub fn generate_solution_type(item: TokenStream) -> TokenStream {
let SolutionDef { vis, ident, count, voter_type, target_type, weight_type, compact_encoding } =
syn::parse_macro_input!(item as SolutionDef);
let imports = imports().unwrap_or_else(|e| e.to_compile_error());
let solution_struct = struct_def(
vis,
ident,
count,
voter_type.clone(),
target_type.clone(),
weight_type.clone(),
compact_encoding,
)
.unwrap_or_else(|e| e.to_compile_error());
quote!(
#imports
#solution_struct
)
.into()
}
fn struct_def(
vis: syn::Visibility,
ident: syn::Ident,
count: usize,
voter_type: syn::Type,
target_type: syn::Type,
weight_type: syn::Type,
compact_encoding: bool,
) -> Result<TokenStream2> {
if count <= 2 {
Err(syn_err("cannot build compact solution struct with capacity less than 3."))?
}
let singles = {
let name = field_name_for(1);
// NOTE: we use the visibility of the struct for the fields as well.. could be made better.
quote!(
#vis #name: _npos::sp_std::prelude::Vec<(#voter_type, #target_type)>,
)
};
let doubles = {
let name = field_name_for(2);
quote!(
#vis #name: _npos::sp_std::prelude::Vec<(#voter_type, (#target_type, #weight_type), #target_type)>,
)
};
let rest = (3..=count)
.map(|c| {
let field_name = field_name_for(c);
let array_len = c - 1;
quote!(
#vis #field_name: _npos::sp_std::prelude::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 = codec::codec_impl(
ident.clone(),
voter_type.clone(),
target_type.clone(),
weight_type.clone(),
count,
);
quote! {
#compact_impl
#[derive(Default, PartialEq, Eq, Clone, Debug, PartialOrd, Ord)]
}
} else {
// automatically derived.
quote!(#[derive(Default, PartialEq, Eq, Clone, Debug, _npos::codec::Encode, _npos::codec::Decode)])
};
let from_impl = assignment::from_impl(count);
let into_impl = assignment::into_impl(count, weight_type.clone());
let from_index_impl = index_assignment::from_impl(count);
Ok(quote! (
/// A struct to encode a election assignment in a compact way.
#derives_and_maybe_compact_encoding
#vis struct #ident { #singles #doubles #rest }
use _npos::__OrInvalidIndex;
impl _npos::CompactSolution for #ident {
const LIMIT: usize = #count;
type Voter = #voter_type;
type Target = #target_type;
type Accuracy = #weight_type;
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) -> _npos::sp_std::prelude::Vec<Self::Target> {
// NOTE: this implementation returns the targets sorted, but we don't use it yet per
// se, nor is the API enforcing it.
use _npos::sp_std::collections::btree_set::BTreeSet;
let mut all_targets: BTreeSet<Self::Target> = BTreeSet::new();
let mut maybe_insert_target = |t: Self::Target| {
all_targets.insert(t);
};
#unique_targets_impl
all_targets.into_iter().collect()
}
fn remove_voter(&mut self, to_remove: Self::Voter) -> bool {
#remove_voter_impl
return false
}
fn from_assignment<FV, FT, A>(
assignments: &[_npos::Assignment<A, #weight_type>],
index_of_voter: FV,
index_of_target: FT,
) -> Result<Self, _npos::Error>
where
A: _npos::IdentifierT,
for<'r> FV: Fn(&'r A) -> Option<Self::Voter>,
for<'r> FT: Fn(&'r A) -> Option<Self::Target>,
{
let mut compact: #ident = Default::default();
for _npos::Assignment { who, distribution } in assignments {
match distribution.len() {
0 => continue,
#from_impl
_ => {
return Err(_npos::Error::CompactTargetOverflow);
}
}
};
Ok(compact)
}
fn into_assignment<A: _npos::IdentifierT>(
self,
voter_at: impl Fn(Self::Voter) -> Option<A>,
target_at: impl Fn(Self::Target) -> Option<A>,
) -> Result<_npos::sp_std::prelude::Vec<_npos::Assignment<A, #weight_type>>, _npos::Error> {
let mut assignments: _npos::sp_std::prelude::Vec<_npos::Assignment<A, #weight_type>> = Default::default();
#into_impl
Ok(assignments)
}
}
type __IndexAssignment = _npos::IndexAssignment<
<#ident as _npos::CompactSolution>::Voter,
<#ident as _npos::CompactSolution>::Target,
<#ident as _npos::CompactSolution>::Accuracy,
>;
impl<'a> _npos::sp_std::convert::TryFrom<&'a [__IndexAssignment]> for #ident {
type Error = _npos::Error;
fn try_from(index_assignments: &'a [__IndexAssignment]) -> Result<Self, Self::Error> {
let mut compact = #ident::default();
for _npos::IndexAssignment { who, distribution } in index_assignments {
match distribution.len() {
0 => {}
#from_index_impl
_ => {
return Err(_npos::Error::CompactTargetOverflow);
}
}
};
Ok(compact)
}
}
))
}
fn remove_voter_impl(count: usize) -> TokenStream2 {
let field_name = field_name_for(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 field_name = field_name_for(2);
let double = quote! {
if let Some(idx) = self.#field_name.iter().position(|(x, _, _)| *x == to_remove) {
self.#field_name.remove(idx);
return true
}
};
let rest = (3..=count)
.map(|c| {
let field_name = field_name_for(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
#double
#rest
}
}
fn len_impl(count: usize) -> TokenStream2 {
(1..=count)
.map(|c| {
let field_name = field_name_for(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 = field_name_for(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 = field_name_for(1);
quote! {
self.#field_name.iter().for_each(|(_, t)| {
maybe_insert_target(*t);
});
}
};
let unique_targets_impl_double = {
let field_name = field_name_for(2);
quote! {
self.#field_name.iter().for_each(|(_, (t1, _), t2)| {
maybe_insert_target(*t1);
maybe_insert_target(*t2);
});
}
};
let unique_targets_impl_rest = (3..=count)
.map(|c| {
let field_name = field_name_for(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_double
#unique_targets_impl_rest
}
}
fn imports() -> Result<TokenStream2> {
match crate_name("sp-npos-elections") {
Ok(FoundCrate::Itself) => Ok(quote! { use crate as _npos; }),
Ok(FoundCrate::Name(sp_npos_elections)) => {
let ident = syn::Ident::new(&sp_npos_elections, Span::call_site());
Ok(quote!( extern crate #ident as _npos; ))
},
Err(e) => Err(syn::Error::new(Span::call_site(), e)),
}
}
struct SolutionDef {
vis: syn::Visibility,
ident: syn::Ident,
voter_type: syn::Type,
target_type: syn::Type,
weight_type: syn::Type,
count: usize,
compact_encoding: bool,
}
fn check_compact_attr(input: ParseStream) -> Result<bool> {
let mut attrs = input.call(syn::Attribute::parse_outer).unwrap_or_default();
if attrs.len() == 1 {
let attr = attrs.pop().expect("Vec with len 1 can be popped.");
if attr.path.segments.len() == 1 {
let segment = attr.path.segments.first().expect("Vec with len 1 can be popped.");
if segment.ident == Ident::new("compact", Span::call_site()) {
Ok(true)
} else {
Err(syn_err("generate_solution_type macro can only accept #[compact] attribute."))
}
} else {
Err(syn_err("generate_solution_type macro can only accept #[compact] attribute."))
}
} else {
Ok(false)
}
}
/// `#[compact] pub struct CompactName::<VoterIndex = u32, TargetIndex = u32, Accuracy = u32>()`
impl Parse for SolutionDef {
fn parse(input: ParseStream) -> syn::Result<Self> {
// optional #[compact]
let compact_encoding = check_compact_attr(input)?;
// <vis> struct <name>
let vis: syn::Visibility = input.parse()?;
let _ = <syn::Token![struct]>::parse(input)?;
let ident: syn::Ident = input.parse()?;
// ::<V, T, W>
let _ = <syn::Token![::]>::parse(input)?;
let generics: syn::AngleBracketedGenericArguments = input.parse()?;
if generics.args.len() != 3 {
return Err(syn_err("Must provide 3 generic args."))
}
let expected_types = ["VoterIndex", "TargetIndex", "Accuracy"];
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::Binding(syn::Binding { 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 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 expr = count_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.")),
};
let count = int_lit.base10_parse::<usize>()?;
Ok(Self { vis, ident, voter_type, target_type, weight_type, count, compact_encoding })
}
}
fn field_name_for(n: usize) -> Ident {
Ident::new(&format!("{}{}", PREFIX, n), Span::call_site())
}
#[cfg(test)]
mod tests {
#[test]
fn ui_fail() {
let cases = trybuild::TestCases::new();
cases.compile_fail("tests/ui/fail/*.rs");
}
}
@@ -1,12 +1,12 @@
[package]
name = "sp-npos-elections-compact"
name = "sp-npos-elections-solution-type"
version = "4.0.0-dev"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
license = "Apache-2.0"
homepage = "https://substrate.dev"
repository = "https://github.com/paritytech/substrate/"
description = "NPoS Compact Solution Type"
description = "NPoS Solution Type"
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
@@ -22,6 +22,6 @@ proc-macro-crate = "1.0.0"
[dev-dependencies]
parity-scale-codec = "2.0.1"
sp-arithmetic = { path = "../../arithmetic" , version = "4.0.0-dev"}
sp-npos-elections = { path = ".." , version = "4.0.0-dev"}
sp-arithmetic = { path = "../../arithmetic", version = "4.0.0-dev"}
sp-npos-elections = { path = "..", version = "4.0.0-dev"}
trybuild = "1.0.43"
@@ -17,7 +17,7 @@
//! Code generation for the ratio assignment type' encode/decode impl.
use crate::field_name_for;
use crate::vote_field;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
@@ -45,7 +45,7 @@ fn decode_impl(
count: usize,
) -> TokenStream2 {
let decode_impl_single = {
let name = field_name_for(1);
let name = vote_field(1);
quote! {
let #name =
<
@@ -60,29 +60,9 @@ fn decode_impl(
}
};
let decode_impl_double = {
let name = field_name_for(2);
quote! {
let #name =
<
_npos::sp_std::prelude::Vec<(
_npos::codec::Compact<#voter_type>,
(_npos::codec::Compact<#target_type>, _npos::codec::Compact<#weight_type>),
_npos::codec::Compact<#target_type>,
)>
as
_npos::codec::Decode
>::decode(value)?;
let #name = #name
.into_iter()
.map(|(v, (t1, w), t2)| (v.0, (t1.0, w.0), t2.0))
.collect::<_npos::sp_std::prelude::Vec<_>>();
}
};
let decode_impl_rest = (3..=count)
let decode_impl_rest = (2..=count)
.map(|c| {
let name = field_name_for(c);
let name = vote_field(c);
let inner_impl = (0..c - 1)
.map(|i| quote! { ( (inner[#i].0).0, (inner[#i].1).0 ), })
@@ -112,7 +92,7 @@ fn decode_impl(
let all_field_names = (1..=count)
.map(|c| {
let name = field_name_for(c);
let name = vote_field(c);
quote! { #name, }
})
.collect::<TokenStream2>();
@@ -121,7 +101,6 @@ fn decode_impl(
impl _npos::codec::Decode for #ident {
fn decode<I: _npos::codec::Input>(value: &mut I) -> Result<Self, _npos::codec::Error> {
#decode_impl_single
#decode_impl_double
#decode_impl_rest
// The above code generates variables with the decoded value with the same name as
@@ -137,7 +116,7 @@ fn decode_impl(
// `Encode` implementation.
fn encode_impl(ident: syn::Ident, count: usize) -> TokenStream2 {
let encode_impl_single = {
let name = field_name_for(1);
let name = vote_field(1);
quote! {
let #name = self.#name
.iter()
@@ -150,30 +129,12 @@ fn encode_impl(ident: syn::Ident, count: usize) -> TokenStream2 {
}
};
let encode_impl_double = {
let name = field_name_for(2);
quote! {
let #name = self.#name
.iter()
.map(|(v, (t1, w), t2)| (
_npos::codec::Compact(v.clone()),
(
_npos::codec::Compact(t1.clone()),
_npos::codec::Compact(w.clone())
),
_npos::codec::Compact(t2.clone()),
))
.collect::<_npos::sp_std::prelude::Vec<_>>();
#name.encode_to(&mut r);
}
};
let encode_impl_rest = (3..=count)
let encode_impl_rest = (2..=count)
.map(|c| {
let name = field_name_for(c);
let name = vote_field(c);
// we use the knowledge of the length to avoid copy_from_slice.
let inners_compact_array = (0..c - 1)
let inners_solution_array = (0..c - 1)
.map(|i| {
quote! {(
_npos::codec::Compact(inner[#i].0.clone()),
@@ -187,7 +148,7 @@ fn encode_impl(ident: syn::Ident, count: usize) -> TokenStream2 {
.iter()
.map(|(v, inner, t_last)| (
_npos::codec::Compact(v.clone()),
[ #inners_compact_array ],
[ #inners_solution_array ],
_npos::codec::Compact(t_last.clone()),
))
.collect::<_npos::sp_std::prelude::Vec<_>>();
@@ -201,7 +162,6 @@ fn encode_impl(ident: syn::Ident, count: usize) -> TokenStream2 {
fn encode(&self) -> _npos::sp_std::prelude::Vec<u8> {
let mut r = vec![];
#encode_impl_single
#encode_impl_double
#encode_impl_rest
r
}
@@ -0,0 +1,56 @@
// This file is part of Substrate.
// Copyright (C) 2020-2021 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,
)
)
)
}
@@ -15,16 +15,16 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//! Code generation for getting the compact representation from the `IndexAssignment` type.
//! Code generation for getting the solution representation from the `IndexAssignment` type.
use crate::field_name_for;
use crate::vote_field;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
pub(crate) fn from_impl(count: usize) -> TokenStream2 {
pub(crate) fn from_impl(struct_name: &syn::Ident, count: usize) -> TokenStream2 {
let from_impl_single = {
let name = field_name_for(1);
quote!(1 => compact.#name.push(
let name = vote_field(1);
quote!(1 => #struct_name.#name.push(
(
*who,
distribution[0].0,
@@ -32,32 +32,18 @@ pub(crate) fn from_impl(count: usize) -> TokenStream2 {
),)
};
let from_impl_double = {
let name = field_name_for(2);
quote!(2 => compact.#name.push(
(
*who,
(
distribution[0].0,
distribution[0].1,
),
distribution[1].0,
)
),)
};
let from_impl_rest = (3..=count)
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 = field_name_for(c);
let field_name = vote_field(c);
let last_index = c - 1;
let last = quote!(distribution[#last_index].0);
quote!(
#c => compact.#field_name.push(
#c => #struct_name.#field_name.push(
(
*who,
[#inner],
@@ -70,7 +56,6 @@ pub(crate) fn from_impl(count: usize) -> TokenStream2 {
quote!(
#from_impl_single
#from_impl_double
#from_impl_rest
)
}
@@ -0,0 +1,243 @@
// This file is part of Substrate.
// Copyright (C) 2020-2021 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 `sp_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`.
///
/// 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 sp_npos_elections_solution_type::generate_solution_type;
/// # use sp_arithmetic::per_things::Perbill;
/// generate_solution_type!(pub struct TestSolution::<
/// VoterIndex = u16,
/// TargetIndex = u8,
/// Accuracy = Perbill,
/// >(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
/// [`sp_npos_elections::Solution`] 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 sp_npos_elections_solution_type::generate_solution_type;
/// # use sp_npos_elections::NposSolution;
/// # use sp_arithmetic::per_things::Perbill;
/// generate_solution_type!(
/// #[compact]
/// pub struct TestSolutionCompact::<VoterIndex = u16, TargetIndex = u8, Accuracy = Perbill>(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,
count: usize,
compact_encoding: bool,
}
fn check_attributes(input: ParseStream) -> syn::Result<bool> {
let attrs = input.call(syn::Attribute::parse_outer).unwrap_or_default();
if attrs.len() > 1 {
return Err(syn_err("compact solution can accept only #[compact]"))
}
Ok(attrs.iter().any(|attr| {
if attr.path.segments.len() == 1 {
let segment = attr.path.segments.first().expect("Vec with len 1 can be popped.");
if segment.ident == Ident::new("compact", Span::call_site()) {
return true
}
}
false
}))
}
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()?;
let _ = <syn::Token![struct]>::parse(input)?;
let ident: syn::Ident = input.parse()?;
// ::<V, T, W>
let _ = <syn::Token![::]>::parse(input)?;
let generics: syn::AngleBracketedGenericArguments = input.parse()?;
if generics.args.len() != 3 {
return Err(syn_err("Must provide 3 generic args."))
}
let expected_types = ["VoterIndex", "TargetIndex", "Accuracy"];
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::Binding(syn::Binding { 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 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, 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("sp-npos-elections") {
Ok(FoundCrate::Itself) => Ok(quote! { use crate as _npos; }),
Ok(FoundCrate::Name(sp_npos_elections)) => {
let ident = syn::Ident::new(&sp_npos_elections, Span::call_site());
Ok(quote!( extern crate #ident as _npos; ))
},
Err(e) => Err(syn::Error::new(Span::call_site(), e)),
}
}
#[cfg(test)]
mod tests {
#[test]
fn ui_fail() {
let cases = trybuild::TestCases::new();
cases.compile_fail("tests/ui/fail/*.rs");
}
}
@@ -0,0 +1,354 @@
// This file is part of Substrate.
// Copyright (C) 2019-2021 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,
compact_encoding,
} = def;
if count <= 2 {
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: _npos::sp_std::prelude::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: _npos::sp_std::prelude::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_impl(
ident.clone(),
voter_type.clone(),
target_type.clone(),
weight_type.clone(),
count,
);
quote! {
#compact_impl
#[derive(Default, PartialEq, Eq, Clone, Debug, PartialOrd, Ord)]
}
} else {
// automatically derived.
quote!(#[derive(Default, PartialEq, Eq, Clone, Debug, _npos::codec::Encode, _npos::codec::Decode)])
};
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);
Ok(quote! (
/// A struct to encode a election assignment in a compact way.
#derives_and_maybe_compact_encoding
#vis struct #ident { #single #rest }
use _npos::__OrInvalidIndex;
impl _npos::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: &[_npos::Assignment<A, #weight_type>],
voter_index: FV,
target_index: FT,
) -> Result<Self, _npos::Error>
where
A: _npos::IdentifierT,
for<'r> FV: Fn(&'r A) -> Option<Self::VoterIndex>,
for<'r> FT: Fn(&'r A) -> Option<Self::TargetIndex>,
{
let mut #struct_name: #ident = Default::default();
for _npos::Assignment { who, distribution } in assignments {
match distribution.len() {
0 => continue,
#from_impl
_ => {
return Err(_npos::Error::SolutionTargetOverflow);
}
}
};
Ok(#struct_name)
}
fn into_assignment<A: _npos::IdentifierT>(
self,
voter_at: impl Fn(Self::VoterIndex) -> Option<A>,
target_at: impl Fn(Self::TargetIndex) -> Option<A>,
) -> Result<_npos::sp_std::prelude::Vec<_npos::Assignment<A, #weight_type>>, _npos::Error> {
let mut #assignment_name: _npos::sp_std::prelude::Vec<_npos::Assignment<A, #weight_type>> = Default::default();
#into_impl
Ok(#assignment_name)
}
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) -> _npos::sp_std::prelude::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 _npos::sp_std::collections::btree_set::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()
}
}
type __IndexAssignment = _npos::IndexAssignment<
<#ident as _npos::NposSolution>::VoterIndex,
<#ident as _npos::NposSolution>::TargetIndex,
<#ident as _npos::NposSolution>::Accuracy,
>;
impl<'a> _npos::sp_std::convert::TryFrom<&'a [__IndexAssignment]> for #ident {
type Error = _npos::Error;
fn try_from(index_assignments: &'a [__IndexAssignment]) -> Result<Self, Self::Error> {
let mut #struct_name = #ident::default();
for _npos::IndexAssignment { who, distribution } in index_assignments {
match distribution.len() {
0 => {}
#from_index_impl
_ => {
return Err(_npos::Error::SolutionTargetOverflow);
}
}
};
Ok(#struct_name)
}
}
))
}
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 {
#assignments.push(_npos::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 {
let mut sum = #per_thing::zero();
let mut inners_parsed = inners
.iter()
.map(|(ref t_idx, p)| {
sum = _npos::sp_arithmetic::traits::Saturating::saturating_add(sum, *p);
let target = target_at(*t_idx).or_invalid_index()?;
Ok((target, *p))
})
.collect::<Result<_npos::sp_std::prelude::Vec<(A, #per_thing)>, _npos::Error>>()?;
if sum >= #per_thing::one() {
return Err(_npos::Error::SolutionWeightOverflow);
}
// defensive only. Since Percent doesn't have `Sub`.
let p_last = _npos::sp_arithmetic::traits::Saturating::saturating_sub(
#per_thing::one(),
sum,
);
inners_parsed.push((target_at(t_last_idx).or_invalid_index()?, p_last));
#assignments.push(_npos::Assignment {
who: voter_at(voter_index).or_invalid_index()?,
distribution: inners_parsed,
});
}
)
})
.collect::<TokenStream2>();
quote!(
#into_impl_single
#into_impl_rest
)
}
@@ -1,4 +1,4 @@
use sp_npos_elections_compact::generate_solution_type;
use sp_npos_elections_solution_type::generate_solution_type;
generate_solution_type!(pub struct TestSolution::<
VoterIndex = u16,
@@ -1,4 +1,4 @@
use sp_npos_elections_compact::generate_solution_type;
use sp_npos_elections_solution_type::generate_solution_type;
generate_solution_type!(pub struct TestSolution::<
VoterIndex = u16,
@@ -1,4 +1,4 @@
use sp_npos_elections_compact::generate_solution_type;
use sp_npos_elections_solution_type::generate_solution_type;
generate_solution_type!(pub struct TestSolution::<
u16,
@@ -1,4 +1,4 @@
use sp_npos_elections_compact::generate_solution_type;
use sp_npos_elections_solution_type::generate_solution_type;
generate_solution_type!(pub struct TestSolution::<
u16,
@@ -1,4 +1,4 @@
use sp_npos_elections_compact::generate_solution_type;
use sp_npos_elections_solution_type::generate_solution_type;
generate_solution_type!(pub struct TestSolution::<
TargetIndex = u16,
@@ -0,0 +1,11 @@
use sp_npos_elections_solution_type::generate_solution_type;
generate_solution_type!(
#[pages(1)] pub struct TestSolution::<
VoterIndex = u8,
TargetIndex = u16,
Accuracy = Perbill,
>(8)
);
fn main() {}
@@ -0,0 +1,38 @@
error[E0412]: cannot find type `Perbill` in this scope
--> $DIR/wrong_page.rs:7:14
|
7 | Accuracy = Perbill,
| ^^^^^^^ not found in this scope
|
help: consider importing this struct
|
1 | use sp_arithmetic::Perbill;
|
error[E0433]: failed to resolve: use of undeclared type `Perbill`
--> $DIR/wrong_page.rs:7:14
|
7 | Accuracy = Perbill,
| ^^^^^^^ not found in this scope
|
help: consider importing this struct
|
1 | use sp_arithmetic::Perbill;
|
error[E0119]: conflicting implementations of trait `std::convert::TryFrom<&[_npos::IndexAssignment<u8, u16, [type error]>]>` for type `TestSolution`
--> $DIR/wrong_page.rs:3:1
|
3 | / generate_solution_type!(
4 | | #[pages(1)] pub struct TestSolution::<
5 | | VoterIndex = u8,
6 | | TargetIndex = u16,
7 | | Accuracy = Perbill,
8 | | >(8)
9 | | );
| |__^
|
= note: conflicting implementation in crate `core`:
- impl<T, U> TryFrom<U> for T
where U: Into<T>;
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
@@ -167,11 +167,11 @@ impl<AccountId> StakedAssignment<AccountId> {
}
}
/// The [`IndexAssignment`] type is an intermediate between the assignments list
/// ([`&[Assignment<T>]`][Assignment]) and `CompactOf<T>`.
/// ([`&[Assignment<T>]`][Assignment]) and `SolutionOf<T>`.
///
/// The voter and target identifiers have already been replaced with appropriate indices,
/// making it fast to repeatedly encode into a `CompactOf<T>`. This property turns out
/// to be important when trimming for compact length.
/// making it fast to repeatedly encode into a `SolutionOf<T>`. This property turns out
/// to be important when trimming for solution length.
#[derive(RuntimeDebug, Clone, Default)]
#[cfg_attr(feature = "std", derive(PartialEq, Eq, Encode, Decode))]
pub struct IndexAssignment<VoterIndex, TargetIndex, P: PerThing> {
@@ -201,9 +201,9 @@ impl<VoterIndex, TargetIndex, P: PerThing> IndexAssignment<VoterIndex, TargetInd
}
}
/// A type alias for [`IndexAssignment`] made from [`crate::CompactSolution`].
/// A type alias for [`IndexAssignment`] made from [`crate::Solution`].
pub type IndexAssignmentOf<C> = IndexAssignment<
<C as crate::CompactSolution>::Voter,
<C as crate::CompactSolution>::Target,
<C as crate::CompactSolution>::Accuracy,
<C as crate::NposSolution>::VoterIndex,
<C as crate::NposSolution>::TargetIndex,
<C as crate::NposSolution>::Accuracy,
>;
+25 -155
View File
@@ -74,21 +74,9 @@
#![cfg_attr(not(feature = "std"), no_std)]
use sp_arithmetic::{
traits::{Bounded, UniqueSaturatedInto, Zero},
Normalizable, PerThing, Rational128, ThresholdOrd,
};
use sp_arithmetic::{traits::Zero, Normalizable, PerThing, Rational128, ThresholdOrd};
use sp_core::RuntimeDebug;
use sp_std::{
cell::RefCell,
cmp::Ordering,
collections::btree_map::BTreeMap,
convert::{TryFrom, TryInto},
fmt::Debug,
ops::Mul,
prelude::*,
rc::Rc,
};
use sp_std::{cell::RefCell, cmp::Ordering, collections::btree_map::BTreeMap, prelude::*, rc::Rc};
use codec::{Decode, Encode};
#[cfg(feature = "std")]
@@ -107,6 +95,7 @@ pub mod phragmen;
pub mod phragmms;
pub mod pjr;
pub mod reduce;
pub mod traits;
pub use assignments::{Assignment, IndexAssignment, IndexAssignmentOf, StakedAssignment};
pub use balancing::*;
@@ -115,8 +104,9 @@ pub use phragmen::*;
pub use phragmms::*;
pub use pjr::*;
pub use reduce::reduce;
pub use traits::{IdentifierT, NposSolution, PerThing128, __OrInvalidIndex};
// re-export the compact macro, with the dependencies of the macro.
// re-export for the solution macro, with the dependencies of the macro.
#[doc(hidden)]
pub use codec;
#[doc(hidden)]
@@ -124,141 +114,21 @@ pub use sp_arithmetic;
#[doc(hidden)]
pub use sp_std;
/// Simple Extension trait to easily convert `None` from index closures to `Err`.
///
/// This is only generated and re-exported for the compact solution code to use.
#[doc(hidden)]
pub trait __OrInvalidIndex<T> {
fn or_invalid_index(self) -> Result<T, Error>;
}
// re-export the solution type macro.
pub use sp_npos_elections_solution_type::generate_solution_type;
impl<T> __OrInvalidIndex<T> for Option<T> {
fn or_invalid_index(self) -> Result<T, Error> {
self.ok_or(Error::CompactInvalidIndex)
}
}
/// A common interface for all compact solutions.
///
/// See [`sp-npos-elections-compact`] for more info.
pub trait CompactSolution
where
Self: Sized + for<'a> sp_std::convert::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 Voter: UniqueSaturatedInto<usize>
+ TryInto<usize>
+ TryFrom<usize>
+ Debug
+ Copy
+ Clone
+ Bounded;
/// The target type. Needs to be an index (convert to usize).
type Target: UniqueSaturatedInto<usize>
+ TryInto<usize>
+ TryFrom<usize>
+ Debug
+ Copy
+ Clone
+ Bounded;
/// The weight/accuracy type of each vote.
type Accuracy: PerThing128;
/// 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::Voter>,
for<'r> FT: Fn(&'r A) -> Option<Self::Target>;
/// Convert self into a `Vec<Assignment<A, Self::Accuracy>>`
fn into_assignment<A: IdentifierT>(
self,
voter_at: impl Fn(Self::Voter) -> Option<A>,
target_at: impl Fn(Self::Target) -> Option<A>,
) -> Result<Vec<Assignment<A, Self::Accuracy>>, Error>;
/// 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::Target>;
/// Get the average edge count.
fn average_edge_count(&self) -> usize {
self.edge_count().checked_div(self.voter_count()).unwrap_or(0)
}
/// 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 from
/// `self.len()`.
fn remove_voter(&mut self, to_remove: Self::Voter) -> bool;
/// Compute the score of this compact solution type.
fn score<A, FS>(
self,
winners: &[A],
stake_of: FS,
voter_at: impl Fn(Self::Voter) -> Option<A>,
target_at: impl Fn(Self::Target) -> 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 = helpers::assignment_ratio_to_staked_normalized(ratio, stake_of)?;
let supports = to_supports(winners, &staked)?;
Ok(supports.evaluate())
}
}
// re-export the compact solution type.
pub use sp_npos_elections_compact::generate_solution_type;
/// an aggregator trait for a generic type of a voter/target identifier. This usually maps to
/// substrate's account id.
pub trait IdentifierT: Clone + Eq + Default + Ord + Debug + codec::Codec {}
impl<T: Clone + Eq + Default + Ord + Debug + codec::Codec> IdentifierT for T {}
/// Aggregator trait for a PerThing that can be multiplied by u128 (ExtendedBalance).
pub trait PerThing128: PerThing + Mul<ExtendedBalance, Output = ExtendedBalance> {}
impl<T: PerThing + Mul<ExtendedBalance, Output = ExtendedBalance>> PerThing128 for T {}
/// The errors that might occur in the this crate and compact.
/// The errors that might occur in the this crate and solution-type.
#[derive(Eq, PartialEq, RuntimeDebug)]
pub enum Error {
/// While going from compact to staked, the stake of all the edges has gone above the total and
/// the last stake cannot be assigned.
CompactStakeOverflow,
/// The compact type has a voter who's number of targets is out of bound.
CompactTargetOverflow,
/// While going from solution indices to ratio, the weight of all the edges has gone above the
/// total.
SolutionWeightOverflow,
/// The solution type has a voter who's number of targets is out of bound.
SolutionTargetOverflow,
/// One of the index functions returned none.
CompactInvalidIndex,
SolutionInvalidIndex,
/// One of the page indices was invalid
SolutionInvalidPageIndex,
/// An error occurred in some arithmetic operation.
ArithmeticError(&'static str),
/// The data provided to create support map was invalid.
@@ -507,12 +377,12 @@ impl<A> FlattenSupportMap<A> for SupportMap<A> {
///
/// The list of winners is basically a redundancy for error checking only; It ensures that all the
/// targets pointed to by the [`Assignment`] are present in the `winners`.
pub fn to_support_map<A: IdentifierT>(
winners: &[A],
assignments: &[StakedAssignment<A>],
) -> Result<SupportMap<A>, Error> {
pub fn to_support_map<AccountId: IdentifierT>(
winners: &[AccountId],
assignments: &[StakedAssignment<AccountId>],
) -> Result<SupportMap<AccountId>, Error> {
// Initialize the support of each candidate.
let mut supports = <SupportMap<A>>::new();
let mut supports = <SupportMap<AccountId>>::new();
winners.iter().for_each(|e| {
supports.insert(e.clone(), Default::default());
});
@@ -535,10 +405,10 @@ pub fn to_support_map<A: IdentifierT>(
/// flat vector.
///
/// Similar to [`to_support_map`], `winners` is used for error checking.
pub fn to_supports<A: IdentifierT>(
winners: &[A],
assignments: &[StakedAssignment<A>],
) -> Result<Supports<A>, Error> {
pub fn to_supports<AccountId: IdentifierT>(
winners: &[AccountId],
assignments: &[StakedAssignment<AccountId>],
) -> Result<Supports<AccountId>, Error> {
to_support_map(winners, assignments).map(FlattenSupportMap::flatten)
}
+37 -19
View File
@@ -17,7 +17,7 @@
//! Mock file for npos-elections.
#![cfg(any(test, mocks))]
#![cfg(test)]
use std::{
collections::{HashMap, HashSet},
@@ -35,20 +35,27 @@ use sp_std::collections::btree_map::BTreeMap;
use crate::{seq_phragmen, Assignment, ElectionResult, ExtendedBalance, PerThing128, VoteWeight};
sp_npos_elections_compact::generate_solution_type!(
#[compact]
pub struct Compact::<VoterIndex = u32, TargetIndex = u16, Accuracy = Accuracy>(16)
);
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 CandidateId = AccountId;
pub type Accuracy = sp_runtime::Perbill;
pub type TestAccuracy = sp_runtime::Perbill;
pub type MockAssignment = crate::Assignment<AccountId, Accuracy>;
crate::generate_solution_type! {
pub struct TestSolution::<
VoterIndex = u32,
TargetIndex = u16,
Accuracy = TestAccuracy,
>(16)
}
pub fn p(p: u8) -> TestAccuracy {
TestAccuracy::from_percent(p.into())
}
pub type MockAssignment = crate::Assignment<AccountId, TestAccuracy>;
pub type Voter = (AccountId, VoteWeight, Vec<AccountId>);
#[derive(Default, Debug)]
@@ -422,7 +429,7 @@ pub fn generate_random_votes(
candidate_count: usize,
voter_count: usize,
mut rng: impl Rng,
) -> (Vec<Voter>, Vec<MockAssignment>, Vec<CandidateId>) {
) -> (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);
@@ -452,7 +459,8 @@ pub fn generate_random_votes(
// 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(16));
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));
@@ -473,16 +481,16 @@ pub fn generate_random_votes(
// distribute the available stake randomly
let stake_distribution = if num_chosen_winners == 0 {
Vec::new()
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);
stake_distribution.push(Accuracy::from_perthousand(stake));
let stake = rng.gen_range(0, available_stake).min(1);
stake_distribution.push(TestAccuracy::from_perthousand(stake));
available_stake -= stake;
}
stake_distribution.push(Accuracy::from_perthousand(available_stake));
stake_distribution.push(TestAccuracy::from_perthousand(available_stake));
stake_distribution.shuffle(&mut rng);
stake_distribution
};
@@ -514,16 +522,26 @@ where
usize: TryInto<VoterIndex>,
{
let cache = generate_cache(voters.iter().map(|(id, _, _)| *id));
move |who| cache.get(who).cloned().and_then(|i| i.try_into().ok())
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: &[CandidateId],
) -> impl Fn(&CandidateId) -> Option<TargetIndex>
candidates: &[AccountId],
) -> impl Fn(&AccountId) -> Option<TargetIndex>
where
usize: TryInto<TargetIndex>,
{
let cache = generate_cache(candidates.iter().cloned());
move |who| cache.get(who).cloned().and_then(|i| i.try_into().ok())
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())
}
}
+120 -188
View File
@@ -19,8 +19,8 @@
use crate::{
balancing, helpers::*, is_score_better, mock::*, seq_phragmen, seq_phragmen_core, setup_inputs,
to_support_map, to_supports, Assignment, CompactSolution, ElectionResult, EvaluateSupport,
ExtendedBalance, IndexAssignment, StakedAssignment, Support, Voter,
to_support_map, to_supports, Assignment, ElectionResult, EvaluateSupport, ExtendedBalance,
IndexAssignment, NposSolution, StakedAssignment, Support, Voter,
};
use rand::{self, SeedableRng};
use sp_arithmetic::{PerU16, Perbill, Percent, Permill};
@@ -917,30 +917,20 @@ mod score {
}
mod solution_type {
use super::AccountId;
use super::*;
use codec::{Decode, Encode};
// these need to come from the same dev-dependency `sp-npos-elections`, not from the crate.
use crate::{generate_solution_type, Assignment, CompactSolution, Error as PhragmenError};
use sp_arithmetic::Percent;
use crate::{generate_solution_type, Assignment, Error as NposError, NposSolution};
use sp_std::{convert::TryInto, fmt::Debug};
type TestAccuracy = Percent;
generate_solution_type!(pub struct TestSolutionCompact::<
VoterIndex = u32,
TargetIndex = u8,
Accuracy = TestAccuracy,
>(16));
#[allow(dead_code)]
mod __private {
// This is just to make sure that that the compact can be generated in a scope without any
// This is just to make sure that the solution can be generated in a scope without any
// imports.
use crate::generate_solution_type;
use sp_arithmetic::Percent;
generate_solution_type!(
#[compact]
struct InnerTestSolutionCompact::<VoterIndex = u32, TargetIndex = u8, Accuracy = Percent>(12)
struct InnerTestSolutionIsolated::<VoterIndex = u32, TargetIndex = u8, Accuracy = sp_runtime::Percent>(12)
);
}
@@ -948,35 +938,34 @@ mod solution_type {
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 = Percent,
>(16));
let compact = InnerTestSolution {
generate_solution_type!(
pub struct InnerTestSolution::<
VoterIndex = u32,
TargetIndex = u32,
Accuracy = TestAccuracy,
>(16)
);
let solution = InnerTestSolution {
votes1: vec![(2, 20), (4, 40)],
votes2: vec![
(1, (10, TestAccuracy::from_percent(80)), 11),
(5, (50, TestAccuracy::from_percent(85)), 51),
],
votes2: vec![(1, [(10, p(80))], 11), (5, [(50, p(85))], 51)],
..Default::default()
};
compact.encode().len()
solution.encode().len()
};
let with_compact = {
generate_solution_type!(#[compact] pub struct InnerTestSolutionCompact::<
VoterIndex = u32,
TargetIndex = u32,
Accuracy = Percent,
>(16));
generate_solution_type!(
#[compact]
pub struct InnerTestSolutionCompact::<
VoterIndex = u32,
TargetIndex = u32,
Accuracy = TestAccuracy,
>(16)
);
let compact = InnerTestSolutionCompact {
votes1: vec![(2, 20), (4, 40)],
votes2: vec![
(1, (10, TestAccuracy::from_percent(80)), 11),
(5, (50, TestAccuracy::from_percent(85)), 51),
],
votes2: vec![(1, [(10, p(80))], 11), (5, [(50, p(85))], 51)],
..Default::default()
};
@@ -988,78 +977,64 @@ mod solution_type {
#[test]
fn solution_struct_is_codec() {
let compact = TestSolutionCompact {
let solution = TestSolution {
votes1: vec![(2, 20), (4, 40)],
votes2: vec![
(1, (10, TestAccuracy::from_percent(80)), 11),
(5, (50, TestAccuracy::from_percent(85)), 51),
],
votes2: vec![(1, [(10, p(80))], 11), (5, [(50, p(85))], 51)],
..Default::default()
};
let encoded = compact.encode();
let encoded = solution.encode();
assert_eq!(compact, Decode::decode(&mut &encoded[..]).unwrap());
assert_eq!(compact.voter_count(), 4);
assert_eq!(compact.edge_count(), 2 + 4);
assert_eq!(compact.unique_targets(), vec![10, 11, 20, 40, 50, 51]);
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 compact = TestSolutionCompact {
let mut solution = TestSolution {
votes1: vec![(0, 2), (1, 6)],
votes2: vec![
(2, (0, TestAccuracy::from_percent(80)), 1),
(3, (7, TestAccuracy::from_percent(85)), 8),
],
votes3: vec![(
4,
[(3, TestAccuracy::from_percent(50)), (4, TestAccuracy::from_percent(25))],
5,
)],
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!(!compact.remove_voter(11));
assert!(compact.remove_voter(2));
assert!(!solution.remove_voter(11));
assert!(solution.remove_voter(2));
assert_eq!(
compact,
TestSolutionCompact {
solution,
TestSolution {
votes1: vec![(0, 2), (1, 6)],
votes2: vec![(3, (7, TestAccuracy::from_percent(85)), 8),],
votes3: vec![(
4,
[(3, TestAccuracy::from_percent(50)), (4, TestAccuracy::from_percent(25))],
5,
),],
votes2: vec![(3, [(7, p(85))], 8)],
votes3: vec![(4, [(3, p(50)), (4, p(25))], 5,)],
..Default::default()
},
);
assert!(compact.remove_voter(4));
assert!(solution.remove_voter(4));
assert_eq!(
compact,
TestSolutionCompact {
solution,
TestSolution {
votes1: vec![(0, 2), (1, 6)],
votes2: vec![(3, (7, TestAccuracy::from_percent(85)), 8),],
votes2: vec![(3, [(7, p(85))], 8)],
..Default::default()
},
);
assert!(compact.remove_voter(1));
assert!(solution.remove_voter(1));
assert_eq!(
compact,
TestSolutionCompact {
solution,
TestSolution {
votes1: vec![(0, 2)],
votes2: vec![(3, (7, TestAccuracy::from_percent(85)), 8),],
votes2: vec![(3, [(7, p(85))], 8),],
..Default::default()
},
);
}
#[test]
fn basic_from_and_into_compact_works_assignments() {
fn from_and_into_assignment_works() {
let voters = vec![2 as AccountId, 4, 1, 5, 3];
let targets = vec![
10 as AccountId,
@@ -1074,182 +1049,144 @@ mod solution_type {
];
let assignments = vec![
Assignment {
who: 2 as AccountId,
distribution: vec![(20u64, TestAccuracy::from_percent(100))],
},
Assignment { who: 4, distribution: vec![(40, TestAccuracy::from_percent(100))] },
Assignment {
who: 1,
distribution: vec![
(10, TestAccuracy::from_percent(80)),
(11, TestAccuracy::from_percent(20)),
],
},
Assignment {
who: 5,
distribution: vec![
(50, TestAccuracy::from_percent(85)),
(51, TestAccuracy::from_percent(15)),
],
},
Assignment {
who: 3,
distribution: vec![
(30, TestAccuracy::from_percent(50)),
(31, TestAccuracy::from_percent(25)),
(32, TestAccuracy::from_percent(25)),
],
},
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<u8> {
let target_index = |a: &AccountId| -> Option<u16> {
targets.iter().position(|x| x == a).map(TryInto::try_into).unwrap().ok()
};
let compacted =
TestSolutionCompact::from_assignment(&assignments, voter_index, target_index).unwrap();
let solution =
TestSolution::from_assignment(&assignments, voter_index, target_index).unwrap();
// basically number of assignments that it is encoding.
assert_eq!(compacted.voter_count(), assignments.len());
assert_eq!(solution.voter_count(), assignments.len());
assert_eq!(
compacted.edge_count(),
solution.edge_count(),
assignments.iter().fold(0, |a, b| a + b.distribution.len()),
);
assert_eq!(
compacted,
TestSolutionCompact {
solution,
TestSolution {
votes1: vec![(0, 2), (1, 6)],
votes2: vec![
(2, (0, TestAccuracy::from_percent(80)), 1),
(3, (7, TestAccuracy::from_percent(85)), 8),
],
votes3: vec![(
4,
[(3, TestAccuracy::from_percent(50)), (4, TestAccuracy::from_percent(25))],
5,
),],
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!(compacted.unique_targets(), vec![0, 1, 2, 3, 4, 5, 6, 7, 8]);
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: u8| -> Option<AccountId> {
targets.get(<u8 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!(compacted.into_assignment(voter_at, target_at).unwrap(), assignments);
assert_eq!(solution.into_assignment(voter_at, target_at).unwrap(), assignments);
}
#[test]
fn unique_targets_len_edge_count_works() {
const ACC: TestAccuracy = TestAccuracy::from_percent(10);
// we don't really care about voters here so all duplicates. This is not invalid per se.
let compact = TestSolutionCompact {
let solution = TestSolution {
votes1: vec![(99, 1), (99, 2)],
votes2: vec![(99, (3, ACC.clone()), 7), (99, (4, ACC.clone()), 8)],
votes3: vec![(99, [(11, ACC.clone()), (12, ACC.clone())], 13)],
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, ACC.clone()),
(66, ACC.clone()),
(66, ACC.clone()),
(66, ACC.clone()),
(66, ACC.clone()),
(66, ACC.clone()),
(66, ACC.clone()),
(66, ACC.clone()),
(66, ACC.clone()),
(66, ACC.clone()),
(66, ACC.clone()),
(66, ACC.clone()),
(66, ACC.clone()),
(66, ACC.clone()),
(66, ACC.clone()),
(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!(compact.unique_targets(), vec![1, 2, 3, 4, 7, 8, 11, 12, 13, 66, 67]);
assert_eq!(compact.edge_count(), 2 + (2 * 2) + 3 + 16);
assert_eq!(compact.voter_count(), 6);
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 compact = TestSolutionCompact {
let solution = TestSolution {
votes1: vec![(99, 1), (99, 1)],
votes2: vec![(99, (3, ACC.clone()), 7), (99, (4, ACC.clone()), 8)],
votes3: vec![(99, [(11, ACC.clone()), (11, ACC.clone())], 13)],
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!(compact.unique_targets(), vec![1, 3, 4, 7, 8, 11, 13]);
assert_eq!(compact.edge_count(), 2 + (2 * 2) + 3);
assert_eq!(compact.voter_count(), 5);
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 compact_into_assignment_must_report_overflow() {
fn solution_into_assignment_must_report_overflow() {
// in votes2
let compact = TestSolutionCompact {
let solution = TestSolution {
votes1: Default::default(),
votes2: vec![(0, (1, TestAccuracy::from_percent(100)), 2)],
votes2: vec![(0, [(1, p(100))], 2)],
..Default::default()
};
let voter_at = |a: u32| -> Option<AccountId> { Some(a as AccountId) };
let target_at = |a: u8| -> Option<AccountId> { Some(a as AccountId) };
let target_at = |a: u16| -> Option<AccountId> { Some(a as AccountId) };
assert_eq!(
compact.into_assignment(&voter_at, &target_at).unwrap_err(),
PhragmenError::CompactStakeOverflow,
solution.into_assignment(&voter_at, &target_at).unwrap_err(),
NposError::SolutionWeightOverflow,
);
// in votes3 onwards
let compact = TestSolutionCompact {
let solution = TestSolution {
votes1: Default::default(),
votes2: Default::default(),
votes3: vec![(
0,
[(1, TestAccuracy::from_percent(70)), (2, TestAccuracy::from_percent(80))],
3,
)],
votes3: vec![(0, [(1, p(70)), (2, p(80))], 3)],
..Default::default()
};
assert_eq!(
compact.into_assignment(&voter_at, &target_at).unwrap_err(),
PhragmenError::CompactStakeOverflow,
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<u8> { Some(*a as u8) };
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, Percent::from_parts(i as u8)))
.collect::<Vec<_>>(),
distribution: (10..27).map(|i| (i as AccountId, p(i as u8))).collect::<Vec<_>>(),
}];
let compacted =
TestSolutionCompact::from_assignment(&assignments, voter_index, target_index);
assert_eq!(compacted.unwrap_err(), PhragmenError::CompactTargetOverflow);
let solution = TestSolution::from_assignment(&assignments, voter_index, target_index);
assert_eq!(solution.unwrap_err(), NposError::SolutionTargetOverflow);
}
#[test]
@@ -1258,31 +1195,25 @@ mod solution_type {
let targets = vec![10 as AccountId, 11];
let assignments = vec![
Assignment {
who: 1 as AccountId,
distribution: vec![
(10, Percent::from_percent(50)),
(11, Percent::from_percent(50)),
],
},
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<u8> {
let target_index = |a: &AccountId| -> Option<u16> {
targets.iter().position(|x| x == a).map(TryInto::try_into).unwrap().ok()
};
let compacted =
TestSolutionCompact::from_assignment(&assignments, voter_index, target_index).unwrap();
let solution =
TestSolution::from_assignment(&assignments, voter_index, target_index).unwrap();
assert_eq!(
compacted,
TestSolutionCompact {
solution,
TestSolution {
votes1: Default::default(),
votes2: vec![(0, (0, Percent::from_percent(50)), 1)],
votes2: vec![(0, [(0, p(50))], 1)],
..Default::default()
}
);
@@ -1290,14 +1221,15 @@ mod solution_type {
}
#[test]
fn index_assignments_generate_same_compact_as_plain_assignments() {
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 compact = Compact::from_assignment(&assignments, &voter_index, &target_index).unwrap();
let solution =
TestSolution::from_assignment(&assignments, &voter_index, &target_index).unwrap();
let index_assignments = assignments
.into_iter()
@@ -1307,5 +1239,5 @@ fn index_assignments_generate_same_compact_as_plain_assignments() {
let index_compact = index_assignments.as_slice().try_into().unwrap();
assert_eq!(compact, index_compact);
assert_eq!(solution, index_compact);
}
@@ -0,0 +1,155 @@
// This file is part of Substrate.
// Copyright (C) 2019-2021 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.
//! Traits for the npos-election operations.
use crate::{
Assignment, ElectionScore, Error, EvaluateSupport, ExtendedBalance, IndexAssignmentOf,
VoteWeight,
};
use codec::Encode;
use sp_arithmetic::{
traits::{Bounded, UniqueSaturatedInto},
PerThing,
};
use sp_std::{
convert::{TryFrom, TryInto},
fmt::Debug,
ops::Mul,
prelude::*,
};
/// an aggregator trait for a generic type of a voter/target identifier. This usually maps to
/// substrate's account id.
pub trait IdentifierT: Clone + Eq + Default + Ord + Debug + codec::Codec {}
impl<T: Clone + Eq + Default + Ord + Debug + codec::Codec> IdentifierT for T {}
/// Aggregator trait for a PerThing that can be multiplied by u128 (ExtendedBalance).
pub trait PerThing128: PerThing + Mul<ExtendedBalance, Output = ExtendedBalance> {}
impl<T: PerThing + Mul<ExtendedBalance, Output = ExtendedBalance>> PerThing128 for T {}
/// Simple Extension trait to easily convert `None` from index closures to `Err`.
///
/// This is only generated and re-exported for the solution code to use.
#[doc(hidden)]
pub trait __OrInvalidIndex<T> {
fn or_invalid_index(self) -> Result<T, Error>;
}
impl<T> __OrInvalidIndex<T> for Option<T> {
fn or_invalid_index(self) -> Result<T, Error> {
self.ok_or(Error::SolutionInvalidIndex)
}
}
/// An opaque index-based, NPoS solution type.
pub trait NposSolution
where
Self: Sized + for<'a> sp_std::convert::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;
/// The target type. Needs to be an index (convert to usize).
type TargetIndex: UniqueSaturatedInto<usize>
+ TryInto<usize>
+ TryFrom<usize>
+ Debug
+ Copy
+ Clone
+ Bounded
+ Encode;
/// 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,
winners: &[A],
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 = crate::helpers::assignment_ratio_to_staked_normalized(ratio, stake_of)?;
let supports = crate::to_supports(winners, &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>;
}