Skip to content

Commit

Permalink
Fix missing storage migration in pallet-parachain-staking (#2979)
Browse files Browse the repository at this point in the history
* feat: initial commit

* feat: outline the plan

* feat: add fix migration to rococo and litentry

* chore

* chore

* chore: add candidate pool check

* chore

* chore

* chore: fix try-runtime

* chore

* chore: improve try-runtime

* add printing

* more printing

---------

Co-authored-by: Kailai Wang <Kailai.Wang@hotmail.com>
  • Loading branch information
wangminqi and Kailai-Wang authored Aug 9, 2024
1 parent 7c073fc commit 789dc80
Show file tree
Hide file tree
Showing 45 changed files with 446 additions and 98 deletions.
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ sp-blockchain = { git = "https://github.com/paritytech/substrate", branch = "pol
sp-consensus-aura = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42", default-features = false }
sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42", default-features = false }
sp-core-hashing = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42", default-features = false }
sp-debug-derive = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42", default-features = false }
sp-inherents = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42", default-features = false }
sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42", default-features = false }
sp-keystore = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42", default-features = false }
Expand Down
4 changes: 4 additions & 0 deletions runtime/litentry/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ name = 'litentry-parachain-runtime'
version = '0.1.0'

[dependencies]
hex = { workspace = true, optional = true }
hex-literal = { workspace = true }
log = { workspace = true }
parity-scale-codec = { workspace = true }
Expand All @@ -14,6 +15,7 @@ sp-api = { workspace = true }
sp-block-builder = { workspace = true }
sp-consensus-aura = { workspace = true }
sp-core = { workspace = true }
sp-debug-derive = { workspace = true, features = ["force-debug"], optional = true }
sp-inherents = { workspace = true }
sp-io = { workspace = true }
sp-offchain = { workspace = true }
Expand Down Expand Up @@ -221,6 +223,8 @@ std = [
"moonbeam-rpc-primitives-txpool/std",
]
try-runtime = [
"hex",
"sp-debug-derive/std",
"cumulus-pallet-aura-ext/try-runtime",
"cumulus-pallet-dmp-queue/try-runtime",
"cumulus-pallet-parachain-system/try-runtime",
Expand Down
14 changes: 1 addition & 13 deletions runtime/litentry/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,19 +134,7 @@ pub type Executive = frame_executive::Executive<
// It was reverse order before.
// See the comment before collation related pallets too.
AllPalletsWithSystem,
(
migration::ReplacePalletIdentityStorage<Runtime>,
migration::ReplacePalletMultisigStorage<Runtime>,
migration::ReplacePalletProxyStorage<Runtime>,
migration::ReplacePalletVestingStorage<Runtime>,
migration::ReplacePalletBountyStorage<Runtime>,
migration::ReplaceTreasuryStorage<Runtime>,
migration::ReplacePreImageStorage<Runtime>,
migration::ReplaceDemocracyStorage<Runtime>,
migration::ReplaceParachainStakingStorage<Runtime>,
migration::ReplaceBalancesRelatedStorage<Runtime>,
migration::ReplaceBridgeRelatedStorage<Runtime>,
),
(migration::FixParachainStakingStorage<Runtime>,),
>;

impl_opaque_keys! {
Expand Down
22 changes: 22 additions & 0 deletions runtime/litentry/src/migration/P9191/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
pub mod migrate_identity;
pub use migrate_identity::ReplacePalletIdentityStorage;
pub mod migrate_multisig;
pub use migrate_multisig::ReplacePalletMultisigStorage;
pub mod migrate_proxy;
pub use migrate_proxy::ReplacePalletProxyStorage;
pub mod migrate_vesting;
pub use migrate_vesting::ReplacePalletVestingStorage;
pub mod migrate_bridge_related;
pub use migrate_bridge_related::ReplaceBridgeRelatedStorage;
pub mod migrate_parachain_staking;
pub use migrate_parachain_staking::ReplaceParachainStakingStorage;
pub mod migrate_balances_transaction_payment;
pub use migrate_balances_transaction_payment::ReplaceBalancesRelatedStorage;
pub mod migrate_bounty;
pub use migrate_bounty::ReplacePalletBountyStorage;
pub mod migrate_democracy;
pub use migrate_democracy::ReplaceDemocracyStorage;
pub mod migrate_preimage;
pub use migrate_preimage::ReplacePreImageStorage;
pub mod migrate_treasury;
pub use migrate_treasury::ReplaceTreasuryStorage;
15 changes: 15 additions & 0 deletions runtime/litentry/src/migration/migration.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
# Migrate
Under fiels P9191
The migration including the following pallets:
Minor pallet migration
Bounty, Democracy, Identity, Multisig, Preimage, Proxy, Treasury, Vesting

Big pallet migration:
Balances, ParachainStaking
ChainBridge, BridgeTransfer => AssetsHandler

These migration is for the follwoing task
https://github.com/litentry/litentry-parachain/releases/tag/v0.9.19-02
(1) token decimal change from 12 to 18
(2) New token bridge related pallet storage migration.

# MigrateCollatorSelectionIntoParachainStaking
P9100.rs
https://github.com/litentry/litentry-parachain/releases/tag/v0.9.10
Expand Down
192 changes: 170 additions & 22 deletions runtime/litentry/src/migration/mod.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,170 @@
pub mod migrate_identity;
pub use migrate_identity::ReplacePalletIdentityStorage;
pub mod migrate_multisig;
pub use migrate_multisig::ReplacePalletMultisigStorage;
pub mod migrate_proxy;
pub use migrate_proxy::ReplacePalletProxyStorage;
pub mod migrate_vesting;
pub use migrate_vesting::ReplacePalletVestingStorage;
pub mod migrate_bridge_related;
pub use migrate_bridge_related::ReplaceBridgeRelatedStorage;
pub mod migrate_parachain_staking;
pub use migrate_parachain_staking::ReplaceParachainStakingStorage;
pub mod migrate_balances_transaction_payment;
pub use migrate_balances_transaction_payment::ReplaceBalancesRelatedStorage;
pub mod migrate_bounty;
pub use migrate_bounty::ReplacePalletBountyStorage;
pub mod migrate_democracy;
pub use migrate_democracy::ReplaceDemocracyStorage;
pub mod migrate_preimage;
pub use migrate_preimage::ReplacePreImageStorage;
pub mod migrate_treasury;
pub use migrate_treasury::ReplaceTreasuryStorage;
// Copyright 2020-2024 Trust Computing GmbH.
// This file is part of Litentry.
//
// Litentry is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Litentry is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Litentry. If not, see <https://www.gnu.org/licenses/>.
#![allow(clippy::type_complexity)]

use frame_support::{
migration::storage_key_iter,
pallet_prelude::*,
traits::{Get, OnRuntimeUpgrade},
Twox64Concat,
};
use sp_runtime::Saturating;
use sp_std::{convert::From, marker::PhantomData, vec::Vec};

use pallet_parachain_staking::{
BalanceOf, Bond, CandidateInfo, CandidatePool, Delegations, TopDelegations, Total,
};
pub const DECIMAL_CONVERTOR: u128 = 1_000_000u128;

// Fix Parachain Staking Storage for missing migrating TopDelegations total
pub struct FixParachainStakingStorage<T>(PhantomData<T>);

impl<T> OnRuntimeUpgrade for FixParachainStakingStorage<T>
where
T: frame_system::Config + pallet_parachain_staking::Config,
BalanceOf<T>: From<u128>,
{
#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<Vec<u8>, &'static str> {
// Does not matter
Ok(Vec::<u8>::new())
}

// Staked is the snapshot of Total, and remove after used, so no fix
// AtStake, will not be fixed, let's wait extra two round with reward = 0 to make this data
// clean DelayedPayouts, will not fix, let's wait extra two round with reward = 0 to make this
// data clean

// TopDelegations require fix
// CandidateInfo require fix
// CandidatePool require fix
// Total fix
fn on_runtime_upgrade() -> frame_support::weights::Weight {
log::info!(
target: "ReplaceParachainStakingStorage",
"running migration to ParachainStaking TopDelegations"
);
let pallet_prefix: &[u8] = b"ParachainStaking";
let storage_item_prefix: &[u8] = b"TopDelegations";
let mut weight: Weight = frame_support::weights::Weight::zero();

let mut candidates = <CandidatePool<T>>::get();
// remove all bonds
candidates.clear();

// intitialized total
let mut total: BalanceOf<T> = 0u128.into();

for (account, mut delegations) in storage_key_iter::<
T::AccountId,
Delegations<T::AccountId, BalanceOf<T>>,
Twox64Concat,
>(pallet_prefix, storage_item_prefix)
.drain()
{
// Patching the missed total value converting
// This storage is already correpted
let mut collator_delegations_sum: BalanceOf<T> = 0u128.into();
for delegation_bond in delegations.delegations.iter() {
collator_delegations_sum += delegation_bond.amount;
}
delegations.total = collator_delegations_sum;

// Get CandidateInfo of the same collator key
let mut metadata = <CandidateInfo<T>>::get(&account).unwrap();
// Self + delegation total
metadata.total_counted = metadata.bond + delegations.total;

// Fix TopDelegations
<TopDelegations<T>>::insert(&account, delegations);

// Bond use its owner value to determine if equal without checking its amount
// We need to check amount later
candidates.insert(Bond { owner: account.clone(), amount: metadata.total_counted });
// Add total
total = total.saturating_add(metadata.total_counted);

// Fix CandidateInfo
<CandidateInfo<T>>::insert(&account, metadata);

weight += T::DbWeight::get().reads_writes(2, 2);
}

// Fix CandidatePool
candidates.0.sort_by(|a, b| a.amount.cmp(&b.amount));
<CandidatePool<T>>::put(candidates);
// Fix Total
<Total<T>>::put(total);

weight
}

// Check Top Delegation total = sum, collator wise
// Check CandidateInfo total count = self bond + sum of delegation, collator wise
// Check CandidatePool =
// Check Total = sum CandidateInfo total count
#[cfg(feature = "try-runtime")]
fn post_upgrade(_state: Vec<u8>) -> Result<(), &'static str> {
// Check Top Delegation total = sum
// Check CandidateInfo total count = self bond + sum of delegation
// Check Total = sum CandidateInfo total count
let mut total: BalanceOf<T> = 0u128.into();
for (account, delegations) in <TopDelegations<T>>::iter() {
log::info!("TopDelegations Collator: {}", hex::encode(account.encode()));
// Start calculating collator delegation sum
let mut collator_delegations_sum: BalanceOf<T> = 0u128.into();

for delegation_bond in delegations.delegations.iter() {
collator_delegations_sum += delegation_bond.amount;
}

// Check Top Delegation total = sum, collator wise
assert_eq!(collator_delegations_sum, delegations.total);

let metadata = <CandidateInfo<T>>::get(account).unwrap();
// Check CandidateInfo total count = self bond + sum of delegation
assert_eq!(metadata.total_counted, metadata.bond + collator_delegations_sum);

// Collator self + Collator delegations
total += metadata.bond + collator_delegations_sum;

log::info!("Delegations total: {:?}", delegations.total);
log::info!("CandidateInfo Metadata: {:?}", metadata);
}
// Check Total = sum CandidateInfo total count
assert_eq!(total, <Total<T>>::get());

// It is hard to check CandidatePool without iterating vector
// So we just check its sum = Total
// Get all ordered_set of bond
let ordered_set = <CandidatePool<T>>::get();
let mut candidate_pool_sum: BalanceOf<T> = 0u128.into();

// Make sure the number of Order set is correct
assert_eq!(ordered_set.0.len(), 9);
for bond in ordered_set.0.iter() {
candidate_pool_sum += bond.amount;
}

log::info!("CandidatePool: {:?}", ordered_set);

// Check CandidatePool element's amount total = total (self bond + sum of delegation)
log::info!("Total: {:?}", total);
assert_eq!(total, candidate_pool_sum);

Ok(())
}
}
14 changes: 0 additions & 14 deletions runtime/litmus/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,6 @@ pub mod constants;
pub mod weights;
pub mod xcm_config;

pub mod migration;

#[cfg(test)]
mod tests;

Expand Down Expand Up @@ -137,18 +135,6 @@ pub type Executive = frame_executive::Executive<
// it was reverse order before.
// See the comment before collation related pallets too.
AllPalletsWithSystem,
(
migration::ReplacePalletIdentityStorage<Runtime>,
migration::ReplacePalletMultisigStorage<Runtime>,
migration::ReplacePalletProxyStorage<Runtime>,
migration::ReplacePalletVestingStorage<Runtime>,
migration::ReplacePalletBountyStorage<Runtime>,
migration::ReplaceTreasuryStorage<Runtime>,
migration::ReplacePreImageStorage<Runtime>,
migration::ReplaceDemocracyStorage<Runtime>,
migration::ReplaceBalancesRelatedStorage<Runtime>,
migration::ReplaceBridgeRelatedStorage<Runtime>,
),
>;

impl_opaque_keys! {
Expand Down
20 changes: 20 additions & 0 deletions runtime/litmus/src/migration/P9191/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
pub mod migrate_identity;
pub use migrate_identity::ReplacePalletIdentityStorage;
pub mod migrate_multisig;
pub use migrate_multisig::ReplacePalletMultisigStorage;
pub mod migrate_proxy;
pub use migrate_proxy::ReplacePalletProxyStorage;
pub mod migrate_vesting;
pub use migrate_vesting::ReplacePalletVestingStorage;
pub mod migrate_bridge_related;
pub use migrate_bridge_related::ReplaceBridgeRelatedStorage;
pub mod migrate_balances_transaction_payment;
pub use migrate_balances_transaction_payment::ReplaceBalancesRelatedStorage;
pub mod migrate_bounty;
pub use migrate_bounty::ReplacePalletBountyStorage;
pub mod migrate_democracy;
pub use migrate_democracy::ReplaceDemocracyStorage;
pub mod migrate_preimage;
pub use migrate_preimage::ReplacePreImageStorage;
pub mod migrate_treasury;
pub use migrate_treasury::ReplaceTreasuryStorage;
16 changes: 16 additions & 0 deletions runtime/litmus/src/migration/migration.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
# Migrate
Under fiels P9191
The migration including the following pallets:
Minor pallet migration
Bounty, Democracy, Identity, Multisig, Preimage, Proxy, Treasury, Vesting

Big pallet migration:
Balances,
ChainBridge, BridgeTransfer => AssetsHandler

These migration is for the follwoing task
https://github.com/litentry/litentry-parachain/releases/tag/v0.9.19-02
(1) token decimal change from 12 to 18
(2) New token bridge related pallet storage migration.


# RemoveSudoAndStorage
P9115.rs
https://github.com/litentry/litentry-parachain/releases/tag/v0.9.11-1
Expand Down
21 changes: 1 addition & 20 deletions runtime/litmus/src/migration/mod.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1 @@
pub mod migrate_identity;
pub use migrate_identity::ReplacePalletIdentityStorage;
pub mod migrate_multisig;
pub use migrate_multisig::ReplacePalletMultisigStorage;
pub mod migrate_proxy;
pub use migrate_proxy::ReplacePalletProxyStorage;
pub mod migrate_vesting;
pub use migrate_vesting::ReplacePalletVestingStorage;
pub mod migrate_bridge_related;
pub use migrate_bridge_related::ReplaceBridgeRelatedStorage;
pub mod migrate_balances_transaction_payment;
pub use migrate_balances_transaction_payment::ReplaceBalancesRelatedStorage;
pub mod migrate_bounty;
pub use migrate_bounty::ReplacePalletBountyStorage;
pub mod migrate_democracy;
pub use migrate_democracy::ReplaceDemocracyStorage;
pub mod migrate_preimage;
pub use migrate_preimage::ReplacePreImageStorage;
pub mod migrate_treasury;
pub use migrate_treasury::ReplaceTreasuryStorage;

Loading

0 comments on commit 789dc80

Please sign in to comment.