mirror of
https://git.ghostchain.io/proxmio/ghost-node.git
synced 2025-12-27 11:19:57 +00:00
Compare commits
23 Commits
pallet-net
...
pallet-slo
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6a2b5a34d2 | ||
|
|
0bb46482b2 | ||
|
|
d76646c191 | ||
|
|
94d28f254f | ||
|
|
55a77cd3d4 | ||
|
|
092679eb0c | ||
|
|
64de0027bf | ||
|
|
a3ed395689 | ||
|
|
7a710ec9cb | ||
|
|
cc141105bb | ||
|
|
0e750c0261 | ||
|
|
cc566ac549 | ||
|
|
18241ea504 | ||
|
|
af14543cc1 | ||
|
|
6acec08fa5 | ||
|
|
d6ecdcd468 | ||
|
|
decf6665df | ||
|
|
ebae9fadbe | ||
|
|
c872eca8ac | ||
|
|
eb181c7f44 | ||
|
|
5307afe352 | ||
|
|
7edc8935b6 | ||
|
|
46aa18aafe |
4
Cargo.lock
generated
4
Cargo.lock
generated
@@ -1186,7 +1186,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "casper-runtime"
|
||||
version = "3.5.31"
|
||||
version = "3.5.33"
|
||||
dependencies = [
|
||||
"casper-runtime-constants",
|
||||
"frame-benchmarking",
|
||||
@@ -3836,7 +3836,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ghost-slow-clap"
|
||||
version = "0.3.39"
|
||||
version = "0.3.47"
|
||||
dependencies = [
|
||||
"frame-benchmarking",
|
||||
"frame-support",
|
||||
|
||||
@@ -51,33 +51,6 @@ pub trait WeightInfo {
|
||||
fn claim() -> Weight;
|
||||
}
|
||||
|
||||
/// Weight for ghost_claims using the Substrate node and recommended hardware.
|
||||
pub struct SubstrateWeight<T>(PhantomData<T>);
|
||||
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
|
||||
/// Storage: `System::Account` (r:2 w:2)
|
||||
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
|
||||
/// Storage: `GhostClaims::Total` (r:1 w:1)
|
||||
/// Proof: `GhostClaims::Total` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `CultCollective::Members` (r:2 w:2)
|
||||
/// Proof: `CultCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`)
|
||||
/// Storage: `CultCollective::MemberCount` (r:6 w:6)
|
||||
/// Proof: `CultCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`)
|
||||
/// Storage: `CultCollective::IdToIndex` (r:6 w:12)
|
||||
/// Proof: `CultCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`)
|
||||
/// Storage: `CultCollective::IndexToId` (r:0 w:6)
|
||||
/// Proof: `CultCollective::IndexToId` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`)
|
||||
fn claim() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `896`
|
||||
// Estimated: `16164`
|
||||
// Minimum execution time: 754_086_000 picoseconds.
|
||||
Weight::from_parts(756_147_000, 0)
|
||||
.saturating_add(Weight::from_parts(0, 16164))
|
||||
.saturating_add(T::DbWeight::get().reads(17))
|
||||
.saturating_add(T::DbWeight::get().writes(29))
|
||||
}
|
||||
}
|
||||
|
||||
impl WeightInfo for () {
|
||||
/// Storage: `System::Account` (r:2 w:2)
|
||||
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
|
||||
|
||||
@@ -63,166 +63,6 @@ pub trait WeightInfo {
|
||||
fn remove_network() -> Weight;
|
||||
}
|
||||
|
||||
/// Weight for ghost_networks using the Substrate node and recommended hardware.
|
||||
pub struct SubstrateWeight<T>(PhantomData<T>);
|
||||
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
|
||||
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
|
||||
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// The range of component `i` is `[1, 20]`.
|
||||
/// The range of component `j` is `[1, 150]`.
|
||||
/// The range of component `k` is `[1, 20]`.
|
||||
fn register_network(_i: u32, _j: u32, k: u32, ) -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `109`
|
||||
// Estimated: `3574`
|
||||
// Minimum execution time: 46_023_000 picoseconds.
|
||||
Weight::from_parts(97_871_287, 0)
|
||||
.saturating_add(Weight::from_parts(0, 3574))
|
||||
// Standard Error: 94_524
|
||||
.saturating_add(Weight::from_parts(940_486, 0).saturating_mul(k.into()))
|
||||
.saturating_add(T::DbWeight::get().reads(1))
|
||||
.saturating_add(T::DbWeight::get().writes(1))
|
||||
}
|
||||
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
|
||||
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// The range of component `n` is `[1, 20]`.
|
||||
fn update_network_name(n: u32, ) -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `302`
|
||||
// Estimated: `3767`
|
||||
// Minimum execution time: 49_906_000 picoseconds.
|
||||
Weight::from_parts(55_537_587, 0)
|
||||
.saturating_add(Weight::from_parts(0, 3767))
|
||||
// Standard Error: 87_704
|
||||
.saturating_add(Weight::from_parts(92_366, 0).saturating_mul(n.into()))
|
||||
.saturating_add(T::DbWeight::get().reads(1))
|
||||
.saturating_add(T::DbWeight::get().writes(1))
|
||||
}
|
||||
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
|
||||
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// The range of component `n` is `[1, 150]`.
|
||||
fn update_network_endpoint(n: u32, ) -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `302`
|
||||
// Estimated: `3767`
|
||||
// Minimum execution time: 50_556_000 picoseconds.
|
||||
Weight::from_parts(57_726_674, 0)
|
||||
.saturating_add(Weight::from_parts(0, 3767))
|
||||
// Standard Error: 12_261
|
||||
.saturating_add(Weight::from_parts(274, 0).saturating_mul(n.into()))
|
||||
.saturating_add(T::DbWeight::get().reads(1))
|
||||
.saturating_add(T::DbWeight::get().writes(1))
|
||||
}
|
||||
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
|
||||
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
fn update_network_finality_delay() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `302`
|
||||
// Estimated: `3767`
|
||||
// Minimum execution time: 49_406_000 picoseconds.
|
||||
Weight::from_parts(51_256_000, 0)
|
||||
.saturating_add(Weight::from_parts(0, 3767))
|
||||
.saturating_add(T::DbWeight::get().reads(1))
|
||||
.saturating_add(T::DbWeight::get().writes(1))
|
||||
}
|
||||
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
|
||||
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
fn update_network_rate_limit_delay() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `302`
|
||||
// Estimated: `3767`
|
||||
// Minimum execution time: 49_572_000 picoseconds.
|
||||
Weight::from_parts(52_584_000, 0)
|
||||
.saturating_add(Weight::from_parts(0, 3767))
|
||||
.saturating_add(T::DbWeight::get().reads(1))
|
||||
.saturating_add(T::DbWeight::get().writes(1))
|
||||
}
|
||||
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
|
||||
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
fn update_network_block_distance() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `302`
|
||||
// Estimated: `3767`
|
||||
// Minimum execution time: 48_880_000 picoseconds.
|
||||
Weight::from_parts(50_596_000, 0)
|
||||
.saturating_add(Weight::from_parts(0, 3767))
|
||||
.saturating_add(T::DbWeight::get().reads(1))
|
||||
.saturating_add(T::DbWeight::get().writes(1))
|
||||
}
|
||||
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
|
||||
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
fn update_network_type() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `302`
|
||||
// Estimated: `3767`
|
||||
// Minimum execution time: 48_282_000 picoseconds.
|
||||
Weight::from_parts(49_137_000, 0)
|
||||
.saturating_add(Weight::from_parts(0, 3767))
|
||||
.saturating_add(T::DbWeight::get().reads(1))
|
||||
.saturating_add(T::DbWeight::get().writes(1))
|
||||
}
|
||||
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
|
||||
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
fn update_network_gatekeeper() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `302`
|
||||
// Estimated: `3767`
|
||||
// Minimum execution time: 50_853_000 picoseconds.
|
||||
Weight::from_parts(51_982_000, 0)
|
||||
.saturating_add(Weight::from_parts(0, 3767))
|
||||
.saturating_add(T::DbWeight::get().reads(1))
|
||||
.saturating_add(T::DbWeight::get().writes(1))
|
||||
}
|
||||
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
|
||||
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
fn update_network_topic_name() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `302`
|
||||
// Estimated: `3767`
|
||||
// Minimum execution time: 50_343_000 picoseconds.
|
||||
Weight::from_parts(52_380_000, 0)
|
||||
.saturating_add(Weight::from_parts(0, 3767))
|
||||
.saturating_add(T::DbWeight::get().reads(1))
|
||||
.saturating_add(T::DbWeight::get().writes(1))
|
||||
}
|
||||
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
|
||||
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
fn update_incoming_network_fee() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `302`
|
||||
// Estimated: `3767`
|
||||
// Minimum execution time: 49_393_000 picoseconds.
|
||||
Weight::from_parts(80_966_000, 0)
|
||||
.saturating_add(Weight::from_parts(0, 3767))
|
||||
.saturating_add(T::DbWeight::get().reads(1))
|
||||
.saturating_add(T::DbWeight::get().writes(1))
|
||||
}
|
||||
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
|
||||
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
fn update_outgoing_network_fee() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `302`
|
||||
// Estimated: `3767`
|
||||
// Minimum execution time: 49_579_000 picoseconds.
|
||||
Weight::from_parts(51_126_000, 0)
|
||||
.saturating_add(Weight::from_parts(0, 3767))
|
||||
.saturating_add(T::DbWeight::get().reads(1))
|
||||
.saturating_add(T::DbWeight::get().writes(1))
|
||||
}
|
||||
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
|
||||
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
fn remove_network() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `302`
|
||||
// Estimated: `3767`
|
||||
// Minimum execution time: 44_634_000 picoseconds.
|
||||
Weight::from_parts(45_815_000, 0)
|
||||
.saturating_add(Weight::from_parts(0, 3767))
|
||||
.saturating_add(T::DbWeight::get().reads(1))
|
||||
.saturating_add(T::DbWeight::get().writes(1))
|
||||
}
|
||||
}
|
||||
|
||||
impl WeightInfo for () {
|
||||
/// Storage: `GhostNetworks::Networks` (r:1 w:1)
|
||||
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ghost-slow-clap"
|
||||
version = "0.3.40"
|
||||
version = "0.3.56"
|
||||
description = "Applause protocol for the EVM bridge"
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
|
||||
@@ -17,62 +17,21 @@ benchmarks! {
|
||||
let minimum_balance = <<T as pallet::Config>::Currency>::minimum_balance();
|
||||
let receiver = create_account::<T>();
|
||||
let amount = minimum_balance + minimum_balance;
|
||||
|
||||
let network_id = NetworkIdOf::<T>::default();
|
||||
let session_index = T::ValidatorSet::session_index();
|
||||
|
||||
let authorities = vec![T::AuthorityId::generate_pair(None)];
|
||||
let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities.clone())
|
||||
.map_err(|()| "more than the maximum number of keys provided")?;
|
||||
Authorities::<T>::set(&session_index, bounded_authorities);
|
||||
|
||||
let clap = Clap {
|
||||
session_index: 0,
|
||||
authority_index: 0,
|
||||
transaction_hash: H256::repeat_byte(1u8),
|
||||
block_number: 69,
|
||||
removed: false,
|
||||
network_id,
|
||||
receiver: receiver.clone(),
|
||||
amount,
|
||||
};
|
||||
|
||||
let authority_id = authorities
|
||||
.get(0usize)
|
||||
.expect("first authority should exist");
|
||||
let encoded_clap = clap.encode();
|
||||
let signature = authority_id.sign(&encoded_clap)
|
||||
.ok_or("couldn't make signature")?;
|
||||
|
||||
}: _(RawOrigin::None, clap, signature)
|
||||
verify {
|
||||
assert_eq!(<<T as pallet::Config>::Currency>::total_balance(&receiver), amount);
|
||||
}
|
||||
|
||||
self_applause {
|
||||
let session_index = T::ValidatorSet::session_index();
|
||||
let authorities = vec![T::AuthorityId::generate_pair(None)];
|
||||
let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities.clone())
|
||||
.map_err(|()| "more than the maximum number of keys provided")?;
|
||||
Authorities::<T>::set(&session_index, bounded_authorities);
|
||||
|
||||
let minimum_balance = <<T as pallet::Config>::Currency>::minimum_balance();
|
||||
let receiver = create_account::<T>();
|
||||
let receiver_clone = receiver.clone();
|
||||
let amount = minimum_balance + minimum_balance;
|
||||
let network_id = NetworkIdOf::<T>::default();
|
||||
let transaction_hash = H256::repeat_byte(1u8);
|
||||
let args_hash = Pallet::<T>::generate_unique_hash(&receiver, &amount, &network_id);
|
||||
|
||||
let unique_transaction_hash = <Pallet<T>>::generate_unique_hash(
|
||||
&receiver,
|
||||
&amount,
|
||||
&network_id,
|
||||
);
|
||||
let storage_key = (session_index, &transaction_hash, &unique_transaction_hash);
|
||||
let authorities = vec![T::AuthorityId::generate_pair(None)];
|
||||
let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities.clone())
|
||||
.map_err(|()| "more than the maximum number of keys provided")?;
|
||||
Authorities::<T>::set(&session_index, bounded_authorities);
|
||||
let authority_index = 0u32;
|
||||
|
||||
<Pallet::<T>>::trigger_nullification_for_benchmark();
|
||||
let clap = Clap {
|
||||
session_index,
|
||||
authority_index: 0,
|
||||
authority_index,
|
||||
transaction_hash,
|
||||
block_number: 69,
|
||||
removed: false,
|
||||
@@ -82,19 +41,54 @@ benchmarks! {
|
||||
};
|
||||
|
||||
let authority_id = authorities
|
||||
.get(0usize)
|
||||
.get(authority_index as usize)
|
||||
.expect("first authority should exist");
|
||||
let encoded_clap = clap.encode();
|
||||
let signature = authority_id.sign(&encoded_clap).unwrap();
|
||||
<Pallet<T>>::slow_clap(RawOrigin::None.into(), clap, signature)?;
|
||||
<Pallet::<T>>::trigger_nullification_for_benchmark();
|
||||
let signature = authority_id.sign(&clap.encode())
|
||||
.ok_or("couldn't make signature")?;
|
||||
|
||||
assert_eq!(<<T as pallet::Config>::Currency>::total_balance(&receiver), Default::default());
|
||||
assert_eq!(ApplausesForTransaction::<T>::get(&storage_key), false);
|
||||
}: _(RawOrigin::Signed(receiver_clone), network_id, session_index, transaction_hash, receiver_clone.clone(), amount)
|
||||
}: _(RawOrigin::None, clap, signature)
|
||||
verify {
|
||||
let clap_key = (session_index, transaction_hash, args_hash);
|
||||
assert_eq!(ReceivedClaps::<T>::get(&clap_key).get(&authority_index).is_some(), true);
|
||||
assert_eq!(<<T as pallet::Config>::Currency>::total_balance(&receiver), amount);
|
||||
assert_eq!(ApplausesForTransaction::<T>::get(&storage_key), true);
|
||||
}
|
||||
|
||||
commit_block {
|
||||
let session_index = T::ValidatorSet::session_index();
|
||||
let network_id = NetworkIdOf::<T>::default();
|
||||
|
||||
let authorities = vec![T::AuthorityId::generate_pair(None)];
|
||||
let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities.clone())
|
||||
.map_err(|()| "more than the maximum number of keys provided")?;
|
||||
Authorities::<T>::set(&session_index, bounded_authorities);
|
||||
let authority_index = 0u32;
|
||||
|
||||
let block_commitment = BlockCommitment {
|
||||
session_index,
|
||||
authority_index,
|
||||
network_id,
|
||||
commitment: CommitmentDetails {
|
||||
last_registered_block: 69,
|
||||
last_seen_block: 420,
|
||||
last_updated: 1337,
|
||||
}
|
||||
};
|
||||
|
||||
let authority_id = authorities
|
||||
.get(authority_index as usize)
|
||||
.expect("first authority should exist");
|
||||
let signature = authority_id.sign(&block_commitment.encode())
|
||||
.ok_or("couldn't make signature")?;
|
||||
|
||||
}: _(RawOrigin::None, block_commitment, signature)
|
||||
verify {
|
||||
let stored_commitment = BlockCommitments::<T>::get(&network_id)
|
||||
.get(&authority_index)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
assert_eq!(stored_commitment.last_registered_block, 69);
|
||||
assert_eq!(stored_commitment.last_seen_block, 420);
|
||||
assert_eq!(stored_commitment.last_updated, 1337);
|
||||
}
|
||||
|
||||
impl_benchmark_test_suite!(
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
use sp_runtime::SaturatedConversion;
|
||||
use sp_staking::SessionIndex;
|
||||
|
||||
use crate::{
|
||||
deserialisations::{
|
||||
de_string_to_bytes, de_string_to_h256, de_string_to_u64, de_string_to_u64_pure,
|
||||
de_string_to_vec_of_bytes,
|
||||
},
|
||||
Decode, Deserialize, Encode, RuntimeDebug, Vec, H256,
|
||||
AuthIndex, BalanceOf, BlockCommitment, BlockCommitments, Call, Clap, CommitmentDetails, Config,
|
||||
Decode, Deserialize, Encode, NetworkIdOf, RuntimeAppPublic, RuntimeDebug, SubmitTransaction,
|
||||
Vec, COMMITMENT_DELAY_MILLIS, H256, LOG_TARGET,
|
||||
};
|
||||
|
||||
const NUMBER_OF_TOPICS: usize = 3;
|
||||
@@ -40,6 +45,219 @@ pub struct Log {
|
||||
pub removed: bool,
|
||||
}
|
||||
|
||||
impl EvmResponseType {
|
||||
fn prepare_block_commitment<T: Config>(
|
||||
&self,
|
||||
from_block: u64,
|
||||
authority_index: AuthIndex,
|
||||
session_index: SessionIndex,
|
||||
network_id: NetworkIdOf<T>,
|
||||
) -> BlockCommitment<NetworkIdOf<T>> {
|
||||
let last_updated = sp_io::offchain::timestamp().unix_millis();
|
||||
let current_block = match self {
|
||||
EvmResponseType::BlockNumber(block_number) => *block_number,
|
||||
EvmResponseType::TransactionLogs(_) => Default::default(),
|
||||
};
|
||||
|
||||
BlockCommitment {
|
||||
session_index,
|
||||
authority_index,
|
||||
network_id,
|
||||
commitment: CommitmentDetails {
|
||||
last_registered_block: from_block,
|
||||
last_seen_block: current_block,
|
||||
last_updated,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_clap<T: Config>(
|
||||
&self,
|
||||
authority_index: AuthIndex,
|
||||
session_index: SessionIndex,
|
||||
network_id: NetworkIdOf<T>,
|
||||
log: &Log,
|
||||
) -> Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>> {
|
||||
Clap {
|
||||
authority_index,
|
||||
session_index,
|
||||
network_id,
|
||||
removed: log.removed,
|
||||
receiver: T::AccountId::decode(&mut &log.topics[1][0..32])
|
||||
.expect("32 bytes always construct an AccountId32"),
|
||||
amount: u128::from_be_bytes(
|
||||
log.topics[2][16..32]
|
||||
.try_into()
|
||||
.expect("amount is valid hex; qed"),
|
||||
)
|
||||
.saturated_into::<BalanceOf<T>>(),
|
||||
transaction_hash: log.transaction_hash.clone().expect("tx hash exists; qed"),
|
||||
block_number: log.block_number.expect("block number exists; qed"),
|
||||
}
|
||||
}
|
||||
|
||||
fn iter_claps_from_logs<T: Config>(
|
||||
&self,
|
||||
authority_index: AuthIndex,
|
||||
session_index: SessionIndex,
|
||||
network_id: NetworkIdOf<T>,
|
||||
) -> Vec<Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>> {
|
||||
match self {
|
||||
EvmResponseType::TransactionLogs(evm_logs) => evm_logs
|
||||
.iter()
|
||||
.filter_map(move |log| {
|
||||
log.is_sufficient().then(|| {
|
||||
self.prepare_clap::<T>(authority_index, session_index, network_id, log)
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
EvmResponseType::BlockNumber(_) => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn sign_and_submit_claps<T: Config>(
|
||||
&self,
|
||||
authority_index: AuthIndex,
|
||||
authority_key: T::AuthorityId,
|
||||
session_index: SessionIndex,
|
||||
network_id: NetworkIdOf<T>,
|
||||
) {
|
||||
let claps = self.iter_claps_from_logs::<T>(authority_index, session_index, network_id);
|
||||
let claps_len = claps.len();
|
||||
|
||||
log::info!(
|
||||
target: LOG_TARGET,
|
||||
"🧐 Found {:?} claps for network {:?}",
|
||||
claps_len,
|
||||
network_id,
|
||||
);
|
||||
|
||||
for (clap_index, clap) in claps.iter().enumerate() {
|
||||
let signature = match authority_key.sign(&clap.encode()) {
|
||||
Some(signature) => signature,
|
||||
None => {
|
||||
log::info!(
|
||||
target: LOG_TARGET,
|
||||
"🧐 Clap #{} signing failed from authority #{:?} for network {:?}",
|
||||
clap_index,
|
||||
authority_index,
|
||||
network_id,
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let call = Call::slow_clap {
|
||||
clap: clap.clone(),
|
||||
signature,
|
||||
};
|
||||
|
||||
if let Err(e) =
|
||||
SubmitTransaction::<T, Call<T>>::submit_unsigned_transaction(call.into())
|
||||
{
|
||||
log::info!(
|
||||
target: LOG_TARGET,
|
||||
"🧐 Failed to submit clap #{} from authority #{:?} for network {:?}: {:?}",
|
||||
clap_index,
|
||||
authority_index,
|
||||
network_id,
|
||||
e,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn sign_and_submit_block_commitment<T: Config>(
|
||||
&self,
|
||||
from_block: u64,
|
||||
authority_index: AuthIndex,
|
||||
authority_key: T::AuthorityId,
|
||||
session_index: SessionIndex,
|
||||
network_id: NetworkIdOf<T>,
|
||||
) {
|
||||
let block_commitment = self.prepare_block_commitment::<T>(
|
||||
from_block,
|
||||
authority_index,
|
||||
session_index,
|
||||
network_id,
|
||||
);
|
||||
|
||||
let stored_last_updated = BlockCommitments::<T>::get(&network_id)
|
||||
.get(&authority_index)
|
||||
.map(|details| details.last_updated)
|
||||
.unwrap_or_default();
|
||||
|
||||
let current_last_updated = block_commitment
|
||||
.commitment
|
||||
.last_updated
|
||||
.saturating_sub(COMMITMENT_DELAY_MILLIS);
|
||||
|
||||
if current_last_updated < stored_last_updated {
|
||||
return;
|
||||
}
|
||||
|
||||
log::info!(
|
||||
target: LOG_TARGET,
|
||||
"🧐 New block commitment from authority #{:?} for network {:?}",
|
||||
authority_index,
|
||||
network_id,
|
||||
);
|
||||
|
||||
let signature = match authority_key.sign(&block_commitment.encode()) {
|
||||
Some(signature) => signature,
|
||||
None => {
|
||||
log::info!(
|
||||
target: LOG_TARGET,
|
||||
"🧐 Block commitment signing failed from authority #{:?} for network {:?}",
|
||||
authority_index,
|
||||
network_id,
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let call = Call::commit_block {
|
||||
block_commitment,
|
||||
signature,
|
||||
};
|
||||
|
||||
if let Err(e) = SubmitTransaction::<T, Call<T>>::submit_unsigned_transaction(call.into()) {
|
||||
log::info!(
|
||||
target: LOG_TARGET,
|
||||
"🧐 Failed to submit block commitment from authority #{:?} for network {:?}: {:?}",
|
||||
authority_index,
|
||||
network_id,
|
||||
e,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn sign_and_submit<T: Config>(
|
||||
&self,
|
||||
from_block: u64,
|
||||
authority_index: AuthIndex,
|
||||
authority_key: T::AuthorityId,
|
||||
session_index: SessionIndex,
|
||||
network_id: NetworkIdOf<T>,
|
||||
) {
|
||||
match self {
|
||||
EvmResponseType::TransactionLogs(_) => self.sign_and_submit_claps::<T>(
|
||||
authority_index,
|
||||
authority_key,
|
||||
session_index,
|
||||
network_id,
|
||||
),
|
||||
EvmResponseType::BlockNumber(_) => self.sign_and_submit_block_commitment::<T>(
|
||||
from_block,
|
||||
authority_index,
|
||||
authority_key,
|
||||
session_index,
|
||||
network_id,
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Log {
|
||||
pub fn is_sufficient(&self) -> bool {
|
||||
self.transaction_hash.is_some()
|
||||
|
||||
@@ -8,8 +8,7 @@ use serde::{Deserialize, Deserializer};
|
||||
use frame_support::{
|
||||
pallet_prelude::*,
|
||||
traits::{
|
||||
tokens::fungible::{Inspect, Mutate},
|
||||
EstimateNextSessionRotation, Get, OneSessionHandler, ValidatorSet,
|
||||
Currency, DisabledValidators, Get, OneSessionHandler, ValidatorSet,
|
||||
ValidatorSetWithIdentification,
|
||||
},
|
||||
WeakBoundedVec,
|
||||
@@ -18,22 +17,23 @@ use frame_system::{
|
||||
offchain::{SendTransactionTypes, SubmitTransaction},
|
||||
pallet_prelude::*,
|
||||
};
|
||||
|
||||
pub use pallet::*;
|
||||
|
||||
use sp_core::H256;
|
||||
use sp_runtime::{
|
||||
offchain::{
|
||||
self as rt_offchain,
|
||||
storage::{MutateStorageError, StorageRetrievalError, StorageValueRef},
|
||||
storage::StorageValueRef,
|
||||
storage_lock::{StorageLock, Time},
|
||||
HttpError,
|
||||
},
|
||||
traits::{BlockNumberProvider, Convert, Saturating, TrailingZeroInput},
|
||||
Perbill, RuntimeAppPublic, RuntimeDebug, SaturatedConversion,
|
||||
traits::{AtLeast32BitUnsigned, BlockNumberProvider, Convert, Saturating, TrailingZeroInput},
|
||||
Perbill, RuntimeAppPublic, RuntimeDebug,
|
||||
};
|
||||
use sp_staking::{
|
||||
offence::{Kind, Offence, ReportOffence},
|
||||
SessionIndex,
|
||||
EraIndex, SessionIndex,
|
||||
};
|
||||
use sp_std::{collections::btree_map::BTreeMap, prelude::*, vec::Vec};
|
||||
|
||||
@@ -71,11 +71,43 @@ pub mod sr25519 {
|
||||
const LOG_TARGET: &str = "runtime::ghost-slow-clap";
|
||||
const DB_PREFIX: &[u8] = b"slow_clap::";
|
||||
|
||||
const MIN_LOCK_GUARD_PERIOD: u64 = 15_000;
|
||||
const FETCH_TIMEOUT_PERIOD: u64 = 3_000;
|
||||
const LOCK_BLOCK_EXPIRATION: u64 = 10;
|
||||
const LOCK_BLOCK_EXPIRATION: u64 = 20;
|
||||
const COMMITMENT_DELAY_MILLIS: u64 = 600_000;
|
||||
|
||||
pub type AuthIndex = u32;
|
||||
|
||||
#[derive(
|
||||
RuntimeDebug,
|
||||
Default,
|
||||
Copy,
|
||||
Clone,
|
||||
Eq,
|
||||
PartialEq,
|
||||
Ord,
|
||||
PartialOrd,
|
||||
Encode,
|
||||
Decode,
|
||||
TypeInfo,
|
||||
MaxEncodedLen,
|
||||
)]
|
||||
pub struct CommitmentDetails {
|
||||
pub last_registered_block: u64,
|
||||
pub last_seen_block: u64,
|
||||
pub last_updated: u64,
|
||||
}
|
||||
|
||||
#[derive(
|
||||
RuntimeDebug, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, MaxEncodedLen,
|
||||
)]
|
||||
pub struct BlockCommitment<NetworkId> {
|
||||
pub session_index: SessionIndex,
|
||||
pub authority_index: AuthIndex,
|
||||
pub network_id: NetworkId,
|
||||
pub commitment: CommitmentDetails,
|
||||
}
|
||||
|
||||
#[derive(
|
||||
RuntimeDebug, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, MaxEncodedLen,
|
||||
)]
|
||||
@@ -98,8 +130,6 @@ pub struct SessionAuthorityInfo {
|
||||
|
||||
#[cfg_attr(test, derive(PartialEq))]
|
||||
enum OffchainErr<NetworkId> {
|
||||
FailedSigning,
|
||||
SubmitTransaction,
|
||||
HttpJsonParsingError,
|
||||
HttpBytesParsingError,
|
||||
HttpRequestError(HttpError),
|
||||
@@ -107,39 +137,65 @@ enum OffchainErr<NetworkId> {
|
||||
HttpResponseNotOk(u16),
|
||||
ErrorInEvmResponse,
|
||||
NoStoredNetworks,
|
||||
NotValidator,
|
||||
NoEndpointAvailable(NetworkId),
|
||||
StorageRetrievalError(NetworkId),
|
||||
ConcurrentModificationError(NetworkId),
|
||||
UtxoNotImplemented(NetworkId),
|
||||
UnknownNetworkType(NetworkId),
|
||||
OffchainTimeoutPeriod(NetworkId),
|
||||
TooManyRequests(NetworkId),
|
||||
}
|
||||
|
||||
impl<NetworkId: core::fmt::Debug> core::fmt::Debug for OffchainErr<NetworkId> {
|
||||
fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
|
||||
match *self {
|
||||
OffchainErr::FailedSigning => write!(fmt, "Failed to sign clap."),
|
||||
OffchainErr::SubmitTransaction => write!(fmt, "Failed to submit transaction."),
|
||||
OffchainErr::HttpJsonParsingError => write!(fmt, "Failed to parse evm response as JSON."),
|
||||
OffchainErr::HttpBytesParsingError => write!(fmt, "Failed to parse evm response as bytes."),
|
||||
OffchainErr::HttpJsonParsingError => {
|
||||
write!(fmt, "Failed to parse evm response as JSON.")
|
||||
}
|
||||
OffchainErr::HttpBytesParsingError => {
|
||||
write!(fmt, "Failed to parse evm response as bytes.")
|
||||
}
|
||||
OffchainErr::HttpRequestError(http_error) => match http_error {
|
||||
HttpError::DeadlineReached => write!(fmt, "Requested action couldn't been completed within a deadline."),
|
||||
HttpError::IoError => write!(fmt, "There was an IO error while processing the request."),
|
||||
HttpError::Invalid => write!(fmt, "The ID of the request is invalid in this context."),
|
||||
HttpError::DeadlineReached => write!(
|
||||
fmt,
|
||||
"Requested action couldn't been completed within a deadline."
|
||||
),
|
||||
HttpError::IoError => {
|
||||
write!(fmt, "There was an IO error while processing the request.")
|
||||
}
|
||||
HttpError::Invalid => {
|
||||
write!(fmt, "The ID of the request is invalid in this context.")
|
||||
}
|
||||
},
|
||||
OffchainErr::ConcurrentModificationError(ref network_id) => write!(fmt, "The underlying DB failed to update due to a concurrent modification for network #{:?}.", network_id),
|
||||
OffchainErr::StorageRetrievalError(ref network_id) => write!(fmt, "Storage value found for network #{:?} but it's undecodable.", network_id),
|
||||
OffchainErr::StorageRetrievalError(ref network_id) => write!(
|
||||
fmt,
|
||||
"Storage value found for network #{:?} but it's undecodable.",
|
||||
network_id
|
||||
),
|
||||
OffchainErr::RequestUncompleted => write!(fmt, "Failed to complete request."),
|
||||
OffchainErr::HttpResponseNotOk(code) => write!(fmt, "Http response returned code {:?}.", code),
|
||||
OffchainErr::HttpResponseNotOk(code) => {
|
||||
write!(fmt, "Http response returned code {:?}.", code)
|
||||
}
|
||||
OffchainErr::ErrorInEvmResponse => write!(fmt, "Error in evm reponse."),
|
||||
OffchainErr::NoStoredNetworks => write!(fmt, "No networks stored for the offchain slow claps."),
|
||||
OffchainErr::NotValidator => write!(fmt, "Not a validator for slow clap, `--validator` flag needed."),
|
||||
OffchainErr::UtxoNotImplemented(ref network_id) => write!(fmt, "Network #{:?} is marked as UTXO, which is not implemented yet.", network_id),
|
||||
OffchainErr::UnknownNetworkType(ref network_id) => write!(fmt, "Unknown type for network #{:?}.", network_id),
|
||||
OffchainErr::OffchainTimeoutPeriod(ref network_id) => write!(fmt, "Offchain request should be in-flight for network #{:?}.", network_id),
|
||||
OffchainErr::TooManyRequests(ref network_id) => write!(fmt, "Too many requests over RPC endpoint for network #{:?}.", network_id),
|
||||
|
||||
OffchainErr::NoStoredNetworks => {
|
||||
write!(fmt, "No networks stored for the offchain slow claps.")
|
||||
}
|
||||
OffchainErr::NoEndpointAvailable(ref network_id) => write!(
|
||||
fmt,
|
||||
"No RPC endpoint available for network #{:?}.",
|
||||
network_id
|
||||
),
|
||||
OffchainErr::UtxoNotImplemented(ref network_id) => write!(
|
||||
fmt,
|
||||
"Network #{:?} is marked as UTXO, which is not implemented yet.",
|
||||
network_id
|
||||
),
|
||||
OffchainErr::UnknownNetworkType(ref network_id) => {
|
||||
write!(fmt, "Unknown type for network #{:?}.", network_id)
|
||||
}
|
||||
OffchainErr::OffchainTimeoutPeriod(ref network_id) => write!(
|
||||
fmt,
|
||||
"Offchain request should be in-flight for network #{:?}.",
|
||||
network_id
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -147,7 +203,7 @@ impl<NetworkId: core::fmt::Debug> core::fmt::Debug for OffchainErr<NetworkId> {
|
||||
pub type NetworkIdOf<T> = <<T as Config>::NetworkDataHandler as NetworkDataBasicHandler>::NetworkId;
|
||||
|
||||
pub type BalanceOf<T> =
|
||||
<<T as Config>::Currency as Inspect<<T as frame_system::Config>::AccountId>>::Balance;
|
||||
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
|
||||
|
||||
pub type ValidatorId<T> = <<T as Config>::ValidatorSet as ValidatorSet<
|
||||
<T as frame_system::Config>::AccountId,
|
||||
@@ -162,11 +218,17 @@ pub type IdentificationTuple<T> = (
|
||||
|
||||
type OffchainResult<T, A> = Result<A, OffchainErr<NetworkIdOf<T>>>;
|
||||
|
||||
pub trait ApplauseListener<Balance: AtLeast32BitUnsigned> {
|
||||
fn get_current_era() -> EraIndex;
|
||||
fn get_threshold_amount(era: EraIndex) -> Balance;
|
||||
fn get_validator_total_exposure(era: EraIndex, index: usize) -> Balance;
|
||||
}
|
||||
|
||||
#[frame_support::pallet]
|
||||
pub mod pallet {
|
||||
use super::*;
|
||||
|
||||
const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
|
||||
const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);
|
||||
|
||||
#[pallet::pallet]
|
||||
#[pallet::storage_version(STORAGE_VERSION)]
|
||||
@@ -183,9 +245,8 @@ pub mod pallet {
|
||||
+ MaybeSerializeDeserialize
|
||||
+ MaxEncodedLen;
|
||||
|
||||
type NextSessionRotation: EstimateNextSessionRotation<BlockNumberFor<Self>>;
|
||||
type ValidatorSet: ValidatorSetWithIdentification<Self::AccountId>;
|
||||
type Currency: Inspect<Self::AccountId> + Mutate<Self::AccountId>;
|
||||
type Currency: Currency<Self::AccountId>;
|
||||
type NetworkDataHandler: NetworkDataBasicHandler
|
||||
+ NetworkDataInspectHandler<NetworkData>
|
||||
+ NetworkDataMutateHandler<NetworkData, BalanceOf<Self>>;
|
||||
@@ -195,6 +256,8 @@ pub mod pallet {
|
||||
IdentificationTuple<Self>,
|
||||
ThrottlingOffence<IdentificationTuple<Self>>,
|
||||
>;
|
||||
type DisabledValidators: DisabledValidators;
|
||||
type ApplauseListener: ApplauseListener<BalanceOf<Self>>;
|
||||
|
||||
#[pallet::constant]
|
||||
type MaxAuthorities: Get<u32>;
|
||||
@@ -211,12 +274,16 @@ pub mod pallet {
|
||||
#[pallet::constant]
|
||||
type HistoryDepth: Get<SessionIndex>;
|
||||
|
||||
#[pallet::constant]
|
||||
type MinAuthoritiesNumber: Get<u32>;
|
||||
|
||||
type WeightInfo: WeightInfo;
|
||||
}
|
||||
|
||||
#[pallet::event]
|
||||
#[pallet::generate_deposit(pub(super) fn deposit_event)]
|
||||
pub enum Event<T: Config> {
|
||||
BlackSwan,
|
||||
AuthoritiesEquilibrium,
|
||||
SomeAuthoritiesTrottling {
|
||||
throttling: Vec<IdentificationTuple<T>>,
|
||||
@@ -233,21 +300,48 @@ pub mod pallet {
|
||||
receiver: T::AccountId,
|
||||
received_amount: BalanceOf<T>,
|
||||
},
|
||||
BlockCommited {
|
||||
authority_id: AuthIndex,
|
||||
network_id: NetworkIdOf<T>,
|
||||
},
|
||||
}
|
||||
|
||||
#[pallet::error]
|
||||
pub enum Error<T> {
|
||||
NotEnoughClaps,
|
||||
NotAnAuthority,
|
||||
CurrentValidatorIsDisabled,
|
||||
AlreadyClapped,
|
||||
UnregisteredClapRemove,
|
||||
TooMuchAuthorities,
|
||||
CouldNotAccumulateCommission,
|
||||
CouldNotAccumulateIncomingImbalance,
|
||||
CouldNotIncreaseGatekeeperAmount,
|
||||
NonExistentAuthorityIndex,
|
||||
TimeWentBackwards,
|
||||
}
|
||||
|
||||
#[pallet::storage]
|
||||
#[pallet::getter(fn clapped_amount)]
|
||||
pub(super) type ClappedAmount<T: Config> = StorageNMap<
|
||||
_,
|
||||
(
|
||||
NMapKey<Twox64Concat, SessionIndex>,
|
||||
NMapKey<Twox64Concat, H256>,
|
||||
NMapKey<Twox64Concat, H256>,
|
||||
),
|
||||
BalanceOf<T>,
|
||||
ValueQuery,
|
||||
>;
|
||||
|
||||
#[pallet::storage]
|
||||
#[pallet::getter(fn block_commitments)]
|
||||
pub(super) type BlockCommitments<T: Config> = StorageMap<
|
||||
_,
|
||||
Twox64Concat,
|
||||
NetworkIdOf<T>,
|
||||
BTreeMap<AuthIndex, CommitmentDetails>,
|
||||
ValueQuery,
|
||||
>;
|
||||
|
||||
#[pallet::storage]
|
||||
#[pallet::getter(fn received_claps)]
|
||||
pub(super) type ReceivedClaps<T: Config> = StorageNMap<
|
||||
@@ -294,6 +388,16 @@ pub mod pallet {
|
||||
ValueQuery,
|
||||
>;
|
||||
|
||||
#[pallet::storage]
|
||||
#[pallet::getter(fn validators)]
|
||||
pub(super) type Validators<T: Config> = StorageMap<
|
||||
_,
|
||||
Twox64Concat,
|
||||
SessionIndex,
|
||||
WeakBoundedVec<ValidatorId<T>, T::MaxAuthorities>,
|
||||
OptionQuery,
|
||||
>;
|
||||
|
||||
#[pallet::genesis_config]
|
||||
#[derive(frame_support::DefaultNoBound)]
|
||||
pub struct GenesisConfig<T: Config> {
|
||||
@@ -326,33 +430,24 @@ pub mod pallet {
|
||||
}
|
||||
|
||||
#[pallet::call_index(1)]
|
||||
#[pallet::weight(T::WeightInfo::self_applause())]
|
||||
pub fn self_applause(
|
||||
#[pallet::weight((T::WeightInfo::commit_block(), DispatchClass::Normal, Pays::No))]
|
||||
pub fn commit_block(
|
||||
origin: OriginFor<T>,
|
||||
network_id: NetworkIdOf<T>,
|
||||
session_index: SessionIndex,
|
||||
transaction_hash: H256,
|
||||
receiver: T::AccountId,
|
||||
amount: BalanceOf<T>,
|
||||
block_commitment: BlockCommitment<NetworkIdOf<T>>,
|
||||
// since signature verification is done in `validate_unsigned`
|
||||
// we can skip doing it here again.
|
||||
_signature: <T::AuthorityId as RuntimeAppPublic>::Signature,
|
||||
) -> DispatchResult {
|
||||
let _ = ensure_signed(origin)?;
|
||||
Self::applause_if_posible(
|
||||
network_id,
|
||||
session_index,
|
||||
transaction_hash,
|
||||
receiver,
|
||||
amount,
|
||||
)
|
||||
ensure_none(origin)?;
|
||||
Self::try_commit_block(&block_commitment)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[pallet::hooks]
|
||||
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
|
||||
fn offchain_worker(now: BlockNumberFor<T>) {
|
||||
match Self::start_slow_clapping(now) {
|
||||
Ok(iter) => {
|
||||
for result in iter.into_iter() {
|
||||
if let Err(e) = result {
|
||||
if let Err(e) = Self::start_slow_clapping(now) {
|
||||
log::info!(
|
||||
target: LOG_TARGET,
|
||||
"👏 Skipping slow clap at {:?}: {:?}",
|
||||
@@ -362,30 +457,56 @@ pub mod pallet {
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => log::info!(
|
||||
target: LOG_TARGET,
|
||||
"👏 Could not start slow clap at {:?}: {:?}",
|
||||
now,
|
||||
e,
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[pallet::validate_unsigned]
|
||||
impl<T: Config> ValidateUnsigned for Pallet<T> {
|
||||
type Call = Call<T>;
|
||||
|
||||
fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity {
|
||||
if let Call::slow_clap { clap, signature } = call {
|
||||
let authorities = Authorities::<T>::get(&clap.session_index);
|
||||
match call {
|
||||
Call::commit_block {
|
||||
block_commitment,
|
||||
signature,
|
||||
} => {
|
||||
let authorities = Authorities::<T>::get(&block_commitment.session_index);
|
||||
let authority = match authorities.get(block_commitment.authority_index as usize)
|
||||
{
|
||||
Some(authority) => authority,
|
||||
None => return InvalidTransaction::BadSigner.into(),
|
||||
};
|
||||
|
||||
let signature_valid = block_commitment.using_encoded(|encoded_commitment| {
|
||||
authority.verify(&encoded_commitment, signature)
|
||||
});
|
||||
|
||||
if !signature_valid {
|
||||
return InvalidTransaction::BadProof.into();
|
||||
}
|
||||
|
||||
ValidTransaction::with_tag_prefix("SlowClap")
|
||||
.priority(T::UnsignedPriority::get())
|
||||
.and_provides(block_commitment.commitment.encode())
|
||||
.longevity(LOCK_BLOCK_EXPIRATION)
|
||||
.propagate(true)
|
||||
.build()
|
||||
}
|
||||
Call::slow_clap { clap, signature } => {
|
||||
let (session_index, _) = Self::mended_session_index(&clap);
|
||||
let authorities = Authorities::<T>::get(&session_index);
|
||||
let authority = match authorities.get(clap.authority_index as usize) {
|
||||
Some(authority) => authority,
|
||||
None => return InvalidTransaction::BadSigner.into(),
|
||||
};
|
||||
|
||||
let signature_valid =
|
||||
clap.using_encoded(|encoded_clap| authority.verify(&encoded_clap, signature));
|
||||
if ClapsInSession::<T>::get(&session_index)
|
||||
.get(&clap.authority_index)
|
||||
.map(|info| info.disabled)
|
||||
.unwrap_or_default()
|
||||
{
|
||||
return InvalidTransaction::BadSigner.into();
|
||||
}
|
||||
|
||||
let signature_valid = clap
|
||||
.using_encoded(|encoded_clap| authority.verify(&encoded_clap, signature));
|
||||
|
||||
if !signature_valid {
|
||||
return InvalidTransaction::BadProof.into();
|
||||
@@ -397,8 +518,8 @@ pub mod pallet {
|
||||
.longevity(LOCK_BLOCK_EXPIRATION)
|
||||
.propagate(true)
|
||||
.build()
|
||||
} else {
|
||||
InvalidTransaction::Call.into()
|
||||
}
|
||||
_ => InvalidTransaction::Call.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -459,29 +580,33 @@ impl<T: Config> Pallet<T> {
|
||||
hex_str
|
||||
}
|
||||
|
||||
fn try_slow_clap(clap: &Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>) -> DispatchResult {
|
||||
let authorities = Authorities::<T>::get(&clap.session_index);
|
||||
ensure!(
|
||||
authorities.get(clap.authority_index as usize).is_some(),
|
||||
Error::<T>::NotAnAuthority
|
||||
);
|
||||
ensure!(
|
||||
ClapsInSession::<T>::get(&clap.session_index)
|
||||
.get(&clap.authority_index)
|
||||
.map(|info| !info.disabled)
|
||||
.unwrap_or(true),
|
||||
Error::<T>::CurrentValidatorIsDisabled
|
||||
);
|
||||
|
||||
fn mended_session_index(
|
||||
clap: &Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>,
|
||||
) -> (SessionIndex, H256) {
|
||||
let prev_session_index = clap.session_index.saturating_sub(1);
|
||||
let clap_unique_hash =
|
||||
Self::generate_unique_hash(&clap.receiver, &clap.amount, &clap.network_id);
|
||||
|
||||
let received_claps_key = (
|
||||
clap.session_index,
|
||||
prev_session_index,
|
||||
&clap.transaction_hash,
|
||||
&clap_unique_hash,
|
||||
);
|
||||
|
||||
let number_of_received_claps =
|
||||
let session_index = ReceivedClaps::<T>::get(&received_claps_key)
|
||||
.is_empty()
|
||||
.then(|| clap.session_index)
|
||||
.unwrap_or(prev_session_index);
|
||||
|
||||
(session_index, clap_unique_hash)
|
||||
}
|
||||
|
||||
fn try_slow_clap(clap: &Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>) -> DispatchResult {
|
||||
let (session_index, clap_unique_hash) = Self::mended_session_index(&clap);
|
||||
let mut claps_in_session = ClapsInSession::<T>::get(&session_index);
|
||||
|
||||
let received_claps_key = (session_index, &clap.transaction_hash, &clap_unique_hash);
|
||||
|
||||
ReceivedClaps::<T>::try_mutate(&received_claps_key, |tree_of_claps| {
|
||||
let number_of_claps = tree_of_claps.len();
|
||||
match (tree_of_claps.contains(&clap.authority_index), clap.removed) {
|
||||
@@ -498,15 +623,15 @@ impl<T: Config> Pallet<T> {
|
||||
}
|
||||
})?;
|
||||
|
||||
ClapsInSession::<T>::mutate(&clap.session_index, |claps_details| {
|
||||
(*claps_details)
|
||||
claps_in_session
|
||||
.entry(clap.authority_index)
|
||||
.and_modify(|individual| (*individual).claps.saturating_inc())
|
||||
.and_modify(|individual| individual.claps.saturating_inc())
|
||||
.or_insert(SessionAuthorityInfo {
|
||||
claps: 1u32,
|
||||
disabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
ClapsInSession::<T>::insert(&session_index, claps_in_session);
|
||||
|
||||
Self::deposit_event(Event::<T>::Clapped {
|
||||
authority_id: clap.authority_index,
|
||||
@@ -517,8 +642,7 @@ impl<T: Config> Pallet<T> {
|
||||
});
|
||||
|
||||
let enough_authorities =
|
||||
Perbill::from_rational(number_of_received_claps as u32, authorities.len() as u32)
|
||||
> Perbill::from_percent(T::ApplauseThreshold::get());
|
||||
Self::validator_clap_by_amount(clap.authority_index, &received_claps_key);
|
||||
|
||||
if enough_authorities {
|
||||
let _ = Self::try_applause(&clap, &received_claps_key).inspect_err(|error_msg| {
|
||||
@@ -533,6 +657,24 @@ impl<T: Config> Pallet<T> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validator_clap_by_amount(
|
||||
authority_index: AuthIndex,
|
||||
received_claps_key: &(SessionIndex, &H256, &H256),
|
||||
) -> bool {
|
||||
let era = T::ApplauseListener::get_current_era();
|
||||
let threshold_amount = T::ApplauseListener::get_threshold_amount(era);
|
||||
let new_clapped_amount =
|
||||
T::ApplauseListener::get_validator_total_exposure(era, authority_index as usize);
|
||||
|
||||
let total_clapped = ClappedAmount::<T>::mutate(received_claps_key, |clapped_amount| {
|
||||
let total_clapped = clapped_amount.saturating_add(new_clapped_amount);
|
||||
*clapped_amount = total_clapped;
|
||||
total_clapped
|
||||
});
|
||||
|
||||
total_clapped >= threshold_amount
|
||||
}
|
||||
|
||||
fn try_applause(
|
||||
clap: &Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>,
|
||||
received_claps_key: &(SessionIndex, &H256, &H256),
|
||||
@@ -556,9 +698,7 @@ impl<T: Config> Pallet<T> {
|
||||
let _ = T::NetworkDataHandler::accumulate_commission(&commission)
|
||||
.map_err(|_| Error::<T>::CouldNotAccumulateCommission)?;
|
||||
|
||||
if final_amount > T::Currency::minimum_balance() {
|
||||
T::Currency::mint_into(&clap.receiver, final_amount)?;
|
||||
}
|
||||
let _ = T::Currency::deposit_creating(&clap.receiver, final_amount);
|
||||
|
||||
*is_applaused = true;
|
||||
|
||||
@@ -572,45 +712,33 @@ impl<T: Config> Pallet<T> {
|
||||
})
|
||||
}
|
||||
|
||||
fn applause_if_posible(
|
||||
network_id: NetworkIdOf<T>,
|
||||
session_index: SessionIndex,
|
||||
transaction_hash: H256,
|
||||
receiver: T::AccountId,
|
||||
amount: BalanceOf<T>,
|
||||
) -> DispatchResult {
|
||||
let clap_unique_hash = Self::generate_unique_hash(&receiver, &amount, &network_id);
|
||||
let received_claps_key = (session_index, &transaction_hash, &clap_unique_hash);
|
||||
fn try_commit_block(new_commitment: &BlockCommitment<NetworkIdOf<T>>) -> DispatchResult {
|
||||
BlockCommitments::<T>::try_mutate(&new_commitment.network_id, |current_commitments| {
|
||||
let authority_index = new_commitment.authority_index;
|
||||
let new_commitment_details = new_commitment.commitment;
|
||||
|
||||
let clap = Clap {
|
||||
authority_index: Default::default(),
|
||||
block_number: Default::default(),
|
||||
removed: false,
|
||||
session_index,
|
||||
network_id,
|
||||
receiver,
|
||||
amount,
|
||||
transaction_hash,
|
||||
};
|
||||
let current_last_updated = current_commitments
|
||||
.get(&authority_index)
|
||||
.map(|details| details.last_updated)
|
||||
.unwrap_or_default();
|
||||
|
||||
let enough_authorities = Perbill::from_rational(
|
||||
ReceivedClaps::<T>::get(&received_claps_key).len() as u32,
|
||||
Authorities::<T>::get(session_index).len() as u32,
|
||||
) > Perbill::from_percent(T::ApplauseThreshold::get());
|
||||
ensure!(
|
||||
new_commitment_details.last_updated > current_last_updated,
|
||||
Error::<T>::TimeWentBackwards
|
||||
);
|
||||
|
||||
ensure!(enough_authorities, Error::<T>::NotEnoughClaps);
|
||||
Self::try_applause(&clap, &received_claps_key)?;
|
||||
current_commitments.insert(authority_index, new_commitment_details);
|
||||
|
||||
Self::deposit_event(Event::<T>::BlockCommited {
|
||||
network_id: new_commitment.network_id,
|
||||
authority_id: authority_index,
|
||||
});
|
||||
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn start_slow_clapping(
|
||||
block_number: BlockNumberFor<T>,
|
||||
) -> OffchainResult<T, impl Iterator<Item = OffchainResult<T, ()>>> {
|
||||
sp_io::offchain::is_validator()
|
||||
.then(|| ())
|
||||
.ok_or(OffchainErr::NotValidator)?;
|
||||
|
||||
fn start_slow_clapping(block_number: BlockNumberFor<T>) -> OffchainResult<T, ()> {
|
||||
let session_index = T::ValidatorSet::session_index();
|
||||
let networks_len = T::NetworkDataHandler::iter().count();
|
||||
let network_in_use = T::NetworkDataHandler::iter()
|
||||
@@ -625,7 +753,6 @@ impl<T: Config> Pallet<T> {
|
||||
|
||||
let network_id_encoded = network_in_use.0.encode();
|
||||
|
||||
let last_timestamp_key = Self::create_storage_key(b"last-timestamp-", &network_id_encoded);
|
||||
let rate_limit_delay_key = Self::create_storage_key(b"rate-limit-", &network_id_encoded);
|
||||
let rate_limit_delay = Self::read_persistent_offchain_storage(
|
||||
&rate_limit_delay_key,
|
||||
@@ -634,51 +761,24 @@ impl<T: Config> Pallet<T> {
|
||||
|
||||
let network_lock_key = Self::create_storage_key(b"network-lock-", &network_id_encoded);
|
||||
let block_until =
|
||||
rt_offchain::Duration::from_millis(networks_len as u64 * FETCH_TIMEOUT_PERIOD);
|
||||
rt_offchain::Duration::from_millis(rate_limit_delay.max(MIN_LOCK_GUARD_PERIOD));
|
||||
let mut network_lock = StorageLock::<Time>::with_deadline(&network_lock_key, block_until);
|
||||
|
||||
network_lock
|
||||
let _lock_guard = network_lock
|
||||
.try_lock()
|
||||
.map_err(|_| OffchainErr::OffchainTimeoutPeriod(network_in_use.0))?;
|
||||
|
||||
StorageValueRef::persistent(&last_timestamp_key)
|
||||
.mutate(
|
||||
|result_timestamp: Result<Option<u64>, StorageRetrievalError>| {
|
||||
let current_timestmap = sp_io::offchain::timestamp().unix_millis();
|
||||
match result_timestamp {
|
||||
Ok(option_timestamp) => match option_timestamp {
|
||||
Some(stored_timestamp) if stored_timestamp > current_timestmap => {
|
||||
Err(OffchainErr::TooManyRequests(network_in_use.0).into())
|
||||
}
|
||||
_ => Ok(current_timestmap.saturating_add(rate_limit_delay)),
|
||||
},
|
||||
Err(_) => Err(OffchainErr::StorageRetrievalError(network_in_use.0).into()),
|
||||
}
|
||||
},
|
||||
)
|
||||
.map_err(|error| match error {
|
||||
MutateStorageError::ValueFunctionFailed(offchain_error) => offchain_error,
|
||||
MutateStorageError::ConcurrentModification(_) => {
|
||||
OffchainErr::ConcurrentModificationError(network_in_use.0).into()
|
||||
}
|
||||
})?;
|
||||
|
||||
Ok(
|
||||
Self::local_authorities(&session_index).map(move |(authority_index, authority_key)| {
|
||||
Self::do_evm_claps_or_save_block(
|
||||
authority_index,
|
||||
authority_key,
|
||||
session_index,
|
||||
log::info!(
|
||||
target: LOG_TARGET,
|
||||
"🧐 Offchain worker started for network #{:?} at block #{:?}",
|
||||
network_in_use.0,
|
||||
&network_in_use.1,
|
||||
)
|
||||
}),
|
||||
)
|
||||
block_number,
|
||||
);
|
||||
|
||||
Self::do_evm_claps_or_save_block(session_index, network_in_use.0, &network_in_use.1)
|
||||
}
|
||||
|
||||
fn do_evm_claps_or_save_block(
|
||||
authority_index: AuthIndex,
|
||||
authority_key: T::AuthorityId,
|
||||
session_index: SessionIndex,
|
||||
network_id: NetworkIdOf<T>,
|
||||
network_data: &NetworkData,
|
||||
@@ -702,167 +802,94 @@ impl<T: Config> Pallet<T> {
|
||||
let random_number = <u32>::decode(&mut TrailingZeroInput::new(random_seed.as_ref()))
|
||||
.expect("input is padded with zeroes; qed");
|
||||
|
||||
let rpc_endpoint = if stored_endpoints.len() > 0 {
|
||||
stored_endpoints
|
||||
.iter()
|
||||
.nth(
|
||||
(random_number as usize)
|
||||
let random_index = (random_number as usize)
|
||||
.checked_rem(stored_endpoints.len())
|
||||
.unwrap_or_default(),
|
||||
)
|
||||
.expect("stored endpoint should be non empty; qed")
|
||||
.unwrap_or_default();
|
||||
|
||||
let endpoints = if !stored_endpoints.is_empty() {
|
||||
&stored_endpoints
|
||||
} else {
|
||||
network_data
|
||||
.default_endpoints
|
||||
.iter()
|
||||
.nth(
|
||||
(random_number as usize)
|
||||
.checked_rem(network_data.default_endpoints.len())
|
||||
.unwrap_or_default(),
|
||||
)
|
||||
.expect("default endpoint should be non empty; qed")
|
||||
&network_data.default_endpoints
|
||||
};
|
||||
|
||||
StorageValueRef::persistent(&block_number_key)
|
||||
.mutate(
|
||||
|result_block_range: Result<Option<(u64, u64)>, StorageRetrievalError>| {
|
||||
match result_block_range {
|
||||
Ok(maybe_block_range) => {
|
||||
let request_body = match maybe_block_range {
|
||||
Some((from_block, to_block))
|
||||
if from_block < to_block.saturating_sub(1) =>
|
||||
{
|
||||
let rpc_endpoint = endpoints
|
||||
.get(random_index)
|
||||
.ok_or(OffchainErr::NoEndpointAvailable(network_id))?;
|
||||
|
||||
let (from_block, to_block): (u64, u64) = StorageValueRef::persistent(&block_number_key)
|
||||
.get()
|
||||
.map_err(|_| OffchainErr::StorageRetrievalError(network_id))?
|
||||
.unwrap_or_default();
|
||||
|
||||
let request_body = if from_block < to_block.saturating_sub(1) {
|
||||
Self::prepare_request_body_for_latest_transfers(
|
||||
from_block,
|
||||
to_block.saturating_sub(1),
|
||||
network_data,
|
||||
)
|
||||
}
|
||||
_ => Self::prepare_request_body_for_latest_block(network_data),
|
||||
} else {
|
||||
Self::prepare_request_body_for_latest_block(network_data)
|
||||
};
|
||||
|
||||
let response_bytes =
|
||||
Self::fetch_from_remote(&rpc_endpoint, &request_body)?;
|
||||
let response_bytes = Self::fetch_from_remote(&rpc_endpoint, &request_body)?;
|
||||
|
||||
match network_data.network_type {
|
||||
NetworkType::Evm => {
|
||||
let maybe_new_evm_block = Self::apply_evm_response(
|
||||
&response_bytes,
|
||||
let parsed_evm_response = Self::parse_evm_response(&response_bytes)?;
|
||||
let new_block_range = match parsed_evm_response {
|
||||
EvmResponseType::BlockNumber(new_evm_block) if from_block.le(&to_block) => {
|
||||
let estimated_block =
|
||||
new_evm_block.saturating_sub(network_data.finality_delay);
|
||||
let adjusted_block =
|
||||
Self::adjust_to_block(estimated_block, from_block, max_block_distance);
|
||||
|
||||
if from_block == 0 {
|
||||
(estimated_block, estimated_block)
|
||||
} else {
|
||||
(from_block, adjusted_block)
|
||||
}
|
||||
}
|
||||
_ => (to_block, to_block),
|
||||
};
|
||||
|
||||
StorageValueRef::persistent(&block_number_key).set(&new_block_range);
|
||||
|
||||
if !sp_io::offchain::is_validator() {
|
||||
log::info!(target: LOG_TARGET, "🧐 Not a validator; no transactions available");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for (authority_index, authority_key) in Self::local_authorities(&session_index) {
|
||||
parsed_evm_response.sign_and_submit::<T>(
|
||||
new_block_range.0,
|
||||
authority_index,
|
||||
authority_key,
|
||||
session_index,
|
||||
network_id,
|
||||
)?;
|
||||
);
|
||||
}
|
||||
|
||||
let estimated_block = maybe_new_evm_block
|
||||
.map(|new_evm_block| {
|
||||
new_evm_block
|
||||
.saturating_sub(network_data.finality_delay)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
Ok(match maybe_block_range {
|
||||
Some((from_block, to_block)) => match maybe_new_evm_block {
|
||||
Some(_) if from_block.le(&to_block) => {
|
||||
let adjusted_to_block = estimated_block
|
||||
.checked_sub(from_block)
|
||||
.map(|current_distance| current_distance
|
||||
.le(&max_block_distance)
|
||||
.then(|| estimated_block)
|
||||
)
|
||||
.flatten()
|
||||
.unwrap_or(from_block
|
||||
.saturating_add(max_block_distance)
|
||||
.min(estimated_block));
|
||||
(from_block, adjusted_to_block)
|
||||
}
|
||||
_ => (to_block, to_block),
|
||||
},
|
||||
None => (estimated_block, estimated_block),
|
||||
})
|
||||
}
|
||||
NetworkType::Utxo => {
|
||||
Err(OffchainErr::UtxoNotImplemented(network_id).into())
|
||||
Ok(())
|
||||
}
|
||||
NetworkType::Utxo => Err(OffchainErr::UtxoNotImplemented(network_id).into()),
|
||||
_ => Err(OffchainErr::UnknownNetworkType(network_id).into()),
|
||||
}
|
||||
}
|
||||
Err(_) => Err(OffchainErr::StorageRetrievalError(network_id).into()),
|
||||
}
|
||||
},
|
||||
)
|
||||
.map_err(|error| match error {
|
||||
MutateStorageError::ValueFunctionFailed(offchain_error) => offchain_error,
|
||||
MutateStorageError::ConcurrentModification(_) => {
|
||||
OffchainErr::ConcurrentModificationError(network_id).into()
|
||||
}
|
||||
|
||||
fn adjust_to_block(estimated_block: u64, from_block: u64, max_block_distance: u64) -> u64 {
|
||||
let fallback_value = from_block
|
||||
.saturating_add(max_block_distance)
|
||||
.min(estimated_block);
|
||||
|
||||
estimated_block
|
||||
.checked_sub(from_block)
|
||||
.map(|current_distance| {
|
||||
current_distance
|
||||
.le(&max_block_distance)
|
||||
.then_some(estimated_block)
|
||||
})
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
fn apply_evm_response(
|
||||
response_bytes: &[u8],
|
||||
authority_index: AuthIndex,
|
||||
authority_key: T::AuthorityId,
|
||||
session_index: SessionIndex,
|
||||
network_id: NetworkIdOf<T>,
|
||||
) -> OffchainResult<T, Option<u64>> {
|
||||
match Self::parse_evm_response(&response_bytes)? {
|
||||
EvmResponseType::BlockNumber(new_evm_block) => {
|
||||
log::info!(
|
||||
target: LOG_TARGET,
|
||||
"🧐 New evm block #{:?} found for network {:?}",
|
||||
new_evm_block,
|
||||
network_id,
|
||||
);
|
||||
Ok(Some(new_evm_block))
|
||||
}
|
||||
EvmResponseType::TransactionLogs(evm_logs) => {
|
||||
let claps: Vec<_> = evm_logs
|
||||
.iter()
|
||||
.filter_map(|log| {
|
||||
log.is_sufficient().then(|| Clap {
|
||||
authority_index,
|
||||
session_index,
|
||||
network_id,
|
||||
removed: log.removed,
|
||||
receiver: T::AccountId::decode(&mut &log.topics[1][0..32])
|
||||
.expect("32 bytes always construct an AccountId32"),
|
||||
amount: u128::from_be_bytes(
|
||||
log.topics[2][16..32]
|
||||
.try_into()
|
||||
.expect("amount is valid hex; qed"),
|
||||
)
|
||||
.saturated_into::<BalanceOf<T>>(),
|
||||
transaction_hash: log
|
||||
.transaction_hash
|
||||
.clone()
|
||||
.expect("tx hash exists; qed"),
|
||||
block_number: log.block_number.expect("block number exists; qed"),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
log::info!(
|
||||
target: LOG_TARGET,
|
||||
"🧐 {:?} evm logs found for network {:?}",
|
||||
claps.len(),
|
||||
network_id,
|
||||
);
|
||||
|
||||
for clap in claps {
|
||||
let signature = authority_key
|
||||
.sign(&clap.encode())
|
||||
.ok_or(OffchainErr::FailedSigning)?;
|
||||
let call = Call::slow_clap { clap, signature };
|
||||
|
||||
SubmitTransaction::<T, Call<T>>::submit_unsigned_transaction(call.into())
|
||||
.map_err(|_| OffchainErr::SubmitTransaction)?;
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
.flatten()
|
||||
.unwrap_or(fallback_value)
|
||||
}
|
||||
|
||||
fn local_authorities(
|
||||
@@ -1026,16 +1053,34 @@ impl<T: Config> Pallet<T> {
|
||||
let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities)
|
||||
.expect("more than the maximum number of authorities");
|
||||
|
||||
let validators = T::ValidatorSet::validators();
|
||||
let bounded_validators = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(validators)
|
||||
.expect("more than the maximum number of validators");
|
||||
|
||||
if let Some(target_session_index) = session_index.checked_sub(T::HistoryDepth::get()) {
|
||||
Self::clear_history(&target_session_index);
|
||||
}
|
||||
|
||||
Validators::<T>::insert(&session_index, bounded_validators);
|
||||
Authorities::<T>::set(&session_index, bounded_authorities);
|
||||
ClapsInSession::<T>::set(&session_index, Default::default());
|
||||
|
||||
let mut disabled_validators: BTreeMap<AuthIndex, SessionAuthorityInfo> = Default::default();
|
||||
for disabled_index in T::DisabledValidators::disabled_validators().iter() {
|
||||
let _ = disabled_validators.insert(
|
||||
*disabled_index,
|
||||
SessionAuthorityInfo {
|
||||
claps: 0u32,
|
||||
disabled: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
ClapsInSession::<T>::set(&session_index, disabled_validators);
|
||||
}
|
||||
|
||||
fn clear_history(target_session_index: &SessionIndex) {
|
||||
ClapsInSession::<T>::remove(target_session_index);
|
||||
Authorities::<T>::remove(target_session_index);
|
||||
Validators::<T>::remove(target_session_index);
|
||||
let mut cursor = ReceivedClaps::<T>::clear_prefix((target_session_index,), u32::MAX, None);
|
||||
debug_assert!(cursor.maybe_cursor.is_none());
|
||||
cursor =
|
||||
@@ -1049,11 +1094,6 @@ impl<T: Config> Pallet<T> {
|
||||
.expect("more than the maximum number of authorities");
|
||||
Authorities::<T>::set(session_index, bounded_authorities);
|
||||
}
|
||||
|
||||
#[cfg(feature = "runtime-benchmarks")]
|
||||
fn trigger_nullification_for_benchmark() {
|
||||
T::NetworkDataHandler::trigger_nullification();
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Config> sp_runtime::BoundToRuntimeAppPublic for Pallet<T> {
|
||||
@@ -1082,13 +1122,17 @@ impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
|
||||
where
|
||||
I: Iterator<Item = (&'a T::AccountId, T::AuthorityId)>,
|
||||
{
|
||||
for (network_id, _) in BlockCommitments::<T>::iter() {
|
||||
BlockCommitments::<T>::remove(network_id);
|
||||
}
|
||||
|
||||
let authorities = validators.map(|x| x.1).collect::<Vec<_>>();
|
||||
Self::initialize_authorities(authorities);
|
||||
}
|
||||
|
||||
fn on_before_session_ending() {
|
||||
let session_index = T::ValidatorSet::session_index();
|
||||
let validators = T::ValidatorSet::validators();
|
||||
let session_index = T::ValidatorSet::session_index().saturating_sub(1);
|
||||
let validators = Validators::<T>::get(&session_index).unwrap_or_default();
|
||||
let authorities_len = Authorities::<T>::get(&session_index).len();
|
||||
let claps_in_session = ClapsInSession::<T>::get(&session_index);
|
||||
|
||||
@@ -1097,16 +1141,31 @@ impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
|
||||
let offenders = validators
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter(|(index, _)| !Self::is_good_actor(*index, median_claps, &claps_in_session))
|
||||
.filter_map(|(_, id)| {
|
||||
.filter_map(|(index, id)| {
|
||||
(!Self::is_good_actor(index, median_claps, &claps_in_session)).then(|| {
|
||||
<T::ValidatorSet as ValidatorSetWithIdentification<T::AccountId>>::IdentificationOf::convert(
|
||||
id.clone(),
|
||||
).map(|full_id| (id, full_id))
|
||||
})
|
||||
.flatten()
|
||||
})
|
||||
.collect::<Vec<IdentificationTuple<T>>>();
|
||||
|
||||
if offenders.is_empty() {
|
||||
let disabled_validators = T::DisabledValidators::disabled_validators()
|
||||
.into_iter()
|
||||
.count();
|
||||
|
||||
let offenders_length = offenders.len();
|
||||
let authorities_left: u32 = authorities_len
|
||||
.saturating_sub(disabled_validators)
|
||||
.saturating_sub(offenders_length)
|
||||
.try_into()
|
||||
.unwrap_or_default();
|
||||
|
||||
if offenders_length == 0 {
|
||||
Self::deposit_event(Event::<T>::AuthoritiesEquilibrium);
|
||||
} else if authorities_left < T::MinAuthoritiesNumber::get() {
|
||||
Self::deposit_event(Event::<T>::BlackSwan);
|
||||
} else {
|
||||
Self::deposit_event(Event::<T>::SomeAuthoritiesTrottling {
|
||||
throttling: offenders.clone(),
|
||||
|
||||
@@ -3,14 +3,13 @@
|
||||
use frame_support::{
|
||||
derive_impl, parameter_types,
|
||||
traits::{ConstU32, ConstU64},
|
||||
weights::Weight,
|
||||
};
|
||||
use frame_system::EnsureRoot;
|
||||
use pallet_session::historical as pallet_session_historical;
|
||||
use sp_runtime::{
|
||||
curve::PiecewiseLinear,
|
||||
testing::{TestXt, UintAuthorityId},
|
||||
traits::ConvertInto,
|
||||
traits::{AtLeast32BitUnsigned, ConvertInto},
|
||||
Permill,
|
||||
};
|
||||
use sp_staking::{
|
||||
@@ -21,7 +20,7 @@ use sp_staking::{
|
||||
use sp_runtime::BuildStorage;
|
||||
|
||||
use crate as slow_clap;
|
||||
use crate::Config;
|
||||
use crate::{ApplauseListener, Config, EraIndex};
|
||||
|
||||
type Block = frame_system::mocking::MockBlock<Runtime>;
|
||||
|
||||
@@ -140,27 +139,6 @@ parameter_types! {
|
||||
pub static MockAverageSessionLength: Option<u64> = None;
|
||||
}
|
||||
|
||||
pub struct TestNextSessionRotation;
|
||||
impl frame_support::traits::EstimateNextSessionRotation<u64> for TestNextSessionRotation {
|
||||
fn average_session_length() -> u64 {
|
||||
let mock = MockAverageSessionLength::mutate(|p| p.take());
|
||||
mock.unwrap_or(pallet_session::PeriodicSessions::<Period, Offset>::average_session_length())
|
||||
}
|
||||
|
||||
fn estimate_current_session_progress(now: u64) -> (Option<Permill>, Weight) {
|
||||
let (estimate, weight) =
|
||||
pallet_session::PeriodicSessions::<Period, Offset>::estimate_current_session_progress(
|
||||
now,
|
||||
);
|
||||
let mock = MockCurrentSessionProgress::mutate(|p| p.take());
|
||||
(mock.unwrap_or(estimate), weight)
|
||||
}
|
||||
|
||||
fn estimate_next_session_rotation(now: u64) -> (Option<u64>, Weight) {
|
||||
pallet_session::PeriodicSessions::<Period, Offset>::estimate_next_session_rotation(now)
|
||||
}
|
||||
}
|
||||
|
||||
impl ghost_networks::Config for Runtime {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
type Currency = Balances;
|
||||
@@ -196,22 +174,50 @@ impl pallet_balances::Config for Runtime {
|
||||
type WeightInfo = ();
|
||||
}
|
||||
|
||||
type Balance = u64;
|
||||
|
||||
pub struct TestSomeCoolTrait;
|
||||
impl ApplauseListener<Balance> for TestSomeCoolTrait
|
||||
where
|
||||
Balance: AtLeast32BitUnsigned + From<u64>,
|
||||
{
|
||||
fn get_current_era() -> EraIndex {
|
||||
1
|
||||
}
|
||||
|
||||
fn get_threshold_amount(_era: EraIndex) -> Balance {
|
||||
666_666_667u64.into()
|
||||
}
|
||||
|
||||
fn get_validator_total_exposure(_era: EraIndex, index: usize) -> Balance {
|
||||
match index {
|
||||
0 => 500_000_000u64,
|
||||
1 => 300_000_000u64,
|
||||
2 => 200_000_000u64,
|
||||
_ => 0,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl Config for Runtime {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
type AuthorityId = UintAuthorityId;
|
||||
|
||||
type NextSessionRotation = TestNextSessionRotation;
|
||||
type ValidatorSet = Historical;
|
||||
type Currency = Balances;
|
||||
type NetworkDataHandler = Networks;
|
||||
type BlockNumberProvider = System;
|
||||
type ReportUnresponsiveness = OffenceHandler;
|
||||
type DisabledValidators = Session;
|
||||
type ApplauseListener = TestSomeCoolTrait;
|
||||
|
||||
type MaxAuthorities = ConstU32<5>;
|
||||
type ApplauseThreshold = ConstU32<50>;
|
||||
type OffenceThreshold = ConstU32<75>;
|
||||
type OffenceThreshold = ConstU32<0>;
|
||||
type UnsignedPriority = ConstU64<{ 1 << 20 }>;
|
||||
type HistoryDepth = HistoryDepth;
|
||||
type MinAuthoritiesNumber = ConstU32<2>;
|
||||
|
||||
type WeightInfo = ();
|
||||
}
|
||||
|
||||
@@ -70,6 +70,35 @@ fn do_clap_from_first_authority(
|
||||
SlowClap::slow_clap(RuntimeOrigin::none(), clap, signature)
|
||||
}
|
||||
|
||||
fn do_block_commitment(
|
||||
session_index: u32,
|
||||
network_id: u32,
|
||||
authority_index: u32,
|
||||
) -> dispatch::DispatchResult {
|
||||
let last_updated = 1337;
|
||||
|
||||
let block_commitment = BlockCommitment {
|
||||
session_index,
|
||||
authority_index,
|
||||
network_id,
|
||||
commitment: CommitmentDetails {
|
||||
last_registered_block: 69,
|
||||
last_seen_block: 420,
|
||||
last_updated,
|
||||
},
|
||||
};
|
||||
let authority = UintAuthorityId::from((authority_index + 1) as u64);
|
||||
let signature = authority.sign(&block_commitment.encode()).unwrap();
|
||||
|
||||
SlowClap::pre_dispatch(&crate::Call::commit_block {
|
||||
block_commitment: block_commitment.clone(),
|
||||
signature: signature.clone(),
|
||||
})
|
||||
.map_err(|e| <&'static str>::from(e))?;
|
||||
|
||||
SlowClap::commit_block(RuntimeOrigin::none(), block_commitment, signature)
|
||||
}
|
||||
|
||||
fn do_clap_from(
|
||||
session_index: u32,
|
||||
network_id: u32,
|
||||
@@ -100,7 +129,7 @@ fn do_clap_from(
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_throttling_slash_function() {
|
||||
fn should_calculate_throttling_slash_function_correctly() {
|
||||
let dummy_offence = ThrottlingOffence {
|
||||
session_index: 0,
|
||||
validator_set_count: 50,
|
||||
@@ -120,7 +149,7 @@ fn test_throttling_slash_function() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_median_calculations_are_correct() {
|
||||
fn should_calculate_median_correctly() {
|
||||
new_test_ext().execute_with(|| {
|
||||
let data = BTreeMap::from([
|
||||
(
|
||||
@@ -304,6 +333,16 @@ fn request_body_is_correct_for_get_logs() {
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_correctly_adjust_to_block() {
|
||||
assert_eq!(SlowClap::adjust_to_block(420, 69, 1337), 420);
|
||||
assert_eq!(SlowClap::adjust_to_block(420, 1337, 69), 420);
|
||||
assert_eq!(SlowClap::adjust_to_block(1337, 420, 69), 489);
|
||||
assert_eq!(SlowClap::adjust_to_block(1337, 69, 420), 489);
|
||||
assert_eq!(SlowClap::adjust_to_block(69, 1337, 420), 69);
|
||||
assert_eq!(SlowClap::adjust_to_block(69, 420, 1337), 69);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_make_http_call_for_block_number() {
|
||||
let (offchain, state) = TestOffchainExt::new();
|
||||
@@ -361,10 +400,14 @@ fn should_make_http_call_and_parse_block_number() {
|
||||
|
||||
let request_body = SlowClap::prepare_request_body_for_latest_block(&network_data);
|
||||
let raw_response = SlowClap::fetch_from_remote(&rpc_endpoint, &request_body)?;
|
||||
let maybe_evm_block_number =
|
||||
SlowClap::apply_evm_response(&raw_response, 69, Default::default(), 420, 1)?;
|
||||
let evm_block_number = SlowClap::parse_evm_response(&raw_response).map(
|
||||
|parsed_response| match parsed_response {
|
||||
EvmResponseType::BlockNumber(block_number) => block_number,
|
||||
EvmResponseType::TransactionLogs(_) => 0,
|
||||
},
|
||||
)?;
|
||||
|
||||
assert_eq!(maybe_evm_block_number, Some(20335745));
|
||||
assert_eq!(evm_block_number, 20335745);
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
@@ -382,7 +425,6 @@ fn should_make_http_call_and_parse_logs() {
|
||||
evm_logs_response(&mut state.write());
|
||||
|
||||
let _: Result<(), OffchainErr<u32>> = t.execute_with(|| {
|
||||
let session_index = advance_session_and_get_index();
|
||||
let rpc_endpoint = get_rpc_endpoint();
|
||||
|
||||
let from_block: u64 = 20335770;
|
||||
@@ -402,15 +444,6 @@ fn should_make_http_call_and_parse_logs() {
|
||||
EvmResponseType::TransactionLogs(evm_logs) => assert_eq!(evm_logs.len(), 2),
|
||||
}
|
||||
|
||||
let maybe_evm_block_number = SlowClap::apply_evm_response(
|
||||
&raw_response,
|
||||
1,
|
||||
UintAuthorityId::from(2),
|
||||
session_index,
|
||||
network_id,
|
||||
)?;
|
||||
|
||||
assert_eq!(maybe_evm_block_number, None);
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
@@ -529,25 +562,25 @@ fn should_applause_and_take_next_claps() {
|
||||
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
|
||||
false
|
||||
);
|
||||
assert_eq!(Balances::balance(&receiver), 0);
|
||||
assert_eq!(Balances::total_balance(&receiver), 0);
|
||||
assert_ok!(do_clap_from(session_index, network_id, 0, false));
|
||||
assert_eq!(
|
||||
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
|
||||
false
|
||||
);
|
||||
assert_eq!(Balances::balance(&receiver), 0);
|
||||
assert_eq!(Balances::total_balance(&receiver), 0);
|
||||
assert_ok!(do_clap_from(session_index, network_id, 1, false));
|
||||
assert_eq!(
|
||||
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
|
||||
true
|
||||
);
|
||||
assert_eq!(Balances::balance(&receiver), amount);
|
||||
assert_eq!(Balances::total_balance(&receiver), amount);
|
||||
assert_ok!(do_clap_from(session_index, network_id, 2, false));
|
||||
assert_eq!(
|
||||
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
|
||||
true
|
||||
);
|
||||
assert_eq!(Balances::balance(&receiver), amount);
|
||||
assert_eq!(Balances::total_balance(&receiver), amount);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -665,15 +698,14 @@ fn should_throw_error_if_session_index_is_not_current() {
|
||||
network_id,
|
||||
authority_prev
|
||||
));
|
||||
assert_ok!(do_clap_from_first_authority(
|
||||
session_index_next,
|
||||
network_id,
|
||||
authority_next
|
||||
));
|
||||
assert_err!(
|
||||
do_clap_from_first_authority(session_index_next, network_id, authority_next),
|
||||
DispatchError::Other("Transaction has a bad signature")
|
||||
);
|
||||
|
||||
assert_claps_info_correct(&storage_key_curr, &session_index_curr, 1);
|
||||
assert_claps_info_correct(&storage_key_prev, &session_index_prev, 1);
|
||||
assert_claps_info_correct(&storage_key_next, &session_index_next, 1);
|
||||
assert_claps_info_correct(&storage_key_next, &session_index_next, 0);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -688,22 +720,12 @@ fn should_throw_error_if_signer_has_incorrect_index() {
|
||||
let storage_key = (session_index, transaction_hash, unique_transaction_hash);
|
||||
|
||||
assert_claps_info_correct(&storage_key, &session_index, 0);
|
||||
let clap = Clap {
|
||||
block_number: 420,
|
||||
removed: false,
|
||||
transaction_hash,
|
||||
session_index,
|
||||
authority_index: 1337,
|
||||
network_id,
|
||||
receiver: 69,
|
||||
amount: 420,
|
||||
};
|
||||
let authority = UintAuthorityId::from((1) as u64);
|
||||
let signature = authority.sign(&clap.encode()).unwrap();
|
||||
assert_err!(
|
||||
SlowClap::slow_clap(RuntimeOrigin::none(), clap, signature),
|
||||
Error::<Runtime>::NotAnAuthority
|
||||
);
|
||||
assert_invalid_signing_address(session_index, network_id, 69);
|
||||
assert_transaction_has_bad_signature(session_index, network_id, 69);
|
||||
assert_invalid_signing_address(session_index, network_id, 420);
|
||||
assert_transaction_has_bad_signature(session_index, network_id, 420);
|
||||
assert_invalid_signing_address(session_index, network_id, 1337);
|
||||
assert_transaction_has_bad_signature(session_index, network_id, 1337);
|
||||
assert_claps_info_correct(&storage_key, &session_index, 0);
|
||||
});
|
||||
}
|
||||
@@ -721,7 +743,7 @@ fn should_throw_error_if_validator_disabled_and_ignore_later() {
|
||||
assert_eq!(Session::disable_index(0), true);
|
||||
assert_err!(
|
||||
do_clap_from(session_index, network_id, 0, false),
|
||||
Error::<Runtime>::CurrentValidatorIsDisabled
|
||||
DispatchError::Other("Invalid signing address")
|
||||
);
|
||||
|
||||
assert_eq!(pallet::ReceivedClaps::<Runtime>::get(&storage_key).len(), 0);
|
||||
@@ -790,8 +812,8 @@ fn should_clap_without_applause_on_gatekeeper_amount_overflow() {
|
||||
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key_first),
|
||||
true
|
||||
);
|
||||
assert_eq!(Balances::balance(&first_receiver), big_amount);
|
||||
assert_eq!(Balances::balance(&second_receiver), 0);
|
||||
assert_eq!(Balances::total_balance(&first_receiver), big_amount);
|
||||
assert_eq!(Balances::total_balance(&second_receiver), 0);
|
||||
|
||||
for authority_index in 0..=2 {
|
||||
let clap = Clap {
|
||||
@@ -809,8 +831,8 @@ fn should_clap_without_applause_on_gatekeeper_amount_overflow() {
|
||||
assert_ok!(SlowClap::slow_clap(RuntimeOrigin::none(), clap, signature));
|
||||
}
|
||||
|
||||
assert_eq!(Balances::balance(&first_receiver), big_amount);
|
||||
assert_eq!(Balances::balance(&second_receiver), 0);
|
||||
assert_eq!(Balances::total_balance(&first_receiver), big_amount);
|
||||
assert_eq!(Balances::total_balance(&second_receiver), 0);
|
||||
|
||||
assert_eq!(Networks::gatekeeper_amount(network_id), big_amount);
|
||||
assert_eq!(Networks::bridged_imbalance().bridged_in, big_amount);
|
||||
@@ -854,8 +876,8 @@ fn should_clap_without_applause_on_commission_overflow() {
|
||||
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key_first),
|
||||
true
|
||||
);
|
||||
assert_eq!(Balances::balance(&first_receiver), big_amount);
|
||||
assert_eq!(Balances::balance(&second_receiver), 0);
|
||||
assert_eq!(Balances::total_balance(&first_receiver), big_amount);
|
||||
assert_eq!(Balances::total_balance(&second_receiver), 0);
|
||||
|
||||
for authority_index in 0..=2 {
|
||||
let clap = Clap {
|
||||
@@ -873,8 +895,8 @@ fn should_clap_without_applause_on_commission_overflow() {
|
||||
assert_ok!(SlowClap::slow_clap(RuntimeOrigin::none(), clap, signature));
|
||||
}
|
||||
|
||||
assert_eq!(Balances::balance(&first_receiver), big_amount);
|
||||
assert_eq!(Balances::balance(&second_receiver), 0);
|
||||
assert_eq!(Balances::total_balance(&first_receiver), big_amount);
|
||||
assert_eq!(Balances::total_balance(&second_receiver), 0);
|
||||
|
||||
assert_eq!(Networks::gatekeeper_amount(network_id), big_amount);
|
||||
assert_eq!(Networks::gatekeeper_amount(network_id_other), big_amount);
|
||||
@@ -907,7 +929,7 @@ fn should_nullify_commission_on_finalize() {
|
||||
total_issuance,
|
||||
0u64
|
||||
),
|
||||
(420000000000000u64, 0u64)
|
||||
(amount, 0u64)
|
||||
); // precomputed values
|
||||
assert_eq!(Networks::is_nullification_period(), true);
|
||||
Networks::on_finalize(System::block_number());
|
||||
@@ -945,19 +967,18 @@ fn should_avoid_applause_during_nullification_period() {
|
||||
|
||||
assert_ok!(do_clap_from(session_index, network_id, 0, false));
|
||||
assert_ok!(do_clap_from(session_index, network_id, 1, false));
|
||||
assert_eq!(Balances::balance(&receiver), 0);
|
||||
assert_eq!(Balances::total_balance(&receiver), 0);
|
||||
|
||||
Networks::on_finalize(System::block_number());
|
||||
assert_eq!(Networks::is_nullification_period(), false);
|
||||
|
||||
assert_ok!(do_clap_from(session_index, network_id, 2, false));
|
||||
assert_eq!(Balances::balance(&receiver), amount);
|
||||
assert_eq!(Balances::total_balance(&receiver), amount);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_self_applause_if_enough_received_claps() {
|
||||
let zero: u64 = 0u64;
|
||||
fn should_avoid_session_overlap_on_mended_session_index() {
|
||||
let (network_id, transaction_hash, unique_transaction_hash) =
|
||||
generate_unique_hash(None, None, None, None);
|
||||
let (_, receiver, amount) = get_mocked_metadata();
|
||||
@@ -967,67 +988,23 @@ fn should_self_applause_if_enough_received_claps() {
|
||||
let session_index = advance_session_and_get_index();
|
||||
let storage_key = (session_index, transaction_hash, unique_transaction_hash);
|
||||
|
||||
assert_err!(
|
||||
SlowClap::self_applause(
|
||||
RuntimeOrigin::signed(receiver),
|
||||
network_id,
|
||||
session_index,
|
||||
transaction_hash,
|
||||
receiver,
|
||||
amount,
|
||||
),
|
||||
Error::<Runtime>::NotEnoughClaps
|
||||
);
|
||||
assert_ok!(do_clap_from(session_index, network_id, 0, false));
|
||||
advance_session();
|
||||
|
||||
assert_eq!(
|
||||
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
|
||||
false
|
||||
);
|
||||
assert_eq!(Balances::balance(&receiver), zero);
|
||||
assert_eq!(
|
||||
BridgedInflationCurve::<RewardCurve, Runtime>::era_payout(zero, zero, zero),
|
||||
(zero, zero)
|
||||
);
|
||||
assert_eq!(Balances::total_balance(&receiver), 0u64);
|
||||
|
||||
assert_ok!(do_clap_from(session_index, network_id, 0, false));
|
||||
assert_ok!(do_clap_from(session_index, network_id, 1, false));
|
||||
assert_ok!(do_clap_from(session_index, network_id, 2, false));
|
||||
|
||||
assert_eq!(
|
||||
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
|
||||
false
|
||||
);
|
||||
assert_eq!(Balances::balance(&receiver), 0);
|
||||
|
||||
assert_ok!(SlowClap::self_applause(
|
||||
RuntimeOrigin::signed(receiver),
|
||||
network_id,
|
||||
session_index,
|
||||
transaction_hash,
|
||||
receiver,
|
||||
amount,
|
||||
));
|
||||
assert_eq!(
|
||||
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
|
||||
false
|
||||
);
|
||||
assert_eq!(Balances::balance(&receiver), 0);
|
||||
|
||||
Networks::on_finalize(System::block_number());
|
||||
|
||||
assert_ok!(SlowClap::self_applause(
|
||||
RuntimeOrigin::signed(receiver),
|
||||
network_id,
|
||||
session_index,
|
||||
transaction_hash,
|
||||
receiver,
|
||||
amount,
|
||||
));
|
||||
assert_eq!(
|
||||
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
|
||||
true
|
||||
);
|
||||
assert_eq!(Balances::balance(&receiver), amount);
|
||||
assert_eq!(Balances::total_balance(&receiver), amount);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1117,7 +1094,7 @@ fn should_not_fail_on_sub_existential_balance() {
|
||||
assert_eq!(Networks::gatekeeper_amount(network_id), 0);
|
||||
assert_eq!(Networks::bridged_imbalance().bridged_in, 0);
|
||||
assert_eq!(Networks::bridged_imbalance().bridged_out, 0);
|
||||
assert_eq!(Balances::balance(&receiver), 0);
|
||||
assert_eq!(Balances::total_balance(&receiver), 0);
|
||||
assert_eq!(
|
||||
SlowClap::applauses_for_transaction(&received_claps_key),
|
||||
false
|
||||
@@ -1131,7 +1108,7 @@ fn should_not_fail_on_sub_existential_balance() {
|
||||
assert_eq!(Networks::gatekeeper_amount(network_id), amount);
|
||||
assert_eq!(Networks::bridged_imbalance().bridged_in, 0);
|
||||
assert_eq!(Networks::bridged_imbalance().bridged_out, 0);
|
||||
assert_eq!(Balances::balance(&receiver), 0);
|
||||
assert_eq!(Balances::total_balance(&receiver), 0);
|
||||
assert_eq!(
|
||||
SlowClap::applauses_for_transaction(&received_claps_key),
|
||||
true
|
||||
@@ -1139,6 +1116,99 @@ fn should_not_fail_on_sub_existential_balance() {
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_emit_black_swan_if_not_enough_authorities_left() {
|
||||
let (network_id, _, _) = generate_unique_hash(None, None, None, None);
|
||||
|
||||
new_test_ext().execute_with(|| {
|
||||
let session_index = advance_session_and_get_index();
|
||||
assert_ok!(do_clap_from(session_index, network_id, 0, false));
|
||||
Session::disable_index(1);
|
||||
Session::disable_index(2);
|
||||
|
||||
advance_session();
|
||||
advance_session();
|
||||
System::assert_has_event(RuntimeEvent::SlowClap(crate::Event::BlackSwan));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_register_block_commitments() {
|
||||
let (network_id, _, _) = generate_unique_hash(None, None, None, None);
|
||||
|
||||
new_test_ext().execute_with(|| {
|
||||
let session_index = advance_session_and_get_index();
|
||||
|
||||
for commitment_details in SlowClap::block_commitments(network_id).values() {
|
||||
assert_eq!(commitment_details.last_registered_block, 0);
|
||||
assert_eq!(commitment_details.last_seen_block, 0);
|
||||
assert_eq!(commitment_details.last_updated, 0);
|
||||
}
|
||||
|
||||
assert_ok!(do_block_commitment(session_index, network_id, 0));
|
||||
assert_ok!(do_block_commitment(session_index, network_id, 1));
|
||||
assert_ok!(do_block_commitment(session_index, network_id, 2));
|
||||
|
||||
assert_err!(
|
||||
do_block_commitment(session_index, network_id, 3),
|
||||
DispatchError::Other("Invalid signing address"),
|
||||
);
|
||||
|
||||
assert_err!(
|
||||
do_block_commitment(session_index, network_id, 1),
|
||||
Error::<Runtime>::TimeWentBackwards,
|
||||
);
|
||||
|
||||
for commitment_details in SlowClap::block_commitments(network_id).values() {
|
||||
assert_eq!(commitment_details.last_registered_block, 69);
|
||||
assert_eq!(commitment_details.last_seen_block, 420);
|
||||
assert_eq!(commitment_details.last_updated, 1337);
|
||||
}
|
||||
|
||||
advance_session();
|
||||
|
||||
for commitment_details in SlowClap::block_commitments(network_id).values() {
|
||||
assert_eq!(commitment_details.last_registered_block, 0);
|
||||
assert_eq!(commitment_details.last_seen_block, 0);
|
||||
assert_eq!(commitment_details.last_updated, 0);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_accumulate_clapped_amount() {
|
||||
let (network_id, transaction_hash, unique_transaction_hash) =
|
||||
generate_unique_hash(None, None, None, None);
|
||||
|
||||
new_test_ext().execute_with(|| {
|
||||
let session_index = advance_session_and_get_index();
|
||||
let storage_key = (session_index, transaction_hash, unique_transaction_hash);
|
||||
|
||||
let era = <Runtime as Config>::ApplauseListener::get_current_era();
|
||||
let threshold_amount = <Runtime as Config>::ApplauseListener::get_threshold_amount(era);
|
||||
|
||||
assert_eq!(
|
||||
ClappedAmount::<Runtime>::get(&storage_key) < threshold_amount,
|
||||
true
|
||||
);
|
||||
assert_ok!(do_clap_from(session_index, network_id, 2, false));
|
||||
assert_eq!(
|
||||
ClappedAmount::<Runtime>::get(&storage_key) < threshold_amount,
|
||||
true
|
||||
);
|
||||
assert_ok!(do_clap_from(session_index, network_id, 1, false));
|
||||
assert_eq!(
|
||||
ClappedAmount::<Runtime>::get(&storage_key) < threshold_amount,
|
||||
true
|
||||
);
|
||||
assert_ok!(do_clap_from(session_index, network_id, 0, false));
|
||||
assert_eq!(
|
||||
ClappedAmount::<Runtime>::get(&storage_key) > threshold_amount,
|
||||
true
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
fn advance_session_and_get_index() -> u32 {
|
||||
advance_session();
|
||||
assert_eq!(Session::validators(), Vec::<u64>::new());
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
//! Autogenerated weights for `ghost_slow_clap`
|
||||
//!
|
||||
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0
|
||||
//! DATE: 2025-06-19, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
|
||||
//! DATE: 2025-11-06, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
|
||||
//! WORST CASE MAP SIZE: `1000000`
|
||||
//! HOSTNAME: `ghostown`, CPU: `Intel(R) Core(TM) i3-2310M CPU @ 2.10GHz`
|
||||
//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("casper-dev")`, DB CACHE: 1024
|
||||
@@ -48,70 +48,7 @@ use core::marker::PhantomData;
|
||||
|
||||
pub trait WeightInfo {
|
||||
fn slow_clap() -> Weight;
|
||||
fn self_applause()-> Weight;
|
||||
}
|
||||
|
||||
/// Weight functions for `ghost_slow_clap`.
|
||||
pub struct SubstrateWeight<T>(PhantomData<T>);
|
||||
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
|
||||
/// Storage: `GhostSlowClaps::Authorities` (r:1 w:0)
|
||||
/// Proof: `GhostSlowClaps::Authorities` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostSlowClaps::ReceivedClaps` (r:1 w:1)
|
||||
/// Proof: `GhostSlowClaps::ReceivedClaps` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostSlowClaps::ClapsInSession` (r:1 w:1)
|
||||
/// Proof: `GhostSlowClaps::ClapsInSession` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:1)
|
||||
/// Proof: `GhostSlowClaps::ApplausesForTransaction` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostNetworks::NullifyNeeded` (r:1 w:0)
|
||||
/// Proof: `GhostNetworks::NullifyNeeded` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostNetworks::Networks` (r:1 w:0)
|
||||
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostNetworks::GatekeeperAmount` (r:1 w:1)
|
||||
/// Proof: `GhostNetworks::GatekeeperAmount` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostNetworks::BridgedImbalance` (r:1 w:1)
|
||||
/// Proof: `GhostNetworks::BridgedImbalance` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostNetworks::AccumulatedCommission` (r:1 w:1)
|
||||
/// Proof: `GhostNetworks::AccumulatedCommission` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `System::Account` (r:1 w:1)
|
||||
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
|
||||
fn slow_clap() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `355`
|
||||
// Estimated: `3820`
|
||||
// Minimum execution time: 213_817_000 picoseconds.
|
||||
Weight::from_parts(216_977_000, 0)
|
||||
.saturating_add(Weight::from_parts(0, 3820))
|
||||
.saturating_add(T::DbWeight::get().reads(10))
|
||||
.saturating_add(T::DbWeight::get().writes(7))
|
||||
}
|
||||
/// Storage: `GhostSlowClaps::ReceivedClaps` (r:1 w:0)
|
||||
/// Proof: `GhostSlowClaps::ReceivedClaps` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostSlowClaps::Authorities` (r:1 w:0)
|
||||
/// Proof: `GhostSlowClaps::Authorities` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:1)
|
||||
/// Proof: `GhostSlowClaps::ApplausesForTransaction` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostNetworks::NullifyNeeded` (r:1 w:0)
|
||||
/// Proof: `GhostNetworks::NullifyNeeded` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostNetworks::Networks` (r:1 w:0)
|
||||
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostNetworks::GatekeeperAmount` (r:1 w:1)
|
||||
/// Proof: `GhostNetworks::GatekeeperAmount` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostNetworks::BridgedImbalance` (r:1 w:1)
|
||||
/// Proof: `GhostNetworks::BridgedImbalance` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostNetworks::AccumulatedCommission` (r:1 w:1)
|
||||
/// Proof: `GhostNetworks::AccumulatedCommission` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `System::Account` (r:1 w:1)
|
||||
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
|
||||
fn self_applause() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `655`
|
||||
// Estimated: `4120`
|
||||
// Minimum execution time: 210_676_000 picoseconds.
|
||||
Weight::from_parts(212_905_000, 0)
|
||||
.saturating_add(Weight::from_parts(0, 4120))
|
||||
.saturating_add(T::DbWeight::get().reads(9))
|
||||
.saturating_add(T::DbWeight::get().writes(5))
|
||||
}
|
||||
fn commit_block()-> Weight;
|
||||
}
|
||||
|
||||
impl WeightInfo for () {
|
||||
@@ -145,32 +82,8 @@ impl WeightInfo for () {
|
||||
.saturating_add(RocksDbWeight::get().reads(10))
|
||||
.saturating_add(RocksDbWeight::get().writes(7))
|
||||
}
|
||||
/// Storage: `GhostSlowClaps::ReceivedClaps` (r:1 w:0)
|
||||
/// Proof: `GhostSlowClaps::ReceivedClaps` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostSlowClaps::Authorities` (r:1 w:0)
|
||||
/// Proof: `GhostSlowClaps::Authorities` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:1)
|
||||
/// Proof: `GhostSlowClaps::ApplausesForTransaction` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostNetworks::NullifyNeeded` (r:1 w:0)
|
||||
/// Proof: `GhostNetworks::NullifyNeeded` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostNetworks::Networks` (r:1 w:0)
|
||||
/// Proof: `GhostNetworks::Networks` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostNetworks::GatekeeperAmount` (r:1 w:1)
|
||||
/// Proof: `GhostNetworks::GatekeeperAmount` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostNetworks::BridgedImbalance` (r:1 w:1)
|
||||
/// Proof: `GhostNetworks::BridgedImbalance` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostNetworks::AccumulatedCommission` (r:1 w:1)
|
||||
/// Proof: `GhostNetworks::AccumulatedCommission` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `System::Account` (r:1 w:1)
|
||||
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
|
||||
fn self_applause() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `655`
|
||||
// Estimated: `4120`
|
||||
// Minimum execution time: 210_676_000 picoseconds.
|
||||
Weight::from_parts(212_905_000, 0)
|
||||
.saturating_add(Weight::from_parts(0, 4120))
|
||||
.saturating_add(RocksDbWeight::get().reads(9))
|
||||
.saturating_add(RocksDbWeight::get().writes(5))
|
||||
|
||||
fn commit_block()-> Weight {
|
||||
Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "casper-runtime"
|
||||
version = "3.5.31"
|
||||
version = "3.5.33"
|
||||
build = "build.rs"
|
||||
description = "Runtime of the Casper Network"
|
||||
edition.workspace = true
|
||||
|
||||
@@ -117,11 +117,11 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
|
||||
spec_name: create_runtime_str!("casper"),
|
||||
impl_name: create_runtime_str!("casper-svengali"),
|
||||
authoring_version: 0,
|
||||
spec_version: 2,
|
||||
impl_version: 0,
|
||||
spec_version: 3,
|
||||
impl_version: 1,
|
||||
apis: RUNTIME_API_VERSIONS,
|
||||
transaction_version: 1,
|
||||
state_version: 0,
|
||||
state_version: 1,
|
||||
};
|
||||
|
||||
/// The BABE epoch configuration at genesis.
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
//! Autogenerated weights for `ghost_slow_clap`
|
||||
//!
|
||||
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0
|
||||
//! DATE: 2025-06-19, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
|
||||
//! DATE: 2025-11-06, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
|
||||
//! WORST CASE MAP SIZE: `1000000`
|
||||
//! HOSTNAME: `ghostown`, CPU: `Intel(R) Core(TM) i3-2310M CPU @ 2.10GHz`
|
||||
//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("casper-dev")`, DB CACHE: 1024
|
||||
@@ -46,12 +46,12 @@ use core::marker::PhantomData;
|
||||
/// Weight functions for `ghost_slow_clap`.
|
||||
pub struct WeightInfo<T>(PhantomData<T>);
|
||||
impl<T: frame_system::Config> ghost_slow_clap::WeightInfo for WeightInfo<T> {
|
||||
/// Storage: `GhostSlowClaps::Authorities` (r:1 w:0)
|
||||
/// Proof: `GhostSlowClaps::Authorities` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostSlowClaps::ReceivedClaps` (r:1 w:1)
|
||||
/// Proof: `GhostSlowClaps::ReceivedClaps` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostSlowClaps::ClapsInSession` (r:1 w:1)
|
||||
/// Proof: `GhostSlowClaps::ClapsInSession` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostSlowClaps::Authorities` (r:1 w:0)
|
||||
/// Proof: `GhostSlowClaps::Authorities` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:1)
|
||||
/// Proof: `GhostSlowClaps::ApplausesForTransaction` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostNetworks::NullifyNeeded` (r:1 w:0)
|
||||
@@ -68,18 +68,20 @@ impl<T: frame_system::Config> ghost_slow_clap::WeightInfo for WeightInfo<T> {
|
||||
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
|
||||
fn slow_clap() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `355`
|
||||
// Estimated: `3820`
|
||||
// Minimum execution time: 213_817_000 picoseconds.
|
||||
Weight::from_parts(216_977_000, 0)
|
||||
.saturating_add(Weight::from_parts(0, 3820))
|
||||
// Measured: `387`
|
||||
// Estimated: `3852`
|
||||
// Minimum execution time: 220_008_000 picoseconds.
|
||||
Weight::from_parts(223_058_000, 0)
|
||||
.saturating_add(Weight::from_parts(0, 3852))
|
||||
.saturating_add(T::DbWeight::get().reads(10))
|
||||
.saturating_add(T::DbWeight::get().writes(7))
|
||||
}
|
||||
/// Storage: `GhostSlowClaps::ReceivedClaps` (r:1 w:0)
|
||||
/// Proof: `GhostSlowClaps::ReceivedClaps` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostSlowClaps::Authorities` (r:1 w:0)
|
||||
/// Storage: `GhostSlowClaps::Authorities` (r:2 w:0)
|
||||
/// Proof: `GhostSlowClaps::Authorities` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostSlowClaps::ReceivedClaps` (r:2 w:0)
|
||||
/// Proof: `GhostSlowClaps::ReceivedClaps` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostSlowClaps::ClapsInSession` (r:1 w:0)
|
||||
/// Proof: `GhostSlowClaps::ClapsInSession` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostSlowClaps::ApplausesForTransaction` (r:1 w:1)
|
||||
/// Proof: `GhostSlowClaps::ApplausesForTransaction` (`max_values`: None, `max_size`: None, mode: `Measured`)
|
||||
/// Storage: `GhostNetworks::NullifyNeeded` (r:1 w:0)
|
||||
@@ -96,12 +98,12 @@ impl<T: frame_system::Config> ghost_slow_clap::WeightInfo for WeightInfo<T> {
|
||||
/// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`)
|
||||
fn self_applause() -> Weight {
|
||||
// Proof Size summary in bytes:
|
||||
// Measured: `655`
|
||||
// Estimated: `4120`
|
||||
// Minimum execution time: 210_676_000 picoseconds.
|
||||
Weight::from_parts(212_905_000, 0)
|
||||
.saturating_add(Weight::from_parts(0, 4120))
|
||||
.saturating_add(T::DbWeight::get().reads(9))
|
||||
// Measured: `861`
|
||||
// Estimated: `6801`
|
||||
// Minimum execution time: 258_510_000 picoseconds.
|
||||
Weight::from_parts(262_353_000, 0)
|
||||
.saturating_add(Weight::from_parts(0, 6801))
|
||||
.saturating_add(T::DbWeight::get().reads(12))
|
||||
.saturating_add(T::DbWeight::get().writes(5))
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user