Squashed 'bridges/' content from commit 062554430

git-subtree-dir: bridges
git-subtree-split: 0625544309ff299307f7e110f252f04eac383102
This commit is contained in:
Branislav Kontur committed 2022-12-01 22:32:52 +01:00
commit d2b7ee2575
357 files changed
+79920

No files matched your search

+75
View File
@@ -0,0 +1,75 @@
[package]
name = "substrate-relay"
version = "1.0.1"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2021"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies]
anyhow = "1.0"
async-std = "1.9.0"
async-trait = "0.1"
codec = { package = "parity-scale-codec", version = "3.1.5" }
futures = "0.3.12"
hex = "0.4"
log = "0.4.17"
num-format = "0.4"
num-traits = "0.2"
structopt = "0.3"
strum = { version = "0.21.0", features = ["derive"] }
# Bridge dependencies
bp-bridge-hub-rococo = { path = "../../primitives/chain-bridge-hub-rococo" }
bp-bridge-hub-wococo = { path = "../../primitives/chain-bridge-hub-wococo" }
bp-header-chain = { path = "../../primitives/header-chain" }
bp-messages = { path = "../../primitives/messages" }
bp-millau = { path = "../../primitives/chain-millau" }
bp-polkadot-core = { path = "../../primitives/polkadot-core" }
bp-rialto = { path = "../../primitives/chain-rialto" }
bp-rialto-parachain = { path = "../../primitives/chain-rialto-parachain" }
bp-rococo = { path = "../../primitives/chain-rococo" }
bp-runtime = { path = "../../primitives/runtime" }
bp-westend = { path = "../../primitives/chain-westend" }
bp-wococo = { path = "../../primitives/chain-wococo" }
bridge-runtime-common = { path = "../../bin/runtime-common" }
messages-relay = { path = "../messages" }
millau-runtime = { path = "../../bin/millau/runtime" }
pallet-bridge-messages = { path = "../../modules/messages" }
pallet-bridge-parachains = { path = "../../modules/parachains" }
parachains-relay = { path = "../parachains" }
relay-millau-client = { path = "../client-millau" }
relay-rialto-client = { path = "../client-rialto" }
relay-rialto-parachain-client = { path = "../client-rialto-parachain" }
relay-bridge-hub-rococo-client = { path = "../client-bridge-hub-rococo" }
relay-bridge-hub-wococo-client = { path = "../client-bridge-hub-wococo" }
relay-rococo-client = { path = "../client-rococo" }
relay-substrate-client = { path = "../client-substrate" }
relay-utils = { path = "../utils" }
relay-westend-client = { path = "../client-westend" }
relay-wococo-client = { path = "../client-wococo" }
rialto-parachain-runtime = { path = "../../bin/rialto-parachain/runtime" }
rialto-runtime = { path = "../../bin/rialto/runtime" }
substrate-relay-helper = { path = "../lib-substrate-relay" }
# Substrate Dependencies
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-version = { git = "https://github.com/paritytech/substrate", branch = "master" }
# Polkadot Dependencies
polkadot-parachain = { git = "https://github.com/paritytech/polkadot", branch = "master" }
polkadot-primitives = { git = "https://github.com/paritytech/polkadot", branch = "master" }
polkadot-runtime-common = { git = "https://github.com/paritytech/polkadot", branch = "master" }
polkadot-runtime-parachains = { git = "https://github.com/paritytech/polkadot", branch = "master" }
xcm = { git = "https://github.com/paritytech/polkadot", branch = "master", default-features = false }
[dev-dependencies]
bp-test-utils = { path = "../../primitives/test-utils" }
hex-literal = "0.3"
sp-keyring = { git = "https://github.com/paritytech/substrate", branch = "master" }
tempfile = "3.2"
finality-grandpa = { version = "0.16.0" }
@@ -0,0 +1,64 @@
// Copyright 2022 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/>.
//! BridgeHubRococo-to-BridgeHubWococo messages sync entrypoint.
use crate::cli::bridge::{CliBridgeBase, MessagesCliBridge};
use bp_messages::Weight;
use relay_bridge_hub_rococo_client::BridgeHubRococo;
use relay_bridge_hub_wococo_client::BridgeHubWococo;
use substrate_relay_helper::messages_lane::SubstrateMessageLane;
pub struct BridgeHubRococoToBridgeHubWococoMessagesCliBridge {}
impl CliBridgeBase for BridgeHubRococoToBridgeHubWococoMessagesCliBridge {
type Source = BridgeHubRococo;
type Target = BridgeHubWococo;
}
impl MessagesCliBridge for BridgeHubRococoToBridgeHubWococoMessagesCliBridge {
const ESTIMATE_MESSAGE_FEE_METHOD: &'static str =
"TODO: not needed now, used for send_message and estimate_fee CLI";
type MessagesLane = BridgeHubRococoMessagesToBridgeHubWococoMessageLane;
}
substrate_relay_helper::generate_mocked_receive_message_proof_call_builder!(
BridgeHubRococoMessagesToBridgeHubWococoMessageLane,
BridgeHubRococoMessagesToBridgeHubWococoMessageLaneReceiveMessagesProofCallBuilder,
relay_bridge_hub_wococo_client::runtime::Call::BridgeRococoMessages,
relay_bridge_hub_wococo_client::runtime::BridgeRococoMessagesCall::receive_messages_proof
);
substrate_relay_helper::generate_mocked_receive_message_delivery_proof_call_builder!(
BridgeHubRococoMessagesToBridgeHubWococoMessageLane,
BridgeHubRococoMessagesToBridgeHubWococoMessageLaneReceiveMessagesDeliveryProofCallBuilder,
relay_bridge_hub_rococo_client::runtime::Call::BridgeWococoMessages,
relay_bridge_hub_rococo_client::runtime::BridgeWococoMessagesCall::receive_messages_delivery_proof
);
/// Description of BridgeHubRococo -> BridgeHubWococo messages bridge.
#[derive(Clone, Debug)]
pub struct BridgeHubRococoMessagesToBridgeHubWococoMessageLane;
impl SubstrateMessageLane for BridgeHubRococoMessagesToBridgeHubWococoMessageLane {
type SourceChain = BridgeHubRococo;
type TargetChain = BridgeHubWococo;
type ReceiveMessagesProofCallBuilder =
BridgeHubRococoMessagesToBridgeHubWococoMessageLaneReceiveMessagesProofCallBuilder;
type ReceiveMessagesDeliveryProofCallBuilder =
BridgeHubRococoMessagesToBridgeHubWococoMessageLaneReceiveMessagesDeliveryProofCallBuilder;
}
@@ -0,0 +1,64 @@
// Copyright 2022 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/>.
//! BridgeHubWococo-to-BridgeHubRococo messages sync entrypoint.
use crate::cli::bridge::{CliBridgeBase, MessagesCliBridge};
use bp_messages::Weight;
use relay_bridge_hub_rococo_client::BridgeHubRococo;
use relay_bridge_hub_wococo_client::BridgeHubWococo;
use substrate_relay_helper::messages_lane::SubstrateMessageLane;
pub struct BridgeHubWococoToBridgeHubRococoMessagesCliBridge {}
impl CliBridgeBase for BridgeHubWococoToBridgeHubRococoMessagesCliBridge {
type Source = BridgeHubWococo;
type Target = BridgeHubRococo;
}
impl MessagesCliBridge for BridgeHubWococoToBridgeHubRococoMessagesCliBridge {
const ESTIMATE_MESSAGE_FEE_METHOD: &'static str =
"TODO: not needed now, used for send_message and estimate_fee CLI";
type MessagesLane = BridgeHubWococoMessagesToBridgeHubRococoMessageLane;
}
substrate_relay_helper::generate_mocked_receive_message_proof_call_builder!(
BridgeHubWococoMessagesToBridgeHubRococoMessageLane,
BridgeHubWococoMessagesToBridgeHubRococoMessageLaneReceiveMessagesProofCallBuilder,
relay_bridge_hub_rococo_client::runtime::Call::BridgeWococoMessages,
relay_bridge_hub_rococo_client::runtime::BridgeWococoMessagesCall::receive_messages_proof
);
substrate_relay_helper::generate_mocked_receive_message_delivery_proof_call_builder!(
BridgeHubWococoMessagesToBridgeHubRococoMessageLane,
BridgeHubWococoMessagesToBridgeHubRococoMessageLaneReceiveMessagesDeliveryProofCallBuilder,
relay_bridge_hub_wococo_client::runtime::Call::BridgeRococoMessages,
relay_bridge_hub_wococo_client::runtime::BridgeRococoMessagesCall::receive_messages_delivery_proof
);
/// Description of BridgeHubWococo -> BridgeHubRococo messages bridge.
#[derive(Clone, Debug)]
pub struct BridgeHubWococoMessagesToBridgeHubRococoMessageLane;
impl SubstrateMessageLane for BridgeHubWococoMessagesToBridgeHubRococoMessageLane {
type SourceChain = BridgeHubWococo;
type TargetChain = BridgeHubRococo;
type ReceiveMessagesProofCallBuilder =
BridgeHubWococoMessagesToBridgeHubRococoMessageLaneReceiveMessagesProofCallBuilder;
type ReceiveMessagesDeliveryProofCallBuilder =
BridgeHubWococoMessagesToBridgeHubRococoMessageLaneReceiveMessagesDeliveryProofCallBuilder;
}
+63
View File
@@ -0,0 +1,63 @@
// 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/>.
//! Millau chain specification for CLI.
use crate::cli::{bridge, encode_message::CliEncodeMessage, CliChain};
use bp_rialto_parachain::RIALTO_PARACHAIN_ID;
use bp_runtime::EncodedOrDecodedCall;
use relay_millau_client::Millau;
use sp_version::RuntimeVersion;
use xcm::latest::prelude::*;
impl CliEncodeMessage for Millau {
fn encode_send_xcm(
message: xcm::VersionedXcm<()>,
bridge_instance_index: u8,
) -> anyhow::Result<EncodedOrDecodedCall<Self::Call>> {
let dest = match bridge_instance_index {
bridge::MILLAU_TO_RIALTO_INDEX =>
(Parent, X1(GlobalConsensus(millau_runtime::xcm_config::RialtoNetwork::get()))),
bridge::MILLAU_TO_RIALTO_PARACHAIN_INDEX => (
Parent,
X2(
GlobalConsensus(millau_runtime::xcm_config::RialtoNetwork::get()),
Parachain(RIALTO_PARACHAIN_ID),
),
),
_ => anyhow::bail!(
"Unsupported target bridge pallet with instance index: {}",
bridge_instance_index
),
};
Ok(millau_runtime::RuntimeCall::XcmPallet(millau_runtime::XcmCall::send {
dest: Box::new(dest.into()),
message: Box::new(message),
})
.into())
}
}
impl CliChain for Millau {
const RUNTIME_VERSION: Option<RuntimeVersion> = Some(millau_runtime::VERSION);
type KeyPair = sp_core::sr25519::Pair;
fn ss58_format() -> u16 {
millau_runtime::SS58Prefix::get() as u16
}
}
@@ -0,0 +1,57 @@
// 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/>.
//! Millau-to-Rialto headers sync entrypoint.
use crate::cli::bridge::{CliBridgeBase, MessagesCliBridge, RelayToRelayHeadersCliBridge};
use substrate_relay_helper::finality::{
engine::Grandpa as GrandpaFinalityEngine, DirectSubmitGrandpaFinalityProofCallBuilder,
SubstrateFinalitySyncPipeline,
};
/// Description of Millau -> Rialto finalized headers bridge.
#[derive(Clone, Debug)]
pub struct MillauFinalityToRialto;
impl SubstrateFinalitySyncPipeline for MillauFinalityToRialto {
type SourceChain = relay_millau_client::Millau;
type TargetChain = relay_rialto_client::Rialto;
type FinalityEngine = GrandpaFinalityEngine<Self::SourceChain>;
type SubmitFinalityProofCallBuilder = DirectSubmitGrandpaFinalityProofCallBuilder<
Self,
rialto_runtime::Runtime,
rialto_runtime::MillauGrandpaInstance,
>;
}
//// `Millau` to `Rialto` bridge definition.
pub struct MillauToRialtoCliBridge {}
impl CliBridgeBase for MillauToRialtoCliBridge {
type Source = relay_millau_client::Millau;
type Target = relay_rialto_client::Rialto;
}
impl RelayToRelayHeadersCliBridge for MillauToRialtoCliBridge {
type Finality = MillauFinalityToRialto;
}
impl MessagesCliBridge for MillauToRialtoCliBridge {
const ESTIMATE_MESSAGE_FEE_METHOD: &'static str =
bp_rialto::TO_RIALTO_ESTIMATE_MESSAGE_FEE_METHOD;
type MessagesLane = crate::chains::millau_messages_to_rialto::MillauMessagesToRialto;
}
@@ -0,0 +1,76 @@
// 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/>.
//! Millau-to-RialtoParachain headers sync entrypoint.
// 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/>.
//! Millau-to-RialtoParachain headers sync entrypoint.
use crate::cli::bridge::{CliBridgeBase, MessagesCliBridge, RelayToRelayHeadersCliBridge};
use substrate_relay_helper::finality::{
engine::Grandpa as GrandpaFinalityEngine, DirectSubmitGrandpaFinalityProofCallBuilder,
SubstrateFinalitySyncPipeline,
};
/// Description of Millau -> Rialto finalized headers bridge.
#[derive(Clone, Debug)]
pub struct MillauFinalityToRialtoParachain;
impl SubstrateFinalitySyncPipeline for MillauFinalityToRialtoParachain {
type SourceChain = relay_millau_client::Millau;
type TargetChain = relay_rialto_parachain_client::RialtoParachain;
type FinalityEngine = GrandpaFinalityEngine<Self::SourceChain>;
type SubmitFinalityProofCallBuilder = DirectSubmitGrandpaFinalityProofCallBuilder<
Self,
rialto_parachain_runtime::Runtime,
rialto_parachain_runtime::MillauGrandpaInstance,
>;
}
//// `Millau` to `RialtoParachain` bridge definition.
pub struct MillauToRialtoParachainCliBridge {}
impl CliBridgeBase for MillauToRialtoParachainCliBridge {
type Source = relay_millau_client::Millau;
type Target = relay_rialto_parachain_client::RialtoParachain;
}
impl RelayToRelayHeadersCliBridge for MillauToRialtoParachainCliBridge {
type Finality = MillauFinalityToRialtoParachain;
}
impl MessagesCliBridge for MillauToRialtoParachainCliBridge {
const ESTIMATE_MESSAGE_FEE_METHOD: &'static str =
bp_rialto_parachain::TO_RIALTO_PARACHAIN_ESTIMATE_MESSAGE_FEE_METHOD;
type MessagesLane =
crate::chains::millau_messages_to_rialto_parachain::MillauMessagesToRialtoParachain;
}
@@ -0,0 +1,44 @@
// 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/>.
//! Millau-to-Rialto messages sync entrypoint.
use relay_millau_client::Millau;
use relay_rialto_client::Rialto;
use substrate_relay_helper::messages_lane::{
DirectReceiveMessagesDeliveryProofCallBuilder, DirectReceiveMessagesProofCallBuilder,
SubstrateMessageLane,
};
/// Description of Millau -> Rialto messages bridge.
#[derive(Clone, Debug)]
pub struct MillauMessagesToRialto;
impl SubstrateMessageLane for MillauMessagesToRialto {
type SourceChain = Millau;
type TargetChain = Rialto;
type ReceiveMessagesProofCallBuilder = DirectReceiveMessagesProofCallBuilder<
Self,
rialto_runtime::Runtime,
rialto_runtime::WithMillauMessagesInstance,
>;
type ReceiveMessagesDeliveryProofCallBuilder = DirectReceiveMessagesDeliveryProofCallBuilder<
Self,
millau_runtime::Runtime,
millau_runtime::WithRialtoMessagesInstance,
>;
}
@@ -0,0 +1,44 @@
// 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/>.
//! Millau-to-RialtoParachain messages sync entrypoint.
use relay_millau_client::Millau;
use relay_rialto_parachain_client::RialtoParachain;
use substrate_relay_helper::messages_lane::{
DirectReceiveMessagesDeliveryProofCallBuilder, DirectReceiveMessagesProofCallBuilder,
SubstrateMessageLane,
};
/// Description of Millau -> RialtoParachain messages bridge.
#[derive(Clone, Debug)]
pub struct MillauMessagesToRialtoParachain;
impl SubstrateMessageLane for MillauMessagesToRialtoParachain {
type SourceChain = Millau;
type TargetChain = RialtoParachain;
type ReceiveMessagesProofCallBuilder = DirectReceiveMessagesProofCallBuilder<
Self,
rialto_parachain_runtime::Runtime,
rialto_parachain_runtime::WithMillauMessagesInstance,
>;
type ReceiveMessagesDeliveryProofCallBuilder = DirectReceiveMessagesDeliveryProofCallBuilder<
Self,
millau_runtime::Runtime,
millau_runtime::WithRialtoParachainMessagesInstance,
>;
}
+125
View File
@@ -0,0 +1,125 @@
// 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/>.
//! Chain-specific relayer configuration.
pub mod bridge_hub_rococo_messages_to_bridge_hub_wococo;
pub mod bridge_hub_wococo_messages_to_bridge_hub_rococo;
pub mod millau_headers_to_rialto;
pub mod millau_headers_to_rialto_parachain;
pub mod millau_messages_to_rialto;
pub mod millau_messages_to_rialto_parachain;
pub mod rialto_headers_to_millau;
pub mod rialto_messages_to_millau;
pub mod rialto_parachain_messages_to_millau;
pub mod rialto_parachains_to_millau;
pub mod rococo_headers_to_bridge_hub_wococo;
pub mod rococo_parachains_to_bridge_hub_wococo;
pub mod westend_headers_to_millau;
pub mod westend_parachains_to_millau;
pub mod wococo_headers_to_bridge_hub_rococo;
pub mod wococo_parachains_to_bridge_hub_rococo;
mod millau;
mod rialto;
mod rialto_parachain;
mod rococo;
mod westend;
mod wococo;
#[cfg(test)]
mod tests {
use crate::cli::encode_message;
use bp_messages::source_chain::TargetHeaderChain;
use bp_runtime::Chain as _;
use codec::Encode;
use relay_millau_client::Millau;
use relay_rialto_client::Rialto;
use relay_substrate_client::{ChainWithTransactions, SignParam, UnsignedTransaction};
#[test]
fn maximal_rialto_to_millau_message_size_is_computed_correctly() {
use rialto_runtime::millau_messages::Millau;
let maximal_message_size = encode_message::compute_maximal_message_size(
bp_rialto::Rialto::max_extrinsic_size(),
bp_millau::Millau::max_extrinsic_size(),
);
let message = vec![42; maximal_message_size as _];
assert_eq!(Millau::verify_message(&message), Ok(()));
let message = vec![42; (maximal_message_size + 1) as _];
assert!(Millau::verify_message(&message).is_err());
}
#[test]
fn maximal_size_remark_to_rialto_is_generated_correctly() {
assert!(
bridge_runtime_common::messages::target::maximal_incoming_message_size(
bp_rialto::Rialto::max_extrinsic_size()
) > bp_millau::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 rialto_tx_extra_bytes_constant_is_correct() {
let rialto_call = rialto_runtime::RuntimeCall::System(rialto_runtime::SystemCall::remark {
remark: vec![],
});
let rialto_tx = Rialto::sign_transaction(
SignParam {
spec_version: 1,
transaction_version: 1,
genesis_hash: Default::default(),
signer: sp_keyring::AccountKeyring::Alice.pair(),
},
UnsignedTransaction::new(rialto_call.clone().into(), 0),
)
.unwrap();
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::RuntimeCall::System(millau_runtime::SystemCall::remark {
remark: vec![],
});
let millau_tx = Millau::sign_transaction(
SignParam {
spec_version: 0,
transaction_version: 0,
genesis_hash: Default::default(),
signer: sp_keyring::AccountKeyring::Alice.pair(),
},
UnsignedTransaction::new(millau_call.clone().into(), 0),
)
.unwrap();
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,
);
}
}
+55
View File
@@ -0,0 +1,55 @@
// 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/>.
//! Rialto chain specification for CLI.
use crate::cli::{bridge, encode_message::CliEncodeMessage, CliChain};
use bp_runtime::EncodedOrDecodedCall;
use relay_rialto_client::Rialto;
use sp_version::RuntimeVersion;
use xcm::latest::prelude::*;
impl CliEncodeMessage for Rialto {
fn encode_send_xcm(
message: xcm::VersionedXcm<()>,
bridge_instance_index: u8,
) -> anyhow::Result<EncodedOrDecodedCall<Self::Call>> {
let dest = match bridge_instance_index {
bridge::RIALTO_TO_MILLAU_INDEX =>
(Parent, X1(GlobalConsensus(rialto_runtime::xcm_config::MillauNetwork::get()))),
_ => anyhow::bail!(
"Unsupported target bridge pallet with instance index: {}",
bridge_instance_index
),
};
Ok(rialto_runtime::RuntimeCall::XcmPallet(rialto_runtime::XcmCall::send {
dest: Box::new(dest.into()),
message: Box::new(message),
})
.into())
}
}
impl CliChain for Rialto {
const RUNTIME_VERSION: Option<RuntimeVersion> = Some(rialto_runtime::VERSION);
type KeyPair = sp_core::sr25519::Pair;
fn ss58_format() -> u16 {
rialto_runtime::SS58Prefix::get() as u16
}
}
@@ -0,0 +1,57 @@
// 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/>.
//! Rialto-to-Millau headers sync entrypoint.
use crate::cli::bridge::{CliBridgeBase, MessagesCliBridge, RelayToRelayHeadersCliBridge};
use substrate_relay_helper::finality::{
engine::Grandpa as GrandpaFinalityEngine, DirectSubmitGrandpaFinalityProofCallBuilder,
SubstrateFinalitySyncPipeline,
};
/// Description of Millau -> Rialto finalized headers bridge.
#[derive(Clone, Debug)]
pub struct RialtoFinalityToMillau;
impl SubstrateFinalitySyncPipeline for RialtoFinalityToMillau {
type SourceChain = relay_rialto_client::Rialto;
type TargetChain = relay_millau_client::Millau;
type FinalityEngine = GrandpaFinalityEngine<Self::SourceChain>;
type SubmitFinalityProofCallBuilder = DirectSubmitGrandpaFinalityProofCallBuilder<
Self,
millau_runtime::Runtime,
millau_runtime::RialtoGrandpaInstance,
>;
}
//// `Rialto` to `Millau` bridge definition.
pub struct RialtoToMillauCliBridge {}
impl CliBridgeBase for RialtoToMillauCliBridge {
type Source = relay_rialto_client::Rialto;
type Target = relay_millau_client::Millau;
}
impl RelayToRelayHeadersCliBridge for RialtoToMillauCliBridge {
type Finality = RialtoFinalityToMillau;
}
impl MessagesCliBridge for RialtoToMillauCliBridge {
const ESTIMATE_MESSAGE_FEE_METHOD: &'static str =
bp_millau::TO_MILLAU_ESTIMATE_MESSAGE_FEE_METHOD;
type MessagesLane = crate::chains::rialto_messages_to_millau::RialtoMessagesToMillau;
}
@@ -0,0 +1,44 @@
// 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/>.
//! Rialto-to-Millau messages sync entrypoint.
use relay_millau_client::Millau;
use relay_rialto_client::Rialto;
use substrate_relay_helper::messages_lane::{
DirectReceiveMessagesDeliveryProofCallBuilder, DirectReceiveMessagesProofCallBuilder,
SubstrateMessageLane,
};
/// Description of Rialto -> Millau messages bridge.
#[derive(Clone, Debug)]
pub struct RialtoMessagesToMillau;
impl SubstrateMessageLane for RialtoMessagesToMillau {
type SourceChain = Rialto;
type TargetChain = Millau;
type ReceiveMessagesProofCallBuilder = DirectReceiveMessagesProofCallBuilder<
Self,
millau_runtime::Runtime,
millau_runtime::WithRialtoMessagesInstance,
>;
type ReceiveMessagesDeliveryProofCallBuilder = DirectReceiveMessagesDeliveryProofCallBuilder<
Self,
rialto_runtime::Runtime,
rialto_runtime::WithMillauMessagesInstance,
>;
}
@@ -0,0 +1,57 @@
// 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/>.
//! Rialto parachain specification for CLI.
use crate::cli::{bridge, encode_message::CliEncodeMessage, CliChain};
use bp_runtime::EncodedOrDecodedCall;
use relay_rialto_parachain_client::RialtoParachain;
use sp_version::RuntimeVersion;
use xcm::latest::prelude::*;
impl CliEncodeMessage for RialtoParachain {
fn encode_send_xcm(
message: xcm::VersionedXcm<()>,
bridge_instance_index: u8,
) -> anyhow::Result<EncodedOrDecodedCall<Self::Call>> {
let dest = match bridge_instance_index {
bridge::RIALTO_PARACHAIN_TO_MILLAU_INDEX =>
(Parent, X1(GlobalConsensus(rialto_parachain_runtime::MillauNetwork::get()))),
_ => anyhow::bail!(
"Unsupported target bridge pallet with instance index: {}",
bridge_instance_index
),
};
Ok(rialto_parachain_runtime::RuntimeCall::PolkadotXcm(
rialto_parachain_runtime::XcmCall::send {
dest: Box::new(dest.into()),
message: Box::new(message),
},
)
.into())
}
}
impl CliChain for RialtoParachain {
const RUNTIME_VERSION: Option<RuntimeVersion> = Some(rialto_parachain_runtime::VERSION);
type KeyPair = sp_core::sr25519::Pair;
fn ss58_format() -> u16 {
rialto_parachain_runtime::SS58Prefix::get() as u16
}
}
@@ -0,0 +1,44 @@
// 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/>.
//! RialtoParachain-to-Millau messages sync entrypoint.
use relay_millau_client::Millau;
use relay_rialto_parachain_client::RialtoParachain;
use substrate_relay_helper::messages_lane::{
DirectReceiveMessagesDeliveryProofCallBuilder, DirectReceiveMessagesProofCallBuilder,
SubstrateMessageLane,
};
/// Description of RialtoParachain -> Millau messages bridge.
#[derive(Clone, Debug)]
pub struct RialtoParachainMessagesToMillau;
impl SubstrateMessageLane for RialtoParachainMessagesToMillau {
type SourceChain = RialtoParachain;
type TargetChain = Millau;
type ReceiveMessagesProofCallBuilder = DirectReceiveMessagesProofCallBuilder<
Self,
millau_runtime::Runtime,
millau_runtime::WithRialtoParachainMessagesInstance,
>;
type ReceiveMessagesDeliveryProofCallBuilder = DirectReceiveMessagesDeliveryProofCallBuilder<
Self,
rialto_parachain_runtime::Runtime,
rialto_parachain_runtime::WithMillauMessagesInstance,
>;
}
@@ -0,0 +1,74 @@
// 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/>.
//! Rialto-to-Millau parachains sync entrypoint.
use crate::cli::bridge::{CliBridgeBase, MessagesCliBridge, ParachainToRelayHeadersCliBridge};
use parachains_relay::ParachainsPipeline;
use relay_millau_client::Millau;
use relay_rialto_client::Rialto;
use relay_rialto_parachain_client::RialtoParachain;
use substrate_relay_helper::parachains::{
DirectSubmitParachainHeadsCallBuilder, SubstrateParachainsPipeline,
};
/// Rialto-to-Millau parachains sync description.
#[derive(Clone, Debug)]
pub struct RialtoParachainsToMillau;
impl ParachainsPipeline for RialtoParachainsToMillau {
type SourceChain = Rialto;
type TargetChain = Millau;
}
impl SubstrateParachainsPipeline for RialtoParachainsToMillau {
type SourceParachain = RialtoParachain;
type SourceRelayChain = Rialto;
type TargetChain = Millau;
type SubmitParachainHeadsCallBuilder = RialtoParachainsToMillauSubmitParachainHeadsCallBuilder;
const SOURCE_PARACHAIN_PARA_ID: u32 = bp_rialto_parachain::RIALTO_PARACHAIN_ID;
}
/// `submit_parachain_heads` call builder for Rialto-to-Millau parachains sync pipeline.
pub type RialtoParachainsToMillauSubmitParachainHeadsCallBuilder =
DirectSubmitParachainHeadsCallBuilder<
RialtoParachainsToMillau,
millau_runtime::Runtime,
millau_runtime::WithRialtoParachainsInstance,
>;
//// `RialtoParachain` to `Millau` bridge definition.
pub struct RialtoParachainToMillauCliBridge {}
impl CliBridgeBase for RialtoParachainToMillauCliBridge {
type Source = RialtoParachain;
type Target = Millau;
}
impl ParachainToRelayHeadersCliBridge for RialtoParachainToMillauCliBridge {
type SourceRelay = Rialto;
type ParachainFinality = RialtoParachainsToMillau;
type RelayFinality = crate::chains::rialto_headers_to_millau::RialtoFinalityToMillau;
}
impl MessagesCliBridge for RialtoParachainToMillauCliBridge {
const ESTIMATE_MESSAGE_FEE_METHOD: &'static str =
bp_millau::TO_MILLAU_ESTIMATE_MESSAGE_FEE_METHOD;
type MessagesLane =
crate::chains::rialto_parachain_messages_to_millau::RialtoParachainMessagesToMillau;
}
+42
View File
@@ -0,0 +1,42 @@
// Copyright 2022 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/>.
//! Rococo + Rococo parachains specification for CLI.
use crate::cli::CliChain;
use relay_bridge_hub_rococo_client::BridgeHubRococo;
use relay_rococo_client::Rococo;
use sp_version::RuntimeVersion;
impl CliChain for Rococo {
const RUNTIME_VERSION: Option<RuntimeVersion> = None;
type KeyPair = sp_core::sr25519::Pair;
fn ss58_format() -> u16 {
bp_rococo::SS58Prefix::get() as u16
}
}
impl CliChain for BridgeHubRococo {
const RUNTIME_VERSION: Option<RuntimeVersion> = None;
type KeyPair = sp_core::sr25519::Pair;
fn ss58_format() -> u16 {
relay_bridge_hub_rococo_client::runtime::SS58Prefix::get()
}
}
@@ -0,0 +1,53 @@
// Copyright 2022 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/>.
//! Rococo-to-Wococo bridge hubs headers sync entrypoint.
use crate::cli::bridge::{CliBridgeBase, RelayToRelayHeadersCliBridge};
use substrate_relay_helper::finality::{
engine::Grandpa as GrandpaFinalityEngine, SubstrateFinalitySyncPipeline,
};
/// Description of Rococo -> Wococo finalized headers bridge.
#[derive(Clone, Debug)]
pub struct RococoFinalityToBridgeHubWococo;
substrate_relay_helper::generate_mocked_submit_finality_proof_call_builder!(
RococoFinalityToBridgeHubWococo,
RococoFinalityToBridgeHubWococoCallBuilder,
relay_bridge_hub_wococo_client::runtime::Call::BridgeRococoGrandpa,
relay_bridge_hub_wococo_client::runtime::BridgeGrandpaRococoCall::submit_finality_proof
);
impl SubstrateFinalitySyncPipeline for RococoFinalityToBridgeHubWococo {
type SourceChain = relay_rococo_client::Rococo;
type TargetChain = relay_bridge_hub_wococo_client::BridgeHubWococo;
type FinalityEngine = GrandpaFinalityEngine<Self::SourceChain>;
type SubmitFinalityProofCallBuilder = RococoFinalityToBridgeHubWococoCallBuilder;
}
/// `Rococo` to BridgeHub `Wococo` bridge definition.
pub struct RococoToBridgeHubWococoCliBridge {}
impl CliBridgeBase for RococoToBridgeHubWococoCliBridge {
type Source = relay_rococo_client::Rococo;
type Target = relay_bridge_hub_wococo_client::BridgeHubWococo;
}
impl RelayToRelayHeadersCliBridge for RococoToBridgeHubWococoCliBridge {
type Finality = RococoFinalityToBridgeHubWococo;
}
@@ -0,0 +1,85 @@
// 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/>.
//! Wococo-to-Rococo parachains sync entrypoint.
use crate::cli::bridge::{CliBridgeBase, MessagesCliBridge, ParachainToRelayHeadersCliBridge};
use bp_polkadot_core::parachains::{ParaHash, ParaHeadsProof, ParaId};
use parachains_relay::ParachainsPipeline;
use relay_substrate_client::{CallOf, HeaderIdOf};
use substrate_relay_helper::parachains::{
SubmitParachainHeadsCallBuilder, SubstrateParachainsPipeline,
};
/// BridgeHub-to-BridgeHub parachain sync description.
#[derive(Clone, Debug)]
pub struct BridgeHubRococoToBridgeHubWococo;
impl ParachainsPipeline for BridgeHubRococoToBridgeHubWococo {
type SourceChain = relay_rococo_client::Rococo;
type TargetChain = relay_bridge_hub_wococo_client::BridgeHubWococo;
}
impl SubstrateParachainsPipeline for BridgeHubRococoToBridgeHubWococo {
type SourceParachain = relay_bridge_hub_rococo_client::BridgeHubRococo;
type SourceRelayChain = relay_rococo_client::Rococo;
type TargetChain = relay_bridge_hub_wococo_client::BridgeHubWococo;
type SubmitParachainHeadsCallBuilder = BridgeHubRococoToBridgeHubWococoCallBuilder;
const SOURCE_PARACHAIN_PARA_ID: u32 = bp_bridge_hub_rococo::BRIDGE_HUB_ROCOCO_PARACHAIN_ID;
}
pub struct BridgeHubRococoToBridgeHubWococoCallBuilder;
impl SubmitParachainHeadsCallBuilder<BridgeHubRococoToBridgeHubWococo>
for BridgeHubRococoToBridgeHubWococoCallBuilder
{
fn build_submit_parachain_heads_call(
at_relay_block: HeaderIdOf<relay_rococo_client::Rococo>,
parachains: Vec<(ParaId, ParaHash)>,
parachain_heads_proof: ParaHeadsProof,
) -> CallOf<relay_bridge_hub_wococo_client::BridgeHubWococo> {
relay_bridge_hub_wococo_client::runtime::Call::BridgeRococoParachain(
relay_bridge_hub_wococo_client::runtime::BridgeParachainCall::submit_parachain_heads(
(at_relay_block.0, at_relay_block.1),
parachains,
parachain_heads_proof,
),
)
}
}
/// `BridgeHubParachain` to `BridgeHubParachain` bridge definition.
pub struct BridgeHubRococoToBridgeHubWococoCliBridge {}
impl ParachainToRelayHeadersCliBridge for BridgeHubRococoToBridgeHubWococoCliBridge {
type SourceRelay = relay_rococo_client::Rococo;
type ParachainFinality = BridgeHubRococoToBridgeHubWococo;
type RelayFinality =
crate::chains::rococo_headers_to_bridge_hub_wococo::RococoFinalityToBridgeHubWococo;
}
impl CliBridgeBase for BridgeHubRococoToBridgeHubWococoCliBridge {
type Source = relay_bridge_hub_rococo_client::BridgeHubRococo;
type Target = relay_bridge_hub_wococo_client::BridgeHubWococo;
}
impl MessagesCliBridge for BridgeHubRococoToBridgeHubWococoCliBridge {
const ESTIMATE_MESSAGE_FEE_METHOD: &'static str =
bp_bridge_hub_wococo::TO_BRIDGE_HUB_WOCOCO_ESTIMATE_MESSAGE_FEE_METHOD;
type MessagesLane =
crate::chains::bridge_hub_rococo_messages_to_bridge_hub_wococo::BridgeHubRococoMessagesToBridgeHubWococoMessageLane;
}
@@ -0,0 +1,47 @@
// 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/>.
//! Westend chain specification for CLI.
use crate::cli::CliChain;
use relay_westend_client::{Westend, Westmint};
use sp_version::RuntimeVersion;
impl CliChain for Westend {
const RUNTIME_VERSION: Option<RuntimeVersion> = None;
type KeyPair = sp_core::sr25519::Pair;
fn ss58_format() -> u16 {
sp_core::crypto::Ss58AddressFormat::from(
sp_core::crypto::Ss58AddressFormatRegistry::SubstrateAccount,
)
.into()
}
}
impl CliChain for Westmint {
const RUNTIME_VERSION: Option<RuntimeVersion> = None;
type KeyPair = sp_core::sr25519::Pair;
fn ss58_format() -> u16 {
sp_core::crypto::Ss58AddressFormat::from(
sp_core::crypto::Ss58AddressFormatRegistry::SubstrateAccount,
)
.into()
}
}
@@ -0,0 +1,51 @@
// 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/>.
//! Westend-to-Millau headers sync entrypoint.
use crate::cli::bridge::{CliBridgeBase, RelayToRelayHeadersCliBridge};
use substrate_relay_helper::finality::{
engine::Grandpa as GrandpaFinalityEngine, DirectSubmitGrandpaFinalityProofCallBuilder,
SubstrateFinalitySyncPipeline,
};
/// Description of Westend -> Millau finalized headers bridge.
#[derive(Clone, Debug)]
pub struct WestendFinalityToMillau;
impl SubstrateFinalitySyncPipeline for WestendFinalityToMillau {
type SourceChain = relay_westend_client::Westend;
type TargetChain = relay_millau_client::Millau;
type FinalityEngine = GrandpaFinalityEngine<Self::SourceChain>;
type SubmitFinalityProofCallBuilder = DirectSubmitGrandpaFinalityProofCallBuilder<
Self,
millau_runtime::Runtime,
millau_runtime::WestendGrandpaInstance,
>;
}
//// `Westend` to `Millau` bridge definition.
pub struct WestendToMillauCliBridge {}
impl CliBridgeBase for WestendToMillauCliBridge {
type Source = relay_westend_client::Westend;
type Target = relay_millau_client::Millau;
}
impl RelayToRelayHeadersCliBridge for WestendToMillauCliBridge {
type Finality = WestendFinalityToMillau;
}
@@ -0,0 +1,66 @@
// 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/>.
//! Westend-to-Millau parachains sync entrypoint.
use crate::cli::bridge::{CliBridgeBase, ParachainToRelayHeadersCliBridge};
use parachains_relay::ParachainsPipeline;
use relay_millau_client::Millau;
use relay_westend_client::{Westend, Westmint};
use substrate_relay_helper::parachains::{
DirectSubmitParachainHeadsCallBuilder, SubstrateParachainsPipeline,
};
/// Westend-to-Millau parachains sync description.
#[derive(Clone, Debug)]
pub struct WestendParachainsToMillau;
impl ParachainsPipeline for WestendParachainsToMillau {
type SourceChain = Westend;
type TargetChain = Millau;
}
impl SubstrateParachainsPipeline for WestendParachainsToMillau {
type SourceParachain = Westmint;
type SourceRelayChain = Westend;
type TargetChain = Millau;
type SubmitParachainHeadsCallBuilder = WestendParachainsToMillauSubmitParachainHeadsCallBuilder;
const SOURCE_PARACHAIN_PARA_ID: u32 = bp_westend::WESTMINT_PARACHAIN_ID;
}
/// `submit_parachain_heads` call builder for Rialto-to-Millau parachains sync pipeline.
pub type WestendParachainsToMillauSubmitParachainHeadsCallBuilder =
DirectSubmitParachainHeadsCallBuilder<
WestendParachainsToMillau,
millau_runtime::Runtime,
millau_runtime::WithWestendParachainsInstance,
>;
//// `WestendParachain` to `Millau` bridge definition.
pub struct WestmintToMillauCliBridge {}
impl ParachainToRelayHeadersCliBridge for WestmintToMillauCliBridge {
type SourceRelay = Westend;
type ParachainFinality = WestendParachainsToMillau;
type RelayFinality = crate::chains::westend_headers_to_millau::WestendFinalityToMillau;
}
impl CliBridgeBase for WestmintToMillauCliBridge {
type Source = Westmint;
type Target = Millau;
}
+42
View File
@@ -0,0 +1,42 @@
// Copyright 2022 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/>.
//! Wococo + Wococo parachains specification for CLI.
use crate::cli::CliChain;
use relay_bridge_hub_wococo_client::BridgeHubWococo;
use relay_wococo_client::Wococo;
use sp_version::RuntimeVersion;
impl CliChain for Wococo {
const RUNTIME_VERSION: Option<RuntimeVersion> = None;
type KeyPair = sp_core::sr25519::Pair;
fn ss58_format() -> u16 {
bp_wococo::SS58Prefix::get() as u16
}
}
impl CliChain for BridgeHubWococo {
const RUNTIME_VERSION: Option<RuntimeVersion> = None;
type KeyPair = sp_core::sr25519::Pair;
fn ss58_format() -> u16 {
relay_bridge_hub_wococo_client::runtime::SS58Prefix::get()
}
}
@@ -0,0 +1,53 @@
// Copyright 2022 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/>.
//! Wococo-to-Rococo bridge hubs headers sync entrypoint.
use crate::cli::bridge::{CliBridgeBase, RelayToRelayHeadersCliBridge};
use substrate_relay_helper::finality::{
engine::Grandpa as GrandpaFinalityEngine, SubstrateFinalitySyncPipeline,
};
/// Description of Wococo -> Rococo finalized headers bridge.
#[derive(Clone, Debug)]
pub struct WococoFinalityToBridgeHubRococo;
substrate_relay_helper::generate_mocked_submit_finality_proof_call_builder!(
WococoFinalityToBridgeHubRococo,
WococoFinalityToBridgeHubRococoCallBuilder,
relay_bridge_hub_rococo_client::runtime::Call::BridgeWococoGrandpa,
relay_bridge_hub_rococo_client::runtime::BridgeWococoGrandpaCall::submit_finality_proof
);
impl SubstrateFinalitySyncPipeline for WococoFinalityToBridgeHubRococo {
type SourceChain = relay_wococo_client::Wococo;
type TargetChain = relay_bridge_hub_rococo_client::BridgeHubRococo;
type FinalityEngine = GrandpaFinalityEngine<Self::SourceChain>;
type SubmitFinalityProofCallBuilder = WococoFinalityToBridgeHubRococoCallBuilder;
}
/// `Wococo` to BridgeHub `Rococo` bridge definition.
pub struct WococoToBridgeHubRococoCliBridge {}
impl CliBridgeBase for WococoToBridgeHubRococoCliBridge {
type Source = relay_wococo_client::Wococo;
type Target = relay_bridge_hub_rococo_client::BridgeHubRococo;
}
impl RelayToRelayHeadersCliBridge for WococoToBridgeHubRococoCliBridge {
type Finality = WococoFinalityToBridgeHubRococo;
}
@@ -0,0 +1,85 @@
// 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/>.
//! Rococo-to-Wococo parachains sync entrypoint.
use crate::cli::bridge::{CliBridgeBase, MessagesCliBridge, ParachainToRelayHeadersCliBridge};
use bp_polkadot_core::parachains::{ParaHash, ParaHeadsProof, ParaId};
use parachains_relay::ParachainsPipeline;
use relay_substrate_client::{CallOf, HeaderIdOf};
use substrate_relay_helper::parachains::{
SubmitParachainHeadsCallBuilder, SubstrateParachainsPipeline,
};
/// BridgeHub-to-BridgeHub parachain sync description.
#[derive(Clone, Debug)]
pub struct BridgeHubWococoToBridgeHubRococo;
impl ParachainsPipeline for BridgeHubWococoToBridgeHubRococo {
type SourceChain = relay_wococo_client::Wococo;
type TargetChain = relay_bridge_hub_rococo_client::BridgeHubRococo;
}
impl SubstrateParachainsPipeline for BridgeHubWococoToBridgeHubRococo {
type SourceParachain = relay_bridge_hub_wococo_client::BridgeHubWococo;
type SourceRelayChain = relay_wococo_client::Wococo;
type TargetChain = relay_bridge_hub_rococo_client::BridgeHubRococo;
type SubmitParachainHeadsCallBuilder = BridgeHubWococoToBridgeHubRococoCallBuilder;
const SOURCE_PARACHAIN_PARA_ID: u32 = bp_bridge_hub_wococo::BRIDGE_HUB_WOCOCO_PARACHAIN_ID;
}
pub struct BridgeHubWococoToBridgeHubRococoCallBuilder;
impl SubmitParachainHeadsCallBuilder<BridgeHubWococoToBridgeHubRococo>
for BridgeHubWococoToBridgeHubRococoCallBuilder
{
fn build_submit_parachain_heads_call(
at_relay_block: HeaderIdOf<relay_wococo_client::Wococo>,
parachains: Vec<(ParaId, ParaHash)>,
parachain_heads_proof: ParaHeadsProof,
) -> CallOf<relay_bridge_hub_rococo_client::BridgeHubRococo> {
relay_bridge_hub_rococo_client::runtime::Call::BridgeWococoParachain(
relay_bridge_hub_rococo_client::runtime::BridgeParachainCall::submit_parachain_heads(
(at_relay_block.0, at_relay_block.1),
parachains,
parachain_heads_proof,
),
)
}
}
/// `BridgeHubParachain` to `BridgeHubParachain` bridge definition.
pub struct BridgeHubWococoToBridgeHubRococoCliBridge {}
impl ParachainToRelayHeadersCliBridge for BridgeHubWococoToBridgeHubRococoCliBridge {
type SourceRelay = relay_wococo_client::Wococo;
type ParachainFinality = BridgeHubWococoToBridgeHubRococo;
type RelayFinality =
crate::chains::wococo_headers_to_bridge_hub_rococo::WococoFinalityToBridgeHubRococo;
}
impl CliBridgeBase for BridgeHubWococoToBridgeHubRococoCliBridge {
type Source = relay_bridge_hub_wococo_client::BridgeHubWococo;
type Target = relay_bridge_hub_rococo_client::BridgeHubRococo;
}
impl MessagesCliBridge for BridgeHubWococoToBridgeHubRococoCliBridge {
const ESTIMATE_MESSAGE_FEE_METHOD: &'static str =
bp_bridge_hub_rococo::TO_BRIDGE_HUB_ROCOCO_ESTIMATE_MESSAGE_FEE_METHOD;
type MessagesLane =
crate::chains::bridge_hub_wococo_messages_to_bridge_hub_rococo::BridgeHubWococoMessagesToBridgeHubRococoMessageLane;
}
+105
View File
@@ -0,0 +1,105 @@
// 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/>.
use crate::cli::CliChain;
use pallet_bridge_parachains::{RelayBlockHash, RelayBlockHasher, RelayBlockNumber};
use parachains_relay::ParachainsPipeline;
use relay_substrate_client::{AccountKeyPairOf, Chain, ChainWithTransactions, RelayChain};
use strum::{EnumString, EnumVariantNames};
use substrate_relay_helper::{
finality::SubstrateFinalitySyncPipeline, messages_lane::SubstrateMessageLane,
parachains::SubstrateParachainsPipeline,
};
#[derive(Debug, PartialEq, Eq, EnumString, EnumVariantNames)]
#[strum(serialize_all = "kebab_case")]
/// Supported full bridges (headers + messages).
pub enum FullBridge {
MillauToRialto,
RialtoToMillau,
MillauToRialtoParachain,
RialtoParachainToMillau,
BridgeHubRococoToBridgeHubWococo,
BridgeHubWococoToBridgeHubRococo,
}
impl FullBridge {
/// Return instance index of the bridge pallet in source runtime.
pub fn bridge_instance_index(&self) -> u8 {
match self {
Self::MillauToRialto => MILLAU_TO_RIALTO_INDEX,
Self::RialtoToMillau => RIALTO_TO_MILLAU_INDEX,
Self::MillauToRialtoParachain => MILLAU_TO_RIALTO_PARACHAIN_INDEX,
Self::RialtoParachainToMillau => RIALTO_PARACHAIN_TO_MILLAU_INDEX,
Self::BridgeHubRococoToBridgeHubWococo | Self::BridgeHubWococoToBridgeHubRococo =>
unimplemented!("Relay doesn't support send-message subcommand on bridge hubs"),
}
}
}
pub const RIALTO_TO_MILLAU_INDEX: u8 = 0;
pub const MILLAU_TO_RIALTO_INDEX: u8 = 0;
pub const MILLAU_TO_RIALTO_PARACHAIN_INDEX: u8 = 1;
pub const RIALTO_PARACHAIN_TO_MILLAU_INDEX: u8 = 0;
/// Minimal bridge representation that can be used from the CLI.
/// It connects a source chain to a target chain.
pub trait CliBridgeBase: Sized {
/// The source chain.
type Source: Chain + CliChain;
/// The target chain.
type Target: ChainWithTransactions + CliChain<KeyPair = AccountKeyPairOf<Self::Target>>;
}
/// Bridge representation that can be used from the CLI for relaying headers
/// from a relay chain to a relay chain.
pub trait RelayToRelayHeadersCliBridge: CliBridgeBase {
/// Finality proofs synchronization pipeline.
type Finality: SubstrateFinalitySyncPipeline<
SourceChain = Self::Source,
TargetChain = Self::Target,
>;
}
/// Bridge representation that can be used from the CLI for relaying headers
/// from a parachain to a relay chain.
pub trait ParachainToRelayHeadersCliBridge: CliBridgeBase {
// The `CliBridgeBase` type represents the parachain in this situation.
// We need to add an extra type for the relay chain.
type SourceRelay: Chain<BlockNumber = RelayBlockNumber, Hash = RelayBlockHash, Hasher = RelayBlockHasher>
+ CliChain
+ RelayChain;
/// Finality proofs synchronization pipeline (source parachain -> target).
type ParachainFinality: SubstrateParachainsPipeline<
SourceRelayChain = Self::SourceRelay,
SourceParachain = Self::Source,
TargetChain = Self::Target,
> + ParachainsPipeline<SourceChain = Self::SourceRelay, TargetChain = Self::Target>;
/// Finality proofs synchronization pipeline (source relay chain -> target).
type RelayFinality: SubstrateFinalitySyncPipeline<
SourceChain = Self::SourceRelay,
TargetChain = Self::Target,
>;
}
/// Bridge representation that can be used from the CLI for relaying messages.
pub trait MessagesCliBridge: CliBridgeBase {
/// Name of the runtime method used to estimate the message dispatch and delivery fee for the
/// defined bridge.
const ESTIMATE_MESSAGE_FEE_METHOD: &'static str;
/// The Source -> Destination messages synchronization pipeline.
type MessagesLane: SubstrateMessageLane<SourceChain = Self::Source, TargetChain = Self::Target>;
}
@@ -0,0 +1,409 @@
// Copyright 2019-2022 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 sp_core::Pair;
use structopt::StructOpt;
use strum::{EnumString, EnumVariantNames};
use crate::cli::CliChain;
pub use relay_substrate_client::ChainRuntimeVersion;
use substrate_relay_helper::TransactionParams;
#[doc = "Runtime version params."]
#[derive(StructOpt, Debug, PartialEq, Eq, Clone, Copy, EnumString, EnumVariantNames)]
pub enum RuntimeVersionType {
/// Auto query version from chain
Auto,
/// Custom `spec_version` and `transaction_version`
Custom,
/// Read version from bundle dependencies directly.
Bundle,
}
/// Create chain-specific set of runtime version parameters.
#[macro_export]
macro_rules! declare_chain_runtime_version_params_cli_schema {
($chain:ident, $chain_prefix:ident) => {
bp_runtime::paste::item! {
#[doc = $chain " runtime version params."]
#[derive(StructOpt, Debug, PartialEq, Eq, Clone, Copy)]
pub struct [<$chain RuntimeVersionParams>] {
#[doc = "The type of runtime version for chain " $chain]
#[structopt(long, default_value = "Bundle")]
pub [<$chain_prefix _version_mode>]: RuntimeVersionType,
#[doc = "The custom sepc_version for chain " $chain]
#[structopt(long)]
pub [<$chain_prefix _spec_version>]: Option<u32>,
#[doc = "The custom transaction_version for chain " $chain]
#[structopt(long)]
pub [<$chain_prefix _transaction_version>]: Option<u32>,
}
impl [<$chain RuntimeVersionParams>] {
/// Converts self into `ChainRuntimeVersion`.
pub fn into_runtime_version(
self,
bundle_runtime_version: Option<sp_version::RuntimeVersion>,
) -> anyhow::Result<ChainRuntimeVersion> {
Ok(match self.[<$chain_prefix _version_mode>] {
RuntimeVersionType::Auto => ChainRuntimeVersion::Auto,
RuntimeVersionType::Custom => {
let except_spec_version = self.[<$chain_prefix _spec_version>]
.ok_or_else(|| anyhow::Error::msg(format!("The {}-spec-version is required when choose custom mode", stringify!($chain_prefix))))?;
let except_transaction_version = self.[<$chain_prefix _transaction_version>]
.ok_or_else(|| anyhow::Error::msg(format!("The {}-transaction-version is required when choose custom mode", stringify!($chain_prefix))))?;
ChainRuntimeVersion::Custom(
except_spec_version,
except_transaction_version
)
},
RuntimeVersionType::Bundle => match bundle_runtime_version {
Some(runtime_version) => ChainRuntimeVersion::Custom(
runtime_version.spec_version,
runtime_version.transaction_version
),
None => ChainRuntimeVersion::Auto
},
})
}
}
}
};
}
/// Create chain-specific set of runtime version parameters.
#[macro_export]
macro_rules! declare_chain_connection_params_cli_schema {
($chain:ident, $chain_prefix:ident) => {
bp_runtime::paste::item! {
#[doc = $chain " connection params."]
#[derive(StructOpt, Debug, PartialEq, Eq, Clone)]
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, default_value = "9944")]
pub [<$chain_prefix _port>]: u16,
#[doc = "Use secure websocket connection."]
#[structopt(long)]
pub [<$chain_prefix _secure>]: bool,
#[doc = "Custom runtime version"]
#[structopt(flatten)]
pub [<$chain_prefix _runtime_version>]: [<$chain RuntimeVersionParams>],
}
impl [<$chain ConnectionParams>] {
/// Convert connection params into Substrate client.
#[allow(dead_code)]
pub async fn into_client<Chain: CliChain>(
self,
) -> anyhow::Result<relay_substrate_client::Client<Chain>> {
let chain_runtime_version = self
.[<$chain_prefix _runtime_version>]
.into_runtime_version(Chain::RUNTIME_VERSION)?;
Ok(relay_substrate_client::Client::new(relay_substrate_client::ConnectionParams {
host: self.[<$chain_prefix _host>],
port: self.[<$chain_prefix _port>],
secure: self.[<$chain_prefix _secure>],
chain_runtime_version,
})
.await
)
}
}
}
};
}
/// Helper trait to override transaction parameters differently.
pub trait TransactionParamsProvider {
/// Returns `true` if transaction parameters are defined by this provider.
fn is_defined(&self) -> bool;
/// Returns transaction parameters.
fn transaction_params<Chain: CliChain>(
&self,
) -> anyhow::Result<TransactionParams<Chain::KeyPair>>;
/// Returns transaction parameters, defined by `self` provider or, if they're not defined,
/// defined by `other` provider.
fn transaction_params_or<Chain: CliChain, T: TransactionParamsProvider>(
&self,
other: &T,
) -> anyhow::Result<TransactionParams<Chain::KeyPair>> {
if self.is_defined() {
self.transaction_params::<Chain>()
} else {
other.transaction_params::<Chain>()
}
}
}
/// Create chain-specific set of signing parameters.
#[macro_export]
macro_rules! declare_chain_signing_params_cli_schema {
($chain:ident, $chain_prefix:ident) => {
bp_runtime::paste::item! {
#[doc = $chain " signing params."]
#[derive(StructOpt, Debug, PartialEq, Eq, Clone)]
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>]: Option<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>,
#[doc = "Path to the file, that contains SURI of secret key to use when transactions are submitted to the " $chain " node. Can be overridden with " $chain_prefix "_signer option."]
#[structopt(long)]
pub [<$chain_prefix _signer_file>]: Option<std::path::PathBuf>,
#[doc = "Path to the file, that password for the SURI of secret key to use when transactions are submitted to the " $chain " node. Can be overridden with " $chain_prefix "_signer_password option."]
#[structopt(long)]
pub [<$chain_prefix _signer_password_file>]: Option<std::path::PathBuf>,
#[doc = "Transactions mortality period, in blocks. MUST be a power of two in [4; 65536] range. MAY NOT be larger than `BlockHashCount` parameter of the chain system module."]
#[structopt(long)]
pub [<$chain_prefix _transactions_mortality>]: Option<u32>,
}
impl [<$chain SigningParams>] {
/// Return transactions mortality.
#[allow(dead_code)]
pub fn transactions_mortality(&self) -> anyhow::Result<Option<u32>> {
self.[<$chain_prefix _transactions_mortality>]
.map(|transactions_mortality| {
if !(4..=65536).contains(&transactions_mortality)
|| !transactions_mortality.is_power_of_two()
{
Err(anyhow::format_err!(
"Transactions mortality {} is not a power of two in a [4; 65536] range",
transactions_mortality,
))
} else {
Ok(transactions_mortality)
}
})
.transpose()
}
/// Parse signing params into chain-specific KeyPair.
#[allow(dead_code)]
pub fn to_keypair<Chain: CliChain>(&self) -> anyhow::Result<Chain::KeyPair> {
let suri = match (self.[<$chain_prefix _signer>].as_ref(), self.[<$chain_prefix _signer_file>].as_ref()) {
(Some(suri), _) => suri.to_owned(),
(None, Some(suri_file)) => std::fs::read_to_string(suri_file)
.map_err(|err| anyhow::format_err!(
"Failed to read SURI from file {:?}: {}",
suri_file,
err,
))?,
(None, None) => return Err(anyhow::format_err!(
"One of options must be specified: '{}' or '{}'",
stringify!([<$chain_prefix _signer>]),
stringify!([<$chain_prefix _signer_file>]),
)),
};
let suri_password = match (
self.[<$chain_prefix _signer_password>].as_ref(),
self.[<$chain_prefix _signer_password_file>].as_ref(),
) {
(Some(suri_password), _) => Some(suri_password.to_owned()),
(None, Some(suri_password_file)) => std::fs::read_to_string(suri_password_file)
.map(Some)
.map_err(|err| anyhow::format_err!(
"Failed to read SURI password from file {:?}: {}",
suri_password_file,
err,
))?,
_ => None,
};
use sp_core::crypto::Pair;
Chain::KeyPair::from_string(
&suri,
suri_password.as_deref()
).map_err(|e| anyhow::format_err!("{:?}", e))
}
}
#[allow(dead_code)]
impl TransactionParamsProvider for [<$chain SigningParams>] {
fn is_defined(&self) -> bool {
self.[<$chain_prefix _signer>].is_some() || self.[<$chain_prefix _signer_file>].is_some()
}
fn transaction_params<Chain: CliChain>(&self) -> anyhow::Result<TransactionParams<Chain::KeyPair>> {
Ok(TransactionParams {
mortality: self.transactions_mortality()?,
signer: self.to_keypair::<Chain>()?,
})
}
}
}
};
}
/// Create chain-specific set of messages pallet owner signing parameters.
#[macro_export]
macro_rules! declare_chain_messages_pallet_owner_signing_params_cli_schema {
($chain:ident, $chain_prefix:ident) => {
bp_runtime::paste::item! {
#[doc = "Parameters required to sign transaction on behalf of owner of the messages pallet at " $chain "."]
#[derive(StructOpt, Debug, PartialEq, Eq)]
pub struct [<$chain MessagesPalletOwnerSigningParams>] {
#[doc = "The SURI of secret key to use when transactions are submitted to the " $chain " node."]
#[structopt(long)]
pub [<$chain_prefix _messages_pallet_owner>]: Option<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 _messages_pallet_owner_password>]: Option<String>,
}
#[allow(dead_code)]
impl [<$chain MessagesPalletOwnerSigningParams>] {
/// Parse signing params into chain-specific KeyPair.
pub fn to_keypair<Chain: CliChain>(&self) -> anyhow::Result<Option<Chain::KeyPair>> {
let [<$chain_prefix _messages_pallet_owner>] = match self.[<$chain_prefix _messages_pallet_owner>] {
Some(ref messages_pallet_owner) => messages_pallet_owner,
None => return Ok(None),
};
Chain::KeyPair::from_string(
[<$chain_prefix _messages_pallet_owner>],
self.[<$chain_prefix _messages_pallet_owner_password>].as_deref()
).map_err(|e| anyhow::format_err!("{:?}", e)).map(Some)
}
}
}
};
}
/// Create chain-specific set of configuration objects: connection parameters,
/// signing parameters and bridge initialization parameters.
#[macro_export]
macro_rules! declare_chain_cli_schema {
($chain:ident, $chain_prefix:ident) => {
$crate::declare_chain_runtime_version_params_cli_schema!($chain, $chain_prefix);
$crate::declare_chain_connection_params_cli_schema!($chain, $chain_prefix);
$crate::declare_chain_signing_params_cli_schema!($chain, $chain_prefix);
$crate::declare_chain_messages_pallet_owner_signing_params_cli_schema!(
$chain,
$chain_prefix
);
};
}
declare_chain_cli_schema!(Source, source);
declare_chain_cli_schema!(Target, target);
declare_chain_cli_schema!(Relaychain, relaychain);
declare_chain_cli_schema!(Parachain, parachain);
#[cfg(test)]
mod tests {
use super::*;
use sp_core::Pair;
#[test]
fn reads_suri_from_file() {
const ALICE: &str = "//Alice";
const BOB: &str = "//Bob";
const ALICE_PASSWORD: &str = "alice_password";
const BOB_PASSWORD: &str = "bob_password";
let alice: sp_core::sr25519::Pair = Pair::from_string(ALICE, Some(ALICE_PASSWORD)).unwrap();
let bob: sp_core::sr25519::Pair = Pair::from_string(BOB, Some(BOB_PASSWORD)).unwrap();
let bob_with_alice_password =
sp_core::sr25519::Pair::from_string(BOB, Some(ALICE_PASSWORD)).unwrap();
let temp_dir = tempfile::tempdir().unwrap();
let mut suri_file_path = temp_dir.path().to_path_buf();
let mut password_file_path = temp_dir.path().to_path_buf();
suri_file_path.push("suri");
password_file_path.push("password");
std::fs::write(&suri_file_path, BOB.as_bytes()).unwrap();
std::fs::write(&password_file_path, BOB_PASSWORD.as_bytes()).unwrap();
// when both seed and password are read from file
assert_eq!(
TargetSigningParams {
target_signer: Some(ALICE.into()),
target_signer_password: Some(ALICE_PASSWORD.into()),
target_signer_file: None,
target_signer_password_file: None,
target_transactions_mortality: None,
}
.to_keypair::<relay_rialto_client::Rialto>()
.map(|p| p.public())
.map_err(drop),
Ok(alice.public()),
);
// when both seed and password are read from file
assert_eq!(
TargetSigningParams {
target_signer: None,
target_signer_password: None,
target_signer_file: Some(suri_file_path.clone()),
target_signer_password_file: Some(password_file_path.clone()),
target_transactions_mortality: None,
}
.to_keypair::<relay_rialto_client::Rialto>()
.map(|p| p.public())
.map_err(drop),
Ok(bob.public()),
);
// when password are is overriden by cli option
assert_eq!(
TargetSigningParams {
target_signer: None,
target_signer_password: Some(ALICE_PASSWORD.into()),
target_signer_file: Some(suri_file_path.clone()),
target_signer_password_file: Some(password_file_path.clone()),
target_transactions_mortality: None,
}
.to_keypair::<relay_rialto_client::Rialto>()
.map(|p| p.public())
.map_err(drop),
Ok(bob_with_alice_password.public()),
);
// when both seed and password are overriden by cli options
assert_eq!(
TargetSigningParams {
target_signer: Some(ALICE.into()),
target_signer_password: Some(ALICE_PASSWORD.into()),
target_signer_file: Some(suri_file_path),
target_signer_password_file: Some(password_file_path),
target_transactions_mortality: None,
}
.to_keypair::<relay_rialto_client::Rialto>()
.map(|p| p.public())
.map_err(drop),
Ok(alice.public()),
);
}
}
@@ -0,0 +1,145 @@
// 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/>.
use crate::cli::{ExplicitOrMaximal, HexBytes};
use bp_runtime::EncodedOrDecodedCall;
use codec::Encode;
use relay_substrate_client::Chain;
use structopt::StructOpt;
/// All possible messages that may be delivered to generic Substrate chain.
///
/// Note this enum may be used in the context of both Source (as part of `encode-call`)
/// and Target chain (as part of `encode-message/send-message`).
#[derive(StructOpt, Debug, PartialEq, Eq)]
pub enum Message {
/// Raw bytes for the message.
Raw {
/// Raw message bytes.
data: HexBytes,
},
/// Message with given size.
Sized {
/// Sized of the message.
size: ExplicitOrMaximal<u32>,
},
}
/// Raw, SCALE-encoded message payload used in expected deployment.
pub type RawMessage = Vec<u8>;
pub trait CliEncodeMessage: Chain {
/// Encode a send XCM call of the XCM pallet.
fn encode_send_xcm(
message: xcm::VersionedXcm<()>,
bridge_instance_index: u8,
) -> anyhow::Result<EncodedOrDecodedCall<Self::Call>>;
}
/// Encode message payload passed through CLI flags.
pub(crate) fn encode_message<Source: Chain, Target: Chain>(
message: &Message,
) -> anyhow::Result<RawMessage> {
Ok(match message {
Message::Raw { ref data } => data.0.clone(),
Message::Sized { ref size } => {
let expected_xcm_size = match *size {
ExplicitOrMaximal::Explicit(size) => size,
ExplicitOrMaximal::Maximal => compute_maximal_message_size(
Source::max_extrinsic_size(),
Target::max_extrinsic_size(),
),
};
// there's no way to craft XCM of the given size - we'll be using `ExpectPallet`
// instruction, which has byte vector inside
let mut current_vec_size = expected_xcm_size;
let xcm = loop {
let xcm = xcm::VersionedXcm::<()>::V3(
vec![xcm::v3::Instruction::ExpectPallet {
index: 0,
name: vec![42; current_vec_size as usize],
module_name: vec![],
crate_major: 0,
min_crate_minor: 0,
}]
.into(),
);
if xcm.encode().len() <= expected_xcm_size as usize {
break xcm
}
current_vec_size -= 1;
};
xcm.encode()
},
})
}
/// Compute maximal message size, given max extrinsic size at source and target chains.
pub(crate) fn compute_maximal_message_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_message_size =
bridge_runtime_common::messages::target::maximal_incoming_message_size(
maximal_target_extrinsic_size,
);
if maximal_message_size > maximal_source_extrinsic_size {
maximal_source_extrinsic_size
} else {
maximal_message_size
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cli::send_message::decode_xcm;
use bp_runtime::Chain;
use relay_millau_client::Millau;
use relay_rialto_client::Rialto;
#[test]
fn encode_explicit_size_message_works() {
let msg = encode_message::<Rialto, Millau>(&Message::Sized {
size: ExplicitOrMaximal::Explicit(100),
})
.unwrap();
assert_eq!(msg.len(), 100);
// check that it decodes to valid xcm
let _ = decode_xcm(msg).unwrap();
}
#[test]
fn encode_maximal_size_message_works() {
let maximal_size = compute_maximal_message_size(
Rialto::max_extrinsic_size(),
Millau::max_extrinsic_size(),
);
let msg =
encode_message::<Rialto, Millau>(&Message::Sized { size: ExplicitOrMaximal::Maximal })
.unwrap();
assert_eq!(msg.len(), maximal_size as usize);
// check that it decodes to valid xcm
let _ = decode_xcm(msg).unwrap();
}
}
+219
View File
@@ -0,0 +1,219 @@
// 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/>.
use async_trait::async_trait;
use codec::Encode;
use crate::{
chains::{
millau_headers_to_rialto::MillauToRialtoCliBridge,
millau_headers_to_rialto_parachain::MillauToRialtoParachainCliBridge,
rialto_headers_to_millau::RialtoToMillauCliBridge,
rococo_headers_to_bridge_hub_wococo::RococoToBridgeHubWococoCliBridge,
westend_headers_to_millau::WestendToMillauCliBridge,
wococo_headers_to_bridge_hub_rococo::WococoToBridgeHubRococoCliBridge,
},
cli::{bridge::CliBridgeBase, chain_schema::*},
};
use bp_runtime::Chain as ChainBase;
use relay_substrate_client::{AccountKeyPairOf, Chain, SignParam, UnsignedTransaction};
use sp_core::Pair;
use structopt::StructOpt;
use strum::{EnumString, EnumVariantNames, VariantNames};
use substrate_relay_helper::finality::engine::{Engine, Grandpa as GrandpaFinalityEngine};
/// Initialize bridge pallet.
#[derive(StructOpt)]
pub struct InitBridge {
/// A bridge instance to initialize.
#[structopt(possible_values = InitBridgeName::VARIANTS, case_insensitive = true)]
bridge: InitBridgeName,
#[structopt(flatten)]
source: SourceConnectionParams,
#[structopt(flatten)]
target: TargetConnectionParams,
#[structopt(flatten)]
target_sign: TargetSigningParams,
/// Generates all required data, but does not submit extrinsic
#[structopt(long)]
dry_run: bool,
}
#[derive(Debug, EnumString, EnumVariantNames)]
#[strum(serialize_all = "kebab_case")]
/// Bridge to initialize.
pub enum InitBridgeName {
MillauToRialto,
RialtoToMillau,
WestendToMillau,
MillauToRialtoParachain,
RococoToBridgeHubWococo,
WococoToBridgeHubRococo,
}
#[async_trait]
trait BridgeInitializer: CliBridgeBase
where
<Self::Target as ChainBase>::AccountId: From<<AccountKeyPairOf<Self::Target> as Pair>::Public>,
{
type Engine: Engine<Self::Source>;
/// Get the encoded call to init the bridge.
fn encode_init_bridge(
init_data: <Self::Engine as Engine<Self::Source>>::InitializationData,
) -> <Self::Target as Chain>::Call;
/// Initialize the bridge.
async fn init_bridge(data: InitBridge) -> anyhow::Result<()> {
let source_client = data.source.into_client::<Self::Source>().await?;
let target_client = data.target.into_client::<Self::Target>().await?;
let target_sign = data.target_sign.to_keypair::<Self::Target>()?;
let dry_run = data.dry_run;
let (spec_version, transaction_version) = target_client.simple_runtime_version().await?;
substrate_relay_helper::finality::initialize::initialize::<Self::Engine, _, _, _>(
source_client,
target_client.clone(),
target_sign.public().into(),
SignParam {
spec_version,
transaction_version,
genesis_hash: *target_client.genesis_hash(),
signer: target_sign,
},
move |transaction_nonce, initialization_data| {
let call = Self::encode_init_bridge(initialization_data);
log::info!(
target: "bridge",
"Initialize bridge call encoded as hex string: {:?}",
format!("0x{}", hex::encode(call.encode()))
);
Ok(UnsignedTransaction::new(call.into(), transaction_nonce))
},
dry_run,
)
.await;
Ok(())
}
}
impl BridgeInitializer for MillauToRialtoCliBridge {
type Engine = GrandpaFinalityEngine<Self::Source>;
fn encode_init_bridge(
init_data: <Self::Engine as Engine<Self::Source>>::InitializationData,
) -> <Self::Target as Chain>::Call {
rialto_runtime::SudoCall::sudo {
call: Box::new(rialto_runtime::BridgeGrandpaCall::initialize { init_data }.into()),
}
.into()
}
}
impl BridgeInitializer for MillauToRialtoParachainCliBridge {
type Engine = GrandpaFinalityEngine<Self::Source>;
fn encode_init_bridge(
init_data: <Self::Engine as Engine<Self::Source>>::InitializationData,
) -> <Self::Target as Chain>::Call {
let initialize_call = rialto_parachain_runtime::BridgeGrandpaCall::<
rialto_parachain_runtime::Runtime,
rialto_parachain_runtime::MillauGrandpaInstance,
>::initialize {
init_data,
};
rialto_parachain_runtime::SudoCall::sudo { call: Box::new(initialize_call.into()) }.into()
}
}
impl BridgeInitializer for RialtoToMillauCliBridge {
type Engine = GrandpaFinalityEngine<Self::Source>;
fn encode_init_bridge(
init_data: <Self::Engine as Engine<Self::Source>>::InitializationData,
) -> <Self::Target as Chain>::Call {
let initialize_call = millau_runtime::BridgeGrandpaCall::<
millau_runtime::Runtime,
millau_runtime::RialtoGrandpaInstance,
>::initialize {
init_data,
};
millau_runtime::SudoCall::sudo { call: Box::new(initialize_call.into()) }.into()
}
}
impl BridgeInitializer for WestendToMillauCliBridge {
type Engine = GrandpaFinalityEngine<Self::Source>;
fn encode_init_bridge(
init_data: <Self::Engine as Engine<Self::Source>>::InitializationData,
) -> <Self::Target as Chain>::Call {
// 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
millau_runtime::BridgeGrandpaCall::<
millau_runtime::Runtime,
millau_runtime::WestendGrandpaInstance,
>::initialize {
init_data,
}
.into()
}
}
impl BridgeInitializer for RococoToBridgeHubWococoCliBridge {
type Engine = GrandpaFinalityEngine<Self::Source>;
fn encode_init_bridge(
init_data: <Self::Engine as Engine<Self::Source>>::InitializationData,
) -> <Self::Target as Chain>::Call {
relay_bridge_hub_wococo_client::runtime::Call::BridgeRococoGrandpa(
relay_bridge_hub_wococo_client::runtime::BridgeGrandpaRococoCall::initialize(init_data),
)
}
}
impl BridgeInitializer for WococoToBridgeHubRococoCliBridge {
type Engine = GrandpaFinalityEngine<Self::Source>;
fn encode_init_bridge(
init_data: <Self::Engine as Engine<Self::Source>>::InitializationData,
) -> <Self::Target as Chain>::Call {
relay_bridge_hub_rococo_client::runtime::Call::BridgeWococoGrandpa(
relay_bridge_hub_rococo_client::runtime::BridgeWococoGrandpaCall::initialize(init_data),
)
}
}
impl InitBridge {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
match self.bridge {
InitBridgeName::MillauToRialto => MillauToRialtoCliBridge::init_bridge(self),
InitBridgeName::RialtoToMillau => RialtoToMillauCliBridge::init_bridge(self),
InitBridgeName::WestendToMillau => WestendToMillauCliBridge::init_bridge(self),
InitBridgeName::MillauToRialtoParachain =>
MillauToRialtoParachainCliBridge::init_bridge(self),
InitBridgeName::RococoToBridgeHubWococo =>
RococoToBridgeHubWococoCliBridge::init_bridge(self),
InitBridgeName::WococoToBridgeHubRococo =>
WococoToBridgeHubRococoCliBridge::init_bridge(self),
}
.await
}
}
+300
View File
@@ -0,0 +1,300 @@
// 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/>.
//! Deal with CLI args of substrate-to-substrate relay.
use std::convert::TryInto;
use codec::{Decode, Encode};
use structopt::{clap::arg_enum, StructOpt};
use strum::{EnumString, EnumVariantNames};
use bp_messages::LaneId;
pub(crate) mod bridge;
pub(crate) mod encode_message;
pub(crate) mod send_message;
mod chain_schema;
mod init_bridge;
mod register_parachain;
mod relay_headers;
mod relay_headers_and_messages;
mod relay_messages;
mod relay_parachains;
mod resubmit_transactions;
/// 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(relay_headers::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(relay_messages::RelayMessages),
/// Start headers and messages relay between two Substrate chains.
///
/// This high-level relay internally starts four low-level relays: two `RelayHeaders`
/// and two `RelayMessages` relays. Headers are only relayed when they are required by
/// the message relays - i.e. when there are messages or confirmations that needs to be
/// relayed between chains.
RelayHeadersAndMessages(Box<relay_headers_and_messages::RelayHeadersAndMessages>),
/// Initialize on-chain bridge pallet with current header data.
///
/// Sends initialization transaction to bootstrap the bridge with current finalized block data.
InitBridge(init_bridge::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(send_message::SendMessage),
/// Resubmit transactions with increased tip if they are stalled.
ResubmitTransactions(resubmit_transactions::ResubmitTransactions),
/// Register parachain.
RegisterParachain(register_parachain::RegisterParachain),
///
RelayParachains(relay_parachains::RelayParachains),
}
impl Command {
// Initialize logger depending on the command.
fn init_logger(&self) {
use relay_utils::initialize::{initialize_logger, initialize_relay};
match self {
Self::RelayHeaders(_) |
Self::RelayMessages(_) |
Self::RelayHeadersAndMessages(_) |
Self::InitBridge(_) => {
initialize_relay();
},
_ => {
initialize_logger(false);
},
}
}
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
self.init_logger();
match self {
Self::RelayHeaders(arg) => arg.run().await?,
Self::RelayMessages(arg) => arg.run().await?,
Self::RelayHeadersAndMessages(arg) => arg.run().await?,
Self::InitBridge(arg) => arg.run().await?,
Self::SendMessage(arg) => arg.run().await?,
Self::ResubmitTransactions(arg) => arg.run().await?,
Self::RegisterParachain(arg) => arg.run().await?,
Self::RelayParachains(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 balance type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Balance(pub u128);
impl std::fmt::Display for Balance {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
use num_format::{Locale, ToFormattedString};
write!(fmt, "{}", self.0.to_formatted_string(&Locale::en))
}
}
impl std::str::FromStr for Balance {
type Err = <u128 as std::str::FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(s.parse()?))
}
}
impl Balance {
/// Cast balance to `u64` type, panicking if it's too large.
pub fn cast(&self) -> u64 {
self.0.try_into().expect("Balance is too high for this chain.")
}
}
// Bridge-supported network definition.
///
/// Used to abstract away CLI commands.
pub trait CliChain: relay_substrate_client::Chain {
/// Current version of the chain runtime, known to relay.
///
/// can be `None` if relay is not going to submit transactions to that chain.
const RUNTIME_VERSION: Option<sp_version::RuntimeVersion>;
/// Crypto KeyPair type used to send messages.
///
/// In case of chains supporting multiple cryptos, pick one used by the CLI.
type KeyPair: sp_core::crypto::Pair;
/// Numeric value of SS58 format.
fn ss58_format() -> u16;
}
/// Lane id.
#[derive(Debug, Clone, PartialEq, Eq)]
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(Default, Encode, Decode, PartialEq, Eq)]
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{self}")
}
}
impl std::fmt::Display for HexBytes {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(fmt, "{}", hex::encode(&self.0))
}
}
/// Prometheus metrics params.
#[derive(Clone, Debug, PartialEq, 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 relay_utils::metrics::MetricsParams {
fn from(cli_params: PrometheusParams) -> relay_utils::metrics::MetricsParams {
if !cli_params.no_prometheus {
Some(relay_utils::metrics::MetricsAddress {
host: cli_params.prometheus_host,
port: cli_params.prometheus_port,
})
.into()
} else {
None.into()
}
}
}
/// Either explicit or maximal allowed value.
#[derive(Debug, Clone, PartialEq, Eq)]
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 '{e:?}'. Expected 'max' or explicit value"))
}
}
#[doc = "Runtime version params."]
#[derive(StructOpt, Debug, PartialEq, Eq, Clone, Copy, EnumString, EnumVariantNames)]
pub enum RuntimeVersionType {
/// Auto query version from chain
Auto,
/// Custom `spec_version` and `transaction_version`
Custom,
/// Read version from bundle dependencies directly.
Bundle,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hex_bytes_display_matches_from_str_for_clap() {
// given
let hex = HexBytes(vec![1, 2, 3, 4]);
let display = format!("{hex}");
// when
let hex2: HexBytes = display.parse().unwrap();
// then
assert_eq!(hex.0, hex2.0);
}
}
@@ -0,0 +1,359 @@
// 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/>.
use crate::cli::{chain_schema::*, Balance};
use codec::Encode;
use frame_support::Twox64Concat;
use num_traits::Zero;
use polkadot_parachain::primitives::{
HeadData as ParaHeadData, Id as ParaId, ValidationCode as ParaValidationCode,
};
use polkadot_runtime_common::{
paras_registrar::Call as ParaRegistrarCall, slots::Call as ParaSlotsCall,
};
use polkadot_runtime_parachains::paras::ParaLifecycle;
use relay_substrate_client::{AccountIdOf, CallOf, Chain, Client, SignParam, UnsignedTransaction};
use relay_utils::{TrackedTransactionStatus, TransactionTracker};
use rialto_runtime::SudoCall;
use sp_core::{
storage::{well_known_keys::CODE, StorageKey},
Pair,
};
use structopt::StructOpt;
use strum::{EnumString, EnumVariantNames, VariantNames};
/// Name of the `NextFreeParaId` value in the `polkadot_runtime_common::paras_registrar` pallet.
const NEXT_FREE_PARA_ID_STORAGE_NAME: &str = "NextFreeParaId";
/// Name of the `ParaLifecycles` map in the `polkadot_runtime_parachains::paras` pallet.
const PARAS_LIFECYCLES_STORAGE_NAME: &str = "ParaLifecycles";
/// Register parachain.
#[derive(StructOpt, Debug, PartialEq, Eq)]
pub struct RegisterParachain {
/// A parachain to register.
#[structopt(possible_values = Parachain::VARIANTS, case_insensitive = true)]
parachain: Parachain,
/// Parachain deposit.
#[structopt(long, default_value = "0")]
deposit: Balance,
/// Lease begin.
#[structopt(long, default_value = "0")]
lease_begin: u32,
/// Lease end.
#[structopt(long, default_value = "256")]
lease_end: u32,
#[structopt(flatten)]
relay_connection: RelaychainConnectionParams,
#[structopt(flatten)]
relay_sign: RelaychainSigningParams,
#[structopt(flatten)]
para_connection: ParachainConnectionParams,
}
/// Parachain to register.
#[derive(Debug, EnumString, EnumVariantNames, PartialEq, Eq)]
#[strum(serialize_all = "kebab_case")]
pub enum Parachain {
RialtoParachain,
}
macro_rules! select_bridge {
($bridge: expr, $generic: tt) => {
match $bridge {
Parachain::RialtoParachain => {
type Relaychain = relay_rialto_client::Rialto;
type Parachain = relay_rialto_parachain_client::RialtoParachain;
use bp_rialto::{PARAS_PALLET_NAME, PARAS_REGISTRAR_PALLET_NAME};
$generic
},
}
};
}
impl RegisterParachain {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
select_bridge!(self.parachain, {
let relay_client = self.relay_connection.into_client::<Relaychain>().await?;
let relay_sign = self.relay_sign.to_keypair::<Relaychain>()?;
let para_client = self.para_connection.into_client::<Parachain>().await?;
// hopefully we're the only actor that is registering parachain right now
// => read next parachain id
let para_id_key = bp_runtime::storage_value_final_key(
PARAS_REGISTRAR_PALLET_NAME.as_bytes(),
NEXT_FREE_PARA_ID_STORAGE_NAME.as_bytes(),
);
let para_id: ParaId = relay_client
.storage_value(StorageKey(para_id_key.to_vec()), None)
.await?
.unwrap_or(polkadot_primitives::v2::LOWEST_PUBLIC_ID)
.max(polkadot_primitives::v2::LOWEST_PUBLIC_ID);
log::info!(target: "bridge", "Going to reserve parachain id: {:?}", para_id);
// step 1: reserve a parachain id
let relay_genesis_hash = *relay_client.genesis_hash();
let relay_sudo_account: AccountIdOf<Relaychain> = relay_sign.public().into();
let reserve_parachain_id_call: CallOf<Relaychain> =
ParaRegistrarCall::reserve {}.into();
let reserve_parachain_signer = relay_sign.clone();
let (spec_version, transaction_version) = relay_client.simple_runtime_version().await?;
let reserve_result = relay_client
.submit_and_watch_signed_extrinsic(
relay_sudo_account.clone(),
SignParam::<Relaychain> {
spec_version,
transaction_version,
genesis_hash: relay_genesis_hash,
signer: reserve_parachain_signer,
},
move |_, transaction_nonce| {
Ok(UnsignedTransaction::new(
reserve_parachain_id_call.into(),
transaction_nonce,
))
},
)
.await?
.wait()
.await;
if reserve_result == TrackedTransactionStatus::Lost {
return Err(anyhow::format_err!(
"Failed to finalize `reserve-parachain-id` transaction"
))
}
log::info!(target: "bridge", "Reserved parachain id: {:?}", para_id);
// step 2: register parathread
let para_genesis_header = para_client.header_by_number(Zero::zero()).await?;
let para_code = para_client
.raw_storage_value(StorageKey(CODE.to_vec()), Some(para_genesis_header.hash()))
.await?
.ok_or_else(|| {
anyhow::format_err!("Cannot fetch validation code of {}", Parachain::NAME)
})?
.0;
log::info!(
target: "bridge",
"Going to register parachain {:?}: genesis len = {} code len = {}",
para_id,
para_genesis_header.encode().len(),
para_code.len(),
);
let register_parathread_call: CallOf<Relaychain> = ParaRegistrarCall::register {
id: para_id,
genesis_head: ParaHeadData(para_genesis_header.encode()),
validation_code: ParaValidationCode(para_code),
}
.into();
let register_parathread_signer = relay_sign.clone();
let register_result = relay_client
.submit_and_watch_signed_extrinsic(
relay_sudo_account.clone(),
SignParam::<Relaychain> {
spec_version,
transaction_version,
genesis_hash: relay_genesis_hash,
signer: register_parathread_signer,
},
move |_, transaction_nonce| {
Ok(UnsignedTransaction::new(
register_parathread_call.into(),
transaction_nonce,
))
},
)
.await?
.wait()
.await;
if register_result == TrackedTransactionStatus::Lost {
return Err(anyhow::format_err!(
"Failed to finalize `register-parathread` transaction"
))
}
log::info!(target: "bridge", "Registered parachain: {:?}. Waiting for onboarding", para_id);
// wait until parathread is onboarded
let para_state_key = bp_runtime::storage_map_final_key::<Twox64Concat>(
PARAS_PALLET_NAME,
PARAS_LIFECYCLES_STORAGE_NAME,
&para_id.encode(),
);
wait_para_state(
&relay_client,
&para_state_key.0,
&[ParaLifecycle::Onboarding, ParaLifecycle::Parathread],
ParaLifecycle::Parathread,
)
.await?;
// step 3: force parachain leases
let lease_begin = self.lease_begin;
let lease_end = self.lease_end;
let para_deposit = self.deposit.cast().into();
log::info!(
target: "bridge",
"Going to force leases of parachain {:?}: [{}; {}]",
para_id,
lease_begin,
lease_end,
);
let force_lease_call: CallOf<Relaychain> = SudoCall::sudo {
call: Box::new(
ParaSlotsCall::force_lease {
para: para_id,
leaser: relay_sudo_account.clone(),
amount: para_deposit,
period_begin: lease_begin,
period_count: lease_end.saturating_sub(lease_begin).saturating_add(1),
}
.into(),
),
}
.into();
let force_lease_signer = relay_sign.clone();
relay_client
.submit_signed_extrinsic(
relay_sudo_account,
SignParam::<Relaychain> {
spec_version,
transaction_version,
genesis_hash: relay_genesis_hash,
signer: force_lease_signer,
},
move |_, transaction_nonce| {
Ok(UnsignedTransaction::new(force_lease_call.into(), transaction_nonce))
},
)
.await?;
log::info!(target: "bridge", "Registered parachain leases: {:?}. Waiting for onboarding", para_id);
// wait until parachain is onboarded
wait_para_state(
&relay_client,
&para_state_key.0,
&[
ParaLifecycle::Onboarding,
ParaLifecycle::UpgradingParathread,
ParaLifecycle::Parathread,
],
ParaLifecycle::Parachain,
)
.await?;
Ok(())
})
}
}
/// Wait until parachain state is changed.
async fn wait_para_state<Relaychain: Chain>(
relay_client: &Client<Relaychain>,
para_state_key: &[u8],
from_states: &[ParaLifecycle],
to_state: ParaLifecycle,
) -> anyhow::Result<()> {
loop {
let para_state: ParaLifecycle = relay_client
.storage_value(StorageKey(para_state_key.to_vec()), None)
.await?
.ok_or_else(|| {
anyhow::format_err!(
"Cannot fetch next free parachain lifecycle from the runtime storage of {}",
Relaychain::NAME,
)
})?;
if para_state == to_state {
log::info!(target: "bridge", "Parachain state is now: {:?}", to_state);
return Ok(())
}
if !from_states.contains(&para_state) {
return Err(anyhow::format_err!("Invalid parachain lifecycle: {:?}", para_state))
}
log::info!(target: "bridge", "Parachain state: {:?}. Waiting for {:?}", para_state, to_state);
async_std::task::sleep(Relaychain::AVERAGE_BLOCK_INTERVAL).await;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn register_rialto_parachain() {
let register_parachain = RegisterParachain::from_iter(vec![
"register-parachain",
"rialto-parachain",
"--parachain-host",
"127.0.0.1",
"--parachain-port",
"11949",
"--relaychain-host",
"127.0.0.1",
"--relaychain-port",
"9944",
"--relaychain-signer",
"//Alice",
"--deposit",
"42",
"--lease-begin",
"100",
"--lease-end",
"200",
]);
assert_eq!(
register_parachain,
RegisterParachain {
parachain: Parachain::RialtoParachain,
deposit: Balance(42),
lease_begin: 100,
lease_end: 200,
relay_connection: RelaychainConnectionParams {
relaychain_host: "127.0.0.1".into(),
relaychain_port: 9944,
relaychain_secure: false,
relaychain_runtime_version: RelaychainRuntimeVersionParams {
relaychain_version_mode: RuntimeVersionType::Bundle,
relaychain_spec_version: None,
relaychain_transaction_version: None,
}
},
relay_sign: RelaychainSigningParams {
relaychain_signer: Some("//Alice".into()),
relaychain_signer_password: None,
relaychain_signer_file: None,
relaychain_signer_password_file: None,
relaychain_transactions_mortality: None,
},
para_connection: ParachainConnectionParams {
parachain_host: "127.0.0.1".into(),
parachain_port: 11949,
parachain_secure: false,
parachain_runtime_version: ParachainRuntimeVersionParams {
parachain_version_mode: RuntimeVersionType::Bundle,
parachain_spec_version: None,
parachain_transaction_version: None,
}
},
}
);
}
}
@@ -0,0 +1,128 @@
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity Bridges Common is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
use async_trait::async_trait;
use relay_substrate_client::{AccountIdOf, AccountKeyPairOf};
use sp_core::Pair;
use structopt::StructOpt;
use strum::{EnumString, EnumVariantNames, VariantNames};
use crate::chains::{
millau_headers_to_rialto::MillauToRialtoCliBridge,
millau_headers_to_rialto_parachain::MillauToRialtoParachainCliBridge,
rialto_headers_to_millau::RialtoToMillauCliBridge,
rococo_headers_to_bridge_hub_wococo::RococoToBridgeHubWococoCliBridge,
westend_headers_to_millau::WestendToMillauCliBridge,
wococo_headers_to_bridge_hub_rococo::WococoToBridgeHubRococoCliBridge,
};
use relay_utils::metrics::{GlobalMetrics, StandaloneMetric};
use substrate_relay_helper::finality::SubstrateFinalitySyncPipeline;
use crate::cli::{bridge::*, chain_schema::*, PrometheusParams};
/// Start headers relayer process.
#[derive(StructOpt)]
pub struct RelayHeaders {
/// A bridge instance to relay headers for.
#[structopt(possible_values = RelayHeadersBridge::VARIANTS, case_insensitive = true)]
bridge: RelayHeadersBridge,
/// If passed, only mandatory headers (headers that are changing the GRANDPA authorities set)
/// are relayed.
#[structopt(long)]
only_mandatory_headers: bool,
#[structopt(flatten)]
source: SourceConnectionParams,
#[structopt(flatten)]
target: TargetConnectionParams,
#[structopt(flatten)]
target_sign: TargetSigningParams,
#[structopt(flatten)]
prometheus_params: PrometheusParams,
}
#[derive(Debug, EnumString, EnumVariantNames)]
#[strum(serialize_all = "kebab_case")]
/// Headers relay bridge.
pub enum RelayHeadersBridge {
MillauToRialto,
RialtoToMillau,
WestendToMillau,
MillauToRialtoParachain,
RococoToBridgeHubWococo,
WococoToBridgeHubRococo,
}
#[async_trait]
trait HeadersRelayer: RelayToRelayHeadersCliBridge
where
AccountIdOf<Self::Target>: From<<AccountKeyPairOf<Self::Target> as Pair>::Public>,
{
/// Relay headers.
async fn relay_headers(data: RelayHeaders) -> anyhow::Result<()> {
let source_client = data.source.into_client::<Self::Source>().await?;
let target_client = data.target.into_client::<Self::Target>().await?;
let target_transactions_mortality = data.target_sign.target_transactions_mortality;
let target_sign = data.target_sign.to_keypair::<Self::Target>()?;
let metrics_params: relay_utils::metrics::MetricsParams = data.prometheus_params.into();
GlobalMetrics::new()?.register_and_spawn(&metrics_params.registry)?;
let target_transactions_params = substrate_relay_helper::TransactionParams {
signer: target_sign,
mortality: target_transactions_mortality,
};
Self::Finality::start_relay_guards(
&target_client,
&target_transactions_params,
target_client.can_start_version_guard(),
)
.await?;
substrate_relay_helper::finality::run::<Self::Finality>(
source_client,
target_client,
data.only_mandatory_headers,
target_transactions_params,
metrics_params,
)
.await
}
}
impl HeadersRelayer for MillauToRialtoCliBridge {}
impl HeadersRelayer for RialtoToMillauCliBridge {}
impl HeadersRelayer for WestendToMillauCliBridge {}
impl HeadersRelayer for MillauToRialtoParachainCliBridge {}
impl HeadersRelayer for RococoToBridgeHubWococoCliBridge {}
impl HeadersRelayer for WococoToBridgeHubRococoCliBridge {}
impl RelayHeaders {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
match self.bridge {
RelayHeadersBridge::MillauToRialto => MillauToRialtoCliBridge::relay_headers(self),
RelayHeadersBridge::RialtoToMillau => RialtoToMillauCliBridge::relay_headers(self),
RelayHeadersBridge::WestendToMillau => WestendToMillauCliBridge::relay_headers(self),
RelayHeadersBridge::MillauToRialtoParachain =>
MillauToRialtoParachainCliBridge::relay_headers(self),
RelayHeadersBridge::RococoToBridgeHubWococo =>
RococoToBridgeHubWococoCliBridge::relay_headers(self),
RelayHeadersBridge::WococoToBridgeHubRococo =>
WococoToBridgeHubRococoCliBridge::relay_headers(self),
}
.await
}
}
@@ -0,0 +1,732 @@
// Copyright 2019-2022 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/>.
//! Complex 2-ways headers+messages relays support.
//!
//! To add new complex relay between `ChainA` and `ChainB`, you must:
//!
//! 1) ensure that there's a `declare_chain_cli_schema!(...)` for both chains.
//! 2) add `declare_chain_to_chain_bridge_schema!(...)` or
//! `declare_chain_to_parachain_bridge_schema` for the bridge.
//! 3) declare a new struct for the added bridge and implement the `Full2WayBridge` trait for it.
#[macro_use]
mod parachain_to_parachain;
#[macro_use]
mod relay_to_relay;
#[macro_use]
mod relay_to_parachain;
use async_trait::async_trait;
use std::{marker::PhantomData, sync::Arc};
use structopt::StructOpt;
use futures::{FutureExt, TryFutureExt};
use relay_to_parachain::*;
use relay_to_relay::*;
use crate::{
chains::{
millau_headers_to_rialto::MillauToRialtoCliBridge,
millau_headers_to_rialto_parachain::MillauToRialtoParachainCliBridge,
rialto_headers_to_millau::RialtoToMillauCliBridge,
rialto_parachains_to_millau::RialtoParachainToMillauCliBridge,
rococo_parachains_to_bridge_hub_wococo::BridgeHubRococoToBridgeHubWococoCliBridge,
wococo_parachains_to_bridge_hub_rococo::BridgeHubWococoToBridgeHubRococoCliBridge,
},
cli::{
bridge::{
CliBridgeBase, MessagesCliBridge, ParachainToRelayHeadersCliBridge,
RelayToRelayHeadersCliBridge,
},
chain_schema::*,
relay_headers_and_messages::parachain_to_parachain::ParachainToParachainBridge,
CliChain, HexLaneId, PrometheusParams,
},
declare_chain_cli_schema,
};
use bp_messages::LaneId;
use bp_runtime::{BalanceOf, BlockNumberOf};
use relay_substrate_client::{
AccountIdOf, AccountKeyPairOf, Chain, ChainWithBalances, ChainWithTransactions, Client,
};
use relay_utils::metrics::MetricsParams;
use sp_core::Pair;
use substrate_relay_helper::{
messages_lane::MessagesRelayParams, on_demand::OnDemandRelay, TaggedAccount, TransactionParams,
};
/// Parameters that have the same names across all bridges.
#[derive(Debug, PartialEq, StructOpt)]
pub struct HeadersAndMessagesSharedParams {
/// Hex-encoded lane identifiers that should be served by the complex relay.
#[structopt(long, default_value = "00000000")]
pub lane: Vec<HexLaneId>,
/// If passed, only mandatory headers (headers that are changing the GRANDPA authorities set)
/// are relayed.
#[structopt(long)]
pub only_mandatory_headers: bool,
#[structopt(flatten)]
pub prometheus_params: PrometheusParams,
}
/// Bridge parameters, shared by all bridge types.
pub struct Full2WayBridgeCommonParams<
Left: ChainWithTransactions + CliChain,
Right: ChainWithTransactions + CliChain,
> {
/// Shared parameters.
pub shared: HeadersAndMessagesSharedParams,
/// Parameters of the left chain.
pub left: BridgeEndCommonParams<Left>,
/// Parameters of the right chain.
pub right: BridgeEndCommonParams<Right>,
/// Common metric parameters.
pub metrics_params: MetricsParams,
}
impl<Left: ChainWithTransactions + CliChain, Right: ChainWithTransactions + CliChain>
Full2WayBridgeCommonParams<Left, Right>
{
/// Creates new bridge parameters from its components.
pub fn new<L2R: MessagesCliBridge<Source = Left, Target = Right>>(
shared: HeadersAndMessagesSharedParams,
left: BridgeEndCommonParams<Left>,
right: BridgeEndCommonParams<Right>,
) -> anyhow::Result<Self> {
// Create metrics registry.
let metrics_params = shared.prometheus_params.clone().into();
let metrics_params = relay_utils::relay_metrics(metrics_params).into_params();
Ok(Self { shared, left, right, metrics_params })
}
}
/// Parameters that are associated with one side of the bridge.
pub struct BridgeEndCommonParams<Chain: ChainWithTransactions + CliChain> {
/// Chain client.
pub client: Client<Chain>,
/// Transactions signer.
pub sign: AccountKeyPairOf<Chain>,
/// Transactions mortality.
pub transactions_mortality: Option<u32>,
/// Account that "owns" messages pallet.
pub messages_pallet_owner: Option<AccountKeyPairOf<Chain>>,
/// Accounts, which balances are exposed as metrics by the relay process.
pub accounts: Vec<TaggedAccount<AccountIdOf<Chain>>>,
}
/// All data of the bidirectional complex relay.
struct FullBridge<
'a,
Source: ChainWithTransactions + CliChain,
Target: ChainWithTransactions + CliChain,
Bridge: MessagesCliBridge<Source = Source, Target = Target>,
> {
source: &'a mut BridgeEndCommonParams<Source>,
target: &'a mut BridgeEndCommonParams<Target>,
metrics_params: &'a MetricsParams,
_phantom_data: PhantomData<Bridge>,
}
impl<
'a,
Source: ChainWithTransactions + CliChain,
Target: ChainWithTransactions + CliChain,
Bridge: MessagesCliBridge<Source = Source, Target = Target>,
> FullBridge<'a, Source, Target, Bridge>
where
AccountIdOf<Source>: From<<AccountKeyPairOf<Source> as Pair>::Public>,
AccountIdOf<Target>: From<<AccountKeyPairOf<Target> as Pair>::Public>,
BalanceOf<Source>: TryFrom<BalanceOf<Target>> + Into<u128>,
{
/// Construct complex relay given it components.
fn new(
source: &'a mut BridgeEndCommonParams<Source>,
target: &'a mut BridgeEndCommonParams<Target>,
metrics_params: &'a MetricsParams,
) -> Self {
Self { source, target, metrics_params, _phantom_data: Default::default() }
}
/// Returns message relay parameters.
fn messages_relay_params(
&self,
source_to_target_headers_relay: Arc<dyn OnDemandRelay<BlockNumberOf<Source>>>,
target_to_source_headers_relay: Arc<dyn OnDemandRelay<BlockNumberOf<Target>>>,
lane_id: LaneId,
) -> MessagesRelayParams<Bridge::MessagesLane> {
MessagesRelayParams {
source_client: self.source.client.clone(),
source_transaction_params: TransactionParams {
signer: self.source.sign.clone(),
mortality: self.source.transactions_mortality,
},
target_client: self.target.client.clone(),
target_transaction_params: TransactionParams {
signer: self.target.sign.clone(),
mortality: self.target.transactions_mortality,
},
source_to_target_headers_relay: Some(source_to_target_headers_relay),
target_to_source_headers_relay: Some(target_to_source_headers_relay),
lane_id,
metrics_params: self.metrics_params.clone().disable(),
}
}
}
// All supported chains.
declare_chain_cli_schema!(Millau, millau);
declare_chain_cli_schema!(Rialto, rialto);
declare_chain_cli_schema!(RialtoParachain, rialto_parachain);
declare_chain_cli_schema!(Rococo, rococo);
declare_chain_cli_schema!(BridgeHubRococo, bridge_hub_rococo);
declare_chain_cli_schema!(Wococo, wococo);
declare_chain_cli_schema!(BridgeHubWococo, bridge_hub_wococo);
// Means to override signers of different layer transactions.
declare_chain_cli_schema!(MillauHeadersToRialto, millau_headers_to_rialto);
declare_chain_cli_schema!(MillauHeadersToRialtoParachain, millau_headers_to_rialto_parachain);
declare_chain_cli_schema!(RialtoHeadersToMillau, rialto_headers_to_millau);
declare_chain_cli_schema!(RialtoParachainsToMillau, rialto_parachains_to_millau);
declare_chain_cli_schema!(RococoHeadersToBridgeHubWococo, rococo_headers_to_bridge_hub_wococo);
declare_chain_cli_schema!(
RococoParachainsToBridgeHubWococo,
rococo_parachains_to_bridge_hub_wococo
);
declare_chain_cli_schema!(WococoHeadersToBridgeHubRococo, wococo_headers_to_bridge_hub_rococo);
declare_chain_cli_schema!(
WococoParachainsToBridgeHubRococo,
wococo_parachains_to_bridge_hub_rococo
);
// All supported bridges.
declare_relay_to_relay_bridge_schema!(Millau, Rialto);
declare_relay_to_parachain_bridge_schema!(Millau, RialtoParachain, Rialto);
declare_parachain_to_parachain_bridge_schema!(BridgeHubRococo, Rococo, BridgeHubWococo, Wococo);
/// Base portion of the bidirectional complex relay.
///
/// This main purpose of extracting this trait is that in different relays the implementation
/// of `start_on_demand_headers_relayers` method will be different. But the number of
/// implementations is limited to relay <> relay, parachain <> relay and parachain <> parachain.
/// This trait allows us to reuse these implementations in different bridges.
#[async_trait]
trait Full2WayBridgeBase: Sized + Send + Sync {
/// The CLI params for the bridge.
type Params;
/// The left relay chain.
type Left: ChainWithTransactions + CliChain<KeyPair = AccountKeyPairOf<Self::Left>>;
/// The right destination chain (it can be a relay or a parachain).
type Right: ChainWithTransactions + CliChain<KeyPair = AccountKeyPairOf<Self::Right>>;
/// Reference to common relay parameters.
fn common(&self) -> &Full2WayBridgeCommonParams<Self::Left, Self::Right>;
/// Mutable reference to common relay parameters.
fn mut_common(&mut self) -> &mut Full2WayBridgeCommonParams<Self::Left, Self::Right>;
/// Start on-demand headers relays.
async fn start_on_demand_headers_relayers(
&mut self,
) -> anyhow::Result<(
Arc<dyn OnDemandRelay<BlockNumberOf<Self::Left>>>,
Arc<dyn OnDemandRelay<BlockNumberOf<Self::Right>>>,
)>;
}
/// Bidirectional complex relay.
#[async_trait]
trait Full2WayBridge: Sized + Sync
where
AccountIdOf<Self::Left>: From<<AccountKeyPairOf<Self::Left> as Pair>::Public>,
AccountIdOf<Self::Right>: From<<AccountKeyPairOf<Self::Right> as Pair>::Public>,
BalanceOf<Self::Left>: TryFrom<BalanceOf<Self::Right>> + Into<u128>,
BalanceOf<Self::Right>: TryFrom<BalanceOf<Self::Left>> + Into<u128>,
{
/// Base portion of the bidirectional complex relay.
type Base: Full2WayBridgeBase<Left = Self::Left, Right = Self::Right>;
/// The left relay chain.
type Left: ChainWithTransactions
+ ChainWithBalances
+ CliChain<KeyPair = AccountKeyPairOf<Self::Left>>;
/// The right relay chain.
type Right: ChainWithTransactions
+ ChainWithBalances
+ CliChain<KeyPair = AccountKeyPairOf<Self::Right>>;
/// Left to Right bridge.
type L2R: MessagesCliBridge<Source = Self::Left, Target = Self::Right>;
/// Right to Left bridge
type R2L: MessagesCliBridge<Source = Self::Right, Target = Self::Left>;
/// Construct new bridge.
fn new(params: <Self::Base as Full2WayBridgeBase>::Params) -> anyhow::Result<Self>;
/// Reference to the base relay portion.
fn base(&self) -> &Self::Base;
/// Mutable reference to the base relay portion.
fn mut_base(&mut self) -> &mut Self::Base;
/// Creates and returns Left to Right complex relay.
fn left_to_right(&mut self) -> FullBridge<Self::Left, Self::Right, Self::L2R> {
let common = self.mut_base().mut_common();
FullBridge::<_, _, Self::L2R>::new(
&mut common.left,
&mut common.right,
&common.metrics_params,
)
}
/// Creates and returns Right to Left complex relay.
fn right_to_left(&mut self) -> FullBridge<Self::Right, Self::Left, Self::R2L> {
let common = self.mut_base().mut_common();
FullBridge::<_, _, Self::R2L>::new(
&mut common.right,
&mut common.left,
&common.metrics_params,
)
}
/// Start complex relay.
async fn run(&mut self) -> anyhow::Result<()> {
// Register standalone metrics.
{
let common = self.mut_base().mut_common();
common.left.accounts.push(TaggedAccount::Messages {
id: common.left.sign.public().into(),
bridged_chain: Self::Right::NAME.to_string(),
});
common.right.accounts.push(TaggedAccount::Messages {
id: common.right.sign.public().into(),
bridged_chain: Self::Left::NAME.to_string(),
});
}
// start on-demand header relays
let (left_to_right_on_demand_headers, right_to_left_on_demand_headers) =
self.mut_base().start_on_demand_headers_relayers().await?;
// add balance-related metrics
{
let common = self.mut_base().mut_common();
substrate_relay_helper::messages_metrics::add_relay_balances_metrics(
common.left.client.clone(),
&mut common.metrics_params,
&common.left.accounts,
)
.await?;
substrate_relay_helper::messages_metrics::add_relay_balances_metrics(
common.right.client.clone(),
&mut common.metrics_params,
&common.right.accounts,
)
.await?;
}
let lanes = self.base().common().shared.lane.clone();
// Need 2x capacity since we consider both directions for each lane
let mut message_relays = Vec::with_capacity(lanes.len() * 2);
for lane in lanes {
let lane = lane.into();
let left_to_right_messages = substrate_relay_helper::messages_lane::run::<
<Self::L2R as MessagesCliBridge>::MessagesLane,
>(self.left_to_right().messages_relay_params(
left_to_right_on_demand_headers.clone(),
right_to_left_on_demand_headers.clone(),
lane,
))
.map_err(|e| anyhow::format_err!("{}", e))
.boxed();
message_relays.push(left_to_right_messages);
let right_to_left_messages = substrate_relay_helper::messages_lane::run::<
<Self::R2L as MessagesCliBridge>::MessagesLane,
>(self.right_to_left().messages_relay_params(
right_to_left_on_demand_headers.clone(),
left_to_right_on_demand_headers.clone(),
lane,
))
.map_err(|e| anyhow::format_err!("{}", e))
.boxed();
message_relays.push(right_to_left_messages);
}
relay_utils::relay_metrics(self.base().common().metrics_params.clone())
.expose()
.await
.map_err(|e| anyhow::format_err!("{}", e))?;
futures::future::select_all(message_relays).await.0
}
}
/// Millau <> Rialto complex relay.
pub struct MillauRialtoFull2WayBridge {
base: <Self as Full2WayBridge>::Base,
}
#[async_trait]
impl Full2WayBridge for MillauRialtoFull2WayBridge {
type Base = RelayToRelayBridge<Self::L2R, Self::R2L>;
type Left = relay_millau_client::Millau;
type Right = relay_rialto_client::Rialto;
type L2R = MillauToRialtoCliBridge;
type R2L = RialtoToMillauCliBridge;
fn new(base: Self::Base) -> anyhow::Result<Self> {
Ok(Self { base })
}
fn base(&self) -> &Self::Base {
&self.base
}
fn mut_base(&mut self) -> &mut Self::Base {
&mut self.base
}
}
/// Millau <> RialtoParachain complex relay.
pub struct MillauRialtoParachainFull2WayBridge {
base: <Self as Full2WayBridge>::Base,
}
#[async_trait]
impl Full2WayBridge for MillauRialtoParachainFull2WayBridge {
type Base = RelayToParachainBridge<Self::L2R, Self::R2L>;
type Left = relay_millau_client::Millau;
type Right = relay_rialto_parachain_client::RialtoParachain;
type L2R = MillauToRialtoParachainCliBridge;
type R2L = RialtoParachainToMillauCliBridge;
fn new(base: Self::Base) -> anyhow::Result<Self> {
Ok(Self { base })
}
fn base(&self) -> &Self::Base {
&self.base
}
fn mut_base(&mut self) -> &mut Self::Base {
&mut self.base
}
}
/// BridgeHubRococo <> BridgeHubWococo complex relay.
pub struct BridgeHubRococoBridgeHubWococoFull2WayBridge {
base: <Self as Full2WayBridge>::Base,
}
#[async_trait]
impl Full2WayBridge for BridgeHubRococoBridgeHubWococoFull2WayBridge {
type Base = ParachainToParachainBridge<Self::L2R, Self::R2L>;
type Left = relay_bridge_hub_rococo_client::BridgeHubRococo;
type Right = relay_bridge_hub_wococo_client::BridgeHubWococo;
type L2R = BridgeHubRococoToBridgeHubWococoCliBridge;
type R2L = BridgeHubWococoToBridgeHubRococoCliBridge;
fn new(base: Self::Base) -> anyhow::Result<Self> {
Ok(Self { base })
}
fn base(&self) -> &Self::Base {
&self.base
}
fn mut_base(&mut self) -> &mut Self::Base {
&mut self.base
}
}
/// Complex headers+messages relay.
#[derive(Debug, PartialEq, StructOpt)]
pub enum RelayHeadersAndMessages {
/// Millau <> Rialto relay.
MillauRialto(MillauRialtoHeadersAndMessages),
/// Millau <> RialtoParachain relay.
MillauRialtoParachain(MillauRialtoParachainHeadersAndMessages),
/// BridgeHubRococo <> BridgeHubWococo relay.
BridgeHubRococoBridgeHubWococo(BridgeHubRococoBridgeHubWococoHeadersAndMessages),
}
impl RelayHeadersAndMessages {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
match self {
RelayHeadersAndMessages::MillauRialto(params) =>
MillauRialtoFull2WayBridge::new(params.into_bridge().await?)?.run().await,
RelayHeadersAndMessages::MillauRialtoParachain(params) =>
MillauRialtoParachainFull2WayBridge::new(params.into_bridge().await?)?
.run()
.await,
RelayHeadersAndMessages::BridgeHubRococoBridgeHubWococo(params) =>
BridgeHubRococoBridgeHubWococoFull2WayBridge::new(params.into_bridge().await?)?
.run()
.await,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_parse_relay_to_relay_options() {
// when
let res = RelayHeadersAndMessages::from_iter(vec![
"relay-headers-and-messages",
"millau-rialto",
"--millau-host",
"millau-node-alice",
"--millau-port",
"9944",
"--millau-signer",
"//Charlie",
"--millau-messages-pallet-owner",
"//RialtoMessagesOwner",
"--millau-transactions-mortality",
"64",
"--rialto-host",
"rialto-node-alice",
"--rialto-port",
"9944",
"--rialto-signer",
"//Charlie",
"--rialto-messages-pallet-owner",
"//MillauMessagesOwner",
"--rialto-transactions-mortality",
"64",
"--lane",
"00000000",
"--lane",
"73776170",
"--prometheus-host",
"0.0.0.0",
]);
// then
assert_eq!(
res,
RelayHeadersAndMessages::MillauRialto(MillauRialtoHeadersAndMessages {
shared: HeadersAndMessagesSharedParams {
lane: vec![
HexLaneId([0x00, 0x00, 0x00, 0x00]),
HexLaneId([0x73, 0x77, 0x61, 0x70])
],
only_mandatory_headers: false,
prometheus_params: PrometheusParams {
no_prometheus: false,
prometheus_host: "0.0.0.0".into(),
prometheus_port: 9616,
},
},
left: MillauConnectionParams {
millau_host: "millau-node-alice".into(),
millau_port: 9944,
millau_secure: false,
millau_runtime_version: MillauRuntimeVersionParams {
millau_version_mode: RuntimeVersionType::Bundle,
millau_spec_version: None,
millau_transaction_version: None,
},
},
left_sign: MillauSigningParams {
millau_signer: Some("//Charlie".into()),
millau_signer_password: None,
millau_signer_file: None,
millau_signer_password_file: None,
millau_transactions_mortality: Some(64),
},
left_messages_pallet_owner: MillauMessagesPalletOwnerSigningParams {
millau_messages_pallet_owner: Some("//RialtoMessagesOwner".into()),
millau_messages_pallet_owner_password: None,
},
left_headers_to_right_sign_override: MillauHeadersToRialtoSigningParams {
millau_headers_to_rialto_signer: None,
millau_headers_to_rialto_signer_password: None,
millau_headers_to_rialto_signer_file: None,
millau_headers_to_rialto_signer_password_file: None,
millau_headers_to_rialto_transactions_mortality: None,
},
right: RialtoConnectionParams {
rialto_host: "rialto-node-alice".into(),
rialto_port: 9944,
rialto_secure: false,
rialto_runtime_version: RialtoRuntimeVersionParams {
rialto_version_mode: RuntimeVersionType::Bundle,
rialto_spec_version: None,
rialto_transaction_version: None,
},
},
right_sign: RialtoSigningParams {
rialto_signer: Some("//Charlie".into()),
rialto_signer_password: None,
rialto_signer_file: None,
rialto_signer_password_file: None,
rialto_transactions_mortality: Some(64),
},
right_messages_pallet_owner: RialtoMessagesPalletOwnerSigningParams {
rialto_messages_pallet_owner: Some("//MillauMessagesOwner".into()),
rialto_messages_pallet_owner_password: None,
},
right_headers_to_left_sign_override: RialtoHeadersToMillauSigningParams {
rialto_headers_to_millau_signer: None,
rialto_headers_to_millau_signer_password: None,
rialto_headers_to_millau_signer_file: None,
rialto_headers_to_millau_signer_password_file: None,
rialto_headers_to_millau_transactions_mortality: None,
},
}),
);
}
#[test]
fn should_parse_relay_to_parachain_options() {
// when
let res = RelayHeadersAndMessages::from_iter(vec![
"relay-headers-and-messages",
"millau-rialto-parachain",
"--millau-host",
"millau-node-alice",
"--millau-port",
"9944",
"--millau-signer",
"//Iden",
"--rialto-headers-to-millau-signer",
"//Ken",
"--millau-messages-pallet-owner",
"//RialtoParachainMessagesOwner",
"--millau-transactions-mortality",
"64",
"--rialto-parachain-host",
"rialto-parachain-collator-charlie",
"--rialto-parachain-port",
"9944",
"--rialto-parachain-signer",
"//George",
"--rialto-parachain-messages-pallet-owner",
"//MillauMessagesOwner",
"--rialto-parachain-transactions-mortality",
"64",
"--rialto-host",
"rialto-node-alice",
"--rialto-port",
"9944",
"--lane",
"00000000",
"--prometheus-host",
"0.0.0.0",
]);
// then
assert_eq!(
res,
RelayHeadersAndMessages::MillauRialtoParachain(
MillauRialtoParachainHeadersAndMessages {
shared: HeadersAndMessagesSharedParams {
lane: vec![HexLaneId([0x00, 0x00, 0x00, 0x00])],
only_mandatory_headers: false,
prometheus_params: PrometheusParams {
no_prometheus: false,
prometheus_host: "0.0.0.0".into(),
prometheus_port: 9616,
},
},
left: MillauConnectionParams {
millau_host: "millau-node-alice".into(),
millau_port: 9944,
millau_secure: false,
millau_runtime_version: MillauRuntimeVersionParams {
millau_version_mode: RuntimeVersionType::Bundle,
millau_spec_version: None,
millau_transaction_version: None,
},
},
left_sign: MillauSigningParams {
millau_signer: Some("//Iden".into()),
millau_signer_password: None,
millau_signer_file: None,
millau_signer_password_file: None,
millau_transactions_mortality: Some(64),
},
left_messages_pallet_owner: MillauMessagesPalletOwnerSigningParams {
millau_messages_pallet_owner: Some("//RialtoParachainMessagesOwner".into()),
millau_messages_pallet_owner_password: None,
},
left_headers_to_right_sign_override:
MillauHeadersToRialtoParachainSigningParams {
millau_headers_to_rialto_parachain_signer: None,
millau_headers_to_rialto_parachain_signer_password: None,
millau_headers_to_rialto_parachain_signer_file: None,
millau_headers_to_rialto_parachain_signer_password_file: None,
millau_headers_to_rialto_parachain_transactions_mortality: None,
},
right: RialtoParachainConnectionParams {
rialto_parachain_host: "rialto-parachain-collator-charlie".into(),
rialto_parachain_port: 9944,
rialto_parachain_secure: false,
rialto_parachain_runtime_version: RialtoParachainRuntimeVersionParams {
rialto_parachain_version_mode: RuntimeVersionType::Bundle,
rialto_parachain_spec_version: None,
rialto_parachain_transaction_version: None,
},
},
right_sign: RialtoParachainSigningParams {
rialto_parachain_signer: Some("//George".into()),
rialto_parachain_signer_password: None,
rialto_parachain_signer_file: None,
rialto_parachain_signer_password_file: None,
rialto_parachain_transactions_mortality: Some(64),
},
right_messages_pallet_owner: RialtoParachainMessagesPalletOwnerSigningParams {
rialto_parachain_messages_pallet_owner: Some(
"//MillauMessagesOwner".into()
),
rialto_parachain_messages_pallet_owner_password: None,
},
right_relay_headers_to_left_sign_override: RialtoHeadersToMillauSigningParams {
rialto_headers_to_millau_signer: Some("//Ken".into()),
rialto_headers_to_millau_signer_password: None,
rialto_headers_to_millau_signer_file: None,
rialto_headers_to_millau_signer_password_file: None,
rialto_headers_to_millau_transactions_mortality: None,
},
right_parachains_to_left_sign_override: RialtoParachainsToMillauSigningParams {
rialto_parachains_to_millau_signer: None,
rialto_parachains_to_millau_signer_password: None,
rialto_parachains_to_millau_signer_file: None,
rialto_parachains_to_millau_signer_password_file: None,
rialto_parachains_to_millau_transactions_mortality: None,
},
right_relay: RialtoConnectionParams {
rialto_host: "rialto-node-alice".into(),
rialto_port: 9944,
rialto_secure: false,
rialto_runtime_version: RialtoRuntimeVersionParams {
rialto_version_mode: RuntimeVersionType::Bundle,
rialto_spec_version: None,
rialto_transaction_version: None,
},
},
}
),
);
}
}
@@ -0,0 +1,281 @@
// Copyright 2019-2022 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/>.
#![allow(unused_macros)] // TODO (https://github.com/paritytech/parity-bridges-common/issues/1629): remove me
use async_trait::async_trait;
use std::sync::Arc;
use crate::cli::{
bridge::{CliBridgeBase, MessagesCliBridge, ParachainToRelayHeadersCliBridge},
relay_headers_and_messages::{Full2WayBridgeBase, Full2WayBridgeCommonParams},
CliChain,
};
use bp_polkadot_core::parachains::ParaHash;
use bp_runtime::BlockNumberOf;
use pallet_bridge_parachains::{RelayBlockHash, RelayBlockHasher, RelayBlockNumber};
use relay_substrate_client::{AccountIdOf, AccountKeyPairOf, Chain, ChainWithTransactions, Client};
use sp_core::Pair;
use substrate_relay_helper::{
finality::SubstrateFinalitySyncPipeline,
on_demand::{
headers::OnDemandHeadersRelay, parachains::OnDemandParachainsRelay, OnDemandRelay,
},
TaggedAccount, TransactionParams,
};
/// A base relay between two parachain from different consensus systems.
///
/// Such relay starts 2 messages relay. It also starts 2 on-demand header relays and 2 on-demand
/// parachain heads relay.
pub struct ParachainToParachainBridge<
L2R: MessagesCliBridge + ParachainToRelayHeadersCliBridge,
R2L: MessagesCliBridge + ParachainToRelayHeadersCliBridge,
> {
/// Parameters that are shared by all bridge types.
pub common:
Full2WayBridgeCommonParams<<R2L as CliBridgeBase>::Target, <L2R as CliBridgeBase>::Target>,
/// Client of the left relay chain.
pub left_relay: Client<<L2R as ParachainToRelayHeadersCliBridge>::SourceRelay>,
/// Client of the right relay chain.
pub right_relay: Client<<R2L as ParachainToRelayHeadersCliBridge>::SourceRelay>,
/// Override for right_relay->left headers signer.
pub right_headers_to_left_transaction_params:
TransactionParams<AccountKeyPairOf<<R2L as CliBridgeBase>::Target>>,
/// Override for left_relay->right headers signer.
pub left_headers_to_right_transaction_params:
TransactionParams<AccountKeyPairOf<<L2R as CliBridgeBase>::Target>>,
/// Override for right->left parachains signer.
pub right_parachains_to_left_transaction_params:
TransactionParams<AccountKeyPairOf<<R2L as CliBridgeBase>::Target>>,
/// Override for left->right parachains signer.
pub left_parachains_to_right_transaction_params:
TransactionParams<AccountKeyPairOf<<L2R as CliBridgeBase>::Target>>,
}
macro_rules! declare_parachain_to_parachain_bridge_schema {
// left-parachain, relay-chain-of-left-parachain, right-parachain, relay-chain-of-right-parachain
($left_parachain:ident, $left_chain:ident, $right_parachain:ident, $right_chain:ident) => {
bp_runtime::paste::item! {
#[doc = $left_parachain ", " $left_chain ", " $right_parachain " and " $right_chain " headers+parachains+messages relay params."]
#[derive(Debug, PartialEq, StructOpt)]
pub struct [<$left_parachain $right_parachain HeadersAndMessages>] {
// shared parameters
#[structopt(flatten)]
shared: HeadersAndMessagesSharedParams,
#[structopt(flatten)]
left: [<$left_parachain ConnectionParams>],
#[structopt(flatten)]
left_relay: [<$left_chain ConnectionParams>],
// default signer, which is always used to sign messages relay transactions on the left chain
#[structopt(flatten)]
left_sign: [<$left_parachain SigningParams>],
// signer used to sign parameter update transactions at the left parachain
#[structopt(flatten)]
left_messages_pallet_owner: [<$left_parachain MessagesPalletOwnerSigningParams>],
#[structopt(flatten)]
right: [<$right_parachain ConnectionParams>],
#[structopt(flatten)]
right_relay: [<$right_chain ConnectionParams>],
// default signer, which is always used to sign messages relay transactions on the right chain
#[structopt(flatten)]
right_sign: [<$right_parachain SigningParams>],
// signer used to sign parameter update transactions at the right parachain
#[structopt(flatten)]
right_messages_pallet_owner: [<$right_parachain MessagesPalletOwnerSigningParams>],
// override for right_relay->left-parachain headers signer
#[structopt(flatten)]
right_relay_headers_to_left_sign_override: [<$right_chain HeadersTo $left_parachain SigningParams>],
// override for left_relay->right-parachain headers signer
#[structopt(flatten)]
left_relay_headers_to_right_sign_override: [<$left_chain HeadersTo $right_parachain SigningParams>],
// override for right->left parachains signer
#[structopt(flatten)]
right_parachains_to_left_sign_override: [<$right_chain ParachainsTo $left_parachain SigningParams>],
// override for left->right parachains signer
#[structopt(flatten)]
left_parachains_to_right_sign_override: [<$left_chain ParachainsTo $right_parachain SigningParams>],
}
impl [<$left_parachain $right_parachain HeadersAndMessages>] {
async fn into_bridge<
Left: ChainWithTransactions + CliChain<KeyPair = AccountKeyPairOf<Left>>,
LeftRelay: CliChain,
Right: ChainWithTransactions + CliChain<KeyPair = AccountKeyPairOf<Right>>,
RightRelay: CliChain,
L2R: CliBridgeBase<Source = Left, Target = Right>
+ MessagesCliBridge
+ ParachainToRelayHeadersCliBridge<SourceRelay = LeftRelay>,
R2L: CliBridgeBase<Source = Right, Target = Left>
+ MessagesCliBridge
+ ParachainToRelayHeadersCliBridge<SourceRelay = RightRelay>,
>(
self,
) -> anyhow::Result<ParachainToParachainBridge<L2R, R2L>> {
Ok(ParachainToParachainBridge {
common: Full2WayBridgeCommonParams::new::<L2R>(
self.shared,
BridgeEndCommonParams {
client: self.left.into_client::<Left>().await?,
sign: self.left_sign.to_keypair::<Left>()?,
transactions_mortality: self.left_sign.transactions_mortality()?,
messages_pallet_owner: self.left_messages_pallet_owner.to_keypair::<Left>()?,
accounts: vec![],
},
BridgeEndCommonParams {
client: self.right.into_client::<Right>().await?,
sign: self.right_sign.to_keypair::<Right>()?,
transactions_mortality: self.right_sign.transactions_mortality()?,
messages_pallet_owner: self.right_messages_pallet_owner.to_keypair::<Right>()?,
accounts: vec![],
},
)?,
left_relay: self.left_relay.into_client::<LeftRelay>().await?,
right_relay: self.right_relay.into_client::<RightRelay>().await?,
right_headers_to_left_transaction_params: self
.right_relay_headers_to_left_sign_override
.transaction_params_or::<Left, _>(&self.left_sign)?,
left_headers_to_right_transaction_params: self
.left_relay_headers_to_right_sign_override
.transaction_params_or::<Right, _>(&self.right_sign)?,
right_parachains_to_left_transaction_params: self
.right_parachains_to_left_sign_override
.transaction_params_or::<Left, _>(&self.left_sign)?,
left_parachains_to_right_transaction_params: self
.left_parachains_to_right_sign_override
.transaction_params_or::<Right, _>(&self.right_sign)?,
})
}
}
}
};
}
#[async_trait]
impl<
Left: Chain<Hash = ParaHash> + ChainWithTransactions + CliChain<KeyPair = AccountKeyPairOf<Left>>,
Right: Chain<Hash = ParaHash>
+ ChainWithTransactions
+ CliChain<KeyPair = AccountKeyPairOf<Right>>,
LeftRelay: Chain<BlockNumber = RelayBlockNumber, Hash = RelayBlockHash, Hasher = RelayBlockHasher>
+ CliChain,
RightRelay: Chain<BlockNumber = RelayBlockNumber, Hash = RelayBlockHash, Hasher = RelayBlockHasher>
+ CliChain,
L2R: CliBridgeBase<Source = Left, Target = Right>
+ MessagesCliBridge
+ ParachainToRelayHeadersCliBridge<SourceRelay = LeftRelay>,
R2L: CliBridgeBase<Source = Right, Target = Left>
+ MessagesCliBridge
+ ParachainToRelayHeadersCliBridge<SourceRelay = RightRelay>,
> Full2WayBridgeBase for ParachainToParachainBridge<L2R, R2L>
where
AccountIdOf<Left>: From<<AccountKeyPairOf<Left> as Pair>::Public>,
AccountIdOf<Right>: From<<AccountKeyPairOf<Right> as Pair>::Public>,
{
type Params = ParachainToParachainBridge<L2R, R2L>;
type Left = Left;
type Right = Right;
fn common(&self) -> &Full2WayBridgeCommonParams<Left, Right> {
&self.common
}
fn mut_common(&mut self) -> &mut Full2WayBridgeCommonParams<Self::Left, Self::Right> {
&mut self.common
}
async fn start_on_demand_headers_relayers(
&mut self,
) -> anyhow::Result<(
Arc<dyn OnDemandRelay<BlockNumberOf<Self::Left>>>,
Arc<dyn OnDemandRelay<BlockNumberOf<Self::Right>>>,
)> {
self.common.left.accounts.push(TaggedAccount::Headers {
id: self.right_headers_to_left_transaction_params.signer.public().into(),
bridged_chain: RightRelay::NAME.to_string(),
});
self.common.left.accounts.push(TaggedAccount::Parachains {
id: self.right_parachains_to_left_transaction_params.signer.public().into(),
bridged_chain: RightRelay::NAME.to_string(),
});
self.common.right.accounts.push(TaggedAccount::Headers {
id: self.left_headers_to_right_transaction_params.signer.public().into(),
bridged_chain: Left::NAME.to_string(),
});
self.common.right.accounts.push(TaggedAccount::Parachains {
id: self.left_parachains_to_right_transaction_params.signer.public().into(),
bridged_chain: LeftRelay::NAME.to_string(),
});
<L2R as ParachainToRelayHeadersCliBridge>::RelayFinality::start_relay_guards(
&self.common.right.client,
&self.left_headers_to_right_transaction_params,
self.common.right.client.can_start_version_guard(),
)
.await?;
<R2L as ParachainToRelayHeadersCliBridge>::RelayFinality::start_relay_guards(
&self.common.left.client,
&self.right_headers_to_left_transaction_params,
self.common.left.client.can_start_version_guard(),
)
.await?;
let left_relay_to_right_on_demand_headers =
OnDemandHeadersRelay::new::<<L2R as ParachainToRelayHeadersCliBridge>::RelayFinality>(
self.left_relay.clone(),
self.common.right.client.clone(),
self.left_headers_to_right_transaction_params.clone(),
self.common.shared.only_mandatory_headers,
);
let right_relay_to_left_on_demand_headers =
OnDemandHeadersRelay::new::<<R2L as ParachainToRelayHeadersCliBridge>::RelayFinality>(
self.right_relay.clone(),
self.common.left.client.clone(),
self.right_headers_to_left_transaction_params.clone(),
self.common.shared.only_mandatory_headers,
);
let left_to_right_on_demand_parachains = OnDemandParachainsRelay::new::<
<L2R as ParachainToRelayHeadersCliBridge>::ParachainFinality,
>(
self.left_relay.clone(),
self.common.right.client.clone(),
self.left_parachains_to_right_transaction_params.clone(),
Arc::new(left_relay_to_right_on_demand_headers),
);
let right_to_left_on_demand_parachains = OnDemandParachainsRelay::new::<
<R2L as ParachainToRelayHeadersCliBridge>::ParachainFinality,
>(
self.right_relay.clone(),
self.common.left.client.clone(),
self.right_parachains_to_left_transaction_params.clone(),
Arc::new(right_relay_to_left_on_demand_headers),
);
Ok((
Arc::new(left_to_right_on_demand_parachains),
Arc::new(right_to_left_on_demand_parachains),
))
}
}
@@ -0,0 +1,254 @@
// Copyright 2019-2022 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 async_trait::async_trait;
use std::sync::Arc;
use crate::cli::{
bridge::{
CliBridgeBase, MessagesCliBridge, ParachainToRelayHeadersCliBridge,
RelayToRelayHeadersCliBridge,
},
relay_headers_and_messages::{Full2WayBridgeBase, Full2WayBridgeCommonParams},
CliChain,
};
use bp_polkadot_core::parachains::ParaHash;
use bp_runtime::BlockNumberOf;
use pallet_bridge_parachains::{RelayBlockHash, RelayBlockHasher, RelayBlockNumber};
use relay_substrate_client::{AccountIdOf, AccountKeyPairOf, Chain, ChainWithTransactions, Client};
use sp_core::Pair;
use substrate_relay_helper::{
finality::SubstrateFinalitySyncPipeline,
on_demand::{
headers::OnDemandHeadersRelay, parachains::OnDemandParachainsRelay, OnDemandRelay,
},
TaggedAccount, TransactionParams,
};
/// A base relay between standalone (relay) chain and a parachain from another consensus system.
///
/// Such relay starts 2 messages relay. It also starts 2 on-demand header relays and 1 on-demand
/// parachain heads relay.
pub struct RelayToParachainBridge<
L2R: MessagesCliBridge + RelayToRelayHeadersCliBridge,
R2L: MessagesCliBridge + ParachainToRelayHeadersCliBridge,
> {
/// Parameters that are shared by all bridge types.
pub common:
Full2WayBridgeCommonParams<<R2L as CliBridgeBase>::Target, <L2R as CliBridgeBase>::Target>,
/// Client of the right relay chain.
pub right_relay: Client<<R2L as ParachainToRelayHeadersCliBridge>::SourceRelay>,
/// Override for right_relay->left headers signer.
pub right_headers_to_left_transaction_params:
TransactionParams<AccountKeyPairOf<<R2L as CliBridgeBase>::Target>>,
/// Override for right->left parachains signer.
pub right_parachains_to_left_transaction_params:
TransactionParams<AccountKeyPairOf<<R2L as CliBridgeBase>::Target>>,
/// Override for left->right headers signer.
pub left_headers_to_right_transaction_params:
TransactionParams<AccountKeyPairOf<<L2R as CliBridgeBase>::Target>>,
}
macro_rules! declare_relay_to_parachain_bridge_schema {
// chain, parachain, relay-chain-of-parachain
($left_chain:ident, $right_parachain:ident, $right_chain:ident) => {
bp_runtime::paste::item! {
#[doc = $left_chain ", " $right_parachain " and " $right_chain " headers+parachains+messages relay params."]
#[derive(Debug, PartialEq, StructOpt)]
pub struct [<$left_chain $right_parachain HeadersAndMessages>] {
// shared parameters
#[structopt(flatten)]
shared: HeadersAndMessagesSharedParams,
#[structopt(flatten)]
left: [<$left_chain ConnectionParams>],
// default signer, which is always used to sign messages relay transactions on the left chain
#[structopt(flatten)]
left_sign: [<$left_chain SigningParams>],
// signer used to sign parameter update transactions at the left chain
#[structopt(flatten)]
left_messages_pallet_owner: [<$left_chain MessagesPalletOwnerSigningParams>],
#[structopt(flatten)]
right: [<$right_parachain ConnectionParams>],
#[structopt(flatten)]
right_relay: [<$right_chain ConnectionParams>],
// default signer, which is always used to sign messages relay transactions on the right chain
#[structopt(flatten)]
right_sign: [<$right_parachain SigningParams>],
// signer used to sign parameter update transactions at the left chain
#[structopt(flatten)]
right_messages_pallet_owner: [<$right_parachain MessagesPalletOwnerSigningParams>],
// override for right_relay->left headers signer
#[structopt(flatten)]
right_relay_headers_to_left_sign_override: [<$right_chain HeadersTo $left_chain SigningParams>],
// override for left->right headers signer
#[structopt(flatten)]
left_headers_to_right_sign_override: [<$left_chain HeadersTo $right_parachain SigningParams>],
// override for right->left parachains signer
#[structopt(flatten)]
right_parachains_to_left_sign_override: [<$right_chain ParachainsTo $left_chain SigningParams>],
}
impl [<$left_chain $right_parachain HeadersAndMessages>] {
async fn into_bridge<
Left: ChainWithTransactions + CliChain<KeyPair = AccountKeyPairOf<Left>>,
Right: ChainWithTransactions + CliChain<KeyPair = AccountKeyPairOf<Right>>,
RightRelay: CliChain,
L2R: CliBridgeBase<Source = Left, Target = Right> + MessagesCliBridge + RelayToRelayHeadersCliBridge,
R2L: CliBridgeBase<Source = Right, Target = Left>
+ MessagesCliBridge
+ ParachainToRelayHeadersCliBridge<SourceRelay = RightRelay>,
>(
self,
) -> anyhow::Result<RelayToParachainBridge<L2R, R2L>> {
Ok(RelayToParachainBridge {
common: Full2WayBridgeCommonParams::new::<L2R>(
self.shared,
BridgeEndCommonParams {
client: self.left.into_client::<Left>().await?,
sign: self.left_sign.to_keypair::<Left>()?,
transactions_mortality: self.left_sign.transactions_mortality()?,
messages_pallet_owner: self.left_messages_pallet_owner.to_keypair::<Left>()?,
accounts: vec![],
},
BridgeEndCommonParams {
client: self.right.into_client::<Right>().await?,
sign: self.right_sign.to_keypair::<Right>()?,
transactions_mortality: self.right_sign.transactions_mortality()?,
messages_pallet_owner: self.right_messages_pallet_owner.to_keypair::<Right>()?,
accounts: vec![],
},
)?,
right_relay: self.right_relay.into_client::<RightRelay>().await?,
right_headers_to_left_transaction_params: self
.right_relay_headers_to_left_sign_override
.transaction_params_or::<Left, _>(
&self.left_sign,
)?,
right_parachains_to_left_transaction_params: self
.right_parachains_to_left_sign_override
.transaction_params_or::<Left, _>(
&self.left_sign,
)?,
left_headers_to_right_transaction_params: self
.left_headers_to_right_sign_override
.transaction_params_or::<Right, _>(&self.right_sign)?,
})
}
}
}
};
}
#[async_trait]
impl<
Left: ChainWithTransactions + CliChain<KeyPair = AccountKeyPairOf<Left>>,
Right: Chain<Hash = ParaHash>
+ ChainWithTransactions
+ CliChain<KeyPair = AccountKeyPairOf<Right>>,
RightRelay: Chain<BlockNumber = RelayBlockNumber, Hash = RelayBlockHash, Hasher = RelayBlockHasher>
+ CliChain,
L2R: CliBridgeBase<Source = Left, Target = Right>
+ MessagesCliBridge
+ RelayToRelayHeadersCliBridge,
R2L: CliBridgeBase<Source = Right, Target = Left>
+ MessagesCliBridge
+ ParachainToRelayHeadersCliBridge<SourceRelay = RightRelay>,
> Full2WayBridgeBase for RelayToParachainBridge<L2R, R2L>
where
AccountIdOf<Left>: From<<AccountKeyPairOf<Left> as Pair>::Public>,
AccountIdOf<Right>: From<<AccountKeyPairOf<Right> as Pair>::Public>,
{
type Params = RelayToParachainBridge<L2R, R2L>;
type Left = Left;
type Right = Right;
fn common(&self) -> &Full2WayBridgeCommonParams<Left, Right> {
&self.common
}
fn mut_common(&mut self) -> &mut Full2WayBridgeCommonParams<Self::Left, Self::Right> {
&mut self.common
}
async fn start_on_demand_headers_relayers(
&mut self,
) -> anyhow::Result<(
Arc<dyn OnDemandRelay<BlockNumberOf<Self::Left>>>,
Arc<dyn OnDemandRelay<BlockNumberOf<Self::Right>>>,
)> {
self.common.left.accounts.push(TaggedAccount::Headers {
id: self.right_headers_to_left_transaction_params.signer.public().into(),
bridged_chain: RightRelay::NAME.to_string(),
});
self.common.left.accounts.push(TaggedAccount::Parachains {
id: self.right_parachains_to_left_transaction_params.signer.public().into(),
bridged_chain: RightRelay::NAME.to_string(),
});
self.common.right.accounts.push(TaggedAccount::Headers {
id: self.left_headers_to_right_transaction_params.signer.public().into(),
bridged_chain: Left::NAME.to_string(),
});
<L2R as RelayToRelayHeadersCliBridge>::Finality::start_relay_guards(
&self.common.right.client,
&self.left_headers_to_right_transaction_params,
self.common.right.client.can_start_version_guard(),
)
.await?;
<R2L as ParachainToRelayHeadersCliBridge>::RelayFinality::start_relay_guards(
&self.common.left.client,
&self.right_headers_to_left_transaction_params,
self.common.left.client.can_start_version_guard(),
)
.await?;
let left_to_right_on_demand_headers =
OnDemandHeadersRelay::new::<<L2R as RelayToRelayHeadersCliBridge>::Finality>(
self.common.left.client.clone(),
self.common.right.client.clone(),
self.left_headers_to_right_transaction_params.clone(),
self.common.shared.only_mandatory_headers,
);
let right_relay_to_left_on_demand_headers =
OnDemandHeadersRelay::new::<<R2L as ParachainToRelayHeadersCliBridge>::RelayFinality>(
self.right_relay.clone(),
self.common.left.client.clone(),
self.right_headers_to_left_transaction_params.clone(),
self.common.shared.only_mandatory_headers,
);
let right_to_left_on_demand_parachains = OnDemandParachainsRelay::new::<
<R2L as ParachainToRelayHeadersCliBridge>::ParachainFinality,
>(
self.right_relay.clone(),
self.common.left.client.clone(),
self.right_parachains_to_left_transaction_params.clone(),
Arc::new(right_relay_to_left_on_demand_headers),
);
Ok((
Arc::new(left_to_right_on_demand_headers),
Arc::new(right_to_left_on_demand_parachains),
))
}
}
@@ -0,0 +1,194 @@
// Copyright 2019-2022 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 async_trait::async_trait;
use std::sync::Arc;
use crate::cli::{
bridge::{CliBridgeBase, MessagesCliBridge, RelayToRelayHeadersCliBridge},
relay_headers_and_messages::{Full2WayBridgeBase, Full2WayBridgeCommonParams},
CliChain,
};
use bp_runtime::BlockNumberOf;
use relay_substrate_client::{AccountIdOf, AccountKeyPairOf, ChainWithTransactions};
use sp_core::Pair;
use substrate_relay_helper::{
finality::SubstrateFinalitySyncPipeline,
on_demand::{headers::OnDemandHeadersRelay, OnDemandRelay},
TaggedAccount, TransactionParams,
};
/// A base relay between two standalone (relay) chains.
///
/// Such relay starts 2 messages relay and 2 on-demand header relays.
pub struct RelayToRelayBridge<
L2R: MessagesCliBridge + RelayToRelayHeadersCliBridge,
R2L: MessagesCliBridge + RelayToRelayHeadersCliBridge,
> {
/// Parameters that are shared by all bridge types.
pub common:
Full2WayBridgeCommonParams<<R2L as CliBridgeBase>::Target, <L2R as CliBridgeBase>::Target>,
/// Override for right->left headers signer.
pub right_to_left_transaction_params:
TransactionParams<AccountKeyPairOf<<R2L as CliBridgeBase>::Target>>,
/// Override for left->right headers signer.
pub left_to_right_transaction_params:
TransactionParams<AccountKeyPairOf<<L2R as CliBridgeBase>::Target>>,
}
macro_rules! declare_relay_to_relay_bridge_schema {
($left_chain:ident, $right_chain:ident) => {
bp_runtime::paste::item! {
#[doc = $left_chain " and " $right_chain " headers+messages relay params."]
#[derive(Debug, PartialEq, StructOpt)]
pub struct [<$left_chain $right_chain HeadersAndMessages>] {
#[structopt(flatten)]
shared: HeadersAndMessagesSharedParams,
// default signer, which is always used to sign messages relay transactions on the left chain
#[structopt(flatten)]
left: [<$left_chain ConnectionParams>],
// override for right->left headers signer
#[structopt(flatten)]
right_headers_to_left_sign_override: [<$right_chain HeadersTo $left_chain SigningParams>],
#[structopt(flatten)]
left_sign: [<$left_chain SigningParams>],
#[structopt(flatten)]
left_messages_pallet_owner: [<$left_chain MessagesPalletOwnerSigningParams>],
// default signer, which is always used to sign messages relay transactions on the right chain
#[structopt(flatten)]
right: [<$right_chain ConnectionParams>],
// override for left->right headers signer
#[structopt(flatten)]
left_headers_to_right_sign_override: [<$left_chain HeadersTo $right_chain SigningParams>],
#[structopt(flatten)]
right_sign: [<$right_chain SigningParams>],
#[structopt(flatten)]
right_messages_pallet_owner: [<$right_chain MessagesPalletOwnerSigningParams>],
}
impl [<$left_chain $right_chain HeadersAndMessages>] {
async fn into_bridge<
Left: ChainWithTransactions + CliChain<KeyPair = AccountKeyPairOf<Left>>,
Right: ChainWithTransactions + CliChain<KeyPair = AccountKeyPairOf<Right>>,
L2R: CliBridgeBase<Source = Left, Target = Right> + MessagesCliBridge + RelayToRelayHeadersCliBridge,
R2L: CliBridgeBase<Source = Right, Target = Left> + MessagesCliBridge + RelayToRelayHeadersCliBridge,
>(
self,
) -> anyhow::Result<RelayToRelayBridge<L2R, R2L>> {
Ok(RelayToRelayBridge {
common: Full2WayBridgeCommonParams::new::<L2R>(
self.shared,
BridgeEndCommonParams {
client: self.left.into_client::<Left>().await?,
sign: self.left_sign.to_keypair::<Left>()?,
transactions_mortality: self.left_sign.transactions_mortality()?,
messages_pallet_owner: self.left_messages_pallet_owner.to_keypair::<Left>()?,
accounts: vec![],
},
BridgeEndCommonParams {
client: self.right.into_client::<Right>().await?,
sign: self.right_sign.to_keypair::<Right>()?,
transactions_mortality: self.right_sign.transactions_mortality()?,
messages_pallet_owner: self.right_messages_pallet_owner.to_keypair::<Right>()?,
accounts: vec![],
},
)?,
right_to_left_transaction_params: self
.right_headers_to_left_sign_override
.transaction_params_or::<Left, _>(&self.left_sign)?,
left_to_right_transaction_params: self
.left_headers_to_right_sign_override
.transaction_params_or::<Right, _>(&self.right_sign)?,
})
}
}
}
};
}
#[async_trait]
impl<
Left: ChainWithTransactions + CliChain<KeyPair = AccountKeyPairOf<Left>>,
Right: ChainWithTransactions + CliChain<KeyPair = AccountKeyPairOf<Right>>,
L2R: CliBridgeBase<Source = Left, Target = Right>
+ MessagesCliBridge
+ RelayToRelayHeadersCliBridge,
R2L: CliBridgeBase<Source = Right, Target = Left>
+ MessagesCliBridge
+ RelayToRelayHeadersCliBridge,
> Full2WayBridgeBase for RelayToRelayBridge<L2R, R2L>
where
AccountIdOf<Left>: From<<AccountKeyPairOf<Left> as Pair>::Public>,
AccountIdOf<Right>: From<<AccountKeyPairOf<Right> as Pair>::Public>,
{
type Params = RelayToRelayBridge<L2R, R2L>;
type Left = Left;
type Right = Right;
fn common(&self) -> &Full2WayBridgeCommonParams<Left, Right> {
&self.common
}
fn mut_common(&mut self) -> &mut Full2WayBridgeCommonParams<Self::Left, Self::Right> {
&mut self.common
}
async fn start_on_demand_headers_relayers(
&mut self,
) -> anyhow::Result<(
Arc<dyn OnDemandRelay<BlockNumberOf<Self::Left>>>,
Arc<dyn OnDemandRelay<BlockNumberOf<Self::Right>>>,
)> {
self.common.right.accounts.push(TaggedAccount::Headers {
id: self.left_to_right_transaction_params.signer.public().into(),
bridged_chain: Self::Left::NAME.to_string(),
});
self.common.left.accounts.push(TaggedAccount::Headers {
id: self.right_to_left_transaction_params.signer.public().into(),
bridged_chain: Self::Right::NAME.to_string(),
});
<L2R as RelayToRelayHeadersCliBridge>::Finality::start_relay_guards(
&self.common.right.client,
&self.left_to_right_transaction_params,
self.common.right.client.can_start_version_guard(),
)
.await?;
<R2L as RelayToRelayHeadersCliBridge>::Finality::start_relay_guards(
&self.common.left.client,
&self.right_to_left_transaction_params,
self.common.left.client.can_start_version_guard(),
)
.await?;
let left_to_right_on_demand_headers =
OnDemandHeadersRelay::new::<<L2R as RelayToRelayHeadersCliBridge>::Finality>(
self.common.left.client.clone(),
self.common.right.client.clone(),
self.left_to_right_transaction_params.clone(),
self.common.shared.only_mandatory_headers,
);
let right_to_left_on_demand_headers =
OnDemandHeadersRelay::new::<<R2L as RelayToRelayHeadersCliBridge>::Finality>(
self.common.right.client.clone(),
self.common.left.client.clone(),
self.right_to_left_transaction_params.clone(),
self.common.shared.only_mandatory_headers,
);
Ok((Arc::new(left_to_right_on_demand_headers), Arc::new(right_to_left_on_demand_headers)))
}
}
@@ -0,0 +1,117 @@
// 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/>.
use async_trait::async_trait;
use sp_core::Pair;
use structopt::StructOpt;
use strum::VariantNames;
use crate::chains::{
bridge_hub_rococo_messages_to_bridge_hub_wococo::BridgeHubRococoToBridgeHubWococoMessagesCliBridge,
bridge_hub_wococo_messages_to_bridge_hub_rococo::BridgeHubWococoToBridgeHubRococoMessagesCliBridge,
millau_headers_to_rialto::MillauToRialtoCliBridge,
millau_headers_to_rialto_parachain::MillauToRialtoParachainCliBridge,
rialto_headers_to_millau::RialtoToMillauCliBridge,
rialto_parachains_to_millau::RialtoParachainToMillauCliBridge,
};
use relay_substrate_client::{AccountIdOf, AccountKeyPairOf, BalanceOf, ChainWithTransactions};
use substrate_relay_helper::{messages_lane::MessagesRelayParams, TransactionParams};
use crate::cli::{bridge::*, chain_schema::*, CliChain, HexLaneId, PrometheusParams};
/// Start messages relayer process.
#[derive(StructOpt)]
pub struct RelayMessages {
/// A bridge instance to relay messages for.
#[structopt(possible_values = FullBridge::VARIANTS, case_insensitive = true)]
bridge: FullBridge,
/// Hex-encoded lane id that should be served by the relay. Defaults to `00000000`.
#[structopt(long, default_value = "00000000")]
lane: HexLaneId,
#[structopt(flatten)]
source: SourceConnectionParams,
#[structopt(flatten)]
source_sign: SourceSigningParams,
#[structopt(flatten)]
target: TargetConnectionParams,
#[structopt(flatten)]
target_sign: TargetSigningParams,
#[structopt(flatten)]
prometheus_params: PrometheusParams,
}
#[async_trait]
trait MessagesRelayer: MessagesCliBridge
where
Self::Source: ChainWithTransactions + CliChain<KeyPair = AccountKeyPairOf<Self::Source>>,
AccountIdOf<Self::Source>: From<<AccountKeyPairOf<Self::Source> as Pair>::Public>,
AccountIdOf<Self::Target>: From<<AccountKeyPairOf<Self::Target> as Pair>::Public>,
BalanceOf<Self::Source>: TryFrom<BalanceOf<Self::Target>>,
{
async fn relay_messages(data: RelayMessages) -> anyhow::Result<()> {
let source_client = data.source.into_client::<Self::Source>().await?;
let source_sign = data.source_sign.to_keypair::<Self::Source>()?;
let source_transactions_mortality = data.source_sign.transactions_mortality()?;
let target_client = data.target.into_client::<Self::Target>().await?;
let target_sign = data.target_sign.to_keypair::<Self::Target>()?;
let target_transactions_mortality = data.target_sign.transactions_mortality()?;
substrate_relay_helper::messages_lane::run::<Self::MessagesLane>(MessagesRelayParams {
source_client,
source_transaction_params: TransactionParams {
signer: source_sign,
mortality: source_transactions_mortality,
},
target_client,
target_transaction_params: TransactionParams {
signer: target_sign,
mortality: target_transactions_mortality,
},
source_to_target_headers_relay: None,
target_to_source_headers_relay: None,
lane_id: data.lane.into(),
metrics_params: data.prometheus_params.into(),
})
.await
.map_err(|e| anyhow::format_err!("{}", e))
}
}
impl MessagesRelayer for MillauToRialtoCliBridge {}
impl MessagesRelayer for RialtoToMillauCliBridge {}
impl MessagesRelayer for MillauToRialtoParachainCliBridge {}
impl MessagesRelayer for RialtoParachainToMillauCliBridge {}
impl MessagesRelayer for BridgeHubRococoToBridgeHubWococoMessagesCliBridge {}
impl MessagesRelayer for BridgeHubWococoToBridgeHubRococoMessagesCliBridge {}
impl RelayMessages {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
match self.bridge {
FullBridge::MillauToRialto => MillauToRialtoCliBridge::relay_messages(self),
FullBridge::RialtoToMillau => RialtoToMillauCliBridge::relay_messages(self),
FullBridge::MillauToRialtoParachain =>
MillauToRialtoParachainCliBridge::relay_messages(self),
FullBridge::RialtoParachainToMillau =>
RialtoParachainToMillauCliBridge::relay_messages(self),
FullBridge::BridgeHubRococoToBridgeHubWococo =>
BridgeHubRococoToBridgeHubWococoMessagesCliBridge::relay_messages(self),
FullBridge::BridgeHubWococoToBridgeHubRococo =>
BridgeHubWococoToBridgeHubRococoMessagesCliBridge::relay_messages(self),
}
.await
}
}
@@ -0,0 +1,139 @@
// 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/>.
use crate::chains::{
rialto_parachains_to_millau::RialtoParachainToMillauCliBridge,
rococo_parachains_to_bridge_hub_wococo::BridgeHubRococoToBridgeHubWococoCliBridge,
westend_parachains_to_millau::WestmintToMillauCliBridge,
wococo_parachains_to_bridge_hub_rococo::BridgeHubWococoToBridgeHubRococoCliBridge,
};
use async_std::sync::Mutex;
use async_trait::async_trait;
use bp_polkadot_core::parachains::ParaId;
use parachains_relay::parachains_loop::{
AvailableHeader, ParachainSyncParams, SourceClient, TargetClient,
};
use relay_utils::metrics::{GlobalMetrics, StandaloneMetric};
use std::sync::Arc;
use structopt::StructOpt;
use strum::{EnumString, EnumVariantNames, VariantNames};
use substrate_relay_helper::{
parachains::{
source::ParachainsSource, target::ParachainsTarget, ParachainsPipelineAdapter,
SubstrateParachainsPipeline,
},
TransactionParams,
};
use crate::cli::{bridge::ParachainToRelayHeadersCliBridge, chain_schema::*, PrometheusParams};
/// Start parachain heads relayer process.
#[derive(StructOpt)]
pub struct RelayParachains {
/// A bridge instance to relay parachains heads for.
#[structopt(possible_values = RelayParachainsBridge::VARIANTS, case_insensitive = true)]
bridge: RelayParachainsBridge,
#[structopt(flatten)]
source: SourceConnectionParams,
#[structopt(flatten)]
target: TargetConnectionParams,
#[structopt(flatten)]
target_sign: TargetSigningParams,
#[structopt(flatten)]
prometheus_params: PrometheusParams,
}
/// Parachain heads relay bridge.
#[derive(Debug, EnumString, EnumVariantNames)]
#[strum(serialize_all = "kebab_case")]
pub enum RelayParachainsBridge {
RialtoToMillau,
// TODO:check-parameter - rename to WestmintToMillau?
WestendToMillau,
BridgeHubRococoToBridgeHubWococo,
BridgeHubWococoToBridgeHubRococo,
}
#[async_trait]
trait ParachainsRelayer: ParachainToRelayHeadersCliBridge
where
ParachainsSource<Self::ParachainFinality>:
SourceClient<ParachainsPipelineAdapter<Self::ParachainFinality>>,
ParachainsTarget<Self::ParachainFinality>:
TargetClient<ParachainsPipelineAdapter<Self::ParachainFinality>>,
{
async fn relay_headers(data: RelayParachains) -> anyhow::Result<()> {
let source_client = data.source.into_client::<Self::SourceRelay>().await?;
let source_client = ParachainsSource::<Self::ParachainFinality>::new(
source_client,
Arc::new(Mutex::new(AvailableHeader::Missing)),
);
let target_transaction_params = TransactionParams {
signer: data.target_sign.to_keypair::<Self::Target>()?,
mortality: data.target_sign.target_transactions_mortality,
};
let target_client = data.target.into_client::<Self::Target>().await?;
let target_client = ParachainsTarget::<Self::ParachainFinality>::new(
target_client.clone(),
target_transaction_params,
);
let metrics_params: relay_utils::metrics::MetricsParams = data.prometheus_params.into();
GlobalMetrics::new()?.register_and_spawn(&metrics_params.registry)?;
parachains_relay::parachains_loop::run(
source_client,
target_client,
ParachainSyncParams {
parachains: vec![
ParaId(<Self::ParachainFinality as SubstrateParachainsPipeline>::SOURCE_PARACHAIN_PARA_ID)
],
stall_timeout: std::time::Duration::from_secs(60),
strategy: parachains_relay::parachains_loop::ParachainSyncStrategy::Any,
},
metrics_params,
futures::future::pending(),
)
.await
.map_err(|e| anyhow::format_err!("{}", e))
}
}
impl ParachainsRelayer for RialtoParachainToMillauCliBridge {}
impl ParachainsRelayer for WestmintToMillauCliBridge {}
impl ParachainsRelayer for BridgeHubRococoToBridgeHubWococoCliBridge {}
impl ParachainsRelayer for BridgeHubWococoToBridgeHubRococoCliBridge {}
impl RelayParachains {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
match self.bridge {
RelayParachainsBridge::RialtoToMillau =>
RialtoParachainToMillauCliBridge::relay_headers(self),
RelayParachainsBridge::WestendToMillau =>
WestmintToMillauCliBridge::relay_headers(self),
RelayParachainsBridge::BridgeHubRococoToBridgeHubWococo =>
BridgeHubRococoToBridgeHubWococoCliBridge::relay_headers(self),
RelayParachainsBridge::BridgeHubWococoToBridgeHubRococo =>
BridgeHubWococoToBridgeHubRococoCliBridge::relay_headers(self),
}
.await
}
}
@@ -0,0 +1,561 @@
// 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/>.
use crate::cli::{chain_schema::*, Balance};
use bp_runtime::HeaderIdProvider;
use codec::{Decode, Encode};
use num_traits::{One, Zero};
use relay_substrate_client::{
AccountKeyPairOf, BlockWithJustification, Chain, ChainWithTransactions, Client,
Error as SubstrateError, HeaderIdOf, HeaderOf, SignParam,
};
use relay_utils::FailedClient;
use sp_core::Bytes;
use sp_runtime::{
traits::{Hash, Header as HeaderT},
transaction_validity::TransactionPriority,
};
use structopt::StructOpt;
use strum::{EnumString, EnumVariantNames, VariantNames};
use substrate_relay_helper::TransactionParams;
/// Start resubmit transactions process.
#[derive(StructOpt)]
pub struct ResubmitTransactions {
/// A bridge instance to relay headers for.
#[structopt(possible_values = RelayChain::VARIANTS, case_insensitive = true)]
chain: RelayChain,
#[structopt(flatten)]
target: TargetConnectionParams,
#[structopt(flatten)]
target_sign: TargetSigningParams,
/// Number of blocks we see before considering queued transaction as stalled.
#[structopt(long, default_value = "5")]
stalled_blocks: u32,
/// Tip limit. We'll never submit transaction with larger tip.
#[structopt(long)]
tip_limit: Balance,
/// Tip increase step. We'll be checking updated transaction priority by increasing its tip by
/// this step.
#[structopt(long)]
tip_step: Balance,
/// Priority selection strategy.
#[structopt(subcommand)]
strategy: PrioritySelectionStrategy,
}
/// Chain, which transactions we're going to track && resubmit.
#[derive(Debug, EnumString, EnumVariantNames)]
#[strum(serialize_all = "kebab_case")]
pub enum RelayChain {
Millau,
}
/// Strategy to use for priority selection.
#[derive(StructOpt, Debug, PartialEq, Eq, Clone, Copy)]
pub enum PrioritySelectionStrategy {
/// Strategy selects tip that changes transaction priority to be better than priority of
/// the first transaction of previous block.
///
/// It only makes sense to use this strategy for Millau transactions. Millau has transactions
/// that are close to block limits, so if there are any other queued transactions, 'large'
/// transaction won't fit the block && will be postponed. To avoid this, we change its priority
/// to some large value, making it best transaction => it'll be 'mined' first.
MakeItBestTransaction,
/// Strategy selects tip that changes transaction priority to be better than priority of
/// selected queued transaction.
///
/// When we first see stalled transaction, we make it better than worst 1/4 of queued
/// transactions. If it is still stalled, we'll make it better than 1/3 of queued transactions,
/// ...
MakeItBetterThanQueuedTransaction,
}
macro_rules! select_bridge {
($bridge: expr, $generic: tt) => {
match $bridge {
RelayChain::Millau => {
type Target = relay_millau_client::Millau;
type TargetSign = relay_millau_client::Millau;
$generic
},
}
};
}
impl ResubmitTransactions {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
select_bridge!(self.chain, {
let relay_loop_name = format!("ResubmitTransactions{}", Target::NAME);
let client = self.target.into_client::<Target>().await?;
let transaction_params = TransactionParams {
signer: self.target_sign.to_keypair::<Target>()?,
mortality: self.target_sign.target_transactions_mortality,
};
relay_utils::relay_loop((), client)
.run(relay_loop_name, move |_, client, _| {
run_until_connection_lost(
client,
transaction_params.clone(),
Context {
strategy: self.strategy,
best_header: HeaderOf::<Target>::new(
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
),
transaction: None,
resubmitted: 0,
stalled_for: Zero::zero(),
stalled_for_limit: self.stalled_blocks as _,
tip_step: self.tip_step.cast() as _,
tip_limit: self.tip_limit.cast() as _,
},
)
})
.await
.map_err(Into::into)
})
}
}
impl PrioritySelectionStrategy {
/// Select target priority.
async fn select_target_priority<C: ChainWithTransactions>(
&self,
client: &Client<C>,
context: &Context<C>,
) -> Result<Option<TransactionPriority>, SubstrateError> {
match *self {
PrioritySelectionStrategy::MakeItBestTransaction =>
read_previous_block_best_priority(client, context).await,
PrioritySelectionStrategy::MakeItBetterThanQueuedTransaction =>
select_priority_from_queue(client, context).await,
}
}
}
#[derive(Debug)]
struct Context<C: Chain> {
/// Priority selection strategy.
strategy: PrioritySelectionStrategy,
/// Best known block header.
best_header: C::Header,
/// Hash of the (potentially) stalled transaction.
transaction: Option<C::Hash>,
/// How many times we have resubmitted this `transaction`?
resubmitted: u32,
/// This transaction is in pool for `stalled_for` wakeup intervals.
stalled_for: C::BlockNumber,
/// When `stalled_for` reaching this limit, transaction is considered stalled.
stalled_for_limit: C::BlockNumber,
/// Tip step interval.
tip_step: C::Balance,
/// Maximal tip.
tip_limit: C::Balance,
}
impl<C: Chain> Context<C> {
/// Return true if transaction has stalled.
fn is_stalled(&self) -> bool {
self.stalled_for >= self.stalled_for_limit
}
/// Notice resubmitted transaction.
fn notice_resubmitted_transaction(mut self, transaction: C::Hash) -> Self {
self.transaction = Some(transaction);
self.stalled_for = Zero::zero();
self.resubmitted += 1;
self
}
/// Notice transaction from the transaction pool.
fn notice_transaction(mut self, transaction: C::Hash) -> Self {
if self.transaction == Some(transaction) {
self.stalled_for += One::one();
} else {
self.transaction = Some(transaction);
self.stalled_for = One::one();
self.resubmitted = 0;
}
self
}
}
/// Run resubmit transactions loop.
async fn run_until_connection_lost<C: ChainWithTransactions>(
client: Client<C>,
transaction_params: TransactionParams<AccountKeyPairOf<C>>,
mut context: Context<C>,
) -> Result<(), FailedClient> {
loop {
async_std::task::sleep(C::AVERAGE_BLOCK_INTERVAL).await;
let result = run_loop_iteration(client.clone(), transaction_params.clone(), context).await;
context = match result {
Ok(context) => context,
Err(error) => {
log::error!(
target: "bridge",
"Resubmit {} transactions loop has failed with error: {:?}",
C::NAME,
error,
);
return Err(FailedClient::Target)
},
};
}
}
/// Run single loop iteration.
async fn run_loop_iteration<C: ChainWithTransactions>(
client: Client<C>,
transaction_params: TransactionParams<AccountKeyPairOf<C>>,
mut context: Context<C>,
) -> Result<Context<C>, SubstrateError> {
// correct best header is required for all other actions
context.best_header = client.best_header().await?;
// check if there's queued transaction, signed by given author
let original_transaction =
match lookup_signer_transaction(&client, &transaction_params.signer).await? {
Some(original_transaction) => original_transaction,
None => {
log::trace!(target: "bridge", "No {} transactions from required signer in the txpool", C::NAME);
return Ok(context)
},
};
let original_transaction_hash = C::Hasher::hash(&original_transaction.encode());
let context = context.notice_transaction(original_transaction_hash);
// if transaction hasn't been mined for `stalled_blocks`, we'll need to resubmit it
if !context.is_stalled() {
log::trace!(
target: "bridge",
"{} transaction {:?} is not yet stalled ({:?}/{:?})",
C::NAME,
context.transaction,
context.stalled_for,
context.stalled_for_limit,
);
return Ok(context)
}
// select priority for updated transaction
let target_priority = match context.strategy.select_target_priority(&client, &context).await? {
Some(target_priority) => target_priority,
None => {
log::trace!(target: "bridge", "Failed to select target priority");
return Ok(context)
},
};
// update transaction tip
let (is_updated, updated_transaction) = update_transaction_tip(
&client,
&transaction_params,
context.best_header.id(),
original_transaction,
context.tip_step,
context.tip_limit,
target_priority,
)
.await?;
if !is_updated {
log::trace!(target: "bridge", "{} transaction tip can not be updated. Reached limit?", C::NAME);
return Ok(context)
}
let updated_transaction = updated_transaction.encode();
let updated_transaction_hash = C::Hasher::hash(&updated_transaction);
client.submit_unsigned_extrinsic(Bytes(updated_transaction)).await?;
log::info!(
target: "bridge",
"Replaced {} transaction {} with {} in txpool",
C::NAME,
original_transaction_hash,
updated_transaction_hash,
);
Ok(context.notice_resubmitted_transaction(updated_transaction_hash))
}
/// Search transaction pool for transaction, signed by given key pair.
async fn lookup_signer_transaction<C: ChainWithTransactions>(
client: &Client<C>,
key_pair: &AccountKeyPairOf<C>,
) -> Result<Option<C::SignedTransaction>, SubstrateError> {
let pending_transactions = client.pending_extrinsics().await?;
for pending_transaction in pending_transactions {
let pending_transaction = C::SignedTransaction::decode(&mut &pending_transaction.0[..])
.map_err(SubstrateError::ResponseParseFailed)?;
if !C::is_signed_by(key_pair, &pending_transaction) {
continue
}
return Ok(Some(pending_transaction))
}
Ok(None)
}
/// Read priority of best signed transaction of previous block.
async fn read_previous_block_best_priority<C: ChainWithTransactions>(
client: &Client<C>,
context: &Context<C>,
) -> Result<Option<TransactionPriority>, SubstrateError> {
let best_block = client.get_block(Some(context.best_header.hash())).await?;
let best_transaction = best_block
.extrinsics()
.iter()
.filter_map(|xt| C::SignedTransaction::decode(&mut &xt[..]).ok())
.find(|xt| C::is_signed(xt));
match best_transaction {
Some(best_transaction) => Ok(Some(
client
.validate_transaction(*context.best_header.parent_hash(), best_transaction)
.await??
.priority,
)),
None => Ok(None),
}
}
/// Select priority of some queued transaction.
async fn select_priority_from_queue<C: ChainWithTransactions>(
client: &Client<C>,
context: &Context<C>,
) -> Result<Option<TransactionPriority>, SubstrateError> {
// select transaction from the queue
let queued_transactions = client.pending_extrinsics().await?;
let selected_transaction = match select_transaction_from_queue(queued_transactions, context) {
Some(selected_transaction) => selected_transaction,
None => return Ok(None),
};
let selected_transaction = C::SignedTransaction::decode(&mut &selected_transaction[..])
.map_err(SubstrateError::ResponseParseFailed)?;
let target_priority = client
.validate_transaction(context.best_header.hash(), selected_transaction)
.await??
.priority;
Ok(Some(target_priority))
}
/// Select transaction with target priority from the vec of queued transactions.
fn select_transaction_from_queue<C: Chain>(
mut queued_transactions: Vec<Bytes>,
context: &Context<C>,
) -> Option<Bytes> {
if queued_transactions.is_empty() {
return None
}
// the more times we resubmit transaction (`context.resubmitted`), the closer we move
// to the front of the transaction queue
let total_transactions = queued_transactions.len();
let resubmitted_factor = context.resubmitted;
let divisor =
1usize.saturating_add(1usize.checked_shl(resubmitted_factor).unwrap_or(usize::MAX));
let transactions_to_skip = total_transactions / divisor;
Some(
queued_transactions
.swap_remove(std::cmp::min(total_transactions - 1, transactions_to_skip)),
)
}
/// Try to find appropriate tip for transaction so that its priority is larger than given.
async fn update_transaction_tip<C: ChainWithTransactions>(
client: &Client<C>,
transaction_params: &TransactionParams<AccountKeyPairOf<C>>,
at_block: HeaderIdOf<C>,
tx: C::SignedTransaction,
tip_step: C::Balance,
tip_limit: C::Balance,
target_priority: TransactionPriority,
) -> Result<(bool, C::SignedTransaction), SubstrateError> {
let stx = format!("{tx:?}");
let mut current_priority = client.validate_transaction(at_block.1, tx.clone()).await??.priority;
let mut unsigned_tx = C::parse_transaction(tx).ok_or_else(|| {
SubstrateError::Custom(format!("Failed to parse {} transaction {stx}", C::NAME,))
})?;
let old_tip = unsigned_tx.tip;
let (spec_version, transaction_version) = client.simple_runtime_version().await?;
while current_priority < target_priority {
let next_tip = unsigned_tx.tip + tip_step;
if next_tip > tip_limit {
break
}
log::trace!(
target: "bridge",
"{} transaction priority with tip={:?}: {}. Target priority: {}",
C::NAME,
unsigned_tx.tip,
current_priority,
target_priority,
);
unsigned_tx.tip = next_tip;
current_priority = client
.validate_transaction(
at_block.1,
C::sign_transaction(
SignParam {
spec_version,
transaction_version,
genesis_hash: *client.genesis_hash(),
signer: transaction_params.signer.clone(),
},
unsigned_tx.clone(),
)?,
)
.await??
.priority;
}
log::debug!(
target: "bridge",
"{} transaction tip has changed from {:?} to {:?}",
C::NAME,
old_tip,
unsigned_tx.tip,
);
Ok((
old_tip != unsigned_tx.tip,
C::sign_transaction(
SignParam {
spec_version,
transaction_version,
genesis_hash: *client.genesis_hash(),
signer: transaction_params.signer.clone(),
},
unsigned_tx.era(relay_substrate_client::TransactionEra::new(
at_block,
transaction_params.mortality,
)),
)?,
))
}
#[cfg(test)]
mod tests {
use super::*;
use bp_rialto::Hash;
use relay_rialto_client::Rialto;
fn context() -> Context<Rialto> {
Context {
strategy: PrioritySelectionStrategy::MakeItBestTransaction,
best_header: HeaderOf::<Rialto>::new(
Default::default(),
Default::default(),
Default::default(),
Default::default(),
Default::default(),
),
transaction: None,
resubmitted: 0,
stalled_for: Zero::zero(),
stalled_for_limit: 3,
tip_step: 100,
tip_limit: 1000,
}
}
#[test]
fn context_works() {
let mut context = context();
// when transaction is noticed 2/3 times, it isn't stalled
context = context.notice_transaction(Default::default());
assert!(!context.is_stalled());
assert_eq!(context.stalled_for, 1);
assert_eq!(context.resubmitted, 0);
context = context.notice_transaction(Default::default());
assert!(!context.is_stalled());
assert_eq!(context.stalled_for, 2);
assert_eq!(context.resubmitted, 0);
// when transaction is noticed for 3rd time in a row, it is considered stalled
context = context.notice_transaction(Default::default());
assert!(context.is_stalled());
assert_eq!(context.stalled_for, 3);
assert_eq!(context.resubmitted, 0);
// and after we resubmit it, we forget previous transaction
context = context.notice_resubmitted_transaction(Hash::from([1; 32]));
assert_eq!(context.transaction, Some(Hash::from([1; 32])));
assert_eq!(context.resubmitted, 1);
assert_eq!(context.stalled_for, 0);
}
#[test]
fn select_transaction_from_queue_works_with_empty_queue() {
assert_eq!(select_transaction_from_queue(vec![], &context()), None);
}
#[test]
fn select_transaction_from_queue_works() {
let mut context = context();
let queued_transactions = vec![
Bytes(vec![1]),
Bytes(vec![2]),
Bytes(vec![3]),
Bytes(vec![4]),
Bytes(vec![5]),
Bytes(vec![6]),
];
// when we resubmit tx for the first time, 1/2 of queue is skipped
assert_eq!(
select_transaction_from_queue(queued_transactions.clone(), &context),
Some(Bytes(vec![4])),
);
// when we resubmit tx for the second time, 1/3 of queue is skipped
context = context.notice_resubmitted_transaction(Hash::from([1; 32]));
assert_eq!(
select_transaction_from_queue(queued_transactions.clone(), &context),
Some(Bytes(vec![3])),
);
// when we resubmit tx for the third time, 1/5 of queue is skipped
context = context.notice_resubmitted_transaction(Hash::from([2; 32]));
assert_eq!(
select_transaction_from_queue(queued_transactions.clone(), &context),
Some(Bytes(vec![2])),
);
// when we resubmit tx for the second time, 1/9 of queue is skipped
context = context.notice_resubmitted_transaction(Hash::from([3; 32]));
assert_eq!(
select_transaction_from_queue(queued_transactions, &context),
Some(Bytes(vec![1])),
);
}
}
@@ -0,0 +1,195 @@
// 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/>.
use crate::{
chains::{
millau_headers_to_rialto::MillauToRialtoCliBridge,
millau_headers_to_rialto_parachain::MillauToRialtoParachainCliBridge,
rialto_headers_to_millau::RialtoToMillauCliBridge,
rialto_parachains_to_millau::RialtoParachainToMillauCliBridge,
},
cli::{
bridge::{FullBridge, MessagesCliBridge},
chain_schema::*,
encode_message::{self, CliEncodeMessage, RawMessage},
CliChain,
},
};
use async_trait::async_trait;
use codec::{Decode, Encode};
use relay_substrate_client::{
AccountIdOf, AccountKeyPairOf, Chain, ChainBase, ChainWithTransactions, SignParam,
UnsignedTransaction,
};
use sp_core::Pair;
use sp_runtime::AccountId32;
use std::fmt::Display;
use structopt::StructOpt;
use strum::VariantNames;
/// Send bridge message.
#[derive(StructOpt)]
pub struct SendMessage {
/// A bridge instance to encode call for.
#[structopt(possible_values = FullBridge::VARIANTS, case_insensitive = true)]
bridge: FullBridge,
#[structopt(flatten)]
source: SourceConnectionParams,
#[structopt(flatten)]
source_sign: SourceSigningParams,
/// Message type.
#[structopt(subcommand)]
message: crate::cli::encode_message::Message,
}
#[async_trait]
trait MessageSender: MessagesCliBridge
where
Self::Source: ChainBase<Index = u32>
+ ChainWithTransactions
+ CliChain<KeyPair = AccountKeyPairOf<Self::Source>>
+ CliEncodeMessage,
<Self::Source as ChainBase>::Balance: Display + From<u64> + Into<u128>,
<Self::Source as Chain>::Call: Sync,
<Self::Source as ChainWithTransactions>::SignedTransaction: Sync,
AccountIdOf<Self::Source>: From<<AccountKeyPairOf<Self::Source> as Pair>::Public>,
AccountId32: From<<AccountKeyPairOf<Self::Source> as Pair>::Public>,
{
async fn send_message(data: SendMessage) -> anyhow::Result<()> {
let payload = encode_message::encode_message::<Self::Source, Self::Target>(&data.message)?;
let source_client = data.source.into_client::<Self::Source>().await?;
let source_sign = data.source_sign.to_keypair::<Self::Source>()?;
let payload_len = payload.encoded_size();
let send_message_call = Self::Source::encode_send_xcm(
decode_xcm(payload)?,
data.bridge.bridge_instance_index(),
)?;
let source_genesis_hash = *source_client.genesis_hash();
let (spec_version, transaction_version) = source_client.simple_runtime_version().await?;
source_client
.submit_signed_extrinsic(
source_sign.public().into(),
SignParam::<Self::Source> {
spec_version,
transaction_version,
genesis_hash: source_genesis_hash,
signer: source_sign.clone(),
},
move |_, transaction_nonce| {
let unsigned = UnsignedTransaction::new(send_message_call, transaction_nonce);
log::info!(
target: "bridge",
"Sending message to {}. Size: {}",
Self::Target::NAME,
payload_len,
);
Ok(unsigned)
},
)
.await?;
Ok(())
}
}
impl MessageSender for MillauToRialtoCliBridge {}
impl MessageSender for RialtoToMillauCliBridge {}
impl MessageSender for MillauToRialtoParachainCliBridge {}
impl MessageSender for RialtoParachainToMillauCliBridge {}
impl SendMessage {
/// Run the command.
pub async fn run(self) -> anyhow::Result<()> {
match self.bridge {
FullBridge::MillauToRialto => MillauToRialtoCliBridge::send_message(self),
FullBridge::RialtoToMillau => RialtoToMillauCliBridge::send_message(self),
FullBridge::MillauToRialtoParachain =>
MillauToRialtoParachainCliBridge::send_message(self),
FullBridge::RialtoParachainToMillau =>
RialtoParachainToMillauCliBridge::send_message(self),
FullBridge::BridgeHubRococoToBridgeHubWococo => unimplemented!(
"Sending message from BridgeHubRococo to BridgeHubWococo is not supported"
),
FullBridge::BridgeHubWococoToBridgeHubRococo => unimplemented!(
"Sending message from BridgeHubWococo to BridgeHubRococo is not supported"
),
}
.await
}
}
/// Decode SCALE encoded raw XCM message.
pub(crate) fn decode_xcm(message: RawMessage) -> anyhow::Result<xcm::VersionedXcm<()>> {
Decode::decode(&mut &message[..])
.map_err(|e| anyhow::format_err!("Failed to decode XCM program: {:?}", e))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cli::{ExplicitOrMaximal, HexBytes};
#[test]
fn send_raw_rialto_to_millau() {
// given
let send_message = SendMessage::from_iter(vec![
"send-message",
"rialto-to-millau",
"--source-port",
"1234",
"--source-signer",
"//Alice",
"raw",
"dead",
]);
// then
assert_eq!(send_message.bridge, FullBridge::RialtoToMillau);
assert_eq!(send_message.source.source_port, 1234);
assert_eq!(send_message.source_sign.source_signer, Some("//Alice".into()));
assert_eq!(
send_message.message,
crate::cli::encode_message::Message::Raw { data: HexBytes(vec![0xDE, 0xAD]) }
);
}
#[test]
fn send_sized_rialto_to_millau() {
// given
let send_message = SendMessage::from_iter(vec![
"send-message",
"rialto-to-millau",
"--source-port",
"1234",
"--source-signer",
"//Alice",
"sized",
"max",
]);
// then
assert_eq!(send_message.bridge, FullBridge::RialtoToMillau);
assert_eq!(send_message.source.source_port, 1234);
assert_eq!(send_message.source_sign.source_signer, Some("//Alice".into()));
assert_eq!(
send_message.message,
crate::cli::encode_message::Message::Sized { size: ExplicitOrMaximal::Maximal }
);
}
}
+31
View File
@@ -0,0 +1,31 @@
// 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 relay entrypoint.
#![warn(missing_docs)]
mod chains;
mod cli;
fn main() {
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", "substrate-relay: {}", error);
}
}