Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rework migration and on runtime upgrade logic execution #1315

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.lock

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

Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@ sp-std = { workspace = true }
[dev-dependencies]
pallet-pot = { path = "../pallet-pot", default-features = false }

frame-executive = { workspace = true }
pallet-balances = { workspace = true }
sp-core = { workspace = true }

[features]
default = ["std"]
std = [
"codec/std",
"frame-executive/std",
"frame-support/std",
"frame-system/std",
"pallet-balances/std",
Expand All @@ -30,6 +32,7 @@ std = [
"sp-std/std",
]
try-runtime = [
"frame-executive/try-runtime",
"frame-support/try-runtime",
"frame-system/try-runtime",
"pallet-balances/try-runtime",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,12 @@ use frame_support::{
};
pub use pallet::*;
use sp_std::cmp::Ordering;
#[cfg(feature = "try-runtime")]
use sp_std::vec::Vec;
pub use weights::*;

pub mod weights;
mod weights;
pub use weights::*;

mod upgrade_init;
pub use upgrade_init::UpgradeInit;

#[cfg(test)]
mod mock;
Expand Down Expand Up @@ -147,23 +146,6 @@ pub mod pallet {
NotBalanced,
}

#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn on_runtime_upgrade() -> Weight {
upgrade_init::on_runtime_upgrade::<T>()
}

#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<Vec<u8>, &'static str> {
upgrade_init::pre_upgrade()
}

#[cfg(feature = "try-runtime")]
fn post_upgrade(state: Vec<u8>) -> Result<(), &'static str> {
upgrade_init::post_upgrade::<T>(state)
}
}

#[pallet::call(weight(T::WeightInfo))]
impl<T: Config> Pallet<T> {
/// Verify if currencies are balanced.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@ use frame_support::{
use sp_core::{ConstU16, H256};

use super::*;
use crate::UpgradeInit;

pub(crate) const FORCE_REBALANCE_ASK_COUNTER: u16 = 0;

type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
type UncheckedExtrinsic =
frame_support::sp_runtime::testing::TestXt<RuntimeCall, frame_system::CheckEra<Test>>;
type Block = frame_support::sp_runtime::testing::Block<UncheckedExtrinsic>;

frame_support::construct_runtime!(
pub struct Test
Expand Down Expand Up @@ -144,3 +146,12 @@ impl pallet_balanced_currency_swap_bridges_initializer::Config for Test {
type ForceRebalanceAskCounter = ConstU16<FORCE_REBALANCE_ASK_COUNTER>;
type WeightInfo = ();
}

pub(crate) type Executive = frame_executive::Executive<
Test,
Block,
frame_system::ChainContext<Test>,
Test,
AllPalletsWithSystem,
UpgradeInit<Test>,
>;
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@ use sp_core::{ConstU16, H256};
pub(crate) const FORCE_REBALANCE_ASK_COUNTER: u16 = 1;

use super::*;
use crate::UpgradeInit;

type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
type UncheckedExtrinsic =
frame_support::sp_runtime::testing::TestXt<RuntimeCall, frame_system::CheckEra<Test>>;
type Block = frame_support::sp_runtime::testing::Block<UncheckedExtrinsic>;

frame_support::construct_runtime!(
pub struct Test
Expand Down Expand Up @@ -144,3 +146,12 @@ impl pallet_balanced_currency_swap_bridges_initializer::Config for Test {
type ForceRebalanceAskCounter = ConstU16<FORCE_REBALANCE_ASK_COUNTER>;
type WeightInfo = ();
}

pub(crate) type Executive = frame_executive::Executive<
Test,
Block,
frame_system::ChainContext<Test>,
Test,
AllPalletsWithSystem,
UpgradeInit<Test>,
>;
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
use frame_support::{
assert_storage_noop,
traits::{Currency, OnRuntimeUpgrade},
};
use frame_support::{assert_storage_noop, traits::Currency};

use crate::{
mock::{new_test_ext_with, v0, v1, v2, with_runtime_lock, *},
Expand Down Expand Up @@ -411,7 +408,7 @@ fn runtime_upgrade() {
assert_eq!(<LastForceRebalanceAskCounter<v1::Test>>::get(), 0);

// Do runtime upgrade hook.
v1::AllPalletsWithoutSystem::on_runtime_upgrade();
v1::Executive::execute_on_runtime_upgrade();

// Verify bridges initialization result.
assert_eq!(
Expand Down Expand Up @@ -457,7 +454,7 @@ fn runtime_upgrade() {
v2::EvmBalances::total_balance(&v2::SwapBridgeEvmToNativePot::account_id());

// Do runtime upgrade hook.
v2::AllPalletsWithoutSystem::on_runtime_upgrade();
v2::Executive::execute_on_runtime_upgrade();

// Verify result.
assert_eq!(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
//! Initialization of the bridge pot accounts on runtime upgrade.

use frame_support::{log, pallet_prelude::*};
use frame_support::{
log::{error, info},
pallet_prelude::*,
traits::OnRuntimeUpgrade,
};
#[cfg(feature = "try-runtime")]
use sp_std::vec::Vec;

Expand All @@ -9,54 +13,54 @@ use crate::{
CURRENT_BRIDGES_INITIALIZER_VERSION,
};

/// Initialize the bridges pot accounts if required.
pub fn on_runtime_upgrade<T: Config>() -> Weight {
let last_initializer_version = <LastInitializerVersion<T>>::get();
let last_force_rebalance_ask_counter = <LastForceRebalanceAskCounter<T>>::get();
let current_force_rebalance_ask_counter = T::ForceRebalanceAskCounter::get();
/// Execute upgrade init.
pub struct UpgradeInit<T>(sp_std::marker::PhantomData<T>);
MOZGIII marked this conversation as resolved.
Show resolved Hide resolved

impl<T: Config> OnRuntimeUpgrade for UpgradeInit<T> {
fn on_runtime_upgrade() -> Weight {
let last_initializer_version = <LastInitializerVersion<T>>::get();
let last_force_rebalance_ask_counter = <LastForceRebalanceAskCounter<T>>::get();
let current_force_rebalance_ask_counter = T::ForceRebalanceAskCounter::get();

let mut weight = T::DbWeight::get().reads(2);

let mut weight = T::DbWeight::get().reads(2);
let is_version_mismatch = last_initializer_version != CURRENT_BRIDGES_INITIALIZER_VERSION;
let is_forced = last_force_rebalance_ask_counter < current_force_rebalance_ask_counter;

let is_version_mismatch = last_initializer_version != CURRENT_BRIDGES_INITIALIZER_VERSION;
let is_forced = last_force_rebalance_ask_counter < current_force_rebalance_ask_counter;
if is_version_mismatch || is_forced {
match Pallet::<T>::initialize() {
Ok(w) => weight.saturating_accrue(w),
Err(err) => error!("error during bridges initialization: {err:?}"),
}

if is_version_mismatch || is_forced {
match Pallet::<T>::initialize() {
Ok(w) => weight.saturating_accrue(w),
Err(err) => log::error!("error during bridges initialization: {err:?}"),
<LastInitializerVersion<T>>::put(CURRENT_BRIDGES_INITIALIZER_VERSION);
<LastForceRebalanceAskCounter<T>>::put(current_force_rebalance_ask_counter);
weight.saturating_accrue(T::DbWeight::get().writes(2));
} else {
info!("Nothing to do. This runtime upgrade probably should be removed");
}

<LastInitializerVersion<T>>::put(CURRENT_BRIDGES_INITIALIZER_VERSION);
<LastForceRebalanceAskCounter<T>>::put(current_force_rebalance_ask_counter);
weight.saturating_accrue(T::DbWeight::get().writes(2));
weight
}

weight
}

/// Check the state before the bridges initialization.
///
/// Panics if anything goes wrong.
#[cfg(feature = "try-runtime")]
pub fn pre_upgrade() -> Result<Vec<u8>, &'static str> {
// Do nothing.
Ok(Vec::new())
}
#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<Vec<u8>, &'static str> {
// Do nothing.
Ok(Vec::new())
}

/// Check the state after the bridges initialization.
///
/// Panics if anything goes wrong.
#[cfg(feature = "try-runtime")]
pub fn post_upgrade<T: Config>(_state: Vec<u8>) -> Result<(), &'static str> {
use frame_support::{storage_root, StateVersion};
#[cfg(feature = "try-runtime")]
fn post_upgrade(_state: Vec<u8>) -> Result<(), &'static str> {
use frame_support::{storage_root, StateVersion};

let storage_root_before = storage_root(StateVersion::V1);
let storage_root_before = storage_root(StateVersion::V1);

if !Pallet::<T>::is_balanced()? {
return Err("currencies are not balanced");
}
if !Pallet::<T>::is_balanced()? {
return Err("currencies are not balanced");
}

assert_eq!(storage_root_before, storage_root(StateVersion::V1));
assert_eq!(storage_root_before, storage_root(StateVersion::V1));

Ok(())
Ok(())
}
}
5 changes: 3 additions & 2 deletions crates/pallet-dummy-precompiles-code/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ frame-system = { workspace = true }
pallet-evm = { workspace = true }
scale-info = { workspace = true, features = ["derive"] }
sp-core = { workspace = true }
sp-std = { workspace = true }

[dev-dependencies]
fp-evm = { workspace = true }
frame-executive = { workspace = true }
hex-literal = { workspace = true }
pallet-balances = { workspace = true, features = ["default"] }
pallet-evm-balances = { workspace = true, features = ["default"] }
Expand All @@ -26,6 +26,7 @@ default = ["std"]
std = [
"codec/std",
"fp-evm/std",
"frame-executive/std",
"frame-support/std",
"frame-system/std",
"pallet-balances/std",
Expand All @@ -35,9 +36,9 @@ std = [
"pallet-timestamp/std",
"scale-info/std",
"sp-core/std",
"sp-std/std",
]
try-runtime = [
"frame-executive/try-runtime",
"frame-support/try-runtime",
"frame-system/try-runtime",
"pallet-balances/try-runtime",
Expand Down
54 changes: 3 additions & 51 deletions crates/pallet-dummy-precompiles-code/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ use frame_support::{
pub use pallet::*;
use sp_core::H160;

mod upgrade_init;
pub use upgrade_init::UpgradeInit;

#[cfg(test)]
mod mock;

Expand All @@ -33,7 +36,6 @@ pub const DUMMY_CODE: &[u8] = &[0x5F, 0x5F, 0xFD];
#[frame_support::pallet]
pub mod pallet {
use frame_support::{pallet_prelude::*, sp_std::vec::Vec};
use frame_system::pallet_prelude::*;

use super::*;

Expand Down Expand Up @@ -76,56 +78,6 @@ pub mod pallet {
<LastForceExecuteAskCounter<T>>::put(T::ForceExecuteAskCounter::get());
}
}

#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn on_runtime_upgrade() -> Weight {
let last_execution_version = Self::last_execution_version();
let last_force_execute_ask_counter = Self::last_force_execute_ask_counter();

let current_force_execute_ask_counter = T::ForceExecuteAskCounter::get();
let mut weight = T::DbWeight::get().reads(2);

let is_version_mismatch = last_execution_version != CURRENT_EXECUTION_VERSION;
let is_forced = last_force_execute_ask_counter < current_force_execute_ask_counter;

if is_version_mismatch || is_forced {
weight.saturating_accrue(Self::precompiles_addresses_add_dummy_code());

<LastExecutionVersion<T>>::put(CURRENT_EXECUTION_VERSION);
<LastForceExecuteAskCounter<T>>::put(current_force_execute_ask_counter);
weight.saturating_accrue(T::DbWeight::get().writes(2));
}

weight
}

#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<Vec<u8>, &'static str> {
// Do nothing.
Ok(Vec::new())
}

#[cfg(feature = "try-runtime")]
fn post_upgrade(_state: Vec<u8>) -> Result<(), &'static str> {
use sp_std::vec::Vec;

let mut not_created_precompiles = Vec::new();

for precompile_address in &T::PrecompilesAddresses::get() {
let code = pallet_evm::AccountCodes::<T>::get(*precompile_address);
if code != DUMMY_CODE {
not_created_precompiles.push(*precompile_address);
}
}

if !not_created_precompiles.is_empty() {
return Err("precompiles not created properly: {:not_created_precompiles}");
}

Ok(())
}
}
}

impl<T: Config> Pallet<T> {
Expand Down
Loading