referrerpolicy=no-referrer-when-downgrade

pallet_election_provider_multi_block/signed/
migrations.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//! Storage migrations of the signed sub-pallet.
19
20use super::*;
21use frame_support::traits::UncheckedOnRuntimeUpgrade;
22
23/// Storage layout before [`v1`].
24mod v0 {
25	use super::*;
26
27	/// [`SubmissionMetadata`] without the `base` field.
28	#[derive(Encode, Decode, DebugNoBound)]
29	pub struct SubmissionMetadata<T: Config> {
30		pub(crate) deposit: BalanceOf<T>,
31		pub(crate) fee: BalanceOf<T>,
32		pub(crate) reward: BalanceOf<T>,
33		pub(crate) claimed_score: ElectionScore,
34		pub(crate) pages: BoundedVec<bool, T::Pages>,
35	}
36
37	#[frame_support::storage_alias]
38	pub(crate) type SubmissionMetadataStorage<T: Config> = StorageDoubleMap<
39		Pallet<T>,
40		Twox64Concat,
41		u32,
42		Twox64Concat,
43		<T as frame_system::Config>::AccountId,
44		SubmissionMetadata<T>,
45	>;
46}
47
48/// Adds the registration base deposit to every [`SubmissionMetadata`] entry.
49///
50/// The base is the held deposit minus the per-page deposit of the stored pages, at the per-page
51/// price at upgrade time. For accounts in [`Invulnerables`], the whole deposit becomes the base.
52/// The base is at least the lowest base deposit for the account's current status, and at most the
53/// held deposit. The base is only read when a submitter changes its pages in the signed
54/// phase. Rewards, slashes and refunds use the held deposit.
55pub mod v1 {
56	use super::*;
57
58	/// Migrates the signed sub-pallet from storage version 0 to 1.
59	pub type MigrateV0ToV1<T> = frame_support::migrations::VersionedMigration<
60		0,
61		1,
62		InnerMigrateV0ToV1<T>,
63		Pallet<T>,
64		<T as frame_system::Config>::DbWeight,
65	>;
66
67	pub struct InnerMigrateV0ToV1<T>(core::marker::PhantomData<T>);
68
69	impl<T: Config> InnerMigrateV0ToV1<T> {
70		fn page_deposit(
71			invulnerables: &[T::AccountId],
72			who: &T::AccountId,
73			pages: &BoundedVec<bool, T::Pages>,
74		) -> BalanceOf<T> {
75			if invulnerables.contains(who) {
76				Zero::zero()
77			} else {
78				T::DepositPerPage::calculate_page_deposit(pages.iter().filter(|x| **x).count())
79			}
80		}
81
82		fn min_base_deposit(invulnerables: &[T::AccountId], who: &T::AccountId) -> BalanceOf<T> {
83			if invulnerables.contains(who) {
84				T::InvulnerableDeposit::get()
85			} else {
86				T::DepositBase::calculate_base_deposit(0)
87			}
88		}
89	}
90
91	impl<T: Config> UncheckedOnRuntimeUpgrade for InnerMigrateV0ToV1<T> {
92		fn on_runtime_upgrade() -> Weight {
93			let invulnerables = Invulnerables::<T>::get();
94			let mut translated: u64 = 0;
95			let mut raised: u64 = 0;
96			SubmissionMetadataStorage::<T>::translate::<v0::SubmissionMetadata<T>, _>(
97				|_round, who, old| {
98					translated.saturating_inc();
99					let page_deposit = Self::page_deposit(&invulnerables, &who, &old.pages);
100					let min_base = Self::min_base_deposit(&invulnerables, &who);
101					let derived = old.deposit.saturating_sub(page_deposit);
102					if derived < min_base {
103						raised.saturating_inc();
104					}
105					let base = derived.max(min_base).min(old.deposit);
106					Some(SubmissionMetadata {
107						deposit: old.deposit,
108						fee: old.fee,
109						reward: old.reward,
110						claimed_score: old.claimed_score,
111						pages: old.pages,
112						base,
113					})
114				},
115			);
116			crate::sublog!(
117				info,
118				"signed",
119				"v0 -> v1: migrated {} submission metadata entries",
120				translated
121			);
122			if raised > 0 {
123				crate::sublog!(
124					warn,
125					"signed",
126					"v0 -> v1: {} entries raised to the lowest base deposit or their held deposit",
127					raised
128				);
129			}
130			T::DbWeight::get().reads_writes(translated.saturating_add(1), translated)
131		}
132
133		#[cfg(feature = "try-runtime")]
134		fn pre_upgrade() -> Result<Vec<u8>, sp_runtime::TryRuntimeError> {
135			let count = v0::SubmissionMetadataStorage::<T>::iter_keys().count();
136			frame_support::ensure!(
137				v0::SubmissionMetadataStorage::<T>::iter().count() == count,
138				"undecodable v0 metadata entry"
139			);
140			Ok((count as u32).encode())
141		}
142
143		#[cfg(feature = "try-runtime")]
144		fn post_upgrade(state: Vec<u8>) -> Result<(), sp_runtime::TryRuntimeError> {
145			let count = u32::decode(&mut &state[..])
146				.map_err(|_| "pre_upgrade state decode failed")? as usize;
147			frame_support::ensure!(
148				SubmissionMetadataStorage::<T>::iter_keys().count() == count,
149				"metadata entry count changed"
150			);
151			let mut decoded = 0usize;
152			for (_round, _who, metadata) in SubmissionMetadataStorage::<T>::iter() {
153				decoded.saturating_inc();
154				frame_support::ensure!(
155					metadata.base <= metadata.deposit,
156					"base is above the held deposit"
157				);
158			}
159			frame_support::ensure!(decoded == count, "undecodable v1 metadata entry");
160			Ok(())
161		}
162	}
163}
164
165#[cfg(test)]
166mod tests {
167	use super::{v1::MigrateV0ToV1, *};
168	use crate::mock::*;
169	use frame_support::{assert_ok, hypothetically, traits::OnRuntimeUpgrade};
170	use sp_core::bounded_vec;
171
172	fn migrate() {
173		#[cfg(feature = "try-runtime")]
174		let state = MigrateV0ToV1::<Runtime>::pre_upgrade().unwrap();
175		MigrateV0ToV1::<Runtime>::on_runtime_upgrade();
176		#[cfg(feature = "try-runtime")]
177		MigrateV0ToV1::<Runtime>::post_upgrade(state).unwrap();
178	}
179
180	#[test]
181	fn migrate_v0_to_v1_derives_base_deposit() {
182		ExtBuilder::signed().build_and_execute(|| {
183			// GIVEN a base deposit that grows with the number of queued submitters.
184			roll_to_signed_open();
185			SignedDepositBaseIncrease::set(10);
186			assert_full_snapshot();
187
188			// AND invulnerable 999 registered first (deposit 7) with one page.
189			SignedPallet::set_invulnerables(RuntimeOrigin::root(), vec![999]).unwrap();
190			assert_ok!(SignedPallet::register(RuntimeOrigin::signed(999), Default::default()));
191			assert_ok!(SignedPallet::submit_page(
192				RuntimeOrigin::signed(999),
193				0,
194				Some(Default::default())
195			));
196
197			// AND 99 registered second (base 15) with two pages.
198			assert_ok!(SignedPallet::register(RuntimeOrigin::signed(99), Default::default()));
199			for page in 0..2 {
200				assert_ok!(SignedPallet::submit_page(
201					RuntimeOrigin::signed(99),
202					page,
203					Some(Default::default())
204				));
205			}
206
207			let expected = Submissions::<Runtime>::metadata_iter(0).collect::<Vec<_>>();
208			assert_eq!(expected.len(), 2);
209			let balances_before = (balances(99), balances(999));
210
211			// AND all entries are stored in the v0 format, plus a lingering entry of an old round.
212			for (who, m) in expected.iter() {
213				v0::SubmissionMetadataStorage::<Runtime>::insert(
214					0,
215					who,
216					v0::SubmissionMetadata::<Runtime> {
217						deposit: m.deposit,
218						fee: m.fee,
219						reward: m.reward,
220						claimed_score: m.claimed_score,
221						pages: m.pages.clone(),
222					},
223				);
224			}
225			v0::SubmissionMetadataStorage::<Runtime>::insert(
226				7,
227				92,
228				v0::SubmissionMetadata::<Runtime> {
229					deposit: 8,
230					fee: 4,
231					reward: 3,
232					claimed_score: Default::default(),
233					pages: bounded_vec![true, true, true],
234				},
235			);
236			StorageVersion::new(0).put::<SignedPallet>();
237
238			hypothetically!({
239				// GIVEN entries holding less than the lowest base deposit (5) plus their per-page
240				// deposit.
241				for (who, deposit) in [(93, 2), (94, 6)] {
242					v0::SubmissionMetadataStorage::<Runtime>::insert(
243						8,
244						who,
245						v0::SubmissionMetadata::<Runtime> {
246							deposit,
247							fee: 4,
248							reward: 3,
249							claimed_score: Default::default(),
250							pages: bounded_vec![true, true, true],
251						},
252					);
253				}
254
255				// WHEN the migration runs.
256				migrate();
257
258				// THEN the base is raised to the lowest base deposit, capped at the held deposit.
259				let base_of = |who| Submissions::<Runtime>::metadata_of(8, who).unwrap().base;
260				assert_eq!((base_of(93), base_of(94)), (2, 5));
261			});
262
263			// WHEN the migration runs.
264			migrate();
265
266			// THEN the current round entries get back the base charged at registration.
267			for (who, m) in expected {
268				assert_eq!(Submissions::<Runtime>::metadata_of(0, who).unwrap(), m);
269			}
270			assert_eq!(Submissions::<Runtime>::metadata_of(0, 999).unwrap().base, 7);
271			assert_eq!(Submissions::<Runtime>::metadata_of(0, 99).unwrap().base, 15);
272
273			// AND the old round entry gets its deposit minus the per-page deposit.
274			let old = Submissions::<Runtime>::metadata_of(7, 92).unwrap();
275			assert_eq!((old.deposit, old.base), (8, 5));
276
277			// AND held balances and the storage version are as expected.
278			assert_eq!((balances(99), balances(999)), balances_before);
279			assert_eq!(SignedPallet::on_chain_storage_version(), 1);
280		});
281	}
282}