Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
53 commits
Select commit Hold shift + click to select a range
d998b12
Base features and traits.
kianenigma Jan 15, 2021
5aea9cc
pallet and unsigned phase
kianenigma Jan 15, 2021
632e107
Undo bad formattings.
kianenigma Jan 15, 2021
c52e65d
Master.into()
kianenigma Jan 18, 2021
b4fc5e1
some formatting cleanup.
kianenigma Jan 18, 2021
cc26881
Small self-cleanup.
kianenigma Jan 18, 2021
67a9fae
Master.into()
kianenigma Jan 27, 2021
75eca3f
Make it all build
kianenigma Jan 27, 2021
8daec3a
self-review
kianenigma Jan 27, 2021
49613ed
Some doc tests.
kianenigma Jan 27, 2021
35f1faf
Some changes from other PR
kianenigma Jan 27, 2021
e01cacc
Fix session test
kianenigma Jan 27, 2021
6278150
Merge branch 'master' into kiz-election-provider-2-two-phase-unsigned
shawntabrizi Feb 4, 2021
4c516cb
Update Cargo.lock
shawntabrizi Feb 4, 2021
8c8d1e6
Update frame/election-provider-multi-phase/src/lib.rs
kianenigma Feb 11, 2021
4b58c91
Some review comments
kianenigma Feb 11, 2021
f4029aa
Merge branch 'kiz-election-provider-2-two-phase-unsigned' of github.c…
kianenigma Feb 11, 2021
f16ac88
Master.into()
kianenigma Feb 11, 2021
528917e
Rename + make encode/decode
kianenigma Feb 12, 2021
1a5794a
Do an assert as well, just in case.
kianenigma Feb 12, 2021
01e63ed
Fix build
kianenigma Feb 12, 2021
4ccecdf
Update frame/election-provider-multi-phase/src/unsigned.rs
kianenigma Feb 12, 2021
83a789e
Las comment
kianenigma Feb 12, 2021
adb3618
Merge branch 'kiz-election-provider-2-two-phase-unsigned' of github.c…
kianenigma Feb 12, 2021
7c71df0
fix staking fuzzer.
kianenigma Feb 12, 2021
12b1640
cargo run --release --features=runtime-benchmarks --manifest-path=bin…
Feb 12, 2021
6397d4a
Add one last layer of feasibility check as well.
kianenigma Feb 12, 2021
80d3c31
Merge branch 'kiz-election-provider-2-two-phase-unsigned' of github.c…
kianenigma Feb 12, 2021
7d6f6ad
Last fixes to benchmarks
kianenigma Feb 12, 2021
2e28437
Some more docs.
kianenigma Feb 12, 2021
5fda744
cargo run --release --features=runtime-benchmarks --manifest-path=bin…
Feb 12, 2021
1ce6c8e
cargo run --release --features=runtime-benchmarks --manifest-path=bin…
Feb 12, 2021
f63c5b8
Some nits
kianenigma Feb 12, 2021
8029c01
Merge branch 'kiz-election-provider-2-two-phase-unsigned' of github.c…
kianenigma Feb 12, 2021
5973b61
It all works
kianenigma Feb 13, 2021
0882c62
Master.into()
kianenigma Mar 8, 2021
e137035
Some self cleanup
kianenigma Mar 9, 2021
428c4c9
Master.into()
kianenigma Mar 12, 2021
a16b964
Update frame/staking/src/lib.rs
kianenigma Mar 12, 2021
6d506a4
remove most todos.
kianenigma Mar 12, 2021
75accd3
Merge branch 'kiz-election-provider-21-enable-multi-phase' of github.…
kianenigma Mar 12, 2021
df3fb9a
Round of self-review.
kianenigma Mar 12, 2021
e76af15
Merge branch 'master' of github.com:paritytech/substrate into kiz-ele…
kianenigma Mar 12, 2021
530ab32
Fix migration
kianenigma Mar 13, 2021
9a61b20
Merge branch 'master' of github.com:paritytech/substrate into kiz-ele…
kianenigma Mar 14, 2021
c92be7e
clean macro
kianenigma Mar 14, 2021
794f0ed
Master.into()
kianenigma Mar 16, 2021
789b35c
Revert wrong merge
kianenigma Mar 16, 2021
cfcdb54
Make the number of nominations configurable
kianenigma Mar 16, 2021
6ecafa2
Master.into()
kianenigma Mar 23, 2021
2004acb
Merge branch 'master' of github.com:paritytech/substrate into kiz-ele…
kianenigma Mar 24, 2021
0b1cb15
Self reivew
kianenigma Mar 24, 2021
07e7285
renmae.
kianenigma Mar 24, 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
Next Next commit
Base features and traits.
  • Loading branch information
kianenigma committed Jan 15, 2021
commit d998b12e7f8edeccb8cf64c84f4c0474a6b2ea61
11 changes: 11 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ members = [
"primitives/database",
"primitives/debug-derive",
"primitives/externalities",
"primitives/election-providers",
"primitives/finality-grandpa",
"primitives/inherents",
"primitives/io",
Expand Down
33 changes: 33 additions & 0 deletions primitives/election-providers/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
[package]
name = "sp-election-providers"
version = "2.0.0"
authors = ["Parity Technologies <[email protected]>"]
edition = "2018"
license = "Apache-2.0"
homepage = "https://substrate.dev"
repository = "https://github.com/paritytech/substrate/"
description = "Primitive election providers"
readme = "README.md"

[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]

[dependencies]
codec = { package = "parity-scale-codec", version = "1.3.4", default-features = false, features = ["derive"] }
sp-std = { version = "2.0.0-rc6", default-features = false, path = "../std" }
sp-arithmetic = { version = "2.0.0-rc6", default-features = false, path = "../arithmetic" }
sp-npos-elections = { version = "2.0.0-rc6", default-features = false, path = "../npos-elections" }

[dev-dependencies]
sp-npos-elections = { version = "2.0.0-rc6", path = "../npos-elections" }
sp-runtime = { version = "2.0.0-rc6", path = "../runtime" }

[features]
default = ["std"]
runtime-benchmarks = []
std = [
"codec/std",
"sp-std/std",
"sp-npos-elections/std",
"sp-arithmetic/std",
]
239 changes: 239 additions & 0 deletions primitives/election-providers/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
// 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.

//! Primitive traits for providing election functionality.
//!
//! This crate provides two traits that could interact to enable extensible election functionality
//! within FRAME pallets.
//!
//! Something that will provide the functionality of election will implement [`ElectionProvider`],
//! whilst needing an associated [`ElectionProvider::DataProvider`], which needs to be fulfilled by
//! an entity implementing [`ElectionDataProvider`]. Most often, *the data provider is* the receiver
//! of the election, resulting in a diagram as below:
//!
//! ```ignore
//! ElectionDataProvider
//! <------------------------------------------+
//! | |
//! v |
//! +-----+----+ +------+---+
//! | | | |
//! pallet-do-election | | | | pallet-needs-election
//! | | | |
//! | | | |
//! +-----+----+ +------+---+
//! | ^
//! | |
//! +------------------------------------------+
//! ElectionProvider
//! ```
//!
//! > It could also be possible that a third party pallet (C), provides the data of election to an
//! > election provider (B), which then passes the election result to another pallet (A).
//!
//! ## Election Types
//!
//! Typically, two types of elections exist:
//!
//! 1. **Stateless**: Election data is provided, and the election result is immediately ready.
//! 2. **Stateful**: Election data is is queried ahead of time, and the election result might be
//! ready some number of blocks in the future.
//!
//! To accommodate both type of elections in one trait, the traits lean toward **stateful
//! election**, as it is more general than the stateless. This is why [`ElectionProvider::elect`]
//! has no parameters. All value and type parameter must be provided by the [`ElectionDataProvider`]
//! trait, even if the election happens immediately.
//!
//! ## Election Data
//!
//! The data associated with an election, essentially what the [`ElectionDataProvider`] must convey
//! is as follows:
//!
//! 1. A list of voters, with their stake.
//! 2. A list of targets (i.e. _candidates_).
//! 3. A number of desired targets to be elected (i.e. _winners_)
//!
//! In addition to that, the [`ElectionDataProvider`] must also hint [`ElectionProvider`] at when
//! the next election might happen ([`ElectionDataProvider::next_election_prediction`]). A stateless
//! election provider would probably ignore this. A stateful election provider can use this to
//! prepare the election result in advance.
//!
//! Nonetheless, an [`ElectionProvider`] shan't rely on this and should preferably provide some
//! means of fallback election as well, in case the `elect` was called immaturely early.
//!
//! ## Example
//!
//! ```rust
//! # use sp_election_providers::*;
//! # use sp_npos_elections::{Support, Assignment};
//!
//! type AccountId = u64;
//! type Balance = u64;
//! type BlockNumber = u32;
//!
//! mod data_provider {
//! use super::*;
//!
//! pub trait Config: Sized {
//! type ElectionProvider: ElectionProvider<
//! AccountId,
//! BlockNumber,
//! DataProvider = Module<Self>,
//! >;
//! }
//!
//! pub struct Module<T: Config>(std::marker::PhantomData<T>);
//!
//! impl<T: Config> ElectionDataProvider<AccountId, BlockNumber> for Module<T> {
//! fn desired_targets() -> u32 {
//! 1
//! }
//! fn voters() -> Vec<(AccountId, VoteWeight, Vec<AccountId>)> {
//! Default::default()
//! }
//! fn targets() -> Vec<AccountId> {
//! vec![10, 20, 30]
//! }
//! fn next_election_prediction(now: BlockNumber) -> BlockNumber {
//! 0
//! }
//! }
//! }
//!
//!
//! mod generic_election_provider {
//! use super::*;
//!
//! pub struct GenericElectionProvider<T: Config>(std::marker::PhantomData<T>);
//!
//! pub trait Config {
//! type DataProvider: ElectionDataProvider<AccountId, BlockNumber>;
//! }
//!
//! impl<T: Config> ElectionProvider<AccountId, BlockNumber> for GenericElectionProvider<T> {
//! type Error = ();
//! type DataProvider = T::DataProvider;
//!
//! fn elect() -> Result<Supports<AccountId>, Self::Error> {
//! Self::DataProvider::targets()
//! .first()
//! .map(|winner| vec![(*winner, Support::default())])
//! .ok_or(())
//! }
//! }
//! }
//!
//! mod runtime {
//! use super::generic_election_provider;
//! use super::data_provider;
//! use super::AccountId;
//!
//! struct Runtime;
//! impl generic_election_provider::Config for Runtime {
//! type DataProvider = data_provider::Module<Runtime>;
//! }
//!
//! impl data_provider::Config for Runtime {
//! type ElectionProvider = generic_election_provider::GenericElectionProvider<Runtime>;
//! }
//!
//! }
//!
//! # fn main() {}
//! ```

#![cfg_attr(not(feature = "std"), no_std)]

pub mod onchain;
use sp_std::prelude::*;

/// Re-export some type as they are used in the interface.
pub use sp_arithmetic::PerThing;
pub use sp_npos_elections::{Assignment, ExtendedBalance, PerThing128, Supports, VoteWeight};

/// Something that can provide the data to an [`ElectionProvider`].
pub trait ElectionDataProvider<AccountId, BlockNumber> {
/// All possible targets for the election, i.e. the candidates.
fn targets() -> Vec<AccountId>;

/// All possible voters for the election.
///
/// Note that if a notion of self-vote exists, it should be represented here.
fn voters() -> Vec<(AccountId, VoteWeight, Vec<AccountId>)>;

/// The number of targets to elect.
fn desired_targets() -> u32;

/// Provide a best effort prediction about when the next election is about to happen.
///
/// In essence, the implementor should predict with this function when it will trigger the
/// [`ElectionProvider::elect`].
///
/// This is only useful for stateful election providers.
fn next_election_prediction(now: BlockNumber) -> BlockNumber;

/// Utility function only to be used in benchmarking scenarios, to be implemented optionally,
/// else a noop.
#[cfg(any(feature = "runtime-benchmarks", test))]
fn put_snapshot(
_voters: Vec<(AccountId, VoteWeight, Vec<AccountId>)>,
_targets: Vec<AccountId>,
) {
}
}

impl<AccountId, BlockNumber> ElectionDataProvider<AccountId, BlockNumber> for () {
fn targets() -> Vec<AccountId> {
Default::default()
}
fn voters() -> Vec<(AccountId, VoteWeight, Vec<AccountId>)> {
Default::default()
}
fn desired_targets() -> u32 {
Default::default()
}
fn next_election_prediction(now: BlockNumber) -> BlockNumber {
now
}
}

/// Something that can compute the result of an election and pass it back to the caller.
///
/// This trait only provides an interface to _request_ an election, i.e.
/// [`ElectionProvider::elect`]. That data required for the election need to be passed to the
/// implemented of this trait through [`ElectionProvider::DataProvider`].
pub trait ElectionProvider<AccountId, BlockNumber> {
/// The error type that is returned by the provider.
type Error: sp_std::fmt::Debug;

/// The data provider of the election.
type DataProvider: ElectionDataProvider<AccountId, BlockNumber>;

/// Elect a new set of winners.
///
/// The result is returned in a target major format, namely as vector of supports.
fn elect() -> Result<Supports<AccountId>, Self::Error>;
}

impl<AccountId, BlockNumber> ElectionProvider<AccountId, BlockNumber> for () {
type Error = &'static str;
type DataProvider = ();

fn elect() -> Result<Supports<AccountId>, Self::Error> {
Err("<() as ElectionProvider> cannot do anything.")
}
}
Loading