referrerpolicy=no-referrer-when-downgrade

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