Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

Commit adba2c9

Browse files
liamaharonkianenigmabkchr
authored andcommitted
Fix Society v2 migration (#14421)
* fix society v2 migration * Update frame/society/src/migrations.rs * Update frame/society/src/migrations.rs Co-authored-by: Bastian Köcher <[email protected]> * Update frame/society/src/migrations.rs Co-authored-by: Bastian Köcher <[email protected]> * update for versioned upgrade * fix society v2 migration * remove references to members being sorted from commnets * fix type * fix can_migrate check * add sanity log * fix sanity check * kick ci * kick ci * run tests with --experimental flag * versioned migration cleanup * revert pipeline change * use defensive! * semicolons * defensive and doc comment * address pr comment * feature gate the versioned migration * defensive_unwrap_or * fix test * fix doc comment * change defensive to a log warning * remove can_migrate anti-pattern * Update frame/society/Cargo.toml Co-authored-by: Bastian Köcher <[email protected]> * add experimental feature warning to doc comment * update doc comment * bump ci * kick ci * kick ci * kick ci --------- Co-authored-by: Kian Paimani <[email protected]> Co-authored-by: Bastian Köcher <[email protected]>
1 parent de849d2 commit adba2c9

File tree

5 files changed

+85
-50
lines changed

5 files changed

+85
-50
lines changed

frame/society/Cargo.toml

+4
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,10 @@ sp-io = { version = "23.0.0", path = "../../primitives/io" }
3535

3636
[features]
3737
default = ["std"]
38+
# Enable `VersionedRuntimeUpgrade` for the migrations that is currently still experimental.
39+
experimental = [
40+
"frame-support/experimental"
41+
]
3842
std = [
3943
"codec/std",
4044
"frame-benchmarking?/std",

frame/society/src/lib.rs

+7-7
Original file line numberDiff line numberDiff line change
@@ -466,12 +466,12 @@ pub struct GroupParams<Balance> {
466466

467467
pub type GroupParamsFor<T, I> = GroupParams<BalanceOf<T, I>>;
468468

469+
pub(crate) const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);
470+
469471
#[frame_support::pallet]
470472
pub mod pallet {
471473
use super::*;
472474

473-
const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);
474-
475475
#[pallet::pallet]
476476
#[pallet::storage_version(STORAGE_VERSION)]
477477
#[pallet::without_storage_info]
@@ -1681,8 +1681,8 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
16811681
bids.iter().any(|bid| bid.who == *who)
16821682
}
16831683

1684-
/// Add a member to the sorted members list. If the user is already a member, do nothing.
1685-
/// Can fail when `MaxMember` limit is reached, but in that case it has no side-effects.
1684+
/// Add a member to the members list. If the user is already a member, do nothing. Can fail when
1685+
/// `MaxMember` limit is reached, but in that case it has no side-effects.
16861686
///
16871687
/// Set the `payouts` for the member. NOTE: This *WILL NOT RESERVE THE FUNDS TO MAKE THE
16881688
/// PAYOUT*. Only set this to be non-empty if you already have the funds reserved in the Payouts
@@ -1703,7 +1703,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
17031703
Ok(())
17041704
}
17051705

1706-
/// Add a member back to the sorted members list, setting their `rank` and `payouts`.
1706+
/// Add a member back to the members list, setting their `rank` and `payouts`.
17071707
///
17081708
/// Can fail when `MaxMember` limit is reached, but in that case it has no side-effects.
17091709
///
@@ -1713,8 +1713,8 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
17131713
Self::insert_member(who, rank)
17141714
}
17151715

1716-
/// Add a member to the sorted members list. If the user is already a member, do nothing.
1717-
/// Can fail when `MaxMember` limit is reached, but in that case it has no side-effects.
1716+
/// Add a member to the members list. If the user is already a member, do nothing. Can fail when
1717+
/// `MaxMember` limit is reached, but in that case it has no side-effects.
17181718
fn add_new_member(who: &T::AccountId, rank: Rank) -> DispatchResult {
17191719
Self::insert_member(who, rank)
17201720
}

frame/society/src/migrations.rs

+54-25
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
2020
use super::*;
2121
use codec::{Decode, Encode};
22-
use frame_support::traits::{Instance, OnRuntimeUpgrade};
22+
use frame_support::traits::{Defensive, DefensiveOption, Instance, OnRuntimeUpgrade};
2323

2424
#[cfg(feature = "try-runtime")]
2525
use sp_runtime::TryRuntimeError;
@@ -28,20 +28,18 @@ use sp_runtime::TryRuntimeError;
2828
const TARGET: &'static str = "runtime::society::migration";
2929

3030
/// This migration moves all the state to v2 of Society.
31-
pub struct MigrateToV2<T: Config<I>, I: 'static, PastPayouts>(
31+
pub struct VersionUncheckedMigrateToV2<T: Config<I>, I: 'static, PastPayouts>(
3232
sp_std::marker::PhantomData<(T, I, PastPayouts)>,
3333
);
3434

3535
impl<
3636
T: Config<I>,
3737
I: Instance + 'static,
3838
PastPayouts: Get<Vec<(<T as frame_system::Config>::AccountId, BalanceOf<T, I>)>>,
39-
> OnRuntimeUpgrade for MigrateToV2<T, I, PastPayouts>
39+
> OnRuntimeUpgrade for VersionUncheckedMigrateToV2<T, I, PastPayouts>
4040
{
4141
#[cfg(feature = "try-runtime")]
4242
fn pre_upgrade() -> Result<Vec<u8>, TryRuntimeError> {
43-
ensure!(can_migrate::<T, I>(), "pallet_society: already upgraded");
44-
4543
let current = Pallet::<T, I>::current_storage_version();
4644
let onchain = Pallet::<T, I>::on_chain_storage_version();
4745
ensure!(onchain == 0 && current == 2, "pallet_society: invalid version");
@@ -50,16 +48,16 @@ impl<
5048
}
5149

5250
fn on_runtime_upgrade() -> Weight {
53-
let current = Pallet::<T, I>::current_storage_version();
5451
let onchain = Pallet::<T, I>::on_chain_storage_version();
55-
if current == 2 && onchain == 0 {
56-
from_original::<T, I>(&mut PastPayouts::get())
57-
} else {
52+
if onchain < 2 {
5853
log::info!(
59-
"Running migration with current storage version {:?} / onchain {:?}",
60-
current,
54+
target: TARGET,
55+
"Running migration against onchain version {:?}",
6156
onchain
6257
);
58+
from_original::<T, I>(&mut PastPayouts::get()).defensive_unwrap_or(Weight::MAX)
59+
} else {
60+
log::warn!("Unexpected onchain version: {:?} (expected 0)", onchain);
6361
T::DbWeight::get().reads(1)
6462
}
6563
}
@@ -95,6 +93,19 @@ impl<
9593
}
9694
}
9795

96+
/// [`VersionUncheckedMigrateToV2`] wrapped in a
97+
/// [`frame_support::migrations::VersionedRuntimeUpgrade`], ensuring the migration is only performed
98+
/// when on-chain version is 0.
99+
#[cfg(feature = "experimental")]
100+
pub type VersionCheckedMigrateToV2<T, I, PastPayouts> =
101+
frame_support::migrations::VersionedRuntimeUpgrade<
102+
0,
103+
2,
104+
VersionUncheckedMigrateToV2<T, I, PastPayouts>,
105+
crate::pallet::Pallet<T, I>,
106+
<T as frame_system::Config>::DbWeight,
107+
>;
108+
98109
pub(crate) mod old {
99110
use super::*;
100111
use frame_support::storage_alias;
@@ -180,10 +191,6 @@ pub(crate) mod old {
180191
StorageMap<Pallet<T, I>, Twox64Concat, <T as frame_system::Config>::AccountId, Vote>;
181192
}
182193

183-
pub fn can_migrate<T: Config<I>, I: Instance + 'static>() -> bool {
184-
old::Members::<T, I>::exists()
185-
}
186-
187194
/// Will panic if there are any inconsistencies in the pallet's state or old keys remaining.
188195
pub fn assert_internal_consistency<T: Config<I>, I: Instance + 'static>() {
189196
// Check all members are valid data.
@@ -235,15 +242,7 @@ pub fn assert_internal_consistency<T: Config<I>, I: Instance + 'static>() {
235242

236243
pub fn from_original<T: Config<I>, I: Instance + 'static>(
237244
past_payouts: &mut [(<T as frame_system::Config>::AccountId, BalanceOf<T, I>)],
238-
) -> Weight {
239-
// First check that this is the original state layout. This is easy since the original layout
240-
// contained the Members value, and this value no longer exists in the new layout.
241-
if !old::Members::<T, I>::exists() {
242-
log::warn!(target: TARGET, "Skipping MigrateToV2 migration since it appears unapplicable");
243-
// Already migrated or no data to migrate: Bail.
244-
return T::DbWeight::get().reads(1)
245-
}
246-
245+
) -> Result<Weight, &'static str> {
247246
// Migrate Bids from old::Bids (just a trunctation).
248247
Bids::<T, I>::put(BoundedVec::<_, T::MaxBids>::truncate_from(old::Bids::<T, I>::take()));
249248

@@ -281,6 +280,36 @@ pub fn from_original<T: Config<I>, I: Instance + 'static>(
281280
let record = MemberRecord { index: member_count, rank: 0, strikes, vouching };
282281
Members::<T, I>::insert(&member, record);
283282
MemberByIndex::<T, I>::insert(member_count, &member);
283+
284+
// The founder must be the first member in Society V2. If we find the founder not in index
285+
// zero, we swap it with the first member.
286+
if member == Founder::<T, I>::get().defensive_ok_or("founder must always be set")? &&
287+
member_count > 0
288+
{
289+
let member_to_swap = MemberByIndex::<T, I>::get(0)
290+
.defensive_ok_or("member_count > 0, we must have at least 1 member")?;
291+
// Swap the founder with the first member in MemberByIndex.
292+
MemberByIndex::<T, I>::swap(0, member_count);
293+
// Update the indicies of the swapped member MemberRecords.
294+
Members::<T, I>::mutate(&member, |m| {
295+
if let Some(member) = m {
296+
member.index = 0;
297+
} else {
298+
frame_support::defensive!(
299+
"Member somehow disapeared from storage after it was inserted"
300+
);
301+
}
302+
});
303+
Members::<T, I>::mutate(&member_to_swap, |m| {
304+
if let Some(member) = m {
305+
member.index = member_count;
306+
} else {
307+
frame_support::defensive!(
308+
"Member somehow disapeared from storage after it was queried"
309+
);
310+
}
311+
});
312+
}
284313
member_count.saturating_inc();
285314
}
286315
MemberCount::<T, I>::put(member_count);
@@ -317,7 +346,7 @@ pub fn from_original<T: Config<I>, I: Instance + 'static>(
317346
old::Defender::<T, I>::kill();
318347
let _ = old::DefenderVotes::<T, I>::clear(u32::MAX, None);
319348

320-
T::BlockWeights::get().max_block
349+
Ok(T::BlockWeights::get().max_block)
321350
}
322351

323352
pub fn from_raw_past_payouts<T: Config<I>, I: Instance + 'static>(

frame/society/src/tests.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ fn migration_works() {
7777
.collect::<Vec<_>>();
7878
old::Bids::<Test, ()>::put(bids);
7979

80-
migrations::from_original::<Test, ()>(&mut [][..]);
80+
migrations::from_original::<Test, ()>(&mut [][..]).expect("migration failed");
8181
migrations::assert_internal_consistency::<Test, ()>();
8282

8383
assert_eq!(

frame/support/src/migrations.rs

+19-17
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,8 @@ use sp_core::Get;
2424
use sp_io::{hashing::twox_128, storage::clear_prefix, KillStorageResult};
2525
use sp_std::marker::PhantomData;
2626

27-
#[cfg(feature = "try-runtime")]
28-
use sp_std::vec::Vec;
29-
30-
#[cfg(feature = "experimental")]
31-
use crate::traits::OnRuntimeUpgrade;
32-
27+
/// EXPERIMENTAL: The API of this feature may change.
28+
///
3329
/// Make it easier to write versioned runtime upgrades.
3430
///
3531
/// [`VersionedRuntimeUpgrade`] allows developers to write migrations without worrying about
@@ -57,13 +53,19 @@ use crate::traits::OnRuntimeUpgrade;
5753
/// // OnRuntimeUpgrade implementation...
5854
/// }
5955
///
60-
/// pub type VersionCheckedMigrateV5ToV6<Runtime, Pallet, DbWeight> =
61-
/// VersionedRuntimeUpgrade<5, 6, VersionUncheckedMigrateV5ToV6<Runtime>, Pallet, DbWeight>;
56+
/// pub type VersionCheckedMigrateV5ToV6<T, I> =
57+
/// VersionedRuntimeUpgrade<
58+
/// 5,
59+
/// 6,
60+
/// VersionUncheckedMigrateV5ToV6<T, I>,
61+
/// crate::pallet::Pallet<T, I>,
62+
/// <T as frame_system::Config>::DbWeight
63+
/// >;
6264
///
6365
/// // Migrations tuple to pass to the Executive pallet:
6466
/// pub type Migrations = (
6567
/// // other migrations...
66-
/// VersionCheckedMigrateV5ToV6<Runtime, Balances, RuntimeDbWeight>,
68+
/// VersionCheckedMigrateV5ToV6<T, ()>,
6769
/// // other migrations...
6870
/// );
6971
/// ```
@@ -78,7 +80,7 @@ pub struct VersionedRuntimeUpgrade<const FROM: u16, const TO: u16, Inner, Pallet
7880
#[derive(codec::Encode, codec::Decode)]
7981
pub enum VersionedPostUpgradeData {
8082
/// The migration ran, inner vec contains pre_upgrade data.
81-
MigrationExecuted(Vec<u8>),
83+
MigrationExecuted(sp_std::vec::Vec<u8>),
8284
/// This migration is a noop, do not run post_upgrade checks.
8385
Noop,
8486
}
@@ -93,16 +95,16 @@ pub enum VersionedPostUpgradeData {
9395
impl<
9496
const FROM: u16,
9597
const TO: u16,
96-
Inner: OnRuntimeUpgrade,
98+
Inner: crate::traits::OnRuntimeUpgrade,
9799
Pallet: GetStorageVersion<CurrentStorageVersion = StorageVersion> + PalletInfoAccess,
98100
DbWeight: Get<RuntimeDbWeight>,
99-
> OnRuntimeUpgrade for VersionedRuntimeUpgrade<FROM, TO, Inner, Pallet, DbWeight>
101+
> crate::traits::OnRuntimeUpgrade for VersionedRuntimeUpgrade<FROM, TO, Inner, Pallet, DbWeight>
100102
{
101103
/// Executes pre_upgrade if the migration will run, and wraps the pre_upgrade bytes in
102104
/// [`VersionedPostUpgradeData`] before passing them to post_upgrade, so it knows whether the
103105
/// migration ran or not.
104106
#[cfg(feature = "try-runtime")]
105-
fn pre_upgrade() -> Result<Vec<u8>, sp_runtime::TryRuntimeError> {
107+
fn pre_upgrade() -> Result<sp_std::vec::Vec<u8>, sp_runtime::TryRuntimeError> {
106108
use codec::Encode;
107109
let on_chain_version = Pallet::on_chain_storage_version();
108110
if on_chain_version == FROM {
@@ -152,7 +154,7 @@ impl<
152154
/// the migration ran, and [`VersionedPostUpgradeData::Noop`] otherwise.
153155
#[cfg(feature = "try-runtime")]
154156
fn post_upgrade(
155-
versioned_post_upgrade_data_bytes: Vec<u8>,
157+
versioned_post_upgrade_data_bytes: sp_std::vec::Vec<u8>,
156158
) -> Result<(), sp_runtime::TryRuntimeError> {
157159
use codec::DecodeAll;
158160
match <VersionedPostUpgradeData>::decode_all(&mut &versioned_post_upgrade_data_bytes[..])
@@ -321,7 +323,7 @@ impl<P: Get<&'static str>, DbWeight: Get<RuntimeDbWeight>> frame_support::traits
321323
}
322324

323325
#[cfg(feature = "try-runtime")]
324-
fn pre_upgrade() -> Result<Vec<u8>, sp_runtime::TryRuntimeError> {
326+
fn pre_upgrade() -> Result<sp_std::vec::Vec<u8>, sp_runtime::TryRuntimeError> {
325327
use crate::storage::unhashed::contains_prefixed_key;
326328

327329
let hashed_prefix = twox_128(P::get().as_bytes());
@@ -332,11 +334,11 @@ impl<P: Get<&'static str>, DbWeight: Get<RuntimeDbWeight>> frame_support::traits
332334
P::get()
333335
),
334336
};
335-
Ok(Vec::new())
337+
Ok(sp_std::vec::Vec::new())
336338
}
337339

338340
#[cfg(feature = "try-runtime")]
339-
fn post_upgrade(_state: Vec<u8>) -> Result<(), sp_runtime::TryRuntimeError> {
341+
fn post_upgrade(_state: sp_std::vec::Vec<u8>) -> Result<(), sp_runtime::TryRuntimeError> {
340342
use crate::storage::unhashed::contains_prefixed_key;
341343

342344
let hashed_prefix = twox_128(P::get().as_bytes());

0 commit comments

Comments
 (0)