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