mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-07-09 19:57:34 +00:00
8e01ba9c03
* Squashed 'bridges/' changes from 1602249f0a..f220d2fcca f220d2fcca Polkadot staging update (#1356) 02fd3d497c fix parse_transaction on Rialto+Millau (#1360) bc191fd9a2 update parity-scale-codec to 3.1.2 (#1359) a37226e79c update chain versions (#1358) ff5d539fcb Update Substrate/Polkadot/Cumulus references (#1353) 1581f60cd5 Support dedicated lanes for pallets (#962) 0a7ccf5c57 ignore more "increase" alerts that are sometimes signalling NoData at startup (#1351) 31165127cc added no_stack_overflow_when_decoding_nested_call_during_dispatch test (#1349) 7000619eb8 replace From<>InboundLaneApi with direct storage reads (#1348) 515df10ccc added alerts for relay balances (#1347) b56f6a87de Mortal conversion rate updater transactions (#1257) 20f2f331ec edition = "2021" (#1346) 99147d4f75 update regex to 1.5.5 (#1345) 686191f379 use DecodeLimit when decoding incoming calls (#1344) a70c276006 get rid of '[No Data] Messages from Millau to Rialto are not being delivered' warnings (#1342) 01f29b8ac1 fix conversion rate metric in dashboards (#1341) 51c3bf351f Increase rate from metric when estimating fee (#1340) 3bb9c4f68f fix generator scripts to be consistent with updatedrelay output (#1339) 0475a1667b fixed mess with conversion rates (#1338) d8fdd7d716 synchronize relay cli changes and token swap generator script (#1337) 6e928137a5 fix conversion rate override in token swap (#1336) 62d4a4811d override conversion rate in tokens swap generator (#1335) ed9e1c839c fi typo in generator script (#1334) 3254b5af7a Override conversion rate when computing message fee (#1261) 66df68b5b8 Revert "Revert "override conversion rate in estimate-message-fee RPC (#1189)" (#1275)" (#1333) 0ca6fc6ef8 fix clippy issues (#1332) 5414b2fffb Reinitialize bridge relay subcommand (#1331) a63d95ba7d removed extra *_RUNTIME_VERSION consts from relay code (#1330) 59fb18a310 fix typo in alert expression (#1329) a6267a47ee Using-same-fork metric for finality and complex relay (#1327) 88d684d37e use mortal transactions in transaction resubmitter (#1326) 8ff88b6844 impl Decode for SignedExtensions (otherwise transaction resubmitter panicks) (#1325) 1ed09854f0 Encode and estimate Rococo/Wococo/Kusama/Polkadot messages (#1322) ddb4517e13 Add some tests to check integrity of chain constants + bridge configuration (#1316) bdeedb7ab9 Fix issues from cargo deny (#1311) d3d79d01e0 expose fee multiplier metrics in messages relay (#1312) c8b3f0ea16 Endow relayer account at target chain in message benchmarks (#1310) f51ecd92b6 fix benchmarks before using it in Polkadot/Kusama/Rococo runtimes (#1309) 6935c619ad increase relay balance guard limits for Polkadot<>Kusama bridge (#1308) 7e31834c66 Fix mandatory headers scanning in on-demand relay (#1306) 92ddc3ea7a Polkadot-staging update (#1305) 3787193a31 fix session length of Rococo and Wococo (#1304) eb468d29c0 Revert nightly docker pin (#1301) e2d4c073e1 Use raw balance value if tokenDecimals property is missing (#1299) 108f4b29d1 Fix ss58 prefixes of Polkadot, Kusama and Westend used by relay (#1298) 64fbd2705e bump chain spec versions (#1297) 5707777b86 Bump Substrate/Polkadot/Cumulus refs (#1295) 29eecdf1fa Merge pull request #1294 from paritytech/polkadot-staging-update 1f0c05368e Relay balance metrics (#1291) 6356bb90b3 when messages pallet is halted, relay shall not submit messages delivery/confirmation transactions (#1289) 800dc2df8d when GRANDPA pallet is halted, relay shall not submit finality transactions (#1288) 3dd8e4f936 disable BEEFY allerts for Rialto (#1285) f58fed7380 support version mode cli options in send-message subcommand (#1284) 3aac448da3 reuse polkadot-service code (#1273) 2bdbb651e1 replace latest_confirmed_nonce runtime APIs with direct storage reads (#1282) 5f9c6d241f move "common" code of messages pallet benchmarks helpers to the common library (#1281) 173d2d8229 Merge pull request #1280 from paritytech/polkadot-staging-update 8b9c4ec16d do not start spec_version guard when version mode is set to auto (#1278) e98d682de2 removed extra messages benchmarks (#1279) c730e25b61 Move benchmarks from Rialto to Millau (#1277) 54146416e7 Merge pull request #1276 from paritytech/polkadot-staging-update df70118174 Merge branch 'master' into polkadot-staging-update ed7def64c4 Revert "override conversion rate in estimate-message-fee RPC (#1189)" (#1275) 38c6c3a49f Use "production" floating tag when uilding docker image from version git tags (#1272) ded9ff6dbb Replace InboundLaneApi::latest_received_nonce with direct storage read (#1269) f704a741ee Polkadot staging update (#1270) 8c65f0d7ab verify that GRANDPA pallet is not initialized before submitting initialization transaction (#1267) e7e83d8944 remove OutboundLaneApi::latest_received_nonce (#1262) 9f4b34acf1 bump rococo version (#1263) 82c08c5a87 read latest_generated_nonce directly from storage (#1260) 50ffb5dd08 override conversion rate in estimate-message-fee RPC (#1189) 467ca5ef59 move storage keys computation to primitivs (#1254) 4f9884066b remporary use pinned bridges-ci image in Dockerfile (#1258) edfcb74e00 Change submit transaction spec_version and transaction_version query from chain (#1248) 4009d970d0 pin bridges-ci image (#1256) 65e51b5e1c decrease startup sleep to 5s for relays and to 120s for generators + remove curl (#1251) 3bc74355d9 Add missing RPC APIs to rialto parachain node (#1250) 80c9429284 Bump relay version to 1.0.0 (#1249) 9ead06af2a runtimes: fix call_size() test (#1245) 4fc8a29357 Use same endowed accounts set on dev/local chains (#1244) fed54371c2 Refactor message relay helpers (#1234) a15b4faae7 post-merge build fix (#1243) 52232d8d54 Fix transactions mortality (#1196) c07bba931f Expose prometheus BEEFY metrics and add them to grafana dashboard (#1242) f927775bd5 Refactor finality relay helpers (#1220) 7bf76f14a8 Update Rococo/Wococo version + prepare relay for Rococo<>Wococo bridge (#1241) e860fecd04 Enable offchain indexing for Rialto/Millau nodes (#1239) 04d4d1c6b4 Enable Beefy debug logs in test deployment (#1237) cd771f1089 Fix storage parameter name computation (#1238) 816ddd2dd2 Integrate BEEFY with Rialto & Millau runtimes (#1227) d94b62b1ac update dependencies (#1229) 98eb9ee13d Add mut support (#1232) ffef6f89f9 fixed set_operational in GRANDPA pallet (#1226) bd2f8bfbd7 Add CODEOWNERS file (#1219) 6b5cf2b591 Unify metric names (#1209) d1541e797e remove abandoned exchange relay (#1217) 39140d0b34 Remove unused `relays/headers` (#1216) 9bc071d42b Remove unused PoA<>Substrate bridge (#1210) 877e8d01e3 Fix UI deployment. (#1211) 6cd5775ebe Add `AtLeast32BitUnsigned` for MessageLance::SourceChainBalance (#1207) git-subtree-dir: bridges git-subtree-split: f220d2fccabbf141101d19456ecb4e3576a1d797 * fix compilation warnings
563 lines
17 KiB
Rust
563 lines
17 KiB
Rust
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
|
// This file is part of Parity Bridges Common.
|
|
|
|
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
|
// it under the terms of the GNU General Public License as published by
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
// (at your option) any later version.
|
|
|
|
// Parity Bridges Common is distributed in the hope that it will be useful,
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
// GNU General Public License for more details.
|
|
|
|
// You should have received a copy of the GNU General Public License
|
|
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
// From construct_runtime macro
|
|
#![allow(clippy::from_over_into)]
|
|
|
|
use crate::{instant_payments::cal_relayers_rewards, Config};
|
|
|
|
use bitvec::prelude::*;
|
|
use bp_messages::{
|
|
source_chain::{
|
|
LaneMessageVerifier, MessageDeliveryAndDispatchPayment, OnDeliveryConfirmed,
|
|
OnMessageAccepted, SenderOrigin, TargetHeaderChain,
|
|
},
|
|
target_chain::{
|
|
DispatchMessage, MessageDispatch, ProvedLaneMessages, ProvedMessages, SourceHeaderChain,
|
|
},
|
|
DeliveredMessages, InboundLaneData, LaneId, Message, MessageData, MessageKey, MessageNonce,
|
|
OutboundLaneData, Parameter as MessagesParameter, UnrewardedRelayer,
|
|
};
|
|
use bp_runtime::{messages::MessageDispatchResult, Size};
|
|
use codec::{Decode, Encode};
|
|
use frame_support::{
|
|
parameter_types,
|
|
weights::{RuntimeDbWeight, Weight},
|
|
};
|
|
use scale_info::TypeInfo;
|
|
use sp_core::H256;
|
|
use sp_runtime::{
|
|
testing::Header as SubstrateHeader,
|
|
traits::{BlakeTwo256, IdentityLookup},
|
|
FixedU128, Perbill,
|
|
};
|
|
use std::{
|
|
collections::{BTreeMap, VecDeque},
|
|
ops::RangeInclusive,
|
|
};
|
|
|
|
pub type AccountId = u64;
|
|
pub type Balance = u64;
|
|
#[derive(Decode, Encode, Clone, Debug, PartialEq, Eq, TypeInfo)]
|
|
pub struct TestPayload {
|
|
/// Field that may be used to identify messages.
|
|
pub id: u64,
|
|
/// Dispatch weight that is declared by the message sender.
|
|
pub declared_weight: Weight,
|
|
/// Message dispatch result.
|
|
///
|
|
/// Note: in correct code `dispatch_result.unspent_weight` will always be <= `declared_weight`,
|
|
/// but for test purposes we'll be making it larger than `declared_weight` sometimes.
|
|
pub dispatch_result: MessageDispatchResult,
|
|
/// Extra bytes that affect payload size.
|
|
pub extra: Vec<u8>,
|
|
}
|
|
pub type TestMessageFee = u64;
|
|
pub type TestRelayer = u64;
|
|
|
|
pub struct AccountIdConverter;
|
|
|
|
impl sp_runtime::traits::Convert<H256, AccountId> for AccountIdConverter {
|
|
fn convert(hash: H256) -> AccountId {
|
|
hash.to_low_u64_ne()
|
|
}
|
|
}
|
|
|
|
type Block = frame_system::mocking::MockBlock<TestRuntime>;
|
|
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<TestRuntime>;
|
|
|
|
use crate as pallet_bridge_messages;
|
|
|
|
frame_support::construct_runtime! {
|
|
pub enum TestRuntime where
|
|
Block = Block,
|
|
NodeBlock = Block,
|
|
UncheckedExtrinsic = UncheckedExtrinsic,
|
|
{
|
|
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
|
|
Balances: pallet_balances::{Pallet, Call, Event<T>},
|
|
Messages: pallet_bridge_messages::{Pallet, Call, Event<T>},
|
|
}
|
|
}
|
|
|
|
parameter_types! {
|
|
pub const BlockHashCount: u64 = 250;
|
|
pub const MaximumBlockWeight: Weight = 1024;
|
|
pub const MaximumBlockLength: u32 = 2 * 1024;
|
|
pub const AvailableBlockRatio: Perbill = Perbill::one();
|
|
pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight { read: 1, write: 2 };
|
|
}
|
|
|
|
impl frame_system::Config for TestRuntime {
|
|
type Origin = Origin;
|
|
type Index = u64;
|
|
type Call = Call;
|
|
type BlockNumber = u64;
|
|
type Hash = H256;
|
|
type Hashing = BlakeTwo256;
|
|
type AccountId = AccountId;
|
|
type Lookup = IdentityLookup<Self::AccountId>;
|
|
type Header = SubstrateHeader;
|
|
type Event = Event;
|
|
type BlockHashCount = BlockHashCount;
|
|
type Version = ();
|
|
type PalletInfo = PalletInfo;
|
|
type AccountData = pallet_balances::AccountData<Balance>;
|
|
type OnNewAccount = ();
|
|
type OnKilledAccount = ();
|
|
type BaseCallFilter = frame_support::traits::Everything;
|
|
type SystemWeightInfo = ();
|
|
type BlockWeights = ();
|
|
type BlockLength = ();
|
|
type DbWeight = DbWeight;
|
|
type SS58Prefix = ();
|
|
type OnSetCode = ();
|
|
type MaxConsumers = frame_support::traits::ConstU32<16>;
|
|
}
|
|
|
|
parameter_types! {
|
|
pub const ExistentialDeposit: u64 = 1;
|
|
}
|
|
|
|
impl pallet_balances::Config for TestRuntime {
|
|
type MaxLocks = ();
|
|
type Balance = Balance;
|
|
type DustRemoval = ();
|
|
type Event = Event;
|
|
type ExistentialDeposit = ExistentialDeposit;
|
|
type AccountStore = frame_system::Pallet<TestRuntime>;
|
|
type WeightInfo = ();
|
|
type MaxReserves = ();
|
|
type ReserveIdentifier = ();
|
|
}
|
|
|
|
parameter_types! {
|
|
pub const MaxMessagesToPruneAtOnce: u64 = 10;
|
|
pub const MaxUnrewardedRelayerEntriesAtInboundLane: u64 = 16;
|
|
pub const MaxUnconfirmedMessagesAtInboundLane: u64 = 32;
|
|
pub storage TokenConversionRate: FixedU128 = 1.into();
|
|
pub const TestBridgedChainId: bp_runtime::ChainId = *b"test";
|
|
}
|
|
|
|
#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq, TypeInfo)]
|
|
pub enum TestMessagesParameter {
|
|
TokenConversionRate(FixedU128),
|
|
}
|
|
|
|
impl MessagesParameter for TestMessagesParameter {
|
|
fn save(&self) {
|
|
match *self {
|
|
TestMessagesParameter::TokenConversionRate(conversion_rate) =>
|
|
TokenConversionRate::set(&conversion_rate),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Config for TestRuntime {
|
|
type Event = Event;
|
|
type WeightInfo = ();
|
|
type Parameter = TestMessagesParameter;
|
|
type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce;
|
|
type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane;
|
|
type MaxUnconfirmedMessagesAtInboundLane = MaxUnconfirmedMessagesAtInboundLane;
|
|
|
|
type OutboundPayload = TestPayload;
|
|
type OutboundMessageFee = TestMessageFee;
|
|
|
|
type InboundPayload = TestPayload;
|
|
type InboundMessageFee = TestMessageFee;
|
|
type InboundRelayer = TestRelayer;
|
|
|
|
type AccountIdConverter = AccountIdConverter;
|
|
|
|
type TargetHeaderChain = TestTargetHeaderChain;
|
|
type LaneMessageVerifier = TestLaneMessageVerifier;
|
|
type MessageDeliveryAndDispatchPayment = TestMessageDeliveryAndDispatchPayment;
|
|
type OnMessageAccepted = TestOnMessageAccepted;
|
|
type OnDeliveryConfirmed = (TestOnDeliveryConfirmed1, TestOnDeliveryConfirmed2);
|
|
|
|
type SourceHeaderChain = TestSourceHeaderChain;
|
|
type MessageDispatch = TestMessageDispatch;
|
|
type BridgedChainId = TestBridgedChainId;
|
|
}
|
|
|
|
impl SenderOrigin<AccountId> for Origin {
|
|
fn linked_account(&self) -> Option<AccountId> {
|
|
match self.caller {
|
|
OriginCaller::system(frame_system::RawOrigin::Signed(ref submitter)) =>
|
|
Some(submitter.clone()),
|
|
_ => None,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Size for TestPayload {
|
|
fn size_hint(&self) -> u32 {
|
|
16 + self.extra.len() as u32
|
|
}
|
|
}
|
|
|
|
/// Account that has balance to use in tests.
|
|
pub const ENDOWED_ACCOUNT: AccountId = 0xDEAD;
|
|
|
|
/// Account id of test relayer.
|
|
pub const TEST_RELAYER_A: AccountId = 100;
|
|
|
|
/// Account id of additional test relayer - B.
|
|
pub const TEST_RELAYER_B: AccountId = 101;
|
|
|
|
/// Account id of additional test relayer - C.
|
|
pub const TEST_RELAYER_C: AccountId = 102;
|
|
|
|
/// Error that is returned by all test implementations.
|
|
pub const TEST_ERROR: &str = "Test error";
|
|
|
|
/// Lane that we're using in tests.
|
|
pub const TEST_LANE_ID: LaneId = [0, 0, 0, 1];
|
|
|
|
/// Regular message payload.
|
|
pub const REGULAR_PAYLOAD: TestPayload = message_payload(0, 50);
|
|
|
|
/// Payload that is rejected by `TestTargetHeaderChain`.
|
|
pub const PAYLOAD_REJECTED_BY_TARGET_CHAIN: TestPayload = message_payload(1, 50);
|
|
|
|
/// Vec of proved messages, grouped by lane.
|
|
pub type MessagesByLaneVec = Vec<(LaneId, ProvedLaneMessages<Message<TestMessageFee>>)>;
|
|
|
|
/// Test messages proof.
|
|
#[derive(Debug, Encode, Decode, Clone, PartialEq, Eq, TypeInfo)]
|
|
pub struct TestMessagesProof {
|
|
pub result: Result<MessagesByLaneVec, ()>,
|
|
}
|
|
|
|
impl Size for TestMessagesProof {
|
|
fn size_hint(&self) -> u32 {
|
|
0
|
|
}
|
|
}
|
|
|
|
impl From<Result<Vec<Message<TestMessageFee>>, ()>> for TestMessagesProof {
|
|
fn from(result: Result<Vec<Message<TestMessageFee>>, ()>) -> Self {
|
|
Self {
|
|
result: result.map(|messages| {
|
|
let mut messages_by_lane: BTreeMap<
|
|
LaneId,
|
|
ProvedLaneMessages<Message<TestMessageFee>>,
|
|
> = BTreeMap::new();
|
|
for message in messages {
|
|
messages_by_lane.entry(message.key.lane_id).or_default().messages.push(message);
|
|
}
|
|
messages_by_lane.into_iter().collect()
|
|
}),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Messages delivery proof used in tests.
|
|
#[derive(Debug, Encode, Decode, Eq, Clone, PartialEq, TypeInfo)]
|
|
pub struct TestMessagesDeliveryProof(pub Result<(LaneId, InboundLaneData<TestRelayer>), ()>);
|
|
|
|
impl Size for TestMessagesDeliveryProof {
|
|
fn size_hint(&self) -> u32 {
|
|
0
|
|
}
|
|
}
|
|
|
|
/// Target header chain that is used in tests.
|
|
#[derive(Debug, Default)]
|
|
pub struct TestTargetHeaderChain;
|
|
|
|
impl TargetHeaderChain<TestPayload, TestRelayer> for TestTargetHeaderChain {
|
|
type Error = &'static str;
|
|
|
|
type MessagesDeliveryProof = TestMessagesDeliveryProof;
|
|
|
|
fn verify_message(payload: &TestPayload) -> Result<(), Self::Error> {
|
|
if *payload == PAYLOAD_REJECTED_BY_TARGET_CHAIN {
|
|
Err(TEST_ERROR)
|
|
} else {
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
fn verify_messages_delivery_proof(
|
|
proof: Self::MessagesDeliveryProof,
|
|
) -> Result<(LaneId, InboundLaneData<TestRelayer>), Self::Error> {
|
|
proof.0.map_err(|_| TEST_ERROR)
|
|
}
|
|
}
|
|
|
|
/// Lane message verifier that is used in tests.
|
|
#[derive(Debug, Default)]
|
|
pub struct TestLaneMessageVerifier;
|
|
|
|
impl LaneMessageVerifier<Origin, AccountId, TestPayload, TestMessageFee>
|
|
for TestLaneMessageVerifier
|
|
{
|
|
type Error = &'static str;
|
|
|
|
fn verify_message(
|
|
_submitter: &Origin,
|
|
delivery_and_dispatch_fee: &TestMessageFee,
|
|
_lane: &LaneId,
|
|
_lane_outbound_data: &OutboundLaneData,
|
|
_payload: &TestPayload,
|
|
) -> Result<(), Self::Error> {
|
|
if *delivery_and_dispatch_fee != 0 {
|
|
Ok(())
|
|
} else {
|
|
Err(TEST_ERROR)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Message fee payment system that is used in tests.
|
|
#[derive(Debug, Default)]
|
|
pub struct TestMessageDeliveryAndDispatchPayment;
|
|
|
|
impl TestMessageDeliveryAndDispatchPayment {
|
|
/// Reject all payments.
|
|
pub fn reject_payments() {
|
|
frame_support::storage::unhashed::put(b":reject-message-fee:", &true);
|
|
}
|
|
|
|
/// Returns true if given fee has been paid by given submitter.
|
|
pub fn is_fee_paid(submitter: AccountId, fee: TestMessageFee) -> bool {
|
|
let raw_origin: Result<frame_system::RawOrigin<_>, _> = Origin::signed(submitter).into();
|
|
frame_support::storage::unhashed::get(b":message-fee:") == Some((raw_origin.unwrap(), fee))
|
|
}
|
|
|
|
/// Returns true if given relayer has been rewarded with given balance. The reward-paid flag is
|
|
/// cleared after the call.
|
|
pub fn is_reward_paid(relayer: AccountId, fee: TestMessageFee) -> bool {
|
|
let key = (b":relayer-reward:", relayer, fee).encode();
|
|
frame_support::storage::unhashed::take::<bool>(&key).is_some()
|
|
}
|
|
}
|
|
|
|
impl MessageDeliveryAndDispatchPayment<Origin, AccountId, TestMessageFee>
|
|
for TestMessageDeliveryAndDispatchPayment
|
|
{
|
|
type Error = &'static str;
|
|
|
|
fn pay_delivery_and_dispatch_fee(
|
|
submitter: &Origin,
|
|
fee: &TestMessageFee,
|
|
_relayer_fund_account: &AccountId,
|
|
) -> Result<(), Self::Error> {
|
|
if frame_support::storage::unhashed::get(b":reject-message-fee:") == Some(true) {
|
|
return Err(TEST_ERROR)
|
|
}
|
|
|
|
let raw_origin: Result<frame_system::RawOrigin<_>, _> = submitter.clone().into();
|
|
frame_support::storage::unhashed::put(b":message-fee:", &(raw_origin.unwrap(), fee));
|
|
Ok(())
|
|
}
|
|
|
|
fn pay_relayers_rewards(
|
|
lane_id: LaneId,
|
|
message_relayers: VecDeque<UnrewardedRelayer<AccountId>>,
|
|
_confirmation_relayer: &AccountId,
|
|
received_range: &RangeInclusive<MessageNonce>,
|
|
_relayer_fund_account: &AccountId,
|
|
) {
|
|
let relayers_rewards =
|
|
cal_relayers_rewards::<TestRuntime, ()>(lane_id, message_relayers, received_range);
|
|
for (relayer, reward) in &relayers_rewards {
|
|
let key = (b":relayer-reward:", relayer, reward.reward).encode();
|
|
frame_support::storage::unhashed::put(&key, &true);
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub struct TestOnMessageAccepted;
|
|
|
|
impl TestOnMessageAccepted {
|
|
/// Verify that the callback has been called when the message is accepted.
|
|
pub fn ensure_called(lane: &LaneId, message: &MessageNonce) {
|
|
let key = (b"TestOnMessageAccepted", lane, message).encode();
|
|
assert_eq!(frame_support::storage::unhashed::get(&key), Some(true));
|
|
}
|
|
|
|
/// Set consumed weight returned by the callback.
|
|
pub fn set_consumed_weight_per_message(weight: Weight) {
|
|
frame_support::storage::unhashed::put(b"TestOnMessageAccepted_Weight", &weight);
|
|
}
|
|
|
|
/// Get consumed weight returned by the callback.
|
|
pub fn get_consumed_weight_per_message() -> Option<Weight> {
|
|
frame_support::storage::unhashed::get(b"TestOnMessageAccepted_Weight")
|
|
}
|
|
}
|
|
|
|
impl OnMessageAccepted for TestOnMessageAccepted {
|
|
fn on_messages_accepted(lane: &LaneId, message: &MessageNonce) -> Weight {
|
|
let key = (b"TestOnMessageAccepted", lane, message).encode();
|
|
frame_support::storage::unhashed::put(&key, &true);
|
|
Self::get_consumed_weight_per_message()
|
|
.unwrap_or_else(|| DbWeight::get().reads_writes(1, 1))
|
|
}
|
|
}
|
|
|
|
/// First on-messages-delivered callback.
|
|
#[derive(Debug)]
|
|
pub struct TestOnDeliveryConfirmed1;
|
|
|
|
impl TestOnDeliveryConfirmed1 {
|
|
/// Verify that the callback has been called with given delivered messages.
|
|
pub fn ensure_called(lane: &LaneId, messages: &DeliveredMessages) {
|
|
let key = (b"TestOnDeliveryConfirmed1", lane, messages).encode();
|
|
assert_eq!(frame_support::storage::unhashed::get(&key), Some(true));
|
|
}
|
|
|
|
/// Set consumed weight returned by the callback.
|
|
pub fn set_consumed_weight_per_message(weight: Weight) {
|
|
frame_support::storage::unhashed::put(b"TestOnDeliveryConfirmed1_Weight", &weight);
|
|
}
|
|
|
|
/// Get consumed weight returned by the callback.
|
|
pub fn get_consumed_weight_per_message() -> Option<Weight> {
|
|
frame_support::storage::unhashed::get(b"TestOnDeliveryConfirmed1_Weight")
|
|
}
|
|
}
|
|
|
|
impl OnDeliveryConfirmed for TestOnDeliveryConfirmed1 {
|
|
fn on_messages_delivered(lane: &LaneId, messages: &DeliveredMessages) -> Weight {
|
|
let key = (b"TestOnDeliveryConfirmed1", lane, messages).encode();
|
|
frame_support::storage::unhashed::put(&key, &true);
|
|
Self::get_consumed_weight_per_message()
|
|
.unwrap_or_else(|| DbWeight::get().reads_writes(1, 1))
|
|
.saturating_mul(messages.total_messages())
|
|
}
|
|
}
|
|
|
|
/// Second on-messages-delivered callback.
|
|
#[derive(Debug)]
|
|
pub struct TestOnDeliveryConfirmed2;
|
|
|
|
impl TestOnDeliveryConfirmed2 {
|
|
/// Verify that the callback has been called with given delivered messages.
|
|
pub fn ensure_called(lane: &LaneId, messages: &DeliveredMessages) {
|
|
let key = (b"TestOnDeliveryConfirmed2", lane, messages).encode();
|
|
assert_eq!(frame_support::storage::unhashed::get(&key), Some(true));
|
|
}
|
|
}
|
|
|
|
impl OnDeliveryConfirmed for TestOnDeliveryConfirmed2 {
|
|
fn on_messages_delivered(lane: &LaneId, messages: &DeliveredMessages) -> Weight {
|
|
let key = (b"TestOnDeliveryConfirmed2", lane, messages).encode();
|
|
frame_support::storage::unhashed::put(&key, &true);
|
|
0
|
|
}
|
|
}
|
|
|
|
/// Source header chain that is used in tests.
|
|
#[derive(Debug)]
|
|
pub struct TestSourceHeaderChain;
|
|
|
|
impl SourceHeaderChain<TestMessageFee> for TestSourceHeaderChain {
|
|
type Error = &'static str;
|
|
|
|
type MessagesProof = TestMessagesProof;
|
|
|
|
fn verify_messages_proof(
|
|
proof: Self::MessagesProof,
|
|
_messages_count: u32,
|
|
) -> Result<ProvedMessages<Message<TestMessageFee>>, Self::Error> {
|
|
proof.result.map(|proof| proof.into_iter().collect()).map_err(|_| TEST_ERROR)
|
|
}
|
|
}
|
|
|
|
/// Source header chain that is used in tests.
|
|
#[derive(Debug)]
|
|
pub struct TestMessageDispatch;
|
|
|
|
impl MessageDispatch<AccountId, TestMessageFee> for TestMessageDispatch {
|
|
type DispatchPayload = TestPayload;
|
|
|
|
fn dispatch_weight(message: &DispatchMessage<TestPayload, TestMessageFee>) -> Weight {
|
|
match message.data.payload.as_ref() {
|
|
Ok(payload) => payload.declared_weight,
|
|
Err(_) => 0,
|
|
}
|
|
}
|
|
|
|
fn dispatch(
|
|
_relayer_account: &AccountId,
|
|
message: DispatchMessage<TestPayload, TestMessageFee>,
|
|
) -> MessageDispatchResult {
|
|
match message.data.payload.as_ref() {
|
|
Ok(payload) => payload.dispatch_result.clone(),
|
|
Err(_) => dispatch_result(0),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Return test lane message with given nonce and payload.
|
|
pub fn message(nonce: MessageNonce, payload: TestPayload) -> Message<TestMessageFee> {
|
|
Message { key: MessageKey { lane_id: TEST_LANE_ID, nonce }, data: message_data(payload) }
|
|
}
|
|
|
|
/// Constructs message payload using given arguments and zero unspent weight.
|
|
pub const fn message_payload(id: u64, declared_weight: Weight) -> TestPayload {
|
|
TestPayload { id, declared_weight, dispatch_result: dispatch_result(0), extra: Vec::new() }
|
|
}
|
|
|
|
/// Return message data with valid fee for given payload.
|
|
pub fn message_data(payload: TestPayload) -> MessageData<TestMessageFee> {
|
|
MessageData { payload: payload.encode(), fee: 1 }
|
|
}
|
|
|
|
/// Returns message dispatch result with given unspent weight.
|
|
pub const fn dispatch_result(unspent_weight: Weight) -> MessageDispatchResult {
|
|
MessageDispatchResult {
|
|
dispatch_result: true,
|
|
unspent_weight,
|
|
dispatch_fee_paid_during_dispatch: true,
|
|
}
|
|
}
|
|
|
|
/// Constructs unrewarded relayer entry from nonces range and relayer id.
|
|
pub fn unrewarded_relayer(
|
|
begin: MessageNonce,
|
|
end: MessageNonce,
|
|
relayer: TestRelayer,
|
|
) -> UnrewardedRelayer<TestRelayer> {
|
|
UnrewardedRelayer {
|
|
relayer,
|
|
messages: DeliveredMessages {
|
|
begin,
|
|
end,
|
|
dispatch_results: if end >= begin {
|
|
bitvec![u8, Msb0; 1; (end - begin + 1) as _]
|
|
} else {
|
|
Default::default()
|
|
},
|
|
},
|
|
}
|
|
}
|
|
|
|
/// Run pallet test.
|
|
pub fn run_test<T>(test: impl FnOnce() -> T) -> T {
|
|
let mut t = frame_system::GenesisConfig::default().build_storage::<TestRuntime>().unwrap();
|
|
pallet_balances::GenesisConfig::<TestRuntime> { balances: vec![(ENDOWED_ACCOUNT, 1_000_000)] }
|
|
.assimilate_storage(&mut t)
|
|
.unwrap();
|
|
let mut ext = sp_io::TestExternalities::new(t);
|
|
ext.execute_with(test)
|
|
}
|