Compare commits

..

No commits in common. "d57589584151ad1327a655fc97768ed190afd18f" and "d8e934a98eaec789d5669e6700ce55aeb5974574" have entirely different histories.

28 changed files with 1870 additions and 2693 deletions

22
Cargo.lock generated
View File

@ -1186,7 +1186,7 @@ dependencies = [
[[package]] [[package]]
name = "casper-runtime" name = "casper-runtime"
version = "3.5.25" version = "3.5.24"
dependencies = [ dependencies = [
"casper-runtime-constants", "casper-runtime-constants",
"frame-benchmarking", "frame-benchmarking",
@ -3504,7 +3504,7 @@ dependencies = [
[[package]] [[package]]
name = "ghost-claims" name = "ghost-claims"
version = "0.2.4" version = "0.2.3"
dependencies = [ dependencies = [
"frame-benchmarking", "frame-benchmarking",
"frame-support", "frame-support",
@ -3528,7 +3528,7 @@ dependencies = [
[[package]] [[package]]
name = "ghost-cli" name = "ghost-cli"
version = "0.7.201" version = "0.7.198"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"clap 4.5.4", "clap 4.5.4",
@ -3584,7 +3584,7 @@ dependencies = [
[[package]] [[package]]
name = "ghost-machine-primitives" name = "ghost-machine-primitives"
version = "0.7.201" version = "0.7.198"
dependencies = [ dependencies = [
"lazy_static", "lazy_static",
"sc-sysinfo", "sc-sysinfo",
@ -3593,7 +3593,7 @@ dependencies = [
[[package]] [[package]]
name = "ghost-metrics" name = "ghost-metrics"
version = "0.7.201" version = "0.7.198"
dependencies = [ dependencies = [
"assert_cmd", "assert_cmd",
"bs58 0.5.1", "bs58 0.5.1",
@ -3648,7 +3648,7 @@ dependencies = [
[[package]] [[package]]
name = "ghost-networks" name = "ghost-networks"
version = "0.1.11" version = "0.1.7"
dependencies = [ dependencies = [
"frame-benchmarking", "frame-benchmarking",
"frame-support", "frame-support",
@ -3667,7 +3667,7 @@ dependencies = [
[[package]] [[package]]
name = "ghost-node" name = "ghost-node"
version = "0.7.201" version = "0.7.198"
dependencies = [ dependencies = [
"assert_cmd", "assert_cmd",
"color-eyre", "color-eyre",
@ -3698,7 +3698,7 @@ dependencies = [
[[package]] [[package]]
name = "ghost-rpc" name = "ghost-rpc"
version = "0.7.201" version = "0.7.198"
dependencies = [ dependencies = [
"ghost-core-primitives", "ghost-core-primitives",
"jsonrpsee", "jsonrpsee",
@ -3750,7 +3750,7 @@ dependencies = [
[[package]] [[package]]
name = "ghost-service" name = "ghost-service"
version = "0.7.201" version = "0.7.198"
dependencies = [ dependencies = [
"assert_matches", "assert_matches",
"async-trait", "async-trait",
@ -3834,7 +3834,7 @@ dependencies = [
[[package]] [[package]]
name = "ghost-slow-clap" name = "ghost-slow-clap"
version = "0.3.33" version = "0.3.28"
dependencies = [ dependencies = [
"frame-benchmarking", "frame-benchmarking",
"frame-support", "frame-support",
@ -3870,7 +3870,7 @@ dependencies = [
[[package]] [[package]]
name = "ghost-traits" name = "ghost-traits"
version = "0.3.23" version = "0.3.22"
dependencies = [ dependencies = [
"frame-support", "frame-support",
"sp-runtime 31.0.1", "sp-runtime 31.0.1",

View File

@ -17,7 +17,7 @@ homepage.workspace = true
[workspace.package] [workspace.package]
license = "GPL-3.0-only" license = "GPL-3.0-only"
authors = ["571nky", "57r37ch", "f4750"] authors = ["571nky", "57r37ch", "f4750"]
version = "0.7.201" version = "0.7.198"
edition = "2021" edition = "2021"
homepage = "https://ghostchain.io" homepage = "https://ghostchain.io"
repository = "https://git.ghostchain.io/ghostchain/ghost-node" repository = "https://git.ghostchain.io/ghostchain/ghost-node"

View File

@ -1,6 +1,6 @@
[package] [package]
name = "ghost-claims" name = "ghost-claims"
version = "0.2.4" version = "0.2.3"
description = "Ghost balance and rank claims based on EVM actions" description = "Ghost balance and rank claims based on EVM actions"
license.workspace = true license.workspace = true
authors.workspace = true authors.workspace = true

View File

@ -6,14 +6,14 @@ use frame_benchmarking::v2::*;
#[instance_benchmarks] #[instance_benchmarks]
mod benchmarks { mod benchmarks {
use super::*; use super::*;
use frame_support::dispatch::RawOrigin;
use pallet_ranked_collective::Pallet as Club; use pallet_ranked_collective::Pallet as Club;
use frame_support::dispatch::RawOrigin;
#[benchmark] #[benchmark]
fn claim() { fn claim() {
let i = 1337u32; let i = 1337u32;
let ethereum_secret_key = let ethereum_secret_key = libsecp256k1::SecretKey::parse(
libsecp256k1::SecretKey::parse(&keccak_256(&i.to_le_bytes())).unwrap(); &keccak_256(&i.to_le_bytes())).unwrap();
let eth_address = crate::secp_utils::eth(&ethereum_secret_key); let eth_address = crate::secp_utils::eth(&ethereum_secret_key);
let balance = CurrencyOf::<T, I>::minimum_balance(); let balance = CurrencyOf::<T, I>::minimum_balance();
@ -22,30 +22,23 @@ mod benchmarks {
Total::<T, I>::put(balance); Total::<T, I>::put(balance);
let pseudo_rank = 5u16; let pseudo_rank = 5u16;
let _ = Club::<T, I>::do_add_member_to_rank(pseudo_account.clone(), pseudo_rank, false); let _ = Club::<T, I>::do_add_member_to_rank(
pseudo_account.clone(),
pseudo_rank,
false,
);
let user_account: T::AccountId = account("user", i, 0); let user_account: T::AccountId = account("user", i, 0);
let signature = let signature = crate::secp_utils::sig::<T, I>(&ethereum_secret_key, &user_account.encode());
crate::secp_utils::sig::<T, I>(&ethereum_secret_key, &user_account.encode());
let prev_balance = CurrencyOf::<T, I>::free_balance(&user_account); let prev_balance = CurrencyOf::<T, I>::free_balance(&user_account);
let prev_rank = Club::<T, I>::rank_of(&user_account); let prev_rank = Club::<T, I>::rank_of(&user_account);
#[extrinsic_call] #[extrinsic_call]
claim( claim(RawOrigin::Signed(user_account.clone()), eth_address, signature);
RawOrigin::Signed(user_account.clone()),
eth_address,
signature,
);
assert_eq!( assert_eq!(CurrencyOf::<T, I>::free_balance(&user_account), prev_balance + balance);
CurrencyOf::<T, I>::free_balance(&user_account), assert_eq!(CurrencyOf::<T, I>::free_balance(&pseudo_account), balance - balance);
prev_balance + balance
);
assert_eq!(
CurrencyOf::<T, I>::free_balance(&pseudo_account),
balance - balance
);
let rank = match prev_rank { let rank = match prev_rank {
Some(current_rank) if pseudo_rank <= current_rank => Some(current_rank), Some(current_rank) if pseudo_rank <= current_rank => Some(current_rank),
@ -55,5 +48,9 @@ mod benchmarks {
assert_eq!(Club::<T, I>::rank_of(&pseudo_account), None); assert_eq!(Club::<T, I>::rank_of(&pseudo_account), None);
} }
impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::Test,); impl_benchmark_test_suite!(
Pallet,
crate::mock::new_test_ext(),
crate::mock::Test,
);
} }

View File

@ -1,20 +1,19 @@
#![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(not(feature = "std"), no_std)]
use frame_support::{ use frame_support::{
ensure, ensure, pallet_prelude::*,
pallet_prelude::*,
traits::{ traits::{
Currency, ExistenceRequirement, Get, RankedMembers, RankedMembersSwapHandler, Currency, ExistenceRequirement, Get, RankedMembers,
VestingSchedule, RankedMembersSwapHandler, VestingSchedule,
}, },
DefaultNoBound, DefaultNoBound,
}; };
use frame_system::pallet_prelude::*; use frame_system::pallet_prelude::*;
pub use pallet::*;
use serde::{self, Deserialize, Deserializer, Serialize, Serializer}; use serde::{self, Deserialize, Deserializer, Serialize, Serializer};
pub use pallet::*;
use sp_io::{crypto::secp256k1_ecdsa_recover, hashing::keccak_256}; use sp_io::{crypto::secp256k1_ecdsa_recover, hashing::keccak_256};
use sp_runtime::traits::{BlockNumberProvider, CheckedDiv, CheckedSub}; use sp_runtime::traits::{CheckedSub, CheckedDiv, BlockNumberProvider};
use sp_std::prelude::*; use sp_std::prelude::*;
extern crate alloc; extern crate alloc;
@ -24,10 +23,10 @@ use alloc::{format, string::String};
mod weights; mod weights;
pub use crate::weights::WeightInfo; pub use crate::weights::WeightInfo;
mod benchmarking;
mod mock;
mod secp_utils;
mod tests; mod tests;
mod mock;
mod benchmarking;
mod secp_utils;
/// An ethereum address (i.e. 20 bytes, used to represent an Ethereum account). /// An ethereum address (i.e. 20 bytes, used to represent an Ethereum account).
/// ///
@ -82,14 +81,15 @@ impl sp_std::fmt::Debug for EcdsaSignature {
} }
type CurrencyOf<T, I> = <<T as Config<I>>::VestingSchedule as VestingSchedule< type CurrencyOf<T, I> = <<T as Config<I>>::VestingSchedule as VestingSchedule<
<T as frame_system::Config>::AccountId, <T as frame_system::Config>::AccountId
>>::Currency; >>::Currency;
type BalanceOf<T, I> = type BalanceOf<T, I> = <CurrencyOf<T, I> as Currency<
<CurrencyOf<T, I> as Currency<<T as frame_system::Config>::AccountId>>::Balance; <T as frame_system::Config>::AccountId>
>::Balance;
type RankOf<T, I> = <pallet_ranked_collective::Pallet<T, I> as RankedMembers>::Rank; type RankOf<T, I> = <pallet_ranked_collective::Pallet::<T, I> as RankedMembers>::Rank;
type AccountIdOf<T, I> = <pallet_ranked_collective::Pallet<T, I> as RankedMembers>::AccountId; type AccountIdOf<T, I> = <pallet_ranked_collective::Pallet::<T, I> as RankedMembers>::AccountId;
#[frame_support::pallet] #[frame_support::pallet]
pub mod pallet { pub mod pallet {
@ -100,11 +100,8 @@ pub mod pallet {
pub struct Pallet<T, I = ()>(_); pub struct Pallet<T, I = ()>(_);
#[pallet::config] #[pallet::config]
pub trait Config<I: 'static = ()>: pub trait Config<I: 'static = ()>: frame_system::Config + pallet_ranked_collective::Config<I> {
frame_system::Config + pallet_ranked_collective::Config<I> type RuntimeEvent: From<Event<Self, I>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
{
type RuntimeEvent: From<Event<Self, I>>
+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
type VestingSchedule: VestingSchedule<Self::AccountId, Moment = BlockNumberFor<Self>>; type VestingSchedule: VestingSchedule<Self::AccountId, Moment = BlockNumberFor<Self>>;
type BlockNumberProvider: BlockNumberProvider<BlockNumber = BlockNumberFor<Self>>; type BlockNumberProvider: BlockNumberProvider<BlockNumber = BlockNumberFor<Self>>;
@ -162,11 +159,7 @@ pub mod pallet {
.map(|(account_id, rank)| { .map(|(account_id, rank)| {
assert!( assert!(
pallet_ranked_collective::Pallet::<T, I>::do_add_member_to_rank( pallet_ranked_collective::Pallet::<T, I>::do_add_member_to_rank(
account_id.clone(), account_id.clone(), *rank, false).is_ok(),
*rank,
false
)
.is_ok(),
"error during adding and promotion" "error during adding and promotion"
); );
account_id account_id
@ -193,13 +186,13 @@ pub mod pallet {
) -> DispatchResult { ) -> DispatchResult {
let who = ensure_signed(origin)?; let who = ensure_signed(origin)?;
let data = who.using_encoded(to_ascii_hex); let data = who.using_encoded(to_ascii_hex);
let recovered_address = Self::recover_ethereum_address(&ethereum_signature, &data) let recovered_address = Self::recover_ethereum_address(
.ok_or(Error::<T, I>::InvalidEthereumSignature)?; &ethereum_signature,
&data,
).ok_or(Error::<T, I>::InvalidEthereumSignature)?;
ensure!( ensure!(recovered_address == ethereum_address,
recovered_address == ethereum_address, Error::<T, I>::InvalidEthereumAddress);
Error::<T, I>::InvalidEthereumAddress
);
Self::do_claim(who, ethereum_address) Self::do_claim(who, ethereum_address)
} }
@ -250,15 +243,12 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
} }
fn do_claim(receiver: T::AccountId, ethereum_address: EthereumAddress) -> DispatchResult { fn do_claim(receiver: T::AccountId, ethereum_address: EthereumAddress) -> DispatchResult {
let donor = Self::into_account_id(ethereum_address) let donor = Self::into_account_id(ethereum_address).ok()
.ok()
.ok_or(Error::<T, I>::AddressDecodingFailed)?; .ok_or(Error::<T, I>::AddressDecodingFailed)?;
let balance_due = CurrencyOf::<T, I>::free_balance(&donor); let balance_due = CurrencyOf::<T, I>::free_balance(&donor);
ensure!( ensure!(balance_due >= CurrencyOf::<T, I>::minimum_balance(),
balance_due >= CurrencyOf::<T, I>::minimum_balance(), Error::<T, I>::NoBalanceToClaim);
Error::<T, I>::NoBalanceToClaim
);
let new_total = Total::<T, I>::get() let new_total = Total::<T, I>::get()
.checked_sub(&balance_due) .checked_sub(&balance_due)
@ -290,32 +280,20 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
)?; )?;
} }
let rank = if let Some(rank) = let rank = if let Some(rank) = <pallet_ranked_collective::Pallet::<T, I> as RankedMembers>::rank_of(&donor) {
<pallet_ranked_collective::Pallet<T, I> as RankedMembers>::rank_of(&donor)
{
pallet_ranked_collective::Pallet::<T, I>::do_remove_member_from_rank(&donor, rank)?; pallet_ranked_collective::Pallet::<T, I>::do_remove_member_from_rank(&donor, rank)?;
let new_rank = let new_rank = match <pallet_ranked_collective::Pallet::<T, I> as RankedMembers>::rank_of(&receiver) {
match <pallet_ranked_collective::Pallet<T, I> as RankedMembers>::rank_of(&receiver)
{
Some(current_rank) if current_rank >= rank => current_rank, Some(current_rank) if current_rank >= rank => current_rank,
Some(current_rank) if current_rank < rank => { Some(current_rank) if current_rank < rank => {
for _ in 0..rank - current_rank { for _ in 0..rank - current_rank {
pallet_ranked_collective::Pallet::<T, I>::do_promote_member( pallet_ranked_collective::Pallet::<T, I>::do_promote_member(receiver.clone(), None, false)?;
receiver.clone(),
None,
false,
)?;
} }
rank rank
} },
_ => { _ => {
pallet_ranked_collective::Pallet::<T, I>::do_add_member_to_rank( pallet_ranked_collective::Pallet::<T, I>::do_add_member_to_rank(receiver.clone(), rank, false)?;
receiver.clone(),
rank,
false,
)?;
rank rank
} },
}; };
<T as pallet::Config<I>>::MemberSwappedHandler::swapped(&donor, &receiver, new_rank); <T as pallet::Config<I>>::MemberSwappedHandler::swapped(&donor, &receiver, new_rank);
Some(new_rank) Some(new_rank)

View File

@ -4,113 +4,51 @@ use super::*;
pub use crate as ghost_claims; pub use crate as ghost_claims;
use frame_support::{ use frame_support::{
derive_impl, parameter_types, parameter_types, derive_impl,
traits::{ConstU16, ConstU64, PollStatus, Polling, WithdrawReasons}, traits::{PollStatus, Polling, WithdrawReasons, ConstU16, ConstU64},
}; };
use frame_system::EnsureRootWithSuccess; use frame_system::EnsureRootWithSuccess;
pub use pallet_ranked_collective::{Rank, TallyOf}; use sp_runtime::{BuildStorage, traits::Convert};
use sp_runtime::{traits::Convert, BuildStorage}; pub use pallet_ranked_collective::{TallyOf, Rank};
pub mod eth_keys { pub mod eth_keys {
use crate::{mock::Test, EcdsaSignature, EthereumAddress}; use crate::{
use codec::Encode; mock::Test,
EcdsaSignature, EthereumAddress,
};
use hex_literal::hex; use hex_literal::hex;
use codec::Encode;
pub fn total_claims() -> u64 { pub fn total_claims() -> u64 { 10 + 100 + 1000 }
10 + 100 + 1000 pub fn alice_account_id() -> <Test as frame_system::Config>::AccountId { 69 }
} pub fn bob_account_id() -> <Test as frame_system::Config>::AccountId { 1337 }
pub fn alice_account_id() -> <Test as frame_system::Config>::AccountId {
69
}
pub fn bob_account_id() -> <Test as frame_system::Config>::AccountId {
1337
}
pub fn first_eth_public_known() -> EthereumAddress { pub fn first_eth_public_known() -> EthereumAddress { EthereumAddress(hex!("1A69d2D5568D1878023EeB121a73d33B9116A760")) }
EthereumAddress(hex!("1A69d2D5568D1878023EeB121a73d33B9116A760")) pub fn second_eth_public_known() -> EthereumAddress { EthereumAddress(hex!("2f86cfBED3fbc1eCf2989B9aE5fc019a837A9C12")) }
} pub fn third_eth_public_known() -> EthereumAddress { EthereumAddress(hex!("e83f67361Ac74D42A48E2DAfb6706eb047D8218D")) }
pub fn second_eth_public_known() -> EthereumAddress { pub fn fourth_eth_public_known() -> EthereumAddress { EthereumAddress(hex!("827ee4ad9b259b6fa1390ed60921508c78befd63")) }
EthereumAddress(hex!("2f86cfBED3fbc1eCf2989B9aE5fc019a837A9C12"))
}
pub fn third_eth_public_known() -> EthereumAddress {
EthereumAddress(hex!("e83f67361Ac74D42A48E2DAfb6706eb047D8218D"))
}
pub fn fourth_eth_public_known() -> EthereumAddress {
EthereumAddress(hex!("827ee4ad9b259b6fa1390ed60921508c78befd63"))
}
fn first_eth_private_key() -> libsecp256k1::SecretKey { fn first_eth_private_key() -> libsecp256k1::SecretKey { libsecp256k1::SecretKey::parse(&hex!("01c928771aea942a1e7ac06adf2b73dfbc9a25d9eaa516e3673116af7f345198")).unwrap() }
libsecp256k1::SecretKey::parse(&hex!( fn second_eth_private_key() -> libsecp256k1::SecretKey { libsecp256k1::SecretKey::parse(&hex!("b19a435901872f817185f7234a1484eae837613f9d10cf21927a23c2d8cb9139")).unwrap() }
"01c928771aea942a1e7ac06adf2b73dfbc9a25d9eaa516e3673116af7f345198" fn third_eth_private_key() -> libsecp256k1::SecretKey { libsecp256k1::SecretKey::parse(&hex!("d3baf57b74d65719b2dc33f5a464176022d0cc5edbca002234229f3e733875fc")).unwrap() }
)) fn fourth_eth_private_key() -> libsecp256k1::SecretKey { libsecp256k1::SecretKey::parse(&hex!("c4683d566436af6b58b4a59c8f501319226e85b21869bf93d5eeb4596d4791d4")).unwrap() }
.unwrap() fn wrong_eth_private_key() -> libsecp256k1::SecretKey { libsecp256k1::SecretKey::parse(&hex!("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef")).unwrap() }
}
fn second_eth_private_key() -> libsecp256k1::SecretKey {
libsecp256k1::SecretKey::parse(&hex!(
"b19a435901872f817185f7234a1484eae837613f9d10cf21927a23c2d8cb9139"
))
.unwrap()
}
fn third_eth_private_key() -> libsecp256k1::SecretKey {
libsecp256k1::SecretKey::parse(&hex!(
"d3baf57b74d65719b2dc33f5a464176022d0cc5edbca002234229f3e733875fc"
))
.unwrap()
}
fn fourth_eth_private_key() -> libsecp256k1::SecretKey {
libsecp256k1::SecretKey::parse(&hex!(
"c4683d566436af6b58b4a59c8f501319226e85b21869bf93d5eeb4596d4791d4"
))
.unwrap()
}
fn wrong_eth_private_key() -> libsecp256k1::SecretKey {
libsecp256k1::SecretKey::parse(&hex!(
"deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
))
.unwrap()
}
pub fn first_eth_public_key() -> EthereumAddress { pub fn first_eth_public_key() -> EthereumAddress { crate::secp_utils::eth(&first_eth_private_key()) }
crate::secp_utils::eth(&first_eth_private_key()) pub fn second_eth_public_key() -> EthereumAddress { crate::secp_utils::eth(&second_eth_private_key()) }
} pub fn third_eth_public_key() -> EthereumAddress { crate::secp_utils::eth(&third_eth_private_key()) }
pub fn second_eth_public_key() -> EthereumAddress { pub fn fourth_eth_public_key() -> EthereumAddress { crate::secp_utils::eth(&fourth_eth_private_key()) }
crate::secp_utils::eth(&second_eth_private_key())
}
pub fn third_eth_public_key() -> EthereumAddress {
crate::secp_utils::eth(&third_eth_private_key())
}
pub fn fourth_eth_public_key() -> EthereumAddress {
crate::secp_utils::eth(&fourth_eth_private_key())
}
pub fn first_account_id() -> <Test as frame_system::Config>::AccountId { pub fn first_account_id() -> <Test as frame_system::Config>::AccountId { crate::secp_utils::into_account_id::<Test, ()>(first_eth_public_key()) }
crate::secp_utils::into_account_id::<Test, ()>(first_eth_public_key()) pub fn second_account_id() -> <Test as frame_system::Config>::AccountId { crate::secp_utils::into_account_id::<Test, ()>(second_eth_public_key()) }
} pub fn third_account_id() -> <Test as frame_system::Config>::AccountId { crate::secp_utils::into_account_id::<Test, ()>(third_eth_public_key()) }
pub fn second_account_id() -> <Test as frame_system::Config>::AccountId { pub fn fourth_account_id() -> <Test as frame_system::Config>::AccountId { crate::secp_utils::into_account_id::<Test, ()>(fourth_eth_public_key()) }
crate::secp_utils::into_account_id::<Test, ()>(second_eth_public_key())
}
pub fn third_account_id() -> <Test as frame_system::Config>::AccountId {
crate::secp_utils::into_account_id::<Test, ()>(third_eth_public_key())
}
pub fn fourth_account_id() -> <Test as frame_system::Config>::AccountId {
crate::secp_utils::into_account_id::<Test, ()>(fourth_eth_public_key())
}
pub fn first_signature() -> EcdsaSignature { pub fn first_signature() -> EcdsaSignature { crate::secp_utils::sig::<Test, ()>(&first_eth_private_key(), &alice_account_id().encode()) }
crate::secp_utils::sig::<Test, ()>(&first_eth_private_key(), &alice_account_id().encode()) pub fn second_signature() -> EcdsaSignature { crate::secp_utils::sig::<Test, ()>(&second_eth_private_key(), &alice_account_id().encode()) }
} pub fn third_signature() -> EcdsaSignature { crate::secp_utils::sig::<Test, ()>(&third_eth_private_key(), &alice_account_id().encode()) }
pub fn second_signature() -> EcdsaSignature { pub fn fourth_signature() -> EcdsaSignature { crate::secp_utils::sig::<Test, ()>(&fourth_eth_private_key(), &bob_account_id().encode()) }
crate::secp_utils::sig::<Test, ()>(&second_eth_private_key(), &alice_account_id().encode()) pub fn wrong_signature() -> EcdsaSignature { crate::secp_utils::sig::<Test, ()>(&wrong_eth_private_key(), &alice_account_id().encode()) }
}
pub fn third_signature() -> EcdsaSignature {
crate::secp_utils::sig::<Test, ()>(&third_eth_private_key(), &alice_account_id().encode())
}
pub fn fourth_signature() -> EcdsaSignature {
crate::secp_utils::sig::<Test, ()>(&fourth_eth_private_key(), &bob_account_id().encode())
}
pub fn wrong_signature() -> EcdsaSignature {
crate::secp_utils::sig::<Test, ()>(&wrong_eth_private_key(), &alice_account_id().encode())
}
} }
#[derive_impl(frame_system::config_preludes::TestDefaultConfig)] #[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
@ -128,6 +66,7 @@ impl pallet_balances::Config for Test {
type AccountStore = System; type AccountStore = System;
} }
parameter_types! { parameter_types! {
pub const MinVestedTransfer: u64 = 1; pub const MinVestedTransfer: u64 = 1;
pub UnvestedFundsAllowedWithdrawReasons: WithdrawReasons = pub UnvestedFundsAllowedWithdrawReasons: WithdrawReasons =
@ -140,7 +79,8 @@ impl pallet_vesting::Config for Test {
type BlockNumberToBalance = sp_runtime::traits::ConvertInto; type BlockNumberToBalance = sp_runtime::traits::ConvertInto;
type MinVestedTransfer = MinVestedTransfer; type MinVestedTransfer = MinVestedTransfer;
type WeightInfo = (); type WeightInfo = ();
type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons; type UnvestedFundsAllowedWithdrawReasons =
UnvestedFundsAllowedWithdrawReasons;
type BlockNumberProvider = System; type BlockNumberProvider = System;
const MAX_VESTING_SCHEDULES: u32 = 28; const MAX_VESTING_SCHEDULES: u32 = 28;

View File

@ -8,8 +8,7 @@ pub fn public(secret: &libsecp256k1::SecretKey) -> libsecp256k1::PublicKey {
pub fn eth(secret: &libsecp256k1::SecretKey) -> EthereumAddress { pub fn eth(secret: &libsecp256k1::SecretKey) -> EthereumAddress {
let mut res = EthereumAddress::default(); let mut res = EthereumAddress::default();
res.0 res.0.copy_from_slice(&keccak_256(&public(secret).serialize()[1..65])[12..]);
.copy_from_slice(&keccak_256(&public(secret).serialize()[1..65])[12..]);
res res
} }
@ -26,7 +25,10 @@ pub fn sig<T: Config<I>, I: 'static>(
&crate::to_ascii_hex(what)[..], &crate::to_ascii_hex(what)[..],
)); ));
let (sig, recovery_id) = libsecp256k1::sign(&libsecp256k1::Message::parse(&msg), secret); let (sig, recovery_id) = libsecp256k1::sign(
&libsecp256k1::Message::parse(&msg),
secret,
);
let mut r = [0u8; 65]; let mut r = [0u8; 65];
r[0..64].copy_from_slice(&sig.serialize()[..]); r[0..64].copy_from_slice(&sig.serialize()[..]);

View File

@ -1,19 +1,21 @@
#![cfg(test)] #![cfg(test)]
use super::*;
use frame_support::{assert_err, assert_ok};
use hex_literal::hex;
use mock::{ use mock::{
new_test_ext, ghost_claims,
Test, System, Balances, Club, Vesting, Claims, RuntimeOrigin, RuntimeEvent,
eth_keys::{ eth_keys::{
alice_account_id, bob_account_id, first_account_id, first_eth_public_key, alice_account_id, total_claims, first_eth_public_known,
first_eth_public_known, first_signature, fourth_account_id, fourth_eth_public_key, first_eth_public_key, first_account_id, first_signature,
fourth_eth_public_known, fourth_signature, second_account_id, second_eth_public_key, second_eth_public_known, second_eth_public_key, second_account_id,
second_eth_public_known, second_signature, third_account_id, third_eth_public_key, second_signature, third_eth_public_known, third_eth_public_key,
third_eth_public_known, third_signature, total_claims, wrong_signature, third_account_id, third_signature, fourth_eth_public_known,
}, fourth_eth_public_key, fourth_account_id, fourth_signature,
ghost_claims, new_test_ext, Balances, Claims, Club, RuntimeEvent, RuntimeOrigin, System, Test, wrong_signature, bob_account_id,
Vesting, }
}; };
use hex_literal::hex;
use frame_support::{assert_err, assert_ok};
use super::*;
#[test] #[test]
fn serde_works() { fn serde_works() {
@ -56,8 +58,7 @@ fn small_claiming_works() {
assert_ok!(Claims::claim( assert_ok!(Claims::claim(
RuntimeOrigin::signed(alice_account_id()), RuntimeOrigin::signed(alice_account_id()),
first_eth_public_key(), first_eth_public_key(),
first_signature() first_signature()));
));
assert_eq!(Balances::usable_balance(&alice_account_id()), 10); assert_eq!(Balances::usable_balance(&alice_account_id()), 10);
assert_eq!(Balances::usable_balance(&first_account_id()), 0); assert_eq!(Balances::usable_balance(&first_account_id()), 0);
@ -112,15 +113,11 @@ fn big_claiming_works() {
assert_eq!(Club::rank_of(&third_account_id()), None); assert_eq!(Club::rank_of(&third_account_id()), None);
assert_eq!(Vesting::vesting_balance(&alice_account_id()), Some(800)); assert_eq!(Vesting::vesting_balance(&alice_account_id()), Some(800));
assert_eq!( assert_eq!(ghost_claims::Total::<Test, ()>::get(), total_claims() - 1000);
ghost_claims::Total::<Test, ()>::get(),
total_claims() - 1000
);
assert_ok!(Balances::transfer_allow_death( assert_ok!(Balances::transfer_allow_death(
RuntimeOrigin::signed(alice_account_id()), RuntimeOrigin::signed(alice_account_id()),
bob_account_id(), bob_account_id(),
200 200));
));
}) })
} }
@ -191,14 +188,11 @@ fn multiple_accounts_reverese_claiming_works() {
#[test] #[test]
fn cannot_claim_with_bad_signature() { fn cannot_claim_with_bad_signature() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
assert_err!( assert_err!(Claims::claim(
Claims::claim(
RuntimeOrigin::signed(alice_account_id()), RuntimeOrigin::signed(alice_account_id()),
first_eth_public_key(), first_eth_public_key(),
wrong_signature() wrong_signature()),
), crate::Error::<Test>::InvalidEthereumAddress);
crate::Error::<Test>::InvalidEthereumAddress
);
assert_eq!(Balances::usable_balance(&alice_account_id()), 0); assert_eq!(Balances::usable_balance(&alice_account_id()), 0);
assert_eq!(Balances::usable_balance(&first_account_id()), 10); assert_eq!(Balances::usable_balance(&first_account_id()), 10);
@ -218,14 +212,11 @@ fn cannot_claim_with_bad_signature() {
#[test] #[test]
fn cannot_claim_with_wrong_address() { fn cannot_claim_with_wrong_address() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
assert_err!( assert_err!(Claims::claim(
Claims::claim(
RuntimeOrigin::signed(bob_account_id()), RuntimeOrigin::signed(bob_account_id()),
first_eth_public_key(), first_eth_public_key(),
first_signature() first_signature()),
), crate::Error::<Test>::InvalidEthereumAddress);
crate::Error::<Test>::InvalidEthereumAddress
);
assert_eq!(Balances::usable_balance(&bob_account_id()), 0); assert_eq!(Balances::usable_balance(&bob_account_id()), 0);
assert_eq!(Balances::usable_balance(&alice_account_id()), 0); assert_eq!(Balances::usable_balance(&alice_account_id()), 0);
@ -246,14 +237,11 @@ fn cannot_claim_with_wrong_address() {
#[test] #[test]
fn cannot_claim_nothing() { fn cannot_claim_nothing() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
assert_err!( assert_err!(Claims::claim(
Claims::claim(
RuntimeOrigin::signed(bob_account_id()), RuntimeOrigin::signed(bob_account_id()),
fourth_eth_public_key(), fourth_eth_public_key(),
fourth_signature() fourth_signature()),
), crate::Error::<Test>::NoBalanceToClaim);
crate::Error::<Test>::NoBalanceToClaim
);
assert_eq!(Balances::usable_balance(&bob_account_id()), 0); assert_eq!(Balances::usable_balance(&bob_account_id()), 0);
assert_eq!(Balances::usable_balance(&fourth_account_id()), 0); assert_eq!(Balances::usable_balance(&fourth_account_id()), 0);
assert_eq!(Vesting::vesting_balance(&bob_account_id()), None); assert_eq!(Vesting::vesting_balance(&bob_account_id()), None);
@ -275,7 +263,8 @@ fn event_emitted_during_claim() {
third_eth_public_key(), third_eth_public_key(),
third_signature(), third_signature(),
)); ));
System::assert_has_event(RuntimeEvent::Claims(crate::Event::Claimed { System::assert_has_event(RuntimeEvent::Claims(
crate::Event::Claimed {
receiver: alice_account_id(), receiver: alice_account_id(),
donor: account, donor: account,
amount, amount,

View File

@ -1,6 +1,6 @@
[package] [package]
name = "ghost-networks" name = "ghost-networks"
version = "0.1.11" version = "0.1.7"
license.workspace = true license.workspace = true
authors.workspace = true authors.workspace = true
edition.workspace = true edition.workspace = true

View File

@ -13,29 +13,26 @@ fn assert_last_event<T: Config>(generic_event: <T as Config>::RuntimeEvent) {
frame_system::Pallet::<T>::assert_last_event(generic_event.into()); frame_system::Pallet::<T>::assert_last_event(generic_event.into());
} }
fn prepare_network<T: Config>(n: u32, m: u32) -> (<T as module::Config>::NetworkId, NetworkData) { fn prepare_network<T: Config>(
n: u32, m: u32,
) -> (<T as module::Config>::NetworkId, NetworkData) {
let chain_id: <T as module::Config>::NetworkId = Default::default(); let chain_id: <T as module::Config>::NetworkId = Default::default();
let chain_id = chain_id.saturating_add((n + m).into()); let chain_id = chain_id.saturating_add((n + m).into());
let mut gatekeeper = b"0x".to_vec(); let mut gatekeeper = b"0x".to_vec();
for i in 0..40 { for i in 0..40 { gatekeeper.push(i); }
gatekeeper.push(i);
}
let mut topic_name = b"0x".to_vec(); let mut topic_name = b"0x".to_vec();
for i in 0..64 { for i in 0..64 { topic_name.push(i); }
topic_name.push(i);
}
let network = NetworkData { let network = NetworkData {
chain_name: sp_std::vec![0x69; n as usize], chain_name: sp_std::vec![0x69; n as usize],
default_endpoint: sp_std::vec![0x69; m as usize], default_endpoint: sp_std::vec![0x69; m as usize],
gatekeeper, gatekeeper,
topic_name, topic_name,
network_type: NetworkType::Evm, finality_delay: Some(69),
finality_delay: 69,
rate_limit_delay: 69,
block_distance: 69, block_distance: 69,
network_type: NetworkType::Evm,
incoming_fee: 0, incoming_fee: 0,
outgoing_fee: 0, outgoing_fee: 0,
}; };
@ -53,11 +50,8 @@ fn create_network<T: Config>(
let authority = T::RegisterOrigin::try_successful_origin() let authority = T::RegisterOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Weightless)?; .map_err(|_| BenchmarkError::Weightless)?;
GhostNetworks::<T>::register_network( GhostNetworks::<T>::register_network(
authority.clone(), authority.clone(), chain_id.clone(), network.clone()
chain_id.clone(), ).map_err(|_| BenchmarkError::Weightless)?;
network.clone(),
)
.map_err(|_| BenchmarkError::Weightless)?;
network network
} }
}; };
@ -113,7 +107,7 @@ benchmarks! {
} }
update_network_finality_delay { update_network_finality_delay {
let delay = 1337; let delay = Some(1337);
let (chain_id, network) = prepare_network::<T>(1, 1); let (chain_id, network) = prepare_network::<T>(1, 1);
let authority = T::UpdateOrigin::try_successful_origin() let authority = T::UpdateOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Weightless)?; .map_err(|_| BenchmarkError::Weightless)?;
@ -126,20 +120,6 @@ benchmarks! {
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network); assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
} }
update_network_rate_limit_delay {
let rate_limit = 1337;
let (chain_id, network) = prepare_network::<T>(1, 1);
let authority = T::UpdateOrigin::try_successful_origin()
.map_err(|_| BenchmarkError::Weightless)?;
let prev_network = create_network::<T>(chain_id.clone(), network.clone())?;
}: _<T::RuntimeOrigin>(authority, chain_id.clone(), rate_limit)
verify {
assert_last_event::<T>(Event::NetworkRateLimitDelayUpdated {
chain_id: chain_id.clone(), rate_limit_delay: rate_limit,
}.into());
assert_ne!(GhostNetworks::<T>::networks(chain_id.clone()), prev_network);
}
update_network_block_distance { update_network_block_distance {
let block_distance = 1337; let block_distance = 1337;
let (chain_id, network) = prepare_network::<T>(1, 1); let (chain_id, network) = prepare_network::<T>(1, 1);

View File

@ -4,27 +4,27 @@
use frame_support::{ use frame_support::{
pallet_prelude::*, pallet_prelude::*,
storage::PrefixIterator, storage::PrefixIterator, traits::{tokens::fungible::Inspect, EnsureOrigin},
traits::{tokens::fungible::Inspect, EnsureOrigin},
}; };
use frame_system::pallet_prelude::*; use frame_system::pallet_prelude::*;
use scale_info::TypeInfo; use scale_info::TypeInfo;
use sp_runtime::{ use sp_runtime::{
traits::{CheckedSub, CheckedAdd, AtLeast32BitUnsigned, Member},
curve::PiecewiseLinear, curve::PiecewiseLinear,
traits::{AtLeast32BitUnsigned, CheckedAdd, CheckedSub, Member},
DispatchResult, DispatchResult,
}; };
use sp_std::{convert::TryInto, prelude::*}; use sp_std::{prelude::*, convert::TryInto};
pub use ghost_traits::networks::{ pub use ghost_traits::networks::{
NetworkDataBasicHandler, NetworkDataInspectHandler, NetworkDataMutateHandler, NetworkDataBasicHandler, NetworkDataInspectHandler,
NetworkDataMutateHandler,
}; };
mod weights; mod weights;
pub use crate::weights::WeightInfo;
pub use module::*; pub use module::*;
pub use crate::weights::WeightInfo;
#[cfg(any(feature = "runtime-benchmarks", test))] #[cfg(any(feature = "runtime-benchmarks", test))]
mod benchmarking; mod benchmarking;
@ -33,8 +33,9 @@ mod mock;
#[cfg(all(feature = "std", test))] #[cfg(all(feature = "std", test))]
mod tests; mod tests;
pub type BalanceOf<T> = pub type BalanceOf<T> = <<T as Config>::Currency as Inspect<
<<T as Config>::Currency as Inspect<<T as frame_system::Config>::AccountId>>::Balance; <T as frame_system::Config>::AccountId,
>>::Balance;
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] #[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub enum NetworkType { pub enum NetworkType {
@ -44,9 +45,7 @@ pub enum NetworkType {
} }
impl Default for NetworkType { impl Default for NetworkType {
fn default() -> Self { fn default() -> Self { NetworkType::Evm }
NetworkType::Evm
}
} }
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] #[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
@ -55,9 +54,8 @@ pub struct NetworkData {
pub default_endpoint: Vec<u8>, pub default_endpoint: Vec<u8>,
pub gatekeeper: Vec<u8>, pub gatekeeper: Vec<u8>,
pub topic_name: Vec<u8>, pub topic_name: Vec<u8>,
pub finality_delay: Option<u64>,
pub network_type: NetworkType, pub network_type: NetworkType,
pub finality_delay: u64,
pub rate_limit_delay: u64,
pub block_distance: u64, pub block_distance: u64,
pub incoming_fee: u32, pub incoming_fee: u32,
pub outgoing_fee: u32, pub outgoing_fee: u32,
@ -70,8 +68,7 @@ pub struct BridgeAdjustment<Balance> {
} }
pub struct BridgedInflationCurve<RewardCurve, T>(core::marker::PhantomData<(RewardCurve, T)>); pub struct BridgedInflationCurve<RewardCurve, T>(core::marker::PhantomData<(RewardCurve, T)>);
impl<Balance, RewardCurve, T> pallet_staking::EraPayout<Balance> impl<Balance, RewardCurve, T> pallet_staking::EraPayout<Balance> for BridgedInflationCurve<RewardCurve, T>
for BridgedInflationCurve<RewardCurve, T>
where where
Balance: Default + AtLeast32BitUnsigned + Clone + Copy + From<u128>, Balance: Default + AtLeast32BitUnsigned + Clone + Copy + From<u128>,
RewardCurve: Get<&'static PiecewiseLinear<'static>>, RewardCurve: Get<&'static PiecewiseLinear<'static>>,
@ -101,8 +98,7 @@ where
match piecewise_linear match piecewise_linear
.calculate_for_fraction_times_denominator(total_staked, adjusted_issuance) .calculate_for_fraction_times_denominator(total_staked, adjusted_issuance)
.checked_mul(&accumulated_balance) .checked_mul(&accumulated_balance)
.and_then(|product| product.checked_div(&adjusted_issuance)) .and_then(|product| product.checked_div(&adjusted_issuance)) {
{
Some(payout) => (payout, accumulated_balance.saturating_sub(payout)), Some(payout) => (payout, accumulated_balance.saturating_sub(payout)),
None => (Balance::default(), Balance::default()), None => (Balance::default(), Balance::default()),
} }
@ -158,53 +154,17 @@ pub mod module {
#[pallet::event] #[pallet::event]
#[pallet::generate_deposit(pub(crate) fn deposit_event)] #[pallet::generate_deposit(pub(crate) fn deposit_event)]
pub enum Event<T: Config> { pub enum Event<T: Config> {
NetworkRegistered { NetworkRegistered { chain_id: T::NetworkId, network: NetworkData },
chain_id: T::NetworkId, NetworkNameUpdated { chain_id: T::NetworkId, chain_name: Vec<u8> },
network: NetworkData, NetworkEndpointUpdated { chain_id: T::NetworkId, default_endpoint: Vec<u8> },
}, NetworkFinalityDelayUpdated { chain_id: T::NetworkId, finality_delay: Option<u64> },
NetworkNameUpdated { NetworkBlockDistanceUpdated { chain_id: T::NetworkId, block_distance: u64 },
chain_id: T::NetworkId, NetworkTypeUpdated { chain_id: T::NetworkId, network_type: NetworkType },
chain_name: Vec<u8>, NetworkGatekeeperUpdated { chain_id: T::NetworkId, gatekeeper: Vec<u8> },
}, NetworkTopicNameUpdated { chain_id: T::NetworkId, topic_name: Vec<u8> },
NetworkEndpointUpdated { NetworkIncomingFeeUpdated { chain_id: T::NetworkId, incoming_fee: u32 },
chain_id: T::NetworkId, NetworkOutgoingFeeUpdated { chain_id: T::NetworkId, outgoing_fee: u32 },
default_endpoint: Vec<u8>, NetworkRemoved { chain_id: T::NetworkId },
},
NetworkFinalityDelayUpdated {
chain_id: T::NetworkId,
finality_delay: u64,
},
NetworkRateLimitDelayUpdated {
chain_id: T::NetworkId,
rate_limit_delay: u64,
},
NetworkBlockDistanceUpdated {
chain_id: T::NetworkId,
block_distance: u64,
},
NetworkTypeUpdated {
chain_id: T::NetworkId,
network_type: NetworkType,
},
NetworkGatekeeperUpdated {
chain_id: T::NetworkId,
gatekeeper: Vec<u8>,
},
NetworkTopicNameUpdated {
chain_id: T::NetworkId,
topic_name: Vec<u8>,
},
NetworkIncomingFeeUpdated {
chain_id: T::NetworkId,
incoming_fee: u32,
},
NetworkOutgoingFeeUpdated {
chain_id: T::NetworkId,
outgoing_fee: u32,
},
NetworkRemoved {
chain_id: T::NetworkId,
},
} }
#[pallet::storage] #[pallet::storage]
@ -218,7 +178,8 @@ pub mod module {
#[pallet::storage] #[pallet::storage]
#[pallet::getter(fn accumulated_commission)] #[pallet::getter(fn accumulated_commission)]
pub type AccumulatedCommission<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>; pub type AccumulatedCommission<T: Config> =
StorageValue<_, BalanceOf<T>, ValueQuery>;
#[pallet::storage] #[pallet::storage]
#[pallet::getter(fn networks)] #[pallet::getter(fn networks)]
@ -227,8 +188,13 @@ pub mod module {
#[pallet::storage] #[pallet::storage]
#[pallet::getter(fn gatekeeper_amount)] #[pallet::getter(fn gatekeeper_amount)]
pub type GatekeeperAmount<T: Config> = pub type GatekeeperAmount<T: Config> = StorageMap<
StorageMap<_, Twox64Concat, T::NetworkId, BalanceOf<T>, ValueQuery>; _,
Twox64Concat,
T::NetworkId,
BalanceOf<T>,
ValueQuery,
>;
#[pallet::genesis_config] #[pallet::genesis_config]
pub struct GenesisConfig<T: Config> { pub struct GenesisConfig<T: Config> {
@ -245,10 +211,9 @@ pub mod module {
impl<T: Config> BuildGenesisConfig for GenesisConfig<T> { impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
fn build(&self) { fn build(&self) {
if !self.networks.is_empty() { if !self.networks.is_empty() {
self.networks self.networks.iter().for_each(|(chain_id, network_metadata)| {
.iter() let network =
.for_each(|(chain_id, network_metadata)| { NetworkData::decode(&mut &network_metadata[..])
let network = NetworkData::decode(&mut &network_metadata[..])
.expect("Error decoding NetworkData"); .expect("Error decoding NetworkData");
Pallet::<T>::do_register_network(chain_id.clone(), network) Pallet::<T>::do_register_network(chain_id.clone(), network)
.expect("Error registering network"); .expect("Error registering network");
@ -301,7 +266,10 @@ pub mod module {
chain_name: Vec<u8>, chain_name: Vec<u8>,
) -> DispatchResult { ) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?; T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_name(chain_id, chain_name) Self::do_update_network_name(
chain_id,
chain_name,
)
} }
#[pallet::call_index(2)] #[pallet::call_index(2)]
@ -314,7 +282,10 @@ pub mod module {
default_endpoint: Vec<u8>, default_endpoint: Vec<u8>,
) -> DispatchResult { ) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?; T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_endpoint(chain_id, default_endpoint) Self::do_update_network_endpoint(
chain_id,
default_endpoint,
)
} }
#[pallet::call_index(3)] #[pallet::call_index(3)]
@ -322,24 +293,16 @@ pub mod module {
pub fn update_network_finality_delay( pub fn update_network_finality_delay(
origin: OriginFor<T>, origin: OriginFor<T>,
chain_id: T::NetworkId, chain_id: T::NetworkId,
finality_delay: u64, finality_delay: Option<u64>,
) -> DispatchResult { ) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?; T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_finality_delay(chain_id, finality_delay) Self::do_update_network_finality_delay(
chain_id,
finality_delay,
)
} }
#[pallet::call_index(4)] #[pallet::call_index(4)]
#[pallet::weight(T::WeightInfo::update_network_rate_limit_delay())]
pub fn update_network_rate_limit_delay(
origin: OriginFor<T>,
chain_id: T::NetworkId,
rate_limit_delay: u64,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_rate_limit_delay(chain_id, rate_limit_delay)
}
#[pallet::call_index(5)]
#[pallet::weight(T::WeightInfo::update_network_block_distance())] #[pallet::weight(T::WeightInfo::update_network_block_distance())]
pub fn update_network_block_distance( pub fn update_network_block_distance(
origin: OriginFor<T>, origin: OriginFor<T>,
@ -347,10 +310,13 @@ pub mod module {
block_distance: u64, block_distance: u64,
) -> DispatchResult { ) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?; T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_block_distance(chain_id, block_distance) Self::do_update_network_block_distance(
chain_id,
block_distance,
)
} }
#[pallet::call_index(6)] #[pallet::call_index(5)]
#[pallet::weight(T::WeightInfo::update_network_type())] #[pallet::weight(T::WeightInfo::update_network_type())]
pub fn update_network_type( pub fn update_network_type(
origin: OriginFor<T>, origin: OriginFor<T>,
@ -358,10 +324,13 @@ pub mod module {
network_type: NetworkType, network_type: NetworkType,
) -> DispatchResult { ) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?; T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_type(chain_id, network_type) Self::do_update_network_type(
chain_id,
network_type,
)
} }
#[pallet::call_index(7)] #[pallet::call_index(6)]
#[pallet::weight(T::WeightInfo::update_network_gatekeeper())] #[pallet::weight(T::WeightInfo::update_network_gatekeeper())]
pub fn update_network_gatekeeper( pub fn update_network_gatekeeper(
origin: OriginFor<T>, origin: OriginFor<T>,
@ -369,10 +338,13 @@ pub mod module {
gatekeeper: Vec<u8>, gatekeeper: Vec<u8>,
) -> DispatchResult { ) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?; T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_gatekeeper(chain_id, gatekeeper) Self::do_update_network_gatekeeper(
chain_id,
gatekeeper,
)
} }
#[pallet::call_index(8)] #[pallet::call_index(7)]
#[pallet::weight(T::WeightInfo::update_network_topic_name())] #[pallet::weight(T::WeightInfo::update_network_topic_name())]
pub fn update_network_topic_name( pub fn update_network_topic_name(
origin: OriginFor<T>, origin: OriginFor<T>,
@ -380,10 +352,13 @@ pub mod module {
topic_name: Vec<u8>, topic_name: Vec<u8>,
) -> DispatchResult { ) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?; T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_network_topic_name(chain_id, topic_name) Self::do_update_network_topic_name(
chain_id,
topic_name,
)
} }
#[pallet::call_index(9)] #[pallet::call_index(8)]
#[pallet::weight(T::WeightInfo::update_incoming_network_fee())] #[pallet::weight(T::WeightInfo::update_incoming_network_fee())]
pub fn update_incoming_network_fee( pub fn update_incoming_network_fee(
origin: OriginFor<T>, origin: OriginFor<T>,
@ -391,10 +366,13 @@ pub mod module {
incoming_fee: u32, incoming_fee: u32,
) -> DispatchResult { ) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?; T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_incoming_network_fee(chain_id, incoming_fee) Self::do_update_incoming_network_fee(
chain_id,
incoming_fee,
)
} }
#[pallet::call_index(10)] #[pallet::call_index(9)]
#[pallet::weight(T::WeightInfo::update_outgoing_network_fee())] #[pallet::weight(T::WeightInfo::update_outgoing_network_fee())]
pub fn update_outgoing_network_fee( pub fn update_outgoing_network_fee(
origin: OriginFor<T>, origin: OriginFor<T>,
@ -402,12 +380,18 @@ pub mod module {
outgoing_fee: u32, outgoing_fee: u32,
) -> DispatchResult { ) -> DispatchResult {
T::UpdateOrigin::ensure_origin_or_root(origin)?; T::UpdateOrigin::ensure_origin_or_root(origin)?;
Self::do_update_outgoing_network_fee(chain_id, outgoing_fee) Self::do_update_outgoing_network_fee(
chain_id,
outgoing_fee,
)
} }
#[pallet::call_index(11)] #[pallet::call_index(10)]
#[pallet::weight(T::WeightInfo::remove_network())] #[pallet::weight(T::WeightInfo::remove_network())]
pub fn remove_network(origin: OriginFor<T>, chain_id: T::NetworkId) -> DispatchResult { pub fn remove_network(
origin: OriginFor<T>,
chain_id: T::NetworkId,
) -> DispatchResult {
T::RemoveOrigin::ensure_origin_or_root(origin)?; T::RemoveOrigin::ensure_origin_or_root(origin)?;
Self::do_remove_network(chain_id) Self::do_remove_network(chain_id)
} }
@ -416,12 +400,12 @@ pub mod module {
impl<T: Config> Pallet<T> { impl<T: Config> Pallet<T> {
/// Register a new network. /// Register a new network.
pub fn do_register_network(chain_id: T::NetworkId, network: NetworkData) -> DispatchResult { pub fn do_register_network(
chain_id: T::NetworkId,
network: NetworkData,
) -> DispatchResult {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult { Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!( ensure!(maybe_network.is_none(), Error::<T>::NetworkAlreadyRegistered);
maybe_network.is_none(),
Error::<T>::NetworkAlreadyRegistered
);
*maybe_network = Some(network.clone()); *maybe_network = Some(network.clone());
Ok(()) Ok(())
})?; })?;
@ -443,7 +427,10 @@ impl<T: Config> Pallet<T> {
} }
/// Update existent network name. /// Update existent network name.
pub fn do_update_network_name(chain_id: T::NetworkId, chain_name: Vec<u8>) -> DispatchResult { pub fn do_update_network_name(
chain_id: T::NetworkId,
chain_name: Vec<u8>,
) -> DispatchResult {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult { Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist); ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
let net = maybe_network.as_mut().unwrap(); let net = maybe_network.as_mut().unwrap();
@ -478,10 +465,10 @@ impl<T: Config> Pallet<T> {
Ok(()) Ok(())
} }
/// Update existent network default finality delay. /// Update existent network default endpoint.
pub fn do_update_network_finality_delay( pub fn do_update_network_finality_delay(
chain_id: T::NetworkId, chain_id: T::NetworkId,
finality_delay: u64, finality_delay: Option<u64>,
) -> DispatchResult { ) -> DispatchResult {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult { Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist); ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
@ -497,25 +484,6 @@ impl<T: Config> Pallet<T> {
Ok(()) Ok(())
} }
/// Update existent network default rate limit delay.
pub fn do_update_network_rate_limit_delay(
chain_id: T::NetworkId,
rate_limit_delay: u64,
) -> DispatchResult {
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
let net = maybe_network.as_mut().unwrap();
net.rate_limit_delay = rate_limit_delay;
*maybe_network = Some(net.clone());
Ok(())
})?;
Self::deposit_event(Event::<T>::NetworkRateLimitDelayUpdated {
chain_id,
rate_limit_delay,
});
Ok(())
}
/// Update existent network default max distance between blocks. /// Update existent network default max distance between blocks.
pub fn do_update_network_block_distance( pub fn do_update_network_block_distance(
chain_id: T::NetworkId, chain_id: T::NetworkId,
@ -559,10 +527,8 @@ impl<T: Config> Pallet<T> {
chain_id: T::NetworkId, chain_id: T::NetworkId,
gatekeeper: Vec<u8>, gatekeeper: Vec<u8>,
) -> DispatchResult { ) -> DispatchResult {
ensure!( ensure!(gatekeeper.len() == 42 && gatekeeper[0] == 48 && gatekeeper[1] == 120,
gatekeeper.len() == 42 && gatekeeper[0] == 48 && gatekeeper[1] == 120, Error::<T>::WrongGatekeeperAddress);
Error::<T>::WrongGatekeeperAddress
);
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult { Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist); ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
let net = maybe_network.as_mut().unwrap(); let net = maybe_network.as_mut().unwrap();
@ -582,10 +548,8 @@ impl<T: Config> Pallet<T> {
chain_id: T::NetworkId, chain_id: T::NetworkId,
topic_name: Vec<u8>, topic_name: Vec<u8>,
) -> DispatchResult { ) -> DispatchResult {
ensure!( ensure!(topic_name.len() == 66 && topic_name[0] == 48 && topic_name[1] == 120,
topic_name.len() == 66 && topic_name[0] == 48 && topic_name[1] == 120, Error::<T>::WrongTopicName);
Error::<T>::WrongTopicName
);
Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult { Networks::<T>::try_mutate(&chain_id, |maybe_network| -> DispatchResult {
ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist); ensure!(maybe_network.is_some(), Error::<T>::NetworkDoesNotExist);
let net = maybe_network.as_mut().unwrap(); let net = maybe_network.as_mut().unwrap();
@ -668,15 +632,14 @@ impl<T: Config> NetworkDataMutateHandler<NetworkData, BalanceOf<T>> for Pallet<T
network_id: &T::NetworkId, network_id: &T::NetworkId,
amount: &BalanceOf<T>, amount: &BalanceOf<T>,
) -> Result<BalanceOf<T>, ()> { ) -> Result<BalanceOf<T>, ()> {
let new_gatekeeper_amount = let new_gatekeeper_amount = GatekeeperAmount::<T>::mutate(network_id, |gatekeeper_amount| {
GatekeeperAmount::<T>::mutate(network_id, |gatekeeper_amount| match gatekeeper_amount match gatekeeper_amount.checked_add(amount) {
.checked_add(amount)
{
Some(value) => { Some(value) => {
*gatekeeper_amount = value; *gatekeeper_amount = value;
Ok(value) Ok(value)
},
None => Err(())
} }
None => Err(()),
})?; })?;
Ok(new_gatekeeper_amount) Ok(new_gatekeeper_amount)
@ -686,15 +649,14 @@ impl<T: Config> NetworkDataMutateHandler<NetworkData, BalanceOf<T>> for Pallet<T
network_id: &T::NetworkId, network_id: &T::NetworkId,
amount: &BalanceOf<T>, amount: &BalanceOf<T>,
) -> Result<BalanceOf<T>, ()> { ) -> Result<BalanceOf<T>, ()> {
let new_gatekeeper_amount = let new_gatekeeper_amount = GatekeeperAmount::<T>::mutate(network_id, |gatekeeper_amount| {
GatekeeperAmount::<T>::mutate(network_id, |gatekeeper_amount| match gatekeeper_amount match gatekeeper_amount.checked_sub(amount) {
.checked_sub(amount)
{
Some(value) => { Some(value) => {
*gatekeeper_amount = value; *gatekeeper_amount = value;
Ok(value) Ok(value)
},
None => Err(())
} }
None => Err(()),
})?; })?;
Ok(new_gatekeeper_amount) Ok(new_gatekeeper_amount)
@ -706,8 +668,8 @@ impl<T: Config> NetworkDataMutateHandler<NetworkData, BalanceOf<T>> for Pallet<T
Some(value) => { Some(value) => {
(*bridged_imbalance).bridged_out = value; (*bridged_imbalance).bridged_out = value;
Ok(value) Ok(value)
} },
None => Err(()), None => Err(())
} }
})?; })?;
@ -720,8 +682,8 @@ impl<T: Config> NetworkDataMutateHandler<NetworkData, BalanceOf<T>> for Pallet<T
Some(value) => { Some(value) => {
(*bridged_imbalance).bridged_in = value; (*bridged_imbalance).bridged_in = value;
Ok(value) Ok(value)
} },
None => Err(()), None => Err(())
} }
})?; })?;
@ -734,7 +696,7 @@ impl<T: Config> NetworkDataMutateHandler<NetworkData, BalanceOf<T>> for Pallet<T
Some(value) => { Some(value) => {
*accumulated = value; *accumulated = value;
Ok(value) Ok(value)
} },
None => Err(()), None => Err(()),
} }
}) })

View File

@ -1,16 +1,17 @@
use crate::{self as ghost_networks}; use crate::{self as ghost_networks};
use frame_system::EnsureSignedBy;
use frame_support::{ use frame_support::{
construct_runtime, ord_parameter_types, parameter_types, construct_runtime, ord_parameter_types, parameter_types,
traits::{ConstU128, ConstU32, Everything}, traits::{ConstU128, ConstU32, Everything},
}; };
use frame_system::EnsureSignedBy;
pub use primitives::{ pub use primitives::{
AccountId, Balance, BlockNumber, FreezeIdentifier, Hash, Nonce, ReserveIdentifier, AccountId, Balance, Nonce, BlockNumber, Hash,
ReserveIdentifier, FreezeIdentifier,
}; };
use sp_runtime::{ use sp_runtime::{
curve::PiecewiseLinear, curve::PiecewiseLinear,
traits::{AccountIdLookup, BlakeTwo256}, traits::{AccountIdLookup, BlakeTwo256},
BuildStorage, BuildStorage
}; };
parameter_types! { parameter_types! {
@ -95,9 +96,9 @@ impl ghost_networks::Config for Test {
type RuntimeEvent = RuntimeEvent; type RuntimeEvent = RuntimeEvent;
type Currency = Balances; type Currency = Balances;
type NetworkId = u32; type NetworkId = u32;
type RegisterOrigin = EnsureSignedBy<RegistererAccount, AccountId>; type RegisterOrigin = EnsureSignedBy::<RegistererAccount, AccountId>;
type UpdateOrigin = EnsureSignedBy<UpdaterAccount, AccountId>; type UpdateOrigin = EnsureSignedBy::<UpdaterAccount, AccountId>;
type RemoveOrigin = EnsureSignedBy<RemoverAccount, AccountId>; type RemoveOrigin = EnsureSignedBy::<RemoverAccount, AccountId>;
type WeightInfo = crate::weights::SubstrateWeight<Test>; type WeightInfo = crate::weights::SubstrateWeight<Test>;
} }

File diff suppressed because it is too large Load Diff

View File

@ -16,7 +16,7 @@
//! Autogenerated weights for `ghost_networks` //! Autogenerated weights for `ghost_networks`
//! //!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0
//! DATE: 2025-06-19, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! DATE: 2025-06-18, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000` //! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `ghostown`, CPU: `Intel(R) Core(TM) i3-2310M CPU @ 2.10GHz` //! HOSTNAME: `ghostown`, CPU: `Intel(R) Core(TM) i3-2310M CPU @ 2.10GHz`
//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("casper-dev")`, DB CACHE: 1024 //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("casper-dev")`, DB CACHE: 1024
@ -53,7 +53,6 @@ pub trait WeightInfo {
fn update_network_name(n: u32, ) -> Weight; fn update_network_name(n: u32, ) -> Weight;
fn update_network_endpoint(n: u32, ) -> Weight; fn update_network_endpoint(n: u32, ) -> Weight;
fn update_network_finality_delay() -> Weight; fn update_network_finality_delay() -> Weight;
fn update_network_rate_limit_delay() -> Weight;
fn update_network_block_distance() -> Weight; fn update_network_block_distance() -> Weight;
fn update_network_type() -> Weight; fn update_network_type() -> Weight;
fn update_network_gatekeeper() -> Weight; fn update_network_gatekeeper() -> Weight;
@ -70,30 +69,30 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// The range of component `i` is `[1, 20]`. /// The range of component `i` is `[1, 20]`.
/// The range of component `j` is `[1, 150]`. /// The range of component `j` is `[1, 150]`.
fn register_network(_i: u32, j: u32, ) -> Weight { fn register_network(i: u32, j: u32, ) -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `109` // Measured: `109`
// Estimated: `3574` // Estimated: `3574`
// Minimum execution time: 43_753_000 picoseconds. // Minimum execution time: 43_624_000 picoseconds.
Weight::from_parts(45_805_520, 0) Weight::from_parts(44_945_690, 0)
.saturating_add(Weight::from_parts(0, 3574)) .saturating_add(Weight::from_parts(0, 3574))
// Standard Error: 412 // Standard Error: 3_439
.saturating_add(Weight::from_parts(1_586, 0).saturating_mul(j.into())) .saturating_add(Weight::from_parts(15_557, 0).saturating_mul(i.into()))
// Standard Error: 450
.saturating_add(Weight::from_parts(3_508, 0).saturating_mul(j.into()))
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }
/// Storage: `GhostNetworks::Networks` (r:1 w:1) /// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// The range of component `n` is `[1, 20]`. /// The range of component `n` is `[1, 20]`.
fn update_network_name(n: u32, ) -> Weight { fn update_network_name(_n: u32, ) -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 49_412_000 picoseconds. // Minimum execution time: 48_741_000 picoseconds.
Weight::from_parts(50_617_210, 0) Weight::from_parts(50_426_703, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
// Standard Error: 3_074
.saturating_add(Weight::from_parts(6_017, 0).saturating_mul(n.into()))
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }
@ -102,13 +101,13 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// The range of component `n` is `[1, 150]`. /// The range of component `n` is `[1, 150]`.
fn update_network_endpoint(n: u32, ) -> Weight { fn update_network_endpoint(n: u32, ) -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 49_485_000 picoseconds. // Minimum execution time: 49_090_000 picoseconds.
Weight::from_parts(50_716_057, 0) Weight::from_parts(50_734_447, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
// Standard Error: 453 // Standard Error: 863
.saturating_add(Weight::from_parts(4_916, 0).saturating_mul(n.into())) .saturating_add(Weight::from_parts(786, 0).saturating_mul(n.into()))
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }
@ -116,23 +115,11 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_finality_delay() -> Weight { fn update_network_finality_delay() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 48_061_000 picoseconds. // Minimum execution time: 48_107_000 picoseconds.
Weight::from_parts(49_072_000, 0) Weight::from_parts(48_993_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.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: `301`
// Estimated: `3766`
// Minimum execution time: 49_066_000 picoseconds.
Weight::from_parts(52_137_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }
@ -140,11 +127,11 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_block_distance() -> Weight { fn update_network_block_distance() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 48_085_000 picoseconds. // Minimum execution time: 48_277_000 picoseconds.
Weight::from_parts(48_838_000, 0) Weight::from_parts(49_393_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }
@ -152,11 +139,11 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_type() -> Weight { fn update_network_type() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 47_872_000 picoseconds. // Minimum execution time: 47_642_000 picoseconds.
Weight::from_parts(48_972_000, 0) Weight::from_parts(49_212_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }
@ -164,11 +151,11 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_gatekeeper() -> Weight { fn update_network_gatekeeper() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 50_029_000 picoseconds. // Minimum execution time: 49_440_000 picoseconds.
Weight::from_parts(50_768_000, 0) Weight::from_parts(50_315_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }
@ -176,11 +163,11 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_topic_name() -> Weight { fn update_network_topic_name() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 50_151_000 picoseconds. // Minimum execution time: 49_469_000 picoseconds.
Weight::from_parts(51_573_000, 0) Weight::from_parts(50_532_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }
@ -188,11 +175,11 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_incoming_network_fee() -> Weight { fn update_incoming_network_fee() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 48_017_000 picoseconds. // Minimum execution time: 47_858_000 picoseconds.
Weight::from_parts(49_513_000, 0) Weight::from_parts(48_703_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }
@ -200,11 +187,11 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_outgoing_network_fee() -> Weight { fn update_outgoing_network_fee() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 48_714_000 picoseconds. // Minimum execution time: 47_895_000 picoseconds.
Weight::from_parts(49_777_000, 0) Weight::from_parts(49_230_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }
@ -212,11 +199,11 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn remove_network() -> Weight { fn remove_network() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 44_583_000 picoseconds. // Minimum execution time: 44_052_000 picoseconds.
Weight::from_parts(45_681_000, 0) Weight::from_parts(44_612_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }
@ -227,30 +214,30 @@ impl WeightInfo for () {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// The range of component `i` is `[1, 20]`. /// The range of component `i` is `[1, 20]`.
/// The range of component `j` is `[1, 150]`. /// The range of component `j` is `[1, 150]`.
fn register_network(_i: u32, j: u32, ) -> Weight { fn register_network(i: u32, j: u32, ) -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `109` // Measured: `109`
// Estimated: `3574` // Estimated: `3574`
// Minimum execution time: 43_753_000 picoseconds. // Minimum execution time: 43_624_000 picoseconds.
Weight::from_parts(45_805_520, 0) Weight::from_parts(44_945_690, 0)
.saturating_add(Weight::from_parts(0, 3574)) .saturating_add(Weight::from_parts(0, 3574))
// Standard Error: 412 // Standard Error: 3_439
.saturating_add(Weight::from_parts(1_586, 0).saturating_mul(j.into())) .saturating_add(Weight::from_parts(15_557, 0).saturating_mul(i.into()))
// Standard Error: 450
.saturating_add(Weight::from_parts(3_508, 0).saturating_mul(j.into()))
.saturating_add(RocksDbWeight::get().reads(1)) .saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1)) .saturating_add(RocksDbWeight::get().writes(1))
} }
/// Storage: `GhostNetworks::Networks` (r:1 w:1) /// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// The range of component `n` is `[1, 20]`. /// The range of component `n` is `[1, 20]`.
fn update_network_name(n: u32, ) -> Weight { fn update_network_name(_n: u32, ) -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 49_412_000 picoseconds. // Minimum execution time: 48_741_000 picoseconds.
Weight::from_parts(50_617_210, 0) Weight::from_parts(50_426_703, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
// Standard Error: 3_074
.saturating_add(Weight::from_parts(6_017, 0).saturating_mul(n.into()))
.saturating_add(RocksDbWeight::get().reads(1)) .saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1)) .saturating_add(RocksDbWeight::get().writes(1))
} }
@ -259,13 +246,13 @@ impl WeightInfo for () {
/// The range of component `n` is `[1, 150]`. /// The range of component `n` is `[1, 150]`.
fn update_network_endpoint(n: u32, ) -> Weight { fn update_network_endpoint(n: u32, ) -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 49_485_000 picoseconds. // Minimum execution time: 49_090_000 picoseconds.
Weight::from_parts(50_716_057, 0) Weight::from_parts(50_734_447, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
// Standard Error: 453 // Standard Error: 863
.saturating_add(Weight::from_parts(4_916, 0).saturating_mul(n.into())) .saturating_add(Weight::from_parts(786, 0).saturating_mul(n.into()))
.saturating_add(RocksDbWeight::get().reads(1)) .saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1)) .saturating_add(RocksDbWeight::get().writes(1))
} }
@ -273,23 +260,11 @@ impl WeightInfo for () {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_finality_delay() -> Weight { fn update_network_finality_delay() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 48_061_000 picoseconds. // Minimum execution time: 48_107_000 picoseconds.
Weight::from_parts(49_072_000, 0) Weight::from_parts(48_993_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::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: `301`
// Estimated: `3766`
// Minimum execution time: 49_066_000 picoseconds.
Weight::from_parts(52_137_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(RocksDbWeight::get().reads(1)) .saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1)) .saturating_add(RocksDbWeight::get().writes(1))
} }
@ -297,11 +272,11 @@ impl WeightInfo for () {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_block_distance() -> Weight { fn update_network_block_distance() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 48_085_000 picoseconds. // Minimum execution time: 48_277_000 picoseconds.
Weight::from_parts(48_838_000, 0) Weight::from_parts(49_393_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.saturating_add(RocksDbWeight::get().reads(1)) .saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1)) .saturating_add(RocksDbWeight::get().writes(1))
} }
@ -309,11 +284,11 @@ impl WeightInfo for () {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_type() -> Weight { fn update_network_type() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 47_872_000 picoseconds. // Minimum execution time: 47_642_000 picoseconds.
Weight::from_parts(48_972_000, 0) Weight::from_parts(49_212_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.saturating_add(RocksDbWeight::get().reads(1)) .saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1)) .saturating_add(RocksDbWeight::get().writes(1))
} }
@ -321,11 +296,11 @@ impl WeightInfo for () {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_gatekeeper() -> Weight { fn update_network_gatekeeper() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 50_029_000 picoseconds. // Minimum execution time: 49_440_000 picoseconds.
Weight::from_parts(50_768_000, 0) Weight::from_parts(50_315_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.saturating_add(RocksDbWeight::get().reads(1)) .saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1)) .saturating_add(RocksDbWeight::get().writes(1))
} }
@ -333,11 +308,11 @@ impl WeightInfo for () {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_topic_name() -> Weight { fn update_network_topic_name() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 50_151_000 picoseconds. // Minimum execution time: 49_469_000 picoseconds.
Weight::from_parts(51_573_000, 0) Weight::from_parts(50_532_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.saturating_add(RocksDbWeight::get().reads(1)) .saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1)) .saturating_add(RocksDbWeight::get().writes(1))
} }
@ -345,11 +320,11 @@ impl WeightInfo for () {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_incoming_network_fee() -> Weight { fn update_incoming_network_fee() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 48_017_000 picoseconds. // Minimum execution time: 47_858_000 picoseconds.
Weight::from_parts(49_513_000, 0) Weight::from_parts(48_703_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.saturating_add(RocksDbWeight::get().reads(1)) .saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1)) .saturating_add(RocksDbWeight::get().writes(1))
} }
@ -357,11 +332,11 @@ impl WeightInfo for () {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_outgoing_network_fee() -> Weight { fn update_outgoing_network_fee() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 48_714_000 picoseconds. // Minimum execution time: 47_895_000 picoseconds.
Weight::from_parts(49_777_000, 0) Weight::from_parts(49_230_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.saturating_add(RocksDbWeight::get().reads(1)) .saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1)) .saturating_add(RocksDbWeight::get().writes(1))
} }
@ -369,11 +344,11 @@ impl WeightInfo for () {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn remove_network() -> Weight { fn remove_network() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 44_583_000 picoseconds. // Minimum execution time: 44_052_000 picoseconds.
Weight::from_parts(45_681_000, 0) Weight::from_parts(44_612_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.saturating_add(RocksDbWeight::get().reads(1)) .saturating_add(RocksDbWeight::get().reads(1))
.saturating_add(RocksDbWeight::get().writes(1)) .saturating_add(RocksDbWeight::get().writes(1))
} }

View File

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

View File

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

View File

@ -1,57 +0,0 @@
use crate::{Deserialize, Deserializer, Vec, H256};
pub fn de_string_to_bytes<'de, D>(de: D) -> Result<Option<Vec<u8>>, D::Error>
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>,
{
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>,
{
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>,
{
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"))
.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>,
{
let strings: Vec<&str> = Deserialize::deserialize(de)?;
Ok(strings
.iter()
.map(|s| {
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"))
.collect::<Vec<u8>>()
})
.collect::<Vec<Vec<u8>>>())
}

View File

@ -1,49 +0,0 @@
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,
};
const NUMBER_OF_TOPICS: usize = 3;
#[derive(RuntimeDebug, Clone, PartialEq, Deserialize, Encode, Decode)]
pub struct EvmResponse {
#[serde(default)]
id: Option<u32>,
#[serde(default, deserialize_with = "de_string_to_bytes")]
jsonrpc: Option<Vec<u8>>,
#[serde(default, deserialize_with = "de_string_to_bytes")]
pub error: Option<Vec<u8>>,
#[serde(default)]
pub result: Option<EvmResponseType>,
}
#[derive(RuntimeDebug, Clone, PartialEq, Deserialize, Encode, Decode)]
#[serde(untagged)]
pub enum EvmResponseType {
#[serde(deserialize_with = "de_string_to_u64_pure")]
BlockNumber(u64),
TransactionLogs(Vec<Log>),
}
#[derive(RuntimeDebug, Clone, Eq, PartialEq, Ord, PartialOrd, Deserialize, Encode, Decode)]
#[serde(rename_all = "camelCase")]
pub struct Log {
#[serde(default, deserialize_with = "de_string_to_h256")]
pub transaction_hash: Option<H256>,
#[serde(default, deserialize_with = "de_string_to_u64")]
pub block_number: Option<u64>,
#[serde(default, deserialize_with = "de_string_to_vec_of_bytes")]
pub topics: Vec<Vec<u8>>,
pub removed: bool,
}
impl Log {
pub fn is_sufficient(&self) -> bool {
self.transaction_hash.is_some()
&& self.block_number.is_some()
&& self.topics.len() == NUMBER_OF_TOPICS
}
}

View File

@ -3,55 +3,52 @@
use codec::{Decode, Encode, MaxEncodedLen}; use codec::{Decode, Encode, MaxEncodedLen};
use scale_info::TypeInfo; use scale_info::TypeInfo;
use serde::{Deserialize, Deserializer}; use serde::{Deserializer, Deserialize};
pub use pallet::*;
use frame_support::{ use frame_support::{
pallet_prelude::*, pallet_prelude::*,
traits::{ traits::{
tokens::fungible::{Inspect, Mutate}, tokens::fungible::{Inspect, Mutate},
EstimateNextSessionRotation, Get, OneSessionHandler, ValidatorSet, EstimateNextSessionRotation, ValidatorSet, ValidatorSetWithIdentification,
ValidatorSetWithIdentification, OneSessionHandler, Get,
}, },
WeakBoundedVec, WeakBoundedVec,
}; };
use frame_system::{ use frame_system::{
offchain::{SendTransactionTypes, SubmitTransaction}, offchain::{SendTransactionTypes, SubmitTransaction},
pallet_prelude::*, pallet_prelude::*,
}; };
pub use pallet::*;
use sp_core::H256; use sp_core::H256;
use sp_runtime::{ use sp_runtime::{
Perbill, RuntimeAppPublic, RuntimeDebug, SaturatedConversion,
offchain::{ offchain::{
self as rt_offchain, self as rt_offchain, HttpError,
storage::{MutateStorageError, StorageRetrievalError, StorageValueRef}, storage::{MutateStorageError, StorageRetrievalError, StorageValueRef},
storage_lock::{StorageLock, Time},
HttpError,
}, },
traits::{BlockNumberProvider, Convert, Saturating}, traits::{BlockNumberProvider, Convert, Saturating},
Perbill, RuntimeAppPublic, RuntimeDebug, SaturatedConversion, };
use sp_std::{
vec::Vec, prelude::*,
collections::btree_map::BTreeMap,
}; };
use sp_staking::{ use sp_staking::{
offence::{Kind, Offence, ReportOffence}, offence::{Kind, Offence, ReportOffence},
SessionIndex, SessionIndex,
}; };
use sp_std::{collections::btree_map::BTreeMap, prelude::*, vec::Vec};
use ghost_networks::{ use ghost_networks::{
NetworkData, NetworkDataBasicHandler, NetworkDataInspectHandler, NetworkDataMutateHandler, NetworkData, NetworkDataBasicHandler, NetworkDataInspectHandler,
NetworkType, NetworkDataMutateHandler, NetworkType,
}; };
pub mod weights; pub mod weights;
pub use crate::weights::WeightInfo; pub use crate::weights::WeightInfo;
mod benchmarking;
mod mock;
mod tests; mod tests;
mod mock;
mod deserialisations; mod benchmarking;
mod evm_types;
use evm_types::{EvmResponse, EvmResponseType};
pub mod sr25519 { pub mod sr25519 {
mod app_sr25519 { mod app_sr25519 {
@ -73,12 +70,113 @@ const DB_PREFIX: &[u8] = b"slow_clap::";
const FETCH_TIMEOUT_PERIOD: u64 = 3_000; const FETCH_TIMEOUT_PERIOD: u64 = 3_000;
const LOCK_BLOCK_EXPIRATION: u64 = 10; const LOCK_BLOCK_EXPIRATION: u64 = 10;
const NUMBER_OF_TOPICS: usize = 3;
pub type AuthIndex = u32; pub type AuthIndex = u32;
#[derive( #[derive(RuntimeDebug, Clone, PartialEq, Deserialize, Encode, Decode)]
RuntimeDebug, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, MaxEncodedLen, struct EvmResponse {
)] #[serde(default)]
id: Option<u32>,
#[serde(default, deserialize_with = "de_string_to_bytes")]
jsonrpc: Option<Vec<u8>>,
#[serde(default, deserialize_with = "de_string_to_bytes")]
error: Option<Vec<u8>>,
#[serde(default)]
result: Option<EvmResponseType>,
}
#[derive(RuntimeDebug, Clone, PartialEq, Deserialize, Encode, Decode)]
#[serde(untagged)]
enum EvmResponseType {
#[serde(deserialize_with = "de_string_to_u64_pure")]
BlockNumber(u64),
TransactionLogs(Vec<Log>),
}
#[derive(RuntimeDebug, Clone, Eq, PartialEq, Ord, PartialOrd, Deserialize, Encode, Decode)]
#[serde(rename_all = "camelCase")]
struct Log {
#[serde(default, deserialize_with = "de_string_to_h256")]
transaction_hash: Option<H256>,
#[serde(default, deserialize_with = "de_string_to_u64")]
block_number: Option<u64>,
#[serde(default, deserialize_with = "de_string_to_vec_of_bytes")]
topics: Vec<Vec<u8>>,
#[serde(default, deserialize_with = "de_string_to_bytes")]
address: Option<Vec<u8>>,
#[serde(default, deserialize_with = "de_string_to_btree_map")]
data: BTreeMap<u128, u128>,
removed: bool,
}
impl Log {
fn is_sufficient(&self) -> bool {
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> {
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> {
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> {
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> {
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"))
.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> {
let strings: Vec<&str> = Deserialize::deserialize(de)?;
Ok(strings
.iter()
.map(|s| {
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"))
.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> {
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"),
))))
}
#[derive(RuntimeDebug, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, MaxEncodedLen)]
pub struct Clap<AccountId, NetworkId, Balance> { pub struct Clap<AccountId, NetworkId, Balance> {
pub session_index: SessionIndex, pub session_index: SessionIndex,
pub authority_index: AuthIndex, pub authority_index: AuthIndex,
@ -106,14 +204,10 @@ enum OffchainErr<NetworkId> {
RequestUncompleted, RequestUncompleted,
HttpResponseNotOk(u16), HttpResponseNotOk(u16),
ErrorInEvmResponse, ErrorInEvmResponse,
NoStoredNetworks,
NotValidator,
StorageRetrievalError(NetworkId), StorageRetrievalError(NetworkId),
ConcurrentModificationError(NetworkId), ConcurrentModificationError(NetworkId),
UtxoNotImplemented(NetworkId), UtxoNotImplemented(NetworkId),
UnknownNetworkType(NetworkId), UnknownNetworkType(NetworkId),
OffchainTimeoutPeriod(NetworkId),
TooManyRequests(NetworkId),
} }
impl<NetworkId: core::fmt::Debug> core::fmt::Debug for OffchainErr<NetworkId> { impl<NetworkId: core::fmt::Debug> core::fmt::Debug for OffchainErr<NetworkId> {
@ -126,28 +220,25 @@ impl<NetworkId: core::fmt::Debug> core::fmt::Debug for OffchainErr<NetworkId> {
OffchainErr::HttpRequestError(http_error) => match http_error { OffchainErr::HttpRequestError(http_error) => match http_error {
HttpError::DeadlineReached => write!(fmt, "Requested action couldn't been completed within a deadline."), 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::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::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::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::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::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::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::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),
} }
} }
} }
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> = pub type BalanceOf<T> = <<T as Config>::Currency as Inspect<
<<T as Config>::Currency as Inspect<<T as frame_system::Config>::AccountId>>::Balance; <T as frame_system::Config>::AccountId,
>>::Balance;
pub type ValidatorId<T> = <<T as Config>::ValidatorSet as ValidatorSet< pub type ValidatorId<T> = <<T as Config>::ValidatorSet as ValidatorSet<
<T as frame_system::Config>::AccountId, <T as frame_system::Config>::AccountId,
@ -186,9 +277,9 @@ pub mod pallet {
type NextSessionRotation: EstimateNextSessionRotation<BlockNumberFor<Self>>; type NextSessionRotation: EstimateNextSessionRotation<BlockNumberFor<Self>>;
type ValidatorSet: ValidatorSetWithIdentification<Self::AccountId>; type ValidatorSet: ValidatorSetWithIdentification<Self::AccountId>;
type Currency: Inspect<Self::AccountId> + Mutate<Self::AccountId>; type Currency: Inspect<Self::AccountId> + Mutate<Self::AccountId>;
type NetworkDataHandler: NetworkDataBasicHandler type NetworkDataHandler: NetworkDataBasicHandler +
+ NetworkDataInspectHandler<NetworkData> NetworkDataInspectHandler<NetworkData> +
+ NetworkDataMutateHandler<NetworkData, BalanceOf<Self>>; NetworkDataMutateHandler<NetworkData, BalanceOf<Self>>;
type BlockNumberProvider: BlockNumberProvider<BlockNumber = BlockNumberFor<Self>>; type BlockNumberProvider: BlockNumberProvider<BlockNumber = BlockNumberFor<Self>>;
type ReportUnresponsiveness: ReportOffence< type ReportUnresponsiveness: ReportOffence<
Self::AccountId, Self::AccountId,
@ -218,9 +309,7 @@ pub mod pallet {
#[pallet::generate_deposit(pub(super) fn deposit_event)] #[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> { pub enum Event<T: Config> {
AuthoritiesEquilibrium, AuthoritiesEquilibrium,
SomeAuthoritiesTrottling { SomeAuthoritiesTrottling { throttling: Vec<IdentificationTuple<T>> },
throttling: Vec<IdentificationTuple<T>>,
},
Clapped { Clapped {
authority_id: AuthIndex, authority_id: AuthIndex,
network_id: NetworkIdOf<T>, network_id: NetworkIdOf<T>,
@ -258,7 +347,7 @@ pub mod pallet {
NMapKey<Twox64Concat, H256>, NMapKey<Twox64Concat, H256>,
), ),
BoundedBTreeSet<AuthIndex, T::MaxAuthorities>, BoundedBTreeSet<AuthIndex, T::MaxAuthorities>,
ValueQuery, ValueQuery
>; >;
#[pallet::storage] #[pallet::storage]
@ -271,7 +360,7 @@ pub mod pallet {
NMapKey<Twox64Concat, H256>, NMapKey<Twox64Concat, H256>,
), ),
bool, bool,
ValueQuery, ValueQuery
>; >;
#[pallet::storage] #[pallet::storage]
@ -349,25 +438,33 @@ pub mod pallet {
#[pallet::hooks] #[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> { impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn offchain_worker(now: BlockNumberFor<T>) { fn offchain_worker(now: BlockNumberFor<T>) {
match Self::start_slow_clapping(now) { // Only send messages of we are a potential validator.
Ok(iter) => { if sp_io::offchain::is_validator() {
for result in iter.into_iter() { let networks_len = T::NetworkDataHandler::iter().count();
if networks_len == 0 {
log::info!(
target: LOG_TARGET,
"👏 Skipping slow clap at {:?}: no evm networks",
now,
);
} else {
for result in Self::start_slow_clapping(now, networks_len).into_iter().flatten() {
if let Err(e) = result { if let Err(e) = result {
log::info!( log::info!(
target: LOG_TARGET, target: LOG_TARGET,
"👏 Skipping slow clap at {:?}: {:?}", "👏 Skipping slow clap at {:?}: {:?}",
now, now,
e, e,
) );
} }
} }
} }
Err(e) => log::info!( } else {
log::info!(
target: LOG_TARGET, target: LOG_TARGET,
"👏 Could not start slow clap at {:?}: {:?}", "🤥 Not a validator, skipping slow clap at {:?}.",
now, now,
e, );
),
} }
} }
} }
@ -384,8 +481,9 @@ pub mod pallet {
None => return InvalidTransaction::BadSigner.into(), None => return InvalidTransaction::BadSigner.into(),
}; };
let signature_valid = let signature_valid = clap.using_encoded(|encoded_clap| {
clap.using_encoded(|encoded_clap| authority.verify(&encoded_clap, signature)); authority.verify(&encoded_clap, signature)
});
if !signature_valid { if !signature_valid {
return InvalidTransaction::BadProof.into(); return InvalidTransaction::BadProof.into();
@ -405,24 +503,6 @@ pub mod pallet {
} }
impl<T: Config> Pallet<T> { impl<T: Config> Pallet<T> {
fn create_storage_key(first: &[u8], second: &[u8]) -> Vec<u8> {
let mut key = DB_PREFIX.to_vec();
key.extend(first);
key.extend(second);
key
}
fn read_persistent_offchain_storage<R: codec::Decode>(
storage_key: &[u8],
default_value: R,
) -> R {
StorageValueRef::persistent(&storage_key)
.get::<R>()
.ok()
.flatten()
.unwrap_or(default_value)
}
fn generate_unique_hash( fn generate_unique_hash(
receiver: &T::AccountId, receiver: &T::AccountId,
amount: &BalanceOf<T>, amount: &BalanceOf<T>,
@ -435,47 +515,14 @@ impl<T: Config> Pallet<T> {
H256::from_slice(&sp_io::hashing::keccak_256(&clap_args_str)[..]) H256::from_slice(&sp_io::hashing::keccak_256(&clap_args_str)[..])
} }
fn u64_to_hexadecimal_bytes(value: u64) -> Vec<u8> {
let mut hex_str = Vec::new();
hex_str.push(b'0');
hex_str.push(b'x');
if value == 0 {
hex_str.push(b'0');
return hex_str;
}
for i in (0..16).rev() {
let nibble = (value >> (i * 4)) & 0xF;
if nibble != 0 || hex_str.len() > 2 {
hex_str.push(match nibble {
0..=9 => b'0' + nibble as u8,
10..=15 => b'a' + (nibble - 10) as u8,
_ => unreachable!(),
});
}
}
hex_str
}
fn try_slow_clap(clap: &Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>) -> DispatchResult { fn try_slow_clap(clap: &Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>) -> DispatchResult {
let authorities = Authorities::<T>::get(&clap.session_index); let authorities = Authorities::<T>::get(&clap.session_index);
ensure!( ensure!(authorities.get(clap.authority_index as usize).is_some(), Error::<T>::NotAnAuthority);
authorities.get(clap.authority_index as usize).is_some(),
Error::<T>::NotAnAuthority
);
let clap_unique_hash = let clap_unique_hash = Self::generate_unique_hash(&clap.receiver, &clap.amount, &clap.network_id);
Self::generate_unique_hash(&clap.receiver, &clap.amount, &clap.network_id); let received_claps_key = (clap.session_index, &clap.transaction_hash, &clap_unique_hash);
let received_claps_key = (
clap.session_index,
&clap.transaction_hash,
&clap_unique_hash,
);
let number_of_received_claps = let number_of_received_claps = ReceivedClaps::<T>::try_mutate(&received_claps_key, |tree_of_claps| {
ReceivedClaps::<T>::try_mutate(&received_claps_key, |tree_of_claps| {
let number_of_claps = tree_of_claps.len(); let number_of_claps = tree_of_claps.len();
match (tree_of_claps.contains(&clap.authority_index), clap.removed) { match (tree_of_claps.contains(&clap.authority_index), clap.removed) {
(true, true) => tree_of_claps (true, true) => tree_of_claps
@ -492,21 +539,14 @@ impl<T: Config> Pallet<T> {
})?; })?;
ClapsInSession::<T>::try_mutate(&clap.session_index, |claps_details| { ClapsInSession::<T>::try_mutate(&clap.session_index, |claps_details| {
if claps_details if claps_details.get(&clap.authority_index).map(|x| x.disabled).unwrap_or_default() {
.get(&clap.authority_index)
.map(|x| x.disabled)
.unwrap_or_default()
{
return Err(Error::<T>::CurrentValidatorIsDisabled); return Err(Error::<T>::CurrentValidatorIsDisabled);
} }
(*claps_details) (*claps_details)
.entry(clap.authority_index) .entry(clap.authority_index)
.and_modify(|individual| (*individual).claps.saturating_inc()) .and_modify(|individual| (*individual).claps.saturating_inc())
.or_insert(SessionAuthorityInfo { .or_insert(SessionAuthorityInfo { claps: 1u32, disabled: false });
claps: 1u32,
disabled: false,
});
Ok(()) Ok(())
})?; })?;
@ -519,18 +559,19 @@ impl<T: Config> Pallet<T> {
amount: clap.amount, amount: clap.amount,
}); });
let enough_authorities = let enough_authorities = Perbill::from_rational(
Perbill::from_rational(number_of_received_claps as u32, authorities.len() as u32) number_of_received_claps as u32,
> Perbill::from_percent(T::ApplauseThreshold::get()); authorities.len() as u32,
) > Perbill::from_percent(T::ApplauseThreshold::get());
if enough_authorities { if enough_authorities {
let _ = Self::try_applause(&clap, &received_claps_key).inspect_err(|error_msg| { if let Err(error_msg) = Self::try_applause(&clap, &received_claps_key) {
log::info!( log::info!(
target: LOG_TARGET, target: LOG_TARGET,
"👏 Could not applause because of: {:?}", "👏 Could not applause because of: {:?}",
error_msg, error_msg,
) );
}); }
} }
Ok(()) Ok(())
@ -542,7 +583,7 @@ impl<T: Config> Pallet<T> {
) -> DispatchResult { ) -> DispatchResult {
ApplausesForTransaction::<T>::try_mutate(received_claps_key, |is_applaused| { ApplausesForTransaction::<T>::try_mutate(received_claps_key, |is_applaused| {
if *is_applaused || T::NetworkDataHandler::is_nullification_period() { if *is_applaused || T::NetworkDataHandler::is_nullification_period() {
return Ok(()); return Ok(())
} }
let commission = T::NetworkDataHandler::get(&clap.network_id) let commission = T::NetworkDataHandler::get(&clap.network_id)
@ -551,8 +592,7 @@ impl<T: Config> Pallet<T> {
.mul_ceil(clap.amount); .mul_ceil(clap.amount);
let final_amount = clap.amount.saturating_sub(commission); let final_amount = clap.amount.saturating_sub(commission);
let _ = let _ = T::NetworkDataHandler::increase_gatekeeper_amount(&clap.network_id, &clap.amount)
T::NetworkDataHandler::increase_gatekeeper_amount(&clap.network_id, &clap.amount)
.map_err(|_| Error::<T>::CouldNotIncreaseGatekeeperAmount)?; .map_err(|_| Error::<T>::CouldNotIncreaseGatekeeperAmount)?;
let _ = T::NetworkDataHandler::accumulate_incoming_imbalance(&final_amount) let _ = T::NetworkDataHandler::accumulate_incoming_imbalance(&final_amount)
.map_err(|_| Error::<T>::CouldNotAccumulateIncomingImbalance)?; .map_err(|_| Error::<T>::CouldNotAccumulateIncomingImbalance)?;
@ -560,7 +600,10 @@ impl<T: Config> Pallet<T> {
.map_err(|_| Error::<T>::CouldNotAccumulateCommission)?; .map_err(|_| Error::<T>::CouldNotAccumulateCommission)?;
if final_amount > T::Currency::minimum_balance() { 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; *is_applaused = true;
@ -581,7 +624,7 @@ impl<T: Config> Pallet<T> {
transaction_hash: H256, transaction_hash: H256,
receiver: T::AccountId, receiver: T::AccountId,
amount: BalanceOf<T>, amount: BalanceOf<T>,
) -> DispatchResult { ) -> DispatchResult{
let clap_unique_hash = Self::generate_unique_hash(&receiver, &amount, &network_id); let clap_unique_hash = Self::generate_unique_hash(&receiver, &amount, &network_id);
let received_claps_key = (session_index, &transaction_hash, &clap_unique_hash); let received_claps_key = (session_index, &transaction_hash, &clap_unique_hash);
@ -609,65 +652,14 @@ impl<T: Config> Pallet<T> {
fn start_slow_clapping( fn start_slow_clapping(
block_number: BlockNumberFor<T>, block_number: BlockNumberFor<T>,
networks_len: usize,
) -> OffchainResult<T, impl Iterator<Item = OffchainResult<T, ()>>> { ) -> OffchainResult<T, impl Iterator<Item = OffchainResult<T, ()>>> {
sp_io::offchain::is_validator()
.then(|| ())
.ok_or(OffchainErr::NotValidator)?;
let session_index = T::ValidatorSet::session_index(); let session_index = T::ValidatorSet::session_index();
let networks_len = T::NetworkDataHandler::iter().count();
let network_in_use = T::NetworkDataHandler::iter() let network_in_use = T::NetworkDataHandler::iter()
.nth( .nth(block_number.into().as_usize() % networks_len)
block_number .expect("network should exist; qed");
.into()
.as_usize()
.checked_rem(networks_len)
.unwrap_or_default(),
)
.ok_or(OffchainErr::NoStoredNetworks)?;
let network_id_encoded = network_in_use.0.encode(); Ok(Self::local_authorities().map(move |(authority_index, authority_key)| {
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,
network_in_use.1.rate_limit_delay,
);
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 mut network_lock = StorageLock::<Time>::with_deadline(&network_lock_key, block_until);
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()
}
})?;
Ok(
Self::local_authorities(&session_index).map(move |(authority_index, authority_key)| {
Self::do_evm_claps_or_save_block( Self::do_evm_claps_or_save_block(
authority_index, authority_index,
authority_key, authority_key,
@ -675,8 +667,14 @@ impl<T: Config> Pallet<T> {
network_in_use.0, network_in_use.0,
&network_in_use.1, &network_in_use.1,
) )
}), }))
) }
fn create_storage_key(first: &[u8], second: &[u8]) -> Vec<u8> {
let mut key = DB_PREFIX.to_vec();
key.extend(first);
key.extend(second);
key
} }
fn do_evm_claps_or_save_block( fn do_evm_claps_or_save_block(
@ -692,35 +690,28 @@ impl<T: Config> Pallet<T> {
let block_distance_key = Self::create_storage_key(b"block-distance-", &network_id_encoded); let block_distance_key = Self::create_storage_key(b"block-distance-", &network_id_encoded);
let endpoint_key = Self::create_storage_key(b"endpoint-", &network_id_encoded); let endpoint_key = Self::create_storage_key(b"endpoint-", &network_id_encoded);
let rpc_endpoint = Self::read_persistent_offchain_storage( let rpc_endpoint = StorageValueRef::persistent(&endpoint_key)
&endpoint_key, .get()
network_data.default_endpoint.clone(), .ok()
); .flatten()
let max_block_distance = Self::read_persistent_offchain_storage( .unwrap_or(network_data.default_endpoint.clone());
&block_distance_key,
network_data.block_distance,
);
StorageValueRef::persistent(&block_number_key) let max_block_distance = StorageValueRef::persistent(&block_distance_key)
.mutate( .get()
|result_block_range: Result<Option<(u64, u64)>, StorageRetrievalError>| { .ok()
.flatten()
.unwrap_or(network_data.block_distance);
let mutation_result = StorageValueRef::persistent(&block_number_key).mutate(|result_block_range: Result<Option<(u64, u64)>, StorageRetrievalError>| {
match result_block_range { match result_block_range {
Ok(maybe_block_range) => { Ok(maybe_block_range) => {
let request_body = match maybe_block_range { let request_body = match maybe_block_range {
Some((from_block, to_block)) Some((from_block, to_block)) if from_block < to_block.saturating_sub(1) =>
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_transfers(
from_block,
to_block.saturating_sub(1),
network_data,
)
}
_ => Self::prepare_request_body_for_latest_block(network_data), _ => Self::prepare_request_body_for_latest_block(network_data),
}; };
let response_bytes = let response_bytes = Self::fetch_from_remote(&rpc_endpoint, &request_body)?;
Self::fetch_from_remote(&rpc_endpoint, &request_body)?;
match network_data.network_type { match network_data.network_type {
NetworkType::Evm => { NetworkType::Evm => {
@ -729,56 +720,41 @@ impl<T: Config> Pallet<T> {
authority_index, authority_index,
authority_key, authority_key,
session_index, session_index,
network_id, network_id
)?; )?;
let finality_delay = network_data.finality_delay.unwrap_or_default();
let estimated_block = maybe_new_evm_block let estimated_block = maybe_new_evm_block
.map(|new_evm_block| { .map(|new_evm_block| new_evm_block.saturating_sub(finality_delay))
new_evm_block
.saturating_sub(network_data.finality_delay)
})
.unwrap_or_default(); .unwrap_or_default();
Ok(match maybe_block_range { Ok(match maybe_block_range {
Some((from_block, to_block)) => match maybe_new_evm_block { Some((from_block, to_block)) => match maybe_new_evm_block {
Some(_) => { Some(_) => match estimated_block.checked_sub(from_block) {
match estimated_block.checked_sub(from_block) { Some(current_distance) if current_distance < max_block_distance =>
Some(current_distance) (from_block, estimated_block),
if current_distance _ => (from_block, from_block
< max_block_distance =>
{
(from_block, estimated_block)
}
_ => (
from_block,
from_block
.saturating_add(max_block_distance) .saturating_add(max_block_distance)
.min(estimated_block), .min(estimated_block)),
), },
}
}
None => (to_block, to_block), None => (to_block, to_block),
}, },
None => (estimated_block, estimated_block), None => (estimated_block, estimated_block),
}) })
} },
NetworkType::Utxo => { NetworkType::Utxo => Err(OffchainErr::UtxoNotImplemented(network_id).into()),
Err(OffchainErr::UtxoNotImplemented(network_id).into())
}
_ => Err(OffchainErr::UnknownNetworkType(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 { match mutation_result {
MutateStorageError::ValueFunctionFailed(offchain_error) => offchain_error, Ok(_) => Ok(()),
MutateStorageError::ConcurrentModification(_) => { Err(MutateStorageError::ValueFunctionFailed(offchain_error)) => Err(offchain_error),
OffchainErr::ConcurrentModificationError(network_id).into() Err(MutateStorageError::ConcurrentModification(_)) => Err(OffchainErr::ConcurrentModificationError(network_id).into()),
} }
})
.map(|_| ())
} }
fn apply_evm_response( fn apply_evm_response(
@ -786,7 +762,7 @@ impl<T: Config> Pallet<T> {
authority_index: AuthIndex, authority_index: AuthIndex,
authority_key: T::AuthorityId, authority_key: T::AuthorityId,
session_index: SessionIndex, session_index: SessionIndex,
network_id: NetworkIdOf<T>, network_id: NetworkIdOf<T>
) -> OffchainResult<T, Option<u64>> { ) -> OffchainResult<T, Option<u64>> {
match Self::parse_evm_response(&response_bytes)? { match Self::parse_evm_response(&response_bytes)? {
EvmResponseType::BlockNumber(new_evm_block) => { EvmResponseType::BlockNumber(new_evm_block) => {
@ -797,31 +773,29 @@ impl<T: Config> Pallet<T> {
network_id, network_id,
); );
Ok(Some(new_evm_block)) Ok(Some(new_evm_block))
} },
EvmResponseType::TransactionLogs(evm_logs) => { EvmResponseType::TransactionLogs(evm_logs) => {
let claps: Vec<_> = evm_logs let claps: Vec<_> = evm_logs
.iter() .iter()
.filter_map(|log| { .filter_map(|log| log.is_sufficient().then(|| {
log.is_sufficient().then(|| Clap { Clap {
authority_index, authority_index,
session_index, session_index,
network_id, network_id,
removed: log.removed, removed: log.removed,
receiver: T::AccountId::decode(&mut &log.topics[1][0..32]) receiver: T::AccountId::decode(&mut &log.topics[1][0..32])
.expect("32 bytes always construct an AccountId32"), .expect("32 bytes always construct an AccountId32"),
amount: u128::from_be_bytes( amount: u128::from_be_bytes(log.topics[2][16..32]
log.topics[2][16..32]
.try_into() .try_into()
.expect("amount is valid hex; qed"), .expect("amount is valid hex; qed"))
)
.saturated_into::<BalanceOf<T>>(), .saturated_into::<BalanceOf<T>>(),
transaction_hash: log transaction_hash: log.transaction_hash
.transaction_hash
.clone() .clone()
.expect("tx hash exists; qed"), .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(); .collect();
log::info!( log::info!(
@ -832,8 +806,7 @@ impl<T: Config> Pallet<T> {
); );
for clap in claps { for clap in claps {
let signature = authority_key let signature = authority_key.sign(&clap.encode())
.sign(&clap.encode())
.ok_or(OffchainErr::FailedSigning)?; .ok_or(OffchainErr::FailedSigning)?;
let call = Call::slow_clap { clap, signature }; let call = Call::slow_clap { clap, signature };
@ -846,17 +819,13 @@ impl<T: Config> Pallet<T> {
} }
} }
fn local_authorities( fn local_authorities() -> impl Iterator<Item = (u32, T::AuthorityId)> {
session_index: &SessionIndex, let session_index = T::ValidatorSet::session_index();
) -> impl Iterator<Item = (u32, T::AuthorityId)> { let authorities = Authorities::<T>::get(&session_index);
let authorities = Authorities::<T>::get(session_index);
let mut local_authorities = T::AuthorityId::all(); let mut local_authorities = T::AuthorityId::all();
local_authorities.sort(); local_authorities.sort();
authorities authorities.into_iter().enumerate().filter_map(move |(index, authority)| {
.into_iter()
.enumerate()
.filter_map(move |(index, authority)| {
local_authorities local_authorities
.binary_search(&authority) .binary_search(&authority)
.ok() .ok()
@ -864,14 +833,14 @@ impl<T: Config> Pallet<T> {
}) })
} }
fn fetch_from_remote(rpc_endpoint: &[u8], request_body: &[u8]) -> OffchainResult<T, Vec<u8>> { fn fetch_from_remote(
let rpc_endpoint_str = rpc_endpoint: &[u8],
core::str::from_utf8(rpc_endpoint).expect("rpc endpoint valid str; qed"); request_body: &[u8],
let request_body_str = ) -> OffchainResult<T, Vec<u8>> {
core::str::from_utf8(request_body).expect("request body valid str: qed"); 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() let deadline = sp_io::offchain::timestamp().add(rt_offchain::Duration::from_millis(FETCH_TIMEOUT_PERIOD));
.add(rt_offchain::Duration::from_millis(FETCH_TIMEOUT_PERIOD));
let pending = rt_offchain::http::Request::post(&rpc_endpoint_str, vec![request_body_str]) let pending = rt_offchain::http::Request::post(&rpc_endpoint_str, vec![request_body_str])
.add_header("Accept", "application/json") .add_header("Accept", "application/json")
@ -886,31 +855,47 @@ impl<T: Config> Pallet<T> {
.map_err(|_| OffchainErr::RequestUncompleted)?; .map_err(|_| OffchainErr::RequestUncompleted)?;
if response.code != 200 { if response.code != 200 {
return Err(OffchainErr::HttpResponseNotOk(response.code)); return Err(OffchainErr::HttpResponseNotOk(response.code))
} }
Ok(response.body().collect::<Vec<u8>>()) Ok(response.body().collect::<Vec<u8>>())
} }
fn u64_to_hexadecimal_bytes(value: u64) -> Vec<u8> {
let mut hex_str = Vec::new();
hex_str.push(b'0');
hex_str.push(b'x');
if value == 0 {
hex_str.push(b'0');
return hex_str;
}
for i in (0..16).rev() {
let nibble = (value >> (i * 4)) & 0xF;
if nibble != 0 || hex_str.len() > 2 {
hex_str.push(match nibble {
0..=9 => b'0' + nibble as u8,
10..=15 => b'a' + (nibble - 10) as u8,
_ => unreachable!(),
});
}
}
hex_str
}
fn prepare_request_body_for_latest_block(network_data: &NetworkData) -> Vec<u8> { fn prepare_request_body_for_latest_block(network_data: &NetworkData) -> Vec<u8> {
match network_data.network_type { match network_data.network_type {
NetworkType::Evm => { NetworkType::Evm => b"{\"id\":0,\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\"}".to_vec(),
b"{\"id\":0,\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\"}".to_vec()
}
_ => Default::default(), _ => Default::default(),
} }
} }
fn prepare_request_body_for_latest_transfers( fn prepare_request_body_for_latest_transfers(from_block: u64, to_block: u64, network_data: &NetworkData) -> Vec<u8> {
from_block: u64,
to_block: u64,
network_data: &NetworkData,
) -> Vec<u8> {
match network_data.network_type { match network_data.network_type {
NetworkType::Evm => { NetworkType::Evm => {
let mut body = let mut body = b"{\"id\":0,\"jsonrpc\":\"2.0\",\"method\":\"eth_getLogs\",\"params\":[{".to_vec();
b"{\"id\":0,\"jsonrpc\":\"2.0\",\"method\":\"eth_getLogs\",\"params\":[{"
.to_vec();
body.extend(b"\"fromBlock\":\"".to_vec()); body.extend(b"\"fromBlock\":\"".to_vec());
body.extend(Self::u64_to_hexadecimal_bytes(from_block)); body.extend(Self::u64_to_hexadecimal_bytes(from_block));
body.extend(b"\",\"toBlock\":\"".to_vec()); body.extend(b"\",\"toBlock\":\"".to_vec());
@ -921,7 +906,7 @@ impl<T: Config> Pallet<T> {
body.extend(network_data.topic_name.to_vec()); body.extend(network_data.topic_name.to_vec());
body.extend(b"\"]}]}".to_vec()); body.extend(b"\"]}]}".to_vec());
body body
} },
_ => Default::default(), _ => Default::default(),
} }
} }
@ -930,38 +915,14 @@ impl<T: Config> Pallet<T> {
let response_str = sp_std::str::from_utf8(&response_bytes) let response_str = sp_std::str::from_utf8(&response_bytes)
.map_err(|_| OffchainErr::HttpBytesParsingError)?; .map_err(|_| OffchainErr::HttpBytesParsingError)?;
let response_result: EvmResponse = let response_result: EvmResponse = serde_json::from_str(&response_str)
serde_json::from_str(&response_str).map_err(|_| OffchainErr::HttpJsonParsingError)?; .map_err(|_| OffchainErr::HttpJsonParsingError)?;
if response_result.error.is_some() { if response_result.error.is_some() {
return Err(OffchainErr::ErrorInEvmResponse); return Err(OffchainErr::ErrorInEvmResponse);
} }
Ok(response_result Ok(response_result.result.ok_or(OffchainErr::ErrorInEvmResponse)?)
.result
.ok_or(OffchainErr::ErrorInEvmResponse)?)
}
fn calculate_median_claps(session_index: &SessionIndex) -> u32 {
let mut claps_in_session = ClapsInSession::<T>::get(session_index)
.values()
.filter_map(|value| (!value.disabled).then(|| value.claps))
.collect::<Vec<_>>();
if claps_in_session.is_empty() {
return 0;
}
claps_in_session.sort();
let number_of_claps = claps_in_session.len();
if number_of_claps % 2 == 0 {
let mid_left = claps_in_session[number_of_claps / 2 - 1];
let mid_right = claps_in_session[number_of_claps / 2];
(mid_left + mid_right) / 2
} else {
claps_in_session[number_of_claps / 2]
}
} }
fn is_good_actor( fn is_good_actor(
@ -988,10 +949,7 @@ impl<T: Config> Pallet<T> {
fn initialize_authorities(authorities: Vec<T::AuthorityId>) { fn initialize_authorities(authorities: Vec<T::AuthorityId>) {
let session_index = T::ValidatorSet::session_index(); let session_index = T::ValidatorSet::session_index();
assert!( assert!(Authorities::<T>::get(&session_index).is_empty(), "Authorities are already initilized!");
Authorities::<T>::get(&session_index).is_empty(),
"Authorities are already initilized!"
);
let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities) let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities)
.expect("more than the maximum number of authorities"); .expect("more than the maximum number of authorities");
@ -1007,11 +965,32 @@ impl<T: Config> Pallet<T> {
ClapsInSession::<T>::remove(target_session_index); ClapsInSession::<T>::remove(target_session_index);
let mut cursor = ReceivedClaps::<T>::clear_prefix((target_session_index,), u32::MAX, None); let mut cursor = ReceivedClaps::<T>::clear_prefix((target_session_index,), u32::MAX, None);
debug_assert!(cursor.maybe_cursor.is_none()); debug_assert!(cursor.maybe_cursor.is_none());
cursor = cursor = ApplausesForTransaction::<T>::clear_prefix((target_session_index,), u32::MAX, None);
ApplausesForTransaction::<T>::clear_prefix((target_session_index,), u32::MAX, None);
debug_assert!(cursor.maybe_cursor.is_none()); debug_assert!(cursor.maybe_cursor.is_none());
} }
fn calculate_median_claps(session_index: &SessionIndex) -> u32 {
let mut claps_in_session = ClapsInSession::<T>::get(session_index)
.values()
.filter_map(|value| (!value.disabled).then(|| value.claps))
.collect::<Vec<_>>();
if claps_in_session.is_empty() {
return 0;
}
claps_in_session.sort();
let number_of_claps = claps_in_session.len();
if number_of_claps % 2 == 0 {
let mid_left = claps_in_session[number_of_claps / 2 - 1];
let mid_right = claps_in_session[number_of_claps / 2];
(mid_left + mid_right) / 2
} else {
claps_in_session[number_of_claps / 2]
}
}
#[cfg(test)] #[cfg(test)]
fn set_test_authorities(session_index: SessionIndex, authorities: Vec<T::AuthorityId>) { fn set_test_authorities(session_index: SessionIndex, authorities: Vec<T::AuthorityId>) {
let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities) let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities)
@ -1076,16 +1055,10 @@ impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
if offenders.is_empty() { if offenders.is_empty() {
Self::deposit_event(Event::<T>::AuthoritiesEquilibrium); Self::deposit_event(Event::<T>::AuthoritiesEquilibrium);
} else { } else {
Self::deposit_event(Event::<T>::SomeAuthoritiesTrottling { Self::deposit_event(Event::<T>::SomeAuthoritiesTrottling { throttling: offenders.clone() });
throttling: offenders.clone(),
});
let validator_set_count = authorities.len() as u32; let validator_set_count = authorities.len() as u32;
let offence = ThrottlingOffence { let offence = ThrottlingOffence { session_index, validator_set_count, offenders };
session_index,
validator_set_count,
offenders,
};
if let Err(e) = T::ReportUnresponsiveness::report_offence(vec![], offence) { if let Err(e) = T::ReportUnresponsiveness::report_offence(vec![], offence) {
sp_runtime::print(e) sp_runtime::print(e)
} }
@ -1098,10 +1071,7 @@ impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
(*claps_details) (*claps_details)
.entry(validator_index as AuthIndex) .entry(validator_index as AuthIndex)
.and_modify(|individual| (*individual).disabled = true) .and_modify(|individual| (*individual).disabled = true)
.or_insert(SessionAuthorityInfo { .or_insert(SessionAuthorityInfo { claps: 0u32, disabled: true });
claps: 0u32,
disabled: true,
});
}); });
} }
} }
@ -1111,7 +1081,7 @@ impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
pub struct ThrottlingOffence<Offender> { pub struct ThrottlingOffence<Offender> {
pub session_index: SessionIndex, pub session_index: SessionIndex,
pub validator_set_count: u32, pub validator_set_count: u32,
pub offenders: Vec<Offender>, pub offenders: Vec<Offender>
} }
impl<Offender: Clone> Offence<Offender> for ThrottlingOffence<Offender> { impl<Offender: Clone> Offence<Offender> for ThrottlingOffence<Offender> {

View File

@ -2,15 +2,13 @@
use frame_support::{ use frame_support::{
derive_impl, parameter_types, derive_impl, parameter_types,
traits::{ConstU32, ConstU64}, traits::{ConstU32, ConstU64}, weights::Weight,
weights::Weight,
}; };
use frame_system::EnsureRoot; use frame_system::EnsureRoot;
use pallet_session::historical as pallet_session_historical; use pallet_session::historical as pallet_session_historical;
use sp_runtime::{ use sp_runtime::{
curve::PiecewiseLinear,
testing::{TestXt, UintAuthorityId}, testing::{TestXt, UintAuthorityId},
traits::ConvertInto, traits::ConvertInto, curve::PiecewiseLinear,
Permill, Permill,
}; };
use sp_staking::{ use sp_staking::{
@ -55,10 +53,13 @@ impl pallet_session::SessionManager<u64> for TestSessionManager {
impl pallet_session::historical::SessionManager<u64, u64> for TestSessionManager { impl pallet_session::historical::SessionManager<u64, u64> for TestSessionManager {
fn new_session(_new_index: SessionIndex) -> Option<Vec<(u64, u64)>> { fn new_session(_new_index: SessionIndex) -> Option<Vec<(u64, u64)>> {
Validators::mutate(|l| { Validators::mutate(|l| l
l.take() .take()
.map(|validators| validators.iter().map(|v| (*v, *v)).collect()) .map(|validators| validators
}) .iter()
.map(|v| (*v, *v))
.collect())
)
} }
fn end_session(_: SessionIndex) {} fn end_session(_: SessionIndex) {}
fn start_session(_: SessionIndex) {} fn start_session(_: SessionIndex) {}
@ -93,10 +94,11 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
result.execute_with(|| { result.execute_with(|| {
for i in 1..=3 { for i in 1..=3 {
System::inc_providers(&i); System::inc_providers(&i);
assert_eq!( assert_eq!(Session::set_keys(
Session::set_keys(RuntimeOrigin::signed(i), i.into(), vec![],), RuntimeOrigin::signed(i),
Ok(()) i.into(),
); vec![],
), Ok(()));
} }
}); });
@ -255,7 +257,8 @@ pub fn advance_session_with_authority(authority: u64) {
UintAuthorityId::from(69), UintAuthorityId::from(69),
UintAuthorityId::from(420), UintAuthorityId::from(420),
UintAuthorityId::from(1337), UintAuthorityId::from(1337),
], ]
); );
assert_eq!(session_index, (now / Period::get()) as u32); 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::{ use sp_core::offchain::{
testing, testing,
testing::{TestOffchainExt, TestTransactionPoolExt}, testing::{TestOffchainExt, TestTransactionPoolExt},
OffchainDbExt, OffchainWorkerExt, TransactionPoolExt, OffchainWorkerExt, OffchainDbExt, TransactionPoolExt,
}; };
use sp_runtime::{testing::UintAuthorityId, DispatchError}; use sp_runtime::{DispatchError, testing::UintAuthorityId};
use ghost_networks::BridgedInflationCurve; use ghost_networks::BridgedInflationCurve;
use pallet_staking::EraPayout; use pallet_staking::EraPayout;
@ -23,8 +23,7 @@ fn prepare_evm_network(
let network_data = NetworkData { let network_data = NetworkData {
chain_name: "Ethereum".into(), chain_name: "Ethereum".into(),
default_endpoint: get_rpc_endpoint(), default_endpoint: get_rpc_endpoint(),
finality_delay: 69, finality_delay: Some(69),
rate_limit_delay: 69,
block_distance: 69, block_distance: 69,
network_type: ghost_networks::NetworkType::Evm, network_type: ghost_networks::NetworkType::Evm,
gatekeeper: get_gatekeeper(), gatekeeper: get_gatekeeper(),
@ -36,8 +35,7 @@ fn prepare_evm_network(
assert_ok!(Networks::register_network( assert_ok!(Networks::register_network(
RuntimeOrigin::root(), RuntimeOrigin::root(),
maybe_network_id.unwrap_or(1u32), maybe_network_id.unwrap_or(1u32),
network_data.clone() network_data.clone()));
));
network_data network_data
} }
@ -109,14 +107,8 @@ fn test_throttling_slash_function() {
assert_eq!(dummy_offence.slash_fraction(1), Perbill::zero()); assert_eq!(dummy_offence.slash_fraction(1), Perbill::zero());
assert_eq!(dummy_offence.slash_fraction(5), Perbill::zero()); assert_eq!(dummy_offence.slash_fraction(5), Perbill::zero());
assert_eq!( assert_eq!(dummy_offence.slash_fraction(7), Perbill::from_parts(4200000));
dummy_offence.slash_fraction(7), assert_eq!(dummy_offence.slash_fraction(17), Perbill::from_parts(46200000));
Perbill::from_parts(4200000)
);
assert_eq!(
dummy_offence.slash_fraction(17),
Perbill::from_parts(46200000)
);
} }
#[test] #[test]
@ -128,10 +120,8 @@ fn request_body_is_correct_for_get_block_number() {
t.execute_with(|| { t.execute_with(|| {
let network_data = prepare_evm_network(Some(1), None); let network_data = prepare_evm_network(Some(1), None);
let request_body = SlowClap::prepare_request_body_for_latest_block(&network_data); let request_body = SlowClap::prepare_request_body_for_latest_block(&network_data);
assert_eq!( assert_eq!(core::str::from_utf8(&request_body).unwrap(),
core::str::from_utf8(&request_body).unwrap(), r#"{"id":0,"jsonrpc":"2.0","method":"eth_blockNumber"}"#);
r#"{"id":0,"jsonrpc":"2.0","method":"eth_blockNumber"}"#
);
}); });
} }
@ -186,10 +176,7 @@ fn should_make_http_call_for_logs() {
let network_data = prepare_evm_network(Some(1), None); let network_data = prepare_evm_network(Some(1), None);
let request_body = SlowClap::prepare_request_body_for_latest_transfers( let request_body = SlowClap::prepare_request_body_for_latest_transfers(
from_block, from_block, to_block, &network_data);
to_block,
&network_data,
);
let raw_response = SlowClap::fetch_from_remote(&rpc_endpoint, &request_body)?; let raw_response = SlowClap::fetch_from_remote(&rpc_endpoint, &request_body)?;
assert_eq!(raw_response.len(), 1805); // precalculated assert_eq!(raw_response.len(), 1805); // precalculated
Ok(()) Ok(())
@ -210,8 +197,7 @@ fn should_make_http_call_and_parse_block_number() {
let request_body = SlowClap::prepare_request_body_for_latest_block(&network_data); let request_body = SlowClap::prepare_request_body_for_latest_block(&network_data);
let raw_response = SlowClap::fetch_from_remote(&rpc_endpoint, &request_body)?; let raw_response = SlowClap::fetch_from_remote(&rpc_endpoint, &request_body)?;
let maybe_evm_block_number = let maybe_evm_block_number = SlowClap::apply_evm_response(&raw_response, 69, Default::default(), 420, 1)?;
SlowClap::apply_evm_response(&raw_response, 69, Default::default(), 420, 1)?;
assert_eq!(maybe_evm_block_number, Some(20335745)); assert_eq!(maybe_evm_block_number, Some(20335745));
Ok(()) Ok(())
@ -240,10 +226,7 @@ fn should_make_http_call_and_parse_logs() {
let network_data = prepare_evm_network(Some(network_id), None); let network_data = prepare_evm_network(Some(network_id), None);
let request_body = SlowClap::prepare_request_body_for_latest_transfers( let request_body = SlowClap::prepare_request_body_for_latest_transfers(
from_block, from_block, to_block, &network_data);
to_block,
&network_data,
);
let raw_response = SlowClap::fetch_from_remote(&rpc_endpoint, &request_body)?; let raw_response = SlowClap::fetch_from_remote(&rpc_endpoint, &request_body)?;
match SlowClap::parse_evm_response(&raw_response)? { match SlowClap::parse_evm_response(&raw_response)? {
@ -275,30 +258,21 @@ fn should_clear_sesions_based_on_history_depth() {
let storage_key = (session_index, transaction_hash, unique_transaction_hash); let storage_key = (session_index, transaction_hash, unique_transaction_hash);
assert_claps_info_correct(&storage_key, &session_index, 0); assert_claps_info_correct(&storage_key, &session_index, 0);
assert_eq!( assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), false);
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, 0, false));
assert_ok!(do_clap_from(session_index, network_id, 1, false)); assert_ok!(do_clap_from(session_index, network_id, 1, false));
assert_ok!(do_clap_from(session_index, network_id, 2, false)); assert_ok!(do_clap_from(session_index, network_id, 2, false));
assert_claps_info_correct(&storage_key, &session_index, 3); assert_claps_info_correct(&storage_key, &session_index, 3);
assert_eq!( assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), true);
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
true
);
for _ in 0..history_depth { for _ in 0..history_depth {
advance_session(); advance_session();
} }
assert_claps_info_correct(&storage_key, &session_index, 0); assert_claps_info_correct(&storage_key, &session_index, 0);
assert_eq!( assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), false);
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
false
);
}); });
} }
@ -337,10 +311,7 @@ fn should_increase_gatkeeper_amount_accordingly() {
assert_ok!(do_clap_from(session_index, network_id, 2, false)); assert_ok!(do_clap_from(session_index, network_id, 2, false));
assert_eq!(Networks::gatekeeper_amount(network_id), amount); assert_eq!(Networks::gatekeeper_amount(network_id), amount);
assert_eq!( assert_eq!(Networks::bridged_imbalance().bridged_in, amount.saturating_div(2));
Networks::bridged_imbalance().bridged_in,
amount.saturating_div(2)
);
assert_eq!(Networks::bridged_imbalance().bridged_out, 0); assert_eq!(Networks::bridged_imbalance().bridged_out, 0);
}); });
} }
@ -374,29 +345,18 @@ fn should_applause_and_take_next_claps() {
let session_index = advance_session_and_get_index(); let session_index = advance_session_and_get_index();
let storage_key = (session_index, transaction_hash, unique_transaction_hash); let storage_key = (session_index, transaction_hash, unique_transaction_hash);
assert_eq!( assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), false);
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
false
);
assert_eq!(Balances::balance(&receiver), 0); assert_eq!(Balances::balance(&receiver), 0);
assert_ok!(do_clap_from(session_index, network_id, 0, false)); assert_ok!(do_clap_from(session_index, network_id, 0, false));
assert_eq!( assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), false);
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
false
);
assert_eq!(Balances::balance(&receiver), 0); assert_eq!(Balances::balance(&receiver), 0);
assert_ok!(do_clap_from(session_index, network_id, 1, false)); assert_ok!(do_clap_from(session_index, network_id, 1, false));
assert_eq!( assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), true);
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
true
);
assert_eq!(Balances::balance(&receiver), amount); assert_eq!(Balances::balance(&receiver), amount);
assert_ok!(do_clap_from(session_index, network_id, 2, false)); assert_ok!(do_clap_from(session_index, network_id, 2, false));
assert_eq!( assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), true);
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
true
);
assert_eq!(Balances::balance(&receiver), amount); assert_eq!(Balances::balance(&receiver), amount);
}); });
} }
@ -412,10 +372,8 @@ fn should_throw_error_on_clap_duplication() {
assert_claps_info_correct(&storage_key, &session_index, 0); assert_claps_info_correct(&storage_key, &session_index, 0);
assert_ok!(do_clap_from(session_index, network_id, 0, false)); assert_ok!(do_clap_from(session_index, network_id, 0, false));
assert_claps_info_correct(&storage_key, &session_index, 1); assert_claps_info_correct(&storage_key, &session_index, 1);
assert_err!( assert_err!(do_clap_from(session_index, network_id, 0, false),
do_clap_from(session_index, network_id, 0, false), Error::<Runtime>::AlreadyClapped);
Error::<Runtime>::AlreadyClapped
);
assert_claps_info_correct(&storage_key, &session_index, 1); assert_claps_info_correct(&storage_key, &session_index, 1);
}); });
} }
@ -430,10 +388,8 @@ fn should_throw_error_on_removal_of_unregistered_clap() {
let storage_key = (session_index, transaction_hash, unique_transaction_hash); let storage_key = (session_index, transaction_hash, unique_transaction_hash);
assert_claps_info_correct(&storage_key, &session_index, 0); assert_claps_info_correct(&storage_key, &session_index, 0);
assert_err!( assert_err!(do_clap_from(session_index, network_id, 0, true),
do_clap_from(session_index, network_id, 0, true), Error::<Runtime>::UnregisteredClapRemove);
Error::<Runtime>::UnregisteredClapRemove
);
assert_claps_info_correct(&storage_key, &session_index, 0); assert_claps_info_correct(&storage_key, &session_index, 0);
}); });
} }
@ -463,21 +419,9 @@ fn should_throw_error_if_session_index_is_not_current() {
let session_index_prev = chunk[0].1; let session_index_prev = chunk[0].1;
let session_index_next = chunk[2].1; let session_index_next = chunk[2].1;
let storage_key_curr = ( let storage_key_curr = (session_index_curr, transaction_hash, unique_transaction_hash);
session_index_curr, let storage_key_prev = (session_index_prev, transaction_hash, unique_transaction_hash);
transaction_hash, let storage_key_next = (session_index_next, transaction_hash, unique_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_curr, &session_index_curr, 0);
assert_claps_info_correct(&storage_key_prev, &session_index_prev, 0); assert_claps_info_correct(&storage_key_prev, &session_index_prev, 0);
@ -504,25 +448,14 @@ 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_prev, &session_index_prev, 0);
assert_claps_info_correct(&storage_key_next, &session_index_next, 0); assert_claps_info_correct(&storage_key_next, &session_index_next, 0);
assert_ok!(do_clap_from_first_authority( assert_ok!(do_clap_from_first_authority(session_index_curr, network_id, authority_curr));
session_index_curr, assert_ok!(do_clap_from_first_authority(session_index_prev, network_id, authority_prev));
network_id, assert_ok!(do_clap_from_first_authority(session_index_next, network_id, authority_next));
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_curr, &session_index_curr, 1);
assert_claps_info_correct(&storage_key_prev, &session_index_prev, 1); assert_claps_info_correct(&storage_key_prev, &session_index_prev, 1);
assert_claps_info_correct(&storage_key_next, &session_index_next, 1); assert_claps_info_correct(&storage_key_next, &session_index_next, 1);
} }
}); });
} }
@ -549,10 +482,8 @@ fn should_throw_error_if_signer_has_incorrect_index() {
}; };
let authority = UintAuthorityId::from((1) as u64); let authority = UintAuthorityId::from((1) as u64);
let signature = authority.sign(&clap.encode()).unwrap(); let signature = authority.sign(&clap.encode()).unwrap();
assert_err!( assert_err!(SlowClap::slow_clap(RuntimeOrigin::none(), clap, signature),
SlowClap::slow_clap(RuntimeOrigin::none(), clap, signature), Error::<Runtime>::NotAnAuthority);
Error::<Runtime>::NotAnAuthority
);
assert_claps_info_correct(&storage_key, &session_index, 0); assert_claps_info_correct(&storage_key, &session_index, 0);
}); });
} }
@ -568,41 +499,27 @@ fn should_throw_error_if_validator_disabled_and_ignore_later() {
assert_claps_info_correct(&storage_key, &session_index, 0); assert_claps_info_correct(&storage_key, &session_index, 0);
assert_eq!(Session::disable_index(0), true); assert_eq!(Session::disable_index(0), true);
assert_err!( assert_err!(do_clap_from(session_index, network_id, 0, false),
do_clap_from(session_index, network_id, 0, false), Error::<Runtime>::CurrentValidatorIsDisabled);
Error::<Runtime>::CurrentValidatorIsDisabled
);
assert_eq!(pallet::ReceivedClaps::<Runtime>::get(&storage_key).len(), 0); assert_eq!(pallet::ReceivedClaps::<Runtime>::get(&storage_key).len(), 0);
assert_eq!( assert_eq!(pallet::ClapsInSession::<Runtime>::get(&session_index).len(), 1);
pallet::ClapsInSession::<Runtime>::get(&session_index).len(), assert_eq!(pallet::ClapsInSession::<Runtime>::get(&session_index)
1
);
assert_eq!(
pallet::ClapsInSession::<Runtime>::get(&session_index)
.into_iter() .into_iter()
.filter(|(_, v)| !v.disabled) .filter(|(_, v)| !v.disabled)
.collect::<Vec<_>>() .collect::<Vec<_>>()
.len(), .len(), 0);
0
);
assert_ok!(do_clap_from(session_index, network_id, 1, false)); assert_ok!(do_clap_from(session_index, network_id, 1, false));
assert_eq!(Session::disable_index(1), true); assert_eq!(Session::disable_index(1), true);
assert_eq!(pallet::ReceivedClaps::<Runtime>::get(&storage_key).len(), 1); assert_eq!(pallet::ReceivedClaps::<Runtime>::get(&storage_key).len(), 1);
assert_eq!( assert_eq!(pallet::ClapsInSession::<Runtime>::get(&session_index).len(), 2);
pallet::ClapsInSession::<Runtime>::get(&session_index).len(), assert_eq!(pallet::ClapsInSession::<Runtime>::get(&session_index)
2
);
assert_eq!(
pallet::ClapsInSession::<Runtime>::get(&session_index)
.into_iter() .into_iter()
.filter(|(_, v)| !v.disabled) .filter(|(_, v)| !v.disabled)
.collect::<Vec<_>>() .collect::<Vec<_>>()
.len(), .len(), 0);
0
);
}); });
} }
@ -635,10 +552,7 @@ fn should_clap_without_applause_on_gatekeeper_amount_overflow() {
} }
assert_claps_info_correct(&storage_key_first, &session_index, 3); assert_claps_info_correct(&storage_key_first, &session_index, 3);
assert_eq!( assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key_first), true);
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key_first),
true
);
assert_eq!(Balances::balance(&first_receiver), big_amount); assert_eq!(Balances::balance(&first_receiver), big_amount);
assert_eq!(Balances::balance(&second_receiver), 0); assert_eq!(Balances::balance(&second_receiver), 0);
@ -699,10 +613,7 @@ fn should_clap_without_applause_on_commission_overflow() {
} }
assert_claps_info_correct(&storage_key_first, &session_index, 3); assert_claps_info_correct(&storage_key_first, &session_index, 3);
assert_eq!( assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key_first), true);
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key_first),
true
);
assert_eq!(Balances::balance(&first_receiver), big_amount); assert_eq!(Balances::balance(&first_receiver), big_amount);
assert_eq!(Balances::balance(&second_receiver), 0); assert_eq!(Balances::balance(&second_receiver), 0);
@ -750,14 +661,10 @@ fn should_nullify_commission_on_finalize() {
assert_eq!(Networks::accumulated_commission(), amount); assert_eq!(Networks::accumulated_commission(), amount);
assert_eq!(Networks::is_nullification_period(), false); assert_eq!(Networks::is_nullification_period(), false);
assert_eq!( assert_eq!(BridgedInflationCurve::<RewardCurve, Runtime>::era_payout(
BridgedInflationCurve::<RewardCurve, Runtime>::era_payout(
total_staked, total_staked,
total_issuance, total_issuance,
0 0), (420000000000000, 0)); // precomputed values
),
(420000000000000, 0)
); // precomputed values
assert_eq!(Networks::is_nullification_period(), true); assert_eq!(Networks::is_nullification_period(), true);
Networks::on_finalize(System::block_number()); Networks::on_finalize(System::block_number());
@ -781,14 +688,10 @@ fn should_avoid_applause_during_nullification_period() {
let session_index = advance_session_and_get_index(); let session_index = advance_session_and_get_index();
assert_eq!(Networks::is_nullification_period(), false); assert_eq!(Networks::is_nullification_period(), false);
assert_eq!( assert_eq!(BridgedInflationCurve::<RewardCurve, Runtime>::era_payout(
BridgedInflationCurve::<RewardCurve, Runtime>::era_payout(
total_staked, total_staked,
total_issuance, total_issuance,
0 0), (0, 0));
),
(0, 0)
);
assert_eq!(Networks::is_nullification_period(), true); assert_eq!(Networks::is_nullification_period(), true);
assert_ok!(do_clap_from(session_index, network_id, 0, false)); assert_ok!(do_clap_from(session_index, network_id, 0, false));
@ -814,36 +717,25 @@ fn should_self_applause_if_enough_received_claps() {
let session_index = advance_session_and_get_index(); let session_index = advance_session_and_get_index();
let storage_key = (session_index, transaction_hash, unique_transaction_hash); let storage_key = (session_index, transaction_hash, unique_transaction_hash);
assert_err!( assert_err!(SlowClap::self_applause(
SlowClap::self_applause(
RuntimeOrigin::signed(receiver), RuntimeOrigin::signed(receiver),
network_id, network_id,
session_index, session_index,
transaction_hash, transaction_hash,
receiver, receiver,
amount, amount,
), ), Error::<Runtime>::NotEnoughClaps);
Error::<Runtime>::NotEnoughClaps
);
assert_eq!( assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), false);
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
false
);
assert_eq!(Balances::balance(&receiver), 0); assert_eq!(Balances::balance(&receiver), 0);
assert_eq!( assert_eq!(BridgedInflationCurve::<RewardCurve, Runtime>::era_payout(
BridgedInflationCurve::<RewardCurve, Runtime>::era_payout(0, 0, 0), 0, 0, 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, 0, false));
assert_ok!(do_clap_from(session_index, network_id, 1, false)); assert_ok!(do_clap_from(session_index, network_id, 1, false));
assert_ok!(do_clap_from(session_index, network_id, 2, false)); assert_ok!(do_clap_from(session_index, network_id, 2, false));
assert_eq!( assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), false);
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
false
);
assert_eq!(Balances::balance(&receiver), 0); assert_eq!(Balances::balance(&receiver), 0);
assert_ok!(SlowClap::self_applause( assert_ok!(SlowClap::self_applause(
@ -854,10 +746,7 @@ fn should_self_applause_if_enough_received_claps() {
receiver, receiver,
amount, amount,
)); ));
assert_eq!( assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), false);
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
false
);
assert_eq!(Balances::balance(&receiver), 0); assert_eq!(Balances::balance(&receiver), 0);
Networks::on_finalize(System::block_number()); Networks::on_finalize(System::block_number());
@ -870,10 +759,7 @@ fn should_self_applause_if_enough_received_claps() {
receiver, receiver,
amount, amount,
)); ));
assert_eq!( assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), true);
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
true
);
assert_eq!(Balances::balance(&receiver), amount); assert_eq!(Balances::balance(&receiver), amount);
}); });
} }
@ -892,13 +778,11 @@ fn should_emit_event_on_each_clap_and_on_applause() {
let session_index = advance_session_and_get_index(); let session_index = advance_session_and_get_index();
let storage_key = (session_index, transaction_hash, unique_transaction_hash); let storage_key = (session_index, transaction_hash, unique_transaction_hash);
assert_eq!( assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), false);
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
false
);
assert_claps_info_correct(&storage_key, &session_index, 0); assert_claps_info_correct(&storage_key, &session_index, 0);
assert_ok!(do_clap_from(session_index, network_id, 0, false)); assert_ok!(do_clap_from(session_index, network_id, 0, false));
System::assert_last_event(RuntimeEvent::SlowClap(crate::Event::Clapped { System::assert_last_event(RuntimeEvent::SlowClap(
crate::Event::Clapped {
receiver: receiver.clone(), receiver: receiver.clone(),
authority_id: 0, authority_id: 0,
network_id, network_id,
@ -906,40 +790,35 @@ fn should_emit_event_on_each_clap_and_on_applause() {
amount, amount,
})); }));
assert_eq!( assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), false);
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
false
);
assert_claps_info_correct(&storage_key, &session_index, 1); assert_claps_info_correct(&storage_key, &session_index, 1);
assert_ok!(do_clap_from(session_index, network_id, 1, false)); assert_ok!(do_clap_from(session_index, network_id, 1, false));
let binding = System::events(); let binding = System::events();
let last_two_events = binding.iter().rev().take(5).collect::<Vec<_>>(); let last_two_events = binding
assert_eq!( .iter()
last_two_events[0].event, .rev()
RuntimeEvent::SlowClap(crate::Event::Applaused { .take(5)
.collect::<Vec<_>>();
assert_eq!(last_two_events[0].event, RuntimeEvent::SlowClap(
crate::Event::Applaused {
network_id, network_id,
receiver: receiver.clone(), receiver: receiver.clone(),
received_amount: amount_after_commission, received_amount: amount_after_commission,
}) }));
); assert_eq!(last_two_events[4].event, RuntimeEvent::SlowClap(
assert_eq!( crate::Event::Clapped {
last_two_events[4].event,
RuntimeEvent::SlowClap(crate::Event::Clapped {
receiver: receiver.clone(), receiver: receiver.clone(),
authority_id: 1, authority_id: 1,
network_id, network_id,
transaction_hash, transaction_hash,
amount, amount,
}) }));
);
assert_eq!( assert_eq!(pallet::ApplausesForTransaction::<Runtime>::get(&storage_key), true);
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
true
);
assert_claps_info_correct(&storage_key, &session_index, 2); assert_claps_info_correct(&storage_key, &session_index, 2);
assert_ok!(do_clap_from(session_index, network_id, 2, false)); assert_ok!(do_clap_from(session_index, network_id, 2, false));
System::assert_last_event(RuntimeEvent::SlowClap(crate::Event::Clapped { System::assert_last_event(RuntimeEvent::SlowClap(
crate::Event::Clapped {
receiver: receiver.clone(), receiver: receiver.clone(),
authority_id: 2, authority_id: 2,
network_id, network_id,
@ -951,8 +830,8 @@ fn should_emit_event_on_each_clap_and_on_applause() {
#[test] #[test]
fn should_not_fail_on_sub_existential_balance() { fn should_not_fail_on_sub_existential_balance() {
let (network_id, transaction_hash, unique_transaction_hash) = let (network_id, transaction_hash, unique_transaction_hash)
generate_unique_hash(None, None, None, None); = generate_unique_hash(None, None, None, None);
let (_, receiver, amount) = get_mocked_metadata(); let (_, receiver, amount) = get_mocked_metadata();
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
@ -965,10 +844,7 @@ fn should_not_fail_on_sub_existential_balance() {
assert_eq!(Networks::bridged_imbalance().bridged_in, 0); assert_eq!(Networks::bridged_imbalance().bridged_in, 0);
assert_eq!(Networks::bridged_imbalance().bridged_out, 0); assert_eq!(Networks::bridged_imbalance().bridged_out, 0);
assert_eq!(Balances::balance(&receiver), 0); assert_eq!(Balances::balance(&receiver), 0);
assert_eq!( assert_eq!(SlowClap::applauses_for_transaction(&received_claps_key), false);
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, 0, false));
assert_ok!(do_clap_from(session_index, network_id, 1, false)); assert_ok!(do_clap_from(session_index, network_id, 1, false));
@ -979,10 +855,7 @@ fn should_not_fail_on_sub_existential_balance() {
assert_eq!(Networks::bridged_imbalance().bridged_in, 0); assert_eq!(Networks::bridged_imbalance().bridged_in, 0);
assert_eq!(Networks::bridged_imbalance().bridged_out, 0); assert_eq!(Networks::bridged_imbalance().bridged_out, 0);
assert_eq!(Balances::balance(&receiver), 0); assert_eq!(Balances::balance(&receiver), 0);
assert_eq!( assert_eq!(SlowClap::applauses_for_transaction(&received_claps_key), true);
SlowClap::applauses_for_transaction(&received_claps_key),
true
);
}); });
} }
@ -1007,34 +880,40 @@ fn generate_unique_hash(
let receiver = maybe_receiver.unwrap_or(receiver); let receiver = maybe_receiver.unwrap_or(receiver);
let amount = maybe_amount.unwrap_or(amount); 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) (network_id, transaction_hash, unique_transaction_hash)
} }
fn assert_claps_info_correct(storage_key: &(u32, H256, H256), session_index: &u32, index: usize) { fn assert_claps_info_correct(
assert_eq!( storage_key: &(u32, H256, H256),
pallet::ReceivedClaps::<Runtime>::get(storage_key).len(), session_index: &u32,
index index: usize,
); ) {
assert_eq!( assert_eq!(pallet::ReceivedClaps::<Runtime>::get(storage_key).len(), index);
pallet::ClapsInSession::<Runtime>::get(session_index).len(), assert_eq!(pallet::ClapsInSession::<Runtime>::get(session_index).len(), index);
index
);
} }
fn assert_transaction_has_bad_signature(session_index: u32, network_id: u32, authority: u64) { fn assert_transaction_has_bad_signature(
assert_err!( session_index: u32,
do_clap_from_first_authority(session_index, network_id, authority), network_id: u32,
DispatchError::Other("Transaction has a bad signature") 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) { fn assert_invalid_signing_address(
assert_err!( session_index: u32,
do_clap_from(session_index, network_id, authority_index, false), network_id: u32,
DispatchError::Other("Invalid signing address") 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> { fn get_rpc_endpoint() -> Vec<u8> {

View File

@ -16,7 +16,7 @@
//! Autogenerated weights for `ghost_slow_clap` //! Autogenerated weights for `ghost_slow_clap`
//! //!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0
//! DATE: 2025-06-19, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! DATE: 2025-06-17, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000` //! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `ghostown`, CPU: `Intel(R) Core(TM) i3-2310M CPU @ 2.10GHz` //! HOSTNAME: `ghostown`, CPU: `Intel(R) Core(TM) i3-2310M CPU @ 2.10GHz`
//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("casper-dev")`, DB CACHE: 1024 //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("casper-dev")`, DB CACHE: 1024
@ -78,8 +78,8 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `355` // Measured: `355`
// Estimated: `3820` // Estimated: `3820`
// Minimum execution time: 213_817_000 picoseconds. // Minimum execution time: 211_154_000 picoseconds.
Weight::from_parts(216_977_000, 0) Weight::from_parts(215_420_000, 0)
.saturating_add(Weight::from_parts(0, 3820)) .saturating_add(Weight::from_parts(0, 3820))
.saturating_add(T::DbWeight::get().reads(10)) .saturating_add(T::DbWeight::get().reads(10))
.saturating_add(T::DbWeight::get().writes(7)) .saturating_add(T::DbWeight::get().writes(7))
@ -106,8 +106,8 @@ impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `655` // Measured: `655`
// Estimated: `4120` // Estimated: `4120`
// Minimum execution time: 210_676_000 picoseconds. // Minimum execution time: 208_453_000 picoseconds.
Weight::from_parts(212_905_000, 0) Weight::from_parts(212_038_000, 0)
.saturating_add(Weight::from_parts(0, 4120)) .saturating_add(Weight::from_parts(0, 4120))
.saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().reads(9))
.saturating_add(T::DbWeight::get().writes(5)) .saturating_add(T::DbWeight::get().writes(5))
@ -139,8 +139,8 @@ impl WeightInfo for () {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `355` // Measured: `355`
// Estimated: `3820` // Estimated: `3820`
// Minimum execution time: 213_817_000 picoseconds. // Minimum execution time: 211_154_000 picoseconds.
Weight::from_parts(216_977_000, 0) Weight::from_parts(215_420_000, 0)
.saturating_add(Weight::from_parts(0, 3820)) .saturating_add(Weight::from_parts(0, 3820))
.saturating_add(RocksDbWeight::get().reads(10)) .saturating_add(RocksDbWeight::get().reads(10))
.saturating_add(RocksDbWeight::get().writes(7)) .saturating_add(RocksDbWeight::get().writes(7))
@ -167,8 +167,8 @@ impl WeightInfo for () {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `655` // Measured: `655`
// Estimated: `4120` // Estimated: `4120`
// Minimum execution time: 210_676_000 picoseconds. // Minimum execution time: 208_453_000 picoseconds.
Weight::from_parts(212_905_000, 0) Weight::from_parts(212_038_000, 0)
.saturating_add(Weight::from_parts(0, 4120)) .saturating_add(Weight::from_parts(0, 4120))
.saturating_add(RocksDbWeight::get().reads(9)) .saturating_add(RocksDbWeight::get().reads(9))
.saturating_add(RocksDbWeight::get().writes(5)) .saturating_add(RocksDbWeight::get().writes(5))

View File

@ -1,6 +1,6 @@
[package] [package]
name = "ghost-traits" name = "ghost-traits"
version = "0.3.23" version = "0.3.22"
license.workspace = true license.workspace = true
authors.workspace = true authors.workspace = true
edition.workspace = true edition.workspace = true

View File

@ -1,7 +1,10 @@
use frame_support::{pallet_prelude::*, storage::PrefixIterator}; use frame_support::{
pallet_prelude::*,
storage::PrefixIterator,
};
use sp_runtime::{ use sp_runtime::{
traits::{AtLeast32BitUnsigned, Member},
DispatchResult, DispatchResult,
traits::{AtLeast32BitUnsigned, Member},
}; };
pub trait NetworkDataBasicHandler { pub trait NetworkDataBasicHandler {
@ -25,14 +28,8 @@ pub trait NetworkDataMutateHandler<Network, Balance>: NetworkDataInspectHandler<
fn register(chain_id: Self::NetworkId, network: Network) -> DispatchResult; fn register(chain_id: Self::NetworkId, network: Network) -> DispatchResult;
fn remove(chain_id: Self::NetworkId) -> DispatchResult; fn remove(chain_id: Self::NetworkId) -> DispatchResult;
fn increase_gatekeeper_amount( fn increase_gatekeeper_amount(chain_id: &Self::NetworkId, amount: &Balance) -> Result<Balance, ()>;
chain_id: &Self::NetworkId, fn decrease_gatekeeper_amount(chain_id: &Self::NetworkId, amount: &Balance) -> Result<Balance, ()>;
amount: &Balance,
) -> Result<Balance, ()>;
fn decrease_gatekeeper_amount(
chain_id: &Self::NetworkId,
amount: &Balance,
) -> Result<Balance, ()>;
fn accumulate_outgoing_imbalance(amount: &Balance) -> Result<Balance, ()>; fn accumulate_outgoing_imbalance(amount: &Balance) -> Result<Balance, ()>;
fn accumulate_incoming_imbalance(amount: &Balance) -> Result<Balance, ()>; fn accumulate_incoming_imbalance(amount: &Balance) -> Result<Balance, ()>;

View File

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

View File

@ -16,7 +16,7 @@
//! Autogenerated weights for `ghost_networks` //! Autogenerated weights for `ghost_networks`
//! //!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0
//! DATE: 2025-06-19, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! DATE: 2025-06-18, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000` //! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `ghostown`, CPU: `Intel(R) Core(TM) i3-2310M CPU @ 2.10GHz` //! HOSTNAME: `ghostown`, CPU: `Intel(R) Core(TM) i3-2310M CPU @ 2.10GHz`
//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("casper-dev")`, DB CACHE: 1024 //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("casper-dev")`, DB CACHE: 1024
@ -50,30 +50,30 @@ impl<T: frame_system::Config> ghost_networks::WeightInfo for WeightInfo<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// The range of component `i` is `[1, 20]`. /// The range of component `i` is `[1, 20]`.
/// The range of component `j` is `[1, 150]`. /// The range of component `j` is `[1, 150]`.
fn register_network(_i: u32, j: u32, ) -> Weight { fn register_network(i: u32, j: u32, ) -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `109` // Measured: `109`
// Estimated: `3574` // Estimated: `3574`
// Minimum execution time: 43_753_000 picoseconds. // Minimum execution time: 43_624_000 picoseconds.
Weight::from_parts(45_805_520, 0) Weight::from_parts(44_945_690, 0)
.saturating_add(Weight::from_parts(0, 3574)) .saturating_add(Weight::from_parts(0, 3574))
// Standard Error: 412 // Standard Error: 3_439
.saturating_add(Weight::from_parts(1_586, 0).saturating_mul(j.into())) .saturating_add(Weight::from_parts(15_557, 0).saturating_mul(i.into()))
// Standard Error: 450
.saturating_add(Weight::from_parts(3_508, 0).saturating_mul(j.into()))
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }
/// Storage: `GhostNetworks::Networks` (r:1 w:1) /// Storage: `GhostNetworks::Networks` (r:1 w:1)
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// The range of component `n` is `[1, 20]`. /// The range of component `n` is `[1, 20]`.
fn update_network_name(n: u32, ) -> Weight { fn update_network_name(_n: u32, ) -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 49_412_000 picoseconds. // Minimum execution time: 48_741_000 picoseconds.
Weight::from_parts(50_617_210, 0) Weight::from_parts(50_426_703, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
// Standard Error: 3_074
.saturating_add(Weight::from_parts(6_017, 0).saturating_mul(n.into()))
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }
@ -82,13 +82,13 @@ impl<T: frame_system::Config> ghost_networks::WeightInfo for WeightInfo<T> {
/// The range of component `n` is `[1, 150]`. /// The range of component `n` is `[1, 150]`.
fn update_network_endpoint(n: u32, ) -> Weight { fn update_network_endpoint(n: u32, ) -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 49_485_000 picoseconds. // Minimum execution time: 49_090_000 picoseconds.
Weight::from_parts(50_716_057, 0) Weight::from_parts(50_734_447, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
// Standard Error: 453 // Standard Error: 863
.saturating_add(Weight::from_parts(4_916, 0).saturating_mul(n.into())) .saturating_add(Weight::from_parts(786, 0).saturating_mul(n.into()))
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }
@ -96,23 +96,11 @@ impl<T: frame_system::Config> ghost_networks::WeightInfo for WeightInfo<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_finality_delay() -> Weight { fn update_network_finality_delay() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 48_061_000 picoseconds. // Minimum execution time: 48_107_000 picoseconds.
Weight::from_parts(49_072_000, 0) Weight::from_parts(48_993_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.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: `301`
// Estimated: `3766`
// Minimum execution time: 49_066_000 picoseconds.
Weight::from_parts(52_137_000, 0)
.saturating_add(Weight::from_parts(0, 3766))
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }
@ -120,11 +108,11 @@ impl<T: frame_system::Config> ghost_networks::WeightInfo for WeightInfo<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_block_distance() -> Weight { fn update_network_block_distance() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 48_085_000 picoseconds. // Minimum execution time: 48_277_000 picoseconds.
Weight::from_parts(48_838_000, 0) Weight::from_parts(49_393_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }
@ -132,11 +120,11 @@ impl<T: frame_system::Config> ghost_networks::WeightInfo for WeightInfo<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_type() -> Weight { fn update_network_type() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 47_872_000 picoseconds. // Minimum execution time: 47_642_000 picoseconds.
Weight::from_parts(48_972_000, 0) Weight::from_parts(49_212_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }
@ -144,11 +132,11 @@ impl<T: frame_system::Config> ghost_networks::WeightInfo for WeightInfo<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_gatekeeper() -> Weight { fn update_network_gatekeeper() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 50_029_000 picoseconds. // Minimum execution time: 49_440_000 picoseconds.
Weight::from_parts(50_768_000, 0) Weight::from_parts(50_315_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }
@ -156,11 +144,11 @@ impl<T: frame_system::Config> ghost_networks::WeightInfo for WeightInfo<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_network_topic_name() -> Weight { fn update_network_topic_name() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 50_151_000 picoseconds. // Minimum execution time: 49_469_000 picoseconds.
Weight::from_parts(51_573_000, 0) Weight::from_parts(50_532_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }
@ -168,11 +156,11 @@ impl<T: frame_system::Config> ghost_networks::WeightInfo for WeightInfo<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_incoming_network_fee() -> Weight { fn update_incoming_network_fee() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 48_017_000 picoseconds. // Minimum execution time: 47_858_000 picoseconds.
Weight::from_parts(49_513_000, 0) Weight::from_parts(48_703_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }
@ -180,11 +168,11 @@ impl<T: frame_system::Config> ghost_networks::WeightInfo for WeightInfo<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn update_outgoing_network_fee() -> Weight { fn update_outgoing_network_fee() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 48_714_000 picoseconds. // Minimum execution time: 47_895_000 picoseconds.
Weight::from_parts(49_777_000, 0) Weight::from_parts(49_230_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }
@ -192,11 +180,11 @@ impl<T: frame_system::Config> ghost_networks::WeightInfo for WeightInfo<T> {
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn remove_network() -> Weight { fn remove_network() -> Weight {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `301` // Measured: `294`
// Estimated: `3766` // Estimated: `3759`
// Minimum execution time: 44_583_000 picoseconds. // Minimum execution time: 44_052_000 picoseconds.
Weight::from_parts(45_681_000, 0) Weight::from_parts(44_612_000, 0)
.saturating_add(Weight::from_parts(0, 3766)) .saturating_add(Weight::from_parts(0, 3759))
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }

View File

@ -16,7 +16,7 @@
//! Autogenerated weights for `ghost_slow_clap` //! Autogenerated weights for `ghost_slow_clap`
//! //!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0
//! DATE: 2025-06-19, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! DATE: 2025-06-17, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000` //! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `ghostown`, CPU: `Intel(R) Core(TM) i3-2310M CPU @ 2.10GHz` //! HOSTNAME: `ghostown`, CPU: `Intel(R) Core(TM) i3-2310M CPU @ 2.10GHz`
//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("casper-dev")`, DB CACHE: 1024 //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("casper-dev")`, DB CACHE: 1024
@ -70,8 +70,8 @@ impl<T: frame_system::Config> ghost_slow_clap::WeightInfo for WeightInfo<T> {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `355` // Measured: `355`
// Estimated: `3820` // Estimated: `3820`
// Minimum execution time: 213_817_000 picoseconds. // Minimum execution time: 211_154_000 picoseconds.
Weight::from_parts(216_977_000, 0) Weight::from_parts(215_420_000, 0)
.saturating_add(Weight::from_parts(0, 3820)) .saturating_add(Weight::from_parts(0, 3820))
.saturating_add(T::DbWeight::get().reads(10)) .saturating_add(T::DbWeight::get().reads(10))
.saturating_add(T::DbWeight::get().writes(7)) .saturating_add(T::DbWeight::get().writes(7))
@ -98,8 +98,8 @@ impl<T: frame_system::Config> ghost_slow_clap::WeightInfo for WeightInfo<T> {
// Proof Size summary in bytes: // Proof Size summary in bytes:
// Measured: `655` // Measured: `655`
// Estimated: `4120` // Estimated: `4120`
// Minimum execution time: 210_676_000 picoseconds. // Minimum execution time: 208_453_000 picoseconds.
Weight::from_parts(212_905_000, 0) Weight::from_parts(212_038_000, 0)
.saturating_add(Weight::from_parts(0, 4120)) .saturating_add(Weight::from_parts(0, 4120))
.saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().reads(9))
.saturating_add(T::DbWeight::get().writes(5)) .saturating_add(T::DbWeight::get().writes(5))

View File

@ -177,8 +177,7 @@ fn casper_testnet_evm_networks() -> Vec<(u32, Vec<u8>)> {
(1, ghost_networks::NetworkData { (1, ghost_networks::NetworkData {
chain_name: "ethereum-mainnet".into(), chain_name: "ethereum-mainnet".into(),
default_endpoint: "https://nd-422-757-666.p2pify.com/0a9d79d93fb2f4a4b1e04695da2b77a7/".into(), default_endpoint: "https://nd-422-757-666.p2pify.com/0a9d79d93fb2f4a4b1e04695da2b77a7/".into(),
finality_delay: 40u64, finality_delay: Some(40u64),
rate_limit_delay: 1_000u64,
block_distance: 50u64, block_distance: 50u64,
network_type: ghost_networks::NetworkType::Evm, network_type: ghost_networks::NetworkType::Evm,
gatekeeper: "0x4d224452801aced8b2f0aebe155379bb5d594381".into(), gatekeeper: "0x4d224452801aced8b2f0aebe155379bb5d594381".into(),
@ -189,8 +188,7 @@ fn casper_testnet_evm_networks() -> Vec<(u32, Vec<u8>)> {
(56, ghost_networks::NetworkData { (56, ghost_networks::NetworkData {
chain_name: "bnb-mainnet".into(), chain_name: "bnb-mainnet".into(),
default_endpoint: "https://bsc-mainnet.core.chainstack.com/35848e183f3e3303c8cfeacbea831cab/".into(), default_endpoint: "https://bsc-mainnet.core.chainstack.com/35848e183f3e3303c8cfeacbea831cab/".into(),
finality_delay: 20u64, finality_delay: Some(20u64),
rate_limit_delay: 1_000u64,
block_distance: 50u64, block_distance: 50u64,
network_type: ghost_networks::NetworkType::Evm, network_type: ghost_networks::NetworkType::Evm,
gatekeeper: "0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82".into(), gatekeeper: "0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82".into(),