Compare commits
11 Commits
72d6be6e29
...
eb181c7f44
| Author | SHA1 | Date | |
|---|---|---|---|
| eb181c7f44 | |||
| 5307afe352 | |||
| 7edc8935b6 | |||
| 46aa18aafe | |||
| f245879925 | |||
| 101e7103f1 | |||
| d9fa416d93 | |||
| 60b887f812 | |||
| f7f25bd087 | |||
| e2c75ca558 | |||
| 9240f424e1 |
7
Cargo.lock
generated
7
Cargo.lock
generated
@ -1186,7 +1186,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "casper-runtime"
|
||||
version = "3.5.30"
|
||||
version = "3.5.31"
|
||||
dependencies = [
|
||||
"casper-runtime-constants",
|
||||
"frame-benchmarking",
|
||||
@ -3649,13 +3649,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ghost-networks"
|
||||
version = "0.1.13"
|
||||
version = "0.1.16"
|
||||
dependencies = [
|
||||
"frame-benchmarking",
|
||||
"frame-support",
|
||||
"frame-system",
|
||||
"ghost-core-primitives",
|
||||
"ghost-traits",
|
||||
"num-traits",
|
||||
"pallet-balances",
|
||||
"pallet-staking",
|
||||
"pallet-staking-reward-curve",
|
||||
@ -3835,7 +3836,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ghost-slow-clap"
|
||||
version = "0.3.39"
|
||||
version = "0.3.42"
|
||||
dependencies = [
|
||||
"frame-benchmarking",
|
||||
"frame-support",
|
||||
|
||||
@ -69,6 +69,7 @@ bs58 = { version = "0.5.0" }
|
||||
prometheus-parse = { version = "0.2.2" }
|
||||
rustc-hex = { version = "2.1.0", default-features = false }
|
||||
log = { version = "0.4", default-features = false }
|
||||
num-traits = { version = "0.2.17", default-features = false }
|
||||
libsecp256k1 = { version = "0.7", default-features = false }
|
||||
bip39 = { package = "parity-bip39", version = "2.0.1" }
|
||||
sha3 = { version = "0.10", default-features = false }
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ghost-networks"
|
||||
version = "0.1.13"
|
||||
version = "0.1.16"
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
@ -10,6 +10,7 @@ repository.workspace = true
|
||||
[dependencies]
|
||||
scale-info = { workspace = true, features = ["derive"] }
|
||||
codec = { workspace = true, features = ["max-encoded-len"] }
|
||||
num-traits = { workspace = true }
|
||||
|
||||
frame-benchmarking = { workspace = true, optional = true }
|
||||
frame-support = { workspace = true }
|
||||
@ -30,6 +31,7 @@ default = ["std"]
|
||||
std = [
|
||||
"scale-info/std",
|
||||
"codec/std",
|
||||
"num-traits/std",
|
||||
"frame-support/std",
|
||||
"frame-system/std",
|
||||
"frame-benchmarking?/std",
|
||||
|
||||
@ -21,9 +21,11 @@ pub use ghost_traits::networks::{
|
||||
NetworkDataBasicHandler, NetworkDataInspectHandler, NetworkDataMutateHandler,
|
||||
};
|
||||
|
||||
mod math;
|
||||
mod weights;
|
||||
|
||||
pub use crate::weights::WeightInfo;
|
||||
use math::MulDiv;
|
||||
pub use module::*;
|
||||
|
||||
#[cfg(any(feature = "runtime-benchmarks", test))]
|
||||
@ -73,7 +75,17 @@ pub struct BridgedInflationCurve<RewardCurve, T>(core::marker::PhantomData<(Rewa
|
||||
impl<Balance, RewardCurve, T> pallet_staking::EraPayout<Balance>
|
||||
for BridgedInflationCurve<RewardCurve, T>
|
||||
where
|
||||
Balance: Default + AtLeast32BitUnsigned + Clone + Copy + From<u128>,
|
||||
Balance: Default
|
||||
+ Copy
|
||||
+ From<BalanceOf<T>>
|
||||
+ AtLeast32BitUnsigned
|
||||
+ num_traits::ops::wrapping::WrappingAdd
|
||||
+ num_traits::ops::overflowing::OverflowingAdd
|
||||
+ sp_std::ops::AddAssign
|
||||
+ sp_std::ops::Not<Output = Balance>
|
||||
+ sp_std::ops::Shl<Output = Balance>
|
||||
+ sp_std::ops::Shr<Output = Balance>
|
||||
+ sp_std::ops::BitAnd<Balance, Output = Balance>,
|
||||
RewardCurve: Get<&'static PiecewiseLinear<'static>>,
|
||||
T: Config,
|
||||
{
|
||||
@ -82,30 +94,27 @@ where
|
||||
total_issuance: Balance,
|
||||
_era_duration_in_millis: u64,
|
||||
) -> (Balance, Balance) {
|
||||
let piecewise_linear = RewardCurve::get();
|
||||
let bridge_adjustment = BridgedImbalance::<T>::get();
|
||||
let reward_curve = RewardCurve::get();
|
||||
let bridged_imbalance = BridgedImbalance::<T>::get();
|
||||
let accumulated_commission = AccumulatedCommission::<T>::get();
|
||||
|
||||
let bridged_out: u128 = bridge_adjustment.bridged_out.try_into().unwrap_or_default();
|
||||
let bridged_in: u128 = bridge_adjustment.bridged_in.try_into().unwrap_or_default();
|
||||
let accumulated_commission: u128 = accumulated_commission.try_into().unwrap_or_default();
|
||||
|
||||
let accumulated_balance = Balance::from(accumulated_commission);
|
||||
let adjusted_issuance = match bridged_out > bridged_in {
|
||||
true => total_issuance.saturating_add(Balance::from(bridged_out - bridged_in)),
|
||||
false => total_issuance.saturating_sub(Balance::from(bridged_in - bridged_out)),
|
||||
};
|
||||
let accumulated_commission: Balance = accumulated_commission.into();
|
||||
let adjusted_issuance: Balance = total_issuance
|
||||
.saturating_add(bridged_imbalance.bridged_out.into())
|
||||
.saturating_sub(bridged_imbalance.bridged_in.into());
|
||||
|
||||
NullifyNeeded::<T>::set(true);
|
||||
|
||||
match piecewise_linear
|
||||
.calculate_for_fraction_times_denominator(total_staked, adjusted_issuance)
|
||||
.checked_mul(&accumulated_balance)
|
||||
.and_then(|product| product.checked_div(&adjusted_issuance))
|
||||
{
|
||||
Some(payout) => (payout, accumulated_balance.saturating_sub(payout)),
|
||||
None => (Balance::default(), Balance::default()),
|
||||
}
|
||||
let estimated_reward =
|
||||
reward_curve.calculate_for_fraction_times_denominator(total_staked, adjusted_issuance);
|
||||
let payout = MulDiv::<Balance>::calculate(
|
||||
estimated_reward,
|
||||
accumulated_commission,
|
||||
adjusted_issuance,
|
||||
);
|
||||
let rest_payout = accumulated_commission.saturating_sub(payout);
|
||||
|
||||
(payout, rest_payout)
|
||||
}
|
||||
}
|
||||
|
||||
@ -779,6 +788,7 @@ impl<T: Config> NetworkDataMutateHandler<NetworkData, BalanceOf<T>> for Pallet<T
|
||||
|
||||
fn nullify_commission() {
|
||||
AccumulatedCommission::<T>::set(Default::default());
|
||||
BridgedImbalance::<T>::set(Default::default());
|
||||
}
|
||||
|
||||
fn trigger_nullification() {
|
||||
|
||||
135
pallets/networks/src/math.rs
Normal file
135
pallets/networks/src/math.rs
Normal file
@ -0,0 +1,135 @@
|
||||
use crate::AtLeast32BitUnsigned;
|
||||
|
||||
pub struct MulDiv<Balance>(core::marker::PhantomData<Balance>);
|
||||
impl<Balance> MulDiv<Balance>
|
||||
where
|
||||
Balance: Copy
|
||||
+ AtLeast32BitUnsigned
|
||||
+ num_traits::ops::wrapping::WrappingAdd
|
||||
+ num_traits::ops::overflowing::OverflowingAdd
|
||||
+ sp_std::ops::AddAssign
|
||||
+ sp_std::ops::Not<Output = Balance>
|
||||
+ sp_std::ops::Shl<Output = Balance>
|
||||
+ sp_std::ops::Shr<Output = Balance>
|
||||
+ sp_std::ops::BitAnd<Balance, Output = Balance>,
|
||||
{
|
||||
|
||||
fn zero(&self) -> Balance {
|
||||
0u32.into()
|
||||
}
|
||||
|
||||
fn one(&self) -> Balance {
|
||||
1u32.into()
|
||||
}
|
||||
|
||||
fn bit_shift(&self) -> Balance {
|
||||
let u32_shift: u32 = core::mem::size_of::<Balance>()
|
||||
.saturating_mul(4)
|
||||
.try_into()
|
||||
.unwrap_or_default();
|
||||
u32_shift.into()
|
||||
}
|
||||
|
||||
fn least_significant_bits(&self, a: Balance) -> Balance {
|
||||
a & ((self.one() << self.bit_shift()) - self.one())
|
||||
}
|
||||
|
||||
fn most_significant_bits(&self, a: Balance) -> Balance {
|
||||
a >> self.bit_shift()
|
||||
}
|
||||
|
||||
fn two_complement(&self, a: Balance) -> Balance {
|
||||
(!a).wrapping_add(&self.one())
|
||||
}
|
||||
|
||||
fn adjusted_ratio(&self, a: Balance) -> Balance {
|
||||
(self.two_complement(a) / a).wrapping_add(&self.one())
|
||||
}
|
||||
|
||||
fn modulo(&self, a: Balance) -> Balance {
|
||||
self.two_complement(a) % a
|
||||
}
|
||||
|
||||
fn overflow_resistant_addition(
|
||||
&self,
|
||||
a0: Balance,
|
||||
a1: Balance,
|
||||
b0: Balance,
|
||||
b1: Balance,
|
||||
) -> (Balance, Balance) {
|
||||
let (r0, overflow) = a0.overflowing_add(&b0);
|
||||
let overflow: Balance = overflow.then(|| 1u32).unwrap_or_default().into();
|
||||
let r1 = a1.wrapping_add(&b1).wrapping_add(&overflow);
|
||||
(r0, r1)
|
||||
}
|
||||
|
||||
fn overflow_resistant_multiplication(&self, a: Balance, b: Balance) -> (Balance, Balance) {
|
||||
let (a0, a1) = (
|
||||
self.least_significant_bits(a),
|
||||
self.most_significant_bits(a),
|
||||
);
|
||||
let (b0, b1) = (
|
||||
self.least_significant_bits(b),
|
||||
self.most_significant_bits(b),
|
||||
);
|
||||
let (x, y) = (a1 * b0, b1 * a0);
|
||||
|
||||
let (r0, r1) = (a0 * b0, a1 * b1);
|
||||
let (r0, r1) = self.overflow_resistant_addition(
|
||||
r0,
|
||||
r1,
|
||||
self.least_significant_bits(x) << self.bit_shift(),
|
||||
self.most_significant_bits(x),
|
||||
);
|
||||
let (r0, r1) = self.overflow_resistant_addition(
|
||||
r0,
|
||||
r1,
|
||||
self.least_significant_bits(y) << self.bit_shift(),
|
||||
self.most_significant_bits(y),
|
||||
);
|
||||
|
||||
(r0, r1)
|
||||
}
|
||||
|
||||
fn overflow_resistant_division(
|
||||
&self,
|
||||
mut a0: Balance,
|
||||
mut a1: Balance,
|
||||
b: Balance,
|
||||
) -> (Balance, Balance) {
|
||||
if b == self.one() {
|
||||
return (a0, a1);
|
||||
}
|
||||
|
||||
let zero: Balance = 0u32.into();
|
||||
let (q, r) = (self.adjusted_ratio(b), self.modulo(b));
|
||||
let (mut x0, mut x1) = (zero, zero);
|
||||
|
||||
while a1 != zero {
|
||||
let (t0, t1) = self.overflow_resistant_multiplication(a1, q);
|
||||
let (new_x0, new_x1) = self.overflow_resistant_addition(x0, x1, t0, t1);
|
||||
x0 = new_x0;
|
||||
x1 = new_x1;
|
||||
|
||||
let (t0, t1) = self.overflow_resistant_multiplication(a1, r);
|
||||
let (new_a0, new_a1) = self.overflow_resistant_addition(t0, t1, a0, zero);
|
||||
a0 = new_a0;
|
||||
a1 = new_a1;
|
||||
}
|
||||
|
||||
self.overflow_resistant_addition(x0, x1, a0 / b, zero)
|
||||
}
|
||||
|
||||
fn mul_div(&self, a: Balance, b: Balance, c: Balance) -> Balance {
|
||||
let (t0, t1) = self.overflow_resistant_multiplication(a, b);
|
||||
self.overflow_resistant_division(t0, t1, c).0
|
||||
}
|
||||
|
||||
pub fn calculate(a: Balance, b: Balance, c: Balance) -> Balance {
|
||||
let inner = MulDiv(core::marker::PhantomData);
|
||||
if c == inner.zero() {
|
||||
return c;
|
||||
}
|
||||
inner.mul_div(a, b, c)
|
||||
}
|
||||
}
|
||||
@ -1295,8 +1295,10 @@ fn accumulated_commission_could_be_nullified() {
|
||||
#[test]
|
||||
fn bridged_inlation_reward_works() {
|
||||
ExtBuilder::build().execute_with(|| {
|
||||
let amount: u128 = 1337 * 1_000_000_000;
|
||||
let commission: u128 = amount / 100; // 1% commission
|
||||
let amount_full: u128 = 1337 * 1_000_000_000;
|
||||
let commission: u128 = amount_full / 100; // 1% commission
|
||||
let amount: u128 = amount_full - commission;
|
||||
|
||||
let total_staked_ideal: u128 = 69;
|
||||
let total_staked_not_ideal: u128 = 68;
|
||||
let total_issuance: u128 = 100;
|
||||
@ -1538,8 +1540,10 @@ fn bridged_inlation_reward_works() {
|
||||
#[test]
|
||||
fn bridged_inflation_era_payout_triggers_need_of_nullification() {
|
||||
ExtBuilder::build().execute_with(|| {
|
||||
let amount: u128 = 1337 * 1_000_000_000;
|
||||
let commission: u128 = amount / 100; // 1% commission
|
||||
let amount_full: u128 = 1337 * 1_000_000_000;
|
||||
let commission: u128 = amount_full / 100; // 1% commission
|
||||
let amount: u128 = amount_full - commission;
|
||||
|
||||
let total_staked_ideal: u128 = 69;
|
||||
let total_issuance: u128 = 100;
|
||||
|
||||
@ -1563,10 +1567,333 @@ fn bridged_inflation_era_payout_triggers_need_of_nullification() {
|
||||
#[test]
|
||||
fn trigger_nullification_works_as_expected() {
|
||||
ExtBuilder::build().execute_with(|| {
|
||||
let commission: u128 = 69;
|
||||
let imbalance = BridgeAdjustment {
|
||||
bridged_in: 1337u128,
|
||||
bridged_out: 420u128,
|
||||
};
|
||||
|
||||
assert_eq!(AccumulatedCommission::<Test>::get(), 0);
|
||||
assert_eq!(BridgedImbalance::<Test>::get(), BridgeAdjustment::default());
|
||||
|
||||
AccumulatedCommission::<Test>::set(commission);
|
||||
BridgedImbalance::<Test>::set(imbalance.clone());
|
||||
|
||||
assert_eq!(AccumulatedCommission::<Test>::get(), commission);
|
||||
assert_eq!(BridgedImbalance::<Test>::get(), imbalance);
|
||||
|
||||
assert_eq!(NullifyNeeded::<Test>::get(), false);
|
||||
GhostNetworks::trigger_nullification();
|
||||
assert_eq!(NullifyNeeded::<Test>::get(), true);
|
||||
GhostNetworks::trigger_nullification();
|
||||
assert_eq!(NullifyNeeded::<Test>::get(), false);
|
||||
assert_eq!(AccumulatedCommission::<Test>::get(), 0);
|
||||
assert_eq!(BridgedImbalance::<Test>::get(), BridgeAdjustment::default());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_substrate_guarantees_not_to_overflow_u128() {
|
||||
ExtBuilder::build().execute_with(|| {
|
||||
let reward_curve = RewardCurve::get();
|
||||
let mut n: u128 = 69;
|
||||
let mut d: u128 = 100;
|
||||
|
||||
loop {
|
||||
n = match n.checked_mul(1_000) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
d = match d.checked_mul(1_000) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
assert_eq!(
|
||||
reward_curve.calculate_for_fraction_times_denominator(n, d),
|
||||
d
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_substrate_guarantees_not_to_overflow_u64() {
|
||||
ExtBuilder::build().execute_with(|| {
|
||||
let reward_curve = RewardCurve::get();
|
||||
let mut n: u64 = 69;
|
||||
let mut d: u64 = 100;
|
||||
|
||||
loop {
|
||||
n = match n.checked_mul(1_000) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
d = match d.checked_mul(1_000) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
assert_eq!(
|
||||
reward_curve.calculate_for_fraction_times_denominator(n, d),
|
||||
d
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_substrate_guarantees_not_to_overflow_u32() {
|
||||
ExtBuilder::build().execute_with(|| {
|
||||
let reward_curve = RewardCurve::get();
|
||||
let mut n: u32 = 69;
|
||||
let mut d: u32 = 100;
|
||||
|
||||
loop {
|
||||
n = match n.checked_mul(1_000) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
d = match d.checked_mul(1_000) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
assert_eq!(
|
||||
reward_curve.calculate_for_fraction_times_denominator(n, d),
|
||||
d
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_muldiv_guarantees_not_to_overflow_for_u128() {
|
||||
ExtBuilder::build().execute_with(|| {
|
||||
let mut a: u128 = 2;
|
||||
let mut b: u128 = 3;
|
||||
let mut c: u128 = 6;
|
||||
let mut result: u128 = 1;
|
||||
|
||||
loop {
|
||||
a = match a.checked_mul(1_000) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
b = match b.checked_mul(1_000) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
c = match c.checked_mul(1_000) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
result = match result.checked_mul(1_000) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
|
||||
assert_eq!(MulDiv::<u128>::calculate(a, b, c), result);
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
MulDiv::<u128>::calculate(u128::MAX, u128::MAX, u128::MAX),
|
||||
u128::MAX
|
||||
);
|
||||
assert_eq!(MulDiv::<u128>::calculate(u128::MAX, 0, 0), 0);
|
||||
assert_eq!(MulDiv::<u128>::calculate(0, u128::MAX, 0), 0);
|
||||
assert_eq!(MulDiv::<u128>::calculate(0, 0, u128::MAX), 0);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_muldiv_guarantees_not_to_overflow_for_u64() {
|
||||
ExtBuilder::build().execute_with(|| {
|
||||
let mut a: u64 = 2;
|
||||
let mut b: u64 = 3;
|
||||
let mut c: u64 = 6;
|
||||
let mut result: u64 = 1;
|
||||
|
||||
loop {
|
||||
a = match a.checked_mul(1_000) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
b = match b.checked_mul(1_000) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
c = match c.checked_mul(1_000) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
result = match result.checked_mul(1_000) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
|
||||
assert_eq!(MulDiv::<u64>::calculate(a, b, c), result);
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
MulDiv::<u64>::calculate(u64::MAX, u64::MAX, u64::MAX),
|
||||
u64::MAX
|
||||
);
|
||||
assert_eq!(MulDiv::<u64>::calculate(u64::MAX, 0, 0), 0);
|
||||
assert_eq!(MulDiv::<u64>::calculate(0, u64::MAX, 0), 0);
|
||||
assert_eq!(MulDiv::<u64>::calculate(0, 0, u64::MAX), 0);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_muldiv_guarantees_not_to_overflow_for_u32() {
|
||||
ExtBuilder::build().execute_with(|| {
|
||||
let mut a: u32 = 2;
|
||||
let mut b: u32 = 3;
|
||||
let mut c: u32 = 6;
|
||||
let mut result: u32 = 1;
|
||||
|
||||
loop {
|
||||
a = match a.checked_mul(1_000) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
b = match b.checked_mul(1_000) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
c = match c.checked_mul(1_000) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
result = match result.checked_mul(1_000) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
|
||||
assert_eq!(MulDiv::<u32>::calculate(a, b, c), result);
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
MulDiv::<u32>::calculate(u32::MAX, u32::MAX, u32::MAX),
|
||||
u32::MAX
|
||||
);
|
||||
assert_eq!(MulDiv::<u32>::calculate(u32::MAX, 0, 0), 0);
|
||||
assert_eq!(MulDiv::<u32>::calculate(0, u32::MAX, 0), 0);
|
||||
assert_eq!(MulDiv::<u32>::calculate(0, 0, u32::MAX), 0);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_bridged_inflation_curve_for_overflow() {
|
||||
ExtBuilder::build().execute_with(|| {
|
||||
let amount_full: u128 = 1337 * 1_000_000_000;
|
||||
let commission: u128 = amount_full / 100; // 1% commission
|
||||
let amount: u128 = amount_full - commission;
|
||||
|
||||
let tollerance: u128 = commission / 100; // 1% tollerance
|
||||
let precomputed_payout: u128 = 13177568884;
|
||||
let precomputed_rest: u128 = 192431116;
|
||||
assert_eq!(precomputed_payout + precomputed_rest, commission);
|
||||
|
||||
let mut total_staked_ideal: u128 = 69_000;
|
||||
let mut total_staked_not_ideal: u128 = 68_000;
|
||||
let mut total_issuance: u128 = 100_000;
|
||||
|
||||
assert_ok!(GhostNetworks::accumulate_commission(&commission));
|
||||
assert_ok!(GhostNetworks::accumulate_incoming_imbalance(&amount));
|
||||
|
||||
loop {
|
||||
total_staked_ideal = match total_staked_ideal.checked_mul(1_000) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
total_staked_not_ideal = match total_staked_not_ideal.checked_mul(1_000) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
total_issuance = match total_issuance.checked_mul(1_000) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
assert_eq!(
|
||||
BridgedInflationCurve::<RewardCurve, Test>::era_payout(
|
||||
total_staked_ideal,
|
||||
total_issuance + amount,
|
||||
0
|
||||
),
|
||||
(commission, 0)
|
||||
);
|
||||
|
||||
let (payout, rest) = BridgedInflationCurve::<RewardCurve, Test>::era_payout(
|
||||
total_staked_not_ideal,
|
||||
total_issuance + amount,
|
||||
0,
|
||||
);
|
||||
|
||||
let payout_deviation = if precomputed_payout > payout {
|
||||
precomputed_payout - payout
|
||||
} else {
|
||||
payout - precomputed_payout
|
||||
};
|
||||
|
||||
let rest_deviation = if precomputed_rest > rest {
|
||||
precomputed_rest - rest
|
||||
} else {
|
||||
rest - precomputed_rest
|
||||
};
|
||||
|
||||
assert!(payout_deviation < tollerance);
|
||||
assert!(rest_deviation < tollerance);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_bridged_inflation_curve_for_big_commissions() {
|
||||
ExtBuilder::build().execute_with(|| {
|
||||
let mut amount_full: u128 = 1337;
|
||||
|
||||
let total_staked_ideal: u128 = 69_000_000;
|
||||
let total_staked_gt_ideal: u128 = 100_000_000;
|
||||
let total_staked_lt_ideal: u128 = 3_000_000;
|
||||
let total_issuance: u128 = 100_000_000;
|
||||
|
||||
loop {
|
||||
amount_full = match amount_full.checked_mul(1_000) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
let commission: u128 = amount_full / 100; // 1% commission
|
||||
let amount: u128 = amount_full - commission;
|
||||
|
||||
AccumulatedCommission::<Test>::set(commission);
|
||||
BridgedImbalance::<Test>::set(BridgeAdjustment {
|
||||
bridged_in: amount,
|
||||
bridged_out: 0,
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
BridgedInflationCurve::<RewardCurve, Test>::era_payout(
|
||||
total_staked_ideal,
|
||||
total_issuance + amount,
|
||||
0
|
||||
),
|
||||
(commission, 0)
|
||||
);
|
||||
|
||||
let (payout, rest) = BridgedInflationCurve::<RewardCurve, Test>::era_payout(
|
||||
total_staked_gt_ideal,
|
||||
total_issuance + amount,
|
||||
0
|
||||
);
|
||||
assert!(payout < commission);
|
||||
assert!(rest < commission);
|
||||
|
||||
let (payout, rest) = BridgedInflationCurve::<RewardCurve, Test>::era_payout(
|
||||
total_staked_lt_ideal,
|
||||
total_issuance + amount,
|
||||
0
|
||||
);
|
||||
assert!(payout < commission);
|
||||
assert!(rest < commission);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ghost-slow-clap"
|
||||
version = "0.3.39"
|
||||
version = "0.3.43"
|
||||
description = "Applause protocol for the EVM bridge"
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
|
||||
@ -72,7 +72,7 @@ const LOG_TARGET: &str = "runtime::ghost-slow-clap";
|
||||
const DB_PREFIX: &[u8] = b"slow_clap::";
|
||||
|
||||
const FETCH_TIMEOUT_PERIOD: u64 = 3_000;
|
||||
const LOCK_BLOCK_EXPIRATION: u64 = 10;
|
||||
const LOCK_BLOCK_EXPIRATION: u64 = 20;
|
||||
|
||||
pub type AuthIndex = u32;
|
||||
|
||||
@ -378,7 +378,8 @@ pub mod pallet {
|
||||
|
||||
fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity {
|
||||
if let Call::slow_clap { clap, signature } = call {
|
||||
let authorities = Authorities::<T>::get(&clap.session_index);
|
||||
let (session_index, _) = Self::mended_session_index(&clap);
|
||||
let authorities = Authorities::<T>::get(&session_index);
|
||||
let authority = match authorities.get(clap.authority_index as usize) {
|
||||
Some(authority) => authority,
|
||||
None => return InvalidTransaction::BadSigner.into(),
|
||||
@ -459,27 +460,49 @@ impl<T: Config> Pallet<T> {
|
||||
hex_str
|
||||
}
|
||||
|
||||
fn try_slow_clap(clap: &Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>) -> DispatchResult {
|
||||
let authorities = Authorities::<T>::get(&clap.session_index);
|
||||
ensure!(
|
||||
authorities.get(clap.authority_index as usize).is_some(),
|
||||
Error::<T>::NotAnAuthority
|
||||
fn mended_session_index(
|
||||
clap: &Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>,
|
||||
) -> (SessionIndex, H256) {
|
||||
let prev_session_index = clap.session_index.saturating_sub(1);
|
||||
let clap_unique_hash =
|
||||
Self::generate_unique_hash(&clap.receiver, &clap.amount, &clap.network_id);
|
||||
|
||||
let received_claps_key = (
|
||||
prev_session_index,
|
||||
&clap.transaction_hash,
|
||||
&clap_unique_hash,
|
||||
);
|
||||
|
||||
let session_index = ReceivedClaps::<T>::get(&received_claps_key)
|
||||
.is_empty()
|
||||
.then(|| clap.session_index)
|
||||
.unwrap_or(prev_session_index);
|
||||
|
||||
(session_index, clap_unique_hash)
|
||||
}
|
||||
|
||||
fn try_slow_clap(clap: &Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>) -> DispatchResult {
|
||||
let (session_index, clap_unique_hash) = Self::mended_session_index(&clap);
|
||||
let mut claps_in_session = ClapsInSession::<T>::get(&session_index);
|
||||
|
||||
ensure!(
|
||||
ClapsInSession::<T>::get(&clap.session_index)
|
||||
claps_in_session
|
||||
.get(&clap.authority_index)
|
||||
.map(|info| !info.disabled)
|
||||
.unwrap_or(true),
|
||||
Error::<T>::CurrentValidatorIsDisabled
|
||||
);
|
||||
|
||||
let clap_unique_hash =
|
||||
Self::generate_unique_hash(&clap.receiver, &clap.amount, &clap.network_id);
|
||||
let received_claps_key = (
|
||||
clap.session_index,
|
||||
&clap.transaction_hash,
|
||||
&clap_unique_hash,
|
||||
);
|
||||
let disabled_authorites = claps_in_session
|
||||
.values()
|
||||
.filter(|info| info.disabled)
|
||||
.count();
|
||||
|
||||
let active_authorities = Authorities::<T>::get(&session_index)
|
||||
.len()
|
||||
.saturating_sub(disabled_authorites);
|
||||
|
||||
let received_claps_key = (session_index, &clap.transaction_hash, &clap_unique_hash);
|
||||
|
||||
let number_of_received_claps =
|
||||
ReceivedClaps::<T>::try_mutate(&received_claps_key, |tree_of_claps| {
|
||||
@ -498,15 +521,15 @@ impl<T: Config> Pallet<T> {
|
||||
}
|
||||
})?;
|
||||
|
||||
ClapsInSession::<T>::mutate(&clap.session_index, |claps_details| {
|
||||
(*claps_details)
|
||||
claps_in_session
|
||||
.entry(clap.authority_index)
|
||||
.and_modify(|individual| (*individual).claps.saturating_inc())
|
||||
.and_modify(|individual| individual.claps.saturating_inc())
|
||||
.or_insert(SessionAuthorityInfo {
|
||||
claps: 1u32,
|
||||
disabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
ClapsInSession::<T>::insert(&session_index, claps_in_session);
|
||||
|
||||
Self::deposit_event(Event::<T>::Clapped {
|
||||
authority_id: clap.authority_index,
|
||||
@ -517,7 +540,7 @@ impl<T: Config> Pallet<T> {
|
||||
});
|
||||
|
||||
let enough_authorities =
|
||||
Perbill::from_rational(number_of_received_claps as u32, authorities.len() as u32)
|
||||
Perbill::from_rational(number_of_received_claps as u32, active_authorities as u32)
|
||||
> Perbill::from_percent(T::ApplauseThreshold::get());
|
||||
|
||||
if enough_authorities {
|
||||
@ -574,32 +597,55 @@ impl<T: Config> Pallet<T> {
|
||||
|
||||
fn applause_if_posible(
|
||||
network_id: NetworkIdOf<T>,
|
||||
session_index: SessionIndex,
|
||||
prev_session_index: SessionIndex,
|
||||
transaction_hash: H256,
|
||||
receiver: T::AccountId,
|
||||
amount: BalanceOf<T>,
|
||||
) -> DispatchResult {
|
||||
let curr_session_index = prev_session_index.saturating_add(1);
|
||||
let clap_unique_hash = Self::generate_unique_hash(&receiver, &amount, &network_id);
|
||||
let received_claps_key = (session_index, &transaction_hash, &clap_unique_hash);
|
||||
let prev_received_claps_key = (prev_session_index, &transaction_hash, &clap_unique_hash);
|
||||
let curr_received_claps_key = (curr_session_index, &transaction_hash, &clap_unique_hash);
|
||||
|
||||
let prev_authorities = Authorities::<T>::get(&prev_session_index);
|
||||
let curr_authorities = Authorities::<T>::get(&curr_session_index);
|
||||
|
||||
let prev_received_claps = ReceivedClaps::<T>::get(&prev_received_claps_key).into_inner();
|
||||
let curr_received_claps = ReceivedClaps::<T>::get(&curr_received_claps_key).into_inner();
|
||||
|
||||
let summary_authority_claps_length = curr_received_claps
|
||||
.difference(&prev_received_claps)
|
||||
.filter_map(|&index| {
|
||||
curr_authorities
|
||||
.get(index as usize)
|
||||
.map(|curr_authority| {
|
||||
prev_authorities
|
||||
.iter()
|
||||
.position(|prev_authority| curr_authority == prev_authority)
|
||||
})
|
||||
.flatten()
|
||||
})
|
||||
.count()
|
||||
.saturating_add(curr_received_claps.len());
|
||||
|
||||
let clap = Clap {
|
||||
authority_index: Default::default(),
|
||||
block_number: Default::default(),
|
||||
removed: false,
|
||||
session_index,
|
||||
removed: Default::default(),
|
||||
session_index: Default::default(),
|
||||
transaction_hash: Default::default(),
|
||||
network_id,
|
||||
receiver,
|
||||
amount,
|
||||
transaction_hash,
|
||||
};
|
||||
|
||||
let enough_authorities = Perbill::from_rational(
|
||||
ReceivedClaps::<T>::get(&received_claps_key).len() as u32,
|
||||
Authorities::<T>::get(session_index).len() as u32,
|
||||
summary_authority_claps_length as u32,
|
||||
Authorities::<T>::get(prev_session_index).len() as u32,
|
||||
) > Perbill::from_percent(T::ApplauseThreshold::get());
|
||||
|
||||
ensure!(enough_authorities, Error::<T>::NotEnoughClaps);
|
||||
Self::try_applause(&clap, &received_claps_key)?;
|
||||
Self::try_applause(&clap, &prev_received_claps_key)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@ -766,14 +812,17 @@ impl<T: Config> Pallet<T> {
|
||||
Some(_) if from_block.le(&to_block) => {
|
||||
let adjusted_to_block = estimated_block
|
||||
.checked_sub(from_block)
|
||||
.map(|current_distance| current_distance
|
||||
.map(|current_distance| {
|
||||
current_distance
|
||||
.le(&max_block_distance)
|
||||
.then(|| estimated_block)
|
||||
)
|
||||
})
|
||||
.flatten()
|
||||
.unwrap_or(from_block
|
||||
.unwrap_or(
|
||||
from_block
|
||||
.saturating_add(max_block_distance)
|
||||
.min(estimated_block));
|
||||
.min(estimated_block),
|
||||
);
|
||||
(from_block, adjusted_to_block)
|
||||
}
|
||||
_ => (to_block, to_block),
|
||||
@ -1087,8 +1136,8 @@ impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
|
||||
}
|
||||
|
||||
fn on_before_session_ending() {
|
||||
let session_index = T::ValidatorSet::session_index();
|
||||
let validators = T::ValidatorSet::validators();
|
||||
let session_index = T::ValidatorSet::session_index().saturating_sub(1);
|
||||
let authorities_len = Authorities::<T>::get(&session_index).len();
|
||||
let claps_in_session = ClapsInSession::<T>::get(&session_index);
|
||||
|
||||
@ -1097,12 +1146,14 @@ impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
|
||||
let offenders = validators
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter(|(index, _)| !Self::is_good_actor(*index, median_claps, &claps_in_session))
|
||||
.filter_map(|(_, id)| {
|
||||
.filter_map(|(index, id)| {
|
||||
(!Self::is_good_actor(index, median_claps, &claps_in_session)).then(|| {
|
||||
<T::ValidatorSet as ValidatorSetWithIdentification<T::AccountId>>::IdentificationOf::convert(
|
||||
id.clone(),
|
||||
).map(|full_id| (id, full_id))
|
||||
})
|
||||
.flatten()
|
||||
})
|
||||
.collect::<Vec<IdentificationTuple<T>>>();
|
||||
|
||||
if offenders.is_empty() {
|
||||
|
||||
@ -905,9 +905,9 @@ fn should_nullify_commission_on_finalize() {
|
||||
BridgedInflationCurve::<RewardCurve, Runtime>::era_payout(
|
||||
total_staked,
|
||||
total_issuance,
|
||||
0
|
||||
0u64
|
||||
),
|
||||
(420000000000000, 0)
|
||||
(420000000000000u64, 0u64)
|
||||
); // precomputed values
|
||||
assert_eq!(Networks::is_nullification_period(), true);
|
||||
Networks::on_finalize(System::block_number());
|
||||
@ -921,6 +921,7 @@ fn should_nullify_commission_on_finalize() {
|
||||
|
||||
#[test]
|
||||
fn should_avoid_applause_during_nullification_period() {
|
||||
let zero: u64 = 0u64;
|
||||
let total_staked = 69_000_000;
|
||||
let total_issuance = 100_000_000;
|
||||
|
||||
@ -936,9 +937,9 @@ fn should_avoid_applause_during_nullification_period() {
|
||||
BridgedInflationCurve::<RewardCurve, Runtime>::era_payout(
|
||||
total_staked,
|
||||
total_issuance,
|
||||
0
|
||||
zero
|
||||
),
|
||||
(0, 0)
|
||||
(zero, zero)
|
||||
);
|
||||
assert_eq!(Networks::is_nullification_period(), true);
|
||||
|
||||
@ -956,6 +957,7 @@ fn should_avoid_applause_during_nullification_period() {
|
||||
|
||||
#[test]
|
||||
fn should_self_applause_if_enough_received_claps() {
|
||||
let zero: u64 = 0u64;
|
||||
let (network_id, transaction_hash, unique_transaction_hash) =
|
||||
generate_unique_hash(None, None, None, None);
|
||||
let (_, receiver, amount) = get_mocked_metadata();
|
||||
@ -981,15 +983,14 @@ fn should_self_applause_if_enough_received_claps() {
|
||||
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
|
||||
false
|
||||
);
|
||||
assert_eq!(Balances::balance(&receiver), 0);
|
||||
assert_eq!(Balances::balance(&receiver), zero);
|
||||
assert_eq!(
|
||||
BridgedInflationCurve::<RewardCurve, Runtime>::era_payout(0, 0, 0),
|
||||
(0, 0)
|
||||
BridgedInflationCurve::<RewardCurve, Runtime>::era_payout(zero, zero, zero),
|
||||
(zero, zero)
|
||||
);
|
||||
|
||||
assert_ok!(do_clap_from(session_index, network_id, 0, false));
|
||||
assert_ok!(do_clap_from(session_index, network_id, 1, false));
|
||||
assert_ok!(do_clap_from(session_index, network_id, 2, false));
|
||||
|
||||
assert_eq!(
|
||||
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
|
||||
@ -997,14 +998,17 @@ fn should_self_applause_if_enough_received_claps() {
|
||||
);
|
||||
assert_eq!(Balances::balance(&receiver), 0);
|
||||
|
||||
assert_ok!(SlowClap::self_applause(
|
||||
assert_err!(
|
||||
SlowClap::self_applause(
|
||||
RuntimeOrigin::signed(receiver),
|
||||
network_id,
|
||||
session_index,
|
||||
transaction_hash,
|
||||
receiver,
|
||||
amount,
|
||||
));
|
||||
),
|
||||
Error::<Runtime>::NotEnoughClaps
|
||||
);
|
||||
assert_eq!(
|
||||
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
|
||||
false
|
||||
@ -1013,6 +1017,26 @@ fn should_self_applause_if_enough_received_claps() {
|
||||
|
||||
Networks::on_finalize(System::block_number());
|
||||
|
||||
advance_session();
|
||||
let next_session_index = Session::session_index();
|
||||
let next_storage_key = (
|
||||
next_session_index,
|
||||
transaction_hash,
|
||||
unique_transaction_hash,
|
||||
);
|
||||
assert_ok!(do_clap_from(next_session_index, network_id, 2, false));
|
||||
|
||||
assert_err!(
|
||||
SlowClap::self_applause(
|
||||
RuntimeOrigin::signed(receiver),
|
||||
network_id,
|
||||
next_session_index,
|
||||
transaction_hash,
|
||||
receiver,
|
||||
amount,
|
||||
),
|
||||
Error::<Runtime>::NotEnoughClaps
|
||||
);
|
||||
assert_ok!(SlowClap::self_applause(
|
||||
RuntimeOrigin::signed(receiver),
|
||||
network_id,
|
||||
@ -1025,6 +1049,10 @@ fn should_self_applause_if_enough_received_claps() {
|
||||
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
|
||||
true
|
||||
);
|
||||
assert_eq!(
|
||||
pallet::ApplausesForTransaction::<Runtime>::get(&next_storage_key),
|
||||
false
|
||||
);
|
||||
assert_eq!(Balances::balance(&receiver), amount);
|
||||
});
|
||||
}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "casper-runtime"
|
||||
version = "3.5.30"
|
||||
version = "3.5.31"
|
||||
build = "build.rs"
|
||||
description = "Runtime of the Casper Network"
|
||||
edition.workspace = true
|
||||
|
||||
@ -117,7 +117,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
|
||||
spec_name: create_runtime_str!("casper"),
|
||||
impl_name: create_runtime_str!("casper-svengali"),
|
||||
authoring_version: 0,
|
||||
spec_version: 1,
|
||||
spec_version: 2,
|
||||
impl_version: 0,
|
||||
apis: RUNTIME_API_VERSIONS,
|
||||
transaction_version: 1,
|
||||
|
||||
@ -229,6 +229,7 @@ if [[ $HARD_RESET = true ]]; then
|
||||
sudo rm -rf "$BASE_PATH/chains/casper_staging_testnet"
|
||||
|
||||
cd $PROJECT_FOLDER
|
||||
git pull origin main
|
||||
echo "[+] starting build in 3 seconds..."
|
||||
sleep 3
|
||||
cargo build --release
|
||||
@ -244,9 +245,8 @@ if [[ $HARD_RESET = true ]]; then
|
||||
echo "[+] ghost executable copied in '$EXECUTABLE_PATH' from '$TARGET'"
|
||||
echo "[+] specification '$SPECIFICATION_NAME.json' copied to '$SPECIFICATION_PATH'"
|
||||
|
||||
# TODO: uncomment later
|
||||
# echo "[+] starting ghost-node"
|
||||
# sudo systemctl start ghost-node
|
||||
echo "[+] starting ghost-node"
|
||||
sudo systemctl start ghost-node
|
||||
|
||||
exit 0
|
||||
fi
|
||||
|
||||
Loading…
Reference in New Issue
Block a user