bp_messages/target_chain.rs
1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Parity Bridges Common.
3
4// Parity Bridges Common is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Parity Bridges Common is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
16
17//! Primitives of messages module, that are used on the target chain.
18
19use crate::{Message, MessageKey, MessageNonce, MessagePayload, OutboundLaneData};
20
21use bp_runtime::{messages::MessageDispatchResult, raw_storage_proof_size, RawStorageProof, Size};
22use codec::{Decode, DecodeWithMemTracking, Encode, Error as CodecError};
23use frame_support::weights::Weight;
24use scale_info::TypeInfo;
25use sp_std::{fmt::Debug, marker::PhantomData, prelude::*};
26
27/// Messages proof from bridged chain.
28///
29/// It contains everything required to prove that bridged (source) chain has
30/// sent us some messages:
31///
32/// - hash of finalized header;
33///
34/// - storage proof of messages and (optionally) outbound lane state;
35///
36/// - lane id;
37///
38/// - nonces (inclusive range) of messages which are included in this proof.
39#[derive(Clone, Decode, DecodeWithMemTracking, Encode, Eq, PartialEq, Debug, TypeInfo)]
40pub struct FromBridgedChainMessagesProof<BridgedHeaderHash, Lane> {
41 /// Hash of the finalized bridged header the proof is for.
42 pub bridged_header_hash: BridgedHeaderHash,
43 /// A storage trie proof of messages being delivered.
44 pub storage_proof: RawStorageProof,
45 /// Messages in this proof are sent over this lane.
46 pub lane: Lane,
47 /// Nonce of the first message being delivered.
48 pub nonces_start: MessageNonce,
49 /// Nonce of the last message being delivered.
50 pub nonces_end: MessageNonce,
51}
52
53impl<BridgedHeaderHash, Lane> Size for FromBridgedChainMessagesProof<BridgedHeaderHash, Lane> {
54 fn size(&self) -> u32 {
55 use frame_support::sp_runtime::SaturatedConversion;
56 raw_storage_proof_size(&self.storage_proof).saturated_into()
57 }
58}
59
60/// Proved messages from the source chain.
61pub type ProvedMessages<LaneId, Message> = (LaneId, ProvedLaneMessages<Message>);
62
63/// Proved messages from single lane of the source chain.
64#[derive(Debug, Encode, Decode, Clone, PartialEq, Eq, TypeInfo)]
65pub struct ProvedLaneMessages<Message> {
66 /// Optional outbound lane state.
67 pub lane_state: Option<OutboundLaneData>,
68 /// Messages sent through this lane.
69 pub messages: Vec<Message>,
70}
71
72/// Message data with decoded dispatch payload.
73#[derive(Debug)]
74pub struct DispatchMessageData<DispatchPayload> {
75 /// Result of dispatch payload decoding.
76 pub payload: Result<DispatchPayload, CodecError>,
77}
78
79/// Message with decoded dispatch payload.
80#[derive(Debug)]
81pub struct DispatchMessage<DispatchPayload, LaneId: Encode> {
82 /// Message key.
83 pub key: MessageKey<LaneId>,
84 /// Message data with decoded dispatch payload.
85 pub data: DispatchMessageData<DispatchPayload>,
86}
87
88/// Called when inbound message is received.
89pub trait MessageDispatch {
90 /// Decoded message payload type. Valid message may contain invalid payload. In this case
91 /// message is delivered, but dispatch fails. Therefore, two separate types of payload
92 /// (opaque `MessagePayload` used in delivery and this `DispatchPayload` used in dispatch).
93 type DispatchPayload: Decode;
94
95 /// Fine-grained result of single message dispatch (for better diagnostic purposes)
96 type DispatchLevelResult: Clone + sp_std::fmt::Debug + Eq;
97
98 /// Lane identifier type.
99 type LaneId: Encode;
100
101 /// Returns `true` if dispatcher is ready to accept additional messages. The `false` should
102 /// be treated as a hint by both dispatcher and its consumers - i.e. dispatcher shall not
103 /// simply drop messages if it returns `false`. The consumer may still call the `dispatch`
104 /// if dispatcher has returned `false`.
105 ///
106 /// We check it in the messages delivery transaction prologue. So if it becomes `false`
107 /// after some portion of messages is already dispatched, it doesn't fail the whole transaction.
108 fn is_active(lane: Self::LaneId) -> bool;
109
110 /// Estimate dispatch weight.
111 ///
112 /// This function must return correct upper bound of dispatch weight. The return value
113 /// of this function is expected to match return value of the corresponding
114 /// `From<Chain>InboundLaneApi::message_details().dispatch_weight` call.
115 fn dispatch_weight(
116 message: &mut DispatchMessage<Self::DispatchPayload, Self::LaneId>,
117 ) -> Weight;
118
119 /// Called when inbound message is received.
120 ///
121 /// It is up to the implementers of this trait to determine whether the message
122 /// is invalid (i.e. improperly encoded, has too large weight, ...) or not.
123 fn dispatch(
124 message: DispatchMessage<Self::DispatchPayload, Self::LaneId>,
125 ) -> MessageDispatchResult<Self::DispatchLevelResult>;
126}
127
128/// Manages payments that are happening at the target chain during message delivery transaction.
129pub trait DeliveryPayments<AccountId> {
130 /// Error type.
131 type Error: Debug + Into<&'static str>;
132
133 /// Pay rewards for delivering messages to the given relayer.
134 ///
135 /// This method is called during message delivery transaction which has been submitted
136 /// by the `relayer`. The transaction brings `total_messages` messages but only
137 /// `valid_messages` have been accepted. The post-dispatch transaction weight is the
138 /// `actual_weight`.
139 fn pay_reward(
140 relayer: AccountId,
141 total_messages: MessageNonce,
142 valid_messages: MessageNonce,
143 actual_weight: Weight,
144 );
145}
146
147impl<Message> Default for ProvedLaneMessages<Message> {
148 fn default() -> Self {
149 ProvedLaneMessages { lane_state: None, messages: Vec::new() }
150 }
151}
152
153impl<DispatchPayload: Decode, LaneId: Encode> From<Message<LaneId>>
154 for DispatchMessage<DispatchPayload, LaneId>
155{
156 fn from(message: Message<LaneId>) -> Self {
157 DispatchMessage { key: message.key, data: message.payload.into() }
158 }
159}
160
161impl<DispatchPayload: Decode> From<MessagePayload> for DispatchMessageData<DispatchPayload> {
162 fn from(payload: MessagePayload) -> Self {
163 DispatchMessageData { payload: DispatchPayload::decode(&mut &payload[..]) }
164 }
165}
166
167impl<AccountId> DeliveryPayments<AccountId> for () {
168 type Error = &'static str;
169
170 fn pay_reward(
171 _relayer: AccountId,
172 _total_messages: MessageNonce,
173 _valid_messages: MessageNonce,
174 _actual_weight: Weight,
175 ) {
176 // this implementation is not rewarding relayer at all
177 }
178}
179
180/// Structure that may be used in place of `MessageDispatch` on chains,
181/// where inbound messages are forbidden.
182pub struct ForbidInboundMessages<DispatchPayload, LaneId>(PhantomData<(DispatchPayload, LaneId)>);
183
184impl<DispatchPayload: Decode, LaneId: Encode> MessageDispatch
185 for ForbidInboundMessages<DispatchPayload, LaneId>
186{
187 type DispatchPayload = DispatchPayload;
188 type DispatchLevelResult = ();
189 type LaneId = LaneId;
190
191 fn is_active(_: LaneId) -> bool {
192 false
193 }
194
195 fn dispatch_weight(
196 _message: &mut DispatchMessage<Self::DispatchPayload, Self::LaneId>,
197 ) -> Weight {
198 Weight::MAX
199 }
200
201 fn dispatch(
202 _: DispatchMessage<Self::DispatchPayload, Self::LaneId>,
203 ) -> MessageDispatchResult<Self::DispatchLevelResult> {
204 MessageDispatchResult { unspent_weight: Weight::zero(), dispatch_level_result: () }
205 }
206}