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