referrerpolicy=no-referrer-when-downgrade

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