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

v4 migration #2175

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
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
2 changes: 1 addition & 1 deletion pallets/capacity/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ pub mod pallet {
}

/// the storage version for this pallet
pub const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);
pub const STORAGE_VERSION: StorageVersion = StorageVersion::new(4);

#[pallet::config]
pub trait Config: frame_system::Config {
Expand Down
3 changes: 2 additions & 1 deletion pallets/capacity/src/migration/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@

/// Migration logic for 6 second block updates sideffects to capacity pallet
pub mod v4;
117 changes: 117 additions & 0 deletions pallets/capacity/src/migration/v4.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
use crate::{Config, EpochLength, Pallet};
use frame_system::pallet_prelude::BlockNumberFor;
use frame_support::{
pallet_prelude::{GetStorageVersion, Weight},
traits::{Get, OnRuntimeUpgrade, StorageVersion},
};

const LOG_TARGET: &str = "runtime::capacity";

#[cfg(feature = "try-runtime")]
use sp_std::vec::Vec;

/// The OnRuntimeUpgrade implementation for this storage migration
pub struct MigrationToV4<T>(sp_std::marker::PhantomData<T>);
impl<T> MigrationToV4<T>
where
T: Config,
{
/// Update the epoch length to double the current value
pub fn update_epoch_length() -> Weight {
let new_epoch_length : BlockNumberFor<T> = 14_400u32.into();

EpochLength::<T>::put(new_epoch_length);

T::DbWeight::get().reads_writes(0, 1)
}
}

impl<T: Config> OnRuntimeUpgrade for MigrationToV4<T>
where
T: Config,
{
fn on_runtime_upgrade() -> Weight {
let on_chain_version = Pallet::<T>::on_chain_storage_version(); // 1r

if on_chain_version.ge(&4) {
log::info!(target: LOG_TARGET, "Old Capacity EpochLength migration attempted to run. Please remove");
return T::DbWeight::get().reads(1);

Check warning on line 38 in pallets/capacity/src/migration/v4.rs

View check run for this annotation

Codecov / codecov/patch

pallets/capacity/src/migration/v4.rs#L37-L38

Added lines #L37 - L38 were not covered by tests
}

log::info!(target: LOG_TARGET, "🔄 Capacity EpochLength update migration started");
// The migration started with 1r to get the STORAGE_VERSION
let mut total_weight = T::DbWeight::get().reads_writes(1, 0);

total_weight += Self::update_epoch_length();

StorageVersion::new(4).put::<Pallet<T>>(); // 1 w

total_weight = total_weight.saturating_add(T::DbWeight::get().reads_writes(0, 1));

log::info!(target: LOG_TARGET, "🔄 Capacity EpochLength second update migration finished");

total_weight
}

#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<Vec<u8>, sp_runtime::TryRuntimeError> {
use frame_support::storage::generator::StorageMap;
let on_chain_version = Pallet::<T>::on_chain_storage_version();
if on_chain_version >= 4 {
return Ok(Vec::new());
}

let pallet_prefix = EpochLength::<T>::pallet_prefix();
let storage_prefix = EpochLength::<T>::storage_prefix();
assert_eq!(&b"Capacity"[..], pallet_prefix);
assert_eq!(&b"EpochLength"[..], storage_prefix);
log::info!(target: LOG_TARGET, "Running pre_upgrade...");

asset_eq!(EpochLength::<T>::get(), 7_200u32);

log::info!(target: LOG_TARGET, "Finish pre_upgrade for {:?} records", count);
Ok(())
}

#[cfg(feature = "try-runtime")]
fn post_upgrade(state: Vec<u8>) -> Result<(), sp_runtime::TryRuntimeError> {
use parity_scale_codec::Decode;
let pre_upgrade_count: u32 = Decode::decode(&mut state.as_slice()).unwrap_or_default();
let on_chain_version = Pallet::<T>::on_chain_storage_version();
if on_chain_version >= 4 {
return Ok(());
}

assert_eq!(on_chain_version, crate::pallet::STORAGE_VERSION);

let post_upgrade_epoch_length = EpochLength::<T>::get();
assert_eq!(post_upgrade_epoch_length, 7_200);

log::info!(target: LOG_TARGET, "✅ migration post_upgrade checks passed");
Ok(())
}
}

#[cfg(test)]
mod test {
use super::*;
use crate::tests::mock::{Test as T, *};

type MigrationOf<T> = MigrationToV4<T>;

#[test]
fn migration_works() {
new_test_ext().execute_with(|| {
EpochLength::<T>::put(7_200u32);

assert_eq!(EpochLength::<T>::get(), 7_200u32);

MigrationOf::<T>::on_runtime_upgrade();

let on_chain_version = Pallet::<T>::on_chain_storage_version();
assert_eq!(on_chain_version, crate::pallet::STORAGE_VERSION);

assert_eq!(EpochLength::<T>::get(), 14_400u32);
})
}
}
20 changes: 4 additions & 16 deletions runtime/common/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub type MaxSchemaGrants = ConstU32<30>;
/// up by `pallet_aura` to implement `fn slot_duration()`.
///
/// Change this to adjust the block time.
pub const MILLISECS_PER_BLOCK: u64 = prod_or_testnet_or_local!(12_000, 6_000, 6_000);
pub const MILLISECS_PER_BLOCK: u64 = 6_000;

// NOTE: Currently it is not possible to change the slot duration after the chain has started.
// Attempting to do so will brick block production.
Expand Down Expand Up @@ -64,13 +64,6 @@ pub const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(5);
/// `Operational` extrinsics.
pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);

#[cfg(not(any(feature = "frequency-testnet", feature = "frequency-local")))]
/// We allow for 0.5 of a second of compute with a 12 second average block time.
pub const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND, 0)
.saturating_div(2)
.set_proof_size(cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64);

#[cfg(any(feature = "frequency-testnet", feature = "frequency-local"))]
/// We allow for 2 seconds of compute with a 6 second average block time.
pub const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2),
Expand All @@ -92,7 +85,7 @@ pub type MsaMaxPublicKeysPerMsa = ConstU8<25>;
/// The maximum size of the provider name (in bytes)
pub type MsaMaxProviderNameSize = ConstU32<16>;
/// The number of blocks per virtual bucket
pub type MSAMortalityWindowSize = ConstU32<100>;
pub type MSAMortalityWindowSize = ConstU32<{ 20 * MINUTES }>;
/// The upper limit on total stored signatures.
/// Set to an average of 50 signatures per block
pub type MSAMaxSignaturesStored = ConstU32<50_000>;
Expand Down Expand Up @@ -135,13 +128,8 @@ pub type MinReleaseTransfer = ConstU128<0>;
pub const MAX_RELEASE_SCHEDULES: u32 = 50;
// -end- TimeRelease Pallet ---

#[cfg(any(feature = "frequency-testnet", feature = "frequency-local"))]
// --- Timestamp Pallet ---
pub type MinimumPeriod = ConstU64<0>;

#[cfg(not(any(feature = "frequency-testnet", feature = "frequency-local")))]
// --- Timestamp Pallet ---
pub type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
// -end- Timestamp Pallet ---

// --- Authorship Pallet ---
Expand Down Expand Up @@ -350,7 +338,7 @@ pub type MaxPaginatedPageId = ConstU16<32>;
/// The maximum number of actions in itemized actions
pub type MaxItemizedActionsCount = ConstU32<5>;
/// The number of blocks for Stateful mortality is 24 hours
pub type StatefulMortalityWindowSize = ConstU32<14400>;
pub type StatefulMortalityWindowSize = ConstU32<{ 2 * DAYS }>;
// -end- Stateful Storage Pallet

impl Default for MaxItemizedPageSizeBytes {
Expand Down Expand Up @@ -397,7 +385,7 @@ impl sp_std::fmt::Debug for MaxItemizedBlobSizeBytes {
pub type CapacityMinimumStakingAmount = ConstU128<{ currency::EXISTENTIAL_DEPOSIT }>;
pub type CapacityMinimumTokenBalance = ConstU128<{ currency::DOLLARS }>;
pub type CapacityMaxUnlockingChunks = ConstU32<4>;
pub type CapacityMaxEpochLength = ConstU32<7_200>; // one day, assuming 12 second blocks.
pub type CapacityMaxEpochLength = ConstU32<{ 2 * DAYS }>; // Two days, assuming 6 second blocks.

#[cfg(not(any(feature = "frequency-local", feature = "frequency-no-relay")))]
pub type CapacityUnstakingThawPeriod = ConstU16<30>; // 30 Epochs, or 30 days given the above
Expand Down
2 changes: 1 addition & 1 deletion runtime/common/src/fee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ mod test {
let full_block = WeightToFee::weight_to_fee(&MAXIMUM_BLOCK_WEIGHT);
// A bounded assertion to consider changes in generated extrinsic base weight.
assert!(full_block >= 2 * 150 * CENTS);
assert!(full_block <= 10 * DOLLARS);
assert!(full_block <= 80 * DOLLARS);
}
#[test]
// This function tests that the fee for `ExtrinsicBaseWeight` of weight is correct
Expand Down
20 changes: 8 additions & 12 deletions runtime/frequency/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,10 @@ pub type Executive = frame_executive::Executive<
frame_system::ChainContext<Runtime>,
Runtime,
AllPalletsWithSystem,
(pallet_schemas::migration::v4::MigrateToV4<Runtime>,),
(
pallet_schemas::migration::v4::MigrateToV4<Runtime>,
pallet_capacity::migration::v4::MigrationToV4<Runtime>,
),
>;

pub mod apis;
Expand Down Expand Up @@ -377,7 +380,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("frequency"),
impl_name: create_runtime_str!("frequency"),
authoring_version: 1,
spec_version: 119,
spec_version: 120,
impl_version: 0,
apis: apis::RUNTIME_API_VERSIONS,
transaction_version: 1,
Expand All @@ -391,7 +394,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("frequency-testnet"),
impl_name: create_runtime_str!("frequency"),
authoring_version: 1,
spec_version: 119,
spec_version: 120,
impl_version: 0,
apis: apis::RUNTIME_API_VERSIONS,
transaction_version: 1,
Expand Down Expand Up @@ -964,16 +967,9 @@ impl pallet_passkey::Config for Runtime {
type Currency = Balances;
}

#[cfg(any(
feature = "frequency",
feature = "runtime-benchmarks",
feature = "frequency-lint-check",
))]
#[cfg(any(not(feature = "frequency-no-relay"), feature = "frequency-lint-check"))]
/// Maximum number of blocks simultaneously accepted by the Runtime, not yet included
/// into the relay chain.
const UNINCLUDED_SEGMENT_CAPACITY: u32 = 1;

#[cfg(any(feature = "frequency-testnet", feature = "frequency-local"))]
const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;

#[cfg(any(not(feature = "frequency-no-relay"), feature = "frequency-lint-check"))]
Expand Down Expand Up @@ -1035,7 +1031,7 @@ impl pallet_aura::Config for Runtime {
type AuthorityId = AuraId;
type DisabledValidators = ();
type MaxAuthorities = AuraMaxAuthorities;
type AllowMultipleBlocksPerSlot = ConstBool<{ prod_or_testnet_or_local!(false, true, true) }>;
type AllowMultipleBlocksPerSlot = ConstBool<true>;
type SlotDuration = ConstU64<SLOT_DURATION>;
}

Expand Down
2 changes: 1 addition & 1 deletion scripts/init.sh
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ start-frequency-instant)
;;

start-frequency-interval)
defaultInterval=12
defaultInterval=6
interval=${3-$defaultInterval}
printf "\nBuilding Frequency without relay. Running with interval sealing with interval of $interval seconds...\n"
cargo build --features frequency-no-relay
Expand Down
Loading