referrerpolicy=no-referrer-when-downgrade

polkadot_runtime_parachains/configuration/migration/
v9.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Polkadot.
3
4// Polkadot is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Polkadot is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.
16
17//! A module that is responsible for migration of storage.
18
19use crate::configuration::{self, Config, Pallet};
20use alloc::vec::Vec;
21use frame_support::{
22	pallet_prelude::*,
23	traits::{Defensive, StorageVersion},
24	weights::Weight,
25};
26use frame_system::pallet_prelude::BlockNumberFor;
27use polkadot_primitives::{
28	AsyncBackingParams, Balance, ExecutorParams, SessionIndex, LEGACY_MIN_BACKING_VOTES,
29	ON_DEMAND_DEFAULT_QUEUE_MAX_SIZE,
30};
31use sp_runtime::Perbill;
32
33use frame_support::traits::OnRuntimeUpgrade;
34
35use super::v8::V8HostConfiguration;
36/// All configuration of the runtime with respect to paras.
37#[derive(Clone, Encode, Decode, Debug)]
38pub struct V9HostConfiguration<BlockNumber> {
39	pub max_code_size: u32,
40	pub max_head_data_size: u32,
41	pub max_upward_queue_count: u32,
42	pub max_upward_queue_size: u32,
43	pub max_upward_message_size: u32,
44	pub max_upward_message_num_per_candidate: u32,
45	pub hrmp_max_message_num_per_candidate: u32,
46	pub validation_upgrade_cooldown: BlockNumber,
47	pub validation_upgrade_delay: BlockNumber,
48	pub async_backing_params: AsyncBackingParams,
49	pub max_pov_size: u32,
50	pub max_downward_message_size: u32,
51	pub hrmp_max_parachain_outbound_channels: u32,
52	pub hrmp_sender_deposit: Balance,
53	pub hrmp_recipient_deposit: Balance,
54	pub hrmp_channel_max_capacity: u32,
55	pub hrmp_channel_max_total_size: u32,
56	pub hrmp_max_parachain_inbound_channels: u32,
57	pub hrmp_channel_max_message_size: u32,
58	pub executor_params: ExecutorParams,
59	pub code_retention_period: BlockNumber,
60	pub on_demand_cores: u32,
61	pub on_demand_retries: u32,
62	pub on_demand_queue_max_size: u32,
63	pub on_demand_target_queue_utilization: Perbill,
64	pub on_demand_fee_variability: Perbill,
65	pub on_demand_base_fee: Balance,
66	pub on_demand_ttl: BlockNumber,
67	pub group_rotation_frequency: BlockNumber,
68	pub paras_availability_period: BlockNumber,
69	pub scheduling_lookahead: u32,
70	pub max_validators_per_core: Option<u32>,
71	pub max_validators: Option<u32>,
72	pub dispute_period: SessionIndex,
73	pub dispute_post_conclusion_acceptance_period: BlockNumber,
74	pub no_show_slots: u32,
75	pub n_delay_tranches: u32,
76	pub zeroth_delay_tranche_width: u32,
77	pub needed_approvals: u32,
78	pub relay_vrf_modulo_samples: u32,
79	pub pvf_voting_ttl: SessionIndex,
80	pub minimum_validation_upgrade_delay: BlockNumber,
81	pub minimum_backing_votes: u32,
82}
83
84impl<BlockNumber: Default + From<u32>> Default for V9HostConfiguration<BlockNumber> {
85	fn default() -> Self {
86		Self {
87			async_backing_params: AsyncBackingParams {
88				max_candidate_depth: 0,
89				allowed_ancestry_len: 0,
90			},
91			group_rotation_frequency: 1u32.into(),
92			paras_availability_period: 1u32.into(),
93			no_show_slots: 1u32.into(),
94			validation_upgrade_cooldown: Default::default(),
95			validation_upgrade_delay: 2u32.into(),
96			code_retention_period: Default::default(),
97			max_code_size: Default::default(),
98			max_pov_size: Default::default(),
99			max_head_data_size: Default::default(),
100			on_demand_cores: Default::default(),
101			on_demand_retries: Default::default(),
102			scheduling_lookahead: 1,
103			max_validators_per_core: Default::default(),
104			max_validators: None,
105			dispute_period: 6,
106			dispute_post_conclusion_acceptance_period: 100.into(),
107			n_delay_tranches: Default::default(),
108			zeroth_delay_tranche_width: Default::default(),
109			needed_approvals: Default::default(),
110			relay_vrf_modulo_samples: Default::default(),
111			max_upward_queue_count: Default::default(),
112			max_upward_queue_size: Default::default(),
113			max_downward_message_size: Default::default(),
114			max_upward_message_size: Default::default(),
115			max_upward_message_num_per_candidate: Default::default(),
116			hrmp_sender_deposit: Default::default(),
117			hrmp_recipient_deposit: Default::default(),
118			hrmp_channel_max_capacity: Default::default(),
119			hrmp_channel_max_total_size: Default::default(),
120			hrmp_max_parachain_inbound_channels: Default::default(),
121			hrmp_channel_max_message_size: Default::default(),
122			hrmp_max_parachain_outbound_channels: Default::default(),
123			hrmp_max_message_num_per_candidate: Default::default(),
124			pvf_voting_ttl: 2u32.into(),
125			minimum_validation_upgrade_delay: 2.into(),
126			executor_params: Default::default(),
127			on_demand_queue_max_size: ON_DEMAND_DEFAULT_QUEUE_MAX_SIZE,
128			on_demand_base_fee: 10_000_000u128,
129			on_demand_fee_variability: Perbill::from_percent(3),
130			on_demand_target_queue_utilization: Perbill::from_percent(25),
131			on_demand_ttl: 5u32.into(),
132			minimum_backing_votes: LEGACY_MIN_BACKING_VOTES,
133		}
134	}
135}
136
137mod v8 {
138	use super::*;
139
140	#[frame_support::storage_alias]
141	pub(crate) type ActiveConfig<T: Config> =
142		StorageValue<Pallet<T>, V8HostConfiguration<BlockNumberFor<T>>, OptionQuery>;
143
144	#[frame_support::storage_alias]
145	pub(crate) type PendingConfigs<T: Config> = StorageValue<
146		Pallet<T>,
147		Vec<(SessionIndex, V8HostConfiguration<BlockNumberFor<T>>)>,
148		OptionQuery,
149	>;
150}
151
152mod v9 {
153	use super::*;
154
155	#[frame_support::storage_alias]
156	pub(crate) type ActiveConfig<T: Config> =
157		StorageValue<Pallet<T>, V9HostConfiguration<BlockNumberFor<T>>, OptionQuery>;
158
159	#[frame_support::storage_alias]
160	pub(crate) type PendingConfigs<T: Config> = StorageValue<
161		Pallet<T>,
162		Vec<(SessionIndex, V9HostConfiguration<BlockNumberFor<T>>)>,
163		OptionQuery,
164	>;
165}
166
167pub struct MigrateToV9<T>(core::marker::PhantomData<T>);
168impl<T: Config> OnRuntimeUpgrade for MigrateToV9<T> {
169	#[cfg(feature = "try-runtime")]
170	fn pre_upgrade() -> Result<Vec<u8>, sp_runtime::TryRuntimeError> {
171		log::trace!(target: crate::configuration::LOG_TARGET, "Running pre_upgrade() for HostConfiguration MigrateToV9");
172		Ok(Vec::new())
173	}
174
175	fn on_runtime_upgrade() -> Weight {
176		log::info!(target: configuration::LOG_TARGET, "HostConfiguration MigrateToV9 started");
177		if StorageVersion::get::<Pallet<T>>() == 8 {
178			let weight_consumed = migrate_to_v9::<T>();
179
180			log::info!(target: configuration::LOG_TARGET, "HostConfiguration MigrateToV9 executed successfully");
181			StorageVersion::new(9).put::<Pallet<T>>();
182
183			weight_consumed
184		} else {
185			log::warn!(target: configuration::LOG_TARGET, "HostConfiguration MigrateToV9 should be removed.");
186			T::DbWeight::get().reads(1)
187		}
188	}
189
190	#[cfg(feature = "try-runtime")]
191	fn post_upgrade(_state: Vec<u8>) -> Result<(), sp_runtime::TryRuntimeError> {
192		log::trace!(target: crate::configuration::LOG_TARGET, "Running post_upgrade() for HostConfiguration MigrateToV9");
193		ensure!(
194			StorageVersion::get::<Pallet<T>>() >= 9,
195			"Storage version should be >= 9 after the migration"
196		);
197
198		Ok(())
199	}
200}
201
202fn migrate_to_v9<T: Config>() -> Weight {
203	// Unusual formatting is justified:
204	// - make it easier to verify that fields assign what they supposed to assign.
205	// - this code is transient and will be removed after all migrations are done.
206	// - this code is important enough to optimize for legibility sacrificing consistency.
207	#[rustfmt::skip]
208	let translate =
209		|pre: V8HostConfiguration<BlockNumberFor<T>>| ->
210		V9HostConfiguration<BlockNumberFor<T>>
211	{
212		V9HostConfiguration {
213max_code_size                            : pre.max_code_size,
214max_head_data_size                       : pre.max_head_data_size,
215max_upward_queue_count                   : pre.max_upward_queue_count,
216max_upward_queue_size                    : pre.max_upward_queue_size,
217max_upward_message_size                  : pre.max_upward_message_size,
218max_upward_message_num_per_candidate     : pre.max_upward_message_num_per_candidate,
219hrmp_max_message_num_per_candidate       : pre.hrmp_max_message_num_per_candidate,
220validation_upgrade_cooldown              : pre.validation_upgrade_cooldown,
221validation_upgrade_delay                 : pre.validation_upgrade_delay,
222max_pov_size                             : pre.max_pov_size,
223max_downward_message_size                : pre.max_downward_message_size,
224hrmp_sender_deposit                      : pre.hrmp_sender_deposit,
225hrmp_recipient_deposit                   : pre.hrmp_recipient_deposit,
226hrmp_channel_max_capacity                : pre.hrmp_channel_max_capacity,
227hrmp_channel_max_total_size              : pre.hrmp_channel_max_total_size,
228hrmp_max_parachain_inbound_channels      : pre.hrmp_max_parachain_inbound_channels,
229hrmp_max_parachain_outbound_channels     : pre.hrmp_max_parachain_outbound_channels,
230hrmp_channel_max_message_size            : pre.hrmp_channel_max_message_size,
231code_retention_period                    : pre.code_retention_period,
232on_demand_cores                          : pre.on_demand_cores,
233on_demand_retries                        : pre.on_demand_retries,
234group_rotation_frequency                 : pre.group_rotation_frequency,
235paras_availability_period                : pre.paras_availability_period,
236scheduling_lookahead                     : pre.scheduling_lookahead,
237max_validators_per_core                  : pre.max_validators_per_core,
238max_validators                           : pre.max_validators,
239dispute_period                           : pre.dispute_period,
240dispute_post_conclusion_acceptance_period: pre.dispute_post_conclusion_acceptance_period,
241no_show_slots                            : pre.no_show_slots,
242n_delay_tranches                         : pre.n_delay_tranches,
243zeroth_delay_tranche_width               : pre.zeroth_delay_tranche_width,
244needed_approvals                         : pre.needed_approvals,
245relay_vrf_modulo_samples                 : pre.relay_vrf_modulo_samples,
246pvf_voting_ttl                           : pre.pvf_voting_ttl,
247minimum_validation_upgrade_delay         : pre.minimum_validation_upgrade_delay,
248async_backing_params                     : pre.async_backing_params,
249executor_params                          : pre.executor_params,
250on_demand_queue_max_size                 : pre.on_demand_queue_max_size,
251on_demand_base_fee                       : pre.on_demand_base_fee,
252on_demand_fee_variability                : pre.on_demand_fee_variability,
253on_demand_target_queue_utilization       : pre.on_demand_target_queue_utilization,
254on_demand_ttl                            : pre.on_demand_ttl,
255minimum_backing_votes                    : LEGACY_MIN_BACKING_VOTES
256		}
257	};
258
259	let v8 = v8::ActiveConfig::<T>::get()
260		.defensive_proof("Could not decode old config")
261		.unwrap_or_default();
262	let v9 = translate(v8);
263	v9::ActiveConfig::<T>::set(Some(v9));
264
265	// Allowed to be empty.
266	let pending_v8 = v8::PendingConfigs::<T>::get().unwrap_or_default();
267	let mut pending_v9 = Vec::new();
268
269	for (session, v8) in pending_v8.into_iter() {
270		let v9 = translate(v8);
271		pending_v9.push((session, v9));
272	}
273	v9::PendingConfigs::<T>::set(Some(pending_v9.clone()));
274
275	let num_configs = (pending_v9.len() + 1) as u64;
276	T::DbWeight::get().reads_writes(num_configs, num_configs)
277}
278
279#[cfg(test)]
280mod tests {
281	use super::*;
282	use crate::mock::{new_test_ext, Test};
283
284	#[test]
285	fn v9_deserialized_from_actual_data() {
286		// Example how to get new `raw_config`:
287		// We'll obtain the raw_config at a specified a block
288		// Steps:
289		// 1. Go to Polkadot.js -> Developer -> Chain state -> Storage: https://polkadot.js.org/apps/#/chainstate
290		// 2. Set these parameters:
291		//   2.1. selected state query: configuration; activeConfig():
292		//        PolkadotRuntimeParachainsConfigurationHostConfiguration
293		//   2.2. blockhash to query at:
294		//        0xf89d3ab5312c5f70d396dc59612f0aa65806c798346f9db4b35278baed2e0e53 (the hash of
295		//        the block)
296		//   2.3. Note the value of encoded storage key ->
297		//        0x06de3d8a54d27e44a9d5ce189618f22db4b49d95320d9021994c850f25b8e385 for the
298		// referenced        block.
299		//   2.4. You'll also need the decoded values to update the test.
300		// 3. Go to Polkadot.js -> Developer -> Chain state -> Raw storage
301		//   3.1 Enter the encoded storage key and you get the raw config.
302
303		// This exceeds the maximal line width length, but that's fine, since this is not code and
304		// doesn't need to be read and also leaving it as one line allows to easily copy it.
305		let raw_config =
306	hex_literal::hex!["
307	0000300000800000080000000000100000c8000005000000050000000200000002000000000000000000000000005000000010000400000000000000000000000000000000000000000000000000000000000000000000000800000000200000040000000000100000b004000000000000000000001027000080b2e60e80c3c901809698000000000000000000000000000500000014000000040000000100000001010000000006000000640000000200000019000000000000000300000002000000020000000500000002000000"
308	];
309
310		let v9 =
311			V9HostConfiguration::<polkadot_primitives::BlockNumber>::decode(&mut &raw_config[..])
312				.unwrap();
313
314		// We check only a sample of the values here. If we missed any fields or messed up data
315		// types that would skew all the fields coming after.
316		assert_eq!(v9.max_code_size, 3_145_728);
317		assert_eq!(v9.validation_upgrade_cooldown, 2);
318		assert_eq!(v9.max_pov_size, 5_242_880);
319		assert_eq!(v9.hrmp_channel_max_message_size, 1_048_576);
320		assert_eq!(v9.n_delay_tranches, 25);
321		assert_eq!(v9.minimum_validation_upgrade_delay, 5);
322		assert_eq!(v9.group_rotation_frequency, 20);
323		assert_eq!(v9.on_demand_cores, 0);
324		assert_eq!(v9.on_demand_base_fee, 10_000_000);
325		assert_eq!(v9.minimum_backing_votes, LEGACY_MIN_BACKING_VOTES);
326	}
327
328	#[test]
329	fn test_migrate_to_v9() {
330		// Host configuration has lots of fields. However, in this migration we only add one
331		// field. The most important part to check are a couple of the last fields. We also pick
332		// extra fields to check arbitrarily, e.g. depending on their position (i.e. the middle) and
333		// also their type.
334		//
335		// We specify only the picked fields and the rest should be provided by the `Default`
336		// implementation. That implementation is copied over between the two types and should work
337		// fine.
338		let v8 = V8HostConfiguration::<polkadot_primitives::BlockNumber> {
339			needed_approvals: 69,
340			paras_availability_period: 55,
341			hrmp_recipient_deposit: 1337,
342			max_pov_size: 1111,
343			minimum_validation_upgrade_delay: 20,
344			..Default::default()
345		};
346
347		let mut pending_configs = Vec::new();
348		pending_configs.push((100, v8.clone()));
349		pending_configs.push((300, v8.clone()));
350
351		new_test_ext(Default::default()).execute_with(|| {
352			// Implant the v8 version in the state.
353			v8::ActiveConfig::<Test>::set(Some(v8));
354			v8::PendingConfigs::<Test>::set(Some(pending_configs));
355
356			migrate_to_v9::<Test>();
357
358			let v9 = v9::ActiveConfig::<Test>::get().unwrap();
359			let mut configs_to_check = v9::PendingConfigs::<Test>::get().unwrap();
360			configs_to_check.push((0, v9.clone()));
361
362			for (_, v8) in configs_to_check {
363				#[rustfmt::skip]
364				{
365					assert_eq!(v8.max_code_size                            , v9.max_code_size);
366					assert_eq!(v8.max_head_data_size                       , v9.max_head_data_size);
367					assert_eq!(v8.max_upward_queue_count                   , v9.max_upward_queue_count);
368					assert_eq!(v8.max_upward_queue_size                    , v9.max_upward_queue_size);
369					assert_eq!(v8.max_upward_message_size                  , v9.max_upward_message_size);
370					assert_eq!(v8.max_upward_message_num_per_candidate     , v9.max_upward_message_num_per_candidate);
371					assert_eq!(v8.hrmp_max_message_num_per_candidate       , v9.hrmp_max_message_num_per_candidate);
372					assert_eq!(v8.validation_upgrade_cooldown              , v9.validation_upgrade_cooldown);
373					assert_eq!(v8.validation_upgrade_delay                 , v9.validation_upgrade_delay);
374					assert_eq!(v8.max_pov_size                             , v9.max_pov_size);
375					assert_eq!(v8.max_downward_message_size                , v9.max_downward_message_size);
376					assert_eq!(v8.hrmp_max_parachain_outbound_channels     , v9.hrmp_max_parachain_outbound_channels);
377					assert_eq!(v8.hrmp_sender_deposit                      , v9.hrmp_sender_deposit);
378					assert_eq!(v8.hrmp_recipient_deposit                   , v9.hrmp_recipient_deposit);
379					assert_eq!(v8.hrmp_channel_max_capacity                , v9.hrmp_channel_max_capacity);
380					assert_eq!(v8.hrmp_channel_max_total_size              , v9.hrmp_channel_max_total_size);
381					assert_eq!(v8.hrmp_max_parachain_inbound_channels      , v9.hrmp_max_parachain_inbound_channels);
382					assert_eq!(v8.hrmp_channel_max_message_size            , v9.hrmp_channel_max_message_size);
383					assert_eq!(v8.code_retention_period                    , v9.code_retention_period);
384					assert_eq!(v8.on_demand_cores                          , v9.on_demand_cores);
385					assert_eq!(v8.on_demand_retries                        , v9.on_demand_retries);
386					assert_eq!(v8.group_rotation_frequency                 , v9.group_rotation_frequency);
387					assert_eq!(v8.paras_availability_period                , v9.paras_availability_period);
388					assert_eq!(v8.scheduling_lookahead                     , v9.scheduling_lookahead);
389					assert_eq!(v8.max_validators_per_core                  , v9.max_validators_per_core);
390					assert_eq!(v8.max_validators                           , v9.max_validators);
391					assert_eq!(v8.dispute_period                           , v9.dispute_period);
392					assert_eq!(v8.no_show_slots                            , v9.no_show_slots);
393					assert_eq!(v8.n_delay_tranches                         , v9.n_delay_tranches);
394					assert_eq!(v8.zeroth_delay_tranche_width               , v9.zeroth_delay_tranche_width);
395					assert_eq!(v8.needed_approvals                         , v9.needed_approvals);
396					assert_eq!(v8.relay_vrf_modulo_samples                 , v9.relay_vrf_modulo_samples);
397					assert_eq!(v8.pvf_voting_ttl                           , v9.pvf_voting_ttl);
398					assert_eq!(v8.minimum_validation_upgrade_delay         , v9.minimum_validation_upgrade_delay);
399					assert_eq!(v8.async_backing_params.allowed_ancestry_len, v9.async_backing_params.allowed_ancestry_len);
400					assert_eq!(v8.async_backing_params.max_candidate_depth , v9.async_backing_params.max_candidate_depth);
401					assert_eq!(v8.executor_params						   , v9.executor_params);
402				    assert_eq!(v8.minimum_backing_votes					   , v9.minimum_backing_votes);
403				}; // ; makes this a statement. `rustfmt::skip` cannot be put on an expression.
404			}
405		});
406	}
407
408	// Test that migration doesn't panic in case there're no pending configurations upgrades in
409	// pallet's storage.
410	#[test]
411	fn test_migrate_to_v9_no_pending() {
412		let v8 = V8HostConfiguration::<polkadot_primitives::BlockNumber>::default();
413
414		new_test_ext(Default::default()).execute_with(|| {
415			// Implant the v8 version in the state.
416			v8::ActiveConfig::<Test>::set(Some(v8));
417			// Ensure there're no pending configs.
418			v8::PendingConfigs::<Test>::set(None);
419
420			// Shouldn't fail.
421			migrate_to_v9::<Test>();
422		});
423	}
424}