referrerpolicy=no-referrer-when-downgrade

pallet_session/migrations/
historical.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
18use core::str;
19use sp_io::hashing::twox_128;
20
21use frame_support::{
22	storage::{generator::StorageValue, StoragePrefixedMap},
23	traits::{
24		Get, GetStorageVersion, PalletInfoAccess, StorageVersion,
25		STORAGE_VERSION_STORAGE_KEY_POSTFIX,
26	},
27	weights::Weight,
28};
29
30use crate::historical as pallet_session_historical;
31
32const LOG_TARGET: &str = "runtime::session_historical";
33
34const OLD_PREFIX: &str = "Session";
35
36/// Migrate the entire storage of this pallet to a new prefix.
37///
38/// This new prefix must be the same as the one set in construct_runtime.
39///
40/// The migration will look into the storage version in order not to trigger a migration on an up
41/// to date storage. Thus the on chain storage version must be less than 1 in order to trigger the
42/// migration.
43pub fn migrate<T: pallet_session_historical::Config, P: GetStorageVersion + PalletInfoAccess>(
44) -> Weight {
45	let new_pallet_name = <P as PalletInfoAccess>::name();
46
47	if new_pallet_name == OLD_PREFIX {
48		log::info!(
49			target: LOG_TARGET,
50			"New pallet name is equal to the old prefix. No migration needs to be done.",
51		);
52		return Weight::zero()
53	}
54
55	let on_chain_storage_version = <P as GetStorageVersion>::on_chain_storage_version();
56	log::info!(
57		target: LOG_TARGET,
58		"Running migration to v1 for session_historical with storage version {:?}",
59		on_chain_storage_version,
60	);
61
62	if on_chain_storage_version < 1 {
63		let storage_prefix = pallet_session_historical::HistoricalSessions::<T>::storage_prefix();
64		frame_support::storage::migration::move_storage_from_pallet(
65			storage_prefix,
66			OLD_PREFIX.as_bytes(),
67			new_pallet_name.as_bytes(),
68		);
69		log_migration("migration", storage_prefix, OLD_PREFIX, new_pallet_name);
70
71		let storage_prefix = pallet_session_historical::StoredRange::<T>::storage_prefix();
72		frame_support::storage::migration::move_storage_from_pallet(
73			storage_prefix,
74			OLD_PREFIX.as_bytes(),
75			new_pallet_name.as_bytes(),
76		);
77		log_migration("migration", storage_prefix, OLD_PREFIX, new_pallet_name);
78
79		StorageVersion::new(1).put::<P>();
80		<T as frame_system::Config>::BlockWeights::get().max_block
81	} else {
82		log::warn!(
83			target: LOG_TARGET,
84			"Attempted to apply migration to v1 but failed because storage version is {:?}",
85			on_chain_storage_version,
86		);
87		Weight::zero()
88	}
89}
90
91/// Some checks prior to migration. This can be linked to
92/// `frame_support::traits::OnRuntimeUpgrade::pre_upgrade` for further testing.
93///
94/// Panics if anything goes wrong.
95pub fn pre_migrate<
96	T: pallet_session_historical::Config,
97	P: GetStorageVersion + PalletInfoAccess,
98>() {
99	let new_pallet_name = <P as PalletInfoAccess>::name();
100
101	let storage_prefix_historical_sessions =
102		pallet_session_historical::HistoricalSessions::<T>::storage_prefix();
103	let storage_prefix_stored_range = pallet_session_historical::StoredRange::<T>::storage_prefix();
104
105	log_migration("pre-migration", storage_prefix_historical_sessions, OLD_PREFIX, new_pallet_name);
106	log_migration("pre-migration", storage_prefix_stored_range, OLD_PREFIX, new_pallet_name);
107
108	if new_pallet_name == OLD_PREFIX {
109		return
110	}
111
112	let new_pallet_prefix = twox_128(new_pallet_name.as_bytes());
113	let storage_version_key = twox_128(STORAGE_VERSION_STORAGE_KEY_POSTFIX);
114
115	let mut new_pallet_prefix_iter = frame_support::storage::KeyPrefixIterator::new(
116		new_pallet_prefix.to_vec(),
117		new_pallet_prefix.to_vec(),
118		|key| Ok(key.to_vec()),
119	);
120
121	// Ensure nothing except the storage_version_key is stored in the new prefix.
122	assert!(new_pallet_prefix_iter.all(|key| key == storage_version_key));
123
124	assert!(<P as GetStorageVersion>::on_chain_storage_version() < 1);
125}
126
127/// Some checks for after migration. This can be linked to
128/// `frame_support::traits::OnRuntimeUpgrade::post_upgrade` for further testing.
129///
130/// Panics if anything goes wrong.
131pub fn post_migrate<
132	T: pallet_session_historical::Config,
133	P: GetStorageVersion + PalletInfoAccess,
134>() {
135	let new_pallet_name = <P as PalletInfoAccess>::name();
136
137	let storage_prefix_historical_sessions =
138		pallet_session_historical::HistoricalSessions::<T>::storage_prefix();
139	let storage_prefix_stored_range = pallet_session_historical::StoredRange::<T>::storage_prefix();
140
141	log_migration(
142		"post-migration",
143		storage_prefix_historical_sessions,
144		OLD_PREFIX,
145		new_pallet_name,
146	);
147	log_migration("post-migration", storage_prefix_stored_range, OLD_PREFIX, new_pallet_name);
148
149	if new_pallet_name == OLD_PREFIX {
150		return
151	}
152
153	// Assert that no `HistoricalSessions` and `StoredRange` storages remains at the old prefix.
154	let old_pallet_prefix = twox_128(OLD_PREFIX.as_bytes());
155	let old_historical_sessions_key =
156		[&old_pallet_prefix, &twox_128(storage_prefix_historical_sessions)[..]].concat();
157	let old_historical_sessions_key_iter = frame_support::storage::KeyPrefixIterator::new(
158		old_historical_sessions_key.to_vec(),
159		old_historical_sessions_key.to_vec(),
160		|_| Ok(()),
161	);
162	assert_eq!(old_historical_sessions_key_iter.count(), 0);
163
164	let old_stored_range_key =
165		[&old_pallet_prefix, &twox_128(storage_prefix_stored_range)[..]].concat();
166	let old_stored_range_key_iter = frame_support::storage::KeyPrefixIterator::new(
167		old_stored_range_key.to_vec(),
168		old_stored_range_key.to_vec(),
169		|_| Ok(()),
170	);
171	assert_eq!(old_stored_range_key_iter.count(), 0);
172
173	// Assert that the `HistoricalSessions` and `StoredRange` storages (if they exist) have been
174	// moved to the new prefix.
175	// NOTE: storage_version_key is already in the new prefix.
176	let new_pallet_prefix = twox_128(new_pallet_name.as_bytes());
177	let new_pallet_prefix_iter = frame_support::storage::KeyPrefixIterator::new(
178		new_pallet_prefix.to_vec(),
179		new_pallet_prefix.to_vec(),
180		|_| Ok(()),
181	);
182	assert!(new_pallet_prefix_iter.count() >= 1);
183
184	assert_eq!(<P as GetStorageVersion>::on_chain_storage_version(), 1);
185}
186
187fn log_migration(stage: &str, storage_prefix: &[u8], old_pallet_name: &str, new_pallet_name: &str) {
188	log::info!(
189		target: LOG_TARGET,
190		"{} prefix of storage '{}': '{}' ==> '{}'",
191		stage,
192		str::from_utf8(storage_prefix).unwrap_or("<Invalid UTF8>"),
193		old_pallet_name,
194		new_pallet_name,
195	);
196}