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

NODE-79, bifrost pallets improvements #34

Merged
merged 44 commits into from
Jan 10, 2024
Merged
Show file tree
Hide file tree
Changes from 43 commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
3cd9812
NODE-79, feature: migrate to standard storage version for bfc-staking
alstjd0921 Dec 22, 2023
eb7ed0c
NODE-79, feature: migrate to use new standard storage version for `bf…
alstjd0921 Dec 24, 2023
b2f2cd7
NODE-79, refactor: replace `OrderedSet` with `BTreeMap` & `BTreeSet`
alstjd0921 Dec 24, 2023
13a2dfa
NODE-79, refactor: calculate translate weight info
alstjd0921 Dec 25, 2023
d41f9a2
NODE-79, refactor: Remove redundant code
alstjd0921 Dec 26, 2023
75c4c89
NODE-79, refactor: Remove panic point in `bfc-staking` as much as pos…
alstjd0921 Dec 26, 2023
5f67a96
NODE-79, refactor: use btree set in `SelectedCandidates`, `SelectedFu…
alstjd0921 Dec 26, 2023
067e860
NODE-79, refactor: remove unnecessary path prefix
alstjd0921 Dec 27, 2023
85eec52
NODE-79, refactor: remove unnecessary reverse
alstjd0921 Dec 27, 2023
133785e
NODE-79, refactor: migrate `CandidatePool` to use BoundedBTreeMap
alstjd0921 Dec 27, 2023
fa07dd0
NODE-79, refactor: kill storage `MinTotalSelected`
alstjd0921 Dec 27, 2023
1ef7636
NODE-79, refactor: remove unnecessary path prefix
alstjd0921 Dec 27, 2023
8200f9a
NODE-79, fix: typo
alstjd0921 Dec 27, 2023
220be67
NODE-79, refactor: use iter_mut
alstjd0921 Dec 28, 2023
10084d9
NODE-79, chore: remove deadcode
alstjd0921 Dec 28, 2023
6217647
NODE-79, refactor: use mutate
alstjd0921 Dec 28, 2023
98b6a14
NODE-79, refactor: clone in small range
alstjd0921 Dec 28, 2023
b546eff
NODE-79, refactor: no need to be complicate
alstjd0921 Dec 28, 2023
643186b
NODE-79, refactor: use getter
alstjd0921 Jan 2, 2024
cfede72
NODE-79, fix: should use take instead get
alstjd0921 Jan 2, 2024
bfd90f8
NODE-79, refactor: remove dead code
alstjd0921 Jan 2, 2024
8e78445
NODE-79, refactor: no need to be complicated
alstjd0921 Jan 2, 2024
ecc8739
NODE-79, refactor: use getter
alstjd0921 Jan 4, 2024
1e67f98
NODE-79, refactor: `relay-manager`
alstjd0921 Jan 4, 2024
ae837c7
NODE-79, refactor: .
alstjd0921 Jan 4, 2024
f00108a
NODE-79, refactor: remove redundant
alstjd0921 Jan 4, 2024
434a5ef
NODE-79, fix: revert message
alstjd0921 Jan 4, 2024
d4fa764
NODE-79, refactor: `bfc-staking`
alstjd0921 Jan 4, 2024
6e2a42a
NODE-79, refactor: `relay-manager`
alstjd0921 Jan 4, 2024
5c771ad
NODE-79, refactor: move under util methods
alstjd0921 Jan 4, 2024
e550af2
NODE-79, refactor: impl From<Offence> for EvmOffence
alstjd0921 Jan 4, 2024
ac19f80
NODE-79, refactor: reduce getter call
alstjd0921 Jan 5, 2024
5716010
NODE-79, refactor: remove unnecessary clone
alstjd0921 Jan 5, 2024
a17d423
NODE-79, refactor: `Nominator.initial_nominations` type to BTreeMap
alstjd0921 Jan 5, 2024
34d1b5b
NODE-79, refactor: .
alstjd0921 Jan 5, 2024
81210f7
NODE-79, chore: remove dead code
alstjd0921 Jan 5, 2024
91a404c
NODE-79, fix:
alstjd0921 Jan 9, 2024
1eb013d
NODE-79, fix:
alstjd0921 Jan 9, 2024
e4db94e
NODE-79, test: fit into new storage format
alstjd0921 Jan 9, 2024
4f42c4e
NODE-79, fix: modify if exists else insert
alstjd0921 Jan 9, 2024
e0e754c
NODE-79, refactor: remove dead code
alstjd0921 Jan 9, 2024
7a2942a
NODE-79, fix: condition check on OnRuntimeUpgrade
alstjd0921 Jan 9, 2024
113a9b7
NODE-79, chore: comment
alstjd0921 Jan 9, 2024
d94f0b5
NODE-79, fix: remove duplicate translate in migrations
alstjd0921 Jan 10, 2024
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
1 change: 1 addition & 0 deletions Cargo.lock

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

16 changes: 16 additions & 0 deletions pallets/bfc-offences/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,22 @@ pub type NegativeImbalanceOf<T> = <<T as Config>::Currency as Currency<
<T as frame_system::Config>::AccountId,
>>::NegativeImbalance;

pub(crate) const LOG_TARGET: &'static str = "runtime::bfc-offences";

// syntactic sugar for logging.
#[macro_export]
macro_rules! log {
($level:tt, $patter:expr $(, $values:expr)* $(,)?) => {
log::$level!(
target: crate::LOG_TARGET,
concat!("[{:?}] 💸 ", $patter), <frame_system::Pallet<T>>::block_number() $(, $values)*
)
};
}

/// Used for release versioning upto v2_0_0.
///
/// Obsolete from v3. Keeping around to make encoding/decoding of old migration code easier.
#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
/// A value that represents the current storage version of this pallet.
///
Expand Down
58 changes: 56 additions & 2 deletions pallets/bfc-offences/src/migrations.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,65 @@
use super::*;
use frame_support::{dispatch::Weight, pallet_prelude::*, storage_alias, traits::OnRuntimeUpgrade};

#[storage_alias]
pub type StorageVersion<T: Config> = StorageValue<Pallet<T>, Releases, ValueQuery>;

pub mod v3 {
alstjd0921 marked this conversation as resolved.
Show resolved Hide resolved
use super::*;
#[cfg(feature = "try-runtime")]
use sp_runtime::TryRuntimeError;

pub struct MigrateToV3<T>(PhantomData<T>);

impl<T: Config> OnRuntimeUpgrade for MigrateToV3<T> {
fn on_runtime_upgrade() -> Weight {
let mut weight = Weight::zero();

let current = Pallet::<T>::current_storage_version();
let onchain = StorageVersion::<T>::get();

if current == 3 && onchain == Releases::V2_0_0 {
// migrate to new standard storage version
StorageVersion::<T>::kill();
current.put::<Pallet<T>>();

log!(info, "bfc-offences storage migration passes v3 update ✅");
weight = weight.saturating_add(T::DbWeight::get().reads_writes(1, 2));
} else {
log!(warn, "Skipping v3, should be removed");
weight = weight.saturating_add(T::DbWeight::get().reads(1));
}

weight
}

#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<Vec<u8>, TryRuntimeError> {
ensure!(
StorageVersion::<T>::get() == Releases::V2_0_0,
"Required v2_0_0 before upgrading to v3"
);

Ok(Default::default())
}

#[cfg(feature = "try-runtime")]
fn post_upgrade(_state: Vec<u8>) -> Result<(), TryRuntimeError> {
ensure!(Pallet::<T>::on_chain_storage_version() == 3, "v3 not applied");

ensure!(!StorageVersion::<T>::exists(), "Storage version not migrated correctly");

Ok(())
}
}
}

pub mod v2 {
use super::*;
use frame_support::{pallet_prelude::Weight, traits::Get};

pub fn pre_migrate<T: Config>() -> Result<(), &'static str> {
frame_support::ensure!(
ensure!(
StorageVersion::<T>::get() == Releases::V1_0_0,
"Storage version must match to v1.0.0",
);
Expand All @@ -27,7 +81,7 @@ pub mod v1 {
use frame_support::{pallet_prelude::Weight, traits::Get};

pub fn pre_migrate<T: Config>() -> Result<(), &'static str> {
frame_support::ensure!(
ensure!(
StorageVersion::<T>::get() == Releases::V1_0_0,
"Storage version must match to v1.0.0",
);
Expand Down
20 changes: 10 additions & 10 deletions pallets/bfc-offences/src/pallet/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,33 +61,33 @@ impl<T: Config> OffenceHandler<T::AccountId, BalanceOf<T>> for Pallet<T> {
slash_fraction: Perbill,
bond: BalanceOf<T>,
) -> BalanceOf<T> {
let mut slash_amount = BalanceOf::<T>::zero();
// slash bonds only if activated
if IsSlashActive::<T>::get() {
slash_amount = slash_fraction * bond;
if Self::is_slash_active() {
let slash_amount = slash_fraction * bond;
// slash the validator's reserved self bond
// the slashed imbalance will be reserved to the treasury
T::Slash::on_unbalanced(T::Currency::slash_reserved(stash, slash_amount).0);
Self::deposit_event(Event::Slashed { who: who.clone(), amount: slash_amount });
return slash_amount;
}
slash_amount
BalanceOf::<T>::zero()
}

fn refresh_offences(session_index: SessionIndex) {
for offences in ValidatorOffences::<T>::iter() {
<ValidatorOffences<T>>::iter().for_each(|offences| {
if (session_index - offences.1.latest_offence_session_index)
> OffenceExpirationInSessions::<T>::get()
> Self::offence_expiration_in_sessions()
{
ValidatorOffences::<T>::remove(&offences.0);
<ValidatorOffences<T>>::remove(&offences.0);
dnjscksdn98 marked this conversation as resolved.
Show resolved Hide resolved
}
}
});
}

fn is_offence_count_exceeds(count: u32, tier: TierType) -> bool {
// if offence count exceeds the configured limit
return match tier {
TierType::Full => count > FullMaximumOffenceCount::<T>::get(),
_ => count > BasicMaximumOffenceCount::<T>::get(),
TierType::Full => count > Self::full_maximum_offence_count(),
_ => count > Self::basic_maximum_offence_count(),
};
}
}
28 changes: 17 additions & 11 deletions pallets/bfc-offences/src/pallet/mod.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
mod impls;

use crate::{
BalanceOf, NegativeImbalanceOf, OffenceCount, Releases, ValidatorOffenceInfo, WeightInfo,
migrations, BalanceOf, NegativeImbalanceOf, OffenceCount, ValidatorOffenceInfo, WeightInfo,
};

use bp_staking::TierType;
use frame_support::{
pallet_prelude::*,
traits::{Currency, OnUnbalanced, ReservableCurrency},
traits::{Currency, OnRuntimeUpgrade, OnUnbalanced, ReservableCurrency, StorageVersion},
};
use frame_system::pallet_prelude::*;
use sp_staking::SessionIndex;
Expand All @@ -16,8 +16,12 @@ use sp_staking::SessionIndex;
pub mod pallet {
use super::*;

/// The current storage version.
const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);

/// Pallet for bfc offences
#[pallet::pallet]
#[pallet::storage_version(STORAGE_VERSION)]
dnjscksdn98 marked this conversation as resolved.
Show resolved Hide resolved
pub struct Pallet<T>(_);

/// Configuration trait of this pallet
Expand Down Expand Up @@ -71,10 +75,6 @@ pub mod pallet {
Slashed { who: T::AccountId, amount: BalanceOf<T> },
}

#[pallet::storage]
/// Storage version of the pallet
pub(crate) type StorageVersion<T: Config> = StorageValue<_, Releases, ValueQuery>;

#[pallet::storage]
#[pallet::unbounded]
#[pallet::getter(fn validator_offences)]
Expand Down Expand Up @@ -107,6 +107,13 @@ pub mod pallet {
/// The current activation of validator slashing
pub type IsSlashActive<T: Config> = StorageValue<_, bool, ValueQuery>;

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

alstjd0921 marked this conversation as resolved.
Show resolved Hide resolved
#[pallet::genesis_config]
pub struct GenesisConfig {}

Expand All @@ -120,7 +127,6 @@ pub mod pallet {
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig {
fn build(&self) {
StorageVersion::<T>::put(Releases::V2_0_0);
OffenceExpirationInSessions::<T>::put(T::DefaultOffenceExpirationInSessions::get());
FullMaximumOffenceCount::<T>::put(T::DefaultFullMaximumOffenceCount::get());
BasicMaximumOffenceCount::<T>::put(T::DefaultBasicMaximumOffenceCount::get());
Expand All @@ -140,7 +146,7 @@ pub mod pallet {
origin: OriginFor<T>,
new: SessionIndex,
) -> DispatchResultWithPostInfo {
frame_system::ensure_root(origin)?;
ensure_root(origin)?;
ensure!(new > 0u32, Error::<T>::CannotSetBelowMin);
let old = <OffenceExpirationInSessions<T>>::get();
ensure!(old != new, Error::<T>::NoWritingSameValue);
Expand All @@ -159,7 +165,7 @@ pub mod pallet {
new: OffenceCount,
tier: TierType,
) -> DispatchResultWithPostInfo {
frame_system::ensure_root(origin)?;
ensure_root(origin)?;
ensure!(new > 0u32, Error::<T>::CannotSetBelowMin);
match tier {
TierType::Full => {
Expand Down Expand Up @@ -207,7 +213,7 @@ pub mod pallet {
origin: OriginFor<T>,
is_active: bool,
) -> DispatchResultWithPostInfo {
frame_system::ensure_root(origin)?;
ensure_root(origin)?;
ensure!(is_active != <IsOffenceActive<T>>::get(), Error::<T>::NoWritingSameValue);
<IsOffenceActive<T>>::put(is_active);
Self::deposit_event(Event::OffenceActivationSet { is_active });
Expand All @@ -223,7 +229,7 @@ pub mod pallet {
origin: OriginFor<T>,
is_active: bool,
) -> DispatchResultWithPostInfo {
frame_system::ensure_root(origin)?;
ensure_root(origin)?;
ensure!(is_active != <IsSlashActive<T>>::get(), Error::<T>::NoWritingSameValue);
<IsSlashActive<T>>::put(is_active);
Self::deposit_event(Event::SlashActivationSet { is_active });
Expand Down
Loading