rustfmt the ghost-slow-clap pallet

Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
This commit is contained in:
Uncle Stinky 2025-06-25 18:20:10 +03:00
parent f7ba592d50
commit 591cce1fb1
Signed by: st1nky
GPG Key ID: 016064BD97603B40
5 changed files with 588 additions and 374 deletions

View File

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

View File

@ -3,8 +3,8 @@
use super::*;
use frame_benchmarking::v1::*;
use frame_system::RawOrigin;
use frame_support::traits::fungible::Inspect;
use frame_system::RawOrigin;
pub fn create_account<T: Config>() -> T::AccountId {
let account_bytes = Vec::from([1u8; 32]);

View File

@ -3,53 +3,50 @@
use codec::{Decode, Encode, MaxEncodedLen};
use scale_info::TypeInfo;
use serde::{Deserializer, Deserialize};
use serde::{Deserialize, Deserializer};
pub use pallet::*;
use frame_support::{
pallet_prelude::*,
traits::{
tokens::fungible::{Inspect, Mutate},
EstimateNextSessionRotation, ValidatorSet, ValidatorSetWithIdentification,
OneSessionHandler, Get,
EstimateNextSessionRotation, Get, OneSessionHandler, ValidatorSet,
ValidatorSetWithIdentification,
},
WeakBoundedVec,
};
use frame_system::{
offchain::{SendTransactionTypes, SubmitTransaction},
pallet_prelude::*,
};
pub use pallet::*;
use sp_core::H256;
use sp_runtime::{
Perbill, RuntimeAppPublic, RuntimeDebug, SaturatedConversion,
offchain::{
self as rt_offchain, HttpError,
self as rt_offchain,
storage::{MutateStorageError, StorageRetrievalError, StorageValueRef},
storage_lock::{StorageLock, Time},
HttpError,
},
traits::{BlockNumberProvider, Convert, Saturating},
};
use sp_std::{
vec::Vec, prelude::*,
collections::btree_map::BTreeMap,
Perbill, RuntimeAppPublic, RuntimeDebug, SaturatedConversion,
};
use sp_staking::{
offence::{Kind, Offence, ReportOffence},
SessionIndex,
};
use sp_std::{collections::btree_map::BTreeMap, prelude::*, vec::Vec};
use ghost_networks::{
NetworkData, NetworkDataBasicHandler, NetworkDataInspectHandler,
NetworkDataMutateHandler, NetworkType,
NetworkData, NetworkDataBasicHandler, NetworkDataInspectHandler, NetworkDataMutateHandler,
NetworkType,
};
pub mod weights;
pub use crate::weights::WeightInfo;
mod tests;
mod mock;
mod benchmarking;
mod mock;
mod tests;
pub mod sr25519 {
mod app_sr25519 {
@ -113,45 +110,55 @@ struct Log {
impl Log {
fn is_sufficient(&self) -> bool {
self.transaction_hash.is_some() &&
self.block_number.is_some() &&
self.topics.len() == NUMBER_OF_TOPICS
self.transaction_hash.is_some()
&& self.block_number.is_some()
&& self.topics.len() == NUMBER_OF_TOPICS
}
}
pub fn de_string_to_bytes<'de, D>(de: D) -> Result<Option<Vec<u8>>, D::Error>
where D: Deserializer<'de> {
where
D: Deserializer<'de>,
{
let s: &str = Deserialize::deserialize(de)?;
Ok(Some(s.as_bytes().to_vec()))
}
pub fn de_string_to_u64<'de, D>(de: D) -> Result<Option<u64>, D::Error>
where D: Deserializer<'de> {
where
D: Deserializer<'de>,
{
let s: &str = Deserialize::deserialize(de)?;
let s = if s.starts_with("0x") { &s[2..] } else { &s };
Ok(u64::from_str_radix(s, 16).ok())
}
pub fn de_string_to_u64_pure<'de, D>(de: D) -> Result<u64, D::Error>
where D: Deserializer<'de> {
where
D: Deserializer<'de>,
{
let s: &str = Deserialize::deserialize(de)?;
let s = if s.starts_with("0x") { &s[2..] } else { &s };
Ok(u64::from_str_radix(s, 16).unwrap_or_default())
}
pub fn de_string_to_h256<'de, D>(de: D) -> Result<Option<H256>, D::Error>
where D: Deserializer<'de> {
where
D: Deserializer<'de>,
{
let s: &str = Deserialize::deserialize(de)?;
let start_index = if s.starts_with("0x") { 2 } else { 0 };
let h256: Vec<_> = (start_index..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i+2], 16).expect("valid u8 symbol; qed"))
.map(|i| u8::from_str_radix(&s[i..i + 2], 16).expect("valid u8 symbol; qed"))
.collect();
Ok(Some(H256::from_slice(&h256)))
}
pub fn de_string_to_vec_of_bytes<'de, D>(de: D) -> Result<Vec<Vec<u8>>, D::Error>
where D: Deserializer<'de> {
where
D: Deserializer<'de>,
{
let strings: Vec<&str> = Deserialize::deserialize(de)?;
Ok(strings
.iter()
@ -159,25 +166,31 @@ where D: Deserializer<'de> {
let start_index = if s.starts_with("0x") { 2 } else { 0 };
(start_index..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i+2], 16).expect("valid u8 symbol; qed"))
.map(|i| u8::from_str_radix(&s[i..i + 2], 16).expect("valid u8 symbol; qed"))
.collect::<Vec<u8>>()
})
.collect::<Vec<Vec<u8>>>())
}
pub fn de_string_to_btree_map<'de, D>(de: D) -> Result<BTreeMap<u128, u128>, D::Error>
where D: Deserializer<'de> {
where
D: Deserializer<'de>,
{
let s: &str = Deserialize::deserialize(de)?;
let start_index = if s.starts_with("0x") { 2 } else { 0 };
Ok(BTreeMap::from_iter((start_index..s.len())
.step_by(64)
.map(|i| (
u128::from_str_radix(&s[i..i+32], 16).expect("valid u8 symbol; qed"),
u128::from_str_radix(&s[i+32..i+64], 16).expect("valid u8 symbol; qed"),
))))
Ok(BTreeMap::from_iter((start_index..s.len()).step_by(64).map(
|i| {
(
u128::from_str_radix(&s[i..i + 32], 16).expect("valid u8 symbol; qed"),
u128::from_str_radix(&s[i + 32..i + 64], 16).expect("valid u8 symbol; qed"),
)
},
)))
}
#[derive(RuntimeDebug, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, MaxEncodedLen)]
#[derive(
RuntimeDebug, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, MaxEncodedLen,
)]
pub struct Clap<AccountId, NetworkId, Balance> {
pub session_index: SessionIndex,
pub authority_index: AuthIndex,
@ -243,12 +256,10 @@ impl<NetworkId: core::fmt::Debug> core::fmt::Debug for OffchainErr<NetworkId> {
}
}
pub type NetworkIdOf<T> =
<<T as Config>::NetworkDataHandler as NetworkDataBasicHandler>::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;
pub type BalanceOf<T> =
<<T as Config>::Currency as Inspect<<T as frame_system::Config>::AccountId>>::Balance;
pub type ValidatorId<T> = <<T as Config>::ValidatorSet as ValidatorSet<
<T as frame_system::Config>::AccountId,
@ -287,9 +298,9 @@ pub mod pallet {
type NextSessionRotation: EstimateNextSessionRotation<BlockNumberFor<Self>>;
type ValidatorSet: ValidatorSetWithIdentification<Self::AccountId>;
type Currency: Inspect<Self::AccountId> + Mutate<Self::AccountId>;
type NetworkDataHandler: NetworkDataBasicHandler +
NetworkDataInspectHandler<NetworkData> +
NetworkDataMutateHandler<NetworkData, BalanceOf<Self>>;
type NetworkDataHandler: NetworkDataBasicHandler
+ NetworkDataInspectHandler<NetworkData>
+ NetworkDataMutateHandler<NetworkData, BalanceOf<Self>>;
type BlockNumberProvider: BlockNumberProvider<BlockNumber = BlockNumberFor<Self>>;
type ReportUnresponsiveness: ReportOffence<
Self::AccountId,
@ -319,7 +330,9 @@ pub mod pallet {
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
AuthoritiesEquilibrium,
SomeAuthoritiesTrottling { throttling: Vec<IdentificationTuple<T>> },
SomeAuthoritiesTrottling {
throttling: Vec<IdentificationTuple<T>>,
},
Clapped {
authority_id: AuthIndex,
network_id: NetworkIdOf<T>,
@ -357,7 +370,7 @@ pub mod pallet {
NMapKey<Twox64Concat, H256>,
),
BoundedBTreeSet<AuthIndex, T::MaxAuthorities>,
ValueQuery
ValueQuery,
>;
#[pallet::storage]
@ -370,7 +383,7 @@ pub mod pallet {
NMapKey<Twox64Concat, H256>,
),
bool,
ValueQuery
ValueQuery,
>;
#[pallet::storage]
@ -449,16 +462,18 @@ pub mod pallet {
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,
)
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!(
target: LOG_TARGET,
"👏 Could not start slow clap at {:?}: {:?}",
@ -481,9 +496,8 @@ pub mod pallet {
None => return InvalidTransaction::BadSigner.into(),
};
let signature_valid = clap.using_encoded(|encoded_clap| {
authority.verify(&encoded_clap, signature)
});
let signature_valid =
clap.using_encoded(|encoded_clap| authority.verify(&encoded_clap, signature));
if !signature_valid {
return InvalidTransaction::BadProof.into();
@ -510,7 +524,10 @@ impl<T: Config> Pallet<T> {
key
}
fn read_persistent_offchain_storage<R: codec::Decode>(storage_key: &[u8], default_value: R) -> R {
fn read_persistent_offchain_storage<R: codec::Decode>(
storage_key: &[u8],
default_value: R,
) -> R {
StorageValueRef::persistent(&storage_key)
.get::<R>()
.ok()
@ -556,36 +573,52 @@ impl<T: Config> Pallet<T> {
fn try_slow_clap(clap: &Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>) -> DispatchResult {
let authorities = Authorities::<T>::get(&clap.session_index);
ensure!(authorities.get(clap.authority_index as usize).is_some(), Error::<T>::NotAnAuthority);
ensure!(
authorities.get(clap.authority_index as usize).is_some(),
Error::<T>::NotAnAuthority
);
let clap_unique_hash = Self::generate_unique_hash(&clap.receiver, &clap.amount, &clap.network_id);
let received_claps_key = (clap.session_index, &clap.transaction_hash, &clap_unique_hash);
let clap_unique_hash =
Self::generate_unique_hash(&clap.receiver, &clap.amount, &clap.network_id);
let received_claps_key = (
clap.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),
}
})?;
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),
}
})?;
ClapsInSession::<T>::try_mutate(&clap.session_index, |claps_details| {
if claps_details.get(&clap.authority_index).map(|x| x.disabled).unwrap_or_default() {
if claps_details
.get(&clap.authority_index)
.map(|x| x.disabled)
.unwrap_or_default()
{
return Err(Error::<T>::CurrentValidatorIsDisabled);
}
(*claps_details)
.entry(clap.authority_index)
.and_modify(|individual| (*individual).claps.saturating_inc())
.or_insert(SessionAuthorityInfo { claps: 1u32, disabled: false });
.or_insert(SessionAuthorityInfo {
claps: 1u32,
disabled: false,
});
Ok(())
})?;
@ -598,18 +631,18 @@ impl<T: Config> Pallet<T> {
amount: clap.amount,
});
let enough_authorities = Perbill::from_rational(
number_of_received_claps as u32,
authorities.len() as u32,
) > Perbill::from_percent(T::ApplauseThreshold::get());
let enough_authorities =
Perbill::from_rational(number_of_received_claps as u32, authorities.len() as u32)
> Perbill::from_percent(T::ApplauseThreshold::get());
if enough_authorities {
let _ = Self::try_applause(&clap, &received_claps_key)
.inspect_err(|error_msg| log::info!(
let _ = Self::try_applause(&clap, &received_claps_key).inspect_err(|error_msg| {
log::info!(
target: LOG_TARGET,
"👏 Could not applause because of: {:?}",
error_msg,
));
)
});
}
Ok(())
@ -621,7 +654,7 @@ impl<T: Config> Pallet<T> {
) -> DispatchResult {
ApplausesForTransaction::<T>::try_mutate(received_claps_key, |is_applaused| {
if *is_applaused || T::NetworkDataHandler::is_nullification_period() {
return Ok(())
return Ok(());
}
let commission = T::NetworkDataHandler::get(&clap.network_id)
@ -630,18 +663,16 @@ impl<T: Config> Pallet<T> {
.mul_ceil(clap.amount);
let final_amount = clap.amount.saturating_sub(commission);
let _ = T::NetworkDataHandler::increase_gatekeeper_amount(&clap.network_id, &clap.amount)
.map_err(|_| Error::<T>::CouldNotIncreaseGatekeeperAmount)?;
let _ =
T::NetworkDataHandler::increase_gatekeeper_amount(&clap.network_id, &clap.amount)
.map_err(|_| Error::<T>::CouldNotIncreaseGatekeeperAmount)?;
let _ = T::NetworkDataHandler::accumulate_incoming_imbalance(&final_amount)
.map_err(|_| Error::<T>::CouldNotAccumulateIncomingImbalance)?;
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
)?;
T::Currency::mint_into(&clap.receiver, final_amount)?;
}
*is_applaused = true;
@ -662,7 +693,7 @@ impl<T: Config> Pallet<T> {
transaction_hash: H256,
receiver: T::AccountId,
amount: BalanceOf<T>,
) -> DispatchResult{
) -> DispatchResult {
let clap_unique_hash = Self::generate_unique_hash(&receiver, &amount, &network_id);
let received_claps_key = (session_index, &transaction_hash, &clap_unique_hash);
@ -689,7 +720,7 @@ impl<T: Config> Pallet<T> {
}
fn start_slow_clapping(
block_number: BlockNumberFor<T>
block_number: BlockNumberFor<T>,
) -> OffchainResult<T, impl Iterator<Item = OffchainResult<T, ()>>> {
sp_io::offchain::is_validator()
.then(|| ())
@ -698,10 +729,13 @@ impl<T: Config> Pallet<T> {
let session_index = T::ValidatorSet::session_index();
let networks_len = T::NetworkDataHandler::iter().count();
let network_in_use = T::NetworkDataHandler::iter()
.nth(block_number.into()
.as_usize()
.checked_rem(networks_len)
.unwrap_or_default())
.nth(
block_number
.into()
.as_usize()
.checked_rem(networks_len)
.unwrap_or_default(),
)
.ok_or(OffchainErr::NoStoredNetworks)?;
let network_id_encoded = network_in_use.0.encode();
@ -714,40 +748,47 @@ 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);
let block_until =
rt_offchain::Duration::from_millis(networks_len as u64 * FETCH_TIMEOUT_PERIOD);
let mut network_lock = StorageLock::<Time>::with_deadline(&network_lock_key, block_until);
network_lock.try_lock().map_err(|_| {
OffchainErr::OffchainTimeoutPeriod(network_in_use.0)
})?;
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()),
}
})
.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(),
MutateStorageError::ConcurrentModification(_) => {
OffchainErr::ConcurrentModificationError(network_in_use.0).into()
}
})?;
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,
)
}))
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,
)
}),
)
}
fn do_evm_claps_or_save_block(
@ -773,56 +814,81 @@ impl<T: Config> Pallet<T> {
);
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),
};
.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 response_bytes = Self::fetch_from_remote(&rpc_endpoint, &request_body)?;
let response_bytes =
Self::fetch_from_remote(&rpc_endpoint, &request_body)?;
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
)?;
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();
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(_) => match estimated_block.checked_sub(from_block) {
Some(current_distance) if current_distance < max_block_distance =>
(from_block, estimated_block),
_ => (from_block, from_block
.saturating_add(max_block_distance)
.min(estimated_block)),
Ok(match maybe_block_range {
Some((from_block, to_block)) => match maybe_new_evm_block {
Some(_) => {
match estimated_block.checked_sub(from_block) {
Some(current_distance)
if current_distance
< max_block_distance =>
{
(from_block, estimated_block)
}
_ => (
from_block,
from_block
.saturating_add(max_block_distance)
.min(estimated_block),
),
}
}
None => (to_block, to_block),
},
None => (to_block, to_block),
},
None => (estimated_block, estimated_block),
})
},
NetworkType::Utxo => Err(OffchainErr::UtxoNotImplemented(network_id).into()),
_ => Err(OffchainErr::UnknownNetworkType(network_id).into()),
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()),
}
Err(_) => Err(OffchainErr::StorageRetrievalError(network_id).into())
}
})
},
)
.map_err(|error| match error {
MutateStorageError::ValueFunctionFailed(offchain_error) => offchain_error,
MutateStorageError::ConcurrentModification(_) =>
OffchainErr::ConcurrentModificationError(network_id).into(),
MutateStorageError::ConcurrentModification(_) => {
OffchainErr::ConcurrentModificationError(network_id).into()
}
})
.map(|_| ())
}
@ -832,7 +898,7 @@ impl<T: Config> Pallet<T> {
authority_index: AuthIndex,
authority_key: T::AuthorityId,
session_index: SessionIndex,
network_id: NetworkIdOf<T>
network_id: NetworkIdOf<T>,
) -> OffchainResult<T, Option<u64>> {
match Self::parse_evm_response(&response_bytes)? {
EvmResponseType::BlockNumber(new_evm_block) => {
@ -843,29 +909,31 @@ impl<T: Config> Pallet<T> {
network_id,
);
Ok(Some(new_evm_block))
},
}
EvmResponseType::TransactionLogs(evm_logs) => {
let claps: Vec<_> = evm_logs
.iter()
.filter_map(|log| log.is_sufficient().then(|| {
Clap {
.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
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"),
}
}))
block_number: log.block_number.expect("block number exists; qed"),
})
})
.collect();
log::info!(
@ -876,7 +944,8 @@ impl<T: Config> Pallet<T> {
);
for clap in claps {
let signature = authority_key.sign(&clap.encode())
let signature = authority_key
.sign(&clap.encode())
.ok_or(OffchainErr::FailedSigning)?;
let call = Call::slow_clap { clap, signature };
@ -889,27 +958,32 @@ impl<T: Config> Pallet<T> {
}
}
fn local_authorities(session_index: &SessionIndex) -> impl Iterator<Item = (u32, T::AuthorityId)> {
fn local_authorities(
session_index: &SessionIndex,
) -> impl Iterator<Item = (u32, T::AuthorityId)> {
let authorities = Authorities::<T>::get(session_index);
let mut local_authorities = T::AuthorityId::all();
local_authorities.sort();
authorities.into_iter().enumerate().filter_map(move |(index, authority)| {
local_authorities
.binary_search(&authority)
.ok()
.map(|location| (index as u32, local_authorities[location].clone()))
})
authorities
.into_iter()
.enumerate()
.filter_map(move |(index, authority)| {
local_authorities
.binary_search(&authority)
.ok()
.map(|location| (index as u32, local_authorities[location].clone()))
})
}
fn fetch_from_remote(
rpc_endpoint: &[u8],
request_body: &[u8],
) -> OffchainResult<T, Vec<u8>> {
let rpc_endpoint_str = core::str::from_utf8(rpc_endpoint).expect("rpc endpoint valid str; qed");
let request_body_str = core::str::from_utf8(request_body).expect("request body valid str: qed");
fn fetch_from_remote(rpc_endpoint: &[u8], request_body: &[u8]) -> OffchainResult<T, Vec<u8>> {
let rpc_endpoint_str =
core::str::from_utf8(rpc_endpoint).expect("rpc endpoint valid str; qed");
let request_body_str =
core::str::from_utf8(request_body).expect("request body valid str: qed");
let deadline = sp_io::offchain::timestamp().add(rt_offchain::Duration::from_millis(FETCH_TIMEOUT_PERIOD));
let deadline = sp_io::offchain::timestamp()
.add(rt_offchain::Duration::from_millis(FETCH_TIMEOUT_PERIOD));
let pending = rt_offchain::http::Request::post(&rpc_endpoint_str, vec![request_body_str])
.add_header("Accept", "application/json")
@ -924,7 +998,7 @@ impl<T: Config> Pallet<T> {
.map_err(|_| OffchainErr::RequestUncompleted)?;
if response.code != 200 {
return Err(OffchainErr::HttpResponseNotOk(response.code))
return Err(OffchainErr::HttpResponseNotOk(response.code));
}
Ok(response.body().collect::<Vec<u8>>())
@ -932,15 +1006,23 @@ impl<T: Config> Pallet<T> {
fn prepare_request_body_for_latest_block(network_data: &NetworkData) -> Vec<u8> {
match network_data.network_type {
NetworkType::Evm => b"{\"id\":0,\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\"}".to_vec(),
NetworkType::Evm => {
b"{\"id\":0,\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\"}".to_vec()
}
_ => Default::default(),
}
}
fn prepare_request_body_for_latest_transfers(from_block: u64, to_block: u64, network_data: &NetworkData) -> Vec<u8> {
fn prepare_request_body_for_latest_transfers(
from_block: u64,
to_block: u64,
network_data: &NetworkData,
) -> Vec<u8> {
match network_data.network_type {
NetworkType::Evm => {
let mut body = b"{\"id\":0,\"jsonrpc\":\"2.0\",\"method\":\"eth_getLogs\",\"params\":[{".to_vec();
let mut body =
b"{\"id\":0,\"jsonrpc\":\"2.0\",\"method\":\"eth_getLogs\",\"params\":[{"
.to_vec();
body.extend(b"\"fromBlock\":\"".to_vec());
body.extend(Self::u64_to_hexadecimal_bytes(from_block));
body.extend(b"\",\"toBlock\":\"".to_vec());
@ -951,7 +1033,7 @@ impl<T: Config> Pallet<T> {
body.extend(network_data.topic_name.to_vec());
body.extend(b"\"]}]}".to_vec());
body
},
}
_ => Default::default(),
}
}
@ -960,14 +1042,16 @@ impl<T: Config> Pallet<T> {
let response_str = sp_std::str::from_utf8(&response_bytes)
.map_err(|_| OffchainErr::HttpBytesParsingError)?;
let response_result: EvmResponse = serde_json::from_str(&response_str)
.map_err(|_| OffchainErr::HttpJsonParsingError)?;
let response_result: EvmResponse =
serde_json::from_str(&response_str).map_err(|_| OffchainErr::HttpJsonParsingError)?;
if response_result.error.is_some() {
return Err(OffchainErr::ErrorInEvmResponse);
}
Ok(response_result.result.ok_or(OffchainErr::ErrorInEvmResponse)?)
Ok(response_result
.result
.ok_or(OffchainErr::ErrorInEvmResponse)?)
}
fn calculate_median_claps(session_index: &SessionIndex) -> u32 {
@ -1016,7 +1100,10 @@ impl<T: Config> Pallet<T> {
fn initialize_authorities(authorities: Vec<T::AuthorityId>) {
let session_index = T::ValidatorSet::session_index();
assert!(Authorities::<T>::get(&session_index).is_empty(), "Authorities are already initilized!");
assert!(
Authorities::<T>::get(&session_index).is_empty(),
"Authorities are already initilized!"
);
let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities)
.expect("more than the maximum number of authorities");
@ -1032,7 +1119,8 @@ impl<T: Config> Pallet<T> {
ClapsInSession::<T>::remove(target_session_index);
let mut cursor = ReceivedClaps::<T>::clear_prefix((target_session_index,), u32::MAX, None);
debug_assert!(cursor.maybe_cursor.is_none());
cursor = ApplausesForTransaction::<T>::clear_prefix((target_session_index,), u32::MAX, None);
cursor =
ApplausesForTransaction::<T>::clear_prefix((target_session_index,), u32::MAX, None);
debug_assert!(cursor.maybe_cursor.is_none());
}
@ -1100,10 +1188,16 @@ impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
if offenders.is_empty() {
Self::deposit_event(Event::<T>::AuthoritiesEquilibrium);
} else {
Self::deposit_event(Event::<T>::SomeAuthoritiesTrottling { throttling: offenders.clone() });
Self::deposit_event(Event::<T>::SomeAuthoritiesTrottling {
throttling: offenders.clone(),
});
let validator_set_count = authorities.len() as u32;
let offence = ThrottlingOffence { session_index, validator_set_count, offenders };
let offence = ThrottlingOffence {
session_index,
validator_set_count,
offenders,
};
if let Err(e) = T::ReportUnresponsiveness::report_offence(vec![], offence) {
sp_runtime::print(e)
}
@ -1116,7 +1210,10 @@ impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
(*claps_details)
.entry(validator_index as AuthIndex)
.and_modify(|individual| (*individual).disabled = true)
.or_insert(SessionAuthorityInfo { claps: 0u32, disabled: true });
.or_insert(SessionAuthorityInfo {
claps: 0u32,
disabled: true,
});
});
}
}
@ -1126,7 +1223,7 @@ impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
pub struct ThrottlingOffence<Offender> {
pub session_index: SessionIndex,
pub validator_set_count: u32,
pub offenders: Vec<Offender>
pub offenders: Vec<Offender>,
}
impl<Offender: Clone> Offence<Offender> for ThrottlingOffence<Offender> {

View File

@ -2,13 +2,15 @@
use frame_support::{
derive_impl, parameter_types,
traits::{ConstU32, ConstU64}, weights::Weight,
traits::{ConstU32, ConstU64},
weights::Weight,
};
use frame_system::EnsureRoot;
use pallet_session::historical as pallet_session_historical;
use sp_runtime::{
curve::PiecewiseLinear,
testing::{TestXt, UintAuthorityId},
traits::ConvertInto, curve::PiecewiseLinear,
traits::ConvertInto,
Permill,
};
use sp_staking::{
@ -53,13 +55,10 @@ impl pallet_session::SessionManager<u64> for TestSessionManager {
impl pallet_session::historical::SessionManager<u64, u64> for TestSessionManager {
fn new_session(_new_index: SessionIndex) -> Option<Vec<(u64, u64)>> {
Validators::mutate(|l| l
.take()
.map(|validators| validators
.iter()
.map(|v| (*v, *v))
.collect())
)
Validators::mutate(|l| {
l.take()
.map(|validators| validators.iter().map(|v| (*v, *v)).collect())
})
}
fn end_session(_: SessionIndex) {}
fn start_session(_: SessionIndex) {}
@ -94,11 +93,10 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
result.execute_with(|| {
for i in 1..=3 {
System::inc_providers(&i);
assert_eq!(Session::set_keys(
RuntimeOrigin::signed(i),
i.into(),
vec![],
), Ok(()));
assert_eq!(
Session::set_keys(RuntimeOrigin::signed(i), i.into(), vec![],),
Ok(())
);
}
});
@ -257,8 +255,7 @@ pub fn advance_session_with_authority(authority: u64) {
UintAuthorityId::from(69),
UintAuthorityId::from(420),
UintAuthorityId::from(1337),
]
],
);
assert_eq!(session_index, (now / Period::get()) as u32);
}

View File

@ -7,9 +7,9 @@ use frame_support::{assert_err, assert_ok, dispatch};
use sp_core::offchain::{
testing,
testing::{TestOffchainExt, TestTransactionPoolExt},
OffchainWorkerExt, OffchainDbExt, TransactionPoolExt,
OffchainDbExt, OffchainWorkerExt, TransactionPoolExt,
};
use sp_runtime::{DispatchError, testing::UintAuthorityId};
use sp_runtime::{testing::UintAuthorityId, DispatchError};
use ghost_networks::BridgedInflationCurve;
use pallet_staking::EraPayout;
@ -36,7 +36,8 @@ fn prepare_evm_network(
assert_ok!(Networks::register_network(
RuntimeOrigin::root(),
maybe_network_id.unwrap_or(1u32),
network_data.clone()));
network_data.clone()
));
network_data
}
@ -108,8 +109,14 @@ fn test_throttling_slash_function() {
assert_eq!(dummy_offence.slash_fraction(1), Perbill::zero());
assert_eq!(dummy_offence.slash_fraction(5), Perbill::zero());
assert_eq!(dummy_offence.slash_fraction(7), Perbill::from_parts(4200000));
assert_eq!(dummy_offence.slash_fraction(17), Perbill::from_parts(46200000));
assert_eq!(
dummy_offence.slash_fraction(7),
Perbill::from_parts(4200000)
);
assert_eq!(
dummy_offence.slash_fraction(17),
Perbill::from_parts(46200000)
);
}
#[test]
@ -121,8 +128,10 @@ fn request_body_is_correct_for_get_block_number() {
t.execute_with(|| {
let network_data = prepare_evm_network(Some(1), None);
let request_body = SlowClap::prepare_request_body_for_latest_block(&network_data);
assert_eq!(core::str::from_utf8(&request_body).unwrap(),
r#"{"id":0,"jsonrpc":"2.0","method":"eth_blockNumber"}"#);
assert_eq!(
core::str::from_utf8(&request_body).unwrap(),
r#"{"id":0,"jsonrpc":"2.0","method":"eth_blockNumber"}"#
);
});
}
@ -177,7 +186,10 @@ fn should_make_http_call_for_logs() {
let network_data = prepare_evm_network(Some(1), None);
let request_body = SlowClap::prepare_request_body_for_latest_transfers(
from_block, to_block, &network_data);
from_block,
to_block,
&network_data,
);
let raw_response = SlowClap::fetch_from_remote(&rpc_endpoint, &request_body)?;
assert_eq!(raw_response.len(), 1805); // precalculated
Ok(())
@ -198,7 +210,8 @@ 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 maybe_evm_block_number =
SlowClap::apply_evm_response(&raw_response, 69, Default::default(), 420, 1)?;
assert_eq!(maybe_evm_block_number, Some(20335745));
Ok(())
@ -227,7 +240,10 @@ fn should_make_http_call_and_parse_logs() {
let network_data = prepare_evm_network(Some(network_id), None);
let request_body = SlowClap::prepare_request_body_for_latest_transfers(
from_block, to_block, &network_data);
from_block,
to_block,
&network_data,
);
let raw_response = SlowClap::fetch_from_remote(&rpc_endpoint, &request_body)?;
match SlowClap::parse_evm_response(&raw_response)? {
@ -259,21 +275,30 @@ fn should_clear_sesions_based_on_history_depth() {
let storage_key = (session_index, transaction_hash, unique_transaction_hash);
assert_claps_info_correct(&storage_key, &session_index, 0);
assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), false);
assert_eq!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
false
);
assert_ok!(do_clap_from(session_index, network_id, 0, false));
assert_ok!(do_clap_from(session_index, network_id, 1, false));
assert_ok!(do_clap_from(session_index, network_id, 2, false));
assert_claps_info_correct(&storage_key, &session_index, 3);
assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), true);
assert_eq!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
true
);
for _ in 0..history_depth {
advance_session();
}
assert_claps_info_correct(&storage_key, &session_index, 0);
assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), false);
assert_eq!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
false
);
});
}
@ -312,7 +337,10 @@ fn should_increase_gatkeeper_amount_accordingly() {
assert_ok!(do_clap_from(session_index, network_id, 2, false));
assert_eq!(Networks::gatekeeper_amount(network_id), amount);
assert_eq!(Networks::bridged_imbalance().bridged_in, amount.saturating_div(2));
assert_eq!(
Networks::bridged_imbalance().bridged_in,
amount.saturating_div(2)
);
assert_eq!(Networks::bridged_imbalance().bridged_out, 0);
});
}
@ -346,18 +374,29 @@ fn should_applause_and_take_next_claps() {
let session_index = advance_session_and_get_index();
let storage_key = (session_index, transaction_hash, unique_transaction_hash);
assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), false);
assert_eq!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
false
);
assert_eq!(Balances::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!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
false
);
assert_eq!(Balances::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!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
true
);
assert_eq!(Balances::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!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
true
);
assert_eq!(Balances::balance(&receiver), amount);
});
}
@ -373,8 +412,10 @@ fn should_throw_error_on_clap_duplication() {
assert_claps_info_correct(&storage_key, &session_index, 0);
assert_ok!(do_clap_from(session_index, network_id, 0, false));
assert_claps_info_correct(&storage_key, &session_index, 1);
assert_err!(do_clap_from(session_index, network_id, 0, false),
Error::<Runtime>::AlreadyClapped);
assert_err!(
do_clap_from(session_index, network_id, 0, false),
Error::<Runtime>::AlreadyClapped
);
assert_claps_info_correct(&storage_key, &session_index, 1);
});
}
@ -389,8 +430,10 @@ fn should_throw_error_on_removal_of_unregistered_clap() {
let storage_key = (session_index, transaction_hash, unique_transaction_hash);
assert_claps_info_correct(&storage_key, &session_index, 0);
assert_err!(do_clap_from(session_index, network_id, 0, true),
Error::<Runtime>::UnregisteredClapRemove);
assert_err!(
do_clap_from(session_index, network_id, 0, true),
Error::<Runtime>::UnregisteredClapRemove
);
assert_claps_info_correct(&storage_key, &session_index, 0);
});
}
@ -420,9 +463,21 @@ fn should_throw_error_if_session_index_is_not_current() {
let session_index_prev = chunk[0].1;
let session_index_next = chunk[2].1;
let storage_key_curr = (session_index_curr, transaction_hash, unique_transaction_hash);
let storage_key_prev = (session_index_prev, transaction_hash, unique_transaction_hash);
let storage_key_next = (session_index_next, transaction_hash, unique_transaction_hash);
let storage_key_curr = (
session_index_curr,
transaction_hash,
unique_transaction_hash,
);
let storage_key_prev = (
session_index_prev,
transaction_hash,
unique_transaction_hash,
);
let storage_key_next = (
session_index_next,
transaction_hash,
unique_transaction_hash,
);
assert_claps_info_correct(&storage_key_curr, &session_index_curr, 0);
assert_claps_info_correct(&storage_key_prev, &session_index_prev, 0);
@ -449,14 +504,25 @@ fn should_throw_error_if_session_index_is_not_current() {
assert_claps_info_correct(&storage_key_prev, &session_index_prev, 0);
assert_claps_info_correct(&storage_key_next, &session_index_next, 0);
assert_ok!(do_clap_from_first_authority(session_index_curr, network_id, authority_curr));
assert_ok!(do_clap_from_first_authority(session_index_prev, network_id, authority_prev));
assert_ok!(do_clap_from_first_authority(session_index_next, network_id, authority_next));
assert_ok!(do_clap_from_first_authority(
session_index_curr,
network_id,
authority_curr
));
assert_ok!(do_clap_from_first_authority(
session_index_prev,
network_id,
authority_prev
));
assert_ok!(do_clap_from_first_authority(
session_index_next,
network_id,
authority_next
));
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_next, &session_index_next, 1);
}
});
}
@ -483,8 +549,10 @@ fn should_throw_error_if_signer_has_incorrect_index() {
};
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_err!(
SlowClap::slow_clap(RuntimeOrigin::none(), clap, signature),
Error::<Runtime>::NotAnAuthority
);
assert_claps_info_correct(&storage_key, &session_index, 0);
});
}
@ -500,27 +568,41 @@ fn should_throw_error_if_validator_disabled_and_ignore_later() {
assert_claps_info_correct(&storage_key, &session_index, 0);
assert_eq!(Session::disable_index(0), true);
assert_err!(do_clap_from(session_index, network_id, 0, false),
Error::<Runtime>::CurrentValidatorIsDisabled);
assert_err!(
do_clap_from(session_index, network_id, 0, false),
Error::<Runtime>::CurrentValidatorIsDisabled
);
assert_eq!(pallet::ReceivedClaps::<Runtime>::get(&storage_key).len(), 0);
assert_eq!(pallet::ClapsInSession::<Runtime>::get(&session_index).len(), 1);
assert_eq!(pallet::ClapsInSession::<Runtime>::get(&session_index)
.into_iter()
.filter(|(_, v)| !v.disabled)
.collect::<Vec<_>>()
.len(), 0);
assert_eq!(
pallet::ClapsInSession::<Runtime>::get(&session_index).len(),
1
);
assert_eq!(
pallet::ClapsInSession::<Runtime>::get(&session_index)
.into_iter()
.filter(|(_, v)| !v.disabled)
.collect::<Vec<_>>()
.len(),
0
);
assert_ok!(do_clap_from(session_index, network_id, 1, false));
assert_eq!(Session::disable_index(1), true);
assert_eq!(pallet::ReceivedClaps::<Runtime>::get(&storage_key).len(), 1);
assert_eq!(pallet::ClapsInSession::<Runtime>::get(&session_index).len(), 2);
assert_eq!(pallet::ClapsInSession::<Runtime>::get(&session_index)
.into_iter()
.filter(|(_, v)| !v.disabled)
.collect::<Vec<_>>()
.len(), 0);
assert_eq!(
pallet::ClapsInSession::<Runtime>::get(&session_index).len(),
2
);
assert_eq!(
pallet::ClapsInSession::<Runtime>::get(&session_index)
.into_iter()
.filter(|(_, v)| !v.disabled)
.collect::<Vec<_>>()
.len(),
0
);
});
}
@ -553,7 +635,10 @@ fn should_clap_without_applause_on_gatekeeper_amount_overflow() {
}
assert_claps_info_correct(&storage_key_first, &session_index, 3);
assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key_first), true);
assert_eq!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key_first),
true
);
assert_eq!(Balances::balance(&first_receiver), big_amount);
assert_eq!(Balances::balance(&second_receiver), 0);
@ -614,7 +699,10 @@ fn should_clap_without_applause_on_commission_overflow() {
}
assert_claps_info_correct(&storage_key_first, &session_index, 3);
assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key_first), true);
assert_eq!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key_first),
true
);
assert_eq!(Balances::balance(&first_receiver), big_amount);
assert_eq!(Balances::balance(&second_receiver), 0);
@ -662,10 +750,14 @@ fn should_nullify_commission_on_finalize() {
assert_eq!(Networks::accumulated_commission(), amount);
assert_eq!(Networks::is_nullification_period(), false);
assert_eq!(BridgedInflationCurve::<RewardCurve, Runtime>::era_payout(
assert_eq!(
BridgedInflationCurve::<RewardCurve, Runtime>::era_payout(
total_staked,
total_issuance,
0), (420000000000000, 0)); // precomputed values
0
),
(420000000000000, 0)
); // precomputed values
assert_eq!(Networks::is_nullification_period(), true);
Networks::on_finalize(System::block_number());
@ -689,10 +781,14 @@ fn should_avoid_applause_during_nullification_period() {
let session_index = advance_session_and_get_index();
assert_eq!(Networks::is_nullification_period(), false);
assert_eq!(BridgedInflationCurve::<RewardCurve, Runtime>::era_payout(
assert_eq!(
BridgedInflationCurve::<RewardCurve, Runtime>::era_payout(
total_staked,
total_issuance,
0), (0, 0));
0
),
(0, 0)
);
assert_eq!(Networks::is_nullification_period(), true);
assert_ok!(do_clap_from(session_index, network_id, 0, false));
@ -718,49 +814,66 @@ fn should_self_applause_if_enough_received_claps() {
let session_index = advance_session_and_get_index();
let storage_key = (session_index, transaction_hash, unique_transaction_hash);
assert_err!(SlowClap::self_applause(
assert_err!(
SlowClap::self_applause(
RuntimeOrigin::signed(receiver),
network_id,
session_index,
transaction_hash,
receiver,
amount,
), Error::<Runtime>::NotEnoughClaps);
),
Error::<Runtime>::NotEnoughClaps
);
assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), false);
assert_eq!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
false
);
assert_eq!(Balances::balance(&receiver), 0);
assert_eq!(BridgedInflationCurve::<RewardCurve, Runtime>::era_payout(
0, 0, 0), (0, 0));
assert_eq!(
BridgedInflationCurve::<RewardCurve, Runtime>::era_payout(0, 0, 0),
(0, 0)
);
assert_ok!(do_clap_from(session_index, network_id, 0, false));
assert_ok!(do_clap_from(session_index, network_id, 1, false));
assert_ok!(do_clap_from(session_index, network_id, 2, false));
assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), 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,
RuntimeOrigin::signed(receiver),
network_id,
session_index,
transaction_hash,
receiver,
amount,
));
assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), false);
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,
RuntimeOrigin::signed(receiver),
network_id,
session_index,
transaction_hash,
receiver,
amount,
));
assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), true);
assert_eq!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
true
);
assert_eq!(Balances::balance(&receiver), amount);
});
}
@ -779,60 +892,67 @@ fn should_emit_event_on_each_clap_and_on_applause() {
let session_index = advance_session_and_get_index();
let storage_key = (session_index, transaction_hash, unique_transaction_hash);
assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), false);
assert_eq!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
false
);
assert_claps_info_correct(&storage_key, &session_index, 0);
assert_ok!(do_clap_from(session_index, network_id, 0, false));
System::assert_last_event(RuntimeEvent::SlowClap(
crate::Event::Clapped {
receiver: receiver.clone(),
authority_id: 0,
network_id,
transaction_hash,
amount,
}));
System::assert_last_event(RuntimeEvent::SlowClap(crate::Event::Clapped {
receiver: receiver.clone(),
authority_id: 0,
network_id,
transaction_hash,
amount,
}));
assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), false);
assert_eq!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
false
);
assert_claps_info_correct(&storage_key, &session_index, 1);
assert_ok!(do_clap_from(session_index, network_id, 1, false));
let binding = System::events();
let last_two_events = binding
.iter()
.rev()
.take(5)
.collect::<Vec<_>>();
assert_eq!(last_two_events[0].event, RuntimeEvent::SlowClap(
crate::Event::Applaused {
network_id,
receiver: receiver.clone(),
received_amount: amount_after_commission,
}));
assert_eq!(last_two_events[4].event, RuntimeEvent::SlowClap(
crate::Event::Clapped {
receiver: receiver.clone(),
authority_id: 1,
network_id,
transaction_hash,
amount,
}));
let last_two_events = binding.iter().rev().take(5).collect::<Vec<_>>();
assert_eq!(
last_two_events[0].event,
RuntimeEvent::SlowClap(crate::Event::Applaused {
network_id,
receiver: receiver.clone(),
received_amount: amount_after_commission,
})
);
assert_eq!(
last_two_events[4].event,
RuntimeEvent::SlowClap(crate::Event::Clapped {
receiver: receiver.clone(),
authority_id: 1,
network_id,
transaction_hash,
amount,
})
);
assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), true);
assert_eq!(
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
true
);
assert_claps_info_correct(&storage_key, &session_index, 2);
assert_ok!(do_clap_from(session_index, network_id, 2, false));
System::assert_last_event(RuntimeEvent::SlowClap(
crate::Event::Clapped {
receiver: receiver.clone(),
authority_id: 2,
network_id,
transaction_hash,
amount,
}));
System::assert_last_event(RuntimeEvent::SlowClap(crate::Event::Clapped {
receiver: receiver.clone(),
authority_id: 2,
network_id,
transaction_hash,
amount,
}));
});
}
#[test]
fn should_not_fail_on_sub_existential_balance() {
let (network_id, transaction_hash, unique_transaction_hash)
= generate_unique_hash(None, None, None, None);
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(|| {
@ -845,7 +965,10 @@ fn should_not_fail_on_sub_existential_balance() {
assert_eq!(Networks::bridged_imbalance().bridged_in, 0);
assert_eq!(Networks::bridged_imbalance().bridged_out, 0);
assert_eq!(Balances::balance(&receiver), 0);
assert_eq!(SlowClap::applauses_for_transaction(&received_claps_key), false);
assert_eq!(
SlowClap::applauses_for_transaction(&received_claps_key),
false
);
assert_ok!(do_clap_from(session_index, network_id, 0, false));
assert_ok!(do_clap_from(session_index, network_id, 1, false));
@ -856,7 +979,10 @@ fn should_not_fail_on_sub_existential_balance() {
assert_eq!(Networks::bridged_imbalance().bridged_in, 0);
assert_eq!(Networks::bridged_imbalance().bridged_out, 0);
assert_eq!(Balances::balance(&receiver), 0);
assert_eq!(SlowClap::applauses_for_transaction(&received_claps_key), true);
assert_eq!(
SlowClap::applauses_for_transaction(&received_claps_key),
true
);
});
}
@ -881,40 +1007,34 @@ fn generate_unique_hash(
let receiver = maybe_receiver.unwrap_or(receiver);
let amount = maybe_amount.unwrap_or(amount);
let unique_transaction_hash = SlowClap::generate_unique_hash(
&receiver,
&amount,
&network_id,
);
let unique_transaction_hash = SlowClap::generate_unique_hash(&receiver, &amount, &network_id);
(network_id, transaction_hash, unique_transaction_hash)
}
fn assert_claps_info_correct(
storage_key: &(u32, H256, H256),
session_index: &u32,
index: usize,
) {
assert_eq!(pallet::ReceivedClaps::<Runtime>::get(storage_key).len(), index);
assert_eq!(pallet::ClapsInSession::<Runtime>::get(session_index).len(), index);
fn assert_claps_info_correct(storage_key: &(u32, H256, H256), session_index: &u32, index: usize) {
assert_eq!(
pallet::ReceivedClaps::<Runtime>::get(storage_key).len(),
index
);
assert_eq!(
pallet::ClapsInSession::<Runtime>::get(session_index).len(),
index
);
}
fn assert_transaction_has_bad_signature(
session_index: u32,
network_id: u32,
authority: u64,
) {
assert_err!(do_clap_from_first_authority(session_index, network_id, authority),
DispatchError::Other("Transaction has a bad signature"));
fn assert_transaction_has_bad_signature(session_index: u32, network_id: u32, authority: u64) {
assert_err!(
do_clap_from_first_authority(session_index, network_id, authority),
DispatchError::Other("Transaction has a bad signature")
);
}
fn assert_invalid_signing_address(
session_index: u32,
network_id: u32,
authority_index: u32,
) {
assert_err!(do_clap_from(session_index, network_id, authority_index, false),
DispatchError::Other("Invalid signing address"));
fn assert_invalid_signing_address(session_index: u32, network_id: u32, authority_index: u32) {
assert_err!(
do_clap_from(session_index, network_id, authority_index, false),
DispatchError::Other("Invalid signing address")
);
}
fn get_rpc_endpoint() -> Vec<u8> {