Skip to content

Commit

Permalink
SYS-3801 Adds state migration for summary pallet (#343)
Browse files Browse the repository at this point in the history
Co-authored-by: aventus-ci-agent <ci-agent-bot@aventus.io>
  • Loading branch information
nahuseyoum and aventus-ci-agent committed Dec 19, 2023
1 parent 941dc1d commit 251dbb3
Show file tree
Hide file tree
Showing 8 changed files with 160 additions and 64 deletions.
37 changes: 19 additions & 18 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ lto = "fat"
codegen-units = 1

[workspace.package]
version = "4.1.0"
version = "4.2.0"
authors = ["Aventus systems team"]
homepage = "https://www.aventus.io/"
repository = "https://github.com/Aventus-Network-Services/avn-node-parachain/"
Expand Down
7 changes: 6 additions & 1 deletion pallets/parachain-staking/src/migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,12 @@ impl<T: Config> OnRuntimeUpgrade for EnableEthBridgeWireUp<T> {

#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<Vec<u8>, &'static str> {
assert_eq!(true, storage_with_voting::VotingPeriod::<T>::exists());
let current = Pallet::<T>::current_storage_version();
let onchain = Pallet::<T>::on_chain_storage_version();

if onchain == 2 && current == 3 {
assert_eq!(true, storage_with_voting::VotingPeriod::<T>::exists());
}

Ok(vec![])
}
Expand Down
2 changes: 1 addition & 1 deletion pallets/summary/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ codec = { package = "parity-scale-codec", version = "3.0.0", default-features =
hex = { version = "0.4.3", default-features = false, features = ["alloc"] }
hex-literal = { version = "0.3.4", default-features = false }
scale-info = { version = "2.0", default-features = false, features = ["derive"] }

log = { version = "0.4.17", default-features = false }
sp-avn-common = { default-features = false, path = "../../primitives/avn-common" }
pallet-avn = { path = "../avn", default-features = false }

Expand Down
44 changes: 10 additions & 34 deletions pallets/summary/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ use sp_std::prelude::*;

use avn::BridgeInterfaceNotification;
use core::convert::TryInto;
use frame_support::{dispatch::DispatchResult, ensure, log, traits::Get, weights::Weight};
use frame_support::{
dispatch::DispatchResult, ensure, log, pallet_prelude::StorageVersion, traits::Get,
weights::Weight,
};
use frame_system::{
self as system, ensure_none, ensure_root,
offchain::{SendTransactionTypes, SubmitTransaction},
Expand All @@ -45,6 +48,7 @@ use sp_application_crypto::RuntimeAppPublic;
use sp_core::H256;
use sp_staking::offence::ReportOffence;

pub mod migration;
pub mod offence;
use crate::offence::{create_and_report_summary_offence, SummaryOffence, SummaryOffenceType};

Expand All @@ -64,6 +68,8 @@ const MIN_VOTING_PERIOD: u32 = 100; // 5 MINUTES
const MAX_VOTING_PERIOD: u32 = 28800; // 1 DAY
const DEFAULT_VOTING_PERIOD: u32 = 600; // 30 MINUTES

const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);

pub mod vote;
use crate::vote::*;

Expand Down Expand Up @@ -120,6 +126,7 @@ pub mod pallet {
}

#[pallet::pallet]
#[pallet::storage_version(STORAGE_VERSION)]
#[pallet::generate_store(pub (super) trait Store)]
pub struct Pallet<T>(_);

Expand Down Expand Up @@ -348,6 +355,8 @@ pub mod pallet {
<CurrentSlotsValidator<T>>::put(
maybe_first_validator.expect("Validator is checked for none"),
);

STORAGE_VERSION.put::<Pallet<T>>();
}
}

Expand Down Expand Up @@ -603,39 +612,6 @@ pub mod pallet {
end_voting_if_required::<T>(block_number, &this_validator);
challenge_slot_if_required::<T>(block_number, &this_validator);
}

// Note: this "special" function will run during every runtime upgrade. Any complicated
// migration logic should be done in a separate function so it can be tested
// properly.
fn on_runtime_upgrade() -> Weight {
let mut weight_write_counter = 0;
sp_runtime::runtime_logger::RuntimeLogger::init();
log::info!("ℹ️ Summary pallet data migration invoked");

if Self::schedule_period() == 0u32.into() {
log::info!(
"ℹ️ Updating SchedulePeriod to a default value of {} blocks",
DEFAULT_SCHEDULE_PERIOD
);
weight_write_counter += 1;
<SchedulePeriod<T>>::put(<T as frame_system::Config>::BlockNumber::from(
DEFAULT_SCHEDULE_PERIOD,
));
}

if Self::voting_period() == 0u32.into() {
log::info!(
"ℹ️ Updating VotingPeriod to a default value of {} blocks",
DEFAULT_VOTING_PERIOD
);
weight_write_counter += 1;
<VotingPeriod<T>>::put(<T as frame_system::Config>::BlockNumber::from(
DEFAULT_VOTING_PERIOD,
));
}

return T::DbWeight::get().writes(weight_write_counter as u64)
}
}

#[pallet::validate_unsigned]
Expand Down
102 changes: 102 additions & 0 deletions pallets/summary/src/migration.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// AvN 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 Moonbeam. If not, see <http://www.gnu.org/licenses/>.

use crate::{
Clone, Config, Decode, Encode, EthereumTransactionId, Pallet, RootData, Roots, TypeInfo, H256,
STORAGE_VERSION,
};

use frame_support::{
dispatch::GetStorageVersion,
pallet_prelude::*,
traits::{Get, OnRuntimeUpgrade},
weights::Weight,
};
use sp_std::prelude::*;

#[derive(Clone, Encode, Decode, TypeInfo, MaxEncodedLen)]
pub struct OldRootData<AccountId> {
pub root_hash: H256,
pub added_by: Option<AccountId>,
pub is_validated: bool,
pub is_finalised: bool,
pub tx_id: Option<u64>,
}

pub fn migrate_roots<T: Config>() -> Weight {
let mut consumed_weight: Weight = Weight::from_ref_time(0);
let mut add_weight = |reads, writes, weight: Weight| {
consumed_weight += T::DbWeight::get().reads_writes(reads, writes);
consumed_weight += weight;
};

let mut counter = 0;

Roots::<T>::translate::<OldRootData<T::AccountId>, _>(
|_range, _ingress, old_root_data: OldRootData<T::AccountId>| {
add_weight(1, 1, Weight::from_ref_time(0));

let new_transaction_id: Option<EthereumTransactionId> =
old_root_data.tx_id.map(|value| value.try_into().ok()).flatten();

let new_root_data: RootData<T::AccountId> = RootData::new(
old_root_data.root_hash,
old_root_data.added_by.expect("Existing data will always have an added by"),
new_transaction_id,
);

counter += 1;
Some(new_root_data)
},
);

//Write: [STORAGE_VERSION]
add_weight(0, 1, Weight::from_ref_time(0));
STORAGE_VERSION.put::<Pallet<T>>();

log::info!(
"✅ Summary root data migration completed successfully. {:?} entries migrated",
counter
);

// add a bit extra as safety margin for computation
return consumed_weight + Weight::from_ref_time(25_000_000_000)
}

/// Migration to enable staking pallet
pub struct MigrateSummaryRootData<T>(PhantomData<T>);
impl<T: Config> OnRuntimeUpgrade for MigrateSummaryRootData<T> {
fn on_runtime_upgrade() -> Weight {
let current = Pallet::<T>::current_storage_version();
let onchain = Pallet::<T>::on_chain_storage_version();

if onchain < 1 {
log::info!(
"🚧 Running summary migration. Current storage version: {:?}, on-chain version: {:?}",
current,
onchain
);
return migrate_roots::<T>()
}

Weight::zero()
}

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

#[cfg(feature = "try-runtime")]
fn post_upgrade(_input: Vec<u8>) -> Result<(), &'static str> {
let onchain_version = Pallet::<T>::on_chain_storage_version();
frame_support::ensure!(onchain_version == 1, "must_upgrade");

Ok(())
}
}
Loading

0 comments on commit 251dbb3

Please sign in to comment.