Skip to content

Commit

Permalink
Ranked Collective pallet (paritytech#11548)
Browse files Browse the repository at this point in the history
* Ranked Collective pallet

* Fixes

* benchmarks

* Weights

* Allow class voting in rank
Use bare ayes for calculating support.
Allow only promotion/demotion by one rank only.
Allow removal of member with rank zero only.
Use new Tally API

* Index by rank, still O(1).

* Custom vote weights

* Formatting

* Update frame/ranked-collective/src/lib.rs

* Broken :(

* origin guard; cleanup uses new API

* Formatting

* Promote/demote by rank

* Formatting

* Use new API

* Remove code in another PR

* Remove code in another PR

* Formatting

* Remove code in another PR

* Docs

* Docs

* Bump

* Fixes

* Formatting

* Fixes
  • Loading branch information
gavofyork authored Jun 1, 2022
1 parent 438f40d commit 4aec7b4
Show file tree
Hide file tree
Showing 22 changed files with 1,641 additions and 17 deletions.
18 changes: 18 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 @@ -115,6 +115,7 @@ members = [
"frame/nomination-pools",
"frame/nomination-pools/benchmarking",
"frame/randomness-collective-flip",
"frame/ranked-collective",
"frame/recovery",
"frame/referenda",
"frame/remark",
Expand Down
4 changes: 4 additions & 0 deletions bin/node/runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ pallet-offences-benchmarking = { version = "4.0.0-dev", path = "../../../frame/o
pallet-preimage = { version = "4.0.0-dev", default-features = false, path = "../../../frame/preimage" }
pallet-proxy = { version = "4.0.0-dev", default-features = false, path = "../../../frame/proxy" }
pallet-randomness-collective-flip = { version = "4.0.0-dev", default-features = false, path = "../../../frame/randomness-collective-flip" }
pallet-ranked-collective = { version = "4.0.0-dev", default-features = false, path = "../../../frame/ranked-collective" }
pallet-recovery = { version = "4.0.0-dev", default-features = false, path = "../../../frame/recovery" }
pallet-referenda = { version = "4.0.0-dev", default-features = false, path = "../../../frame/referenda" }
pallet-remark = { version = "4.0.0-dev", default-features = false, path = "../../../frame/remark" }
Expand Down Expand Up @@ -176,6 +177,7 @@ std = [
"pallet-utility/std",
"sp-version/std",
"pallet-society/std",
"pallet-ranked-collective/std",
"pallet-referenda/std",
"pallet-remark/std",
"pallet-recovery/std",
Expand Down Expand Up @@ -218,6 +220,7 @@ runtime-benchmarks = [
"pallet-preimage/runtime-benchmarks",
"pallet-proxy/runtime-benchmarks",
"pallet-scheduler/runtime-benchmarks",
"pallet-ranked-collective/runtime-benchmarks",
"pallet-referenda/runtime-benchmarks",
"pallet-recovery/runtime-benchmarks",
"pallet-remark/runtime-benchmarks",
Expand Down Expand Up @@ -265,6 +268,7 @@ try-runtime = [
"pallet-offences/try-runtime",
"pallet-preimage/try-runtime",
"pallet-proxy/try-runtime",
"pallet-ranked-collective/try-runtime",
"pallet-randomness-collective-flip/try-runtime",
"pallet-recovery/try-runtime",
"pallet-referenda/try-runtime",
Expand Down
41 changes: 36 additions & 5 deletions bin/node/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
#![cfg_attr(not(feature = "std"), no_std)]
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
#![recursion_limit = "256"]
#![recursion_limit = "512"]

use codec::{Decode, Encode, MaxEncodedLen};
use frame_election_provider_support::{
Expand All @@ -43,7 +43,7 @@ use frame_support::{
};
use frame_system::{
limits::{BlockLength, BlockWeights},
EnsureRoot, EnsureSigned,
EnsureRoot, EnsureRootWithSuccess, EnsureSigned,
};
pub use node_primitives::{AccountId, Signature};
use node_primitives::{AccountIndex, Balance, BlockNumber, Hash, Index, Moment};
Expand Down Expand Up @@ -780,11 +780,11 @@ parameter_types! {

pub struct TracksInfo;
impl pallet_referenda::TracksInfo<Balance, BlockNumber> for TracksInfo {
type Id = u8;
type Id = u16;
type Origin = <Origin as frame_support::traits::OriginTrait>::PalletsOrigin;
fn tracks() -> &'static [(Self::Id, pallet_referenda::TrackInfo<Balance, BlockNumber>)] {
static DATA: [(u8, pallet_referenda::TrackInfo<Balance, BlockNumber>); 1] = [(
0u8,
static DATA: [(u16, pallet_referenda::TrackInfo<Balance, BlockNumber>); 1] = [(
0u16,
pallet_referenda::TrackInfo {
name: "root",
max_deciding: 1,
Expand Down Expand Up @@ -837,6 +837,34 @@ impl pallet_referenda::Config for Runtime {
type Tracks = TracksInfo;
}

impl pallet_referenda::Config<pallet_referenda::Instance2> for Runtime {
type WeightInfo = pallet_referenda::weights::SubstrateWeight<Self>;
type Call = Call;
type Event = Event;
type Scheduler = Scheduler;
type Currency = pallet_balances::Pallet<Self>;
type CancelOrigin = EnsureRoot<AccountId>;
type KillOrigin = EnsureRoot<AccountId>;
type Slash = ();
type Votes = pallet_ranked_collective::Votes;
type Tally = pallet_ranked_collective::TallyOf<Runtime>;
type SubmissionDeposit = SubmissionDeposit;
type MaxQueued = ConstU32<100>;
type UndecidingTimeout = UndecidingTimeout;
type AlarmInterval = AlarmInterval;
type Tracks = TracksInfo;
}

impl pallet_ranked_collective::Config for Runtime {
type WeightInfo = pallet_ranked_collective::weights::SubstrateWeight<Self>;
type Event = Event;
type PromoteOrigin = EnsureRootWithSuccess<AccountId, ConstU16<65535>>;
type DemoteOrigin = EnsureRootWithSuccess<AccountId, ConstU16<65535>>;
type Polls = RankedPolls;
type MinRankOfClass = traits::Identity;
type VoteWeight = pallet_ranked_collective::Geometric;
}

impl pallet_remark::Config for Runtime {
type WeightInfo = pallet_remark::weights::SubstrateWeight<Self>;
type Event = Event;
Expand Down Expand Up @@ -1534,6 +1562,8 @@ construct_runtime!(
ConvictionVoting: pallet_conviction_voting,
Whitelist: pallet_whitelist,
NominationPools: pallet_nomination_pools,
RankedPolls: pallet_referenda::<Instance2>,
RankedCollective: pallet_ranked_collective,
}
);

Expand Down Expand Up @@ -1622,6 +1652,7 @@ mod benches {
[pallet_offences, OffencesBench::<Runtime>]
[pallet_preimage, Preimage]
[pallet_proxy, Proxy]
[pallet_ranked_collective, RankedCollective]
[pallet_referenda, Referenda]
[pallet_recovery, Recovery]
[pallet_remark, Remark]
Expand Down
49 changes: 49 additions & 0 deletions frame/ranked-collective/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
[package]
name = "pallet-ranked-collective"
version = "4.0.0-dev"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2021"
license = "Apache-2.0"
homepage = "https://substrate.io"
repository = "https://github.com/paritytech/substrate/"
description = "Ranked collective system: Members of a set of account IDs can make their collective feelings known through dispatched calls from one of two specialized origins."
readme = "README.md"

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

[dependencies]
codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] }
log = { version = "0.4.16", default-features = false }
scale-info = { version = "2.0.1", default-features = false, features = ["derive"] }
frame-benchmarking = { version = "4.0.0-dev", default-features = false, optional = true, path = "../benchmarking" }
frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" }
frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" }
sp-arithmetic = { version = "5.0.0", default-features = false, path = "../../primitives/arithmetic" }
sp-core = { version = "6.0.0", default-features = false, path = "../../primitives/core" }
sp-io = { version = "6.0.0", default-features = false, path = "../../primitives/io" }
sp-runtime = { version = "6.0.0", default-features = false, path = "../../primitives/runtime" }
sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" }

[features]
default = ["std"]
std = [
"codec/std",
"frame-benchmarking/std",
"frame-support/std",
"frame-system/std",
"log/std",
"scale-info/std",
"sp-arithmetic/std",
"sp-core/std",
"sp-io/std",
"sp-runtime/std",
"sp-std/std",
]
runtime-benchmarks = [
"frame-benchmarking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
]
try-runtime = ["frame-support/try-runtime"]
22 changes: 22 additions & 0 deletions frame/ranked-collective/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Ranked collective system.

This is a membership pallet providing a `Tally` implementation ready for use with polling
systems such as the Referenda pallet. Members each have a rank, with zero being the lowest.
There is no complexity limitation on either the number of members at a rank or the number of
ranks in the system thus allowing potentially public membership. A member of at least a given
rank can be selected at random in O(1) time, allowing for various games to constructed using
this as a primitive. Members may only be promoted and demoted by one rank at a time, however
all operations (save one) are O(1) in complexity. The only operation which is not O(1) is the
`remove_member` since they must be removed from all ranks from the present down to zero.

Different ranks have different voting power, and are able to vote in different polls. In general
rank privileges are cumulative. Higher ranks are able to vote in any polls open to lower ranks.
Similarly, higher ranks always have at least as much voting power in any given poll as lower
ranks.

Two `Config` trait items control these "rank privileges": `MinRankOfClass` and `VoteWeight`.
The first controls which ranks are allowed to vote on a particular class of poll. The second
controls the weight of a vote given the voters rank compared to the minimum rank of the poll.

An origin control, `EnsureRank`, ensures that the origin is a member of the collective of at
least a particular rank.
155 changes: 155 additions & 0 deletions frame/ranked-collective/src/benchmarking.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
// This file is part of Substrate.

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

//! Staking pallet benchmarking.
use super::*;
#[allow(unused_imports)]
use crate::Pallet as RankedCollective;

use frame_benchmarking::{account, benchmarks_instance_pallet, whitelisted_caller};
use frame_support::{assert_ok, dispatch::UnfilteredDispatchable};
use frame_system::RawOrigin as SystemOrigin;

const SEED: u32 = 0;

fn assert_last_event<T: Config<I>, I: 'static>(generic_event: <T as Config<I>>::Event) {
frame_system::Pallet::<T>::assert_last_event(generic_event.into());
}

fn make_member<T: Config<I>, I: 'static>(rank: Rank) -> T::AccountId {
let who = account::<T::AccountId>("member", MemberCount::<T, I>::get(0), SEED);
assert_ok!(Pallet::<T, I>::add_member(T::PromoteOrigin::successful_origin(), who.clone()));
for _ in 0..rank {
assert_ok!(Pallet::<T, I>::promote_member(
T::PromoteOrigin::successful_origin(),
who.clone()
));
}
who
}

benchmarks_instance_pallet! {
add_member {
let who = account::<T::AccountId>("member", 0, SEED);
let origin = T::PromoteOrigin::successful_origin();
let call = Call::<T, I>::add_member { who: who.clone() };
}: { call.dispatch_bypass_filter(origin)? }
verify {
assert_eq!(MemberCount::<T, I>::get(0), 1);
assert_last_event::<T, I>(Event::MemberAdded { who }.into());
}

remove_member {
let r in 0 .. 10;
let rank = r as u16;
let first = make_member::<T, I>(rank);
let who = make_member::<T, I>(rank);
let last = make_member::<T, I>(rank);
let last_index = (0..=rank).map(|r| IdToIndex::<T, I>::get(r, &last).unwrap()).collect::<Vec<_>>();
let origin = T::DemoteOrigin::successful_origin();
let call = Call::<T, I>::remove_member { who: who.clone(), min_rank: rank };
}: { call.dispatch_bypass_filter(origin)? }
verify {
for r in 0..=rank {
assert_eq!(MemberCount::<T, I>::get(r), 2);
assert_ne!(last_index[r as usize], IdToIndex::<T, I>::get(r, &last).unwrap());
}
assert_last_event::<T, I>(Event::MemberRemoved { who, rank }.into());
}

promote_member {
let r in 0 .. 10;
let rank = r as u16;
let who = make_member::<T, I>(rank);
let origin = T::PromoteOrigin::successful_origin();
let call = Call::<T, I>::promote_member { who: who.clone() };
}: { call.dispatch_bypass_filter(origin)? }
verify {
assert_eq!(Members::<T, I>::get(&who).unwrap().rank, rank + 1);
assert_last_event::<T, I>(Event::RankChanged { who, rank: rank + 1 }.into());
}

demote_member {
let r in 0 .. 10;
let rank = r as u16;
let first = make_member::<T, I>(rank);
let who = make_member::<T, I>(rank);
let last = make_member::<T, I>(rank);
let last_index = IdToIndex::<T, I>::get(rank, &last).unwrap();
let origin = T::DemoteOrigin::successful_origin();
let call = Call::<T, I>::demote_member { who: who.clone() };
}: { call.dispatch_bypass_filter(origin)? }
verify {
assert_eq!(Members::<T, I>::get(&who).map(|x| x.rank), rank.checked_sub(1));
assert_eq!(MemberCount::<T, I>::get(rank), 2);
assert_ne!(last_index, IdToIndex::<T, I>::get(rank, &last).unwrap());
assert_last_event::<T, I>(match rank {
0 => Event::MemberRemoved { who, rank: 0 },
r => Event::RankChanged { who, rank: r - 1 },
}.into());
}

vote {
let caller: T::AccountId = whitelisted_caller();
assert_ok!(Pallet::<T, I>::add_member(T::PromoteOrigin::successful_origin(), caller.clone()));
// Create a poll
let class = T::Polls::classes().into_iter().next().unwrap();
let rank = T::MinRankOfClass::convert(class.clone());
for _ in 0..rank {
assert_ok!(Pallet::<T, I>::promote_member(
T::PromoteOrigin::successful_origin(),
caller.clone()
));
}

let poll = T::Polls::create_ongoing(class).expect("Must always be able to create a poll for rank 0");

// Vote once.
assert_ok!(Pallet::<T, I>::vote(SystemOrigin::Signed(caller.clone()).into(), poll, true));
}: _(SystemOrigin::Signed(caller.clone()), poll, false)
verify {
let tally = Tally::from_parts(0, 0, 1);
let ev = Event::Voted { who: caller, poll, vote: VoteRecord::Nay(1), tally };
assert_last_event::<T, I>(ev.into());
}

cleanup_poll {
let n in 1 .. 100;

// Create a poll
let class = T::Polls::classes().into_iter().next().unwrap();
let rank = T::MinRankOfClass::convert(class.clone());
let poll = T::Polls::create_ongoing(class).expect("Must always be able to create a poll");

// Vote in the poll by each of `n` members
for i in 0..n {
let who = make_member::<T, I>(rank);
assert_ok!(Pallet::<T, I>::vote(SystemOrigin::Signed(who).into(), poll, true));
}

// End the poll.
T::Polls::end_ongoing(poll, false).expect("Must always be able to end a poll");

assert_eq!(Voting::<T, I>::iter_prefix(poll).count(), n as usize);
}: _(SystemOrigin::Signed(whitelisted_caller()), poll, n)
verify {
assert_eq!(Voting::<T, I>::iter().count(), 0);
}

impl_benchmark_test_suite!(RankedCollective, crate::tests::new_test_ext(), crate::tests::Test);
}
Loading

0 comments on commit 4aec7b4

Please sign in to comment.