Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
89 commits
Select commit Hold shift + click to select a range
25bddc9
mockup
kianenigma Sep 11, 2020
7bef52f
Add files
kianenigma Sep 11, 2020
4f3dfa4
Merge branch 'master' of github.com:paritytech/substrate into kiz-ele…
kianenigma Sep 23, 2020
bc30ce1
More mockup
kianenigma Sep 24, 2020
9e52fbc
Merge branch 'master' of github.com:paritytech/substrate into kiz-ele…
kianenigma Oct 1, 2020
14ebc95
Lots more changes and tests. Initial design of signed is forseable now.
kianenigma Oct 2, 2020
0587fc9
Merge branch 'master' of github.com:paritytech/substrate into kiz-ele…
kianenigma Oct 8, 2020
233d4e1
More changes for the signed phase, now going to the cluster-fu*k of g…
kianenigma Oct 9, 2020
9c880f3
Finally decoupled solution from the pallet.. such a PITA.
kianenigma Oct 9, 2020
0cb35eb
Much simplifications and cleanups.
kianenigma Oct 9, 2020
c1ff3ec
A skeleton for the unsigned version.
kianenigma Oct 9, 2020
85a346e
Master.into()
kianenigma Oct 13, 2020
6a2542d
Staking builds and tests compile, some tests fail
kianenigma Oct 13, 2020
c361911
All staking tests work
kianenigma Oct 14, 2020
218db10
Unsigned almost done, primitive crate added.
kianenigma Oct 15, 2020
5e21a79
Merge branch 'master' of github.com:paritytech/substrate into kiz-ele…
kianenigma Oct 15, 2020
25c1bc3
Use decl_error
kianenigma Oct 15, 2020
d53785c
Add basic benchmark setup, needs more work
kianenigma Oct 16, 2020
525f6e0
Comment.
kianenigma Oct 16, 2020
3026316
Checkpoint.
kianenigma Oct 20, 2020
9841e3b
node-runtime builds.
kianenigma Oct 20, 2020
16c0550
Builds and all good?
kianenigma Dec 3, 2020
f197b6b
Undo some formatting mistakes
kianenigma Dec 3, 2020
5005281
Working on benchmarks'
kianenigma Dec 7, 2020
bd0d331
Fix bench
kianenigma Dec 8, 2020
67dd4d1
Strange merge -- everything builds.
kianenigma Dec 8, 2020
eac4571
Everything compiles and good -- need to fix benches.
kianenigma Dec 8, 2020
a7c4841
Some Staking stuff left to do.
kianenigma Dec 9, 2020
2ca3dcf
Master.into()
kianenigma Dec 14, 2020
4922897
Split the snapshot; type for CompactSolution and MaxNominations
kianenigma Dec 15, 2020
ef593a7
Fix a bunch more issues.
kianenigma Dec 15, 2020
8661814
check new design
kianenigma Dec 18, 2020
57f7294
Everything within the module works and compiles.
kianenigma Dec 21, 2020
af304d1
Stkaing also builds
kianenigma Dec 21, 2020
80e7450
Everything builds with the new scheme.
kianenigma Dec 25, 2020
4b4712a
Master.into()
kianenigma Dec 26, 2020
206933a
Simplify elect API.
kianenigma Dec 26, 2020
af9b97d
Fix all other tests.
kianenigma Dec 26, 2020
9663fea
make the staking api better and well tested.
kianenigma Jan 4, 2021
7f4f5b7
Almost done with conversion
kianenigma Jan 4, 2021
8fb11f1
Move to pallet V2 + construct_runtime
kianenigma Jan 5, 2021
bd6d4d9
Master.into()
kianenigma Jan 5, 2021
65f5ac1
Revert staking changes;
kianenigma Jan 5, 2021
3860885
Revert Staking fuzzer.
kianenigma Jan 5, 2021
392f35a
Fix fuzzers
kianenigma Jan 5, 2021
1337e1b
Update frame/election-providers/src/two_phase/mod.rs
kianenigma Jan 6, 2021
4f6ec0d
a round of self review
kianenigma Jan 6, 2021
b3113f7
A large number of bugfixes after local test and self-review
kianenigma Jan 7, 2021
abca039
Upstream.into()
kianenigma Jan 7, 2021
6bc578a
Master.into()
kianenigma Jan 7, 2021
876f666
Apply suggestions from code review
kianenigma Jan 7, 2021
81df1df
Update frame/election-providers/src/two_phase/benchmarking.rs
kianenigma Jan 7, 2021
e3862ce
Fix some review grumbles.
kianenigma Jan 8, 2021
ca06f8e
Fix some docs
kianenigma Jan 8, 2021
6206c32
Merge branch 'kiz-election-provider' of github.com:paritytech/substra…
kianenigma Jan 8, 2021
95d7a3c
Master.into()
kianenigma Jan 8, 2021
63776ff
Maybe relocalte the code?
kianenigma Jan 8, 2021
4732854
Master.into()
kianenigma Jan 8, 2021
a922f0b
Witness -> SoltionSize
kianenigma Jan 8, 2021
6d8247a
cargo run --release --features=runtime-benchmarks --manifest-path=bin…
Jan 8, 2021
e9f4437
cargo run --release --features=runtime-benchmarks --manifest-path=bin…
Jan 8, 2021
02069e1
Update frame/session/src/lib.rs
kianenigma Jan 12, 2021
000ecdc
Revamp macros
kianenigma Jan 12, 2021
cb6f156
Merge branch 'kiz-election-provider' of github.com:paritytech/substra…
kianenigma Jan 12, 2021
df04ef3
Merge remote-tracking branch 'origin/master' into kiz-election-provider
Jan 12, 2021
ee2a316
Master.into()
kianenigma Jan 12, 2021
0d92ed5
Merge branch 'kiz-election-provider' of github.com:paritytech/substra…
kianenigma Jan 12, 2021
88a96a0
Fix build
kianenigma Jan 12, 2021
6480ce1
Merge remote-tracking branch 'origin/master' into kiz-election-provider
Jan 12, 2021
8a68915
cargo run --release --features=runtime-benchmarks --manifest-path=bin…
Jan 12, 2021
f4e2c03
Merge branch 'master' of github.com:paritytech/substrate into kiz-ele…
kianenigma Jan 12, 2021
c41ecb0
fix all the tests.
kianenigma Jan 13, 2021
b42336a
Merge branch 'kiz-election-provider' of github.com:paritytech/substra…
kianenigma Jan 13, 2021
f5e23f9
Fix the strange issue with cargo lock
kianenigma Jan 13, 2021
56bb93c
revamp closures.
kianenigma Jan 14, 2021
257795c
Update frame/two-phase-election-provider/src/benchmarking.rs
kianenigma Jan 14, 2021
9c114bc
Merge remote-tracking branch 'origin/master' into kiz-election-provider
Jan 14, 2021
1ac97f5
Some review grumbles.
kianenigma Jan 14, 2021
366b15b
Merge branch 'master' of github.com:paritytech/substrate into kiz-ele…
kianenigma Jan 14, 2021
afa5507
Upstream.into()
kianenigma Jan 14, 2021
5d206ab
Fix build
kianenigma Jan 14, 2021
ea193c7
Bring back benches
kianenigma Jan 14, 2021
60e57d7
cargo run --release --features=runtime-benchmarks --manifest-path=bin…
Jan 14, 2021
77f53a3
Add a bunch of more fixes: signed weight check, tests etc.
kianenigma Jan 15, 2021
9ce9d6b
Merge branch 'kiz-election-provider' of github.com:paritytech/substra…
kianenigma Jan 15, 2021
b30dfb3
Fix build
kianenigma Jan 15, 2021
6001d7d
Master.into()
kianenigma Jan 15, 2021
a066e4a
Last small tweaks
kianenigma Jan 15, 2021
10f6e7b
Fix all tests.
kianenigma Jan 15, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
revamp closures.
  • Loading branch information
kianenigma committed Jan 14, 2021
commit 56bb93c415a7f8439b71ab35e9f04c9922d87a57
12 changes: 6 additions & 6 deletions frame/staking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1083,37 +1083,37 @@ decl_storage! {
/// Snapshot of validators at the beginning of the current election window. This should only
/// have a value when [`EraElectionStatus`] == `ElectionStatus::Open(_)`.
///
/// DEPRECATED.
/// TODO: TWO_PHASE: should be removed once we switch to two-phase.
pub SnapshotValidators get(fn snapshot_validators): Option<Vec<T::AccountId>>;

/// Snapshot of nominators at the beginning of the current election window. This should only
/// have a value when [`EraElectionStatus`] == `ElectionStatus::Open(_)`.
///
/// DEPRECATED.
/// TODO: TWO_PHASE: should be removed once we switch to two-phase.
pub SnapshotNominators get(fn snapshot_nominators): Option<Vec<T::AccountId>>;

/// The next validator set. At the end of an era, if this is available (potentially from the
/// result of an offchain worker), it is immediately used. Otherwise, the on-chain election
/// is executed.
///
/// DEPRECATED.
/// TODO: TWO_PHASE: should be removed once we switch to two-phase.
pub QueuedElected get(fn queued_elected): Option<ElectionResult<T::AccountId, BalanceOf<T>>>;

/// The score of the current [`QueuedElected`].
///
/// DEPRECATED.
/// TODO: TWO_PHASE: should be removed once we switch to two-phase.
pub QueuedScore get(fn queued_score): Option<ElectionScore>;

/// Flag to control the execution of the offchain election. When `Open(_)`, we accept
/// solutions to be submitted.
///
/// DEPRECATED.
/// TODO: TWO_PHASE: should be removed once we switch to two-phase.
pub EraElectionStatus get(fn era_election_status): ElectionStatus<T::BlockNumber>;

/// True if the current **planned** session is final. Note that this does not take era
/// forcing into account.
///
/// DEPRECATED.
/// TODO: TWO_PHASE: should be removed once we switch to two-phase.
pub IsCurrentSessionFinal get(fn is_current_session_final): bool = false;

/// True if network has been upgraded to this version.
Expand Down
11 changes: 6 additions & 5 deletions frame/two-phase-election-provider/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,11 +127,12 @@ where
// write the snapshot to staking or whoever is the data provider.
T::DataProvider::put_snapshot(all_voters.clone(), targets.clone());

crate::stake_of_fn!(let stake_of, all_voters, T);
crate::voter_index_fn!(let voter_index, all_voters, T);
crate::voter_at_fn!(let voter_at, all_voters, T);
crate::target_at_fn!(let target_at, targets, T);
crate::target_index_fn!(let target_index, targets, T);
let cache = helpers::generate_voter_cache::<T>(&all_voters);
let stake_of = helpers::stake_of_fn::<T>(&all_voters, &cache);
let voter_index = helpers::voter_index_fn::<T>(&cache);
let target_index = helpers::target_index_fn_linear::<T>(&targets);
let voter_at = helpers::voter_at_fn::<T>(&all_voters);
let target_at = helpers::target_at_fn::<T>(&targets);

let assignments = active_voters
.iter()
Expand Down
208 changes: 208 additions & 0 deletions frame/two-phase-election-provider/src/helpers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
// This file is part of Substrate.

// Copyright (C) 2020 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.

//! Some helper functions/macros for this crate.

use super::{
Config, VoteWeight, CompactVoterIndexOf, CompactTargetIndexOf, CompactAccuracyOf,
OnChainAccuracyOf, ExtendedBalance,
};
use sp_runtime::InnerOf;
use sp_std::{collections::btree_map::BTreeMap, convert::TryInto};

#[macro_export]
macro_rules! log {
($level:tt, $patter:expr $(, $values:expr)* $(,)?) => {
frame_support::debug::$level!(
target: $crate::LOG_TARGET,
concat!("🏦 ", $patter) $(, $values)*
)
};
}

/// Generate a btree-map cache of the voters and their indices.
///
/// This can be used to efficiently build index getter closures.
pub fn generate_voter_cache<T: Config>(
snapshot: &Vec<(T::AccountId, VoteWeight, Vec<T::AccountId>)>,
) -> BTreeMap<T::AccountId, usize>
where
ExtendedBalance: From<InnerOf<CompactAccuracyOf<T>>>,
ExtendedBalance: From<InnerOf<OnChainAccuracyOf<T>>>,
{
let mut cache: BTreeMap<T::AccountId, usize> = BTreeMap::new();
snapshot.iter().enumerate().for_each(|(i, (x, _, _))| {
let _existed = cache.insert(x.clone(), i);
// if a duplicate exists, we only consider the last one. Defensive only, should never happen.
debug_assert!(_existed.is_none());
});

cache
}

/// Create a function the returns the index a voter in the snapshot.
///
/// The returning index type is the same as the one defined in [`T::CompactSolution::Voter`].
///
/// ## Warning
///
/// The snapshot must be the same is the one used to create `cache`.
pub fn voter_index_fn<T: Config>(
cache: &BTreeMap<T::AccountId, usize>,
) -> Box<dyn Fn(&T::AccountId) -> Option<CompactVoterIndexOf<T>> + '_>
where
ExtendedBalance: From<InnerOf<CompactAccuracyOf<T>>>,
ExtendedBalance: From<InnerOf<OnChainAccuracyOf<T>>>,
{
Box::new(move |who| {
cache
.get(who)
.and_then(|i| <usize as TryInto<CompactVoterIndexOf<T>>>::try_into(*i).ok())
})
}

/// Same as [`voter_index_fn`], but the returning index is converted into usize, if possible.
///
/// ## Warning
///
/// The snapshot must be the same is the one used to create `cache`.
pub fn voter_index_fn_usize<T: Config>(
cache: &BTreeMap<T::AccountId, usize>,
) -> Box<dyn Fn(&T::AccountId) -> Option<usize> + '_>
where
ExtendedBalance: From<InnerOf<CompactAccuracyOf<T>>>,
ExtendedBalance: From<InnerOf<OnChainAccuracyOf<T>>>,
{
Box::new(move |who| cache.get(who).cloned())
}

/// A non-optimized, linear version of [`voter_index_fn`] that does not need a cache and does a
/// linear search.
///
/// ## Warning
///
/// Not meant to be used in production.
pub fn voter_index_fn_linear<T: Config>(
snapshot: &Vec<(T::AccountId, VoteWeight, Vec<T::AccountId>)>,
) -> Box<dyn Fn(&T::AccountId) -> Option<CompactVoterIndexOf<T>> + '_>
where
ExtendedBalance: From<InnerOf<CompactAccuracyOf<T>>>,
ExtendedBalance: From<InnerOf<OnChainAccuracyOf<T>>>,
{
Box::new(move |who| {
snapshot
.iter()
.position(|(x, _, _)| x == who)
.and_then(|i| <usize as TryInto<CompactVoterIndexOf<T>>>::try_into(i).ok())
})
}

/// Create a function the returns the index a targets in the snapshot.
///
/// The returning index type is the same as the one defined in [`T::CompactSolution::Target`].
pub fn target_index_fn_linear<T: Config>(
snapshot: &Vec<T::AccountId>,
) -> Box<dyn Fn(&T::AccountId) -> Option<CompactTargetIndexOf<T>> + '_>
where
ExtendedBalance: From<InnerOf<CompactAccuracyOf<T>>>,
ExtendedBalance: From<InnerOf<OnChainAccuracyOf<T>>>,
{
Box::new(move |who| {
snapshot
.iter()
.position(|x| x == who)
.and_then(|i| <usize as TryInto<CompactTargetIndexOf<T>>>::try_into(i).ok())
})
}

/// Create a function that can map a voter index ([`CompactVoterIndexOf`]) 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>)>,
) -> Box<dyn Fn(CompactVoterIndexOf<T>) -> Option<T::AccountId> + '_>
where
ExtendedBalance: From<InnerOf<CompactAccuracyOf<T>>>,
ExtendedBalance: From<InnerOf<OnChainAccuracyOf<T>>>,
{
Box::new(move |i| {
<CompactVoterIndexOf<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
/// account using a linearly indexible snapshot.
pub fn target_at_fn<T: Config>(
snapshot: &Vec<T::AccountId>,
) -> Box<dyn Fn(CompactTargetIndexOf<T>) -> Option<T::AccountId> + '_>
where
ExtendedBalance: From<InnerOf<CompactAccuracyOf<T>>>,
ExtendedBalance: From<InnerOf<OnChainAccuracyOf<T>>>,
{
Box::new(move |i| {
<CompactTargetIndexOf<T> as TryInto<usize>>::try_into(i)
.ok()
.and_then(|i| snapshot.get(i).cloned())
})
}

/// Create a function to get the stake of a voter.
///
/// This is not optimized and uses a linear search.
pub fn stake_of_fn_linear<T: Config>(
snapshot: &Vec<(T::AccountId, VoteWeight, Vec<T::AccountId>)>,
) -> Box<dyn Fn(&T::AccountId) -> VoteWeight + '_>
where
ExtendedBalance: From<InnerOf<CompactAccuracyOf<T>>>,
ExtendedBalance: From<InnerOf<OnChainAccuracyOf<T>>>,
{
Box::new(move |who| {
snapshot
.iter()
.find(|(x, _, _)| x == who)
.map(|(_, x, _)| *x)
.unwrap_or_default()
})
}

/// Create a function to get the stake of a voter.
///
/// ## Warning
///
/// The cache need must be derived from the same snapshot. Zero is returned if a voter is
/// non-existent.
pub fn stake_of_fn<'a, T: Config>(
snapshot: &'a Vec<(T::AccountId, VoteWeight, Vec<T::AccountId>)>,
cache: &'a BTreeMap<T::AccountId, usize>,
) -> Box<dyn Fn(&T::AccountId) -> VoteWeight + 'a>
where
ExtendedBalance: From<InnerOf<CompactAccuracyOf<T>>>,
ExtendedBalance: From<InnerOf<OnChainAccuracyOf<T>>>,
{
Box::new(move |who| {
if let Some(index) = cache.get(who) {
snapshot
.get(*index)
.map(|(_, x, _)| x)
.cloned()
.unwrap_or_default()
} else {
0
}
})
}
22 changes: 15 additions & 7 deletions frame/two-phase-election-provider/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ mod benchmarking;
#[cfg(test)]
mod mock;
#[macro_use]
pub(crate) mod macros;
pub mod helpers;

const LOG_TARGET: &'static str = "election-provider";

Expand Down Expand Up @@ -634,8 +634,15 @@ pub mod pallet {
}

fn integrity_test() {
let max_vote: usize = <CompactOf<T> as CompactSolution>::LIMIT;
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>());

// ----------------------------
// based on the requirements of [`sp_npos_elections::Assignment::try_normalize`].
let max_vote: usize = <CompactOf<T> as CompactSolution>::LIMIT;

// 1. Maximum sum of [ChainAccuracy; 16] must fit into `UpperOf<ChainAccuracy>`..
let maximum_chain_accuracy: Vec<UpperOf<OnChainAccuracyOf<T>>> = (0..max_vote)
Expand Down Expand Up @@ -1064,9 +1071,10 @@ where
} = Self::snapshot().ok_or(FeasibilityError::SnapshotUnavailable)?;

// ----- Start building. First, we need some closures.
crate::voter_at_fn!(let voter_at , snapshot_voters, T);
crate::target_at_fn!(let target_at, snapshot_targets, T);
crate::voter_index_fn_usize!(let voter_index, snapshot_voters, T);
let cache = helpers::generate_voter_cache::<T>(&snapshot_voters);
let voter_at = helpers::voter_at_fn::<T>(&snapshot_voters);
let target_at = helpers::target_at_fn::<T>(&snapshot_targets);
let voter_index = helpers::voter_index_fn_usize::<T>(&cache);

// first, make sure that all the winners are sane.
let winners = winners
Expand Down Expand Up @@ -1106,8 +1114,8 @@ where
})
.collect::<Result<(), FeasibilityError>>()?;

// ----- Start building support. First, we need some more closures.
stake_of_fn!(let stake_of, snapshot_voters, T);
// ----- Start building support. First, we need one more closure.
let stake_of = helpers::stake_of_fn::<T>(&snapshot_voters, &cache);

// This might fail if the normalization fails. Very unlikely. See `integrity_test`.
let staked_assignments = assignment_ratio_to_staked_normalized(assignments, stake_of)
Expand Down
Loading