Skip to content

Commit

Permalink
Gj/thea hot fixes (#908)
Browse files Browse the repository at this point in the history
## Describe your changes

Hot fixes for parachain runtime upgrade
  • Loading branch information
Gauthamastro authored Feb 2, 2024
2 parents ad05ce2 + ba3afdd commit aa87f4c
Show file tree
Hide file tree
Showing 14 changed files with 159 additions and 188 deletions.
4 changes: 2 additions & 2 deletions pallets/thea-executor/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ benchmarks! {
assert_eq!(ready_withdrawal.len(), 1);
}

ethereum_withdraw {
evm_withdraw {
let r in 1 .. 1000;
let asset_id: <T as pallet::Config>::AssetId = 100u128.into();
let admin = account::<T::AccountId>("admin", 1, r);
Expand All @@ -128,7 +128,7 @@ benchmarks! {
<Metadata<T>>::insert(100, metadata);
<WithdrawalFees<T>>::insert(network_id, 1_000);
let beneficiary: sp_core::H160 = sp_core::H160::default();
}: _(RawOrigin::Signed(account.clone()), 100, 1_000_000_000_000, beneficiary, true, false)
}: _(RawOrigin::Signed(account.clone()), 100, 1_000_000_000_000, beneficiary, network_id, true, false)
verify {
let ready_withdrawal = <ReadyWithdrawals<T>>::get(<frame_system::Pallet<T>>::block_number(), network_id);
assert_eq!(ready_withdrawal.len(), 1);
Expand Down
6 changes: 3 additions & 3 deletions pallets/thea-executor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ pub mod pallet {
use sp_std::vec::Vec;
use thea_primitives::{
types::{AssetMetadata, Deposit, Withdraw},
Network, TheaIncomingExecutor, TheaOutgoingExecutor, ETHEREUM_NETWORK, NATIVE_NETWORK,
Network, TheaIncomingExecutor, TheaOutgoingExecutor, NATIVE_NETWORK,
};
use xcm::VersionedMultiLocation;

Expand Down Expand Up @@ -380,16 +380,16 @@ pub mod pallet {
/// * `pay_with_tokens`: Pay with withdrawing tokens.
#[pallet::call_index(5)]
#[pallet::weight(< T as Config >::TheaExecWeightInfo::ethereum_withdraw(1))]
pub fn ethereum_withdraw(
pub fn evm_withdraw(
origin: OriginFor<T>,
asset_id: u128,
amount: u128,
beneficiary: H160,
network: Network,
pay_for_remaining: bool,
pay_with_tokens: bool,
) -> DispatchResult {
let user = ensure_signed(origin)?;
let network = ETHEREUM_NETWORK;
Self::do_withdraw(
user,
asset_id,
Expand Down
5 changes: 3 additions & 2 deletions pallets/thea-executor/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ fn test_do_withdrawal_with_total_amount_consumed_returns_error() {
}

#[test]
fn test_ethereum_withdraw() {
fn test_evm_withdraw() {
new_test_ext().execute_with(|| {
let asset_id: <Test as Config>::AssetId = 100u128;
let admin = 1u64;
Expand Down Expand Up @@ -437,11 +437,12 @@ fn test_ethereum_withdraw() {
<Metadata<Test>>::insert(100, metadata);
<WithdrawalFees<Test>>::insert(network_id, 1_000);
let beneficiary = H160::from_slice(&[1; 20]);
assert_ok!(TheaExecutor::ethereum_withdraw(
assert_ok!(TheaExecutor::evm_withdraw(
RuntimeOrigin::signed(account),
asset_id,
1_000_000_000,
beneficiary.clone(),
network_id,
false,
false
));
Expand Down
9 changes: 9 additions & 0 deletions pallets/thea-message-handler/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,15 @@ benchmarks! {
verify {
assert_eq!(b, <OutgoingNonce<T>>::get());
}

send_thea_message {
let public = <T as Config>::TheaId::decode(&mut KEY.as_ref()).unwrap();
let authorities = BoundedVec::truncate_from(vec![public]);
let validator_set_id = 1;
<ValidatorSetId<T>>::put(validator_set_id);
<Authorities<T>>::insert(validator_set_id, authorities);
let message = vec![1u8;10];
}: _(RawOrigin::Root, message)
}

#[cfg(test)]
Expand Down
24 changes: 19 additions & 5 deletions pallets/thea-message-handler/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ pub trait WeightInfo {
fn incoming_message() -> Weight;
fn update_incoming_nonce(_b: u32) -> Weight;
fn update_outgoing_nonce(_b: u32) -> Weight;
fn send_thea_message() -> Weight;
}

pub mod weights;
Expand All @@ -61,7 +62,7 @@ pub mod pallet {
use super::*;
use frame_support::transactional;
use sp_std::vec;
use thea_primitives::{types::Message, TheaIncomingExecutor};
use thea_primitives::{types::Message, TheaIncomingExecutor, TheaOutgoingExecutor};

#[pallet::config]
pub trait Config: frame_system::Config {
Expand Down Expand Up @@ -258,6 +259,16 @@ pub mod pallet {
<OutgoingNonce<T>>::put(nonce);
Ok(())
}

/// A governance endpoint to send thea messages
#[pallet::call_index(4)]
#[pallet::weight(<T as Config>::WeightInfo::send_thea_message())]
#[transactional]
pub fn send_thea_message(origin: OriginFor<T>, data: Vec<u8>) -> DispatchResult {
ensure_root(origin)?;
Self::execute_withdrawals(1, data)?;
Ok(())
}
}
}

Expand Down Expand Up @@ -286,11 +297,14 @@ impl<T: Config> Pallet<T> {
log::debug!(target:"thea", "Get auth of index: {:?}",index);
match authorities.get(*index as usize) {
None => return InvalidTransaction::Custom(3).into(),
Some(auth) =>
if !auth.verify(&encoded_payload, &((*signature).clone().into())) {
Some(auth) => {
let signature: sp_core::ecdsa::Signature = signature.clone().into();
let auth: sp_core::ecdsa::Public = auth.clone().into();
if !sp_io::crypto::ecdsa_verify_prehashed(&signature, &encoded_payload, &auth) {
log::debug!(target:"thea", "signature of index: {:?} -> {:?}, Failed",index,auth);
return InvalidTransaction::Custom(4).into()
},
return InvalidTransaction::Custom(4).into();
}
},
}
}

Expand Down
2 changes: 1 addition & 1 deletion pallets/thea-message-handler/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ impl pallet_assets::Config for Test {
}

parameter_types! {
pub const MaxAuthorities: u32 = 10;
pub const MaxAuthorities: u32 = 200;
}

impl thea::Config for Test {
Expand Down
33 changes: 32 additions & 1 deletion pallets/thea-message-handler/src/test.rs

Large diffs are not rendered by default.

36 changes: 27 additions & 9 deletions pallets/thea-message-handler/src/weights.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Autogenerated weights for `thea_message_handler`
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
//! DATE: 2024-02-01, STEPS: `100`, REPEAT: `200`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! DATE: 2024-02-02, STEPS: `100`, REPEAT: `200`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `ip-172-31-41-122`, CPU: `AMD EPYC 7571`
//! WASM-EXECUTION: `Compiled`, CHAIN: `None`, DB CACHE: 1024
Expand Down Expand Up @@ -41,8 +41,8 @@ impl<T: frame_system::Config> crate::WeightInfo for WeightInfo<T> {
// Proof Size summary in bytes:
// Measured: `0`
// Estimated: `0`
// Minimum execution time: 20_410_000 picoseconds.
Weight::from_parts(21_438_172, 0)
// Minimum execution time: 19_840_000 picoseconds.
Weight::from_parts(20_793_457, 0)
.saturating_add(Weight::from_parts(0, 0))
.saturating_add(T::DbWeight::get().writes(2))
}
Expand All @@ -58,8 +58,8 @@ impl<T: frame_system::Config> crate::WeightInfo for WeightInfo<T> {
// Proof Size summary in bytes:
// Measured: `82`
// Estimated: `3547`
// Minimum execution time: 96_801_000 picoseconds.
Weight::from_parts(98_251_000, 0)
// Minimum execution time: 95_831_000 picoseconds.
Weight::from_parts(97_451_000, 0)
.saturating_add(Weight::from_parts(0, 3547))
.saturating_add(T::DbWeight::get().reads(2))
.saturating_add(T::DbWeight::get().writes(2))
Expand All @@ -71,8 +71,8 @@ impl<T: frame_system::Config> crate::WeightInfo for WeightInfo<T> {
// Proof Size summary in bytes:
// Measured: `0`
// Estimated: `0`
// Minimum execution time: 15_140_000 picoseconds.
Weight::from_parts(15_919_964, 0)
// Minimum execution time: 14_960_000 picoseconds.
Weight::from_parts(15_638_456, 0)
.saturating_add(Weight::from_parts(0, 0))
.saturating_add(T::DbWeight::get().writes(1))
}
Expand All @@ -83,9 +83,27 @@ impl<T: frame_system::Config> crate::WeightInfo for WeightInfo<T> {
// Proof Size summary in bytes:
// Measured: `0`
// Estimated: `0`
// Minimum execution time: 15_180_000 picoseconds.
Weight::from_parts(16_059_670, 0)
// Minimum execution time: 14_740_000 picoseconds.
Weight::from_parts(15_625_467, 0)
.saturating_add(Weight::from_parts(0, 0))
.saturating_add(T::DbWeight::get().writes(1))
}
/// Storage: `TheaMH::ValidatorSetId` (r:1 w:0)
/// Proof: `TheaMH::ValidatorSetId` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `TheaMH::Authorities` (r:1 w:0)
/// Proof: `TheaMH::Authorities` (`max_values`: None, `max_size`: None, mode: `Measured`)
/// Storage: `TheaMH::OutgoingNonce` (r:1 w:1)
/// Proof: `TheaMH::OutgoingNonce` (`max_values`: Some(1), `max_size`: None, mode: `Measured`)
/// Storage: `TheaMH::OutgoingMessages` (r:0 w:1)
/// Proof: `TheaMH::OutgoingMessages` (`max_values`: None, `max_size`: None, mode: `Measured`)
fn send_thea_message() -> Weight {
// Proof Size summary in bytes:
// Measured: `172`
// Estimated: `3637`
// Minimum execution time: 41_120_000 picoseconds.
Weight::from_parts(42_110_000, 0)
.saturating_add(Weight::from_parts(0, 3637))
.saturating_add(T::DbWeight::get().reads(3))
.saturating_add(T::DbWeight::get().writes(2))
}
}
43 changes: 36 additions & 7 deletions pallets/thea/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,11 @@ pub mod pallet {
OptionQuery,
>;

/// Temporary allowlist for relayer
#[pallet::storage]
pub(super) type AllowListTestingRelayers<T: Config> =
StorageMap<_, Identity, Network, T::AccountId, OptionQuery>;

#[pallet::event]
#[pallet::generate_deposit(pub (super) fn deposit_event)]
pub enum Event<T: Config> {
Expand All @@ -280,6 +285,12 @@ pub mod pallet {
NotEnoughStake,
/// MessageNotFound
MessageNotFound,
/// No Relayer found
NoRelayersFound,
/// Not expected relayer origin
NotAnAllowlistedRelayer,
/// Nonce Error
NonceError,
}

#[pallet::hooks]
Expand All @@ -288,19 +299,17 @@ pub mod pallet {
// Every block check the next incoming nonce and if fork period is over, execute them
let active_networks = <ActiveNetworks<T>>::get();
for network in active_networks.clone() {
let next_nonce = <IncomingNonce<T>>::get(network);
match <IncomingMessagesQueue<T>>::get(network, next_nonce) {
let last_processed_nonce = <IncomingNonce<T>>::get(network);
let next_nonce = last_processed_nonce.saturating_add(1);
match <IncomingMessagesQueue<T>>::take(network, next_nonce) {
None => continue,
Some(msg) => {
if msg.execute_at <= blk.saturated_into::<u32>() {
T::Executor::execute_deposits(
msg.message.network,
msg.message.data.clone(),
);
<IncomingNonce<T>>::insert(
msg.message.network,
next_nonce.saturating_add(1),
);
<IncomingNonce<T>>::insert(msg.message.network, next_nonce);
Self::deposit_event(Event::<T>::TheaPayloadProcessed(
msg.message.network,
msg.message.nonce,
Expand Down Expand Up @@ -362,12 +371,19 @@ pub mod pallet {
stake: Balance,
) -> DispatchResult {
let signer = ensure_signed(origin)?;
let expected_signer = <AllowListTestingRelayers<T>>::get(payload.network)
.ok_or(Error::<T>::NoRelayersFound)?;
ensure!(signer == expected_signer, Error::<T>::NotAnAllowlistedRelayer);

let config = <NetworkConfig<T>>::get(payload.network);

if stake < config.min_stake {
return Err(Error::<T>::NotEnoughStake.into())
}

let next_nonce = <IncomingNonce<T>>::get(payload.network);
ensure!(payload.nonce > next_nonce, Error::<T>::NonceError);

match <IncomingMessagesQueue<T>>::get(payload.network, payload.nonce) {
None => {
// Lock balance
Expand Down Expand Up @@ -630,6 +646,19 @@ pub mod pallet {
}
Ok(())
}

/// Adds a relayer origin for deposits - will be removed after mainnet testing
#[pallet::call_index(9)]
#[pallet::weight(< T as Config >::WeightInfo::add_thea_network())]
pub fn add_relayer_origin_for_network(
origin: OriginFor<T>,
network: Network,
relayer: T::AccountId,
) -> DispatchResult {
ensure_root(origin)?;
<AllowListTestingRelayers<T>>::insert(network, relayer);
Ok(())
}
}
}

Expand Down Expand Up @@ -680,7 +709,7 @@ impl<T: Config> Pallet<T> {
}

ValidTransaction::with_tag_prefix("thea")
.priority(TransactionPriority::MAX/3)
.priority(TransactionPriority::MAX / 3)
.and_provides((id, auth_index))
.longevity(10)
.propagate(true)
Expand Down
23 changes: 22 additions & 1 deletion pallets/thea/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,10 @@ fn test_report_misbehaviour_happy_path() {
})
}

use frame_support::{assert_noop, traits::fungible::MutateHold};
use frame_support::{
assert_noop,
traits::{fungible::MutateHold, tokens::Precision},
};
use thea_primitives::types::{AssetMetadata, IncomingMessage, SignedMessage, THEA_HOLD_REASON};

#[test]
Expand Down Expand Up @@ -730,3 +733,21 @@ fn test_asset_metadata_convert_from_native_decimals() {
1000000000000000000
);
}

#[test]
fn test_locks() {
new_test_ext().execute_with(|| {
let relayer = 1u64;
// Mint Balance
let _ = Balances::deposit_creating(&relayer, 100 * UNIT_BALANCE);
let stake = 1 * UNIT_BALANCE;
// Reserve balance
Balances::hold(&THEA_HOLD_REASON, &relayer, stake).unwrap();
Balances::hold(&THEA_HOLD_REASON, &relayer, stake).unwrap();
assert_eq!(Balances::reserved_balance(&relayer), 2 * UNIT_BALANCE);
Balances::release(&THEA_HOLD_REASON, &relayer, stake, Precision::BestEffort).unwrap();
assert_eq!(Balances::reserved_balance(&relayer), 1 * UNIT_BALANCE);
Balances::release(&THEA_HOLD_REASON, &relayer, stake, Precision::BestEffort).unwrap();
assert_eq!(Balances::reserved_balance(&relayer), 0);
})
}
6 changes: 3 additions & 3 deletions primitives/thea/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,13 @@

use frame_support::__private::log;
use parity_scale_codec::{Decode, Encode};
use polkadex_primitives::UNIT_BALANCE;
use scale_info::TypeInfo;
use serde::{Deserialize, Serialize};
use sp_std::{cmp::Ordering, collections::btree_map::BTreeMap};
use sp_runtime::Percent;
use polkadex_primitives::UNIT_BALANCE;
#[cfg(not(feature = "std"))]
use sp_std::vec::Vec;
use sp_std::{cmp::Ordering, collections::btree_map::BTreeMap};

use crate::{Network, ValidatorSetId};

Expand Down Expand Up @@ -105,7 +105,7 @@ impl<Signature> SignedMessage<Signature> {
pub fn threshold_reached(&self, max_len: usize) -> bool {
const MAJORITY: u8 = 67;
let p = Percent::from_percent(MAJORITY);
let threshold = p*max_len;
let threshold = p * max_len;
self.signatures.len() >= threshold
}

Expand Down
2 changes: 1 addition & 1 deletion runtimes/mainnet/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
// and set impl_version to 0. If only runtime
// implementation changes and behavior does not, then leave spec_version as
// is and increment impl_version.
spec_version: 325,
spec_version: 327,
impl_version: 0,
apis: RUNTIME_API_VERSIONS,
transaction_version: 2,
Expand Down
2 changes: 1 addition & 1 deletion runtimes/parachain/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("polkadex-parachain"),
impl_name: create_runtime_str!("polkadex-parachain"),
authoring_version: 1,
spec_version: 10,
spec_version: 11,
impl_version: 0,
apis: RUNTIME_API_VERSIONS,
transaction_version: 1,
Expand Down
Loading

0 comments on commit aa87f4c

Please sign in to comment.