Flatten back the structure (#837)

* Remove chains.

* Move relay clients.

* Flatten generic.

* Fix fmt.
This commit is contained in:
Tomasz Drwięga
2021-03-23 14:17:33 +01:00
committed by Bastian Köcher
parent 647eb80165
commit acb872fbb0
109 changed files with 87 additions and 86 deletions
+416
View File
@@ -0,0 +1,416 @@
// Copyright 2019-2020 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/>.
//! Deal with CLI args of substrate-to-substrate relay.
use bp_messages::LaneId;
use codec::{Decode, Encode};
use sp_runtime::app_crypto::Ss58Codec;
use structopt::{clap::arg_enum, StructOpt};
use crate::rialto_millau::cli as rialto_millau;
/// Parse relay CLI args.
pub fn parse_args() -> Command {
Command::from_args()
}
/// Substrate-to-Substrate bridge utilities.
#[derive(StructOpt)]
#[structopt(about = "Substrate-to-Substrate relay")]
pub enum Command {
/// Start headers relay between two chains.
///
/// The on-chain bridge component should have been already initialized with
/// `init-bridge` sub-command.
RelayHeaders(RelayHeaders),
/// Start messages relay between two chains.
///
/// Ties up to `Messages` pallets on both chains and starts relaying messages.
/// Requires the header relay to be already running.
RelayMessages(RelayMessages),
/// Initialize on-chain bridge pallet with current header data.
///
/// Sends initialization transaction to bootstrap the bridge with current finalized block data.
InitBridge(InitBridge),
/// Send custom message over the bridge.
///
/// Allows interacting with the bridge by sending messages over `Messages` component.
/// The message is being sent to the source chain, delivered to the target chain and dispatched
/// there.
SendMessage(SendMessage),
/// Generate SCALE-encoded `Call` for choosen network.
///
/// The call can be used either as message payload or can be wrapped into a transaction
/// and executed on the chain directly.
EncodeCall(EncodeCall),
/// Generate SCALE-encoded `MessagePayload` object that can be sent over selected bridge.
///
/// The `MessagePayload` can be then fed to `Messages::send_message` function and sent over
/// the bridge.
EncodeMessagePayload(EncodeMessagePayload),
/// Estimate Delivery and Dispatch Fee required for message submission to messages pallet.
EstimateFee(EstimateFee),
/// Given a source chain `AccountId`, derive the corresponding `AccountId` for the target chain.
DeriveAccount(DeriveAccount),
}
impl Command {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
match self {
Self::InitBridge(arg) => arg.run().await?,
Self::RelayHeaders(arg) => arg.run().await?,
Self::RelayMessages(arg) => arg.run().await?,
Self::SendMessage(arg) => arg.run().await?,
Self::EncodeCall(arg) => arg.run().await?,
Self::EncodeMessagePayload(arg) => arg.run().await?,
Self::EstimateFee(arg) => arg.run().await?,
Self::DeriveAccount(arg) => arg.run().await?,
}
Ok(())
}
}
/// Start headers relayer process.
#[derive(StructOpt)]
pub enum RelayHeaders {
#[structopt(flatten)]
RialtoMillau(rialto_millau::RelayHeaders),
}
impl RelayHeaders {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
match self {
Self::RialtoMillau(arg) => arg.run().await?,
}
Ok(())
}
}
/// Start message relayer process.
#[derive(StructOpt)]
pub enum RelayMessages {
#[structopt(flatten)]
RialtoMillau(rialto_millau::RelayMessages),
}
impl RelayMessages {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
match self {
Self::RialtoMillau(arg) => arg.run().await?,
}
Ok(())
}
}
/// Initialize bridge pallet.
#[derive(StructOpt)]
pub enum InitBridge {
#[structopt(flatten)]
RialtoMillau(rialto_millau::InitBridge),
}
impl InitBridge {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
match self {
Self::RialtoMillau(arg) => arg.run().await?,
}
Ok(())
}
}
/// Send bridge message.
#[derive(StructOpt)]
pub enum SendMessage {
#[structopt(flatten)]
RialtoMillau(rialto_millau::SendMessage),
}
impl SendMessage {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
match self {
Self::RialtoMillau(arg) => arg.run().await?,
}
Ok(())
}
}
/// A call to encode.
#[derive(StructOpt)]
pub enum EncodeCall {
#[structopt(flatten)]
RialtoMillau(rialto_millau::EncodeCall),
}
impl EncodeCall {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
match self {
Self::RialtoMillau(arg) => arg.run().await?,
}
Ok(())
}
}
/// A `MessagePayload` to encode.
#[derive(StructOpt)]
pub enum EncodeMessagePayload {
#[structopt(flatten)]
RialtoMillau(rialto_millau::EncodeMessagePayload),
}
impl EncodeMessagePayload {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
match self {
Self::RialtoMillau(arg) => arg.run().await?,
}
Ok(())
}
}
/// Estimate Delivery & Dispatch Fee command.
#[derive(StructOpt)]
pub enum EstimateFee {
#[structopt(flatten)]
RialtoMillau(rialto_millau::EstimateFee),
}
impl EstimateFee {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
match self {
Self::RialtoMillau(arg) => arg.run().await?,
}
Ok(())
}
}
/// Given a source chain `AccountId`, derive the corresponding `AccountId` for the target chain.
///
/// The (derived) target chain `AccountId` is going to be used as dispatch origin of the call
/// that has been sent over the bridge.
/// This account can also be used to receive target-chain funds (or other form of ownership),
/// since messages sent over the bridge will be able to spend these.
#[derive(StructOpt)]
pub enum DeriveAccount {
#[structopt(flatten)]
RialtoMillau(rialto_millau::DeriveAccount),
}
impl DeriveAccount {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
match self {
Self::RialtoMillau(arg) => arg.run().await?,
}
Ok(())
}
}
arg_enum! {
#[derive(Debug)]
/// The origin to use when dispatching the message on the target chain.
///
/// - `Target` uses account existing on the target chain (requires target private key).
/// - `Origin` uses account derived from the source-chain account.
pub enum Origins {
Target,
Source,
}
}
/// Generic account id with custom parser.
#[derive(Debug)]
pub struct AccountId {
account: sp_runtime::AccountId32,
version: sp_core::crypto::Ss58AddressFormat,
}
impl std::str::FromStr for AccountId {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (account, version) = sp_runtime::AccountId32::from_ss58check_with_version(s)
.map_err(|err| format!("Unable to decode SS58 address: {:?}", err))?;
Ok(Self { account, version })
}
}
impl AccountId {
/// Perform runtime checks of SS58 version and get Rialto's AccountId.
pub fn into_rialto(self) -> bp_rialto::AccountId {
self.check_and_get("Rialto", rialto_runtime::SS58Prefix::get())
}
/// Perform runtime checks of SS58 version and get Millau's AccountId.
pub fn into_millau(self) -> bp_millau::AccountId {
self.check_and_get("Millau", millau_runtime::SS58Prefix::get())
}
/// Check SS58Prefix and return the account id.
fn check_and_get(self, net: &str, expected_prefix: u8) -> sp_runtime::AccountId32 {
let version: u16 = self.version.into();
println!("Version: {} vs {}", version, expected_prefix);
if version != expected_prefix as u16 {
log::warn!(
target: "bridge",
"Following address: {} does not seem to match {}'s format, got: {}",
self.account,
net,
self.version,
)
}
self.account
}
}
/// Lane id.
#[derive(Debug)]
pub struct HexLaneId(pub LaneId);
impl From<HexLaneId> for LaneId {
fn from(lane_id: HexLaneId) -> LaneId {
lane_id.0
}
}
impl std::str::FromStr for HexLaneId {
type Err = hex::FromHexError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut lane_id = LaneId::default();
hex::decode_to_slice(s, &mut lane_id)?;
Ok(HexLaneId(lane_id))
}
}
/// Nicer formatting for raw bytes vectors.
#[derive(Encode, Decode)]
pub struct HexBytes(pub Vec<u8>);
impl std::str::FromStr for HexBytes {
type Err = hex::FromHexError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(hex::decode(s)?))
}
}
impl std::fmt::Debug for HexBytes {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(fmt, "0x{}", hex::encode(&self.0))
}
}
impl HexBytes {
/// Encode given object and wrap into nicely formatted bytes.
pub fn encode<T: Encode>(t: &T) -> Self {
Self(t.encode())
}
}
/// Prometheus metrics params.
#[derive(StructOpt)]
pub struct PrometheusParams {
/// Do not expose a Prometheus metric endpoint.
#[structopt(long)]
pub no_prometheus: bool,
/// Expose Prometheus endpoint at given interface.
#[structopt(long, default_value = "127.0.0.1")]
pub prometheus_host: String,
/// Expose Prometheus endpoint at given port.
#[structopt(long, default_value = "9616")]
pub prometheus_port: u16,
}
impl From<PrometheusParams> for Option<relay_utils::metrics::MetricsParams> {
fn from(cli_params: PrometheusParams) -> Option<relay_utils::metrics::MetricsParams> {
if !cli_params.no_prometheus {
Some(relay_utils::metrics::MetricsParams {
host: cli_params.prometheus_host,
port: cli_params.prometheus_port,
})
} else {
None
}
}
}
/// Either explicit or maximal allowed value.
#[derive(Debug)]
pub enum ExplicitOrMaximal<V> {
/// User has explicitly specified argument value.
Explicit(V),
/// Maximal allowed value for this argument.
Maximal,
}
impl<V: std::str::FromStr> std::str::FromStr for ExplicitOrMaximal<V>
where
V::Err: std::fmt::Debug,
{
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.to_lowercase() == "max" {
return Ok(ExplicitOrMaximal::Maximal);
}
V::from_str(s)
.map(ExplicitOrMaximal::Explicit)
.map_err(|e| format!("Failed to parse '{:?}'. Expected 'max' or explicit value", e))
}
}
/// Create chain-specific set of configuration objects: connection parameters,
/// signing parameters and bridge initialisation parameters.
#[macro_export]
macro_rules! declare_chain_options {
($chain:ident, $chain_prefix:ident) => {
paste::item! {
#[doc = $chain " connection params."]
#[derive(StructOpt)]
pub struct [<$chain ConnectionParams>] {
#[doc = "Connect to " $chain " node at given host."]
#[structopt(long, default_value = "127.0.0.1")]
pub [<$chain_prefix _host>]: String,
#[doc = "Connect to " $chain " node websocket server at given port."]
#[structopt(long)]
pub [<$chain_prefix _port>]: u16,
#[doc = "Use secure websocket connection."]
#[structopt(long)]
pub [<$chain_prefix _secure>]: bool,
}
#[doc = $chain " signing params."]
#[derive(StructOpt)]
pub struct [<$chain SigningParams>] {
#[doc = "The SURI of secret key to use when transactions are submitted to the " $chain " node."]
#[structopt(long)]
pub [<$chain_prefix _signer>]: String,
#[doc = "The password for the SURI of secret key to use when transactions are submitted to the " $chain " node."]
#[structopt(long)]
pub [<$chain_prefix _signer_password>]: Option<String>,
}
}
};
}
@@ -0,0 +1,131 @@
// 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/>.
//! Substrate-to-Substrate headers sync entrypoint.
use crate::finality_target::SubstrateFinalityTarget;
use async_trait::async_trait;
use codec::Encode;
use finality_relay::{FinalitySyncParams, FinalitySyncPipeline};
use relay_substrate_client::{
finality_source::{FinalitySource, Justification},
BlockNumberOf, Chain, Client, Error as SubstrateError, HashOf, SyncHeader,
};
use relay_utils::BlockNumberBase;
use std::{fmt::Debug, marker::PhantomData, time::Duration};
/// Default synchronization loop timeout.
const STALL_TIMEOUT: Duration = Duration::from_secs(120);
/// Default limit of recent finality proofs.
///
/// Finality delay of 4096 blocks is unlikely to happen in practice in
/// Substrate+GRANDPA based chains (good to know).
const RECENT_FINALITY_PROOFS_LIMIT: usize = 4096;
/// Headers sync pipeline for Substrate <-> Substrate relays.
#[async_trait]
pub trait SubstrateFinalitySyncPipeline: FinalitySyncPipeline {
/// Name of the runtime method that returns id of best finalized source header at target chain.
const BEST_FINALIZED_SOURCE_HEADER_ID_AT_TARGET: &'static str;
/// Signed transaction type.
type SignedTransaction: Send + Sync + Encode;
/// Make submit header transaction.
async fn make_submit_finality_proof_transaction(
&self,
header: Self::Header,
proof: Self::FinalityProof,
) -> Result<Self::SignedTransaction, SubstrateError>;
}
/// Substrate-to-Substrate finality proof pipeline.
#[derive(Debug, Clone)]
pub struct SubstrateFinalityToSubstrate<SourceChain, TargetChain: Chain, TargetSign> {
/// Client for the target chain.
pub(crate) target_client: Client<TargetChain>,
/// Data required to sign target chain transactions.
pub(crate) target_sign: TargetSign,
/// Unused generic arguments dump.
_marker: PhantomData<SourceChain>,
}
impl<SourceChain, TargetChain: Chain, TargetSign> SubstrateFinalityToSubstrate<SourceChain, TargetChain, TargetSign> {
/// Create new Substrate-to-Substrate headers pipeline.
pub fn new(target_client: Client<TargetChain>, target_sign: TargetSign) -> Self {
SubstrateFinalityToSubstrate {
target_client,
target_sign,
_marker: Default::default(),
}
}
}
impl<SourceChain, TargetChain, TargetSign> FinalitySyncPipeline
for SubstrateFinalityToSubstrate<SourceChain, TargetChain, TargetSign>
where
SourceChain: Clone + Chain + Debug,
BlockNumberOf<SourceChain>: BlockNumberBase,
TargetChain: Clone + Chain + Debug,
TargetSign: Clone + Send + Sync + Debug,
{
const SOURCE_NAME: &'static str = SourceChain::NAME;
const TARGET_NAME: &'static str = TargetChain::NAME;
type Hash = HashOf<SourceChain>;
type Number = BlockNumberOf<SourceChain>;
type Header = SyncHeader<SourceChain::Header>;
type FinalityProof = Justification<SourceChain::BlockNumber>;
}
/// Run Substrate-to-Substrate finality sync.
pub async fn run<SourceChain, TargetChain, P>(
pipeline: P,
source_client: Client<SourceChain>,
target_client: Client<TargetChain>,
metrics_params: Option<relay_utils::metrics::MetricsParams>,
) where
P: SubstrateFinalitySyncPipeline<
Hash = HashOf<SourceChain>,
Number = BlockNumberOf<SourceChain>,
Header = SyncHeader<SourceChain::Header>,
FinalityProof = Justification<SourceChain::BlockNumber>,
>,
SourceChain: Clone + Chain,
BlockNumberOf<SourceChain>: BlockNumberBase,
TargetChain: Clone + Chain,
{
log::info!(
target: "bridge",
"Starting {} -> {} finality proof relay",
SourceChain::NAME,
TargetChain::NAME,
);
finality_relay::run(
FinalitySource::new(source_client),
SubstrateFinalityTarget::new(target_client, pipeline),
FinalitySyncParams {
tick: std::cmp::max(SourceChain::AVERAGE_BLOCK_INTERVAL, TargetChain::AVERAGE_BLOCK_INTERVAL),
recent_finality_proofs_limit: RECENT_FINALITY_PROOFS_LIMIT,
stall_timeout: STALL_TIMEOUT,
},
metrics_params,
futures::future::pending(),
)
.await;
}
@@ -0,0 +1,91 @@
// Copyright 2019-2020 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/>.
//! Substrate client as Substrate finality proof target. The chain we connect to should have
//! runtime that implements `<BridgedChainName>FinalityApi` to allow bridging with
//! <BridgedName> chain.
use crate::finality_pipeline::SubstrateFinalitySyncPipeline;
use async_trait::async_trait;
use codec::{Decode, Encode};
use finality_relay::TargetClient;
use futures::TryFutureExt;
use relay_substrate_client::{Chain, Client, Error as SubstrateError};
use relay_utils::relay_loop::Client as RelayClient;
use sp_core::Bytes;
/// Substrate client as Substrate finality target.
pub struct SubstrateFinalityTarget<C: Chain, P> {
client: Client<C>,
pipeline: P,
}
impl<C: Chain, P> SubstrateFinalityTarget<C, P> {
/// Create new Substrate headers target.
pub fn new(client: Client<C>, pipeline: P) -> Self {
SubstrateFinalityTarget { client, pipeline }
}
}
impl<C: Chain, P: SubstrateFinalitySyncPipeline> Clone for SubstrateFinalityTarget<C, P> {
fn clone(&self) -> Self {
SubstrateFinalityTarget {
client: self.client.clone(),
pipeline: self.pipeline.clone(),
}
}
}
#[async_trait]
impl<C: Chain, P: SubstrateFinalitySyncPipeline> RelayClient for SubstrateFinalityTarget<C, P> {
type Error = SubstrateError;
async fn reconnect(&mut self) -> Result<(), SubstrateError> {
self.client.reconnect().await
}
}
#[async_trait]
impl<C, P> TargetClient<P> for SubstrateFinalityTarget<C, P>
where
C: Chain,
P::Number: Decode,
P::Hash: Decode,
P: SubstrateFinalitySyncPipeline,
{
async fn best_finalized_source_block_number(&self) -> Result<P::Number, SubstrateError> {
// we can't continue to relay finality if target node is out of sync, because
// it may have already received (some of) headers that we're going to relay
self.client.ensure_synced().await?;
Ok(crate::messages_source::read_client_state::<C, P::Hash, P::Number>(
&self.client,
P::BEST_FINALIZED_SOURCE_HEADER_ID_AT_TARGET,
)
.await?
.best_finalized_peer_at_best_self
.0)
}
async fn submit_finality_proof(&self, header: P::Header, proof: P::FinalityProof) -> Result<(), SubstrateError> {
self.pipeline
.make_submit_finality_proof_transaction(header, proof)
.and_then(|tx| self.client.submit_extrinsic(Bytes(tx.encode())))
.await
.map(drop)
}
}
@@ -0,0 +1,243 @@
// Copyright 2019-2020 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/>.
//! Initialize Substrate -> Substrate headers bridge.
//!
//! Initialization is a transaction that calls `initialize()` function of the
//! `pallet-finality-verifier` pallet. This transaction brings initial header
//! and authorities set from source to target chain. The headers sync starts
//! with this header.
use bp_header_chain::{
find_grandpa_authorities_scheduled_change,
justification::{decode_justification_target, verify_justification},
};
use codec::Decode;
use finality_grandpa::voter_set::VoterSet;
use num_traits::{One, Zero};
use pallet_finality_verifier::InitializationData;
use relay_substrate_client::{Chain, Client};
use sp_core::Bytes;
use sp_finality_grandpa::AuthorityList as GrandpaAuthoritiesSet;
use sp_runtime::traits::Header as HeaderT;
/// Submit headers-bridge initialization transaction.
pub async fn initialize<SourceChain: Chain, TargetChain: Chain>(
source_client: Client<SourceChain>,
target_client: Client<TargetChain>,
prepare_initialize_transaction: impl FnOnce(InitializationData<SourceChain::Header>) -> Result<Bytes, String>,
) {
let result = do_initialize(source_client, target_client, prepare_initialize_transaction).await;
match result {
Ok(tx_hash) => log::info!(
target: "bridge",
"Successfully submitted {}-headers bridge initialization transaction to {}: {:?}",
SourceChain::NAME,
TargetChain::NAME,
tx_hash,
),
Err(err) => log::error!(
target: "bridge",
"Failed to submit {}-headers bridge initialization transaction to {}: {:?}",
SourceChain::NAME,
TargetChain::NAME,
err,
),
}
}
/// Craft and submit initialization transaction, returning any error that may occur.
async fn do_initialize<SourceChain: Chain, TargetChain: Chain>(
source_client: Client<SourceChain>,
target_client: Client<TargetChain>,
prepare_initialize_transaction: impl FnOnce(InitializationData<SourceChain::Header>) -> Result<Bytes, String>,
) -> Result<TargetChain::Hash, String> {
let initialization_data = prepare_initialization_data(source_client).await?;
log::info!(
target: "bridge",
"Prepared initialization data for {}-headers bridge at {}: {:?}",
SourceChain::NAME,
TargetChain::NAME,
initialization_data,
);
let initialization_tx = prepare_initialize_transaction(initialization_data)?;
let initialization_tx_hash = target_client
.submit_extrinsic(initialization_tx)
.await
.map_err(|err| format!("Failed to submit {} transaction: {:?}", TargetChain::NAME, err))?;
Ok(initialization_tx_hash)
}
/// Prepare initialization data for the finality-verifier pallet.
async fn prepare_initialization_data<SourceChain: Chain>(
source_client: Client<SourceChain>,
) -> Result<InitializationData<SourceChain::Header>, String> {
// In ideal world we just need to get best finalized header and then to read GRANDPA authorities
// set (`pallet_grandpa::CurrentSetId` + `GrandpaApi::grandpa_authorities()`) at this header.
//
// But now there are problems with this approach - `CurrentSetId` may return invalid value. So here
// we're waiting for the next justification, read the authorities set and then try to figure out
// the set id with bruteforce.
let mut justifications = source_client
.subscribe_justifications()
.await
.map_err(|err| format!("Failed to subscribe to {} justifications: {:?}", SourceChain::NAME, err))?;
// Read next justification - the header that it finalizes will be used as initial header.
let justification = justifications.next().await.ok_or_else(|| {
format!(
"Failed to read {} justification from the stream: stream has ended unexpectedly",
SourceChain::NAME,
)
})?;
// Read initial header.
let (initial_header_hash, initial_header_number) =
decode_justification_target::<SourceChain::Header>(&justification.0)
.map_err(|err| format!("Failed to decode {} justification: {:?}", SourceChain::NAME, err))?;
let initial_header = source_header(&source_client, initial_header_hash).await?;
log::trace!(target: "bridge", "Selected {} initial header: {}/{}",
SourceChain::NAME,
initial_header_number,
initial_header_hash,
);
// Read GRANDPA authorities set at initial header.
let initial_authorities_set = source_authorities_set(&source_client, initial_header_hash).await?;
log::trace!(target: "bridge", "Selected {} initial authorities set: {:?}",
SourceChain::NAME,
initial_authorities_set,
);
// If initial header changes the GRANDPA authorities set, then we need previous authorities
// to verify justification.
let mut authorities_for_verification = initial_authorities_set.clone();
let scheduled_change = find_grandpa_authorities_scheduled_change(&initial_header);
assert!(
scheduled_change.as_ref().map(|c| c.delay.is_zero()).unwrap_or(true),
"GRANDPA authorities change at {} scheduled to happen in {:?} blocks. We expect\
regular hange to have zero delay",
initial_header_hash,
scheduled_change.as_ref().map(|c| c.delay),
);
let schedules_change = scheduled_change.is_some();
if schedules_change {
authorities_for_verification = source_authorities_set(&source_client, *initial_header.parent_hash()).await?;
log::trace!(
target: "bridge",
"Selected {} header is scheduling GRANDPA authorities set changes. Using previous set: {:?}",
SourceChain::NAME,
authorities_for_verification,
);
}
// Now let's try to guess authorities set id by verifying justification.
let mut initial_authorities_set_id = 0;
let mut min_possible_block_number = SourceChain::BlockNumber::zero();
let authorities_for_verification = VoterSet::new(authorities_for_verification.clone()).ok_or_else(|| {
format!(
"Read invalid {} authorities set: {:?}",
SourceChain::NAME,
authorities_for_verification,
)
})?;
loop {
log::trace!(
target: "bridge", "Trying {} GRANDPA authorities set id: {}",
SourceChain::NAME,
initial_authorities_set_id,
);
let is_valid_set_id = verify_justification::<SourceChain::Header>(
(initial_header_hash, initial_header_number),
initial_authorities_set_id,
&authorities_for_verification,
&justification.0,
)
.is_ok();
if is_valid_set_id {
break;
}
initial_authorities_set_id += 1;
min_possible_block_number += One::one();
if min_possible_block_number > initial_header_number {
// there can't be more authorities set changes than headers => if we have reached `initial_block_number`
// and still have not found correct value of `initial_authorities_set_id`, then something
// else is broken => fail
return Err(format!(
"Failed to guess initial {} GRANDPA authorities set id: checked all\
possible ids in range [0; {}]",
SourceChain::NAME,
initial_header_number
));
}
}
Ok(InitializationData {
header: initial_header,
authority_list: initial_authorities_set,
set_id: if schedules_change {
initial_authorities_set_id + 1
} else {
initial_authorities_set_id
},
is_halted: false,
})
}
/// Read header by hash from the source client.
async fn source_header<SourceChain: Chain>(
source_client: &Client<SourceChain>,
header_hash: SourceChain::Hash,
) -> Result<SourceChain::Header, String> {
source_client.header_by_hash(header_hash).await.map_err(|err| {
format!(
"Failed to retrive {} header with hash {}: {:?}",
SourceChain::NAME,
header_hash,
err,
)
})
}
/// Read GRANDPA authorities set at given header.
async fn source_authorities_set<SourceChain: Chain>(
source_client: &Client<SourceChain>,
header_hash: SourceChain::Hash,
) -> Result<GrandpaAuthoritiesSet, String> {
let raw_authorities_set = source_client
.grandpa_authorities_set(header_hash)
.await
.map_err(|err| {
format!(
"Failed to retrive {} GRANDPA authorities set at header {}: {:?}",
SourceChain::NAME,
header_hash,
err,
)
})?;
GrandpaAuthoritiesSet::decode(&mut &raw_authorities_set[..]).map_err(|err| {
format!(
"Failed to decode {} GRANDPA authorities set at header {}: {:?}",
SourceChain::NAME,
header_hash,
err,
)
})
}
+41
View File
@@ -0,0 +1,41 @@
// Copyright 2019-2020 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/>.
//! Substrate-to-substrate relay entrypoint.
#![warn(missing_docs)]
use relay_utils::initialize::initialize_relay;
mod cli;
mod finality_pipeline;
mod finality_target;
mod headers_initialize;
mod messages_lane;
mod messages_source;
mod messages_target;
mod rialto_millau;
fn main() {
initialize_relay();
let command = cli::parse_args();
let run = command.run();
let result = async_std::task::block_on(run);
if let Err(error) = result {
log::error!(target: "bridge", "Failed to start relay: {}", error);
}
}
@@ -0,0 +1,182 @@
// Copyright 2019-2020 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/>.
use crate::messages_source::SubstrateMessagesProof;
use crate::messages_target::SubstrateMessagesReceivingProof;
use async_trait::async_trait;
use bp_messages::MessageNonce;
use codec::Encode;
use frame_support::weights::Weight;
use messages_relay::message_lane::{MessageLane, SourceHeaderIdOf, TargetHeaderIdOf};
use relay_substrate_client::{BlockNumberOf, Chain, Client, Error as SubstrateError, HashOf};
use relay_utils::BlockNumberBase;
use std::ops::RangeInclusive;
/// Message sync pipeline for Substrate <-> Substrate relays.
#[async_trait]
pub trait SubstrateMessageLane: MessageLane {
/// Name of the runtime method that returns dispatch weight of outbound messages at the source chain.
const OUTBOUND_LANE_MESSAGES_DISPATCH_WEIGHT_METHOD: &'static str;
/// Name of the runtime method that returns latest generated nonce at the source chain.
const OUTBOUND_LANE_LATEST_GENERATED_NONCE_METHOD: &'static str;
/// Name of the runtime method that returns latest received (confirmed) nonce at the the source chain.
const OUTBOUND_LANE_LATEST_RECEIVED_NONCE_METHOD: &'static str;
/// Name of the runtime method that returns latest received nonce at the target chain.
const INBOUND_LANE_LATEST_RECEIVED_NONCE_METHOD: &'static str;
/// Name of the runtime method that returns latest confirmed (reward-paid) nonce at the target chain.
const INBOUND_LANE_LATEST_CONFIRMED_NONCE_METHOD: &'static str;
/// Numebr of the runtime method that returns state of "unrewarded relayers" set at the target chain.
const INBOUND_LANE_UNREWARDED_RELAYERS_STATE: &'static str;
/// Name of the runtime method that returns id of best finalized source header at target chain.
const BEST_FINALIZED_SOURCE_HEADER_ID_AT_TARGET: &'static str;
/// Name of the runtime method that returns id of best finalized target header at source chain.
const BEST_FINALIZED_TARGET_HEADER_ID_AT_SOURCE: &'static str;
/// Signed transaction type of the source chain.
type SourceSignedTransaction: Send + Sync + Encode;
/// Signed transaction type of the target chain.
type TargetSignedTransaction: Send + Sync + Encode;
/// Make messages delivery transaction.
async fn make_messages_delivery_transaction(
&self,
generated_at_header: SourceHeaderIdOf<Self>,
nonces: RangeInclusive<MessageNonce>,
proof: Self::MessagesProof,
) -> Result<Self::TargetSignedTransaction, SubstrateError>;
/// Make messages receiving proof transaction.
async fn make_messages_receiving_proof_transaction(
&self,
generated_at_header: TargetHeaderIdOf<Self>,
proof: Self::MessagesReceivingProof,
) -> Result<Self::SourceSignedTransaction, SubstrateError>;
}
/// Substrate-to-Substrate message lane.
#[derive(Debug)]
pub struct SubstrateMessageLaneToSubstrate<Source: Chain, SourceSignParams, Target: Chain, TargetSignParams> {
/// Client for the source Substrate chain.
pub(crate) source_client: Client<Source>,
/// Parameters required to sign transactions for source chain.
pub(crate) source_sign: SourceSignParams,
/// Client for the target Substrate chain.
pub(crate) target_client: Client<Target>,
/// Parameters required to sign transactions for target chain.
pub(crate) target_sign: TargetSignParams,
/// Account id of relayer at the source chain.
pub(crate) relayer_id_at_source: Source::AccountId,
}
impl<Source: Chain, SourceSignParams: Clone, Target: Chain, TargetSignParams: Clone> Clone
for SubstrateMessageLaneToSubstrate<Source, SourceSignParams, Target, TargetSignParams>
{
fn clone(&self) -> Self {
Self {
source_client: self.source_client.clone(),
source_sign: self.source_sign.clone(),
target_client: self.target_client.clone(),
target_sign: self.target_sign.clone(),
relayer_id_at_source: self.relayer_id_at_source.clone(),
}
}
}
impl<Source: Chain, SourceSignParams, Target: Chain, TargetSignParams> MessageLane
for SubstrateMessageLaneToSubstrate<Source, SourceSignParams, Target, TargetSignParams>
where
SourceSignParams: Clone + Send + Sync + 'static,
TargetSignParams: Clone + Send + Sync + 'static,
BlockNumberOf<Source>: BlockNumberBase,
BlockNumberOf<Target>: BlockNumberBase,
{
const SOURCE_NAME: &'static str = Source::NAME;
const TARGET_NAME: &'static str = Target::NAME;
type MessagesProof = SubstrateMessagesProof<Source>;
type MessagesReceivingProof = SubstrateMessagesReceivingProof<Target>;
type SourceHeaderNumber = BlockNumberOf<Source>;
type SourceHeaderHash = HashOf<Source>;
type TargetHeaderNumber = BlockNumberOf<Target>;
type TargetHeaderHash = HashOf<Target>;
}
/// Returns maximal number of messages and their maximal cumulative dispatch weight, based
/// on given chain parameters.
pub fn select_delivery_transaction_limits<W: pallet_bridge_messages::WeightInfoExt>(
max_extrinsic_weight: Weight,
max_unconfirmed_messages_at_inbound_lane: MessageNonce,
) -> (MessageNonce, Weight) {
// We may try to guess accurate value, based on maximal number of messages and per-message
// weight overhead, but the relay loop isn't using this info in a super-accurate way anyway.
// So just a rough guess: let's say 1/3 of max tx weight is for tx itself and the rest is
// for messages dispatch.
// Another thing to keep in mind is that our runtimes (when this code was written) accept
// messages with dispatch weight <= max_extrinsic_weight/2. So we can't reserve less than
// that for dispatch.
let weight_for_delivery_tx = max_extrinsic_weight / 3;
let weight_for_messages_dispatch = max_extrinsic_weight - weight_for_delivery_tx;
let delivery_tx_base_weight =
W::receive_messages_proof_overhead() + W::receive_messages_proof_outbound_lane_state_overhead();
let delivery_tx_weight_rest = weight_for_delivery_tx - delivery_tx_base_weight;
let max_number_of_messages = std::cmp::min(
delivery_tx_weight_rest / W::receive_messages_proof_messages_overhead(1),
max_unconfirmed_messages_at_inbound_lane,
);
assert!(
max_number_of_messages > 0,
"Relay should fit at least one message in every delivery transaction",
);
assert!(
weight_for_messages_dispatch >= max_extrinsic_weight / 2,
"Relay shall be able to deliver messages with dispatch weight = max_extrinsic_weight / 2",
);
(max_number_of_messages, weight_for_messages_dispatch)
}
#[cfg(test)]
mod tests {
use super::*;
type RialtoToMillauMessagesWeights = pallet_bridge_messages::weights::RialtoWeight<rialto_runtime::Runtime>;
#[test]
fn select_delivery_transaction_limits_works() {
let (max_count, max_weight) = select_delivery_transaction_limits::<RialtoToMillauMessagesWeights>(
bp_millau::max_extrinsic_weight(),
bp_millau::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE,
);
assert_eq!(
(max_count, max_weight),
// We don't actually care about these values, so feel free to update them whenever test
// fails. The only thing to do before that is to ensure that new values looks sane: i.e. weight
// reserved for messages dispatch allows dispatch of non-trivial messages.
//
// Any significant change in this values should attract additional attention.
(955, 216_583_333_334),
);
}
}
@@ -0,0 +1,373 @@
// Copyright 2019-2020 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/>.
//! Substrate client as Substrate messages source. The chain we connect to should have
//! runtime that implements `<BridgedChainName>HeaderApi` to allow bridging with
//! <BridgedName> chain.
use crate::messages_lane::SubstrateMessageLane;
use async_trait::async_trait;
use bp_messages::{LaneId, MessageNonce};
use bp_runtime::InstanceId;
use bridge_runtime_common::messages::target::FromBridgedChainMessagesProof;
use codec::{Decode, Encode};
use frame_support::weights::Weight;
use messages_relay::{
message_lane::{SourceHeaderIdOf, TargetHeaderIdOf},
message_lane_loop::{
ClientState, MessageProofParameters, MessageWeights, MessageWeightsMap, SourceClient, SourceClientState,
},
};
use relay_substrate_client::{Chain, Client, Error as SubstrateError, HashOf, HeaderIdOf};
use relay_utils::{relay_loop::Client as RelayClient, BlockNumberBase, HeaderId};
use sp_core::Bytes;
use sp_runtime::{traits::Header as HeaderT, DeserializeOwned};
use std::ops::RangeInclusive;
/// Intermediate message proof returned by the source Substrate node. Includes everything
/// required to submit to the target node: cumulative dispatch weight of bundled messages and
/// the proof itself.
pub type SubstrateMessagesProof<C> = (Weight, FromBridgedChainMessagesProof<HashOf<C>>);
/// Substrate client as Substrate messages source.
pub struct SubstrateMessagesSource<C: Chain, P> {
client: Client<C>,
lane: P,
lane_id: LaneId,
instance: InstanceId,
}
impl<C: Chain, P> SubstrateMessagesSource<C, P> {
/// Create new Substrate headers source.
pub fn new(client: Client<C>, lane: P, lane_id: LaneId, instance: InstanceId) -> Self {
SubstrateMessagesSource {
client,
lane,
lane_id,
instance,
}
}
}
impl<C: Chain, P: SubstrateMessageLane> Clone for SubstrateMessagesSource<C, P> {
fn clone(&self) -> Self {
Self {
client: self.client.clone(),
lane: self.lane.clone(),
lane_id: self.lane_id,
instance: self.instance,
}
}
}
#[async_trait]
impl<C: Chain, P: SubstrateMessageLane> RelayClient for SubstrateMessagesSource<C, P> {
type Error = SubstrateError;
async fn reconnect(&mut self) -> Result<(), SubstrateError> {
self.client.reconnect().await
}
}
#[async_trait]
impl<C, P> SourceClient<P> for SubstrateMessagesSource<C, P>
where
C: Chain,
C::Header: DeserializeOwned,
C::Index: DeserializeOwned,
C::BlockNumber: BlockNumberBase,
P: SubstrateMessageLane<
MessagesProof = SubstrateMessagesProof<C>,
SourceHeaderNumber = <C::Header as HeaderT>::Number,
SourceHeaderHash = <C::Header as HeaderT>::Hash,
>,
P::TargetHeaderNumber: Decode,
P::TargetHeaderHash: Decode,
{
async fn state(&self) -> Result<SourceClientState<P>, SubstrateError> {
// we can't continue to deliver confirmations if source node is out of sync, because
// it may have already received confirmations that we're going to deliver
self.client.ensure_synced().await?;
read_client_state::<_, P::TargetHeaderHash, P::TargetHeaderNumber>(
&self.client,
P::BEST_FINALIZED_TARGET_HEADER_ID_AT_SOURCE,
)
.await
}
async fn latest_generated_nonce(
&self,
id: SourceHeaderIdOf<P>,
) -> Result<(SourceHeaderIdOf<P>, MessageNonce), SubstrateError> {
let encoded_response = self
.client
.state_call(
P::OUTBOUND_LANE_LATEST_GENERATED_NONCE_METHOD.into(),
Bytes(self.lane_id.encode()),
Some(id.1),
)
.await?;
let latest_generated_nonce: MessageNonce =
Decode::decode(&mut &encoded_response.0[..]).map_err(SubstrateError::ResponseParseFailed)?;
Ok((id, latest_generated_nonce))
}
async fn latest_confirmed_received_nonce(
&self,
id: SourceHeaderIdOf<P>,
) -> Result<(SourceHeaderIdOf<P>, MessageNonce), SubstrateError> {
let encoded_response = self
.client
.state_call(
P::OUTBOUND_LANE_LATEST_RECEIVED_NONCE_METHOD.into(),
Bytes(self.lane_id.encode()),
Some(id.1),
)
.await?;
let latest_received_nonce: MessageNonce =
Decode::decode(&mut &encoded_response.0[..]).map_err(SubstrateError::ResponseParseFailed)?;
Ok((id, latest_received_nonce))
}
async fn generated_messages_weights(
&self,
id: SourceHeaderIdOf<P>,
nonces: RangeInclusive<MessageNonce>,
) -> Result<MessageWeightsMap, SubstrateError> {
let encoded_response = self
.client
.state_call(
P::OUTBOUND_LANE_MESSAGES_DISPATCH_WEIGHT_METHOD.into(),
Bytes((self.lane_id, nonces.start(), nonces.end()).encode()),
Some(id.1),
)
.await?;
make_message_weights_map::<C>(
Decode::decode(&mut &encoded_response.0[..]).map_err(SubstrateError::ResponseParseFailed)?,
nonces,
)
}
async fn prove_messages(
&self,
id: SourceHeaderIdOf<P>,
nonces: RangeInclusive<MessageNonce>,
proof_parameters: MessageProofParameters,
) -> Result<(SourceHeaderIdOf<P>, RangeInclusive<MessageNonce>, P::MessagesProof), SubstrateError> {
let proof = self
.client
.prove_messages(
self.instance,
self.lane_id,
nonces.clone(),
proof_parameters.outbound_state_proof_required,
id.1,
)
.await?
.iter_nodes()
.collect();
let proof = FromBridgedChainMessagesProof {
bridged_header_hash: id.1,
storage_proof: proof,
lane: self.lane_id,
nonces_start: *nonces.start(),
nonces_end: *nonces.end(),
};
Ok((id, nonces, (proof_parameters.dispatch_weight, proof)))
}
async fn submit_messages_receiving_proof(
&self,
generated_at_block: TargetHeaderIdOf<P>,
proof: P::MessagesReceivingProof,
) -> Result<(), SubstrateError> {
let tx = self
.lane
.make_messages_receiving_proof_transaction(generated_at_block, proof)
.await?;
self.client.submit_extrinsic(Bytes(tx.encode())).await?;
Ok(())
}
}
pub async fn read_client_state<SelfChain, BridgedHeaderHash, BridgedHeaderNumber>(
self_client: &Client<SelfChain>,
best_finalized_header_id_method_name: &str,
) -> Result<ClientState<HeaderIdOf<SelfChain>, HeaderId<BridgedHeaderHash, BridgedHeaderNumber>>, SubstrateError>
where
SelfChain: Chain,
SelfChain::Header: DeserializeOwned,
SelfChain::Index: DeserializeOwned,
BridgedHeaderHash: Decode,
BridgedHeaderNumber: Decode,
{
// let's read our state first: we need best finalized header hash on **this** chain
let self_best_finalized_header_hash = self_client.best_finalized_header_hash().await?;
let self_best_finalized_header = self_client.header_by_hash(self_best_finalized_header_hash).await?;
let self_best_finalized_id = HeaderId(*self_best_finalized_header.number(), self_best_finalized_header_hash);
// now let's read our best header on **this** chain
let self_best_header = self_client.best_header().await?;
let self_best_hash = self_best_header.hash();
let self_best_id = HeaderId(*self_best_header.number(), self_best_hash);
// now let's read id of best finalized peer header at our best finalized block
let encoded_best_finalized_peer_on_self = self_client
.state_call(
best_finalized_header_id_method_name.into(),
Bytes(Vec::new()),
Some(self_best_hash),
)
.await?;
let decoded_best_finalized_peer_on_self: (BridgedHeaderNumber, BridgedHeaderHash) =
Decode::decode(&mut &encoded_best_finalized_peer_on_self.0[..]).map_err(SubstrateError::ResponseParseFailed)?;
let peer_on_self_best_finalized_id = HeaderId(
decoded_best_finalized_peer_on_self.0,
decoded_best_finalized_peer_on_self.1,
);
Ok(ClientState {
best_self: self_best_id,
best_finalized_self: self_best_finalized_id,
best_finalized_peer_at_best_self: peer_on_self_best_finalized_id,
})
}
fn make_message_weights_map<C: Chain>(
weights: Vec<(MessageNonce, Weight, u32)>,
nonces: RangeInclusive<MessageNonce>,
) -> Result<MessageWeightsMap, SubstrateError> {
let make_missing_nonce_error = |expected_nonce| {
Err(SubstrateError::Custom(format!(
"Missing nonce {} in messages_dispatch_weight call result. Expected all nonces from {:?}",
expected_nonce, nonces,
)))
};
let mut weights_map = MessageWeightsMap::new();
// this is actually prevented by external logic
if nonces.is_empty() {
return Ok(weights_map);
}
// check if last nonce is missing - loop below is not checking this
let last_nonce_is_missing = weights
.last()
.map(|(last_nonce, _, _)| last_nonce != nonces.end())
.unwrap_or(true);
if last_nonce_is_missing {
return make_missing_nonce_error(*nonces.end());
}
let mut expected_nonce = *nonces.start();
let mut is_at_head = true;
for (nonce, weight, size) in weights {
match (nonce == expected_nonce, is_at_head) {
(true, _) => (),
(false, true) => {
// this may happen if some messages were already pruned from the source node
//
// this is not critical error and will be auto-resolved by messages lane (and target node)
log::info!(
target: "bridge",
"Some messages are missing from the {} node: {:?}. Target node may be out of sync?",
C::NAME,
expected_nonce..nonce,
);
}
(false, false) => {
// some nonces are missing from the middle/tail of the range
//
// this is critical error, because we can't miss any nonces
return make_missing_nonce_error(expected_nonce);
}
}
weights_map.insert(
nonce,
MessageWeights {
weight,
size: size as _,
},
);
expected_nonce = nonce + 1;
is_at_head = false;
}
Ok(weights_map)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn make_message_weights_map_succeeds_if_no_messages_are_missing() {
assert_eq!(
make_message_weights_map::<relay_rialto_client::Rialto>(vec![(1, 0, 0), (2, 0, 0), (3, 0, 0)], 1..=3,)
.unwrap(),
vec![
(1, MessageWeights { weight: 0, size: 0 }),
(2, MessageWeights { weight: 0, size: 0 }),
(3, MessageWeights { weight: 0, size: 0 }),
]
.into_iter()
.collect(),
);
}
#[test]
fn make_message_weights_map_succeeds_if_head_messages_are_missing() {
assert_eq!(
make_message_weights_map::<relay_rialto_client::Rialto>(vec![(2, 0, 0), (3, 0, 0)], 1..=3,).unwrap(),
vec![
(2, MessageWeights { weight: 0, size: 0 }),
(3, MessageWeights { weight: 0, size: 0 }),
]
.into_iter()
.collect(),
);
}
#[test]
fn make_message_weights_map_fails_if_mid_messages_are_missing() {
assert!(matches!(
make_message_weights_map::<relay_rialto_client::Rialto>(vec![(1, 0, 0), (3, 0, 0)], 1..=3,),
Err(SubstrateError::Custom(_))
));
}
#[test]
fn make_message_weights_map_fails_if_tail_messages_are_missing() {
assert!(matches!(
make_message_weights_map::<relay_rialto_client::Rialto>(vec![(1, 0, 0), (2, 0, 0)], 1..=3,),
Err(SubstrateError::Custom(_))
));
}
#[test]
fn make_message_weights_map_fails_if_all_messages_are_missing() {
assert!(matches!(
make_message_weights_map::<relay_rialto_client::Rialto>(vec![], 1..=3),
Err(SubstrateError::Custom(_))
));
}
}
@@ -0,0 +1,193 @@
// 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/>.
//! Substrate client as Substrate messages target. The chain we connect to should have
//! runtime that implements `<BridgedChainName>HeaderApi` to allow bridging with
//! <BridgedName> chain.
use crate::messages_lane::SubstrateMessageLane;
use crate::messages_source::read_client_state;
use async_trait::async_trait;
use bp_messages::{LaneId, MessageNonce, UnrewardedRelayersState};
use bp_runtime::InstanceId;
use bridge_runtime_common::messages::source::FromBridgedChainMessagesDeliveryProof;
use codec::{Decode, Encode};
use messages_relay::{
message_lane::{SourceHeaderIdOf, TargetHeaderIdOf},
message_lane_loop::{TargetClient, TargetClientState},
};
use relay_substrate_client::{Chain, Client, Error as SubstrateError, HashOf};
use relay_utils::{relay_loop::Client as RelayClient, BlockNumberBase};
use sp_core::Bytes;
use sp_runtime::{traits::Header as HeaderT, DeserializeOwned};
use std::ops::RangeInclusive;
/// Message receiving proof returned by the target Substrate node.
pub type SubstrateMessagesReceivingProof<C> = (
UnrewardedRelayersState,
FromBridgedChainMessagesDeliveryProof<HashOf<C>>,
);
/// Substrate client as Substrate messages target.
pub struct SubstrateMessagesTarget<C: Chain, P> {
client: Client<C>,
lane: P,
lane_id: LaneId,
instance: InstanceId,
}
impl<C: Chain, P> SubstrateMessagesTarget<C, P> {
/// Create new Substrate headers target.
pub fn new(client: Client<C>, lane: P, lane_id: LaneId, instance: InstanceId) -> Self {
SubstrateMessagesTarget {
client,
lane,
lane_id,
instance,
}
}
}
impl<C: Chain, P: SubstrateMessageLane> Clone for SubstrateMessagesTarget<C, P> {
fn clone(&self) -> Self {
Self {
client: self.client.clone(),
lane: self.lane.clone(),
lane_id: self.lane_id,
instance: self.instance,
}
}
}
#[async_trait]
impl<C: Chain, P: SubstrateMessageLane> RelayClient for SubstrateMessagesTarget<C, P> {
type Error = SubstrateError;
async fn reconnect(&mut self) -> Result<(), SubstrateError> {
self.client.reconnect().await
}
}
#[async_trait]
impl<C, P> TargetClient<P> for SubstrateMessagesTarget<C, P>
where
C: Chain,
C::Header: DeserializeOwned,
C::Index: DeserializeOwned,
<C::Header as HeaderT>::Number: BlockNumberBase,
P: SubstrateMessageLane<
MessagesReceivingProof = SubstrateMessagesReceivingProof<C>,
TargetHeaderNumber = <C::Header as HeaderT>::Number,
TargetHeaderHash = <C::Header as HeaderT>::Hash,
>,
P::SourceHeaderNumber: Decode,
P::SourceHeaderHash: Decode,
{
async fn state(&self) -> Result<TargetClientState<P>, SubstrateError> {
// we can't continue to deliver messages if target node is out of sync, because
// it may have already received (some of) messages that we're going to deliver
self.client.ensure_synced().await?;
read_client_state::<_, P::SourceHeaderHash, P::SourceHeaderNumber>(
&self.client,
P::BEST_FINALIZED_SOURCE_HEADER_ID_AT_TARGET,
)
.await
}
async fn latest_received_nonce(
&self,
id: TargetHeaderIdOf<P>,
) -> Result<(TargetHeaderIdOf<P>, MessageNonce), SubstrateError> {
let encoded_response = self
.client
.state_call(
P::INBOUND_LANE_LATEST_RECEIVED_NONCE_METHOD.into(),
Bytes(self.lane_id.encode()),
Some(id.1),
)
.await?;
let latest_received_nonce: MessageNonce =
Decode::decode(&mut &encoded_response.0[..]).map_err(SubstrateError::ResponseParseFailed)?;
Ok((id, latest_received_nonce))
}
async fn latest_confirmed_received_nonce(
&self,
id: TargetHeaderIdOf<P>,
) -> Result<(TargetHeaderIdOf<P>, MessageNonce), SubstrateError> {
let encoded_response = self
.client
.state_call(
P::INBOUND_LANE_LATEST_CONFIRMED_NONCE_METHOD.into(),
Bytes(self.lane_id.encode()),
Some(id.1),
)
.await?;
let latest_received_nonce: MessageNonce =
Decode::decode(&mut &encoded_response.0[..]).map_err(SubstrateError::ResponseParseFailed)?;
Ok((id, latest_received_nonce))
}
async fn unrewarded_relayers_state(
&self,
id: TargetHeaderIdOf<P>,
) -> Result<(TargetHeaderIdOf<P>, UnrewardedRelayersState), SubstrateError> {
let encoded_response = self
.client
.state_call(
P::INBOUND_LANE_UNREWARDED_RELAYERS_STATE.into(),
Bytes(self.lane_id.encode()),
Some(id.1),
)
.await?;
let unrewarded_relayers_state: UnrewardedRelayersState =
Decode::decode(&mut &encoded_response.0[..]).map_err(SubstrateError::ResponseParseFailed)?;
Ok((id, unrewarded_relayers_state))
}
async fn prove_messages_receiving(
&self,
id: TargetHeaderIdOf<P>,
) -> Result<(TargetHeaderIdOf<P>, P::MessagesReceivingProof), SubstrateError> {
let (id, relayers_state) = self.unrewarded_relayers_state(id).await?;
let proof = self
.client
.prove_messages_delivery(self.instance, self.lane_id, id.1)
.await?;
let proof = FromBridgedChainMessagesDeliveryProof {
bridged_header_hash: id.1,
storage_proof: proof,
lane: self.lane_id,
};
Ok((id, (relayers_state, proof)))
}
async fn submit_messages_proof(
&self,
generated_at_header: SourceHeaderIdOf<P>,
nonces: RangeInclusive<MessageNonce>,
proof: P::MessagesProof,
) -> Result<RangeInclusive<MessageNonce>, SubstrateError> {
let tx = self
.lane
.make_messages_delivery_transaction(generated_at_header, nonces.clone(), proof)
.await?;
self.client.submit_extrinsic(Bytes(tx.encode())).await?;
Ok(nonces)
}
}
@@ -0,0 +1,440 @@
// Copyright 2019-2020 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/>.
//! Deal with CLI args of Rialto <> Millau relay.
use frame_support::weights::Weight;
use structopt::StructOpt;
use crate::cli::{AccountId, ExplicitOrMaximal, HexBytes, HexLaneId, Origins, PrometheusParams};
use crate::declare_chain_options;
/// Start headers relayer process.
#[derive(StructOpt)]
pub enum RelayHeaders {
/// Relay Millau headers to Rialto.
MillauToRialto {
#[structopt(flatten)]
millau: MillauConnectionParams,
#[structopt(flatten)]
rialto: RialtoConnectionParams,
#[structopt(flatten)]
rialto_sign: RialtoSigningParams,
#[structopt(flatten)]
prometheus_params: PrometheusParams,
},
/// Relay Rialto headers to Millau.
RialtoToMillau {
#[structopt(flatten)]
rialto: RialtoConnectionParams,
#[structopt(flatten)]
millau: MillauConnectionParams,
#[structopt(flatten)]
millau_sign: MillauSigningParams,
#[structopt(flatten)]
prometheus_params: PrometheusParams,
},
/// Relay Westend headers to Millau.
WestendToMillau {
#[structopt(flatten)]
westend: WestendConnectionParams,
#[structopt(flatten)]
millau: MillauConnectionParams,
#[structopt(flatten)]
millau_sign: MillauSigningParams,
#[structopt(flatten)]
prometheus_params: PrometheusParams,
},
}
impl RelayHeaders {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
super::run_relay_headers(self).await.map_err(format_err)?;
Ok(())
}
}
/// Start message relayer process.
#[derive(StructOpt)]
pub enum RelayMessages {
/// Serve given lane of Millau -> Rialto messages.
MillauToRialto {
#[structopt(flatten)]
millau: MillauConnectionParams,
#[structopt(flatten)]
millau_sign: MillauSigningParams,
#[structopt(flatten)]
rialto: RialtoConnectionParams,
#[structopt(flatten)]
rialto_sign: RialtoSigningParams,
#[structopt(flatten)]
prometheus_params: PrometheusParams,
/// Hex-encoded lane id that should be served by the relay. Defaults to `00000000`.
#[structopt(long, default_value = "00000000")]
lane: HexLaneId,
},
/// Serve given lane of Rialto -> Millau messages.
RialtoToMillau {
#[structopt(flatten)]
rialto: RialtoConnectionParams,
#[structopt(flatten)]
rialto_sign: RialtoSigningParams,
#[structopt(flatten)]
millau: MillauConnectionParams,
#[structopt(flatten)]
millau_sign: MillauSigningParams,
#[structopt(flatten)]
prometheus_params: PrometheusParams,
/// Hex-encoded lane id that should be served by the relay. Defaults to `00000000`.
#[structopt(long, default_value = "00000000")]
lane: HexLaneId,
},
}
impl RelayMessages {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
super::run_relay_messages(self).await.map_err(format_err)?;
Ok(())
}
}
/// Initialize bridge pallet.
#[derive(StructOpt)]
pub enum InitBridge {
/// Initialize Millau headers bridge in Rialto.
MillauToRialto {
#[structopt(flatten)]
millau: MillauConnectionParams,
#[structopt(flatten)]
rialto: RialtoConnectionParams,
#[structopt(flatten)]
rialto_sign: RialtoSigningParams,
},
/// Initialize Rialto headers bridge in Millau.
RialtoToMillau {
#[structopt(flatten)]
rialto: RialtoConnectionParams,
#[structopt(flatten)]
millau: MillauConnectionParams,
#[structopt(flatten)]
millau_sign: MillauSigningParams,
},
/// Initialize Westend headers bridge in Millau.
WestendToMillau {
#[structopt(flatten)]
westend: WestendConnectionParams,
#[structopt(flatten)]
millau: MillauConnectionParams,
#[structopt(flatten)]
millau_sign: MillauSigningParams,
},
}
impl InitBridge {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
super::run_init_bridge(self).await.map_err(format_err)?;
Ok(())
}
}
/// Send bridge message.
#[derive(StructOpt)]
pub enum SendMessage {
/// Submit message to given Millau -> Rialto lane.
MillauToRialto {
#[structopt(flatten)]
millau: MillauConnectionParams,
#[structopt(flatten)]
millau_sign: MillauSigningParams,
#[structopt(flatten)]
rialto_sign: RialtoSigningParams,
/// Hex-encoded lane id. Defaults to `00000000`.
#[structopt(long, default_value = "00000000")]
lane: HexLaneId,
/// Dispatch weight of the message. If not passed, determined automatically.
#[structopt(long)]
dispatch_weight: Option<ExplicitOrMaximal<Weight>>,
/// Delivery and dispatch fee in source chain base currency units. If not passed, determined automatically.
#[structopt(long)]
fee: Option<bp_millau::Balance>,
/// Message type.
#[structopt(subcommand)]
message: ToRialtoMessage,
/// The origin to use when dispatching the message on the target chain. Defaults to
/// `SourceAccount`.
#[structopt(long, possible_values = &Origins::variants(), default_value = "Source")]
origin: Origins,
},
/// Submit message to given Rialto -> Millau lane.
RialtoToMillau {
#[structopt(flatten)]
rialto: RialtoConnectionParams,
#[structopt(flatten)]
rialto_sign: RialtoSigningParams,
#[structopt(flatten)]
millau_sign: MillauSigningParams,
/// Hex-encoded lane id. Defaults to `00000000`.
#[structopt(long, default_value = "00000000")]
lane: HexLaneId,
/// Dispatch weight of the message. If not passed, determined automatically.
#[structopt(long)]
dispatch_weight: Option<ExplicitOrMaximal<Weight>>,
/// Delivery and dispatch fee in source chain base currency units. If not passed, determined automatically.
#[structopt(long)]
fee: Option<bp_rialto::Balance>,
/// Message type.
#[structopt(subcommand)]
message: ToMillauMessage,
/// The origin to use when dispatching the message on the target chain. Defaults to
/// `SourceAccount`.
#[structopt(long, possible_values = &Origins::variants(), default_value = "Source")]
origin: Origins,
},
}
impl SendMessage {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
super::run_send_message(self).await.map_err(format_err)?;
Ok(())
}
}
/// A call to encode.
#[derive(StructOpt)]
pub enum EncodeCall {
/// Encode Rialto's Call.
Rialto {
#[structopt(flatten)]
call: ToRialtoMessage,
},
/// Encode Millau's Call.
Millau {
#[structopt(flatten)]
call: ToMillauMessage,
},
}
impl EncodeCall {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
super::run_encode_call(self).await.map_err(format_err)?;
Ok(())
}
}
/// A `MessagePayload` to encode.
#[derive(StructOpt)]
pub enum EncodeMessagePayload {
/// Message Payload of Rialto to Millau call.
RialtoToMillau {
#[structopt(flatten)]
payload: RialtoToMillauMessagePayload,
},
/// Message Payload of Millau to Rialto call.
MillauToRialto {
#[structopt(flatten)]
payload: MillauToRialtoMessagePayload,
},
}
impl EncodeMessagePayload {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
super::run_encode_message_payload(self).await.map_err(format_err)?;
Ok(())
}
}
/// Estimate Delivery & Dispatch Fee command.
#[derive(StructOpt)]
pub enum EstimateFee {
/// Estimate fee of Rialto to Millau message.
RialtoToMillau {
#[structopt(flatten)]
rialto: RialtoConnectionParams,
/// Hex-encoded id of lane that will be delivering the message.
#[structopt(long)]
lane: HexLaneId,
/// Payload to send over the bridge.
#[structopt(flatten)]
payload: RialtoToMillauMessagePayload,
},
/// Estimate fee of Rialto to Millau message.
MillauToRialto {
#[structopt(flatten)]
millau: MillauConnectionParams,
/// Hex-encoded id of lane that will be delivering the message.
#[structopt(long)]
lane: HexLaneId,
/// Payload to send over the bridge.
#[structopt(flatten)]
payload: MillauToRialtoMessagePayload,
},
}
impl EstimateFee {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
super::run_estimate_fee(self).await.map_err(format_err)?;
Ok(())
}
}
/// Given a source chain `AccountId`, derive the corresponding `AccountId` for the target chain.
///
/// The (derived) target chain `AccountId` is going to be used as dispatch origin of the call
/// that has been sent over the bridge.
/// This account can also be used to receive target-chain funds (or other form of ownership),
/// since messages sent over the bridge will be able to spend these.
#[derive(StructOpt)]
pub enum DeriveAccount {
/// Given Rialto AccountId, display corresponding Millau AccountId.
RialtoToMillau { account: AccountId },
/// Given Millau AccountId, display corresponding Rialto AccountId.
MillauToRialto { account: AccountId },
}
impl DeriveAccount {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
super::run_derive_account(self).await.map_err(format_err)?;
Ok(())
}
}
fn format_err(err: String) -> anyhow::Error {
anyhow::anyhow!(err)
}
/// MessagePayload that can be delivered to messages pallet on Millau.
#[derive(StructOpt, Debug)]
pub enum MillauToRialtoMessagePayload {
/// Raw, SCALE-encoded `MessagePayload`.
Raw {
/// Hex-encoded SCALE data.
data: HexBytes,
},
/// Construct message to send over the bridge.
Message {
/// Message details.
#[structopt(flatten)]
message: ToRialtoMessage,
/// SS58 encoded account that will send the payload (must have SS58Prefix = 42)
#[structopt(long)]
sender: AccountId,
},
}
/// MessagePayload that can be delivered to messages pallet on Rialto.
#[derive(StructOpt, Debug)]
pub enum RialtoToMillauMessagePayload {
/// Raw, SCALE-encoded `MessagePayload`.
Raw {
/// Hex-encoded SCALE data.
data: HexBytes,
},
/// Construct message to send over the bridge.
Message {
/// Message details.
#[structopt(flatten)]
message: ToMillauMessage,
/// SS58 encoded account that will send the payload (must have SS58Prefix = 42)
#[structopt(long)]
sender: AccountId,
},
}
/// All possible messages that may be delivered to the Rialto chain.
#[derive(StructOpt, Debug)]
pub enum ToRialtoMessage {
/// Raw bytes for the message
Raw {
/// Raw, SCALE-encoded message
data: HexBytes,
},
/// Make an on-chain remark (comment).
Remark {
/// Remark size. If not passed, small UTF8-encoded string is generated by relay as remark.
#[structopt(long)]
remark_size: Option<ExplicitOrMaximal<usize>>,
},
/// Transfer the specified `amount` of native tokens to a particular `recipient`.
Transfer {
/// SS58 encoded account that will receive the transfer (must have SS58Prefix = 42)
#[structopt(long)]
recipient: AccountId,
/// Amount of target tokens to send in target chain base currency units.
#[structopt(long)]
amount: bp_rialto::Balance,
},
/// A call to the Millau Bridge Messages pallet to send a message over the bridge.
MillauSendMessage {
/// Hex-encoded lane id that should be served by the relay. Defaults to `00000000`.
#[structopt(long, default_value = "00000000")]
lane: HexLaneId,
/// Raw SCALE-encoded Message Payload to submit to the messages pallet.
#[structopt(long)]
payload: HexBytes,
/// Declared delivery and dispatch fee in base source-chain currency units.
#[structopt(long)]
fee: bp_rialto::Balance,
},
}
/// All possible messages that may be delivered to the Millau chain.
#[derive(StructOpt, Debug)]
pub enum ToMillauMessage {
/// Raw bytes for the message
Raw {
/// Raw, SCALE-encoded message
data: HexBytes,
},
/// Make an on-chain remark (comment).
Remark {
/// Size of the remark. If not passed, small UTF8-encoded string is generated by relay as remark.
#[structopt(long)]
remark_size: Option<ExplicitOrMaximal<usize>>,
},
/// Transfer the specified `amount` of native tokens to a particular `recipient`.
Transfer {
/// SS58 encoded account that will receive the transfer (must have SS58Prefix = 42)
#[structopt(long)]
recipient: AccountId,
/// Amount of target tokens to send in target chain base currency units.
#[structopt(long)]
amount: bp_millau::Balance,
},
/// A call to the Rialto Bridge Messages pallet to send a message over the bridge.
RialtoSendMessage {
/// Hex-encoded lane id that should be served by the relay. Defaults to `00000000`.
#[structopt(long, default_value = "00000000")]
lane: HexLaneId,
/// Raw SCALE-encoded Message Payload to submit to the messages pallet.
#[structopt(long)]
payload: HexBytes,
/// Declared delivery and dispatch fee in base source-chain currency units.
#[structopt(long)]
fee: bp_millau::Balance,
},
}
declare_chain_options!(Rialto, rialto);
declare_chain_options!(Millau, millau);
declare_chain_options!(Westend, westend);
@@ -0,0 +1,69 @@
// Copyright 2019-2020 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/>.
//! Millau-to-Rialto headers sync entrypoint.
use super::{MillauClient, RialtoClient};
use crate::finality_pipeline::{SubstrateFinalitySyncPipeline, SubstrateFinalityToSubstrate};
use async_trait::async_trait;
use relay_millau_client::{Millau, SyncHeader as MillauSyncHeader};
use relay_rialto_client::{Rialto, SigningParams as RialtoSigningParams};
use relay_substrate_client::{finality_source::Justification, Error as SubstrateError, TransactionSignScheme};
use sp_core::Pair;
/// Millau-to-Rialto finality sync pipeline.
pub(crate) type MillauFinalityToRialto = SubstrateFinalityToSubstrate<Millau, Rialto, RialtoSigningParams>;
#[async_trait]
impl SubstrateFinalitySyncPipeline for MillauFinalityToRialto {
const BEST_FINALIZED_SOURCE_HEADER_ID_AT_TARGET: &'static str = bp_millau::BEST_FINALIZED_MILLAU_HEADER_METHOD;
type SignedTransaction = <Rialto as TransactionSignScheme>::SignedTransaction;
async fn make_submit_finality_proof_transaction(
&self,
header: MillauSyncHeader,
proof: Justification<bp_millau::BlockNumber>,
) -> Result<Self::SignedTransaction, SubstrateError> {
let account_id = self.target_sign.signer.public().as_array_ref().clone().into();
let nonce = self.target_client.next_account_index(account_id).await?;
let call =
rialto_runtime::FinalityBridgeMillauCall::submit_finality_proof(header.into_inner(), proof.into_inner())
.into();
let genesis_hash = *self.target_client.genesis_hash();
let transaction = Rialto::sign_transaction(genesis_hash, &self.target_sign.signer, nonce, call);
Ok(transaction)
}
}
/// Run Millau-to-Rialto finality sync.
pub async fn run(
millau_client: MillauClient,
rialto_client: RialtoClient,
rialto_sign: RialtoSigningParams,
metrics_params: Option<relay_utils::metrics::MetricsParams>,
) {
crate::finality_pipeline::run(
MillauFinalityToRialto::new(rialto_client.clone(), rialto_sign),
millau_client,
rialto_client,
metrics_params,
)
.await;
}
@@ -0,0 +1,190 @@
// Copyright 2019-2020 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/>.
//! Millau-to-Rialto messages sync entrypoint.
use super::{MillauClient, RialtoClient};
use crate::messages_lane::{select_delivery_transaction_limits, SubstrateMessageLane, SubstrateMessageLaneToSubstrate};
use crate::messages_source::SubstrateMessagesSource;
use crate::messages_target::SubstrateMessagesTarget;
use async_trait::async_trait;
use bp_messages::{LaneId, MessageNonce};
use bp_runtime::{MILLAU_BRIDGE_INSTANCE, RIALTO_BRIDGE_INSTANCE};
use bridge_runtime_common::messages::target::FromBridgedChainMessagesProof;
use codec::Encode;
use frame_support::dispatch::GetDispatchInfo;
use messages_relay::message_lane::MessageLane;
use relay_millau_client::{HeaderId as MillauHeaderId, Millau, SigningParams as MillauSigningParams};
use relay_rialto_client::{HeaderId as RialtoHeaderId, Rialto, SigningParams as RialtoSigningParams};
use relay_substrate_client::{Chain, Error as SubstrateError, TransactionSignScheme};
use relay_utils::metrics::MetricsParams;
use sp_core::Pair;
use std::{ops::RangeInclusive, time::Duration};
/// Millau-to-Rialto message lane.
type MillauMessagesToRialto = SubstrateMessageLaneToSubstrate<Millau, MillauSigningParams, Rialto, RialtoSigningParams>;
#[async_trait]
impl SubstrateMessageLane for MillauMessagesToRialto {
const OUTBOUND_LANE_MESSAGES_DISPATCH_WEIGHT_METHOD: &'static str =
bp_rialto::TO_RIALTO_MESSAGES_DISPATCH_WEIGHT_METHOD;
const OUTBOUND_LANE_LATEST_GENERATED_NONCE_METHOD: &'static str =
bp_rialto::TO_RIALTO_LATEST_GENERATED_NONCE_METHOD;
const OUTBOUND_LANE_LATEST_RECEIVED_NONCE_METHOD: &'static str = bp_rialto::TO_RIALTO_LATEST_RECEIVED_NONCE_METHOD;
const INBOUND_LANE_LATEST_RECEIVED_NONCE_METHOD: &'static str = bp_millau::FROM_MILLAU_LATEST_RECEIVED_NONCE_METHOD;
const INBOUND_LANE_LATEST_CONFIRMED_NONCE_METHOD: &'static str =
bp_millau::FROM_MILLAU_LATEST_CONFIRMED_NONCE_METHOD;
const INBOUND_LANE_UNREWARDED_RELAYERS_STATE: &'static str = bp_millau::FROM_MILLAU_UNREWARDED_RELAYERS_STATE;
const BEST_FINALIZED_SOURCE_HEADER_ID_AT_TARGET: &'static str = bp_millau::BEST_FINALIZED_MILLAU_HEADER_METHOD;
const BEST_FINALIZED_TARGET_HEADER_ID_AT_SOURCE: &'static str = bp_rialto::BEST_FINALIZED_RIALTO_HEADER_METHOD;
type SourceSignedTransaction = <Millau as TransactionSignScheme>::SignedTransaction;
type TargetSignedTransaction = <Rialto as TransactionSignScheme>::SignedTransaction;
async fn make_messages_receiving_proof_transaction(
&self,
_generated_at_block: RialtoHeaderId,
proof: <Self as MessageLane>::MessagesReceivingProof,
) -> Result<Self::SourceSignedTransaction, SubstrateError> {
let (relayers_state, proof) = proof;
let account_id = self.source_sign.signer.public().as_array_ref().clone().into();
let nonce = self.source_client.next_account_index(account_id).await?;
let call: millau_runtime::Call =
millau_runtime::MessagesCall::receive_messages_delivery_proof(proof, relayers_state).into();
let call_weight = call.get_dispatch_info().weight;
let genesis_hash = *self.source_client.genesis_hash();
let transaction = Millau::sign_transaction(genesis_hash, &self.source_sign.signer, nonce, call);
log::trace!(
target: "bridge",
"Prepared Rialto -> Millau confirmation transaction. Weight: {}/{}, size: {}/{}",
call_weight,
bp_millau::max_extrinsic_weight(),
transaction.encode().len(),
bp_millau::max_extrinsic_size(),
);
Ok(transaction)
}
async fn make_messages_delivery_transaction(
&self,
_generated_at_header: MillauHeaderId,
_nonces: RangeInclusive<MessageNonce>,
proof: <Self as MessageLane>::MessagesProof,
) -> Result<Self::TargetSignedTransaction, SubstrateError> {
let (dispatch_weight, proof) = proof;
let FromBridgedChainMessagesProof {
ref nonces_start,
ref nonces_end,
..
} = proof;
let messages_count = nonces_end - nonces_start + 1;
let account_id = self.target_sign.signer.public().as_array_ref().clone().into();
let nonce = self.target_client.next_account_index(account_id).await?;
let call: rialto_runtime::Call = rialto_runtime::MessagesCall::receive_messages_proof(
self.relayer_id_at_source.clone(),
proof,
messages_count as _,
dispatch_weight,
)
.into();
let call_weight = call.get_dispatch_info().weight;
let genesis_hash = *self.target_client.genesis_hash();
let transaction = Rialto::sign_transaction(genesis_hash, &self.target_sign.signer, nonce, call);
log::trace!(
target: "bridge",
"Prepared Millau -> Rialto delivery transaction. Weight: {}/{}, size: {}/{}",
call_weight,
bp_rialto::max_extrinsic_weight(),
transaction.encode().len(),
bp_rialto::max_extrinsic_size(),
);
Ok(transaction)
}
}
/// Millau node as messages source.
type MillauSourceClient = SubstrateMessagesSource<Millau, MillauMessagesToRialto>;
/// Rialto node as messages target.
type RialtoTargetClient = SubstrateMessagesTarget<Rialto, MillauMessagesToRialto>;
/// Run Millau-to-Rialto messages sync.
pub async fn run(
millau_client: MillauClient,
millau_sign: MillauSigningParams,
rialto_client: RialtoClient,
rialto_sign: RialtoSigningParams,
lane_id: LaneId,
metrics_params: Option<MetricsParams>,
) {
let stall_timeout = Duration::from_secs(5 * 60);
let relayer_id_at_millau = millau_sign.signer.public().as_array_ref().clone().into();
let lane = MillauMessagesToRialto {
source_client: millau_client.clone(),
source_sign: millau_sign,
target_client: rialto_client.clone(),
target_sign: rialto_sign,
relayer_id_at_source: relayer_id_at_millau,
};
// 2/3 is reserved for proofs and tx overhead
let max_messages_size_in_single_batch = bp_rialto::max_extrinsic_size() as usize / 3;
// TODO: use Millau weights after https://github.com/paritytech/parity-bridges-common/issues/390
let (max_messages_in_single_batch, max_messages_weight_in_single_batch) =
select_delivery_transaction_limits::<pallet_bridge_messages::weights::RialtoWeight<millau_runtime::Runtime>>(
bp_rialto::max_extrinsic_weight(),
bp_rialto::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE,
);
log::info!(
target: "bridge",
"Starting Millau -> Rialto messages relay.\n\t\
Millau relayer account id: {:?}\n\t\
Max messages in single transaction: {}\n\t\
Max messages size in single transaction: {}\n\t\
Max messages weight in single transaction: {}",
lane.relayer_id_at_source,
max_messages_in_single_batch,
max_messages_size_in_single_batch,
max_messages_weight_in_single_batch,
);
messages_relay::message_lane_loop::run(
messages_relay::message_lane_loop::Params {
lane: lane_id,
source_tick: Millau::AVERAGE_BLOCK_INTERVAL,
target_tick: Rialto::AVERAGE_BLOCK_INTERVAL,
reconnect_delay: relay_utils::relay_loop::RECONNECT_DELAY,
stall_timeout,
delivery_params: messages_relay::message_lane_loop::MessageDeliveryParams {
max_unrewarded_relayer_entries_at_target: bp_rialto::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE,
max_unconfirmed_nonces_at_target: bp_rialto::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE,
max_messages_in_single_batch,
max_messages_weight_in_single_batch,
max_messages_size_in_single_batch,
},
},
MillauSourceClient::new(millau_client, lane.clone(), lane_id, RIALTO_BRIDGE_INSTANCE),
RialtoTargetClient::new(rialto_client, lane, lane_id, MILLAU_BRIDGE_INSTANCE),
metrics_params,
futures::future::pending(),
)
.await;
}
@@ -0,0 +1,973 @@
// Copyright 2019-2020 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/>.
//! Rialto <> Millau Bridge commands.
pub mod cli;
pub mod millau_headers_to_rialto;
pub mod millau_messages_to_rialto;
pub mod rialto_headers_to_millau;
pub mod rialto_messages_to_millau;
pub mod westend_headers_to_millau;
/// Millau node client.
pub type MillauClient = relay_substrate_client::Client<Millau>;
/// Rialto node client.
pub type RialtoClient = relay_substrate_client::Client<Rialto>;
/// Westend node client.
pub type WestendClient = relay_substrate_client::Client<Westend>;
use crate::cli::{ExplicitOrMaximal, HexBytes, Origins};
use codec::{Decode, Encode};
use frame_support::weights::{GetDispatchInfo, Weight};
use pallet_bridge_call_dispatch::{CallOrigin, MessagePayload};
use relay_millau_client::{Millau, SigningParams as MillauSigningParams};
use relay_rialto_client::{Rialto, SigningParams as RialtoSigningParams};
use relay_substrate_client::{Chain, ConnectionParams, TransactionSignScheme};
use relay_westend_client::Westend;
use sp_core::{Bytes, Pair};
use sp_runtime::traits::IdentifyAccount;
use std::fmt::Debug;
async fn run_init_bridge(command: cli::InitBridge) -> Result<(), String> {
match command {
cli::InitBridge::MillauToRialto {
millau,
rialto,
rialto_sign,
} => {
let millau_client = millau.into_client().await?;
let rialto_client = rialto.into_client().await?;
let rialto_sign = rialto_sign.parse()?;
let rialto_signer_next_index = rialto_client
.next_account_index(rialto_sign.signer.public().into())
.await?;
crate::headers_initialize::initialize(millau_client, rialto_client.clone(), move |initialization_data| {
Ok(Bytes(
Rialto::sign_transaction(
*rialto_client.genesis_hash(),
&rialto_sign.signer,
rialto_signer_next_index,
rialto_runtime::SudoCall::sudo(Box::new(
rialto_runtime::FinalityBridgeMillauCall::initialize(initialization_data).into(),
))
.into(),
)
.encode(),
))
})
.await;
}
cli::InitBridge::RialtoToMillau {
rialto,
millau,
millau_sign,
} => {
let rialto_client = rialto.into_client().await?;
let millau_client = millau.into_client().await?;
let millau_sign = millau_sign.parse()?;
let millau_signer_next_index = millau_client
.next_account_index(millau_sign.signer.public().into())
.await?;
crate::headers_initialize::initialize(rialto_client, millau_client.clone(), move |initialization_data| {
let initialize_call = millau_runtime::FinalityBridgeRialtoCall::<
millau_runtime::Runtime,
millau_runtime::RialtoFinalityVerifierInstance,
>::initialize(initialization_data);
Ok(Bytes(
Millau::sign_transaction(
*millau_client.genesis_hash(),
&millau_sign.signer,
millau_signer_next_index,
millau_runtime::SudoCall::sudo(Box::new(initialize_call.into())).into(),
)
.encode(),
))
})
.await;
}
cli::InitBridge::WestendToMillau {
westend,
millau,
millau_sign,
} => {
let westend_client = westend.into_client().await?;
let millau_client = millau.into_client().await?;
let millau_sign = millau_sign.parse()?;
let millau_signer_next_index = millau_client
.next_account_index(millau_sign.signer.public().into())
.await?;
// at Westend -> Millau initialization we're not using sudo, because otherwise our deployments
// may fail, because we need to initialize both Rialto -> Millau and Westend -> Millau bridge.
// => since there's single possible sudo account, one of transaction may fail with duplicate nonce error
crate::headers_initialize::initialize(westend_client, millau_client.clone(), move |initialization_data| {
let initialize_call = millau_runtime::FinalityBridgeWestendCall::<
millau_runtime::Runtime,
millau_runtime::WestendFinalityVerifierInstance,
>::initialize(initialization_data);
Ok(Bytes(
Millau::sign_transaction(
*millau_client.genesis_hash(),
&millau_sign.signer,
millau_signer_next_index,
initialize_call.into(),
)
.encode(),
))
})
.await;
}
}
Ok(())
}
async fn run_relay_headers(command: cli::RelayHeaders) -> Result<(), String> {
match command {
cli::RelayHeaders::MillauToRialto {
millau,
rialto,
rialto_sign,
prometheus_params,
} => {
let millau_client = millau.into_client().await?;
let rialto_client = rialto.into_client().await?;
let rialto_sign = rialto_sign.parse()?;
millau_headers_to_rialto::run(millau_client, rialto_client, rialto_sign, prometheus_params.into()).await;
}
cli::RelayHeaders::RialtoToMillau {
rialto,
millau,
millau_sign,
prometheus_params,
} => {
let rialto_client = rialto.into_client().await?;
let millau_client = millau.into_client().await?;
let millau_sign = millau_sign.parse()?;
rialto_headers_to_millau::run(rialto_client, millau_client, millau_sign, prometheus_params.into()).await;
}
cli::RelayHeaders::WestendToMillau {
westend,
millau,
millau_sign,
prometheus_params,
} => {
let westend_client = westend.into_client().await?;
let millau_client = millau.into_client().await?;
let millau_sign = millau_sign.parse()?;
westend_headers_to_millau::run(westend_client, millau_client, millau_sign, prometheus_params.into()).await;
}
}
Ok(())
}
async fn run_relay_messages(command: cli::RelayMessages) -> Result<(), String> {
match command {
cli::RelayMessages::MillauToRialto {
millau,
millau_sign,
rialto,
rialto_sign,
prometheus_params,
lane,
} => {
let millau_client = millau.into_client().await?;
let millau_sign = millau_sign.parse()?;
let rialto_client = rialto.into_client().await?;
let rialto_sign = rialto_sign.parse()?;
millau_messages_to_rialto::run(
millau_client,
millau_sign,
rialto_client,
rialto_sign,
lane.into(),
prometheus_params.into(),
)
.await;
}
cli::RelayMessages::RialtoToMillau {
rialto,
rialto_sign,
millau,
millau_sign,
prometheus_params,
lane,
} => {
let rialto_client = rialto.into_client().await?;
let rialto_sign = rialto_sign.parse()?;
let millau_client = millau.into_client().await?;
let millau_sign = millau_sign.parse()?;
rialto_messages_to_millau::run(
rialto_client,
rialto_sign,
millau_client,
millau_sign,
lane.into(),
prometheus_params.into(),
)
.await;
}
}
Ok(())
}
async fn run_send_message(command: cli::SendMessage) -> Result<(), String> {
match command {
cli::SendMessage::MillauToRialto {
millau,
millau_sign,
rialto_sign,
lane,
message,
dispatch_weight,
fee,
origin,
..
} => {
let millau_client = millau.into_client().await?;
let millau_sign = millau_sign.parse()?;
let rialto_sign = rialto_sign.parse()?;
let rialto_call = message.into_call()?;
let payload =
millau_to_rialto_message_payload(&millau_sign, &rialto_sign, &rialto_call, origin, dispatch_weight);
let dispatch_weight = payload.weight;
let lane = lane.into();
let fee = get_fee(fee, || {
estimate_message_delivery_and_dispatch_fee(
&millau_client,
bp_rialto::TO_RIALTO_ESTIMATE_MESSAGE_FEE_METHOD,
lane,
payload.clone(),
)
})
.await?;
let millau_call = millau_runtime::Call::BridgeRialtoMessages(millau_runtime::MessagesCall::send_message(
lane, payload, fee,
));
let signed_millau_call = Millau::sign_transaction(
*millau_client.genesis_hash(),
&millau_sign.signer,
millau_client
.next_account_index(millau_sign.signer.public().clone().into())
.await?,
millau_call,
)
.encode();
log::info!(
target: "bridge",
"Sending message to Rialto. Size: {}. Dispatch weight: {}. Fee: {}",
signed_millau_call.len(),
dispatch_weight,
fee,
);
log::info!(target: "bridge", "Signed Millau Call: {:?}", HexBytes::encode(&signed_millau_call));
millau_client.submit_extrinsic(Bytes(signed_millau_call)).await?;
}
cli::SendMessage::RialtoToMillau {
rialto,
rialto_sign,
millau_sign,
lane,
message,
dispatch_weight,
fee,
origin,
..
} => {
let rialto_client = rialto.into_client().await?;
let rialto_sign = rialto_sign.parse()?;
let millau_sign = millau_sign.parse()?;
let millau_call = message.into_call()?;
let payload =
rialto_to_millau_message_payload(&rialto_sign, &millau_sign, &millau_call, origin, dispatch_weight);
let dispatch_weight = payload.weight;
let lane = lane.into();
let fee = get_fee(fee, || {
estimate_message_delivery_and_dispatch_fee(
&rialto_client,
bp_millau::TO_MILLAU_ESTIMATE_MESSAGE_FEE_METHOD,
lane,
payload.clone(),
)
})
.await?;
let rialto_call = rialto_runtime::Call::BridgeMillauMessages(rialto_runtime::MessagesCall::send_message(
lane, payload, fee,
));
let signed_rialto_call = Rialto::sign_transaction(
*rialto_client.genesis_hash(),
&rialto_sign.signer,
rialto_client
.next_account_index(rialto_sign.signer.public().clone().into())
.await?,
rialto_call,
)
.encode();
log::info!(
target: "bridge",
"Sending message to Millau. Size: {}. Dispatch weight: {}. Fee: {}",
signed_rialto_call.len(),
dispatch_weight,
fee,
);
log::info!(target: "bridge", "Signed Rialto Call: {:?}", HexBytes::encode(&signed_rialto_call));
rialto_client.submit_extrinsic(Bytes(signed_rialto_call)).await?;
}
}
Ok(())
}
async fn run_encode_call(call: cli::EncodeCall) -> Result<(), String> {
match call {
cli::EncodeCall::Rialto { call } => {
let call = call.into_call()?;
println!("{:?}", HexBytes::encode(&call));
}
cli::EncodeCall::Millau { call } => {
let call = call.into_call()?;
println!("{:?}", HexBytes::encode(&call));
}
}
Ok(())
}
async fn run_encode_message_payload(call: cli::EncodeMessagePayload) -> Result<(), String> {
match call {
cli::EncodeMessagePayload::RialtoToMillau { payload } => {
let payload = payload.into_payload()?;
println!("{:?}", HexBytes::encode(&payload));
}
cli::EncodeMessagePayload::MillauToRialto { payload } => {
let payload = payload.into_payload()?;
println!("{:?}", HexBytes::encode(&payload));
}
}
Ok(())
}
async fn run_estimate_fee(cmd: cli::EstimateFee) -> Result<(), String> {
match cmd {
cli::EstimateFee::RialtoToMillau { rialto, lane, payload } => {
let client = rialto.into_client().await?;
let lane = lane.into();
let payload = payload.into_payload()?;
let fee: Option<bp_rialto::Balance> = estimate_message_delivery_and_dispatch_fee(
&client,
bp_millau::TO_MILLAU_ESTIMATE_MESSAGE_FEE_METHOD,
lane,
payload,
)
.await?;
println!("Fee: {:?}", fee);
}
cli::EstimateFee::MillauToRialto { millau, lane, payload } => {
let client = millau.into_client().await?;
let lane = lane.into();
let payload = payload.into_payload()?;
let fee: Option<bp_millau::Balance> = estimate_message_delivery_and_dispatch_fee(
&client,
bp_rialto::TO_RIALTO_ESTIMATE_MESSAGE_FEE_METHOD,
lane,
payload,
)
.await?;
println!("Fee: {:?}", fee);
}
}
Ok(())
}
async fn run_derive_account(cmd: cli::DeriveAccount) -> Result<(), String> {
match cmd {
cli::DeriveAccount::RialtoToMillau { account } => {
let account = account.into_rialto();
let acc = bp_runtime::SourceAccount::Account(account.clone());
let id = bp_millau::derive_account_from_rialto_id(acc);
println!(
"{} (Rialto)\n\nCorresponding (derived) account id:\n-> {} (Millau)",
account, id
)
}
cli::DeriveAccount::MillauToRialto { account } => {
let account = account.into_millau();
let acc = bp_runtime::SourceAccount::Account(account.clone());
let id = bp_rialto::derive_account_from_millau_id(acc);
println!(
"{} (Millau)\n\nCorresponding (derived) account id:\n-> {} (Rialto)",
account, id
)
}
}
Ok(())
}
async fn estimate_message_delivery_and_dispatch_fee<Fee: Decode, C: Chain, P: Encode>(
client: &relay_substrate_client::Client<C>,
estimate_fee_method: &str,
lane: bp_messages::LaneId,
payload: P,
) -> Result<Option<Fee>, relay_substrate_client::Error> {
let encoded_response = client
.state_call(estimate_fee_method.into(), (lane, payload).encode().into(), None)
.await?;
let decoded_response: Option<Fee> =
Decode::decode(&mut &encoded_response.0[..]).map_err(relay_substrate_client::Error::ResponseParseFailed)?;
Ok(decoded_response)
}
fn remark_payload(remark_size: Option<ExplicitOrMaximal<usize>>, maximal_allowed_size: u32) -> Vec<u8> {
match remark_size {
Some(ExplicitOrMaximal::Explicit(remark_size)) => vec![0; remark_size],
Some(ExplicitOrMaximal::Maximal) => vec![0; maximal_allowed_size as _],
None => format!(
"Unix time: {}",
std::time::SystemTime::now()
.duration_since(std::time::SystemTime::UNIX_EPOCH)
.unwrap_or_default()
.as_secs(),
)
.as_bytes()
.to_vec(),
}
}
fn message_payload<SAccountId, TPublic, TSignature>(
spec_version: u32,
weight: Weight,
origin: CallOrigin<SAccountId, TPublic, TSignature>,
call: &impl Encode,
) -> MessagePayload<SAccountId, TPublic, TSignature, Vec<u8>>
where
SAccountId: Encode + Debug,
TPublic: Encode + Debug,
TSignature: Encode + Debug,
{
// Display nicely formatted call.
let payload = MessagePayload {
spec_version,
weight,
origin,
call: HexBytes::encode(call),
};
log::info!(target: "bridge", "Created Message Payload: {:#?}", payload);
log::info!(target: "bridge", "Encoded Message Payload: {:?}", HexBytes::encode(&payload));
// re-pack to return `Vec<u8>`
let MessagePayload {
spec_version,
weight,
origin,
call,
} = payload;
MessagePayload {
spec_version,
weight,
origin,
call: call.0,
}
}
fn rialto_to_millau_message_payload(
rialto_sign: &RialtoSigningParams,
millau_sign: &MillauSigningParams,
millau_call: &millau_runtime::Call,
origin: Origins,
user_specified_dispatch_weight: Option<ExplicitOrMaximal<Weight>>,
) -> rialto_runtime::millau_messages::ToMillauMessagePayload {
let millau_call_weight = prepare_call_dispatch_weight(
user_specified_dispatch_weight,
ExplicitOrMaximal::Explicit(millau_call.get_dispatch_info().weight),
compute_maximal_message_dispatch_weight(bp_millau::max_extrinsic_weight()),
);
let rialto_sender_public: bp_rialto::AccountSigner = rialto_sign.signer.public().clone().into();
let rialto_account_id: bp_rialto::AccountId = rialto_sender_public.into_account();
let millau_origin_public = millau_sign.signer.public();
message_payload(
millau_runtime::VERSION.spec_version,
millau_call_weight,
match origin {
Origins::Source => CallOrigin::SourceAccount(rialto_account_id),
Origins::Target => {
let digest = rialto_runtime::millau_account_ownership_digest(
&millau_call,
rialto_account_id.clone(),
millau_runtime::VERSION.spec_version,
);
let digest_signature = millau_sign.signer.sign(&digest);
CallOrigin::TargetAccount(rialto_account_id, millau_origin_public.into(), digest_signature.into())
}
},
&millau_call,
)
}
fn millau_to_rialto_message_payload(
millau_sign: &MillauSigningParams,
rialto_sign: &RialtoSigningParams,
rialto_call: &rialto_runtime::Call,
origin: Origins,
user_specified_dispatch_weight: Option<ExplicitOrMaximal<Weight>>,
) -> millau_runtime::rialto_messages::ToRialtoMessagePayload {
let rialto_call_weight = prepare_call_dispatch_weight(
user_specified_dispatch_weight,
ExplicitOrMaximal::Explicit(rialto_call.get_dispatch_info().weight),
compute_maximal_message_dispatch_weight(bp_rialto::max_extrinsic_weight()),
);
let millau_sender_public: bp_millau::AccountSigner = millau_sign.signer.public().clone().into();
let millau_account_id: bp_millau::AccountId = millau_sender_public.into_account();
let rialto_origin_public = rialto_sign.signer.public();
message_payload(
rialto_runtime::VERSION.spec_version,
rialto_call_weight,
match origin {
Origins::Source => CallOrigin::SourceAccount(millau_account_id),
Origins::Target => {
let digest = millau_runtime::rialto_account_ownership_digest(
&rialto_call,
millau_account_id.clone(),
rialto_runtime::VERSION.spec_version,
);
let digest_signature = rialto_sign.signer.sign(&digest);
CallOrigin::TargetAccount(millau_account_id, rialto_origin_public.into(), digest_signature.into())
}
},
&rialto_call,
)
}
fn prepare_call_dispatch_weight(
user_specified_dispatch_weight: Option<ExplicitOrMaximal<Weight>>,
weight_from_pre_dispatch_call: ExplicitOrMaximal<Weight>,
maximal_allowed_weight: Weight,
) -> Weight {
match user_specified_dispatch_weight.unwrap_or(weight_from_pre_dispatch_call) {
ExplicitOrMaximal::Explicit(weight) => weight,
ExplicitOrMaximal::Maximal => maximal_allowed_weight,
}
}
async fn get_fee<Fee, F, R, E>(fee: Option<Fee>, f: F) -> Result<Fee, String>
where
Fee: Decode,
F: FnOnce() -> R,
R: std::future::Future<Output = Result<Option<Fee>, E>>,
E: Debug,
{
match fee {
Some(fee) => Ok(fee),
None => match f().await {
Ok(Some(fee)) => Ok(fee),
Ok(None) => Err("Failed to estimate message fee. Message is too heavy?".into()),
Err(error) => Err(format!("Failed to estimate message fee: {:?}", error)),
},
}
}
fn compute_maximal_message_dispatch_weight(maximal_extrinsic_weight: Weight) -> Weight {
bridge_runtime_common::messages::target::maximal_incoming_message_dispatch_weight(maximal_extrinsic_weight)
}
fn compute_maximal_message_arguments_size(
maximal_source_extrinsic_size: u32,
maximal_target_extrinsic_size: u32,
) -> u32 {
// assume that both signed extensions and other arguments fit 1KB
let service_tx_bytes_on_source_chain = 1024;
let maximal_source_extrinsic_size = maximal_source_extrinsic_size - service_tx_bytes_on_source_chain;
let maximal_call_size =
bridge_runtime_common::messages::target::maximal_incoming_message_size(maximal_target_extrinsic_size);
let maximal_call_size = if maximal_call_size > maximal_source_extrinsic_size {
maximal_source_extrinsic_size
} else {
maximal_call_size
};
// bytes in Call encoding that are used to encode everything except arguments
let service_bytes = 1 + 1 + 4;
maximal_call_size - service_bytes
}
impl cli::MillauToRialtoMessagePayload {
/// Parse the CLI parameters and construct message payload.
pub fn into_payload(
self,
) -> Result<MessagePayload<bp_rialto::AccountId, bp_rialto::AccountSigner, bp_rialto::Signature, Vec<u8>>, String> {
match self {
Self::Raw { data } => MessagePayload::decode(&mut &*data.0)
.map_err(|e| format!("Failed to decode Millau's MessagePayload: {:?}", e)),
Self::Message { message, sender } => {
let spec_version = rialto_runtime::VERSION.spec_version;
let origin = CallOrigin::SourceAccount(sender.into_millau());
let call = message.into_call()?;
let weight = call.get_dispatch_info().weight;
Ok(message_payload(spec_version, weight, origin, &call))
}
}
}
}
impl cli::RialtoToMillauMessagePayload {
/// Parse the CLI parameters and construct message payload.
pub fn into_payload(
self,
) -> Result<MessagePayload<bp_millau::AccountId, bp_millau::AccountSigner, bp_millau::Signature, Vec<u8>>, String> {
match self {
Self::Raw { data } => MessagePayload::decode(&mut &*data.0)
.map_err(|e| format!("Failed to decode Rialto's MessagePayload: {:?}", e)),
Self::Message { message, sender } => {
let spec_version = millau_runtime::VERSION.spec_version;
let origin = CallOrigin::SourceAccount(sender.into_rialto());
let call = message.into_call()?;
let weight = call.get_dispatch_info().weight;
Ok(message_payload(spec_version, weight, origin, &call))
}
}
}
}
impl cli::RialtoSigningParams {
/// Parse CLI parameters into typed signing params.
pub fn parse(self) -> Result<RialtoSigningParams, String> {
RialtoSigningParams::from_suri(&self.rialto_signer, self.rialto_signer_password.as_deref())
.map_err(|e| format!("Failed to parse rialto-signer: {:?}", e))
}
}
impl cli::MillauSigningParams {
/// Parse CLI parameters into typed signing params.
pub fn parse(self) -> Result<MillauSigningParams, String> {
MillauSigningParams::from_suri(&self.millau_signer, self.millau_signer_password.as_deref())
.map_err(|e| format!("Failed to parse millau-signer: {:?}", e))
}
}
impl cli::MillauConnectionParams {
/// Convert CLI connection parameters into Millau RPC Client.
pub async fn into_client(self) -> relay_substrate_client::Result<MillauClient> {
MillauClient::new(ConnectionParams {
host: self.millau_host,
port: self.millau_port,
secure: self.millau_secure,
})
.await
}
}
impl cli::RialtoConnectionParams {
/// Convert CLI connection parameters into Rialto RPC Client.
pub async fn into_client(self) -> relay_substrate_client::Result<RialtoClient> {
RialtoClient::new(ConnectionParams {
host: self.rialto_host,
port: self.rialto_port,
secure: self.rialto_secure,
})
.await
}
}
impl cli::WestendConnectionParams {
/// Convert CLI connection parameters into Westend RPC Client.
pub async fn into_client(self) -> relay_substrate_client::Result<WestendClient> {
WestendClient::new(ConnectionParams {
host: self.westend_host,
port: self.westend_port,
secure: self.westend_secure,
})
.await
}
}
impl cli::ToRialtoMessage {
/// Convert CLI call request into runtime `Call` instance.
pub fn into_call(self) -> Result<rialto_runtime::Call, String> {
let call = match self {
cli::ToRialtoMessage::Raw { data } => {
Decode::decode(&mut &*data.0).map_err(|e| format!("Unable to decode message: {:#?}", e))?
}
cli::ToRialtoMessage::Remark { remark_size } => {
rialto_runtime::Call::System(rialto_runtime::SystemCall::remark(remark_payload(
remark_size,
compute_maximal_message_arguments_size(
bp_millau::max_extrinsic_size(),
bp_rialto::max_extrinsic_size(),
),
)))
}
cli::ToRialtoMessage::Transfer { recipient, amount } => {
let recipient = recipient.into_rialto();
rialto_runtime::Call::Balances(rialto_runtime::BalancesCall::transfer(recipient, amount))
}
cli::ToRialtoMessage::MillauSendMessage { lane, payload, fee } => {
let payload = cli::RialtoToMillauMessagePayload::Raw { data: payload }.into_payload()?;
let lane = lane.into();
rialto_runtime::Call::BridgeMillauMessages(rialto_runtime::MessagesCall::send_message(
lane, payload, fee,
))
}
};
log::info!(target: "bridge", "Generated Rialto call: {:#?}", call);
log::info!(target: "bridge", "Weight of Rialto call: {}", call.get_dispatch_info().weight);
log::info!(target: "bridge", "Encoded Rialto call: {:?}", HexBytes::encode(&call));
Ok(call)
}
}
impl cli::ToMillauMessage {
/// Convert CLI call request into runtime `Call` instance.
pub fn into_call(self) -> Result<millau_runtime::Call, String> {
let call = match self {
cli::ToMillauMessage::Raw { data } => {
Decode::decode(&mut &*data.0).map_err(|e| format!("Unable to decode message: {:#?}", e))?
}
cli::ToMillauMessage::Remark { remark_size } => {
millau_runtime::Call::System(millau_runtime::SystemCall::remark(remark_payload(
remark_size,
compute_maximal_message_arguments_size(
bp_rialto::max_extrinsic_size(),
bp_millau::max_extrinsic_size(),
),
)))
}
cli::ToMillauMessage::Transfer { recipient, amount } => {
let recipient = recipient.into_millau();
millau_runtime::Call::Balances(millau_runtime::BalancesCall::transfer(recipient, amount))
}
cli::ToMillauMessage::RialtoSendMessage { lane, payload, fee } => {
let payload = cli::MillauToRialtoMessagePayload::Raw { data: payload }.into_payload()?;
let lane = lane.into();
millau_runtime::Call::BridgeRialtoMessages(millau_runtime::MessagesCall::send_message(
lane, payload, fee,
))
}
};
log::info!(target: "bridge", "Generated Millau call: {:#?}", call);
log::info!(target: "bridge", "Weight of Millau call: {}", call.get_dispatch_info().weight);
log::info!(target: "bridge", "Encoded Millau call: {:?}", HexBytes::encode(&call));
Ok(call)
}
}
#[cfg(test)]
mod tests {
use super::*;
use bp_messages::source_chain::TargetHeaderChain;
use sp_core::Pair;
use sp_runtime::traits::{IdentifyAccount, Verify};
#[test]
fn millau_signature_is_valid_on_rialto() {
let millau_sign = relay_millau_client::SigningParams::from_suri("//Dave", None).unwrap();
let call = rialto_runtime::Call::System(rialto_runtime::SystemCall::remark(vec![]));
let millau_public: bp_millau::AccountSigner = millau_sign.signer.public().clone().into();
let millau_account_id: bp_millau::AccountId = millau_public.into_account();
let digest = millau_runtime::rialto_account_ownership_digest(
&call,
millau_account_id,
rialto_runtime::VERSION.spec_version,
);
let rialto_signer = relay_rialto_client::SigningParams::from_suri("//Dave", None).unwrap();
let signature = rialto_signer.signer.sign(&digest);
assert!(signature.verify(&digest[..], &rialto_signer.signer.public()));
}
#[test]
fn rialto_signature_is_valid_on_millau() {
let rialto_sign = relay_rialto_client::SigningParams::from_suri("//Dave", None).unwrap();
let call = millau_runtime::Call::System(millau_runtime::SystemCall::remark(vec![]));
let rialto_public: bp_rialto::AccountSigner = rialto_sign.signer.public().clone().into();
let rialto_account_id: bp_rialto::AccountId = rialto_public.into_account();
let digest = rialto_runtime::millau_account_ownership_digest(
&call,
rialto_account_id,
millau_runtime::VERSION.spec_version,
);
let millau_signer = relay_millau_client::SigningParams::from_suri("//Dave", None).unwrap();
let signature = millau_signer.signer.sign(&digest);
assert!(signature.verify(&digest[..], &millau_signer.signer.public()));
}
#[test]
fn maximal_rialto_to_millau_message_arguments_size_is_computed_correctly() {
use rialto_runtime::millau_messages::Millau;
let maximal_remark_size =
compute_maximal_message_arguments_size(bp_rialto::max_extrinsic_size(), bp_millau::max_extrinsic_size());
let call: millau_runtime::Call = millau_runtime::SystemCall::remark(vec![42; maximal_remark_size as _]).into();
let payload = message_payload(
Default::default(),
call.get_dispatch_info().weight,
pallet_bridge_call_dispatch::CallOrigin::SourceRoot,
&call,
);
assert_eq!(Millau::verify_message(&payload), Ok(()));
let call: millau_runtime::Call =
millau_runtime::SystemCall::remark(vec![42; (maximal_remark_size + 1) as _]).into();
let payload = message_payload(
Default::default(),
call.get_dispatch_info().weight,
pallet_bridge_call_dispatch::CallOrigin::SourceRoot,
&call,
);
assert!(Millau::verify_message(&payload).is_err());
}
#[test]
fn maximal_size_remark_to_rialto_is_generated_correctly() {
assert!(
bridge_runtime_common::messages::target::maximal_incoming_message_size(
bp_rialto::max_extrinsic_size()
) > bp_millau::max_extrinsic_size(),
"We can't actually send maximal messages to Rialto from Millau, because Millau extrinsics can't be that large",
)
}
#[test]
fn maximal_rialto_to_millau_message_dispatch_weight_is_computed_correctly() {
use rialto_runtime::millau_messages::Millau;
let maximal_dispatch_weight = compute_maximal_message_dispatch_weight(bp_millau::max_extrinsic_weight());
let call: millau_runtime::Call = rialto_runtime::SystemCall::remark(vec![]).into();
let payload = message_payload(
Default::default(),
maximal_dispatch_weight,
pallet_bridge_call_dispatch::CallOrigin::SourceRoot,
&call,
);
assert_eq!(Millau::verify_message(&payload), Ok(()));
let payload = message_payload(
Default::default(),
maximal_dispatch_weight + 1,
pallet_bridge_call_dispatch::CallOrigin::SourceRoot,
&call,
);
assert!(Millau::verify_message(&payload).is_err());
}
#[test]
fn maximal_weight_fill_block_to_rialto_is_generated_correctly() {
use millau_runtime::rialto_messages::Rialto;
let maximal_dispatch_weight = compute_maximal_message_dispatch_weight(bp_rialto::max_extrinsic_weight());
let call: rialto_runtime::Call = millau_runtime::SystemCall::remark(vec![]).into();
let payload = message_payload(
Default::default(),
maximal_dispatch_weight,
pallet_bridge_call_dispatch::CallOrigin::SourceRoot,
&call,
);
assert_eq!(Rialto::verify_message(&payload), Ok(()));
let payload = message_payload(
Default::default(),
maximal_dispatch_weight + 1,
pallet_bridge_call_dispatch::CallOrigin::SourceRoot,
&call,
);
assert!(Rialto::verify_message(&payload).is_err());
}
#[test]
fn rialto_tx_extra_bytes_constant_is_correct() {
let rialto_call = rialto_runtime::Call::System(rialto_runtime::SystemCall::remark(vec![]));
let rialto_tx = Rialto::sign_transaction(
Default::default(),
&sp_keyring::AccountKeyring::Alice.pair(),
0,
rialto_call.clone(),
);
let extra_bytes_in_transaction = rialto_tx.encode().len() - rialto_call.encode().len();
assert!(
bp_rialto::TX_EXTRA_BYTES as usize >= extra_bytes_in_transaction,
"Hardcoded number of extra bytes in Rialto transaction {} is lower than actual value: {}",
bp_rialto::TX_EXTRA_BYTES,
extra_bytes_in_transaction,
);
}
#[test]
fn millau_tx_extra_bytes_constant_is_correct() {
let millau_call = millau_runtime::Call::System(millau_runtime::SystemCall::remark(vec![]));
let millau_tx = Millau::sign_transaction(
Default::default(),
&sp_keyring::AccountKeyring::Alice.pair(),
0,
millau_call.clone(),
);
let extra_bytes_in_transaction = millau_tx.encode().len() - millau_call.encode().len();
assert!(
bp_millau::TX_EXTRA_BYTES as usize >= extra_bytes_in_transaction,
"Hardcoded number of extra bytes in Millau transaction {} is lower than actual value: {}",
bp_millau::TX_EXTRA_BYTES,
extra_bytes_in_transaction,
);
}
}
@@ -0,0 +1,72 @@
// Copyright 2019-2020 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/>.
//! Rialto-to-Millau headers sync entrypoint.
use super::{MillauClient, RialtoClient};
use crate::finality_pipeline::{SubstrateFinalitySyncPipeline, SubstrateFinalityToSubstrate};
use async_trait::async_trait;
use relay_millau_client::{Millau, SigningParams as MillauSigningParams};
use relay_rialto_client::{Rialto, SyncHeader as RialtoSyncHeader};
use relay_substrate_client::{finality_source::Justification, Error as SubstrateError, TransactionSignScheme};
use sp_core::Pair;
/// Rialto-to-Millau finality sync pipeline.
pub(crate) type RialtoFinalityToMillau = SubstrateFinalityToSubstrate<Rialto, Millau, MillauSigningParams>;
#[async_trait]
impl SubstrateFinalitySyncPipeline for RialtoFinalityToMillau {
const BEST_FINALIZED_SOURCE_HEADER_ID_AT_TARGET: &'static str = bp_rialto::BEST_FINALIZED_RIALTO_HEADER_METHOD;
type SignedTransaction = <Millau as TransactionSignScheme>::SignedTransaction;
async fn make_submit_finality_proof_transaction(
&self,
header: RialtoSyncHeader,
proof: Justification<bp_rialto::BlockNumber>,
) -> Result<Self::SignedTransaction, SubstrateError> {
let account_id = self.target_sign.signer.public().as_array_ref().clone().into();
let nonce = self.target_client.next_account_index(account_id).await?;
let call = millau_runtime::FinalityBridgeRialtoCall::<
millau_runtime::Runtime,
millau_runtime::RialtoFinalityVerifierInstance,
>::submit_finality_proof(header.into_inner(), proof.into_inner())
.into();
let genesis_hash = *self.target_client.genesis_hash();
let transaction = Millau::sign_transaction(genesis_hash, &self.target_sign.signer, nonce, call);
Ok(transaction)
}
}
/// Run Rialto-to-Millau finality sync.
pub async fn run(
rialto_client: RialtoClient,
millau_client: MillauClient,
millau_sign: MillauSigningParams,
metrics_params: Option<relay_utils::metrics::MetricsParams>,
) {
crate::finality_pipeline::run(
RialtoFinalityToMillau::new(millau_client.clone(), millau_sign),
rialto_client,
millau_client,
metrics_params,
)
.await;
}
@@ -0,0 +1,189 @@
// Copyright 2019-2020 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/>.
//! Rialto-to-Millau messages sync entrypoint.
use super::{MillauClient, RialtoClient};
use crate::messages_lane::{select_delivery_transaction_limits, SubstrateMessageLane, SubstrateMessageLaneToSubstrate};
use crate::messages_source::SubstrateMessagesSource;
use crate::messages_target::SubstrateMessagesTarget;
use async_trait::async_trait;
use bp_messages::{LaneId, MessageNonce};
use bp_runtime::{MILLAU_BRIDGE_INSTANCE, RIALTO_BRIDGE_INSTANCE};
use bridge_runtime_common::messages::target::FromBridgedChainMessagesProof;
use codec::Encode;
use frame_support::dispatch::GetDispatchInfo;
use messages_relay::message_lane::MessageLane;
use relay_millau_client::{HeaderId as MillauHeaderId, Millau, SigningParams as MillauSigningParams};
use relay_rialto_client::{HeaderId as RialtoHeaderId, Rialto, SigningParams as RialtoSigningParams};
use relay_substrate_client::{Chain, Error as SubstrateError, TransactionSignScheme};
use relay_utils::metrics::MetricsParams;
use sp_core::Pair;
use std::{ops::RangeInclusive, time::Duration};
/// Rialto-to-Millau message lane.
type RialtoMessagesToMillau = SubstrateMessageLaneToSubstrate<Rialto, RialtoSigningParams, Millau, MillauSigningParams>;
#[async_trait]
impl SubstrateMessageLane for RialtoMessagesToMillau {
const OUTBOUND_LANE_MESSAGES_DISPATCH_WEIGHT_METHOD: &'static str =
bp_millau::TO_MILLAU_MESSAGES_DISPATCH_WEIGHT_METHOD;
const OUTBOUND_LANE_LATEST_GENERATED_NONCE_METHOD: &'static str =
bp_millau::TO_MILLAU_LATEST_GENERATED_NONCE_METHOD;
const OUTBOUND_LANE_LATEST_RECEIVED_NONCE_METHOD: &'static str = bp_millau::TO_MILLAU_LATEST_RECEIVED_NONCE_METHOD;
const INBOUND_LANE_LATEST_RECEIVED_NONCE_METHOD: &'static str = bp_rialto::FROM_RIALTO_LATEST_RECEIVED_NONCE_METHOD;
const INBOUND_LANE_LATEST_CONFIRMED_NONCE_METHOD: &'static str =
bp_rialto::FROM_RIALTO_LATEST_CONFIRMED_NONCE_METHOD;
const INBOUND_LANE_UNREWARDED_RELAYERS_STATE: &'static str = bp_rialto::FROM_RIALTO_UNREWARDED_RELAYERS_STATE;
const BEST_FINALIZED_SOURCE_HEADER_ID_AT_TARGET: &'static str = bp_rialto::BEST_FINALIZED_RIALTO_HEADER_METHOD;
const BEST_FINALIZED_TARGET_HEADER_ID_AT_SOURCE: &'static str = bp_millau::BEST_FINALIZED_MILLAU_HEADER_METHOD;
type SourceSignedTransaction = <Rialto as TransactionSignScheme>::SignedTransaction;
type TargetSignedTransaction = <Millau as TransactionSignScheme>::SignedTransaction;
async fn make_messages_receiving_proof_transaction(
&self,
_generated_at_block: MillauHeaderId,
proof: <Self as MessageLane>::MessagesReceivingProof,
) -> Result<Self::SourceSignedTransaction, SubstrateError> {
let (relayers_state, proof) = proof;
let account_id = self.source_sign.signer.public().as_array_ref().clone().into();
let nonce = self.source_client.next_account_index(account_id).await?;
let call: rialto_runtime::Call =
rialto_runtime::MessagesCall::receive_messages_delivery_proof(proof, relayers_state).into();
let call_weight = call.get_dispatch_info().weight;
let genesis_hash = *self.source_client.genesis_hash();
let transaction = Rialto::sign_transaction(genesis_hash, &self.source_sign.signer, nonce, call);
log::trace!(
target: "bridge",
"Prepared Millau -> Rialto confirmation transaction. Weight: {}/{}, size: {}/{}",
call_weight,
bp_rialto::max_extrinsic_weight(),
transaction.encode().len(),
bp_rialto::max_extrinsic_size(),
);
Ok(transaction)
}
async fn make_messages_delivery_transaction(
&self,
_generated_at_header: RialtoHeaderId,
_nonces: RangeInclusive<MessageNonce>,
proof: <Self as MessageLane>::MessagesProof,
) -> Result<Self::TargetSignedTransaction, SubstrateError> {
let (dispatch_weight, proof) = proof;
let FromBridgedChainMessagesProof {
ref nonces_start,
ref nonces_end,
..
} = proof;
let messages_count = nonces_end - nonces_start + 1;
let account_id = self.target_sign.signer.public().as_array_ref().clone().into();
let nonce = self.target_client.next_account_index(account_id).await?;
let call: millau_runtime::Call = millau_runtime::MessagesCall::receive_messages_proof(
self.relayer_id_at_source.clone(),
proof,
messages_count as _,
dispatch_weight,
)
.into();
let call_weight = call.get_dispatch_info().weight;
let genesis_hash = *self.target_client.genesis_hash();
let transaction = Millau::sign_transaction(genesis_hash, &self.target_sign.signer, nonce, call);
log::trace!(
target: "bridge",
"Prepared Rialto -> Millau delivery transaction. Weight: {}/{}, size: {}/{}",
call_weight,
bp_millau::max_extrinsic_weight(),
transaction.encode().len(),
bp_millau::max_extrinsic_size(),
);
Ok(transaction)
}
}
/// Rialto node as messages source.
type RialtoSourceClient = SubstrateMessagesSource<Rialto, RialtoMessagesToMillau>;
/// Millau node as messages target.
type MillauTargetClient = SubstrateMessagesTarget<Millau, RialtoMessagesToMillau>;
/// Run Rialto-to-Millau messages sync.
pub async fn run(
rialto_client: RialtoClient,
rialto_sign: RialtoSigningParams,
millau_client: MillauClient,
millau_sign: MillauSigningParams,
lane_id: LaneId,
metrics_params: Option<MetricsParams>,
) {
let stall_timeout = Duration::from_secs(5 * 60);
let relayer_id_at_rialto = rialto_sign.signer.public().as_array_ref().clone().into();
let lane = RialtoMessagesToMillau {
source_client: rialto_client.clone(),
source_sign: rialto_sign,
target_client: millau_client.clone(),
target_sign: millau_sign,
relayer_id_at_source: relayer_id_at_rialto,
};
// 2/3 is reserved for proofs and tx overhead
let max_messages_size_in_single_batch = bp_millau::max_extrinsic_size() as usize / 3;
let (max_messages_in_single_batch, max_messages_weight_in_single_batch) =
select_delivery_transaction_limits::<pallet_bridge_messages::weights::RialtoWeight<rialto_runtime::Runtime>>(
bp_millau::max_extrinsic_weight(),
bp_millau::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE,
);
log::info!(
target: "bridge",
"Starting Rialto -> Millau messages relay.\n\t\
Rialto relayer account id: {:?}\n\t\
Max messages in single transaction: {}\n\t\
Max messages size in single transaction: {}\n\t\
Max messages weight in single transaction: {}",
lane.relayer_id_at_source,
max_messages_in_single_batch,
max_messages_size_in_single_batch,
max_messages_weight_in_single_batch,
);
messages_relay::message_lane_loop::run(
messages_relay::message_lane_loop::Params {
lane: lane_id,
source_tick: Rialto::AVERAGE_BLOCK_INTERVAL,
target_tick: Millau::AVERAGE_BLOCK_INTERVAL,
reconnect_delay: relay_utils::relay_loop::RECONNECT_DELAY,
stall_timeout,
delivery_params: messages_relay::message_lane_loop::MessageDeliveryParams {
max_unrewarded_relayer_entries_at_target: bp_millau::MAX_UNREWARDED_RELAYER_ENTRIES_AT_INBOUND_LANE,
max_unconfirmed_nonces_at_target: bp_millau::MAX_UNCONFIRMED_MESSAGES_AT_INBOUND_LANE,
max_messages_in_single_batch,
max_messages_weight_in_single_batch,
max_messages_size_in_single_batch,
},
},
RialtoSourceClient::new(rialto_client, lane.clone(), lane_id, MILLAU_BRIDGE_INSTANCE),
MillauTargetClient::new(millau_client, lane, lane_id, RIALTO_BRIDGE_INSTANCE),
metrics_params,
futures::future::pending(),
)
.await;
}
@@ -0,0 +1,72 @@
// Copyright 2019-2020 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/>.
//! Westend-to-Millau headers sync entrypoint.
use super::{MillauClient, WestendClient};
use crate::finality_pipeline::{SubstrateFinalitySyncPipeline, SubstrateFinalityToSubstrate};
use async_trait::async_trait;
use relay_millau_client::{Millau, SigningParams as MillauSigningParams};
use relay_substrate_client::{finality_source::Justification, Error as SubstrateError, TransactionSignScheme};
use relay_westend_client::{SyncHeader as WestendSyncHeader, Westend};
use sp_core::Pair;
/// Westend-to-Millau finality sync pipeline.
pub(crate) type WestendFinalityToMillau = SubstrateFinalityToSubstrate<Westend, Millau, MillauSigningParams>;
#[async_trait]
impl SubstrateFinalitySyncPipeline for WestendFinalityToMillau {
const BEST_FINALIZED_SOURCE_HEADER_ID_AT_TARGET: &'static str = bp_westend::BEST_FINALIZED_WESTEND_HEADER_METHOD;
type SignedTransaction = <Millau as TransactionSignScheme>::SignedTransaction;
async fn make_submit_finality_proof_transaction(
&self,
header: WestendSyncHeader,
proof: Justification<bp_westend::BlockNumber>,
) -> Result<Self::SignedTransaction, SubstrateError> {
let account_id = self.target_sign.signer.public().as_array_ref().clone().into();
let nonce = self.target_client.next_account_index(account_id).await?;
let call = millau_runtime::FinalityBridgeWestendCall::<
millau_runtime::Runtime,
millau_runtime::WestendFinalityVerifierInstance,
>::submit_finality_proof(header.into_inner(), proof.into_inner())
.into();
let genesis_hash = *self.target_client.genesis_hash();
let transaction = Millau::sign_transaction(genesis_hash, &self.target_sign.signer, nonce, call);
Ok(transaction)
}
}
/// Run Westend-to-Millau finality sync.
pub async fn run(
westend_client: WestendClient,
millau_client: MillauClient,
millau_sign: MillauSigningParams,
metrics_params: Option<relay_utils::metrics::MetricsParams>,
) {
crate::finality_pipeline::run(
WestendFinalityToMillau::new(millau_client.clone(), millau_sign),
westend_client,
millau_client,
metrics_params,
)
.await;
}