Skip to content

Commit

Permalink
implement democracy benchmarks (#348)
Browse files Browse the repository at this point in the history
Co-authored-by: brenzi <brenzi@users.noreply.github.com>
  • Loading branch information
pifragile and brenzi committed Sep 17, 2023
1 parent 94cbcca commit 1933ce2
Show file tree
Hide file tree
Showing 6 changed files with 222 additions and 5 deletions.
4 changes: 4 additions & 0 deletions democracy/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,7 @@ std = [
]

runtime-benchmarks = ["frame-benchmarking", "sp-application-crypto", "sp-core"]

try-runtime = [
"frame-system/try-runtime",
]
91 changes: 91 additions & 0 deletions democracy/src/benchmarking.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
use crate::{Pallet as EncointerDemocracy, *};
use codec::Encode;
use encointer_primitives::{
ceremonies::Reputation,
communities::CommunityIdentifier,
democracy::{ProposalState, Tally, Vote},
storage::{current_ceremony_index_key, global_reputation_count, participant_reputation},
};
use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite};
use frame_support::{assert_ok, traits::OnInitialize, BoundedVec};
use frame_system::RawOrigin;
#[cfg(not(feature = "std"))]
use sp_std::vec;

fn advance_n_blocks<T: Config>(n: u64) {
for _ in 0..n {
frame_system::Pallet::<T>::set_block_number(
frame_system::Pallet::<T>::block_number() + 1u32.into(),
);
frame_system::Pallet::<T>::on_initialize(frame_system::Pallet::<T>::block_number());
}
}

benchmarks! {

submit_proposal {
let zoran = account("zoran", 1, 1);
let proposal_action = ProposalAction::SetInactivityTimeout(8);
assert!(<Proposals<T>>::iter().next().is_none());
}: _(RawOrigin::Signed(zoran), proposal_action)
verify {
assert!(<Proposals<T>>::iter().next().is_some());
}

vote {
frame_support::storage::unhashed::put_raw(&current_ceremony_index_key(), &7u32.encode());

let zoran = account::<T::AccountId>("zoran", 1, 1);
let cid = CommunityIdentifier::default();

let proposal_action = ProposalAction::SetInactivityTimeout(8);
assert_ok!(EncointerDemocracy::<T>::submit_proposal(
RawOrigin::Signed(zoran.clone()).into(),
proposal_action
));

frame_support::storage::unhashed::put_raw(&participant_reputation((cid, 3), &zoran), &Reputation::VerifiedUnlinked.encode());
frame_support::storage::unhashed::put_raw(&participant_reputation((cid, 4), &zoran), &Reputation::VerifiedUnlinked.encode());
frame_support::storage::unhashed::put_raw(&participant_reputation((cid, 5), &zoran), &Reputation::VerifiedUnlinked.encode());
let reputation_vec: ReputationVecOf<T> = BoundedVec::try_from(vec![
(cid, 3),
(cid, 4),
(cid, 5),
]).unwrap();

assert!(<VoteEntries<T>>::iter().next().is_none());
}: _(RawOrigin::Signed(zoran.clone()),
1,
Vote::Aye,
reputation_vec)
verify {
assert!(<VoteEntries<T>>::iter().next().is_some());
}

update_proposal_state {
frame_support::storage::unhashed::put_raw(&current_ceremony_index_key(), &7u32.encode());
let zoran = account::<T::AccountId>("zoran", 1, 1);
let cid = CommunityIdentifier::default();

let proposal_action = ProposalAction::SetInactivityTimeout(8);
assert_ok!(EncointerDemocracy::<T>::submit_proposal(
RawOrigin::Signed(zoran.clone()).into(),
proposal_action
));


Tallies::<T>::insert(1, Tally { turnout: 3, ayes: 3 });

frame_support::storage::unhashed::put_raw(&global_reputation_count(5), &3u128.encode());
assert_eq!(EncointerDemocracy::<T>::proposals(1).unwrap().state, ProposalState::Ongoing);
EncointerDemocracy::<T>::update_proposal_state(RawOrigin::Signed(zoran.clone()).into(), 1).ok();
assert!(<EnactmentQueue<T>>::iter().next().is_none());
advance_n_blocks::<T>(21);

}: _(RawOrigin::Signed(zoran), 1)
verify {
assert!(<EnactmentQueue<T>>::iter().next().is_some());
}
}

impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::TestRuntime);
17 changes: 13 additions & 4 deletions democracy/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,17 @@ use encointer_primitives::{
};
use encointer_scheduler::OnCeremonyPhaseChange;
use frame_support::traits::Get;
pub use weights::WeightInfo;

#[cfg(not(feature = "std"))]
use sp_std::vec::Vec;

// Logger target
//const LOG: &str = "encointer";

#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;

pub use pallet::*;

type ReputationVecOf<T> = ReputationVec<<T as pallet::Config>::MaxReputationVecLength>;
Expand Down Expand Up @@ -63,6 +71,7 @@ pub mod pallet {
type ProposalLifetimeCycles: Get<u32>; // ceil of the proposal lifetime in cycles
#[pallet::constant]
type MinTurnout: Get<u128>; // in permill
type WeightInfo: WeightInfo;
}

#[pallet::event]
Expand Down Expand Up @@ -145,7 +154,7 @@ pub mod pallet {
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight({10000})]
#[pallet::weight((<T as Config>::WeightInfo::submit_proposal(), DispatchClass::Normal, Pays::Yes))]
pub fn submit_proposal(
origin: OriginFor<T>,
proposal_action: ProposalAction,
Expand Down Expand Up @@ -173,7 +182,7 @@ pub mod pallet {
}

#[pallet::call_index(1)]
#[pallet::weight({10000})]
#[pallet::weight((<T as Config>::WeightInfo::vote(), DispatchClass::Normal, Pays::Yes))]
pub fn vote(
origin: OriginFor<T>,
proposal_id: ProposalIdType,
Expand Down Expand Up @@ -216,7 +225,7 @@ pub mod pallet {
}

#[pallet::call_index(2)]
#[pallet::weight({10000})]
#[pallet::weight((<T as Config>::WeightInfo::update_proposal_state(), DispatchClass::Normal, Pays::Yes))]
pub fn update_proposal_state(
origin: OriginFor<T>,
proposal_id: ProposalIdType,
Expand Down Expand Up @@ -445,11 +454,11 @@ impl<T: Config> OnCeremonyPhaseChange for Pallet<T> {
}
}

// mod weights;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
mod weights;
//
// #[cfg(feature = "runtime-benchmarks")]
// mod benchmarking;
1 change: 1 addition & 0 deletions democracy/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ impl dut::Config for TestRuntime {
type ProposalLifetime = ConstU64<40>;
type ProposalLifetimeCycles = ConstU32<1>;
type MinTurnout = ConstU128<20>; // 2%
type WeightInfo = (); // 2%
}

// boilerplate
Expand Down
94 changes: 94 additions & 0 deletions democracy/src/weights.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
Copyright 2022 Encointer
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.
*/

//! Autogenerated weights for pallet_encointer_democracy with reference hardware:
//! * 2.3 GHz 8-Core Intel Core i9
//! * 16 GB 2400 MHz DDR4
//! * SSD
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
//! DATE: 2023-09-13, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! EXECUTION: , WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024

// Executed Command:
// target/release/encointer-node-notee
// benchmark
// pallet
// --chain=dev
// --steps=50
// --repeat=20
// --pallet=pallet_encointer_democracy
// --extrinsic=*
// --wasm-execution=compiled
// --heap-pages=4096
// --output=runtime/src/weights/pallet_encointer_democracy.rs
// --template=/Users/pigu/Documents/code/encointer/encointer-node/scripts/frame-weight-template-full-info.hbs

#![allow(unused_parens)]
#![allow(unused_imports)]

use frame_support::{
traits::Get,
weights::{constants::RocksDbWeight, Weight},
};
use sp_std::marker::PhantomData;

/// Weight functions needed for pallet_encointer_democracy.
pub trait WeightInfo {
fn submit_proposal() -> Weight;
fn vote() -> Weight;
fn update_proposal_state() -> Weight;
}

/// Weights for pallet_encointer_democracy using the Encointer solo chain node and recommended hardware.
pub struct EncointerWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for EncointerWeight<T> {
fn submit_proposal() -> Weight {
Weight::from_parts(40_000_000, 0)
.saturating_add(T::DbWeight::get().reads(3))
.saturating_add(T::DbWeight::get().writes(3))
}
fn vote() -> Weight {
Weight::from_parts(168_000_000, 0)
.saturating_add(T::DbWeight::get().reads(16))
.saturating_add(T::DbWeight::get().writes(5))
}
fn update_proposal_state() -> Weight {
Weight::from_parts(116_000_000, 0)
.saturating_add(T::DbWeight::get().reads(9))
.saturating_add(T::DbWeight::get().writes(3))
}
}

// For tests
impl WeightInfo for () {
fn submit_proposal() -> Weight {
Weight::from_parts(40_000_000, 0)
.saturating_add(RocksDbWeight::get().reads(3))
.saturating_add(RocksDbWeight::get().writes(3))
}
fn vote() -> Weight {
Weight::from_parts(168_000_000, 0)
.saturating_add(RocksDbWeight::get().reads(16))
.saturating_add(RocksDbWeight::get().writes(5))
}
fn update_proposal_state() -> Weight {
Weight::from_parts(116_000_000, 0)
.saturating_add(RocksDbWeight::get().reads(9))
.saturating_add(RocksDbWeight::get().writes(3))
}
}
20 changes: 19 additions & 1 deletion primitives/src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

//! Helper functions to manipulate the storage, to get a specific state in the tests

use crate::ceremonies::CommunityCeremony;
use crate::{ceremonies::CommunityCeremony, scheduler::CeremonyIndexType};
use frame_support::pallet_prelude::Encode;
use sp_io::hashing::{blake2_128, twox_128};

Expand All @@ -40,6 +40,14 @@ pub fn participant_reputation<AccountId: Encode>(
storage_double_map_key("EncointerCeremonies", "ParticipantReputation", c, &account)
}

pub fn global_reputation_count(c: CeremonyIndexType) -> StorageKey {
storage_map_key("EncointerCeremonies", "GlobalReputationCount", c)
}

pub fn current_ceremony_index_key() -> StorageKey {
storage_key("EncointerScheduler", "CurrentCeremonyIndex")
}

pub fn storage_key(module: &str, storage_key_name: &str) -> StorageKey {
let mut key = twox_128(module.as_bytes()).to_vec();
key.extend(&twox_128(storage_key_name.as_bytes()));
Expand All @@ -63,6 +71,16 @@ where
bytes
}

pub fn storage_map_key<K>(module: &str, storage_key_name: &str, key1: K) -> StorageKey
where
K: Encode,
{
let mut bytes = twox_128(module.as_bytes()).to_vec();
bytes.extend(&twox_128(storage_key_name.as_bytes())[..]);
bytes.extend(key_hash(&key1));
bytes
}

pub fn key_hash<K: Encode>(key: &K) -> StorageKey {
let encoded_key = key.encode();
let x: &[u8] = encoded_key.as_slice();
Expand Down

0 comments on commit 1933ce2

Please sign in to comment.