referrerpolicy=no-referrer-when-downgrade
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// 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 for exposing the messages relaying functionality in the CLI.

use crate::{
	cli::{bridge::*, chain_schema::*, HexLaneId, PrometheusParams},
	messages::MessagesRelayParams,
	TransactionParams,
};

use async_trait::async_trait;
use sp_core::Pair;
use structopt::StructOpt;

use bp_messages::MessageNonce;
use bp_runtime::HeaderIdProvider;
use relay_substrate_client::{
	AccountIdOf, AccountKeyPairOf, BalanceOf, Chain, ChainWithRuntimeVersion,
	ChainWithTransactions, Client,
};
use relay_utils::UniqueSaturatedInto;
use sp_runtime::traits::TryConvert;

/// Messages relaying params.
#[derive(StructOpt)]
pub struct RelayMessagesParams {
	/// Hex-encoded lane id that should be served by the relay.
	#[structopt(long)]
	lane: HexLaneId,
	#[structopt(flatten)]
	source: SourceConnectionParams,
	#[structopt(flatten)]
	source_sign: SourceSigningParams,
	#[structopt(flatten)]
	target: TargetConnectionParams,
	#[structopt(flatten)]
	target_sign: TargetSigningParams,
	#[structopt(flatten)]
	prometheus_params: PrometheusParams,
}

/// Messages range relaying params.
#[derive(StructOpt)]
pub struct RelayMessagesRangeParams {
	/// Number of the source chain header that we will use to prepare a messages proof.
	/// This header must be previously proved to the target chain.
	#[structopt(long)]
	at_source_block: u128,
	/// Hex-encoded lane id that should be served by the relay.
	#[structopt(long)]
	lane: HexLaneId,
	/// Nonce (inclusive) of the first message to relay.
	#[structopt(long)]
	messages_start: MessageNonce,
	/// Nonce (inclusive) of the last message to relay.
	#[structopt(long)]
	messages_end: MessageNonce,
	/// Whether the outbound lane state proof should be included into transaction.
	#[structopt(long)]
	outbound_state_proof_required: bool,
	#[structopt(flatten)]
	source: SourceConnectionParams,
	#[structopt(flatten)]
	source_sign: SourceSigningParams,
	#[structopt(flatten)]
	target: TargetConnectionParams,
	#[structopt(flatten)]
	target_sign: TargetSigningParams,
}

/// Messages delivery confirmation relaying params.
#[derive(StructOpt)]
pub struct RelayMessagesDeliveryConfirmationParams {
	/// Number of the target chain header that we will use to prepare a messages
	/// delivery proof. This header must be previously proved to the source chain.
	#[structopt(long)]
	at_target_block: u128,
	/// Hex-encoded lane id that should be served by the relay.
	#[structopt(long)]
	lane: HexLaneId,
	#[structopt(flatten)]
	source: SourceConnectionParams,
	#[structopt(flatten)]
	source_sign: SourceSigningParams,
	#[structopt(flatten)]
	target: TargetConnectionParams,
}

/// Trait used for relaying messages between 2 chains.
#[async_trait]
pub trait MessagesRelayer: MessagesCliBridge
where
	Self::Source: ChainWithTransactions + ChainWithRuntimeVersion,
	AccountIdOf<Self::Source>: From<<AccountKeyPairOf<Self::Source> as Pair>::Public>,
	AccountIdOf<Self::Target>: From<<AccountKeyPairOf<Self::Target> as Pair>::Public>,
	BalanceOf<Self::Source>: TryFrom<BalanceOf<Self::Target>>,
{
	/// Start relaying messages.
	async fn relay_messages(data: RelayMessagesParams) -> anyhow::Result<()> {
		let source_client = data.source.into_client::<Self::Source>().await?;
		let source_sign = data.source_sign.to_keypair::<Self::Source>()?;
		let source_transactions_mortality = data.source_sign.transactions_mortality()?;
		let target_client = data.target.into_client::<Self::Target>().await?;
		let target_sign = data.target_sign.to_keypair::<Self::Target>()?;
		let target_transactions_mortality = data.target_sign.transactions_mortality()?;
		let lane_id = HexLaneId::try_convert(data.lane).map_err(|invalid_lane_id| {
			anyhow::format_err!("Invalid laneId: {:?}!", invalid_lane_id)
		})?;

		Self::start_relay_guards(&target_client, target_client.can_start_version_guard()).await?;

		crate::messages::run::<Self::MessagesLane, _, _>(MessagesRelayParams {
			source_client,
			source_transaction_params: TransactionParams {
				signer: source_sign,
				mortality: source_transactions_mortality,
			},
			target_client,
			target_transaction_params: TransactionParams {
				signer: target_sign,
				mortality: target_transactions_mortality,
			},
			source_to_target_headers_relay: None,
			target_to_source_headers_relay: None,
			lane_id,
			limits: Self::maybe_messages_limits(),
			metrics_params: data.prometheus_params.into_metrics_params()?,
		})
		.await
		.map_err(|e| anyhow::format_err!("{}", e))
	}

	/// Relay a consequitive range of messages.
	async fn relay_messages_range(data: RelayMessagesRangeParams) -> anyhow::Result<()> {
		let source_client = data.source.into_client::<Self::Source>().await?;
		let target_client = data.target.into_client::<Self::Target>().await?;
		let source_sign = data.source_sign.to_keypair::<Self::Source>()?;
		let source_transactions_mortality = data.source_sign.transactions_mortality()?;
		let target_sign = data.target_sign.to_keypair::<Self::Target>()?;
		let target_transactions_mortality = data.target_sign.transactions_mortality()?;
		let lane_id = HexLaneId::try_convert(data.lane).map_err(|invalid_lane_id| {
			anyhow::format_err!("Invalid laneId: {:?}!", invalid_lane_id)
		})?;

		let at_source_block = source_client
			.header_by_number(data.at_source_block.unique_saturated_into())
			.await
			.map_err(|e| {
				log::trace!(
					target: "bridge",
					"Failed to read {} header with number {}: {e:?}",
					Self::Source::NAME,
					data.at_source_block,
				);
				anyhow::format_err!("The command has failed")
			})?
			.id();

		crate::messages::relay_messages_range::<Self::MessagesLane>(
			source_client,
			target_client,
			TransactionParams { signer: source_sign, mortality: source_transactions_mortality },
			TransactionParams { signer: target_sign, mortality: target_transactions_mortality },
			at_source_block,
			lane_id,
			data.messages_start..=data.messages_end,
			data.outbound_state_proof_required,
		)
		.await
	}

	/// Relay a messages delivery confirmation.
	async fn relay_messages_delivery_confirmation(
		data: RelayMessagesDeliveryConfirmationParams,
	) -> anyhow::Result<()> {
		let source_client = data.source.into_client::<Self::Source>().await?;
		let target_client = data.target.into_client::<Self::Target>().await?;
		let source_sign = data.source_sign.to_keypair::<Self::Source>()?;
		let source_transactions_mortality = data.source_sign.transactions_mortality()?;
		let lane_id = HexLaneId::try_convert(data.lane).map_err(|invalid_lane_id| {
			anyhow::format_err!("Invalid laneId: {:?}!", invalid_lane_id)
		})?;

		let at_target_block = target_client
			.header_by_number(data.at_target_block.unique_saturated_into())
			.await
			.map_err(|e| {
				log::trace!(
					target: "bridge",
					"Failed to read {} header with number {}: {e:?}",
					Self::Target::NAME,
					data.at_target_block,
				);
				anyhow::format_err!("The command has failed")
			})?
			.id();

		crate::messages::relay_messages_delivery_confirmation::<Self::MessagesLane>(
			source_client,
			target_client,
			TransactionParams { signer: source_sign, mortality: source_transactions_mortality },
			at_target_block,
			lane_id,
		)
		.await
	}

	/// Add relay guards if required.
	async fn start_relay_guards(
		target_client: &impl Client<Self::Target>,
		enable_version_guard: bool,
	) -> relay_substrate_client::Result<()> {
		if enable_version_guard {
			relay_substrate_client::guard::abort_on_spec_version_change(
				target_client.clone(),
				target_client.simple_runtime_version().await?.spec_version,
			);
		}
		Ok(())
	}
}