referrerpolicy=no-referrer-when-downgrade

substrate_relay_helper/messages/
target.rs

1// Copyright 2019-2021 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//! Substrate client as Substrate messages target. The chain we connect to should have
18//! runtime that implements `<BridgedChainName>HeaderApi` to allow bridging with
19//! `<BridgedName>` chain.
20
21use crate::{
22	messages::{
23		source::{
24			ensure_messages_pallet_active, read_client_state_from_both_chains,
25			SubstrateMessagesProof,
26		},
27		BatchProofTransaction, MessageLaneAdapter, ReceiveMessagesProofCallBuilder,
28		SubstrateMessageLane,
29	},
30	on_demand::OnDemandRelay,
31	proofs::to_raw_storage_proof,
32	TransactionParams,
33};
34
35use async_std::sync::Arc;
36use async_trait::async_trait;
37use bp_messages::{
38	source_chain::FromBridgedChainMessagesDeliveryProof, storage_keys::inbound_lane_data_key,
39	ChainWithMessages as _, LaneState, MessageNonce, UnrewardedRelayer, UnrewardedRelayersState,
40};
41use codec::Decode;
42use messages_relay::{
43	message_lane::{MessageLane, SourceHeaderIdOf, TargetHeaderIdOf},
44	message_lane_loop::{NoncesSubmitArtifacts, TargetClient, TargetClientState},
45};
46use relay_substrate_client::{
47	AccountIdOf, AccountKeyPairOf, BalanceOf, CallOf, Chain, Client, Error as SubstrateError,
48	HashOf, TransactionEra, TransactionTracker, UnsignedTransaction,
49};
50use relay_utils::relay_loop::Client as RelayClient;
51use sp_core::Pair;
52use std::{collections::VecDeque, convert::TryFrom, ops::RangeInclusive};
53
54/// Message receiving proof returned by the target Substrate node.
55pub type SubstrateMessagesDeliveryProof<C, L> =
56	(UnrewardedRelayersState, FromBridgedChainMessagesDeliveryProof<HashOf<C>, L>);
57
58/// Inbound lane data - for backwards compatibility with `bp_messages::InboundLaneData` which has
59/// additional `lane_state` attribute.
60///
61/// TODO: remove - https://github.com/paritytech/polkadot-sdk/issues/5923
62#[derive(Decode)]
63struct LegacyInboundLaneData<RelayerId> {
64	relayers: VecDeque<UnrewardedRelayer<RelayerId>>,
65	last_confirmed_nonce: MessageNonce,
66}
67impl<RelayerId> Default for LegacyInboundLaneData<RelayerId> {
68	fn default() -> Self {
69		let full = bp_messages::InboundLaneData::default();
70		Self { relayers: full.relayers, last_confirmed_nonce: full.last_confirmed_nonce }
71	}
72}
73
74impl<RelayerId> LegacyInboundLaneData<RelayerId> {
75	pub fn last_delivered_nonce(self) -> MessageNonce {
76		bp_messages::InboundLaneData {
77			relayers: self.relayers,
78			last_confirmed_nonce: self.last_confirmed_nonce,
79			// we don't care about the state here
80			state: LaneState::Opened,
81		}
82		.last_delivered_nonce()
83	}
84}
85
86impl<RelayerId> From<LegacyInboundLaneData<RelayerId>> for UnrewardedRelayersState {
87	fn from(value: LegacyInboundLaneData<RelayerId>) -> Self {
88		(&bp_messages::InboundLaneData {
89			relayers: value.relayers,
90			last_confirmed_nonce: value.last_confirmed_nonce,
91			// we don't care about the state here
92			state: LaneState::Opened,
93		})
94			.into()
95	}
96}
97
98/// Substrate client as Substrate messages target.
99pub struct SubstrateMessagesTarget<P: SubstrateMessageLane, SourceClnt, TargetClnt> {
100	target_client: TargetClnt,
101	source_client: SourceClnt,
102	lane_id: P::LaneId,
103	relayer_id_at_source: AccountIdOf<P::SourceChain>,
104	transaction_params: Option<TransactionParams<AccountKeyPairOf<P::TargetChain>>>,
105	source_to_target_headers_relay: Option<Arc<dyn OnDemandRelay<P::SourceChain, P::TargetChain>>>,
106}
107
108impl<P, SourceClnt, TargetClnt> SubstrateMessagesTarget<P, SourceClnt, TargetClnt>
109where
110	P: SubstrateMessageLane,
111	TargetClnt: Client<P::TargetChain>,
112{
113	/// Create new Substrate headers target.
114	pub fn new(
115		target_client: TargetClnt,
116		source_client: SourceClnt,
117		lane_id: P::LaneId,
118		relayer_id_at_source: AccountIdOf<P::SourceChain>,
119		transaction_params: Option<TransactionParams<AccountKeyPairOf<P::TargetChain>>>,
120		source_to_target_headers_relay: Option<
121			Arc<dyn OnDemandRelay<P::SourceChain, P::TargetChain>>,
122		>,
123	) -> Self {
124		SubstrateMessagesTarget {
125			target_client,
126			source_client,
127			lane_id,
128			relayer_id_at_source,
129			transaction_params,
130			source_to_target_headers_relay,
131		}
132	}
133
134	/// Read inbound lane state from the on-chain storage at given block.
135	async fn inbound_lane_data(
136		&self,
137		id: TargetHeaderIdOf<MessageLaneAdapter<P>>,
138	) -> Result<Option<LegacyInboundLaneData<AccountIdOf<P::SourceChain>>>, SubstrateError> {
139		self.target_client
140			.storage_value(
141				id.hash(),
142				inbound_lane_data_key(
143					P::SourceChain::WITH_CHAIN_MESSAGES_PALLET_NAME,
144					&self.lane_id,
145				),
146			)
147			.await
148	}
149
150	/// Ensure that the messages pallet at target chain is active.
151	async fn ensure_pallet_active(&self) -> Result<(), SubstrateError> {
152		ensure_messages_pallet_active::<P::TargetChain, P::SourceChain, _>(&self.target_client)
153			.await
154	}
155}
156
157impl<P: SubstrateMessageLane, SourceClnt: Clone, TargetClnt: Clone> Clone
158	for SubstrateMessagesTarget<P, SourceClnt, TargetClnt>
159{
160	fn clone(&self) -> Self {
161		Self {
162			target_client: self.target_client.clone(),
163			source_client: self.source_client.clone(),
164			lane_id: self.lane_id,
165			relayer_id_at_source: self.relayer_id_at_source.clone(),
166			transaction_params: self.transaction_params.clone(),
167			source_to_target_headers_relay: self.source_to_target_headers_relay.clone(),
168		}
169	}
170}
171
172#[async_trait]
173impl<
174		P: SubstrateMessageLane,
175		SourceClnt: Client<P::SourceChain>,
176		TargetClnt: Client<P::TargetChain>,
177	> RelayClient for SubstrateMessagesTarget<P, SourceClnt, TargetClnt>
178{
179	type Error = SubstrateError;
180
181	async fn reconnect(&mut self) -> Result<(), SubstrateError> {
182		// since the client calls RPC methods on both sides, we need to reconnect both
183		self.target_client.reconnect().await?;
184		self.source_client.reconnect().await?;
185
186		// call reconnect on on-demand headers relay, because we may use different chains there
187		// and the error that has lead to reconnect may have came from those other chains
188		// (see `require_source_header_on_target`)
189		//
190		// this may lead to multiple reconnects to the same node during the same call and it
191		// needs to be addressed in the future
192		// TODO: https://github.com/paritytech/parity-bridges-common/issues/1928
193		if let Some(ref mut source_to_target_headers_relay) = self.source_to_target_headers_relay {
194			source_to_target_headers_relay.reconnect().await?;
195		}
196
197		Ok(())
198	}
199}
200
201#[async_trait]
202impl<
203		P: SubstrateMessageLane,
204		SourceClnt: Client<P::SourceChain>,
205		TargetClnt: Client<P::TargetChain>,
206	> TargetClient<MessageLaneAdapter<P>> for SubstrateMessagesTarget<P, SourceClnt, TargetClnt>
207where
208	AccountIdOf<P::TargetChain>: From<<AccountKeyPairOf<P::TargetChain> as Pair>::Public>,
209	BalanceOf<P::SourceChain>: TryFrom<BalanceOf<P::TargetChain>>,
210{
211	type BatchTransaction =
212		BatchProofTransaction<P::TargetChain, P::SourceChain, P::TargetBatchCallBuilder>;
213	type TransactionTracker = TransactionTracker<P::TargetChain, TargetClnt>;
214
215	async fn state(&self) -> Result<TargetClientState<MessageLaneAdapter<P>>, SubstrateError> {
216		// we can't continue to deliver confirmations if source node is out of sync, because
217		// it may have already received confirmations that we're going to deliver
218		//
219		// we can't continue to deliver messages if target node is out of sync, because
220		// it may have already received (some of) messages that we're going to deliver
221		self.source_client.ensure_synced().await?;
222		self.target_client.ensure_synced().await?;
223		// we can't relay messages if messages pallet at target chain is halted
224		self.ensure_pallet_active().await?;
225
226		read_client_state_from_both_chains(&self.target_client, &self.source_client).await
227	}
228
229	async fn latest_received_nonce(
230		&self,
231		id: TargetHeaderIdOf<MessageLaneAdapter<P>>,
232	) -> Result<(TargetHeaderIdOf<MessageLaneAdapter<P>>, MessageNonce), SubstrateError> {
233		// lane data missing from the storage is fine until first message is received
234		let latest_received_nonce = self
235			.inbound_lane_data(id)
236			.await?
237			.map(|data| data.last_delivered_nonce())
238			.unwrap_or(0);
239		Ok((id, latest_received_nonce))
240	}
241
242	async fn latest_confirmed_received_nonce(
243		&self,
244		id: TargetHeaderIdOf<MessageLaneAdapter<P>>,
245	) -> Result<(TargetHeaderIdOf<MessageLaneAdapter<P>>, MessageNonce), SubstrateError> {
246		// lane data missing from the storage is fine until first message is received
247		let last_confirmed_nonce = self
248			.inbound_lane_data(id)
249			.await?
250			.map(|data| data.last_confirmed_nonce)
251			.unwrap_or(0);
252		Ok((id, last_confirmed_nonce))
253	}
254
255	async fn unrewarded_relayers_state(
256		&self,
257		id: TargetHeaderIdOf<MessageLaneAdapter<P>>,
258	) -> Result<(TargetHeaderIdOf<MessageLaneAdapter<P>>, UnrewardedRelayersState), SubstrateError>
259	{
260		let inbound_lane_data =
261			self.inbound_lane_data(id).await?.unwrap_or(LegacyInboundLaneData::default());
262		Ok((id, inbound_lane_data.into()))
263	}
264
265	async fn prove_messages_receiving(
266		&self,
267		id: TargetHeaderIdOf<MessageLaneAdapter<P>>,
268	) -> Result<
269		(
270			TargetHeaderIdOf<MessageLaneAdapter<P>>,
271			<MessageLaneAdapter<P> as MessageLane>::MessagesReceivingProof,
272		),
273		SubstrateError,
274	> {
275		let (id, relayers_state) = self.unrewarded_relayers_state(id).await?;
276		let storage_keys = vec![inbound_lane_data_key(
277			P::SourceChain::WITH_CHAIN_MESSAGES_PALLET_NAME,
278			&self.lane_id,
279		)];
280
281		let storage_proof =
282			self.target_client.prove_storage(id.hash(), storage_keys.clone()).await?;
283		let proof = FromBridgedChainMessagesDeliveryProof {
284			bridged_header_hash: id.1,
285			storage_proof: to_raw_storage_proof::<P::TargetChain>(storage_proof),
286			lane: self.lane_id,
287		};
288		Ok((id, (relayers_state, proof)))
289	}
290
291	async fn submit_messages_proof(
292		&self,
293		maybe_batch_tx: Option<Self::BatchTransaction>,
294		_generated_at_header: SourceHeaderIdOf<MessageLaneAdapter<P>>,
295		nonces: RangeInclusive<MessageNonce>,
296		proof: <MessageLaneAdapter<P> as MessageLane>::MessagesProof,
297	) -> Result<NoncesSubmitArtifacts<Self::TransactionTracker>, SubstrateError> {
298		let messages_proof_call = make_messages_delivery_call::<P>(
299			self.relayer_id_at_source.clone(),
300			proof.1.nonces_start..=proof.1.nonces_end,
301			proof,
302			maybe_batch_tx.is_none(),
303		);
304		let final_call = match maybe_batch_tx {
305			Some(batch_tx) => batch_tx.append_call_and_build(messages_proof_call),
306			None => messages_proof_call,
307		};
308
309		let transaction_params = self.transaction_params.clone().map(Ok).unwrap_or_else(|| {
310			// this error shall never happen in practice, so it not deserves
311			// a separate error variant
312			Err(SubstrateError::Custom(format!(
313				"Cannot sign transaction of {} chain",
314				P::TargetChain::NAME,
315			)))
316		})?;
317		let tx_tracker = self
318			.target_client
319			.submit_and_watch_signed_extrinsic(
320				&transaction_params.signer,
321				move |best_block_id, transaction_nonce| {
322					Ok(UnsignedTransaction::new(final_call.into(), transaction_nonce)
323						.era(TransactionEra::new(best_block_id, transaction_params.mortality)))
324				},
325			)
326			.await?;
327		Ok(NoncesSubmitArtifacts { nonces, tx_tracker })
328	}
329
330	async fn require_source_header_on_target(
331		&self,
332		id: SourceHeaderIdOf<MessageLaneAdapter<P>>,
333	) -> Result<Option<Self::BatchTransaction>, SubstrateError> {
334		if let Some(ref source_to_target_headers_relay) = self.source_to_target_headers_relay {
335			if let Some(batch_tx) =
336				BatchProofTransaction::new(source_to_target_headers_relay.clone(), id.0).await?
337			{
338				return Ok(Some(batch_tx))
339			}
340
341			source_to_target_headers_relay.require_more_headers(id.0).await;
342		}
343
344		Ok(None)
345	}
346}
347
348/// Make messages delivery call from given proof.
349fn make_messages_delivery_call<P: SubstrateMessageLane>(
350	relayer_id_at_source: AccountIdOf<P::SourceChain>,
351	nonces: RangeInclusive<MessageNonce>,
352	proof: SubstrateMessagesProof<P::SourceChain, P::LaneId>,
353	trace_call: bool,
354) -> CallOf<P::TargetChain> {
355	let messages_count = nonces.end() - nonces.start() + 1;
356	let dispatch_weight = proof.0;
357	P::ReceiveMessagesProofCallBuilder::build_receive_messages_proof_call(
358		relayer_id_at_source,
359		proof,
360		messages_count as _,
361		dispatch_weight,
362		trace_call,
363	)
364}
365
366#[cfg(test)]
367mod tests {
368	use super::*;
369	use bp_messages::{DeliveredMessages, UnrewardedRelayer};
370	use codec::Encode;
371
372	#[test]
373	fn inbound_lane_data_wrapper_is_compatible() {
374		let bytes_without_state =
375			vec![4, 0, 2, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0];
376		let bytes_with_state = {
377			// add state byte `bp_messages::LaneState::Opened`
378			let mut b = bytes_without_state.clone();
379			b.push(0);
380			b
381		};
382
383		let full = bp_messages::InboundLaneData::<u8> {
384			relayers: vec![UnrewardedRelayer {
385				relayer: Default::default(),
386				messages: DeliveredMessages { begin: 2, end: 5 },
387			}]
388			.into_iter()
389			.collect(),
390			last_confirmed_nonce: 6,
391			state: bp_messages::LaneState::Opened,
392		};
393		assert_eq!(full.encode(), bytes_with_state);
394		assert_ne!(full.encode(), bytes_without_state);
395
396		// decode from `bytes_with_state`
397		let decoded: LegacyInboundLaneData<u8> =
398			Decode::decode(&mut &bytes_with_state[..]).unwrap();
399		assert_eq!(full.relayers, decoded.relayers);
400		assert_eq!(full.last_confirmed_nonce, decoded.last_confirmed_nonce);
401		assert_eq!(full.last_delivered_nonce(), decoded.last_delivered_nonce());
402
403		// decode from `bytes_without_state`
404		let decoded: LegacyInboundLaneData<u8> =
405			Decode::decode(&mut &bytes_without_state[..]).unwrap();
406		assert_eq!(full.relayers, decoded.relayers);
407		assert_eq!(full.last_confirmed_nonce, decoded.last_confirmed_nonce);
408		assert_eq!(full.last_delivered_nonce(), decoded.last_delivered_nonce());
409	}
410}