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
@@ -40,15 +40,15 @@ fn solution_with_size<T: Config>(
size: SolutionOrSnapshotSize,
active_voters_count: u32,
desired_targets: u32,
) -> Result<RawSolution<CompactOf<T>>, &'static str> {
) -> Result<RawSolution<SolutionOf<T>>, &'static str> {
ensure!(size.targets >= desired_targets, "must have enough targets");
ensure!(
size.targets >= (<CompactOf<T>>::LIMIT * 2) as u32,
size.targets >= (<SolutionOf<T>>::LIMIT * 2) as u32,
"must have enough targets for unique votes."
);
ensure!(size.voters >= active_voters_count, "must have enough voters");
ensure!(
(<CompactOf<T>>::LIMIT as u32) < desired_targets,
(<SolutionOf<T>>::LIMIT as u32) < desired_targets,
"must have enough winners to give them votes."
);
@@ -75,7 +75,7 @@ fn solution_with_size<T: Config>(
// chose a random subset of winners.
let winner_votes = winners
.as_slice()
.choose_multiple(&mut rng, <CompactOf<T>>::LIMIT)
.choose_multiple(&mut rng, <SolutionOf<T>>::LIMIT)
.cloned()
.collect::<Vec<_>>();
let voter = frame_benchmarking::account::<T::AccountId>("Voter", i, SEED);
@@ -92,7 +92,7 @@ fn solution_with_size<T: Config>(
let rest_voters = (active_voters_count..size.voters)
.map(|i| {
let votes = (&non_winners)
.choose_multiple(&mut rng, <CompactOf<T>>::LIMIT)
.choose_multiple(&mut rng, <SolutionOf<T>>::LIMIT)
.cloned()
.collect::<Vec<T::AccountId>>();
let voter = frame_benchmarking::account::<T::AccountId>("Voter", i, SEED);
@@ -129,25 +129,25 @@ fn solution_with_size<T: Config>(
let assignments = active_voters
.iter()
.map(|(voter, _stake, votes)| {
let percent_per_edge: InnerOf<CompactAccuracyOf<T>> =
let percent_per_edge: InnerOf<SolutionAccuracyOf<T>> =
(100 / votes.len()).try_into().unwrap_or_else(|_| panic!("failed to convert"));
crate::unsigned::Assignment::<T> {
who: voter.clone(),
distribution: votes
.iter()
.map(|t| (t.clone(), <CompactAccuracyOf<T>>::from_percent(percent_per_edge)))
.map(|t| (t.clone(), <SolutionAccuracyOf<T>>::from_percent(percent_per_edge)))
.collect::<Vec<_>>(),
}
})
.collect::<Vec<_>>();
let compact =
<CompactOf<T>>::from_assignment(&assignments, &voter_index, &target_index).unwrap();
let score = compact.clone().score(&winners, stake_of, voter_at, target_at).unwrap();
let solution =
<SolutionOf<T>>::from_assignment(&assignments, &voter_index, &target_index).unwrap();
let score = solution.clone().score(&winners, stake_of, voter_at, target_at).unwrap();
let round = <MultiPhase<T>>::round();
assert!(score[0] > 0, "score is zero, this probably means that the stakes are not set.");
Ok(RawSolution { compact, score, round })
Ok(RawSolution { solution, score, round })
}
fn set_up_data_provider<T: Config>(v: u32, t: u32) {
@@ -265,7 +265,7 @@ frame_benchmarking::benchmarks! {
let v in (T::BenchmarkingConfig::VOTERS[0]) .. T::BenchmarkingConfig::VOTERS[1];
// number of targets in snapshot.
let t in (T::BenchmarkingConfig::TARGETS[0]) .. T::BenchmarkingConfig::TARGETS[1];
// number of assignments, i.e. compact.len(). This means the active nominators, thus must be
// number of assignments, i.e. solution.len(). This means the active nominators, thus must be
// a subset of `v` component.
let a in (T::BenchmarkingConfig::ACTIVE_VOTERS[0]) .. T::BenchmarkingConfig::ACTIVE_VOTERS[1];
// number of desired targets. Must be a subset of `t` component.
@@ -308,11 +308,11 @@ frame_benchmarking::benchmarks! {
let mut signed_submissions = SignedSubmissions::<T>::get();
for i in 0..c {
let solution = RawSolution {
let raw_solution = RawSolution {
score: [(10_000_000 + i).into(), 0, 0],
..Default::default()
};
let signed_submission = SignedSubmission { solution, ..Default::default() };
let signed_submission = SignedSubmission { raw_solution, ..Default::default() };
signed_submissions.insert(signed_submission);
}
signed_submissions.put();
@@ -330,7 +330,7 @@ frame_benchmarking::benchmarks! {
let v in (T::BenchmarkingConfig::VOTERS[0]) .. T::BenchmarkingConfig::VOTERS[1];
// number of targets in snapshot.
let t in (T::BenchmarkingConfig::TARGETS[0]) .. T::BenchmarkingConfig::TARGETS[1];
// number of assignments, i.e. compact.len(). This means the active nominators, thus must be
// number of assignments, i.e. solution.len(). This means the active nominators, thus must be
// a subset of `v` component.
let a in
(T::BenchmarkingConfig::ACTIVE_VOTERS[0]) .. T::BenchmarkingConfig::ACTIVE_VOTERS[1];
@@ -369,7 +369,7 @@ frame_benchmarking::benchmarks! {
let v in (T::BenchmarkingConfig::VOTERS[0]) .. T::BenchmarkingConfig::VOTERS[1];
// number of targets in snapshot.
let t in (T::BenchmarkingConfig::TARGETS[0]) .. T::BenchmarkingConfig::TARGETS[1];
// number of assignments, i.e. compact.len(). This means the active nominators, thus must be
// number of assignments, i.e. solution.len(). This means the active nominators, thus must be
// a subset of `v` component.
let a in (T::BenchmarkingConfig::ACTIVE_VOTERS[0]) .. T::BenchmarkingConfig::ACTIVE_VOTERS[1];
// number of desired targets. Must be a subset of `t` component.
@@ -378,8 +378,8 @@ frame_benchmarking::benchmarks! {
let size = SolutionOrSnapshotSize { voters: v, targets: t };
let raw_solution = solution_with_size::<T>(size, a, d)?;
assert_eq!(raw_solution.compact.voter_count() as u32, a);
assert_eq!(raw_solution.compact.unique_targets().len() as u32, d);
assert_eq!(raw_solution.solution.voter_count() as u32, a);
assert_eq!(raw_solution.solution.unique_targets().len() as u32, d);
// encode the most significant storage item that needs to be decoded in the dispatch.
let encoded_snapshot = <MultiPhase<T>>::snapshot().unwrap().encode();
@@ -447,7 +447,7 @@ frame_benchmarking::benchmarks! {
let v in (T::BenchmarkingConfig::VOTERS[0]) .. T::BenchmarkingConfig::VOTERS[1];
// number of targets in snapshot.
let t in (T::BenchmarkingConfig::TARGETS[0]) .. T::BenchmarkingConfig::TARGETS[1];
// number of assignments, i.e. compact.len(). This means the active nominators, thus must be
// number of assignments, i.e. solution.len(). This means the active nominators, thus must be
// a subset of `v` component.
let a in
(T::BenchmarkingConfig::ACTIVE_VOTERS[0]) .. T::BenchmarkingConfig::ACTIVE_VOTERS[1];
@@ -461,11 +461,11 @@ frame_benchmarking::benchmarks! {
// Compute a random solution, then work backwards to get the lists of voters, targets, and
// assignments
let witness = SolutionOrSnapshotSize { voters: v, targets: t };
let RawSolution { compact, .. } = solution_with_size::<T>(witness, a, d)?;
let RawSolution { solution, .. } = solution_with_size::<T>(witness, a, d)?;
let RoundSnapshot { voters, targets } = MultiPhase::<T>::snapshot().unwrap();
let voter_at = helpers::voter_at_fn::<T>(&voters);
let target_at = helpers::target_at_fn::<T>(&targets);
let mut assignments = compact.into_assignment(voter_at, target_at).unwrap();
let mut assignments = solution.into_assignment(voter_at, target_at).unwrap();
// make a voter cache and some helper functions for access
let cache = helpers::generate_voter_cache::<T>(&voters);
@@ -488,7 +488,7 @@ frame_benchmarking::benchmarks! {
.unwrap();
let encoded_size_of = |assignments: &[IndexAssignmentOf<T>]| {
CompactOf::<T>::try_from(assignments).map(|compact| compact.encoded_size())
SolutionOf::<T>::try_from(assignments).map(|solution| solution.encoded_size())
};
let desired_size = Percent::from_percent(100 - f.saturated_into::<u8>())
@@ -501,8 +501,8 @@ frame_benchmarking::benchmarks! {
&encoded_size_of,
).unwrap();
} verify {
let compact = CompactOf::<T>::try_from(index_assignments.as_slice()).unwrap();
let encoding = compact.encode();
let solution = SolutionOf::<T>::try_from(index_assignments.as_slice()).unwrap();
let encoding = solution.encode();
log!(
trace,
"encoded size prediction = {}",
@@ -17,7 +17,7 @@
//! Some helper functions/macros for this crate.
use super::{CompactTargetIndexOf, CompactVoterIndexOf, Config, VoteWeight};
use super::{Config, SolutionTargetIndexOf, SolutionVoterIndexOf, VoteWeight};
use sp_std::{collections::btree_map::BTreeMap, convert::TryInto, prelude::*};
#[macro_export]
@@ -49,18 +49,18 @@ pub fn generate_voter_cache<T: Config>(
/// Create a function that returns the index of a voter in the snapshot.
///
/// The returning index type is the same as the one defined in `T::CompactSolution::Voter`.
/// The returning index type is the same as the one defined in `T::Solution::Voter`.
///
/// ## Warning
///
/// Note that this will represent the snapshot data from which the `cache` is generated.
pub fn voter_index_fn<T: Config>(
cache: &BTreeMap<T::AccountId, usize>,
) -> impl Fn(&T::AccountId) -> Option<CompactVoterIndexOf<T>> + '_ {
) -> impl Fn(&T::AccountId) -> Option<SolutionVoterIndexOf<T>> + '_ {
move |who| {
cache
.get(who)
.and_then(|i| <usize as TryInto<CompactVoterIndexOf<T>>>::try_into(*i).ok())
.and_then(|i| <usize as TryInto<SolutionVoterIndexOf<T>>>::try_into(*i).ok())
}
}
@@ -70,11 +70,11 @@ pub fn voter_index_fn<T: Config>(
/// borrowed.
pub fn voter_index_fn_owned<T: Config>(
cache: BTreeMap<T::AccountId, usize>,
) -> impl Fn(&T::AccountId) -> Option<CompactVoterIndexOf<T>> {
) -> impl Fn(&T::AccountId) -> Option<SolutionVoterIndexOf<T>> {
move |who| {
cache
.get(who)
.and_then(|i| <usize as TryInto<CompactVoterIndexOf<T>>>::try_into(*i).ok())
.and_then(|i| <usize as TryInto<SolutionVoterIndexOf<T>>>::try_into(*i).ok())
}
}
@@ -98,37 +98,37 @@ pub fn voter_index_fn_usize<T: Config>(
#[cfg(test)]
pub fn voter_index_fn_linear<T: Config>(
snapshot: &Vec<(T::AccountId, VoteWeight, Vec<T::AccountId>)>,
) -> impl Fn(&T::AccountId) -> Option<CompactVoterIndexOf<T>> + '_ {
) -> impl Fn(&T::AccountId) -> Option<SolutionVoterIndexOf<T>> + '_ {
move |who| {
snapshot
.iter()
.position(|(x, _, _)| x == who)
.and_then(|i| <usize as TryInto<CompactVoterIndexOf<T>>>::try_into(i).ok())
.and_then(|i| <usize as TryInto<SolutionVoterIndexOf<T>>>::try_into(i).ok())
}
}
/// Create a function that returns the index of a target in the snapshot.
///
/// The returned index type is the same as the one defined in `T::CompactSolution::Target`.
/// The returned index type is the same as the one defined in `T::Solution::Target`.
///
/// Note: to the extent possible, the returned function should be cached and reused. Producing that
/// function requires a `O(n log n)` data transform. Each invocation of that function completes
/// in `O(log n)`.
pub fn target_index_fn<T: Config>(
snapshot: &Vec<T::AccountId>,
) -> impl Fn(&T::AccountId) -> Option<CompactTargetIndexOf<T>> + '_ {
) -> impl Fn(&T::AccountId) -> Option<SolutionTargetIndexOf<T>> + '_ {
let cache: BTreeMap<_, _> =
snapshot.iter().enumerate().map(|(idx, account_id)| (account_id, idx)).collect();
move |who| {
cache
.get(who)
.and_then(|i| <usize as TryInto<CompactTargetIndexOf<T>>>::try_into(*i).ok())
.and_then(|i| <usize as TryInto<SolutionTargetIndexOf<T>>>::try_into(*i).ok())
}
}
/// Create a function the returns the index to a target in the snapshot.
///
/// The returned index type is the same as the one defined in `T::CompactSolution::Target`.
/// The returned index type is the same as the one defined in `T::Solution::Target`.
///
/// ## Warning
///
@@ -136,34 +136,34 @@ pub fn target_index_fn<T: Config>(
#[cfg(test)]
pub fn target_index_fn_linear<T: Config>(
snapshot: &Vec<T::AccountId>,
) -> impl Fn(&T::AccountId) -> Option<CompactTargetIndexOf<T>> + '_ {
) -> impl Fn(&T::AccountId) -> Option<SolutionTargetIndexOf<T>> + '_ {
move |who| {
snapshot
.iter()
.position(|x| x == who)
.and_then(|i| <usize as TryInto<CompactTargetIndexOf<T>>>::try_into(i).ok())
.and_then(|i| <usize as TryInto<SolutionTargetIndexOf<T>>>::try_into(i).ok())
}
}
/// Create a function that can map a voter index ([`CompactVoterIndexOf`]) to the actual voter
/// Create a function that can map a voter index ([`SolutionVoterIndexOf`]) to the actual voter
/// account using a linearly indexible snapshot.
pub fn voter_at_fn<T: Config>(
snapshot: &Vec<(T::AccountId, VoteWeight, Vec<T::AccountId>)>,
) -> impl Fn(CompactVoterIndexOf<T>) -> Option<T::AccountId> + '_ {
) -> impl Fn(SolutionVoterIndexOf<T>) -> Option<T::AccountId> + '_ {
move |i| {
<CompactVoterIndexOf<T> as TryInto<usize>>::try_into(i)
<SolutionVoterIndexOf<T> as TryInto<usize>>::try_into(i)
.ok()
.and_then(|i| snapshot.get(i).map(|(x, _, _)| x).cloned())
}
}
/// Create a function that can map a target index ([`CompactTargetIndexOf`]) to the actual target
/// Create a function that can map a target index ([`SolutionTargetIndexOf`]) to the actual target
/// account using a linearly indexible snapshot.
pub fn target_at_fn<T: Config>(
snapshot: &Vec<T::AccountId>,
) -> impl Fn(CompactTargetIndexOf<T>) -> Option<T::AccountId> + '_ {
) -> impl Fn(SolutionTargetIndexOf<T>) -> Option<T::AccountId> + '_ {
move |i| {
<CompactTargetIndexOf<T> as TryInto<usize>>::try_into(i)
<SolutionTargetIndexOf<T> as TryInto<usize>>::try_into(i)
.ok()
.and_then(|i| snapshot.get(i).cloned())
}
@@ -148,7 +148,7 @@
//!
//! The accuracy of the election is configured via two trait parameters. namely,
//! [`OnChainAccuracyOf`] dictates the accuracy used to compute the on-chain fallback election and
//! [`CompactAccuracyOf`] is the accuracy that the submitted solutions must adhere to.
//! [`SolutionAccuracyOf`] is the accuracy that the submitted solutions must adhere to.
//!
//! Note that both accuracies are of great importance. The offchain solution should be as small as
//! possible, reducing solutions size/weight. The on-chain solution can use more space for accuracy,
@@ -212,7 +212,7 @@
//! there is a tie. Even more harsh should be to enforce the bound of the `reduce` algorithm.
//!
//! **Make the number of nominators configurable from the runtime**. Remove `sp_npos_elections`
//! dependency from staking and the compact solution type. It should be generated at runtime, there
//! dependency from staking and the solution type. It should be generated at runtime, there
//! it should be encoded how many votes each nominators have. Essentially translate
//! <https://github.com/paritytech/substrate/pull/7929> to this pallet.
//!
@@ -241,7 +241,7 @@ use sp_arithmetic::{
UpperOf,
};
use sp_npos_elections::{
assignment_ratio_to_staked_normalized, CompactSolution, ElectionScore, EvaluateSupport,
assignment_ratio_to_staked_normalized, ElectionScore, EvaluateSupport, NposSolution,
PerThing128, Supports, VoteWeight,
};
use sp_runtime::{
@@ -273,15 +273,15 @@ pub use signed::{
};
pub use weights::WeightInfo;
/// The compact solution type used by this crate.
pub type CompactOf<T> = <T as Config>::CompactSolution;
/// The solution type used by this crate.
pub type SolutionOf<T> = <T as Config>::Solution;
/// The voter index. Derived from [`CompactOf`].
pub type CompactVoterIndexOf<T> = <CompactOf<T> as CompactSolution>::Voter;
/// The target index. Derived from [`CompactOf`].
pub type CompactTargetIndexOf<T> = <CompactOf<T> as CompactSolution>::Target;
/// The accuracy of the election, when submitted from offchain. Derived from [`CompactOf`].
pub type CompactAccuracyOf<T> = <CompactOf<T> as CompactSolution>::Accuracy;
/// The voter index. Derived from [`SolutionOf`].
pub type SolutionVoterIndexOf<T> = <SolutionOf<T> as NposSolution>::VoterIndex;
/// The target index. Derived from [`SolutionOf`].
pub type SolutionTargetIndexOf<T> = <SolutionOf<T> as NposSolution>::TargetIndex;
/// The accuracy of the election, when submitted from offchain. Derived from [`SolutionOf`].
pub type SolutionAccuracyOf<T> = <SolutionOf<T> as NposSolution>::Accuracy;
/// The accuracy of the election, when computed on-chain. Equal to [`Config::OnChainAccuracy`].
pub type OnChainAccuracyOf<T> = <T as Config>::OnChainAccuracy;
@@ -422,11 +422,11 @@ impl Default for ElectionCompute {
/// This is what will get submitted to the chain.
///
/// Such a solution should never become effective in anyway before being checked by the
/// `Pallet::feasibility_check`
/// `Pallet::feasibility_check`.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, PartialOrd, Ord)]
pub struct RawSolution<C> {
/// Compact election edges.
pub compact: C,
pub struct RawSolution<S> {
/// the solution itself.
pub solution: S,
/// The _claimed_ score of the solution.
pub score: ElectionScore,
/// The round at which this solution should be submitted.
@@ -436,7 +436,7 @@ pub struct RawSolution<C> {
impl<C: Default> Default for RawSolution<C> {
fn default() -> Self {
// Round 0 is always invalid, only set this to 1.
Self { round: 1, compact: Default::default(), score: Default::default() }
Self { round: 1, solution: Default::default(), score: Default::default() }
}
}
@@ -651,15 +651,15 @@ pub mod pallet {
/// Something that will provide the election data.
type DataProvider: ElectionDataProvider<Self::AccountId, Self::BlockNumber>;
/// The compact solution type
type CompactSolution: codec::Codec
/// The solution type.
type Solution: codec::Codec
+ Default
+ PartialEq
+ Eq
+ Clone
+ sp_std::fmt::Debug
+ Ord
+ CompactSolution;
+ NposSolution;
/// Accuracy used for fallback on-chain election.
type OnChainAccuracy: PerThing128;
@@ -790,12 +790,12 @@ pub mod pallet {
use sp_std::mem::size_of;
// The index type of both voters and targets need to be smaller than that of usize (very
// unlikely to be the case, but anyhow).
assert!(size_of::<CompactVoterIndexOf<T>>() <= size_of::<usize>());
assert!(size_of::<CompactTargetIndexOf<T>>() <= size_of::<usize>());
assert!(size_of::<SolutionVoterIndexOf<T>>() <= size_of::<usize>());
assert!(size_of::<SolutionTargetIndexOf<T>>() <= size_of::<usize>());
// ----------------------------
// Based on the requirements of [`sp_npos_elections::Assignment::try_normalize`].
let max_vote: usize = <CompactOf<T> as CompactSolution>::LIMIT;
let max_vote: usize = <SolutionOf<T> as NposSolution>::LIMIT;
// 1. Maximum sum of [ChainAccuracy; 16] must fit into `UpperOf<ChainAccuracy>`..
let maximum_chain_accuracy: Vec<UpperOf<OnChainAccuracyOf<T>>> = (0..max_vote)
@@ -809,26 +809,26 @@ pub mod pallet {
.iter()
.fold(Zero::zero(), |acc, x| acc.checked_add(x).unwrap());
// 2. Maximum sum of [CompactAccuracy; 16] must fit into `UpperOf<OffchainAccuracy>`.
let maximum_chain_accuracy: Vec<UpperOf<CompactAccuracyOf<T>>> = (0..max_vote)
// 2. Maximum sum of [SolutionAccuracy; 16] must fit into `UpperOf<OffchainAccuracy>`.
let maximum_chain_accuracy: Vec<UpperOf<SolutionAccuracyOf<T>>> = (0..max_vote)
.map(|_| {
<UpperOf<CompactAccuracyOf<T>>>::from(
<CompactAccuracyOf<T>>::one().deconstruct(),
<UpperOf<SolutionAccuracyOf<T>>>::from(
<SolutionAccuracyOf<T>>::one().deconstruct(),
)
})
.collect();
let _: UpperOf<CompactAccuracyOf<T>> = maximum_chain_accuracy
let _: UpperOf<SolutionAccuracyOf<T>> = maximum_chain_accuracy
.iter()
.fold(Zero::zero(), |acc, x| acc.checked_add(x).unwrap());
// We only accept data provider who's maximum votes per voter matches our
// `T::CompactSolution`'s `LIMIT`.
// `T::Solution`'s `LIMIT`.
//
// NOTE that this pallet does not really need to enforce this in runtime. The compact
// NOTE that this pallet does not really need to enforce this in runtime. The
// solution cannot represent any voters more than `LIMIT` anyhow.
assert_eq!(
<T::DataProvider as ElectionDataProvider<T::AccountId, T::BlockNumber>>::MAXIMUM_VOTES_PER_VOTER,
<CompactOf<T> as CompactSolution>::LIMIT as u32,
<SolutionOf<T> as NposSolution>::LIMIT as u32,
);
}
}
@@ -853,14 +853,14 @@ pub mod pallet {
T::WeightInfo::submit_unsigned(
witness.voters,
witness.targets,
solution.compact.voter_count() as u32,
solution.compact.unique_targets().len() as u32
raw_solution.solution.voter_count() as u32,
raw_solution.solution.unique_targets().len() as u32
),
DispatchClass::Operational,
))]
pub fn submit_unsigned(
origin: OriginFor<T>,
solution: Box<RawSolution<CompactOf<T>>>,
raw_solution: Box<RawSolution<SolutionOf<T>>>,
witness: SolutionOrSnapshotSize,
) -> DispatchResultWithPostInfo {
ensure_none(origin)?;
@@ -868,7 +868,7 @@ pub mod pallet {
deprive validator from their authoring reward.";
// Check score being an improvement, phase, and desired targets.
Self::unsigned_pre_dispatch_checks(&solution).expect(error_message);
Self::unsigned_pre_dispatch_checks(&raw_solution).expect(error_message);
// Ensure witness was correct.
let SolutionOrSnapshotSize { voters, targets } =
@@ -878,8 +878,8 @@ pub mod pallet {
assert!(voters as u32 == witness.voters, "{}", error_message);
assert!(targets as u32 == witness.targets, "{}", error_message);
let ready =
Self::feasibility_check(*solution, ElectionCompute::Unsigned).expect(error_message);
let ready = Self::feasibility_check(*raw_solution, ElectionCompute::Unsigned)
.expect(error_message);
// Store the newly received solution.
log!(info, "queued unsigned solution with score {:?}", ready.score);
@@ -950,7 +950,7 @@ pub mod pallet {
#[pallet::weight(T::WeightInfo::submit(*num_signed_submissions))]
pub fn submit(
origin: OriginFor<T>,
solution: Box<RawSolution<CompactOf<T>>>,
raw_solution: Box<RawSolution<SolutionOf<T>>>,
num_signed_submissions: u32,
) -> DispatchResult {
let who = ensure_signed(origin)?;
@@ -973,20 +973,20 @@ pub mod pallet {
let size = Self::snapshot_metadata().ok_or(Error::<T>::MissingSnapshotMetadata)?;
ensure!(
Self::feasibility_weight_of(&solution, size) < T::SignedMaxWeight::get(),
Self::feasibility_weight_of(&raw_solution, size) < T::SignedMaxWeight::get(),
Error::<T>::SignedTooMuchWeight,
);
// create the submission
let deposit = Self::deposit_for(&solution, size);
let deposit = Self::deposit_for(&raw_solution, size);
let reward = {
let call = Call::submit(solution.clone(), num_signed_submissions);
let call = Call::submit(raw_solution.clone(), num_signed_submissions);
let call_fee = T::EstimateCallFee::estimate_call_fee(&call, None.into());
T::SignedRewardBase::get().saturating_add(call_fee)
};
let submission =
SignedSubmission { who: who.clone(), deposit, solution: *solution, reward };
SignedSubmission { who: who.clone(), deposit, raw_solution: *raw_solution, reward };
// insert the submission if the queue has space or it's better than the weakest
// eject the weakest if the queue was full
@@ -1299,8 +1299,8 @@ impl<T: Config> Pallet<T> {
///
/// Returns `Ok(consumed_weight)` if operation is okay.
pub fn create_snapshot() -> Result<Weight, ElectionError> {
let target_limit = <CompactTargetIndexOf<T>>::max_value().saturated_into::<usize>();
let voter_limit = <CompactVoterIndexOf<T>>::max_value().saturated_into::<usize>();
let target_limit = <SolutionTargetIndexOf<T>>::max_value().saturated_into::<usize>();
let voter_limit = <SolutionVoterIndexOf<T>>::max_value().saturated_into::<usize>();
let (targets, w1) =
T::DataProvider::targets(Some(target_limit)).map_err(ElectionError::DataProvider)?;
@@ -1353,16 +1353,16 @@ impl<T: Config> Pallet<T> {
/// Checks the feasibility of a solution.
pub fn feasibility_check(
solution: RawSolution<CompactOf<T>>,
raw_solution: RawSolution<SolutionOf<T>>,
compute: ElectionCompute,
) -> Result<ReadySolution<T::AccountId>, FeasibilityError> {
let RawSolution { compact, score, round } = solution;
let RawSolution { solution, score, round } = raw_solution;
// First, check round.
ensure!(Self::round() == round, FeasibilityError::InvalidRound);
// Winners are not directly encoded in the solution.
let winners = compact.unique_targets();
let winners = solution.unique_targets();
let desired_targets =
Self::desired_targets().ok_or(FeasibilityError::SnapshotUnavailable)?;
@@ -1373,7 +1373,7 @@ impl<T: Config> Pallet<T> {
ensure!(winners.len() as u32 == desired_targets, FeasibilityError::WrongWinnerCount);
// Ensure that the solution's score can pass absolute min-score.
let submitted_score = solution.score.clone();
let submitted_score = raw_solution.score.clone();
ensure!(
Self::minimum_untrusted_score().map_or(true, |min_score| {
sp_npos_elections::is_score_better(submitted_score, min_score, Perbill::zero())
@@ -1394,15 +1394,15 @@ impl<T: Config> Pallet<T> {
// First, make sure that all the winners are sane.
// OPTIMIZATION: we could first build the assignments, and then extract the winners directly
// from that, as that would eliminate a little bit of duplicate work. For now, we keep them
// separate: First extract winners separately from compact, and then assignments. This is
// separate: First extract winners separately from solution, and then assignments. This is
// also better, because we can reject solutions that don't meet `desired_targets` early on.
let winners = winners
.into_iter()
.map(|i| target_at(i).ok_or(FeasibilityError::InvalidWinner))
.collect::<Result<Vec<T::AccountId>, FeasibilityError>>()?;
// Then convert compact -> assignment. This will fail if any of the indices are gibberish.
let assignments = compact
// Then convert solution -> assignment. This will fail if any of the indices are gibberish.
let assignments = solution
.into_assignment(voter_at, target_at)
.map_err::<FeasibilityError, _>(Into::into)?;
@@ -1413,7 +1413,7 @@ impl<T: Config> Pallet<T> {
// Check that assignment.who is actually a voter (defensive-only).
// NOTE: while using the index map from `voter_index` is better than a blind linear
// search, this *still* has room for optimization. Note that we had the index when
// we did `compact -> assignment` and we lost it. Ideal is to keep the index around.
// we did `solution -> assignment` and we lost it. Ideal is to keep the index around.
// Defensive-only: must exist in the snapshot.
let snapshot_index =
@@ -1438,7 +1438,7 @@ impl<T: Config> Pallet<T> {
.map_err::<FeasibilityError, _>(Into::into)?;
// This might fail if one of the voter edges is pointing to a non-winner, which is not
// really possible anymore because all the winners come from the same `compact`.
// really possible anymore because all the winners come from the same `solution`.
let supports = sp_npos_elections::to_supports(&winners, &staked_assignments)
.map_err::<FeasibilityError, _>(Into::into)?;
@@ -1611,13 +1611,13 @@ mod feasibility_check {
roll_to(<EpochLength>::get() - <SignedPhase>::get() - <UnsignedPhase>::get());
assert!(MultiPhase::current_phase().is_signed());
let solution = raw_solution();
let raw = raw_solution();
assert_eq!(solution.compact.unique_targets().len(), 4);
assert_eq!(raw.solution.unique_targets().len(), 4);
assert_eq!(MultiPhase::desired_targets().unwrap(), 8);
assert_noop!(
MultiPhase::feasibility_check(solution, COMPUTE),
MultiPhase::feasibility_check(raw, COMPUTE),
FeasibilityError::WrongWinnerCount,
);
})
@@ -1629,20 +1629,19 @@ mod feasibility_check {
roll_to(<EpochLength>::get() - <SignedPhase>::get() - <UnsignedPhase>::get());
assert!(MultiPhase::current_phase().is_signed());
let mut solution = raw_solution();
let mut raw = raw_solution();
assert_eq!(MultiPhase::snapshot().unwrap().targets.len(), 4);
// ----------------------------------------------------^^ valid range is [0..3].
// Swap all votes from 3 to 4. This will ensure that the number of unique winners
// will still be 4, but one of the indices will be gibberish. Requirement is to make
// sure 3 a winner, which we don't do here.
solution
.compact
// Swap all votes from 3 to 4. This will ensure that the number of unique winners will
// still be 4, but one of the indices will be gibberish. Requirement is to make sure 3 a
// winner, which we don't do here.
raw.solution
.votes1
.iter_mut()
.filter(|(_, t)| *t == TargetIndex::from(3u16))
.for_each(|(_, t)| *t += 1);
solution.compact.votes2.iter_mut().for_each(|(_, (t0, _), t1)| {
raw.solution.votes2.iter_mut().for_each(|(_, [(t0, _)], t1)| {
if *t0 == TargetIndex::from(3u16) {
*t0 += 1
};
@@ -1651,7 +1650,7 @@ mod feasibility_check {
};
});
assert_noop!(
MultiPhase::feasibility_check(solution, COMPUTE),
MultiPhase::feasibility_check(raw, COMPUTE),
FeasibilityError::InvalidWinner
);
})
@@ -1659,7 +1658,7 @@ mod feasibility_check {
#[test]
fn voter_indices() {
// Should be caught in `compact.into_assignment`.
// Should be caught in `solution.into_assignment`.
ExtBuilder::default().desired_targets(2).build_and_execute(|| {
roll_to(<EpochLength>::get() - <SignedPhase>::get() - <UnsignedPhase>::get());
assert!(MultiPhase::current_phase().is_signed());
@@ -1671,7 +1670,7 @@ mod feasibility_check {
// Check that there is an index 7 in votes1, and flip to 8.
assert!(
solution
.compact
.solution
.votes1
.iter_mut()
.filter(|(v, _)| *v == VoterIndex::from(7u32))
@@ -1680,7 +1679,7 @@ mod feasibility_check {
);
assert_noop!(
MultiPhase::feasibility_check(solution, COMPUTE),
FeasibilityError::NposElection(sp_npos_elections::Error::CompactInvalidIndex),
FeasibilityError::NposElection(sp_npos_elections::Error::SolutionInvalidIndex),
);
})
}
@@ -1699,7 +1698,7 @@ mod feasibility_check {
// vote. Then, change the vote to 2 (30).
assert_eq!(
solution
.compact
.solution
.votes1
.iter_mut()
.filter(|(v, t)| *v == 7 && *t == 3)
@@ -31,7 +31,7 @@ use sp_core::{
};
use sp_npos_elections::{
assignment_ratio_to_staked_normalized, seq_phragmen, to_supports, to_without_backing,
CompactSolution, ElectionResult, EvaluateSupport,
ElectionResult, EvaluateSupport, NposSolution,
};
use sp_runtime::{
testing::Header,
@@ -63,7 +63,7 @@ pub(crate) type TargetIndex = u16;
sp_npos_elections::generate_solution_type!(
#[compact]
pub struct TestCompact::<VoterIndex = VoterIndex, TargetIndex = TargetIndex, Accuracy = PerU16>(16)
pub struct TestNposSolution::<VoterIndex = VoterIndex, TargetIndex = TargetIndex, Accuracy = PerU16>(16)
);
/// All events of this pallet.
@@ -101,7 +101,7 @@ pub struct TrimHelpers {
pub voter_index: Box<
dyn Fn(
&<Runtime as frame_system::Config>::AccountId,
) -> Option<CompactVoterIndexOf<Runtime>>,
) -> Option<SolutionVoterIndexOf<Runtime>>,
>,
}
@@ -113,11 +113,11 @@ pub fn trim_helpers() -> TrimHelpers {
let stakes: std::collections::HashMap<_, _> =
voters.iter().map(|(id, stake, _)| (*id, *stake)).collect();
// Compute the size of a compact solution comprised of the selected arguments.
// Compute the size of a solution comprised of the selected arguments.
//
// This function completes in `O(edges)`; it's expensive, but linear.
let encoded_size_of = Box::new(|assignments: &[IndexAssignmentOf<Runtime>]| {
CompactOf::<Runtime>::try_from(assignments).map(|compact| compact.encoded_size())
SolutionOf::<Runtime>::try_from(assignments).map(|s| s.encoded_size())
});
let cache = helpers::generate_voter_cache::<Runtime>(&voters);
let voter_index = helpers::voter_index_fn_owned::<Runtime>(cache);
@@ -125,7 +125,7 @@ pub fn trim_helpers() -> TrimHelpers {
let desired_targets = MultiPhase::desired_targets().unwrap();
let ElectionResult { mut assignments, .. } = seq_phragmen::<_, CompactAccuracyOf<Runtime>>(
let ElectionResult { mut assignments, .. } = seq_phragmen::<_, SolutionAccuracyOf<Runtime>>(
desired_targets as usize,
targets.clone(),
voters.clone(),
@@ -153,11 +153,11 @@ pub fn trim_helpers() -> TrimHelpers {
/// Spit out a verifiable raw solution.
///
/// This is a good example of what an offchain miner would do.
pub fn raw_solution() -> RawSolution<CompactOf<Runtime>> {
pub fn raw_solution() -> RawSolution<SolutionOf<Runtime>> {
let RoundSnapshot { voters, targets } = MultiPhase::snapshot().unwrap();
let desired_targets = MultiPhase::desired_targets().unwrap();
let ElectionResult { winners, assignments } = seq_phragmen::<_, CompactAccuracyOf<Runtime>>(
let ElectionResult { winners, assignments } = seq_phragmen::<_, SolutionAccuracyOf<Runtime>>(
desired_targets as usize,
targets.clone(),
voters.clone(),
@@ -177,11 +177,11 @@ pub fn raw_solution() -> RawSolution<CompactOf<Runtime>> {
let staked = assignment_ratio_to_staked_normalized(assignments.clone(), &stake_of).unwrap();
to_supports(&winners, &staked).unwrap().evaluate()
};
let compact =
<CompactOf<Runtime>>::from_assignment(&assignments, &voter_index, &target_index).unwrap();
let solution =
<SolutionOf<Runtime>>::from_assignment(&assignments, &voter_index, &target_index).unwrap();
let round = MultiPhase::round();
RawSolution { compact, score, round }
RawSolution { solution, score, round }
}
pub fn witness() -> SolutionOrSnapshotSize {
@@ -378,7 +378,7 @@ impl crate::Config for Runtime {
type OnChainAccuracy = Perbill;
type Fallback = Fallback;
type ForceOrigin = frame_system::EnsureRoot<AccountId>;
type CompactSolution = TestCompact;
type Solution = TestNposSolution;
}
impl<LocalCall> frame_system::offchain::SendTransactionTypes<LocalCall> for Runtime
@@ -396,7 +396,7 @@ pub struct ExtBuilder {}
pub struct StakingMock;
impl ElectionDataProvider<AccountId, u64> for StakingMock {
const MAXIMUM_VOTES_PER_VOTER: u32 = <TestCompact as CompactSolution>::LIMIT as u32;
const MAXIMUM_VOTES_PER_VOTER: u32 = <TestNposSolution as NposSolution>::LIMIT as u32;
fn targets(maybe_max_len: Option<usize>) -> data_provider::Result<(Vec<AccountId>, Weight)> {
let targets = Targets::get();
@@ -18,8 +18,8 @@
//! The signed phase implementation.
use crate::{
CompactOf, Config, ElectionCompute, Pallet, QueuedSolution, RawSolution, ReadySolution,
SignedSubmissionIndices, SignedSubmissionNextIndex, SignedSubmissionsMap,
Config, ElectionCompute, Pallet, QueuedSolution, RawSolution, ReadySolution,
SignedSubmissionIndices, SignedSubmissionNextIndex, SignedSubmissionsMap, SolutionOf,
SolutionOrSnapshotSize, Weight, WeightInfo,
};
use codec::{Decode, Encode, HasCompact};
@@ -29,7 +29,7 @@ use frame_support::{
DebugNoBound,
};
use sp_arithmetic::traits::SaturatedConversion;
use sp_npos_elections::{is_score_better, CompactSolution, ElectionScore};
use sp_npos_elections::{is_score_better, ElectionScore, NposSolution};
use sp_runtime::{
traits::{Saturating, Zero},
RuntimeDebug,
@@ -44,42 +44,40 @@ use sp_std::{
///
/// This is just a wrapper around [`RawSolution`] and some additional info.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, Default)]
pub struct SignedSubmission<AccountId, Balance: HasCompact, CompactSolution> {
pub struct SignedSubmission<AccountId, Balance: HasCompact, Solution> {
/// Who submitted this solution.
pub who: AccountId,
/// The deposit reserved for storing this solution.
pub deposit: Balance,
/// The raw solution itself.
pub solution: RawSolution<CompactSolution>,
pub raw_solution: RawSolution<Solution>,
/// The reward that should potentially be paid for this solution, if accepted.
pub reward: Balance,
}
impl<AccountId, Balance, CompactSolution> Ord
for SignedSubmission<AccountId, Balance, CompactSolution>
impl<AccountId, Balance, Solution> Ord for SignedSubmission<AccountId, Balance, Solution>
where
AccountId: Ord,
Balance: Ord + HasCompact,
CompactSolution: Ord,
RawSolution<CompactSolution>: Ord,
Solution: Ord,
RawSolution<Solution>: Ord,
{
fn cmp(&self, other: &Self) -> Ordering {
self.solution
self.raw_solution
.score
.cmp(&other.solution.score)
.then_with(|| self.solution.cmp(&other.solution))
.cmp(&other.raw_solution.score)
.then_with(|| self.raw_solution.cmp(&other.raw_solution))
.then_with(|| self.deposit.cmp(&other.deposit))
.then_with(|| self.who.cmp(&other.who))
}
}
impl<AccountId, Balance, CompactSolution> PartialOrd
for SignedSubmission<AccountId, Balance, CompactSolution>
impl<AccountId, Balance, Solution> PartialOrd for SignedSubmission<AccountId, Balance, Solution>
where
AccountId: Ord,
Balance: Ord + HasCompact,
CompactSolution: Ord,
RawSolution<CompactSolution>: Ord,
Solution: Ord,
RawSolution<Solution>: Ord,
{
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
@@ -95,7 +93,7 @@ pub type NegativeImbalanceOf<T> = <<T as Config>::Currency as Currency<
<T as frame_system::Config>::AccountId,
>>::NegativeImbalance;
pub type SignedSubmissionOf<T> =
SignedSubmission<<T as frame_system::Config>::AccountId, BalanceOf<T>, CompactOf<T>>;
SignedSubmission<<T as frame_system::Config>::AccountId, BalanceOf<T>, SolutionOf<T>>;
pub type SubmissionIndicesOf<T> =
BoundedBTreeMap<ElectionScore, u32, <T as Config>::SignedMaxSubmissions>;
@@ -270,13 +268,13 @@ impl<T: Config> SignedSubmissions<T> {
// verify the expectation that we never reuse an index
debug_assert!(!self.indices.values().any(|&idx| idx == self.next_idx));
let weakest = match self.indices.try_insert(submission.solution.score, self.next_idx) {
let weakest = match self.indices.try_insert(submission.raw_solution.score, self.next_idx) {
Ok(Some(prev_idx)) => {
// a submission of equal score was already present in the set;
// no point editing the actual backing map as we know that the newer solution can't
// be better than the old. However, we do need to put the old value back.
self.indices
.try_insert(submission.solution.score, prev_idx)
.try_insert(submission.raw_solution.score, prev_idx)
.expect("didn't change the map size; qed");
return InsertResult::NotInserted
},
@@ -354,8 +352,8 @@ impl<T: Config> Pallet<T> {
Self::snapshot_metadata().unwrap_or_default();
while let Some(best) = all_submissions.pop_last() {
let SignedSubmission { solution, who, deposit, reward } = best;
let active_voters = solution.compact.voter_count() as u32;
let SignedSubmission { raw_solution, who, deposit, reward } = best;
let active_voters = raw_solution.solution.voter_count() as u32;
let feasibility_weight = {
// defensive only: at the end of signed phase, snapshot will exits.
let desired_targets = Self::desired_targets().unwrap_or_default();
@@ -363,7 +361,7 @@ impl<T: Config> Pallet<T> {
};
// the feasibility check itself has some weight
weight = weight.saturating_add(feasibility_weight);
match Self::feasibility_check(solution, ElectionCompute::Signed) {
match Self::feasibility_check(raw_solution, ElectionCompute::Signed) {
Ok(ready_solution) => {
Self::finalize_signed_phase_accept_solution(
ready_solution,
@@ -447,14 +445,14 @@ impl<T: Config> Pallet<T> {
/// The feasibility weight of the given raw solution.
pub fn feasibility_weight_of(
solution: &RawSolution<CompactOf<T>>,
raw_solution: &RawSolution<SolutionOf<T>>,
size: SolutionOrSnapshotSize,
) -> Weight {
T::WeightInfo::feasibility_check(
size.voters,
size.targets,
solution.compact.voter_count() as u32,
solution.compact.unique_targets().len() as u32,
raw_solution.solution.voter_count() as u32,
raw_solution.solution.unique_targets().len() as u32,
)
}
@@ -466,12 +464,12 @@ impl<T: Config> Pallet<T> {
/// 2. a per-byte deposit, for renting the state usage.
/// 3. a per-weight deposit, for the potential weight usage in an upcoming on_initialize
pub fn deposit_for(
solution: &RawSolution<CompactOf<T>>,
raw_solution: &RawSolution<SolutionOf<T>>,
size: SolutionOrSnapshotSize,
) -> BalanceOf<T> {
let encoded_len: u32 = solution.encoded_size().saturated_into();
let encoded_len: u32 = raw_solution.encoded_size().saturated_into();
let encoded_len: BalanceOf<T> = encoded_len.into();
let feasibility_weight = Self::feasibility_weight_of(solution, size);
let feasibility_weight = Self::feasibility_weight_of(raw_solution, size);
let len_deposit = T::SignedDepositByte::get().saturating_mul(encoded_len);
let weight_deposit =
@@ -497,7 +495,7 @@ mod tests {
fn submit_with_witness(
origin: Origin,
solution: RawSolution<CompactOf<Runtime>>,
solution: RawSolution<SolutionOf<Runtime>>,
) -> DispatchResult {
MultiPhase::submit(
origin,
@@ -663,7 +661,7 @@ mod tests {
assert_eq!(
MultiPhase::signed_submissions()
.iter()
.map(|s| s.solution.score[0])
.map(|s| s.raw_solution.score[0])
.collect::<Vec<_>>(),
vec![5, 6, 7, 8, 9]
);
@@ -676,7 +674,7 @@ mod tests {
assert_eq!(
MultiPhase::signed_submissions()
.iter()
.map(|s| s.solution.score[0])
.map(|s| s.raw_solution.score[0])
.collect::<Vec<_>>(),
vec![6, 7, 8, 9, 20]
);
@@ -701,7 +699,7 @@ mod tests {
assert_eq!(
MultiPhase::signed_submissions()
.iter()
.map(|s| s.solution.score[0])
.map(|s| s.raw_solution.score[0])
.collect::<Vec<_>>(),
vec![4, 6, 7, 8, 9],
);
@@ -714,7 +712,7 @@ mod tests {
assert_eq!(
MultiPhase::signed_submissions()
.iter()
.map(|s| s.solution.score[0])
.map(|s| s.raw_solution.score[0])
.collect::<Vec<_>>(),
vec![5, 6, 7, 8, 9],
);
@@ -759,7 +757,7 @@ mod tests {
assert_eq!(
MultiPhase::signed_submissions()
.iter()
.map(|s| s.solution.score[0])
.map(|s| s.raw_solution.score[0])
.collect::<Vec<_>>(),
vec![5, 6, 7]
);
@@ -828,33 +826,33 @@ mod tests {
roll_to(15);
assert!(MultiPhase::current_phase().is_signed());
let (solution, witness) = MultiPhase::mine_solution(2).unwrap();
let (raw, witness) = MultiPhase::mine_solution(2).unwrap();
let solution_weight = <Runtime as Config>::WeightInfo::feasibility_check(
witness.voters,
witness.targets,
solution.compact.voter_count() as u32,
solution.compact.unique_targets().len() as u32,
raw.solution.voter_count() as u32,
raw.solution.unique_targets().len() as u32,
);
// default solution will have 5 edges (5 * 5 + 10)
assert_eq!(solution_weight, 35);
assert_eq!(solution.compact.voter_count(), 5);
assert_eq!(raw.solution.voter_count(), 5);
assert_eq!(<Runtime as Config>::SignedMaxWeight::get(), 40);
assert_ok!(submit_with_witness(Origin::signed(99), solution.clone()));
assert_ok!(submit_with_witness(Origin::signed(99), raw.clone()));
<SignedMaxWeight>::set(30);
// note: resubmitting the same solution is technically okay as long as the queue has
// space.
assert_noop!(
submit_with_witness(Origin::signed(99), solution),
submit_with_witness(Origin::signed(99), raw),
Error::<Runtime>::SignedTooMuchWeight,
);
})
}
#[test]
fn insufficient_deposit_doesnt_store_submission() {
fn insufficient_deposit_does_not_store_submission() {
ExtBuilder::default().build_and_execute(|| {
roll_to(15);
assert!(MultiPhase::current_phase().is_signed());
@@ -18,8 +18,9 @@
//! The unsigned phase, and its miner.
use crate::{
helpers, Call, CompactAccuracyOf, CompactOf, Config, ElectionCompute, Error, FeasibilityError,
Pallet, RawSolution, ReadySolution, RoundSnapshot, SolutionOrSnapshotSize, Weight, WeightInfo,
helpers, Call, Config, ElectionCompute, Error, FeasibilityError, Pallet, RawSolution,
ReadySolution, RoundSnapshot, SolutionAccuracyOf, SolutionOf, SolutionOrSnapshotSize, Weight,
WeightInfo,
};
use codec::{Decode, Encode};
use frame_support::{dispatch::DispatchResult, ensure, traits::Get};
@@ -27,7 +28,7 @@ use frame_system::offchain::SubmitTransaction;
use sp_arithmetic::Perbill;
use sp_npos_elections::{
assignment_ratio_to_staked_normalized, assignment_staked_to_ratio_normalized, is_score_better,
seq_phragmen, CompactSolution, ElectionResult,
seq_phragmen, ElectionResult, NposSolution,
};
use sp_runtime::{
offchain::storage::{MutateStorageError, StorageValueRef},
@@ -54,11 +55,11 @@ pub type Voter<T> = (
/// The relative distribution of a voter's stake among the winning targets.
pub type Assignment<T> =
sp_npos_elections::Assignment<<T as frame_system::Config>::AccountId, CompactAccuracyOf<T>>;
sp_npos_elections::Assignment<<T as frame_system::Config>::AccountId, SolutionAccuracyOf<T>>;
/// The [`IndexAssignment`][sp_npos_elections::IndexAssignment] type specialized for a particular
/// runtime `T`.
pub type IndexAssignmentOf<T> = sp_npos_elections::IndexAssignmentOf<CompactOf<T>>;
pub type IndexAssignmentOf<T> = sp_npos_elections::IndexAssignmentOf<SolutionOf<T>>;
#[derive(Debug, Eq, PartialEq)]
pub enum MinerError {
@@ -231,7 +232,7 @@ impl<T: Config> Pallet<T> {
//
// Performance: note that it internally clones the provided solution.
pub fn basic_checks(
raw_solution: &RawSolution<CompactOf<T>>,
raw_solution: &RawSolution<SolutionOf<T>>,
solution_type: &str,
) -> Result<(), MinerError> {
Self::unsigned_pre_dispatch_checks(raw_solution).map_err(|err| {
@@ -257,7 +258,7 @@ impl<T: Config> Pallet<T> {
/// [`Pallet::mine_check_save_submit`].
pub fn mine_and_check(
iters: usize,
) -> Result<(RawSolution<CompactOf<T>>, SolutionOrSnapshotSize), MinerError> {
) -> Result<(RawSolution<SolutionOf<T>>, SolutionOrSnapshotSize), MinerError> {
let (raw_solution, witness) = Self::mine_solution(iters)?;
Self::basic_checks(&raw_solution, "mined")?;
Ok((raw_solution, witness))
@@ -266,12 +267,12 @@ impl<T: Config> Pallet<T> {
/// Mine a new npos solution.
pub fn mine_solution(
iters: usize,
) -> Result<(RawSolution<CompactOf<T>>, SolutionOrSnapshotSize), MinerError> {
) -> Result<(RawSolution<SolutionOf<T>>, SolutionOrSnapshotSize), MinerError> {
let RoundSnapshot { voters, targets } =
Self::snapshot().ok_or(MinerError::SnapshotUnAvailable)?;
let desired_targets = Self::desired_targets().ok_or(MinerError::SnapshotUnAvailable)?;
seq_phragmen::<_, CompactAccuracyOf<T>>(
seq_phragmen::<_, SolutionAccuracyOf<T>>(
desired_targets as usize,
targets,
voters,
@@ -286,8 +287,8 @@ impl<T: Config> Pallet<T> {
///
/// Will always reduce the solution as well.
pub fn prepare_election_result(
election_result: ElectionResult<T::AccountId, CompactAccuracyOf<T>>,
) -> Result<(RawSolution<CompactOf<T>>, SolutionOrSnapshotSize), MinerError> {
election_result: ElectionResult<T::AccountId, SolutionAccuracyOf<T>>,
) -> Result<(RawSolution<SolutionOf<T>>, SolutionOrSnapshotSize), MinerError> {
// NOTE: This code path is generally not optimized as it is run offchain. Could use some at
// some point though.
@@ -304,11 +305,11 @@ impl<T: Config> Pallet<T> {
let target_at = helpers::target_at_fn::<T>(&targets);
let stake_of = helpers::stake_of_fn::<T>(&voters, &cache);
// Compute the size of a compact solution comprised of the selected arguments.
// Compute the size of a solution comprised of the selected arguments.
//
// This function completes in `O(edges)`; it's expensive, but linear.
let encoded_size_of = |assignments: &[IndexAssignmentOf<T>]| {
CompactOf::<T>::try_from(assignments).map(|compact| compact.encoded_size())
SolutionOf::<T>::try_from(assignments).map(|s| s.encoded_size())
};
let ElectionResult { assignments, winners } = election_result;
@@ -345,7 +346,7 @@ impl<T: Config> Pallet<T> {
};
// convert to `IndexAssignment`. This improves the runtime complexity of repeatedly
// converting to `Compact`.
// converting to `Solution`.
let mut index_assignments = sorted_assignments
.into_iter()
.map(|assignment| IndexAssignmentOf::<T>::new(&assignment, &voter_index, &target_index))
@@ -366,15 +367,15 @@ impl<T: Config> Pallet<T> {
&encoded_size_of,
)?;
// now make compact.
let compact = CompactOf::<T>::try_from(&index_assignments)?;
// now make solution.
let solution = SolutionOf::<T>::try_from(&index_assignments)?;
// re-calc score.
let winners = sp_npos_elections::to_without_backing(winners);
let score = compact.clone().score(&winners, stake_of, voter_at, target_at)?;
let score = solution.clone().score(&winners, stake_of, voter_at, target_at)?;
let round = Self::round();
Ok((RawSolution { compact, score, round }, size))
Ok((RawSolution { solution, score, round }, size))
}
/// Get a random number of iterations to run the balancing in the OCW.
@@ -502,7 +503,7 @@ impl<T: Config> Pallet<T> {
Ok(())
}
/// Find the maximum `len` that a compact can have in order to fit into the block weight.
/// Find the maximum `len` that a solution can have in order to fit into the block weight.
///
/// This only returns a value between zero and `size.nominators`.
pub fn maximum_voter_for_weight<W: WeightInfo>(
@@ -623,24 +624,26 @@ impl<T: Config> Pallet<T> {
///
/// NOTE: Ideally, these tests should move more and more outside of this and more to the miner's
/// code, so that we do less and less storage reads here.
pub fn unsigned_pre_dispatch_checks(solution: &RawSolution<CompactOf<T>>) -> DispatchResult {
pub fn unsigned_pre_dispatch_checks(
raw_solution: &RawSolution<SolutionOf<T>>,
) -> DispatchResult {
// ensure solution is timely. Don't panic yet. This is a cheap check.
ensure!(Self::current_phase().is_unsigned_open(), Error::<T>::PreDispatchEarlySubmission);
// ensure round is current
ensure!(Self::round() == solution.round, Error::<T>::OcwCallWrongEra);
ensure!(Self::round() == raw_solution.round, Error::<T>::OcwCallWrongEra);
// ensure correct number of winners.
ensure!(
Self::desired_targets().unwrap_or_default() ==
solution.compact.unique_targets().len() as u32,
raw_solution.solution.unique_targets().len() as u32,
Error::<T>::PreDispatchWrongWinnerCount,
);
// ensure score is being improved. Panic henceforth.
ensure!(
Self::queued_solution().map_or(true, |q: ReadySolution<_>| is_score_better::<Perbill>(
solution.score,
raw_solution.score,
q.score,
T::SolutionImprovementThreshold::get()
)),
@@ -753,7 +756,7 @@ mod tests {
mock::{
roll_to, roll_to_with_ocw, trim_helpers, witness, BlockNumber, Call as OuterCall,
ExtBuilder, Extrinsic, MinerMaxWeight, MultiPhase, Origin, Runtime, System,
TestCompact, TrimHelpers, UnsignedPhase,
TestNposSolution, TrimHelpers, UnsignedPhase,
},
CurrentPhase, InvalidTransaction, Phase, QueuedSolution, TransactionSource,
TransactionValidityError,
@@ -772,7 +775,8 @@ mod tests {
#[test]
fn validate_unsigned_retracts_wrong_phase() {
ExtBuilder::default().desired_targets(0).build_and_execute(|| {
let solution = RawSolution::<TestCompact> { score: [5, 0, 0], ..Default::default() };
let solution =
RawSolution::<TestNposSolution> { score: [5, 0, 0], ..Default::default() };
let call = Call::submit_unsigned(Box::new(solution.clone()), witness());
// initial
@@ -841,7 +845,8 @@ mod tests {
roll_to(25);
assert!(MultiPhase::current_phase().is_unsigned());
let solution = RawSolution::<TestCompact> { score: [5, 0, 0], ..Default::default() };
let solution =
RawSolution::<TestNposSolution> { score: [5, 0, 0], ..Default::default() };
let call = Call::submit_unsigned(Box::new(solution.clone()), witness());
// initial
@@ -878,9 +883,9 @@ mod tests {
roll_to(25);
assert!(MultiPhase::current_phase().is_unsigned());
let solution = RawSolution::<TestCompact> { score: [5, 0, 0], ..Default::default() };
let call = Call::submit_unsigned(Box::new(solution.clone()), witness());
assert_eq!(solution.compact.unique_targets().len(), 0);
let raw = RawSolution::<TestNposSolution> { score: [5, 0, 0], ..Default::default() };
let call = Call::submit_unsigned(Box::new(raw.clone()), witness());
assert_eq!(raw.solution.unique_targets().len(), 0);
// won't work anymore.
assert!(matches!(
@@ -904,7 +909,7 @@ mod tests {
assert!(MultiPhase::current_phase().is_unsigned());
let solution =
RawSolution::<TestCompact> { score: [5, 0, 0], ..Default::default() };
RawSolution::<TestNposSolution> { score: [5, 0, 0], ..Default::default() };
let call = Call::submit_unsigned(Box::new(solution.clone()), witness());
assert_eq!(
@@ -930,7 +935,8 @@ mod tests {
assert!(MultiPhase::current_phase().is_unsigned());
// This is in itself an invalid BS solution.
let solution = RawSolution::<TestCompact> { score: [5, 0, 0], ..Default::default() };
let solution =
RawSolution::<TestNposSolution> { score: [5, 0, 0], ..Default::default() };
let call = Call::submit_unsigned(Box::new(solution.clone()), witness());
let outer_call: OuterCall = call.into();
let _ = outer_call.dispatch(Origin::none());
@@ -946,7 +952,8 @@ mod tests {
assert!(MultiPhase::current_phase().is_unsigned());
// This solution is unfeasible as well, but we won't even get there.
let solution = RawSolution::<TestCompact> { score: [5, 0, 0], ..Default::default() };
let solution =
RawSolution::<TestNposSolution> { score: [5, 0, 0], ..Default::default() };
let mut correct_witness = witness();
correct_witness.voters += 1;
@@ -986,30 +993,30 @@ mod tests {
roll_to(25);
assert!(MultiPhase::current_phase().is_unsigned());
let (solution, witness) = MultiPhase::mine_solution(2).unwrap();
let (raw, witness) = MultiPhase::mine_solution(2).unwrap();
let solution_weight = <Runtime as Config>::WeightInfo::submit_unsigned(
witness.voters,
witness.targets,
solution.compact.voter_count() as u32,
solution.compact.unique_targets().len() as u32,
raw.solution.voter_count() as u32,
raw.solution.unique_targets().len() as u32,
);
// default solution will have 5 edges (5 * 5 + 10)
assert_eq!(solution_weight, 35);
assert_eq!(solution.compact.voter_count(), 5);
assert_eq!(raw.solution.voter_count(), 5);
// now reduce the max weight
<MinerMaxWeight>::set(25);
let (solution, witness) = MultiPhase::mine_solution(2).unwrap();
let (raw, witness) = MultiPhase::mine_solution(2).unwrap();
let solution_weight = <Runtime as Config>::WeightInfo::submit_unsigned(
witness.voters,
witness.targets,
solution.compact.voter_count() as u32,
solution.compact.unique_targets().len() as u32,
raw.solution.voter_count() as u32,
raw.solution.unique_targets().len() as u32,
);
// default solution will have 5 edges (5 * 5 + 10)
assert_eq!(solution_weight, 25);
assert_eq!(solution.compact.voter_count(), 3);
assert_eq!(raw.solution.voter_count(), 3);
})
}
@@ -1068,7 +1075,7 @@ mod tests {
Assignment { who: 10, distribution: vec![(10, PerU16::one())] },
Assignment {
who: 7,
// note: this percent doesn't even matter, in compact it is 100%.
// note: this percent doesn't even matter, in solution it is 100%.
distribution: vec![(10, PerU16::one())],
},
],
@@ -1090,7 +1097,7 @@ mod tests {
Assignment { who: 7, distribution: vec![(10, PerU16::one())] },
Assignment {
who: 8,
// note: this percent doesn't even matter, in compact it is 100%.
// note: this percent doesn't even matter, in solution it is 100%.
distribution: vec![(10, PerU16::one())],
},
],
@@ -1400,17 +1407,17 @@ mod tests {
// given
let TrimHelpers { mut assignments, encoded_size_of, .. } = trim_helpers();
let compact = CompactOf::<Runtime>::try_from(assignments.as_slice()).unwrap();
let encoded_len = compact.encoded_size() as u32;
let compact_clone = compact.clone();
let solution = SolutionOf::<Runtime>::try_from(assignments.as_slice()).unwrap();
let encoded_len = solution.encoded_size() as u32;
let solution_clone = solution.clone();
// when
MultiPhase::trim_assignments_length(encoded_len, &mut assignments, encoded_size_of)
.unwrap();
// then
let compact = CompactOf::<Runtime>::try_from(assignments.as_slice()).unwrap();
assert_eq!(compact, compact_clone);
let solution = SolutionOf::<Runtime>::try_from(assignments.as_slice()).unwrap();
assert_eq!(solution, solution_clone);
});
}
@@ -1421,9 +1428,9 @@ mod tests {
// given
let TrimHelpers { mut assignments, encoded_size_of, .. } = trim_helpers();
let compact = CompactOf::<Runtime>::try_from(assignments.as_slice()).unwrap();
let encoded_len = compact.encoded_size();
let compact_clone = compact.clone();
let solution = SolutionOf::<Runtime>::try_from(assignments.as_slice()).unwrap();
let encoded_len = solution.encoded_size();
let solution_clone = solution.clone();
// when
MultiPhase::trim_assignments_length(
@@ -1434,9 +1441,9 @@ mod tests {
.unwrap();
// then
let compact = CompactOf::<Runtime>::try_from(assignments.as_slice()).unwrap();
assert_ne!(compact, compact_clone);
assert!(compact.encoded_size() < encoded_len);
let solution = SolutionOf::<Runtime>::try_from(assignments.as_slice()).unwrap();
assert_ne!(solution, solution_clone);
assert!(solution.encoded_size() < encoded_len);
});
}
@@ -1448,8 +1455,8 @@ mod tests {
// given
let TrimHelpers { voters, mut assignments, encoded_size_of, voter_index } =
trim_helpers();
let compact = CompactOf::<Runtime>::try_from(assignments.as_slice()).unwrap();
let encoded_len = compact.encoded_size() as u32;
let solution = SolutionOf::<Runtime>::try_from(assignments.as_slice()).unwrap();
let encoded_len = solution.encoded_size() as u32;
let count = assignments.len();
let min_stake_voter = voters
.iter()
@@ -1476,15 +1483,15 @@ mod tests {
// we shan't panic if assignments are initially empty.
ExtBuilder::default().build_and_execute(|| {
let encoded_size_of = Box::new(|assignments: &[IndexAssignmentOf<Runtime>]| {
CompactOf::<Runtime>::try_from(assignments).map(|compact| compact.encoded_size())
SolutionOf::<Runtime>::try_from(assignments).map(|solution| solution.encoded_size())
});
let mut assignments = vec![];
// since we have 16 fields, we need to store the length fields of 16 vecs, thus 16 bytes
// minimum.
let min_compact_size = encoded_size_of(&assignments).unwrap();
assert_eq!(min_compact_size, CompactOf::<Runtime>::LIMIT);
let min_solution_size = encoded_size_of(&assignments).unwrap();
assert_eq!(min_solution_size, SolutionOf::<Runtime>::LIMIT);
// all of this should not panic.
MultiPhase::trim_assignments_length(0, &mut assignments, encoded_size_of.clone())
@@ -1492,7 +1499,7 @@ mod tests {
MultiPhase::trim_assignments_length(1, &mut assignments, encoded_size_of.clone())
.unwrap();
MultiPhase::trim_assignments_length(
min_compact_size as u32,
min_solution_size as u32,
&mut assignments,
encoded_size_of,
)
@@ -1506,10 +1513,10 @@ mod tests {
let TrimHelpers { mut assignments, encoded_size_of, .. } = trim_helpers();
assert!(assignments.len() > 0);
// trim to min compact size.
let min_compact_size = CompactOf::<Runtime>::LIMIT as u32;
// trim to min solution size.
let min_solution_size = SolutionOf::<Runtime>::LIMIT as u32;
MultiPhase::trim_assignments_length(
min_compact_size,
min_solution_size,
&mut assignments,
encoded_size_of,
)
@@ -1529,14 +1536,14 @@ mod tests {
// how long would the default solution be?
let solution = MultiPhase::mine_solution(0).unwrap();
let max_length = <Runtime as Config>::MinerMaxLength::get();
let solution_size = solution.0.compact.encoded_size();
let solution_size = solution.0.solution.encoded_size();
assert!(solution_size <= max_length as usize);
// now set the max size to less than the actual size and regenerate
<Runtime as Config>::MinerMaxLength::set(solution_size as u32 - 1);
let solution = MultiPhase::mine_solution(0).unwrap();
let max_length = <Runtime as Config>::MinerMaxLength::get();
let solution_size = solution.0.compact.encoded_size();
let solution_size = solution.0.solution.encoded_size();
assert!(solution_size <= max_length as usize);
});
}