referrerpolicy=no-referrer-when-downgrade

polkadot_runtime_parachains/configuration/migration/
v12.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::{
20	self,
21	migration::{
22		v11::V11HostConfiguration,
23		v13::{V12HostConfiguration, V12SchedulerParams},
24	},
25	Config, Pallet,
26};
27use alloc::vec::Vec;
28use frame_support::{
29	migrations::VersionedMigration,
30	pallet_prelude::*,
31	traits::{Defensive, UncheckedOnRuntimeUpgrade},
32};
33use frame_system::pallet_prelude::BlockNumberFor;
34use sp_core::Get;
35use sp_staking::SessionIndex;
36
37mod v11 {
38	use super::*;
39
40	#[frame_support::storage_alias]
41	pub(crate) type ActiveConfig<T: Config> =
42		StorageValue<Pallet<T>, V11HostConfiguration<BlockNumberFor<T>>, OptionQuery>;
43
44	#[frame_support::storage_alias]
45	pub(crate) type PendingConfigs<T: Config> = StorageValue<
46		Pallet<T>,
47		Vec<(SessionIndex, V11HostConfiguration<BlockNumberFor<T>>)>,
48		OptionQuery,
49	>;
50}
51
52mod v12 {
53	use super::*;
54
55	#[frame_support::storage_alias]
56	pub(crate) type ActiveConfig<T: Config> =
57		StorageValue<Pallet<T>, V12HostConfiguration<BlockNumberFor<T>>, OptionQuery>;
58
59	#[frame_support::storage_alias]
60	pub(crate) type PendingConfigs<T: Config> = StorageValue<
61		Pallet<T>,
62		Vec<(SessionIndex, V12HostConfiguration<BlockNumberFor<T>>)>,
63		OptionQuery,
64	>;
65}
66
67pub type MigrateToV12<T> = VersionedMigration<
68	11,
69	12,
70	UncheckedMigrateToV12<T>,
71	Pallet<T>,
72	<T as frame_system::Config>::DbWeight,
73>;
74
75pub struct UncheckedMigrateToV12<T>(core::marker::PhantomData<T>);
76
77impl<T: Config> UncheckedOnRuntimeUpgrade for UncheckedMigrateToV12<T> {
78	#[cfg(feature = "try-runtime")]
79	fn pre_upgrade() -> Result<Vec<u8>, sp_runtime::TryRuntimeError> {
80		log::trace!(target: crate::configuration::LOG_TARGET, "Running pre_upgrade() for HostConfiguration MigrateToV12");
81		Ok(Vec::new())
82	}
83
84	fn on_runtime_upgrade() -> Weight {
85		log::info!(target: configuration::LOG_TARGET, "HostConfiguration MigrateToV12 started");
86		let weight_consumed = migrate_to_v12::<T>();
87
88		log::info!(target: configuration::LOG_TARGET, "HostConfiguration MigrateToV12 executed successfully");
89
90		weight_consumed
91	}
92
93	#[cfg(feature = "try-runtime")]
94	fn post_upgrade(_state: Vec<u8>) -> Result<(), sp_runtime::TryRuntimeError> {
95		log::trace!(target: crate::configuration::LOG_TARGET, "Running post_upgrade() for HostConfiguration MigrateToV12");
96		ensure!(
97			StorageVersion::get::<Pallet<T>>() >= 12,
98			"Storage version should be >= 12 after the migration"
99		);
100
101		Ok(())
102	}
103}
104
105fn migrate_to_v12<T: Config>() -> Weight {
106	// Unusual formatting is justified:
107	// - make it easier to verify that fields assign what they supposed to assign.
108	// - this code is transient and will be removed after all migrations are done.
109	// - this code is important enough to optimize for legibility sacrificing consistency.
110	#[rustfmt::skip]
111		let translate =
112		|pre: V11HostConfiguration<BlockNumberFor<T>>| ->
113		V12HostConfiguration<BlockNumberFor<T>>
114			{
115				V12HostConfiguration {
116					max_code_size                            : pre.max_code_size,
117					max_head_data_size                       : pre.max_head_data_size,
118					max_upward_queue_count                   : pre.max_upward_queue_count,
119					max_upward_queue_size                    : pre.max_upward_queue_size,
120					max_upward_message_size                  : pre.max_upward_message_size,
121					max_upward_message_num_per_candidate     : pre.max_upward_message_num_per_candidate,
122					hrmp_max_message_num_per_candidate       : pre.hrmp_max_message_num_per_candidate,
123					validation_upgrade_cooldown              : pre.validation_upgrade_cooldown,
124					validation_upgrade_delay                 : pre.validation_upgrade_delay,
125					max_pov_size                             : pre.max_pov_size,
126					max_downward_message_size                : pre.max_downward_message_size,
127					hrmp_sender_deposit                      : pre.hrmp_sender_deposit,
128					hrmp_recipient_deposit                   : pre.hrmp_recipient_deposit,
129					hrmp_channel_max_capacity                : pre.hrmp_channel_max_capacity,
130					hrmp_channel_max_total_size              : pre.hrmp_channel_max_total_size,
131					hrmp_max_parachain_inbound_channels      : pre.hrmp_max_parachain_inbound_channels,
132					hrmp_max_parachain_outbound_channels     : pre.hrmp_max_parachain_outbound_channels,
133					hrmp_channel_max_message_size            : pre.hrmp_channel_max_message_size,
134					code_retention_period                    : pre.code_retention_period,
135					max_validators                           : pre.max_validators,
136					dispute_period                           : pre.dispute_period,
137					dispute_post_conclusion_acceptance_period: pre.dispute_post_conclusion_acceptance_period,
138					no_show_slots                            : pre.no_show_slots,
139					n_delay_tranches                         : pre.n_delay_tranches,
140					zeroth_delay_tranche_width               : pre.zeroth_delay_tranche_width,
141					needed_approvals                         : pre.needed_approvals,
142					relay_vrf_modulo_samples                 : pre.relay_vrf_modulo_samples,
143					pvf_voting_ttl                           : pre.pvf_voting_ttl,
144					minimum_validation_upgrade_delay         : pre.minimum_validation_upgrade_delay,
145					async_backing_params                     : pre.async_backing_params,
146					executor_params                          : pre.executor_params,
147					minimum_backing_votes                    : pre.minimum_backing_votes,
148					node_features                            : pre.node_features,
149					approval_voting_params                   : pre.approval_voting_params,
150					#[allow(deprecated)]
151					scheduler_params: V12SchedulerParams {
152							group_rotation_frequency             : pre.group_rotation_frequency,
153							paras_availability_period            : pre.paras_availability_period,
154							max_validators_per_core              : pre.max_validators_per_core,
155							lookahead                            : pre.scheduling_lookahead,
156							num_cores                            : pre.coretime_cores,
157							max_availability_timeouts            : pre.on_demand_retries,
158							on_demand_queue_max_size             : pre.on_demand_queue_max_size,
159							on_demand_target_queue_utilization   : pre.on_demand_target_queue_utilization,
160							on_demand_fee_variability            : pre.on_demand_fee_variability,
161							on_demand_base_fee                   : pre.on_demand_base_fee,
162							ttl                                  : pre.on_demand_ttl,
163					}
164				}
165			};
166
167	let v11 = v11::ActiveConfig::<T>::get()
168		.defensive_proof("Could not decode old config")
169		.unwrap_or_default();
170	let v12 = translate(v11);
171	v12::ActiveConfig::<T>::set(Some(v12));
172
173	// Allowed to be empty.
174	let pending_v11 = v11::PendingConfigs::<T>::get().unwrap_or_default();
175	let mut pending_v12 = Vec::new();
176
177	for (session, v11) in pending_v11.into_iter() {
178		let v12 = translate(v11);
179		pending_v12.push((session, v12));
180	}
181	v12::PendingConfigs::<T>::set(Some(pending_v12.clone()));
182
183	let num_configs = (pending_v12.len() + 1) as u64;
184	T::DbWeight::get().reads_writes(num_configs, num_configs)
185}
186
187#[cfg(test)]
188mod tests {
189	use polkadot_primitives::LEGACY_MIN_BACKING_VOTES;
190	use sp_arithmetic::Perbill;
191
192	use super::*;
193	use crate::mock::{new_test_ext, Test};
194
195	#[test]
196	fn v12_deserialized_from_actual_data() {
197		// Example how to get new `raw_config`:
198		// We'll obtain the raw_config at a specified a block
199		// Steps:
200		// 1. Go to Polkadot.js -> Developer -> Chain state -> Storage: https://polkadot.js.org/apps/#/chainstate
201		// 2. Set these parameters:
202		//   2.1. selected state query: configuration; activeConfig():
203		//        PolkadotRuntimeParachainsConfigurationHostConfiguration
204		//   2.2. blockhash to query at:
205		//        0xf89d3ab5312c5f70d396dc59612f0aa65806c798346f9db4b35278baed2e0e53 (the hash of
206		//        the block)
207		//   2.3. Note the value of encoded storage key ->
208		//        0x06de3d8a54d27e44a9d5ce189618f22db4b49d95320d9021994c850f25b8e385 for the
209		//        referenced block.
210		//   2.4. You'll also need the decoded values to update the test.
211		// 3. Go to Polkadot.js -> Developer -> Chain state -> Raw storage
212		//   3.1 Enter the encoded storage key and you get the raw config.
213
214		// This exceeds the maximal line width length, but that's fine, since this is not code and
215		// doesn't need to be read and also leaving it as one line allows to easily copy it.
216		let raw_config =
217	hex_literal::hex![
218	"0000300000800000080000000000100000c8000005000000050000000200000002000000000000000000000000005000000010000400000000000000000000000000000000000000000000000000000000000000000000000800000000200000040000000000100000b004000000060000006400000002000000190000000000000002000000020000000200000005000000020000000001000000140000000400000001010000000100000001000000000000001027000080b2e60e80c3c9018096980000000000000000000000000005000000"
219	];
220
221		let v12 =
222			V12HostConfiguration::<polkadot_primitives::BlockNumber>::decode(&mut &raw_config[..])
223				.unwrap();
224
225		// We check only a sample of the values here. If we missed any fields or messed up data
226		// types that would skew all the fields coming after.
227		assert_eq!(v12.max_code_size, 3_145_728);
228		assert_eq!(v12.validation_upgrade_cooldown, 2);
229		assert_eq!(v12.max_pov_size, 5_242_880);
230		assert_eq!(v12.hrmp_channel_max_message_size, 1_048_576);
231		assert_eq!(v12.n_delay_tranches, 25);
232		assert_eq!(v12.minimum_validation_upgrade_delay, 5);
233		assert_eq!(v12.minimum_backing_votes, LEGACY_MIN_BACKING_VOTES);
234		assert_eq!(v12.approval_voting_params.max_approval_coalesce_count, 1);
235		assert_eq!(v12.scheduler_params.group_rotation_frequency, 20);
236		assert_eq!(v12.scheduler_params.paras_availability_period, 4);
237		assert_eq!(v12.scheduler_params.lookahead, 1);
238		assert_eq!(v12.scheduler_params.num_cores, 1);
239		#[allow(deprecated)]
240		{
241			assert_eq!(v12.scheduler_params.max_availability_timeouts, 0);
242		}
243		assert_eq!(v12.scheduler_params.on_demand_queue_max_size, 10_000);
244		assert_eq!(
245			v12.scheduler_params.on_demand_target_queue_utilization,
246			Perbill::from_percent(25)
247		);
248		assert_eq!(v12.scheduler_params.on_demand_fee_variability, Perbill::from_percent(3));
249		assert_eq!(v12.scheduler_params.on_demand_base_fee, 10_000_000);
250		#[allow(deprecated)]
251		{
252			assert_eq!(v12.scheduler_params.ttl, 5);
253		}
254	}
255
256	#[test]
257	fn test_migrate_to_v12() {
258		// Host configuration has lots of fields. However, in this migration we only add one
259		// field. The most important part to check are a couple of the last fields. We also pick
260		// extra fields to check arbitrarily, e.g. depending on their position (i.e. the middle) and
261		// also their type.
262		//
263		// We specify only the picked fields and the rest should be provided by the `Default`
264		// implementation. That implementation is copied over between the two types and should work
265		// fine.
266		let v11 = V11HostConfiguration::<polkadot_primitives::BlockNumber> {
267			needed_approvals: 69,
268			paras_availability_period: 55,
269			hrmp_recipient_deposit: 1337,
270			max_pov_size: 1111,
271			minimum_validation_upgrade_delay: 20,
272			on_demand_ttl: 3,
273			on_demand_retries: 10,
274			..Default::default()
275		};
276
277		let mut pending_configs = Vec::new();
278		pending_configs.push((100, v11.clone()));
279		pending_configs.push((300, v11.clone()));
280
281		new_test_ext(Default::default()).execute_with(|| {
282			// Implant the v10 version in the state.
283			v11::ActiveConfig::<Test>::set(Some(v11.clone()));
284			v11::PendingConfigs::<Test>::set(Some(pending_configs));
285
286			migrate_to_v12::<Test>();
287
288			let v12 = v12::ActiveConfig::<Test>::get().unwrap();
289			assert_eq!(v12.approval_voting_params.max_approval_coalesce_count, 1);
290
291			let mut configs_to_check = v12::PendingConfigs::<Test>::get().unwrap();
292			configs_to_check.push((0, v12.clone()));
293
294			for (_, v12) in configs_to_check {
295				#[rustfmt::skip]
296				#[allow(deprecated)]
297				{
298					assert_eq!(v11.max_code_size                            , v12.max_code_size);
299					assert_eq!(v11.max_head_data_size                       , v12.max_head_data_size);
300					assert_eq!(v11.max_upward_queue_count                   , v12.max_upward_queue_count);
301					assert_eq!(v11.max_upward_queue_size                    , v12.max_upward_queue_size);
302					assert_eq!(v11.max_upward_message_size                  , v12.max_upward_message_size);
303					assert_eq!(v11.max_upward_message_num_per_candidate     , v12.max_upward_message_num_per_candidate);
304					assert_eq!(v11.hrmp_max_message_num_per_candidate       , v12.hrmp_max_message_num_per_candidate);
305					assert_eq!(v11.validation_upgrade_cooldown              , v12.validation_upgrade_cooldown);
306					assert_eq!(v11.validation_upgrade_delay                 , v12.validation_upgrade_delay);
307					assert_eq!(v11.max_pov_size                             , v12.max_pov_size);
308					assert_eq!(v11.max_downward_message_size                , v12.max_downward_message_size);
309					assert_eq!(v11.hrmp_max_parachain_outbound_channels     , v12.hrmp_max_parachain_outbound_channels);
310					assert_eq!(v11.hrmp_sender_deposit                      , v12.hrmp_sender_deposit);
311					assert_eq!(v11.hrmp_recipient_deposit                   , v12.hrmp_recipient_deposit);
312					assert_eq!(v11.hrmp_channel_max_capacity                , v12.hrmp_channel_max_capacity);
313					assert_eq!(v11.hrmp_channel_max_total_size              , v12.hrmp_channel_max_total_size);
314					assert_eq!(v11.hrmp_max_parachain_inbound_channels      , v12.hrmp_max_parachain_inbound_channels);
315					assert_eq!(v11.hrmp_channel_max_message_size            , v12.hrmp_channel_max_message_size);
316					assert_eq!(v11.code_retention_period                    , v12.code_retention_period);
317					assert_eq!(v11.max_validators                           , v12.max_validators);
318					assert_eq!(v11.dispute_period                           , v12.dispute_period);
319					assert_eq!(v11.no_show_slots                            , v12.no_show_slots);
320					assert_eq!(v11.n_delay_tranches                         , v12.n_delay_tranches);
321					assert_eq!(v11.zeroth_delay_tranche_width               , v12.zeroth_delay_tranche_width);
322					assert_eq!(v11.needed_approvals                         , v12.needed_approvals);
323					assert_eq!(v11.relay_vrf_modulo_samples                 , v12.relay_vrf_modulo_samples);
324					assert_eq!(v11.pvf_voting_ttl                           , v12.pvf_voting_ttl);
325					assert_eq!(v11.minimum_validation_upgrade_delay         , v12.minimum_validation_upgrade_delay);
326					assert_eq!(v11.async_backing_params.allowed_ancestry_len, v12.async_backing_params.allowed_ancestry_len);
327					assert_eq!(v11.async_backing_params.max_candidate_depth , v12.async_backing_params.max_candidate_depth);
328					assert_eq!(v11.executor_params                          , v12.executor_params);
329				    assert_eq!(v11.minimum_backing_votes                    , v12.minimum_backing_votes);
330					assert_eq!(v11.group_rotation_frequency                 , v12.scheduler_params.group_rotation_frequency);
331					assert_eq!(v11.paras_availability_period                , v12.scheduler_params.paras_availability_period);
332					assert_eq!(v11.max_validators_per_core                  , v12.scheduler_params.max_validators_per_core);
333					assert_eq!(v11.scheduling_lookahead                     , v12.scheduler_params.lookahead);
334					assert_eq!(v11.coretime_cores                           , v12.scheduler_params.num_cores);
335					assert_eq!(v11.on_demand_retries                        , v12.scheduler_params.max_availability_timeouts);
336					assert_eq!(v11.on_demand_queue_max_size                 , v12.scheduler_params.on_demand_queue_max_size);
337					assert_eq!(v11.on_demand_target_queue_utilization       , v12.scheduler_params.on_demand_target_queue_utilization);
338					assert_eq!(v11.on_demand_fee_variability                , v12.scheduler_params.on_demand_fee_variability);
339					assert_eq!(v11.on_demand_base_fee                       , v12.scheduler_params.on_demand_base_fee);
340					assert_eq!(v11.on_demand_ttl                            , v12.scheduler_params.ttl);
341				}; // ; makes this a statement. `rustfmt::skip` cannot be put on an expression.
342			}
343		});
344	}
345
346	// Test that migration doesn't panic in case there are no pending configurations upgrades in
347	// pallet's storage.
348	#[test]
349	fn test_migrate_to_v12_no_pending() {
350		let v11 = V11HostConfiguration::<polkadot_primitives::BlockNumber>::default();
351
352		new_test_ext(Default::default()).execute_with(|| {
353			// Implant the v10 version in the state.
354			v11::ActiveConfig::<Test>::set(Some(v11));
355			// Ensure there are no pending configs.
356			v12::PendingConfigs::<Test>::set(None);
357
358			// Shouldn't fail.
359			migrate_to_v12::<Test>();
360		});
361	}
362}