Compare commits

..

No commits in common. "main" and "pallet-networks" have entirely different histories.

12 changed files with 305 additions and 402 deletions

4
Cargo.lock generated
View File

@ -1186,7 +1186,7 @@ dependencies = [
[[package]] [[package]]
name = "casper-runtime" name = "casper-runtime"
version = "3.5.36" version = "3.5.31"
dependencies = [ dependencies = [
"casper-runtime-constants", "casper-runtime-constants",
"frame-benchmarking", "frame-benchmarking",
@ -3836,7 +3836,7 @@ dependencies = [
[[package]] [[package]]
name = "ghost-slow-clap" name = "ghost-slow-clap"
version = "0.3.53" version = "0.3.39"
dependencies = [ dependencies = [
"frame-benchmarking", "frame-benchmarking",
"frame-support", "frame-support",

126
README.md
View File

@ -150,8 +150,28 @@ rustup default stable
rustup update rustup update
``` ```
Add the nightly release and the nightly WebAssembly (wasm) targets
to your development environment by running the following commands:
```bash ```bash
rustup target add wasm32-unknown-unknown --toolchain stable rustup update nightly
```
```bash
rustup target add wasm32-unknown-unknown --toolchain nightly
```
```bash
rustup target add wasm32-unknown-unknown --toolchain stable-x86_64-unknown-linux-gnu
```
If you are trying to install WebAssembly (wasm) on an ARM-based processor like the ones in Raspberry Pi try this instead:
```bash
rustup target add wasm32-unknown-unknown --toolchain stable-aarch64-unknown-linux-gnu
```
**_IF error try_**
```bash
rustup target add wasm32-unknown-unknown --toolchain default
``` ```
Verify the configuration of your development environment by running Verify the configuration of your development environment by running
@ -160,6 +180,10 @@ the following command:
rustup show rustup show
``` ```
```bash
rustup +nightly show
```
You should see something like this: You should see something like this:
![images/img_9.png](images/img_9.png) ![images/img_9.png](images/img_9.png)
@ -170,6 +194,13 @@ Now run:
rustup component add rust-src --toolchain stable rustup component add rust-src --toolchain stable
``` ```
**_IF error try_**
```bash
rustup component add rust-src --toolchain default
```
## Install GHOST ## Install GHOST
Check if Git is already installed: Check if Git is already installed:
@ -180,7 +211,7 @@ git --version
Make a GHOST Directory and go to it: Make a GHOST Directory and go to it:
```bash ```bash
mkdir ~/ghost && cd ~/ghost mkdir ghost && cd ghost
``` ```
Clone GHOST Node Git: Clone GHOST Node Git:
@ -195,7 +226,7 @@ cd ghost-node
Compile the node template by running the following command: Compile the node template by running the following command:
```bash ```bash
./scripts/starter.sh --release cargo build --release
``` ```
The build can take up to 20 minutes depending on the specifications of your machine. The build can take up to 20 minutes depending on the specifications of your machine.
@ -203,6 +234,7 @@ The build can take up to 20 minutes depending on the specifications of your mach
![images/img_12.png](images/img_12.png) ![images/img_12.png](images/img_12.png)
# Boot Node Qualification # Boot Node Qualification
## Boot Node Qualification Test ## Boot Node Qualification Test
@ -288,7 +320,7 @@ Only `port 30333` should be opened.
Press _CTRL+C_ to stop the node. Press _CTRL+C_ to stop the node.
# Launching GHOST TestNet # Launching GHOST TestNet 3.1
Switch to main GIT branch: Switch to main GIT branch:
```bash ```bash
@ -316,7 +348,66 @@ To generate the node key use the following command:
./target/release/ghost key generate-node-key --bin --file=/etc/ghost/node-key ./target/release/ghost key generate-node-key --bin --file=/etc/ghost/node-key
``` ```
Feel free to backup the file on a separate storage device. Generate Wallet Key file with the following command:
```bash
./target/release/ghost key generate | grep "Secret seed" | awk '{$1=$2=""; sub(/^[ \t]+/, ""); print}' > /etc/ghost/wallet-key
```
Display the wallet-key on the screen by using cat command:
```bash
./target/release/ghost key inspect $(cat /etc/ghost/wallet-key)
```
![images/img_22.png](images/img_22.png)
Feel free to back the file on a separate storage device.
Generate Stash Key file with the following command:
```bash
./target/release/ghost key generate | grep "Secret seed" | awk '{$1=$2=""; sub(/^[ \t]+/, ""); print}' > /etc/ghost/stash-key
```
Display the stash-key on the screen by using cat command:
```bash
./target/release/ghost key inspect $(cat /etc/ghost/stash-key)
```
![images/img_23.png](images/img_23.png)
Generate Session Key file with the following command:
```bash
./target/release/ghost key generate | grep "Secret seed" | awk '{$1=$2=""; sub(/^[ \t]+/, ""); print}' > /etc/ghost/session-key
```
You have generates 4 types of Session Keys:
1. Session Key AUDI
2. Session Key BABE
3. Session Key SLOW
4. Session Key GRAN
Now let's display them!
Display the session-key//audi on the screen by using cat command:
```bash
./target/release/ghost key inspect "$(cat /etc/ghost/session-key)//audi"
```
![images/img_24.png](images/img_24.png)
Display the session-key//babe on the screen by using cat command:
```bash
./target/release/ghost key inspect "$(cat /etc/ghost/session-key)//babe"
```
![images/img_25.png](images/img_25.png)
Display the session-key//slow on the screen by using cat command:
```bash
./target/release/ghost key inspect "$(cat /etc/ghost/session-key)//slow"
```
![images/img_26.png](images/img_26.png)
Display the session-key//gran on the screen by using cat command:
```bash
./target/release/ghost key inspect "$(cat /etc/ghost/session-key)//gran" --scheme=ed25519
```
![images/img_27.png](images/img_27.png)
## Build and start the ghost-node ## Build and start the ghost-node
@ -346,7 +437,7 @@ sha256sum /etc/ghost/casper.json
You should see: You should see:
``` ```
9da6045ed6d4fd844e3939573b31c013d0e564e542029330faa6d978cb4a915a ad653233c978bfd00c5e4525b17628632bc4319c5f5f4b4dcc2f050ef3c3d145
``` ```
Create running `ghost-node` service that starts on system boot using `--unit-file` flag. Create running `ghost-node` service that starts on system boot using `--unit-file` flag.
@ -372,7 +463,10 @@ To choose default options press Enter here:
![images/img_30.png](images/img_30.png) ![images/img_30.png](images/img_30.png)
If you want to validate from this node press Enter: Currently, you have to qualify to become a validator node through [GHOST Whales](https://ghostchain.io/whales-apply).
If you were NOT included in the [ghosties file](https://git.ghostchain.io/ghostchain/ghost-node/src/branch/main/service/ghosties) then you cannot be a validator node,
and you can only be a full node so for `disable validator mode? [y/N]` type `y`.
If you were included in the ghosties file you can press Enter:
``` ```
disable validator mode? [y/N]: y disable validator mode? [y/N]: y
``` ```
@ -417,6 +511,17 @@ Type `y` and press _Enter_ for create dedicated user for running `ghost-node`:
![images/img_37.png](images/img_37.png) ![images/img_37.png](images/img_37.png)
Now you can check whether or not the keys on your GHOST Node match those
in the [ghosties file](https://git.ghostchain.io/ghostchain/ghost-node/src/branch/main/service/ghosties) on GHOST Git.
If you are running a **Validator Node** and if you have followed
the Generating Keys Part you will see all `[+]`.
If you are a running a **Full Node** you will see errors:
(Press _Enter_ for prompts)
```bash
./scripts/starter.sh --check-keys
```
Full Node: Full Node:
![images/img_38.png](images/img_38.png) ![images/img_38.png](images/img_38.png)
@ -430,7 +535,7 @@ Start `ghost-node`:
sudo systemctl start ghost-node sudo systemctl start ghost-node
``` ```
Wait ~60 seconds! Wait 60 seconds!
Check node is started: Check node is started:
```bash ```bash
@ -440,6 +545,11 @@ sudo systemctl status ghost-node
For exit press _CTRL+C_ For exit press _CTRL+C_
In order to insert keys run the following flags `--check-keys` `--insert-keys`:
```bash
./scripts/starter.sh --check-keys --insert-keys
```
Restart `ghost-node`: Restart `ghost-node`:
```bash ```bash
sudo systemctl restart ghost-node sudo systemctl restart ghost-node

View File

@ -1,6 +1,6 @@
[package] [package]
name = "ghost-slow-clap" name = "ghost-slow-clap"
version = "0.3.53" version = "0.3.40"
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

@ -50,15 +50,10 @@ benchmarks! {
self_applause { self_applause {
let session_index = T::ValidatorSet::session_index(); let session_index = T::ValidatorSet::session_index();
let next_session_index = session_index.saturating_add(1); let authorities = vec![T::AuthorityId::generate_pair(None)];
let authorities = vec![
T::AuthorityId::generate_pair(None),
T::AuthorityId::generate_pair(None),
];
let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities.clone()) let bounded_authorities = 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>::set(&session_index, bounded_authorities.clone()); Authorities::<T>::set(&session_index, bounded_authorities);
Authorities::<T>::set(&next_session_index, bounded_authorities);
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 receiver = create_account::<T>();
@ -73,7 +68,6 @@ benchmarks! {
&network_id, &network_id,
); );
let storage_key = (session_index, &transaction_hash, &unique_transaction_hash); let storage_key = (session_index, &transaction_hash, &unique_transaction_hash);
let next_storage_key = (next_session_index, &transaction_hash, &unique_transaction_hash);
<Pallet::<T>>::trigger_nullification_for_benchmark(); <Pallet::<T>>::trigger_nullification_for_benchmark();
let clap = Clap { let clap = Clap {
@ -92,18 +86,11 @@ benchmarks! {
.expect("first authority should exist"); .expect("first authority should exist");
let encoded_clap = clap.encode(); let encoded_clap = clap.encode();
let signature = authority_id.sign(&encoded_clap).unwrap(); let signature = authority_id.sign(&encoded_clap).unwrap();
Pallet::<T>::slow_clap(RawOrigin::None.into(), clap, signature)?; <Pallet<T>>::slow_clap(RawOrigin::None.into(), clap, signature)?;
Pallet::<T>::trigger_nullification_for_benchmark(); <Pallet::<T>>::trigger_nullification_for_benchmark();
assert_eq!(<<T as pallet::Config>::Currency>::total_balance(&receiver), Default::default()); assert_eq!(<<T as pallet::Config>::Currency>::total_balance(&receiver), Default::default());
assert_eq!(ApplausesForTransaction::<T>::get(&storage_key), false); assert_eq!(ApplausesForTransaction::<T>::get(&storage_key), false);
frame_system::Pallet::<T>::on_initialize(1u32.into());
let mut fake_received_clap =
BoundedBTreeSet::<AuthIndex, T::MaxAuthorities>::new();
assert_eq!(fake_received_clap.try_insert(1).unwrap(), true);
pallet::ReceivedClaps::<T>::insert(&next_storage_key, fake_received_clap);
}: _(RawOrigin::Signed(receiver_clone), network_id, session_index, transaction_hash, receiver_clone.clone(), amount) }: _(RawOrigin::Signed(receiver_clone), network_id, session_index, transaction_hash, receiver_clone.clone(), amount)
verify { verify {
assert_eq!(<<T as pallet::Config>::Currency>::total_balance(&receiver), amount); assert_eq!(<<T as pallet::Config>::Currency>::total_balance(&receiver), amount);

View File

@ -9,7 +9,8 @@ use frame_support::{
pallet_prelude::*, pallet_prelude::*,
traits::{ traits::{
tokens::fungible::{Inspect, Mutate}, tokens::fungible::{Inspect, Mutate},
DisabledValidators, Get, OneSessionHandler, ValidatorSet, ValidatorSetWithIdentification, EstimateNextSessionRotation, Get, OneSessionHandler, ValidatorSet,
ValidatorSetWithIdentification,
}, },
WeakBoundedVec, WeakBoundedVec,
}; };
@ -71,7 +72,7 @@ const LOG_TARGET: &str = "runtime::ghost-slow-clap";
const DB_PREFIX: &[u8] = b"slow_clap::"; const DB_PREFIX: &[u8] = b"slow_clap::";
const FETCH_TIMEOUT_PERIOD: u64 = 3_000; const FETCH_TIMEOUT_PERIOD: u64 = 3_000;
const LOCK_BLOCK_EXPIRATION: u64 = 20; const LOCK_BLOCK_EXPIRATION: u64 = 10;
pub type AuthIndex = u32; pub type AuthIndex = u32;
@ -138,6 +139,7 @@ impl<NetworkId: core::fmt::Debug> core::fmt::Debug for OffchainErr<NetworkId> {
OffchainErr::UnknownNetworkType(ref network_id) => write!(fmt, "Unknown type for network #{:?}.", network_id), OffchainErr::UnknownNetworkType(ref network_id) => write!(fmt, "Unknown type for network #{:?}.", network_id),
OffchainErr::OffchainTimeoutPeriod(ref network_id) => write!(fmt, "Offchain request should be in-flight for network #{:?}.", network_id), OffchainErr::OffchainTimeoutPeriod(ref network_id) => write!(fmt, "Offchain request should be in-flight for network #{:?}.", network_id),
OffchainErr::TooManyRequests(ref network_id) => write!(fmt, "Too many requests over RPC endpoint for network #{:?}.", network_id), OffchainErr::TooManyRequests(ref network_id) => write!(fmt, "Too many requests over RPC endpoint for network #{:?}.", network_id),
} }
} }
} }
@ -164,7 +166,7 @@ type OffchainResult<T, A> = Result<A, OffchainErr<NetworkIdOf<T>>>;
pub mod pallet { pub mod pallet {
use super::*; use super::*;
const STORAGE_VERSION: StorageVersion = StorageVersion::new(2); const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
#[pallet::pallet] #[pallet::pallet]
#[pallet::storage_version(STORAGE_VERSION)] #[pallet::storage_version(STORAGE_VERSION)]
@ -181,6 +183,7 @@ pub mod pallet {
+ MaybeSerializeDeserialize + MaybeSerializeDeserialize
+ MaxEncodedLen; + MaxEncodedLen;
type NextSessionRotation: EstimateNextSessionRotation<BlockNumberFor<Self>>;
type ValidatorSet: ValidatorSetWithIdentification<Self::AccountId>; type ValidatorSet: ValidatorSetWithIdentification<Self::AccountId>;
type Currency: Inspect<Self::AccountId> + Mutate<Self::AccountId>; type Currency: Inspect<Self::AccountId> + Mutate<Self::AccountId>;
type NetworkDataHandler: NetworkDataBasicHandler type NetworkDataHandler: NetworkDataBasicHandler
@ -192,7 +195,6 @@ pub mod pallet {
IdentificationTuple<Self>, IdentificationTuple<Self>,
ThrottlingOffence<IdentificationTuple<Self>>, ThrottlingOffence<IdentificationTuple<Self>>,
>; >;
type DisabledValidators: DisabledValidators;
#[pallet::constant] #[pallet::constant]
type MaxAuthorities: Get<u32>; type MaxAuthorities: Get<u32>;
@ -209,16 +211,12 @@ pub mod pallet {
#[pallet::constant] #[pallet::constant]
type HistoryDepth: Get<SessionIndex>; type HistoryDepth: Get<SessionIndex>;
#[pallet::constant]
type MinAuthoritiesNumber: Get<u32>;
type WeightInfo: WeightInfo; type WeightInfo: WeightInfo;
} }
#[pallet::event] #[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)] #[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> { pub enum Event<T: Config> {
BlackSwan,
AuthoritiesEquilibrium, AuthoritiesEquilibrium,
SomeAuthoritiesTrottling { SomeAuthoritiesTrottling {
throttling: Vec<IdentificationTuple<T>>, throttling: Vec<IdentificationTuple<T>>,
@ -240,6 +238,8 @@ pub mod pallet {
#[pallet::error] #[pallet::error]
pub enum Error<T> { pub enum Error<T> {
NotEnoughClaps, NotEnoughClaps,
NotAnAuthority,
CurrentValidatorIsDisabled,
AlreadyClapped, AlreadyClapped,
UnregisteredClapRemove, UnregisteredClapRemove,
TooMuchAuthorities, TooMuchAuthorities,
@ -294,16 +294,6 @@ pub mod pallet {
ValueQuery, ValueQuery,
>; >;
#[pallet::storage]
#[pallet::getter(fn validators)]
pub(super) type Validators<T: Config> = StorageMap<
_,
Twox64Concat,
SessionIndex,
WeakBoundedVec<ValidatorId<T>, T::MaxAuthorities>,
OptionQuery,
>;
#[pallet::genesis_config] #[pallet::genesis_config]
#[derive(frame_support::DefaultNoBound)] #[derive(frame_support::DefaultNoBound)]
pub struct GenesisConfig<T: Config> { pub struct GenesisConfig<T: Config> {
@ -340,7 +330,7 @@ pub mod pallet {
pub fn self_applause( pub fn self_applause(
origin: OriginFor<T>, origin: OriginFor<T>,
network_id: NetworkIdOf<T>, network_id: NetworkIdOf<T>,
prev_session_index: SessionIndex, session_index: SessionIndex,
transaction_hash: H256, transaction_hash: H256,
receiver: T::AccountId, receiver: T::AccountId,
amount: BalanceOf<T>, amount: BalanceOf<T>,
@ -348,7 +338,7 @@ pub mod pallet {
let _ = ensure_signed(origin)?; let _ = ensure_signed(origin)?;
Self::applause_if_posible( Self::applause_if_posible(
network_id, network_id,
prev_session_index, session_index,
transaction_hash, transaction_hash,
receiver, receiver,
amount, amount,
@ -388,21 +378,12 @@ pub mod pallet {
fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity { fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity {
if let Call::slow_clap { clap, signature } = call { if let Call::slow_clap { clap, signature } = call {
let (session_index, _) = Self::mended_session_index(&clap); let authorities = Authorities::<T>::get(&clap.session_index);
let authorities = Authorities::<T>::get(&session_index);
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::BadSigner.into(),
}; };
if ClapsInSession::<T>::get(&session_index)
.get(&clap.authority_index)
.map(|info| info.disabled)
.unwrap_or_default()
{
return InvalidTransaction::BadSigner.into();
}
let signature_valid = let signature_valid =
clap.using_encoded(|encoded_clap| authority.verify(&encoded_clap, signature)); clap.using_encoded(|encoded_clap| authority.verify(&encoded_clap, signature));
@ -478,42 +459,28 @@ impl<T: Config> Pallet<T> {
hex_str hex_str
} }
fn mended_session_index( fn try_slow_clap(clap: &Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>) -> DispatchResult {
clap: &Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>, let authorities = Authorities::<T>::get(&clap.session_index);
) -> (SessionIndex, H256) { ensure!(
let prev_session_index = clap.session_index.saturating_sub(1); authorities.get(clap.authority_index as usize).is_some(),
Error::<T>::NotAnAuthority
);
ensure!(
ClapsInSession::<T>::get(&clap.session_index)
.get(&clap.authority_index)
.map(|info| !info.disabled)
.unwrap_or(true),
Error::<T>::CurrentValidatorIsDisabled
);
let clap_unique_hash = let clap_unique_hash =
Self::generate_unique_hash(&clap.receiver, &clap.amount, &clap.network_id); Self::generate_unique_hash(&clap.receiver, &clap.amount, &clap.network_id);
let received_claps_key = ( let received_claps_key = (
prev_session_index, clap.session_index,
&clap.transaction_hash, &clap.transaction_hash,
&clap_unique_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);
let disabled_authorities = claps_in_session
.values()
.filter(|info| info.disabled)
.count();
let active_authorities = Authorities::<T>::get(&session_index)
.len()
.saturating_sub(disabled_authorities);
let received_claps_key = (session_index, &clap.transaction_hash, &clap_unique_hash);
let number_of_received_claps = let number_of_received_claps =
ReceivedClaps::<T>::try_mutate(&received_claps_key, |tree_of_claps| { ReceivedClaps::<T>::try_mutate(&received_claps_key, |tree_of_claps| {
let number_of_claps = tree_of_claps.len(); let number_of_claps = tree_of_claps.len();
@ -531,15 +498,15 @@ impl<T: Config> Pallet<T> {
} }
})?; })?;
claps_in_session ClapsInSession::<T>::mutate(&clap.session_index, |claps_details| {
(*claps_details)
.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 { .or_insert(SessionAuthorityInfo {
claps: 1u32, claps: 1u32,
disabled: false, disabled: false,
}); });
});
ClapsInSession::<T>::insert(&session_index, claps_in_session);
Self::deposit_event(Event::<T>::Clapped { Self::deposit_event(Event::<T>::Clapped {
authority_id: clap.authority_index, authority_id: clap.authority_index,
@ -550,7 +517,7 @@ impl<T: Config> Pallet<T> {
}); });
let enough_authorities = let enough_authorities =
Perbill::from_rational(number_of_received_claps as u32, active_authorities as u32) Perbill::from_rational(number_of_received_claps as u32, authorities.len() as u32)
> Perbill::from_percent(T::ApplauseThreshold::get()); > Perbill::from_percent(T::ApplauseThreshold::get());
if enough_authorities { if enough_authorities {
@ -607,75 +574,32 @@ impl<T: Config> Pallet<T> {
fn applause_if_posible( fn applause_if_posible(
network_id: NetworkIdOf<T>, network_id: NetworkIdOf<T>,
prev_session_index: SessionIndex, session_index: SessionIndex,
transaction_hash: H256, transaction_hash: H256,
receiver: T::AccountId, receiver: T::AccountId,
amount: BalanceOf<T>, amount: BalanceOf<T>,
) -> DispatchResult { ) -> DispatchResult {
let curr_session_index = prev_session_index.saturating_add(1);
let clap_unique_hash = Self::generate_unique_hash(&receiver, &amount, &network_id); 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_authorities = Authorities::<T>::get(&prev_session_index)
.into_iter()
.enumerate()
.map(|(i, auth)| (auth, i as AuthIndex))
.collect::<BTreeMap<T::AuthorityId, AuthIndex>>();
let curr_authorities = Authorities::<T>::get(&curr_session_index);
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 mut previous_claps = ClapsInSession::<T>::get(&prev_session_index);
let mut total_received_claps =
ReceivedClaps::<T>::get(&prev_received_claps_key).into_inner();
for (auth_index, info) in ClapsInSession::<T>::get(&curr_session_index).iter() {
if !info.disabled {
continue;
}
if let Some(curr_authority) = curr_authorities.get(*auth_index as usize) {
if let Some(prev_position) = prev_authorities.get(&curr_authority) {
previous_claps
.entry(*prev_position as AuthIndex)
.and_modify(|individual| (*individual).disabled = true)
.or_insert(SessionAuthorityInfo {
claps: 0u32,
disabled: true,
});
}
}
}
for auth_index in ReceivedClaps::<T>::get(&curr_received_claps_key).into_iter() {
if let Some(curr_authority) = curr_authorities.get(auth_index as usize) {
if let Some(prev_position) = prev_authorities.get(&curr_authority) {
let _ = total_received_claps.insert(*prev_position as AuthIndex);
}
}
}
let disabled_authorities = previous_claps.values().filter(|info| info.disabled).count();
let active_authorities = prev_authorities.len().saturating_sub(disabled_authorities);
let clap = Clap { let clap = Clap {
authority_index: Default::default(), authority_index: Default::default(),
block_number: Default::default(), block_number: Default::default(),
removed: Default::default(), removed: false,
session_index: Default::default(), session_index,
transaction_hash: Default::default(),
network_id, network_id,
receiver, receiver,
amount, amount,
transaction_hash,
}; };
let enough_authorities = let enough_authorities = Perbill::from_rational(
Perbill::from_rational(total_received_claps.len() as u32, active_authorities as u32) ReceivedClaps::<T>::get(&received_claps_key).len() as u32,
> Perbill::from_percent(T::ApplauseThreshold::get()); Authorities::<T>::get(session_index).len() as u32,
) > Perbill::from_percent(T::ApplauseThreshold::get());
ensure!(enough_authorities, Error::<T>::NotEnoughClaps); ensure!(enough_authorities, Error::<T>::NotEnoughClaps);
Self::try_applause(&clap, &prev_received_claps_key)?; Self::try_applause(&clap, &received_claps_key)?;
Ok(()) Ok(())
} }
@ -842,17 +766,14 @@ impl<T: Config> Pallet<T> {
Some(_) if from_block.le(&to_block) => { Some(_) if from_block.le(&to_block) => {
let adjusted_to_block = estimated_block let adjusted_to_block = estimated_block
.checked_sub(from_block) .checked_sub(from_block)
.map(|current_distance| { .map(|current_distance| current_distance
current_distance
.le(&max_block_distance) .le(&max_block_distance)
.then(|| estimated_block) .then(|| estimated_block)
}) )
.flatten() .flatten()
.unwrap_or( .unwrap_or(from_block
from_block
.saturating_add(max_block_distance) .saturating_add(max_block_distance)
.min(estimated_block), .min(estimated_block));
);
(from_block, adjusted_to_block) (from_block, adjusted_to_block)
} }
_ => (to_block, to_block), _ => (to_block, to_block),
@ -897,20 +818,6 @@ impl<T: Config> Pallet<T> {
Ok(Some(new_evm_block)) Ok(Some(new_evm_block))
} }
EvmResponseType::TransactionLogs(evm_logs) => { EvmResponseType::TransactionLogs(evm_logs) => {
if ClapsInSession::<T>::get(&session_index)
.get(&authority_index)
.map(|info| info.disabled)
.unwrap_or_default()
{
log::info!(
target: LOG_TARGET,
"🧐 Authority #{:?} disabled in session {:?}; no claps available",
authority_index,
session_index
);
return Ok(None);
}
let claps: Vec<_> = evm_logs let claps: Vec<_> = evm_logs
.iter() .iter()
.filter_map(|log| { .filter_map(|log| {
@ -1119,34 +1026,16 @@ impl<T: Config> Pallet<T> {
let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities) let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities)
.expect("more than the maximum number of authorities"); .expect("more than the maximum number of authorities");
let validators = T::ValidatorSet::validators();
let bounded_validators = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(validators)
.expect("more than the maximum number of validators");
if let Some(target_session_index) = session_index.checked_sub(T::HistoryDepth::get()) { if let Some(target_session_index) = session_index.checked_sub(T::HistoryDepth::get()) {
Self::clear_history(&target_session_index); Self::clear_history(&target_session_index);
} }
Validators::<T>::insert(&session_index, bounded_validators);
Authorities::<T>::set(&session_index, bounded_authorities); Authorities::<T>::set(&session_index, bounded_authorities);
ClapsInSession::<T>::set(&session_index, Default::default());
let mut disabled_validators: BTreeMap<AuthIndex, SessionAuthorityInfo> = Default::default();
for disabled_index in T::DisabledValidators::disabled_validators().iter() {
let _ = disabled_validators.insert(
*disabled_index,
SessionAuthorityInfo {
claps: 0u32,
disabled: true,
},
);
}
ClapsInSession::<T>::set(&session_index, disabled_validators);
} }
fn clear_history(target_session_index: &SessionIndex) { fn clear_history(target_session_index: &SessionIndex) {
ClapsInSession::<T>::remove(target_session_index); ClapsInSession::<T>::remove(target_session_index);
Authorities::<T>::remove(target_session_index);
Validators::<T>::remove(target_session_index);
let mut cursor = ReceivedClaps::<T>::clear_prefix((target_session_index,), u32::MAX, None); let mut cursor = ReceivedClaps::<T>::clear_prefix((target_session_index,), u32::MAX, None);
debug_assert!(cursor.maybe_cursor.is_none()); debug_assert!(cursor.maybe_cursor.is_none());
cursor = cursor =
@ -1198,8 +1087,8 @@ impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
} }
fn on_before_session_ending() { fn on_before_session_ending() {
let session_index = T::ValidatorSet::session_index().saturating_sub(1); let session_index = T::ValidatorSet::session_index();
let validators = Validators::<T>::get(&session_index).unwrap_or_default(); let validators = T::ValidatorSet::validators();
let authorities_len = Authorities::<T>::get(&session_index).len(); let authorities_len = Authorities::<T>::get(&session_index).len();
let claps_in_session = ClapsInSession::<T>::get(&session_index); let claps_in_session = ClapsInSession::<T>::get(&session_index);
@ -1208,31 +1097,16 @@ impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
let offenders = validators let offenders = validators
.into_iter() .into_iter()
.enumerate() .enumerate()
.filter_map(|(index, id)| { .filter(|(index, _)| !Self::is_good_actor(*index, median_claps, &claps_in_session))
(!Self::is_good_actor(index, median_claps, &claps_in_session)).then(|| { .filter_map(|(_, id)| {
<T::ValidatorSet as ValidatorSetWithIdentification<T::AccountId>>::IdentificationOf::convert( <T::ValidatorSet as ValidatorSetWithIdentification<T::AccountId>>::IdentificationOf::convert(
id.clone(), id.clone(),
).map(|full_id| (id, full_id)) ).map(|full_id| (id, full_id))
}) })
.flatten()
})
.collect::<Vec<IdentificationTuple<T>>>(); .collect::<Vec<IdentificationTuple<T>>>();
let disabled_validators = T::DisabledValidators::disabled_validators() if offenders.is_empty() {
.into_iter()
.count();
let offenders_length = offenders.len();
let authorities_left: u32 = authorities_len
.saturating_sub(disabled_validators)
.saturating_sub(offenders_length)
.try_into()
.unwrap_or_default();
if offenders_length == 0 {
Self::deposit_event(Event::<T>::AuthoritiesEquilibrium); Self::deposit_event(Event::<T>::AuthoritiesEquilibrium);
} else if authorities_left < T::MinAuthoritiesNumber::get() {
Self::deposit_event(Event::<T>::BlackSwan);
} else { } else {
Self::deposit_event(Event::<T>::SomeAuthoritiesTrottling { Self::deposit_event(Event::<T>::SomeAuthoritiesTrottling {
throttling: offenders.clone(), throttling: offenders.clone(),

View File

@ -3,6 +3,7 @@
use frame_support::{ use frame_support::{
derive_impl, parameter_types, derive_impl, parameter_types,
traits::{ConstU32, ConstU64}, traits::{ConstU32, ConstU64},
weights::Weight,
}; };
use frame_system::EnsureRoot; use frame_system::EnsureRoot;
use pallet_session::historical as pallet_session_historical; use pallet_session::historical as pallet_session_historical;
@ -139,6 +140,27 @@ parameter_types! {
pub static MockAverageSessionLength: Option<u64> = None; pub static MockAverageSessionLength: Option<u64> = None;
} }
pub struct TestNextSessionRotation;
impl frame_support::traits::EstimateNextSessionRotation<u64> for TestNextSessionRotation {
fn average_session_length() -> u64 {
let mock = MockAverageSessionLength::mutate(|p| p.take());
mock.unwrap_or(pallet_session::PeriodicSessions::<Period, Offset>::average_session_length())
}
fn estimate_current_session_progress(now: u64) -> (Option<Permill>, Weight) {
let (estimate, weight) =
pallet_session::PeriodicSessions::<Period, Offset>::estimate_current_session_progress(
now,
);
let mock = MockCurrentSessionProgress::mutate(|p| p.take());
(mock.unwrap_or(estimate), weight)
}
fn estimate_next_session_rotation(now: u64) -> (Option<u64>, Weight) {
pallet_session::PeriodicSessions::<Period, Offset>::estimate_next_session_rotation(now)
}
}
impl ghost_networks::Config for Runtime { impl ghost_networks::Config for Runtime {
type RuntimeEvent = RuntimeEvent; type RuntimeEvent = RuntimeEvent;
type Currency = Balances; type Currency = Balances;
@ -178,19 +200,18 @@ impl Config for Runtime {
type RuntimeEvent = RuntimeEvent; type RuntimeEvent = RuntimeEvent;
type AuthorityId = UintAuthorityId; type AuthorityId = UintAuthorityId;
type NextSessionRotation = TestNextSessionRotation;
type ValidatorSet = Historical; type ValidatorSet = Historical;
type Currency = Balances; type Currency = Balances;
type NetworkDataHandler = Networks; type NetworkDataHandler = Networks;
type BlockNumberProvider = System; type BlockNumberProvider = System;
type ReportUnresponsiveness = OffenceHandler; type ReportUnresponsiveness = OffenceHandler;
type DisabledValidators = Session;
type MaxAuthorities = ConstU32<5>; type MaxAuthorities = ConstU32<5>;
type ApplauseThreshold = ConstU32<50>; type ApplauseThreshold = ConstU32<50>;
type OffenceThreshold = ConstU32<0>; type OffenceThreshold = ConstU32<75>;
type UnsignedPriority = ConstU64<{ 1 << 20 }>; type UnsignedPriority = ConstU64<{ 1 << 20 }>;
type HistoryDepth = HistoryDepth; type HistoryDepth = HistoryDepth;
type MinAuthoritiesNumber = ConstU32<2>;
type WeightInfo = (); type WeightInfo = ();
} }

View File

@ -665,14 +665,15 @@ fn should_throw_error_if_session_index_is_not_current() {
network_id, network_id,
authority_prev authority_prev
)); ));
assert_err!( assert_ok!(do_clap_from_first_authority(
do_clap_from_first_authority(session_index_next, network_id, authority_next), session_index_next,
DispatchError::Other("Transaction has a bad signature") network_id,
); authority_next
));
assert_claps_info_correct(&storage_key_curr, &session_index_curr, 1); assert_claps_info_correct(&storage_key_curr, &session_index_curr, 1);
assert_claps_info_correct(&storage_key_prev, &session_index_prev, 1); assert_claps_info_correct(&storage_key_prev, &session_index_prev, 1);
assert_claps_info_correct(&storage_key_next, &session_index_next, 0); assert_claps_info_correct(&storage_key_next, &session_index_next, 1);
} }
}); });
} }
@ -687,12 +688,22 @@ fn should_throw_error_if_signer_has_incorrect_index() {
let storage_key = (session_index, transaction_hash, unique_transaction_hash); let storage_key = (session_index, transaction_hash, unique_transaction_hash);
assert_claps_info_correct(&storage_key, &session_index, 0); assert_claps_info_correct(&storage_key, &session_index, 0);
assert_invalid_signing_address(session_index, network_id, 69); let clap = Clap {
assert_transaction_has_bad_signature(session_index, network_id, 69); block_number: 420,
assert_invalid_signing_address(session_index, network_id, 420); removed: false,
assert_transaction_has_bad_signature(session_index, network_id, 420); transaction_hash,
assert_invalid_signing_address(session_index, network_id, 1337); session_index,
assert_transaction_has_bad_signature(session_index, network_id, 1337); authority_index: 1337,
network_id,
receiver: 69,
amount: 420,
};
let authority = UintAuthorityId::from((1) as u64);
let signature = authority.sign(&clap.encode()).unwrap();
assert_err!(
SlowClap::slow_clap(RuntimeOrigin::none(), clap, signature),
Error::<Runtime>::NotAnAuthority
);
assert_claps_info_correct(&storage_key, &session_index, 0); assert_claps_info_correct(&storage_key, &session_index, 0);
}); });
} }
@ -710,7 +721,7 @@ fn should_throw_error_if_validator_disabled_and_ignore_later() {
assert_eq!(Session::disable_index(0), true); assert_eq!(Session::disable_index(0), true);
assert_err!( assert_err!(
do_clap_from(session_index, network_id, 0, false), do_clap_from(session_index, network_id, 0, false),
DispatchError::Other("Invalid signing address") Error::<Runtime>::CurrentValidatorIsDisabled
); );
assert_eq!(pallet::ReceivedClaps::<Runtime>::get(&storage_key).len(), 0); assert_eq!(pallet::ReceivedClaps::<Runtime>::get(&storage_key).len(), 0);
@ -945,8 +956,8 @@ fn should_avoid_applause_during_nullification_period() {
} }
#[test] #[test]
fn should_self_applause_after_diabled() { fn should_self_applause_if_enough_received_claps() {
let zero = 0u64; let zero: u64 = 0u64;
let (network_id, transaction_hash, unique_transaction_hash) = let (network_id, transaction_hash, unique_transaction_hash) =
generate_unique_hash(None, None, None, None); generate_unique_hash(None, None, None, None);
let (_, receiver, amount) = get_mocked_metadata(); let (_, receiver, amount) = get_mocked_metadata();
@ -965,7 +976,7 @@ fn should_self_applause_after_diabled() {
receiver, receiver,
amount, amount,
), ),
Error::<Runtime>::NotEnoughClaps, Error::<Runtime>::NotEnoughClaps
); );
assert_eq!( assert_eq!(
@ -973,126 +984,45 @@ fn should_self_applause_after_diabled() {
false false
); );
assert_eq!(Balances::balance(&receiver), zero); assert_eq!(Balances::balance(&receiver), zero);
assert_eq!(
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, 0, false));
advance_session();
let curr_session_index = Session::session_index();
pallet::ClapsInSession::<Runtime>::mutate(&session_index, |claps| {
claps
.entry(1 as AuthIndex)
.and_modify(|individual| (*individual).disabled = true)
.or_insert(SessionAuthorityInfo {
claps: 0u32,
disabled: true,
});
});
pallet::ClapsInSession::<Runtime>::mutate(&curr_session_index, |claps| {
claps
.entry(2 as AuthIndex)
.and_modify(|individual| (*individual).disabled = true)
.or_insert(SessionAuthorityInfo {
claps: 0u32,
disabled: true,
});
});
assert_ok!(SlowClap::self_applause(
RuntimeOrigin::signed(receiver),
network_id,
session_index,
transaction_hash,
receiver,
amount,
));
assert_eq!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
true
);
assert_eq!(Balances::balance(&receiver), amount);
});
}
#[test]
fn should_self_applause_if_enough_claps() {
let zero = 0u64;
let (network_id, transaction_hash, unique_transaction_hash) =
generate_unique_hash(None, None, None, None);
let (_, receiver, amount) = get_mocked_metadata();
new_test_ext().execute_with(|| {
let _ = prepare_evm_network(Some(network_id), Some(0));
let session_index = advance_session_and_get_index();
let storage_key = (session_index, transaction_hash, unique_transaction_hash);
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
);
assert_eq!(Balances::balance(&receiver), zero);
assert_ok!(do_clap_from(session_index, network_id, 0, false));
advance_session();
let mut fake_received_clap =
BoundedBTreeSet::<AuthIndex, <Runtime as pallet::Config>::MaxAuthorities>::new();
assert_eq!(fake_received_clap.try_insert(1).unwrap(), true);
assert_eq!(fake_received_clap.try_insert(2).unwrap(), true);
pallet::ReceivedClaps::<Runtime>::insert(&storage_key, fake_received_clap);
assert_ok!(SlowClap::self_applause(
RuntimeOrigin::signed(receiver),
network_id,
session_index,
transaction_hash,
receiver,
amount,
));
assert_eq!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
true
);
assert_eq!(Balances::balance(&receiver), amount);
});
}
#[test]
fn should_avoid_session_overlap_on_mended_session_index() {
let (network_id, transaction_hash, unique_transaction_hash) =
generate_unique_hash(None, None, None, None);
let (_, receiver, amount) = get_mocked_metadata();
new_test_ext().execute_with(|| {
let _ = prepare_evm_network(Some(network_id), Some(0));
let session_index = advance_session_and_get_index();
let storage_key = (session_index, transaction_hash, unique_transaction_hash);
assert_ok!(do_clap_from(session_index, network_id, 0, false));
advance_session();
assert_eq!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
false
);
assert_eq!(Balances::balance(&receiver), 0u64);
assert_ok!(do_clap_from(session_index, network_id, 1, false)); assert_ok!(do_clap_from(session_index, network_id, 1, false));
assert_ok!(do_clap_from(session_index, network_id, 2, false)); assert_ok!(do_clap_from(session_index, network_id, 2, false));
assert_eq!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
false
);
assert_eq!(Balances::balance(&receiver), 0);
assert_ok!(SlowClap::self_applause(
RuntimeOrigin::signed(receiver),
network_id,
session_index,
transaction_hash,
receiver,
amount,
));
assert_eq!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
false
);
assert_eq!(Balances::balance(&receiver), 0);
Networks::on_finalize(System::block_number());
assert_ok!(SlowClap::self_applause(
RuntimeOrigin::signed(receiver),
network_id,
session_index,
transaction_hash,
receiver,
amount,
));
assert_eq!( assert_eq!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
true true
@ -1209,22 +1139,6 @@ fn should_not_fail_on_sub_existential_balance() {
}); });
} }
#[test]
fn should_emit_black_swan_if_not_enough_authorities_left() {
let (network_id, _, _) = generate_unique_hash(None, None, None, None);
new_test_ext().execute_with(|| {
let session_index = advance_session_and_get_index();
assert_ok!(do_clap_from(session_index, network_id, 0, false));
Session::disable_index(1);
Session::disable_index(2);
advance_session();
advance_session();
System::assert_has_event(RuntimeEvent::SlowClap(crate::Event::BlackSwan));
});
}
fn advance_session_and_get_index() -> u32 { fn advance_session_and_get_index() -> u32 {
advance_session(); advance_session();
assert_eq!(Session::validators(), Vec::<u64>::new()); assert_eq!(Session::validators(), Vec::<u64>::new());

View File

@ -16,7 +16,7 @@
//! Autogenerated weights for `ghost_slow_clap` //! Autogenerated weights for `ghost_slow_clap`
//! //!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0
//! DATE: 2025-11-06, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! DATE: 2025-06-19, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000` //! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `ghostown`, CPU: `Intel(R) Core(TM) i3-2310M CPU @ 2.10GHz` //! HOSTNAME: `ghostown`, CPU: `Intel(R) Core(TM) i3-2310M CPU @ 2.10GHz`
//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("casper-dev")`, DB CACHE: 1024 //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("casper-dev")`, DB CACHE: 1024

View File

@ -1,6 +1,6 @@
[package] [package]
name = "casper-runtime" name = "casper-runtime"
version = "3.5.36" version = "3.5.31"
build = "build.rs" build = "build.rs"
description = "Runtime of the Casper Network" description = "Runtime of the Casper Network"
edition.workspace = true edition.workspace = true

View File

@ -117,11 +117,11 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("casper"), spec_name: create_runtime_str!("casper"),
impl_name: create_runtime_str!("casper-svengali"), impl_name: create_runtime_str!("casper-svengali"),
authoring_version: 0, authoring_version: 0,
spec_version: 6, spec_version: 2,
impl_version: 4, impl_version: 0,
apis: RUNTIME_API_VERSIONS, apis: RUNTIME_API_VERSIONS,
transaction_version: 1, transaction_version: 1,
state_version: 1, state_version: 0,
}; };
/// The BABE epoch configuration at genesis. /// The BABE epoch configuration at genesis.
@ -1059,11 +1059,9 @@ impl ghost_claims::Config<CultCollectiveInstance> for Runtime {
parameter_types! { parameter_types! {
// will be used in `Perbill::from_percent()` // will be used in `Perbill::from_percent()`
pub const ApplauseThreshold: u32 = 66; pub const ApplauseThreshold: u32 = 70;
// will be used in `Perbill::from_percent()` // will be used in `Perbill::from_percent()`
pub const OffenceThreshold: u32 = 5; pub const OffenceThreshold: u32 = 40;
// 4 validators should be functional if 1 is offline
pub const MinAuthoritiesNumber: u32 = 5;
pub const SlowClapUnsignedPriority: TransactionPriority = TransactionPriority::MAX; pub const SlowClapUnsignedPriority: TransactionPriority = TransactionPriority::MAX;
pub const SlowClapHistoryDepth: sp_staking::SessionIndex = pub const SlowClapHistoryDepth: sp_staking::SessionIndex =
StakingHistoryDepth::get() * SessionsPerEra::get(); StakingHistoryDepth::get() * SessionsPerEra::get();
@ -1073,19 +1071,18 @@ impl ghost_slow_clap::Config for Runtime {
type RuntimeEvent = RuntimeEvent; type RuntimeEvent = RuntimeEvent;
type AuthorityId = SlowClapId; type AuthorityId = SlowClapId;
type NextSessionRotation = Babe;
type ValidatorSet = Historical; type ValidatorSet = Historical;
type Currency = Balances; type Currency = Balances;
type NetworkDataHandler = GhostNetworks; type NetworkDataHandler = GhostNetworks;
type BlockNumberProvider = System; type BlockNumberProvider = System;
type ReportUnresponsiveness = Offences; type ReportUnresponsiveness = Offences;
type DisabledValidators = Session;
type MaxAuthorities = MaxAuthorities; type MaxAuthorities = MaxAuthorities;
type ApplauseThreshold = ApplauseThreshold; type ApplauseThreshold = ApplauseThreshold;
type OffenceThreshold = OffenceThreshold; type OffenceThreshold = OffenceThreshold;
type UnsignedPriority = SlowClapUnsignedPriority; type UnsignedPriority = SlowClapUnsignedPriority;
type HistoryDepth = SlowClapHistoryDepth; type HistoryDepth = SlowClapHistoryDepth;
type MinAuthoritiesNumber = MinAuthoritiesNumber;
type WeightInfo = weights::ghost_slow_clap::WeightInfo<Runtime>; type WeightInfo = weights::ghost_slow_clap::WeightInfo<Runtime>;
} }

View File

@ -16,7 +16,7 @@
//! Autogenerated weights for `ghost_slow_clap` //! Autogenerated weights for `ghost_slow_clap`
//! //!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0
//! DATE: 2025-11-06, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! DATE: 2025-06-19, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000` //! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `ghostown`, CPU: `Intel(R) Core(TM) i3-2310M CPU @ 2.10GHz` //! HOSTNAME: `ghostown`, CPU: `Intel(R) Core(TM) i3-2310M CPU @ 2.10GHz`
//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("casper-dev")`, DB CACHE: 1024 //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("casper-dev")`, DB CACHE: 1024
@ -46,12 +46,12 @@ use core::marker::PhantomData;
/// Weight functions for `ghost_slow_clap`. /// Weight functions for `ghost_slow_clap`.
pub struct WeightInfo<T>(PhantomData<T>); pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> ghost_slow_clap::WeightInfo for WeightInfo<T> { impl<T: frame_system::Config> ghost_slow_clap::WeightInfo for WeightInfo<T> {
/// Storage: `GhostSlowClaps::Authorities` (r:1 w:0)
/// Proof: `GhostSlowClaps::Authorities` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ReceivedClaps` (r:1 w:1) /// Storage: `GhostSlowClaps::ReceivedClaps` (r:1 w:1)
/// Proof: `GhostSlowClaps::ReceivedClaps` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostSlowClaps::ReceivedClaps` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ClapsInSession` (r:1 w:1) /// Storage: `GhostSlowClaps::ClapsInSession` (r:1 w:1)
/// Proof: `GhostSlowClaps::ClapsInSession` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostSlowClaps::ClapsInSession` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::Authorities` (r:1 w:0)
/// Proof: `GhostSlowClaps::Authorities` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:1) /// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:1)
/// Proof: `GhostSlowClaps::ApplausesForTransaction` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostSlowClaps::ApplausesForTransaction` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::NullifyNeeded` (r:1 w:0) /// Storage: `GhostNetworks::NullifyNeeded` (r:1 w:0)
@ -68,20 +68,18 @@ impl<T: frame_system::Config> ghost_slow_clap::WeightInfo for WeightInfo<T> {
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
fn slow_clap() -> Weight { fn slow_clap() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `387` // Measured: `355`
// Estimated: `3852` // Estimated: `3820`
// Minimum execution time: 220_008_000 picoseconds. // Minimum execution time: 213_817_000 picoseconds.
Weight::from_parts(223_058_000, 0) Weight::from_parts(216_977_000, 0)
.saturating_add(Weight::from_parts(0, 3852)) .saturating_add(Weight::from_parts(0, 3820))
.saturating_add(T::DbWeight::get().reads(10)) .saturating_add(T::DbWeight::get().reads(10))
.saturating_add(T::DbWeight::get().writes(7)) .saturating_add(T::DbWeight::get().writes(7))
} }
/// Storage: `GhostSlowClaps::Authorities` (r:2 w:0) /// Storage: `GhostSlowClaps::ReceivedClaps` (r:1 w:0)
/// Proof: `GhostSlowClaps::Authorities` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ReceivedClaps` (r:2 w:0)
/// Proof: `GhostSlowClaps::ReceivedClaps` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostSlowClaps::ReceivedClaps` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ClapsInSession` (r:1 w:0) /// Storage: `GhostSlowClaps::Authorities` (r:1 w:0)
/// Proof: `GhostSlowClaps::ClapsInSession` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostSlowClaps::Authorities` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:1) /// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:1)
/// Proof: `GhostSlowClaps::ApplausesForTransaction` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostSlowClaps::ApplausesForTransaction` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::NullifyNeeded` (r:1 w:0) /// Storage: `GhostNetworks::NullifyNeeded` (r:1 w:0)
@ -98,12 +96,12 @@ impl<T: frame_system::Config> ghost_slow_clap::WeightInfo for WeightInfo<T> {
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
fn self_applause() -> Weight { fn self_applause() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `861` // Measured: `655`
// Estimated: `6801` // Estimated: `4120`
// Minimum execution time: 258_510_000 picoseconds. // Minimum execution time: 210_676_000 picoseconds.
Weight::from_parts(262_353_000, 0) Weight::from_parts(212_905_000, 0)
.saturating_add(Weight::from_parts(0, 6801)) .saturating_add(Weight::from_parts(0, 4120))
.saturating_add(T::DbWeight::get().reads(12)) .saturating_add(T::DbWeight::get().reads(9))
.saturating_add(T::DbWeight::get().writes(5)) .saturating_add(T::DbWeight::get().writes(5))
} }
} }

View File

@ -81,18 +81,20 @@ extract_seed() {
} }
downgrade_compiler_if_needed() { downgrade_compiler_if_needed() {
echo "[+] fetching the latest ghost-node source code" # TODO: uncomment later
git switch main # echo "[+] fetching the latest ghost-node source code"
git pull origin main # git switch main
# git pull origin main
# 1.86.0 works fine, tested with: # 1.83.0 works fine, tested with:
# ...
# 1.87.0 throws errors during compilation # 1.87.0 throws errors during compilation
# 1.88.0 throws errors during compilation # 1.88.0 throws errors during compilation
LATEST_TESTED_VERSION=86 LATEST_TESTED_VERSION=83
cargo_version=$(cargo --version | cut -d'.' -f2) cargo_version=$(cargo --version | cut -d'.' -f2)
if [ "$cargo_version" -gt "$LATEST_TESTED_VERSION" ]; then if [ "$cargo_version" -gt "$LATEST_TESTED_VERSION" ]; then
echo "[+] downgrading rustc compiler version to 1.86.0" echo "[+] downgrading rustc compiler version to 1.83.0"
rustup default 1.86.0 rustup default 1.83.0
toolchain_name=$(rustup show | grep default | head -n 1 | cut -d' ' -f1) toolchain_name=$(rustup show | grep default | head -n 1 | cut -d' ' -f1)
rustup target add wasm32-unknown-unknown --toolchain $toolchain_name rustup target add wasm32-unknown-unknown --toolchain $toolchain_name
rustup component add rust-src --toolchain $toolchain_name rustup component add rust-src --toolchain $toolchain_name