referrerpolicy=no-referrer-when-downgrade

pallet_registrar_relay/
benchmarking.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Benchmarks for `pallet-registrar-relay`.
19
20use super::*;
21use frame_benchmarking::v2::*;
22use frame_support::traits::Get;
23use frame_system::RawOrigin;
24// The registry refuses smaller code, and both upgrade benchmarks go through it.
25use polkadot_primitives::MIN_CODE_SIZE;
26use registrar_primitives::{MessageToRelay, MessageToRelayV1};
27use sp_runtime::traits::{BlakeTwo256, Hash, Saturating};
28
29/// A para id no benchmark setup will collide on.
30const PARA_ID: ParaId = 4_242;
31
32fn code_of(len: u32) -> Vec<u8> {
33	alloc::vec![1u8; len as usize]
34}
35
36/// Park a pending registration for `PARA_ID` expecting exactly `code`.
37///
38/// Written straight to storage rather than pushed through [`Pallet::receive`]: going through the
39/// call would put the whole range at the mercy of whatever minimum code size the configured
40/// [`ParachainRegistrar`] enforces, and `c = 0` would fail setup instead of measuring anything.
41fn park<T: Config>(code: &[u8]) -> Result<(), BenchmarkError> {
42	let genesis_head = alloc::vec![2u8; T::MaxHeadDataSize::get() as usize];
43	let pending = PendingRegistration {
44		message_id: 0,
45		manager: account("manager", 0, 0),
46		genesis_head: genesis_head.try_into().map_err(|_| "head data exceeds its own bound")?,
47		code_hash: BlakeTwo256::hash(code),
48		code_len: code.len() as u32,
49	};
50
51	PendingRegistrations::<T>::insert(PARA_ID, pending);
52	Ok(())
53}
54
55/// Register `PARA_ID` and authorize a code upgrade for it expecting exactly `code`.
56fn authorize<T: Config>(code: &[u8]) -> Result<(), BenchmarkError> {
57	T::Registrar::setup_worst_case_code_upgrade(PARA_ID)?;
58	let expire_at =
59		frame_system::Pallet::<T>::block_number().saturating_add(T::CodeUpgradeValidPeriod::get());
60	PendingCodeUpgrades::<T>::insert(
61		PARA_ID,
62		PendingCodeUpgrade {
63			message_id: 0,
64			code_hash: BlakeTwo256::hash(code),
65			code_len: code.len() as u32,
66			expire_at,
67		},
68	);
69	Ok(())
70}
71
72#[benchmarks]
73mod benchmarks {
74	use super::*;
75
76	/// Accepting a registration request. Dominated by writing the head data.
77	#[benchmark]
78	fn receive_register(h: Linear<0, { T::MaxHeadDataSize::get() }>) -> Result<(), BenchmarkError> {
79		let manager: T::AccountId = account("manager", 0, 0);
80		let code = code_of(T::MaxCodeSize::get());
81		let message = MessageToRelay::V1(MessageToRelayV1::Register {
82			para_id: PARA_ID,
83			message_id: 0,
84			manager,
85			genesis_head: alloc::vec![2u8; h as usize],
86			code_hash: BlakeTwo256::hash(&code),
87			code_len: code.len() as u32,
88		});
89
90		#[extrinsic_call]
91		receive(RawOrigin::Root, message);
92
93		assert!(PendingRegistrations::<T>::contains_key(PARA_ID));
94		Ok(())
95	}
96
97	/// Uploading the validation code. Dominated by hashing and onboarding the blob.
98	#[benchmark]
99	fn apply_authorized_code(
100		c: Linear<0, { T::MaxCodeSize::get() }>,
101	) -> Result<(), BenchmarkError> {
102		let code = code_of(c);
103		park::<T>(&code)?;
104
105		#[extrinsic_call]
106		_(RawOrigin::Authorized, PARA_ID, code);
107
108		assert!(!PendingRegistrations::<T>::contains_key(PARA_ID));
109		Ok(())
110	}
111
112	/// Deciding whether an unsigned `apply_authorized_code` may enter the pool.
113	///
114	/// This runs on every node for every candidate transaction, so it is the number that keeps
115	/// the free call from being a cheap way to make everyone hash megabytes.
116	#[benchmark]
117	fn authorize_apply_authorized_code(
118		c: Linear<0, { T::MaxCodeSize::get() }>,
119	) -> Result<(), BenchmarkError> {
120		let code = code_of(c);
121		park::<T>(&code)?;
122		let call = Call::<T>::apply_authorized_code { para_id: PARA_ID, validation_code: code };
123
124		#[block]
125		{
126			use frame_support::pallet_prelude::Authorize;
127			call.authorize(sp_runtime::transaction_validity::TransactionSource::External)
128				.ok_or("call must give some authorization")??;
129		}
130
131		Ok(())
132	}
133
134	/// Dropping an authorization. The worst case carries the largest head data, since that is what
135	/// the entry being removed holds.
136	#[benchmark]
137	fn receive_cancel_registration() -> Result<(), BenchmarkError> {
138		park::<T>(&code_of(T::MaxCodeSize::get()))?;
139		let message = MessageToRelay::V1(MessageToRelayV1::CancelRegistration {
140			para_id: PARA_ID,
141			message_id: 0,
142		});
143
144		#[extrinsic_call]
145		receive(RawOrigin::Root, message);
146
147		assert!(!PendingRegistrations::<T>::contains_key(PARA_ID));
148		Ok(())
149	}
150
151	/// Authorizing a code upgrade. One look at the registry, one write, one report.
152	#[benchmark]
153	fn receive_authorize_code_upgrade() -> Result<(), BenchmarkError> {
154		T::Registrar::setup_worst_case_code_upgrade(PARA_ID)?;
155		let code = code_of(T::MaxCodeSize::get());
156		let message = MessageToRelay::V1(MessageToRelayV1::AuthorizeCodeUpgrade {
157			para_id: PARA_ID,
158			message_id: 0,
159			code_hash: BlakeTwo256::hash(&code),
160			code_len: code.len() as u32,
161		});
162
163		#[extrinsic_call]
164		receive(RawOrigin::Root, message);
165
166		assert!(PendingCodeUpgrades::<T>::contains_key(PARA_ID));
167		Ok(())
168	}
169
170	/// Uploading the new validation code. Dominated by hashing and scheduling the blob.
171	#[benchmark]
172	fn apply_authorized_code_upgrade(
173		c: Linear<{ MIN_CODE_SIZE }, { T::MaxCodeSize::get() }>,
174	) -> Result<(), BenchmarkError> {
175		let code = code_of(c);
176		authorize::<T>(&code)?;
177
178		#[extrinsic_call]
179		_(RawOrigin::Authorized, PARA_ID, code);
180
181		assert!(!PendingCodeUpgrades::<T>::contains_key(PARA_ID));
182		Ok(())
183	}
184
185	/// Deciding whether an unsigned `apply_authorized_code_upgrade` may enter the pool.
186	#[benchmark]
187	fn authorize_apply_authorized_code_upgrade(
188		c: Linear<{ MIN_CODE_SIZE }, { T::MaxCodeSize::get() }>,
189	) -> Result<(), BenchmarkError> {
190		let code = code_of(c);
191		authorize::<T>(&code)?;
192		let call =
193			Call::<T>::apply_authorized_code_upgrade { para_id: PARA_ID, validation_code: code };
194
195		#[block]
196		{
197			use frame_support::pallet_prelude::Authorize;
198			call.authorize(sp_runtime::transaction_validity::TransactionSource::External)
199				.ok_or("call must give some authorization")??;
200		}
201
202		Ok(())
203	}
204
205	/// Telling the parachain a para produced its first head.
206	#[benchmark]
207	fn on_new_head() {
208		AwaitingFirstHead::<T>::insert(PARA_ID, ());
209
210		#[block]
211		{
212			<Pallet<T> as OnNewHead>::on_new_head(PARA_ID.into(), &HeadData(alloc::vec![]));
213		}
214
215		assert!(!AwaitingFirstHead::<T>::contains_key(PARA_ID));
216	}
217
218	/// A later head, where the first one has already been reported.
219	#[benchmark]
220	fn on_new_head_already_noted() {
221		#[block]
222		{
223			<Pallet<T> as OnNewHead>::on_new_head(PARA_ID.into(), &HeadData(alloc::vec![]));
224		}
225	}
226
227	/// Dropping a para from the registry, which is where the whole cost of this sits.
228	#[benchmark]
229	fn receive_deregister() -> Result<(), BenchmarkError> {
230		T::Registrar::setup_worst_case_deregister(PARA_ID)?;
231		AwaitingFirstHead::<T>::insert(PARA_ID, ());
232		let message =
233			MessageToRelay::V1(MessageToRelayV1::Deregister { para_id: PARA_ID, message_id: 0 });
234
235		#[extrinsic_call]
236		receive(RawOrigin::Root, message);
237
238		assert!(!AwaitingFirstHead::<T>::contains_key(PARA_ID));
239		Ok(())
240	}
241
242	/// Setting a head. Dominated by the head data.
243	#[benchmark]
244	fn receive_set_current_head(
245		h: Linear<0, { T::MaxHeadDataSize::get() }>,
246	) -> Result<(), BenchmarkError> {
247		// Any registered para will do; this is the only registry setup the trait offers.
248		T::Registrar::setup_worst_case_deregister(PARA_ID)?;
249		let message = MessageToRelay::V1(MessageToRelayV1::SetCurrentHead {
250			para_id: PARA_ID,
251			message_id: 0,
252			head: alloc::vec![2u8; h as usize],
253		});
254
255		#[extrinsic_call]
256		receive(RawOrigin::Root, message);
257
258		frame_system::Pallet::<T>::assert_last_event(
259			<T as Config>::RuntimeEvent::from(Event::<T>::HeadUpdated {
260				para_id: PARA_ID,
261				message_id: 0,
262			})
263			.into(),
264		);
265		Ok(())
266	}
267
268	impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::Test);
269}