Compare commits

...

6 Commits

Author SHA1 Message Date
04a63e234d
tests updated and small tweaks of the lib
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-02 19:20:14 +03:00
2b738c009b
merge latest ghost-network version
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-06-02 19:17:16 +03:00
f3d8ee3ab2
make bridge imbalance fields accesible aka public
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-06-02 19:11:11 +03:00
2da07d7b24
chmod 644 Cargo.toml for ghost-slow-claps
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-05-31 14:55:30 +03:00
9ba25d6b3d
friendly merge for ghost-claims weights
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-05-31 14:51:53 +03:00
3234341fed
use benchmarked weights as a default weights for ghost-claims pallet
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-05-31 14:48:08 +03:00
11 changed files with 656 additions and 778 deletions

6
Cargo.lock generated
View File

@ -3504,7 +3504,7 @@ dependencies = [
[[package]] [[package]]
name = "ghost-claims" name = "ghost-claims"
version = "0.2.2" version = "0.2.3"
dependencies = [ dependencies = [
"frame-benchmarking", "frame-benchmarking",
"frame-support", "frame-support",
@ -3648,7 +3648,7 @@ dependencies = [
[[package]] [[package]]
name = "ghost-networks" name = "ghost-networks"
version = "0.1.2" version = "0.1.3"
dependencies = [ dependencies = [
"frame-benchmarking", "frame-benchmarking",
"frame-support", "frame-support",
@ -3834,7 +3834,7 @@ dependencies = [
[[package]] [[package]]
name = "ghost-slow-clap" name = "ghost-slow-clap"
version = "0.3.16" version = "0.3.17"
dependencies = [ dependencies = [
"frame-benchmarking", "frame-benchmarking",
"frame-support", "frame-support",

View File

@ -1,6 +1,6 @@
[package] [package]
name = "ghost-claims" name = "ghost-claims"
version = "0.2.2" version = "0.2.3"
description = "Ghost balance and rank claims based on EVM actions" description = "Ghost balance and rank claims based on EVM actions"
license.workspace = true license.workspace = true
authors.workspace = true authors.workspace = true

View File

@ -20,8 +20,9 @@ extern crate alloc;
#[cfg(not(feature = "std"))] #[cfg(not(feature = "std"))]
use alloc::{format, string::String}; use alloc::{format, string::String};
pub mod weights; mod weights;
pub use crate::weights::WeightInfo; pub use crate::weights::WeightInfo;
mod tests; mod tests;
mod mock; mod mock;
mod benchmarking; mod benchmarking;

View File

@ -1,9 +1,104 @@
use frame_support::weights::Weight; // This file is part of Ghost Network.
// Ghost Network is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Ghost Network 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 Ghost Network. If not, see <http://www.gnu.org/licenses/>.
//! Autogenerated weights for `ghost_claims`
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0
//! DATE: 2024-08-02, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `ghostown`, CPU: `Intel(R) Core(TM) i3-2310M CPU @ 2.10GHz`
//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("casper-dev")`, DB CACHE: 1024
// Executed Command:
// ./target/release/ghost
// benchmark
// pallet
// --chain=casper-dev
// --steps=50
// --repeat=20
// --pallet=ghost_claims
// --extrinsic=*
// --wasm-execution=compiled
// --heap-pages=4096
// --header=./file_header.txt
// --output=./runtime/casper/src/weights/ghost_claims.rs
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]
#![allow(missing_docs)]
use frame_support::{
traits::Get,
weights::{Weight, constants::RocksDbWeight},
};
use core::marker::PhantomData;
/// Weight functions needed for `ghost_claims`.
pub trait WeightInfo { pub trait WeightInfo {
fn claim() -> Weight; fn claim() -> Weight;
}
/// Weight for ghost_claims using the Substrate node and recommended hardware.
pub struct SubstrateWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Storage: `System::Account` (r:2 w:2)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
/// Storage: `GhostClaims::Total` (r:1 w:1)
/// Proof: `GhostClaims::Total` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `CultCollective::Members` (r:2 w:2)
/// Proof: `CultCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`)
/// Storage: `CultCollective::MemberCount` (r:6 w:6)
/// Proof: `CultCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`)
/// Storage: `CultCollective::IdToIndex` (r:6 w:12)
/// Proof: `CultCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`)
/// Storage: `CultCollective::IndexToId` (r:0 w:6)
/// Proof: `CultCollective::IndexToId` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`)
fn claim() -> Weight {
// Proof Size summary in bytes:
// Measured: `896`
// Estimated: `16164`
// Minimum execution time: 754_086_000 picoseconds.
Weight::from_parts(756_147_000, 0)
.saturating_add(Weight::from_parts(0, 16164))
.saturating_add(T::DbWeight::get().reads(17))
.saturating_add(T::DbWeight::get().writes(29))
}
} }
impl WeightInfo for () { impl WeightInfo for () {
fn claim() -> Weight { Weight::zero() } /// Storage: `System::Account` (r:2 w:2)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
/// Storage: `GhostClaims::Total` (r:1 w:1)
/// Proof: `GhostClaims::Total` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `CultCollective::Members` (r:2 w:2)
/// Proof: `CultCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`)
/// Storage: `CultCollective::MemberCount` (r:6 w:6)
/// Proof: `CultCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`)
/// Storage: `CultCollective::IdToIndex` (r:6 w:12)
/// Proof: `CultCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`)
/// Storage: `CultCollective::IndexToId` (r:0 w:6)
/// Proof: `CultCollective::IndexToId` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`)
fn claim() -> Weight {
// Proof Size summary in bytes:
// Measured: `896`
// Estimated: `16164`
// Minimum execution time: 754_086_000 picoseconds.
Weight::from_parts(756_147_000, 0)
.saturating_add(Weight::from_parts(0, 16164))
.saturating_add(RocksDbWeight::get().reads(17))
.saturating_add(RocksDbWeight::get().writes(29))
}
} }

View File

@ -1,6 +1,6 @@
[package] [package]
name = "ghost-networks" name = "ghost-networks"
version = "0.1.2" version = "0.1.3"
license.workspace = true license.workspace = true
authors.workspace = true authors.workspace = true
edition.workspace = true edition.workspace = true

View File

@ -63,8 +63,8 @@ pub struct NetworkData {
#[derive(Default, Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] #[derive(Default, Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub struct BridgeAdjustment<Balance> { pub struct BridgeAdjustment<Balance> {
bridged_out: Balance, pub bridged_out: Balance,
bridged_in: Balance, pub bridged_in: Balance,
} }
pub struct BridgedInflationCurve<RewardCurve, T>(core::marker::PhantomData<(RewardCurve, T)>); pub struct BridgedInflationCurve<RewardCurve, T>(core::marker::PhantomData<(RewardCurve, T)>);

2
pallets/slow-clap/Cargo.toml Executable file → Normal file
View File

@ -1,6 +1,6 @@
[package] [package]
name = "ghost-slow-clap" name = "ghost-slow-clap"
version = "0.3.16" version = "0.3.17"
description = "Applause protocol for the EVM bridge" description = "Applause protocol for the EVM bridge"
license.workspace = true license.workspace = true
authors.workspace = true authors.workspace = true

View File

@ -4,12 +4,7 @@ use super::*;
use frame_benchmarking::v1::*; use frame_benchmarking::v1::*;
use frame_system::RawOrigin; use frame_system::RawOrigin;
use frame_support::traits::fungible::{Inspect, Mutate}; use frame_support::traits::fungible::Inspect;
use crate::Pallet as SlowClap;
const MAX_CLAPS: u32 = 100;
const MAX_COMPANIONS: u32 = 20;
pub fn create_account<T: Config>() -> T::AccountId { pub fn create_account<T: Config>() -> T::AccountId {
let account_bytes = Vec::from([1u8; 32]); let account_bytes = Vec::from([1u8; 32]);
@ -17,184 +12,40 @@ pub fn create_account<T: Config>() -> T::AccountId {
.expect("32 bytes always construct an AccountId32") .expect("32 bytes always construct an AccountId32")
} }
pub fn create_companions<T: Config>(
total: usize,
network_id: NetworkIdOf<T>,
user_account: T::AccountId,
fee: H256,
receiver: H160,
) -> Result<CompanionId, &'static str> {
T::NetworkDataHandler::register(network_id.into(), NetworkData {
chain_name: "Ethereum".into(),
default_endpoint:
"https://base-mainnet.core.chainstack.com/2fc1de7f08c0465f6a28e3c355e0cb14/".into(),
finality_delay: Some(0),
release_delay: Some(0),
network_type: Default::default(),
gatekeeper: b"0x1234567891234567891234567891234567891234".to_vec(),
topic_name: b"0x12345678912345678912345678912345678912345678912345678912345678".to_vec(),
incoming_fee: 0,
outgoing_fee: 0,
}).map_err(|_| BenchmarkError::Weightless)?;
let mut last_companion_id = 0;
for _ in 0..total {
let minimum_balance = <<T as pallet::Config>::Currency>::minimum_balance();
let balance = minimum_balance + minimum_balance;
let companion = Companion::<NetworkIdOf::<T>, BalanceOf::<T>> {
network_id: network_id.into(), receiver,
fee, amount: balance,
};
let _ = <<T as pallet::Config>::Currency>::mint_into(&user_account, balance);
let companion_id = SlowClap::<T>::current_companion_id();
let _ = SlowClap::<T>::propose_companion(
RawOrigin::Signed(user_account.clone()).into(),
network_id,
companion,
)?;
last_companion_id = companion_id;
}
Ok(last_companion_id)
}
pub fn create_claps<T: Config>(i: u32, j: u32) -> Result<
(
Vec<crate::Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>>,
<T::AuthorityId as RuntimeAppPublic>::Signature,
),
&'static str,
> {
let minimum_balance = <<T as pallet::Config>::Currency>::minimum_balance();
let amount = minimum_balance + minimum_balance;
let total_amount = amount.saturating_mul(j.into());
let network_id = NetworkIdOf::<T>::default();
let mut claps = Vec::new();
let mut companions = BTreeMap::new();
let authorities = vec![T::AuthorityId::generate_pair(None)];
let bounded_authorities =
WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities.clone())
.map_err(|()| "more than the maximum number of keys provided")?;
Authorities::<T>::put(bounded_authorities);
for index in 0..j {
companions.insert(
index.into(),
amount,
);
}
for _ in 0..i {
claps.push(Clap {
session_index: 1,
authority_index: 0,
network_id,
transaction_hash: H256::repeat_byte(1u8),
block_number: 69,
removed: true,
receiver: create_account::<T>(),
amount: total_amount,
companions: companions.clone(),
});
}
let authority_id = authorities
.get(0usize)
.expect("first authority should exist");
let encoded_claps = claps.encode();
let signature = authority_id.sign(&encoded_claps)
.ok_or("couldn't make signature")?;
Ok((claps, signature))
}
benchmarks! { benchmarks! {
slow_clap { slow_clap {
let k in 1 .. MAX_CLAPS;
let j in 1 .. MAX_COMPANIONS;
let receiver = H160::repeat_byte(69u8);
let fee = H256::repeat_byte(0u8);
let user_account: T::AccountId = whitelisted_caller();
let network_id = <<T as pallet::Config>::NetworkDataHandler as NetworkDataBasicHandler>::NetworkId::default();
let (claps, signature) = create_claps::<T>(k, j)?;
let _ = create_companions::<T>(j as usize, network_id, user_account, fee, receiver)?;
}: _(RawOrigin::None, claps, signature)
verify {
let minimum_balance = <<T as pallet::Config>::Currency>::minimum_balance(); let minimum_balance = <<T as pallet::Config>::Currency>::minimum_balance();
let total_amount = (minimum_balance + minimum_balance).saturating_mul(j.into()); let receiver = create_account::<T>();
} let amount = minimum_balance + minimum_balance;
let network_id = NetworkIdOf::<T>::default();
propose_companion { let authorities = vec![T::AuthorityId::generate_pair(None)];
let receiver = H160::repeat_byte(69u8); let bounded_authorities =
let fee = H256::repeat_byte(0u8); WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities.clone())
let user_account: T::AccountId = whitelisted_caller(); .map_err(|()| "more than the maximum number of keys provided")?;
let network_id = <<T as pallet::Config>::NetworkDataHandler as NetworkDataBasicHandler>::NetworkId::default(); Authorities::<T>::put(bounded_authorities);
// T::NetworkDataHandler::register(network_id.into(), NetworkData {
// chain_name: "Ethereum".into(), let clap = Clap {
// // https://nd-422-757-666.p2pify.com/0a9d79d93fb2f4a4b1e04695da2b77a7/ session_index: 0,
// default_endpoint: authority_index: 0,
// "https://base-mainnet.core.chainstack.com/2fc1de7f08c0465f6a28e3c355e0cb14/".into(), transaction_hash: H256::repeat_byte(1u8),
// finality_delay: Some(50), block_number: 69,
// release_delay: Some(100), removed: false,
// network_type: Default::default(), network_id,
// gatekeeper: b"0x1234567891234567891234567891234567891234".to_vec(), receiver: receiver.clone(),
// topic_name: b"0x12345678912345678912345678912345678912345678912345678912345678".to_vec(), amount,
// incoming_fee: 0,
// outgoing_fee: 0,
// }).map_err(|_| BenchmarkError::Weightless)?;
let companion_id = create_companions::<T>(1, network_id, user_account.clone(), fee, receiver)?;
let companion_id = SlowClap::<T>::current_companion_id();
let minimum_balance = <<T as pallet::Config>::Currency>::minimum_balance();
let balance = minimum_balance + minimum_balance;
let companion = Companion::<NetworkIdOf::<T>, BalanceOf::<T>> {
network_id: network_id.into(), receiver,
fee, amount: balance,
}; };
let _ = <<T as pallet::Config>::Currency>::mint_into(&user_account, balance);
assert_eq!(SlowClap::<T>::current_companion_id(), companion_id);
}: _(RawOrigin::Signed(user_account), network_id.into(), companion)
verify {
assert_eq!(SlowClap::<T>::current_companion_id(), companion_id + 1);
}
release_companion { let authority_id = authorities
let receiver = H160::repeat_byte(69u8); .get(0usize)
let fee = H256::repeat_byte(0u8); .expect("first authority should exist");
let user_account: T::AccountId = whitelisted_caller(); let encoded_clap = clap.encode();
let network_id = <<T as pallet::Config>::NetworkDataHandler as NetworkDataBasicHandler>::NetworkId::default(); let signature = authority_id.sign(&encoded_clap)
let companion_id = create_companions::<T>(1, network_id, user_account.clone(), fee, receiver)?; .ok_or("couldn't make signature")?;
assert_eq!(SlowClap::<T>::release_blocks(companion_id), BlockNumberFor::<T>::default());
}: _(RawOrigin::Signed(user_account), network_id.into(), companion_id)
verify {
assert_ne!(SlowClap::<T>::release_blocks(companion_id), BlockNumberFor::<T>::default());
}
kill_companion { }: _(RawOrigin::None, clap, signature)
let receiver = H160::repeat_byte(69u8);
let fee = H256::repeat_byte(0u8);
let user_account: T::AccountId = whitelisted_caller();
let network_id = <<T as pallet::Config>::NetworkDataHandler as NetworkDataBasicHandler>::NetworkId::default();
let companion_id = create_companions::<T>(1, network_id, user_account.clone(), fee, receiver)?;
SlowClap::<T>::release_companion(
RawOrigin::Signed(user_account.clone()).into(),
network_id,
companion_id,
)?;
let block_shift =
<<T as pallet::Config>::NetworkDataHandler as NetworkDataInspectHandler<NetworkData>>::get(&network_id)
.unwrap()
.release_delay
.unwrap();
frame_system::Pallet::<T>::set_block_number((block_shift + 1).saturated_into());
}: _(RawOrigin::Signed(user_account), network_id.into(), companion_id)
verify { verify {
assert_eq!(SlowClap::<T>::companions(network_id, companion_id), None); assert_eq!(<<T as pallet::Config>::Currency>::total_balance(&receiver), amount);
assert_eq!(SlowClap::<T>::companion_details(companion_id), None);
assert_eq!(SlowClap::<T>::current_companion_id(), companion_id + 1);
} }
impl_benchmark_test_suite!( impl_benchmark_test_suite!(

View File

@ -13,7 +13,7 @@ use frame_support::{
EstimateNextSessionRotation, ValidatorSet, ValidatorSetWithIdentification, EstimateNextSessionRotation, ValidatorSet, ValidatorSetWithIdentification,
OneSessionHandler, Get, OneSessionHandler, Get,
}, },
PalletId, BoundedSlice, WeakBoundedVec, BoundedSlice, WeakBoundedVec,
}; };
use frame_system::{ use frame_system::{
@ -188,12 +188,6 @@ pub struct Clap<AccountId, NetworkId, Balance> {
pub amount: Balance, pub amount: Balance,
} }
#[derive(Default, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo)]
pub struct AuthorityClapsInfo {
pub total: u32,
pub individual: BTreeMap<AuthIndex, SessionAuthorityInfo>,
}
#[derive(Default, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo)] #[derive(Default, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo)]
pub struct SessionAuthorityInfo { pub struct SessionAuthorityInfo {
pub claps: u32, pub claps: u32,
@ -305,9 +299,6 @@ pub mod pallet {
#[pallet::constant] #[pallet::constant]
type UnsignedPriority: Get<TransactionPriority>; type UnsignedPriority: Get<TransactionPriority>;
#[pallet::constant]
type TreasuryPalletId: Get<PalletId>;
type WeightInfo: WeightInfo; type WeightInfo: WeightInfo;
} }
@ -333,12 +324,11 @@ pub mod pallet {
#[pallet::error] #[pallet::error]
pub enum Error<T> { pub enum Error<T> {
NotAnAuthority, NotAnAuthority,
ClapForThePastSession, ClapForWrongSession,
CurrentValidatorIsDisabled, CurrentValidatorIsDisabled,
AlreadyClapped, AlreadyClapped,
UnregisteredClapRemove, UnregisteredClapRemove,
TooMuchAuthorities, TooMuchAuthorities,
NotEnoughToApplause,
CouldNotAccumulateCommission, CouldNotAccumulateCommission,
CouldNotIncreaseGatekeeperAmount, CouldNotIncreaseGatekeeperAmount,
} }
@ -369,25 +359,13 @@ pub mod pallet {
ValueQuery ValueQuery
>; >;
#[pallet::storage]
#[pallet::getter(fn authorities_claps)]
pub(super) type AuthoritiesClaps<T: Config> = StorageDoubleMap<
_,
Twox64Concat,
T::AuthorityId,
Twox64Concat,
H256,
bool,
ValueQuery,
>;
#[pallet::storage] #[pallet::storage]
#[pallet::getter(fn claps_in_session)] #[pallet::getter(fn claps_in_session)]
pub(super) type ClapsInSession<T: Config> = StorageMap< pub(super) type ClapsInSession<T: Config> = StorageMap<
_, _,
Twox64Concat, Twox64Concat,
SessionIndex, SessionIndex,
AuthorityClapsInfo, BTreeMap<AuthIndex, SessionAuthorityInfo>,
ValueQuery, ValueQuery,
>; >;
@ -479,7 +457,7 @@ pub mod pallet {
let authorities = Authorities::<T>::get(); let authorities = Authorities::<T>::get();
let authority = match authorities.get(clap.authority_index as usize) { let authority = match authorities.get(clap.authority_index as usize) {
Some(authority) => authority, Some(authority) => authority,
None => return InvalidTransaction::BadProof.into(), None => return InvalidTransaction::BadSigner.into(),
}; };
let signature_valid = clap.using_encoded(|encoded_clap| { let signature_valid = clap.using_encoded(|encoded_clap| {
@ -518,7 +496,7 @@ impl<T: Config> Pallet<T> {
fn try_slow_clap(clap: &Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>) -> DispatchResult { fn try_slow_clap(clap: &Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>) -> DispatchResult {
let current_session_index = T::ValidatorSet::session_index(); let current_session_index = T::ValidatorSet::session_index();
ensure!(current_session_index == clap.session_index, Error::<T>::ClapForThePastSession); ensure!(current_session_index == clap.session_index, Error::<T>::ClapForWrongSession);
let authorities = Authorities::<T>::get(); let authorities = Authorities::<T>::get();
ensure!(authorities.get(clap.authority_index as usize).is_some(), Error::<T>::NotAnAuthority); ensure!(authorities.get(clap.authority_index as usize).is_some(), Error::<T>::NotAnAuthority);
@ -543,15 +521,14 @@ impl<T: Config> Pallet<T> {
})?; })?;
ClapsInSession::<T>::try_mutate(&clap.session_index, |claps_details| { ClapsInSession::<T>::try_mutate(&clap.session_index, |claps_details| {
if claps_details.individual.get(&clap.authority_index).map(|x| x.disabled).unwrap_or_default() { if claps_details.get(&clap.authority_index).map(|x| x.disabled).unwrap_or_default() {
return Err(Error::<T>::CurrentValidatorIsDisabled); return Err(Error::<T>::CurrentValidatorIsDisabled);
} }
(*claps_details).total.saturating_inc(); (*claps_details)
(*claps_details).individual
.entry(clap.authority_index) .entry(clap.authority_index)
.and_modify(|individual| (*individual).claps.saturating_inc()) .and_modify(|individual| (*individual).claps.saturating_inc())
.or_default(); .or_insert(SessionAuthorityInfo { claps: 1u32, disabled: false });
Ok(()) Ok(())
})?; })?;
@ -888,7 +865,6 @@ impl<T: Config> Pallet<T> {
} }
let number_of_claps = ClapsInSession::<T>::get(session_index) let number_of_claps = ClapsInSession::<T>::get(session_index)
.individual
.entry(authority_index as AuthIndex) .entry(authority_index as AuthIndex)
.or_default() .or_default()
.claps; .claps;
@ -905,10 +881,17 @@ impl<T: Config> Pallet<T> {
if !authorities.is_empty() { if !authorities.is_empty() {
assert!(Authorities::<T>::get().is_empty(), "Authorities are already initilized!"); assert!(Authorities::<T>::get().is_empty(), "Authorities are already initilized!");
let bounded_authorities = BoundedSlice::<'_, _, T::MaxAuthorities>::try_from(authorities) let bounded_authorities = BoundedSlice::<'_, _, T::MaxAuthorities>::try_from(authorities)
.expect("more than the maximum number of clappers"); .expect("more than the maximum number of authorities");
Authorities::<T>::put(bounded_authorities); Authorities::<T>::put(bounded_authorities);
} }
} }
#[cfg(test)]
fn set_test_authorities(authorities: Vec<T::AuthorityId>) {
let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities)
.expect("more than the maximum number of authorities");
Authorities::<T>::put(bounded_authorities);
}
} }
impl<T: Config> sp_runtime::BoundToRuntimeAppPublic for Pallet<T> { impl<T: Config> sp_runtime::BoundToRuntimeAppPublic for Pallet<T> {
@ -948,17 +931,16 @@ impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
let validators = T::ValidatorSet::validators(); let validators = T::ValidatorSet::validators();
let authorities = Authorities::<T>::get(); let authorities = Authorities::<T>::get();
let claps_details = ClapsInSession::<T>::get(session_index); let (sum_claps, total_claps) = ClapsInSession::<T>::get(&session_index)
let total_claps_in_session = claps_details.total;
let average_claps = claps_details
.individual
.iter() .iter()
.filter(|(_, value)| !value.disabled) .filter(|(_, value)| !value.disabled)
.fold(0u32, |acc, (_, value)| acc.saturating_add(value.claps)) .fold((0u32, 0u32), |(sum, total), (_, value)|
.checked_div(total_claps_in_session) (sum.saturating_add(value.claps), total.saturating_add(1))
.unwrap_or_default(); );
// TODO: seems like it's not working let average_claps = sum_claps
.checked_div(total_claps)
.unwrap_or_default();
let offenders = validators let offenders = validators
.into_iter() .into_iter()
@ -988,7 +970,6 @@ impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
let session_index = T::ValidatorSet::session_index(); let session_index = T::ValidatorSet::session_index();
ClapsInSession::<T>::mutate(&session_index, |claps_details| { ClapsInSession::<T>::mutate(&session_index, |claps_details| {
(*claps_details) (*claps_details)
.individual
.entry(validator_index as AuthIndex) .entry(validator_index as AuthIndex)
.and_modify(|individual| (*individual).disabled = true) .and_modify(|individual| (*individual).disabled = true)
.or_insert(SessionAuthorityInfo { claps: 0u32, disabled: true }); .or_insert(SessionAuthorityInfo { claps: 0u32, disabled: true });

View File

@ -11,13 +11,16 @@ use pallet_session::historical as pallet_session_historical;
use sp_runtime::{ use sp_runtime::{
testing::{TestXt, UintAuthorityId}, testing::{TestXt, UintAuthorityId},
traits::ConvertInto, traits::ConvertInto,
BuildStorage, Permill, Permill,
}; };
use sp_staking::{ use sp_staking::{
offence::{OffenceError, ReportOffence}, offence::{OffenceError, ReportOffence},
SessionIndex, SessionIndex,
}; };
#[cfg(feature = "runtime-benchmarks")]
use sp_runtime::BuildStorage;
use crate as slow_clap; use crate as slow_clap;
use crate::Config; use crate::Config;
@ -84,24 +87,22 @@ impl ReportOffence<u64, IdentificationTuple, Offence> for OffenceHandler {
} }
} }
pub fn alice_account_id() -> <Runtime as frame_system::Config>::AccountId { 69 }
pub fn eve_account_id() -> <Runtime as frame_system::Config>::AccountId { 1337 }
pub fn new_test_ext() -> sp_io::TestExternalities { pub fn new_test_ext() -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::<Runtime>::default() let t = frame_system::GenesisConfig::<Runtime>::default()
.build_storage() .build_storage()
.unwrap(); .unwrap();
pallet_balances::GenesisConfig::<Runtime> {
balances: vec![ (alice_account_id(), 100) ],
}
.assimilate_storage(&mut t)
.unwrap();
let mut result = sp_io::TestExternalities::new(t); let mut result = sp_io::TestExternalities::new(t);
result.execute_with(|| { result.execute_with(|| {
System::set_block_number(1); for i in 1..=3 {
System::inc_providers(&i);
assert_eq!(Session::set_keys(
RuntimeOrigin::signed(i),
i.into(),
vec![],
), Ok(()));
}
}); });
result result
@ -167,6 +168,7 @@ impl frame_support::traits::EstimateNextSessionRotation<u64> for TestNextSession
impl ghost_networks::Config for Runtime { impl ghost_networks::Config for Runtime {
type RuntimeEvent = RuntimeEvent; type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type NetworkId = u32; type NetworkId = u32;
type RegisterOrigin = EnsureRoot<Self::AccountId>; type RegisterOrigin = EnsureRoot<Self::AccountId>;
type UpdateOrigin = EnsureRoot<Self::AccountId>; type UpdateOrigin = EnsureRoot<Self::AccountId>;
@ -199,23 +201,15 @@ impl Config for Runtime {
type ReportUnresponsiveness = OffenceHandler; type ReportUnresponsiveness = OffenceHandler;
type MaxAuthorities = ConstU32<5>; type MaxAuthorities = ConstU32<5>;
type MaxNumberOfClaps = ConstU32<100>; type ApplauseThreshold = ConstU32<50>;
type ApplauseThreshold = ConstU32<0>; type OffenceThreshold = ConstU32<75>;
type MaxAuthorityInfoInSession = ConstU32<5_000>;
type OffenceThreshold = ConstU32<40>;
type UnsignedPriority = ConstU64<{ 1 << 20 }>; type UnsignedPriority = ConstU64<{ 1 << 20 }>;
type TreasuryPalletId = TreasuryPalletId;
type WeightInfo = (); type WeightInfo = ();
} }
pub type Extrinsic = TestXt<RuntimeCall, ()>; pub type Extrinsic = TestXt<RuntimeCall, ()>;
// impl frame_system::offchain::SigningTypes for Runtime {
// type Public = <Signature as Verify>::Signer;
// type Signature = Signature;
// }
impl<LocalCall> frame_system::offchain::SendTransactionTypes<LocalCall> for Runtime impl<LocalCall> frame_system::offchain::SendTransactionTypes<LocalCall> for Runtime
where where
RuntimeCall: From<LocalCall>, RuntimeCall: From<LocalCall>,
@ -224,30 +218,16 @@ where
type Extrinsic = Extrinsic; type Extrinsic = Extrinsic;
} }
// impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime pub fn advance_session() {
// where let now = System::block_number().max(1);
// RuntimeCall: From<LocalCall>, System::set_block_number(now + 1);
// { Session::rotate_session();
// fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
// call: Self::OverarchingCall,
// _public: Self::Public,
// _account: Self::AccountId,
// nonce: Self::Nonce,
// ) -> Option<(RuntimeCall, <Extrinsic as ExtrinsicT>::SignaturePayload)> {
// Some((call, (nonce.into(), ())))
// }
// }
// pub fn advance_session() { let authorities = Session::validators()
// let now = System::block_number().max(1); .into_iter()
// System::set_block_number(now + 1); .map(UintAuthorityId)
// Session::rotate_session(); .collect();
//
// let authorities = Session::validators() SlowClap::set_test_authorities(authorities);
// .into_iter() assert_eq!(Session::current_index(), (now / Period::get()) as u32);
// .map(UintAuthorityId) }
// .collect();
//
// SlowClap::set_authorities(authorities);
// assert_eq!(Session::current_index(), (now / Period::get()) as u32);
// }

File diff suppressed because it is too large Load Diff