difftreelog
cargo fmt
in: master
1 file changed
pallets/collator-selection/src/benchmarking.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license:18// Copyright (C) 2021 Parity Technologies (UK) Ltd.19// SPDX-License-Identifier: Apache-2.02021// Licensed under the Apache License, Version 2.0 (the "License");22// you may not use this file except in compliance with the License.23// You may obtain a copy of the License at24//25// http://www.apache.org/licenses/LICENSE-2.026//27// Unless required by applicable law or agreed to in writing, software28// distributed under the License is distributed on an "AS IS" BASIS,29// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.30// See the License for the specific language governing permissions and31// limitations under the License.3233//! Benchmarking setup for pallet-collator-selection3435use super::*;3637#[allow(unused)]38use crate::Pallet as CollatorSelection;39use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite, whitelisted_caller};40use frame_support::{41 assert_ok,42 codec::Decode,43 traits::{Currency, EnsureOrigin, Get},44};45use frame_system::{EventRecord, RawOrigin};46use pallet_authorship::EventHandler;47use pallet_session::{self as session, SessionManager};48use pallet_configuration::{49 self as configuration, BalanceOf,50 CollatorSelectionDesiredCollatorsOverride as DesiredCollators,51 CollatorSelectionLicenseBondOverride as LicenseBond,52};53use sp_std::prelude::*;5455const SEED: u32 = 0;5657// TODO: remove if this is given in substrate commit.58macro_rules! whitelist {59 ($acc:ident) => {60 frame_benchmarking::benchmarking::add_to_whitelist(61 frame_system::Account::<T>::hashed_key_for(&$acc).into(),62 );63 };64}6566fn assert_last_event<T: Config>(generic_event: <T as Config>::RuntimeEvent) {67 let events = frame_system::Pallet::<T>::events();68 let system_event: <T as frame_system::Config>::RuntimeEvent = generic_event.into();69 // compare to the last event record70 let EventRecord { event, .. } = &events[events.len() - 1];71 assert_eq!(event, &system_event);72}7374fn create_funded_user<T: Config>(75 string: &'static str,76 n: u32,77 balance_factor: u32,78) -> T::AccountId {79 let user = account(string, n, SEED);80 let balance = T::Currency::minimum_balance() * balance_factor.into();81 let _ = T::Currency::make_free_balance_be(&user, balance);82 user83}8485fn keys<T: Config + session::Config>(c: u32) -> <T as session::Config>::Keys {86 use rand::{RngCore, SeedableRng};8788 let keys = {89 let mut keys = [0u8; 128];9091 if c > 0 {92 let mut rng = rand::rngs::StdRng::seed_from_u64(c as u64);93 rng.fill_bytes(&mut keys);94 }9596 keys97 };9899 Decode::decode(&mut &keys[..]).unwrap()100}101102fn validator<T: Config + session::Config>(c: u32) -> (T::AccountId, <T as session::Config>::Keys) {103 (create_funded_user::<T>("candidate", c, 1000), keys::<T>(c))104}105106fn register_validators<T: Config + session::Config>(count: u32) -> Vec<T::AccountId> {107 let validators = (0..count).map(|c| validator::<T>(c)).collect::<Vec<_>>();108109 for (who, keys) in validators.clone() {110 <session::Pallet<T>>::set_keys(RawOrigin::Signed(who).into(), keys, Vec::new()).unwrap();111 }112113 validators.into_iter().map(|(who, _)| who).collect()114}115116fn register_invulnerables<T: Config + configuration::Config>(count: u32) {117 let candidates = (0..count)118 .map(|c| account("candidate", c, SEED))119 .collect::<Vec<_>>();120121 for who in candidates {122 <CollatorSelection<T>>::add_invulnerable(T::UpdateOrigin::successful_origin(), who).unwrap();123 }124}125126fn register_candidates<T: Config + configuration::Config>(count: u32) {127 let candidates = (0..count)128 .map(|c| account("candidate", c, SEED))129 .collect::<Vec<_>>();130 /*assert!(131 <LicenseBond<T>>::get() > 0u32.into(),132 "Bond cannot be zero!"133 );*/134135 for who in candidates {136 T::Currency::make_free_balance_be(&who, <LicenseBond<T>>::get() * 2u32.into());137 <CollatorSelection<T>>::get_license(RawOrigin::Signed(who.clone()).into()).unwrap();138 <CollatorSelection<T>>::onboard(RawOrigin::Signed(who).into()).unwrap();139 }140}141142fn get_licenses<T: Config + configuration::Config>(count: u32) {143 let candidates = (0..count)144 .map(|c| account("candidate", c, SEED))145 .collect::<Vec<_>>();146 /*assert!(147 <LicenseBond<T>>::get() > 0u32.into(),148 "Bond cannot be zero!"149 );*/150151 for who in candidates {152 T::Currency::make_free_balance_be(&who, <LicenseBond<T>>::get() * 2u32.into());153 <CollatorSelection<T>>::get_license(RawOrigin::Signed(who.clone()).into()).unwrap();154 }155}156157benchmarks! {158 where_clause { where T: pallet_authorship::Config + session::Config + configuration::Config }159160 add_invulnerable {161 let b in 1 .. T::MaxCollators::get() - 3;162 register_validators::<T>(b);163 register_invulnerables::<T>(b);164165 // log::info!("{} {}", <Invulnerables<T>>::get().len(), b);166167 let new_invulnerable: T::AccountId = whitelisted_caller();168 let bond: BalanceOf<T> = T::Currency::minimum_balance() * 2u32.into();169 T::Currency::make_free_balance_be(&new_invulnerable, bond.clone());170171 <session::Pallet<T>>::set_keys(172 RawOrigin::Signed(new_invulnerable.clone()).into(),173 keys::<T>(b + 1),174 Vec::new()175 ).unwrap();176177 let root_origin = T::UpdateOrigin::successful_origin();178 }: {179 assert_ok!(180 <CollatorSelection<T>>::add_invulnerable(root_origin, new_invulnerable.clone())181 );182 }183 verify {184 assert_last_event::<T>(Event::InvulnerableAdded{invulnerable: new_invulnerable}.into());185 }186187 remove_invulnerable {188 let b in 1 .. T::MaxCollators::get();189 register_validators::<T>(b);190 register_invulnerables::<T>(b);191192 let root_origin = T::UpdateOrigin::successful_origin();193 let leaving = <Invulnerables<T>>::get().last().unwrap().clone();194 whitelist!(leaving);195 }: {196 assert_ok!(197 <CollatorSelection<T>>::remove_invulnerable(root_origin, leaving.clone())198 );199 }200 verify {201 assert_last_event::<T>(Event::InvulnerableRemoved{invulnerable: leaving}.into());202 }203204 get_license {205 let c in 1 .. T::MaxCollators::get();206207 <LicenseBond<T>>::put(T::Currency::minimum_balance());208209 register_validators::<T>(c);210 get_licenses::<T>(c);211212 let caller: T::AccountId = whitelisted_caller();213 let bond: BalanceOf<T> = T::Currency::minimum_balance() * 2u32.into();214 T::Currency::make_free_balance_be(&caller, bond.clone());215216 <session::Pallet<T>>::set_keys(217 RawOrigin::Signed(caller.clone()).into(),218 keys::<T>(c + 1),219 Vec::new()220 ).unwrap();221222 }: _(RawOrigin::Signed(caller.clone()))223 verify {224 assert_last_event::<T>(Event::LicenseObtained{account_id: caller, deposit: bond / 2u32.into()}.into());225 }226227 // worst case is when we have all the max-candidate slots filled except one, and we fill that228 // one.229 onboard {230 let c in 1 .. 5;231232 <LicenseBond<T>>::put(T::Currency::minimum_balance());233 <DesiredCollators<T>>::put(c + 2);234235 register_validators::<T>(c);236 register_candidates::<T>(c);237238 let caller: T::AccountId = whitelisted_caller();239 let bond: BalanceOf<T> = T::Currency::minimum_balance() * 2u32.into();240 T::Currency::make_free_balance_be(&caller, bond.clone());241242 let origin = RawOrigin::Signed(caller.clone());243244 <session::Pallet<T>>::set_keys(245 origin.clone().into(),246 keys::<T>(c + 1),247 Vec::new()248 ).unwrap();249250 assert_ok!(251 <CollatorSelection<T>>::get_license(origin.clone().into())252 );253 }: _(origin)254 verify {255 assert_last_event::<T>(Event::CandidateAdded{account_id: caller}.into());256 }257258 // worst case is the last candidate leaving.259 offboard {260 let c in 1 .. T::MaxCollators::get();261 <LicenseBond<T>>::put(T::Currency::minimum_balance());262 <DesiredCollators<T>>::put(c + 2);263264 register_validators::<T>(c);265 register_candidates::<T>(c);266267 let leaving = <Candidates<T>>::get().last().unwrap().clone();268 whitelist!(leaving);269 }: _(RawOrigin::Signed(leaving.clone()))270 verify {271 assert_last_event::<T>(Event::CandidateRemoved{account_id: leaving}.into());272 }273274 // worst case is the last candidate leaving.275 release_license {276 let c in 1 .. T::MaxCollators::get();277 let bond = T::Currency::minimum_balance();278 <LicenseBond<T>>::put(bond);279 <DesiredCollators<T>>::put(c);280281 register_validators::<T>(c);282 register_candidates::<T>(c);283284 let leaving = <Candidates<T>>::get().last().unwrap().clone();285 whitelist!(leaving);286 }: _(RawOrigin::Signed(leaving.clone()))287 verify {288 assert_last_event::<T>(Event::LicenseReleased{account_id: leaving, deposit_returned: bond}.into());289 }290291 // worst case is the last candidate leaving.292 force_release_license {293 let c in 1 .. T::MaxCollators::get();294 let bond = T::Currency::minimum_balance();295 <LicenseBond<T>>::put(bond);296 <DesiredCollators<T>>::put(c);297298 register_validators::<T>(c);299 register_candidates::<T>(c);300301 let leaving = <Candidates<T>>::get().last().unwrap().clone();302 whitelist!(leaving);303 let origin = T::UpdateOrigin::successful_origin();304 }: {305 assert_ok!(306 <CollatorSelection<T>>::force_release_license(origin, leaving.clone())307 );308 }309 verify {310 assert_last_event::<T>(Event::LicenseReleased{account_id: leaving, deposit_returned: bond}.into());311 }312313 // worst case is paying a non-existing candidate account.314 note_author {315 <LicenseBond<T>>::put(T::Currency::minimum_balance());316 T::Currency::make_free_balance_be(317 &<CollatorSelection<T>>::account_id(),318 T::Currency::minimum_balance() * 4u32.into(),319 );320 let author = account("author", 0, SEED);321 let new_block: T::BlockNumber = 10u32.into();322323 frame_system::Pallet::<T>::set_block_number(new_block);324 assert!(T::Currency::free_balance(&author) == 0u32.into());325 }: {326 <CollatorSelection<T> as EventHandler<_, _>>::note_author(author.clone())327 } verify {328 assert!(T::Currency::free_balance(&author) > 0u32.into());329 assert_eq!(frame_system::Pallet::<T>::block_number(), new_block);330 }331332 // worst case for new session.333 new_session {334 let r in 1 .. T::MaxCollators::get();335 let c in 1 .. T::MaxCollators::get();336337 <LicenseBond<T>>::put(T::Currency::minimum_balance());338 <DesiredCollators<T>>::put(c);339 frame_system::Pallet::<T>::set_block_number(0u32.into());340341 register_validators::<T>(c);342 register_candidates::<T>(c);343344 let new_block: T::BlockNumber = 1800u32.into();345 let zero_block: T::BlockNumber = 0u32.into();346 let candidates = <Candidates<T>>::get();347348 let non_removals = c.saturating_sub(r);349350 for i in 0..c {351 <LastAuthoredBlock<T>>::insert(candidates[i as usize].clone(), zero_block);352 }353354 if non_removals > 0 {355 for i in 0..non_removals {356 <LastAuthoredBlock<T>>::insert(candidates[i as usize].clone(), new_block);357 }358 } else {359 for i in 0..c {360 <LastAuthoredBlock<T>>::insert(candidates[i as usize].clone(), new_block);361 }362 }363364 let pre_length = <Candidates<T>>::get().len();365366 frame_system::Pallet::<T>::set_block_number(new_block);367368 assert!(<Candidates<T>>::get().len() == c as usize);369 }: {370 <CollatorSelection<T> as SessionManager<_>>::new_session(0)371 } verify {372 if c > r {373 assert!(<Candidates<T>>::get().len() < pre_length);374 } else {375 assert!(<Candidates<T>>::get().len() == pre_length);376 }377 }378}379380impl_benchmark_test_suite!(381 CollatorSelection,382 crate::mock::new_test_ext(),383 crate::mock::Test,384);