difftreelog
fix use root origin in benchmarks
in: master
1 file changed
pallets/scheduler-v2/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// This file is part of Substrate.1920// Copyright (C) 2020-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435//! Scheduler pallet benchmarking.3637use super::*;38use frame_benchmarking::{account, benchmarks};39use frame_support::{40 ensure,41 traits::{schedule::Priority, PreimageRecipient},42};43use frame_system::RawOrigin;44use sp_std::{prelude::*, vec};45use sp_io::hashing::blake2_256;4647use crate::{Pallet as Scheduler, ScheduledCall, EncodedCall};48use frame_system::Call as SystemCall;4950const SEED: u32 = 0;5152const BLOCK_NUMBER: u32 = 2;5354type SystemOrigin<T> = <T as frame_system::Config>::RuntimeOrigin;5556/// Add `n` items to the schedule.57///58/// For `resolved`:59/// - `60/// - `None`: aborted (hash without preimage)61/// - `Some(true)`: hash resolves into call if possible, plain call otherwise62/// - `Some(false)`: plain call63fn fill_schedule<T: Config>(when: T::BlockNumber, n: u32) -> Result<(), &'static str> {64 let t = DispatchTime::At(when);65 let origin: <T as Config>::PalletsOrigin = frame_system::RawOrigin::Root.into();66 for i in 0..n {67 let call = make_call::<T>(None);68 let period = Some(((i + 100).into(), 100));69 let name = u32_to_name(i);70 Scheduler::<T>::do_schedule_named(name, t, period, 0, origin.clone(), call)?;71 }72 ensure!(73 Agenda::<T>::get(when).agenda.len() == n as usize,74 "didn't fill schedule"75 );76 Ok(())77}7879fn u32_to_name(i: u32) -> TaskName {80 i.using_encoded(blake2_256)81}8283fn make_task<T: Config>(84 periodic: bool,85 named: bool,86 signed: bool,87 maybe_lookup_len: Option<u32>,88 priority: Priority,89) -> ScheduledOf<T> {90 let call = make_call::<T>(maybe_lookup_len);91 let maybe_periodic = match periodic {92 true => Some((100u32.into(), 100)),93 false => None,94 };95 let maybe_id = match named {96 true => Some(u32_to_name(0)),97 false => None,98 };99 let origin = make_origin::<T>(signed);100 Scheduled {101 maybe_id,102 priority,103 call,104 maybe_periodic,105 origin,106 _phantom: PhantomData,107 }108}109110fn bounded<T: Config>(len: u32) -> Option<ScheduledCall<T>> {111 let call = <<T as Config>::RuntimeCall>::from(SystemCall::remark {112 remark: vec![0; len as usize],113 });114 ScheduledCall::new(call).ok()115}116117fn make_call<T: Config>(maybe_lookup_len: Option<u32>) -> ScheduledCall<T> {118 let bound = EncodedCall::bound() as u32;119 let mut len = match maybe_lookup_len {120 Some(len) => {121 len.min(<T::Preimages as PreimageRecipient<T::Hash>>::MaxSize::get() - 2)122 .max(bound) - 3123 }124 None => bound.saturating_sub(4),125 };126127 loop {128 let c = match bounded::<T>(len) {129 Some(x) => x,130 None => {131 len -= 1;132 continue;133 }134 };135 if c.lookup_needed() == maybe_lookup_len.is_some() {136 break c;137 }138 if maybe_lookup_len.is_some() {139 len += 1;140 } else {141 if len > 0 {142 len -= 1;143 } else {144 break c;145 }146 }147 }148}149150fn make_origin<T: Config>(signed: bool) -> <T as Config>::PalletsOrigin {151 match signed {152 true => frame_system::RawOrigin::Signed(account("origin", 0, SEED)).into(),153 false => frame_system::RawOrigin::Root.into(),154 }155}156157fn dummy_counter() -> WeightCounter {158 WeightCounter {159 used: Weight::zero(),160 limit: Weight::MAX,161 }162}163164benchmarks! {165 // `service_agendas` when no work is done.166 service_agendas_base {167 let now = T::BlockNumber::from(BLOCK_NUMBER);168 IncompleteSince::<T>::put(now - One::one());169 }: {170 Scheduler::<T>::service_agendas(&mut dummy_counter(), now, 0);171 } verify {172 assert_eq!(IncompleteSince::<T>::get(), Some(now - One::one()));173 }174175 // `service_agenda` when no work is done.176 service_agenda_base {177 let now = BLOCK_NUMBER.into();178 let s in 0 .. T::MaxScheduledPerBlock::get();179 fill_schedule::<T>(now, s)?;180 let mut executed = 0;181 }: {182 Scheduler::<T>::service_agenda(&mut dummy_counter(), &mut executed, now, now, 0);183 } verify {184 assert_eq!(executed, 0);185 }186187 // `service_task` when the task is a non-periodic, non-named, non-fetched call which is not188 // dispatched (e.g. due to being overweight).189 service_task_base {190 let now = BLOCK_NUMBER.into();191 let task = make_task::<T>(false, false, false, None, 0);192 // prevent any tasks from actually being executed as we only want the surrounding weight.193 let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };194 }: {195 let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);196 } verify {197 //assert_eq!(result, Ok(()));198 }199200 // TODO uncomment if we will use the Preimages201 // // `service_task` when the task is a non-periodic, non-named, fetched call (with a known202 // // preimage length) and which is not dispatched (e.g. due to being overweight).203 // service_task_fetched {204 // let s in (EncodedCall::bound() as u32) .. (<T::Preimages as PreimageRecipient<T::Hash>>::MaxSize::get());205 // let now = BLOCK_NUMBER.into();206 // let task = make_task::<T>(false, false, false, Some(s), 0);207 // // prevent any tasks from actually being executed as we only want the surrounding weight.208 // let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };209 // }: {210 // let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);211 // } verify {212 // }213214 // `service_task` when the task is a non-periodic, named, non-fetched call which is not215 // dispatched (e.g. due to being overweight).216 service_task_named {217 let now = BLOCK_NUMBER.into();218 let task = make_task::<T>(false, true, false, None, 0);219 // prevent any tasks from actually being executed as we only want the surrounding weight.220 let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };221 }: {222 let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);223 } verify {224 }225226 // `service_task` when the task is a periodic, non-named, non-fetched call which is not227 // dispatched (e.g. due to being overweight).228 service_task_periodic {229 let now = BLOCK_NUMBER.into();230 let task = make_task::<T>(true, false, false, None, 0);231 // prevent any tasks from actually being executed as we only want the surrounding weight.232 let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };233 }: {234 let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);235 } verify {236 }237238 // `execute_dispatch` when the origin is `Signed`, not counting the dispatable's weight.239 execute_dispatch_signed {240 let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::MAX };241 let origin = make_origin::<T>(true);242 let call = T::Preimages::realize(&make_call::<T>(None)).unwrap().0;243 }: {244 assert!(Scheduler::<T>::execute_dispatch(&mut counter, origin, call).is_ok());245 }246 verify {247 }248249 // `execute_dispatch` when the origin is not `Signed`, not counting the dispatable's weight.250 execute_dispatch_unsigned {251 let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::MAX };252 let origin = make_origin::<T>(false);253 let call = T::Preimages::realize(&make_call::<T>(None)).unwrap().0;254 }: {255 assert!(Scheduler::<T>::execute_dispatch(&mut counter, origin, call).is_ok());256 }257 verify {258 }259260 schedule {261 let s in 0 .. (T::MaxScheduledPerBlock::get() - 1);262 let when = BLOCK_NUMBER.into();263 let periodic = Some((T::BlockNumber::one(), 100));264 let priority = Some(0);265 // Essentially a no-op call.266 let call = Box::new(SystemCall::set_storage { items: vec![] }.into());267268 fill_schedule::<T>(when, s)?;269 }: _(RawOrigin::Root, when, periodic, priority, call)270 verify {271 ensure!(272 Agenda::<T>::get(when).agenda.len() == (s + 1) as usize,273 "didn't add to schedule"274 );275 }276277 cancel {278 let s in 1 .. T::MaxScheduledPerBlock::get();279 let when = BLOCK_NUMBER.into();280281 fill_schedule::<T>(when, s)?;282 assert_eq!(Agenda::<T>::get(when).agenda.len(), s as usize);283 let schedule_origin = T::ScheduleOrigin::successful_origin();284 }: _<SystemOrigin<T>>(schedule_origin, when, 0)285 verify {286 ensure!(287 Lookup::<T>::get(u32_to_name(0)).is_none(),288 "didn't remove from lookup"289 );290 // Removed schedule is NONE291 ensure!(292 Agenda::<T>::get(when).agenda[0].is_none(),293 "didn't remove from schedule"294 );295 }296297 schedule_named {298 let s in 0 .. (T::MaxScheduledPerBlock::get() - 1);299 let id = u32_to_name(s);300 let when = BLOCK_NUMBER.into();301 let periodic = Some((T::BlockNumber::one(), 100));302 let priority = Some(0);303 // Essentially a no-op call.304 let call = Box::new(SystemCall::set_storage { items: vec![] }.into());305306 fill_schedule::<T>(when, s)?;307 }: _(RawOrigin::Root, id, when, periodic, priority, call)308 verify {309 ensure!(310 Agenda::<T>::get(when).agenda.len() == (s + 1) as usize,311 "didn't add to schedule"312 );313 }314315 cancel_named {316 let s in 1 .. T::MaxScheduledPerBlock::get();317 let when = BLOCK_NUMBER.into();318319 fill_schedule::<T>(when, s)?;320 }: _(RawOrigin::Root, u32_to_name(0))321 verify {322 ensure!(323 Lookup::<T>::get(u32_to_name(0)).is_none(),324 "didn't remove from lookup"325 );326 // Removed schedule is NONE327 ensure!(328 Agenda::<T>::get(when).agenda[0].is_none(),329 "didn't remove from schedule"330 );331 }332333 change_named_priority {334 let origin: RawOrigin<T::AccountId> = frame_system::RawOrigin::Root;335 let s in 1 .. T::MaxScheduledPerBlock::get();336 let when = BLOCK_NUMBER.into();337 let idx = s - 1;338 let id = u32_to_name(idx);339 let priority = 42;340 fill_schedule::<T>(when, s)?;341 }: _(origin, id, priority)342 verify {343 ensure!(344 Agenda::<T>::get(when).agenda[idx as usize].clone().unwrap().priority == priority,345 "didn't change the priority"346 );347 }348349 impl_benchmark_test_suite!(Scheduler, crate::mock::new_test_ext(), crate::mock::Test);350}1// 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// This file is part of Substrate.1920// Copyright (C) 2020-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435//! Scheduler pallet benchmarking.3637use super::*;38use frame_benchmarking::{account, benchmarks};39use frame_support::{40 ensure,41 traits::{schedule::Priority, PreimageRecipient},42};43use frame_system::RawOrigin;44use sp_std::{prelude::*, vec};45use sp_io::hashing::blake2_256;4647use crate::{Pallet as Scheduler, ScheduledCall, EncodedCall};48use frame_system::Call as SystemCall;4950const SEED: u32 = 0;5152const BLOCK_NUMBER: u32 = 2;5354/// Add `n` items to the schedule.55///56/// For `resolved`:57/// - `58/// - `None`: aborted (hash without preimage)59/// - `Some(true)`: hash resolves into call if possible, plain call otherwise60/// - `Some(false)`: plain call61fn fill_schedule<T: Config>(when: T::BlockNumber, n: u32) -> Result<(), &'static str> {62 let t = DispatchTime::At(when);63 let origin: <T as Config>::PalletsOrigin = frame_system::RawOrigin::Root.into();64 for i in 0..n {65 let call = make_call::<T>(None);66 let period = Some(((i + 100).into(), 100));67 let name = u32_to_name(i);68 Scheduler::<T>::do_schedule_named(name, t, period, 0, origin.clone(), call)?;69 }70 ensure!(71 Agenda::<T>::get(when).agenda.len() == n as usize,72 "didn't fill schedule"73 );74 Ok(())75}7677fn u32_to_name(i: u32) -> TaskName {78 i.using_encoded(blake2_256)79}8081fn make_task<T: Config>(82 periodic: bool,83 named: bool,84 signed: bool,85 maybe_lookup_len: Option<u32>,86 priority: Priority,87) -> ScheduledOf<T> {88 let call = make_call::<T>(maybe_lookup_len);89 let maybe_periodic = match periodic {90 true => Some((100u32.into(), 100)),91 false => None,92 };93 let maybe_id = match named {94 true => Some(u32_to_name(0)),95 false => None,96 };97 let origin = make_origin::<T>(signed);98 Scheduled {99 maybe_id,100 priority,101 call,102 maybe_periodic,103 origin,104 _phantom: PhantomData,105 }106}107108fn bounded<T: Config>(len: u32) -> Option<ScheduledCall<T>> {109 let call = <<T as Config>::RuntimeCall>::from(SystemCall::remark {110 remark: vec![0; len as usize],111 });112 ScheduledCall::new(call).ok()113}114115fn make_call<T: Config>(maybe_lookup_len: Option<u32>) -> ScheduledCall<T> {116 let bound = EncodedCall::bound() as u32;117 let mut len = match maybe_lookup_len {118 Some(len) => {119 len.min(<T::Preimages as PreimageRecipient<T::Hash>>::MaxSize::get() - 2)120 .max(bound) - 3121 }122 None => bound.saturating_sub(4),123 };124125 loop {126 let c = match bounded::<T>(len) {127 Some(x) => x,128 None => {129 len -= 1;130 continue;131 }132 };133 if c.lookup_needed() == maybe_lookup_len.is_some() {134 break c;135 }136 if maybe_lookup_len.is_some() {137 len += 1;138 } else {139 if len > 0 {140 len -= 1;141 } else {142 break c;143 }144 }145 }146}147148fn make_origin<T: Config>(signed: bool) -> <T as Config>::PalletsOrigin {149 match signed {150 true => frame_system::RawOrigin::Signed(account("origin", 0, SEED)).into(),151 false => frame_system::RawOrigin::Root.into(),152 }153}154155fn dummy_counter() -> WeightCounter {156 WeightCounter {157 used: Weight::zero(),158 limit: Weight::MAX,159 }160}161162benchmarks! {163 // `service_agendas` when no work is done.164 service_agendas_base {165 let now = T::BlockNumber::from(BLOCK_NUMBER);166 IncompleteSince::<T>::put(now - One::one());167 }: {168 Scheduler::<T>::service_agendas(&mut dummy_counter(), now, 0);169 } verify {170 assert_eq!(IncompleteSince::<T>::get(), Some(now - One::one()));171 }172173 // `service_agenda` when no work is done.174 service_agenda_base {175 let now = BLOCK_NUMBER.into();176 let s in 0 .. T::MaxScheduledPerBlock::get();177 fill_schedule::<T>(now, s)?;178 let mut executed = 0;179 }: {180 Scheduler::<T>::service_agenda(&mut dummy_counter(), &mut executed, now, now, 0);181 } verify {182 assert_eq!(executed, 0);183 }184185 // `service_task` when the task is a non-periodic, non-named, non-fetched call which is not186 // dispatched (e.g. due to being overweight).187 service_task_base {188 let now = BLOCK_NUMBER.into();189 let task = make_task::<T>(false, false, false, None, 0);190 // prevent any tasks from actually being executed as we only want the surrounding weight.191 let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };192 }: {193 let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);194 } verify {195 //assert_eq!(result, Ok(()));196 }197198 // TODO uncomment if we will use the Preimages199 // // `service_task` when the task is a non-periodic, non-named, fetched call (with a known200 // // preimage length) and which is not dispatched (e.g. due to being overweight).201 // service_task_fetched {202 // let s in (EncodedCall::bound() as u32) .. (<T::Preimages as PreimageRecipient<T::Hash>>::MaxSize::get());203 // let now = BLOCK_NUMBER.into();204 // let task = make_task::<T>(false, false, false, Some(s), 0);205 // // prevent any tasks from actually being executed as we only want the surrounding weight.206 // let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };207 // }: {208 // let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);209 // } verify {210 // }211212 // `service_task` when the task is a non-periodic, named, non-fetched call which is not213 // dispatched (e.g. due to being overweight).214 service_task_named {215 let now = BLOCK_NUMBER.into();216 let task = make_task::<T>(false, true, false, None, 0);217 // prevent any tasks from actually being executed as we only want the surrounding weight.218 let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };219 }: {220 let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);221 } verify {222 }223224 // `service_task` when the task is a periodic, non-named, non-fetched call which is not225 // dispatched (e.g. due to being overweight).226 service_task_periodic {227 let now = BLOCK_NUMBER.into();228 let task = make_task::<T>(true, false, false, None, 0);229 // prevent any tasks from actually being executed as we only want the surrounding weight.230 let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };231 }: {232 let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);233 } verify {234 }235236 // `execute_dispatch` when the origin is `Signed`, not counting the dispatable's weight.237 execute_dispatch_signed {238 let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::MAX };239 let origin = make_origin::<T>(true);240 let call = T::Preimages::realize(&make_call::<T>(None)).unwrap().0;241 }: {242 assert!(Scheduler::<T>::execute_dispatch(&mut counter, origin, call).is_ok());243 }244 verify {245 }246247 // `execute_dispatch` when the origin is not `Signed`, not counting the dispatable's weight.248 execute_dispatch_unsigned {249 let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::MAX };250 let origin = make_origin::<T>(false);251 let call = T::Preimages::realize(&make_call::<T>(None)).unwrap().0;252 }: {253 assert!(Scheduler::<T>::execute_dispatch(&mut counter, origin, call).is_ok());254 }255 verify {256 }257258 schedule {259 let s in 0 .. (T::MaxScheduledPerBlock::get() - 1);260 let when = BLOCK_NUMBER.into();261 let periodic = Some((T::BlockNumber::one(), 100));262 let priority = Some(0);263 // Essentially a no-op call.264 let call = Box::new(SystemCall::set_storage { items: vec![] }.into());265266 fill_schedule::<T>(when, s)?;267 }: _(RawOrigin::Root, when, periodic, priority, call)268 verify {269 ensure!(270 Agenda::<T>::get(when).agenda.len() == (s + 1) as usize,271 "didn't add to schedule"272 );273 }274275 cancel {276 let s in 1 .. T::MaxScheduledPerBlock::get();277 let when = BLOCK_NUMBER.into();278279 fill_schedule::<T>(when, s)?;280 assert_eq!(Agenda::<T>::get(when).agenda.len(), s as usize);281 }: _(RawOrigin::Root, when, 0)282 verify {283 ensure!(284 Lookup::<T>::get(u32_to_name(0)).is_none(),285 "didn't remove from lookup"286 );287 // Removed schedule is NONE288 ensure!(289 Agenda::<T>::get(when).agenda[0].is_none(),290 "didn't remove from schedule"291 );292 }293294 schedule_named {295 let s in 0 .. (T::MaxScheduledPerBlock::get() - 1);296 let id = u32_to_name(s);297 let when = BLOCK_NUMBER.into();298 let periodic = Some((T::BlockNumber::one(), 100));299 let priority = Some(0);300 // Essentially a no-op call.301 let call = Box::new(SystemCall::set_storage { items: vec![] }.into());302303 fill_schedule::<T>(when, s)?;304 }: _(RawOrigin::Root, id, when, periodic, priority, call)305 verify {306 ensure!(307 Agenda::<T>::get(when).agenda.len() == (s + 1) as usize,308 "didn't add to schedule"309 );310 }311312 cancel_named {313 let s in 1 .. T::MaxScheduledPerBlock::get();314 let when = BLOCK_NUMBER.into();315316 fill_schedule::<T>(when, s)?;317 }: _(RawOrigin::Root, u32_to_name(0))318 verify {319 ensure!(320 Lookup::<T>::get(u32_to_name(0)).is_none(),321 "didn't remove from lookup"322 );323 // Removed schedule is NONE324 ensure!(325 Agenda::<T>::get(when).agenda[0].is_none(),326 "didn't remove from schedule"327 );328 }329330 change_named_priority {331 let origin: RawOrigin<T::AccountId> = frame_system::RawOrigin::Root;332 let s in 1 .. T::MaxScheduledPerBlock::get();333 let when = BLOCK_NUMBER.into();334 let idx = s - 1;335 let id = u32_to_name(idx);336 let priority = 42;337 fill_schedule::<T>(when, s)?;338 }: _(origin, id, priority)339 verify {340 ensure!(341 Agenda::<T>::get(when).agenda[idx as usize].clone().unwrap().priority == priority,342 "didn't change the priority"343 );344 }345346 impl_benchmark_test_suite!(Scheduler, crate::mock::new_test_ext(), crate::mock::Test);347}