offchain worker restructure and block commitments added
Signed-off-by: Uncle Stinky <uncle.stinky@ghostchain.io>
This commit is contained in:
parent
d76646c191
commit
0bb46482b2
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ghost-slow-clap"
|
||||
version = "0.3.54"
|
||||
version = "0.3.55"
|
||||
description = "Applause protocol for the EVM bridge"
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
|
||||
@ -17,68 +17,21 @@ benchmarks! {
|
||||
let minimum_balance = <<T as pallet::Config>::Currency>::minimum_balance();
|
||||
let receiver = create_account::<T>();
|
||||
let amount = minimum_balance + minimum_balance;
|
||||
|
||||
let network_id = NetworkIdOf::<T>::default();
|
||||
let session_index = T::ValidatorSet::session_index();
|
||||
let transaction_hash = H256::repeat_byte(1u8);
|
||||
let args_hash = Pallet::<T>::generate_unique_hash(&receiver, &amount, &network_id);
|
||||
|
||||
let authorities = vec![T::AuthorityId::generate_pair(None)];
|
||||
let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities.clone())
|
||||
.map_err(|()| "more than the maximum number of keys provided")?;
|
||||
Authorities::<T>::set(&session_index, bounded_authorities);
|
||||
let authority_index = 0u32;
|
||||
|
||||
let clap = Clap {
|
||||
session_index: 0,
|
||||
authority_index: 0,
|
||||
transaction_hash: H256::repeat_byte(1u8),
|
||||
block_number: 69,
|
||||
removed: false,
|
||||
network_id,
|
||||
receiver: receiver.clone(),
|
||||
amount,
|
||||
};
|
||||
|
||||
let authority_id = authorities
|
||||
.get(0usize)
|
||||
.expect("first authority should exist");
|
||||
let encoded_clap = clap.encode();
|
||||
let signature = authority_id.sign(&encoded_clap)
|
||||
.ok_or("couldn't make signature")?;
|
||||
|
||||
}: _(RawOrigin::None, clap, signature)
|
||||
verify {
|
||||
assert_eq!(<<T as pallet::Config>::Currency>::total_balance(&receiver), amount);
|
||||
}
|
||||
|
||||
self_applause {
|
||||
let session_index = T::ValidatorSet::session_index();
|
||||
let next_session_index = session_index.saturating_add(1);
|
||||
let authorities = vec![
|
||||
T::AuthorityId::generate_pair(None),
|
||||
T::AuthorityId::generate_pair(None),
|
||||
];
|
||||
let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities.clone())
|
||||
.map_err(|()| "more than the maximum number of keys provided")?;
|
||||
Authorities::<T>::set(&session_index, bounded_authorities.clone());
|
||||
Authorities::<T>::set(&next_session_index, bounded_authorities);
|
||||
|
||||
let minimum_balance = <<T as pallet::Config>::Currency>::minimum_balance();
|
||||
let receiver = create_account::<T>();
|
||||
let receiver_clone = receiver.clone();
|
||||
let amount = minimum_balance + minimum_balance;
|
||||
let network_id = NetworkIdOf::<T>::default();
|
||||
let transaction_hash = H256::repeat_byte(1u8);
|
||||
|
||||
let unique_transaction_hash = <Pallet<T>>::generate_unique_hash(
|
||||
&receiver,
|
||||
&amount,
|
||||
&network_id,
|
||||
);
|
||||
let storage_key = (session_index, &transaction_hash, &unique_transaction_hash);
|
||||
let next_storage_key = (next_session_index, &transaction_hash, &unique_transaction_hash);
|
||||
|
||||
<Pallet::<T>>::trigger_nullification_for_benchmark();
|
||||
let clap = Clap {
|
||||
session_index,
|
||||
authority_index: 0,
|
||||
authority_index,
|
||||
transaction_hash,
|
||||
block_number: 69,
|
||||
removed: false,
|
||||
@ -88,26 +41,54 @@ benchmarks! {
|
||||
};
|
||||
|
||||
let authority_id = authorities
|
||||
.get(0usize)
|
||||
.get(authority_index as usize)
|
||||
.expect("first authority should exist");
|
||||
let encoded_clap = clap.encode();
|
||||
let signature = authority_id.sign(&encoded_clap).unwrap();
|
||||
Pallet::<T>::slow_clap(RawOrigin::None.into(), clap, signature)?;
|
||||
Pallet::<T>::trigger_nullification_for_benchmark();
|
||||
let signature = authority_id.sign(&clap.encode())
|
||||
.ok_or("couldn't make signature")?;
|
||||
|
||||
assert_eq!(<<T as pallet::Config>::Currency>::total_balance(&receiver), Default::default());
|
||||
assert_eq!(ApplausesForTransaction::<T>::get(&storage_key), false);
|
||||
|
||||
frame_system::Pallet::<T>::on_initialize(1u32.into());
|
||||
|
||||
let mut fake_received_clap =
|
||||
BoundedBTreeSet::<AuthIndex, T::MaxAuthorities>::new();
|
||||
assert_eq!(fake_received_clap.try_insert(1).unwrap(), true);
|
||||
pallet::ReceivedClaps::<T>::insert(&next_storage_key, fake_received_clap);
|
||||
}: _(RawOrigin::Signed(receiver_clone), network_id, session_index, transaction_hash, receiver_clone.clone(), amount)
|
||||
}: _(RawOrigin::None, clap, signature)
|
||||
verify {
|
||||
let clap_key = (session_index, transaction_hash, args_hash);
|
||||
assert_eq!(ReceivedClaps::<T>::get(&clap_key).get(&authority_index).is_some(), true);
|
||||
assert_eq!(<<T as pallet::Config>::Currency>::total_balance(&receiver), amount);
|
||||
assert_eq!(ApplausesForTransaction::<T>::get(&storage_key), true);
|
||||
}
|
||||
|
||||
commit_block {
|
||||
let session_index = T::ValidatorSet::session_index();
|
||||
let network_id = NetworkIdOf::<T>::default();
|
||||
|
||||
let authorities = vec![T::AuthorityId::generate_pair(None)];
|
||||
let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities.clone())
|
||||
.map_err(|()| "more than the maximum number of keys provided")?;
|
||||
Authorities::<T>::set(&session_index, bounded_authorities);
|
||||
let authority_index = 0u32;
|
||||
|
||||
let block_commitment = BlockCommitment {
|
||||
session_index,
|
||||
authority_index,
|
||||
network_id,
|
||||
commitment: CommitmentDetails {
|
||||
last_registered_block: 69,
|
||||
last_seen_block: 420,
|
||||
last_updated: 1337,
|
||||
}
|
||||
};
|
||||
|
||||
let authority_id = authorities
|
||||
.get(authority_index as usize)
|
||||
.expect("first authority should exist");
|
||||
let signature = authority_id.sign(&block_commitment.encode())
|
||||
.ok_or("couldn't make signature")?;
|
||||
|
||||
}: _(RawOrigin::None, block_commitment, signature)
|
||||
verify {
|
||||
let stored_commitment = BlockCommitments::<T>::get(&network_id)
|
||||
.get(&authority_index)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
assert_eq!(stored_commitment.last_registered_block, 69);
|
||||
assert_eq!(stored_commitment.last_seen_block, 420);
|
||||
assert_eq!(stored_commitment.last_updated, 1337);
|
||||
}
|
||||
|
||||
impl_benchmark_test_suite!(
|
||||
|
||||
@ -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()
|
||||
|
||||
@ -28,7 +28,7 @@ use sp_runtime::{
|
||||
HttpError,
|
||||
},
|
||||
traits::{BlockNumberProvider, Convert, Saturating, TrailingZeroInput},
|
||||
Perbill, RuntimeAppPublic, RuntimeDebug, SaturatedConversion,
|
||||
Perbill, RuntimeAppPublic, RuntimeDebug,
|
||||
};
|
||||
use sp_staking::{
|
||||
offence::{Kind, Offence, ReportOffence},
|
||||
@ -70,11 +70,43 @@ pub mod sr25519 {
|
||||
const LOG_TARGET: &str = "runtime::ghost-slow-clap";
|
||||
const DB_PREFIX: &[u8] = b"slow_clap::";
|
||||
|
||||
const MIN_LOCK_GUARD_PERIOD: u64 = 15_000;
|
||||
const FETCH_TIMEOUT_PERIOD: u64 = 3_000;
|
||||
const LOCK_BLOCK_EXPIRATION: u64 = 20;
|
||||
const COMMITMENT_DELAY_MILLIS: u64 = 600_000;
|
||||
|
||||
pub type AuthIndex = u32;
|
||||
|
||||
#[derive(
|
||||
RuntimeDebug,
|
||||
Default,
|
||||
Copy,
|
||||
Clone,
|
||||
Eq,
|
||||
PartialEq,
|
||||
Ord,
|
||||
PartialOrd,
|
||||
Encode,
|
||||
Decode,
|
||||
TypeInfo,
|
||||
MaxEncodedLen,
|
||||
)]
|
||||
pub struct CommitmentDetails {
|
||||
pub last_registered_block: u64,
|
||||
pub last_seen_block: u64,
|
||||
pub last_updated: u64,
|
||||
}
|
||||
|
||||
#[derive(
|
||||
RuntimeDebug, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, MaxEncodedLen,
|
||||
)]
|
||||
pub struct BlockCommitment<NetworkId> {
|
||||
pub session_index: SessionIndex,
|
||||
pub authority_index: AuthIndex,
|
||||
pub network_id: NetworkId,
|
||||
pub commitment: CommitmentDetails,
|
||||
}
|
||||
|
||||
#[derive(
|
||||
RuntimeDebug, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, MaxEncodedLen,
|
||||
)]
|
||||
@ -260,6 +292,10 @@ pub mod pallet {
|
||||
receiver: T::AccountId,
|
||||
received_amount: BalanceOf<T>,
|
||||
},
|
||||
BlockCommited {
|
||||
authority_id: AuthIndex,
|
||||
network_id: NetworkIdOf<T>,
|
||||
},
|
||||
}
|
||||
|
||||
#[pallet::error]
|
||||
@ -271,8 +307,20 @@ pub mod pallet {
|
||||
CouldNotAccumulateCommission,
|
||||
CouldNotAccumulateIncomingImbalance,
|
||||
CouldNotIncreaseGatekeeperAmount,
|
||||
NonExistentAuthorityIndex,
|
||||
TimeWentBackwards,
|
||||
}
|
||||
|
||||
#[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<
|
||||
@ -361,23 +409,17 @@ pub mod pallet {
|
||||
}
|
||||
|
||||
#[pallet::call_index(1)]
|
||||
#[pallet::weight(T::WeightInfo::self_applause())]
|
||||
pub fn self_applause(
|
||||
#[pallet::weight((T::WeightInfo::commit_block(), DispatchClass::Normal, Pays::No))]
|
||||
pub fn commit_block(
|
||||
origin: OriginFor<T>,
|
||||
network_id: NetworkIdOf<T>,
|
||||
prev_session_index: SessionIndex,
|
||||
transaction_hash: H256,
|
||||
receiver: T::AccountId,
|
||||
amount: BalanceOf<T>,
|
||||
block_commitment: BlockCommitment<NetworkIdOf<T>>,
|
||||
// since signature verification is done in `validate_unsigned`
|
||||
// we can skip doing it here again.
|
||||
_signature: <T::AuthorityId as RuntimeAppPublic>::Signature,
|
||||
) -> DispatchResult {
|
||||
let _ = ensure_signed(origin)?;
|
||||
Self::applause_if_posible(
|
||||
network_id,
|
||||
prev_session_index,
|
||||
transaction_hash,
|
||||
receiver,
|
||||
amount,
|
||||
)
|
||||
ensure_none(origin)?;
|
||||
Self::try_commit_block(&block_commitment)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@ -398,39 +440,65 @@ pub mod pallet {
|
||||
#[pallet::validate_unsigned]
|
||||
impl<T: Config> ValidateUnsigned for Pallet<T> {
|
||||
type Call = Call<T>;
|
||||
|
||||
fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity {
|
||||
if let Call::slow_clap { clap, signature } = call {
|
||||
let (session_index, _) = Self::mended_session_index(&clap);
|
||||
let authorities = Authorities::<T>::get(&session_index);
|
||||
let authority = match authorities.get(clap.authority_index as usize) {
|
||||
Some(authority) => authority,
|
||||
None => return InvalidTransaction::BadSigner.into(),
|
||||
};
|
||||
match call {
|
||||
Call::commit_block {
|
||||
block_commitment,
|
||||
signature,
|
||||
} => {
|
||||
let authorities = Authorities::<T>::get(&block_commitment.session_index);
|
||||
let authority = match authorities.get(block_commitment.authority_index as usize)
|
||||
{
|
||||
Some(authority) => authority,
|
||||
None => return InvalidTransaction::BadSigner.into(),
|
||||
};
|
||||
|
||||
if ClapsInSession::<T>::get(&session_index)
|
||||
.get(&clap.authority_index)
|
||||
.map(|info| info.disabled)
|
||||
.unwrap_or_default()
|
||||
{
|
||||
return InvalidTransaction::BadSigner.into();
|
||||
let signature_valid = block_commitment.using_encoded(|encoded_commitment| {
|
||||
authority.verify(&encoded_commitment, signature)
|
||||
});
|
||||
|
||||
if !signature_valid {
|
||||
return InvalidTransaction::BadProof.into();
|
||||
}
|
||||
|
||||
ValidTransaction::with_tag_prefix("SlowClap")
|
||||
.priority(T::UnsignedPriority::get())
|
||||
.and_provides(block_commitment.commitment.encode())
|
||||
.longevity(LOCK_BLOCK_EXPIRATION)
|
||||
.propagate(true)
|
||||
.build()
|
||||
}
|
||||
Call::slow_clap { clap, signature } => {
|
||||
let (session_index, _) = Self::mended_session_index(&clap);
|
||||
let authorities = Authorities::<T>::get(&session_index);
|
||||
let authority = match authorities.get(clap.authority_index as usize) {
|
||||
Some(authority) => authority,
|
||||
None => return InvalidTransaction::BadSigner.into(),
|
||||
};
|
||||
|
||||
let signature_valid =
|
||||
clap.using_encoded(|encoded_clap| authority.verify(&encoded_clap, signature));
|
||||
if ClapsInSession::<T>::get(&session_index)
|
||||
.get(&clap.authority_index)
|
||||
.map(|info| info.disabled)
|
||||
.unwrap_or_default()
|
||||
{
|
||||
return InvalidTransaction::BadSigner.into();
|
||||
}
|
||||
|
||||
if !signature_valid {
|
||||
return InvalidTransaction::BadProof.into();
|
||||
let signature_valid = clap
|
||||
.using_encoded(|encoded_clap| authority.verify(&encoded_clap, signature));
|
||||
|
||||
if !signature_valid {
|
||||
return InvalidTransaction::BadProof.into();
|
||||
}
|
||||
|
||||
ValidTransaction::with_tag_prefix("SlowClap")
|
||||
.priority(T::UnsignedPriority::get())
|
||||
.and_provides(signature)
|
||||
.longevity(LOCK_BLOCK_EXPIRATION)
|
||||
.propagate(true)
|
||||
.build()
|
||||
}
|
||||
|
||||
ValidTransaction::with_tag_prefix("SlowClap")
|
||||
.priority(T::UnsignedPriority::get())
|
||||
.and_provides(signature)
|
||||
.longevity(LOCK_BLOCK_EXPIRATION)
|
||||
.propagate(true)
|
||||
.build()
|
||||
} else {
|
||||
InvalidTransaction::Call.into()
|
||||
_ => InvalidTransaction::Call.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -618,79 +686,30 @@ impl<T: Config> Pallet<T> {
|
||||
})
|
||||
}
|
||||
|
||||
fn applause_if_posible(
|
||||
network_id: NetworkIdOf<T>,
|
||||
prev_session_index: SessionIndex,
|
||||
transaction_hash: H256,
|
||||
receiver: T::AccountId,
|
||||
amount: BalanceOf<T>,
|
||||
) -> DispatchResult {
|
||||
let curr_session_index = prev_session_index.saturating_add(1);
|
||||
let clap_unique_hash = Self::generate_unique_hash(&receiver, &amount, &network_id);
|
||||
fn try_commit_block(new_commitment: &BlockCommitment<NetworkIdOf<T>>) -> DispatchResult {
|
||||
BlockCommitments::<T>::try_mutate(&new_commitment.network_id, |current_commitments| {
|
||||
let authority_index = new_commitment.authority_index;
|
||||
let new_commitment_details = new_commitment.commitment;
|
||||
|
||||
let prev_authorities = Authorities::<T>::get(&prev_session_index)
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, auth)| (auth, i as AuthIndex))
|
||||
.collect::<BTreeMap<T::AuthorityId, AuthIndex>>();
|
||||
let curr_authorities = Authorities::<T>::get(&curr_session_index);
|
||||
let current_last_updated = current_commitments
|
||||
.get(&authority_index)
|
||||
.map(|details| details.last_updated)
|
||||
.unwrap_or_default();
|
||||
|
||||
let prev_received_claps_key = (prev_session_index, &transaction_hash, &clap_unique_hash);
|
||||
let curr_received_claps_key = (curr_session_index, &transaction_hash, &clap_unique_hash);
|
||||
ensure!(
|
||||
new_commitment_details.last_updated > current_last_updated,
|
||||
Error::<T>::TimeWentBackwards
|
||||
);
|
||||
|
||||
let mut previous_claps = ClapsInSession::<T>::get(&prev_session_index);
|
||||
let mut total_received_claps =
|
||||
ReceivedClaps::<T>::get(&prev_received_claps_key).into_inner();
|
||||
current_commitments.insert(authority_index, new_commitment_details);
|
||||
|
||||
for (auth_index, info) in ClapsInSession::<T>::get(&curr_session_index).iter() {
|
||||
if !info.disabled {
|
||||
continue;
|
||||
}
|
||||
Self::deposit_event(Event::<T>::BlockCommited {
|
||||
network_id: new_commitment.network_id,
|
||||
authority_id: authority_index,
|
||||
});
|
||||
|
||||
if let Some(curr_authority) = curr_authorities.get(*auth_index as usize) {
|
||||
if let Some(prev_position) = prev_authorities.get(&curr_authority) {
|
||||
previous_claps
|
||||
.entry(*prev_position as AuthIndex)
|
||||
.and_modify(|individual| (*individual).disabled = true)
|
||||
.or_insert(SessionAuthorityInfo {
|
||||
claps: 0u32,
|
||||
disabled: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for auth_index in ReceivedClaps::<T>::get(&curr_received_claps_key).into_iter() {
|
||||
if let Some(curr_authority) = curr_authorities.get(auth_index as usize) {
|
||||
if let Some(prev_position) = prev_authorities.get(&curr_authority) {
|
||||
let _ = total_received_claps.insert(*prev_position as AuthIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let disabled_authorities = previous_claps.values().filter(|info| info.disabled).count();
|
||||
|
||||
let active_authorities = prev_authorities.len().saturating_sub(disabled_authorities);
|
||||
|
||||
let clap = Clap {
|
||||
authority_index: Default::default(),
|
||||
block_number: Default::default(),
|
||||
removed: Default::default(),
|
||||
session_index: Default::default(),
|
||||
transaction_hash: Default::default(),
|
||||
network_id,
|
||||
receiver,
|
||||
amount,
|
||||
};
|
||||
|
||||
let enough_authorities =
|
||||
Perbill::from_rational(total_received_claps.len() as u32, active_authorities as u32)
|
||||
> Perbill::from_percent(T::ApplauseThreshold::get());
|
||||
|
||||
ensure!(enough_authorities, Error::<T>::NotEnoughClaps);
|
||||
Self::try_applause(&clap, &prev_received_claps_key)?;
|
||||
|
||||
Ok(())
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn start_slow_clapping(block_number: BlockNumberFor<T>) -> OffchainResult<T, ()> {
|
||||
@ -716,7 +735,7 @@ 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(rate_limit_delay.max(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);
|
||||
|
||||
let _lock_guard = network_lock
|
||||
@ -771,44 +790,59 @@ impl<T: Config> Pallet<T> {
|
||||
.get(random_index)
|
||||
.ok_or(OffchainErr::NoEndpointAvailable(network_id))?;
|
||||
|
||||
let maybe_block_range: Option<(u64, u64)> = StorageValueRef::persistent(&block_number_key)
|
||||
let (from_block, to_block): (u64, u64) = StorageValueRef::persistent(&block_number_key)
|
||||
.get()
|
||||
.map_err(|_| OffchainErr::StorageRetrievalError(network_id))?;
|
||||
.map_err(|_| OffchainErr::StorageRetrievalError(network_id))?
|
||||
.unwrap_or_default();
|
||||
|
||||
let request_body = match maybe_block_range {
|
||||
Some((from_block, to_block)) if from_block < to_block.saturating_sub(1) => {
|
||||
Self::prepare_request_body_for_latest_transfers(
|
||||
from_block,
|
||||
to_block.saturating_sub(1),
|
||||
network_data,
|
||||
)
|
||||
}
|
||||
_ => Self::prepare_request_body_for_latest_block(network_data),
|
||||
let 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,
|
||||
)
|
||||
} else {
|
||||
Self::prepare_request_body_for_latest_block(network_data)
|
||||
};
|
||||
|
||||
let response_bytes = Self::fetch_from_remote(&rpc_endpoint, &request_body)?;
|
||||
|
||||
match network_data.network_type {
|
||||
NetworkType::Evm => {
|
||||
let maybe_new_evm_block =
|
||||
Self::apply_evm_response(&response_bytes, session_index, network_id)?;
|
||||
let estimated_block = maybe_new_evm_block
|
||||
.map(|new_evm_block| new_evm_block.saturating_sub(network_data.finality_delay))
|
||||
.unwrap_or_default();
|
||||
let 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);
|
||||
|
||||
let new_block_range = match maybe_block_range {
|
||||
Some((from_block, to_block)) => match maybe_new_evm_block {
|
||||
Some(_) if from_block.le(&to_block) => (
|
||||
from_block,
|
||||
Self::adjust_to_block(estimated_block, from_block, max_block_distance),
|
||||
),
|
||||
_ => (to_block, to_block),
|
||||
},
|
||||
None => (estimated_block, estimated_block),
|
||||
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,
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
NetworkType::Utxo => Err(OffchainErr::UtxoNotImplemented(network_id).into()),
|
||||
@ -816,123 +850,6 @@ impl<T: Config> Pallet<T> {
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_evm_response(
|
||||
response_bytes: &[u8],
|
||||
session_index: SessionIndex,
|
||||
network_id: NetworkIdOf<T>,
|
||||
) -> OffchainResult<T, Option<u64>> {
|
||||
match Self::parse_evm_response(&response_bytes)? {
|
||||
EvmResponseType::BlockNumber(new_evm_block) => {
|
||||
log::info!(
|
||||
target: LOG_TARGET,
|
||||
"🧐 New evm block #{:?} found for network {:?}",
|
||||
new_evm_block,
|
||||
network_id,
|
||||
);
|
||||
Ok(Some(new_evm_block))
|
||||
}
|
||||
EvmResponseType::TransactionLogs(evm_logs) => {
|
||||
if sp_io::offchain::is_validator() {
|
||||
log::info!(target: LOG_TARGET, "🧐 Not a validator; no claps available");
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
for (authority_index, authority_key) in Self::local_authorities(&session_index) {
|
||||
if ClapsInSession::<T>::get(&session_index)
|
||||
.get(&authority_index)
|
||||
.map(|info| info.disabled)
|
||||
.unwrap_or_default()
|
||||
{
|
||||
log::info!(
|
||||
target: LOG_TARGET,
|
||||
"🧐 Authority #{:?} disabled in session {:?}; no claps available",
|
||||
authority_index,
|
||||
session_index
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
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,
|
||||
);
|
||||
|
||||
Self::sign_and_submit_claps(authority_key, authority_index, network_id, &claps);
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn sign_and_submit_claps(
|
||||
authority_key: T::AuthorityId,
|
||||
authority_index: AuthIndex,
|
||||
network_id: NetworkIdOf<T>,
|
||||
claps: &Vec<Clap<T::AccountId, NetworkIdOf<T>, BalanceOf<T>>>,
|
||||
) {
|
||||
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,
|
||||
"🧐 Failed to sign clap #{:?} from authority #{:?} for network {:?}",
|
||||
clap_index,
|
||||
authority_index,
|
||||
network_id,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
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 adjust_to_block(estimated_block: u64, from_block: u64, max_block_distance: u64) -> u64 {
|
||||
let fallback_value = from_block
|
||||
.saturating_add(max_block_distance)
|
||||
@ -943,7 +860,7 @@ impl<T: Config> Pallet<T> {
|
||||
.map(|current_distance| {
|
||||
current_distance
|
||||
.le(&max_block_distance)
|
||||
.then(|| estimated_block)
|
||||
.then_some(estimated_block)
|
||||
})
|
||||
.flatten()
|
||||
.unwrap_or(fallback_value)
|
||||
@ -1151,11 +1068,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> {
|
||||
@ -1184,6 +1096,10 @@ impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
|
||||
where
|
||||
I: Iterator<Item = (&'a T::AccountId, T::AuthorityId)>,
|
||||
{
|
||||
for (network_id, _) in BlockCommitments::<T>::iter() {
|
||||
BlockCommitments::<T>::remove(network_id);
|
||||
}
|
||||
|
||||
let authorities = validators.map(|x| x.1).collect::<Vec<_>>();
|
||||
Self::initialize_authorities(authorities);
|
||||
}
|
||||
|
||||
@ -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([
|
||||
(
|
||||
@ -371,9 +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, 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(())
|
||||
});
|
||||
}
|
||||
@ -391,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;
|
||||
@ -411,10 +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, session_index, network_id)?;
|
||||
|
||||
assert_eq!(maybe_evm_block_number, None);
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
@ -900,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());
|
||||
@ -948,132 +977,6 @@ fn should_avoid_applause_during_nullification_period() {
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_self_applause_after_diabled() {
|
||||
let zero = 0u64;
|
||||
let (network_id, transaction_hash, unique_transaction_hash) =
|
||||
generate_unique_hash(None, None, None, None);
|
||||
let (_, receiver, amount) = get_mocked_metadata();
|
||||
|
||||
new_test_ext().execute_with(|| {
|
||||
let _ = prepare_evm_network(Some(network_id), Some(0));
|
||||
let session_index = advance_session_and_get_index();
|
||||
let storage_key = (session_index, transaction_hash, unique_transaction_hash);
|
||||
|
||||
assert_err!(
|
||||
SlowClap::self_applause(
|
||||
RuntimeOrigin::signed(receiver),
|
||||
network_id,
|
||||
session_index,
|
||||
transaction_hash,
|
||||
receiver,
|
||||
amount,
|
||||
),
|
||||
Error::<Runtime>::NotEnoughClaps,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
|
||||
false
|
||||
);
|
||||
assert_eq!(Balances::balance(&receiver), zero);
|
||||
|
||||
assert_ok!(do_clap_from(session_index, network_id, 0, false));
|
||||
advance_session();
|
||||
let curr_session_index = Session::session_index();
|
||||
|
||||
pallet::ClapsInSession::<Runtime>::mutate(&session_index, |claps| {
|
||||
claps
|
||||
.entry(1 as AuthIndex)
|
||||
.and_modify(|individual| (*individual).disabled = true)
|
||||
.or_insert(SessionAuthorityInfo {
|
||||
claps: 0u32,
|
||||
disabled: true,
|
||||
});
|
||||
});
|
||||
|
||||
pallet::ClapsInSession::<Runtime>::mutate(&curr_session_index, |claps| {
|
||||
claps
|
||||
.entry(2 as AuthIndex)
|
||||
.and_modify(|individual| (*individual).disabled = true)
|
||||
.or_insert(SessionAuthorityInfo {
|
||||
claps: 0u32,
|
||||
disabled: true,
|
||||
});
|
||||
});
|
||||
|
||||
assert_ok!(SlowClap::self_applause(
|
||||
RuntimeOrigin::signed(receiver),
|
||||
network_id,
|
||||
session_index,
|
||||
transaction_hash,
|
||||
receiver,
|
||||
amount,
|
||||
));
|
||||
assert_eq!(
|
||||
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
|
||||
true
|
||||
);
|
||||
assert_eq!(Balances::balance(&receiver), amount);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_self_applause_if_enough_claps() {
|
||||
let zero = 0u64;
|
||||
let (network_id, transaction_hash, unique_transaction_hash) =
|
||||
generate_unique_hash(None, None, None, None);
|
||||
let (_, receiver, amount) = get_mocked_metadata();
|
||||
|
||||
new_test_ext().execute_with(|| {
|
||||
let _ = prepare_evm_network(Some(network_id), Some(0));
|
||||
let session_index = advance_session_and_get_index();
|
||||
let storage_key = (session_index, transaction_hash, unique_transaction_hash);
|
||||
|
||||
assert_err!(
|
||||
SlowClap::self_applause(
|
||||
RuntimeOrigin::signed(receiver),
|
||||
network_id,
|
||||
session_index,
|
||||
transaction_hash,
|
||||
receiver,
|
||||
amount,
|
||||
),
|
||||
Error::<Runtime>::NotEnoughClaps,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
|
||||
false
|
||||
);
|
||||
assert_eq!(Balances::balance(&receiver), zero);
|
||||
|
||||
assert_ok!(do_clap_from(session_index, network_id, 0, false));
|
||||
advance_session();
|
||||
|
||||
let mut fake_received_clap =
|
||||
BoundedBTreeSet::<AuthIndex, <Runtime as pallet::Config>::MaxAuthorities>::new();
|
||||
assert_eq!(fake_received_clap.try_insert(1).unwrap(), true);
|
||||
assert_eq!(fake_received_clap.try_insert(2).unwrap(), true);
|
||||
|
||||
pallet::ReceivedClaps::<Runtime>::insert(&storage_key, fake_received_clap);
|
||||
|
||||
assert_ok!(SlowClap::self_applause(
|
||||
RuntimeOrigin::signed(receiver),
|
||||
network_id,
|
||||
session_index,
|
||||
transaction_hash,
|
||||
receiver,
|
||||
amount,
|
||||
));
|
||||
assert_eq!(
|
||||
pallet::ApplausesForTransaction::<Runtime>::get(&storage_key),
|
||||
true
|
||||
);
|
||||
assert_eq!(Balances::balance(&receiver), amount);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_avoid_session_overlap_on_mended_session_index() {
|
||||
let (network_id, transaction_hash, unique_transaction_hash) =
|
||||
@ -1229,6 +1132,49 @@ fn should_emit_black_swan_if_not_enough_authorities_left() {
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_register_block_commitments() {
|
||||
let (network_id, _, _) = generate_unique_hash(None, None, None, None);
|
||||
|
||||
new_test_ext().execute_with(|| {
|
||||
let session_index = advance_session_and_get_index();
|
||||
|
||||
for commitment_details in SlowClap::block_commitments(network_id).values() {
|
||||
assert_eq!(commitment_details.last_registered_block, 0);
|
||||
assert_eq!(commitment_details.last_seen_block, 0);
|
||||
assert_eq!(commitment_details.last_updated, 0);
|
||||
}
|
||||
|
||||
assert_ok!(do_block_commitment(session_index, network_id, 0));
|
||||
assert_ok!(do_block_commitment(session_index, network_id, 1));
|
||||
assert_ok!(do_block_commitment(session_index, network_id, 2));
|
||||
|
||||
assert_err!(
|
||||
do_block_commitment(session_index, network_id, 3),
|
||||
DispatchError::Other("Invalid signing address"),
|
||||
);
|
||||
|
||||
assert_err!(
|
||||
do_block_commitment(session_index, network_id, 1),
|
||||
Error::<Runtime>::TimeWentBackwards,
|
||||
);
|
||||
|
||||
for commitment_details in SlowClap::block_commitments(network_id).values() {
|
||||
assert_eq!(commitment_details.last_registered_block, 69);
|
||||
assert_eq!(commitment_details.last_seen_block, 420);
|
||||
assert_eq!(commitment_details.last_updated, 1337);
|
||||
}
|
||||
|
||||
advance_session();
|
||||
|
||||
for commitment_details in SlowClap::block_commitments(network_id).values() {
|
||||
assert_eq!(commitment_details.last_registered_block, 0);
|
||||
assert_eq!(commitment_details.last_seen_block, 0);
|
||||
assert_eq!(commitment_details.last_updated, 0);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn advance_session_and_get_index() -> u32 {
|
||||
advance_session();
|
||||
assert_eq!(Session::validators(), Vec::<u64>::new());
|
||||
|
||||
@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user