referrerpolicy=no-referrer-when-downgrade

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