referrerpolicy=no-referrer-when-downgrade

pallet_validator_collators/
migrations.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// SPDX-License-Identifier: Apache-2.0
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// 	http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Storage migrations of the pallet.
17
18use crate::{
19	CollatorDraw, Config, ExternalValidatorSet, MaxCollators, Pallet, PendingRotation,
20	RotationState, LOG_TARGET,
21};
22use frame_support::{
23	migrations::VersionedMigration,
24	pallet_prelude::*,
25	traits::{StorageVersion, UncheckedOnRuntimeUpgrade},
26};
27
28/// The in-code storage version.
29pub const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
30
31/// Moves [`MaxCollators`] to [`CollatorDraw`] with [`Config::DefaultMaxCollators`] as default.
32pub mod v1 {
33	use super::*;
34	#[cfg(feature = "try-runtime")]
35	use alloc::vec::Vec;
36	use codec::DecodeAll;
37	use frame_support::storage::unhashed;
38
39	/// Rewrites a cap stored as a `u32` as [`CollatorDraw::UpTo`].
40	///
41	/// A stored `Option<u32>` already reads as the [`CollatorDraw`] of the same meaning, so it is
42	/// left as it is.
43	///
44	/// Without a stored cap, [`MaxCollators`] reads [`Config::DefaultMaxCollators`]. When a
45	/// validator set is stored, it sets [`PendingRotation`] to [`RotationState::AwaitingQueue`], so
46	/// the set is drawn again under the default, as [`Pallet::set_max_collators`] does.
47	pub struct VersionUncheckedMigrateV0ToV1<T>(PhantomData<T>);
48
49	/// The cap if the stored bytes are exactly a `u32`.
50	fn u32_cap(raw: &[u8]) -> Option<u32> {
51		u32::decode_all(&mut &raw[..]).ok()
52	}
53
54	impl<T: Config> UncheckedOnRuntimeUpgrade for VersionUncheckedMigrateV0ToV1<T> {
55		fn on_runtime_upgrade() -> Weight {
56			match unhashed::get_raw(&MaxCollators::<T>::hashed_key()) {
57				Some(raw) => match u32_cap(&raw) {
58					Some(cap) => {
59						MaxCollators::<T>::put(CollatorDraw::UpTo(cap));
60						T::DbWeight::get().reads_writes(1, 1)
61					},
62					None => {
63						if CollatorDraw::decode_all(&mut &raw[..]).is_err() {
64							log::error!(target: LOG_TARGET, "MaxCollators does not decode");
65						}
66						T::DbWeight::get().reads(1)
67					},
68				},
69				None if ExternalValidatorSet::<T>::exists() => {
70					PendingRotation::<T>::put(RotationState::AwaitingQueue);
71					T::DbWeight::get().reads_writes(2, 1)
72				},
73				None => T::DbWeight::get().reads(2),
74			}
75		}
76
77		#[cfg(feature = "try-runtime")]
78		fn pre_upgrade() -> Result<Vec<u8>, sp_runtime::TryRuntimeError> {
79			let raw = unhashed::get_raw(&MaxCollators::<T>::hashed_key());
80			let redraw = raw.is_none() && ExternalValidatorSet::<T>::exists();
81			Ok((raw, redraw).encode())
82		}
83
84		#[cfg(feature = "try-runtime")]
85		fn post_upgrade(state: Vec<u8>) -> Result<(), sp_runtime::TryRuntimeError> {
86			let (before, redraw) = <(Option<Vec<u8>>, bool)>::decode(&mut &state[..])
87				.map_err(|_| "the pre-upgrade state does not decode")?;
88			let after = unhashed::get_raw(&MaxCollators::<T>::hashed_key());
89			match before.as_deref().and_then(u32_cap) {
90				Some(cap) => ensure!(
91					MaxCollators::<T>::get() == CollatorDraw::UpTo(cap),
92					"the u32 cap is not kept"
93				),
94				None => ensure!(after == before, "MaxCollators changed in the migration"),
95			}
96			if let Some(after) = after {
97				ensure!(
98					CollatorDraw::decode_all(&mut &after[..]).is_ok(),
99					"MaxCollators does not decode as a CollatorDraw"
100				);
101			}
102			ensure!(
103				!redraw || PendingRotation::<T>::get() == RotationState::AwaitingQueue,
104				"the set is not drawn again under the default cap"
105			);
106			Ok(())
107		}
108	}
109
110	/// [`VersionUncheckedMigrateV0ToV1`], run only at storage version 0.
111	pub type MigrateV0ToV1<T> = VersionedMigration<
112		0,
113		1,
114		VersionUncheckedMigrateV0ToV1<T>,
115		Pallet<T>,
116		<T as frame_system::Config>::DbWeight,
117	>;
118}