referrerpolicy=no-referrer-when-downgrade

pallet_collective/migrations/
v5.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Migration to storage version 5.
19//!
20//! Up to version 4 a proposal was keyed by the hash of the proposed call alone. From version 5
21//! the key is [`Pallet::proposal_hash`](crate::Pallet::proposal_hash), the hash of
22//! `(call, threshold)`. This migration re-keys every active proposal so that on-chain state
23//! satisfies the new derivation.
24
25use super::super::{Config, CostOf, Pallet, ProposalOf, Proposals, Voting, LOG_TARGET};
26use alloc::vec::Vec;
27use core::marker::PhantomData;
28use frame_support::{
29	migrations::VersionedMigration,
30	pallet_prelude::*,
31	traits::{DefensiveTruncateFrom, UncheckedOnRuntimeUpgrade},
32	weights::Weight,
33};
34#[cfg(feature = "try-runtime")]
35use sp_runtime::TryRuntimeError;
36
37/// Re-key every active proposal from `hash(call)` to `hash((call, threshold))`.
38///
39/// The entries in [`ProposalOf`], [`Voting`] and [`CostOf`] are moved under the new key and
40/// [`Proposals`] is rewritten in the same order. An entry that lacks its call or its votes is
41/// left untouched under its old key and logged, since it cannot be re-keyed and removing it
42/// could strand a proposer's deposit.
43///
44/// Use [`MigrateToV5`], which wraps this in a [`VersionedMigration`].
45pub struct UncheckedMigrateToV5<T, I = ()>(PhantomData<(T, I)>);
46
47impl<T: Config<I>, I: 'static> UncheckedOnRuntimeUpgrade for UncheckedMigrateToV5<T, I> {
48	#[cfg(feature = "try-runtime")]
49	fn pre_upgrade() -> Result<Vec<u8>, TryRuntimeError> {
50		let proposals = Proposals::<T, I>::get();
51		let entries: Vec<(T::Hash, <T as Config<I>>::Proposal, u32, u32, bool)> = proposals
52			.iter()
53			.filter_map(|old_hash| {
54				let call = ProposalOf::<T, I>::get(old_hash)?;
55				let votes = Voting::<T, I>::get(old_hash)?;
56				Some((
57					*old_hash,
58					call,
59					votes.threshold,
60					votes.index,
61					CostOf::<T, I>::contains_key(old_hash),
62				))
63			})
64			.collect();
65		Ok((proposals.len() as u32, entries).encode())
66	}
67
68	fn on_runtime_upgrade() -> Weight {
69		let old_hashes = Proposals::<T, I>::get();
70		let mut reads: u64 = 1;
71		let mut writes: u64 = 1;
72		let mut new_hashes = Vec::with_capacity(old_hashes.len());
73
74		for old_hash in old_hashes.iter() {
75			reads = reads.saturating_add(2);
76			let (Some(call), Some(votes)) =
77				(ProposalOf::<T, I>::get(old_hash), Voting::<T, I>::get(old_hash))
78			else {
79				log::warn!(
80					target: LOG_TARGET,
81					"Proposal {:?} has no call or no votes; leaving it under its old key.",
82					old_hash,
83				);
84				new_hashes.push(*old_hash);
85				continue;
86			};
87
88			let new_hash = Pallet::<T, I>::proposal_hash(&call, votes.threshold);
89			new_hashes.push(new_hash);
90			if new_hash == *old_hash {
91				continue;
92			}
93
94			ProposalOf::<T, I>::remove(old_hash);
95			ProposalOf::<T, I>::insert(new_hash, call);
96			Voting::<T, I>::remove(old_hash);
97			Voting::<T, I>::insert(new_hash, votes);
98			writes = writes.saturating_add(4);
99
100			reads = reads.saturating_add(1);
101			if let Some(cost) = CostOf::<T, I>::take(old_hash) {
102				CostOf::<T, I>::insert(new_hash, cost);
103				writes = writes.saturating_add(2);
104			}
105		}
106
107		let migrated = new_hashes.len();
108		Proposals::<T, I>::put(BoundedVec::<_, T::MaxProposals>::defensive_truncate_from(
109			new_hashes,
110		));
111		log::info!(target: LOG_TARGET, "Re-keyed {} proposals to storage version 5.", migrated);
112
113		T::DbWeight::get().reads_writes(reads, writes)
114	}
115
116	#[cfg(feature = "try-runtime")]
117	fn post_upgrade(state: Vec<u8>) -> Result<(), TryRuntimeError> {
118		let (pre_len, entries): (u32, Vec<(T::Hash, <T as Config<I>>::Proposal, u32, u32, bool)>) =
119			Decode::decode(&mut &state[..]).map_err(|_| "pre_upgrade provides a valid state")?;
120
121		let proposals = Proposals::<T, I>::get();
122		ensure!(proposals.len() as u32 == pre_len, "Proposal count changed during migration.");
123
124		for (old_hash, call, threshold, index, had_cost) in entries {
125			let new_hash = Pallet::<T, I>::proposal_hash(&call, threshold);
126			ensure!(proposals.contains(&new_hash), "Re-keyed proposal missing from `Proposals`.");
127			ensure!(
128				ProposalOf::<T, I>::get(new_hash).as_ref() == Some(&call),
129				"Re-keyed proposal missing from `ProposalOf`."
130			);
131			let votes = Voting::<T, I>::get(new_hash).ok_or("Re-keyed proposal has no votes.")?;
132			ensure!(votes.threshold == threshold, "Threshold changed during migration.");
133			ensure!(votes.index == index, "Proposal index changed during migration.");
134			ensure!(
135				CostOf::<T, I>::contains_key(new_hash) == had_cost,
136				"Proposal cost was not moved with the proposal."
137			);
138			if new_hash != old_hash {
139				ensure!(
140					!ProposalOf::<T, I>::contains_key(old_hash) &&
141						!Voting::<T, I>::contains_key(old_hash) &&
142						!CostOf::<T, I>::contains_key(old_hash),
143					"Old key still holds state after migration."
144				);
145			}
146		}
147		Ok(())
148	}
149}
150
151/// [`UncheckedMigrateToV5`] wrapped in a [`VersionedMigration`], so that it runs exactly once
152/// when the on-chain storage version is 4 and bumps it to 5.
153pub type MigrateToV5<T, I> = VersionedMigration<
154	4,
155	5,
156	UncheckedMigrateToV5<T, I>,
157	Pallet<T, I>,
158	<T as frame_system::Config>::DbWeight,
159>;