Skip to content

Commit

Permalink
feat: Update slashing values for mainnet (#4148)
Browse files Browse the repository at this point in the history
Co-authored-by: dandanlen <3168260+dandanlen@users.noreply.github.com>
  • Loading branch information
marcellorigotti and dandanlen authored Nov 1, 2023
1 parent d21557a commit 3fafc45
Show file tree
Hide file tree
Showing 19 changed files with 187 additions and 56 deletions.
8 changes: 6 additions & 2 deletions state-chain/cf-integration-tests/src/mock_runtime.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use chainflip_node::test_account_from_seed;
use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use sp_consensus_grandpa::AuthorityId as GrandpaId;
use sp_runtime::Percent;
use sp_runtime::{Percent, Permill};
use state_chain_runtime::{
chainflip::Offence, constants::common::*, opaque::SessionKeys, test_runner::*, AccountId,
AccountRolesConfig, EmissionsConfig, EthereumVaultConfig, FlipConfig, FundingConfig,
Expand Down Expand Up @@ -118,7 +118,10 @@ impl ExtBuilder {
})
.collect::<Vec<_>>(),
},
flip: FlipConfig { total_issuance: TOTAL_ISSUANCE },
flip: FlipConfig {
total_issuance: TOTAL_ISSUANCE,
daily_slashing_rate: Permill::from_perthousand(1),
},
funding: FundingConfig {
genesis_accounts: self.genesis_accounts.clone(),
redemption_tax: MIN_FUNDING / 2,
Expand Down Expand Up @@ -165,6 +168,7 @@ impl ExtBuilder {
vault_key: Some(ethereum_vault_key),
deployment_block: 0,
keygen_response_timeout: 4,
amount_to_slash: FLIPPERINOS_PER_FLIP,
},
emissions: EmissionsConfig {
current_authority_emission_inflation: CURRENT_AUTHORITY_EMISSION_INFLATION_PERBILL,
Expand Down
10 changes: 7 additions & 3 deletions state-chain/custom-rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1076,6 +1076,7 @@ where

mod test {
use super::*;
use cf_primitives::FLIPPERINOS_PER_FLIP;
use sp_core::H160;

/*
Expand Down Expand Up @@ -1128,8 +1129,8 @@ mod test {
#[test]
fn test_validator_serialization() {
let validator = RpcAccountInfo::validator(RuntimeApiAccountInfoV2 {
balance: 10u128.pow(18),
bond: 10u128.pow(18),
balance: FLIPPERINOS_PER_FLIP,
bond: FLIPPERINOS_PER_FLIP,
last_heartbeat: 0,
reputation_points: 0,
keyholder_epochs: vec![123],
Expand All @@ -1140,7 +1141,10 @@ mod test {
is_qualified: true,
bound_redeem_address: Some(H160::from([1; 20])),
apy_bp: Some(100u32),
restricted_balances: BTreeMap::from_iter(vec![(H160::from([1; 20]), 10u128.pow(18))]),
restricted_balances: BTreeMap::from_iter(vec![(
H160::from([1; 20]),
FLIPPERINOS_PER_FLIP,
)]),
});

insta::assert_display_snapshot!(serde_json::to_value(validator).unwrap());
Expand Down
10 changes: 8 additions & 2 deletions state-chain/node/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ use utilities::clean_hex_address;

use sp_runtime::{
traits::{IdentifyAccount, Verify},
Percent,
Percent, Permill,
};

pub mod berghain;
Expand Down Expand Up @@ -247,6 +247,7 @@ pub fn inner_cf_development_config(
eth_init_agg_key,
ethereum_deployment_block,
devnet::TOTAL_ISSUANCE,
common::DAILY_SLASHING_RATE,
genesis_funding_amount,
min_funding,
devnet::REDEMPTION_TAX,
Expand Down Expand Up @@ -373,6 +374,7 @@ macro_rules! network_spec {
eth_init_agg_key,
ethereum_deployment_block,
TOTAL_ISSUANCE,
DAILY_SLASHING_RATE,
genesis_funding_amount,
min_funding,
REDEMPTION_TAX,
Expand Down Expand Up @@ -430,6 +432,7 @@ fn testnet_genesis(
eth_init_agg_key: [u8; 33],
ethereum_deployment_block: u64,
total_issuance: FlipBalance,
daily_slashing_rate: Permill,
genesis_funding_amount: u128,
minimum_funding: u128,
redemption_tax: u128,
Expand Down Expand Up @@ -560,7 +563,7 @@ fn testnet_genesis(
.map(|x| (x.0.clone(), x.0.clone(), session_keys(x.1.clone(), x.2.clone())))
.collect::<Vec<_>>(),
},
flip: FlipConfig { total_issuance },
flip: FlipConfig { total_issuance, daily_slashing_rate },
funding: FundingConfig {
genesis_accounts: Vec::from_iter(all_accounts.clone()),
minimum_funding,
Expand Down Expand Up @@ -593,17 +596,20 @@ fn testnet_genesis(
vault_key: Some(cf_chains::evm::AggKey::from_pubkey_compressed(eth_init_agg_key)),
deployment_block: ethereum_deployment_block,
keygen_response_timeout: keygen_ceremony_timeout_blocks,
amount_to_slash: FLIPPERINOS_PER_FLIP,
},

polkadot_vault: PolkadotVaultConfig {
vault_key: None,
deployment_block: 0,
keygen_response_timeout: keygen_ceremony_timeout_blocks,
amount_to_slash: FLIPPERINOS_PER_FLIP,
},
bitcoin_vault: BitcoinVaultConfig {
vault_key: None,
deployment_block: 0,
keygen_response_timeout: keygen_ceremony_timeout_blocks,
amount_to_slash: FLIPPERINOS_PER_FLIP,
},
ethereum_threshold_signer: EthereumThresholdSignerConfig {
threshold_signature_response_timeout: threshold_signature_ceremony_timeout_blocks,
Expand Down
4 changes: 4 additions & 0 deletions state-chain/node/src/chain_spec/common.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use cf_primitives::{Asset, AssetAmount, AuthorityCount};
use sp_runtime::Permill;
pub use state_chain_runtime::constants::common::*;
use state_chain_runtime::{chainflip::Offence, BlockNumber, FlipBalance};

Expand Down Expand Up @@ -47,3 +48,6 @@ pub const MINIMUM_SWAP_AMOUNTS: &[(Asset, AssetAmount)] = &[
(Asset::Dot, 2_000_000_000u128), // 1 USD worth of DOT = 0.2 * 10 d.p
(Asset::Btc, 390_000u128), // 1 USD worth of BTC = 0.000039 * 10 d.p
];

/// Daily slashing rate 0.1% (of the bond) for offline authority
pub const DAILY_SLASHING_RATE: Permill = Permill::from_perthousand(1);
4 changes: 3 additions & 1 deletion state-chain/pallets/cf-emissions/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use frame_support::{
};
use frame_system as system;
use scale_info::TypeInfo;
use sp_arithmetic::Permill;
use sp_core::H256;
use sp_runtime::traits::{BlakeTwo256, IdentityLookup};

Expand All @@ -27,6 +28,7 @@ pub type AccountId = u64;
pub const FLIP_TO_BURN: u128 = 10_000;
pub const SUPPLY_UPDATE_INTERVAL: u32 = 10;
pub const TOTAL_ISSUANCE: u128 = 1_000_000_000;
pub const DAILY_SLASHING_RATE: Permill = Permill::from_perthousand(1);

cf_traits::impl_mock_on_account_funded!(AccountId, u128);
type Block = frame_system::mocking::MockBlock<Test>;
Expand Down Expand Up @@ -214,7 +216,7 @@ cf_test_utilities::impl_test_helpers! {
Test,
RuntimeGenesisConfig {
system: Default::default(),
flip: FlipConfig { total_issuance: TOTAL_ISSUANCE },
flip: FlipConfig { total_issuance: TOTAL_ISSUANCE, daily_slashing_rate: DAILY_SLASHING_RATE },
emissions: {
EmissionsConfig {
current_authority_emission_inflation: 2720,
Expand Down
27 changes: 19 additions & 8 deletions state-chain/pallets/cf-flip/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ mod imbalances;
mod on_charge_transaction;

pub mod weights;
use cf_primitives::FlipBalance;
use scale_info::TypeInfo;
pub use weights::WeightInfo;

Expand All @@ -28,7 +29,7 @@ use frame_support::{
pallet_prelude::*,
sp_runtime::{
traits::{AtLeast32BitUnsigned, MaybeSerializeDeserialize, Saturating, Zero},
DispatchError, Percent, Permill, RuntimeDebug,
DispatchError, Permill, RuntimeDebug,
},
};
use frame_system::pallet_prelude::*;
Expand Down Expand Up @@ -107,7 +108,7 @@ pub mod pallet {
#[pallet::getter(fn total_issuance)]
pub type TotalIssuance<T: Config> = StorageValue<_, T::Balance, ValueQuery>;

/// The per-block slashing rate expressed as a proportion of a validator's bond.
/// The per-day slashing rate expressed as a proportion of a validator's bond.
#[pallet::storage]
#[pallet::getter(fn slashing_rate)]
pub type SlashingRate<T: Config> = StorageValue<_, Permill, ValueQuery>;
Expand Down Expand Up @@ -206,12 +207,13 @@ pub mod pallet {
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
pub total_issuance: T::Balance,
pub daily_slashing_rate: Permill,
}

impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
use frame_support::sp_runtime::traits::Zero;
Self { total_issuance: Zero::zero() }
Self { total_issuance: Zero::zero(), daily_slashing_rate: Permill::zero() }
}
}

Expand All @@ -220,7 +222,7 @@ pub mod pallet {
fn build(&self) {
TotalIssuance::<T>::set(self.total_issuance);
OffchainFunds::<T>::set(self.total_issuance);
SlashingRate::<T>::set(Permill::zero());
SlashingRate::<T>::set(self.daily_slashing_rate);
}
}
}
Expand Down Expand Up @@ -596,16 +598,25 @@ where
{
type AccountId = T::AccountId;
type BlockNumber = BlockNumberFor<T>;
type Balance = T::Balance;

fn slash(account_id: &Self::AccountId, blocks: Self::BlockNumber) {
let account = Account::<T>::get(account_id);
let slash_amount = (SlashingRate::<T>::get() * account.bond).saturating_mul(blocks.into());
let slash_amount = Self::calculate_slash_amount(account_id, blocks);
Self::attempt_slash(account_id, account, slash_amount);
}

fn slash_balance(account_id: &Self::AccountId, slash_rate: Percent) {
fn slash_balance(account_id: &Self::AccountId, slash_amount: FlipBalance) {
let account = Account::<T>::get(account_id);
let slash_amount = slash_rate * account.balance;
Self::attempt_slash(account_id, account, slash_amount);
Self::attempt_slash(account_id, account, slash_amount.into());
}

fn calculate_slash_amount(
account_id: &Self::AccountId,
blocks: Self::BlockNumber,
) -> Self::Balance {
let account = Account::<T>::get(account_id);
(SlashingRate::<T>::get() * account.bond / T::BlocksPerDay::get().into())
.saturating_mul(blocks.into())
}
}
2 changes: 1 addition & 1 deletion state-chain/pallets/cf-flip/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ cf_test_utilities::impl_test_helpers! {
Test,
RuntimeGenesisConfig {
system: Default::default(),
flip: FlipConfig { total_issuance: 1_000 },
flip: FlipConfig { total_issuance: 1_000, daily_slashing_rate: Permill::from_perthousand(1) },
transaction_payment: Default::default(),
},
|| {
Expand Down
8 changes: 3 additions & 5 deletions state-chain/pallets/cf-flip/src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#![cfg(test)]

use std::mem;

use super::*;
use crate::{
mock::*, Account, Bonder, Error, FlipAccount, FlipIssuance, FlipSlasher, OffchainFunds,
Reserve, SlashingRate, TotalIssuance,
Expand All @@ -16,6 +15,7 @@ use frame_support::{
use quickcheck::{Arbitrary, Gen, TestResult};
use quickcheck_macros::quickcheck;
use sp_runtime::Permill;
use std::mem;

impl FlipOperation {
pub fn execute(&self) -> bool {
Expand Down Expand Up @@ -116,7 +116,6 @@ impl FlipOperation {
},
// Mint To Reserve
FlipOperation::MintToReserve(amount) => {
use crate::ReserveId;
const TEST_RESERVE: ReserveId = *b"TEST";
let previous_issuance = TotalIssuance::<Test>::get();
let previous_reserve = Reserve::<Test>::try_get(TEST_RESERVE).unwrap_or(0);
Expand All @@ -138,7 +137,6 @@ impl FlipOperation {
},
// Burn From Reserve
FlipOperation::BurnFromReserve(amount) => {
use crate::ReserveId;
const TEST_RESERVE: ReserveId = *b"TEST";
let previous_issuance = TotalIssuance::<Test>::get();
let previous_reserve = Reserve::<Test>::try_get(TEST_RESERVE).unwrap_or(0);
Expand Down Expand Up @@ -291,7 +289,7 @@ impl FlipOperation {
SlashingRate::<Test>::set(*slashing_rate);

let attempted_slash: u128 =
(*slashing_rate * *bond).saturating_mul((*blocks).into());
FlipSlasher::<Test>::calculate_slash_amount(account_id, *blocks);
let expected_slash =
if Account::<Test>::get(account_id).can_be_slashed(attempted_slash) {
attempted_slash
Expand Down
4 changes: 2 additions & 2 deletions state-chain/pallets/cf-funding/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use frame_system::pallet_prelude::BlockNumberFor;
use scale_info::TypeInfo;
use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup},
AccountId32,
AccountId32, Permill,
};
use std::time::Duration;

Expand Down Expand Up @@ -205,7 +205,7 @@ cf_test_utilities::impl_test_helpers! {
Test,
RuntimeGenesisConfig {
system: Default::default(),
flip: FlipConfig { total_issuance: 1_000_000 },
flip: FlipConfig { total_issuance: 1_000_000, daily_slashing_rate: Permill::from_perthousand(1)},
funding: FundingConfig {
genesis_accounts: vec![(CHARLIE, AccountRole::Validator, MIN_FUNDING)],
redemption_tax: REDEMPTION_TAX,
Expand Down
14 changes: 13 additions & 1 deletion state-chain/pallets/cf-reputation/src/mock.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use super::*;
use crate::{self as pallet_cf_reputation, PalletSafeMode};
use cf_primitives::FlipBalance;
use cf_traits::{impl_mock_chainflip, impl_mock_runtime_safe_mode, AccountRoleRegistry, Slashing};
use frame_support::{assert_ok, construct_runtime, parameter_types};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -86,6 +87,7 @@ impl MockSlasher {
impl Slashing for MockSlasher {
type AccountId = ValidatorId;
type BlockNumber = u64;
type Balance = u128;

fn slash(validator_id: &Self::AccountId, _blocks: Self::BlockNumber) {
// Count those slashes
Expand All @@ -94,7 +96,17 @@ impl Slashing for MockSlasher {
});
}

fn slash_balance(_account_id: &Self::AccountId, _amount: sp_runtime::Percent) {
fn slash_balance(account_id: &Self::AccountId, _amount: FlipBalance) {
// Count those slashes
SLASHES.with(|count| {
count.borrow_mut().push(*account_id);
});
}

fn calculate_slash_amount(
_account_id: &Self::AccountId,
_blocks: Self::BlockNumber,
) -> Self::Balance {
unimplemented!()
}
}
Expand Down
5 changes: 3 additions & 2 deletions state-chain/pallets/cf-reputation/src/reporting_adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
//!
//! Hence in this module we simply define [ReportOffence].
use crate::*;
use cf_primitives::FLIPPERINOS_PER_FLIP;
use cf_traits::offence_reporting::OffenceReporter;
use codec::Encode;
use frame_support::{traits::OnKilledAccount, Blake2_128Concat, StorageHasher};
Expand Down Expand Up @@ -99,8 +100,8 @@ where
);

// TODO: Reconsider the slashing rate here. For now we assume we are reporting the node
// for equivocation, and that each report corresponds to equivocation on a single block.
T::Slasher::slash(&offender, 1u32.into());
// for equivocation, and that each report corresponds to 1 FLIP.
T::Slasher::slash_balance(&offender, FLIPPERINOS_PER_FLIP);

Pallet::<T>::report(offence, offender);
Ok(())
Expand Down
10 changes: 5 additions & 5 deletions state-chain/pallets/cf-validator/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@

use super::*;

use pallet_cf_funding::Config as FundingConfig;
use pallet_cf_reputation::Config as ReputationConfig;
use pallet_session::Config as SessionConfig;

use cf_primitives::FLIPPERINOS_PER_FLIP;
use cf_traits::{AccountRoleRegistry, SafeMode, SetSafeMode, VaultStatus};
use frame_benchmarking::{account, benchmarks, whitelisted_caller};
use frame_support::{
Expand All @@ -16,6 +13,9 @@ use frame_support::{
traits::OnNewAccount,
};
use frame_system::{pallet_prelude::OriginFor, Pallet as SystemPallet, RawOrigin};
use pallet_cf_funding::Config as FundingConfig;
use pallet_cf_reputation::Config as ReputationConfig;
use pallet_session::Config as SessionConfig;
use sp_application_crypto::RuntimeAppPublic;
use sp_std::vec;

Expand Down Expand Up @@ -50,7 +50,7 @@ pub fn init_bidders<T: RuntimeConfig>(n: u32, set_id: u32, flip_funded: u128) {
assert_ok!(pallet_cf_funding::Pallet::<T>::funded(
T::EnsureWitnessed::try_successful_origin().unwrap(),
bidder.clone(),
(flip_funded * 10u128.pow(18)).unique_saturated_into(),
(flip_funded * FLIPPERINOS_PER_FLIP).unique_saturated_into(),
Default::default(),
Default::default()
));
Expand Down
Loading

0 comments on commit 3fafc45

Please sign in to comment.