Initial version of bridging pallets as git subtree (#2458)

* Initial version of bridges pallet as subtree of https://github.com/paritytech/parity-bridges-common
Added `Bridges subtree files` pr review rule

* Squashed 'bridges/' content from commit d30927c08

git-subtree-dir: bridges
git-subtree-split: d30927c089bd9e73092d1ec1a62895603cb277a3

* Updated REAMDE.md and BRIDGES.md (inspired by original https://github.com/paritytech/polkadot/blob/d22eb62fe40e55e15eb91d375f48cc540d83a47e/BRIDGES.md)

* Squashed 'bridges/' changes from d30927c08..d3970944b

d3970944b Small simplifications (#2050)

git-subtree-dir: bridges
git-subtree-split: d3970944b0cfc4ea5226225e1ca07dab234c3556

* Squashed 'bridges/' changes from d3970944b..2180797fb

2180797fb Removed CODEOWNERS (#2051)

git-subtree-dir: bridges
git-subtree-split: 2180797fbf8a990490c67853dcffd81bc8dd083c

* Squashed 'bridges/' changes from 2180797fbf..4850aac8ce

4850aac8ce Removed relayer_account: &AccountId from MessageDispatch  (#2080)
8c8adafd54 Revert "Fix max-size messages at test chains (#2064)" (#2077)
c01a63efd8 Fixed off-by-one when confirming rewards in messages pallet (#2075)
a298be96aa Update subxt dependencies (#2072)
c0eef51eab Fix max-size messages at test chains (#2064)
3a658e3697 Messages relay fixes (#2073)
0022b5ab22 Slash relayers for invalid transactions (#2025)
198104007f Bump enumflags2 from 0.7.5 to 0.7.7
9229b257e5 [ci] Fix rules for docker build (#2069)
660d791390 [ci] Update buildah command and version (#2058)
e4535c0ca4 fix the way latest_confirmed_nonce_at_source is "calculated" (#2067)
dbc2d37590 select nothing if we have already selected nonces to submit or have submitted something (#2065)
a7eedd21fe [relay-substrate-client] Bump jsonrpsee (#2066)
8875d5aeae Bump clap from 4.2.2 to 4.2.4
25f9cf55e2 Another use of RangeInclusiveExt::checked_len() (#2060)
4942c12a5f submit lane unblock transactions from relay (#2030)
c0325d3c9c Test deployments fixes (#2057)
fc7b9b7ed7 Use the new matrix server (#2056)
63bcb5c10b Fixed delivery alert rule (#2052)

git-subtree-dir: bridges
git-subtree-split: 4850aac8ce6c34e5ca6246b88cd14c873a879cba

* Squashed 'bridges/' changes from 4850aac8ce..66aaf0dd23

66aaf0dd23 Nits (#2083)

git-subtree-dir: bridges
git-subtree-split: 66aaf0dd239dde40b64264061a77c921e2c82568

* Squashed 'bridges/' changes from 66aaf0dd23..557ecbcecc

557ecbcecc Fix sized messages (Follow-up on #2064) (#2103)
54f587a066 Add weight of refund extension post_dispatch to the weights of messages pallet (#2089)
5b1626f8c4 fix pallet param for nightly benchmarks check (#2099)
ae44c6b7a1 Add millau specific messages weights (#2097)
6ad0bd1f1e Add integrity tests to rialto parachain runtiime (#2096)
6919556de5 Bump tokio from 1.27.0 to 1.28.0
58795fcb75 Bump clap from 4.2.4 to 4.2.5
01bf31085b Bump scale-info from 2.5.0 to 2.6.0
8fe383240d Bump anyhow from 1.0.70 to 1.0.71
8d94e82ad5 deployments: add new BEEFY metrics and alarms (#2090)
e9a4749e7e Bump wasmtime from 6.0.1 to 6.0.2
9d9936c0d9 Bump wasmtime from 6.0.1 to 6.0.2 in /tools/runtime-codegen
5d77cd7bee Add more logs to relayer and message pallets (#2082)
75fbb9d3ef Update comment (#2081)
9904d09cf6 Benchmarks for new relayers pallet calls (#2040)

git-subtree-dir: bridges
git-subtree-split: 557ecbcecc585547b744a5ac9fb8d7f3b9de4521

* fmt

* Squashed 'bridges/' changes from 557ecbcecc..04b3dda6aa

04b3dda6aa Remove from subtree (#2111)
f8ff15e7e7 Add `MessagesPalletInstance` for integrity tests (#2107)
92ccef58e6 Use generated runtimes for BHR/BHW (#2106)
b33e0a585b Fix comment (#2105)

git-subtree-dir: bridges
git-subtree-split: 04b3dda6aa38599e612ff637710b6d2cff275ef3

* ".git/.scripts/commands/fmt/fmt.sh"

---------

Co-authored-by: parity-processbot <>
This commit is contained in:
Branislav Kontur
2023-05-04 08:36:58 +02:00
committed by GitHub
parent 587242ec2d
commit d810f65044
114 changed files with 26856 additions and 6 deletions
@@ -0,0 +1,38 @@
[package]
name = "bp-messages"
description = "Primitives of messages module."
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2021"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies]
codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false, features = ["derive", "bit-vec"] }
scale-info = { version = "2.6.0", default-features = false, features = ["bit-vec", "derive"] }
serde = { version = "1.0", optional = true, features = ["derive"] }
# Bridge dependencies
bp-runtime = { path = "../runtime", default-features = false }
# Substrate Dependencies
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
[dev-dependencies]
hex = "0.4"
hex-literal = "0.4"
[features]
default = ["std"]
std = [
"bp-runtime/std",
"codec/std",
"frame-support/std",
"scale-info/std",
"serde",
"sp-core/std",
"sp-std/std"
]
@@ -0,0 +1,484 @@
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity Bridges Common is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
//! Primitives of messages module.
#![cfg_attr(not(feature = "std"), no_std)]
// RuntimeApi generated functions
#![allow(clippy::too_many_arguments)]
use bp_runtime::{BasicOperatingMode, OperatingMode, RangeInclusiveExt};
use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::RuntimeDebug;
use scale_info::TypeInfo;
use source_chain::RelayersRewards;
use sp_core::TypeId;
use sp_std::{collections::vec_deque::VecDeque, ops::RangeInclusive, prelude::*};
pub mod source_chain;
pub mod storage_keys;
pub mod target_chain;
use bp_runtime::messages::MessageDispatchResult;
// Weight is reexported to avoid additional frame-support dependencies in related crates.
pub use frame_support::weights::Weight;
/// Messages pallet operating mode.
#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub enum MessagesOperatingMode {
/// Basic operating mode (Normal/Halted)
Basic(BasicOperatingMode),
/// The pallet is not accepting outbound messages. Inbound messages and receiving proofs
/// are still accepted.
///
/// This mode may be used e.g. when bridged chain expects upgrade. Then to avoid dispatch
/// failures, the pallet owner may stop accepting new messages, while continuing to deliver
/// queued messages to the bridged chain. Once upgrade is completed, the mode may be switched
/// back to `Normal`.
RejectingOutboundMessages,
}
impl Default for MessagesOperatingMode {
fn default() -> Self {
MessagesOperatingMode::Basic(BasicOperatingMode::Normal)
}
}
impl OperatingMode for MessagesOperatingMode {
fn is_halted(&self) -> bool {
match self {
Self::Basic(operating_mode) => operating_mode.is_halted(),
_ => false,
}
}
}
/// Lane id which implements `TypeId`.
#[derive(
Clone, Copy, Decode, Default, Encode, Eq, Ord, PartialOrd, PartialEq, TypeInfo, MaxEncodedLen,
)]
pub struct LaneId(pub [u8; 4]);
impl core::fmt::Debug for LaneId {
fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
self.0.fmt(fmt)
}
}
impl AsRef<[u8]> for LaneId {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl TypeId for LaneId {
const TYPE_ID: [u8; 4] = *b"blan";
}
/// Message nonce. Valid messages will never have 0 nonce.
pub type MessageNonce = u64;
/// Message id as a tuple.
pub type BridgeMessageId = (LaneId, MessageNonce);
/// Opaque message payload. We only decode this payload when it is dispatched.
pub type MessagePayload = Vec<u8>;
/// Message key (unique message identifier) as it is stored in the storage.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
pub struct MessageKey {
/// ID of the message lane.
pub lane_id: LaneId,
/// Message nonce.
pub nonce: MessageNonce,
}
/// Message as it is stored in the storage.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub struct Message {
/// Message key.
pub key: MessageKey,
/// Message payload.
pub payload: MessagePayload,
}
/// Inbound lane data.
#[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq, TypeInfo)]
pub struct InboundLaneData<RelayerId> {
/// Identifiers of relayers and messages that they have delivered to this lane (ordered by
/// message nonce).
///
/// This serves as a helper storage item, to allow the source chain to easily pay rewards
/// to the relayers who successfully delivered messages to the target chain (inbound lane).
///
/// It is guaranteed to have at most N entries, where N is configured at the module level.
/// If there are N entries in this vec, then:
/// 1) all incoming messages are rejected if they're missing corresponding
/// `proof-of(outbound-lane.state)`; 2) all incoming messages are rejected if
/// `proof-of(outbound-lane.state).last_delivered_nonce` is equal to
/// `self.last_confirmed_nonce`. Given what is said above, all nonces in this queue are in
/// range: `(self.last_confirmed_nonce; self.last_delivered_nonce()]`.
///
/// When a relayer sends a single message, both of MessageNonces are the same.
/// When relayer sends messages in a batch, the first arg is the lowest nonce, second arg the
/// highest nonce. Multiple dispatches from the same relayer are allowed.
pub relayers: VecDeque<UnrewardedRelayer<RelayerId>>,
/// Nonce of the last message that
/// a) has been delivered to the target (this) chain and
/// b) the delivery has been confirmed on the source chain
///
/// that the target chain knows of.
///
/// This value is updated indirectly when an `OutboundLane` state of the source
/// chain is received alongside with new messages delivery.
pub last_confirmed_nonce: MessageNonce,
}
impl<RelayerId> Default for InboundLaneData<RelayerId> {
fn default() -> Self {
InboundLaneData { relayers: VecDeque::new(), last_confirmed_nonce: 0 }
}
}
impl<RelayerId> InboundLaneData<RelayerId> {
/// Returns approximate size of the struct, given a number of entries in the `relayers` set and
/// size of each entry.
///
/// Returns `None` if size overflows `usize` limits.
pub fn encoded_size_hint(relayers_entries: usize) -> Option<usize>
where
RelayerId: MaxEncodedLen,
{
relayers_entries
.checked_mul(UnrewardedRelayer::<RelayerId>::max_encoded_len())?
.checked_add(MessageNonce::max_encoded_len())
}
/// Returns the approximate size of the struct as u32, given a number of entries in the
/// `relayers` set and the size of each entry.
///
/// Returns `u32::MAX` if size overflows `u32` limits.
pub fn encoded_size_hint_u32(relayers_entries: usize) -> u32
where
RelayerId: MaxEncodedLen,
{
Self::encoded_size_hint(relayers_entries)
.and_then(|x| u32::try_from(x).ok())
.unwrap_or(u32::MAX)
}
/// Nonce of the last message that has been delivered to this (target) chain.
pub fn last_delivered_nonce(&self) -> MessageNonce {
self.relayers
.back()
.map(|entry| entry.messages.end)
.unwrap_or(self.last_confirmed_nonce)
}
}
/// Outbound message details, returned by runtime APIs.
#[derive(Clone, Encode, Decode, RuntimeDebug, PartialEq, Eq, TypeInfo)]
pub struct OutboundMessageDetails {
/// Nonce assigned to the message.
pub nonce: MessageNonce,
/// Message dispatch weight.
///
/// Depending on messages pallet configuration, it may be declared by the message submitter,
/// computed automatically or just be zero if dispatch fee is paid at the target chain.
pub dispatch_weight: Weight,
/// Size of the encoded message.
pub size: u32,
}
/// Inbound message details, returned by runtime APIs.
#[derive(Clone, Encode, Decode, RuntimeDebug, PartialEq, Eq, TypeInfo)]
pub struct InboundMessageDetails {
/// Computed message dispatch weight.
///
/// Runtime API guarantees that it will match the value, returned by
/// `target_chain::MessageDispatch::dispatch_weight`. This means that if the runtime
/// has failed to decode the message, it will be zero - that's because `undecodable`
/// message cannot be dispatched.
pub dispatch_weight: Weight,
}
/// Unrewarded relayer entry stored in the inbound lane data.
///
/// This struct represents a continuous range of messages that have been delivered by the same
/// relayer and whose confirmations are still pending.
#[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq, TypeInfo, MaxEncodedLen)]
pub struct UnrewardedRelayer<RelayerId> {
/// Identifier of the relayer.
pub relayer: RelayerId,
/// Messages range, delivered by this relayer.
pub messages: DeliveredMessages,
}
/// Received messages with their dispatch result.
#[derive(Clone, Default, Encode, Decode, RuntimeDebug, PartialEq, Eq, TypeInfo)]
pub struct ReceivedMessages<DispatchLevelResult> {
/// Id of the lane which is receiving messages.
pub lane: LaneId,
/// Result of messages which we tried to dispatch
pub receive_results: Vec<(MessageNonce, ReceivalResult<DispatchLevelResult>)>,
}
impl<DispatchLevelResult> ReceivedMessages<DispatchLevelResult> {
pub fn new(
lane: LaneId,
receive_results: Vec<(MessageNonce, ReceivalResult<DispatchLevelResult>)>,
) -> Self {
ReceivedMessages { lane, receive_results }
}
pub fn push(&mut self, message: MessageNonce, result: ReceivalResult<DispatchLevelResult>) {
self.receive_results.push((message, result));
}
}
/// Result of single message receival.
#[derive(RuntimeDebug, Encode, Decode, PartialEq, Eq, Clone, TypeInfo)]
pub enum ReceivalResult<DispatchLevelResult> {
/// Message has been received and dispatched. Note that we don't care whether dispatch has
/// been successful or not - in both case message falls into this category.
///
/// The message dispatch result is also returned.
Dispatched(MessageDispatchResult<DispatchLevelResult>),
/// Message has invalid nonce and lane has rejected to accept this message.
InvalidNonce,
/// There are too many unrewarded relayer entries at the lane.
TooManyUnrewardedRelayers,
/// There are too many unconfirmed messages at the lane.
TooManyUnconfirmedMessages,
}
/// Delivered messages with their dispatch result.
#[derive(Clone, Default, Encode, Decode, RuntimeDebug, PartialEq, Eq, TypeInfo, MaxEncodedLen)]
pub struct DeliveredMessages {
/// Nonce of the first message that has been delivered (inclusive).
pub begin: MessageNonce,
/// Nonce of the last message that has been delivered (inclusive).
pub end: MessageNonce,
}
impl DeliveredMessages {
/// Create new `DeliveredMessages` struct that confirms delivery of single nonce with given
/// dispatch result.
pub fn new(nonce: MessageNonce) -> Self {
DeliveredMessages { begin: nonce, end: nonce }
}
/// Return total count of delivered messages.
pub fn total_messages(&self) -> MessageNonce {
(self.begin..=self.end).checked_len().unwrap_or(0)
}
/// Note new dispatched message.
pub fn note_dispatched_message(&mut self) {
self.end += 1;
}
/// Returns true if delivered messages contain message with given nonce.
pub fn contains_message(&self, nonce: MessageNonce) -> bool {
(self.begin..=self.end).contains(&nonce)
}
}
/// Gist of `InboundLaneData::relayers` field used by runtime APIs.
#[derive(Clone, Default, Encode, Decode, RuntimeDebug, PartialEq, Eq, TypeInfo)]
pub struct UnrewardedRelayersState {
/// Number of entries in the `InboundLaneData::relayers` set.
pub unrewarded_relayer_entries: MessageNonce,
/// Number of messages in the oldest entry of `InboundLaneData::relayers`. This is the
/// minimal number of reward proofs required to push out this entry from the set.
pub messages_in_oldest_entry: MessageNonce,
/// Total number of messages in the relayers vector.
pub total_messages: MessageNonce,
/// Nonce of the latest message that has been delivered to the target chain.
///
/// This corresponds to the result of the `InboundLaneData::last_delivered_nonce` call
/// at the bridged chain.
pub last_delivered_nonce: MessageNonce,
}
impl<RelayerId> From<&InboundLaneData<RelayerId>> for UnrewardedRelayersState {
fn from(lane: &InboundLaneData<RelayerId>) -> UnrewardedRelayersState {
UnrewardedRelayersState {
unrewarded_relayer_entries: lane.relayers.len() as _,
messages_in_oldest_entry: lane
.relayers
.front()
.and_then(|entry| (entry.messages.begin..=entry.messages.end).checked_len())
.unwrap_or(0),
total_messages: total_unrewarded_messages(&lane.relayers).unwrap_or(MessageNonce::MAX),
last_delivered_nonce: lane.last_delivered_nonce(),
}
}
}
/// Outbound lane data.
#[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq, TypeInfo, MaxEncodedLen)]
pub struct OutboundLaneData {
/// Nonce of the oldest message that we haven't yet pruned. May point to not-yet-generated
/// message if all sent messages are already pruned.
pub oldest_unpruned_nonce: MessageNonce,
/// Nonce of the latest message, received by bridged chain.
pub latest_received_nonce: MessageNonce,
/// Nonce of the latest message, generated by us.
pub latest_generated_nonce: MessageNonce,
}
impl Default for OutboundLaneData {
fn default() -> Self {
OutboundLaneData {
// it is 1 because we're pruning everything in [oldest_unpruned_nonce;
// latest_received_nonce]
oldest_unpruned_nonce: 1,
latest_received_nonce: 0,
latest_generated_nonce: 0,
}
}
}
/// Returns total number of messages in the `InboundLaneData::relayers` vector.
///
/// Returns `None` if there are more messages that `MessageNonce` may fit (i.e. `MessageNonce + 1`).
pub fn total_unrewarded_messages<RelayerId>(
relayers: &VecDeque<UnrewardedRelayer<RelayerId>>,
) -> Option<MessageNonce> {
match (relayers.front(), relayers.back()) {
(Some(front), Some(back)) => {
if let Some(difference) = back.messages.end.checked_sub(front.messages.begin) {
difference.checked_add(1)
} else {
Some(0)
}
},
_ => Some(0),
}
}
/// Calculate the number of messages that the relayers have delivered.
pub fn calc_relayers_rewards<AccountId>(
messages_relayers: VecDeque<UnrewardedRelayer<AccountId>>,
received_range: &RangeInclusive<MessageNonce>,
) -> RelayersRewards<AccountId>
where
AccountId: sp_std::cmp::Ord,
{
// remember to reward relayers that have delivered messages
// this loop is bounded by `T::MaxUnrewardedRelayerEntriesAtInboundLane` on the bridged chain
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());
if nonce_end >= nonce_begin {
*relayers_rewards.entry(entry.relayer).or_default() += nonce_end - nonce_begin + 1;
}
}
relayers_rewards
}
/// A minimized version of `pallet-bridge-messages::Call` that can be used without a runtime.
#[derive(Encode, Decode, Debug, PartialEq, Eq, Clone, TypeInfo)]
#[allow(non_camel_case_types)]
pub enum BridgeMessagesCall<AccountId, MessagesProof, MessagesDeliveryProof> {
/// `pallet-bridge-messages::Call::receive_messages_proof`
#[codec(index = 2)]
receive_messages_proof {
relayer_id_at_bridged_chain: AccountId,
proof: MessagesProof,
messages_count: u32,
dispatch_weight: Weight,
},
/// `pallet-bridge-messages::Call::receive_messages_delivery_proof`
#[codec(index = 3)]
receive_messages_delivery_proof {
proof: MessagesDeliveryProof,
relayers_state: UnrewardedRelayersState,
},
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn total_unrewarded_messages_does_not_overflow() {
assert_eq!(
total_unrewarded_messages(
&vec![
UnrewardedRelayer { relayer: 1, messages: DeliveredMessages::new(0) },
UnrewardedRelayer {
relayer: 2,
messages: DeliveredMessages::new(MessageNonce::MAX)
},
]
.into_iter()
.collect()
),
None,
);
}
#[test]
fn inbound_lane_data_returns_correct_hint() {
let test_cases = vec![
// single relayer, multiple messages
(1, 128u8),
// multiple relayers, single message per relayer
(128u8, 128u8),
// several messages per relayer
(13u8, 128u8),
];
for (relayer_entries, messages_count) in test_cases {
let expected_size = InboundLaneData::<u8>::encoded_size_hint(relayer_entries as _);
let actual_size = InboundLaneData {
relayers: (1u8..=relayer_entries)
.map(|i| UnrewardedRelayer {
relayer: i,
messages: DeliveredMessages::new(i as _),
})
.collect(),
last_confirmed_nonce: messages_count as _,
}
.encode()
.len();
let difference = (expected_size.unwrap() as f64 - actual_size as f64).abs();
assert!(
difference / (std::cmp::min(actual_size, expected_size.unwrap()) as f64) < 0.1,
"Too large difference between actual ({actual_size}) and expected ({expected_size:?}) inbound lane data size. Test case: {relayer_entries}+{messages_count}",
);
}
}
#[test]
fn contains_result_works() {
let delivered_messages = DeliveredMessages { begin: 100, end: 150 };
assert!(!delivered_messages.contains_message(99));
assert!(delivered_messages.contains_message(100));
assert!(delivered_messages.contains_message(150));
assert!(!delivered_messages.contains_message(151));
}
#[test]
fn lane_id_debug_format_matches_inner_array_format() {
assert_eq!(format!("{:?}", LaneId([0, 0, 0, 0])), format!("{:?}", [0, 0, 0, 0]),);
}
}
@@ -0,0 +1,211 @@
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity Bridges Common is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
//! Primitives of messages module, that are used on the source chain.
use crate::{InboundLaneData, LaneId, MessageNonce, OutboundLaneData};
use crate::UnrewardedRelayer;
use bp_runtime::Size;
use frame_support::{Parameter, RuntimeDebug};
use sp_std::{
collections::{btree_map::BTreeMap, vec_deque::VecDeque},
fmt::Debug,
ops::RangeInclusive,
};
/// Number of messages, delivered by relayers.
pub type RelayersRewards<AccountId> = BTreeMap<AccountId, MessageNonce>;
/// Target chain API. Used by source chain to verify target chain proofs.
///
/// 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.
///
/// The `Payload` type here means the payload of the message that is sent from the
/// source chain to the target chain. The `AccountId` type here means the account
/// type used by the source chain.
pub trait TargetHeaderChain<Payload, AccountId> {
/// Error type.
type Error: Debug;
/// Proof that messages have been received by target chain.
type MessagesDeliveryProof: Parameter + Size;
/// Verify message payload before we accept it.
///
/// **CAUTION**: this is very important function. Incorrect implementation may lead
/// to stuck lanes and/or relayers loses.
///
/// The proper implementation must ensure that the delivery-transaction with this
/// payload would (at least) be accepted into target chain transaction pool AND
/// eventually will be successfully mined. The most obvious incorrect implementation
/// example would be implementation for BTC chain that accepts payloads larger than
/// 1MB. BTC nodes aren't accepting transactions that are larger than 1MB, so relayer
/// will be unable to craft valid transaction => this (and all subsequent) messages will
/// never be delivered.
fn verify_message(payload: &Payload) -> Result<(), Self::Error>;
/// Verify messages delivery proof and return lane && nonce of the latest received message.
fn verify_messages_delivery_proof(
proof: Self::MessagesDeliveryProof,
) -> Result<(LaneId, InboundLaneData<AccountId>), Self::Error>;
}
/// Lane message verifier.
///
/// Runtime developer may implement any additional validation logic over message-lane mechanism.
/// E.g. if lanes should have some security (e.g. you can only accept Lane1 messages from
/// Submitter1, Lane2 messages for those who has submitted first message to this lane, disable
/// Lane3 until some block, ...), then it may be built using this verifier.
///
/// Any fee requirements should also be enforced here.
pub trait LaneMessageVerifier<SenderOrigin, Payload> {
/// Error type.
type Error: Debug + Into<&'static str>;
/// Verify message payload and return Ok(()) if message is valid and allowed to be sent over the
/// lane.
fn verify_message(
submitter: &SenderOrigin,
lane: &LaneId,
outbound_data: &OutboundLaneData,
payload: &Payload,
) -> Result<(), Self::Error>;
}
/// Manages payments that are happening at the source chain during delivery confirmation
/// transaction.
pub trait DeliveryConfirmationPayments<AccountId> {
/// Error type.
type Error: Debug + Into<&'static str>;
/// Pay rewards for delivering messages to the given relayers.
///
/// The implementation may also choose to pay reward to the `confirmation_relayer`, which is
/// a relayer that has submitted delivery confirmation transaction.
///
/// Returns number of actually rewarded relayers.
fn pay_reward(
lane_id: LaneId,
messages_relayers: VecDeque<UnrewardedRelayer<AccountId>>,
confirmation_relayer: &AccountId,
received_range: &RangeInclusive<MessageNonce>,
) -> MessageNonce;
}
impl<AccountId> DeliveryConfirmationPayments<AccountId> for () {
type Error = &'static str;
fn pay_reward(
_lane_id: LaneId,
_messages_relayers: VecDeque<UnrewardedRelayer<AccountId>>,
_confirmation_relayer: &AccountId,
_received_range: &RangeInclusive<MessageNonce>,
) -> MessageNonce {
// this implementation is not rewarding relayers at all
0
}
}
/// Send message artifacts.
#[derive(Eq, RuntimeDebug, PartialEq)]
pub struct SendMessageArtifacts {
/// Nonce of the message.
pub nonce: MessageNonce,
}
/// Messages bridge API to be used from other pallets.
pub trait MessagesBridge<SenderOrigin, Payload> {
/// Error type.
type Error: Debug;
/// Send message over the bridge.
///
/// Returns unique message nonce or error if send has failed.
fn send_message(
sender: SenderOrigin,
lane: LaneId,
message: Payload,
) -> Result<SendMessageArtifacts, Self::Error>;
}
/// Bridge that does nothing when message is being sent.
#[derive(Eq, RuntimeDebug, PartialEq)]
pub struct NoopMessagesBridge;
impl<SenderOrigin, Payload> MessagesBridge<SenderOrigin, Payload> for NoopMessagesBridge {
type Error = &'static str;
fn send_message(
_sender: SenderOrigin,
_lane: LaneId,
_message: Payload,
) -> Result<SendMessageArtifacts, Self::Error> {
Ok(SendMessageArtifacts { nonce: 0 })
}
}
/// Structure that may be used in place of `TargetHeaderChain`, `LaneMessageVerifier` and
/// `MessageDeliveryAndDispatchPayment` on chains, where outbound messages are forbidden.
pub struct ForbidOutboundMessages;
/// Error message that is used in `ForbidOutboundMessages` implementation.
const ALL_OUTBOUND_MESSAGES_REJECTED: &str =
"This chain is configured to reject all outbound messages";
impl<Payload, AccountId> TargetHeaderChain<Payload, AccountId> for ForbidOutboundMessages {
type Error = &'static str;
type MessagesDeliveryProof = ();
fn verify_message(_payload: &Payload) -> Result<(), Self::Error> {
Err(ALL_OUTBOUND_MESSAGES_REJECTED)
}
fn verify_messages_delivery_proof(
_proof: Self::MessagesDeliveryProof,
) -> Result<(LaneId, InboundLaneData<AccountId>), Self::Error> {
Err(ALL_OUTBOUND_MESSAGES_REJECTED)
}
}
impl<SenderOrigin, Payload> LaneMessageVerifier<SenderOrigin, Payload> for ForbidOutboundMessages {
type Error = &'static str;
fn verify_message(
_submitter: &SenderOrigin,
_lane: &LaneId,
_outbound_data: &OutboundLaneData,
_payload: &Payload,
) -> Result<(), Self::Error> {
Err(ALL_OUTBOUND_MESSAGES_REJECTED)
}
}
impl<AccountId> DeliveryConfirmationPayments<AccountId> for ForbidOutboundMessages {
type Error = &'static str;
fn pay_reward(
_lane_id: LaneId,
_messages_relayers: VecDeque<UnrewardedRelayer<AccountId>>,
_confirmation_relayer: &AccountId,
_received_range: &RangeInclusive<MessageNonce>,
) -> MessageNonce {
0
}
}
@@ -0,0 +1,128 @@
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity Bridges Common is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
//! Storage keys of bridge messages pallet.
/// Name of the `OPERATING_MODE_VALUE_NAME` storage value.
pub const OPERATING_MODE_VALUE_NAME: &str = "PalletOperatingMode";
/// Name of the `OutboundMessages` storage map.
pub const OUTBOUND_MESSAGES_MAP_NAME: &str = "OutboundMessages";
/// Name of the `OutboundLanes` storage map.
pub const OUTBOUND_LANES_MAP_NAME: &str = "OutboundLanes";
/// Name of the `InboundLanes` storage map.
pub const INBOUND_LANES_MAP_NAME: &str = "InboundLanes";
use crate::{LaneId, MessageKey, MessageNonce};
use codec::Encode;
use frame_support::Blake2_128Concat;
use sp_core::storage::StorageKey;
/// Storage key of the `PalletOperatingMode` value in the runtime storage.
pub fn operating_mode_key(pallet_prefix: &str) -> StorageKey {
StorageKey(
bp_runtime::storage_value_final_key(
pallet_prefix.as_bytes(),
OPERATING_MODE_VALUE_NAME.as_bytes(),
)
.to_vec(),
)
}
/// Storage key of the outbound message in the runtime storage.
pub fn message_key(pallet_prefix: &str, lane: &LaneId, nonce: MessageNonce) -> StorageKey {
bp_runtime::storage_map_final_key::<Blake2_128Concat>(
pallet_prefix,
OUTBOUND_MESSAGES_MAP_NAME,
&MessageKey { lane_id: *lane, nonce }.encode(),
)
}
/// Storage key of the outbound message lane state in the runtime storage.
pub fn outbound_lane_data_key(pallet_prefix: &str, lane: &LaneId) -> StorageKey {
bp_runtime::storage_map_final_key::<Blake2_128Concat>(
pallet_prefix,
OUTBOUND_LANES_MAP_NAME,
&lane.encode(),
)
}
/// Storage key of the inbound message lane state in the runtime storage.
pub fn inbound_lane_data_key(pallet_prefix: &str, lane: &LaneId) -> StorageKey {
bp_runtime::storage_map_final_key::<Blake2_128Concat>(
pallet_prefix,
INBOUND_LANES_MAP_NAME,
&lane.encode(),
)
}
#[cfg(test)]
mod tests {
use super::*;
use hex_literal::hex;
#[test]
fn operating_mode_key_computed_properly() {
// If this test fails, then something has been changed in module storage that is possibly
// breaking all existing message relays.
let storage_key = operating_mode_key("BridgeMessages").0;
assert_eq!(
storage_key,
hex!("dd16c784ebd3390a9bc0357c7511ed010f4cf0917788d791142ff6c1f216e7b3").to_vec(),
"Unexpected storage key: {}",
hex::encode(&storage_key),
);
}
#[test]
fn storage_message_key_computed_properly() {
// If this test fails, then something has been changed in module storage that is breaking
// all previously crafted messages proofs.
let storage_key = message_key("BridgeMessages", &LaneId(*b"test"), 42).0;
assert_eq!(
storage_key,
hex!("dd16c784ebd3390a9bc0357c7511ed018a395e6242c6813b196ca31ed0547ea79446af0e09063bd4a7874aef8a997cec746573742a00000000000000").to_vec(),
"Unexpected storage key: {}",
hex::encode(&storage_key),
);
}
#[test]
fn outbound_lane_data_key_computed_properly() {
// If this test fails, then something has been changed in module storage that is breaking
// all previously crafted outbound lane state proofs.
let storage_key = outbound_lane_data_key("BridgeMessages", &LaneId(*b"test")).0;
assert_eq!(
storage_key,
hex!("dd16c784ebd3390a9bc0357c7511ed0196c246acb9b55077390e3ca723a0ca1f44a8995dd50b6657a037a7839304535b74657374").to_vec(),
"Unexpected storage key: {}",
hex::encode(&storage_key),
);
}
#[test]
fn inbound_lane_data_key_computed_properly() {
// If this test fails, then something has been changed in module storage that is breaking
// all previously crafted inbound lane state proofs.
let storage_key = inbound_lane_data_key("BridgeMessages", &LaneId(*b"test")).0;
assert_eq!(
storage_key,
hex!("dd16c784ebd3390a9bc0357c7511ed01e5f83cf83f2127eb47afdc35d6e43fab44a8995dd50b6657a037a7839304535b74657374").to_vec(),
"Unexpected storage key: {}",
hex::encode(&storage_key),
);
}
}
@@ -0,0 +1,200 @@
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity Bridges Common is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
//! Primitives of messages module, that are used on the target chain.
use crate::{LaneId, Message, MessageKey, MessageNonce, MessagePayload, OutboundLaneData};
use bp_runtime::{messages::MessageDispatchResult, Size};
use codec::{Decode, Encode, Error as CodecError};
use frame_support::{weights::Weight, Parameter, RuntimeDebug};
use scale_info::TypeInfo;
use sp_std::{collections::btree_map::BTreeMap, fmt::Debug, marker::PhantomData, prelude::*};
/// Proved messages from the source chain.
pub type ProvedMessages<Message> = BTreeMap<LaneId, ProvedLaneMessages<Message>>;
/// Proved messages from single lane of the source chain.
#[derive(RuntimeDebug, Encode, Decode, Clone, PartialEq, Eq, TypeInfo)]
pub struct ProvedLaneMessages<Message> {
/// Optional outbound lane state.
pub lane_state: Option<OutboundLaneData>,
/// Messages sent through this lane.
pub messages: Vec<Message>,
}
/// Message data with decoded dispatch payload.
#[derive(RuntimeDebug)]
pub struct DispatchMessageData<DispatchPayload> {
/// Result of dispatch payload decoding.
pub payload: Result<DispatchPayload, CodecError>,
}
/// Message with decoded dispatch payload.
#[derive(RuntimeDebug)]
pub struct DispatchMessage<DispatchPayload> {
/// Message key.
pub key: MessageKey,
/// Message data with decoded dispatch payload.
pub data: DispatchMessageData<DispatchPayload>,
}
/// Source chain API. Used by target chain, to verify source chain proofs.
///
/// 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 {
/// Error type.
type Error: Debug;
/// Proof that messages are sent from source chain. This may also include proof
/// of corresponding outbound lane states.
type MessagesProof: Parameter + Size;
/// Verify messages proof and return proved messages.
///
/// Returns error if either proof is incorrect, or the number of messages in the proof
/// is not matching the `messages_count`.
///
/// Messages vector is required to be sorted by nonce within each lane. Out-of-order
/// messages will be rejected.
///
/// The `messages_count` argument verification (sane limits) is supposed to be made
/// outside this function. This function only verifies that the proof declares exactly
/// `messages_count` messages.
fn verify_messages_proof(
proof: Self::MessagesProof,
messages_count: u32,
) -> Result<ProvedMessages<Message>, Self::Error>;
}
/// Called when inbound message is received.
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).
type DispatchPayload: Decode;
/// Fine-grained result of single message dispatch (for better diagnostic purposes)
type DispatchLevelResult: Clone + sp_std::fmt::Debug + Eq;
/// Estimate dispatch weight.
///
/// 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
/// `From<Chain>InboundLaneApi::message_details().dispatch_weight` call.
fn dispatch_weight(message: &mut DispatchMessage<Self::DispatchPayload>) -> Weight;
/// Called when inbound message is received.
///
/// It is up to the implementers of this trait to determine whether the message
/// is invalid (i.e. improperly encoded, has too large weight, ...) or not.
fn dispatch(
message: DispatchMessage<Self::DispatchPayload>,
) -> MessageDispatchResult<Self::DispatchLevelResult>;
}
/// Manages payments that are happening at the target chain during message delivery transaction.
pub trait DeliveryPayments<AccountId> {
/// Error type.
type Error: Debug + Into<&'static str>;
/// Pay rewards for delivering messages to the given relayer.
///
/// This method is called during message delivery transaction which has been submitted
/// by the `relayer`. The transaction brings `total_messages` messages but only
/// `valid_messages` have been accepted. The post-dispatch transaction weight is the
/// `actual_weight`.
fn pay_reward(
relayer: AccountId,
total_messages: MessageNonce,
valid_messages: MessageNonce,
actual_weight: Weight,
);
}
impl<Message> Default for ProvedLaneMessages<Message> {
fn default() -> Self {
ProvedLaneMessages { lane_state: None, messages: Vec::new() }
}
}
impl<DispatchPayload: Decode> From<Message> for DispatchMessage<DispatchPayload> {
fn from(message: Message) -> Self {
DispatchMessage { key: message.key, data: message.payload.into() }
}
}
impl<DispatchPayload: Decode> From<MessagePayload> for DispatchMessageData<DispatchPayload> {
fn from(payload: MessagePayload) -> Self {
DispatchMessageData { payload: DispatchPayload::decode(&mut &payload[..]) }
}
}
impl<AccountId> DeliveryPayments<AccountId> for () {
type Error = &'static str;
fn pay_reward(
_relayer: AccountId,
_total_messages: MessageNonce,
_valid_messages: MessageNonce,
_actual_weight: Weight,
) {
// this implementation is not rewarding relayer at all
}
}
/// Structure that may be used in place of `SourceHeaderChain` and `MessageDispatch` on chains,
/// where inbound messages are forbidden.
pub struct ForbidInboundMessages<MessagesProof, DispatchPayload>(
PhantomData<(MessagesProof, DispatchPayload)>,
);
/// Error message that is used in `ForbidOutboundMessages` implementation.
const ALL_INBOUND_MESSAGES_REJECTED: &str =
"This chain is configured to reject all inbound messages";
impl<MessagesProof: Parameter + Size, DispatchPayload> SourceHeaderChain
for ForbidInboundMessages<MessagesProof, DispatchPayload>
{
type Error = &'static str;
type MessagesProof = MessagesProof;
fn verify_messages_proof(
_proof: Self::MessagesProof,
_messages_count: u32,
) -> Result<ProvedMessages<Message>, Self::Error> {
Err(ALL_INBOUND_MESSAGES_REJECTED)
}
}
impl<MessagesProof, DispatchPayload: Decode> MessageDispatch
for ForbidInboundMessages<MessagesProof, DispatchPayload>
{
type DispatchPayload = DispatchPayload;
type DispatchLevelResult = ();
fn dispatch_weight(_message: &mut DispatchMessage<Self::DispatchPayload>) -> Weight {
Weight::MAX
}
fn dispatch(
_: DispatchMessage<Self::DispatchPayload>,
) -> MessageDispatchResult<Self::DispatchLevelResult> {
MessageDispatchResult { unspent_weight: Weight::zero(), dispatch_level_result: () }
}
}