Compare commits

...

29 Commits

Author SHA1 Message Date
6fa5e5ed97
update casper runtime based on new version of slow clap
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-11-12 20:00:57 +03:00
58c5f1f33d
apply latest version of slow clap
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-11-12 19:06:42 +03:00
55a77cd3d4
introduce black swan event e.g. disable everybody
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-12 19:03:58 +03:00
2cf4637d0c
update casper runtime version
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-11-10 21:23:08 +03:00
8123295f91
Merge branch 'pallet-slow-clap'
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-11-10 20:55:37 +03:00
092679eb0c
disable only claps during offchain worker but not the block gathering
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-10 20:54:37 +03:00
75268b4c0a
casper runtime upgrade
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-11-09 16:09:56 +03:00
275567ef79
Merge branch 'pallet-slow-clap'
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-11-09 15:31:43 +03:00
64de0027bf
align self-applause logic and disable offchain worker if authority index is disabled
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-09 15:29:50 +03:00
a3ed395689
take disabled from the next session and rustfmt pallet code
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-08 14:02:04 +03:00
7a710ec9cb
check if validator disabled during the validate_unsigned and small typo fixes
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-08 13:48:14 +03:00
cc141105bb
propagate disabled authorities to upcoming sessions in era
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-08 13:38:15 +03:00
fc2e4e6bff
bump slow clap version inside lock file
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-11-06 17:06:11 +03:00
0e750c0261
update lock file
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-11-06 16:53:19 +03:00
cc566ac549
update weights for slow clap in casper runtime
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-11-06 15:01:01 +03:00
18241ea504
update weights for the slow clap
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-11-06 14:59:27 +03:00
af14543cc1
change casper runtime versioning
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-06 14:33:25 +03:00
6acec08fa5
increase storage version for the pallet
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-06 14:32:04 +03:00
d6ecdcd468
correct benchmarking of self applause and remove of unnecessary storage during tests
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-05 22:13:28 +03:00
decf6665df
make slow-clap tests work again based on new functionality, new tests added too
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-05 20:55:04 +03:00
ebae9fadbe
fixes for self_applause function
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-05 20:52:00 +03:00
c872eca8ac
back look during the slashing
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-05 15:55:37 +03:00
eb181c7f44
fixes for the inconsistency of the slow claps
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-04 17:43:36 +03:00
fae0fa4d7b
fixes in the readme guide
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-09-01 20:30:49 +03:00
71eb90a5fb
increase stable compiler version to match the ghost-eye dependencies
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-09-01 19:23:20 +03:00
5307afe352
bump locked version
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-08-27 15:33:26 +03:00
7edc8935b6
optimize offenders gathering with a single pass over the data
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-08-27 15:31:32 +03:00
46aa18aafe
implement cross session claim via self_applause
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-08-27 14:41:46 +03:00
25fcfed586
bump slow clap version
Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
2025-08-15 23:07:13 +03:00
12 changed files with 402 additions and 305 deletions

4
Cargo.lock generated
View File

@ -1186,7 +1186,7 @@ dependencies = [
[[package]] [[package]]
name = "casper-runtime" name = "casper-runtime"
version = "3.5.31" version = "3.5.36"
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.39" version = "0.3.53"
dependencies = [ dependencies = [
"frame-benchmarking", "frame-benchmarking",
"frame-support", "frame-support",

126
README.md
View File

@ -150,28 +150,8 @@ 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 update nightly rustup target add wasm32-unknown-unknown --toolchain stable
```
```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
@ -180,10 +160,6 @@ 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)
@ -194,13 +170,6 @@ 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:
@ -211,7 +180,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:
@ -226,7 +195,7 @@ cd ghost-node
Compile the node template by running the following command: Compile the node template by running the following command:
```bash ```bash
cargo build --release ./scripts/starter.sh --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.
@ -234,7 +203,6 @@ 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
@ -320,7 +288,7 @@ Only `port 30333` should be opened.
Press _CTRL+C_ to stop the node. Press _CTRL+C_ to stop the node.
# Launching GHOST TestNet 3.1 # Launching GHOST TestNet
Switch to main GIT branch: Switch to main GIT branch:
```bash ```bash
@ -348,66 +316,7 @@ 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
``` ```
Generate Wallet Key file with the following command: Feel free to backup the file on a separate storage device.
```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
@ -437,7 +346,7 @@ sha256sum /etc/ghost/casper.json
You should see: You should see:
``` ```
ad653233c978bfd00c5e4525b17628632bc4319c5f5f4b4dcc2f050ef3c3d145 9da6045ed6d4fd844e3939573b31c013d0e564e542029330faa6d978cb4a915a
``` ```
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.
@ -463,10 +372,7 @@ To choose default options press Enter here:
![images/img_30.png](images/img_30.png) ![images/img_30.png](images/img_30.png)
Currently, you have to qualify to become a validator node through [GHOST Whales](https://ghostchain.io/whales-apply). If you want to validate from this node press Enter:
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
``` ```
@ -511,17 +417,6 @@ 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)
@ -535,7 +430,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
@ -545,11 +440,6 @@ 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.40" version = "0.3.53"
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,10 +50,15 @@ benchmarks! {
self_applause { self_applause {
let session_index = T::ValidatorSet::session_index(); let session_index = T::ValidatorSet::session_index();
let authorities = vec![T::AuthorityId::generate_pair(None)]; let next_session_index = session_index.saturating_add(1);
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); Authorities::<T>::set(&session_index, bounded_authorities.clone());
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>();
@ -68,6 +73,7 @@ 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 {
@ -86,11 +92,18 @@ 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,8 +9,7 @@ use frame_support::{
pallet_prelude::*, pallet_prelude::*,
traits::{ traits::{
tokens::fungible::{Inspect, Mutate}, tokens::fungible::{Inspect, Mutate},
EstimateNextSessionRotation, Get, OneSessionHandler, ValidatorSet, DisabledValidators, Get, OneSessionHandler, ValidatorSet, ValidatorSetWithIdentification,
ValidatorSetWithIdentification,
}, },
WeakBoundedVec, WeakBoundedVec,
}; };
@ -72,7 +71,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 = 10; const LOCK_BLOCK_EXPIRATION: u64 = 20;
pub type AuthIndex = u32; pub type AuthIndex = u32;
@ -139,7 +138,6 @@ 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),
} }
} }
} }
@ -166,7 +164,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(1); const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);
#[pallet::pallet] #[pallet::pallet]
#[pallet::storage_version(STORAGE_VERSION)] #[pallet::storage_version(STORAGE_VERSION)]
@ -183,7 +181,6 @@ 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
@ -195,6 +192,7 @@ 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>;
@ -211,12 +209,16 @@ 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>>,
@ -238,8 +240,6 @@ 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,6 +294,16 @@ 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> {
@ -330,7 +340,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>,
session_index: SessionIndex, prev_session_index: SessionIndex,
transaction_hash: H256, transaction_hash: H256,
receiver: T::AccountId, receiver: T::AccountId,
amount: BalanceOf<T>, amount: BalanceOf<T>,
@ -338,7 +348,7 @@ pub mod pallet {
let _ = ensure_signed(origin)?; let _ = ensure_signed(origin)?;
Self::applause_if_posible( Self::applause_if_posible(
network_id, network_id,
session_index, prev_session_index,
transaction_hash, transaction_hash,
receiver, receiver,
amount, amount,
@ -378,12 +388,21 @@ 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 authorities = Authorities::<T>::get(&clap.session_index); let (session_index, _) = Self::mended_session_index(&clap);
let authorities = Authorities::<T>::get(&session_index);
let authority = match authorities.get(clap.authority_index as usize) { 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));
@ -459,28 +478,42 @@ impl<T: Config> Pallet<T> {
hex_str hex_str
} }
fn try_slow_clap(clap: &Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>) -> DispatchResult { fn mended_session_index(
let authorities = Authorities::<T>::get(&clap.session_index); clap: &Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>,
ensure!( ) -> (SessionIndex, H256) {
authorities.get(clap.authority_index as usize).is_some(), let prev_session_index = clap.session_index.saturating_sub(1);
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 = (
clap.session_index, prev_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();
@ -498,15 +531,15 @@ impl<T: Config> Pallet<T> {
} }
})?; })?;
ClapsInSession::<T>::mutate(&clap.session_index, |claps_details| { claps_in_session
(*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,
@ -517,7 +550,7 @@ impl<T: Config> Pallet<T> {
}); });
let enough_authorities = let enough_authorities =
Perbill::from_rational(number_of_received_claps as u32, authorities.len() as u32) Perbill::from_rational(number_of_received_claps as u32, active_authorities as u32)
> Perbill::from_percent(T::ApplauseThreshold::get()); > Perbill::from_percent(T::ApplauseThreshold::get());
if enough_authorities { if enough_authorities {
@ -574,32 +607,75 @@ impl<T: Config> Pallet<T> {
fn applause_if_posible( fn applause_if_posible(
network_id: NetworkIdOf<T>, network_id: NetworkIdOf<T>,
session_index: SessionIndex, prev_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: false, removed: Default::default(),
session_index, session_index: Default::default(),
transaction_hash: Default::default(),
network_id, network_id,
receiver, receiver,
amount, amount,
transaction_hash,
}; };
let enough_authorities = Perbill::from_rational( let enough_authorities =
ReceivedClaps::<T>::get(&received_claps_key).len() as u32, Perbill::from_rational(total_received_claps.len() as u32, active_authorities as u32)
Authorities::<T>::get(session_index).len() as u32, > Perbill::from_percent(T::ApplauseThreshold::get());
) > Perbill::from_percent(T::ApplauseThreshold::get());
ensure!(enough_authorities, Error::<T>::NotEnoughClaps); ensure!(enough_authorities, Error::<T>::NotEnoughClaps);
Self::try_applause(&clap, &received_claps_key)?; Self::try_applause(&clap, &prev_received_claps_key)?;
Ok(()) Ok(())
} }
@ -766,14 +842,17 @@ 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| current_distance .map(|current_distance| {
.le(&max_block_distance) current_distance
.then(|| estimated_block) .le(&max_block_distance)
) .then(|| estimated_block)
})
.flatten() .flatten()
.unwrap_or(from_block .unwrap_or(
.saturating_add(max_block_distance) from_block
.min(estimated_block)); .saturating_add(max_block_distance)
.min(estimated_block),
);
(from_block, adjusted_to_block) (from_block, adjusted_to_block)
} }
_ => (to_block, to_block), _ => (to_block, to_block),
@ -818,6 +897,20 @@ 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| {
@ -1026,16 +1119,34 @@ 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 =
@ -1087,8 +1198,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(); let session_index = T::ValidatorSet::session_index().saturating_sub(1);
let validators = T::ValidatorSet::validators(); let validators = Validators::<T>::get(&session_index).unwrap_or_default();
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);
@ -1097,16 +1208,31 @@ impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
let offenders = validators let offenders = validators
.into_iter() .into_iter()
.enumerate() .enumerate()
.filter(|(index, _)| !Self::is_good_actor(*index, median_claps, &claps_in_session)) .filter_map(|(index, id)| {
.filter_map(|(_, id)| { (!Self::is_good_actor(index, median_claps, &claps_in_session)).then(|| {
<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>>>();
if offenders.is_empty() { let disabled_validators = T::DisabledValidators::disabled_validators()
.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,7 +3,6 @@
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;
@ -140,27 +139,6 @@ 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;
@ -200,18 +178,19 @@ 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<75>; type OffenceThreshold = ConstU32<0>;
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,15 +665,14 @@ fn should_throw_error_if_session_index_is_not_current() {
network_id, network_id,
authority_prev authority_prev
)); ));
assert_ok!(do_clap_from_first_authority( assert_err!(
session_index_next, do_clap_from_first_authority(session_index_next, network_id, authority_next),
network_id, DispatchError::Other("Transaction has a bad signature")
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, 1); assert_claps_info_correct(&storage_key_next, &session_index_next, 0);
} }
}); });
} }
@ -688,22 +687,12 @@ 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);
let clap = Clap { assert_invalid_signing_address(session_index, network_id, 69);
block_number: 420, assert_transaction_has_bad_signature(session_index, network_id, 69);
removed: false, assert_invalid_signing_address(session_index, network_id, 420);
transaction_hash, assert_transaction_has_bad_signature(session_index, network_id, 420);
session_index, assert_invalid_signing_address(session_index, network_id, 1337);
authority_index: 1337, assert_transaction_has_bad_signature(session_index, network_id, 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);
}); });
} }
@ -721,7 +710,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),
Error::<Runtime>::CurrentValidatorIsDisabled DispatchError::Other("Invalid signing address")
); );
assert_eq!(pallet::ReceivedClaps::<Runtime>::get(&storage_key).len(), 0); assert_eq!(pallet::ReceivedClaps::<Runtime>::get(&storage_key).len(), 0);
@ -956,8 +945,8 @@ fn should_avoid_applause_during_nullification_period() {
} }
#[test] #[test]
fn should_self_applause_if_enough_received_claps() { fn should_self_applause_after_diabled() {
let zero: u64 = 0u64; let zero = 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();
@ -976,7 +965,7 @@ fn should_self_applause_if_enough_received_claps() {
receiver, receiver,
amount, amount,
), ),
Error::<Runtime>::NotEnoughClaps Error::<Runtime>::NotEnoughClaps,
); );
assert_eq!( assert_eq!(
@ -984,45 +973,126 @@ fn should_self_applause_if_enough_received_claps() {
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
@ -1139,6 +1209,22 @@ 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-06-19, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! DATE: 2025-11-06, 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.31" version = "3.5.36"
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: 2, spec_version: 6,
impl_version: 0, impl_version: 4,
apis: RUNTIME_API_VERSIONS, apis: RUNTIME_API_VERSIONS,
transaction_version: 1, transaction_version: 1,
state_version: 0, state_version: 1,
}; };
/// The BABE epoch configuration at genesis. /// The BABE epoch configuration at genesis.
@ -1059,9 +1059,11 @@ 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 = 70; pub const ApplauseThreshold: u32 = 66;
// will be used in `Perbill::from_percent()` // will be used in `Perbill::from_percent()`
pub const OffenceThreshold: u32 = 40; pub const OffenceThreshold: u32 = 5;
// 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();
@ -1071,18 +1073,19 @@ 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-06-19, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! DATE: 2025-11-06, 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,18 +68,20 @@ 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: `355` // Measured: `387`
// Estimated: `3820` // Estimated: `3852`
// Minimum execution time: 213_817_000 picoseconds. // Minimum execution time: 220_008_000 picoseconds.
Weight::from_parts(216_977_000, 0) Weight::from_parts(223_058_000, 0)
.saturating_add(Weight::from_parts(0, 3820)) .saturating_add(Weight::from_parts(0, 3852))
.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::ReceivedClaps` (r:1 w:0) /// Storage: `GhostSlowClaps::Authorities` (r:2 w:0)
/// Proof: `GhostSlowClaps::ReceivedClaps` (`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`) /// 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`)
/// Storage: `GhostSlowClaps::ClapsInSession` (r:1 w:0)
/// Proof: `GhostSlowClaps::ClapsInSession` (`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)
@ -96,12 +98,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: `655` // Measured: `861`
// Estimated: `4120` // Estimated: `6801`
// Minimum execution time: 210_676_000 picoseconds. // Minimum execution time: 258_510_000 picoseconds.
Weight::from_parts(212_905_000, 0) Weight::from_parts(262_353_000, 0)
.saturating_add(Weight::from_parts(0, 4120)) .saturating_add(Weight::from_parts(0, 6801))
.saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().reads(12))
.saturating_add(T::DbWeight::get().writes(5)) .saturating_add(T::DbWeight::get().writes(5))
} }
} }

View File

@ -81,20 +81,18 @@ extract_seed() {
} }
downgrade_compiler_if_needed() { downgrade_compiler_if_needed() {
# TODO: uncomment later echo "[+] fetching the latest ghost-node source code"
# echo "[+] fetching the latest ghost-node source code" git switch main
# git switch main git pull origin main
# git pull origin main
# 1.83.0 works fine, tested with: # 1.86.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=83 LATEST_TESTED_VERSION=86
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.83.0" echo "[+] downgrading rustc compiler version to 1.86.0"
rustup default 1.83.0 rustup default 1.86.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