Compare commits

..

4 Commits

Author SHA1 Message Date
6a2b5a34d2
applause based on the external expousre
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-21 13:46:22 +03:00
0bb46482b2
offchain worker restructure and block commitments added
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-20 03:06:48 +03:00
d76646c191
remove unused structs to avoid warning during compilation
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-18 16:01:29 +03:00
94d28f254f
update offchain worker logic
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
2025-11-18 16:00:17 +03:00
14 changed files with 916 additions and 938 deletions

4
Cargo.lock generated
View File

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

126
README.md
View File

@ -150,8 +150,28 @@ rustup default stable
rustup update
```
Add the nightly release and the nightly WebAssembly (wasm) targets
to your development environment by running the following commands:
```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
@ -160,6 +180,10 @@ the following command:
rustup show
```
```bash
rustup +nightly show
```
You should see something like this:
![images/img_9.png](images/img_9.png)
@ -170,6 +194,13 @@ Now run:
rustup component add rust-src --toolchain stable
```
**_IF error try_**
```bash
rustup component add rust-src --toolchain default
```
## Install GHOST
Check if Git is already installed:
@ -180,7 +211,7 @@ git --version
Make a GHOST Directory and go to it:
```bash
mkdir ~/ghost && cd ~/ghost
mkdir ghost && cd ghost
```
Clone GHOST Node Git:
@ -195,7 +226,7 @@ cd ghost-node
Compile the node template by running the following command:
```bash
./scripts/starter.sh --release
cargo build --release
```
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)
# Boot Node Qualification
## Boot Node Qualification Test
@ -288,7 +320,7 @@ Only `port 30333` should be opened.
Press _CTRL+C_ to stop the node.
# Launching GHOST TestNet
# Launching GHOST TestNet 3.1
Switch to main GIT branch:
```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
```
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
@ -346,7 +437,7 @@ sha256sum /etc/ghost/casper.json
You should see:
```
9da6045ed6d4fd844e3939573b31c013d0e564e542029330faa6d978cb4a915a
ad653233c978bfd00c5e4525b17628632bc4319c5f5f4b4dcc2f050ef3c3d145
```
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)
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
```
@ -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)
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:
![images/img_38.png](images/img_38.png)
@ -430,7 +535,7 @@ Start `ghost-node`:
sudo systemctl start ghost-node
```
Wait ~60 seconds!
Wait 60 seconds!
Check node is started:
```bash
@ -440,6 +545,11 @@ sudo systemctl status ghost-node
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`:
```bash
sudo systemctl restart ghost-node

View File

@ -51,33 +51,6 @@ pub trait WeightInfo {
fn claim() -> Weight;
}
/// Weight for ghost_claims using the Substrate node and recommended hardware.
pub struct SubstrateWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Storage: `System::Account` (r:2 w:2)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
/// Storage: `GhostClaims::Total` (r:1 w:1)
/// Proof: `GhostClaims::Total` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `CultCollective::Members` (r:2 w:2)
/// Proof: `CultCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`)
/// Storage: `CultCollective::MemberCount` (r:6 w:6)
/// Proof: `CultCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`)
/// Storage: `CultCollective::IdToIndex` (r:6 w:12)
/// Proof: `CultCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`)
/// Storage: `CultCollective::IndexToId` (r:0 w:6)
/// Proof: `CultCollective::IndexToId` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`)
fn claim() -> Weight {
// Proof Size summary in bytes:
// Measured: `896`
// Estimated: `16164`
// Minimum execution time: 754_086_000 picoseconds.
Weight::from_parts(756_147_000, 0)
.saturating_add(Weight::from_parts(0, 16164))
.saturating_add(T::DbWeight::get().reads(17))
.saturating_add(T::DbWeight::get().writes(29))
}
}
impl WeightInfo for () {
/// Storage: `System::Account` (r:2 w:2)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)

View File

@ -63,166 +63,6 @@ pub trait WeightInfo {
fn remove_network() -> Weight;
}
/// Weight for ghost_networks using the Substrate node and recommended hardware.
pub struct SubstrateWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// The range of component `i` is `[1, 20]`.
/// The range of component `j` is `[1, 150]`.
/// The range of component `k` is `[1, 20]`.
fn register_network(_i: u32, _j: u32, k: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `109`
// Estimated: `3574`
// Minimum execution time: 46_023_000 picoseconds.
Weight::from_parts(97_871_287, 0)
.saturating_add(Weight::from_parts(0, 3574))
// Standard Error: 94_524
.saturating_add(Weight::from_parts(940_486, 0).saturating_mul(k.into()))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// The range of component `n` is `[1, 20]`.
fn update_network_name(n: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 49_906_000 picoseconds.
Weight::from_parts(55_537_587, 0)
.saturating_add(Weight::from_parts(0, 3767))
// Standard Error: 87_704
.saturating_add(Weight::from_parts(92_366, 0).saturating_mul(n.into()))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// The range of component `n` is `[1, 150]`.
fn update_network_endpoint(n: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 50_556_000 picoseconds.
Weight::from_parts(57_726_674, 0)
.saturating_add(Weight::from_parts(0, 3767))
// Standard Error: 12_261
.saturating_add(Weight::from_parts(274, 0).saturating_mul(n.into()))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_finality_delay() -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 49_406_000 picoseconds.
Weight::from_parts(51_256_000, 0)
.saturating_add(Weight::from_parts(0, 3767))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_rate_limit_delay() -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 49_572_000 picoseconds.
Weight::from_parts(52_584_000, 0)
.saturating_add(Weight::from_parts(0, 3767))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_block_distance() -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 48_880_000 picoseconds.
Weight::from_parts(50_596_000, 0)
.saturating_add(Weight::from_parts(0, 3767))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_type() -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 48_282_000 picoseconds.
Weight::from_parts(49_137_000, 0)
.saturating_add(Weight::from_parts(0, 3767))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_gatekeeper() -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 50_853_000 picoseconds.
Weight::from_parts(51_982_000, 0)
.saturating_add(Weight::from_parts(0, 3767))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_topic_name() -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 50_343_000 picoseconds.
Weight::from_parts(52_380_000, 0)
.saturating_add(Weight::from_parts(0, 3767))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_incoming_network_fee() -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 49_393_000 picoseconds.
Weight::from_parts(80_966_000, 0)
.saturating_add(Weight::from_parts(0, 3767))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_outgoing_network_fee() -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 49_579_000 picoseconds.
Weight::from_parts(51_126_000, 0)
.saturating_add(Weight::from_parts(0, 3767))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn remove_network() -> Weight {
// Proof Size summary in bytes:
// Measured: `302`
// Estimated: `3767`
// Minimum execution time: 44_634_000 picoseconds.
Weight::from_parts(45_815_000, 0)
.saturating_add(Weight::from_parts(0, 3767))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
}
impl WeightInfo for () {
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)

View File

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

View File

@ -17,68 +17,21 @@ benchmarks! {
let minimum_balance = <<T as pallet::Config>::Currency>::minimum_balance();
let receiver = create_account::<T>();
let amount = minimum_balance + minimum_balance;
let network_id = NetworkIdOf::<T>::default();
let session_index = T::ValidatorSet::session_index();
let transaction_hash = H256::repeat_byte(1u8);
let args_hash = Pallet::<T>::generate_unique_hash(&receiver, &amount, &network_id);
let authorities = vec![T::AuthorityId::generate_pair(None)];
let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities.clone())
.map_err(|()| "more than the maximum number of keys provided")?;
Authorities::<T>::set(&session_index, bounded_authorities);
let authority_index = 0u32;
let clap = Clap {
session_index: 0,
authority_index: 0,
transaction_hash: H256::repeat_byte(1u8),
block_number: 69,
removed: false,
network_id,
receiver: receiver.clone(),
amount,
};
let authority_id = authorities
.get(0usize)
.expect("first authority should exist");
let encoded_clap = clap.encode();
let signature = authority_id.sign(&encoded_clap)
.ok_or("couldn't make signature")?;
}: _(RawOrigin::None, clap, signature)
verify {
assert_eq!(<<T as pallet::Config>::Currency>::total_balance(&receiver), amount);
}
self_applause {
let session_index = T::ValidatorSet::session_index();
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())
.map_err(|()| "more than the maximum number of keys provided")?;
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 receiver = create_account::<T>();
let receiver_clone = receiver.clone();
let amount = minimum_balance + minimum_balance;
let network_id = NetworkIdOf::<T>::default();
let transaction_hash = H256::repeat_byte(1u8);
let unique_transaction_hash = <Pallet<T>>::generate_unique_hash(
&receiver,
&amount,
&network_id,
);
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();
let clap = Clap {
session_index,
authority_index: 0,
authority_index,
transaction_hash,
block_number: 69,
removed: false,
@ -88,26 +41,54 @@ benchmarks! {
};
let authority_id = authorities
.get(0usize)
.get(authority_index as usize)
.expect("first authority should exist");
let encoded_clap = clap.encode();
let signature = authority_id.sign(&encoded_clap).unwrap();
Pallet::<T>::slow_clap(RawOrigin::None.into(), clap, signature)?;
Pallet::<T>::trigger_nullification_for_benchmark();
let signature = authority_id.sign(&clap.encode())
.ok_or("couldn't make signature")?;
assert_eq!(<<T as pallet::Config>::Currency>::total_balance(&receiver), Default::default());
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::None, clap, signature)
verify {
let clap_key = (session_index, transaction_hash, args_hash);
assert_eq!(ReceivedClaps::<T>::get(&clap_key).get(&authority_index).is_some(), true);
assert_eq!(<<T as pallet::Config>::Currency>::total_balance(&receiver), amount);
assert_eq!(ApplausesForTransaction::<T>::get(&storage_key), true);
}
commit_block {
let session_index = T::ValidatorSet::session_index();
let network_id = NetworkIdOf::<T>::default();
let authorities = vec![T::AuthorityId::generate_pair(None)];
let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities.clone())
.map_err(|()| "more than the maximum number of keys provided")?;
Authorities::<T>::set(&session_index, bounded_authorities);
let authority_index = 0u32;
let block_commitment = BlockCommitment {
session_index,
authority_index,
network_id,
commitment: CommitmentDetails {
last_registered_block: 69,
last_seen_block: 420,
last_updated: 1337,
}
};
let authority_id = authorities
.get(authority_index as usize)
.expect("first authority should exist");
let signature = authority_id.sign(&block_commitment.encode())
.ok_or("couldn't make signature")?;
}: _(RawOrigin::None, block_commitment, signature)
verify {
let stored_commitment = BlockCommitments::<T>::get(&network_id)
.get(&authority_index)
.cloned()
.unwrap_or_default();
assert_eq!(stored_commitment.last_registered_block, 69);
assert_eq!(stored_commitment.last_seen_block, 420);
assert_eq!(stored_commitment.last_updated, 1337);
}
impl_benchmark_test_suite!(

View File

@ -1,9 +1,14 @@
use sp_runtime::SaturatedConversion;
use sp_staking::SessionIndex;
use crate::{
deserialisations::{
de_string_to_bytes, de_string_to_h256, de_string_to_u64, de_string_to_u64_pure,
de_string_to_vec_of_bytes,
},
Decode, Deserialize, Encode, RuntimeDebug, Vec, H256,
AuthIndex, BalanceOf, BlockCommitment, BlockCommitments, Call, Clap, CommitmentDetails, Config,
Decode, Deserialize, Encode, NetworkIdOf, RuntimeAppPublic, RuntimeDebug, SubmitTransaction,
Vec, COMMITMENT_DELAY_MILLIS, H256, LOG_TARGET,
};
const NUMBER_OF_TOPICS: usize = 3;
@ -40,6 +45,219 @@ pub struct Log {
pub removed: bool,
}
impl EvmResponseType {
fn prepare_block_commitment<T: Config>(
&self,
from_block: u64,
authority_index: AuthIndex,
session_index: SessionIndex,
network_id: NetworkIdOf<T>,
) -> BlockCommitment<NetworkIdOf<T>> {
let last_updated = sp_io::offchain::timestamp().unix_millis();
let current_block = match self {
EvmResponseType::BlockNumber(block_number) => *block_number,
EvmResponseType::TransactionLogs(_) => Default::default(),
};
BlockCommitment {
session_index,
authority_index,
network_id,
commitment: CommitmentDetails {
last_registered_block: from_block,
last_seen_block: current_block,
last_updated,
},
}
}
fn prepare_clap<T: Config>(
&self,
authority_index: AuthIndex,
session_index: SessionIndex,
network_id: NetworkIdOf<T>,
log: &Log,
) -> Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>> {
Clap {
authority_index,
session_index,
network_id,
removed: log.removed,
receiver: T::AccountId::decode(&mut &log.topics[1][0..32])
.expect("32 bytes always construct an AccountId32"),
amount: u128::from_be_bytes(
log.topics[2][16..32]
.try_into()
.expect("amount is valid hex; qed"),
)
.saturated_into::<BalanceOf<T>>(),
transaction_hash: log.transaction_hash.clone().expect("tx hash exists; qed"),
block_number: log.block_number.expect("block number exists; qed"),
}
}
fn iter_claps_from_logs<T: Config>(
&self,
authority_index: AuthIndex,
session_index: SessionIndex,
network_id: NetworkIdOf<T>,
) -> Vec<Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>> {
match self {
EvmResponseType::TransactionLogs(evm_logs) => evm_logs
.iter()
.filter_map(move |log| {
log.is_sufficient().then(|| {
self.prepare_clap::<T>(authority_index, session_index, network_id, log)
})
})
.collect(),
EvmResponseType::BlockNumber(_) => Vec::new(),
}
}
fn sign_and_submit_claps<T: Config>(
&self,
authority_index: AuthIndex,
authority_key: T::AuthorityId,
session_index: SessionIndex,
network_id: NetworkIdOf<T>,
) {
let claps = self.iter_claps_from_logs::<T>(authority_index, session_index, network_id);
let claps_len = claps.len();
log::info!(
target: LOG_TARGET,
"🧐 Found {:?} claps for network {:?}",
claps_len,
network_id,
);
for (clap_index, clap) in claps.iter().enumerate() {
let signature = match authority_key.sign(&clap.encode()) {
Some(signature) => signature,
None => {
log::info!(
target: LOG_TARGET,
"🧐 Clap #{} signing failed from authority #{:?} for network {:?}",
clap_index,
authority_index,
network_id,
);
return;
}
};
let call = Call::slow_clap {
clap: clap.clone(),
signature,
};
if let Err(e) =
SubmitTransaction::<T, Call<T>>::submit_unsigned_transaction(call.into())
{
log::info!(
target: LOG_TARGET,
"🧐 Failed to submit clap #{} from authority #{:?} for network {:?}: {:?}",
clap_index,
authority_index,
network_id,
e,
);
}
}
}
fn sign_and_submit_block_commitment<T: Config>(
&self,
from_block: u64,
authority_index: AuthIndex,
authority_key: T::AuthorityId,
session_index: SessionIndex,
network_id: NetworkIdOf<T>,
) {
let block_commitment = self.prepare_block_commitment::<T>(
from_block,
authority_index,
session_index,
network_id,
);
let stored_last_updated = BlockCommitments::<T>::get(&network_id)
.get(&authority_index)
.map(|details| details.last_updated)
.unwrap_or_default();
let current_last_updated = block_commitment
.commitment
.last_updated
.saturating_sub(COMMITMENT_DELAY_MILLIS);
if current_last_updated < stored_last_updated {
return;
}
log::info!(
target: LOG_TARGET,
"🧐 New block commitment from authority #{:?} for network {:?}",
authority_index,
network_id,
);
let signature = match authority_key.sign(&block_commitment.encode()) {
Some(signature) => signature,
None => {
log::info!(
target: LOG_TARGET,
"🧐 Block commitment signing failed from authority #{:?} for network {:?}",
authority_index,
network_id,
);
return;
}
};
let call = Call::commit_block {
block_commitment,
signature,
};
if let Err(e) = SubmitTransaction::<T, Call<T>>::submit_unsigned_transaction(call.into()) {
log::info!(
target: LOG_TARGET,
"🧐 Failed to submit block commitment from authority #{:?} for network {:?}: {:?}",
authority_index,
network_id,
e,
);
}
}
pub fn sign_and_submit<T: Config>(
&self,
from_block: u64,
authority_index: AuthIndex,
authority_key: T::AuthorityId,
session_index: SessionIndex,
network_id: NetworkIdOf<T>,
) {
match self {
EvmResponseType::TransactionLogs(_) => self.sign_and_submit_claps::<T>(
authority_index,
authority_key,
session_index,
network_id,
),
EvmResponseType::BlockNumber(_) => self.sign_and_submit_block_commitment::<T>(
from_block,
authority_index,
authority_key,
session_index,
network_id,
),
}
}
}
impl Log {
pub fn is_sufficient(&self) -> bool {
self.transaction_hash.is_some()

View File

@ -8,8 +8,8 @@ use serde::{Deserialize, Deserializer};
use frame_support::{
pallet_prelude::*,
traits::{
tokens::fungible::{Inspect, Mutate},
DisabledValidators, Get, OneSessionHandler, ValidatorSet, ValidatorSetWithIdentification,
Currency, DisabledValidators, Get, OneSessionHandler, ValidatorSet,
ValidatorSetWithIdentification,
},
WeakBoundedVec,
};
@ -17,22 +17,23 @@ use frame_system::{
offchain::{SendTransactionTypes, SubmitTransaction},
pallet_prelude::*,
};
pub use pallet::*;
use sp_core::H256;
use sp_runtime::{
offchain::{
self as rt_offchain,
storage::{MutateStorageError, StorageRetrievalError, StorageValueRef},
storage::StorageValueRef,
storage_lock::{StorageLock, Time},
HttpError,
},
traits::{BlockNumberProvider, Convert, Saturating, TrailingZeroInput},
Perbill, RuntimeAppPublic, RuntimeDebug, SaturatedConversion,
traits::{AtLeast32BitUnsigned, BlockNumberProvider, Convert, Saturating, TrailingZeroInput},
Perbill, RuntimeAppPublic, RuntimeDebug,
};
use sp_staking::{
offence::{Kind, Offence, ReportOffence},
SessionIndex,
EraIndex, SessionIndex,
};
use sp_std::{collections::btree_map::BTreeMap, prelude::*, vec::Vec};
@ -70,11 +71,43 @@ pub mod sr25519 {
const LOG_TARGET: &str = "runtime::ghost-slow-clap";
const DB_PREFIX: &[u8] = b"slow_clap::";
const MIN_LOCK_GUARD_PERIOD: u64 = 15_000;
const FETCH_TIMEOUT_PERIOD: u64 = 3_000;
const LOCK_BLOCK_EXPIRATION: u64 = 20;
const COMMITMENT_DELAY_MILLIS: u64 = 600_000;
pub type AuthIndex = u32;
#[derive(
RuntimeDebug,
Default,
Copy,
Clone,
Eq,
PartialEq,
Ord,
PartialOrd,
Encode,
Decode,
TypeInfo,
MaxEncodedLen,
)]
pub struct CommitmentDetails {
pub last_registered_block: u64,
pub last_seen_block: u64,
pub last_updated: u64,
}
#[derive(
RuntimeDebug, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, MaxEncodedLen,
)]
pub struct BlockCommitment<NetworkId> {
pub session_index: SessionIndex,
pub authority_index: AuthIndex,
pub network_id: NetworkId,
pub commitment: CommitmentDetails,
}
#[derive(
RuntimeDebug, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, MaxEncodedLen,
)]
@ -97,8 +130,6 @@ pub struct SessionAuthorityInfo {
#[cfg_attr(test, derive(PartialEq))]
enum OffchainErr<NetworkId> {
FailedSigning,
SubmitTransaction,
HttpJsonParsingError,
HttpBytesParsingError,
HttpRequestError(HttpError),
@ -106,38 +137,65 @@ enum OffchainErr<NetworkId> {
HttpResponseNotOk(u16),
ErrorInEvmResponse,
NoStoredNetworks,
NotValidator,
NoEndpointAvailable(NetworkId),
StorageRetrievalError(NetworkId),
ConcurrentModificationError(NetworkId),
UtxoNotImplemented(NetworkId),
UnknownNetworkType(NetworkId),
OffchainTimeoutPeriod(NetworkId),
TooManyRequests(NetworkId),
}
impl<NetworkId: core::fmt::Debug> core::fmt::Debug for OffchainErr<NetworkId> {
fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
match *self {
OffchainErr::FailedSigning => write!(fmt, "Failed to sign clap."),
OffchainErr::SubmitTransaction => write!(fmt, "Failed to submit transaction."),
OffchainErr::HttpJsonParsingError => write!(fmt, "Failed to parse evm response as JSON."),
OffchainErr::HttpBytesParsingError => write!(fmt, "Failed to parse evm response as bytes."),
OffchainErr::HttpJsonParsingError => {
write!(fmt, "Failed to parse evm response as JSON.")
}
OffchainErr::HttpBytesParsingError => {
write!(fmt, "Failed to parse evm response as bytes.")
}
OffchainErr::HttpRequestError(http_error) => match http_error {
HttpError::DeadlineReached => write!(fmt, "Requested action couldn't been completed within a deadline."),
HttpError::IoError => write!(fmt, "There was an IO error while processing the request."),
HttpError::Invalid => write!(fmt, "The ID of the request is invalid in this context."),
HttpError::DeadlineReached => write!(
fmt,
"Requested action couldn't been completed within a deadline."
),
HttpError::IoError => {
write!(fmt, "There was an IO error while processing the request.")
}
HttpError::Invalid => {
write!(fmt, "The ID of the request is invalid in this context.")
}
},
OffchainErr::ConcurrentModificationError(ref network_id) => write!(fmt, "The underlying DB failed to update due to a concurrent modification for network #{:?}.", network_id),
OffchainErr::StorageRetrievalError(ref network_id) => write!(fmt, "Storage value found for network #{:?} but it's undecodable.", network_id),
OffchainErr::StorageRetrievalError(ref network_id) => write!(
fmt,
"Storage value found for network #{:?} but it's undecodable.",
network_id
),
OffchainErr::RequestUncompleted => write!(fmt, "Failed to complete request."),
OffchainErr::HttpResponseNotOk(code) => write!(fmt, "Http response returned code {:?}.", code),
OffchainErr::HttpResponseNotOk(code) => {
write!(fmt, "Http response returned code {:?}.", code)
}
OffchainErr::ErrorInEvmResponse => write!(fmt, "Error in evm reponse."),
OffchainErr::NoStoredNetworks => write!(fmt, "No networks stored for the offchain slow claps."),
OffchainErr::NotValidator => write!(fmt, "Not a validator for slow clap, `--validator` flag needed."),
OffchainErr::UtxoNotImplemented(ref network_id) => write!(fmt, "Network #{:?} is marked as UTXO, which is not implemented yet.", 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::TooManyRequests(ref network_id) => write!(fmt, "Too many requests over RPC endpoint for network #{:?}.", network_id),
OffchainErr::NoStoredNetworks => {
write!(fmt, "No networks stored for the offchain slow claps.")
}
OffchainErr::NoEndpointAvailable(ref network_id) => write!(
fmt,
"No RPC endpoint available for network #{:?}.",
network_id
),
OffchainErr::UtxoNotImplemented(ref network_id) => write!(
fmt,
"Network #{:?} is marked as UTXO, which is not implemented yet.",
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
),
}
}
}
@ -145,7 +203,7 @@ impl<NetworkId: core::fmt::Debug> core::fmt::Debug for OffchainErr<NetworkId> {
pub type NetworkIdOf<T> = <<T as Config>::NetworkDataHandler as NetworkDataBasicHandler>::NetworkId;
pub type BalanceOf<T> =
<<T as Config>::Currency as Inspect<<T as frame_system::Config>::AccountId>>::Balance;
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
pub type ValidatorId<T> = <<T as Config>::ValidatorSet as ValidatorSet<
<T as frame_system::Config>::AccountId,
@ -160,6 +218,12 @@ pub type IdentificationTuple<T> = (
type OffchainResult<T, A> = Result<A, OffchainErr<NetworkIdOf<T>>>;
pub trait ApplauseListener<Balance: AtLeast32BitUnsigned> {
fn get_current_era() -> EraIndex;
fn get_threshold_amount(era: EraIndex) -> Balance;
fn get_validator_total_exposure(era: EraIndex, index: usize) -> Balance;
}
#[frame_support::pallet]
pub mod pallet {
use super::*;
@ -182,7 +246,7 @@ pub mod pallet {
+ MaxEncodedLen;
type ValidatorSet: ValidatorSetWithIdentification<Self::AccountId>;
type Currency: Inspect<Self::AccountId> + Mutate<Self::AccountId>;
type Currency: Currency<Self::AccountId>;
type NetworkDataHandler: NetworkDataBasicHandler
+ NetworkDataInspectHandler<NetworkData>
+ NetworkDataMutateHandler<NetworkData, BalanceOf<Self>>;
@ -193,6 +257,7 @@ pub mod pallet {
ThrottlingOffence<IdentificationTuple<Self>>,
>;
type DisabledValidators: DisabledValidators;
type ApplauseListener: ApplauseListener<BalanceOf<Self>>;
#[pallet::constant]
type MaxAuthorities: Get<u32>;
@ -235,6 +300,10 @@ pub mod pallet {
receiver: T::AccountId,
received_amount: BalanceOf<T>,
},
BlockCommited {
authority_id: AuthIndex,
network_id: NetworkIdOf<T>,
},
}
#[pallet::error]
@ -246,8 +315,33 @@ pub mod pallet {
CouldNotAccumulateCommission,
CouldNotAccumulateIncomingImbalance,
CouldNotIncreaseGatekeeperAmount,
NonExistentAuthorityIndex,
TimeWentBackwards,
}
#[pallet::storage]
#[pallet::getter(fn clapped_amount)]
pub(super) type ClappedAmount<T: Config> = StorageNMap<
_,
(
NMapKey<Twox64Concat, SessionIndex>,
NMapKey<Twox64Concat, H256>,
NMapKey<Twox64Concat, H256>,
),
BalanceOf<T>,
ValueQuery,
>;
#[pallet::storage]
#[pallet::getter(fn block_commitments)]
pub(super) type BlockCommitments<T: Config> = StorageMap<
_,
Twox64Concat,
NetworkIdOf<T>,
BTreeMap<AuthIndex, CommitmentDetails>,
ValueQuery,
>;
#[pallet::storage]
#[pallet::getter(fn received_claps)]
pub(super) type ReceivedClaps<T: Config> = StorageNMap<
@ -336,48 +430,30 @@ pub mod pallet {
}
#[pallet::call_index(1)]
#[pallet::weight(T::WeightInfo::self_applause())]
pub fn self_applause(
#[pallet::weight((T::WeightInfo::commit_block(), DispatchClass::Normal, Pays::No))]
pub fn commit_block(
origin: OriginFor<T>,
network_id: NetworkIdOf<T>,
prev_session_index: SessionIndex,
transaction_hash: H256,
receiver: T::AccountId,
amount: BalanceOf<T>,
block_commitment: BlockCommitment<NetworkIdOf<T>>,
// since signature verification is done in `validate_unsigned`
// we can skip doing it here again.
_signature: <T::AuthorityId as RuntimeAppPublic>::Signature,
) -> DispatchResult {
let _ = ensure_signed(origin)?;
Self::applause_if_posible(
network_id,
prev_session_index,
transaction_hash,
receiver,
amount,
)
ensure_none(origin)?;
Self::try_commit_block(&block_commitment)?;
Ok(())
}
}
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn offchain_worker(now: BlockNumberFor<T>) {
match Self::start_slow_clapping(now) {
Ok(iter) => {
for result in iter.into_iter() {
if let Err(e) = result {
log::info!(
target: LOG_TARGET,
"👏 Skipping slow clap at {:?}: {:?}",
now,
e,
)
}
}
}
Err(e) => log::info!(
if let Err(e) = Self::start_slow_clapping(now) {
log::info!(
target: LOG_TARGET,
"👏 Could not start slow clap at {:?}: {:?}",
"👏 Skipping slow clap at {:?}: {:?}",
now,
e,
),
)
}
}
}
@ -385,39 +461,65 @@ pub mod pallet {
#[pallet::validate_unsigned]
impl<T: Config> ValidateUnsigned for Pallet<T> {
type Call = Call<T>;
fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity {
if let Call::slow_clap { clap, signature } = call {
let (session_index, _) = Self::mended_session_index(&clap);
let authorities = Authorities::<T>::get(&session_index);
let authority = match authorities.get(clap.authority_index as usize) {
Some(authority) => authority,
None => return InvalidTransaction::BadSigner.into(),
};
match call {
Call::commit_block {
block_commitment,
signature,
} => {
let authorities = Authorities::<T>::get(&block_commitment.session_index);
let authority = match authorities.get(block_commitment.authority_index as usize)
{
Some(authority) => authority,
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 = block_commitment.using_encoded(|encoded_commitment| {
authority.verify(&encoded_commitment, signature)
});
if !signature_valid {
return InvalidTransaction::BadProof.into();
}
ValidTransaction::with_tag_prefix("SlowClap")
.priority(T::UnsignedPriority::get())
.and_provides(block_commitment.commitment.encode())
.longevity(LOCK_BLOCK_EXPIRATION)
.propagate(true)
.build()
}
Call::slow_clap { clap, signature } => {
let (session_index, _) = Self::mended_session_index(&clap);
let authorities = Authorities::<T>::get(&session_index);
let authority = match authorities.get(clap.authority_index as usize) {
Some(authority) => authority,
None => return InvalidTransaction::BadSigner.into(),
};
let signature_valid =
clap.using_encoded(|encoded_clap| authority.verify(&encoded_clap, signature));
if ClapsInSession::<T>::get(&session_index)
.get(&clap.authority_index)
.map(|info| info.disabled)
.unwrap_or_default()
{
return InvalidTransaction::BadSigner.into();
}
if !signature_valid {
return InvalidTransaction::BadProof.into();
let signature_valid = clap
.using_encoded(|encoded_clap| authority.verify(&encoded_clap, signature));
if !signature_valid {
return InvalidTransaction::BadProof.into();
}
ValidTransaction::with_tag_prefix("SlowClap")
.priority(T::UnsignedPriority::get())
.and_provides(signature)
.longevity(LOCK_BLOCK_EXPIRATION)
.propagate(true)
.build()
}
ValidTransaction::with_tag_prefix("SlowClap")
.priority(T::UnsignedPriority::get())
.and_provides(signature)
.longevity(LOCK_BLOCK_EXPIRATION)
.propagate(true)
.build()
} else {
InvalidTransaction::Call.into()
_ => InvalidTransaction::Call.into(),
}
}
}
@ -503,33 +605,23 @@ impl<T: Config> Pallet<T> {
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 =
ReceivedClaps::<T>::try_mutate(&received_claps_key, |tree_of_claps| {
let number_of_claps = tree_of_claps.len();
match (tree_of_claps.contains(&clap.authority_index), clap.removed) {
(true, true) => tree_of_claps
.remove(&clap.authority_index)
.then(|| number_of_claps.saturating_sub(1))
.ok_or(Error::<T>::UnregisteredClapRemove),
(true, false) => Err(Error::<T>::AlreadyClapped),
(false, true) => Err(Error::<T>::UnregisteredClapRemove),
(false, false) => tree_of_claps
.try_insert(clap.authority_index)
.map(|_| number_of_claps.saturating_add(1))
.map_err(|_| Error::<T>::TooMuchAuthorities),
}
})?;
ReceivedClaps::<T>::try_mutate(&received_claps_key, |tree_of_claps| {
let number_of_claps = tree_of_claps.len();
match (tree_of_claps.contains(&clap.authority_index), clap.removed) {
(true, true) => tree_of_claps
.remove(&clap.authority_index)
.then(|| number_of_claps.saturating_sub(1))
.ok_or(Error::<T>::UnregisteredClapRemove),
(true, false) => Err(Error::<T>::AlreadyClapped),
(false, true) => Err(Error::<T>::UnregisteredClapRemove),
(false, false) => tree_of_claps
.try_insert(clap.authority_index)
.map(|_| number_of_claps.saturating_add(1))
.map_err(|_| Error::<T>::TooMuchAuthorities),
}
})?;
claps_in_session
.entry(clap.authority_index)
@ -550,8 +642,7 @@ impl<T: Config> Pallet<T> {
});
let enough_authorities =
Perbill::from_rational(number_of_received_claps as u32, active_authorities as u32)
> Perbill::from_percent(T::ApplauseThreshold::get());
Self::validator_clap_by_amount(clap.authority_index, &received_claps_key);
if enough_authorities {
let _ = Self::try_applause(&clap, &received_claps_key).inspect_err(|error_msg| {
@ -566,6 +657,24 @@ impl<T: Config> Pallet<T> {
Ok(())
}
fn validator_clap_by_amount(
authority_index: AuthIndex,
received_claps_key: &(SessionIndex, &H256, &H256),
) -> bool {
let era = T::ApplauseListener::get_current_era();
let threshold_amount = T::ApplauseListener::get_threshold_amount(era);
let new_clapped_amount =
T::ApplauseListener::get_validator_total_exposure(era, authority_index as usize);
let total_clapped = ClappedAmount::<T>::mutate(received_claps_key, |clapped_amount| {
let total_clapped = clapped_amount.saturating_add(new_clapped_amount);
*clapped_amount = total_clapped;
total_clapped
});
total_clapped >= threshold_amount
}
fn try_applause(
clap: &Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>,
received_claps_key: &(SessionIndex, &H256, &H256),
@ -589,9 +698,7 @@ impl<T: Config> Pallet<T> {
let _ = T::NetworkDataHandler::accumulate_commission(&commission)
.map_err(|_| Error::<T>::CouldNotAccumulateCommission)?;
if final_amount > T::Currency::minimum_balance() {
T::Currency::mint_into(&clap.receiver, final_amount)?;
}
let _ = T::Currency::deposit_creating(&clap.receiver, final_amount);
*is_applaused = true;
@ -605,88 +712,33 @@ impl<T: Config> Pallet<T> {
})
}
fn applause_if_posible(
network_id: NetworkIdOf<T>,
prev_session_index: SessionIndex,
transaction_hash: H256,
receiver: T::AccountId,
amount: BalanceOf<T>,
) -> DispatchResult {
let curr_session_index = prev_session_index.saturating_add(1);
let clap_unique_hash = Self::generate_unique_hash(&receiver, &amount, &network_id);
fn try_commit_block(new_commitment: &BlockCommitment<NetworkIdOf<T>>) -> DispatchResult {
BlockCommitments::<T>::try_mutate(&new_commitment.network_id, |current_commitments| {
let authority_index = new_commitment.authority_index;
let new_commitment_details = new_commitment.commitment;
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 current_last_updated = current_commitments
.get(&authority_index)
.map(|details| details.last_updated)
.unwrap_or_default();
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);
ensure!(
new_commitment_details.last_updated > current_last_updated,
Error::<T>::TimeWentBackwards
);
let mut previous_claps = ClapsInSession::<T>::get(&prev_session_index);
let mut total_received_claps =
ReceivedClaps::<T>::get(&prev_received_claps_key).into_inner();
current_commitments.insert(authority_index, new_commitment_details);
for (auth_index, info) in ClapsInSession::<T>::get(&curr_session_index).iter() {
if !info.disabled {
continue;
}
Self::deposit_event(Event::<T>::BlockCommited {
network_id: new_commitment.network_id,
authority_id: authority_index,
});
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 {
authority_index: Default::default(),
block_number: Default::default(),
removed: Default::default(),
session_index: Default::default(),
transaction_hash: Default::default(),
network_id,
receiver,
amount,
};
let enough_authorities =
Perbill::from_rational(total_received_claps.len() as u32, active_authorities as u32)
> Perbill::from_percent(T::ApplauseThreshold::get());
ensure!(enough_authorities, Error::<T>::NotEnoughClaps);
Self::try_applause(&clap, &prev_received_claps_key)?;
Ok(())
Ok(())
})
}
fn start_slow_clapping(
block_number: BlockNumberFor<T>,
) -> OffchainResult<T, impl Iterator<Item = OffchainResult<T, ()>>> {
sp_io::offchain::is_validator()
.then(|| ())
.ok_or(OffchainErr::NotValidator)?;
fn start_slow_clapping(block_number: BlockNumberFor<T>) -> OffchainResult<T, ()> {
let session_index = T::ValidatorSet::session_index();
let networks_len = T::NetworkDataHandler::iter().count();
let network_in_use = T::NetworkDataHandler::iter()
@ -701,7 +753,6 @@ impl<T: Config> Pallet<T> {
let network_id_encoded = network_in_use.0.encode();
let last_timestamp_key = Self::create_storage_key(b"last-timestamp-", &network_id_encoded);
let rate_limit_delay_key = Self::create_storage_key(b"rate-limit-", &network_id_encoded);
let rate_limit_delay = Self::read_persistent_offchain_storage(
&rate_limit_delay_key,
@ -710,51 +761,24 @@ impl<T: Config> Pallet<T> {
let network_lock_key = Self::create_storage_key(b"network-lock-", &network_id_encoded);
let block_until =
rt_offchain::Duration::from_millis(networks_len as u64 * FETCH_TIMEOUT_PERIOD);
rt_offchain::Duration::from_millis(rate_limit_delay.max(MIN_LOCK_GUARD_PERIOD));
let mut network_lock = StorageLock::<Time>::with_deadline(&network_lock_key, block_until);
network_lock
let _lock_guard = network_lock
.try_lock()
.map_err(|_| OffchainErr::OffchainTimeoutPeriod(network_in_use.0))?;
StorageValueRef::persistent(&last_timestamp_key)
.mutate(
|result_timestamp: Result<Option<u64>, StorageRetrievalError>| {
let current_timestmap = sp_io::offchain::timestamp().unix_millis();
match result_timestamp {
Ok(option_timestamp) => match option_timestamp {
Some(stored_timestamp) if stored_timestamp > current_timestmap => {
Err(OffchainErr::TooManyRequests(network_in_use.0).into())
}
_ => Ok(current_timestmap.saturating_add(rate_limit_delay)),
},
Err(_) => Err(OffchainErr::StorageRetrievalError(network_in_use.0).into()),
}
},
)
.map_err(|error| match error {
MutateStorageError::ValueFunctionFailed(offchain_error) => offchain_error,
MutateStorageError::ConcurrentModification(_) => {
OffchainErr::ConcurrentModificationError(network_in_use.0).into()
}
})?;
log::info!(
target: LOG_TARGET,
"🧐 Offchain worker started for network #{:?} at block #{:?}",
network_in_use.0,
block_number,
);
Ok(
Self::local_authorities(&session_index).map(move |(authority_index, authority_key)| {
Self::do_evm_claps_or_save_block(
authority_index,
authority_key,
session_index,
network_in_use.0,
&network_in_use.1,
)
}),
)
Self::do_evm_claps_or_save_block(session_index, network_in_use.0, &network_in_use.1)
}
fn do_evm_claps_or_save_block(
authority_index: AuthIndex,
authority_key: T::AuthorityId,
session_index: SessionIndex,
network_id: NetworkIdOf<T>,
network_data: &NetworkData,
@ -778,184 +802,94 @@ impl<T: Config> Pallet<T> {
let random_number = <u32>::decode(&mut TrailingZeroInput::new(random_seed.as_ref()))
.expect("input is padded with zeroes; qed");
let rpc_endpoint = if stored_endpoints.len() > 0 {
stored_endpoints
.iter()
.nth(
(random_number as usize)
.checked_rem(stored_endpoints.len())
.unwrap_or_default(),
)
.expect("stored endpoint should be non empty; qed")
let random_index = (random_number as usize)
.checked_rem(stored_endpoints.len())
.unwrap_or_default();
let endpoints = if !stored_endpoints.is_empty() {
&stored_endpoints
} else {
network_data
.default_endpoints
.iter()
.nth(
(random_number as usize)
.checked_rem(network_data.default_endpoints.len())
.unwrap_or_default(),
)
.expect("default endpoint should be non empty; qed")
&network_data.default_endpoints
};
StorageValueRef::persistent(&block_number_key)
.mutate(
|result_block_range: Result<Option<(u64, u64)>, StorageRetrievalError>| {
match result_block_range {
Ok(maybe_block_range) => {
let request_body = match maybe_block_range {
Some((from_block, to_block))
if from_block < to_block.saturating_sub(1) =>
{
Self::prepare_request_body_for_latest_transfers(
from_block,
to_block.saturating_sub(1),
network_data,
)
}
_ => Self::prepare_request_body_for_latest_block(network_data),
};
let rpc_endpoint = endpoints
.get(random_index)
.ok_or(OffchainErr::NoEndpointAvailable(network_id))?;
let response_bytes =
Self::fetch_from_remote(&rpc_endpoint, &request_body)?;
let (from_block, to_block): (u64, u64) = StorageValueRef::persistent(&block_number_key)
.get()
.map_err(|_| OffchainErr::StorageRetrievalError(network_id))?
.unwrap_or_default();
match network_data.network_type {
NetworkType::Evm => {
let maybe_new_evm_block = Self::apply_evm_response(
&response_bytes,
authority_index,
authority_key,
session_index,
network_id,
)?;
let estimated_block = maybe_new_evm_block
.map(|new_evm_block| {
new_evm_block
.saturating_sub(network_data.finality_delay)
})
.unwrap_or_default();
Ok(match maybe_block_range {
Some((from_block, to_block)) => match maybe_new_evm_block {
Some(_) if from_block.le(&to_block) => {
let adjusted_to_block = estimated_block
.checked_sub(from_block)
.map(|current_distance| {
current_distance
.le(&max_block_distance)
.then(|| estimated_block)
})
.flatten()
.unwrap_or(
from_block
.saturating_add(max_block_distance)
.min(estimated_block),
);
(from_block, adjusted_to_block)
}
_ => (to_block, to_block),
},
None => (estimated_block, estimated_block),
})
}
NetworkType::Utxo => {
Err(OffchainErr::UtxoNotImplemented(network_id).into())
}
_ => Err(OffchainErr::UnknownNetworkType(network_id).into()),
}
}
Err(_) => Err(OffchainErr::StorageRetrievalError(network_id).into()),
}
},
let request_body = if from_block < to_block.saturating_sub(1) {
Self::prepare_request_body_for_latest_transfers(
from_block,
to_block.saturating_sub(1),
network_data,
)
.map_err(|error| match error {
MutateStorageError::ValueFunctionFailed(offchain_error) => offchain_error,
MutateStorageError::ConcurrentModification(_) => {
OffchainErr::ConcurrentModificationError(network_id).into()
} else {
Self::prepare_request_body_for_latest_block(network_data)
};
let response_bytes = Self::fetch_from_remote(&rpc_endpoint, &request_body)?;
match network_data.network_type {
NetworkType::Evm => {
let parsed_evm_response = Self::parse_evm_response(&response_bytes)?;
let new_block_range = match parsed_evm_response {
EvmResponseType::BlockNumber(new_evm_block) if from_block.le(&to_block) => {
let estimated_block =
new_evm_block.saturating_sub(network_data.finality_delay);
let adjusted_block =
Self::adjust_to_block(estimated_block, from_block, max_block_distance);
if from_block == 0 {
(estimated_block, estimated_block)
} else {
(from_block, adjusted_block)
}
}
_ => (to_block, to_block),
};
StorageValueRef::persistent(&block_number_key).set(&new_block_range);
if !sp_io::offchain::is_validator() {
log::info!(target: LOG_TARGET, "🧐 Not a validator; no transactions available");
return Ok(());
}
})
.map(|_| ())
for (authority_index, authority_key) in Self::local_authorities(&session_index) {
parsed_evm_response.sign_and_submit::<T>(
new_block_range.0,
authority_index,
authority_key,
session_index,
network_id,
);
}
Ok(())
}
NetworkType::Utxo => Err(OffchainErr::UtxoNotImplemented(network_id).into()),
_ => Err(OffchainErr::UnknownNetworkType(network_id).into()),
}
}
fn apply_evm_response(
response_bytes: &[u8],
authority_index: AuthIndex,
authority_key: T::AuthorityId,
session_index: SessionIndex,
network_id: NetworkIdOf<T>,
) -> OffchainResult<T, Option<u64>> {
match Self::parse_evm_response(&response_bytes)? {
EvmResponseType::BlockNumber(new_evm_block) => {
log::info!(
target: LOG_TARGET,
"🧐 New evm block #{:?} found for network {:?}",
new_evm_block,
network_id,
);
Ok(Some(new_evm_block))
}
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);
}
fn adjust_to_block(estimated_block: u64, from_block: u64, max_block_distance: u64) -> u64 {
let fallback_value = from_block
.saturating_add(max_block_distance)
.min(estimated_block);
let claps: Vec<_> = evm_logs
.iter()
.filter_map(|log| {
log.is_sufficient().then(|| Clap {
authority_index,
session_index,
network_id,
removed: log.removed,
receiver: T::AccountId::decode(&mut &log.topics[1][0..32])
.expect("32 bytes always construct an AccountId32"),
amount: u128::from_be_bytes(
log.topics[2][16..32]
.try_into()
.expect("amount is valid hex; qed"),
)
.saturated_into::<BalanceOf<T>>(),
transaction_hash: log
.transaction_hash
.clone()
.expect("tx hash exists; qed"),
block_number: log.block_number.expect("block number exists; qed"),
})
})
.collect();
log::info!(
target: LOG_TARGET,
"🧐 {:?} evm logs found for network {:?}",
claps.len(),
network_id,
);
for clap in claps {
let signature = authority_key
.sign(&clap.encode())
.ok_or(OffchainErr::FailedSigning)?;
let call = Call::slow_clap { clap, signature };
SubmitTransaction::<T, Call<T>>::submit_unsigned_transaction(call.into())
.map_err(|_| OffchainErr::SubmitTransaction)?;
}
Ok(None)
}
}
estimated_block
.checked_sub(from_block)
.map(|current_distance| {
current_distance
.le(&max_block_distance)
.then_some(estimated_block)
})
.flatten()
.unwrap_or(fallback_value)
}
fn local_authorities(
@ -1160,11 +1094,6 @@ impl<T: Config> Pallet<T> {
.expect("more than the maximum number of authorities");
Authorities::<T>::set(session_index, bounded_authorities);
}
#[cfg(feature = "runtime-benchmarks")]
fn trigger_nullification_for_benchmark() {
T::NetworkDataHandler::trigger_nullification();
}
}
impl<T: Config> sp_runtime::BoundToRuntimeAppPublic for Pallet<T> {
@ -1193,6 +1122,10 @@ impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
where
I: Iterator<Item = (&'a T::AccountId, T::AuthorityId)>,
{
for (network_id, _) in BlockCommitments::<T>::iter() {
BlockCommitments::<T>::remove(network_id);
}
let authorities = validators.map(|x| x.1).collect::<Vec<_>>();
Self::initialize_authorities(authorities);
}

View File

@ -9,7 +9,7 @@ use pallet_session::historical as pallet_session_historical;
use sp_runtime::{
curve::PiecewiseLinear,
testing::{TestXt, UintAuthorityId},
traits::ConvertInto,
traits::{AtLeast32BitUnsigned, ConvertInto},
Permill,
};
use sp_staking::{
@ -20,7 +20,7 @@ use sp_staking::{
use sp_runtime::BuildStorage;
use crate as slow_clap;
use crate::Config;
use crate::{ApplauseListener, Config, EraIndex};
type Block = frame_system::mocking::MockBlock<Runtime>;
@ -174,6 +174,32 @@ impl pallet_balances::Config for Runtime {
type WeightInfo = ();
}
type Balance = u64;
pub struct TestSomeCoolTrait;
impl ApplauseListener<Balance> for TestSomeCoolTrait
where
Balance: AtLeast32BitUnsigned + From<u64>,
{
fn get_current_era() -> EraIndex {
1
}
fn get_threshold_amount(_era: EraIndex) -> Balance {
666_666_667u64.into()
}
fn get_validator_total_exposure(_era: EraIndex, index: usize) -> Balance {
match index {
0 => 500_000_000u64,
1 => 300_000_000u64,
2 => 200_000_000u64,
_ => 0,
}
.into()
}
}
impl Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type AuthorityId = UintAuthorityId;
@ -184,6 +210,7 @@ impl Config for Runtime {
type BlockNumberProvider = System;
type ReportUnresponsiveness = OffenceHandler;
type DisabledValidators = Session;
type ApplauseListener = TestSomeCoolTrait;
type MaxAuthorities = ConstU32<5>;
type ApplauseThreshold = ConstU32<50>;

View File

@ -70,6 +70,35 @@ fn do_clap_from_first_authority(
SlowClap::slow_clap(RuntimeOrigin::none(), clap, signature)
}
fn do_block_commitment(
session_index: u32,
network_id: u32,
authority_index: u32,
) -> dispatch::DispatchResult {
let last_updated = 1337;
let block_commitment = BlockCommitment {
session_index,
authority_index,
network_id,
commitment: CommitmentDetails {
last_registered_block: 69,
last_seen_block: 420,
last_updated,
},
};
let authority = UintAuthorityId::from((authority_index + 1) as u64);
let signature = authority.sign(&block_commitment.encode()).unwrap();
SlowClap::pre_dispatch(&crate::Call::commit_block {
block_commitment: block_commitment.clone(),
signature: signature.clone(),
})
.map_err(|e| <&'static str>::from(e))?;
SlowClap::commit_block(RuntimeOrigin::none(), block_commitment, signature)
}
fn do_clap_from(
session_index: u32,
network_id: u32,
@ -100,7 +129,7 @@ fn do_clap_from(
}
#[test]
fn test_throttling_slash_function() {
fn should_calculate_throttling_slash_function_correctly() {
let dummy_offence = ThrottlingOffence {
session_index: 0,
validator_set_count: 50,
@ -120,7 +149,7 @@ fn test_throttling_slash_function() {
}
#[test]
fn test_median_calculations_are_correct() {
fn should_calculate_median_correctly() {
new_test_ext().execute_with(|| {
let data = BTreeMap::from([
(
@ -304,6 +333,16 @@ fn request_body_is_correct_for_get_logs() {
});
}
#[test]
fn should_correctly_adjust_to_block() {
assert_eq!(SlowClap::adjust_to_block(420, 69, 1337), 420);
assert_eq!(SlowClap::adjust_to_block(420, 1337, 69), 420);
assert_eq!(SlowClap::adjust_to_block(1337, 420, 69), 489);
assert_eq!(SlowClap::adjust_to_block(1337, 69, 420), 489);
assert_eq!(SlowClap::adjust_to_block(69, 1337, 420), 69);
assert_eq!(SlowClap::adjust_to_block(69, 420, 1337), 69);
}
#[test]
fn should_make_http_call_for_block_number() {
let (offchain, state) = TestOffchainExt::new();
@ -361,10 +400,14 @@ fn should_make_http_call_and_parse_block_number() {
let request_body = SlowClap::prepare_request_body_for_latest_block(&network_data);
let raw_response = SlowClap::fetch_from_remote(&rpc_endpoint, &request_body)?;
let maybe_evm_block_number =
SlowClap::apply_evm_response(&raw_response, 69, Default::default(), 420, 1)?;
let evm_block_number = SlowClap::parse_evm_response(&raw_response).map(
|parsed_response| match parsed_response {
EvmResponseType::BlockNumber(block_number) => block_number,
EvmResponseType::TransactionLogs(_) => 0,
},
)?;
assert_eq!(maybe_evm_block_number, Some(20335745));
assert_eq!(evm_block_number, 20335745);
Ok(())
});
}
@ -382,7 +425,6 @@ fn should_make_http_call_and_parse_logs() {
evm_logs_response(&mut state.write());
let _: Result<(), OffchainErr<u32>> = t.execute_with(|| {
let session_index = advance_session_and_get_index();
let rpc_endpoint = get_rpc_endpoint();
let from_block: u64 = 20335770;
@ -402,15 +444,6 @@ fn should_make_http_call_and_parse_logs() {
EvmResponseType::TransactionLogs(evm_logs) => assert_eq!(evm_logs.len(), 2),
}
let maybe_evm_block_number = SlowClap::apply_evm_response(
&raw_response,
1,
UintAuthorityId::from(2),
session_index,
network_id,
)?;
assert_eq!(maybe_evm_block_number, None);
Ok(())
});
}
@ -529,25 +562,25 @@ fn should_applause_and_take_next_claps() {
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
false
);
assert_eq!(Balances::balance(&receiver), 0);
assert_eq!(Balances::total_balance(&receiver), 0);
assert_ok!(do_clap_from(session_index, network_id, 0, false));
assert_eq!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
false
);
assert_eq!(Balances::balance(&receiver), 0);
assert_eq!(Balances::total_balance(&receiver), 0);
assert_ok!(do_clap_from(session_index, network_id, 1, false));
assert_eq!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
true
);
assert_eq!(Balances::balance(&receiver), amount);
assert_eq!(Balances::total_balance(&receiver), amount);
assert_ok!(do_clap_from(session_index, network_id, 2, false));
assert_eq!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
true
);
assert_eq!(Balances::balance(&receiver), amount);
assert_eq!(Balances::total_balance(&receiver), amount);
});
}
@ -779,8 +812,8 @@ fn should_clap_without_applause_on_gatekeeper_amount_overflow() {
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key_first),
true
);
assert_eq!(Balances::balance(&first_receiver), big_amount);
assert_eq!(Balances::balance(&second_receiver), 0);
assert_eq!(Balances::total_balance(&first_receiver), big_amount);
assert_eq!(Balances::total_balance(&second_receiver), 0);
for authority_index in 0..=2 {
let clap = Clap {
@ -798,8 +831,8 @@ fn should_clap_without_applause_on_gatekeeper_amount_overflow() {
assert_ok!(SlowClap::slow_clap(RuntimeOrigin::none(), clap, signature));
}
assert_eq!(Balances::balance(&first_receiver), big_amount);
assert_eq!(Balances::balance(&second_receiver), 0);
assert_eq!(Balances::total_balance(&first_receiver), big_amount);
assert_eq!(Balances::total_balance(&second_receiver), 0);
assert_eq!(Networks::gatekeeper_amount(network_id), big_amount);
assert_eq!(Networks::bridged_imbalance().bridged_in, big_amount);
@ -843,8 +876,8 @@ fn should_clap_without_applause_on_commission_overflow() {
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key_first),
true
);
assert_eq!(Balances::balance(&first_receiver), big_amount);
assert_eq!(Balances::balance(&second_receiver), 0);
assert_eq!(Balances::total_balance(&first_receiver), big_amount);
assert_eq!(Balances::total_balance(&second_receiver), 0);
for authority_index in 0..=2 {
let clap = Clap {
@ -862,8 +895,8 @@ fn should_clap_without_applause_on_commission_overflow() {
assert_ok!(SlowClap::slow_clap(RuntimeOrigin::none(), clap, signature));
}
assert_eq!(Balances::balance(&first_receiver), big_amount);
assert_eq!(Balances::balance(&second_receiver), 0);
assert_eq!(Balances::total_balance(&first_receiver), big_amount);
assert_eq!(Balances::total_balance(&second_receiver), 0);
assert_eq!(Networks::gatekeeper_amount(network_id), big_amount);
assert_eq!(Networks::gatekeeper_amount(network_id_other), big_amount);
@ -896,7 +929,7 @@ fn should_nullify_commission_on_finalize() {
total_issuance,
0u64
),
(420000000000000u64, 0u64)
(amount, 0u64)
); // precomputed values
assert_eq!(Networks::is_nullification_period(), true);
Networks::on_finalize(System::block_number());
@ -934,139 +967,13 @@ fn should_avoid_applause_during_nullification_period() {
assert_ok!(do_clap_from(session_index, network_id, 0, false));
assert_ok!(do_clap_from(session_index, network_id, 1, false));
assert_eq!(Balances::balance(&receiver), 0);
assert_eq!(Balances::total_balance(&receiver), 0);
Networks::on_finalize(System::block_number());
assert_eq!(Networks::is_nullification_period(), false);
assert_ok!(do_clap_from(session_index, network_id, 2, false));
assert_eq!(Balances::balance(&receiver), amount);
});
}
#[test]
fn should_self_applause_after_diabled() {
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 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);
assert_eq!(Balances::total_balance(&receiver), amount);
});
}
@ -1088,7 +995,7 @@ fn should_avoid_session_overlap_on_mended_session_index() {
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
false
);
assert_eq!(Balances::balance(&receiver), 0u64);
assert_eq!(Balances::total_balance(&receiver), 0u64);
assert_ok!(do_clap_from(session_index, network_id, 1, false));
assert_ok!(do_clap_from(session_index, network_id, 2, false));
@ -1097,7 +1004,7 @@ fn should_avoid_session_overlap_on_mended_session_index() {
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
true
);
assert_eq!(Balances::balance(&receiver), amount);
assert_eq!(Balances::total_balance(&receiver), amount);
});
}
@ -1187,7 +1094,7 @@ fn should_not_fail_on_sub_existential_balance() {
assert_eq!(Networks::gatekeeper_amount(network_id), 0);
assert_eq!(Networks::bridged_imbalance().bridged_in, 0);
assert_eq!(Networks::bridged_imbalance().bridged_out, 0);
assert_eq!(Balances::balance(&receiver), 0);
assert_eq!(Balances::total_balance(&receiver), 0);
assert_eq!(
SlowClap::applauses_for_transaction(&received_claps_key),
false
@ -1201,7 +1108,7 @@ fn should_not_fail_on_sub_existential_balance() {
assert_eq!(Networks::gatekeeper_amount(network_id), amount);
assert_eq!(Networks::bridged_imbalance().bridged_in, 0);
assert_eq!(Networks::bridged_imbalance().bridged_out, 0);
assert_eq!(Balances::balance(&receiver), 0);
assert_eq!(Balances::total_balance(&receiver), 0);
assert_eq!(
SlowClap::applauses_for_transaction(&received_claps_key),
true
@ -1225,6 +1132,83 @@ fn should_emit_black_swan_if_not_enough_authorities_left() {
});
}
#[test]
fn should_register_block_commitments() {
let (network_id, _, _) = generate_unique_hash(None, None, None, None);
new_test_ext().execute_with(|| {
let session_index = advance_session_and_get_index();
for commitment_details in SlowClap::block_commitments(network_id).values() {
assert_eq!(commitment_details.last_registered_block, 0);
assert_eq!(commitment_details.last_seen_block, 0);
assert_eq!(commitment_details.last_updated, 0);
}
assert_ok!(do_block_commitment(session_index, network_id, 0));
assert_ok!(do_block_commitment(session_index, network_id, 1));
assert_ok!(do_block_commitment(session_index, network_id, 2));
assert_err!(
do_block_commitment(session_index, network_id, 3),
DispatchError::Other("Invalid signing address"),
);
assert_err!(
do_block_commitment(session_index, network_id, 1),
Error::<Runtime>::TimeWentBackwards,
);
for commitment_details in SlowClap::block_commitments(network_id).values() {
assert_eq!(commitment_details.last_registered_block, 69);
assert_eq!(commitment_details.last_seen_block, 420);
assert_eq!(commitment_details.last_updated, 1337);
}
advance_session();
for commitment_details in SlowClap::block_commitments(network_id).values() {
assert_eq!(commitment_details.last_registered_block, 0);
assert_eq!(commitment_details.last_seen_block, 0);
assert_eq!(commitment_details.last_updated, 0);
}
});
}
#[test]
fn should_accumulate_clapped_amount() {
let (network_id, transaction_hash, unique_transaction_hash) =
generate_unique_hash(None, None, None, None);
new_test_ext().execute_with(|| {
let session_index = advance_session_and_get_index();
let storage_key = (session_index, transaction_hash, unique_transaction_hash);
let era = <Runtime as Config>::ApplauseListener::get_current_era();
let threshold_amount = <Runtime as Config>::ApplauseListener::get_threshold_amount(era);
assert_eq!(
ClappedAmount::<Runtime>::get(&storage_key) < threshold_amount,
true
);
assert_ok!(do_clap_from(session_index, network_id, 2, false));
assert_eq!(
ClappedAmount::<Runtime>::get(&storage_key) < threshold_amount,
true
);
assert_ok!(do_clap_from(session_index, network_id, 1, false));
assert_eq!(
ClappedAmount::<Runtime>::get(&storage_key) < threshold_amount,
true
);
assert_ok!(do_clap_from(session_index, network_id, 0, false));
assert_eq!(
ClappedAmount::<Runtime>::get(&storage_key) > threshold_amount,
true
);
});
}
fn advance_session_and_get_index() -> u32 {
advance_session();
assert_eq!(Session::validators(), Vec::<u64>::new());

View File

@ -48,70 +48,7 @@ use core::marker::PhantomData;
pub trait WeightInfo {
fn slow_clap() -> Weight;
fn self_applause()-> Weight;
}
/// Weight functions for `ghost_slow_clap`.
pub struct SubstrateWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<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)
/// Proof: `GhostSlowClaps::ReceivedClaps` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ClapsInSession` (r:1 w:1)
/// Proof: `GhostSlowClaps::ClapsInSession` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:1)
/// Proof: `GhostSlowClaps::ApplausesForTransaction` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::NullifyNeeded` (r:1 w:0)
/// Proof: `GhostNetworks::NullifyNeeded` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::Networks` (r:1 w:0)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::GatekeeperAmount` (r:1 w:1)
/// Proof: `GhostNetworks::GatekeeperAmount` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::BridgedImbalance` (r:1 w:1)
/// Proof: `GhostNetworks::BridgedImbalance` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::AccumulatedCommission` (r:1 w:1)
/// Proof: `GhostNetworks::AccumulatedCommission` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `System::Account` (r:1 w:1)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
fn slow_clap() -> Weight {
// Proof Size summary in bytes:
// Measured: `355`
// Estimated: `3820`
// Minimum execution time: 213_817_000 picoseconds.
Weight::from_parts(216_977_000, 0)
.saturating_add(Weight::from_parts(0, 3820))
.saturating_add(T::DbWeight::get().reads(10))
.saturating_add(T::DbWeight::get().writes(7))
}
/// Storage: `GhostSlowClaps::ReceivedClaps` (r:1 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`)
/// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:1)
/// Proof: `GhostSlowClaps::ApplausesForTransaction` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::NullifyNeeded` (r:1 w:0)
/// Proof: `GhostNetworks::NullifyNeeded` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::Networks` (r:1 w:0)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::GatekeeperAmount` (r:1 w:1)
/// Proof: `GhostNetworks::GatekeeperAmount` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::BridgedImbalance` (r:1 w:1)
/// Proof: `GhostNetworks::BridgedImbalance` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::AccumulatedCommission` (r:1 w:1)
/// Proof: `GhostNetworks::AccumulatedCommission` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `System::Account` (r:1 w:1)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
fn self_applause() -> Weight {
// Proof Size summary in bytes:
// Measured: `655`
// Estimated: `4120`
// Minimum execution time: 210_676_000 picoseconds.
Weight::from_parts(212_905_000, 0)
.saturating_add(Weight::from_parts(0, 4120))
.saturating_add(T::DbWeight::get().reads(9))
.saturating_add(T::DbWeight::get().writes(5))
}
fn commit_block()-> Weight;
}
impl WeightInfo for () {
@ -145,32 +82,8 @@ impl WeightInfo for () {
.saturating_add(RocksDbWeight::get().reads(10))
.saturating_add(RocksDbWeight::get().writes(7))
}
/// Storage: `GhostSlowClaps::ReceivedClaps` (r:1 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`)
/// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:1)
/// Proof: `GhostSlowClaps::ApplausesForTransaction` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::NullifyNeeded` (r:1 w:0)
/// Proof: `GhostNetworks::NullifyNeeded` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::Networks` (r:1 w:0)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::GatekeeperAmount` (r:1 w:1)
/// Proof: `GhostNetworks::GatekeeperAmount` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::BridgedImbalance` (r:1 w:1)
/// Proof: `GhostNetworks::BridgedImbalance` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `GhostNetworks::AccumulatedCommission` (r:1 w:1)
/// Proof: `GhostNetworks::AccumulatedCommission` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `System::Account` (r:1 w:1)
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
fn self_applause() -> Weight {
// Proof Size summary in bytes:
// Measured: `655`
// Estimated: `4120`
// Minimum execution time: 210_676_000 picoseconds.
Weight::from_parts(212_905_000, 0)
.saturating_add(Weight::from_parts(0, 4120))
.saturating_add(RocksDbWeight::get().reads(9))
.saturating_add(RocksDbWeight::get().writes(5))
fn commit_block()-> Weight {
Default::default()
}
}

View File

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

View File

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

View File

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