pallet_validator_collators/
migrations.rs1use 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
28pub const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
30
31pub 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 pub struct VersionUncheckedMigrateV0ToV1<T>(PhantomData<T>);
48
49 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 pub type MigrateV0ToV1<T> = VersionedMigration<
112 0,
113 1,
114 VersionUncheckedMigrateV0ToV1<T>,
115 Pallet<T>,
116 <T as frame_system::Config>::DbWeight,
117 >;
118}