Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

Commit 58f0223

Browse files
chevdorgui1117kianenigma
authored
Multi-Block Election part 0: preparation and some cleanup. (#9442) (#9767)
* Partially applied * Everything builds, need to implement compact encoding as well. * Fix some tests, add a ui test as well. * Fix everything and everything. * Update primitives/npos-elections/solution-type/src/lib.rs * factor out double type * fix try-build Co-authored-by: Guillaume Thiolliere <gui.thiolliere@gmail.com> Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
1 parent 6ddfb71 commit 58f0223

36 files changed

+1327
-1364
lines changed

Cargo.lock

Lines changed: 15 additions & 15 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ members = [
156156
"primitives/keystore",
157157
"primitives/maybe-compressed-blob",
158158
"primitives/npos-elections",
159-
"primitives/npos-elections/compact",
159+
"primitives/npos-elections/solution-type",
160160
"primitives/npos-elections/fuzzer",
161161
"primitives/offchain",
162162
"primitives/panic-handler",

bin/node/runtime/src/lib.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -548,15 +548,14 @@ parameter_types! {
548548

549549
sp_npos_elections::generate_solution_type!(
550550
#[compact]
551-
pub struct NposCompactSolution16::<
551+
pub struct NposSolution16::<
552552
VoterIndex = u32,
553553
TargetIndex = u16,
554554
Accuracy = sp_runtime::PerU16,
555555
>(16)
556556
);
557557

558-
pub const MAX_NOMINATIONS: u32 =
559-
<NposCompactSolution16 as sp_npos_elections::CompactSolution>::LIMIT as u32;
558+
pub const MAX_NOMINATIONS: u32 = <NposSolution16 as sp_npos_elections::NposSolution>::LIMIT as u32;
560559

561560
/// The numbers configured here should always be more than the the maximum limits of staking pallet
562561
/// to ensure election snapshot will not run out of memory.
@@ -593,7 +592,7 @@ impl pallet_election_provider_multi_phase::Config for Runtime {
593592
type RewardHandler = (); // nothing to do upon rewards
594593
type DataProvider = Staking;
595594
type OnChainAccuracy = Perbill;
596-
type CompactSolution = NposCompactSolution16;
595+
type Solution = NposSolution16;
597596
type Fallback = Fallback;
598597
type WeightInfo = pallet_election_provider_multi_phase::weights::SubstrateWeight<Runtime>;
599598
type ForceOrigin = EnsureRootOrHalfCouncil;

frame/election-provider-multi-phase/Cargo.toml

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ hex-literal = "0.3.1"
4040
substrate-test-utils = { version = "4.0.0-dev", path = "../../test-utils" }
4141
sp-core = { version = "4.0.0-dev", default-features = false, path = "../../primitives/core" }
4242
sp-io = { version = "4.0.0-dev", path = "../../primitives/io" }
43-
sp-npos-elections = { version = "4.0.0-dev", default-features = false, features = [ "mocks" ], path = "../../primitives/npos-elections" }
43+
sp-npos-elections = { version = "4.0.0-dev", default-features = false, path = "../../primitives/npos-elections" }
4444
sp-tracing = { version = "4.0.0-dev", path = "../../primitives/tracing" }
4545
frame-election-provider-support = { version = "4.0.0-dev", features = ["runtime-benchmarks"], path = "../election-provider-support" }
4646
pallet-balances = { version = "4.0.0-dev", path = "../balances" }
@@ -67,6 +67,5 @@ std = [
6767
runtime-benchmarks = [
6868
"frame-benchmarking",
6969
"rand",
70-
"sp-npos-elections/mocks",
7170
]
7271
try-runtime = ["frame-support/try-runtime"]

frame/election-provider-multi-phase/src/benchmarking.rs

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -40,15 +40,15 @@ fn solution_with_size<T: Config>(
4040
size: SolutionOrSnapshotSize,
4141
active_voters_count: u32,
4242
desired_targets: u32,
43-
) -> Result<RawSolution<CompactOf<T>>, &'static str> {
43+
) -> Result<RawSolution<SolutionOf<T>>, &'static str> {
4444
ensure!(size.targets >= desired_targets, "must have enough targets");
4545
ensure!(
46-
size.targets >= (<CompactOf<T>>::LIMIT * 2) as u32,
46+
size.targets >= (<SolutionOf<T>>::LIMIT * 2) as u32,
4747
"must have enough targets for unique votes."
4848
);
4949
ensure!(size.voters >= active_voters_count, "must have enough voters");
5050
ensure!(
51-
(<CompactOf<T>>::LIMIT as u32) < desired_targets,
51+
(<SolutionOf<T>>::LIMIT as u32) < desired_targets,
5252
"must have enough winners to give them votes."
5353
);
5454

@@ -75,7 +75,7 @@ fn solution_with_size<T: Config>(
7575
// chose a random subset of winners.
7676
let winner_votes = winners
7777
.as_slice()
78-
.choose_multiple(&mut rng, <CompactOf<T>>::LIMIT)
78+
.choose_multiple(&mut rng, <SolutionOf<T>>::LIMIT)
7979
.cloned()
8080
.collect::<Vec<_>>();
8181
let voter = frame_benchmarking::account::<T::AccountId>("Voter", i, SEED);
@@ -92,7 +92,7 @@ fn solution_with_size<T: Config>(
9292
let rest_voters = (active_voters_count..size.voters)
9393
.map(|i| {
9494
let votes = (&non_winners)
95-
.choose_multiple(&mut rng, <CompactOf<T>>::LIMIT)
95+
.choose_multiple(&mut rng, <SolutionOf<T>>::LIMIT)
9696
.cloned()
9797
.collect::<Vec<T::AccountId>>();
9898
let voter = frame_benchmarking::account::<T::AccountId>("Voter", i, SEED);
@@ -129,25 +129,25 @@ fn solution_with_size<T: Config>(
129129
let assignments = active_voters
130130
.iter()
131131
.map(|(voter, _stake, votes)| {
132-
let percent_per_edge: InnerOf<CompactAccuracyOf<T>> =
132+
let percent_per_edge: InnerOf<SolutionAccuracyOf<T>> =
133133
(100 / votes.len()).try_into().unwrap_or_else(|_| panic!("failed to convert"));
134134
crate::unsigned::Assignment::<T> {
135135
who: voter.clone(),
136136
distribution: votes
137137
.iter()
138-
.map(|t| (t.clone(), <CompactAccuracyOf<T>>::from_percent(percent_per_edge)))
138+
.map(|t| (t.clone(), <SolutionAccuracyOf<T>>::from_percent(percent_per_edge)))
139139
.collect::<Vec<_>>(),
140140
}
141141
})
142142
.collect::<Vec<_>>();
143143

144-
let compact =
145-
<CompactOf<T>>::from_assignment(&assignments, &voter_index, &target_index).unwrap();
146-
let score = compact.clone().score(&winners, stake_of, voter_at, target_at).unwrap();
144+
let solution =
145+
<SolutionOf<T>>::from_assignment(&assignments, &voter_index, &target_index).unwrap();
146+
let score = solution.clone().score(&winners, stake_of, voter_at, target_at).unwrap();
147147
let round = <MultiPhase<T>>::round();
148148

149149
assert!(score[0] > 0, "score is zero, this probably means that the stakes are not set.");
150-
Ok(RawSolution { compact, score, round })
150+
Ok(RawSolution { solution, score, round })
151151
}
152152

153153
fn set_up_data_provider<T: Config>(v: u32, t: u32) {
@@ -265,7 +265,7 @@ frame_benchmarking::benchmarks! {
265265
let v in (T::BenchmarkingConfig::VOTERS[0]) .. T::BenchmarkingConfig::VOTERS[1];
266266
// number of targets in snapshot.
267267
let t in (T::BenchmarkingConfig::TARGETS[0]) .. T::BenchmarkingConfig::TARGETS[1];
268-
// number of assignments, i.e. compact.len(). This means the active nominators, thus must be
268+
// number of assignments, i.e. solution.len(). This means the active nominators, thus must be
269269
// a subset of `v` component.
270270
let a in (T::BenchmarkingConfig::ACTIVE_VOTERS[0]) .. T::BenchmarkingConfig::ACTIVE_VOTERS[1];
271271
// number of desired targets. Must be a subset of `t` component.
@@ -308,11 +308,11 @@ frame_benchmarking::benchmarks! {
308308

309309
let mut signed_submissions = SignedSubmissions::<T>::get();
310310
for i in 0..c {
311-
let solution = RawSolution {
311+
let raw_solution = RawSolution {
312312
score: [(10_000_000 + i).into(), 0, 0],
313313
..Default::default()
314314
};
315-
let signed_submission = SignedSubmission { solution, ..Default::default() };
315+
let signed_submission = SignedSubmission { raw_solution, ..Default::default() };
316316
signed_submissions.insert(signed_submission);
317317
}
318318
signed_submissions.put();
@@ -330,7 +330,7 @@ frame_benchmarking::benchmarks! {
330330
let v in (T::BenchmarkingConfig::VOTERS[0]) .. T::BenchmarkingConfig::VOTERS[1];
331331
// number of targets in snapshot.
332332
let t in (T::BenchmarkingConfig::TARGETS[0]) .. T::BenchmarkingConfig::TARGETS[1];
333-
// number of assignments, i.e. compact.len(). This means the active nominators, thus must be
333+
// number of assignments, i.e. solution.len(). This means the active nominators, thus must be
334334
// a subset of `v` component.
335335
let a in
336336
(T::BenchmarkingConfig::ACTIVE_VOTERS[0]) .. T::BenchmarkingConfig::ACTIVE_VOTERS[1];
@@ -369,7 +369,7 @@ frame_benchmarking::benchmarks! {
369369
let v in (T::BenchmarkingConfig::VOTERS[0]) .. T::BenchmarkingConfig::VOTERS[1];
370370
// number of targets in snapshot.
371371
let t in (T::BenchmarkingConfig::TARGETS[0]) .. T::BenchmarkingConfig::TARGETS[1];
372-
// number of assignments, i.e. compact.len(). This means the active nominators, thus must be
372+
// number of assignments, i.e. solution.len(). This means the active nominators, thus must be
373373
// a subset of `v` component.
374374
let a in (T::BenchmarkingConfig::ACTIVE_VOTERS[0]) .. T::BenchmarkingConfig::ACTIVE_VOTERS[1];
375375
// number of desired targets. Must be a subset of `t` component.
@@ -378,8 +378,8 @@ frame_benchmarking::benchmarks! {
378378
let size = SolutionOrSnapshotSize { voters: v, targets: t };
379379
let raw_solution = solution_with_size::<T>(size, a, d)?;
380380

381-
assert_eq!(raw_solution.compact.voter_count() as u32, a);
382-
assert_eq!(raw_solution.compact.unique_targets().len() as u32, d);
381+
assert_eq!(raw_solution.solution.voter_count() as u32, a);
382+
assert_eq!(raw_solution.solution.unique_targets().len() as u32, d);
383383

384384
// encode the most significant storage item that needs to be decoded in the dispatch.
385385
let encoded_snapshot = <MultiPhase<T>>::snapshot().unwrap().encode();
@@ -447,7 +447,7 @@ frame_benchmarking::benchmarks! {
447447
let v in (T::BenchmarkingConfig::VOTERS[0]) .. T::BenchmarkingConfig::VOTERS[1];
448448
// number of targets in snapshot.
449449
let t in (T::BenchmarkingConfig::TARGETS[0]) .. T::BenchmarkingConfig::TARGETS[1];
450-
// number of assignments, i.e. compact.len(). This means the active nominators, thus must be
450+
// number of assignments, i.e. solution.len(). This means the active nominators, thus must be
451451
// a subset of `v` component.
452452
let a in
453453
(T::BenchmarkingConfig::ACTIVE_VOTERS[0]) .. T::BenchmarkingConfig::ACTIVE_VOTERS[1];
@@ -461,11 +461,11 @@ frame_benchmarking::benchmarks! {
461461
// Compute a random solution, then work backwards to get the lists of voters, targets, and
462462
// assignments
463463
let witness = SolutionOrSnapshotSize { voters: v, targets: t };
464-
let RawSolution { compact, .. } = solution_with_size::<T>(witness, a, d)?;
464+
let RawSolution { solution, .. } = solution_with_size::<T>(witness, a, d)?;
465465
let RoundSnapshot { voters, targets } = MultiPhase::<T>::snapshot().unwrap();
466466
let voter_at = helpers::voter_at_fn::<T>(&voters);
467467
let target_at = helpers::target_at_fn::<T>(&targets);
468-
let mut assignments = compact.into_assignment(voter_at, target_at).unwrap();
468+
let mut assignments = solution.into_assignment(voter_at, target_at).unwrap();
469469

470470
// make a voter cache and some helper functions for access
471471
let cache = helpers::generate_voter_cache::<T>(&voters);
@@ -488,7 +488,7 @@ frame_benchmarking::benchmarks! {
488488
.unwrap();
489489

490490
let encoded_size_of = |assignments: &[IndexAssignmentOf<T>]| {
491-
CompactOf::<T>::try_from(assignments).map(|compact| compact.encoded_size())
491+
SolutionOf::<T>::try_from(assignments).map(|solution| solution.encoded_size())
492492
};
493493

494494
let desired_size = Percent::from_percent(100 - f.saturated_into::<u8>())
@@ -501,8 +501,8 @@ frame_benchmarking::benchmarks! {
501501
&encoded_size_of,
502502
).unwrap();
503503
} verify {
504-
let compact = CompactOf::<T>::try_from(index_assignments.as_slice()).unwrap();
505-
let encoding = compact.encode();
504+
let solution = SolutionOf::<T>::try_from(index_assignments.as_slice()).unwrap();
505+
let encoding = solution.encode();
506506
log!(
507507
trace,
508508
"encoded size prediction = {}",

frame/election-provider-multi-phase/src/helpers.rs

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
//! Some helper functions/macros for this crate.
1919
20-
use super::{CompactTargetIndexOf, CompactVoterIndexOf, Config, VoteWeight};
20+
use super::{Config, SolutionTargetIndexOf, SolutionVoterIndexOf, VoteWeight};
2121
use sp_std::{collections::btree_map::BTreeMap, convert::TryInto, prelude::*};
2222

2323
#[macro_export]
@@ -49,18 +49,18 @@ pub fn generate_voter_cache<T: Config>(
4949

5050
/// Create a function that returns the index of a voter in the snapshot.
5151
///
52-
/// The returning index type is the same as the one defined in `T::CompactSolution::Voter`.
52+
/// The returning index type is the same as the one defined in `T::Solution::Voter`.
5353
///
5454
/// ## Warning
5555
///
5656
/// Note that this will represent the snapshot data from which the `cache` is generated.
5757
pub fn voter_index_fn<T: Config>(
5858
cache: &BTreeMap<T::AccountId, usize>,
59-
) -> impl Fn(&T::AccountId) -> Option<CompactVoterIndexOf<T>> + '_ {
59+
) -> impl Fn(&T::AccountId) -> Option<SolutionVoterIndexOf<T>> + '_ {
6060
move |who| {
6161
cache
6262
.get(who)
63-
.and_then(|i| <usize as TryInto<CompactVoterIndexOf<T>>>::try_into(*i).ok())
63+
.and_then(|i| <usize as TryInto<SolutionVoterIndexOf<T>>>::try_into(*i).ok())
6464
}
6565
}
6666

@@ -70,11 +70,11 @@ pub fn voter_index_fn<T: Config>(
7070
/// borrowed.
7171
pub fn voter_index_fn_owned<T: Config>(
7272
cache: BTreeMap<T::AccountId, usize>,
73-
) -> impl Fn(&T::AccountId) -> Option<CompactVoterIndexOf<T>> {
73+
) -> impl Fn(&T::AccountId) -> Option<SolutionVoterIndexOf<T>> {
7474
move |who| {
7575
cache
7676
.get(who)
77-
.and_then(|i| <usize as TryInto<CompactVoterIndexOf<T>>>::try_into(*i).ok())
77+
.and_then(|i| <usize as TryInto<SolutionVoterIndexOf<T>>>::try_into(*i).ok())
7878
}
7979
}
8080

@@ -98,72 +98,72 @@ pub fn voter_index_fn_usize<T: Config>(
9898
#[cfg(test)]
9999
pub fn voter_index_fn_linear<T: Config>(
100100
snapshot: &Vec<(T::AccountId, VoteWeight, Vec<T::AccountId>)>,
101-
) -> impl Fn(&T::AccountId) -> Option<CompactVoterIndexOf<T>> + '_ {
101+
) -> impl Fn(&T::AccountId) -> Option<SolutionVoterIndexOf<T>> + '_ {
102102
move |who| {
103103
snapshot
104104
.iter()
105105
.position(|(x, _, _)| x == who)
106-
.and_then(|i| <usize as TryInto<CompactVoterIndexOf<T>>>::try_into(i).ok())
106+
.and_then(|i| <usize as TryInto<SolutionVoterIndexOf<T>>>::try_into(i).ok())
107107
}
108108
}
109109

110110
/// Create a function that returns the index of a target in the snapshot.
111111
///
112-
/// The returned index type is the same as the one defined in `T::CompactSolution::Target`.
112+
/// The returned index type is the same as the one defined in `T::Solution::Target`.
113113
///
114114
/// Note: to the extent possible, the returned function should be cached and reused. Producing that
115115
/// function requires a `O(n log n)` data transform. Each invocation of that function completes
116116
/// in `O(log n)`.
117117
pub fn target_index_fn<T: Config>(
118118
snapshot: &Vec<T::AccountId>,
119-
) -> impl Fn(&T::AccountId) -> Option<CompactTargetIndexOf<T>> + '_ {
119+
) -> impl Fn(&T::AccountId) -> Option<SolutionTargetIndexOf<T>> + '_ {
120120
let cache: BTreeMap<_, _> =
121121
snapshot.iter().enumerate().map(|(idx, account_id)| (account_id, idx)).collect();
122122
move |who| {
123123
cache
124124
.get(who)
125-
.and_then(|i| <usize as TryInto<CompactTargetIndexOf<T>>>::try_into(*i).ok())
125+
.and_then(|i| <usize as TryInto<SolutionTargetIndexOf<T>>>::try_into(*i).ok())
126126
}
127127
}
128128

129129
/// Create a function the returns the index to a target in the snapshot.
130130
///
131-
/// The returned index type is the same as the one defined in `T::CompactSolution::Target`.
131+
/// The returned index type is the same as the one defined in `T::Solution::Target`.
132132
///
133133
/// ## Warning
134134
///
135135
/// Not meant to be used in production.
136136
#[cfg(test)]
137137
pub fn target_index_fn_linear<T: Config>(
138138
snapshot: &Vec<T::AccountId>,
139-
) -> impl Fn(&T::AccountId) -> Option<CompactTargetIndexOf<T>> + '_ {
139+
) -> impl Fn(&T::AccountId) -> Option<SolutionTargetIndexOf<T>> + '_ {
140140
move |who| {
141141
snapshot
142142
.iter()
143143
.position(|x| x == who)
144-
.and_then(|i| <usize as TryInto<CompactTargetIndexOf<T>>>::try_into(i).ok())
144+
.and_then(|i| <usize as TryInto<SolutionTargetIndexOf<T>>>::try_into(i).ok())
145145
}
146146
}
147147

148-
/// Create a function that can map a voter index ([`CompactVoterIndexOf`]) to the actual voter
148+
/// Create a function that can map a voter index ([`SolutionVoterIndexOf`]) to the actual voter
149149
/// account using a linearly indexible snapshot.
150150
pub fn voter_at_fn<T: Config>(
151151
snapshot: &Vec<(T::AccountId, VoteWeight, Vec<T::AccountId>)>,
152-
) -> impl Fn(CompactVoterIndexOf<T>) -> Option<T::AccountId> + '_ {
152+
) -> impl Fn(SolutionVoterIndexOf<T>) -> Option<T::AccountId> + '_ {
153153
move |i| {
154-
<CompactVoterIndexOf<T> as TryInto<usize>>::try_into(i)
154+
<SolutionVoterIndexOf<T> as TryInto<usize>>::try_into(i)
155155
.ok()
156156
.and_then(|i| snapshot.get(i).map(|(x, _, _)| x).cloned())
157157
}
158158
}
159159

160-
/// Create a function that can map a target index ([`CompactTargetIndexOf`]) to the actual target
160+
/// Create a function that can map a target index ([`SolutionTargetIndexOf`]) to the actual target
161161
/// account using a linearly indexible snapshot.
162162
pub fn target_at_fn<T: Config>(
163163
snapshot: &Vec<T::AccountId>,
164-
) -> impl Fn(CompactTargetIndexOf<T>) -> Option<T::AccountId> + '_ {
164+
) -> impl Fn(SolutionTargetIndexOf<T>) -> Option<T::AccountId> + '_ {
165165
move |i| {
166-
<CompactTargetIndexOf<T> as TryInto<usize>>::try_into(i)
166+
<SolutionTargetIndexOf<T> as TryInto<usize>>::try_into(i)
167167
.ok()
168168
.and_then(|i| snapshot.get(i).cloned())
169169
}

0 commit comments

Comments
 (0)