referrerpolicy=no-referrer-when-downgrade

pallet_validator_collators/
benchmarking.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// SPDX-License-Identifier: Apache-2.0
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// 	http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Benchmarking setup for pallet-validator-collators.
17
18#![cfg(feature = "runtime-benchmarks")]
19
20use super::*;
21
22#[allow(unused)]
23use crate::Pallet as ValidatorCollators;
24use alloc::{collections::BTreeSet, vec::Vec};
25use cumulus_pallet_parachain_system::OnSystemEvent;
26use frame_benchmarking::{account, v2::*, BenchmarkError};
27use frame_support::{
28	traits::{EnsureOrigin, Get, Hooks},
29	weights::WeightMeter,
30	BoundedBTreeSet,
31};
32use frame_system::pallet_prelude::BlockNumberFor;
33use sp_runtime::traits::Saturating;
34
35#[benchmarks]
36mod benchmarks {
37	use super::*;
38
39	#[benchmark]
40	fn set_validators(n: Linear<1, { T::MaxValidators::get() }>) -> Result<(), BenchmarkError> {
41		let set = |name: &'static str, count: u32| {
42			BoundedBTreeSet::try_from(
43				(0..count).map(|i| account(name, i, 0)).collect::<BTreeSet<_>>(),
44			)
45			.map_err(|_| BenchmarkError::Stop("the set exceeds MaxValidators"))
46		};
47		Pallet::<T>::do_receive_validator_set(0, set("stored", T::MaxValidators::get())?)?;
48		let validators = set("validator", n)?;
49
50		#[block]
51		{
52			Pallet::<T>::do_receive_validator_set(1, validators)?;
53		}
54
55		assert_eq!(
56			ExternalValidatorSet::<T>::get().map(|set| (set.era, set.validators.len() as u32)),
57			Some((1, n))
58		);
59		assert_eq!(PendingRotation::<T>::get(), RotationState::AwaitingQueue);
60		Ok(())
61	}
62
63	/// Worst case: a change with a stored set, which forces the rotations.
64	#[benchmark]
65	fn set_max_collators() -> Result<(), BenchmarkError> {
66		let origin =
67			T::UpdateOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?;
68		let max = T::MaxValidators::get();
69		let stored = BoundedBTreeSet::try_from(
70			(0..max).map(|i| account("stored", i, 0)).collect::<BTreeSet<_>>(),
71		)
72		.map_err(|_| BenchmarkError::Stop("the set exceeds MaxValidators"))?;
73		Pallet::<T>::do_receive_validator_set(0, stored)?;
74
75		#[extrinsic_call]
76		_(origin as T::RuntimeOrigin, CollatorDraw::UpTo(max));
77
78		assert_eq!(MaxCollators::<T>::get(), CollatorDraw::UpTo(max));
79		assert_eq!(PendingRotation::<T>::get(), RotationState::AwaitingQueue);
80		Ok(())
81	}
82
83	/// The relay chain epoch randomness changes, so the cache is written.
84	#[benchmark]
85	fn on_relay_state_proof() {
86		EpochRandomness::<T>::put([1; 32]);
87		let proof = crate::relay_proof::with_epoch_randomness([2; 32]);
88
89		#[block]
90		{
91			<Pallet<T> as OnSystemEvent>::on_relay_state_proof(&proof);
92		}
93
94		assert_eq!(EpochRandomness::<T>::get(), Some([2; 32]));
95	}
96
97	#[benchmark]
98	fn set_report_period() -> Result<(), BenchmarkError> {
99		let origin =
100			T::UpdateOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?;
101		let period = T::DefaultReportPeriod::get().saturating_add(1u32.into());
102
103		#[extrinsic_call]
104		_(origin as T::RuntimeOrigin, period);
105
106		assert_eq!(ReportPeriod::<T>::get(), period);
107		Ok(())
108	}
109
110	#[benchmark]
111	fn set_expected_era_duration() -> Result<(), BenchmarkError> {
112		let origin =
113			T::UpdateOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?;
114		let duration = T::DefaultExpectedEraDuration::get().saturating_add(1);
115
116		#[extrinsic_call]
117		_(origin as T::RuntimeOrigin, duration);
118
119		assert_eq!(ExpectedEraDuration::<T>::get(), duration);
120		Ok(())
121	}
122
123	#[benchmark]
124	fn set_report_margin() -> Result<(), BenchmarkError> {
125		let origin =
126			T::UpdateOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?;
127		let margin = T::MaxReportMargin::get();
128
129		#[extrinsic_call]
130		_(origin as T::RuntimeOrigin, margin);
131
132		assert_eq!(ReportMargin::<T>::get(), margin);
133		Ok(())
134	}
135
136	/// The first block of an author, which inserts its entry and bumps the counter.
137	#[benchmark]
138	fn note_author() {
139		let author: T::AccountId = account("author", 0, 0);
140
141		#[block]
142		{
143			<Pallet<T> as pallet_authorship::EventHandler<_, _>>::note_author(author.clone());
144		}
145
146		assert_eq!(AuthoredBlocks::<T>::get(&author), 1);
147	}
148
149	/// A block at a multiple of `ReportPeriod` that makes the early report of the stored set with
150	/// no counts.
151	///
152	/// This is the weight of the checks only: the report itself is weighed by `report_blocks`.
153	#[benchmark]
154	fn on_poll() -> Result<(), BenchmarkError> {
155		let validators = BoundedBTreeSet::try_from(BTreeSet::from([account("validator", 0, 0)]))
156			.map_err(|_| BenchmarkError::Stop("the set exceeds MaxValidators"))?;
157		Pallet::<T>::do_receive_validator_set(0, validators)?;
158		// The early report is due at any time with a zero expected era duration.
159		ExpectedEraDuration::<T>::put(0);
160		let now = ReportPeriod::<T>::get();
161		// Events are recorded from block 1 on, so that the check below sees them.
162		frame_system::Pallet::<T>::set_block_number(now);
163		assert_eq!(AuthoredBlocks::<T>::count(), 0);
164		let events = frame_system::Pallet::<T>::events().len();
165
166		#[block]
167		{
168			<Pallet<T> as Hooks<BlockNumberFor<T>>>::on_poll(now, &mut WeightMeter::new());
169		}
170
171		assert_eq!(ExternalSetReceivedAt::<T>::get(), None);
172		// The reporter was not reached: every call to it ends in `BlocksReported` or
173		// `BlocksReportFailed`, and the poll deposited no event.
174		assert_eq!(frame_system::Pallet::<T>::events().len(), events);
175		Ok(())
176	}
177
178	/// A stored set of `MaxValidators` validators, `v` of them with counts, all handed to the
179	/// runtime's reporter, and `o` authors outside the set with counts, which are removed.
180	#[benchmark]
181	fn report_blocks(
182		v: Linear<1, { T::MaxValidators::get() }>,
183		o: Linear<0, { T::MaxEntriesPerReport::get().saturating_sub(T::MaxValidators::get()) }>,
184	) -> Result<(), BenchmarkError> {
185		let validators = (0..T::MaxValidators::get())
186			.map(|i| account("validator", i, 0))
187			.collect::<Vec<T::AccountId>>();
188		Pallet::<T>::receive_validator_set(0, validators.iter().cloned())?;
189		let blocks = validators.into_iter().take(v as usize).map(|v| (v, 1)).collect::<Vec<_>>();
190		let others = (0..o).map(|i| (account::<T::AccountId>("author", i, 0), 1));
191		for (who, count) in blocks.iter().cloned().chain(others) {
192			AuthoredBlocks::<T>::insert(who, count);
193		}
194		T::BlockReporter::ensure_successful_report(&blocks);
195
196		#[block]
197		{
198			Pallet::<T>::report_blocks(v + o);
199		}
200
201		assert_eq!(AuthoredBlocks::<T>::count(), 0);
202		frame_system::Pallet::<T>::assert_last_event(
203			<T as frame_system::Config>::RuntimeEvent::from(Event::<T>::BlocksReported {
204				authors: v + o,
205				reported: v,
206			}),
207		);
208		Ok(())
209	}
210
211	impl_benchmark_test_suite!(ValidatorCollators, crate::mock::new_test_ext(), crate::mock::Test);
212}