diff --git a/modules/messages/src/benchmarking.rs b/modules/messages/src/benchmarking.rs index d2764b08..05c1f649 100644 --- a/modules/messages/src/benchmarking.rs +++ b/modules/messages/src/benchmarking.rs @@ -18,35 +18,25 @@ use crate::{ inbound_lane::InboundLaneStorage, inbound_lane_storage, outbound_lane, - outbound_lane::ReceivalConfirmationResult, weights_ext::EXPECTED_DEFAULT_MESSAGE_LENGTH, Call, - OutboundLanes, + weights_ext::EXPECTED_DEFAULT_MESSAGE_LENGTH, Call, OutboundLanes, }; use bp_messages::{ source_chain::TargetHeaderChain, target_chain::SourceHeaderChain, DeliveredMessages, - InboundLaneData, LaneId, MessageData, MessageNonce, OutboundLaneData, UnrewardedRelayer, + InboundLaneData, LaneId, MessageNonce, OutboundLaneData, UnrewardedRelayer, UnrewardedRelayersState, }; -use bp_runtime::{messages::DispatchFeePayment, StorageProofSize}; +use bp_runtime::StorageProofSize; use frame_benchmarking::{account, benchmarks_instance_pallet}; -use frame_support::{traits::Get, weights::Weight}; +use frame_support::weights::Weight; use frame_system::RawOrigin; -use sp_std::{collections::vec_deque::VecDeque, ops::RangeInclusive, prelude::*}; +use sp_std::{ops::RangeInclusive, prelude::*}; const SEED: u32 = 0; /// Pallet we're benchmarking here. pub struct Pallet, I: 'static>(crate::Pallet); -/// Benchmark-specific message parameters. -#[derive(Debug)] -pub struct MessageParams { - /// Size of the message payload. - pub size: u32, - /// Message sender account. - pub sender_account: ThisAccountId, -} - /// Benchmark-specific message proof parameters. #[derive(Debug)] pub struct MessageProofParams { @@ -58,8 +48,6 @@ pub struct MessageProofParams { pub outbound_lane_data: Option, /// Proof size requirements. pub size: StorageProofSize, - /// Where the fee for dispatching message is paid? - pub dispatch_fee_payment: DispatchFeePayment, } /// Benchmark-specific message delivery proof parameters. @@ -79,29 +67,14 @@ pub trait Config: crate::Config { fn bench_lane_id() -> LaneId { Default::default() } - /// Get maximal size of the message payload. - fn maximal_message_size() -> u32; /// Return id of relayer account at the bridged chain. fn bridged_relayer_id() -> Self::InboundRelayer; - /// Return balance of given account. - fn account_balance(account: &Self::AccountId) -> Self::OutboundMessageFee; /// Create given account and give it enough balance for test purposes. fn endow_account(account: &Self::AccountId); - /// Fee paid by submitter for single message delivery. - fn message_fee() -> Self::OutboundMessageFee { - 100_000_000_000_000.into() - } - /// Prepare message to send over lane. - fn prepare_outbound_message( - params: MessageParams, - ) -> (Self::OutboundPayload, Self::OutboundMessageFee); /// Prepare messages proof to receive by the module. fn prepare_message_proof( params: MessageProofParams, - ) -> ( - >::MessagesProof, - Weight, - ); + ) -> (::MessagesProof, Weight); /// Prepare messages delivery proof to receive by the module. fn prepare_message_delivery_proof( params: MessageDeliveryProofParams, @@ -115,112 +88,6 @@ benchmarks_instance_pallet! { // Benchmarks that are used directly by the runtime. // - // Benchmark `send_message` extrinsic with the worst possible conditions: - // * outbound lane already has state, so it needs to be read and decoded; - // * relayers fund account does not exists (in practice it needs to exist in production environment); - // * maximal number of messages is being pruned during the call; - // * message size is minimal for the target chain. - // - // Result of this benchmark is used as a base weight for `send_message` call. Then the 'message weight' - // (estimated using `send_half_maximal_message_worst_case` and `send_maximal_message_worst_case`) is - // added. - send_minimal_message_worst_case { - let lane_id = T::bench_lane_id(); - let sender = account("sender", 0, SEED); - T::endow_account(&sender); - - // 'send' messages that are to be pruned when our message is sent - for _nonce in 1..=T::MaxMessagesToPruneAtOnce::get() { - send_regular_message::(); - } - confirm_message_delivery::(T::MaxMessagesToPruneAtOnce::get()); - - let (payload, fee) = T::prepare_outbound_message(MessageParams { - size: 0, - sender_account: sender.clone(), - }); - }: send_message(RawOrigin::Signed(sender), lane_id, payload, fee) - verify { - assert_eq!( - crate::OutboundLanes::::get(&T::bench_lane_id()).latest_generated_nonce, - T::MaxMessagesToPruneAtOnce::get() + 1, - ); - } - - // Benchmark `send_message` extrinsic with the worst possible conditions: - // * outbound lane already has state, so it needs to be read and decoded; - // * relayers fund account does not exists (in practice it needs to exist in production environment); - // * maximal number of messages is being pruned during the call; - // * message size is 1KB. - // - // With single KB of message size, the weight of the call is increased (roughly) by - // `(send_16_kb_message_worst_case - send_1_kb_message_worst_case) / 15`. - send_1_kb_message_worst_case { - let lane_id = T::bench_lane_id(); - let sender = account("sender", 0, SEED); - T::endow_account(&sender); - - // 'send' messages that are to be pruned when our message is sent - for _nonce in 1..=T::MaxMessagesToPruneAtOnce::get() { - send_regular_message::(); - } - confirm_message_delivery::(T::MaxMessagesToPruneAtOnce::get()); - - let size = 1024; - assert!( - T::maximal_message_size() > size, - "This benchmark can only be used with runtime that accepts 1KB messages", - ); - - let (payload, fee) = T::prepare_outbound_message(MessageParams { - size, - sender_account: sender.clone(), - }); - }: send_message(RawOrigin::Signed(sender), lane_id, payload, fee) - verify { - assert_eq!( - crate::OutboundLanes::::get(&T::bench_lane_id()).latest_generated_nonce, - T::MaxMessagesToPruneAtOnce::get() + 1, - ); - } - - // Benchmark `send_message` extrinsic with the worst possible conditions: - // * outbound lane already has state, so it needs to be read and decoded; - // * relayers fund account does not exists (in practice it needs to exist in production environment); - // * maximal number of messages is being pruned during the call; - // * message size is 16KB. - // - // With single KB of message size, the weight of the call is increased (roughly) by - // `(send_16_kb_message_worst_case - send_1_kb_message_worst_case) / 15`. - send_16_kb_message_worst_case { - let lane_id = T::bench_lane_id(); - let sender = account("sender", 0, SEED); - T::endow_account(&sender); - - // 'send' messages that are to be pruned when our message is sent - for _nonce in 1..=T::MaxMessagesToPruneAtOnce::get() { - send_regular_message::(); - } - confirm_message_delivery::(T::MaxMessagesToPruneAtOnce::get()); - - let size = 16 * 1024; - assert!( - T::maximal_message_size() > size, - "This benchmark can only be used with runtime that accepts 16KB messages", - ); - - let (payload, fee) = T::prepare_outbound_message(MessageParams { - size, - sender_account: sender.clone(), - }); - }: send_message(RawOrigin::Signed(sender), lane_id, payload, fee) - verify { - assert_eq!( - crate::OutboundLanes::::get(&T::bench_lane_id()).latest_generated_nonce, - T::MaxMessagesToPruneAtOnce::get() + 1, - ); - } - // Benchmark `receive_messages_proof` extrinsic with single minimal-weight message and following conditions: // * proof does not include outbound lane state proof; // * inbound lane already has state, so it needs to be read and decoded; @@ -242,7 +109,6 @@ benchmarks_instance_pallet! { message_nonces: 21..=21, outbound_lane_data: None, size: StorageProofSize::Minimal(EXPECTED_DEFAULT_MESSAGE_LENGTH), - dispatch_fee_payment: DispatchFeePayment::AtTargetChain, }); }: receive_messages_proof(RawOrigin::Signed(relayer_id_on_target), relayer_id_on_source, proof, 1, dispatch_weight) verify { @@ -277,7 +143,6 @@ benchmarks_instance_pallet! { message_nonces: 21..=22, outbound_lane_data: None, size: StorageProofSize::Minimal(EXPECTED_DEFAULT_MESSAGE_LENGTH), - dispatch_fee_payment: DispatchFeePayment::AtTargetChain, }); }: receive_messages_proof(RawOrigin::Signed(relayer_id_on_target), relayer_id_on_source, proof, 2, dispatch_weight) verify { @@ -316,7 +181,6 @@ benchmarks_instance_pallet! { latest_generated_nonce: 21, }), size: StorageProofSize::Minimal(EXPECTED_DEFAULT_MESSAGE_LENGTH), - dispatch_fee_payment: DispatchFeePayment::AtTargetChain, }); }: receive_messages_proof(RawOrigin::Signed(relayer_id_on_target), relayer_id_on_source, proof, 1, dispatch_weight) verify { @@ -348,7 +212,6 @@ benchmarks_instance_pallet! { message_nonces: 21..=21, outbound_lane_data: None, size: StorageProofSize::HasExtraNodes(1024), - dispatch_fee_payment: DispatchFeePayment::AtTargetChain, }); }: receive_messages_proof(RawOrigin::Signed(relayer_id_on_target), relayer_id_on_source, proof, 1, dispatch_weight) verify { @@ -383,7 +246,6 @@ benchmarks_instance_pallet! { message_nonces: 21..=21, outbound_lane_data: None, size: StorageProofSize::HasExtraNodes(16 * 1024), - dispatch_fee_payment: DispatchFeePayment::AtTargetChain, }); }: receive_messages_proof(RawOrigin::Signed(relayer_id_on_target), relayer_id_on_source, proof, 1, dispatch_weight) verify { @@ -417,7 +279,6 @@ benchmarks_instance_pallet! { message_nonces: 21..=21, outbound_lane_data: None, size: StorageProofSize::Minimal(EXPECTED_DEFAULT_MESSAGE_LENGTH), - dispatch_fee_payment: DispatchFeePayment::AtSourceChain, }); }: receive_messages_proof(RawOrigin::Signed(relayer_id_on_target), relayer_id_on_source, proof, 1, dispatch_weight) verify { @@ -435,7 +296,6 @@ benchmarks_instance_pallet! { // This is base benchmark for all other confirmations delivery benchmarks. receive_delivery_proof_for_single_message { let relayer_id: T::AccountId = account("relayer", 0, SEED); - let relayer_balance = T::account_balance(&relayer_id); // send message that we're going to confirm send_regular_message::(); @@ -471,7 +331,6 @@ benchmarks_instance_pallet! { // - weight(receive_delivery_proof_for_single_message)`. receive_delivery_proof_for_two_messages_by_single_relayer { let relayer_id: T::AccountId = account("relayer", 0, SEED); - let relayer_balance = T::account_balance(&relayer_id); // send message that we're going to confirm send_regular_message::(); @@ -510,9 +369,7 @@ benchmarks_instance_pallet! { // - weight(receive_delivery_proof_for_two_messages_by_single_relayer)`. receive_delivery_proof_for_two_messages_by_two_relayers { let relayer1_id: T::AccountId = account("relayer1", 1, SEED); - let relayer1_balance = T::account_balance(&relayer1_id); let relayer2_id: T::AccountId = account("relayer2", 2, SEED); - let relayer2_balance = T::account_balance(&relayer2_id); // send message that we're going to confirm send_regular_message::(); @@ -549,23 +406,7 @@ benchmarks_instance_pallet! { fn send_regular_message, I: 'static>() { let mut outbound_lane = outbound_lane::(T::bench_lane_id()); - outbound_lane.send_message(MessageData { payload: vec![], fee: T::message_fee() }); -} - -fn confirm_message_delivery, I: 'static>(nonce: MessageNonce) { - let mut outbound_lane = outbound_lane::(T::bench_lane_id()); - let latest_received_nonce = outbound_lane.data().latest_received_nonce; - let mut relayers = VecDeque::with_capacity((nonce - latest_received_nonce) as usize); - for nonce in latest_received_nonce + 1..=nonce { - relayers.push_back(UnrewardedRelayer { - relayer: (), - messages: DeliveredMessages::new(nonce, true), - }); - } - assert!(matches!( - outbound_lane.confirm_delivery(nonce - latest_received_nonce, nonce, &relayers), - ReceivalConfirmationResult::ConfirmedMessages(_), - )); + outbound_lane.send_message(vec![]); } fn receive_messages, I: 'static>(nonce: MessageNonce) { diff --git a/modules/messages/src/inbound_lane.rs b/modules/messages/src/inbound_lane.rs index 0526b15a..3e7d4803 100644 --- a/modules/messages/src/inbound_lane.rs +++ b/modules/messages/src/inbound_lane.rs @@ -31,8 +31,6 @@ use frame_support::{traits::Get, RuntimeDebug}; /// Inbound lane storage. pub trait InboundLaneStorage { - /// Delivery and dispatch fee type on source chain. - type MessageFee; /// Id of relayer on source chain. type Relayer: Clone + PartialEq; @@ -159,12 +157,12 @@ impl InboundLane { } /// Receive new message. - pub fn receive_message, AccountId>( + pub fn receive_message, AccountId>( &mut self, relayer_at_bridged_chain: &S::Relayer, relayer_at_this_chain: &AccountId, nonce: MessageNonce, - message_data: DispatchMessageData, + message_data: DispatchMessageData, ) -> ReceivalResult { let mut data = self.storage.data(); let is_correct_message = nonce == data.last_delivered_nonce() + 1; @@ -223,9 +221,9 @@ mod tests { use crate::{ inbound_lane, mock::{ - dispatch_result, message_data, run_test, unrewarded_relayer, TestMessageDispatch, - TestRuntime, REGULAR_PAYLOAD, TEST_LANE_ID, TEST_RELAYER_A, TEST_RELAYER_B, - TEST_RELAYER_C, + dispatch_result, inbound_message_data, run_test, unrewarded_relayer, + TestMessageDispatch, TestRuntime, REGULAR_PAYLOAD, TEST_LANE_ID, TEST_RELAYER_A, + TEST_RELAYER_B, TEST_RELAYER_C, }, RuntimeInboundLaneStorage, }; @@ -239,7 +237,7 @@ mod tests { &TEST_RELAYER_A, &TEST_RELAYER_A, nonce, - message_data(REGULAR_PAYLOAD).into() + inbound_message_data(REGULAR_PAYLOAD) ), ReceivalResult::Dispatched(dispatch_result(0)) ); @@ -367,7 +365,7 @@ mod tests { &TEST_RELAYER_A, &TEST_RELAYER_A, 10, - message_data(REGULAR_PAYLOAD).into() + inbound_message_data(REGULAR_PAYLOAD) ), ReceivalResult::InvalidNonce ); @@ -387,7 +385,7 @@ mod tests { &(TEST_RELAYER_A + current_nonce), &(TEST_RELAYER_A + current_nonce), current_nonce, - message_data(REGULAR_PAYLOAD).into() + inbound_message_data(REGULAR_PAYLOAD) ), ReceivalResult::Dispatched(dispatch_result(0)) ); @@ -398,7 +396,7 @@ mod tests { &(TEST_RELAYER_A + max_nonce + 1), &(TEST_RELAYER_A + max_nonce + 1), max_nonce + 1, - message_data(REGULAR_PAYLOAD).into() + inbound_message_data(REGULAR_PAYLOAD) ), ReceivalResult::TooManyUnrewardedRelayers, ); @@ -408,7 +406,7 @@ mod tests { &(TEST_RELAYER_A + max_nonce), &(TEST_RELAYER_A + max_nonce), max_nonce + 1, - message_data(REGULAR_PAYLOAD).into() + inbound_message_data(REGULAR_PAYLOAD) ), ReceivalResult::TooManyUnrewardedRelayers, ); @@ -426,7 +424,7 @@ mod tests { &TEST_RELAYER_A, &TEST_RELAYER_A, current_nonce, - message_data(REGULAR_PAYLOAD).into() + inbound_message_data(REGULAR_PAYLOAD) ), ReceivalResult::Dispatched(dispatch_result(0)) ); @@ -437,7 +435,7 @@ mod tests { &TEST_RELAYER_B, &TEST_RELAYER_B, max_nonce + 1, - message_data(REGULAR_PAYLOAD).into() + inbound_message_data(REGULAR_PAYLOAD) ), ReceivalResult::TooManyUnconfirmedMessages, ); @@ -447,7 +445,7 @@ mod tests { &TEST_RELAYER_A, &TEST_RELAYER_A, max_nonce + 1, - message_data(REGULAR_PAYLOAD).into() + inbound_message_data(REGULAR_PAYLOAD) ), ReceivalResult::TooManyUnconfirmedMessages, ); @@ -463,7 +461,7 @@ mod tests { &TEST_RELAYER_A, &TEST_RELAYER_A, 1, - message_data(REGULAR_PAYLOAD).into() + inbound_message_data(REGULAR_PAYLOAD) ), ReceivalResult::Dispatched(dispatch_result(0)) ); @@ -472,7 +470,7 @@ mod tests { &TEST_RELAYER_B, &TEST_RELAYER_B, 2, - message_data(REGULAR_PAYLOAD).into() + inbound_message_data(REGULAR_PAYLOAD) ), ReceivalResult::Dispatched(dispatch_result(0)) ); @@ -481,7 +479,7 @@ mod tests { &TEST_RELAYER_A, &TEST_RELAYER_A, 3, - message_data(REGULAR_PAYLOAD).into() + inbound_message_data(REGULAR_PAYLOAD) ), ReceivalResult::Dispatched(dispatch_result(0)) ); @@ -505,7 +503,7 @@ mod tests { &TEST_RELAYER_A, &TEST_RELAYER_A, 1, - message_data(REGULAR_PAYLOAD).into() + inbound_message_data(REGULAR_PAYLOAD) ), ReceivalResult::Dispatched(dispatch_result(0)) ); @@ -514,7 +512,7 @@ mod tests { &TEST_RELAYER_B, &TEST_RELAYER_B, 1, - message_data(REGULAR_PAYLOAD).into() + inbound_message_data(REGULAR_PAYLOAD) ), ReceivalResult::InvalidNonce, ); @@ -541,7 +539,7 @@ mod tests { &TEST_RELAYER_A, &TEST_RELAYER_A, 1, - message_data(payload).into() + inbound_message_data(payload) ), ReceivalResult::Dispatched(dispatch_result(1)) ); diff --git a/modules/messages/src/lib.rs b/modules/messages/src/lib.rs index 53f5014c..4d6999ce 100644 --- a/modules/messages/src/lib.rs +++ b/modules/messages/src/lib.rs @@ -50,7 +50,7 @@ mod inbound_lane; pub use inbound_lane::StoredInboundLaneData; mod outbound_lane; -pub use outbound_lane::StoredMessageData; +pub use outbound_lane::StoredMessagePayload; mod weights_ext; pub use weights_ext::{ @@ -60,7 +60,7 @@ pub use weights_ext::{ // crates.io use codec::{Decode, Encode, MaxEncodedLen}; -use num_traits::{SaturatingAdd, Zero}; +use num_traits::Zero; // darwinia-network use crate::{ inbound_lane::{InboundLane, InboundLaneStorage}, @@ -75,9 +75,8 @@ use bp_messages::{ DispatchMessage, MessageDispatch, ProvedLaneMessages, ProvedMessages, SourceHeaderChain, }, total_unrewarded_messages, DeliveredMessages, InboundLaneData, InboundMessageDetails, LaneId, - MessageData, MessageKey, MessageNonce, MessagePayload, OperatingMode, OutboundLaneData, - OutboundMessageDetails, Parameter as MessagesParameter, UnrewardedRelayer, - UnrewardedRelayersState, + MessageKey, MessageNonce, MessagePayload, MessagesOperatingMode, OutboundLaneData, + OutboundMessageDetails, UnrewardedRelayer, UnrewardedRelayersState, }; use bp_runtime::{BasicOperatingMode, ChainId, OwnedBridgeModule, Size}; // paritytech @@ -85,8 +84,8 @@ use frame_support::{dispatch::PostDispatchInfo, ensure, fail, log, traits::Get}; use sp_core::H256; use sp_runtime::traits::Convert; use sp_std::{ - cell::RefCell, cmp::PartialOrd, collections::vec_deque::VecDeque, marker::PhantomData, - ops::RangeInclusive, prelude::*, + cell::RefCell, collections::vec_deque::VecDeque, marker::PhantomData, ops::RangeInclusive, + prelude::*, }; /// The target that will be used when publishing logs related to this pallet. @@ -112,11 +111,6 @@ pub mod pallet { /// Gets the chain id value from the instance. #[pallet::constant] type BridgedChainId: Get; - /// Pallet parameter that is opaque to the pallet itself, but may be used by the runtime - /// for integrating the pallet. - /// - /// All pallet parameters may only be updated either by the root, or by the pallet owner. - type Parameter: MessagesParameter; /// Maximal number of messages that may be pruned during maintenance. Maintenance occurs /// whenever new message is sent. The reason is that if you want to use lane, you should @@ -146,25 +140,14 @@ pub mod pallet { /// these messages are from different lanes. type MaxUnconfirmedMessagesAtInboundLane: Get; - /// Maximal size of the outbound payload. + /// Maximal encoded size of the outbound payload. #[pallet::constant] type MaximalOutboundPayloadSize: Get; /// Payload type of outbound messages. This payload is dispatched on the bridged chain. type OutboundPayload: Parameter + Size; - /// Message fee type of outbound messages. This fee is paid on this chain. - type OutboundMessageFee: Default - + From - + PartialOrd - + Parameter - + SaturatingAdd - + Zero - + Copy - + MaxEncodedLen; /// Payload type of inbound messages. This payload is dispatched on this chain. type InboundPayload: Decode; - /// Message fee type of inbound messages. This fee is paid on the bridged chain. - type InboundMessageFee: Decode + Zero; /// Identifier of relayer that deliver messages to this chain. Relayer reward is paid on the /// bridged chain. type InboundRelayer: Parameter + MaxEncodedLen; @@ -179,16 +162,11 @@ pub mod pallet { /// Target header chain. type TargetHeaderChain: TargetHeaderChain; /// Message payload verifier. - type LaneMessageVerifier: LaneMessageVerifier< - Self::RuntimeOrigin, - Self::OutboundPayload, - Self::OutboundMessageFee, - >; + type LaneMessageVerifier: LaneMessageVerifier; /// Message delivery payment. type MessageDeliveryAndDispatchPayment: MessageDeliveryAndDispatchPayment< Self::RuntimeOrigin, Self::AccountId, - Self::OutboundMessageFee, >; /// Handler for accepted messages. type OnMessageAccepted: OnMessageAccepted; @@ -198,19 +176,17 @@ pub mod pallet { // Types that are used by inbound_lane (on target chain). /// Source header chain, as it is represented on target chain. - type SourceHeaderChain: SourceHeaderChain; + type SourceHeaderChain: SourceHeaderChain; /// Message dispatch. type MessageDispatch: MessageDispatch< Self::AccountId, - Self::InboundMessageFee, DispatchPayload = Self::InboundPayload, >; } /// Shortcut to messages proof type for Config. - type MessagesProofOf = <>::SourceHeaderChain as SourceHeaderChain< - >::InboundMessageFee, - >>::MessagesProof; + type MessagesProofOf = + <>::SourceHeaderChain as SourceHeaderChain>::MessagesProof; /// Shortcut to messages delivery proof type for Config. type MessagesDeliveryProofOf = <>::TargetHeaderChain as TargetHeaderChain< @@ -253,41 +229,6 @@ pub mod pallet { >::set_operating_mode(origin, operating_mode) } - /// Update pallet parameter. - /// - /// May only be called either by root, or by `PalletOwner`. - /// - /// The weight is: single read for permissions check + 2 writes for parameter value and - /// event. - #[pallet::call_index(2)] - #[pallet::weight((T::DbWeight::get().reads_writes(1, 2), DispatchClass::Operational))] - pub fn update_pallet_parameter( - origin: OriginFor, - parameter: T::Parameter, - ) -> DispatchResult { - Self::ensure_owner_or_root(origin)?; - parameter.save(); - Self::deposit_event(Event::ParameterUpdated { parameter }); - Ok(()) - } - - /// Send message over lane. - #[pallet::call_index(3)] - #[pallet::weight(T::WeightInfo::send_message_weight(payload, T::DbWeight::get()))] - pub fn send_message( - origin: OriginFor, - lane_id: LaneId, - payload: T::OutboundPayload, - delivery_and_dispatch_fee: T::OutboundMessageFee, - ) -> DispatchResultWithPostInfo { - crate::send_message::(origin, lane_id, payload, delivery_and_dispatch_fee).map( - |sent_message| PostDispatchInfo { - actual_weight: Some(sent_message.weight), - pays_fee: Pays::Yes, - }, - ) - } - /// Receive messages proof from bridged chain. /// /// The weight of the call assumes that the transaction always brings outbound lane @@ -334,7 +275,6 @@ pub mod pallet { // verify messages proof && convert proof into messages let messages = verify_and_decode_messages_proof::< T::SourceHeaderChain, - T::InboundMessageFee, T::InboundPayload, >(proof, messages_count) .map_err(|err| { @@ -613,8 +553,6 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event, I: 'static = ()> { - /// Pallet parameter has been updated. - ParameterUpdated { parameter: T::Parameter }, /// Message has been accepted and is waiting to be delivered. MessageAccepted { lane_id: LaneId, nonce: MessageNonce }, /// Messages have been received from the bridged chain. @@ -684,7 +622,7 @@ pub mod pallet { /// All queued outbound messages. #[pallet::storage] pub type OutboundMessages, I: 'static = ()> = - StorageMap<_, Blake2_128Concat, MessageKey, StoredMessageData>; + StorageMap<_, Blake2_128Concat, MessageKey, StoredMessagePayload>; #[pallet::genesis_config] pub struct GenesisConfig, I: 'static = ()> { @@ -719,10 +657,7 @@ pub mod pallet { impl, I: 'static> Pallet { /// Get stored data of the outbound message with given nonce. - pub fn outbound_message_data( - lane: LaneId, - nonce: MessageNonce, - ) -> Option> { + pub fn outbound_message_data(lane: LaneId, nonce: MessageNonce) -> Option { OutboundMessages::::get(MessageKey { lane_id: lane, nonce }) } @@ -730,12 +665,11 @@ pub mod pallet { pub fn inbound_message_data( lane: LaneId, payload: MessagePayload, - outbound_details: OutboundMessageDetails, + outbound_details: OutboundMessageDetails, ) -> InboundMessageDetails { let mut dispatch_message = DispatchMessage { key: MessageKey { lane_id: lane, nonce: outbound_details.nonce }, - data: MessageData { payload, fee: outbound_details.delivery_and_dispatch_fee } - .into(), + data: payload.into(), }; InboundMessageDetails { dispatch_weight: T::MessageDispatch::dispatch_weight(&mut dispatch_message), @@ -755,8 +689,7 @@ pub fn relayer_fund_account_id - bp_messages::source_chain::MessagesBridge +impl bp_messages::source_chain::MessagesBridge for Pallet where T: Config, @@ -768,9 +701,8 @@ where sender: T::RuntimeOrigin, lane: LaneId, message: T::OutboundPayload, - delivery_and_dispatch_fee: T::OutboundMessageFee, ) -> Result { - crate::send_message::(sender, lane, message, delivery_and_dispatch_fee) + crate::send_message::(sender, lane, message) } } @@ -780,8 +712,6 @@ pub struct RuntimeOutboundLaneStorage { _phantom: PhantomData<(T, I)>, } impl, I: 'static> OutboundLaneStorage for RuntimeOutboundLaneStorage { - type MessageFee = T::OutboundMessageFee; - fn id(&self) -> LaneId { self.lane_id } @@ -795,17 +725,20 @@ impl, I: 'static> OutboundLaneStorage for RuntimeOutboundLaneStorag } #[cfg(test)] - fn message(&self, nonce: &MessageNonce) -> Option> { + fn message(&self, nonce: &MessageNonce) -> Option { OutboundMessages::::get(MessageKey { lane_id: self.lane_id, nonce: *nonce }) .map(Into::into) } - fn save_message( - &mut self, - nonce: MessageNonce, - mesage_data: MessageData, - ) { - OutboundMessages::::insert(MessageKey { lane_id: self.lane_id, nonce }, mesage_data); + fn save_message(&mut self, nonce: MessageNonce, message_payload: MessagePayload) { + OutboundMessages::::insert( + MessageKey { lane_id: self.lane_id, nonce }, + StoredMessagePayload::::try_from(message_payload).expect( + "save_message is called after all checks in send_message; \ + send_message checks message size; \ + qed", + ), + ); } fn remove_message(&mut self, nonce: &MessageNonce) { @@ -818,22 +751,14 @@ fn send_message, I: 'static>( submitter: T::RuntimeOrigin, lane_id: LaneId, payload: T::OutboundPayload, - delivery_and_dispatch_fee: T::OutboundMessageFee, ) -> sp_std::result::Result< SendMessageArtifacts, sp_runtime::DispatchErrorWithPostInfo, > { ensure_normal_operating_mode::()?; - // the most lightweigh check is the message size check - ensure!( - payload.size() <= T::MaximalOutboundPayloadSize::get(), - Error::::MessageIsTooLarge, - ); - // initially, actual (post-dispatch) weight is equal to pre-dispatch weight - let mut actual_weight = T::WeightInfo::send_message_weight(&payload, T::DbWeight::get()); - + let mut actual_weight = frame_support::weights::Weight::zero(); // TODO (https://github.com/paritytech/parity-bridges-common/issues/1647): remove this // let's first check if message can be delivered to target chain T::TargetHeaderChain::verify_message(&payload).map_err(|err| { log::trace!( @@ -848,47 +773,27 @@ fn send_message, I: 'static>( // now let's enforce any additional lane rules let mut lane = outbound_lane::(lane_id); - T::LaneMessageVerifier::verify_message( - &submitter, - &delivery_and_dispatch_fee, - &lane_id, - &lane.data(), - &payload, - ) - .map_err(|err| { - log::trace!( - target: LOG_TARGET, - "Message to lane {:?} is rejected by lane verifier: {:?}", - lane_id, - err, - ); - - Error::::MessageRejectedByLaneVerifier - })?; - - // let's withdraw delivery and dispatch fee from submitter - T::MessageDeliveryAndDispatchPayment::pay_delivery_and_dispatch_fee( - &submitter, - &delivery_and_dispatch_fee, - &relayer_fund_account_id::(), - ) - .map_err(|err| { - log::trace!( - target: LOG_TARGET, - "Message to lane {:?} is rejected because submitter is unable to pay fee {:?}: {:?}", - lane_id, - delivery_and_dispatch_fee, - err, - ); - - Error::::FailedToWithdrawMessageFee - })?; + T::LaneMessageVerifier::verify_message(&submitter, &lane_id, &lane.data(), &payload).map_err( + |err| { + log::trace!( + target: LOG_TARGET, + "Message to lane {:?} is rejected by lane verifier: {:?}", + lane_id, + err, + ); + Error::::MessageRejectedByLaneVerifier + }, + )?; // finally, save message in outbound storage and emit event let encoded_payload = payload.encode(); let encoded_payload_len = encoded_payload.len(); - let nonce = - lane.send_message(MessageData { payload: encoded_payload, fee: delivery_and_dispatch_fee }); + ensure!( + encoded_payload_len <= T::MaximalOutboundPayloadSize::get() as usize, + Error::::MessageIsTooLarge + ); + let nonce = lane.send_message(encoded_payload); + // Guaranteed to be called outside only when the message is accepted. // We assume that the maximum weight call back used is `single_message_callback_overhead`, so do // not perform complex db operation in callback. If you want to, put these magic logic in @@ -943,31 +848,26 @@ fn send_message, I: 'static>( Ok(SendMessageArtifacts { nonce, weight: actual_weight }) } -/// Calculate the relayers rewards +/// Calculate the number of messages that the relayers have delivered. pub fn calc_relayers_rewards( - lane_id: LaneId, messages_relayers: VecDeque>, received_range: &RangeInclusive, -) -> RelayersRewards +) -> RelayersRewards where T: frame_system::Config + crate::Config, I: 'static, { // remember to reward relayers that have delivered messages // this loop is bounded by `T::MaxUnrewardedRelayerEntriesAtInboundLane` on the bridged chain - let mut relayers_rewards: RelayersRewards<_, T::OutboundMessageFee> = RelayersRewards::new(); + let mut relayers_rewards = RelayersRewards::new(); for entry in messages_relayers { let nonce_begin = sp_std::cmp::max(entry.messages.begin, *received_range.start()); let nonce_end = sp_std::cmp::min(entry.messages.end, *received_range.end()); // loop won't proceed if current entry is ahead of received range (begin > end). // this loop is bound by `T::MaxUnconfirmedMessagesAtInboundLane` on the bridged chain - let mut relayer_reward = relayers_rewards.entry(entry.relayer).or_default(); - for nonce in nonce_begin..=nonce_end { - let message_data = OutboundMessages::::get(MessageKey { lane_id, nonce }) - .expect("message was just confirmed; we never prune unconfirmed messages; qed"); - relayer_reward.reward = relayer_reward.reward.saturating_add(&message_data.fee); - relayer_reward.messages += 1; + if nonce_end >= nonce_begin { + *relayers_rewards.entry(entry.relayer).or_default() += nonce_end - nonce_begin + 1; } } relayers_rewards @@ -1016,7 +916,6 @@ struct RuntimeInboundLaneStorage, I: 'static = ()> { _phantom: PhantomData, } impl, I: 'static> InboundLaneStorage for RuntimeInboundLaneStorage { - type MessageFee = T::InboundMessageFee; type Relayer = T::InboundRelayer; fn id(&self) -> LaneId { @@ -1056,10 +955,10 @@ impl, I: 'static> InboundLaneStorage for RuntimeInboundLaneStorage< } /// Verify messages proof and return proved messages with decoded payload. -fn verify_and_decode_messages_proof, Fee, DispatchPayload: Decode>( +fn verify_and_decode_messages_proof( proof: Chain::MessagesProof, messages_count: u32, -) -> Result>, Chain::Error> { +) -> Result>, Chain::Error> { // `receive_messages_proof` weight formula and `MaxUnconfirmedMessagesAtInboundLane` check // guarantees that the `message_count` is sane and Vec may be allocated. // (tx with too many messages will either be rejected from the pool, or will fail earlier) @@ -1084,12 +983,12 @@ mod tests { // darwinia-network use super::*; use crate::mock::{ - message, message_payload, run_test, unrewarded_relayer, Balance, RuntimeEvent as TestEvent, + message, message_payload, run_test, unrewarded_relayer, RuntimeEvent as TestEvent, RuntimeOrigin, TestMessageDeliveryAndDispatchPayment, TestMessagesDeliveryProof, - TestMessagesParameter, TestMessagesProof, TestOnDeliveryConfirmed1, - TestOnDeliveryConfirmed2, TestOnMessageAccepted, TestRuntime, TokenConversionRate, - MAX_OUTBOUND_PAYLOAD_SIZE, PAYLOAD_REJECTED_BY_TARGET_CHAIN, REGULAR_PAYLOAD, TEST_LANE_ID, - TEST_RELAYER_A, TEST_RELAYER_B, + TestMessagesProof, TestOnDeliveryConfirmed1, TestOnDeliveryConfirmed2, + TestOnMessageAccepted, TestRuntime, MAX_OUTBOUND_PAYLOAD_SIZE, + PAYLOAD_REJECTED_BY_TARGET_CHAIN, REGULAR_PAYLOAD, TEST_LANE_ID, TEST_RELAYER_A, + TEST_RELAYER_B, }; use bp_messages::{UnrewardedRelayer, UnrewardedRelayersState}; use bp_test_utils::generate_owned_bridge_module_tests; @@ -1129,15 +1028,13 @@ mod tests { let message_nonce = outbound_lane::(TEST_LANE_ID).data().latest_generated_nonce + 1; - let weight = Pallet::::send_message( + let weight = send_message::( RuntimeOrigin::signed(1), TEST_LANE_ID, REGULAR_PAYLOAD, - REGULAR_PAYLOAD.declared_weight.ref_time(), ) .expect("send_message has failed") - .actual_weight - .expect("send_message always returns Some"); + .weight; // check event with assigned nonce assert_eq!( @@ -1152,12 +1049,6 @@ mod tests { }], ); - // check that fee has been withdrawn from submitter - assert!(TestMessageDeliveryAndDispatchPayment::is_fee_paid( - 1, - REGULAR_PAYLOAD.declared_weight.ref_time() - )); - weight } @@ -1200,102 +1091,6 @@ mod tests { ); } - #[test] - fn pallet_parameter_may_be_updated_by_root() { - run_test(|| { - get_ready_for_events(); - - let parameter = TestMessagesParameter::TokenConversionRate(10.into()); - assert_ok!(Pallet::::update_pallet_parameter( - RuntimeOrigin::root(), - parameter.clone(), - )); - - assert_eq!(TokenConversionRate::get(), 10.into()); - assert_eq!( - System::::events(), - vec![EventRecord { - phase: Phase::Initialization, - event: TestEvent::Messages(Event::ParameterUpdated { parameter }), - topics: vec![], - }], - ); - }); - } - - #[test] - fn pallet_parameter_may_be_updated_by_owner() { - run_test(|| { - PalletOwner::::put(2); - get_ready_for_events(); - - let parameter = TestMessagesParameter::TokenConversionRate(10.into()); - assert_ok!(Pallet::::update_pallet_parameter( - RuntimeOrigin::signed(2), - parameter.clone(), - )); - - assert_eq!(TokenConversionRate::get(), 10.into()); - assert_eq!( - System::::events(), - vec![EventRecord { - phase: Phase::Initialization, - event: TestEvent::Messages(Event::ParameterUpdated { parameter }), - topics: vec![], - }], - ); - }); - } - - #[test] - fn pallet_parameter_cant_be_updated_by_arbitrary_submitter() { - run_test(|| { - assert_noop!( - Pallet::::update_pallet_parameter( - RuntimeOrigin::signed(2), - TestMessagesParameter::TokenConversionRate(10.into()), - ), - DispatchError::BadOrigin, - ); - - PalletOwner::::put(2); - - assert_noop!( - Pallet::::update_pallet_parameter( - RuntimeOrigin::signed(1), - TestMessagesParameter::TokenConversionRate(10.into()), - ), - DispatchError::BadOrigin, - ); - }); - } - - #[test] - fn fixed_u128_works_as_i_think() { - // this test is here just to be sure that conversion rate may be represented with FixedU128 - run_test(|| { - use sp_runtime::{FixedPointNumber, FixedU128}; - - // 1:1 conversion that we use by default for testnets - let rialto_token = 1u64; - let rialto_token_in_millau_tokens = - TokenConversionRate::get().saturating_mul_int(rialto_token); - assert_eq!(rialto_token_in_millau_tokens, 1); - - // let's say conversion rate is 1:1.7 - let conversion_rate = FixedU128::saturating_from_rational(170, 100); - let rialto_tokens = 100u64; - let rialto_tokens_in_millau_tokens = conversion_rate.saturating_mul_int(rialto_tokens); - assert_eq!(rialto_tokens_in_millau_tokens, 170); - - // let's say conversion rate is 1:0.25 - let conversion_rate = FixedU128::saturating_from_rational(25, 100); - let rialto_tokens = 100u64; - let rialto_tokens_in_millau_tokens = conversion_rate.saturating_mul_int(rialto_tokens); - assert_eq!(rialto_tokens_in_millau_tokens, 25); - }); - } - #[test] fn pallet_rejects_transactions_if_halted() { run_test(|| { @@ -1307,26 +1102,14 @@ mod tests { )); assert_noop!( - Pallet::::send_message( + send_message::( RuntimeOrigin::signed(1), TEST_LANE_ID, REGULAR_PAYLOAD, - REGULAR_PAYLOAD.declared_weight.ref_time(), ), Error::::NotOperatingNormally, ); - assert_noop!( - Pallet::::receive_messages_proof( - RuntimeOrigin::signed(1), - TEST_RELAYER_A, - Ok(vec![message(2, REGULAR_PAYLOAD)]).into(), - 1, - REGULAR_PAYLOAD.declared_weight - ), - Error::::BridgeModule(bp_runtime::OwnedBridgeModuleError::Halted), - ); - assert_noop!( Pallet::::receive_messages_delivery_proof( RuntimeOrigin::signed(1), @@ -1362,23 +1145,14 @@ mod tests { ); assert_noop!( - Pallet::::send_message( + send_message::( RuntimeOrigin::signed(1), TEST_LANE_ID, REGULAR_PAYLOAD, - REGULAR_PAYLOAD.declared_weight.ref_time(), ), Error::::NotOperatingNormally, ); - assert_ok!(Pallet::::receive_messages_proof( - RuntimeOrigin::signed(1), - TEST_RELAYER_A, - Ok(vec![message(1, REGULAR_PAYLOAD)]).into(), - 1, - REGULAR_PAYLOAD.declared_weight - ),); - assert_ok!(Pallet::::receive_messages_delivery_proof( RuntimeOrigin::signed(1), TestMessagesDeliveryProof(Ok(( @@ -1415,25 +1189,23 @@ mod tests { // `MAX_OUTBOUND_PAYLOAD_SIZE` if we add `MAX_OUTBOUND_PAYLOAD_SIZE` bytes to extra message_payload.extra.extend_from_slice(&[0u8; MAX_OUTBOUND_PAYLOAD_SIZE as usize]); assert_noop!( - Pallet::::send_message( + send_message::( RuntimeOrigin::signed(1), TEST_LANE_ID, message_payload.clone(), - Balance::MAX, ), Error::::MessageIsTooLarge, ); // let's check that we're able to send `MAX_OUTBOUND_PAYLOAD_SIZE` messages - while message_payload.size() > MAX_OUTBOUND_PAYLOAD_SIZE { + while message_payload.encoded_size() as u32 > MAX_OUTBOUND_PAYLOAD_SIZE { message_payload.extra.pop(); } - assert_eq!(message_payload.size(), MAX_OUTBOUND_PAYLOAD_SIZE); - assert_ok!(Pallet::::send_message( + assert_eq!(message_payload.encoded_size() as u32, MAX_OUTBOUND_PAYLOAD_SIZE); + assert_ok!(send_message::( RuntimeOrigin::signed(1), TEST_LANE_ID, message_payload, - Balance::MAX, ),); }) } @@ -1443,11 +1215,10 @@ mod tests { run_test(|| { // messages with this payload are rejected by target chain verifier assert_noop!( - Pallet::::send_message( + send_message::( RuntimeOrigin::signed(1), TEST_LANE_ID, PAYLOAD_REJECTED_BY_TARGET_CHAIN, - PAYLOAD_REJECTED_BY_TARGET_CHAIN.declared_weight.ref_time() ), Error::::MessageRejectedByChainVerifier, ); @@ -1458,34 +1229,15 @@ mod tests { fn lane_verifier_rejects_invalid_message_in_send_message() { run_test(|| { // messages with zero fee are rejected by lane verifier + let mut message = REGULAR_PAYLOAD; + message.reject_by_lane_verifier = true; assert_noop!( - Pallet::::send_message( - RuntimeOrigin::signed(1), - TEST_LANE_ID, - REGULAR_PAYLOAD, - 0 - ), + send_message::(RuntimeOrigin::signed(1), TEST_LANE_ID, message,), Error::::MessageRejectedByLaneVerifier, ); }); } - #[test] - fn message_send_fails_if_submitter_cant_pay_message_fee() { - run_test(|| { - TestMessageDeliveryAndDispatchPayment::reject_payments(); - assert_noop!( - Pallet::::send_message( - RuntimeOrigin::signed(1), - TEST_LANE_ID, - REGULAR_PAYLOAD, - REGULAR_PAYLOAD.declared_weight.ref_time() - ), - Error::::FailedToWithdrawMessageFee, - ); - }); - } - #[test] fn receive_messages_proof_works() { run_test(|| { @@ -1629,17 +1381,15 @@ mod tests { #[test] fn receive_messages_delivery_proof_rewards_relayers() { run_test(|| { - assert_ok!(Pallet::::send_message( + assert_ok!(send_message::( RuntimeOrigin::signed(1), TEST_LANE_ID, REGULAR_PAYLOAD, - 1000, )); - assert_ok!(Pallet::::send_message( + assert_ok!(send_message::( RuntimeOrigin::signed(1), TEST_LANE_ID, REGULAR_PAYLOAD, - 2000, )); // this reports delivery of message 1 => reward is paid to TEST_RELAYER_A @@ -1661,8 +1411,8 @@ mod tests { ..Default::default() }, )); - assert!(TestMessageDeliveryAndDispatchPayment::is_reward_paid(TEST_RELAYER_A, 1000)); - assert!(!TestMessageDeliveryAndDispatchPayment::is_reward_paid(TEST_RELAYER_B, 2000)); + assert!(TestMessageDeliveryAndDispatchPayment::is_reward_paid(TEST_RELAYER_A, 1)); + assert!(!TestMessageDeliveryAndDispatchPayment::is_reward_paid(TEST_RELAYER_B, 1)); // this reports delivery of both message 1 and message 2 => reward is paid only to // TEST_RELAYER_B @@ -1687,8 +1437,8 @@ mod tests { ..Default::default() }, )); - assert!(!TestMessageDeliveryAndDispatchPayment::is_reward_paid(TEST_RELAYER_A, 1000)); - assert!(TestMessageDeliveryAndDispatchPayment::is_reward_paid(TEST_RELAYER_B, 2000)); + assert!(!TestMessageDeliveryAndDispatchPayment::is_reward_paid(TEST_RELAYER_A, 1)); + assert!(TestMessageDeliveryAndDispatchPayment::is_reward_paid(TEST_RELAYER_B, 1)); }); } @@ -1793,7 +1543,7 @@ mod tests { fn receive_messages_accepts_single_message_with_invalid_payload() { run_test(|| { let mut invalid_message = message(1, REGULAR_PAYLOAD); - invalid_message.data.payload = Vec::new(); + invalid_message.payload = Vec::new(); assert_ok!(Pallet::::receive_messages_proof( RuntimeOrigin::signed(1), @@ -1812,7 +1562,7 @@ mod tests { fn receive_messages_accepts_batch_with_message_with_invalid_payload() { run_test(|| { let mut invalid_message = message(2, REGULAR_PAYLOAD); - invalid_message.data.payload = Vec::new(); + invalid_message.payload = Vec::new(); assert_ok!(Pallet::::receive_messages_proof( RuntimeOrigin::signed(1), @@ -2084,51 +1834,6 @@ mod tests { }); } - #[test] - fn weight_is_refunded_for_messages_that_are_not_pruned() { - run_test(|| { - // send first MAX messages - no messages are pruned - let max_messages_to_prune = crate::mock::MaxMessagesToPruneAtOnce::get(); - let when_zero_messages_are_pruned = send_regular_message(); - let mut delivered_messages = DeliveredMessages::new(1, true); - for _ in 1..max_messages_to_prune { - assert_eq!(send_regular_message(), when_zero_messages_are_pruned); - delivered_messages.note_dispatched_message(true); - } - - // confirm delivery of all sent messages - assert_ok!(Pallet::::receive_messages_delivery_proof( - RuntimeOrigin::signed(1), - TestMessagesDeliveryProof(Ok(( - TEST_LANE_ID, - InboundLaneData { - last_confirmed_nonce: 1, - relayers: vec![UnrewardedRelayer { - relayer: 0, - messages: delivered_messages, - }] - .into_iter() - .collect(), - }, - ))), - UnrewardedRelayersState { - unrewarded_relayer_entries: 1, - total_messages: max_messages_to_prune, - last_delivered_nonce: max_messages_to_prune, - ..Default::default() - }, - )); - - // when next message is sent, MAX messages are pruned - let weight_when_max_messages_are_pruned = send_regular_message(); - assert_eq!( - weight_when_max_messages_are_pruned, - when_zero_messages_are_pruned - + crate::mock::DbWeight::get().writes(max_messages_to_prune), - ); - }); - } - #[test] fn message_accepted_callbacks_are_called() { run_test(|| { @@ -2149,27 +1854,6 @@ mod tests { }); } - #[test] - fn message_accepted_refunds_non_zero_weight() { - run_test(|| { - TestOnMessageAccepted::set_consumed_weight_per_message( - crate::mock::DbWeight::get().writes(1), - ); - let actual_callback_weight = send_regular_message(); - let pre_dispatch_weight = ::WeightInfo::send_message_weight( - ®ULAR_PAYLOAD, - crate::mock::DbWeight::get(), - ); - let prune_weight = crate::mock::DbWeight::get() - .writes(::MaxMessagesToPruneAtOnce::get()); - - assert_eq!( - pre_dispatch_weight.saturating_sub(actual_callback_weight), - crate::mock::DbWeight::get().reads(1).saturating_add(prune_weight) - ); - }); - } - #[test] fn storage_keys_computed_properly() { assert_eq!( @@ -2207,9 +1891,6 @@ mod tests { nonce: 0, dispatch_weight: 0, size: 0, - delivery_and_dispatch_fee: 0, - dispatch_fee_payment: - bp_runtime::messages::DispatchFeePayment::AtTargetChain, }, ), InboundMessageDetails { dispatch_weight: REGULAR_PAYLOAD.declared_weight }, diff --git a/modules/messages/src/mock.rs b/modules/messages/src/mock.rs index 7fe5e7be..9aa25cb6 100644 --- a/modules/messages/src/mock.rs +++ b/modules/messages/src/mock.rs @@ -35,10 +35,11 @@ use bp_messages::{ OnMessageAccepted, TargetHeaderChain, }, target_chain::{ - DispatchMessage, MessageDispatch, ProvedLaneMessages, ProvedMessages, SourceHeaderChain, + DispatchMessage, DispatchMessageData, MessageDispatch, ProvedLaneMessages, ProvedMessages, + SourceHeaderChain, }, - DeliveredMessages, InboundLaneData, LaneId, Message, MessageData, MessageKey, MessageNonce, - OutboundLaneData, Parameter as MessagesParameter, UnrewardedRelayer, + DeliveredMessages, InboundLaneData, LaneId, Message, MessageKey, MessageNonce, MessagePayload, + OutboundLaneData, UnrewardedRelayer, }; use bp_runtime::{messages::MessageDispatchResult, Size}; // paritytech @@ -51,7 +52,7 @@ use sp_core::{ConstU64, H256}; use sp_runtime::{ testing::Header as SubstrateHeader, traits::{BlakeTwo256, IdentityLookup}, - FixedU128, Perbill, + Perbill, }; pub type AccountId = u64; @@ -64,7 +65,7 @@ type Block = MockBlock; type UncheckedExtrinsic = MockUncheckedExtrinsic; /// Vec of proved messages, grouped by lane. -pub type MessagesByLaneVec = Vec<(LaneId, ProvedLaneMessages>)>; +pub type MessagesByLaneVec = Vec<(LaneId, ProvedLaneMessages)>; /// Maximal outbound payload size. pub const MAX_OUTBOUND_PAYLOAD_SIZE: u32 = 4096; @@ -97,6 +98,8 @@ pub const PAYLOAD_REJECTED_BY_TARGET_CHAIN: TestPayload = message_payload(1, 50) pub struct TestPayload { /// Field that may be used to identify messages. pub id: u64, + /// Reject this message by lane verifier? + pub reject_by_lane_verifier: bool, /// Dispatch weight that is declared by the message sender. pub declared_weight: Weight, /// Message dispatch result. @@ -172,29 +175,15 @@ impl pallet_balances::Config for TestRuntime { type WeightInfo = (); } -#[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), - } - } -} 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"; } impl Config for TestRuntime { type AccountIdConverter = AccountIdConverter; type BridgedChainId = TestBridgedChainId; - type InboundMessageFee = TestMessageFee; type InboundPayload = TestPayload; type InboundRelayer = TestRelayer; type LaneMessageVerifier = TestLaneMessageVerifier; @@ -206,9 +195,7 @@ impl Config for TestRuntime { type MessageDispatch = TestMessageDispatch; type OnDeliveryConfirmed = (TestOnDeliveryConfirmed1, TestOnDeliveryConfirmed2); type OnMessageAccepted = TestOnMessageAccepted; - type OutboundMessageFee = TestMessageFee; type OutboundPayload = TestPayload; - type Parameter = TestMessagesParameter; type RuntimeEvent = RuntimeEvent; type SourceHeaderChain = TestSourceHeaderChain; type TargetHeaderChain = TestTargetHeaderChain; @@ -231,14 +218,12 @@ impl Size for TestMessagesProof { 0 } } -impl From>, ()>> for TestMessagesProof { - fn from(result: Result>, ()>) -> Self { +impl From, ()>> for TestMessagesProof { + fn from(result: Result, ()>) -> Self { Self { result: result.map(|messages| { - let mut messages_by_lane: BTreeMap< - LaneId, - ProvedLaneMessages>, - > = BTreeMap::new(); + let mut messages_by_lane: BTreeMap> = + BTreeMap::new(); for message in messages { messages_by_lane.entry(message.key.lane_id).or_default().messages.push(message); } @@ -282,17 +267,16 @@ impl TargetHeaderChain for TestTargetHeaderChain { /// Lane message verifier that is used in tests. #[derive(Debug, Default)] pub struct TestLaneMessageVerifier; -impl LaneMessageVerifier for TestLaneMessageVerifier { +impl LaneMessageVerifier for TestLaneMessageVerifier { type Error = &'static str; fn verify_message( _submitter: &RuntimeOrigin, - delivery_and_dispatch_fee: &TestMessageFee, _lane: &LaneId, _lane_outbound_data: &OutboundLaneData, - _payload: &TestPayload, + payload: &TestPayload, ) -> Result<(), Self::Error> { - if *delivery_and_dispatch_fee != 0 { + if !payload.reject_by_lane_verifier { Ok(()) } else { Err(TEST_ERROR) @@ -304,18 +288,6 @@ impl LaneMessageVerifier for TestLan #[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, _> = - RuntimeOrigin::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 { @@ -323,27 +295,13 @@ impl TestMessageDeliveryAndDispatchPayment { frame_support::storage::unhashed::take::(&key).is_some() } } -impl MessageDeliveryAndDispatchPayment +impl MessageDeliveryAndDispatchPayment for TestMessageDeliveryAndDispatchPayment { type Error = &'static str; - fn pay_delivery_and_dispatch_fee( - submitter: &RuntimeOrigin, - 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, _> = submitter.clone().into(); - frame_support::storage::unhashed::put(b":message-fee:", &(raw_origin.unwrap(), fee)); - Ok(()) - } - fn pay_relayers_rewards( - lane_id: LaneId, + _lane_id: LaneId, message_relayers: VecDeque>, _confirmation_relayer: &AccountId, received_range: &RangeInclusive, @@ -362,9 +320,9 @@ impl MessageDeliveryAndDispatchPayment } let relayers_rewards = - calc_relayers_rewards::(lane_id, message_relayers, received_range); + calc_relayers_rewards::(message_relayers, received_range); for (relayer, reward) in &relayers_rewards { - let key = (b":relayer-reward:", relayer, reward.reward).encode(); + let key = (b":relayer-reward:", relayer, reward).encode(); frame_support::storage::unhashed::put(&key, &true); } } @@ -449,14 +407,14 @@ impl OnDeliveryConfirmed for TestOnDeliveryConfirmed2 { /// Source header chain that is used in tests. #[derive(Debug)] pub struct TestSourceHeaderChain; -impl SourceHeaderChain for TestSourceHeaderChain { +impl SourceHeaderChain for TestSourceHeaderChain { type Error = &'static str; type MessagesProof = TestMessagesProof; fn verify_messages_proof( proof: Self::MessagesProof, _messages_count: u32, - ) -> Result>, Self::Error> { + ) -> Result, Self::Error> { proof.result.map(|proof| proof.into_iter().collect()).map_err(|_| TEST_ERROR) } } @@ -464,10 +422,10 @@ impl SourceHeaderChain for TestSourceHeaderChain { /// Source header chain that is used in tests. #[derive(Debug)] pub struct TestMessageDispatch; -impl MessageDispatch for TestMessageDispatch { +impl MessageDispatch for TestMessageDispatch { type DispatchPayload = TestPayload; - fn dispatch_weight(message: &mut DispatchMessage) -> Weight { + fn dispatch_weight(message: &mut DispatchMessage) -> Weight { match message.data.payload.as_ref() { Ok(payload) => payload.declared_weight, Err(_) => Weight::zero(), @@ -483,7 +441,7 @@ impl MessageDispatch for TestMessageDispatch { fn dispatch( _relayer_account: &AccountId, - message: DispatchMessage, + message: DispatchMessage, ) -> MessageDispatchResult { match message.data.payload.as_ref() { Ok(payload) => payload.dispatch_result.clone(), @@ -493,25 +451,31 @@ impl MessageDispatch for TestMessageDispatch { } /// Return test lane message with given nonce and payload. -pub fn message(nonce: MessageNonce, payload: TestPayload) -> Message { - Message { key: MessageKey { lane_id: TEST_LANE_ID, nonce }, data: message_data(payload) } +pub fn message(nonce: MessageNonce, payload: TestPayload) -> Message { + Message { key: MessageKey { lane_id: TEST_LANE_ID, nonce }, payload: payload.encode() } +} + +/// Return valid outbound message data, constructed from given payload. +pub fn outbound_message_data(payload: TestPayload) -> MessagePayload { + payload.encode() +} + +/// Return valid inbound (dispatch) message data, constructed from given payload. +pub fn inbound_message_data(payload: TestPayload) -> DispatchMessageData { + DispatchMessageData { payload: Ok(payload) } } /// Constructs message payload using given arguments and zero unspent weight. pub const fn message_payload(id: u64, declared_weight: u64) -> TestPayload { TestPayload { id, + reject_by_lane_verifier: false, declared_weight: Weight::from_ref_time(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 { - MessageData { payload: payload.encode(), fee: 1 } -} - /// Returns message dispatch result with given unspent weight. pub const fn dispatch_result(unspent_weight: u64) -> MessageDispatchResult { MessageDispatchResult { diff --git a/modules/messages/src/outbound_lane.rs b/modules/messages/src/outbound_lane.rs index 88846c80..59c7b034 100644 --- a/modules/messages/src/outbound_lane.rs +++ b/modules/messages/src/outbound_lane.rs @@ -18,23 +18,18 @@ // crates.io use bitvec::prelude::*; -use codec::{Decode, Encode, EncodeLike, MaxEncodedLen}; -use scale_info::{Type, TypeInfo}; // darwinia-network use crate::Config; use bp_messages::{ - DeliveredMessages, DispatchResultsBitVec, LaneId, MessageData, MessageNonce, OutboundLaneData, - UnrewardedRelayer, + DeliveredMessages, DispatchResultsBitVec, LaneId, MessageNonce, MessagePayload, + OutboundLaneData, UnrewardedRelayer, }; // paritytech -use frame_support::{traits::Get, RuntimeDebug}; +use frame_support::{BoundedVec, RuntimeDebug}; use sp_std::collections::vec_deque::VecDeque; /// Outbound lane storage. pub trait OutboundLaneStorage { - /// Delivery and dispatch fee type on source chain. - type MessageFee; - /// Lane id. fn id(&self) -> LaneId; /// Get lane data from the storage. @@ -43,58 +38,15 @@ pub trait OutboundLaneStorage { fn set_data(&mut self, data: OutboundLaneData); /// Returns saved outbound message payload. #[cfg(test)] - fn message(&self, nonce: &MessageNonce) -> Option>; + fn message(&self, nonce: &MessageNonce) -> Option; /// Save outbound message in the storage. - fn save_message(&mut self, nonce: MessageNonce, message_data: MessageData); + fn save_message(&mut self, nonce: MessageNonce, message_payload: MessagePayload); /// Remove outbound message from the storage. fn remove_message(&mut self, nonce: &MessageNonce); } /// Outbound message data wrapper that implements `MaxEncodedLen`. -/// -/// We have already had `MaxEncodedLen`-like functionality before, but its usage has -/// been localized and we haven't been passing it everywhere. This wrapper allows us -/// to avoid passing these generic bounds all over the code. -/// -/// The encoding of this type matches encoding of the corresponding `MessageData`. -#[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq)] -pub struct StoredMessageData, I: 'static>(pub MessageData); -impl, I: 'static> sp_std::ops::Deref for StoredMessageData { - type Target = MessageData; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} -impl, I: 'static> sp_std::ops::DerefMut for StoredMessageData { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 - } -} -impl, I: 'static> From> - for MessageData -{ - fn from(data: StoredMessageData) -> Self { - data.0 - } -} -impl, I: 'static> TypeInfo for StoredMessageData { - type Identity = Self; - - fn type_info() -> Type { - MessageData::::type_info() - } -} -impl, I: 'static> EncodeLike> - for MessageData -{ -} -impl, I: 'static> MaxEncodedLen for StoredMessageData { - fn max_encoded_len() -> usize { - T::OutboundMessageFee::max_encoded_len() - .saturating_add(T::MaximalOutboundPayloadSize::get() as usize) - } -} +pub type StoredMessagePayload = BoundedVec>::MaximalOutboundPayloadSize>; /// Result of messages receival confirmation. #[derive(RuntimeDebug, PartialEq, Eq)] @@ -138,12 +90,12 @@ impl OutboundLane { /// Send message over lane. /// /// Returns new message nonce. - pub fn send_message(&mut self, message_data: MessageData) -> MessageNonce { + pub fn send_message(&mut self, message_payload: MessagePayload) -> MessageNonce { let mut data = self.storage.data(); let nonce = data.latest_generated_nonce + 1; data.latest_generated_nonce = nonce; - self.storage.save_message(nonce, message_data); + self.storage.save_message(nonce, message_payload); self.storage.set_data(data); nonce @@ -290,8 +242,8 @@ mod tests { use super::*; use crate::{ mock::{ - message_data, run_test, unrewarded_relayer, TestRelayer, TestRuntime, REGULAR_PAYLOAD, - TEST_LANE_ID, + outbound_message_data, run_test, unrewarded_relayer, TestRelayer, TestRuntime, + REGULAR_PAYLOAD, TEST_LANE_ID, }, outbound_lane, }; @@ -317,9 +269,9 @@ mod tests { ) -> ReceivalConfirmationResult { run_test(|| { let mut lane = outbound_lane::(TEST_LANE_ID); - lane.send_message(message_data(REGULAR_PAYLOAD)); - lane.send_message(message_data(REGULAR_PAYLOAD)); - lane.send_message(message_data(REGULAR_PAYLOAD)); + lane.send_message(outbound_message_data(REGULAR_PAYLOAD)); + lane.send_message(outbound_message_data(REGULAR_PAYLOAD)); + lane.send_message(outbound_message_data(REGULAR_PAYLOAD)); assert_eq!(lane.storage.data().latest_generated_nonce, 3); assert_eq!(lane.storage.data().latest_received_nonce, 0); let result = lane.confirm_delivery(3, latest_received_nonce, relayers); @@ -334,7 +286,7 @@ mod tests { run_test(|| { let mut lane = outbound_lane::(TEST_LANE_ID); assert_eq!(lane.storage.data().latest_generated_nonce, 0); - assert_eq!(lane.send_message(message_data(REGULAR_PAYLOAD)), 1); + assert_eq!(lane.send_message(outbound_message_data(REGULAR_PAYLOAD)), 1); assert!(lane.storage.message(&1).is_some()); assert_eq!(lane.storage.data().latest_generated_nonce, 1); }); @@ -344,9 +296,9 @@ mod tests { fn confirm_delivery_works() { run_test(|| { let mut lane = outbound_lane::(TEST_LANE_ID); - assert_eq!(lane.send_message(message_data(REGULAR_PAYLOAD)), 1); - assert_eq!(lane.send_message(message_data(REGULAR_PAYLOAD)), 2); - assert_eq!(lane.send_message(message_data(REGULAR_PAYLOAD)), 3); + assert_eq!(lane.send_message(outbound_message_data(REGULAR_PAYLOAD)), 1); + assert_eq!(lane.send_message(outbound_message_data(REGULAR_PAYLOAD)), 2); + assert_eq!(lane.send_message(outbound_message_data(REGULAR_PAYLOAD)), 3); assert_eq!(lane.storage.data().latest_generated_nonce, 3); assert_eq!(lane.storage.data().latest_received_nonce, 0); assert_eq!( @@ -362,9 +314,9 @@ mod tests { fn confirm_delivery_rejects_nonce_lesser_than_latest_received() { run_test(|| { let mut lane = outbound_lane::(TEST_LANE_ID); - lane.send_message(message_data(REGULAR_PAYLOAD)); - lane.send_message(message_data(REGULAR_PAYLOAD)); - lane.send_message(message_data(REGULAR_PAYLOAD)); + lane.send_message(outbound_message_data(REGULAR_PAYLOAD)); + lane.send_message(outbound_message_data(REGULAR_PAYLOAD)); + lane.send_message(outbound_message_data(REGULAR_PAYLOAD)); assert_eq!(lane.storage.data().latest_generated_nonce, 3); assert_eq!(lane.storage.data().latest_received_nonce, 0); assert_eq!( @@ -463,9 +415,9 @@ mod tests { assert_eq!(lane.prune_messages(100), 0); assert_eq!(lane.storage.data().oldest_unpruned_nonce, 1); // when nothing is confirmed, nothing is pruned - lane.send_message(message_data(REGULAR_PAYLOAD)); - lane.send_message(message_data(REGULAR_PAYLOAD)); - lane.send_message(message_data(REGULAR_PAYLOAD)); + lane.send_message(outbound_message_data(REGULAR_PAYLOAD)); + lane.send_message(outbound_message_data(REGULAR_PAYLOAD)); + lane.send_message(outbound_message_data(REGULAR_PAYLOAD)); assert_eq!(lane.prune_messages(100), 0); assert_eq!(lane.storage.data().oldest_unpruned_nonce, 1); // after confirmation, some messages are received @@ -489,9 +441,9 @@ mod tests { fn confirm_delivery_detects_when_more_than_expected_messages_are_confirmed() { run_test(|| { let mut lane = outbound_lane::(TEST_LANE_ID); - lane.send_message(message_data(REGULAR_PAYLOAD)); - lane.send_message(message_data(REGULAR_PAYLOAD)); - lane.send_message(message_data(REGULAR_PAYLOAD)); + lane.send_message(outbound_message_data(REGULAR_PAYLOAD)); + lane.send_message(outbound_message_data(REGULAR_PAYLOAD)); + lane.send_message(outbound_message_data(REGULAR_PAYLOAD)); assert_eq!( lane.confirm_delivery(0, 3, &unrewarded_relayers(1..=3)), ReceivalConfirmationResult::TryingToConfirmMoreMessagesThanExpected(3), diff --git a/modules/messages/src/weights.rs b/modules/messages/src/weights.rs index a7c416ab..c96cd9b5 100644 --- a/modules/messages/src/weights.rs +++ b/modules/messages/src/weights.rs @@ -48,10 +48,6 @@ use sp_std::marker::PhantomData; /// Weight functions needed for `pallet_bridge_messages`. pub trait WeightInfo { - fn send_minimal_message_worst_case() -> Weight; - fn send_1_kb_message_worst_case() -> Weight; - fn send_16_kb_message_worst_case() -> Weight; - fn maximal_increase_message_fee() -> Weight; fn receive_single_message_proof() -> Weight; fn receive_two_messages_proof() -> Weight; fn receive_single_message_proof_with_outbound_lane_state() -> Weight; @@ -66,30 +62,6 @@ pub trait WeightInfo { /// Weights for `pallet_bridge_messages` using the Millau node and recommended hardware. pub struct BridgeWeight(PhantomData); impl WeightInfo for BridgeWeight { - fn send_minimal_message_worst_case() -> Weight { - Weight::from_ref_time(117_480_000 as u64) - .saturating_add(T::DbWeight::get().reads(7 as u64)) - .saturating_add(T::DbWeight::get().writes(12 as u64)) - } - - fn send_1_kb_message_worst_case() -> Weight { - Weight::from_ref_time(128_391_000 as u64) - .saturating_add(T::DbWeight::get().reads(7 as u64)) - .saturating_add(T::DbWeight::get().writes(12 as u64)) - } - - fn send_16_kb_message_worst_case() -> Weight { - Weight::from_ref_time(149_149_000 as u64) - .saturating_add(T::DbWeight::get().reads(7 as u64)) - .saturating_add(T::DbWeight::get().writes(12 as u64)) - } - - fn maximal_increase_message_fee() -> Weight { - Weight::from_ref_time(6_015_058_000 as u64) - .saturating_add(T::DbWeight::get().reads(5 as u64)) - .saturating_add(T::DbWeight::get().writes(3 as u64)) - } - fn receive_single_message_proof() -> Weight { Weight::from_ref_time(179_892_000 as u64) .saturating_add(T::DbWeight::get().reads(6 as u64)) @@ -147,30 +119,6 @@ impl WeightInfo for BridgeWeight { // For backwards compatibility and tests impl WeightInfo for () { - fn send_minimal_message_worst_case() -> Weight { - Weight::from_ref_time(117_480_000 as u64) - .saturating_add(RocksDbWeight::get().reads(7 as u64)) - .saturating_add(RocksDbWeight::get().writes(12 as u64)) - } - - fn send_1_kb_message_worst_case() -> Weight { - Weight::from_ref_time(128_391_000 as u64) - .saturating_add(RocksDbWeight::get().reads(7 as u64)) - .saturating_add(RocksDbWeight::get().writes(12 as u64)) - } - - fn send_16_kb_message_worst_case() -> Weight { - Weight::from_ref_time(149_149_000 as u64) - .saturating_add(RocksDbWeight::get().reads(7 as u64)) - .saturating_add(RocksDbWeight::get().writes(12 as u64)) - } - - fn maximal_increase_message_fee() -> Weight { - Weight::from_ref_time(6_015_058_000 as u64) - .saturating_add(RocksDbWeight::get().reads(5 as u64)) - .saturating_add(RocksDbWeight::get().writes(3 as u64)) - } - fn receive_single_message_proof() -> Weight { Weight::from_ref_time(179_892_000 as u64) .saturating_add(RocksDbWeight::get().reads(6 as u64)) diff --git a/modules/messages/src/weights_ext.rs b/modules/messages/src/weights_ext.rs index 9e940446..869854ce 100644 --- a/modules/messages/src/weights_ext.rs +++ b/modules/messages/src/weights_ext.rs @@ -36,82 +36,16 @@ const SIGNED_EXTENSIONS_SIZE: u32 = 1024; pub const EXTRA_STORAGE_PROOF_SIZE: u32 = 1024; /// Ensure that weights from `WeightInfoExt` implementation are looking correct. -pub fn ensure_weights_are_correct( - expected_default_message_delivery_tx_weight: Weight, - expected_additional_byte_delivery_weight: Weight, - expected_messages_delivery_confirmation_tx_weight: Weight, - expected_pay_inbound_dispatch_fee_weight: Weight, - db_weight: RuntimeDbWeight, -) { - // verify `send_message` weight components - assert_ne!(W::send_message_overhead(), Weight::zero()); - assert_ne!(W::send_message_size_overhead(0), Weight::zero()); - +pub fn ensure_weights_are_correct() { // verify `receive_messages_proof` weight components assert_ne!(W::receive_messages_proof_overhead(), Weight::zero()); assert_ne!(W::receive_messages_proof_messages_overhead(1), Weight::zero()); assert_ne!(W::receive_messages_proof_outbound_lane_state_overhead(), Weight::zero()); assert_ne!(W::storage_proof_size_overhead(1), Weight::zero()); - // verify that the hardcoded value covers `receive_messages_proof` weight - let actual_single_regular_message_delivery_tx_weight = W::receive_messages_proof_weight( - &PreComputedSize( - (EXPECTED_DEFAULT_MESSAGE_LENGTH + W::expected_extra_storage_proof_size()) as usize, - ), - 1, - Weight::zero(), - ); - assert!( - actual_single_regular_message_delivery_tx_weight - .all_lte(expected_default_message_delivery_tx_weight), - "Default message delivery transaction weight {} is larger than expected weight {}", - actual_single_regular_message_delivery_tx_weight, - expected_default_message_delivery_tx_weight, - ); - - // verify that hardcoded value covers additional byte length of `receive_messages_proof` weight - let actual_additional_byte_delivery_weight = W::storage_proof_size_overhead(1); - assert!( - actual_additional_byte_delivery_weight.all_lte(expected_additional_byte_delivery_weight), - "Single additional byte delivery weight {} is larger than expected weight {}", - actual_additional_byte_delivery_weight, - expected_additional_byte_delivery_weight, - ); - // verify `receive_messages_delivery_proof` weight components assert_ne!(W::receive_messages_delivery_proof_overhead(), Weight::zero()); assert_ne!(W::storage_proof_size_overhead(1), Weight::zero()); - - // `receive_messages_delivery_proof_messages_overhead` and - // `receive_messages_delivery_proof_relayers_overhead` may return zero if rewards are not paid - // during confirmations delivery, so we're not checking it here - - // verify that the hardcoded value covers `receive_messages_delivery_proof` weight - let actual_messages_delivery_confirmation_tx_weight = W::receive_messages_delivery_proof_weight( - &PreComputedSize(W::expected_extra_storage_proof_size() as usize), - &UnrewardedRelayersState { - unrewarded_relayer_entries: 1, - total_messages: 1, - ..Default::default() - }, - db_weight, - ); - assert!( - actual_messages_delivery_confirmation_tx_weight - .all_lte(expected_messages_delivery_confirmation_tx_weight), - "Messages delivery confirmation transaction weight {} is larger than expected weight {}", - actual_messages_delivery_confirmation_tx_weight, - expected_messages_delivery_confirmation_tx_weight, - ); - - // verify pay-dispatch-fee overhead for inbound messages - let actual_pay_inbound_dispatch_fee_weight = W::pay_inbound_dispatch_fee_overhead(); - assert!( - actual_pay_inbound_dispatch_fee_weight.all_lte(expected_pay_inbound_dispatch_fee_weight), - "Weight {} of pay-dispatch-fee overhead for inbound messages is larger than expected weight {}", - actual_pay_inbound_dispatch_fee_weight, - expected_pay_inbound_dispatch_fee_weight, - ); } /// Ensure that we're able to receive maximal (by-size and by-weight) message from other chain. @@ -199,17 +133,6 @@ pub trait WeightInfoExt: WeightInfo { // Functions that are directly mapped to extrinsics weights. - /// Weight of message send extrinsic. - fn send_message_weight(message: &impl Size, db_weight: RuntimeDbWeight) -> Weight { - let transaction_overhead = Self::send_message_overhead(); - let message_size_overhead = Self::send_message_size_overhead(message.size()); - let call_back_overhead = Self::single_message_callback_overhead(db_weight); - - transaction_overhead - .saturating_add(message_size_overhead) - .saturating_add(call_back_overhead) - } - /// Weight of message delivery extrinsic. fn receive_messages_proof_weight( proof: &impl Size, @@ -275,20 +198,6 @@ pub trait WeightInfoExt: WeightInfo { // Functions that are used by extrinsics weights formulas. - /// Returns weight of message send transaction (`send_message`). - fn send_message_overhead() -> Weight { - Self::send_minimal_message_worst_case() - } - - /// Returns weight that needs to be accounted when message of given size is sent - /// (`send_message`). - fn send_message_size_overhead(message_size: u32) -> Weight { - let message_size_in_kb = (1024u64 + message_size as u64) / 1024; - let single_kb_weight = - (Self::send_16_kb_message_worst_case() - Self::send_1_kb_message_worst_case()) / 15; - message_size_in_kb * single_kb_weight - } - /// Returns weight overhead of message delivery transaction (`receive_messages_proof`). fn receive_messages_proof_overhead() -> Weight { let weight_of_two_messages_and_two_tx_overheads = diff --git a/primitives/messages/src/lib.rs b/primitives/messages/src/lib.rs index 3406b092..a26a47ac 100644 --- a/primitives/messages/src/lib.rs +++ b/primitives/messages/src/lib.rs @@ -29,7 +29,7 @@ use bitvec::prelude::*; use codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; // darwinia-network -use bp_runtime::{BasicOperatingMode, OperatingMode, messages::DispatchFeePayment}; +use bp_runtime::{BasicOperatingMode, OperatingMode}; // paritytech use frame_support::RuntimeDebug; use sp_std::{collections::vec_deque::VecDeque, prelude::*}; @@ -53,15 +53,6 @@ pub type MessagePayload = Vec; /// Bit vector of message dispatch results. pub type DispatchResultsBitVec = BitVec; -/// Messages pallet parameter. -pub trait Parameter: frame_support::Parameter { - /// Save parameter value in the runtime storage. - fn save(&self); -} -impl Parameter for () { - fn save(&self) {} -} - /// Messages pallet operating mode. #[derive(Clone, Copy, PartialEq, Eq, Encode, Decode, RuntimeDebug, MaxEncodedLen, TypeInfo)] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] @@ -100,22 +91,13 @@ pub struct MessageKey { pub nonce: MessageNonce, } -/// Message data as it is stored in the storage. -#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] -pub struct MessageData { - /// Message payload. - pub payload: MessagePayload, - /// Message delivery and dispatch fee, paid by the submitter. - pub fee: Fee, -} - /// Message as it is stored in the storage. #[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] -pub struct Message { +pub struct Message { /// Message key. pub key: MessageKey, - /// Message data. - pub data: MessageData, + /// Message payload. + pub payload: MessagePayload, } /// Inbound lane data. @@ -197,7 +179,7 @@ impl InboundLaneData { /// Outbound message details, returned by runtime APIs. #[derive(Clone, Encode, Decode, RuntimeDebug, PartialEq, Eq)] -pub struct OutboundMessageDetails { +pub struct OutboundMessageDetails { /// Nonce assigned to the message. pub nonce: MessageNonce, /// Message dispatch weight. @@ -207,10 +189,6 @@ pub struct OutboundMessageDetails { pub dispatch_weight: Weight, /// Size of the encoded message. pub size: u32, - /// Delivery+dispatch fee paid by the message submitter at the source chain. - pub delivery_and_dispatch_fee: OutboundMessageFee, - /// Where the fee for dispatching message is paid? - pub dispatch_fee_payment: DispatchFeePayment, } /// Inbound message details, returned by runtime APIs. diff --git a/primitives/messages/src/source_chain.rs b/primitives/messages/src/source_chain.rs index 1ac45cdb..2ed4c678 100644 --- a/primitives/messages/src/source_chain.rs +++ b/primitives/messages/src/source_chain.rs @@ -29,17 +29,8 @@ use sp_std::{collections::btree_map::BTreeMap, collections::vec_deque::VecDeque, const ALL_OUTBOUND_MESSAGES_REJECTED: &str = "This chain is configured to reject all outbound messages"; -/// Relayers rewards, grouped by relayer account id. -pub type RelayersRewards = BTreeMap>; - -/// Single relayer rewards. -#[derive(RuntimeDebug, Default)] -pub struct RelayerRewards { - /// Total rewards that are to be paid to the relayer. - pub reward: Balance, - /// Total number of messages relayed by this relayer. - pub messages: MessageNonce, -} +/// Number of messages, delivered by relayers. +pub type RelayersRewards = BTreeMap; /// Target chain API. Used by source chain to verify target chain proofs. /// @@ -85,7 +76,7 @@ pub trait TargetHeaderChain { /// Lane3 until some block, ...), then it may be built using this verifier. /// /// Any fee requirements should also be enforced here. -pub trait LaneMessageVerifier { +pub trait LaneMessageVerifier { /// Error type. type Error: Debug + Into<&'static str>; @@ -93,7 +84,6 @@ pub trait LaneMessageVerifier { /// lane. fn verify_message( submitter: &SenderOrigin, - delivery_and_dispatch_fee: &Fee, lane: &LaneId, outbound_data: &OutboundLaneData, payload: &Payload, @@ -109,22 +99,10 @@ pub trait LaneMessageVerifier { /// 3) message-dispatch fee. It is paid by relayer for processing message by target chain; /// 4) message-receiving-delivery-transaction-fee. It is submitted to the source node /// by relayer. -/// -/// So to be sure that any non-altruist relayer would agree to deliver message, submitter -/// should set `delivery_and_dispatch_fee` to at least (equivalent of): sum of fees from (2) -/// to (4) above, plus some interest for the relayer. -pub trait MessageDeliveryAndDispatchPayment { +pub trait MessageDeliveryAndDispatchPayment { /// Error type. type Error: Debug + Into<&'static str>; - /// Withhold/write-off delivery_and_dispatch_fee from submitter account to - /// some relayers-fund account. - fn pay_delivery_and_dispatch_fee( - submitter: &SenderOrigin, - fee: &Balance, - relayer_fund_account: &AccountId, - ) -> Result<(), Self::Error>; - /// Pay rewards for delivering messages to the given relayers. /// /// The implementation may also choose to pay reward to the `confirmation_relayer`, which is @@ -137,19 +115,9 @@ pub trait MessageDeliveryAndDispatchPayment { relayer_fund_account: &AccountId, ); } -impl - MessageDeliveryAndDispatchPayment for () -{ +impl MessageDeliveryAndDispatchPayment for () { type Error = &'static str; - fn pay_delivery_and_dispatch_fee( - _submitter: &SenderOrigin, - _fee: &Balance, - _relayer_fund_account: &AccountId, - ) -> Result<(), Self::Error> { - Ok(()) - } - fn pay_relayers_rewards( _lane_id: LaneId, _messages_relayers: VecDeque>, @@ -210,7 +178,7 @@ pub struct SendMessageArtifacts { } /// Messages bridge API to be used from other pallets. -pub trait MessagesBridge { +pub trait MessagesBridge { /// Error type. type Error: Debug; @@ -221,7 +189,6 @@ pub trait MessagesBridge { sender: SenderOrigin, lane: LaneId, message: Payload, - delivery_and_dispatch_fee: Balance, ) -> Result; } @@ -229,16 +196,13 @@ pub trait MessagesBridge { #[derive(Eq, PartialEq, RuntimeDebug)] pub struct NoopMessagesBridge; -impl MessagesBridge - for NoopMessagesBridge -{ +impl MessagesBridge for NoopMessagesBridge { type Error = &'static str; fn send_message( _sender: SenderOrigin, _lane: LaneId, _message: Payload, - _delivery_and_dispatch_fee: Balance, ) -> Result { Ok(SendMessageArtifacts { nonce: 0, weight: Weight::zero() }) } @@ -261,14 +225,11 @@ impl TargetHeaderChain for ForbidOutboun Err(ALL_OUTBOUND_MESSAGES_REJECTED) } } -impl LaneMessageVerifier - for ForbidOutboundMessages -{ +impl LaneMessageVerifier for ForbidOutboundMessages { type Error = &'static str; fn verify_message( _submitter: &SenderOrigin, - _delivery_and_dispatch_fee: &Fee, _lane: &LaneId, _outbound_data: &OutboundLaneData, _payload: &Payload, @@ -276,19 +237,11 @@ impl LaneMessageVerifier Err(ALL_OUTBOUND_MESSAGES_REJECTED) } } -impl - MessageDeliveryAndDispatchPayment for ForbidOutboundMessages +impl MessageDeliveryAndDispatchPayment + for ForbidOutboundMessages { type Error = &'static str; - fn pay_delivery_and_dispatch_fee( - _submitter: &SenderOrigin, - _fee: &Balance, - _relayer_fund_account: &AccountId, - ) -> Result<(), Self::Error> { - Err(ALL_OUTBOUND_MESSAGES_REJECTED) - } - fn pay_relayers_rewards( _lane_id: LaneId, _messages_relayers: VecDeque>, diff --git a/primitives/messages/src/target_chain.rs b/primitives/messages/src/target_chain.rs index f37c282c..35eb0e76 100644 --- a/primitives/messages/src/target_chain.rs +++ b/primitives/messages/src/target_chain.rs @@ -16,7 +16,7 @@ //! Primitives of messages module, that are used on the target chain. -use crate::{LaneId, Message, MessageData, MessageKey, OutboundLaneData}; +use crate::{LaneId, Message, MessageKey, MessagePayload, OutboundLaneData}; use bp_runtime::{messages::MessageDispatchResult, Size}; use codec::{Decode, Encode, Error as CodecError}; @@ -36,7 +36,7 @@ const ALL_INBOUND_MESSAGES_REJECTED: &str = /// All implementations of this trait should only work with finalized data that /// can't change. Wrong implementation may lead to invalid lane states (i.e. lane /// that's stuck) and/or processing messages without paying fees. -pub trait SourceHeaderChain { +pub trait SourceHeaderChain { /// Error type. type Error: Debug + Into<&'static str>; @@ -58,11 +58,11 @@ pub trait SourceHeaderChain { fn verify_messages_proof( proof: Self::MessagesProof, messages_count: u32, - ) -> Result>, Self::Error>; + ) -> Result, Self::Error>; } /// Called when inbound message is received. -pub trait MessageDispatch { +pub trait MessageDispatch { /// Decoded message payload type. Valid message may contain invalid payload. In this case /// message is delivered, but dispatch fails. Therefore, two separate types of payload /// (opaque `MessagePayload` used in delivery and this `DispatchPayload` used in dispatch). @@ -73,7 +73,7 @@ pub trait MessageDispatch { /// This function must return correct upper bound of dispatch weight. The return value /// of this function is expected to match return value of the corresponding /// `FromInboundLaneApi::message_details().dispatch_weight` call. - fn dispatch_weight(message: &mut DispatchMessage) -> Weight; + fn dispatch_weight(message: &mut DispatchMessage) -> Weight; /// Checking in message receiving step before dispatch /// @@ -93,7 +93,7 @@ pub trait MessageDispatch { /// it must be paid inside this method to the `relayer_account`. fn dispatch( relayer_account: &AccountId, - message: DispatchMessage, + message: DispatchMessage, ) -> MessageDispatchResult; } @@ -113,69 +113,59 @@ impl Default for ProvedLaneMessages { /// Message data with decoded dispatch payload. #[derive(RuntimeDebug)] -pub struct DispatchMessageData { +pub struct DispatchMessageData { /// Result of dispatch payload decoding. pub payload: Result, - /// Message delivery and dispatch fee, paid by the submitter. - pub fee: Fee, } -impl From> - for DispatchMessageData -{ - fn from(data: MessageData) -> Self { - DispatchMessageData { - payload: DispatchPayload::decode(&mut &data.payload[..]), - fee: data.fee, - } +impl From for DispatchMessageData { + fn from(payload: MessagePayload) -> Self { + DispatchMessageData { payload: DispatchPayload::decode(&mut &payload[..]) } } } /// Message with decoded dispatch payload. #[derive(RuntimeDebug)] -pub struct DispatchMessage { +pub struct DispatchMessage { /// Message key. pub key: MessageKey, /// Message data with decoded dispatch payload. - pub data: DispatchMessageData, + pub data: DispatchMessageData, } -impl From> for DispatchMessage { - fn from(message: Message) -> Self { - DispatchMessage { key: message.key, data: message.data.into() } +impl From for DispatchMessage { + fn from(message: Message) -> Self { + DispatchMessage { key: message.key, data: message.payload.into() } } } /// Structure that may be used in place of `SourceHeaderChain` and `MessageDispatch` on chains, /// where inbound messages are forbidden. pub struct ForbidInboundMessages; -impl SourceHeaderChain for ForbidInboundMessages { +impl SourceHeaderChain for ForbidInboundMessages { type Error = &'static str; type MessagesProof = (); fn verify_messages_proof( _proof: Self::MessagesProof, _messages_count: u32, - ) -> Result>, Self::Error> { + ) -> Result, Self::Error> { Err(ALL_INBOUND_MESSAGES_REJECTED) } } -impl MessageDispatch for ForbidInboundMessages { +impl MessageDispatch for ForbidInboundMessages { type DispatchPayload = (); - fn dispatch_weight(_message: &mut DispatchMessage) -> Weight { + fn dispatch_weight(_message: &mut DispatchMessage) -> Weight { Weight::MAX } fn pre_dispatch( _: &AccountId, - _message: &DispatchMessage, + _message: &DispatchMessage, ) -> Result<(), &'static str> { Ok(()) } - fn dispatch( - _: &AccountId, - _: DispatchMessage, - ) -> MessageDispatchResult { + fn dispatch(_: &AccountId, _: DispatchMessage) -> MessageDispatchResult { MessageDispatchResult { dispatch_result: false, unspent_weight: Weight::zero(), diff --git a/primitives/runtime/src/messages.rs b/primitives/runtime/src/messages.rs index a46890dc..8cfccfd0 100644 --- a/primitives/runtime/src/messages.rs +++ b/primitives/runtime/src/messages.rs @@ -22,20 +22,6 @@ use scale_info::TypeInfo; // paritytech use frame_support::{weights::Weight, RuntimeDebug}; -/// Where message dispatch fee is paid? -#[derive(Clone, Copy, PartialEq, Eq, Encode, Decode, RuntimeDebug, TypeInfo)] -pub enum DispatchFeePayment { - /// The dispatch fee is paid at the source chain. - AtSourceChain, - /// The dispatch fee is paid at the target chain. - /// - /// The fee will be paid right before the message is dispatched. So in case of any other - /// issues (like invalid call encoding, invalid signature, ...) the dispatch module won't - /// do any direct transfers. Instead, it'll return fee related to this message dispatch to the - /// relayer. - AtTargetChain, -} - /// Message dispatch result. #[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug, TypeInfo)] pub struct MessageDispatchResult { diff --git a/runtime-common/src/integrity.rs b/runtime-common/src/integrity.rs index d82c0501..1d61b5a7 100644 --- a/runtime-common/src/integrity.rs +++ b/runtime-common/src/integrity.rs @@ -88,10 +88,8 @@ macro_rules! assert_bridge_messages_pallet_types( use static_assertions::assert_type_eq_all; assert_type_eq_all!(<$r as MessagesConfig<$i>>::OutboundPayload, FromThisChainMessagePayload); - assert_type_eq_all!(<$r as MessagesConfig<$i>>::OutboundMessageFee, BalanceOf>); assert_type_eq_all!(<$r as MessagesConfig<$i>>::InboundPayload, FromBridgedChainMessagePayload>>); - assert_type_eq_all!(<$r as MessagesConfig<$i>>::InboundMessageFee, BalanceOf>); assert_type_eq_all!(<$r as MessagesConfig<$i>>::InboundRelayer, AccountIdOf>); assert_type_eq_all!(<$r as MessagesConfig<$i>>::TargetHeaderChain, BridgedChain<$bridge>); diff --git a/runtime-common/src/messages.rs b/runtime-common/src/messages.rs index 0caf792f..018df9c3 100644 --- a/runtime-common/src/messages.rs +++ b/runtime-common/src/messages.rs @@ -23,14 +23,14 @@ // core use core::marker::PhantomData; // crates.io -use codec::{Decode, DecodeLimit, Encode, MaxEncodedLen}; +use codec::{Decode, DecodeLimit, Encode}; use hash_db::Hasher; use scale_info::TypeInfo; // darwinia-network use bp_messages::{ source_chain::LaneMessageVerifier, target_chain::{DispatchMessage, MessageDispatch, ProvedLaneMessages, ProvedMessages}, - InboundLaneData, LaneId, Message, MessageData, MessageKey, MessageNonce, OutboundLaneData, + InboundLaneData, LaneId, Message, MessageKey, MessageNonce, MessagePayload, OutboundLaneData, }; use bp_polkadot_core::parachains::{ParaHash, ParaHasher, ParaId}; use bp_runtime::{messages::MessageDispatchResult, ChainId, Size, StorageProofChecker}; @@ -40,10 +40,6 @@ use frame_support::{ weights::Weight, RuntimeDebug, }; -use sp_runtime::{ - traits::{CheckedAdd, CheckedDiv, CheckedMul, Header as HeaderT}, - FixedPointNumber, FixedPointOperand, -}; use sp_std::prelude::*; use sp_trie::StorageProof; use xcm::latest::prelude::*; @@ -209,12 +205,8 @@ pub mod source { /// The error message returned from LaneMessageVerifier when the message fee is too low. pub const TOO_LOW_FEE: &str = "Provided fee is below minimal threshold required by the lane."; - impl - LaneMessageVerifier< - OriginOf>, - FromThisChainMessagePayload, - BalanceOf>, - > for FromThisChainMessageVerifier + impl LaneMessageVerifier>, FromThisChainMessagePayload> + for FromThisChainMessageVerifier where B: MessageBridge, F: pallet_fee_market::Config, @@ -231,10 +223,9 @@ pub mod source { #[cfg(not(feature = "runtime-benchmarks"))] fn verify_message( submitter: &OriginOf>, - delivery_and_dispatch_fee: &BalanceOf>, lane: &LaneId, lane_outbound_data: &OutboundLaneData, - payload: &FromThisChainMessagePayload, + _payload: &FromThisChainMessagePayload, ) -> Result<(), Self::Error> { // reject message if lane is blocked if !ThisChain::::is_message_accepted(submitter, lane) { @@ -407,7 +398,6 @@ pub mod source { /// Runtime message sender adapter. type MessageSender: bp_messages::source_chain::MessagesBridge< OriginOf>, - BalanceOf>, FromThisChainMessagePayload, >; @@ -429,7 +419,7 @@ pub mod source { BalanceOf>: Into, OriginOf>: From, { - type Ticket = (BalanceOf>, FromThisChainMessagePayload); + type Ticket = FromThisChainMessagePayload; fn validate( dest: &mut Option, @@ -444,39 +434,22 @@ pub mod source { let route = T::build_destination(); let msg = (route, msg.take().ok_or(SendError::MissingArgument)?).encode(); - let fee = estimate_message_dispatch_and_delivery_fee::( - &msg, - T::MessageBridge::RELAYER_FEE_PERCENT, - None, - ); - let fee = match fee { - Ok(fee) => fee, - Err(e) => { - log::trace!( - target: "runtime::bridge", - "Failed to comupte fee for XCM message to {:?}: {:?}", - T::MessageBridge::BRIDGED_CHAIN_ID, - e, - ); - *dest = Some(d); - return Err(SendError::Transport(e)) - }, - }; - let fee_assets = MultiAssets::from((Here, fee)); + // let's just take fixed (out of thin air) fee per message in our test bridges + // (this code won't be used in production anyway) + let fee_assets = MultiAssets::from((Here, 1_000_000_u128)); - Ok(((fee, msg), fee_assets)) + Ok((msg, fee_assets)) } fn deliver(ticket: Self::Ticket) -> Result { use bp_messages::source_chain::MessagesBridge; let lane = T::xcm_lane(); - let (fee, msg) = ticket; + let msg = ticket; let result = T::MessageSender::send_message( pallet_xcm::Origin::from(MultiLocation::from(T::universal_location())).into(), lane, msg, - fee, ); result .map(|artifacts| { @@ -574,7 +547,7 @@ pub mod target { _marker: PhantomData<(B, XcmExecutor, XcmWeigher, WeightCredit)>, } impl - MessageDispatch>, BalanceOf>> + MessageDispatch>> for FromBridgedChainMessageDispatch where XcmExecutor: xcm::v3::ExecuteXcm>>, @@ -584,7 +557,7 @@ pub mod target { type DispatchPayload = FromBridgedChainMessagePayload>>; fn dispatch_weight( - message: &mut DispatchMessage>>, + message: &mut DispatchMessage, ) -> frame_support::weights::Weight { match message.data.payload { Ok(ref mut payload) => { @@ -614,7 +587,7 @@ pub mod target { fn pre_dispatch( relayer_account: &AccountIdOf>, - message: &DispatchMessage>>, + message: &DispatchMessage, ) -> Result<(), &'static str> { pallet_bridge_dispatch::Pallet::::pre_dispatch( relayer_account, @@ -624,7 +597,7 @@ pub mod target { fn dispatch( _relayer_account: &AccountIdOf>, - message: DispatchMessage>>, + message: DispatchMessage, ) -> MessageDispatchResult { let message_id = (message.key.lane_id, message.key.nonce); let do_dispatch = move || -> sp_std::result::Result { @@ -684,7 +657,7 @@ pub mod target { pub fn verify_messages_proof( proof: FromBridgedChainMessagesProof>>, messages_count: u32, - ) -> Result>>>, &'static str> + ) -> Result, &'static str> where ThisRuntime: pallet_bridge_grandpa::Config, HashOf>: Into< @@ -824,7 +797,7 @@ pub mod target { proof: FromBridgedChainMessagesProof>>, messages_count: u32, build_parser: BuildParser, - ) -> Result>>>, MessageProofError> + ) -> Result, MessageProofError> where BuildParser: FnOnce(HashOf>, RawStorageProof) -> Result, @@ -1112,73 +1085,39 @@ mod tests { } } - // fn test_lane_outbound_data() -> OutboundLaneData { - // OutboundLaneData::default() - // } - fn regular_outbound_message_payload() -> source::FromThisChainMessagePayload { vec![42] } #[test] - fn message_fee_is_checked_by_verifier() { - const EXPECTED_MINIMAL_FEE: u32 = 2860; - - // payload of the This -> Bridged chain message - let payload = regular_outbound_message_payload(); - - // and now check that the verifier checks the fee + fn message_is_rejected_when_sent_using_disabled_lane() { assert_eq!( source::FromThisChainMessageVerifier::::verify_message( &ThisChainOrigin(Ok(frame_system::RawOrigin::Root)), - &ThisChainBalance(1), - TEST_LANE_ID, + b"dsbl", &test_lane_outbound_data(), - &payload, + ®ular_outbound_message_payload(), ), - Err(source::TOO_LOW_FEE) + Err(source::MESSAGE_REJECTED_BY_OUTBOUND_LANE) ); - assert!(source::FromThisChainMessageVerifier::::verify_message( - &ThisChainOrigin(Ok(frame_system::RawOrigin::Root)), - &ThisChainBalance(1_000_000), - TEST_LANE_ID, - &test_lane_outbound_data(), - &payload, - ) - .is_ok(),); } - // #[test] - // fn message_is_rejected_when_sent_using_disabled_lane() { - // assert_eq!( - // source::FromThisChainMessageVerifier::::verify_message( - // &ThisChainOrigin(Ok(frame_system::RawOrigin::Root)), - // &ThisChainBalance(1_000_000), - // b"dsbl", - // &test_lane_outbound_data(), - // ®ular_outbound_message_payload(), - // ), - // Err(source::MESSAGE_REJECTED_BY_OUTBOUND_LANE) - // ); - // } - - // #[test] - // fn message_is_rejected_when_there_are_too_many_pending_messages_at_outbound_lane() { - // assert_eq!( - // source::FromThisChainMessageVerifier::::verify_message( - // &ThisChainOrigin(Ok(frame_system::RawOrigin::Root)), - // &ThisChainBalance(1_000_000), - // TEST_LANE_ID, - // &OutboundLaneData { - // latest_received_nonce: 100, - // latest_generated_nonce: 100 + MAXIMAL_PENDING_MESSAGES_AT_TEST_LANE + 1, - // ..Default::default() - // }, - // ®ular_outbound_message_payload(), - // ), - // Err(source::TOO_MANY_PENDING_MESSAGES) - // ); - // } + #[test] + fn message_is_rejected_when_there_are_too_many_pending_messages_at_outbound_lane() { + assert_eq!( + source::FromThisChainMessageVerifier::::verify_message( + &ThisChainOrigin(Ok(frame_system::RawOrigin::Root)), + TEST_LANE_ID, + &OutboundLaneData { + latest_received_nonce: 100, + latest_generated_nonce: 100 + MAXIMAL_PENDING_MESSAGES_AT_TEST_LANE + 1, + ..Default::default() + }, + ®ular_outbound_message_payload(), + ), + Err(source::TOO_MANY_PENDING_MESSAGES) + ); + } #[test] fn verify_chain_message_rejects_message_with_too_small_declared_weight() { diff --git a/runtime-common/src/messages_benchmarking.rs b/runtime-common/src/messages_benchmarking.rs index 192d6d8c..3a29994e 100644 --- a/runtime-common/src/messages_benchmarking.rs +++ b/runtime-common/src/messages_benchmarking.rs @@ -24,8 +24,7 @@ use codec::Encode; // darwinia-network use crate::{ messages::{ - source::{FromBridgedChainMessagesDeliveryProof, FromThisChainMessagePayload}, - target::FromBridgedChainMessagesProof, + source::FromBridgedChainMessagesDeliveryProof, target::FromBridgedChainMessagesProof, AccountIdOf, BalanceOf, BridgedChain, CallOf, HashOf, MessageBridge, ThisChain, }, messages_generation::{ @@ -33,9 +32,7 @@ use crate::{ }, }; use bp_messages::storage_keys; -use pallet_bridge_messages::benchmarking::{ - MessageDeliveryProofParams, MessageParams, MessageProofParams, -}; +use pallet_bridge_messages::benchmarking::{MessageDeliveryProofParams, MessageProofParams}; // paritytech use frame_support::weights::{GetDispatchInfo, Weight}; use sp_core::Hasher; @@ -43,17 +40,6 @@ use sp_runtime::traits::{Header, MaybeSerializeDeserialize, Zero}; use sp_std::{fmt::Debug, prelude::*}; use sp_trie::{trie_types::TrieDBMutBuilderV1, LayoutV1, MemoryDB, Recorder, TrieMut}; -/// Prepare outbound message for the `send_message` call. -pub fn prepare_outbound_message( - params: MessageParams>>, -) -> FromThisChainMessagePayload -where - B: MessageBridge, - BalanceOf>: From, -{ - vec![0; params.size as usize] -} - /// Prepare proof of messages for the `receive_messages_proof` call. /// /// In addition to returning valid messages proof, environment is prepared to verify this message diff --git a/runtime-common/src/messages_extension.rs b/runtime-common/src/messages_extension.rs index 37a2243d..06d3eb5c 100644 --- a/runtime-common/src/messages_extension.rs +++ b/runtime-common/src/messages_extension.rs @@ -33,7 +33,6 @@ use sp_runtime::transaction_validity::TransactionValidity; impl< BridgedHeaderHash, SourceHeaderChain: bp_messages::target_chain::SourceHeaderChain< - >::InboundMessageFee, MessagesProof = FromBridgedChainMessagesProof, >, TargetHeaderChain: bp_messages::source_chain::TargetHeaderChain< diff --git a/runtime-common/src/messages_generation.rs b/runtime-common/src/messages_generation.rs index 822b635c..560033d1 100644 --- a/runtime-common/src/messages_generation.rs +++ b/runtime-common/src/messages_generation.rs @@ -18,23 +18,19 @@ #![cfg(any(feature = "runtime-benchmarks", test))] -use crate::messages::{BalanceOf, BridgedChain, HashOf, HasherOf, MessageBridge, RawStorageProof}; +use crate::messages::{BridgedChain, HashOf, HasherOf, MessageBridge, RawStorageProof}; use bp_messages::{ - storage_keys, LaneId, MessageData, MessageKey, MessageNonce, MessagePayload, OutboundLaneData, + storage_keys, LaneId, MessageKey, MessageNonce, MessagePayload, OutboundLaneData, }; use bp_runtime::{record_all_trie_keys, StorageProofSize}; use codec::Encode; use sp_core::Hasher; -use sp_runtime::traits::Zero; use sp_std::{ops::RangeInclusive, prelude::*}; use sp_trie::{trie_types::TrieDBMutBuilderV1, LayoutV1, MemoryDB, Recorder, TrieMut}; /// Simple and correct message data encode function. -pub(crate) fn encode_all_messages( - _: MessageNonce, - m: &MessageData, -) -> Option> { +pub(crate) fn encode_all_messages(_: MessageNonce, m: &MessagePayload) -> Option> { Some(m.encode()) } @@ -52,7 +48,7 @@ pub(crate) fn prepare_messages_storage_proof( outbound_lane_data: Option, size: StorageProofSize, message_payload: MessagePayload, - encode_message: impl Fn(MessageNonce, &MessageData>>) -> Option>, + encode_message: impl Fn(MessageNonce, &MessagePayload) -> Option>, encode_outbound_lane_data: impl Fn(&OutboundLaneData) -> Vec, ) -> (HashOf>, RawStorageProof) where @@ -71,12 +67,8 @@ where // insert messages for nonce in message_nonces { let message_key = MessageKey { lane_id: lane, nonce }; - let message_data = MessageData { - fee: BalanceOf::>::zero(), - payload: message_payload.clone(), - }; - let message_data = match encode_message(nonce, &message_data) { - Some(message_data) => message_data, + let message_payload = match encode_message(nonce, &message_payload) { + Some(message_payload) => message_payload, None => continue, }; let storage_key = storage_keys::message_key( @@ -85,7 +77,7 @@ where message_key.nonce, ) .0; - trie.insert(&storage_key, &message_data) + trie.insert(&storage_key, &message_payload) .map_err(|_| "TrieMut::insert has failed") .expect("TrieMut::insert should not fail in benchmarks"); storage_keys.push(storage_key);