Compare commits

..

No commits in common. "04a63e234ddfa6ede7fbb0bb00e951536d69268e" and "fa2cb811a843f4478972fb37201b06d3b3fd85df" have entirely different histories.

11 changed files with 780 additions and 658 deletions

6
Cargo.lock generated
View File

@ -3504,7 +3504,7 @@ dependencies = [
[[package]] [[package]]
name = "ghost-claims" name = "ghost-claims"
version = "0.2.3" version = "0.2.2"
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.3" version = "0.1.2"
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.17" version = "0.3.16"
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.3" version = "0.2.2"
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,9 +20,8 @@ extern crate alloc;
#[cfg(not(feature = "std"))] #[cfg(not(feature = "std"))]
use alloc::{format, string::String}; use alloc::{format, string::String};
mod weights; pub 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,104 +1,9 @@
// This file is part of Ghost Network. use frame_support::weights::Weight;
// 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 () {
/// Storage: `System::Account` (r:2 w:2) fn claim() -> Weight { Weight::zero() }
/// 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.3" version = "0.1.2"
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> {
pub bridged_out: Balance, bridged_out: Balance,
pub bridged_in: Balance, 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 Normal file → Executable file
View File

@ -1,6 +1,6 @@
[package] [package]
name = "ghost-slow-clap" name = "ghost-slow-clap"
version = "0.3.17" version = "0.3.16"
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,7 +4,12 @@ use super::*;
use frame_benchmarking::v1::*; use frame_benchmarking::v1::*;
use frame_system::RawOrigin; use frame_system::RawOrigin;
use frame_support::traits::fungible::Inspect; use frame_support::traits::fungible::{Inspect, Mutate};
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]);
@ -12,40 +17,184 @@ pub fn create_account<T: Config>() -> T::AccountId {
.expect("32 bytes always construct an AccountId32") .expect("32 bytes always construct an AccountId32")
} }
benchmarks! { pub fn create_companions<T: Config>(
slow_clap { 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 minimum_balance = <<T as pallet::Config>::Currency>::minimum_balance();
let receiver = create_account::<T>();
let amount = minimum_balance + minimum_balance; let amount = minimum_balance + minimum_balance;
let total_amount = amount.saturating_mul(j.into());
let network_id = NetworkIdOf::<T>::default(); 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 authorities = vec![T::AuthorityId::generate_pair(None)];
let bounded_authorities = let bounded_authorities =
WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities.clone()) WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities.clone())
.map_err(|()| "more than the maximum number of keys provided")?; .map_err(|()| "more than the maximum number of keys provided")?;
Authorities::<T>::put(bounded_authorities); Authorities::<T>::put(bounded_authorities);
let clap = Clap { for index in 0..j {
session_index: 0, companions.insert(
index.into(),
amount,
);
}
for _ in 0..i {
claps.push(Clap {
session_index: 1,
authority_index: 0, authority_index: 0,
network_id,
transaction_hash: H256::repeat_byte(1u8), transaction_hash: H256::repeat_byte(1u8),
block_number: 69, block_number: 69,
removed: false, removed: true,
network_id, receiver: create_account::<T>(),
receiver: receiver.clone(), amount: total_amount,
amount, companions: companions.clone(),
}; });
}
let authority_id = authorities let authority_id = authorities
.get(0usize) .get(0usize)
.expect("first authority should exist"); .expect("first authority should exist");
let encoded_clap = clap.encode(); let encoded_claps = claps.encode();
let signature = authority_id.sign(&encoded_clap) let signature = authority_id.sign(&encoded_claps)
.ok_or("couldn't make signature")?; .ok_or("couldn't make signature")?;
}: _(RawOrigin::None, clap, signature) Ok((claps, signature))
}
benchmarks! {
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 { verify {
assert_eq!(<<T as pallet::Config>::Currency>::total_balance(&receiver), amount); let minimum_balance = <<T as pallet::Config>::Currency>::minimum_balance();
let total_amount = (minimum_balance + minimum_balance).saturating_mul(j.into());
}
propose_companion {
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();
// T::NetworkDataHandler::register(network_id.into(), NetworkData {
// chain_name: "Ethereum".into(),
// // https://nd-422-757-666.p2pify.com/0a9d79d93fb2f4a4b1e04695da2b77a7/
// default_endpoint:
// "https://base-mainnet.core.chainstack.com/2fc1de7f08c0465f6a28e3c355e0cb14/".into(),
// finality_delay: Some(50),
// release_delay: Some(100),
// 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 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 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)?;
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 {
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 {
assert_eq!(SlowClap::<T>::companions(network_id, companion_id), None);
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,
}, },
BoundedSlice, WeakBoundedVec, PalletId, BoundedSlice, WeakBoundedVec,
}; };
use frame_system::{ use frame_system::{
@ -188,6 +188,12 @@ 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,
@ -299,6 +305,9 @@ 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;
} }
@ -324,11 +333,12 @@ pub mod pallet {
#[pallet::error] #[pallet::error]
pub enum Error<T> { pub enum Error<T> {
NotAnAuthority, NotAnAuthority,
ClapForWrongSession, ClapForThePastSession,
CurrentValidatorIsDisabled, CurrentValidatorIsDisabled,
AlreadyClapped, AlreadyClapped,
UnregisteredClapRemove, UnregisteredClapRemove,
TooMuchAuthorities, TooMuchAuthorities,
NotEnoughToApplause,
CouldNotAccumulateCommission, CouldNotAccumulateCommission,
CouldNotIncreaseGatekeeperAmount, CouldNotIncreaseGatekeeperAmount,
} }
@ -359,13 +369,25 @@ 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,
BTreeMap<AuthIndex, SessionAuthorityInfo>, AuthorityClapsInfo,
ValueQuery, ValueQuery,
>; >;
@ -457,7 +479,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::BadSigner.into(), None => return InvalidTransaction::BadProof.into(),
}; };
let signature_valid = clap.using_encoded(|encoded_clap| { let signature_valid = clap.using_encoded(|encoded_clap| {
@ -496,7 +518,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>::ClapForWrongSession); ensure!(current_session_index == clap.session_index, Error::<T>::ClapForThePastSession);
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);
@ -521,14 +543,15 @@ 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.get(&clap.authority_index).map(|x| x.disabled).unwrap_or_default() { if claps_details.individual.get(&clap.authority_index).map(|x| x.disabled).unwrap_or_default() {
return Err(Error::<T>::CurrentValidatorIsDisabled); return Err(Error::<T>::CurrentValidatorIsDisabled);
} }
(*claps_details) (*claps_details).total.saturating_inc();
(*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_insert(SessionAuthorityInfo { claps: 1u32, disabled: false }); .or_default();
Ok(()) Ok(())
})?; })?;
@ -865,6 +888,7 @@ 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;
@ -881,17 +905,10 @@ 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 authorities"); .expect("more than the maximum number of clappers");
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> {
@ -931,17 +948,18 @@ 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 (sum_claps, total_claps) = ClapsInSession::<T>::get(&session_index) let claps_details = 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, 0u32), |(sum, total), (_, value)| .fold(0u32, |acc, (_, value)| acc.saturating_add(value.claps))
(sum.saturating_add(value.claps), total.saturating_add(1)) .checked_div(total_claps_in_session)
);
let average_claps = sum_claps
.checked_div(total_claps)
.unwrap_or_default(); .unwrap_or_default();
// TODO: seems like it's not working
let offenders = validators let offenders = validators
.into_iter() .into_iter()
.enumerate() .enumerate()
@ -970,6 +988,7 @@ 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,16 +11,13 @@ use pallet_session::historical as pallet_session_historical;
use sp_runtime::{ use sp_runtime::{
testing::{TestXt, UintAuthorityId}, testing::{TestXt, UintAuthorityId},
traits::ConvertInto, traits::ConvertInto,
Permill, BuildStorage, 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;
@ -87,22 +84,24 @@ 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 t = frame_system::GenesisConfig::<Runtime>::default() let mut 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(|| {
for i in 1..=3 { System::set_block_number(1);
System::inc_providers(&i);
assert_eq!(Session::set_keys(
RuntimeOrigin::signed(i),
i.into(),
vec![],
), Ok(()));
}
}); });
result result
@ -168,7 +167,6 @@ 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>;
@ -201,15 +199,23 @@ impl Config for Runtime {
type ReportUnresponsiveness = OffenceHandler; type ReportUnresponsiveness = OffenceHandler;
type MaxAuthorities = ConstU32<5>; type MaxAuthorities = ConstU32<5>;
type ApplauseThreshold = ConstU32<50>; type MaxNumberOfClaps = ConstU32<100>;
type OffenceThreshold = ConstU32<75>; type ApplauseThreshold = ConstU32<0>;
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>,
@ -218,16 +224,30 @@ where
type Extrinsic = Extrinsic; type Extrinsic = Extrinsic;
} }
pub fn advance_session() { // impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime
let now = System::block_number().max(1); // where
System::set_block_number(now + 1); // RuntimeCall: From<LocalCall>,
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(), ())))
// }
// }
let authorities = Session::validators() // pub fn advance_session() {
.into_iter() // let now = System::block_number().max(1);
.map(UintAuthorityId) // System::set_block_number(now + 1);
.collect(); // Session::rotate_session();
//
SlowClap::set_test_authorities(authorities); // let authorities = Session::validators()
assert_eq!(Session::current_index(), (now / Period::get()) as u32); // .into_iter()
} // .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