mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-11-28 21:39:56 +00:00
Squashed 'bridges/' content from commit 062554430
git-subtree-dir: bridges git-subtree-split: 0625544309ff299307f7e110f252f04eac383102
This commit is contained in:
commit
d2b7ee2575
357 files changed
+79920
No files matched your search
@@ -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;
|
||||
}
|
||||
@@ -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,
|
||||
>;
|
||||
}
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
¶_id.encode(),
|
||||
);
|
||||
wait_para_state(
|
||||
&relay_client,
|
||||
¶_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,
|
||||
¶_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(¶_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 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
[package]
|
||||
name = "relay-bridge-hub-rococo-client"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
codec = { package = "parity-scale-codec", version = "3.1.5", features = ["derive"] }
|
||||
scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }
|
||||
relay-substrate-client = { path = "../client-substrate" }
|
||||
|
||||
# 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-polkadot-core = { path = "../../primitives/polkadot-core" }
|
||||
bp-runtime = { path = "../../primitives/runtime" }
|
||||
|
||||
bridge-runtime-common = { path = "../../bin/runtime-common" }
|
||||
# Substrate Dependencies
|
||||
|
||||
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
|
||||
[dev-dependencies]
|
||||
sp-finality-grandpa = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
@@ -0,0 +1,171 @@
|
||||
// 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/>.
|
||||
|
||||
//! Types used to connect to the BridgeHub-Rococo-Substrate parachain.
|
||||
|
||||
use bp_messages::{MessageNonce, Weight};
|
||||
use codec::Encode;
|
||||
use relay_substrate_client::{
|
||||
Chain, ChainBase, ChainWithBalances, ChainWithMessages, ChainWithTransactions,
|
||||
Error as SubstrateError, SignParam, UnsignedTransaction,
|
||||
};
|
||||
use sp_core::{storage::StorageKey, Pair};
|
||||
use sp_runtime::{generic::SignedPayload, traits::IdentifyAccount};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Re-export runtime wrapper
|
||||
pub mod runtime_wrapper;
|
||||
pub use runtime_wrapper as runtime;
|
||||
|
||||
/// Rococo chain definition
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct BridgeHubRococo;
|
||||
|
||||
impl ChainBase for BridgeHubRococo {
|
||||
type BlockNumber = bp_bridge_hub_rococo::BlockNumber;
|
||||
type Hash = bp_bridge_hub_rococo::Hash;
|
||||
type Hasher = bp_bridge_hub_rococo::Hashing;
|
||||
type Header = bp_bridge_hub_rococo::Header;
|
||||
|
||||
type AccountId = bp_bridge_hub_rococo::AccountId;
|
||||
type Balance = bp_bridge_hub_rococo::Balance;
|
||||
type Index = bp_bridge_hub_rococo::Nonce;
|
||||
type Signature = bp_bridge_hub_rococo::Signature;
|
||||
|
||||
fn max_extrinsic_size() -> u32 {
|
||||
bp_bridge_hub_rococo::BridgeHubRococo::max_extrinsic_size()
|
||||
}
|
||||
|
||||
fn max_extrinsic_weight() -> Weight {
|
||||
bp_bridge_hub_rococo::BridgeHubRococo::max_extrinsic_weight()
|
||||
}
|
||||
}
|
||||
|
||||
impl Chain for BridgeHubRococo {
|
||||
const NAME: &'static str = "BridgeHubRococo";
|
||||
const TOKEN_ID: Option<&'static str> = None;
|
||||
const BEST_FINALIZED_HEADER_ID_METHOD: &'static str =
|
||||
bp_bridge_hub_rococo::BEST_FINALIZED_BRIDGE_HUB_ROCOCO_HEADER_METHOD;
|
||||
const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_secs(6);
|
||||
|
||||
type SignedBlock = bp_bridge_hub_rococo::SignedBlock;
|
||||
type Call = runtime::Call;
|
||||
}
|
||||
|
||||
impl ChainWithBalances for BridgeHubRococo {
|
||||
fn account_info_storage_key(account_id: &Self::AccountId) -> StorageKey {
|
||||
bp_bridge_hub_rococo::AccountInfoStorageMapKeyProvider::final_key(account_id)
|
||||
}
|
||||
}
|
||||
|
||||
impl ChainWithTransactions for BridgeHubRococo {
|
||||
type AccountKeyPair = sp_core::sr25519::Pair;
|
||||
type SignedTransaction = runtime::UncheckedExtrinsic;
|
||||
|
||||
fn sign_transaction(
|
||||
param: SignParam<Self>,
|
||||
unsigned: UnsignedTransaction<Self>,
|
||||
) -> Result<Self::SignedTransaction, SubstrateError> {
|
||||
let raw_payload = SignedPayload::new(
|
||||
unsigned.call,
|
||||
bp_bridge_hub_rococo::SignedExtensions::new(
|
||||
param.spec_version,
|
||||
param.transaction_version,
|
||||
unsigned.era,
|
||||
param.genesis_hash,
|
||||
unsigned.nonce,
|
||||
unsigned.tip,
|
||||
),
|
||||
)?;
|
||||
|
||||
let signature = raw_payload.using_encoded(|payload| param.signer.sign(payload));
|
||||
let signer: sp_runtime::MultiSigner = param.signer.public().into();
|
||||
let (call, extra, _) = raw_payload.deconstruct();
|
||||
|
||||
Ok(bp_bridge_hub_rococo::UncheckedExtrinsic::new_signed(
|
||||
call,
|
||||
signer.into_account().into(),
|
||||
signature.into(),
|
||||
extra,
|
||||
))
|
||||
}
|
||||
|
||||
fn is_signed(tx: &Self::SignedTransaction) -> bool {
|
||||
tx.signature.is_some()
|
||||
}
|
||||
|
||||
fn is_signed_by(signer: &Self::AccountKeyPair, tx: &Self::SignedTransaction) -> bool {
|
||||
tx.signature
|
||||
.as_ref()
|
||||
.map(|(address, _, _)| {
|
||||
*address == bp_bridge_hub_rococo::Address::Id(signer.public().into())
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn parse_transaction(tx: Self::SignedTransaction) -> Option<UnsignedTransaction<Self>> {
|
||||
let extra = &tx.signature.as_ref()?.2;
|
||||
Some(UnsignedTransaction::new(tx.function, extra.nonce()).tip(extra.tip()))
|
||||
}
|
||||
}
|
||||
|
||||
impl ChainWithMessages for BridgeHubRococo {
|
||||
const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str =
|
||||
bp_bridge_hub_rococo::WITH_BRIDGE_HUB_ROCOCO_MESSAGES_PALLET_NAME;
|
||||
|
||||
const TO_CHAIN_MESSAGE_DETAILS_METHOD: &'static str =
|
||||
bp_bridge_hub_rococo::TO_BRIDGE_HUB_ROCOCO_MESSAGE_DETAILS_METHOD;
|
||||
const FROM_CHAIN_MESSAGE_DETAILS_METHOD: &'static str =
|
||||
bp_bridge_hub_rococo::FROM_BRIDGE_HUB_ROCOCO_MESSAGE_DETAILS_METHOD;
|
||||
|
||||
const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce =
|
||||
bp_bridge_hub_rococo::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX;
|
||||
const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce =
|
||||
bp_bridge_hub_rococo::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX;
|
||||
|
||||
type WeightToFee = bp_bridge_hub_rococo::WeightToFee;
|
||||
// TODO: fix (https://github.com/paritytech/parity-bridges-common/issues/1640)
|
||||
type WeightInfo = ();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use relay_substrate_client::TransactionEra;
|
||||
|
||||
#[test]
|
||||
fn parse_transaction_works() {
|
||||
let unsigned = UnsignedTransaction {
|
||||
call: runtime::Call::System(runtime::SystemCall::remark(b"Hello world!".to_vec()))
|
||||
.into(),
|
||||
nonce: 777,
|
||||
tip: 888,
|
||||
era: TransactionEra::immortal(),
|
||||
};
|
||||
let signed_transaction = BridgeHubRococo::sign_transaction(
|
||||
SignParam {
|
||||
spec_version: 42,
|
||||
transaction_version: 50000,
|
||||
genesis_hash: [42u8; 32].into(),
|
||||
signer: sp_core::sr25519::Pair::from_seed_slice(&[1u8; 32]).unwrap(),
|
||||
},
|
||||
unsigned.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
let parsed_transaction = BridgeHubRococo::parse_transaction(signed_transaction).unwrap();
|
||||
assert_eq!(parsed_transaction, unsigned);
|
||||
}
|
||||
}
|
||||
@@ -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/>.
|
||||
|
||||
// TODO: join with primitives do we need this here or move to the primitives?
|
||||
|
||||
//! Types that are specific to the BridgeHubRococo runtime.
|
||||
|
||||
use bp_polkadot_core::PolkadotLike;
|
||||
use codec::{Decode, Encode};
|
||||
use scale_info::TypeInfo;
|
||||
|
||||
pub use bp_bridge_hub_rococo::SS58Prefix;
|
||||
use bp_messages::UnrewardedRelayersState;
|
||||
use bp_polkadot_core::parachains::{ParaHash, ParaHeadsProof, ParaId};
|
||||
use bp_runtime::Chain;
|
||||
|
||||
// TODO:check-parameter - check SignedExtension
|
||||
/// Unchecked BridgeHubRococo extrinsic.
|
||||
pub type UncheckedExtrinsic = bp_bridge_hub_rococo::UncheckedExtrinsic<Call>;
|
||||
|
||||
/// Rococo Runtime `Call` enum.
|
||||
///
|
||||
/// The enum represents a subset of possible `Call`s we can send to Rococo chain.
|
||||
/// Ideally this code would be auto-generated from metadata, because we want to
|
||||
/// avoid depending directly on the ENTIRE runtime just to get the encoding of `Dispatchable`s.
|
||||
///
|
||||
/// All entries here (like pretty much in the entire file) must be kept in sync with Rococo
|
||||
/// `construct_runtime`, so that we maintain SCALE-compatibility.
|
||||
///
|
||||
/// // TODO:check-parameter -> change bko-bridge-rococo-wococo when merged to master in cumulus
|
||||
/// See: [link](https://github.com/paritytech/cumulus/blob/bko-bridge-rococo-wococo/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs)
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
#[derive(Encode, Decode, Debug, PartialEq, Eq, Clone, TypeInfo)]
|
||||
pub enum Call {
|
||||
/// System pallet.
|
||||
#[codec(index = 0)]
|
||||
System(SystemCall),
|
||||
/// Wococo bridge pallet.
|
||||
#[codec(index = 41)]
|
||||
BridgeWococoGrandpa(BridgeWococoGrandpaCall),
|
||||
/// Rococo bridge pallet.
|
||||
#[codec(index = 43)]
|
||||
BridgeRococoGrandpa(BridgeRococoGrandpaCall),
|
||||
|
||||
/// Wococo parachain bridge pallet.
|
||||
#[codec(index = 42)]
|
||||
BridgeWococoParachain(BridgeParachainCall),
|
||||
/// Rococo parachain bridge pallet.
|
||||
#[codec(index = 44)]
|
||||
BridgeRococoParachain(BridgeParachainCall),
|
||||
|
||||
/// Wococo messages bridge pallet.
|
||||
#[codec(index = 46)]
|
||||
BridgeWococoMessages(BridgeWococoMessagesCall),
|
||||
/// Rococo messages bridge pallet.
|
||||
#[codec(index = 45)]
|
||||
BridgeRococoMessages(BridgeRococoMessagesCall),
|
||||
}
|
||||
|
||||
#[derive(Encode, Decode, Debug, PartialEq, Eq, Clone, TypeInfo)]
|
||||
#[allow(non_camel_case_types)]
|
||||
pub enum SystemCall {
|
||||
#[codec(index = 1)]
|
||||
remark(Vec<u8>),
|
||||
}
|
||||
|
||||
#[derive(Encode, Decode, Debug, PartialEq, Eq, Clone, TypeInfo)]
|
||||
#[allow(non_camel_case_types)]
|
||||
pub enum BridgeWococoGrandpaCall {
|
||||
#[codec(index = 0)]
|
||||
submit_finality_proof(
|
||||
Box<<PolkadotLike as Chain>::Header>,
|
||||
bp_header_chain::justification::GrandpaJustification<<PolkadotLike as Chain>::Header>,
|
||||
),
|
||||
#[codec(index = 1)]
|
||||
initialize(bp_header_chain::InitializationData<<PolkadotLike as Chain>::Header>),
|
||||
}
|
||||
|
||||
#[derive(Encode, Decode, Debug, PartialEq, Eq, Clone, TypeInfo)]
|
||||
#[allow(non_camel_case_types)]
|
||||
pub enum BridgeRococoGrandpaCall {
|
||||
#[codec(index = 0)]
|
||||
submit_finality_proof(
|
||||
Box<<PolkadotLike as Chain>::Header>,
|
||||
bp_header_chain::justification::GrandpaJustification<<PolkadotLike as Chain>::Header>,
|
||||
),
|
||||
#[codec(index = 1)]
|
||||
initialize(bp_header_chain::InitializationData<<PolkadotLike as Chain>::Header>),
|
||||
}
|
||||
|
||||
pub type RelayBlockHash = bp_polkadot_core::Hash;
|
||||
pub type RelayBlockNumber = bp_polkadot_core::BlockNumber;
|
||||
|
||||
#[derive(Encode, Decode, Debug, PartialEq, Eq, Clone, TypeInfo)]
|
||||
#[allow(non_camel_case_types)]
|
||||
pub enum BridgeParachainCall {
|
||||
#[codec(index = 0)]
|
||||
submit_parachain_heads(
|
||||
(RelayBlockNumber, RelayBlockHash),
|
||||
Vec<(ParaId, ParaHash)>,
|
||||
ParaHeadsProof,
|
||||
),
|
||||
}
|
||||
|
||||
#[derive(Encode, Decode, Debug, PartialEq, Eq, Clone, TypeInfo)]
|
||||
#[allow(non_camel_case_types)]
|
||||
pub enum BridgeWococoMessagesCall {
|
||||
#[codec(index = 2)]
|
||||
receive_messages_proof(
|
||||
relay_substrate_client::AccountIdOf<bp_bridge_hub_wococo::BridgeHubWococo>,
|
||||
bridge_runtime_common::messages::target::FromBridgedChainMessagesProof<
|
||||
relay_substrate_client::HashOf<bp_bridge_hub_wococo::BridgeHubWococo>,
|
||||
>,
|
||||
u32,
|
||||
bp_messages::Weight,
|
||||
),
|
||||
|
||||
#[codec(index = 3)]
|
||||
receive_messages_delivery_proof(
|
||||
bridge_runtime_common::messages::source::FromBridgedChainMessagesDeliveryProof<
|
||||
relay_substrate_client::HashOf<bp_bridge_hub_wococo::BridgeHubWococo>,
|
||||
>,
|
||||
UnrewardedRelayersState,
|
||||
),
|
||||
}
|
||||
|
||||
#[derive(Encode, Decode, Debug, PartialEq, Eq, Clone, TypeInfo)]
|
||||
#[allow(non_camel_case_types)]
|
||||
pub enum BridgeRococoMessagesCall {
|
||||
#[codec(index = 2)]
|
||||
receive_messages_proof(
|
||||
relay_substrate_client::AccountIdOf<bp_bridge_hub_rococo::BridgeHubRococo>,
|
||||
bridge_runtime_common::messages::target::FromBridgedChainMessagesProof<
|
||||
relay_substrate_client::HashOf<bp_bridge_hub_rococo::BridgeHubRococo>,
|
||||
>,
|
||||
u32,
|
||||
bp_messages::Weight,
|
||||
),
|
||||
|
||||
#[codec(index = 3)]
|
||||
receive_messages_delivery_proof(
|
||||
bridge_runtime_common::messages::source::FromBridgedChainMessagesDeliveryProof<
|
||||
relay_substrate_client::HashOf<bp_bridge_hub_rococo::BridgeHubRococo>,
|
||||
>,
|
||||
UnrewardedRelayersState,
|
||||
),
|
||||
}
|
||||
|
||||
impl sp_runtime::traits::Dispatchable for Call {
|
||||
type RuntimeOrigin = ();
|
||||
type Config = ();
|
||||
type Info = ();
|
||||
type PostInfo = ();
|
||||
|
||||
fn dispatch(
|
||||
self,
|
||||
_origin: Self::RuntimeOrigin,
|
||||
) -> sp_runtime::DispatchResultWithInfo<Self::PostInfo> {
|
||||
unimplemented!("The Call is not expected to be dispatched.")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use bp_runtime::BasicOperatingMode;
|
||||
use sp_core::hexdisplay::HexDisplay;
|
||||
use sp_finality_grandpa::AuthorityList;
|
||||
use sp_runtime::traits::Header;
|
||||
use std::str::FromStr;
|
||||
|
||||
pub type RelayBlockHasher = bp_polkadot_core::Hasher;
|
||||
pub type RelayBlockHeader = sp_runtime::generic::Header<RelayBlockNumber, RelayBlockHasher>;
|
||||
|
||||
#[test]
|
||||
fn encode_decode_calls() {
|
||||
let header = RelayBlockHeader::new(
|
||||
75,
|
||||
bp_polkadot_core::Hash::from_str(
|
||||
"0xd2c0afaab32de0cb8f7f0d89217e37c5ea302c1ffb5a7a83e10d20f12c32874d",
|
||||
)
|
||||
.expect("invalid value"),
|
||||
bp_polkadot_core::Hash::from_str(
|
||||
"0x92b965f0656a4e0e5fc0167da2d4b5ee72b3be2c1583c4c1e5236c8c12aa141b",
|
||||
)
|
||||
.expect("invalid value"),
|
||||
bp_polkadot_core::Hash::from_str(
|
||||
"0xae4a25acf250d72ed02c149ecc7dd3c9ee976d41a2888fc551de8064521dc01d",
|
||||
)
|
||||
.expect("invalid value"),
|
||||
Default::default(),
|
||||
);
|
||||
let init_data = bp_header_chain::InitializationData {
|
||||
header: Box::new(header),
|
||||
authority_list: AuthorityList::default(),
|
||||
set_id: 6,
|
||||
operating_mode: BasicOperatingMode::Normal,
|
||||
};
|
||||
let call = BridgeRococoGrandpaCall::initialize(init_data);
|
||||
let tx = Call::BridgeRococoGrandpa(call);
|
||||
|
||||
// encode call as hex string
|
||||
let hex_encoded_call = format!("0x{:?}", HexDisplay::from(&Encode::encode(&tx)));
|
||||
assert_eq!(hex_encoded_call, "0x2b01ae4a25acf250d72ed02c149ecc7dd3c9ee976d41a2888fc551de8064521dc01d2d0192b965f0656a4e0e5fc0167da2d4b5ee72b3be2c1583c4c1e5236c8c12aa141bd2c0afaab32de0cb8f7f0d89217e37c5ea302c1ffb5a7a83e10d20f12c32874d0000060000000000000000");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "relay-bridge-hub-wococo-client"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
codec = { package = "parity-scale-codec", version = "3.1.5", features = ["derive"] }
|
||||
scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }
|
||||
relay-substrate-client = { path = "../client-substrate" }
|
||||
|
||||
# Bridge dependencies
|
||||
|
||||
bp-bridge-hub-wococo = { path = "../../primitives/chain-bridge-hub-wococo" }
|
||||
bp-messages = { path = "../../primitives/messages" }
|
||||
relay-bridge-hub-rococo-client = { path = "../client-bridge-hub-rococo" }
|
||||
|
||||
# Substrate Dependencies
|
||||
|
||||
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
@@ -0,0 +1,171 @@
|
||||
// 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/>.
|
||||
|
||||
//! Types used to connect to the BridgeHub-Wococo-Substrate parachain.
|
||||
|
||||
use bp_messages::{MessageNonce, Weight};
|
||||
use codec::Encode;
|
||||
use relay_substrate_client::{
|
||||
Chain, ChainBase, ChainWithBalances, ChainWithMessages, ChainWithTransactions,
|
||||
Error as SubstrateError, SignParam, UnsignedTransaction,
|
||||
};
|
||||
use sp_core::{storage::StorageKey, Pair};
|
||||
use sp_runtime::{generic::SignedPayload, traits::IdentifyAccount};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Re-export runtime wrapper
|
||||
pub mod runtime_wrapper;
|
||||
pub use runtime_wrapper as runtime;
|
||||
|
||||
/// Wococo chain definition
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct BridgeHubWococo;
|
||||
|
||||
impl ChainBase for BridgeHubWococo {
|
||||
type BlockNumber = bp_bridge_hub_wococo::BlockNumber;
|
||||
type Hash = bp_bridge_hub_wococo::Hash;
|
||||
type Hasher = bp_bridge_hub_wococo::Hashing;
|
||||
type Header = bp_bridge_hub_wococo::Header;
|
||||
|
||||
type AccountId = bp_bridge_hub_wococo::AccountId;
|
||||
type Balance = bp_bridge_hub_wococo::Balance;
|
||||
type Index = bp_bridge_hub_wococo::Nonce;
|
||||
type Signature = bp_bridge_hub_wococo::Signature;
|
||||
|
||||
fn max_extrinsic_size() -> u32 {
|
||||
bp_bridge_hub_wococo::BridgeHubWococo::max_extrinsic_size()
|
||||
}
|
||||
|
||||
fn max_extrinsic_weight() -> Weight {
|
||||
bp_bridge_hub_wococo::BridgeHubWococo::max_extrinsic_weight()
|
||||
}
|
||||
}
|
||||
|
||||
impl Chain for BridgeHubWococo {
|
||||
const NAME: &'static str = "BridgeHubWococo";
|
||||
const TOKEN_ID: Option<&'static str> = None;
|
||||
const BEST_FINALIZED_HEADER_ID_METHOD: &'static str =
|
||||
bp_bridge_hub_wococo::BEST_FINALIZED_BRIDGE_HUB_WOCOCO_HEADER_METHOD;
|
||||
const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_secs(6);
|
||||
|
||||
type SignedBlock = bp_bridge_hub_wococo::SignedBlock;
|
||||
type Call = runtime::Call;
|
||||
}
|
||||
|
||||
impl ChainWithBalances for BridgeHubWococo {
|
||||
fn account_info_storage_key(account_id: &Self::AccountId) -> StorageKey {
|
||||
bp_bridge_hub_wococo::AccountInfoStorageMapKeyProvider::final_key(account_id)
|
||||
}
|
||||
}
|
||||
|
||||
impl ChainWithTransactions for BridgeHubWococo {
|
||||
type AccountKeyPair = sp_core::sr25519::Pair;
|
||||
type SignedTransaction = runtime::UncheckedExtrinsic;
|
||||
|
||||
fn sign_transaction(
|
||||
param: SignParam<Self>,
|
||||
unsigned: UnsignedTransaction<Self>,
|
||||
) -> Result<Self::SignedTransaction, SubstrateError> {
|
||||
let raw_payload = SignedPayload::new(
|
||||
unsigned.call,
|
||||
bp_bridge_hub_wococo::SignedExtensions::new(
|
||||
param.spec_version,
|
||||
param.transaction_version,
|
||||
unsigned.era,
|
||||
param.genesis_hash,
|
||||
unsigned.nonce,
|
||||
unsigned.tip,
|
||||
),
|
||||
)?;
|
||||
|
||||
let signature = raw_payload.using_encoded(|payload| param.signer.sign(payload));
|
||||
let signer: sp_runtime::MultiSigner = param.signer.public().into();
|
||||
let (call, extra, _) = raw_payload.deconstruct();
|
||||
|
||||
Ok(bp_bridge_hub_wococo::UncheckedExtrinsic::new_signed(
|
||||
call,
|
||||
signer.into_account().into(),
|
||||
signature.into(),
|
||||
extra,
|
||||
))
|
||||
}
|
||||
|
||||
fn is_signed(tx: &Self::SignedTransaction) -> bool {
|
||||
tx.signature.is_some()
|
||||
}
|
||||
|
||||
fn is_signed_by(signer: &Self::AccountKeyPair, tx: &Self::SignedTransaction) -> bool {
|
||||
tx.signature
|
||||
.as_ref()
|
||||
.map(|(address, _, _)| {
|
||||
*address == bp_bridge_hub_wococo::Address::Id(signer.public().into())
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn parse_transaction(tx: Self::SignedTransaction) -> Option<UnsignedTransaction<Self>> {
|
||||
let extra = &tx.signature.as_ref()?.2;
|
||||
Some(UnsignedTransaction::new(tx.function, extra.nonce()).tip(extra.tip()))
|
||||
}
|
||||
}
|
||||
|
||||
impl ChainWithMessages for BridgeHubWococo {
|
||||
const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str =
|
||||
bp_bridge_hub_wococo::WITH_BRIDGE_HUB_WOCOCO_MESSAGES_PALLET_NAME;
|
||||
|
||||
const TO_CHAIN_MESSAGE_DETAILS_METHOD: &'static str =
|
||||
bp_bridge_hub_wococo::TO_BRIDGE_HUB_WOCOCO_MESSAGE_DETAILS_METHOD;
|
||||
const FROM_CHAIN_MESSAGE_DETAILS_METHOD: &'static str =
|
||||
bp_bridge_hub_wococo::FROM_BRIDGE_HUB_WOCOCO_MESSAGE_DETAILS_METHOD;
|
||||
|
||||
const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce =
|
||||
bp_bridge_hub_wococo::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX;
|
||||
const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce =
|
||||
bp_bridge_hub_wococo::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX;
|
||||
|
||||
type WeightToFee = bp_bridge_hub_wococo::WeightToFee;
|
||||
// TODO: fix (https://github.com/paritytech/parity-bridges-common/issues/1640)
|
||||
type WeightInfo = ();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use relay_substrate_client::TransactionEra;
|
||||
|
||||
#[test]
|
||||
fn parse_transaction_works() {
|
||||
let unsigned = UnsignedTransaction {
|
||||
call: runtime::Call::System(runtime::SystemCall::remark(b"Hello world!".to_vec()))
|
||||
.into(),
|
||||
nonce: 777,
|
||||
tip: 888,
|
||||
era: TransactionEra::immortal(),
|
||||
};
|
||||
let signed_transaction = BridgeHubWococo::sign_transaction(
|
||||
SignParam {
|
||||
spec_version: 42,
|
||||
transaction_version: 50000,
|
||||
genesis_hash: [42u8; 32].into(),
|
||||
signer: sp_core::sr25519::Pair::from_seed_slice(&[1u8; 32]).unwrap(),
|
||||
},
|
||||
unsigned.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
let parsed_transaction = BridgeHubWococo::parse_transaction(signed_transaction).unwrap();
|
||||
assert_eq!(parsed_transaction, unsigned);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// 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/>.
|
||||
|
||||
//! Types that are specific to the BridgeHubWococo runtime.
|
||||
|
||||
pub use bp_bridge_hub_wococo::SS58Prefix;
|
||||
|
||||
// We reuse everything from rococo runtime wrapper
|
||||
pub type Call = relay_bridge_hub_rococo_client::runtime::Call;
|
||||
pub type UncheckedExtrinsic = bp_bridge_hub_wococo::UncheckedExtrinsic<Call>;
|
||||
pub type BridgeGrandpaRococoCall = relay_bridge_hub_rococo_client::runtime::BridgeRococoGrandpaCall;
|
||||
pub type BridgeParachainCall = relay_bridge_hub_rococo_client::runtime::BridgeParachainCall;
|
||||
pub type BridgeRococoMessagesCall =
|
||||
relay_bridge_hub_rococo_client::runtime::BridgeRococoMessagesCall;
|
||||
pub type SystemCall = relay_bridge_hub_rococo_client::runtime::SystemCall;
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "relay-kusama-client"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
relay-substrate-client = { path = "../client-substrate" }
|
||||
relay-utils = { path = "../utils" }
|
||||
|
||||
# Bridge dependencies
|
||||
|
||||
bp-kusama = { path = "../../primitives/chain-kusama" }
|
||||
|
||||
# Substrate Dependencies
|
||||
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
@@ -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/>.
|
||||
|
||||
//! Types used to connect to the Kusama chain.
|
||||
|
||||
use bp_kusama::AccountInfoStorageMapKeyProvider;
|
||||
use frame_support::weights::Weight;
|
||||
use relay_substrate_client::{Chain, ChainBase, ChainWithBalances, ChainWithGrandpa};
|
||||
use sp_core::storage::StorageKey;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Kusama header id.
|
||||
pub type HeaderId = relay_utils::HeaderId<bp_kusama::Hash, bp_kusama::BlockNumber>;
|
||||
|
||||
/// Kusama chain definition
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Kusama;
|
||||
|
||||
impl ChainBase for Kusama {
|
||||
type BlockNumber = bp_kusama::BlockNumber;
|
||||
type Hash = bp_kusama::Hash;
|
||||
type Hasher = bp_kusama::Hasher;
|
||||
type Header = bp_kusama::Header;
|
||||
|
||||
type AccountId = bp_kusama::AccountId;
|
||||
type Balance = bp_kusama::Balance;
|
||||
type Index = bp_kusama::Nonce;
|
||||
type Signature = bp_kusama::Signature;
|
||||
|
||||
fn max_extrinsic_size() -> u32 {
|
||||
bp_kusama::Kusama::max_extrinsic_size()
|
||||
}
|
||||
|
||||
fn max_extrinsic_weight() -> Weight {
|
||||
bp_kusama::Kusama::max_extrinsic_weight()
|
||||
}
|
||||
}
|
||||
|
||||
impl Chain for Kusama {
|
||||
const NAME: &'static str = "Kusama";
|
||||
const TOKEN_ID: Option<&'static str> = Some("kusama");
|
||||
const BEST_FINALIZED_HEADER_ID_METHOD: &'static str =
|
||||
bp_kusama::BEST_FINALIZED_KUSAMA_HEADER_METHOD;
|
||||
const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_secs(6);
|
||||
|
||||
type SignedBlock = bp_kusama::SignedBlock;
|
||||
type Call = ();
|
||||
}
|
||||
|
||||
impl ChainWithGrandpa for Kusama {
|
||||
const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str = bp_kusama::WITH_KUSAMA_GRANDPA_PALLET_NAME;
|
||||
}
|
||||
|
||||
impl ChainWithBalances for Kusama {
|
||||
fn account_info_storage_key(account_id: &Self::AccountId) -> StorageKey {
|
||||
AccountInfoStorageMapKeyProvider::final_key(account_id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Kusama header type used in headers sync.
|
||||
pub type SyncHeader = relay_substrate_client::SyncHeader<bp_kusama::Header>;
|
||||
@@ -0,0 +1,25 @@
|
||||
[package]
|
||||
name = "relay-millau-client"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
codec = { package = "parity-scale-codec", version = "3.1.5" }
|
||||
relay-substrate-client = { path = "../client-substrate" }
|
||||
relay-utils = { path = "../utils" }
|
||||
|
||||
# Supported Chains
|
||||
|
||||
bp-messages = { path = "../../primitives/messages" }
|
||||
bp-millau = { path = "../../primitives/chain-millau" }
|
||||
millau-runtime = { path = "../../bin/millau/runtime" }
|
||||
|
||||
# Substrate Dependencies
|
||||
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
frame-system = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
pallet-transaction-payment = { 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" }
|
||||
@@ -0,0 +1,202 @@
|
||||
// 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/>.
|
||||
|
||||
//! Types used to connect to the Millau-Substrate chain.
|
||||
|
||||
use bp_messages::MessageNonce;
|
||||
use codec::{Compact, Decode, Encode};
|
||||
use frame_support::weights::Weight;
|
||||
use relay_substrate_client::{
|
||||
BalanceOf, Chain, ChainBase, ChainWithBalances, ChainWithGrandpa, ChainWithMessages,
|
||||
ChainWithTransactions, Error as SubstrateError, IndexOf, SignParam, UnsignedTransaction,
|
||||
};
|
||||
use sp_core::{storage::StorageKey, Pair};
|
||||
use sp_runtime::{generic::SignedPayload, traits::IdentifyAccount};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Millau header id.
|
||||
pub type HeaderId = relay_utils::HeaderId<millau_runtime::Hash, millau_runtime::BlockNumber>;
|
||||
|
||||
/// Millau chain definition.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Millau;
|
||||
|
||||
impl ChainBase for Millau {
|
||||
type BlockNumber = millau_runtime::BlockNumber;
|
||||
type Hash = millau_runtime::Hash;
|
||||
type Hasher = millau_runtime::Hashing;
|
||||
type Header = millau_runtime::Header;
|
||||
|
||||
type AccountId = millau_runtime::AccountId;
|
||||
type Balance = millau_runtime::Balance;
|
||||
type Index = millau_runtime::Index;
|
||||
type Signature = millau_runtime::Signature;
|
||||
|
||||
fn max_extrinsic_size() -> u32 {
|
||||
bp_millau::Millau::max_extrinsic_size()
|
||||
}
|
||||
|
||||
fn max_extrinsic_weight() -> Weight {
|
||||
bp_millau::Millau::max_extrinsic_weight()
|
||||
}
|
||||
}
|
||||
|
||||
impl ChainWithGrandpa for Millau {
|
||||
const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str = bp_millau::WITH_MILLAU_GRANDPA_PALLET_NAME;
|
||||
}
|
||||
|
||||
impl ChainWithMessages for Millau {
|
||||
const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str =
|
||||
bp_millau::WITH_MILLAU_MESSAGES_PALLET_NAME;
|
||||
const TO_CHAIN_MESSAGE_DETAILS_METHOD: &'static str =
|
||||
bp_millau::TO_MILLAU_MESSAGE_DETAILS_METHOD;
|
||||
const FROM_CHAIN_MESSAGE_DETAILS_METHOD: &'static str =
|
||||
bp_millau::FROM_MILLAU_MESSAGE_DETAILS_METHOD;
|
||||
const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce =
|
||||
bp_millau::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX;
|
||||
const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce =
|
||||
bp_millau::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX;
|
||||
type WeightToFee = bp_millau::WeightToFee;
|
||||
type WeightInfo = ();
|
||||
}
|
||||
|
||||
impl Chain for Millau {
|
||||
const NAME: &'static str = "Millau";
|
||||
// Rialto token has no value, but we associate it with KSM token
|
||||
const TOKEN_ID: Option<&'static str> = Some("kusama");
|
||||
const BEST_FINALIZED_HEADER_ID_METHOD: &'static str =
|
||||
bp_millau::BEST_FINALIZED_MILLAU_HEADER_METHOD;
|
||||
const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_secs(5);
|
||||
|
||||
type SignedBlock = millau_runtime::SignedBlock;
|
||||
type Call = millau_runtime::RuntimeCall;
|
||||
}
|
||||
|
||||
impl ChainWithBalances for Millau {
|
||||
fn account_info_storage_key(account_id: &Self::AccountId) -> StorageKey {
|
||||
use frame_support::storage::generator::StorageMap;
|
||||
StorageKey(frame_system::Account::<millau_runtime::Runtime>::storage_map_final_key(
|
||||
account_id,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl ChainWithTransactions for Millau {
|
||||
type AccountKeyPair = sp_core::sr25519::Pair;
|
||||
type SignedTransaction = millau_runtime::UncheckedExtrinsic;
|
||||
|
||||
fn sign_transaction(
|
||||
param: SignParam<Self>,
|
||||
unsigned: UnsignedTransaction<Self>,
|
||||
) -> Result<Self::SignedTransaction, SubstrateError> {
|
||||
let raw_payload = SignedPayload::from_raw(
|
||||
unsigned.call.clone(),
|
||||
(
|
||||
frame_system::CheckNonZeroSender::<millau_runtime::Runtime>::new(),
|
||||
frame_system::CheckSpecVersion::<millau_runtime::Runtime>::new(),
|
||||
frame_system::CheckTxVersion::<millau_runtime::Runtime>::new(),
|
||||
frame_system::CheckGenesis::<millau_runtime::Runtime>::new(),
|
||||
frame_system::CheckEra::<millau_runtime::Runtime>::from(unsigned.era.frame_era()),
|
||||
frame_system::CheckNonce::<millau_runtime::Runtime>::from(unsigned.nonce),
|
||||
frame_system::CheckWeight::<millau_runtime::Runtime>::new(),
|
||||
pallet_transaction_payment::ChargeTransactionPayment::<millau_runtime::Runtime>::from(unsigned.tip),
|
||||
millau_runtime::BridgeRejectObsoleteHeadersAndMessages,
|
||||
),
|
||||
(
|
||||
(),
|
||||
param.spec_version,
|
||||
param.transaction_version,
|
||||
param.genesis_hash,
|
||||
unsigned.era.signed_payload(param.genesis_hash),
|
||||
(),
|
||||
(),
|
||||
(),
|
||||
(),
|
||||
),
|
||||
);
|
||||
let signature = raw_payload.using_encoded(|payload| param.signer.sign(payload));
|
||||
let signer: sp_runtime::MultiSigner = param.signer.public().into();
|
||||
let (call, extra, _) = raw_payload.deconstruct();
|
||||
|
||||
Ok(millau_runtime::UncheckedExtrinsic::new_signed(
|
||||
call.into_decoded()?,
|
||||
signer.into_account(),
|
||||
signature.into(),
|
||||
extra,
|
||||
))
|
||||
}
|
||||
|
||||
fn is_signed(tx: &Self::SignedTransaction) -> bool {
|
||||
tx.signature.is_some()
|
||||
}
|
||||
|
||||
fn is_signed_by(signer: &Self::AccountKeyPair, tx: &Self::SignedTransaction) -> bool {
|
||||
tx.signature
|
||||
.as_ref()
|
||||
.map(|(address, _, _)| {
|
||||
*address == millau_runtime::Address::from(*signer.public().as_array_ref())
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn parse_transaction(tx: Self::SignedTransaction) -> Option<UnsignedTransaction<Self>> {
|
||||
let extra = &tx.signature.as_ref()?.2;
|
||||
Some(
|
||||
UnsignedTransaction::new(
|
||||
tx.function.into(),
|
||||
Compact::<IndexOf<Self>>::decode(&mut &extra.5.encode()[..]).ok()?.into(),
|
||||
)
|
||||
.tip(Compact::<BalanceOf<Self>>::decode(&mut &extra.7.encode()[..]).ok()?.into()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Millau signing params.
|
||||
pub type SigningParams = sp_core::sr25519::Pair;
|
||||
|
||||
/// Millau header type used in headers sync.
|
||||
pub type SyncHeader = relay_substrate_client::SyncHeader<millau_runtime::Header>;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use relay_substrate_client::TransactionEra;
|
||||
|
||||
#[test]
|
||||
fn parse_transaction_works() {
|
||||
let unsigned = UnsignedTransaction {
|
||||
call: millau_runtime::RuntimeCall::System(millau_runtime::SystemCall::remark {
|
||||
remark: b"Hello world!".to_vec(),
|
||||
})
|
||||
.into(),
|
||||
nonce: 777,
|
||||
tip: 888,
|
||||
era: TransactionEra::immortal(),
|
||||
};
|
||||
let signed_transaction = Millau::sign_transaction(
|
||||
SignParam {
|
||||
spec_version: 42,
|
||||
transaction_version: 50000,
|
||||
genesis_hash: [42u8; 64].into(),
|
||||
signer: sp_core::sr25519::Pair::from_seed_slice(&[1u8; 32]).unwrap(),
|
||||
},
|
||||
unsigned.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
let parsed_transaction = Millau::parse_transaction(signed_transaction).unwrap();
|
||||
assert_eq!(parsed_transaction, unsigned);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "relay-polkadot-client"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
relay-substrate-client = { path = "../client-substrate" }
|
||||
relay-utils = { path = "../utils" }
|
||||
|
||||
# Bridge dependencies
|
||||
|
||||
bp-polkadot = { path = "../../primitives/chain-polkadot" }
|
||||
|
||||
# Substrate Dependencies
|
||||
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
@@ -0,0 +1,75 @@
|
||||
// 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/>.
|
||||
|
||||
//! Types used to connect to the Polkadot chain.
|
||||
|
||||
use bp_polkadot::AccountInfoStorageMapKeyProvider;
|
||||
use frame_support::weights::Weight;
|
||||
use relay_substrate_client::{Chain, ChainBase, ChainWithBalances, ChainWithGrandpa};
|
||||
use sp_core::storage::StorageKey;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Polkadot header id.
|
||||
pub type HeaderId = relay_utils::HeaderId<bp_polkadot::Hash, bp_polkadot::BlockNumber>;
|
||||
|
||||
/// Polkadot chain definition
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Polkadot;
|
||||
|
||||
impl ChainBase for Polkadot {
|
||||
type BlockNumber = bp_polkadot::BlockNumber;
|
||||
type Hash = bp_polkadot::Hash;
|
||||
type Hasher = bp_polkadot::Hasher;
|
||||
type Header = bp_polkadot::Header;
|
||||
|
||||
type AccountId = bp_polkadot::AccountId;
|
||||
type Balance = bp_polkadot::Balance;
|
||||
type Index = bp_polkadot::Nonce;
|
||||
type Signature = bp_polkadot::Signature;
|
||||
|
||||
fn max_extrinsic_size() -> u32 {
|
||||
bp_polkadot::Polkadot::max_extrinsic_size()
|
||||
}
|
||||
|
||||
fn max_extrinsic_weight() -> Weight {
|
||||
bp_polkadot::Polkadot::max_extrinsic_weight()
|
||||
}
|
||||
}
|
||||
|
||||
impl Chain for Polkadot {
|
||||
const NAME: &'static str = "Polkadot";
|
||||
const TOKEN_ID: Option<&'static str> = Some("polkadot");
|
||||
const BEST_FINALIZED_HEADER_ID_METHOD: &'static str =
|
||||
bp_polkadot::BEST_FINALIZED_POLKADOT_HEADER_METHOD;
|
||||
const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_secs(6);
|
||||
|
||||
type SignedBlock = bp_polkadot::SignedBlock;
|
||||
type Call = ();
|
||||
}
|
||||
|
||||
impl ChainWithGrandpa for Polkadot {
|
||||
const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str =
|
||||
bp_polkadot::WITH_POLKADOT_GRANDPA_PALLET_NAME;
|
||||
}
|
||||
|
||||
impl ChainWithBalances for Polkadot {
|
||||
fn account_info_storage_key(account_id: &Self::AccountId) -> StorageKey {
|
||||
AccountInfoStorageMapKeyProvider::final_key(account_id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Polkadot header type used in headers sync.
|
||||
pub type SyncHeader = relay_substrate_client::SyncHeader<bp_polkadot::Header>;
|
||||
@@ -0,0 +1,25 @@
|
||||
[package]
|
||||
name = "relay-rialto-parachain-client"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
codec = { package = "parity-scale-codec", version = "3.1.5" }
|
||||
relay-substrate-client = { path = "../client-substrate" }
|
||||
relay-utils = { path = "../utils" }
|
||||
|
||||
# Bridge dependencies
|
||||
|
||||
bp-messages = { path = "../../primitives/messages" }
|
||||
bp-rialto-parachain = { path = "../../primitives/chain-rialto-parachain" }
|
||||
rialto-parachain-runtime = { path = "../../bin/rialto-parachain/runtime" }
|
||||
|
||||
# Substrate Dependencies
|
||||
|
||||
frame-system = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
pallet-transaction-payment = { 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" }
|
||||
@@ -0,0 +1,165 @@
|
||||
// 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/>.
|
||||
|
||||
//! Types used to connect to the Rialto-Substrate chain.
|
||||
|
||||
use bp_messages::MessageNonce;
|
||||
use codec::Encode;
|
||||
use frame_support::weights::Weight;
|
||||
use relay_substrate_client::{
|
||||
Chain, ChainBase, ChainWithBalances, ChainWithMessages, ChainWithTransactions,
|
||||
Error as SubstrateError, SignParam, UnsignedTransaction,
|
||||
};
|
||||
use sp_core::{storage::StorageKey, Pair};
|
||||
use sp_runtime::{generic::SignedPayload, traits::IdentifyAccount};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Rialto header id.
|
||||
pub type HeaderId =
|
||||
relay_utils::HeaderId<rialto_parachain_runtime::Hash, rialto_parachain_runtime::BlockNumber>;
|
||||
|
||||
/// Rialto parachain definition
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct RialtoParachain;
|
||||
|
||||
impl ChainBase for RialtoParachain {
|
||||
type BlockNumber = rialto_parachain_runtime::BlockNumber;
|
||||
type Hash = rialto_parachain_runtime::Hash;
|
||||
type Hasher = rialto_parachain_runtime::Hashing;
|
||||
type Header = rialto_parachain_runtime::Header;
|
||||
|
||||
type AccountId = rialto_parachain_runtime::AccountId;
|
||||
type Balance = rialto_parachain_runtime::Balance;
|
||||
type Index = rialto_parachain_runtime::Index;
|
||||
type Signature = rialto_parachain_runtime::Signature;
|
||||
|
||||
fn max_extrinsic_size() -> u32 {
|
||||
bp_rialto_parachain::RialtoParachain::max_extrinsic_size()
|
||||
}
|
||||
|
||||
fn max_extrinsic_weight() -> Weight {
|
||||
bp_rialto_parachain::RialtoParachain::max_extrinsic_weight()
|
||||
}
|
||||
}
|
||||
|
||||
impl Chain for RialtoParachain {
|
||||
const NAME: &'static str = "RialtoParachain";
|
||||
// RialtoParachain token has no value, but we associate it with DOT token
|
||||
const TOKEN_ID: Option<&'static str> = Some("polkadot");
|
||||
const BEST_FINALIZED_HEADER_ID_METHOD: &'static str =
|
||||
bp_rialto_parachain::BEST_FINALIZED_RIALTO_PARACHAIN_HEADER_METHOD;
|
||||
const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_secs(5);
|
||||
|
||||
type SignedBlock = rialto_parachain_runtime::SignedBlock;
|
||||
type Call = rialto_parachain_runtime::RuntimeCall;
|
||||
}
|
||||
|
||||
impl ChainWithBalances for RialtoParachain {
|
||||
fn account_info_storage_key(account_id: &Self::AccountId) -> StorageKey {
|
||||
use frame_support::storage::generator::StorageMap;
|
||||
StorageKey(
|
||||
frame_system::Account::<rialto_parachain_runtime::Runtime>::storage_map_final_key(
|
||||
account_id,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl ChainWithMessages for RialtoParachain {
|
||||
const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str =
|
||||
bp_rialto_parachain::WITH_RIALTO_PARACHAIN_MESSAGES_PALLET_NAME;
|
||||
const TO_CHAIN_MESSAGE_DETAILS_METHOD: &'static str =
|
||||
bp_rialto_parachain::TO_RIALTO_PARACHAIN_MESSAGE_DETAILS_METHOD;
|
||||
const FROM_CHAIN_MESSAGE_DETAILS_METHOD: &'static str =
|
||||
bp_rialto_parachain::FROM_RIALTO_PARACHAIN_MESSAGE_DETAILS_METHOD;
|
||||
const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce =
|
||||
bp_rialto_parachain::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX;
|
||||
const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce =
|
||||
bp_rialto_parachain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX;
|
||||
type WeightToFee = bp_rialto_parachain::WeightToFee;
|
||||
type WeightInfo = ();
|
||||
}
|
||||
|
||||
impl ChainWithTransactions for RialtoParachain {
|
||||
type AccountKeyPair = sp_core::sr25519::Pair;
|
||||
type SignedTransaction = rialto_parachain_runtime::UncheckedExtrinsic;
|
||||
|
||||
fn sign_transaction(
|
||||
param: SignParam<Self>,
|
||||
unsigned: UnsignedTransaction<Self>,
|
||||
) -> Result<Self::SignedTransaction, SubstrateError> {
|
||||
let raw_payload = SignedPayload::from_raw(
|
||||
unsigned.call,
|
||||
(
|
||||
frame_system::CheckNonZeroSender::<rialto_parachain_runtime::Runtime>::new(),
|
||||
frame_system::CheckSpecVersion::<rialto_parachain_runtime::Runtime>::new(),
|
||||
frame_system::CheckTxVersion::<rialto_parachain_runtime::Runtime>::new(),
|
||||
frame_system::CheckGenesis::<rialto_parachain_runtime::Runtime>::new(),
|
||||
frame_system::CheckEra::<rialto_parachain_runtime::Runtime>::from(
|
||||
unsigned.era.frame_era(),
|
||||
),
|
||||
frame_system::CheckNonce::<rialto_parachain_runtime::Runtime>::from(unsigned.nonce),
|
||||
frame_system::CheckWeight::<rialto_parachain_runtime::Runtime>::new(),
|
||||
pallet_transaction_payment::ChargeTransactionPayment::<
|
||||
rialto_parachain_runtime::Runtime,
|
||||
>::from(unsigned.tip),
|
||||
),
|
||||
(
|
||||
(),
|
||||
param.spec_version,
|
||||
param.transaction_version,
|
||||
param.genesis_hash,
|
||||
unsigned.era.signed_payload(param.genesis_hash),
|
||||
(),
|
||||
(),
|
||||
(),
|
||||
),
|
||||
);
|
||||
let signature = raw_payload.using_encoded(|payload| param.signer.sign(payload));
|
||||
let signer: sp_runtime::MultiSigner = param.signer.public().into();
|
||||
let (call, extra, _) = raw_payload.deconstruct();
|
||||
|
||||
Ok(rialto_parachain_runtime::UncheckedExtrinsic::new_signed(
|
||||
call.into_decoded()?,
|
||||
signer.into_account().into(),
|
||||
signature.into(),
|
||||
extra,
|
||||
))
|
||||
}
|
||||
|
||||
fn is_signed(tx: &Self::SignedTransaction) -> bool {
|
||||
tx.signature.is_some()
|
||||
}
|
||||
|
||||
fn is_signed_by(signer: &Self::AccountKeyPair, tx: &Self::SignedTransaction) -> bool {
|
||||
tx.signature
|
||||
.as_ref()
|
||||
.map(|(address, _, _)| {
|
||||
*address == rialto_parachain_runtime::Address::Id(signer.public().into())
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn parse_transaction(_tx: Self::SignedTransaction) -> Option<UnsignedTransaction<Self>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// RialtoParachain signing params.
|
||||
pub type SigningParams = sp_core::sr25519::Pair;
|
||||
|
||||
/// RialtoParachain header type used in headers sync.
|
||||
pub type SyncHeader = relay_substrate_client::SyncHeader<rialto_parachain_runtime::Header>;
|
||||
@@ -0,0 +1,25 @@
|
||||
[package]
|
||||
name = "relay-rialto-client"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
codec = { package = "parity-scale-codec", version = "3.1.5" }
|
||||
relay-substrate-client = { path = "../client-substrate" }
|
||||
relay-utils = { path = "../utils" }
|
||||
|
||||
# Bridge dependencies
|
||||
|
||||
bp-messages = { path = "../../primitives/messages" }
|
||||
bp-rialto = { path = "../../primitives/chain-rialto" }
|
||||
rialto-runtime = { path = "../../bin/rialto/runtime" }
|
||||
|
||||
# Substrate Dependencies
|
||||
|
||||
frame-system = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
pallet-transaction-payment = { 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" }
|
||||
@@ -0,0 +1,205 @@
|
||||
// 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/>.
|
||||
|
||||
//! Types used to connect to the Rialto-Substrate chain.
|
||||
|
||||
use bp_messages::MessageNonce;
|
||||
use codec::{Compact, Decode, Encode};
|
||||
use frame_support::weights::Weight;
|
||||
use relay_substrate_client::{
|
||||
BalanceOf, Chain, ChainBase, ChainWithBalances, ChainWithGrandpa, ChainWithMessages,
|
||||
ChainWithTransactions, Error as SubstrateError, IndexOf, RelayChain, SignParam,
|
||||
UnsignedTransaction,
|
||||
};
|
||||
use sp_core::{storage::StorageKey, Pair};
|
||||
use sp_runtime::{generic::SignedPayload, traits::IdentifyAccount};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Rialto header id.
|
||||
pub type HeaderId = relay_utils::HeaderId<rialto_runtime::Hash, rialto_runtime::BlockNumber>;
|
||||
|
||||
/// Rialto chain definition
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Rialto;
|
||||
|
||||
impl ChainBase for Rialto {
|
||||
type BlockNumber = rialto_runtime::BlockNumber;
|
||||
type Hash = rialto_runtime::Hash;
|
||||
type Hasher = rialto_runtime::Hashing;
|
||||
type Header = rialto_runtime::Header;
|
||||
|
||||
type AccountId = rialto_runtime::AccountId;
|
||||
type Balance = rialto_runtime::Balance;
|
||||
type Index = rialto_runtime::Index;
|
||||
type Signature = rialto_runtime::Signature;
|
||||
|
||||
fn max_extrinsic_size() -> u32 {
|
||||
bp_rialto::Rialto::max_extrinsic_size()
|
||||
}
|
||||
|
||||
fn max_extrinsic_weight() -> Weight {
|
||||
bp_rialto::Rialto::max_extrinsic_weight()
|
||||
}
|
||||
}
|
||||
|
||||
impl Chain for Rialto {
|
||||
const NAME: &'static str = "Rialto";
|
||||
// Rialto token has no value, but we associate it with DOT token
|
||||
const TOKEN_ID: Option<&'static str> = Some("polkadot");
|
||||
const BEST_FINALIZED_HEADER_ID_METHOD: &'static str =
|
||||
bp_rialto::BEST_FINALIZED_RIALTO_HEADER_METHOD;
|
||||
const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_secs(5);
|
||||
|
||||
type SignedBlock = rialto_runtime::SignedBlock;
|
||||
type Call = rialto_runtime::RuntimeCall;
|
||||
}
|
||||
|
||||
impl RelayChain for Rialto {
|
||||
const PARAS_PALLET_NAME: &'static str = bp_rialto::PARAS_PALLET_NAME;
|
||||
const PARACHAINS_FINALITY_PALLET_NAME: &'static str =
|
||||
bp_rialto::WITH_RIALTO_BRIDGE_PARAS_PALLET_NAME;
|
||||
}
|
||||
|
||||
impl ChainWithGrandpa for Rialto {
|
||||
const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str = bp_rialto::WITH_RIALTO_GRANDPA_PALLET_NAME;
|
||||
}
|
||||
|
||||
impl ChainWithMessages for Rialto {
|
||||
const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str =
|
||||
bp_rialto::WITH_RIALTO_MESSAGES_PALLET_NAME;
|
||||
const TO_CHAIN_MESSAGE_DETAILS_METHOD: &'static str =
|
||||
bp_rialto::TO_RIALTO_MESSAGE_DETAILS_METHOD;
|
||||
const FROM_CHAIN_MESSAGE_DETAILS_METHOD: &'static str =
|
||||
bp_rialto::FROM_RIALTO_MESSAGE_DETAILS_METHOD;
|
||||
const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce =
|
||||
bp_rialto::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX;
|
||||
const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce =
|
||||
bp_rialto::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX;
|
||||
type WeightToFee = bp_rialto::WeightToFee;
|
||||
type WeightInfo = ();
|
||||
}
|
||||
|
||||
impl ChainWithBalances for Rialto {
|
||||
fn account_info_storage_key(account_id: &Self::AccountId) -> StorageKey {
|
||||
use frame_support::storage::generator::StorageMap;
|
||||
StorageKey(frame_system::Account::<rialto_runtime::Runtime>::storage_map_final_key(
|
||||
account_id,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl ChainWithTransactions for Rialto {
|
||||
type AccountKeyPair = sp_core::sr25519::Pair;
|
||||
type SignedTransaction = rialto_runtime::UncheckedExtrinsic;
|
||||
|
||||
fn sign_transaction(
|
||||
param: SignParam<Self>,
|
||||
unsigned: UnsignedTransaction<Self>,
|
||||
) -> Result<Self::SignedTransaction, SubstrateError> {
|
||||
let raw_payload = SignedPayload::from_raw(
|
||||
unsigned.call.clone(),
|
||||
(
|
||||
frame_system::CheckNonZeroSender::<rialto_runtime::Runtime>::new(),
|
||||
frame_system::CheckSpecVersion::<rialto_runtime::Runtime>::new(),
|
||||
frame_system::CheckTxVersion::<rialto_runtime::Runtime>::new(),
|
||||
frame_system::CheckGenesis::<rialto_runtime::Runtime>::new(),
|
||||
frame_system::CheckEra::<rialto_runtime::Runtime>::from(unsigned.era.frame_era()),
|
||||
frame_system::CheckNonce::<rialto_runtime::Runtime>::from(unsigned.nonce),
|
||||
frame_system::CheckWeight::<rialto_runtime::Runtime>::new(),
|
||||
pallet_transaction_payment::ChargeTransactionPayment::<rialto_runtime::Runtime>::from(unsigned.tip),
|
||||
),
|
||||
(
|
||||
(),
|
||||
param.spec_version,
|
||||
param.transaction_version,
|
||||
param.genesis_hash,
|
||||
unsigned.era.signed_payload(param.genesis_hash),
|
||||
(),
|
||||
(),
|
||||
(),
|
||||
),
|
||||
);
|
||||
let signature = raw_payload.using_encoded(|payload| param.signer.sign(payload));
|
||||
let signer: sp_runtime::MultiSigner = param.signer.public().into();
|
||||
let (call, extra, _) = raw_payload.deconstruct();
|
||||
|
||||
Ok(rialto_runtime::UncheckedExtrinsic::new_signed(
|
||||
call.into_decoded()?,
|
||||
signer.into_account().into(),
|
||||
signature.into(),
|
||||
extra,
|
||||
))
|
||||
}
|
||||
|
||||
fn is_signed(tx: &Self::SignedTransaction) -> bool {
|
||||
tx.signature.is_some()
|
||||
}
|
||||
|
||||
fn is_signed_by(signer: &Self::AccountKeyPair, tx: &Self::SignedTransaction) -> bool {
|
||||
tx.signature
|
||||
.as_ref()
|
||||
.map(|(address, _, _)| *address == rialto_runtime::Address::Id(signer.public().into()))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn parse_transaction(tx: Self::SignedTransaction) -> Option<UnsignedTransaction<Self>> {
|
||||
let extra = &tx.signature.as_ref()?.2;
|
||||
Some(
|
||||
UnsignedTransaction::new(
|
||||
tx.function.into(),
|
||||
Compact::<IndexOf<Self>>::decode(&mut &extra.5.encode()[..]).ok()?.into(),
|
||||
)
|
||||
.tip(Compact::<BalanceOf<Self>>::decode(&mut &extra.7.encode()[..]).ok()?.into()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Rialto signing params.
|
||||
pub type SigningParams = sp_core::sr25519::Pair;
|
||||
|
||||
/// Rialto header type used in headers sync.
|
||||
pub type SyncHeader = relay_substrate_client::SyncHeader<rialto_runtime::Header>;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use relay_substrate_client::TransactionEra;
|
||||
|
||||
#[test]
|
||||
fn parse_transaction_works() {
|
||||
let unsigned = UnsignedTransaction {
|
||||
call: rialto_runtime::RuntimeCall::System(rialto_runtime::SystemCall::remark {
|
||||
remark: b"Hello world!".to_vec(),
|
||||
})
|
||||
.into(),
|
||||
nonce: 777,
|
||||
tip: 888,
|
||||
era: TransactionEra::immortal(),
|
||||
};
|
||||
let signed_transaction = Rialto::sign_transaction(
|
||||
SignParam {
|
||||
spec_version: 42,
|
||||
transaction_version: 50000,
|
||||
genesis_hash: [42u8; 32].into(),
|
||||
signer: sp_core::sr25519::Pair::from_seed_slice(&[1u8; 32]).unwrap(),
|
||||
},
|
||||
unsigned.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
let parsed_transaction = Rialto::parse_transaction(signed_transaction).unwrap();
|
||||
assert_eq!(parsed_transaction, unsigned);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "relay-rococo-client"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
relay-substrate-client = { path = "../client-substrate" }
|
||||
relay-utils = { path = "../utils" }
|
||||
|
||||
# Bridge dependencies
|
||||
|
||||
bp-rococo = { path = "../../primitives/chain-rococo" }
|
||||
|
||||
# Substrate Dependencies
|
||||
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
@@ -0,0 +1,78 @@
|
||||
// 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/>.
|
||||
|
||||
//! Types used to connect to the Rococo-Substrate chain.
|
||||
|
||||
use frame_support::weights::Weight;
|
||||
use relay_substrate_client::{Chain, ChainBase, ChainWithBalances, ChainWithGrandpa, RelayChain};
|
||||
use sp_core::storage::StorageKey;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Rococo header id.
|
||||
pub type HeaderId = relay_utils::HeaderId<bp_rococo::Hash, bp_rococo::BlockNumber>;
|
||||
|
||||
/// Rococo header type used in headers sync.
|
||||
pub type SyncHeader = relay_substrate_client::SyncHeader<bp_rococo::Header>;
|
||||
|
||||
/// Rococo chain definition
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Rococo;
|
||||
|
||||
impl ChainBase for Rococo {
|
||||
type BlockNumber = bp_rococo::BlockNumber;
|
||||
type Hash = bp_rococo::Hash;
|
||||
type Hasher = bp_rococo::Hashing;
|
||||
type Header = bp_rococo::Header;
|
||||
|
||||
type AccountId = bp_rococo::AccountId;
|
||||
type Balance = bp_rococo::Balance;
|
||||
type Index = bp_rococo::Nonce;
|
||||
type Signature = bp_rococo::Signature;
|
||||
|
||||
fn max_extrinsic_size() -> u32 {
|
||||
bp_rococo::Rococo::max_extrinsic_size()
|
||||
}
|
||||
|
||||
fn max_extrinsic_weight() -> Weight {
|
||||
bp_rococo::Rococo::max_extrinsic_weight()
|
||||
}
|
||||
}
|
||||
|
||||
impl Chain for Rococo {
|
||||
const NAME: &'static str = "Rococo";
|
||||
const TOKEN_ID: Option<&'static str> = None;
|
||||
const BEST_FINALIZED_HEADER_ID_METHOD: &'static str =
|
||||
bp_rococo::BEST_FINALIZED_ROCOCO_HEADER_METHOD;
|
||||
const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_secs(6);
|
||||
|
||||
type SignedBlock = bp_rococo::SignedBlock;
|
||||
type Call = ();
|
||||
}
|
||||
|
||||
impl ChainWithGrandpa for Rococo {
|
||||
const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str = bp_rococo::WITH_ROCOCO_GRANDPA_PALLET_NAME;
|
||||
}
|
||||
|
||||
impl ChainWithBalances for Rococo {
|
||||
fn account_info_storage_key(account_id: &Self::AccountId) -> StorageKey {
|
||||
bp_rococo::AccountInfoStorageMapKeyProvider::final_key(account_id)
|
||||
}
|
||||
}
|
||||
|
||||
impl RelayChain for Rococo {
|
||||
const PARAS_PALLET_NAME: &'static str = bp_rococo::PARAS_PALLET_NAME;
|
||||
const PARACHAINS_FINALITY_PALLET_NAME: &'static str = "bridgeRococoParachain";
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
[package]
|
||||
name = "relay-substrate-client"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
async-std = { version = "1.6.5", features = ["attributes"] }
|
||||
async-trait = "0.1"
|
||||
codec = { package = "parity-scale-codec", version = "3.1.5" }
|
||||
futures = "0.3.7"
|
||||
jsonrpsee = { version = "0.15", features = ["macros", "ws-client"] }
|
||||
log = "0.4.17"
|
||||
num-traits = "0.2"
|
||||
rand = "0.7"
|
||||
tokio = { version = "1.8", features = ["rt-multi-thread"] }
|
||||
thiserror = "1.0.26"
|
||||
|
||||
# Bridge dependencies
|
||||
|
||||
bp-header-chain = { path = "../../primitives/header-chain" }
|
||||
bp-messages = { path = "../../primitives/messages" }
|
||||
bp-runtime = { path = "../../primitives/runtime" }
|
||||
pallet-bridge-messages = { path = "../../modules/messages" }
|
||||
finality-relay = { path = "../finality" }
|
||||
relay-utils = { path = "../utils" }
|
||||
|
||||
# Substrate Dependencies
|
||||
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
frame-system = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
pallet-transaction-payment = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sc-chain-spec = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sc-rpc-api = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sc-transaction-pool-api = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-finality-grandpa = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-rpc = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-storage = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-trie = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-version = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
|
||||
[features]
|
||||
default = []
|
||||
test-helpers = []
|
||||
@@ -0,0 +1,235 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
use bp_messages::MessageNonce;
|
||||
use bp_runtime::{
|
||||
Chain as ChainBase, EncodedOrDecodedCall, HashOf, TransactionEra, TransactionEraOf,
|
||||
};
|
||||
use codec::{Codec, Encode};
|
||||
use frame_support::weights::WeightToFee;
|
||||
use jsonrpsee::core::{DeserializeOwned, Serialize};
|
||||
use num_traits::Zero;
|
||||
use sc_transaction_pool_api::TransactionStatus;
|
||||
use sp_core::{storage::StorageKey, Pair};
|
||||
use sp_runtime::{
|
||||
generic::SignedBlock,
|
||||
traits::{Block as BlockT, Dispatchable, Member},
|
||||
ConsensusEngineId, EncodedJustification,
|
||||
};
|
||||
use std::{fmt::Debug, time::Duration};
|
||||
|
||||
/// Substrate-based chain from minimal relay-client point of view.
|
||||
pub trait Chain: ChainBase + Clone {
|
||||
/// Chain name.
|
||||
const NAME: &'static str;
|
||||
/// Identifier of the basic token of the chain (if applicable).
|
||||
///
|
||||
/// This identifier is used to fetch token price. In case of testnets, you may either
|
||||
/// set it to `None`, or associate testnet with one of the existing tokens.
|
||||
const TOKEN_ID: Option<&'static str>;
|
||||
/// Name of the runtime API method that is returning best known finalized header number
|
||||
/// and hash (as tuple).
|
||||
///
|
||||
/// Keep in mind that this method is normally provided by the other chain, which is
|
||||
/// bridged with this chain.
|
||||
const BEST_FINALIZED_HEADER_ID_METHOD: &'static str;
|
||||
|
||||
/// Average block interval.
|
||||
///
|
||||
/// How often blocks are produced on that chain. It's suggested to set this value
|
||||
/// to match the block time of the chain.
|
||||
const AVERAGE_BLOCK_INTERVAL: Duration;
|
||||
|
||||
/// Block type.
|
||||
type SignedBlock: Member + Serialize + DeserializeOwned + BlockWithJustification<Self::Header>;
|
||||
/// The aggregated `Call` type.
|
||||
type Call: Clone + Codec + Dispatchable + Debug + Send;
|
||||
}
|
||||
|
||||
/// Substrate-based relay chain that supports parachains.
|
||||
///
|
||||
/// We assume that the parachains are supported using `runtime_parachains::paras` pallet.
|
||||
pub trait RelayChain: Chain {
|
||||
/// Name of the `runtime_parachains::paras` pallet in the runtime of this chain.
|
||||
const PARAS_PALLET_NAME: &'static str;
|
||||
/// Name of the bridge parachains pallet (used in `construct_runtime` macro call) that is
|
||||
/// deployed at the **bridged** chain.
|
||||
///
|
||||
/// We assume that all chains that are bridging with this `ChainWithGrandpa` are using
|
||||
/// the same name.
|
||||
const PARACHAINS_FINALITY_PALLET_NAME: &'static str;
|
||||
}
|
||||
|
||||
/// Substrate-based chain that is using direct GRANDPA finality from minimal relay-client point of
|
||||
/// view.
|
||||
///
|
||||
/// Keep in mind that parachains are relying on relay chain GRANDPA, so they should not implement
|
||||
/// this trait.
|
||||
pub trait ChainWithGrandpa: Chain {
|
||||
/// Name of the bridge GRANDPA pallet (used in `construct_runtime` macro call) that is deployed
|
||||
/// at some other chain to bridge with this `ChainWithGrandpa`.
|
||||
///
|
||||
/// We assume that all chains that are bridging with this `ChainWithGrandpa` are using
|
||||
/// the same name.
|
||||
const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str;
|
||||
}
|
||||
|
||||
/// Substrate-based chain with messaging support from minimal relay-client point of view.
|
||||
pub trait ChainWithMessages: Chain {
|
||||
/// Name of the bridge messages pallet (used in `construct_runtime` macro call) that is deployed
|
||||
/// at some other chain to bridge with this `ChainWithMessages`.
|
||||
///
|
||||
/// We assume that all chains that are bridging with this `ChainWithMessages` are using
|
||||
/// the same name.
|
||||
const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str;
|
||||
|
||||
/// Name of the `To<ChainWithMessages>OutboundLaneApi::message_details` runtime API method.
|
||||
/// The method is provided by the runtime that is bridged with this `ChainWithMessages`.
|
||||
const TO_CHAIN_MESSAGE_DETAILS_METHOD: &'static str;
|
||||
|
||||
/// Name of the `From<ChainWithMessages>InboundLaneApi::message_details` runtime API method.
|
||||
/// The method is provided by the runtime that is bridged with this `ChainWithMessages`.
|
||||
const FROM_CHAIN_MESSAGE_DETAILS_METHOD: &'static str;
|
||||
|
||||
/// Maximal number of unrewarded relayers in a single confirmation transaction at this
|
||||
/// `ChainWithMessages`.
|
||||
const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce;
|
||||
/// Maximal number of unconfirmed messages in a single confirmation transaction at this
|
||||
/// `ChainWithMessages`.
|
||||
const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce;
|
||||
|
||||
/// Type that is used by the chain, to convert from weight to fee.
|
||||
type WeightToFee: WeightToFee<Balance = Self::Balance>;
|
||||
/// Weights of message pallet calls.
|
||||
type WeightInfo: pallet_bridge_messages::WeightInfoExt;
|
||||
}
|
||||
|
||||
/// Call type used by the chain.
|
||||
pub type CallOf<C> = <C as Chain>::Call;
|
||||
/// Weight-to-Fee type used by the chain.
|
||||
pub type WeightToFeeOf<C> = <C as ChainWithMessages>::WeightToFee;
|
||||
/// Transaction status of the chain.
|
||||
pub type TransactionStatusOf<C> = TransactionStatus<HashOf<C>, HashOf<C>>;
|
||||
|
||||
/// Substrate-based chain with `AccountData` generic argument of `frame_system::AccountInfo` set to
|
||||
/// the `pallet_balances::AccountData<Balance>`.
|
||||
pub trait ChainWithBalances: Chain {
|
||||
/// Return runtime storage key for getting `frame_system::AccountInfo` of given account.
|
||||
fn account_info_storage_key(account_id: &Self::AccountId) -> StorageKey;
|
||||
}
|
||||
|
||||
/// SCALE-encoded extrinsic.
|
||||
pub type EncodedExtrinsic = Vec<u8>;
|
||||
|
||||
/// Block with justification.
|
||||
pub trait BlockWithJustification<Header> {
|
||||
/// Return block header.
|
||||
fn header(&self) -> Header;
|
||||
/// Return encoded block extrinsics.
|
||||
fn extrinsics(&self) -> Vec<EncodedExtrinsic>;
|
||||
/// Return block justification, if known.
|
||||
fn justification(&self, engine_id: ConsensusEngineId) -> Option<&EncodedJustification>;
|
||||
}
|
||||
|
||||
/// Transaction before it is signed.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct UnsignedTransaction<C: Chain> {
|
||||
/// Runtime call of this transaction.
|
||||
pub call: EncodedOrDecodedCall<C::Call>,
|
||||
/// Transaction nonce.
|
||||
pub nonce: C::Index,
|
||||
/// Tip included into transaction.
|
||||
pub tip: C::Balance,
|
||||
/// Transaction era used by the chain.
|
||||
pub era: TransactionEraOf<C>,
|
||||
}
|
||||
|
||||
impl<C: Chain> UnsignedTransaction<C> {
|
||||
/// Create new unsigned transaction with given call, nonce, era and zero tip.
|
||||
pub fn new(call: EncodedOrDecodedCall<C::Call>, nonce: C::Index) -> Self {
|
||||
Self { call, nonce, era: TransactionEra::Immortal, tip: Zero::zero() }
|
||||
}
|
||||
|
||||
/// Set transaction tip.
|
||||
#[must_use]
|
||||
pub fn tip(mut self, tip: C::Balance) -> Self {
|
||||
self.tip = tip;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set transaction era.
|
||||
#[must_use]
|
||||
pub fn era(mut self, era: TransactionEraOf<C>) -> Self {
|
||||
self.era = era;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Account key pair used by transactions signing scheme.
|
||||
pub type AccountKeyPairOf<S> = <S as ChainWithTransactions>::AccountKeyPair;
|
||||
|
||||
/// Substrate-based chain transactions signing scheme.
|
||||
pub trait ChainWithTransactions: Chain {
|
||||
/// Type of key pairs used to sign transactions.
|
||||
type AccountKeyPair: Pair;
|
||||
/// Signed transaction.
|
||||
type SignedTransaction: Clone + Debug + Codec + Send + 'static;
|
||||
|
||||
/// Create transaction for given runtime call, signed by given account.
|
||||
fn sign_transaction(
|
||||
param: SignParam<Self>,
|
||||
unsigned: UnsignedTransaction<Self>,
|
||||
) -> Result<Self::SignedTransaction, crate::Error>
|
||||
where
|
||||
Self: Sized;
|
||||
|
||||
/// Returns true if transaction is signed.
|
||||
fn is_signed(tx: &Self::SignedTransaction) -> bool;
|
||||
|
||||
/// Returns true if transaction is signed by given signer.
|
||||
fn is_signed_by(signer: &Self::AccountKeyPair, tx: &Self::SignedTransaction) -> bool;
|
||||
|
||||
/// Parse signed transaction into its unsigned part.
|
||||
///
|
||||
/// Returns `None` if signed transaction has unsupported format.
|
||||
fn parse_transaction(tx: Self::SignedTransaction) -> Option<UnsignedTransaction<Self>>;
|
||||
}
|
||||
|
||||
/// Sign transaction parameters
|
||||
pub struct SignParam<C: ChainWithTransactions> {
|
||||
/// Version of the runtime specification.
|
||||
pub spec_version: u32,
|
||||
/// Transaction version
|
||||
pub transaction_version: u32,
|
||||
/// Hash of the genesis block.
|
||||
pub genesis_hash: HashOf<C>,
|
||||
/// Signer account
|
||||
pub signer: AccountKeyPairOf<C>,
|
||||
}
|
||||
|
||||
impl<Block: BlockT> BlockWithJustification<Block::Header> for SignedBlock<Block> {
|
||||
fn header(&self) -> Block::Header {
|
||||
self.block.header().clone()
|
||||
}
|
||||
|
||||
fn extrinsics(&self) -> Vec<EncodedExtrinsic> {
|
||||
self.block.extrinsics().iter().map(Encode::encode).collect()
|
||||
}
|
||||
|
||||
fn justification(&self, engine_id: ConsensusEngineId) -> Option<&EncodedJustification> {
|
||||
self.justifications.as_ref().and_then(|j| j.get(engine_id))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,742 @@
|
||||
// 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 node client.
|
||||
|
||||
use crate::{
|
||||
chain::{Chain, ChainWithBalances, ChainWithTransactions},
|
||||
rpc::{
|
||||
SubstrateAuthorClient, SubstrateChainClient, SubstrateFinalityClient,
|
||||
SubstrateFrameSystemClient, SubstrateStateClient, SubstrateSystemClient,
|
||||
SubstrateTransactionPaymentClient,
|
||||
},
|
||||
transaction_stall_timeout, ConnectionParams, Error, HashOf, HeaderIdOf, Result, SignParam,
|
||||
TransactionTracker, UnsignedTransaction,
|
||||
};
|
||||
|
||||
use async_std::sync::{Arc, Mutex};
|
||||
use async_trait::async_trait;
|
||||
use bp_runtime::{HeaderIdProvider, StorageDoubleMapKeyProvider, StorageMapKeyProvider};
|
||||
use codec::{Decode, Encode};
|
||||
use frame_system::AccountInfo;
|
||||
use futures::{SinkExt, StreamExt};
|
||||
use jsonrpsee::{
|
||||
core::DeserializeOwned,
|
||||
ws_client::{WsClient as RpcClient, WsClientBuilder as RpcClientBuilder},
|
||||
};
|
||||
use num_traits::{Bounded, Zero};
|
||||
use pallet_balances::AccountData;
|
||||
use pallet_transaction_payment::InclusionFee;
|
||||
use relay_utils::{relay_loop::RECONNECT_DELAY, STALL_TIMEOUT};
|
||||
use sp_core::{
|
||||
storage::{StorageData, StorageKey},
|
||||
Bytes, Hasher,
|
||||
};
|
||||
use sp_runtime::{
|
||||
traits::Header as HeaderT,
|
||||
transaction_validity::{TransactionSource, TransactionValidity},
|
||||
};
|
||||
use sp_trie::StorageProof;
|
||||
use sp_version::RuntimeVersion;
|
||||
use std::{convert::TryFrom, future::Future};
|
||||
|
||||
const SUB_API_GRANDPA_AUTHORITIES: &str = "GrandpaApi_grandpa_authorities";
|
||||
const SUB_API_TXPOOL_VALIDATE_TRANSACTION: &str = "TaggedTransactionQueue_validate_transaction";
|
||||
const MAX_SUBSCRIPTION_CAPACITY: usize = 4096;
|
||||
|
||||
/// Opaque justifications subscription type.
|
||||
pub struct Subscription<T>(pub(crate) Mutex<futures::channel::mpsc::Receiver<Option<T>>>);
|
||||
|
||||
/// Opaque GRANDPA authorities set.
|
||||
pub type OpaqueGrandpaAuthoritiesSet = Vec<u8>;
|
||||
|
||||
/// Chain runtime version in client
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum ChainRuntimeVersion {
|
||||
/// Auto query from chain.
|
||||
Auto,
|
||||
/// Custom runtime version, defined by user.
|
||||
/// the first is `spec_version`
|
||||
/// the second is `transaction_version`
|
||||
Custom(u32, u32),
|
||||
}
|
||||
|
||||
/// Substrate client type.
|
||||
///
|
||||
/// Cloning `Client` is a cheap operation.
|
||||
pub struct Client<C: Chain> {
|
||||
/// Tokio runtime handle.
|
||||
tokio: Arc<tokio::runtime::Runtime>,
|
||||
/// Client connection params.
|
||||
params: Arc<ConnectionParams>,
|
||||
/// Substrate RPC client.
|
||||
client: Arc<RpcClient>,
|
||||
/// Genesis block hash.
|
||||
genesis_hash: HashOf<C>,
|
||||
/// If several tasks are submitting their transactions simultaneously using
|
||||
/// `submit_signed_extrinsic` method, they may get the same transaction nonce. So one of
|
||||
/// transactions will be rejected from the pool. This lock is here to prevent situations like
|
||||
/// that.
|
||||
submit_signed_extrinsic_lock: Arc<Mutex<()>>,
|
||||
/// Saved chain runtime version
|
||||
chain_runtime_version: ChainRuntimeVersion,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<C: Chain> relay_utils::relay_loop::Client for Client<C> {
|
||||
type Error = Error;
|
||||
|
||||
async fn reconnect(&mut self) -> Result<()> {
|
||||
let (tokio, client) = Self::build_client(&self.params).await?;
|
||||
self.tokio = tokio;
|
||||
self.client = client;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: Chain> Clone for Client<C> {
|
||||
fn clone(&self) -> Self {
|
||||
Client {
|
||||
tokio: self.tokio.clone(),
|
||||
params: self.params.clone(),
|
||||
client: self.client.clone(),
|
||||
genesis_hash: self.genesis_hash,
|
||||
submit_signed_extrinsic_lock: self.submit_signed_extrinsic_lock.clone(),
|
||||
chain_runtime_version: self.chain_runtime_version.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: Chain> std::fmt::Debug for Client<C> {
|
||||
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
fmt.debug_struct("Client").field("genesis_hash", &self.genesis_hash).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: Chain> Client<C> {
|
||||
/// Returns client that is able to call RPCs on Substrate node over websocket connection.
|
||||
///
|
||||
/// This function will keep connecting to given Substrate node until connection is established
|
||||
/// and is functional. If attempt fail, it will wait for `RECONNECT_DELAY` and retry again.
|
||||
pub async fn new(params: ConnectionParams) -> Self {
|
||||
let params = Arc::new(params);
|
||||
loop {
|
||||
match Self::try_connect(params.clone()).await {
|
||||
Ok(client) => return client,
|
||||
Err(error) => log::error!(
|
||||
target: "bridge",
|
||||
"Failed to connect to {} node: {:?}. Going to retry in {}s",
|
||||
C::NAME,
|
||||
error,
|
||||
RECONNECT_DELAY.as_secs(),
|
||||
),
|
||||
}
|
||||
|
||||
async_std::task::sleep(RECONNECT_DELAY).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to connect to Substrate node over websocket. Returns Substrate RPC client if connection
|
||||
/// has been established or error otherwise.
|
||||
pub async fn try_connect(params: Arc<ConnectionParams>) -> Result<Self> {
|
||||
let (tokio, client) = Self::build_client(¶ms).await?;
|
||||
|
||||
let number: C::BlockNumber = Zero::zero();
|
||||
let genesis_hash_client = client.clone();
|
||||
let genesis_hash = tokio
|
||||
.spawn(async move {
|
||||
SubstrateChainClient::<C>::block_hash(&*genesis_hash_client, Some(number)).await
|
||||
})
|
||||
.await??;
|
||||
|
||||
let chain_runtime_version = params.chain_runtime_version.clone();
|
||||
Ok(Self {
|
||||
tokio,
|
||||
params,
|
||||
client,
|
||||
genesis_hash,
|
||||
submit_signed_extrinsic_lock: Arc::new(Mutex::new(())),
|
||||
chain_runtime_version,
|
||||
})
|
||||
}
|
||||
|
||||
/// Build client to use in connection.
|
||||
async fn build_client(
|
||||
params: &ConnectionParams,
|
||||
) -> Result<(Arc<tokio::runtime::Runtime>, Arc<RpcClient>)> {
|
||||
let tokio = tokio::runtime::Runtime::new()?;
|
||||
let uri = format!(
|
||||
"{}://{}:{}",
|
||||
if params.secure { "wss" } else { "ws" },
|
||||
params.host,
|
||||
params.port,
|
||||
);
|
||||
log::info!(target: "bridge", "Connecting to {} node at {}", C::NAME, uri);
|
||||
|
||||
let client = tokio
|
||||
.spawn(async move {
|
||||
RpcClientBuilder::default()
|
||||
.max_notifs_per_subscription(MAX_SUBSCRIPTION_CAPACITY)
|
||||
.build(&uri)
|
||||
.await
|
||||
})
|
||||
.await??;
|
||||
|
||||
Ok((Arc::new(tokio), Arc::new(client)))
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: Chain> Client<C> {
|
||||
/// Return simple runtime version, only include `spec_version` and `transaction_version`.
|
||||
pub async fn simple_runtime_version(&self) -> Result<(u32, u32)> {
|
||||
let (spec_version, transaction_version) = match self.chain_runtime_version {
|
||||
ChainRuntimeVersion::Auto => {
|
||||
let runtime_version = self.runtime_version().await?;
|
||||
(runtime_version.spec_version, runtime_version.transaction_version)
|
||||
},
|
||||
ChainRuntimeVersion::Custom(spec_version, transaction_version) =>
|
||||
(spec_version, transaction_version),
|
||||
};
|
||||
Ok((spec_version, transaction_version))
|
||||
}
|
||||
|
||||
/// Returns true if client is connected to at least one peer and is in synced state.
|
||||
pub async fn ensure_synced(&self) -> Result<()> {
|
||||
self.jsonrpsee_execute(|client| async move {
|
||||
let health = SubstrateSystemClient::<C>::health(&*client).await?;
|
||||
let is_synced = !health.is_syncing && (!health.should_have_peers || health.peers > 0);
|
||||
if is_synced {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::ClientNotSynced(health))
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Return hash of the genesis block.
|
||||
pub fn genesis_hash(&self) -> &C::Hash {
|
||||
&self.genesis_hash
|
||||
}
|
||||
|
||||
/// Return hash of the best finalized block.
|
||||
pub async fn best_finalized_header_hash(&self) -> Result<C::Hash> {
|
||||
self.jsonrpsee_execute(|client| async move {
|
||||
Ok(SubstrateChainClient::<C>::finalized_head(&*client).await?)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Return number of the best finalized block.
|
||||
pub async fn best_finalized_header_number(&self) -> Result<C::BlockNumber> {
|
||||
Ok(*self.header_by_hash(self.best_finalized_header_hash().await?).await?.number())
|
||||
}
|
||||
|
||||
/// Return header of the best finalized block.
|
||||
pub async fn best_finalized_header(&self) -> Result<C::Header> {
|
||||
self.header_by_hash(self.best_finalized_header_hash().await?).await
|
||||
}
|
||||
|
||||
/// Returns the best Substrate header.
|
||||
pub async fn best_header(&self) -> Result<C::Header>
|
||||
where
|
||||
C::Header: DeserializeOwned,
|
||||
{
|
||||
self.jsonrpsee_execute(|client| async move {
|
||||
Ok(SubstrateChainClient::<C>::header(&*client, None).await?)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Get a Substrate block from its hash.
|
||||
pub async fn get_block(&self, block_hash: Option<C::Hash>) -> Result<C::SignedBlock> {
|
||||
self.jsonrpsee_execute(move |client| async move {
|
||||
Ok(SubstrateChainClient::<C>::block(&*client, block_hash).await?)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Get a Substrate header by its hash.
|
||||
pub async fn header_by_hash(&self, block_hash: C::Hash) -> Result<C::Header>
|
||||
where
|
||||
C::Header: DeserializeOwned,
|
||||
{
|
||||
self.jsonrpsee_execute(move |client| async move {
|
||||
Ok(SubstrateChainClient::<C>::header(&*client, Some(block_hash)).await?)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Get a Substrate block hash by its number.
|
||||
pub async fn block_hash_by_number(&self, number: C::BlockNumber) -> Result<C::Hash> {
|
||||
self.jsonrpsee_execute(move |client| async move {
|
||||
Ok(SubstrateChainClient::<C>::block_hash(&*client, Some(number)).await?)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Get a Substrate header by its number.
|
||||
pub async fn header_by_number(&self, block_number: C::BlockNumber) -> Result<C::Header>
|
||||
where
|
||||
C::Header: DeserializeOwned,
|
||||
{
|
||||
let block_hash = Self::block_hash_by_number(self, block_number).await?;
|
||||
let header_by_hash = Self::header_by_hash(self, block_hash).await?;
|
||||
Ok(header_by_hash)
|
||||
}
|
||||
|
||||
/// Return runtime version.
|
||||
pub async fn runtime_version(&self) -> Result<RuntimeVersion> {
|
||||
self.jsonrpsee_execute(move |client| async move {
|
||||
Ok(SubstrateStateClient::<C>::runtime_version(&*client).await?)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Read value from runtime storage.
|
||||
pub async fn storage_value<T: Send + Decode + 'static>(
|
||||
&self,
|
||||
storage_key: StorageKey,
|
||||
block_hash: Option<C::Hash>,
|
||||
) -> Result<Option<T>> {
|
||||
self.raw_storage_value(storage_key, block_hash)
|
||||
.await?
|
||||
.map(|encoded_value| {
|
||||
T::decode(&mut &encoded_value.0[..]).map_err(Error::ResponseParseFailed)
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
/// Read `MapStorage` value from runtime storage.
|
||||
pub async fn storage_map_value<T: StorageMapKeyProvider>(
|
||||
&self,
|
||||
pallet_prefix: &str,
|
||||
key: &T::Key,
|
||||
block_hash: Option<C::Hash>,
|
||||
) -> Result<Option<T::Value>> {
|
||||
let storage_key = T::final_key(pallet_prefix, key);
|
||||
|
||||
self.raw_storage_value(storage_key, block_hash)
|
||||
.await?
|
||||
.map(|encoded_value| {
|
||||
T::Value::decode(&mut &encoded_value.0[..]).map_err(Error::ResponseParseFailed)
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
/// Read `DoubleMapStorage` value from runtime storage.
|
||||
pub async fn storage_double_map_value<T: StorageDoubleMapKeyProvider>(
|
||||
&self,
|
||||
pallet_prefix: &str,
|
||||
key1: &T::Key1,
|
||||
key2: &T::Key2,
|
||||
block_hash: Option<C::Hash>,
|
||||
) -> Result<Option<T::Value>> {
|
||||
let storage_key = T::final_key(pallet_prefix, key1, key2);
|
||||
|
||||
self.raw_storage_value(storage_key, block_hash)
|
||||
.await?
|
||||
.map(|encoded_value| {
|
||||
T::Value::decode(&mut &encoded_value.0[..]).map_err(Error::ResponseParseFailed)
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
/// Read raw value from runtime storage.
|
||||
pub async fn raw_storage_value(
|
||||
&self,
|
||||
storage_key: StorageKey,
|
||||
block_hash: Option<C::Hash>,
|
||||
) -> Result<Option<StorageData>> {
|
||||
self.jsonrpsee_execute(move |client| async move {
|
||||
Ok(SubstrateStateClient::<C>::storage(&*client, storage_key, block_hash).await?)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Return native tokens balance of the account.
|
||||
pub async fn free_native_balance(&self, account: C::AccountId) -> Result<C::Balance>
|
||||
where
|
||||
C: ChainWithBalances,
|
||||
{
|
||||
self.jsonrpsee_execute(move |client| async move {
|
||||
let storage_key = C::account_info_storage_key(&account);
|
||||
let encoded_account_data =
|
||||
SubstrateStateClient::<C>::storage(&*client, storage_key, None)
|
||||
.await?
|
||||
.ok_or(Error::AccountDoesNotExist)?;
|
||||
let decoded_account_data = AccountInfo::<C::Index, AccountData<C::Balance>>::decode(
|
||||
&mut &encoded_account_data.0[..],
|
||||
)
|
||||
.map_err(Error::ResponseParseFailed)?;
|
||||
Ok(decoded_account_data.data.free)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Get the nonce of the given Substrate account.
|
||||
///
|
||||
/// Note: It's the caller's responsibility to make sure `account` is a valid SS58 address.
|
||||
pub async fn next_account_index(&self, account: C::AccountId) -> Result<C::Index> {
|
||||
self.jsonrpsee_execute(move |client| async move {
|
||||
Ok(SubstrateFrameSystemClient::<C>::account_next_index(&*client, account).await?)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Submit unsigned extrinsic for inclusion in a block.
|
||||
///
|
||||
/// Note: The given transaction needs to be SCALE encoded beforehand.
|
||||
pub async fn submit_unsigned_extrinsic(&self, transaction: Bytes) -> Result<C::Hash> {
|
||||
self.jsonrpsee_execute(move |client| async move {
|
||||
let tx_hash = SubstrateAuthorClient::<C>::submit_extrinsic(&*client, transaction)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
log::error!(target: "bridge", "Failed to send transaction to {} node: {:?}", C::NAME, e);
|
||||
e
|
||||
})?;
|
||||
log::trace!(target: "bridge", "Sent transaction to {} node: {:?}", C::NAME, tx_hash);
|
||||
Ok(tx_hash)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Submit an extrinsic signed by given account.
|
||||
///
|
||||
/// All calls of this method are synchronized, so there can't be more than one active
|
||||
/// `submit_signed_extrinsic()` call. This guarantees that no nonces collision may happen
|
||||
/// if all client instances are clones of the same initial `Client`.
|
||||
///
|
||||
/// Note: The given transaction needs to be SCALE encoded beforehand.
|
||||
pub async fn submit_signed_extrinsic(
|
||||
&self,
|
||||
extrinsic_signer: C::AccountId,
|
||||
signing_data: SignParam<C>,
|
||||
prepare_extrinsic: impl FnOnce(HeaderIdOf<C>, C::Index) -> Result<UnsignedTransaction<C>>
|
||||
+ Send
|
||||
+ 'static,
|
||||
) -> Result<C::Hash>
|
||||
where
|
||||
C: ChainWithTransactions,
|
||||
{
|
||||
let _guard = self.submit_signed_extrinsic_lock.lock().await;
|
||||
let transaction_nonce = self.next_account_index(extrinsic_signer).await?;
|
||||
let best_header = self.best_header().await?;
|
||||
|
||||
// By using parent of best block here, we are protecing again best-block reorganizations.
|
||||
// E.g. transaction may have been submitted when the best block was `A[num=100]`. Then it
|
||||
// has been changed to `B[num=100]`. Hash of `A` has been included into transaction
|
||||
// signature payload. So when signature will be checked, the check will fail and transaction
|
||||
// will be dropped from the pool.
|
||||
let best_header_id = best_header.parent_id().unwrap_or_else(|| best_header.id());
|
||||
|
||||
self.jsonrpsee_execute(move |client| async move {
|
||||
let extrinsic = prepare_extrinsic(best_header_id, transaction_nonce)?;
|
||||
let signed_extrinsic = C::sign_transaction(signing_data, extrinsic)?.encode();
|
||||
let tx_hash =
|
||||
SubstrateAuthorClient::<C>::submit_extrinsic(&*client, Bytes(signed_extrinsic))
|
||||
.await
|
||||
.map_err(|e| {
|
||||
log::error!(target: "bridge", "Failed to send transaction to {} node: {:?}", C::NAME, e);
|
||||
e
|
||||
})?;
|
||||
log::trace!(target: "bridge", "Sent transaction to {} node: {:?}", C::NAME, tx_hash);
|
||||
Ok(tx_hash)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Does exactly the same as `submit_signed_extrinsic`, but keeps watching for extrinsic status
|
||||
/// after submission.
|
||||
pub async fn submit_and_watch_signed_extrinsic(
|
||||
&self,
|
||||
extrinsic_signer: C::AccountId,
|
||||
signing_data: SignParam<C>,
|
||||
prepare_extrinsic: impl FnOnce(HeaderIdOf<C>, C::Index) -> Result<UnsignedTransaction<C>>
|
||||
+ Send
|
||||
+ 'static,
|
||||
) -> Result<TransactionTracker<C, Self>>
|
||||
where
|
||||
C: ChainWithTransactions,
|
||||
{
|
||||
let self_clone = self.clone();
|
||||
let _guard = self.submit_signed_extrinsic_lock.lock().await;
|
||||
let transaction_nonce = self.next_account_index(extrinsic_signer).await?;
|
||||
let best_header = self.best_header().await?;
|
||||
let best_header_id = best_header.id();
|
||||
let (sender, receiver) = futures::channel::mpsc::channel(MAX_SUBSCRIPTION_CAPACITY);
|
||||
let (tracker, subscription) = self
|
||||
.jsonrpsee_execute(move |client| async move {
|
||||
let extrinsic = prepare_extrinsic(best_header_id, transaction_nonce)?;
|
||||
let stall_timeout = transaction_stall_timeout(
|
||||
extrinsic.era.mortality_period(),
|
||||
C::AVERAGE_BLOCK_INTERVAL,
|
||||
STALL_TIMEOUT,
|
||||
);
|
||||
let signed_extrinsic = C::sign_transaction(signing_data, extrinsic)?.encode();
|
||||
let tx_hash = C::Hasher::hash(&signed_extrinsic);
|
||||
let subscription = SubstrateAuthorClient::<C>::submit_and_watch_extrinsic(
|
||||
&*client,
|
||||
Bytes(signed_extrinsic),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
log::error!(target: "bridge", "Failed to send transaction to {} node: {:?}", C::NAME, e);
|
||||
e
|
||||
})?;
|
||||
log::trace!(target: "bridge", "Sent transaction to {} node: {:?}", C::NAME, tx_hash);
|
||||
let tracker = TransactionTracker::new(
|
||||
self_clone,
|
||||
stall_timeout,
|
||||
tx_hash,
|
||||
Subscription(Mutex::new(receiver)),
|
||||
);
|
||||
Ok((tracker, subscription))
|
||||
})
|
||||
.await?;
|
||||
self.tokio.spawn(Subscription::background_worker(
|
||||
C::NAME.into(),
|
||||
"extrinsic".into(),
|
||||
subscription,
|
||||
sender,
|
||||
));
|
||||
Ok(tracker)
|
||||
}
|
||||
|
||||
/// Returns pending extrinsics from transaction pool.
|
||||
pub async fn pending_extrinsics(&self) -> Result<Vec<Bytes>> {
|
||||
self.jsonrpsee_execute(move |client| async move {
|
||||
Ok(SubstrateAuthorClient::<C>::pending_extrinsics(&*client).await?)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Validate transaction at given block state.
|
||||
pub async fn validate_transaction<SignedTransaction: Encode + Send + 'static>(
|
||||
&self,
|
||||
at_block: C::Hash,
|
||||
transaction: SignedTransaction,
|
||||
) -> Result<TransactionValidity> {
|
||||
self.jsonrpsee_execute(move |client| async move {
|
||||
let call = SUB_API_TXPOOL_VALIDATE_TRANSACTION.to_string();
|
||||
let data = Bytes((TransactionSource::External, transaction, at_block).encode());
|
||||
|
||||
let encoded_response =
|
||||
SubstrateStateClient::<C>::call(&*client, call, data, Some(at_block)).await?;
|
||||
let validity = TransactionValidity::decode(&mut &encoded_response.0[..])
|
||||
.map_err(Error::ResponseParseFailed)?;
|
||||
|
||||
Ok(validity)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Estimate fee that will be spent on given extrinsic.
|
||||
pub async fn estimate_extrinsic_fee(
|
||||
&self,
|
||||
transaction: Bytes,
|
||||
) -> Result<InclusionFee<C::Balance>> {
|
||||
self.jsonrpsee_execute(move |client| async move {
|
||||
let fee_details =
|
||||
SubstrateTransactionPaymentClient::<C>::fee_details(&*client, transaction, None)
|
||||
.await?;
|
||||
let inclusion_fee = fee_details
|
||||
.inclusion_fee
|
||||
.map(|inclusion_fee| InclusionFee {
|
||||
base_fee: C::Balance::try_from(inclusion_fee.base_fee.into_u256())
|
||||
.unwrap_or_else(|_| C::Balance::max_value()),
|
||||
len_fee: C::Balance::try_from(inclusion_fee.len_fee.into_u256())
|
||||
.unwrap_or_else(|_| C::Balance::max_value()),
|
||||
adjusted_weight_fee: C::Balance::try_from(
|
||||
inclusion_fee.adjusted_weight_fee.into_u256(),
|
||||
)
|
||||
.unwrap_or_else(|_| C::Balance::max_value()),
|
||||
})
|
||||
.unwrap_or_else(|| InclusionFee {
|
||||
base_fee: Zero::zero(),
|
||||
len_fee: Zero::zero(),
|
||||
adjusted_weight_fee: Zero::zero(),
|
||||
});
|
||||
Ok(inclusion_fee)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Get the GRANDPA authority set at given block.
|
||||
pub async fn grandpa_authorities_set(
|
||||
&self,
|
||||
block: C::Hash,
|
||||
) -> Result<OpaqueGrandpaAuthoritiesSet> {
|
||||
self.jsonrpsee_execute(move |client| async move {
|
||||
let call = SUB_API_GRANDPA_AUTHORITIES.to_string();
|
||||
let data = Bytes(Vec::new());
|
||||
|
||||
let encoded_response =
|
||||
SubstrateStateClient::<C>::call(&*client, call, data, Some(block)).await?;
|
||||
let authority_list = encoded_response.0;
|
||||
|
||||
Ok(authority_list)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Execute runtime call at given block, provided the input and output types.
|
||||
/// It also performs the input encode and output decode.
|
||||
pub async fn typed_state_call<Input: codec::Encode, Output: codec::Decode>(
|
||||
&self,
|
||||
method_name: String,
|
||||
input: Input,
|
||||
at_block: Option<C::Hash>,
|
||||
) -> Result<Output> {
|
||||
let encoded_output = self.state_call(method_name, Bytes(input.encode()), at_block).await?;
|
||||
Output::decode(&mut &encoded_output.0[..]).map_err(Error::ResponseParseFailed)
|
||||
}
|
||||
|
||||
/// Execute runtime call at given block.
|
||||
pub async fn state_call(
|
||||
&self,
|
||||
method: String,
|
||||
data: Bytes,
|
||||
at_block: Option<C::Hash>,
|
||||
) -> Result<Bytes> {
|
||||
self.jsonrpsee_execute(move |client| async move {
|
||||
SubstrateStateClient::<C>::call(&*client, method, data, at_block)
|
||||
.await
|
||||
.map_err(Into::into)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Returns storage proof of given storage keys.
|
||||
pub async fn prove_storage(
|
||||
&self,
|
||||
keys: Vec<StorageKey>,
|
||||
at_block: C::Hash,
|
||||
) -> Result<StorageProof> {
|
||||
self.jsonrpsee_execute(move |client| async move {
|
||||
SubstrateStateClient::<C>::prove_storage(&*client, keys, Some(at_block))
|
||||
.await
|
||||
.map(|proof| {
|
||||
StorageProof::new(proof.proof.into_iter().map(|b| b.0).collect::<Vec<_>>())
|
||||
})
|
||||
.map_err(Into::into)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Return `tokenDecimals` property from the set of chain properties.
|
||||
pub async fn token_decimals(&self) -> Result<Option<u64>> {
|
||||
self.jsonrpsee_execute(move |client| async move {
|
||||
let system_properties = SubstrateSystemClient::<C>::properties(&*client).await?;
|
||||
Ok(system_properties.get("tokenDecimals").and_then(|v| v.as_u64()))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Return new finality justifications stream.
|
||||
pub async fn subscribe_finality_justifications<FC: SubstrateFinalityClient<C>>(
|
||||
&self,
|
||||
) -> Result<Subscription<Bytes>> {
|
||||
let subscription = self
|
||||
.jsonrpsee_execute(move |client| async move {
|
||||
Ok(FC::subscribe_justifications(&client).await?)
|
||||
})
|
||||
.await?;
|
||||
let (sender, receiver) = futures::channel::mpsc::channel(MAX_SUBSCRIPTION_CAPACITY);
|
||||
self.tokio.spawn(Subscription::background_worker(
|
||||
C::NAME.into(),
|
||||
"justification".into(),
|
||||
subscription,
|
||||
sender,
|
||||
));
|
||||
Ok(Subscription(Mutex::new(receiver)))
|
||||
}
|
||||
|
||||
/// Execute jsonrpsee future in tokio context.
|
||||
async fn jsonrpsee_execute<MF, F, T>(&self, make_jsonrpsee_future: MF) -> Result<T>
|
||||
where
|
||||
MF: FnOnce(Arc<RpcClient>) -> F + Send + 'static,
|
||||
F: Future<Output = Result<T>> + Send,
|
||||
T: Send + 'static,
|
||||
{
|
||||
let client = self.client.clone();
|
||||
self.tokio.spawn(async move { make_jsonrpsee_future(client).await }).await?
|
||||
}
|
||||
|
||||
/// Returns `true` if version guard can be started.
|
||||
///
|
||||
/// There's no reason to run version guard when version mode is set to `Auto`. It can
|
||||
/// lead to relay shutdown when chain is upgraded, even though we have explicitly
|
||||
/// said that we don't want to shutdown.
|
||||
pub fn can_start_version_guard(&self) -> bool {
|
||||
!matches!(self.chain_runtime_version, ChainRuntimeVersion::Auto)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: DeserializeOwned> Subscription<T> {
|
||||
/// Consumes subscription and returns future statuses stream.
|
||||
pub fn into_stream(self) -> impl futures::Stream<Item = T> {
|
||||
futures::stream::unfold(self, |this| async {
|
||||
let item = this.0.lock().await.next().await.unwrap_or(None);
|
||||
item.map(|i| (i, this))
|
||||
})
|
||||
}
|
||||
|
||||
/// Return next item from the subscription.
|
||||
pub async fn next(&self) -> Result<Option<T>> {
|
||||
let mut receiver = self.0.lock().await;
|
||||
let item = receiver.next().await;
|
||||
Ok(item.unwrap_or(None))
|
||||
}
|
||||
|
||||
/// Background worker that is executed in tokio context as `jsonrpsee` requires.
|
||||
async fn background_worker(
|
||||
chain_name: String,
|
||||
item_type: String,
|
||||
mut subscription: jsonrpsee::core::client::Subscription<T>,
|
||||
mut sender: futures::channel::mpsc::Sender<Option<T>>,
|
||||
) {
|
||||
loop {
|
||||
match subscription.next().await {
|
||||
Some(Ok(item)) =>
|
||||
if sender.send(Some(item)).await.is_err() {
|
||||
break
|
||||
},
|
||||
Some(Err(e)) => {
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"{} {} subscription stream has returned '{:?}'. Stream needs to be restarted.",
|
||||
chain_name,
|
||||
item_type,
|
||||
e,
|
||||
);
|
||||
let _ = sender.send(None).await;
|
||||
break
|
||||
},
|
||||
None => {
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"{} {} subscription stream has returned None. Stream needs to be restarted.",
|
||||
chain_name,
|
||||
item_type,
|
||||
);
|
||||
let _ = sender.send(None).await;
|
||||
break
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// 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 node RPC errors.
|
||||
|
||||
use jsonrpsee::core::Error as RpcError;
|
||||
use relay_utils::MaybeConnectionError;
|
||||
use sc_rpc_api::system::Health;
|
||||
use sp_runtime::transaction_validity::TransactionValidityError;
|
||||
use thiserror::Error;
|
||||
|
||||
/// Result type used by Substrate client.
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// Errors that can occur only when interacting with
|
||||
/// a Substrate node through RPC.
|
||||
#[derive(Error, Debug)]
|
||||
pub enum Error {
|
||||
/// IO error.
|
||||
#[error("IO error: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
/// An error that can occur when making a request to
|
||||
/// an JSON-RPC server.
|
||||
#[error("RPC error: {0}")]
|
||||
RpcError(#[from] RpcError),
|
||||
/// The response from the server could not be SCALE decoded.
|
||||
#[error("Response parse failed: {0}")]
|
||||
ResponseParseFailed(#[from] codec::Error),
|
||||
/// Account does not exist on the chain.
|
||||
#[error("Account does not exist on the chain.")]
|
||||
AccountDoesNotExist,
|
||||
/// Runtime storage is missing some mandatory value.
|
||||
#[error("Mandatory storage value is missing from the runtime storage.")]
|
||||
MissingMandatoryStorageValue,
|
||||
/// The client we're connected to is not synced, so we can't rely on its state.
|
||||
#[error("Substrate client is not synced {0}.")]
|
||||
ClientNotSynced(Health),
|
||||
/// The bridge pallet is halted and all transactions will be rejected.
|
||||
#[error("Bridge pallet is halted.")]
|
||||
BridgePalletIsHalted,
|
||||
/// The bridge pallet is not yet initialized and all transactions will be rejected.
|
||||
#[error("Bridge pallet is not initialized.")]
|
||||
BridgePalletIsNotInitialized,
|
||||
/// An error has happened when we have tried to parse storage proof.
|
||||
#[error("Error when parsing storage proof: {0:?}.")]
|
||||
StorageProofError(bp_runtime::StorageProofError),
|
||||
/// The Substrate transaction is invalid.
|
||||
#[error("Substrate transaction is invalid: {0:?}")]
|
||||
TransactionInvalid(#[from] TransactionValidityError),
|
||||
/// Custom logic error.
|
||||
#[error("{0}")]
|
||||
Custom(String),
|
||||
}
|
||||
|
||||
impl From<tokio::task::JoinError> for Error {
|
||||
fn from(error: tokio::task::JoinError) -> Self {
|
||||
Error::Custom(format!("Failed to wait tokio task: {error}"))
|
||||
}
|
||||
}
|
||||
|
||||
impl MaybeConnectionError for Error {
|
||||
fn is_connection_error(&self) -> bool {
|
||||
matches!(
|
||||
*self,
|
||||
Error::RpcError(RpcError::Transport(_))
|
||||
// right now if connection to the ws server is dropped (after it is already established),
|
||||
// we're getting this error
|
||||
| Error::RpcError(RpcError::Internal(_))
|
||||
| Error::RpcError(RpcError::RestartNeeded(_))
|
||||
| Error::ClientNotSynced(_),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
// 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/>.
|
||||
|
||||
//! Pallet provides a set of guard functions that are running in background threads
|
||||
//! and are aborting process if some condition fails.
|
||||
|
||||
use crate::{error::Error, Chain, ChainWithBalances, Client};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use num_traits::CheckedSub;
|
||||
use sp_version::RuntimeVersion;
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
fmt::Display,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
/// Guards environment.
|
||||
#[async_trait]
|
||||
pub trait Environment<C: ChainWithBalances>: Send + Sync + 'static {
|
||||
/// Error type.
|
||||
type Error: Display + Send + Sync + 'static;
|
||||
|
||||
/// Return current runtime version.
|
||||
async fn runtime_version(&mut self) -> Result<RuntimeVersion, Self::Error>;
|
||||
/// Return free native balance of the account on the chain.
|
||||
async fn free_native_balance(
|
||||
&mut self,
|
||||
account: C::AccountId,
|
||||
) -> Result<C::Balance, Self::Error>;
|
||||
|
||||
/// Return current time.
|
||||
fn now(&self) -> Instant {
|
||||
Instant::now()
|
||||
}
|
||||
|
||||
/// Sleep given amount of time.
|
||||
async fn sleep(&mut self, duration: Duration) {
|
||||
async_std::task::sleep(duration).await
|
||||
}
|
||||
|
||||
/// Abort current process. Called when guard condition check fails.
|
||||
async fn abort(&mut self) {
|
||||
std::process::abort();
|
||||
}
|
||||
}
|
||||
|
||||
/// Abort when runtime spec version is different from specified.
|
||||
pub fn abort_on_spec_version_change<C: ChainWithBalances>(
|
||||
mut env: impl Environment<C>,
|
||||
expected_spec_version: u32,
|
||||
) {
|
||||
async_std::task::spawn(async move {
|
||||
log::info!(
|
||||
target: "bridge-guard",
|
||||
"Starting spec_version guard for {}. Expected spec_version: {}",
|
||||
C::NAME,
|
||||
expected_spec_version,
|
||||
);
|
||||
|
||||
loop {
|
||||
let actual_spec_version = env.runtime_version().await;
|
||||
match actual_spec_version {
|
||||
Ok(version) if version.spec_version == expected_spec_version => (),
|
||||
Ok(version) => {
|
||||
log::error!(
|
||||
target: "bridge-guard",
|
||||
"{} runtime spec version has changed from {} to {}. Aborting relay",
|
||||
C::NAME,
|
||||
expected_spec_version,
|
||||
version.spec_version,
|
||||
);
|
||||
|
||||
env.abort().await;
|
||||
},
|
||||
Err(error) => log::warn!(
|
||||
target: "bridge-guard",
|
||||
"Failed to read {} runtime version: {}. Relay may need to be stopped manually",
|
||||
C::NAME,
|
||||
error,
|
||||
),
|
||||
}
|
||||
|
||||
env.sleep(conditions_check_delay::<C>()).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Abort if, during 24 hours, free balance of given account is decreased at least by given value.
|
||||
/// Other components may increase (or decrease) balance of account and it WILL affect logic of the
|
||||
/// guard.
|
||||
pub fn abort_when_account_balance_decreased<C: ChainWithBalances>(
|
||||
mut env: impl Environment<C>,
|
||||
account_id: C::AccountId,
|
||||
maximal_decrease: C::Balance,
|
||||
) {
|
||||
const DAY: Duration = Duration::from_secs(60 * 60 * 24);
|
||||
|
||||
async_std::task::spawn(async move {
|
||||
log::info!(
|
||||
target: "bridge-guard",
|
||||
"Starting balance guard for {}/{:?}. Maximal decrease: {:?}",
|
||||
C::NAME,
|
||||
account_id,
|
||||
maximal_decrease,
|
||||
);
|
||||
|
||||
let mut balances = VecDeque::new();
|
||||
|
||||
loop {
|
||||
let current_time = env.now();
|
||||
|
||||
// remember balances that are beyound 24h border
|
||||
if let Some(time_border) = current_time.checked_sub(DAY) {
|
||||
while balances.front().map(|(time, _)| *time < time_border).unwrap_or(false) {
|
||||
balances.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
// read balance of the account
|
||||
let current_balance = env.free_native_balance(account_id.clone()).await;
|
||||
|
||||
// remember balance and check difference
|
||||
match current_balance {
|
||||
Ok(current_balance) => {
|
||||
// remember balance
|
||||
balances.push_back((current_time, current_balance));
|
||||
|
||||
// check if difference between current and oldest balance is too large
|
||||
let (oldest_time, oldest_balance) =
|
||||
balances.front().expect("pushed to queue couple of lines above; qed");
|
||||
let balances_difference = oldest_balance.checked_sub(¤t_balance);
|
||||
if balances_difference > Some(maximal_decrease) {
|
||||
log::error!(
|
||||
target: "bridge-guard",
|
||||
"Balance of {} account {:?} has decreased from {:?} to {:?} in {} minutes. Aborting relay",
|
||||
C::NAME,
|
||||
account_id,
|
||||
oldest_balance,
|
||||
current_balance,
|
||||
current_time.duration_since(*oldest_time).as_secs() / 60,
|
||||
);
|
||||
|
||||
env.abort().await;
|
||||
}
|
||||
},
|
||||
Err(error) => {
|
||||
log::warn!(
|
||||
target: "bridge-guard",
|
||||
"Failed to read {} account {:?} balance: {}. Relay may need to be stopped manually",
|
||||
C::NAME,
|
||||
account_id,
|
||||
error,
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
env.sleep(conditions_check_delay::<C>()).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Delay between conditions check.
|
||||
fn conditions_check_delay<C: Chain>() -> Duration {
|
||||
C::AVERAGE_BLOCK_INTERVAL * (10 + rand::random::<u32>() % 10)
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<C: ChainWithBalances> Environment<C> for Client<C> {
|
||||
type Error = Error;
|
||||
|
||||
async fn runtime_version(&mut self) -> Result<RuntimeVersion, Self::Error> {
|
||||
Client::<C>::runtime_version(self).await
|
||||
}
|
||||
|
||||
async fn free_native_balance(
|
||||
&mut self,
|
||||
account: C::AccountId,
|
||||
) -> Result<C::Balance, Self::Error> {
|
||||
Client::<C>::free_native_balance(self, account).await
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_chain::TestChain;
|
||||
use futures::{
|
||||
channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender},
|
||||
future::FutureExt,
|
||||
stream::StreamExt,
|
||||
SinkExt,
|
||||
};
|
||||
|
||||
struct TestEnvironment {
|
||||
runtime_version_rx: UnboundedReceiver<RuntimeVersion>,
|
||||
free_native_balance_rx: UnboundedReceiver<u32>,
|
||||
slept_tx: UnboundedSender<()>,
|
||||
aborted_tx: UnboundedSender<()>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Environment<TestChain> for TestEnvironment {
|
||||
type Error = Error;
|
||||
|
||||
async fn runtime_version(&mut self) -> Result<RuntimeVersion, Self::Error> {
|
||||
Ok(self.runtime_version_rx.next().await.unwrap_or_default())
|
||||
}
|
||||
|
||||
async fn free_native_balance(&mut self, _account: u32) -> Result<u32, Self::Error> {
|
||||
Ok(self.free_native_balance_rx.next().await.unwrap_or_default())
|
||||
}
|
||||
|
||||
async fn sleep(&mut self, _duration: Duration) {
|
||||
let _ = self.slept_tx.send(()).await;
|
||||
}
|
||||
|
||||
async fn abort(&mut self) {
|
||||
let _ = self.aborted_tx.send(()).await;
|
||||
// simulate process abort :)
|
||||
async_std::task::sleep(Duration::from_secs(60)).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aborts_when_spec_version_is_changed() {
|
||||
async_std::task::block_on(async {
|
||||
let (
|
||||
(mut runtime_version_tx, runtime_version_rx),
|
||||
(_free_native_balance_tx, free_native_balance_rx),
|
||||
(slept_tx, mut slept_rx),
|
||||
(aborted_tx, mut aborted_rx),
|
||||
) = (unbounded(), unbounded(), unbounded(), unbounded());
|
||||
abort_on_spec_version_change(
|
||||
TestEnvironment {
|
||||
runtime_version_rx,
|
||||
free_native_balance_rx,
|
||||
slept_tx,
|
||||
aborted_tx,
|
||||
},
|
||||
0,
|
||||
);
|
||||
|
||||
// client responds with wrong version
|
||||
runtime_version_tx
|
||||
.send(RuntimeVersion { spec_version: 42, ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// then the `abort` function is called
|
||||
aborted_rx.next().await;
|
||||
// and we do not reach the `sleep` function call
|
||||
assert!(slept_rx.next().now_or_never().is_none());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn does_not_aborts_when_spec_version_is_unchanged() {
|
||||
async_std::task::block_on(async {
|
||||
let (
|
||||
(mut runtime_version_tx, runtime_version_rx),
|
||||
(_free_native_balance_tx, free_native_balance_rx),
|
||||
(slept_tx, mut slept_rx),
|
||||
(aborted_tx, mut aborted_rx),
|
||||
) = (unbounded(), unbounded(), unbounded(), unbounded());
|
||||
abort_on_spec_version_change(
|
||||
TestEnvironment {
|
||||
runtime_version_rx,
|
||||
free_native_balance_rx,
|
||||
slept_tx,
|
||||
aborted_tx,
|
||||
},
|
||||
42,
|
||||
);
|
||||
|
||||
// client responds with the same version
|
||||
runtime_version_tx
|
||||
.send(RuntimeVersion { spec_version: 42, ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// then the `sleep` function is called
|
||||
slept_rx.next().await;
|
||||
// and the `abort` function is not called
|
||||
assert!(aborted_rx.next().now_or_never().is_none());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aborts_when_balance_is_too_low() {
|
||||
async_std::task::block_on(async {
|
||||
let (
|
||||
(_runtime_version_tx, runtime_version_rx),
|
||||
(mut free_native_balance_tx, free_native_balance_rx),
|
||||
(slept_tx, mut slept_rx),
|
||||
(aborted_tx, mut aborted_rx),
|
||||
) = (unbounded(), unbounded(), unbounded(), unbounded());
|
||||
abort_when_account_balance_decreased(
|
||||
TestEnvironment {
|
||||
runtime_version_rx,
|
||||
free_native_balance_rx,
|
||||
slept_tx,
|
||||
aborted_tx,
|
||||
},
|
||||
0,
|
||||
100,
|
||||
);
|
||||
|
||||
// client responds with initial balance
|
||||
free_native_balance_tx.send(1000).await.unwrap();
|
||||
|
||||
// then the guard sleeps
|
||||
slept_rx.next().await;
|
||||
|
||||
// and then client responds with updated balance, which is too low
|
||||
free_native_balance_tx.send(899).await.unwrap();
|
||||
|
||||
// then the `abort` function is called
|
||||
aborted_rx.next().await;
|
||||
// and we do not reach next `sleep` function call
|
||||
assert!(slept_rx.next().now_or_never().is_none());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn does_not_aborts_when_balance_is_enough() {
|
||||
async_std::task::block_on(async {
|
||||
let (
|
||||
(_runtime_version_tx, runtime_version_rx),
|
||||
(mut free_native_balance_tx, free_native_balance_rx),
|
||||
(slept_tx, mut slept_rx),
|
||||
(aborted_tx, mut aborted_rx),
|
||||
) = (unbounded(), unbounded(), unbounded(), unbounded());
|
||||
abort_when_account_balance_decreased(
|
||||
TestEnvironment {
|
||||
runtime_version_rx,
|
||||
free_native_balance_rx,
|
||||
slept_tx,
|
||||
aborted_tx,
|
||||
},
|
||||
0,
|
||||
100,
|
||||
);
|
||||
|
||||
// client responds with initial balance
|
||||
free_native_balance_tx.send(1000).await.unwrap();
|
||||
|
||||
// then the guard sleeps
|
||||
slept_rx.next().await;
|
||||
|
||||
// and then client responds with updated balance, which is enough
|
||||
free_native_balance_tx.send(950).await.unwrap();
|
||||
|
||||
// then the `sleep` function is called
|
||||
slept_rx.next().await;
|
||||
// and `abort` is not called
|
||||
assert!(aborted_rx.next().now_or_never().is_none());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// 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/>.
|
||||
|
||||
//! Tools to interact with Substrate node using RPC methods.
|
||||
|
||||
#![warn(missing_docs)]
|
||||
|
||||
mod chain;
|
||||
mod client;
|
||||
mod error;
|
||||
mod rpc;
|
||||
mod sync_header;
|
||||
mod transaction_tracker;
|
||||
|
||||
pub mod guard;
|
||||
pub mod metrics;
|
||||
pub mod test_chain;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
pub use crate::{
|
||||
chain::{
|
||||
AccountKeyPairOf, BlockWithJustification, CallOf, Chain, ChainWithBalances,
|
||||
ChainWithGrandpa, ChainWithMessages, ChainWithTransactions, RelayChain, SignParam,
|
||||
TransactionStatusOf, UnsignedTransaction, WeightToFeeOf,
|
||||
},
|
||||
client::{ChainRuntimeVersion, Client, OpaqueGrandpaAuthoritiesSet, Subscription},
|
||||
error::{Error, Result},
|
||||
rpc::{SubstrateBeefyFinalityClient, SubstrateFinalityClient, SubstrateGrandpaFinalityClient},
|
||||
sync_header::SyncHeader,
|
||||
transaction_tracker::TransactionTracker,
|
||||
};
|
||||
pub use bp_runtime::{
|
||||
AccountIdOf, AccountPublicOf, BalanceOf, BlockNumberOf, Chain as ChainBase, HashOf, HeaderOf,
|
||||
IndexOf, SignatureOf, TransactionEra, TransactionEraOf,
|
||||
};
|
||||
|
||||
/// Header id used by the chain.
|
||||
pub type HeaderIdOf<C> = relay_utils::HeaderId<HashOf<C>, BlockNumberOf<C>>;
|
||||
|
||||
/// Substrate-over-websocket connection params.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ConnectionParams {
|
||||
/// Websocket server host name.
|
||||
pub host: String,
|
||||
/// Websocket server TCP port.
|
||||
pub port: u16,
|
||||
/// Use secure websocket connection.
|
||||
pub secure: bool,
|
||||
/// Defined chain runtime version
|
||||
pub chain_runtime_version: ChainRuntimeVersion,
|
||||
}
|
||||
|
||||
impl Default for ConnectionParams {
|
||||
fn default() -> Self {
|
||||
ConnectionParams {
|
||||
host: "localhost".into(),
|
||||
port: 9944,
|
||||
secure: false,
|
||||
chain_runtime_version: ChainRuntimeVersion::Auto,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns stall timeout for relay loop.
|
||||
///
|
||||
/// Relay considers himself stalled if he has submitted transaction to the node, but it has not
|
||||
/// been mined for this period.
|
||||
pub fn transaction_stall_timeout(
|
||||
mortality_period: Option<u32>,
|
||||
average_block_interval: Duration,
|
||||
default_stall_timeout: Duration,
|
||||
) -> Duration {
|
||||
// 1 extra block for transaction to reach the pool && 1 for relayer to awake after it is mined
|
||||
mortality_period
|
||||
.map(|mortality_period| average_block_interval.saturating_mul(mortality_period + 1 + 1))
|
||||
.unwrap_or(default_stall_timeout)
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
// 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::{chain::Chain, client::Client, Error as SubstrateError};
|
||||
|
||||
use async_std::sync::{Arc, RwLock};
|
||||
use async_trait::async_trait;
|
||||
use codec::Decode;
|
||||
use num_traits::One;
|
||||
use relay_utils::metrics::{
|
||||
metric_name, register, F64SharedRef, Gauge, Metric, PrometheusError, Registry,
|
||||
StandaloneMetric, F64,
|
||||
};
|
||||
use sp_core::storage::{StorageData, StorageKey};
|
||||
use sp_runtime::{traits::UniqueSaturatedInto, FixedPointNumber, FixedU128};
|
||||
use std::{marker::PhantomData, time::Duration};
|
||||
|
||||
/// Storage value update interval (in blocks).
|
||||
const UPDATE_INTERVAL_IN_BLOCKS: u32 = 5;
|
||||
|
||||
/// Fied-point storage value and the way it is decoded from the raw storage value.
|
||||
pub trait FloatStorageValue: 'static + Clone + Send + Sync {
|
||||
/// Type of the value.
|
||||
type Value: FixedPointNumber;
|
||||
/// Try to decode value from the raw storage value.
|
||||
fn decode(
|
||||
&self,
|
||||
maybe_raw_value: Option<StorageData>,
|
||||
) -> Result<Option<Self::Value>, SubstrateError>;
|
||||
}
|
||||
|
||||
/// Implementation of `FloatStorageValue` that expects encoded `FixedU128` value and returns `1` if
|
||||
/// value is missing from the storage.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct FixedU128OrOne;
|
||||
|
||||
impl FloatStorageValue for FixedU128OrOne {
|
||||
type Value = FixedU128;
|
||||
|
||||
fn decode(
|
||||
&self,
|
||||
maybe_raw_value: Option<StorageData>,
|
||||
) -> Result<Option<Self::Value>, SubstrateError> {
|
||||
maybe_raw_value
|
||||
.map(|raw_value| {
|
||||
FixedU128::decode(&mut &raw_value.0[..])
|
||||
.map_err(SubstrateError::ResponseParseFailed)
|
||||
.map(Some)
|
||||
})
|
||||
.unwrap_or_else(|| Ok(Some(FixedU128::one())))
|
||||
}
|
||||
}
|
||||
|
||||
/// Metric that represents fixed-point runtime storage value as float gauge.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FloatStorageValueMetric<C: Chain, V: FloatStorageValue> {
|
||||
value_converter: V,
|
||||
client: Client<C>,
|
||||
storage_key: StorageKey,
|
||||
metric: Gauge<F64>,
|
||||
shared_value_ref: F64SharedRef,
|
||||
_phantom: PhantomData<V>,
|
||||
}
|
||||
|
||||
impl<C: Chain, V: FloatStorageValue> FloatStorageValueMetric<C, V> {
|
||||
/// Create new metric.
|
||||
pub fn new(
|
||||
value_converter: V,
|
||||
client: Client<C>,
|
||||
storage_key: StorageKey,
|
||||
name: String,
|
||||
help: String,
|
||||
) -> Result<Self, PrometheusError> {
|
||||
let shared_value_ref = Arc::new(RwLock::new(None));
|
||||
Ok(FloatStorageValueMetric {
|
||||
value_converter,
|
||||
client,
|
||||
storage_key,
|
||||
metric: Gauge::new(metric_name(None, &name), help)?,
|
||||
shared_value_ref,
|
||||
_phantom: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Get shared reference to metric value.
|
||||
pub fn shared_value_ref(&self) -> F64SharedRef {
|
||||
self.shared_value_ref.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: Chain, V: FloatStorageValue> Metric for FloatStorageValueMetric<C, V> {
|
||||
fn register(&self, registry: &Registry) -> Result<(), PrometheusError> {
|
||||
register(self.metric.clone(), registry).map(drop)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<C: Chain, V: FloatStorageValue> StandaloneMetric for FloatStorageValueMetric<C, V> {
|
||||
fn update_interval(&self) -> Duration {
|
||||
C::AVERAGE_BLOCK_INTERVAL * UPDATE_INTERVAL_IN_BLOCKS
|
||||
}
|
||||
|
||||
async fn update(&self) {
|
||||
let value = self
|
||||
.client
|
||||
.raw_storage_value(self.storage_key.clone(), None)
|
||||
.await
|
||||
.and_then(|maybe_storage_value| {
|
||||
self.value_converter.decode(maybe_storage_value).map(|maybe_fixed_point_value| {
|
||||
maybe_fixed_point_value.map(|fixed_point_value| {
|
||||
fixed_point_value.into_inner().unique_saturated_into() as f64 /
|
||||
V::Value::DIV.unique_saturated_into() as f64
|
||||
})
|
||||
})
|
||||
})
|
||||
.map_err(|e| e.to_string());
|
||||
relay_utils::metrics::set_gauge_value(&self.metric, value.clone());
|
||||
*self.shared_value_ref.write().await = value.ok().and_then(|x| x);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Contains several Substrate-specific metrics that may be exposed by relay.
|
||||
|
||||
pub use float_storage_value::{FixedU128OrOne, FloatStorageValue, FloatStorageValueMetric};
|
||||
|
||||
mod float_storage_value;
|
||||
@@ -0,0 +1,170 @@
|
||||
// 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/>.
|
||||
|
||||
//! The most generic Substrate node RPC interface.
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use crate::{Chain, ChainWithGrandpa, TransactionStatusOf};
|
||||
|
||||
use jsonrpsee::{
|
||||
core::{client::Subscription, RpcResult},
|
||||
proc_macros::rpc,
|
||||
ws_client::WsClient,
|
||||
};
|
||||
use pallet_transaction_payment_rpc_runtime_api::FeeDetails;
|
||||
use sc_rpc_api::{state::ReadProof, system::Health};
|
||||
use sp_core::{
|
||||
storage::{StorageData, StorageKey},
|
||||
Bytes,
|
||||
};
|
||||
use sp_rpc::number::NumberOrHex;
|
||||
use sp_version::RuntimeVersion;
|
||||
|
||||
/// RPC methods of Substrate `system` namespace, that we are using.
|
||||
#[rpc(client, client_bounds(C: Chain), namespace = "system")]
|
||||
pub(crate) trait SubstrateSystem<C> {
|
||||
/// Return node health.
|
||||
#[method(name = "health")]
|
||||
async fn health(&self) -> RpcResult<Health>;
|
||||
/// Return system properties.
|
||||
#[method(name = "properties")]
|
||||
async fn properties(&self) -> RpcResult<sc_chain_spec::Properties>;
|
||||
}
|
||||
|
||||
/// RPC methods of Substrate `chain` namespace, that we are using.
|
||||
#[rpc(client, client_bounds(C: Chain), namespace = "chain")]
|
||||
pub(crate) trait SubstrateChain<C> {
|
||||
/// Get block hash by its number.
|
||||
#[method(name = "getBlockHash")]
|
||||
async fn block_hash(&self, block_number: Option<C::BlockNumber>) -> RpcResult<C::Hash>;
|
||||
/// Return block header by its hash.
|
||||
#[method(name = "getHeader")]
|
||||
async fn header(&self, block_hash: Option<C::Hash>) -> RpcResult<C::Header>;
|
||||
/// Return best finalized block hash.
|
||||
#[method(name = "getFinalizedHead")]
|
||||
async fn finalized_head(&self) -> RpcResult<C::Hash>;
|
||||
/// Return signed block (with justifications) by its hash.
|
||||
#[method(name = "getBlock")]
|
||||
async fn block(&self, block_hash: Option<C::Hash>) -> RpcResult<C::SignedBlock>;
|
||||
}
|
||||
|
||||
/// RPC methods of Substrate `author` namespace, that we are using.
|
||||
#[rpc(client, client_bounds(C: Chain), namespace = "author")]
|
||||
pub(crate) trait SubstrateAuthor<C> {
|
||||
/// Submit extrinsic to the transaction pool.
|
||||
#[method(name = "submitExtrinsic")]
|
||||
async fn submit_extrinsic(&self, extrinsic: Bytes) -> RpcResult<C::Hash>;
|
||||
/// Return vector of pending extrinsics from the transaction pool.
|
||||
#[method(name = "pendingExtrinsics")]
|
||||
async fn pending_extrinsics(&self) -> RpcResult<Vec<Bytes>>;
|
||||
/// Submit and watch for extrinsic state.
|
||||
#[subscription(name = "submitAndWatchExtrinsic", unsubscribe = "unwatchExtrinsic", item = TransactionStatusOf<C>)]
|
||||
fn submit_and_watch_extrinsic(&self, extrinsic: Bytes);
|
||||
}
|
||||
|
||||
/// RPC methods of Substrate `state` namespace, that we are using.
|
||||
#[rpc(client, client_bounds(C: Chain), namespace = "state")]
|
||||
pub(crate) trait SubstrateState<C> {
|
||||
/// Get current runtime version.
|
||||
#[method(name = "getRuntimeVersion")]
|
||||
async fn runtime_version(&self) -> RpcResult<RuntimeVersion>;
|
||||
/// Call given runtime method.
|
||||
#[method(name = "call")]
|
||||
async fn call(
|
||||
&self,
|
||||
method: String,
|
||||
data: Bytes,
|
||||
at_block: Option<C::Hash>,
|
||||
) -> RpcResult<Bytes>;
|
||||
/// Get value of the runtime storage.
|
||||
#[method(name = "getStorage")]
|
||||
async fn storage(
|
||||
&self,
|
||||
key: StorageKey,
|
||||
at_block: Option<C::Hash>,
|
||||
) -> RpcResult<Option<StorageData>>;
|
||||
/// Get proof of the runtime storage value.
|
||||
#[method(name = "getReadProof")]
|
||||
async fn prove_storage(
|
||||
&self,
|
||||
keys: Vec<StorageKey>,
|
||||
hash: Option<C::Hash>,
|
||||
) -> RpcResult<ReadProof<C::Hash>>;
|
||||
}
|
||||
|
||||
/// RPC methods that we are using for a certain finality gadget.
|
||||
#[async_trait]
|
||||
pub trait SubstrateFinalityClient<C: Chain> {
|
||||
/// Subscribe to finality justifications.
|
||||
async fn subscribe_justifications(client: &WsClient) -> RpcResult<Subscription<Bytes>>;
|
||||
}
|
||||
|
||||
/// RPC methods of Substrate `grandpa` namespace, that we are using.
|
||||
#[rpc(client, client_bounds(C: ChainWithGrandpa), namespace = "grandpa")]
|
||||
pub(crate) trait SubstrateGrandpa<C> {
|
||||
/// Subscribe to GRANDPA justifications.
|
||||
#[subscription(name = "subscribeJustifications", unsubscribe = "unsubscribeJustifications", item = Bytes)]
|
||||
fn subscribe_justifications(&self);
|
||||
}
|
||||
|
||||
/// RPC finality methods of Substrate `grandpa` namespace, that we are using.
|
||||
pub struct SubstrateGrandpaFinalityClient;
|
||||
#[async_trait]
|
||||
impl<C: ChainWithGrandpa> SubstrateFinalityClient<C> for SubstrateGrandpaFinalityClient {
|
||||
async fn subscribe_justifications(client: &WsClient) -> RpcResult<Subscription<Bytes>> {
|
||||
SubstrateGrandpaClient::<C>::subscribe_justifications(client).await
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Use `ChainWithBeefy` instead of `Chain` after #1606 is merged
|
||||
/// RPC methods of Substrate `beefy` namespace, that we are using.
|
||||
#[rpc(client, client_bounds(C: Chain), namespace = "beefy")]
|
||||
pub(crate) trait SubstrateBeefy<C> {
|
||||
/// Subscribe to BEEFY justifications.
|
||||
#[subscription(name = "subscribeJustifications", unsubscribe = "unsubscribeJustifications", item = Bytes)]
|
||||
fn subscribe_justifications(&self);
|
||||
}
|
||||
|
||||
/// RPC finality methods of Substrate `beefy` namespace, that we are using.
|
||||
pub struct SubstrateBeefyFinalityClient;
|
||||
// TODO: Use `ChainWithBeefy` instead of `Chain` after #1606 is merged
|
||||
#[async_trait]
|
||||
impl<C: Chain> SubstrateFinalityClient<C> for SubstrateBeefyFinalityClient {
|
||||
async fn subscribe_justifications(client: &WsClient) -> RpcResult<Subscription<Bytes>> {
|
||||
SubstrateBeefyClient::<C>::subscribe_justifications(client).await
|
||||
}
|
||||
}
|
||||
|
||||
/// RPC methods of Substrate `system` frame pallet, that we are using.
|
||||
#[rpc(client, client_bounds(C: Chain), namespace = "system")]
|
||||
pub(crate) trait SubstrateFrameSystem<C> {
|
||||
/// Return index of next account transaction.
|
||||
#[method(name = "accountNextIndex")]
|
||||
async fn account_next_index(&self, account_id: C::AccountId) -> RpcResult<C::Index>;
|
||||
}
|
||||
|
||||
/// RPC methods of Substrate `pallet_transaction_payment` frame pallet, that we are using.
|
||||
#[rpc(client, client_bounds(C: Chain), namespace = "payment")]
|
||||
pub(crate) trait SubstrateTransactionPayment<C> {
|
||||
/// Query transaction fee details.
|
||||
#[method(name = "queryFeeDetails")]
|
||||
async fn fee_details(
|
||||
&self,
|
||||
extrinsic: Bytes,
|
||||
at_block: Option<C::Hash>,
|
||||
) -> RpcResult<FeeDetails<NumberOrHex>>;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// 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 bp_header_chain::ConsensusLogReader;
|
||||
use finality_relay::SourceHeader as FinalitySourceHeader;
|
||||
use sp_runtime::traits::Header as HeaderT;
|
||||
|
||||
/// Generic wrapper for `sp_runtime::traits::Header` based headers, that
|
||||
/// implements `finality_relay::SourceHeader` and may be used in headers sync directly.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SyncHeader<Header>(Header);
|
||||
|
||||
impl<Header> SyncHeader<Header> {
|
||||
/// Extracts wrapped header from self.
|
||||
pub fn into_inner(self) -> Header {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<Header> std::ops::Deref for SyncHeader<Header> {
|
||||
type Target = Header;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<Header> From<Header> for SyncHeader<Header> {
|
||||
fn from(header: Header) -> Self {
|
||||
Self(header)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Header: HeaderT, R: ConsensusLogReader> FinalitySourceHeader<Header::Hash, Header::Number, R>
|
||||
for SyncHeader<Header>
|
||||
{
|
||||
fn hash(&self) -> Header::Hash {
|
||||
self.0.hash()
|
||||
}
|
||||
|
||||
fn number(&self) -> Header::Number {
|
||||
*self.0.number()
|
||||
}
|
||||
|
||||
fn is_mandatory(&self) -> bool {
|
||||
R::schedules_authorities_change(self.digest())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// 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/>.
|
||||
|
||||
//! Pallet provides a set of guard functions that are running in background threads
|
||||
//! and are aborting process if some condition fails.
|
||||
|
||||
//! Test chain implementation to use in tests.
|
||||
|
||||
#![cfg(any(feature = "test-helpers", test))]
|
||||
|
||||
use crate::{Chain, ChainWithBalances};
|
||||
use frame_support::weights::Weight;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Chain that may be used in tests.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct TestChain;
|
||||
|
||||
impl bp_runtime::Chain for TestChain {
|
||||
type BlockNumber = u32;
|
||||
type Hash = sp_core::H256;
|
||||
type Hasher = sp_runtime::traits::BlakeTwo256;
|
||||
type Header = sp_runtime::generic::Header<u32, sp_runtime::traits::BlakeTwo256>;
|
||||
|
||||
type AccountId = u32;
|
||||
type Balance = u32;
|
||||
type Index = u32;
|
||||
type Signature = sp_runtime::testing::TestSignature;
|
||||
|
||||
fn max_extrinsic_size() -> u32 {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
fn max_extrinsic_weight() -> Weight {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
|
||||
impl Chain for TestChain {
|
||||
const NAME: &'static str = "Test";
|
||||
const TOKEN_ID: Option<&'static str> = None;
|
||||
const BEST_FINALIZED_HEADER_ID_METHOD: &'static str = "TestMethod";
|
||||
const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_millis(0);
|
||||
|
||||
type SignedBlock = sp_runtime::generic::SignedBlock<
|
||||
sp_runtime::generic::Block<Self::Header, sp_runtime::OpaqueExtrinsic>,
|
||||
>;
|
||||
type Call = ();
|
||||
}
|
||||
|
||||
impl ChainWithBalances for TestChain {
|
||||
fn account_info_storage_key(_account_id: &u32) -> sp_core::storage::StorageKey {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
// 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/>.
|
||||
|
||||
//! Helper for tracking transaction invalidation events.
|
||||
|
||||
use crate::{Chain, Client, Error, HashOf, HeaderIdOf, Subscription, TransactionStatusOf};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use futures::{future::Either, Future, FutureExt, Stream, StreamExt};
|
||||
use relay_utils::{HeaderId, TrackedTransactionStatus};
|
||||
use sp_runtime::traits::Header as _;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Transaction tracker environment.
|
||||
#[async_trait]
|
||||
pub trait Environment<C: Chain>: Send + Sync {
|
||||
/// Returns header id by its hash.
|
||||
async fn header_id_by_hash(&self, hash: HashOf<C>) -> Result<HeaderIdOf<C>, Error>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<C: Chain> Environment<C> for Client<C> {
|
||||
async fn header_id_by_hash(&self, hash: HashOf<C>) -> Result<HeaderIdOf<C>, Error> {
|
||||
self.header_by_hash(hash).await.map(|h| HeaderId(*h.number(), hash))
|
||||
}
|
||||
}
|
||||
|
||||
/// Substrate transaction tracker implementation.
|
||||
///
|
||||
/// Substrate node provides RPC API to submit and watch for transaction events. This way
|
||||
/// we may know when transaction is included into block, finalized or rejected. There are
|
||||
/// some edge cases, when we can't fully trust this mechanism - e.g. transaction may broadcasted
|
||||
/// and then dropped out of node transaction pool (some other cases are also possible - node
|
||||
/// restarts, connection lost, ...). Then we can't know for sure - what is currently happening
|
||||
/// with our transaction. Is the transaction really lost? Is it still alive on the chain network?
|
||||
///
|
||||
/// We have several options to handle such cases:
|
||||
///
|
||||
/// 1) hope that the transaction is still alive and wait for its mining until it is spoiled;
|
||||
///
|
||||
/// 2) assume that the transaction is lost and resubmit another transaction instantly;
|
||||
///
|
||||
/// 3) wait for some time (if transaction is mortal - then until block where it dies; if it is
|
||||
/// immortal - then for some time that we assume is long enough to mine it) and assume that
|
||||
/// it is lost.
|
||||
///
|
||||
/// This struct implements third option as it seems to be the most optimal.
|
||||
pub struct TransactionTracker<C: Chain, E> {
|
||||
environment: E,
|
||||
transaction_hash: HashOf<C>,
|
||||
stall_timeout: Duration,
|
||||
subscription: Subscription<TransactionStatusOf<C>>,
|
||||
}
|
||||
|
||||
impl<C: Chain, E: Environment<C>> TransactionTracker<C, E> {
|
||||
/// Create transaction tracker.
|
||||
pub fn new(
|
||||
environment: E,
|
||||
stall_timeout: Duration,
|
||||
transaction_hash: HashOf<C>,
|
||||
subscription: Subscription<TransactionStatusOf<C>>,
|
||||
) -> Self {
|
||||
Self { environment, stall_timeout, transaction_hash, subscription }
|
||||
}
|
||||
|
||||
/// Wait for final transaction status and return it along with last known internal invalidation
|
||||
/// status.
|
||||
async fn do_wait(
|
||||
self,
|
||||
wait_for_stall_timeout: impl Future<Output = ()>,
|
||||
wait_for_stall_timeout_rest: impl Future<Output = ()>,
|
||||
) -> (TrackedTransactionStatus<HeaderIdOf<C>>, Option<InvalidationStatus<HeaderIdOf<C>>>) {
|
||||
// sometimes we want to wait for the rest of the stall timeout even if
|
||||
// `wait_for_invalidation` has been "select"ed first => it is shared
|
||||
let wait_for_invalidation = watch_transaction_status::<_, C, _>(
|
||||
self.environment,
|
||||
self.transaction_hash,
|
||||
self.subscription.into_stream(),
|
||||
);
|
||||
futures::pin_mut!(wait_for_stall_timeout, wait_for_invalidation);
|
||||
|
||||
match futures::future::select(wait_for_stall_timeout, wait_for_invalidation).await {
|
||||
Either::Left((_, _)) => {
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"{} transaction {:?} is considered lost after timeout (no status response from the node)",
|
||||
C::NAME,
|
||||
self.transaction_hash,
|
||||
);
|
||||
|
||||
(TrackedTransactionStatus::Lost, None)
|
||||
},
|
||||
Either::Right((invalidation_status, _)) => match invalidation_status {
|
||||
InvalidationStatus::Finalized(at_block) =>
|
||||
(TrackedTransactionStatus::Finalized(at_block), Some(invalidation_status)),
|
||||
InvalidationStatus::Invalid =>
|
||||
(TrackedTransactionStatus::Lost, Some(invalidation_status)),
|
||||
InvalidationStatus::Lost => {
|
||||
// wait for the rest of stall timeout - this way we'll be sure that the
|
||||
// transaction is actually dead if it has been crafted properly
|
||||
wait_for_stall_timeout_rest.await;
|
||||
// if someone is still watching for our transaction, then we're reporting
|
||||
// an error here (which is treated as "transaction lost")
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"{} transaction {:?} is considered lost after timeout",
|
||||
C::NAME,
|
||||
self.transaction_hash,
|
||||
);
|
||||
|
||||
(TrackedTransactionStatus::Lost, Some(invalidation_status))
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<C: Chain, E: Environment<C>> relay_utils::TransactionTracker for TransactionTracker<C, E> {
|
||||
type HeaderId = HeaderIdOf<C>;
|
||||
|
||||
async fn wait(self) -> TrackedTransactionStatus<HeaderIdOf<C>> {
|
||||
let wait_for_stall_timeout = async_std::task::sleep(self.stall_timeout).shared();
|
||||
let wait_for_stall_timeout_rest = wait_for_stall_timeout.clone();
|
||||
self.do_wait(wait_for_stall_timeout, wait_for_stall_timeout_rest).await.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Transaction invalidation status.
|
||||
///
|
||||
/// Note that in places where the `TransactionTracker` is used, the finalization event will be
|
||||
/// ignored - relay loops are detecting the mining/finalization using their own
|
||||
/// techniques. That's why we're using `InvalidationStatus` here.
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum InvalidationStatus<BlockId> {
|
||||
/// Transaction has been included into block and finalized at given block.
|
||||
Finalized(BlockId),
|
||||
/// Transaction has been invalidated.
|
||||
Invalid,
|
||||
/// We have lost track of transaction status.
|
||||
Lost,
|
||||
}
|
||||
|
||||
/// Watch for transaction status until transaction is finalized or we lose track of its status.
|
||||
async fn watch_transaction_status<
|
||||
E: Environment<C>,
|
||||
C: Chain,
|
||||
S: Stream<Item = TransactionStatusOf<C>>,
|
||||
>(
|
||||
environment: E,
|
||||
transaction_hash: HashOf<C>,
|
||||
subscription: S,
|
||||
) -> InvalidationStatus<HeaderIdOf<C>> {
|
||||
futures::pin_mut!(subscription);
|
||||
|
||||
loop {
|
||||
match subscription.next().await {
|
||||
Some(TransactionStatusOf::<C>::Finalized((block_hash, _))) => {
|
||||
// the only "successful" outcome of this method is when the block with transaction
|
||||
// has been finalized
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"{} transaction {:?} has been finalized at block: {:?}",
|
||||
C::NAME,
|
||||
transaction_hash,
|
||||
block_hash,
|
||||
);
|
||||
|
||||
let header_id = match environment.header_id_by_hash(block_hash).await {
|
||||
Ok(header_id) => header_id,
|
||||
Err(e) => {
|
||||
log::error!(
|
||||
target: "bridge",
|
||||
"Failed to read header {:?} when watching for {} transaction {:?}: {:?}",
|
||||
block_hash,
|
||||
C::NAME,
|
||||
transaction_hash,
|
||||
e,
|
||||
);
|
||||
// that's the best option we have here
|
||||
return InvalidationStatus::Lost
|
||||
},
|
||||
};
|
||||
return InvalidationStatus::Finalized(header_id)
|
||||
},
|
||||
Some(TransactionStatusOf::<C>::Invalid) => {
|
||||
// if node says that the transaction is invalid, there are still chances that
|
||||
// it is not actually invalid - e.g. if the block where transaction has been
|
||||
// revalidated is retracted and transaction (at some other node pool) becomes
|
||||
// valid again on other fork. But let's assume that the chances of this event
|
||||
// are almost zero - there's a lot of things that must happen for this to be the
|
||||
// case.
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"{} transaction {:?} has been invalidated",
|
||||
C::NAME,
|
||||
transaction_hash,
|
||||
);
|
||||
return InvalidationStatus::Invalid
|
||||
},
|
||||
Some(TransactionStatusOf::<C>::Future) |
|
||||
Some(TransactionStatusOf::<C>::Ready) |
|
||||
Some(TransactionStatusOf::<C>::Broadcast(_)) => {
|
||||
// nothing important (for us) has happened
|
||||
},
|
||||
Some(TransactionStatusOf::<C>::InBlock(block_hash)) => {
|
||||
// TODO: read matching system event (ExtrinsicSuccess or ExtrinsicFailed), log it
|
||||
// here and use it later (on finality) for reporting invalid transaction
|
||||
// https://github.com/paritytech/parity-bridges-common/issues/1464
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"{} transaction {:?} has been included in block: {:?}",
|
||||
C::NAME,
|
||||
transaction_hash,
|
||||
block_hash,
|
||||
);
|
||||
},
|
||||
Some(TransactionStatusOf::<C>::Retracted(block_hash)) => {
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"{} transaction {:?} at block {:?} has been retracted",
|
||||
C::NAME,
|
||||
transaction_hash,
|
||||
block_hash,
|
||||
);
|
||||
},
|
||||
Some(TransactionStatusOf::<C>::FinalityTimeout(block_hash)) => {
|
||||
// finality is lagging? let's wait a bit more and report a stall
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"{} transaction {:?} block {:?} has not been finalized for too long",
|
||||
C::NAME,
|
||||
transaction_hash,
|
||||
block_hash,
|
||||
);
|
||||
return InvalidationStatus::Lost
|
||||
},
|
||||
Some(TransactionStatusOf::<C>::Usurped(new_transaction_hash)) => {
|
||||
// this may be result of our transaction resubmitter work or some manual
|
||||
// intervention. In both cases - let's start stall timeout, because the meaning
|
||||
// of transaction may have changed
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"{} transaction {:?} has been usurped by new transaction: {:?}",
|
||||
C::NAME,
|
||||
transaction_hash,
|
||||
new_transaction_hash,
|
||||
);
|
||||
return InvalidationStatus::Lost
|
||||
},
|
||||
Some(TransactionStatusOf::<C>::Dropped) => {
|
||||
// the transaction has been removed from the pool because of its limits. Let's wait
|
||||
// a bit and report a stall
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"{} transaction {:?} has been dropped from the pool",
|
||||
C::NAME,
|
||||
transaction_hash,
|
||||
);
|
||||
return InvalidationStatus::Lost
|
||||
},
|
||||
None => {
|
||||
// the status of transaction is unknown to us (the subscription has been closed?).
|
||||
// Let's wait a bit and report a stall
|
||||
return InvalidationStatus::Lost
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_chain::TestChain;
|
||||
use futures::{FutureExt, SinkExt};
|
||||
use sc_transaction_pool_api::TransactionStatus;
|
||||
|
||||
struct TestEnvironment(Result<HeaderIdOf<TestChain>, Error>);
|
||||
|
||||
#[async_trait]
|
||||
impl Environment<TestChain> for TestEnvironment {
|
||||
async fn header_id_by_hash(
|
||||
&self,
|
||||
_hash: HashOf<TestChain>,
|
||||
) -> Result<HeaderIdOf<TestChain>, Error> {
|
||||
self.0.as_ref().map_err(|_| Error::BridgePalletIsNotInitialized).cloned()
|
||||
}
|
||||
}
|
||||
|
||||
async fn on_transaction_status(
|
||||
status: TransactionStatus<HashOf<TestChain>, HashOf<TestChain>>,
|
||||
) -> Option<(
|
||||
TrackedTransactionStatus<HeaderIdOf<TestChain>>,
|
||||
InvalidationStatus<HeaderIdOf<TestChain>>,
|
||||
)> {
|
||||
let (mut sender, receiver) = futures::channel::mpsc::channel(1);
|
||||
let tx_tracker = TransactionTracker::<TestChain, TestEnvironment>::new(
|
||||
TestEnvironment(Ok(HeaderId(0, Default::default()))),
|
||||
Duration::from_secs(0),
|
||||
Default::default(),
|
||||
Subscription(async_std::sync::Mutex::new(receiver)),
|
||||
);
|
||||
|
||||
let wait_for_stall_timeout = futures::future::pending();
|
||||
let wait_for_stall_timeout_rest = futures::future::ready(());
|
||||
sender.send(Some(status)).await.unwrap();
|
||||
tx_tracker
|
||||
.do_wait(wait_for_stall_timeout, wait_for_stall_timeout_rest)
|
||||
.now_or_never()
|
||||
.map(|(ts, is)| (ts, is.unwrap()))
|
||||
}
|
||||
|
||||
#[async_std::test]
|
||||
async fn returns_finalized_on_finalized() {
|
||||
assert_eq!(
|
||||
on_transaction_status(TransactionStatus::Finalized(Default::default())).await,
|
||||
Some((
|
||||
TrackedTransactionStatus::Finalized(Default::default()),
|
||||
InvalidationStatus::Finalized(Default::default())
|
||||
)),
|
||||
);
|
||||
}
|
||||
|
||||
#[async_std::test]
|
||||
async fn returns_lost_on_finalized_and_environment_error() {
|
||||
assert_eq!(
|
||||
watch_transaction_status::<_, TestChain, _>(
|
||||
TestEnvironment(Err(Error::BridgePalletIsNotInitialized)),
|
||||
Default::default(),
|
||||
futures::stream::iter([TransactionStatus::Finalized(Default::default())])
|
||||
)
|
||||
.now_or_never(),
|
||||
Some(InvalidationStatus::Lost),
|
||||
);
|
||||
}
|
||||
|
||||
#[async_std::test]
|
||||
async fn returns_invalid_on_invalid() {
|
||||
assert_eq!(
|
||||
on_transaction_status(TransactionStatus::Invalid).await,
|
||||
Some((TrackedTransactionStatus::Lost, InvalidationStatus::Invalid)),
|
||||
);
|
||||
}
|
||||
|
||||
#[async_std::test]
|
||||
async fn waits_on_future() {
|
||||
assert_eq!(on_transaction_status(TransactionStatus::Future).await, None,);
|
||||
}
|
||||
|
||||
#[async_std::test]
|
||||
async fn waits_on_ready() {
|
||||
assert_eq!(on_transaction_status(TransactionStatus::Ready).await, None,);
|
||||
}
|
||||
|
||||
#[async_std::test]
|
||||
async fn waits_on_broadcast() {
|
||||
assert_eq!(
|
||||
on_transaction_status(TransactionStatus::Broadcast(Default::default())).await,
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
#[async_std::test]
|
||||
async fn waits_on_in_block() {
|
||||
assert_eq!(
|
||||
on_transaction_status(TransactionStatus::InBlock(Default::default())).await,
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
#[async_std::test]
|
||||
async fn waits_on_retracted() {
|
||||
assert_eq!(
|
||||
on_transaction_status(TransactionStatus::Retracted(Default::default())).await,
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
#[async_std::test]
|
||||
async fn lost_on_finality_timeout() {
|
||||
assert_eq!(
|
||||
on_transaction_status(TransactionStatus::FinalityTimeout(Default::default())).await,
|
||||
Some((TrackedTransactionStatus::Lost, InvalidationStatus::Lost)),
|
||||
);
|
||||
}
|
||||
|
||||
#[async_std::test]
|
||||
async fn lost_on_usurped() {
|
||||
assert_eq!(
|
||||
on_transaction_status(TransactionStatus::Usurped(Default::default())).await,
|
||||
Some((TrackedTransactionStatus::Lost, InvalidationStatus::Lost)),
|
||||
);
|
||||
}
|
||||
|
||||
#[async_std::test]
|
||||
async fn lost_on_dropped() {
|
||||
assert_eq!(
|
||||
on_transaction_status(TransactionStatus::Dropped).await,
|
||||
Some((TrackedTransactionStatus::Lost, InvalidationStatus::Lost)),
|
||||
);
|
||||
}
|
||||
|
||||
#[async_std::test]
|
||||
async fn lost_on_subscription_error() {
|
||||
assert_eq!(
|
||||
watch_transaction_status::<_, TestChain, _>(
|
||||
TestEnvironment(Ok(HeaderId(0, Default::default()))),
|
||||
Default::default(),
|
||||
futures::stream::iter([])
|
||||
)
|
||||
.now_or_never(),
|
||||
Some(InvalidationStatus::Lost),
|
||||
);
|
||||
}
|
||||
|
||||
#[async_std::test]
|
||||
async fn lost_on_timeout_when_waiting_for_invalidation_status() {
|
||||
let (_sender, receiver) = futures::channel::mpsc::channel(1);
|
||||
let tx_tracker = TransactionTracker::<TestChain, TestEnvironment>::new(
|
||||
TestEnvironment(Ok(HeaderId(0, Default::default()))),
|
||||
Duration::from_secs(0),
|
||||
Default::default(),
|
||||
Subscription(async_std::sync::Mutex::new(receiver)),
|
||||
);
|
||||
|
||||
let wait_for_stall_timeout = futures::future::ready(()).shared();
|
||||
let wait_for_stall_timeout_rest = wait_for_stall_timeout.clone();
|
||||
let wait_result = tx_tracker
|
||||
.do_wait(wait_for_stall_timeout, wait_for_stall_timeout_rest)
|
||||
.now_or_never();
|
||||
|
||||
assert_eq!(wait_result, Some((TrackedTransactionStatus::Lost, None)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "relay-westend-client"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
relay-substrate-client = { path = "../client-substrate" }
|
||||
relay-utils = { path = "../utils" }
|
||||
|
||||
# Bridge dependencies
|
||||
|
||||
bp-westend = { path = "../../primitives/chain-westend" }
|
||||
|
||||
# Substrate Dependencies
|
||||
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
@@ -0,0 +1,119 @@
|
||||
// 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/>.
|
||||
|
||||
//! Types used to connect to the Westend chain.
|
||||
|
||||
use frame_support::weights::Weight;
|
||||
use relay_substrate_client::{Chain, ChainBase, ChainWithBalances, ChainWithGrandpa, RelayChain};
|
||||
use sp_core::storage::StorageKey;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Westend header id.
|
||||
pub type HeaderId = relay_utils::HeaderId<bp_westend::Hash, bp_westend::BlockNumber>;
|
||||
|
||||
/// Westend header type used in headers sync.
|
||||
pub type SyncHeader = relay_substrate_client::SyncHeader<bp_westend::Header>;
|
||||
|
||||
/// Westend chain definition
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Westend;
|
||||
|
||||
impl ChainBase for Westend {
|
||||
type BlockNumber = bp_westend::BlockNumber;
|
||||
type Hash = bp_westend::Hash;
|
||||
type Hasher = bp_westend::Hasher;
|
||||
type Header = bp_westend::Header;
|
||||
|
||||
type AccountId = bp_westend::AccountId;
|
||||
type Balance = bp_westend::Balance;
|
||||
type Index = bp_westend::Nonce;
|
||||
type Signature = bp_westend::Signature;
|
||||
|
||||
fn max_extrinsic_size() -> u32 {
|
||||
bp_westend::Westend::max_extrinsic_size()
|
||||
}
|
||||
|
||||
fn max_extrinsic_weight() -> Weight {
|
||||
bp_westend::Westend::max_extrinsic_weight()
|
||||
}
|
||||
}
|
||||
|
||||
impl Chain for Westend {
|
||||
const NAME: &'static str = "Westend";
|
||||
const TOKEN_ID: Option<&'static str> = None;
|
||||
const BEST_FINALIZED_HEADER_ID_METHOD: &'static str =
|
||||
bp_westend::BEST_FINALIZED_WESTEND_HEADER_METHOD;
|
||||
const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_secs(6);
|
||||
|
||||
type SignedBlock = bp_westend::SignedBlock;
|
||||
type Call = ();
|
||||
}
|
||||
|
||||
impl RelayChain for Westend {
|
||||
const PARAS_PALLET_NAME: &'static str = bp_westend::PARAS_PALLET_NAME;
|
||||
const PARACHAINS_FINALITY_PALLET_NAME: &'static str =
|
||||
bp_westend::WITH_WESTEND_BRIDGE_PARAS_PALLET_NAME;
|
||||
}
|
||||
|
||||
impl ChainWithGrandpa for Westend {
|
||||
const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str =
|
||||
bp_westend::WITH_WESTEND_GRANDPA_PALLET_NAME;
|
||||
}
|
||||
|
||||
impl ChainWithBalances for Westend {
|
||||
fn account_info_storage_key(account_id: &Self::AccountId) -> StorageKey {
|
||||
bp_westend::AccountInfoStorageMapKeyProvider::final_key(account_id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Westmint parachain definition
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Westmint;
|
||||
|
||||
// Westmint seems to use the same configuration as all Polkadot-like chains, so we'll use Westend
|
||||
// primitives here.
|
||||
impl ChainBase for Westmint {
|
||||
type BlockNumber = bp_westend::BlockNumber;
|
||||
type Hash = bp_westend::Hash;
|
||||
type Hasher = bp_westend::Hasher;
|
||||
type Header = bp_westend::Header;
|
||||
|
||||
type AccountId = bp_westend::AccountId;
|
||||
type Balance = bp_westend::Balance;
|
||||
type Index = bp_westend::Nonce;
|
||||
type Signature = bp_westend::Signature;
|
||||
|
||||
fn max_extrinsic_size() -> u32 {
|
||||
bp_westend::Westend::max_extrinsic_size()
|
||||
}
|
||||
|
||||
fn max_extrinsic_weight() -> Weight {
|
||||
bp_westend::Westend::max_extrinsic_weight()
|
||||
}
|
||||
}
|
||||
|
||||
// Westmint seems to use the same configuration as all Polkadot-like chains, so we'll use Westend
|
||||
// primitives here.
|
||||
impl Chain for Westmint {
|
||||
const NAME: &'static str = "Westmint";
|
||||
const TOKEN_ID: Option<&'static str> = None;
|
||||
const BEST_FINALIZED_HEADER_ID_METHOD: &'static str =
|
||||
bp_westend::BEST_FINALIZED_WESTMINT_HEADER_METHOD;
|
||||
const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_secs(6);
|
||||
|
||||
type SignedBlock = bp_westend::SignedBlock;
|
||||
type Call = ();
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "relay-wococo-client"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
relay-substrate-client = { path = "../client-substrate" }
|
||||
relay-utils = { path = "../utils" }
|
||||
|
||||
# Bridge dependencies
|
||||
|
||||
bp-wococo = { path = "../../primitives/chain-wococo" }
|
||||
|
||||
# Substrate Dependencies
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
@@ -0,0 +1,78 @@
|
||||
// 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/>.
|
||||
|
||||
//! Types used to connect to the Wococo-Substrate chain.
|
||||
|
||||
use frame_support::weights::Weight;
|
||||
use relay_substrate_client::{Chain, ChainBase, ChainWithBalances, ChainWithGrandpa, RelayChain};
|
||||
use sp_core::storage::StorageKey;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Wococo header id.
|
||||
pub type HeaderId = relay_utils::HeaderId<bp_wococo::Hash, bp_wococo::BlockNumber>;
|
||||
|
||||
/// Wococo header type used in headers sync.
|
||||
pub type SyncHeader = relay_substrate_client::SyncHeader<bp_wococo::Header>;
|
||||
|
||||
/// Wococo chain definition
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Wococo;
|
||||
|
||||
impl ChainBase for Wococo {
|
||||
type BlockNumber = bp_wococo::BlockNumber;
|
||||
type Hash = bp_wococo::Hash;
|
||||
type Hasher = bp_wococo::Hashing;
|
||||
type Header = bp_wococo::Header;
|
||||
|
||||
type AccountId = bp_wococo::AccountId;
|
||||
type Balance = bp_wococo::Balance;
|
||||
type Index = bp_wococo::Nonce;
|
||||
type Signature = bp_wococo::Signature;
|
||||
|
||||
fn max_extrinsic_size() -> u32 {
|
||||
bp_wococo::Wococo::max_extrinsic_size()
|
||||
}
|
||||
|
||||
fn max_extrinsic_weight() -> Weight {
|
||||
bp_wococo::Wococo::max_extrinsic_weight()
|
||||
}
|
||||
}
|
||||
|
||||
impl Chain for Wococo {
|
||||
const NAME: &'static str = "Wococo";
|
||||
const TOKEN_ID: Option<&'static str> = None;
|
||||
const BEST_FINALIZED_HEADER_ID_METHOD: &'static str =
|
||||
bp_wococo::BEST_FINALIZED_WOCOCO_HEADER_METHOD;
|
||||
const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_secs(6);
|
||||
|
||||
type SignedBlock = bp_wococo::SignedBlock;
|
||||
type Call = ();
|
||||
}
|
||||
|
||||
impl ChainWithGrandpa for Wococo {
|
||||
const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str = bp_wococo::WITH_WOCOCO_GRANDPA_PALLET_NAME;
|
||||
}
|
||||
|
||||
impl ChainWithBalances for Wococo {
|
||||
fn account_info_storage_key(account_id: &Self::AccountId) -> StorageKey {
|
||||
bp_wococo::AccountInfoStorageMapKeyProvider::final_key(account_id)
|
||||
}
|
||||
}
|
||||
|
||||
impl RelayChain for Wococo {
|
||||
const PARAS_PALLET_NAME: &'static str = bp_wococo::PARAS_PALLET_NAME;
|
||||
const PARACHAINS_FINALITY_PALLET_NAME: &'static str = "bridgeWococoParachain";
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "finality-relay"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
description = "Finality proofs relay"
|
||||
|
||||
[dependencies]
|
||||
async-std = "1.6.5"
|
||||
async-trait = "0.1"
|
||||
backoff = "0.2"
|
||||
bp-header-chain = { path = "../../primitives/header-chain" }
|
||||
futures = "0.3.5"
|
||||
log = "0.4.17"
|
||||
num-traits = "0.2"
|
||||
relay-utils = { path = "../utils" }
|
||||
|
||||
[dev-dependencies]
|
||||
parking_lot = "0.11.0"
|
||||
@@ -0,0 +1,761 @@
|
||||
// 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/>.
|
||||
|
||||
//! The loop basically reads all missing headers and their finality proofs from the source client.
|
||||
//! The proof for the best possible header is then submitted to the target node. The only exception
|
||||
//! is the mandatory headers, which we always submit to the target node. For such headers, we
|
||||
//! assume that the persistent proof either exists, or will eventually become available.
|
||||
|
||||
use crate::{
|
||||
sync_loop_metrics::SyncLoopMetrics, FinalityProof, FinalitySyncPipeline, SourceHeader,
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use backoff::backoff::Backoff;
|
||||
use futures::{select, Future, FutureExt, Stream, StreamExt};
|
||||
use num_traits::{One, Saturating};
|
||||
use relay_utils::{
|
||||
metrics::MetricsParams, relay_loop::Client as RelayClient, retry_backoff, FailedClient,
|
||||
HeaderId, MaybeConnectionError, TrackedTransactionStatus, TransactionTracker,
|
||||
};
|
||||
use std::{
|
||||
fmt::Debug,
|
||||
pin::Pin,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
/// Finality proof synchronization loop parameters.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FinalitySyncParams {
|
||||
/// Interval at which we check updates on both clients. Normally should be larger than
|
||||
/// `min(source_block_time, target_block_time)`.
|
||||
///
|
||||
/// This parameter may be used to limit transactions rate. Increase the value && you'll get
|
||||
/// infrequent updates => sparse headers => potential slow down of bridge applications, but
|
||||
/// pallet storage won't be super large. Decrease the value to near `source_block_time` and
|
||||
/// you'll get transaction for (almost) every block of the source chain => all source headers
|
||||
/// will be known to the target chain => bridge applications will run faster, but pallet
|
||||
/// storage may explode (but if pruning is there, then it's fine).
|
||||
pub tick: Duration,
|
||||
/// Number of finality proofs to keep in internal buffer between loop iterations.
|
||||
///
|
||||
/// While in "major syncing" state, we still read finality proofs from the stream. They're
|
||||
/// stored in the internal buffer between loop iterations. When we're close to the tip of the
|
||||
/// chain, we may meet finality delays if headers are not finalized frequently. So instead of
|
||||
/// waiting for next finality proof to appear in the stream, we may use existing proof from
|
||||
/// that buffer.
|
||||
pub recent_finality_proofs_limit: usize,
|
||||
/// Timeout before we treat our transactions as lost and restart the whole sync process.
|
||||
pub stall_timeout: Duration,
|
||||
/// If true, only mandatory headers are relayed.
|
||||
pub only_mandatory_headers: bool,
|
||||
}
|
||||
|
||||
/// Source client used in finality synchronization loop.
|
||||
#[async_trait]
|
||||
pub trait SourceClient<P: FinalitySyncPipeline>: RelayClient {
|
||||
/// Stream of new finality proofs. The stream is allowed to miss proofs for some
|
||||
/// headers, even if those headers are mandatory.
|
||||
type FinalityProofsStream: Stream<Item = P::FinalityProof> + Send;
|
||||
|
||||
/// Get best finalized block number.
|
||||
async fn best_finalized_block_number(&self) -> Result<P::Number, Self::Error>;
|
||||
|
||||
/// Get canonical header and its finality proof by number.
|
||||
async fn header_and_finality_proof(
|
||||
&self,
|
||||
number: P::Number,
|
||||
) -> Result<(P::Header, Option<P::FinalityProof>), Self::Error>;
|
||||
|
||||
/// Subscribe to new finality proofs.
|
||||
async fn finality_proofs(&self) -> Result<Self::FinalityProofsStream, Self::Error>;
|
||||
}
|
||||
|
||||
/// Target client used in finality synchronization loop.
|
||||
#[async_trait]
|
||||
pub trait TargetClient<P: FinalitySyncPipeline>: RelayClient {
|
||||
/// Transaction tracker to track submitted transactions.
|
||||
type TransactionTracker: TransactionTracker;
|
||||
|
||||
/// Get best finalized source block number.
|
||||
async fn best_finalized_source_block_id(
|
||||
&self,
|
||||
) -> Result<HeaderId<P::Hash, P::Number>, Self::Error>;
|
||||
|
||||
/// Submit header finality proof.
|
||||
async fn submit_finality_proof(
|
||||
&self,
|
||||
header: P::Header,
|
||||
proof: P::FinalityProof,
|
||||
) -> Result<Self::TransactionTracker, Self::Error>;
|
||||
}
|
||||
|
||||
/// Return prefix that will be used by default to expose Prometheus metrics of the finality proofs
|
||||
/// sync loop.
|
||||
pub fn metrics_prefix<P: FinalitySyncPipeline>() -> String {
|
||||
format!("{}_to_{}_Sync", P::SOURCE_NAME, P::TARGET_NAME)
|
||||
}
|
||||
|
||||
/// Run finality proofs synchronization loop.
|
||||
pub async fn run<P: FinalitySyncPipeline>(
|
||||
source_client: impl SourceClient<P>,
|
||||
target_client: impl TargetClient<P>,
|
||||
sync_params: FinalitySyncParams,
|
||||
metrics_params: MetricsParams,
|
||||
exit_signal: impl Future<Output = ()> + 'static + Send,
|
||||
) -> Result<(), relay_utils::Error> {
|
||||
let exit_signal = exit_signal.shared();
|
||||
relay_utils::relay_loop(source_client, target_client)
|
||||
.with_metrics(metrics_params)
|
||||
.loop_metric(SyncLoopMetrics::new(
|
||||
Some(&metrics_prefix::<P>()),
|
||||
"source",
|
||||
"source_at_target",
|
||||
)?)?
|
||||
.expose()
|
||||
.await?
|
||||
.run(metrics_prefix::<P>(), move |source_client, target_client, metrics| {
|
||||
run_until_connection_lost(
|
||||
source_client,
|
||||
target_client,
|
||||
sync_params.clone(),
|
||||
metrics,
|
||||
exit_signal.clone(),
|
||||
)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Unjustified headers container. Ordered by header number.
|
||||
pub(crate) type UnjustifiedHeaders<H> = Vec<H>;
|
||||
/// Finality proofs container. Ordered by target header number.
|
||||
pub(crate) type FinalityProofs<P> =
|
||||
Vec<(<P as FinalitySyncPipeline>::Number, <P as FinalitySyncPipeline>::FinalityProof)>;
|
||||
/// Reference to finality proofs container.
|
||||
pub(crate) type FinalityProofsRef<'a, P> =
|
||||
&'a [(<P as FinalitySyncPipeline>::Number, <P as FinalitySyncPipeline>::FinalityProof)];
|
||||
|
||||
/// Error that may happen inside finality synchronization loop.
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum Error<P: FinalitySyncPipeline, SourceError, TargetError> {
|
||||
/// Source client request has failed with given error.
|
||||
Source(SourceError),
|
||||
/// Target client request has failed with given error.
|
||||
Target(TargetError),
|
||||
/// Finality proof for mandatory header is missing from the source node.
|
||||
MissingMandatoryFinalityProof(P::Number),
|
||||
}
|
||||
|
||||
impl<P, SourceError, TargetError> Error<P, SourceError, TargetError>
|
||||
where
|
||||
P: FinalitySyncPipeline,
|
||||
SourceError: MaybeConnectionError,
|
||||
TargetError: MaybeConnectionError,
|
||||
{
|
||||
fn fail_if_connection_error(&self) -> Result<(), FailedClient> {
|
||||
match *self {
|
||||
Error::Source(ref error) if error.is_connection_error() => Err(FailedClient::Source),
|
||||
Error::Target(ref error) if error.is_connection_error() => Err(FailedClient::Target),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Information about transaction that we have submitted.
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct Transaction<Tracker, Number> {
|
||||
/// Submitted transaction tracker.
|
||||
pub tracker: Tracker,
|
||||
/// The number of the header we have submitted.
|
||||
pub submitted_header_number: Number,
|
||||
}
|
||||
|
||||
impl<Tracker: TransactionTracker, Number: Debug + PartialOrd> Transaction<Tracker, Number> {
|
||||
pub async fn submit<
|
||||
C: TargetClient<P, TransactionTracker = Tracker>,
|
||||
P: FinalitySyncPipeline<Number = Number>,
|
||||
>(
|
||||
target_client: &C,
|
||||
header: P::Header,
|
||||
justification: P::FinalityProof,
|
||||
) -> Result<Self, C::Error> {
|
||||
let submitted_header_number = header.number();
|
||||
log::debug!(
|
||||
target: "bridge",
|
||||
"Going to submit finality proof of {} header #{:?} to {}",
|
||||
P::SOURCE_NAME,
|
||||
submitted_header_number,
|
||||
P::TARGET_NAME,
|
||||
);
|
||||
|
||||
let tracker = target_client.submit_finality_proof(header, justification).await?;
|
||||
Ok(Transaction { tracker, submitted_header_number })
|
||||
}
|
||||
|
||||
pub async fn track<C: TargetClient<P>, P: FinalitySyncPipeline<Number = Number>>(
|
||||
self,
|
||||
target_client: &C,
|
||||
) -> Result<(), String> {
|
||||
match self.tracker.wait().await {
|
||||
TrackedTransactionStatus::Finalized(_) => {
|
||||
// The transaction has been finalized, but it may have been finalized in the
|
||||
// "failed" state. So let's check if the block number was actually updated.
|
||||
// If it wasn't then we are stalled.
|
||||
//
|
||||
// Please also note that we're returning an error if we fail to read required data
|
||||
// from the target client - that's the best we can do here to avoid actual stall.
|
||||
target_client
|
||||
.best_finalized_source_block_id()
|
||||
.await
|
||||
.map_err(|e| format!("failed to read best block from target node: {e:?}"))
|
||||
.and_then(|best_id_at_target| {
|
||||
if self.submitted_header_number > best_id_at_target.0 {
|
||||
return Err(format!(
|
||||
"best block at target after tx is {:?} and we've submitted {:?}",
|
||||
best_id_at_target.0, self.submitted_header_number,
|
||||
))
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
},
|
||||
TrackedTransactionStatus::Lost => Err("transaction failed".to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Finality proofs stream that may be restarted.
|
||||
pub(crate) struct RestartableFinalityProofsStream<S> {
|
||||
/// Flag that the stream needs to be restarted.
|
||||
pub(crate) needs_restart: bool,
|
||||
/// The stream itself.
|
||||
stream: Pin<Box<S>>,
|
||||
}
|
||||
|
||||
impl<S: Stream> RestartableFinalityProofsStream<S> {
|
||||
pub async fn create_raw_stream<
|
||||
C: SourceClient<P, FinalityProofsStream = S>,
|
||||
P: FinalitySyncPipeline,
|
||||
>(
|
||||
source_client: &C,
|
||||
) -> Result<S, FailedClient> {
|
||||
source_client.finality_proofs().await.map_err(|error| {
|
||||
log::error!(
|
||||
target: "bridge",
|
||||
"Failed to subscribe to {} justifications: {:?}. Going to reconnect",
|
||||
P::SOURCE_NAME,
|
||||
error,
|
||||
);
|
||||
|
||||
FailedClient::Source
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn restart_if_scheduled<
|
||||
C: SourceClient<P, FinalityProofsStream = S>,
|
||||
P: FinalitySyncPipeline,
|
||||
>(
|
||||
&mut self,
|
||||
source_client: &C,
|
||||
) -> Result<(), FailedClient> {
|
||||
if self.needs_restart {
|
||||
log::warn!(target: "bridge", "{} finality proofs stream is being restarted", P::SOURCE_NAME);
|
||||
|
||||
self.needs_restart = false;
|
||||
self.stream = Box::pin(Self::create_raw_stream(source_client).await?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn next(&mut self) -> Option<S::Item> {
|
||||
match self.stream.next().now_or_never() {
|
||||
Some(Some(finality_proof)) => Some(finality_proof),
|
||||
Some(None) => {
|
||||
self.needs_restart = true;
|
||||
None
|
||||
},
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> From<S> for RestartableFinalityProofsStream<S> {
|
||||
fn from(stream: S) -> Self {
|
||||
RestartableFinalityProofsStream { needs_restart: false, stream: Box::pin(stream) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Finality synchronization loop state.
|
||||
pub(crate) struct FinalityLoopState<'a, P: FinalitySyncPipeline, FinalityProofsStream> {
|
||||
/// Synchronization loop progress.
|
||||
pub(crate) progress: &'a mut (Instant, Option<P::Number>),
|
||||
/// Finality proofs stream.
|
||||
pub(crate) finality_proofs_stream:
|
||||
&'a mut RestartableFinalityProofsStream<FinalityProofsStream>,
|
||||
/// Recent finality proofs that we have read from the stream.
|
||||
pub(crate) recent_finality_proofs: &'a mut FinalityProofs<P>,
|
||||
/// Number of the last header, submitted to the target node.
|
||||
pub(crate) submitted_header_number: Option<P::Number>,
|
||||
}
|
||||
|
||||
/// Run finality relay loop until connection to one of nodes is lost.
|
||||
pub(crate) async fn run_until_connection_lost<P: FinalitySyncPipeline>(
|
||||
source_client: impl SourceClient<P>,
|
||||
target_client: impl TargetClient<P>,
|
||||
sync_params: FinalitySyncParams,
|
||||
metrics_sync: Option<SyncLoopMetrics>,
|
||||
exit_signal: impl Future<Output = ()>,
|
||||
) -> Result<(), FailedClient> {
|
||||
let last_transaction_tracker = futures::future::Fuse::terminated();
|
||||
let exit_signal = exit_signal.fuse();
|
||||
futures::pin_mut!(last_transaction_tracker, exit_signal);
|
||||
|
||||
let mut finality_proofs_stream =
|
||||
RestartableFinalityProofsStream::create_raw_stream(&source_client).await?.into();
|
||||
let mut recent_finality_proofs = Vec::new();
|
||||
|
||||
let mut progress = (Instant::now(), None);
|
||||
let mut retry_backoff = retry_backoff();
|
||||
let mut last_submitted_header_number = None;
|
||||
|
||||
loop {
|
||||
// run loop iteration
|
||||
let iteration_result = run_loop_iteration(
|
||||
&source_client,
|
||||
&target_client,
|
||||
FinalityLoopState {
|
||||
progress: &mut progress,
|
||||
finality_proofs_stream: &mut finality_proofs_stream,
|
||||
recent_finality_proofs: &mut recent_finality_proofs,
|
||||
submitted_header_number: last_submitted_header_number,
|
||||
},
|
||||
&sync_params,
|
||||
&metrics_sync,
|
||||
)
|
||||
.await;
|
||||
|
||||
// deal with errors
|
||||
let next_tick = match iteration_result {
|
||||
Ok(Some(updated_transaction)) => {
|
||||
last_submitted_header_number = Some(updated_transaction.submitted_header_number);
|
||||
last_transaction_tracker.set(updated_transaction.track(&target_client).fuse());
|
||||
retry_backoff.reset();
|
||||
sync_params.tick
|
||||
},
|
||||
Ok(None) => {
|
||||
retry_backoff.reset();
|
||||
sync_params.tick
|
||||
},
|
||||
Err(error) => {
|
||||
log::error!(target: "bridge", "Finality sync loop iteration has failed with error: {:?}", error);
|
||||
error.fail_if_connection_error()?;
|
||||
retry_backoff.next_backoff().unwrap_or(relay_utils::relay_loop::RECONNECT_DELAY)
|
||||
},
|
||||
};
|
||||
finality_proofs_stream.restart_if_scheduled(&source_client).await?;
|
||||
|
||||
// wait till exit signal, or new source block
|
||||
select! {
|
||||
transaction_result = last_transaction_tracker => {
|
||||
transaction_result.map_err(|e| {
|
||||
log::error!(
|
||||
target: "bridge",
|
||||
"Finality synchronization from {} to {} has stalled with error: {}. Going to restart",
|
||||
P::SOURCE_NAME,
|
||||
P::TARGET_NAME,
|
||||
e,
|
||||
);
|
||||
|
||||
// Restart the loop if we're stalled.
|
||||
FailedClient::Both
|
||||
})?
|
||||
},
|
||||
_ = async_std::task::sleep(next_tick).fuse() => {},
|
||||
_ = exit_signal => return Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn run_loop_iteration<P, SC, TC>(
|
||||
source_client: &SC,
|
||||
target_client: &TC,
|
||||
state: FinalityLoopState<'_, P, SC::FinalityProofsStream>,
|
||||
sync_params: &FinalitySyncParams,
|
||||
metrics_sync: &Option<SyncLoopMetrics>,
|
||||
) -> Result<Option<Transaction<TC::TransactionTracker, P::Number>>, Error<P, SC::Error, TC::Error>>
|
||||
where
|
||||
P: FinalitySyncPipeline,
|
||||
SC: SourceClient<P>,
|
||||
TC: TargetClient<P>,
|
||||
{
|
||||
// read best source headers ids from source and target nodes
|
||||
let best_number_at_source =
|
||||
source_client.best_finalized_block_number().await.map_err(Error::Source)?;
|
||||
let best_id_at_target =
|
||||
target_client.best_finalized_source_block_id().await.map_err(Error::Target)?;
|
||||
let best_number_at_target = best_id_at_target.0;
|
||||
|
||||
let different_hash_at_source = ensure_same_fork::<P, _>(&best_id_at_target, source_client)
|
||||
.await
|
||||
.map_err(Error::Source)?;
|
||||
let using_same_fork = different_hash_at_source.is_none();
|
||||
if let Some(ref different_hash_at_source) = different_hash_at_source {
|
||||
log::error!(
|
||||
target: "bridge",
|
||||
"Source node ({}) and pallet at target node ({}) have different headers at the same height {:?}: \
|
||||
at-source {:?} vs at-target {:?}",
|
||||
P::SOURCE_NAME,
|
||||
P::TARGET_NAME,
|
||||
best_number_at_target,
|
||||
different_hash_at_source,
|
||||
best_id_at_target.1,
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(ref metrics_sync) = *metrics_sync {
|
||||
metrics_sync.update_best_block_at_source(best_number_at_source);
|
||||
metrics_sync.update_best_block_at_target(best_number_at_target);
|
||||
metrics_sync.update_using_same_fork(using_same_fork);
|
||||
}
|
||||
*state.progress =
|
||||
print_sync_progress::<P>(*state.progress, best_number_at_source, best_number_at_target);
|
||||
|
||||
// if we have already submitted header, then we just need to wait for it
|
||||
// if we're waiting too much, then we believe our transaction has been lost and restart sync
|
||||
if let Some(submitted_header_number) = state.submitted_header_number {
|
||||
if best_number_at_target >= submitted_header_number {
|
||||
// transaction has been mined && we can continue
|
||||
} else {
|
||||
return Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
// submit new header if we have something new
|
||||
match select_header_to_submit(
|
||||
source_client,
|
||||
target_client,
|
||||
state.finality_proofs_stream,
|
||||
state.recent_finality_proofs,
|
||||
best_number_at_source,
|
||||
best_number_at_target,
|
||||
sync_params,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
Some((header, justification)) => {
|
||||
let transaction = Transaction::submit(target_client, header, justification)
|
||||
.await
|
||||
.map_err(Error::Target)?;
|
||||
Ok(Some(transaction))
|
||||
},
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn select_header_to_submit<P, SC, TC>(
|
||||
source_client: &SC,
|
||||
target_client: &TC,
|
||||
finality_proofs_stream: &mut RestartableFinalityProofsStream<SC::FinalityProofsStream>,
|
||||
recent_finality_proofs: &mut FinalityProofs<P>,
|
||||
best_number_at_source: P::Number,
|
||||
best_number_at_target: P::Number,
|
||||
sync_params: &FinalitySyncParams,
|
||||
) -> Result<Option<(P::Header, P::FinalityProof)>, Error<P, SC::Error, TC::Error>>
|
||||
where
|
||||
P: FinalitySyncPipeline,
|
||||
SC: SourceClient<P>,
|
||||
TC: TargetClient<P>,
|
||||
{
|
||||
// to see that the loop is progressing
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"Considering range of headers ({:?}; {:?}]",
|
||||
best_number_at_target,
|
||||
best_number_at_source,
|
||||
);
|
||||
|
||||
// read missing headers. if we see that the header schedules GRANDPA change, we need to
|
||||
// submit this header
|
||||
let selected_finality_proof = read_missing_headers::<P, SC, TC>(
|
||||
source_client,
|
||||
target_client,
|
||||
best_number_at_source,
|
||||
best_number_at_target,
|
||||
)
|
||||
.await?;
|
||||
let (mut unjustified_headers, mut selected_finality_proof) = match selected_finality_proof {
|
||||
SelectedFinalityProof::Mandatory(header, finality_proof) =>
|
||||
return Ok(Some((header, finality_proof))),
|
||||
_ if sync_params.only_mandatory_headers => {
|
||||
// we are not reading finality proofs from the stream, so eventually it'll break
|
||||
// but we don't care about transient proofs at all, so it is acceptable
|
||||
return Ok(None)
|
||||
},
|
||||
SelectedFinalityProof::Regular(unjustified_headers, header, finality_proof) =>
|
||||
(unjustified_headers, Some((header, finality_proof))),
|
||||
SelectedFinalityProof::None(unjustified_headers) => (unjustified_headers, None),
|
||||
};
|
||||
|
||||
// all headers that are missing from the target client are non-mandatory
|
||||
// => even if we have already selected some header and its persistent finality proof,
|
||||
// we may try to select better header by reading non-persistent proofs from the stream
|
||||
read_finality_proofs_from_stream::<P, _>(finality_proofs_stream, recent_finality_proofs);
|
||||
selected_finality_proof = select_better_recent_finality_proof::<P>(
|
||||
recent_finality_proofs,
|
||||
&mut unjustified_headers,
|
||||
selected_finality_proof,
|
||||
);
|
||||
|
||||
// remove obsolete 'recent' finality proofs + keep its size under certain limit
|
||||
let oldest_finality_proof_to_keep = selected_finality_proof
|
||||
.as_ref()
|
||||
.map(|(header, _)| header.number())
|
||||
.unwrap_or(best_number_at_target);
|
||||
prune_recent_finality_proofs::<P>(
|
||||
oldest_finality_proof_to_keep,
|
||||
recent_finality_proofs,
|
||||
sync_params.recent_finality_proofs_limit,
|
||||
);
|
||||
|
||||
Ok(selected_finality_proof)
|
||||
}
|
||||
|
||||
/// Ensures that both clients are on the same fork.
|
||||
///
|
||||
/// Returns `Some(_)` with header has at the source client if headers are different.
|
||||
async fn ensure_same_fork<P: FinalitySyncPipeline, SC: SourceClient<P>>(
|
||||
best_id_at_target: &HeaderId<P::Hash, P::Number>,
|
||||
source_client: &SC,
|
||||
) -> Result<Option<P::Hash>, SC::Error> {
|
||||
let header_at_source = source_client.header_and_finality_proof(best_id_at_target.0).await?.0;
|
||||
let header_hash_at_source = header_at_source.hash();
|
||||
Ok(if best_id_at_target.1 == header_hash_at_source {
|
||||
None
|
||||
} else {
|
||||
Some(header_hash_at_source)
|
||||
})
|
||||
}
|
||||
|
||||
/// Finality proof that has been selected by the `read_missing_headers` function.
|
||||
pub(crate) enum SelectedFinalityProof<Header, FinalityProof> {
|
||||
/// Mandatory header and its proof has been selected. We shall submit proof for this header.
|
||||
Mandatory(Header, FinalityProof),
|
||||
/// Regular header and its proof has been selected. We may submit this proof, or proof for
|
||||
/// some better header.
|
||||
Regular(UnjustifiedHeaders<Header>, Header, FinalityProof),
|
||||
/// We haven't found any missing header with persistent proof at the target client.
|
||||
None(UnjustifiedHeaders<Header>),
|
||||
}
|
||||
|
||||
/// Read missing headers and their persistent finality proofs from the target client.
|
||||
///
|
||||
/// If we have found some header with known proof, it is returned.
|
||||
/// Otherwise, `SelectedFinalityProof::None` is returned.
|
||||
///
|
||||
/// Unless we have found mandatory header, all missing headers are collected and returned.
|
||||
pub(crate) async fn read_missing_headers<
|
||||
P: FinalitySyncPipeline,
|
||||
SC: SourceClient<P>,
|
||||
TC: TargetClient<P>,
|
||||
>(
|
||||
source_client: &SC,
|
||||
_target_client: &TC,
|
||||
best_number_at_source: P::Number,
|
||||
best_number_at_target: P::Number,
|
||||
) -> Result<SelectedFinalityProof<P::Header, P::FinalityProof>, Error<P, SC::Error, TC::Error>> {
|
||||
let mut unjustified_headers = Vec::new();
|
||||
let mut selected_finality_proof = None;
|
||||
let mut header_number = best_number_at_target + One::one();
|
||||
while header_number <= best_number_at_source {
|
||||
let (header, finality_proof) = source_client
|
||||
.header_and_finality_proof(header_number)
|
||||
.await
|
||||
.map_err(Error::Source)?;
|
||||
let is_mandatory = header.is_mandatory();
|
||||
|
||||
match (is_mandatory, finality_proof) {
|
||||
(true, Some(finality_proof)) => {
|
||||
log::trace!(target: "bridge", "Header {:?} is mandatory", header_number);
|
||||
return Ok(SelectedFinalityProof::Mandatory(header, finality_proof))
|
||||
},
|
||||
(true, None) => return Err(Error::MissingMandatoryFinalityProof(header.number())),
|
||||
(false, Some(finality_proof)) => {
|
||||
log::trace!(target: "bridge", "Header {:?} has persistent finality proof", header_number);
|
||||
unjustified_headers.clear();
|
||||
selected_finality_proof = Some((header, finality_proof));
|
||||
},
|
||||
(false, None) => {
|
||||
unjustified_headers.push(header);
|
||||
},
|
||||
}
|
||||
|
||||
header_number = header_number + One::one();
|
||||
}
|
||||
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"Read {} {} headers. Selected finality proof for header: {:?}",
|
||||
best_number_at_source.saturating_sub(best_number_at_target),
|
||||
P::SOURCE_NAME,
|
||||
selected_finality_proof.as_ref().map(|(header, _)| header),
|
||||
);
|
||||
|
||||
Ok(match selected_finality_proof {
|
||||
Some((header, proof)) => SelectedFinalityProof::Regular(unjustified_headers, header, proof),
|
||||
None => SelectedFinalityProof::None(unjustified_headers),
|
||||
})
|
||||
}
|
||||
|
||||
/// Read finality proofs from the stream.
|
||||
pub(crate) fn read_finality_proofs_from_stream<
|
||||
P: FinalitySyncPipeline,
|
||||
FPS: Stream<Item = P::FinalityProof>,
|
||||
>(
|
||||
finality_proofs_stream: &mut RestartableFinalityProofsStream<FPS>,
|
||||
recent_finality_proofs: &mut FinalityProofs<P>,
|
||||
) {
|
||||
let mut proofs_count = 0;
|
||||
let mut first_header_number = None;
|
||||
let mut last_header_number = None;
|
||||
while let Some(finality_proof) = finality_proofs_stream.next() {
|
||||
let target_header_number = finality_proof.target_header_number();
|
||||
if first_header_number.is_none() {
|
||||
first_header_number = Some(target_header_number);
|
||||
}
|
||||
last_header_number = Some(target_header_number);
|
||||
proofs_count += 1;
|
||||
|
||||
recent_finality_proofs.push((target_header_number, finality_proof));
|
||||
}
|
||||
|
||||
if proofs_count != 0 {
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"Read {} finality proofs from {} finality stream for headers in range [{:?}; {:?}]",
|
||||
proofs_count,
|
||||
P::SOURCE_NAME,
|
||||
first_header_number,
|
||||
last_header_number,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to select better header and its proof, given finality proofs that we
|
||||
/// have recently read from the stream.
|
||||
pub(crate) fn select_better_recent_finality_proof<P: FinalitySyncPipeline>(
|
||||
recent_finality_proofs: FinalityProofsRef<P>,
|
||||
unjustified_headers: &mut UnjustifiedHeaders<P::Header>,
|
||||
selected_finality_proof: Option<(P::Header, P::FinalityProof)>,
|
||||
) -> Option<(P::Header, P::FinalityProof)> {
|
||||
if unjustified_headers.is_empty() || recent_finality_proofs.is_empty() {
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"Can not improve selected {} finality proof {:?}. No unjustified headers and recent proofs",
|
||||
P::SOURCE_NAME,
|
||||
selected_finality_proof.as_ref().map(|(h, _)| h.number()),
|
||||
);
|
||||
return selected_finality_proof
|
||||
}
|
||||
|
||||
const NOT_EMPTY_PROOF: &str = "we have checked that the vec is not empty; qed";
|
||||
|
||||
// we need proofs for headers in range unjustified_range_begin..=unjustified_range_end
|
||||
let unjustified_range_begin = unjustified_headers.first().expect(NOT_EMPTY_PROOF).number();
|
||||
let unjustified_range_end = unjustified_headers.last().expect(NOT_EMPTY_PROOF).number();
|
||||
|
||||
// we have proofs for headers in range buffered_range_begin..=buffered_range_end
|
||||
let buffered_range_begin = recent_finality_proofs.first().expect(NOT_EMPTY_PROOF).0;
|
||||
let buffered_range_end = recent_finality_proofs.last().expect(NOT_EMPTY_PROOF).0;
|
||||
|
||||
// we have two ranges => find intersection
|
||||
let intersection_begin = std::cmp::max(unjustified_range_begin, buffered_range_begin);
|
||||
let intersection_end = std::cmp::min(unjustified_range_end, buffered_range_end);
|
||||
let intersection = intersection_begin..=intersection_end;
|
||||
|
||||
// find last proof from intersection
|
||||
let selected_finality_proof_index = recent_finality_proofs
|
||||
.binary_search_by_key(intersection.end(), |(number, _)| *number)
|
||||
.unwrap_or_else(|index| index.saturating_sub(1));
|
||||
let (selected_header_number, finality_proof) =
|
||||
&recent_finality_proofs[selected_finality_proof_index];
|
||||
let has_selected_finality_proof = intersection.contains(selected_header_number);
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"Trying to improve selected {} finality proof {:?}. Headers range: [{:?}; {:?}]. Proofs range: [{:?}; {:?}].\
|
||||
Trying to improve to: {:?}. Result: {}",
|
||||
P::SOURCE_NAME,
|
||||
selected_finality_proof.as_ref().map(|(h, _)| h.number()),
|
||||
unjustified_range_begin,
|
||||
unjustified_range_end,
|
||||
buffered_range_begin,
|
||||
buffered_range_end,
|
||||
selected_header_number,
|
||||
if has_selected_finality_proof { "improved" } else { "not improved" },
|
||||
);
|
||||
if !has_selected_finality_proof {
|
||||
return selected_finality_proof
|
||||
}
|
||||
|
||||
// now remove all obsolete headers and extract selected header
|
||||
let selected_header_position = unjustified_headers
|
||||
.binary_search_by_key(selected_header_number, |header| header.number())
|
||||
.expect("unjustified_headers contain all headers from intersection; qed");
|
||||
let selected_header = unjustified_headers.swap_remove(selected_header_position);
|
||||
Some((selected_header, finality_proof.clone()))
|
||||
}
|
||||
|
||||
pub(crate) fn prune_recent_finality_proofs<P: FinalitySyncPipeline>(
|
||||
justified_header_number: P::Number,
|
||||
recent_finality_proofs: &mut FinalityProofs<P>,
|
||||
recent_finality_proofs_limit: usize,
|
||||
) {
|
||||
let justified_header_idx = recent_finality_proofs
|
||||
.binary_search_by_key(&justified_header_number, |(header_number, _)| *header_number)
|
||||
.map(|idx| idx + 1)
|
||||
.unwrap_or_else(|idx| idx);
|
||||
let proofs_limit_idx =
|
||||
recent_finality_proofs.len().saturating_sub(recent_finality_proofs_limit);
|
||||
|
||||
*recent_finality_proofs =
|
||||
recent_finality_proofs.split_off(std::cmp::max(justified_header_idx, proofs_limit_idx));
|
||||
}
|
||||
|
||||
fn print_sync_progress<P: FinalitySyncPipeline>(
|
||||
progress_context: (Instant, Option<P::Number>),
|
||||
best_number_at_source: P::Number,
|
||||
best_number_at_target: P::Number,
|
||||
) -> (Instant, Option<P::Number>) {
|
||||
let (prev_time, prev_best_number_at_target) = progress_context;
|
||||
let now = Instant::now();
|
||||
|
||||
let need_update = now - prev_time > Duration::from_secs(10) ||
|
||||
prev_best_number_at_target
|
||||
.map(|prev_best_number_at_target| {
|
||||
best_number_at_target.saturating_sub(prev_best_number_at_target) > 10.into()
|
||||
})
|
||||
.unwrap_or(true);
|
||||
|
||||
if !need_update {
|
||||
return (prev_time, prev_best_number_at_target)
|
||||
}
|
||||
|
||||
log::info!(
|
||||
target: "bridge",
|
||||
"Synced {:?} of {:?} headers",
|
||||
best_number_at_target,
|
||||
best_number_at_source,
|
||||
);
|
||||
(now, Some(best_number_at_target))
|
||||
}
|
||||
@@ -0,0 +1,598 @@
|
||||
// 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/>.
|
||||
|
||||
//! Tests for finality synchronization loop.
|
||||
|
||||
#![cfg(test)]
|
||||
|
||||
use crate::{
|
||||
finality_loop::{
|
||||
prune_recent_finality_proofs, read_finality_proofs_from_stream, run_loop_iteration,
|
||||
run_until_connection_lost, select_better_recent_finality_proof, select_header_to_submit,
|
||||
FinalityLoopState, FinalityProofs, FinalitySyncParams, RestartableFinalityProofsStream,
|
||||
SourceClient, TargetClient,
|
||||
},
|
||||
sync_loop_metrics::SyncLoopMetrics,
|
||||
FinalityProof, FinalitySyncPipeline, SourceHeader,
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use bp_header_chain::GrandpaConsensusLogReader;
|
||||
use futures::{FutureExt, Stream, StreamExt};
|
||||
use parking_lot::Mutex;
|
||||
use relay_utils::{
|
||||
relay_loop::Client as RelayClient, FailedClient, HeaderId, MaybeConnectionError,
|
||||
TrackedTransactionStatus, TransactionTracker,
|
||||
};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
pin::Pin,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
type IsMandatory = bool;
|
||||
type TestNumber = u64;
|
||||
type TestHash = u64;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct TestTransactionTracker(TrackedTransactionStatus<HeaderId<TestHash, TestNumber>>);
|
||||
|
||||
impl Default for TestTransactionTracker {
|
||||
fn default() -> TestTransactionTracker {
|
||||
TestTransactionTracker(TrackedTransactionStatus::Finalized(Default::default()))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TransactionTracker for TestTransactionTracker {
|
||||
type HeaderId = HeaderId<TestHash, TestNumber>;
|
||||
|
||||
async fn wait(self) -> TrackedTransactionStatus<HeaderId<TestHash, TestNumber>> {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum TestError {
|
||||
NonConnection,
|
||||
}
|
||||
|
||||
impl MaybeConnectionError for TestError {
|
||||
fn is_connection_error(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct TestFinalitySyncPipeline;
|
||||
|
||||
impl FinalitySyncPipeline for TestFinalitySyncPipeline {
|
||||
const SOURCE_NAME: &'static str = "TestSource";
|
||||
const TARGET_NAME: &'static str = "TestTarget";
|
||||
|
||||
type Hash = TestHash;
|
||||
type Number = TestNumber;
|
||||
type ConsensusLogReader = GrandpaConsensusLogReader<TestNumber>;
|
||||
type Header = TestSourceHeader;
|
||||
type FinalityProof = TestFinalityProof;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct TestSourceHeader(IsMandatory, TestNumber, TestHash);
|
||||
|
||||
impl SourceHeader<TestHash, TestNumber, GrandpaConsensusLogReader<TestNumber>>
|
||||
for TestSourceHeader
|
||||
{
|
||||
fn hash(&self) -> TestHash {
|
||||
self.2
|
||||
}
|
||||
|
||||
fn number(&self) -> TestNumber {
|
||||
self.1
|
||||
}
|
||||
|
||||
fn is_mandatory(&self) -> bool {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct TestFinalityProof(TestNumber);
|
||||
|
||||
impl FinalityProof<TestNumber> for TestFinalityProof {
|
||||
fn target_header_number(&self) -> TestNumber {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct ClientsData {
|
||||
source_best_block_number: TestNumber,
|
||||
source_headers: HashMap<TestNumber, (TestSourceHeader, Option<TestFinalityProof>)>,
|
||||
source_proofs: Vec<TestFinalityProof>,
|
||||
|
||||
target_best_block_id: HeaderId<TestHash, TestNumber>,
|
||||
target_headers: Vec<(TestSourceHeader, TestFinalityProof)>,
|
||||
target_transaction_tracker: TestTransactionTracker,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct TestSourceClient {
|
||||
on_method_call: Arc<dyn Fn(&mut ClientsData) + Send + Sync>,
|
||||
data: Arc<Mutex<ClientsData>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl RelayClient for TestSourceClient {
|
||||
type Error = TestError;
|
||||
|
||||
async fn reconnect(&mut self) -> Result<(), TestError> {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl SourceClient<TestFinalitySyncPipeline> for TestSourceClient {
|
||||
type FinalityProofsStream = Pin<Box<dyn Stream<Item = TestFinalityProof> + 'static + Send>>;
|
||||
|
||||
async fn best_finalized_block_number(&self) -> Result<TestNumber, TestError> {
|
||||
let mut data = self.data.lock();
|
||||
(self.on_method_call)(&mut data);
|
||||
Ok(data.source_best_block_number)
|
||||
}
|
||||
|
||||
async fn header_and_finality_proof(
|
||||
&self,
|
||||
number: TestNumber,
|
||||
) -> Result<(TestSourceHeader, Option<TestFinalityProof>), TestError> {
|
||||
let mut data = self.data.lock();
|
||||
(self.on_method_call)(&mut data);
|
||||
data.source_headers.get(&number).cloned().ok_or(TestError::NonConnection)
|
||||
}
|
||||
|
||||
async fn finality_proofs(&self) -> Result<Self::FinalityProofsStream, TestError> {
|
||||
let mut data = self.data.lock();
|
||||
(self.on_method_call)(&mut data);
|
||||
Ok(futures::stream::iter(data.source_proofs.clone()).boxed())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct TestTargetClient {
|
||||
on_method_call: Arc<dyn Fn(&mut ClientsData) + Send + Sync>,
|
||||
data: Arc<Mutex<ClientsData>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl RelayClient for TestTargetClient {
|
||||
type Error = TestError;
|
||||
|
||||
async fn reconnect(&mut self) -> Result<(), TestError> {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TargetClient<TestFinalitySyncPipeline> for TestTargetClient {
|
||||
type TransactionTracker = TestTransactionTracker;
|
||||
|
||||
async fn best_finalized_source_block_id(
|
||||
&self,
|
||||
) -> Result<HeaderId<TestHash, TestNumber>, TestError> {
|
||||
let mut data = self.data.lock();
|
||||
(self.on_method_call)(&mut data);
|
||||
Ok(data.target_best_block_id)
|
||||
}
|
||||
|
||||
async fn submit_finality_proof(
|
||||
&self,
|
||||
header: TestSourceHeader,
|
||||
proof: TestFinalityProof,
|
||||
) -> Result<TestTransactionTracker, TestError> {
|
||||
let mut data = self.data.lock();
|
||||
(self.on_method_call)(&mut data);
|
||||
data.target_best_block_id = HeaderId(header.number(), header.hash());
|
||||
data.target_headers.push((header, proof));
|
||||
(self.on_method_call)(&mut data);
|
||||
Ok(data.target_transaction_tracker.clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_test_clients(
|
||||
exit_sender: futures::channel::mpsc::UnboundedSender<()>,
|
||||
state_function: impl Fn(&mut ClientsData) -> bool + Send + Sync + 'static,
|
||||
source_headers: HashMap<TestNumber, (TestSourceHeader, Option<TestFinalityProof>)>,
|
||||
) -> (TestSourceClient, TestTargetClient) {
|
||||
let internal_state_function: Arc<dyn Fn(&mut ClientsData) + Send + Sync> =
|
||||
Arc::new(move |data| {
|
||||
if state_function(data) {
|
||||
exit_sender.unbounded_send(()).unwrap();
|
||||
}
|
||||
});
|
||||
let clients_data = Arc::new(Mutex::new(ClientsData {
|
||||
source_best_block_number: 10,
|
||||
source_headers,
|
||||
source_proofs: vec![TestFinalityProof(12), TestFinalityProof(14)],
|
||||
|
||||
target_best_block_id: HeaderId(5, 5),
|
||||
target_headers: vec![],
|
||||
target_transaction_tracker: TestTransactionTracker(TrackedTransactionStatus::Finalized(
|
||||
Default::default(),
|
||||
)),
|
||||
}));
|
||||
(
|
||||
TestSourceClient {
|
||||
on_method_call: internal_state_function.clone(),
|
||||
data: clients_data.clone(),
|
||||
},
|
||||
TestTargetClient { on_method_call: internal_state_function, data: clients_data },
|
||||
)
|
||||
}
|
||||
|
||||
fn test_sync_params() -> FinalitySyncParams {
|
||||
FinalitySyncParams {
|
||||
tick: Duration::from_secs(0),
|
||||
recent_finality_proofs_limit: 1024,
|
||||
stall_timeout: Duration::from_secs(1),
|
||||
only_mandatory_headers: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn run_sync_loop(
|
||||
state_function: impl Fn(&mut ClientsData) -> bool + Send + Sync + 'static,
|
||||
) -> (ClientsData, Result<(), FailedClient>) {
|
||||
let (exit_sender, exit_receiver) = futures::channel::mpsc::unbounded();
|
||||
let (source_client, target_client) = prepare_test_clients(
|
||||
exit_sender,
|
||||
state_function,
|
||||
vec![
|
||||
(5, (TestSourceHeader(false, 5, 5), None)),
|
||||
(6, (TestSourceHeader(false, 6, 6), None)),
|
||||
(7, (TestSourceHeader(false, 7, 7), Some(TestFinalityProof(7)))),
|
||||
(8, (TestSourceHeader(true, 8, 8), Some(TestFinalityProof(8)))),
|
||||
(9, (TestSourceHeader(false, 9, 9), Some(TestFinalityProof(9)))),
|
||||
(10, (TestSourceHeader(false, 10, 10), None)),
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
);
|
||||
let sync_params = test_sync_params();
|
||||
|
||||
let clients_data = source_client.data.clone();
|
||||
let result = async_std::task::block_on(run_until_connection_lost(
|
||||
source_client,
|
||||
target_client,
|
||||
sync_params,
|
||||
None,
|
||||
exit_receiver.into_future().map(|(_, _)| ()),
|
||||
));
|
||||
|
||||
let clients_data = clients_data.lock().clone();
|
||||
(clients_data, result)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finality_sync_loop_works() {
|
||||
let (client_data, result) = run_sync_loop(|data| {
|
||||
// header#7 has persistent finality proof, but it isn't mandatory => it isn't submitted,
|
||||
// because header#8 has persistent finality proof && it is mandatory => it is submitted
|
||||
// header#9 has persistent finality proof, but it isn't mandatory => it is submitted,
|
||||
// because there are no more persistent finality proofs
|
||||
//
|
||||
// once this ^^^ is done, we generate more blocks && read proof for blocks 12 and 14 from
|
||||
// the stream
|
||||
if data.target_best_block_id.0 == 9 {
|
||||
data.source_best_block_number = 14;
|
||||
data.source_headers.insert(11, (TestSourceHeader(false, 11, 11), None));
|
||||
data.source_headers
|
||||
.insert(12, (TestSourceHeader(false, 12, 12), Some(TestFinalityProof(12))));
|
||||
data.source_headers.insert(13, (TestSourceHeader(false, 13, 13), None));
|
||||
data.source_headers
|
||||
.insert(14, (TestSourceHeader(false, 14, 14), Some(TestFinalityProof(14))));
|
||||
}
|
||||
// once this ^^^ is done, we generate more blocks && read persistent proof for block 16
|
||||
if data.target_best_block_id.0 == 14 {
|
||||
data.source_best_block_number = 17;
|
||||
data.source_headers.insert(15, (TestSourceHeader(false, 15, 15), None));
|
||||
data.source_headers
|
||||
.insert(16, (TestSourceHeader(false, 16, 16), Some(TestFinalityProof(16))));
|
||||
data.source_headers.insert(17, (TestSourceHeader(false, 17, 17), None));
|
||||
}
|
||||
|
||||
data.target_best_block_id.0 == 16
|
||||
});
|
||||
|
||||
assert_eq!(result, Ok(()));
|
||||
assert_eq!(
|
||||
client_data.target_headers,
|
||||
vec![
|
||||
// before adding 11..14: finality proof for mandatory header#8
|
||||
(TestSourceHeader(true, 8, 8), TestFinalityProof(8)),
|
||||
// before adding 11..14: persistent finality proof for non-mandatory header#9
|
||||
(TestSourceHeader(false, 9, 9), TestFinalityProof(9)),
|
||||
// after adding 11..14: ephemeral finality proof for non-mandatory header#14
|
||||
(TestSourceHeader(false, 14, 14), TestFinalityProof(14)),
|
||||
// after adding 15..17: persistent finality proof for non-mandatory header#16
|
||||
(TestSourceHeader(false, 16, 16), TestFinalityProof(16)),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
fn run_only_mandatory_headers_mode_test(
|
||||
only_mandatory_headers: bool,
|
||||
has_mandatory_headers: bool,
|
||||
) -> Option<(TestSourceHeader, TestFinalityProof)> {
|
||||
let (exit_sender, _) = futures::channel::mpsc::unbounded();
|
||||
let (source_client, target_client) = prepare_test_clients(
|
||||
exit_sender,
|
||||
|_| false,
|
||||
vec![
|
||||
(6, (TestSourceHeader(false, 6, 6), Some(TestFinalityProof(6)))),
|
||||
(7, (TestSourceHeader(false, 7, 7), Some(TestFinalityProof(7)))),
|
||||
(8, (TestSourceHeader(has_mandatory_headers, 8, 8), Some(TestFinalityProof(8)))),
|
||||
(9, (TestSourceHeader(false, 9, 9), Some(TestFinalityProof(9)))),
|
||||
(10, (TestSourceHeader(false, 10, 10), Some(TestFinalityProof(10)))),
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
);
|
||||
async_std::task::block_on(select_header_to_submit(
|
||||
&source_client,
|
||||
&target_client,
|
||||
&mut RestartableFinalityProofsStream::from(futures::stream::empty().boxed()),
|
||||
&mut vec![],
|
||||
10,
|
||||
5,
|
||||
&FinalitySyncParams {
|
||||
tick: Duration::from_secs(0),
|
||||
recent_finality_proofs_limit: 0,
|
||||
stall_timeout: Duration::from_secs(0),
|
||||
only_mandatory_headers,
|
||||
},
|
||||
))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_header_to_submit_skips_non_mandatory_headers_when_only_mandatory_headers_are_required() {
|
||||
assert_eq!(run_only_mandatory_headers_mode_test(true, false), None);
|
||||
assert_eq!(
|
||||
run_only_mandatory_headers_mode_test(false, false),
|
||||
Some((TestSourceHeader(false, 10, 10), TestFinalityProof(10))),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_header_to_submit_selects_mandatory_headers_when_only_mandatory_headers_are_required() {
|
||||
assert_eq!(
|
||||
run_only_mandatory_headers_mode_test(true, true),
|
||||
Some((TestSourceHeader(true, 8, 8), TestFinalityProof(8))),
|
||||
);
|
||||
assert_eq!(
|
||||
run_only_mandatory_headers_mode_test(false, true),
|
||||
Some((TestSourceHeader(true, 8, 8), TestFinalityProof(8))),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_better_recent_finality_proof_works() {
|
||||
// if there are no unjustified headers, nothing is changed
|
||||
assert_eq!(
|
||||
select_better_recent_finality_proof::<TestFinalitySyncPipeline>(
|
||||
&[(5, TestFinalityProof(5))],
|
||||
&mut vec![],
|
||||
Some((TestSourceHeader(false, 2, 2), TestFinalityProof(2))),
|
||||
),
|
||||
Some((TestSourceHeader(false, 2, 2), TestFinalityProof(2))),
|
||||
);
|
||||
|
||||
// if there are no recent finality proofs, nothing is changed
|
||||
assert_eq!(
|
||||
select_better_recent_finality_proof::<TestFinalitySyncPipeline>(
|
||||
&[],
|
||||
&mut vec![TestSourceHeader(false, 5, 5)],
|
||||
Some((TestSourceHeader(false, 2, 2), TestFinalityProof(2))),
|
||||
),
|
||||
Some((TestSourceHeader(false, 2, 2), TestFinalityProof(2))),
|
||||
);
|
||||
|
||||
// if there's no intersection between recent finality proofs and unjustified headers, nothing is
|
||||
// changed
|
||||
let mut unjustified_headers =
|
||||
vec![TestSourceHeader(false, 9, 9), TestSourceHeader(false, 10, 10)];
|
||||
assert_eq!(
|
||||
select_better_recent_finality_proof::<TestFinalitySyncPipeline>(
|
||||
&[(1, TestFinalityProof(1)), (4, TestFinalityProof(4))],
|
||||
&mut unjustified_headers,
|
||||
Some((TestSourceHeader(false, 2, 2), TestFinalityProof(2))),
|
||||
),
|
||||
Some((TestSourceHeader(false, 2, 2), TestFinalityProof(2))),
|
||||
);
|
||||
|
||||
// if there's intersection between recent finality proofs and unjustified headers, but there are
|
||||
// no proofs in this intersection, nothing is changed
|
||||
let mut unjustified_headers = vec![
|
||||
TestSourceHeader(false, 8, 8),
|
||||
TestSourceHeader(false, 9, 9),
|
||||
TestSourceHeader(false, 10, 10),
|
||||
];
|
||||
assert_eq!(
|
||||
select_better_recent_finality_proof::<TestFinalitySyncPipeline>(
|
||||
&[(7, TestFinalityProof(7)), (11, TestFinalityProof(11))],
|
||||
&mut unjustified_headers,
|
||||
Some((TestSourceHeader(false, 2, 2), TestFinalityProof(2))),
|
||||
),
|
||||
Some((TestSourceHeader(false, 2, 2), TestFinalityProof(2))),
|
||||
);
|
||||
assert_eq!(
|
||||
unjustified_headers,
|
||||
vec![
|
||||
TestSourceHeader(false, 8, 8),
|
||||
TestSourceHeader(false, 9, 9),
|
||||
TestSourceHeader(false, 10, 10)
|
||||
]
|
||||
);
|
||||
|
||||
// if there's intersection between recent finality proofs and unjustified headers and there's
|
||||
// a proof in this intersection:
|
||||
// - this better (last from intersection) proof is selected;
|
||||
// - 'obsolete' unjustified headers are pruned.
|
||||
let mut unjustified_headers = vec![
|
||||
TestSourceHeader(false, 8, 8),
|
||||
TestSourceHeader(false, 9, 9),
|
||||
TestSourceHeader(false, 10, 10),
|
||||
];
|
||||
assert_eq!(
|
||||
select_better_recent_finality_proof::<TestFinalitySyncPipeline>(
|
||||
&[(7, TestFinalityProof(7)), (9, TestFinalityProof(9))],
|
||||
&mut unjustified_headers,
|
||||
Some((TestSourceHeader(false, 2, 2), TestFinalityProof(2))),
|
||||
),
|
||||
Some((TestSourceHeader(false, 9, 9), TestFinalityProof(9))),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_finality_proofs_from_stream_works() {
|
||||
// when stream is currently empty, nothing is changed
|
||||
let mut recent_finality_proofs = vec![(1, TestFinalityProof(1))];
|
||||
let mut stream = futures::stream::pending().into();
|
||||
read_finality_proofs_from_stream::<TestFinalitySyncPipeline, _>(
|
||||
&mut stream,
|
||||
&mut recent_finality_proofs,
|
||||
);
|
||||
assert_eq!(recent_finality_proofs, vec![(1, TestFinalityProof(1))]);
|
||||
assert!(!stream.needs_restart);
|
||||
|
||||
// when stream has entry with target, it is added to the recent proofs container
|
||||
let mut stream = futures::stream::iter(vec![TestFinalityProof(4)])
|
||||
.chain(futures::stream::pending())
|
||||
.into();
|
||||
read_finality_proofs_from_stream::<TestFinalitySyncPipeline, _>(
|
||||
&mut stream,
|
||||
&mut recent_finality_proofs,
|
||||
);
|
||||
assert_eq!(recent_finality_proofs, vec![(1, TestFinalityProof(1)), (4, TestFinalityProof(4))]);
|
||||
assert!(!stream.needs_restart);
|
||||
|
||||
// when stream has ended, we'll need to restart it
|
||||
let mut stream = futures::stream::empty().into();
|
||||
read_finality_proofs_from_stream::<TestFinalitySyncPipeline, _>(
|
||||
&mut stream,
|
||||
&mut recent_finality_proofs,
|
||||
);
|
||||
assert_eq!(recent_finality_proofs, vec![(1, TestFinalityProof(1)), (4, TestFinalityProof(4))]);
|
||||
assert!(stream.needs_restart);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prune_recent_finality_proofs_works() {
|
||||
let original_recent_finality_proofs: FinalityProofs<TestFinalitySyncPipeline> = vec![
|
||||
(10, TestFinalityProof(10)),
|
||||
(13, TestFinalityProof(13)),
|
||||
(15, TestFinalityProof(15)),
|
||||
(17, TestFinalityProof(17)),
|
||||
(19, TestFinalityProof(19)),
|
||||
]
|
||||
.into_iter()
|
||||
.collect();
|
||||
|
||||
// when there's proof for justified header in the vec
|
||||
let mut recent_finality_proofs = original_recent_finality_proofs.clone();
|
||||
prune_recent_finality_proofs::<TestFinalitySyncPipeline>(10, &mut recent_finality_proofs, 1024);
|
||||
assert_eq!(&original_recent_finality_proofs[1..], recent_finality_proofs,);
|
||||
|
||||
// when there are no proof for justified header in the vec
|
||||
let mut recent_finality_proofs = original_recent_finality_proofs.clone();
|
||||
prune_recent_finality_proofs::<TestFinalitySyncPipeline>(11, &mut recent_finality_proofs, 1024);
|
||||
assert_eq!(&original_recent_finality_proofs[1..], recent_finality_proofs,);
|
||||
|
||||
// when there are too many entries after initial prune && they also need to be pruned
|
||||
let mut recent_finality_proofs = original_recent_finality_proofs.clone();
|
||||
prune_recent_finality_proofs::<TestFinalitySyncPipeline>(10, &mut recent_finality_proofs, 2);
|
||||
assert_eq!(&original_recent_finality_proofs[3..], recent_finality_proofs,);
|
||||
|
||||
// when last entry is pruned
|
||||
let mut recent_finality_proofs = original_recent_finality_proofs.clone();
|
||||
prune_recent_finality_proofs::<TestFinalitySyncPipeline>(19, &mut recent_finality_proofs, 2);
|
||||
assert_eq!(&original_recent_finality_proofs[5..], recent_finality_proofs,);
|
||||
|
||||
// when post-last entry is pruned
|
||||
let mut recent_finality_proofs = original_recent_finality_proofs.clone();
|
||||
prune_recent_finality_proofs::<TestFinalitySyncPipeline>(20, &mut recent_finality_proofs, 2);
|
||||
assert_eq!(&original_recent_finality_proofs[5..], recent_finality_proofs,);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_forks_at_source_and_at_target_are_detected() {
|
||||
let (exit_sender, _exit_receiver) = futures::channel::mpsc::unbounded();
|
||||
let (source_client, target_client) = prepare_test_clients(
|
||||
exit_sender,
|
||||
|_| false,
|
||||
vec![
|
||||
(5, (TestSourceHeader(false, 5, 42), None)),
|
||||
(6, (TestSourceHeader(false, 6, 6), None)),
|
||||
(7, (TestSourceHeader(false, 7, 7), None)),
|
||||
(8, (TestSourceHeader(false, 8, 8), None)),
|
||||
(9, (TestSourceHeader(false, 9, 9), None)),
|
||||
(10, (TestSourceHeader(false, 10, 10), None)),
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
);
|
||||
|
||||
let mut progress = (Instant::now(), None);
|
||||
let mut finality_proofs_stream = futures::stream::iter(vec![]).boxed().into();
|
||||
let mut recent_finality_proofs = Vec::new();
|
||||
let metrics_sync = SyncLoopMetrics::new(None, "source", "target").unwrap();
|
||||
async_std::task::block_on(run_loop_iteration::<TestFinalitySyncPipeline, _, _>(
|
||||
&source_client,
|
||||
&target_client,
|
||||
FinalityLoopState {
|
||||
progress: &mut progress,
|
||||
finality_proofs_stream: &mut finality_proofs_stream,
|
||||
recent_finality_proofs: &mut recent_finality_proofs,
|
||||
submitted_header_number: None,
|
||||
},
|
||||
&test_sync_params(),
|
||||
&Some(metrics_sync.clone()),
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
assert!(!metrics_sync.is_using_same_fork());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stalls_when_transaction_tracker_returns_error() {
|
||||
let (_, result) = run_sync_loop(|data| {
|
||||
data.target_transaction_tracker = TestTransactionTracker(TrackedTransactionStatus::Lost);
|
||||
data.target_best_block_id = HeaderId(5, 5);
|
||||
data.target_best_block_id.0 == 16
|
||||
});
|
||||
|
||||
assert_eq!(result, Err(FailedClient::Both));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stalls_when_transaction_tracker_returns_finalized_but_transaction_fails() {
|
||||
let (_, result) = run_sync_loop(|data| {
|
||||
data.target_best_block_id = HeaderId(5, 5);
|
||||
data.target_best_block_id.0 == 16
|
||||
});
|
||||
|
||||
assert_eq!(result, Err(FailedClient::Both));
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// 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/>.
|
||||
|
||||
//! This crate has single entrypoint to run synchronization loop that is built around finality
|
||||
//! proofs, as opposed to headers synchronization loop, which is built around headers. The headers
|
||||
//! are still submitted to the target node, but are treated as auxiliary data as we are not trying
|
||||
//! to submit all source headers to the target node.
|
||||
|
||||
pub use crate::{
|
||||
finality_loop::{metrics_prefix, run, FinalitySyncParams, SourceClient, TargetClient},
|
||||
sync_loop_metrics::SyncLoopMetrics,
|
||||
};
|
||||
|
||||
use bp_header_chain::{ConsensusLogReader, FinalityProof};
|
||||
use std::fmt::Debug;
|
||||
|
||||
mod finality_loop;
|
||||
mod finality_loop_tests;
|
||||
mod sync_loop_metrics;
|
||||
|
||||
/// Finality proofs synchronization pipeline.
|
||||
pub trait FinalitySyncPipeline: 'static + Clone + Debug + Send + Sync {
|
||||
/// Name of the finality proofs source.
|
||||
const SOURCE_NAME: &'static str;
|
||||
/// Name of the finality proofs target.
|
||||
const TARGET_NAME: &'static str;
|
||||
|
||||
/// Headers we're syncing are identified by this hash.
|
||||
type Hash: Eq + Clone + Copy + Send + Sync + Debug;
|
||||
/// Headers we're syncing are identified by this number.
|
||||
type Number: relay_utils::BlockNumberBase;
|
||||
/// A reader that can extract the consensus log from the header digest and interpret it.
|
||||
type ConsensusLogReader: ConsensusLogReader;
|
||||
/// Type of header that we're syncing.
|
||||
type Header: SourceHeader<Self::Hash, Self::Number, Self::ConsensusLogReader>;
|
||||
/// Finality proof type.
|
||||
type FinalityProof: FinalityProof<Self::Number>;
|
||||
}
|
||||
|
||||
/// Header that we're receiving from source node.
|
||||
pub trait SourceHeader<Hash, Number, Reader>: Clone + Debug + PartialEq + Send + Sync {
|
||||
/// Returns hash of header.
|
||||
fn hash(&self) -> Hash;
|
||||
/// Returns number of header.
|
||||
fn number(&self) -> Number;
|
||||
/// Returns true if this header needs to be submitted to target node.
|
||||
fn is_mandatory(&self) -> bool;
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// 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/>.
|
||||
|
||||
//! Metrics for headers synchronization relay loop.
|
||||
|
||||
use relay_utils::metrics::{metric_name, register, IntGauge, Metric, PrometheusError, Registry};
|
||||
|
||||
/// Headers sync metrics.
|
||||
#[derive(Clone)]
|
||||
pub struct SyncLoopMetrics {
|
||||
/// Best syncing header at the source.
|
||||
best_source_block_number: IntGauge,
|
||||
/// Best syncing header at the target.
|
||||
best_target_block_number: IntGauge,
|
||||
/// Flag that has `0` value when best source headers at the source node and at-target-chain
|
||||
/// are matching and `1` otherwise.
|
||||
using_different_forks: IntGauge,
|
||||
}
|
||||
|
||||
impl SyncLoopMetrics {
|
||||
/// Create and register headers loop metrics.
|
||||
pub fn new(
|
||||
prefix: Option<&str>,
|
||||
at_source_chain_label: &str,
|
||||
at_target_chain_label: &str,
|
||||
) -> Result<Self, PrometheusError> {
|
||||
Ok(SyncLoopMetrics {
|
||||
best_source_block_number: IntGauge::new(
|
||||
metric_name(prefix, &format!("best_{at_source_chain_label}_block_number")),
|
||||
format!("Best block number at the {at_source_chain_label}"),
|
||||
)?,
|
||||
best_target_block_number: IntGauge::new(
|
||||
metric_name(prefix, &format!("best_{at_target_chain_label}_block_number")),
|
||||
format!("Best block number at the {at_target_chain_label}"),
|
||||
)?,
|
||||
using_different_forks: IntGauge::new(
|
||||
metric_name(prefix, &format!("is_{at_source_chain_label}_and_{at_target_chain_label}_using_different_forks")),
|
||||
"Whether the best finalized source block at target node is different (value 1) from the \
|
||||
corresponding block at the source node",
|
||||
)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns current value of the using-same-fork flag.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn is_using_same_fork(&self) -> bool {
|
||||
self.using_different_forks.get() == 0
|
||||
}
|
||||
|
||||
/// Update best block number at source.
|
||||
pub fn update_best_block_at_source<Number: Into<u64>>(&self, source_best_number: Number) {
|
||||
self.best_source_block_number.set(source_best_number.into());
|
||||
}
|
||||
|
||||
/// Update best block number at target.
|
||||
pub fn update_best_block_at_target<Number: Into<u64>>(&self, target_best_number: Number) {
|
||||
self.best_target_block_number.set(target_best_number.into());
|
||||
}
|
||||
|
||||
/// Update using-same-fork flag.
|
||||
pub fn update_using_same_fork(&self, using_same_fork: bool) {
|
||||
self.using_different_forks.set((!using_same_fork).into())
|
||||
}
|
||||
}
|
||||
|
||||
impl Metric for SyncLoopMetrics {
|
||||
fn register(&self, registry: &Registry) -> Result<(), PrometheusError> {
|
||||
register(self.best_source_block_number.clone(), registry)?;
|
||||
register(self.best_target_block_number.clone(), registry)?;
|
||||
register(self.using_different_forks.clone(), registry)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
[package]
|
||||
name = "substrate-relay-helper"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0"
|
||||
thiserror = "1.0.26"
|
||||
async-std = "1.9.0"
|
||||
async-trait = "0.1"
|
||||
codec = { package = "parity-scale-codec", version = "3.1.5" }
|
||||
futures = "0.3.12"
|
||||
num-traits = "0.2"
|
||||
log = "0.4.17"
|
||||
|
||||
# Bridge dependencies
|
||||
|
||||
bp-header-chain = { path = "../../primitives/header-chain" }
|
||||
bp-parachains = { path = "../../primitives/parachains" }
|
||||
bp-polkadot-core = { path = "../../primitives/polkadot-core" }
|
||||
bridge-runtime-common = { path = "../../bin/runtime-common" }
|
||||
|
||||
finality-grandpa = { version = "0.16.0" }
|
||||
finality-relay = { path = "../finality" }
|
||||
parachains-relay = { path = "../parachains" }
|
||||
relay-utils = { path = "../utils" }
|
||||
messages-relay = { path = "../messages" }
|
||||
relay-substrate-client = { path = "../client-substrate" }
|
||||
|
||||
pallet-bridge-grandpa = { path = "../../modules/grandpa" }
|
||||
pallet-bridge-messages = { path = "../../modules/messages" }
|
||||
pallet-bridge-parachains = { path = "../../modules/parachains" }
|
||||
|
||||
bp-runtime = { path = "../../primitives/runtime" }
|
||||
bp-messages = { path = "../../primitives/messages" }
|
||||
|
||||
# Substrate Dependencies
|
||||
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
frame-system = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-finality-grandpa = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
|
||||
[dev-dependencies]
|
||||
bp-millau = { path = "../../primitives/chain-millau" }
|
||||
bp-rialto = { path = "../../primitives/chain-rialto" }
|
||||
bp-rococo = { path = "../../primitives/chain-rococo" }
|
||||
bp-wococo = { path = "../../primitives/chain-wococo" }
|
||||
pallet-transaction-payment = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
relay-rialto-client = { path = "../client-rialto" }
|
||||
relay-rococo-client = { path = "../client-rococo" }
|
||||
relay-wococo-client = { path = "../client-wococo" }
|
||||
rialto-runtime = { path = "../../bin/rialto/runtime" }
|
||||
@@ -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/>.
|
||||
|
||||
//! Relay errors.
|
||||
|
||||
use relay_substrate_client as client;
|
||||
use sp_finality_grandpa::AuthorityList;
|
||||
use sp_runtime::traits::MaybeDisplay;
|
||||
use std::fmt::Debug;
|
||||
use thiserror::Error;
|
||||
|
||||
/// Relay errors.
|
||||
#[derive(Error, Debug)]
|
||||
pub enum Error<Hash: Debug + MaybeDisplay, HeaderNumber: Debug + MaybeDisplay> {
|
||||
/// Failed to submit signed extrinsic from to the target chain.
|
||||
#[error("Failed to submit {0} transaction: {1:?}")]
|
||||
SubmitTransaction(&'static str, client::Error),
|
||||
/// Failed subscribe to justification stream of the source chain.
|
||||
#[error("Failed to subscribe to {0} justifications: {1:?}")]
|
||||
Subscribe(&'static str, client::Error),
|
||||
/// Failed subscribe to read justification from the source chain (client error).
|
||||
#[error("Failed to read {0} justification from the stream: {1}")]
|
||||
ReadJustification(&'static str, client::Error),
|
||||
/// Failed subscribe to read justification from the source chain (stream ended).
|
||||
#[error("Failed to read {0} justification from the stream: stream has ended unexpectedly")]
|
||||
ReadJustificationStreamEnded(&'static str),
|
||||
/// Failed subscribe to decode justification from the source chain.
|
||||
#[error("Failed to decode {0} justification: {1:?}")]
|
||||
DecodeJustification(&'static str, codec::Error),
|
||||
/// GRANDPA authorities read from the source chain are invalid.
|
||||
#[error("Read invalid {0} authorities set: {1:?}")]
|
||||
ReadInvalidAuthorities(&'static str, AuthorityList),
|
||||
/// Failed to guess initial GRANDPA authorities at the given header of the source chain.
|
||||
#[error("Failed to guess initial {0} GRANDPA authorities set id: checked all possible ids in range [0; {1}]")]
|
||||
GuessInitialAuthorities(&'static str, HeaderNumber),
|
||||
/// Failed to retrieve GRANDPA authorities at the given header from the source chain.
|
||||
#[error("Failed to retrive {0} GRANDPA authorities set at header {1}: {2:?}")]
|
||||
RetrieveAuthorities(&'static str, Hash, client::Error),
|
||||
/// Failed to decode GRANDPA authorities at the given header of the source chain.
|
||||
#[error("Failed to decode {0} GRANDPA authorities set at header {1}: {2:?}")]
|
||||
DecodeAuthorities(&'static str, Hash, codec::Error),
|
||||
/// Failed to retrieve header by the hash from the source chain.
|
||||
#[error("Failed to retrieve {0} header with hash {1}: {2:?}")]
|
||||
RetrieveHeader(&'static str, Hash, client::Error),
|
||||
/// Failed to submit signed extrinsic from to the target chain.
|
||||
#[error(
|
||||
"Failed to retrieve `is_initialized` flag of the with-{0} finality pallet at {1}: {2:?}"
|
||||
)]
|
||||
IsInitializedRetrieve(&'static str, &'static str, client::Error),
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
// 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/>.
|
||||
|
||||
//! Support of different finality engines, available in Substrate.
|
||||
|
||||
use crate::error::Error;
|
||||
use async_trait::async_trait;
|
||||
use bp_header_chain::{
|
||||
justification::{verify_justification, GrandpaJustification},
|
||||
ConsensusLogReader, FinalityProof, GrandpaConsensusLogReader,
|
||||
};
|
||||
use bp_runtime::{BasicOperatingMode, OperatingMode};
|
||||
use codec::{Decode, Encode};
|
||||
use finality_grandpa::voter_set::VoterSet;
|
||||
use num_traits::{One, Zero};
|
||||
use relay_substrate_client::{
|
||||
BlockNumberOf, Chain, ChainWithGrandpa, Client, Error as SubstrateError, HashOf, HeaderOf,
|
||||
Subscription, SubstrateFinalityClient, SubstrateGrandpaFinalityClient,
|
||||
};
|
||||
use sp_core::{storage::StorageKey, Bytes};
|
||||
use sp_finality_grandpa::{AuthorityList as GrandpaAuthoritiesSet, GRANDPA_ENGINE_ID};
|
||||
use sp_runtime::{traits::Header, ConsensusEngineId};
|
||||
use std::marker::PhantomData;
|
||||
|
||||
/// Finality engine, used by the Substrate chain.
|
||||
#[async_trait]
|
||||
pub trait Engine<C: Chain>: Send {
|
||||
/// Unique consensus engine identifier.
|
||||
const ID: ConsensusEngineId;
|
||||
/// A reader that can extract the consensus log from the header digest and interpret it.
|
||||
type ConsensusLogReader: ConsensusLogReader;
|
||||
/// Type of Finality RPC client used by this engine.
|
||||
type FinalityClient: SubstrateFinalityClient<C>;
|
||||
/// Type of finality proofs, used by consensus engine.
|
||||
type FinalityProof: FinalityProof<BlockNumberOf<C>> + Decode + Encode;
|
||||
/// Type of bridge pallet initialization data.
|
||||
type InitializationData: std::fmt::Debug + Send + Sync + 'static;
|
||||
/// Type of bridge pallet operating mode.
|
||||
type OperatingMode: OperatingMode + 'static;
|
||||
|
||||
/// Returns storage at the bridged (target) chain that corresponds to some value that is
|
||||
/// missing from the storage until bridge pallet is initialized.
|
||||
///
|
||||
/// Note that we don't care about type of the value - just if it present or not.
|
||||
fn is_initialized_key() -> StorageKey;
|
||||
|
||||
/// Returns `Ok(true)` if finality pallet at the bridged chain has already been initialized.
|
||||
async fn is_initialized<TargetChain: Chain>(
|
||||
target_client: &Client<TargetChain>,
|
||||
) -> Result<bool, SubstrateError> {
|
||||
Ok(target_client
|
||||
.raw_storage_value(Self::is_initialized_key(), None)
|
||||
.await?
|
||||
.is_some())
|
||||
}
|
||||
|
||||
/// Returns storage key at the bridged (target) chain that corresponds to the variable
|
||||
/// that holds the operating mode of the pallet.
|
||||
fn pallet_operating_mode_key() -> StorageKey;
|
||||
|
||||
/// Returns `Ok(true)` if finality pallet at the bridged chain is halted.
|
||||
async fn is_halted<TargetChain: Chain>(
|
||||
target_client: &Client<TargetChain>,
|
||||
) -> Result<bool, SubstrateError> {
|
||||
Ok(target_client
|
||||
.storage_value::<Self::OperatingMode>(Self::pallet_operating_mode_key(), None)
|
||||
.await?
|
||||
.map(|operating_mode| operating_mode.is_halted())
|
||||
.unwrap_or(false))
|
||||
}
|
||||
|
||||
/// A method to subscribe to encoded finality proofs, given source client.
|
||||
async fn finality_proofs(client: &Client<C>) -> Result<Subscription<Bytes>, SubstrateError> {
|
||||
client.subscribe_finality_justifications::<Self::FinalityClient>().await
|
||||
}
|
||||
|
||||
/// Prepare initialization data for the finality bridge pallet.
|
||||
async fn prepare_initialization_data(
|
||||
client: Client<C>,
|
||||
) -> Result<Self::InitializationData, Error<HashOf<C>, BlockNumberOf<C>>>;
|
||||
}
|
||||
|
||||
/// GRANDPA finality engine.
|
||||
pub struct Grandpa<C>(PhantomData<C>);
|
||||
|
||||
impl<C: ChainWithGrandpa> Grandpa<C> {
|
||||
/// Read header by hash from the source client.
|
||||
async fn source_header(
|
||||
source_client: &Client<C>,
|
||||
header_hash: C::Hash,
|
||||
) -> Result<C::Header, Error<HashOf<C>, BlockNumberOf<C>>> {
|
||||
source_client
|
||||
.header_by_hash(header_hash)
|
||||
.await
|
||||
.map_err(|err| Error::RetrieveHeader(C::NAME, header_hash, err))
|
||||
}
|
||||
|
||||
/// Read GRANDPA authorities set at given header.
|
||||
async fn source_authorities_set(
|
||||
source_client: &Client<C>,
|
||||
header_hash: C::Hash,
|
||||
) -> Result<GrandpaAuthoritiesSet, Error<HashOf<C>, BlockNumberOf<C>>> {
|
||||
let raw_authorities_set = source_client
|
||||
.grandpa_authorities_set(header_hash)
|
||||
.await
|
||||
.map_err(|err| Error::RetrieveAuthorities(C::NAME, header_hash, err))?;
|
||||
GrandpaAuthoritiesSet::decode(&mut &raw_authorities_set[..])
|
||||
.map_err(|err| Error::DecodeAuthorities(C::NAME, header_hash, err))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<C: ChainWithGrandpa> Engine<C> for Grandpa<C> {
|
||||
const ID: ConsensusEngineId = GRANDPA_ENGINE_ID;
|
||||
type ConsensusLogReader = GrandpaConsensusLogReader<<C::Header as Header>::Number>;
|
||||
type FinalityClient = SubstrateGrandpaFinalityClient;
|
||||
type FinalityProof = GrandpaJustification<HeaderOf<C>>;
|
||||
type InitializationData = bp_header_chain::InitializationData<C::Header>;
|
||||
type OperatingMode = BasicOperatingMode;
|
||||
|
||||
fn is_initialized_key() -> StorageKey {
|
||||
bp_header_chain::storage_keys::best_finalized_key(C::WITH_CHAIN_GRANDPA_PALLET_NAME)
|
||||
}
|
||||
|
||||
fn pallet_operating_mode_key() -> StorageKey {
|
||||
bp_header_chain::storage_keys::pallet_operating_mode_key(C::WITH_CHAIN_GRANDPA_PALLET_NAME)
|
||||
}
|
||||
|
||||
/// Prepare initialization data for the GRANDPA verifier pallet.
|
||||
async fn prepare_initialization_data(
|
||||
source_client: Client<C>,
|
||||
) -> Result<Self::InitializationData, Error<HashOf<C>, BlockNumberOf<C>>> {
|
||||
// In ideal world we just need to get best finalized header and then to read GRANDPA
|
||||
// authorities set (`pallet_grandpa::CurrentSetId` + `GrandpaApi::grandpa_authorities()`) at
|
||||
// this header.
|
||||
//
|
||||
// But now there are problems with this approach - `CurrentSetId` may return invalid value.
|
||||
// So here we're waiting for the next justification, read the authorities set and then try
|
||||
// to figure out the set id with bruteforce.
|
||||
let justifications = Self::finality_proofs(&source_client)
|
||||
.await
|
||||
.map_err(|err| Error::Subscribe(C::NAME, err))?;
|
||||
// Read next justification - the header that it finalizes will be used as initial header.
|
||||
let justification = justifications
|
||||
.next()
|
||||
.await
|
||||
.map_err(|e| Error::ReadJustification(C::NAME, e))
|
||||
.and_then(|justification| {
|
||||
justification.ok_or(Error::ReadJustificationStreamEnded(C::NAME))
|
||||
})?;
|
||||
|
||||
// Read initial header.
|
||||
let justification: GrandpaJustification<C::Header> =
|
||||
Decode::decode(&mut &justification.0[..])
|
||||
.map_err(|err| Error::DecodeJustification(C::NAME, err))?;
|
||||
|
||||
let (initial_header_hash, initial_header_number) =
|
||||
(justification.commit.target_hash, justification.commit.target_number);
|
||||
|
||||
let initial_header = Self::source_header(&source_client, initial_header_hash).await?;
|
||||
log::trace!(target: "bridge", "Selected {} initial header: {}/{}",
|
||||
C::NAME,
|
||||
initial_header_number,
|
||||
initial_header_hash,
|
||||
);
|
||||
|
||||
// Read GRANDPA authorities set at initial header.
|
||||
let initial_authorities_set =
|
||||
Self::source_authorities_set(&source_client, initial_header_hash).await?;
|
||||
log::trace!(target: "bridge", "Selected {} initial authorities set: {:?}",
|
||||
C::NAME,
|
||||
initial_authorities_set,
|
||||
);
|
||||
|
||||
// If initial header changes the GRANDPA authorities set, then we need previous authorities
|
||||
// to verify justification.
|
||||
let mut authorities_for_verification = initial_authorities_set.clone();
|
||||
let scheduled_change =
|
||||
GrandpaConsensusLogReader::<BlockNumberOf<C>>::find_authorities_change(
|
||||
initial_header.digest(),
|
||||
);
|
||||
assert!(
|
||||
scheduled_change.as_ref().map(|c| c.delay.is_zero()).unwrap_or(true),
|
||||
"GRANDPA authorities change at {} scheduled to happen in {:?} blocks. We expect\
|
||||
regular change to have zero delay",
|
||||
initial_header_hash,
|
||||
scheduled_change.as_ref().map(|c| c.delay),
|
||||
);
|
||||
let schedules_change = scheduled_change.is_some();
|
||||
if schedules_change {
|
||||
authorities_for_verification =
|
||||
Self::source_authorities_set(&source_client, *initial_header.parent_hash()).await?;
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"Selected {} header is scheduling GRANDPA authorities set changes. Using previous set: {:?}",
|
||||
C::NAME,
|
||||
authorities_for_verification,
|
||||
);
|
||||
}
|
||||
|
||||
// Now let's try to guess authorities set id by verifying justification.
|
||||
let mut initial_authorities_set_id = 0;
|
||||
let mut min_possible_block_number = C::BlockNumber::zero();
|
||||
let authorities_for_verification = VoterSet::new(authorities_for_verification.clone())
|
||||
.ok_or(Error::ReadInvalidAuthorities(C::NAME, authorities_for_verification))?;
|
||||
loop {
|
||||
log::trace!(
|
||||
target: "bridge", "Trying {} GRANDPA authorities set id: {}",
|
||||
C::NAME,
|
||||
initial_authorities_set_id,
|
||||
);
|
||||
|
||||
let is_valid_set_id = verify_justification::<C::Header>(
|
||||
(initial_header_hash, initial_header_number),
|
||||
initial_authorities_set_id,
|
||||
&authorities_for_verification,
|
||||
&justification,
|
||||
)
|
||||
.is_ok();
|
||||
|
||||
if is_valid_set_id {
|
||||
break
|
||||
}
|
||||
|
||||
initial_authorities_set_id += 1;
|
||||
min_possible_block_number += One::one();
|
||||
if min_possible_block_number > initial_header_number {
|
||||
// there can't be more authorities set changes than headers => if we have reached
|
||||
// `initial_block_number` and still have not found correct value of
|
||||
// `initial_authorities_set_id`, then something else is broken => fail
|
||||
return Err(Error::GuessInitialAuthorities(C::NAME, initial_header_number))
|
||||
}
|
||||
}
|
||||
|
||||
Ok(bp_header_chain::InitializationData {
|
||||
header: Box::new(initial_header),
|
||||
authority_list: initial_authorities_set,
|
||||
set_id: if schedules_change {
|
||||
initial_authorities_set_id + 1
|
||||
} else {
|
||||
initial_authorities_set_id
|
||||
},
|
||||
operating_mode: BasicOperatingMode::Normal,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// 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/>.
|
||||
|
||||
//! Tools for starting guards of finality relays.
|
||||
|
||||
use crate::TransactionParams;
|
||||
|
||||
use relay_substrate_client::{
|
||||
AccountIdOf, AccountKeyPairOf, ChainWithBalances, ChainWithTransactions,
|
||||
};
|
||||
use sp_core::Pair;
|
||||
|
||||
/// Start finality relay guards.
|
||||
pub async fn start<C: ChainWithBalances + ChainWithTransactions>(
|
||||
target_client: &relay_substrate_client::Client<C>,
|
||||
transaction_params: &TransactionParams<AccountKeyPairOf<C>>,
|
||||
enable_version_guard: bool,
|
||||
maximal_balance_decrease_per_day: C::Balance,
|
||||
) -> relay_substrate_client::Result<()>
|
||||
where
|
||||
AccountIdOf<C>: From<<AccountKeyPairOf<C> as Pair>::Public>,
|
||||
{
|
||||
if enable_version_guard {
|
||||
relay_substrate_client::guard::abort_on_spec_version_change(
|
||||
target_client.clone(),
|
||||
target_client.simple_runtime_version().await?.0,
|
||||
);
|
||||
}
|
||||
relay_substrate_client::guard::abort_when_account_balance_decreased(
|
||||
target_client.clone(),
|
||||
transaction_params.signer.public().into(),
|
||||
maximal_balance_decrease_per_day,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
// 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/>.
|
||||
|
||||
//! Initialize Substrate -> Substrate finality bridge.
|
||||
//!
|
||||
//! Initialization is a transaction that calls `initialize()` function of the
|
||||
//! finality pallet (GRANDPA/BEEFY/...). This transaction brings initial header
|
||||
//! and authorities set from source to target chain. The finality sync starts
|
||||
//! with this header.
|
||||
|
||||
use crate::{error::Error, finality::engine::Engine};
|
||||
|
||||
use relay_substrate_client::{
|
||||
Chain, ChainWithTransactions, Client, Error as SubstrateError, SignParam, UnsignedTransaction,
|
||||
};
|
||||
use sp_runtime::traits::Header as HeaderT;
|
||||
|
||||
/// Submit headers-bridge initialization transaction.
|
||||
pub async fn initialize<
|
||||
E: Engine<SourceChain>,
|
||||
SourceChain: Chain,
|
||||
TargetChain: ChainWithTransactions,
|
||||
F,
|
||||
>(
|
||||
source_client: Client<SourceChain>,
|
||||
target_client: Client<TargetChain>,
|
||||
target_transactions_signer: TargetChain::AccountId,
|
||||
target_signing_data: SignParam<TargetChain>,
|
||||
prepare_initialize_transaction: F,
|
||||
dry_run: bool,
|
||||
) where
|
||||
F: FnOnce(
|
||||
TargetChain::Index,
|
||||
E::InitializationData,
|
||||
) -> Result<UnsignedTransaction<TargetChain>, SubstrateError>
|
||||
+ Send
|
||||
+ 'static,
|
||||
{
|
||||
let result = do_initialize::<E, _, _, _>(
|
||||
source_client,
|
||||
target_client,
|
||||
target_transactions_signer,
|
||||
target_signing_data,
|
||||
prepare_initialize_transaction,
|
||||
dry_run,
|
||||
)
|
||||
.await;
|
||||
|
||||
match result {
|
||||
Ok(Some(tx_hash)) => log::info!(
|
||||
target: "bridge",
|
||||
"Successfully submitted {}-headers bridge initialization transaction to {}: {:?}",
|
||||
SourceChain::NAME,
|
||||
TargetChain::NAME,
|
||||
tx_hash,
|
||||
),
|
||||
Ok(None) => (),
|
||||
Err(err) => log::error!(
|
||||
target: "bridge",
|
||||
"Failed to submit {}-headers bridge initialization transaction to {}: {:?}",
|
||||
SourceChain::NAME,
|
||||
TargetChain::NAME,
|
||||
err,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Craft and submit initialization transaction, returning any error that may occur.
|
||||
async fn do_initialize<
|
||||
E: Engine<SourceChain>,
|
||||
SourceChain: Chain,
|
||||
TargetChain: ChainWithTransactions,
|
||||
F,
|
||||
>(
|
||||
source_client: Client<SourceChain>,
|
||||
target_client: Client<TargetChain>,
|
||||
target_transactions_signer: TargetChain::AccountId,
|
||||
target_signing_data: SignParam<TargetChain>,
|
||||
prepare_initialize_transaction: F,
|
||||
dry_run: bool,
|
||||
) -> Result<
|
||||
Option<TargetChain::Hash>,
|
||||
Error<SourceChain::Hash, <SourceChain::Header as HeaderT>::Number>,
|
||||
>
|
||||
where
|
||||
F: FnOnce(
|
||||
TargetChain::Index,
|
||||
E::InitializationData,
|
||||
) -> Result<UnsignedTransaction<TargetChain>, SubstrateError>
|
||||
+ Send
|
||||
+ 'static,
|
||||
{
|
||||
let is_initialized = E::is_initialized(&target_client)
|
||||
.await
|
||||
.map_err(|e| Error::IsInitializedRetrieve(SourceChain::NAME, TargetChain::NAME, e))?;
|
||||
if is_initialized {
|
||||
log::info!(
|
||||
target: "bridge",
|
||||
"{}-headers bridge at {} is already initialized. Skipping",
|
||||
SourceChain::NAME,
|
||||
TargetChain::NAME,
|
||||
);
|
||||
if !dry_run {
|
||||
return Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
let initialization_data = E::prepare_initialization_data(source_client).await?;
|
||||
log::info!(
|
||||
target: "bridge",
|
||||
"Prepared initialization data for {}-headers bridge at {}: {:?}",
|
||||
SourceChain::NAME,
|
||||
TargetChain::NAME,
|
||||
initialization_data,
|
||||
);
|
||||
|
||||
let initialization_tx_hash = target_client
|
||||
.submit_signed_extrinsic(
|
||||
target_transactions_signer,
|
||||
target_signing_data,
|
||||
move |_, transaction_nonce| {
|
||||
let tx = prepare_initialize_transaction(transaction_nonce, initialization_data);
|
||||
if dry_run {
|
||||
Err(SubstrateError::Custom(
|
||||
"Not submitting extrinsic in `dry-run` mode!".to_string(),
|
||||
))
|
||||
} else {
|
||||
tx
|
||||
}
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|err| Error::SubmitTransaction(TargetChain::NAME, err))?;
|
||||
|
||||
Ok(Some(initialization_tx_hash))
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
// 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/>.
|
||||
|
||||
//! Types and functions intended to ease adding of new Substrate -> Substrate
|
||||
//! finality proofs synchronization pipelines.
|
||||
|
||||
use crate::{
|
||||
finality::{
|
||||
engine::Engine,
|
||||
source::{SubstrateFinalityProof, SubstrateFinalitySource},
|
||||
target::SubstrateFinalityTarget,
|
||||
},
|
||||
TransactionParams,
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use bp_header_chain::justification::GrandpaJustification;
|
||||
use finality_relay::FinalitySyncPipeline;
|
||||
use pallet_bridge_grandpa::{Call as BridgeGrandpaCall, Config as BridgeGrandpaConfig};
|
||||
use relay_substrate_client::{
|
||||
transaction_stall_timeout, AccountIdOf, AccountKeyPairOf, BlockNumberOf, CallOf, Chain,
|
||||
ChainWithTransactions, Client, HashOf, HeaderOf, SyncHeader,
|
||||
};
|
||||
use relay_utils::metrics::MetricsParams;
|
||||
use sp_core::Pair;
|
||||
use std::{fmt::Debug, marker::PhantomData};
|
||||
|
||||
pub mod engine;
|
||||
pub mod guards;
|
||||
pub mod initialize;
|
||||
pub mod source;
|
||||
pub mod target;
|
||||
|
||||
/// Default limit of recent finality proofs.
|
||||
///
|
||||
/// Finality delay of 4096 blocks is unlikely to happen in practice in
|
||||
/// Substrate+GRANDPA based chains (good to know).
|
||||
pub(crate) const RECENT_FINALITY_PROOFS_LIMIT: usize = 4096;
|
||||
|
||||
/// Substrate -> Substrate finality proofs synchronization pipeline.
|
||||
#[async_trait]
|
||||
pub trait SubstrateFinalitySyncPipeline: 'static + Clone + Debug + Send + Sync {
|
||||
/// Headers of this chain are submitted to the `TargetChain`.
|
||||
type SourceChain: Chain;
|
||||
/// Headers of the `SourceChain` are submitted to this chain.
|
||||
type TargetChain: ChainWithTransactions;
|
||||
|
||||
/// Finality engine.
|
||||
type FinalityEngine: Engine<Self::SourceChain>;
|
||||
/// How submit finality proof call is built?
|
||||
type SubmitFinalityProofCallBuilder: SubmitFinalityProofCallBuilder<Self>;
|
||||
|
||||
/// Add relay guards if required.
|
||||
async fn start_relay_guards(
|
||||
_target_client: &Client<Self::TargetChain>,
|
||||
_transaction_params: &TransactionParams<AccountKeyPairOf<Self::TargetChain>>,
|
||||
_enable_version_guard: bool,
|
||||
) -> relay_substrate_client::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Adapter that allows all `SubstrateFinalitySyncPipeline` to act as `FinalitySyncPipeline`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FinalitySyncPipelineAdapter<P: SubstrateFinalitySyncPipeline> {
|
||||
_phantom: PhantomData<P>,
|
||||
}
|
||||
|
||||
impl<P: SubstrateFinalitySyncPipeline> FinalitySyncPipeline for FinalitySyncPipelineAdapter<P> {
|
||||
const SOURCE_NAME: &'static str = P::SourceChain::NAME;
|
||||
const TARGET_NAME: &'static str = P::TargetChain::NAME;
|
||||
|
||||
type Hash = HashOf<P::SourceChain>;
|
||||
type Number = BlockNumberOf<P::SourceChain>;
|
||||
type ConsensusLogReader = <P::FinalityEngine as Engine<P::SourceChain>>::ConsensusLogReader;
|
||||
type Header = SyncHeader<HeaderOf<P::SourceChain>>;
|
||||
type FinalityProof = SubstrateFinalityProof<P>;
|
||||
}
|
||||
|
||||
/// Different ways of building `submit_finality_proof` calls.
|
||||
pub trait SubmitFinalityProofCallBuilder<P: SubstrateFinalitySyncPipeline> {
|
||||
/// Given source chain header and its finality proofs, build call of `submit_finality_proof`
|
||||
/// function of bridge GRANDPA module at the target chain.
|
||||
fn build_submit_finality_proof_call(
|
||||
header: SyncHeader<HeaderOf<P::SourceChain>>,
|
||||
proof: SubstrateFinalityProof<P>,
|
||||
) -> CallOf<P::TargetChain>;
|
||||
}
|
||||
|
||||
/// Building `submit_finality_proof` call when you have direct access to the target
|
||||
/// chain runtime.
|
||||
pub struct DirectSubmitGrandpaFinalityProofCallBuilder<P, R, I> {
|
||||
_phantom: PhantomData<(P, R, I)>,
|
||||
}
|
||||
|
||||
impl<P, R, I> SubmitFinalityProofCallBuilder<P>
|
||||
for DirectSubmitGrandpaFinalityProofCallBuilder<P, R, I>
|
||||
where
|
||||
P: SubstrateFinalitySyncPipeline,
|
||||
R: BridgeGrandpaConfig<I>,
|
||||
I: 'static,
|
||||
R::BridgedChain: bp_runtime::Chain<Header = HeaderOf<P::SourceChain>>,
|
||||
CallOf<P::TargetChain>: From<BridgeGrandpaCall<R, I>>,
|
||||
P::FinalityEngine:
|
||||
Engine<P::SourceChain, FinalityProof = GrandpaJustification<HeaderOf<P::SourceChain>>>,
|
||||
{
|
||||
fn build_submit_finality_proof_call(
|
||||
header: SyncHeader<HeaderOf<P::SourceChain>>,
|
||||
proof: GrandpaJustification<HeaderOf<P::SourceChain>>,
|
||||
) -> CallOf<P::TargetChain> {
|
||||
BridgeGrandpaCall::<R, I>::submit_finality_proof {
|
||||
finality_target: Box::new(header.into_inner()),
|
||||
justification: proof,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
/// Macro that generates `SubmitFinalityProofCallBuilder` implementation for the case when
|
||||
/// you only have an access to the mocked version of target chain runtime. In this case you
|
||||
/// should provide "name" of the call variant for the bridge GRANDPA calls and the "name" of
|
||||
/// the variant for the `submit_finality_proof` call within that first option.
|
||||
#[rustfmt::skip]
|
||||
#[macro_export]
|
||||
macro_rules! generate_mocked_submit_finality_proof_call_builder {
|
||||
($pipeline:ident, $mocked_builder:ident, $bridge_grandpa:path, $submit_finality_proof:path) => {
|
||||
pub struct $mocked_builder;
|
||||
|
||||
impl $crate::finality::SubmitFinalityProofCallBuilder<$pipeline>
|
||||
for $mocked_builder
|
||||
{
|
||||
fn build_submit_finality_proof_call(
|
||||
header: relay_substrate_client::SyncHeader<
|
||||
relay_substrate_client::HeaderOf<
|
||||
<$pipeline as $crate::finality::SubstrateFinalitySyncPipeline>::SourceChain
|
||||
>
|
||||
>,
|
||||
proof: bp_header_chain::justification::GrandpaJustification<
|
||||
relay_substrate_client::HeaderOf<
|
||||
<$pipeline as $crate::finality::SubstrateFinalitySyncPipeline>::SourceChain
|
||||
>
|
||||
>,
|
||||
) -> relay_substrate_client::CallOf<
|
||||
<$pipeline as $crate::finality::SubstrateFinalitySyncPipeline>::TargetChain
|
||||
> {
|
||||
$bridge_grandpa($submit_finality_proof(Box::new(header.into_inner()), proof))
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Run Substrate-to-Substrate finality sync loop.
|
||||
pub async fn run<P: SubstrateFinalitySyncPipeline>(
|
||||
source_client: Client<P::SourceChain>,
|
||||
target_client: Client<P::TargetChain>,
|
||||
only_mandatory_headers: bool,
|
||||
transaction_params: TransactionParams<AccountKeyPairOf<P::TargetChain>>,
|
||||
metrics_params: MetricsParams,
|
||||
) -> anyhow::Result<()>
|
||||
where
|
||||
AccountIdOf<P::TargetChain>: From<<AccountKeyPairOf<P::TargetChain> as Pair>::Public>,
|
||||
{
|
||||
log::info!(
|
||||
target: "bridge",
|
||||
"Starting {} -> {} finality proof relay",
|
||||
P::SourceChain::NAME,
|
||||
P::TargetChain::NAME,
|
||||
);
|
||||
|
||||
finality_relay::run(
|
||||
SubstrateFinalitySource::<P>::new(source_client, None),
|
||||
SubstrateFinalityTarget::<P>::new(target_client, transaction_params.clone()),
|
||||
finality_relay::FinalitySyncParams {
|
||||
tick: std::cmp::max(
|
||||
P::SourceChain::AVERAGE_BLOCK_INTERVAL,
|
||||
P::TargetChain::AVERAGE_BLOCK_INTERVAL,
|
||||
),
|
||||
recent_finality_proofs_limit: RECENT_FINALITY_PROOFS_LIMIT,
|
||||
stall_timeout: transaction_stall_timeout(
|
||||
transaction_params.mortality,
|
||||
P::TargetChain::AVERAGE_BLOCK_INTERVAL,
|
||||
relay_utils::STALL_TIMEOUT,
|
||||
),
|
||||
only_mandatory_headers,
|
||||
},
|
||||
metrics_params,
|
||||
futures::future::pending(),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| anyhow::format_err!("{}", e))
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
// 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/>.
|
||||
|
||||
//! Default generic implementation of finality source for basic Substrate client.
|
||||
|
||||
use crate::finality::{engine::Engine, FinalitySyncPipelineAdapter, SubstrateFinalitySyncPipeline};
|
||||
|
||||
use async_std::sync::{Arc, Mutex};
|
||||
use async_trait::async_trait;
|
||||
use codec::Decode;
|
||||
use finality_relay::SourceClient;
|
||||
use futures::stream::{unfold, Stream, StreamExt};
|
||||
use relay_substrate_client::{
|
||||
BlockNumberOf, BlockWithJustification, Chain, Client, Error, HeaderOf,
|
||||
};
|
||||
use relay_utils::relay_loop::Client as RelayClient;
|
||||
use std::pin::Pin;
|
||||
|
||||
/// Shared updatable reference to the maximal header number that we want to sync from the source.
|
||||
pub type RequiredHeaderNumberRef<C> = Arc<Mutex<<C as bp_runtime::Chain>::BlockNumber>>;
|
||||
|
||||
/// Substrate finality proofs stream.
|
||||
pub type SubstrateFinalityProofsStream<P> =
|
||||
Pin<Box<dyn Stream<Item = SubstrateFinalityProof<P>> + Send>>;
|
||||
|
||||
/// Substrate finality proof. Specific to the used `FinalityEngine`.
|
||||
pub type SubstrateFinalityProof<P> =
|
||||
<<P as SubstrateFinalitySyncPipeline>::FinalityEngine as Engine<
|
||||
<P as SubstrateFinalitySyncPipeline>::SourceChain,
|
||||
>>::FinalityProof;
|
||||
|
||||
/// Substrate node as finality source.
|
||||
pub struct SubstrateFinalitySource<P: SubstrateFinalitySyncPipeline> {
|
||||
client: Client<P::SourceChain>,
|
||||
maximal_header_number: Option<RequiredHeaderNumberRef<P::SourceChain>>,
|
||||
}
|
||||
|
||||
impl<P: SubstrateFinalitySyncPipeline> SubstrateFinalitySource<P> {
|
||||
/// Create new headers source using given client.
|
||||
pub fn new(
|
||||
client: Client<P::SourceChain>,
|
||||
maximal_header_number: Option<RequiredHeaderNumberRef<P::SourceChain>>,
|
||||
) -> Self {
|
||||
SubstrateFinalitySource { client, maximal_header_number }
|
||||
}
|
||||
|
||||
/// Returns reference to the underlying RPC client.
|
||||
pub fn client(&self) -> &Client<P::SourceChain> {
|
||||
&self.client
|
||||
}
|
||||
|
||||
/// Returns best finalized block number.
|
||||
pub async fn on_chain_best_finalized_block_number(
|
||||
&self,
|
||||
) -> Result<BlockNumberOf<P::SourceChain>, Error> {
|
||||
// we **CAN** continue to relay finality proofs if source node is out of sync, because
|
||||
// target node may be missing proofs that are already available at the source
|
||||
self.client.best_finalized_header_number().await
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: SubstrateFinalitySyncPipeline> Clone for SubstrateFinalitySource<P> {
|
||||
fn clone(&self) -> Self {
|
||||
SubstrateFinalitySource {
|
||||
client: self.client.clone(),
|
||||
maximal_header_number: self.maximal_header_number.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<P: SubstrateFinalitySyncPipeline> RelayClient for SubstrateFinalitySource<P> {
|
||||
type Error = Error;
|
||||
|
||||
async fn reconnect(&mut self) -> Result<(), Error> {
|
||||
self.client.reconnect().await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<P: SubstrateFinalitySyncPipeline> SourceClient<FinalitySyncPipelineAdapter<P>>
|
||||
for SubstrateFinalitySource<P>
|
||||
{
|
||||
type FinalityProofsStream = SubstrateFinalityProofsStream<P>;
|
||||
|
||||
async fn best_finalized_block_number(&self) -> Result<BlockNumberOf<P::SourceChain>, Error> {
|
||||
let mut finalized_header_number = self.on_chain_best_finalized_block_number().await?;
|
||||
// never return block number larger than requested. This way we'll never sync headers
|
||||
// past `maximal_header_number`
|
||||
if let Some(ref maximal_header_number) = self.maximal_header_number {
|
||||
let maximal_header_number = *maximal_header_number.lock().await;
|
||||
if finalized_header_number > maximal_header_number {
|
||||
finalized_header_number = maximal_header_number;
|
||||
}
|
||||
}
|
||||
Ok(finalized_header_number)
|
||||
}
|
||||
|
||||
async fn header_and_finality_proof(
|
||||
&self,
|
||||
number: BlockNumberOf<P::SourceChain>,
|
||||
) -> Result<
|
||||
(
|
||||
relay_substrate_client::SyncHeader<HeaderOf<P::SourceChain>>,
|
||||
Option<SubstrateFinalityProof<P>>,
|
||||
),
|
||||
Error,
|
||||
> {
|
||||
let header_hash = self.client.block_hash_by_number(number).await?;
|
||||
let signed_block = self.client.get_block(Some(header_hash)).await?;
|
||||
|
||||
let justification = signed_block
|
||||
.justification(P::FinalityEngine::ID)
|
||||
.map(|raw_justification| {
|
||||
SubstrateFinalityProof::<P>::decode(&mut raw_justification.as_slice())
|
||||
})
|
||||
.transpose()
|
||||
.map_err(Error::ResponseParseFailed)?;
|
||||
|
||||
Ok((signed_block.header().into(), justification))
|
||||
}
|
||||
|
||||
async fn finality_proofs(&self) -> Result<Self::FinalityProofsStream, Error> {
|
||||
Ok(unfold(
|
||||
P::FinalityEngine::finality_proofs(&self.client).await?,
|
||||
move |subscription| async move {
|
||||
loop {
|
||||
let log_error = |err| {
|
||||
log::error!(
|
||||
target: "bridge",
|
||||
"Failed to read justification target from the {} justifications stream: {:?}",
|
||||
P::SourceChain::NAME,
|
||||
err,
|
||||
);
|
||||
};
|
||||
|
||||
let next_justification = subscription
|
||||
.next()
|
||||
.await
|
||||
.map_err(|err| log_error(err.to_string()))
|
||||
.ok()??;
|
||||
|
||||
let decoded_justification =
|
||||
<P::FinalityEngine as Engine<P::SourceChain>>::FinalityProof::decode(
|
||||
&mut &next_justification[..],
|
||||
);
|
||||
|
||||
let justification = match decoded_justification {
|
||||
Ok(j) => j,
|
||||
Err(err) => {
|
||||
log_error(format!("decode failed with error {err:?}"));
|
||||
continue
|
||||
},
|
||||
};
|
||||
|
||||
return Some((justification, subscription))
|
||||
}
|
||||
},
|
||||
)
|
||||
.boxed())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Substrate client as Substrate finality proof target.
|
||||
|
||||
use crate::{
|
||||
finality::{
|
||||
engine::Engine, source::SubstrateFinalityProof, FinalitySyncPipelineAdapter,
|
||||
SubmitFinalityProofCallBuilder, SubstrateFinalitySyncPipeline,
|
||||
},
|
||||
TransactionParams,
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use finality_relay::TargetClient;
|
||||
use relay_substrate_client::{
|
||||
AccountIdOf, AccountKeyPairOf, Chain, Client, Error, HeaderIdOf, HeaderOf, SignParam,
|
||||
SyncHeader, TransactionEra, TransactionTracker, UnsignedTransaction,
|
||||
};
|
||||
use relay_utils::relay_loop::Client as RelayClient;
|
||||
use sp_core::Pair;
|
||||
|
||||
/// Substrate client as Substrate finality target.
|
||||
pub struct SubstrateFinalityTarget<P: SubstrateFinalitySyncPipeline> {
|
||||
client: Client<P::TargetChain>,
|
||||
transaction_params: TransactionParams<AccountKeyPairOf<P::TargetChain>>,
|
||||
}
|
||||
|
||||
impl<P: SubstrateFinalitySyncPipeline> SubstrateFinalityTarget<P> {
|
||||
/// Create new Substrate headers target.
|
||||
pub fn new(
|
||||
client: Client<P::TargetChain>,
|
||||
transaction_params: TransactionParams<AccountKeyPairOf<P::TargetChain>>,
|
||||
) -> Self {
|
||||
SubstrateFinalityTarget { client, transaction_params }
|
||||
}
|
||||
|
||||
/// Ensure that the bridge pallet at target chain is active.
|
||||
pub async fn ensure_pallet_active(&self) -> Result<(), Error> {
|
||||
let is_halted = P::FinalityEngine::is_halted(&self.client).await?;
|
||||
if is_halted {
|
||||
return Err(Error::BridgePalletIsHalted)
|
||||
}
|
||||
|
||||
let is_initialized = P::FinalityEngine::is_initialized(&self.client).await?;
|
||||
if !is_initialized {
|
||||
return Err(Error::BridgePalletIsNotInitialized)
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: SubstrateFinalitySyncPipeline> Clone for SubstrateFinalityTarget<P> {
|
||||
fn clone(&self) -> Self {
|
||||
SubstrateFinalityTarget {
|
||||
client: self.client.clone(),
|
||||
transaction_params: self.transaction_params.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<P: SubstrateFinalitySyncPipeline> RelayClient for SubstrateFinalityTarget<P> {
|
||||
type Error = Error;
|
||||
|
||||
async fn reconnect(&mut self) -> Result<(), Error> {
|
||||
self.client.reconnect().await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<P: SubstrateFinalitySyncPipeline> TargetClient<FinalitySyncPipelineAdapter<P>>
|
||||
for SubstrateFinalityTarget<P>
|
||||
where
|
||||
AccountIdOf<P::TargetChain>: From<<AccountKeyPairOf<P::TargetChain> as Pair>::Public>,
|
||||
{
|
||||
type TransactionTracker = TransactionTracker<P::TargetChain, Client<P::TargetChain>>;
|
||||
|
||||
async fn best_finalized_source_block_id(&self) -> Result<HeaderIdOf<P::SourceChain>, Error> {
|
||||
// we can't continue to relay finality if target node is out of sync, because
|
||||
// it may have already received (some of) headers that we're going to relay
|
||||
self.client.ensure_synced().await?;
|
||||
// we can't relay finality if bridge pallet at target chain is halted
|
||||
self.ensure_pallet_active().await?;
|
||||
|
||||
Ok(crate::messages_source::read_client_state::<P::TargetChain, P::SourceChain>(
|
||||
&self.client,
|
||||
None,
|
||||
P::SourceChain::BEST_FINALIZED_HEADER_ID_METHOD,
|
||||
)
|
||||
.await?
|
||||
.best_finalized_peer_at_best_self)
|
||||
}
|
||||
|
||||
async fn submit_finality_proof(
|
||||
&self,
|
||||
header: SyncHeader<HeaderOf<P::SourceChain>>,
|
||||
proof: SubstrateFinalityProof<P>,
|
||||
) -> Result<Self::TransactionTracker, Error> {
|
||||
let genesis_hash = *self.client.genesis_hash();
|
||||
let transaction_params = self.transaction_params.clone();
|
||||
let call =
|
||||
P::SubmitFinalityProofCallBuilder::build_submit_finality_proof_call(header, proof);
|
||||
let (spec_version, transaction_version) = self.client.simple_runtime_version().await?;
|
||||
self.client
|
||||
.submit_and_watch_signed_extrinsic(
|
||||
self.transaction_params.signer.public().into(),
|
||||
SignParam::<P::TargetChain> {
|
||||
spec_version,
|
||||
transaction_version,
|
||||
genesis_hash,
|
||||
signer: transaction_params.signer.clone(),
|
||||
},
|
||||
move |best_block_id, transaction_nonce| {
|
||||
Ok(UnsignedTransaction::new(call.into(), transaction_nonce)
|
||||
.era(TransactionEra::new(best_block_id, transaction_params.mortality)))
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// 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/>.
|
||||
|
||||
//! The library of substrate relay. contains some public codes to provide to substrate relay.
|
||||
|
||||
#![warn(missing_docs)]
|
||||
|
||||
pub mod error;
|
||||
pub mod finality;
|
||||
pub mod messages_lane;
|
||||
pub mod messages_metrics;
|
||||
pub mod messages_source;
|
||||
pub mod messages_target;
|
||||
pub mod on_demand;
|
||||
pub mod parachains;
|
||||
|
||||
/// Transaction creation parameters.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TransactionParams<TS> {
|
||||
/// Transactions author.
|
||||
pub signer: TS,
|
||||
/// Transactions mortality.
|
||||
pub mortality: Option<u32>,
|
||||
}
|
||||
|
||||
/// Tagged relay account, which balance may be exposed as metrics by the relay.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum TaggedAccount<AccountId> {
|
||||
/// Account, used to sign headers relay transactions from given bridged chain.
|
||||
Headers {
|
||||
/// Account id.
|
||||
id: AccountId,
|
||||
/// Name of the bridged chain, which headers are relayed.
|
||||
bridged_chain: String,
|
||||
},
|
||||
/// Account, used to sign parachains relay transactions from given bridged relay chain.
|
||||
Parachains {
|
||||
/// Account id.
|
||||
id: AccountId,
|
||||
/// Name of the bridged relay chain with parachain heads.
|
||||
bridged_chain: String,
|
||||
},
|
||||
/// Account, used to sign message relay transactions from given bridged chain.
|
||||
Messages {
|
||||
/// Account id.
|
||||
id: AccountId,
|
||||
/// Name of the bridged chain, which sends us messages or delivery confirmations.
|
||||
bridged_chain: String,
|
||||
},
|
||||
/// Account, used to sign messages with-bridged-chain pallet parameters update transactions.
|
||||
MessagesPalletOwner {
|
||||
/// Account id.
|
||||
id: AccountId,
|
||||
/// Name of the chain, bridged using messages pallet at our chain.
|
||||
bridged_chain: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl<AccountId> TaggedAccount<AccountId> {
|
||||
/// Returns reference to the account id.
|
||||
pub fn id(&self) -> &AccountId {
|
||||
match *self {
|
||||
TaggedAccount::Headers { ref id, .. } => id,
|
||||
TaggedAccount::Parachains { ref id, .. } => id,
|
||||
TaggedAccount::Messages { ref id, .. } => id,
|
||||
TaggedAccount::MessagesPalletOwner { ref id, .. } => id,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns stringified account tag.
|
||||
pub fn tag(&self) -> String {
|
||||
match *self {
|
||||
TaggedAccount::Headers { ref bridged_chain, .. } => format!("{bridged_chain}Headers"),
|
||||
TaggedAccount::Parachains { ref bridged_chain, .. } => {
|
||||
format!("{bridged_chain}Parachains")
|
||||
},
|
||||
TaggedAccount::Messages { ref bridged_chain, .. } => {
|
||||
format!("{bridged_chain}Messages")
|
||||
},
|
||||
TaggedAccount::MessagesPalletOwner { ref bridged_chain, .. } => {
|
||||
format!("{bridged_chain}MessagesPalletOwner")
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,449 @@
|
||||
// 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/>.
|
||||
|
||||
//! Tools for supporting message lanes between two Substrate-based chains.
|
||||
|
||||
use crate::{
|
||||
messages_source::{SubstrateMessagesProof, SubstrateMessagesSource},
|
||||
messages_target::{SubstrateMessagesDeliveryProof, SubstrateMessagesTarget},
|
||||
on_demand::OnDemandRelay,
|
||||
TransactionParams,
|
||||
};
|
||||
|
||||
use async_std::sync::Arc;
|
||||
use bp_messages::{LaneId, MessageNonce};
|
||||
use bp_runtime::{AccountIdOf, Chain as _, WeightExtraOps};
|
||||
use bridge_runtime_common::messages::{
|
||||
source::FromBridgedChainMessagesDeliveryProof, target::FromBridgedChainMessagesProof,
|
||||
};
|
||||
use codec::Encode;
|
||||
use frame_support::{dispatch::GetDispatchInfo, weights::Weight};
|
||||
use messages_relay::message_lane::MessageLane;
|
||||
use pallet_bridge_messages::{Call as BridgeMessagesCall, Config as BridgeMessagesConfig};
|
||||
use relay_substrate_client::{
|
||||
transaction_stall_timeout, AccountKeyPairOf, BalanceOf, BlockNumberOf, CallOf, Chain,
|
||||
ChainWithMessages, ChainWithTransactions, Client, HashOf,
|
||||
};
|
||||
use relay_utils::{
|
||||
metrics::{GlobalMetrics, MetricsParams, StandaloneMetric},
|
||||
STALL_TIMEOUT,
|
||||
};
|
||||
use sp_core::Pair;
|
||||
use std::{convert::TryFrom, fmt::Debug, marker::PhantomData};
|
||||
|
||||
/// Substrate -> Substrate messages synchronization pipeline.
|
||||
pub trait SubstrateMessageLane: 'static + Clone + Debug + Send + Sync {
|
||||
/// Messages of this chain are relayed to the `TargetChain`.
|
||||
type SourceChain: ChainWithMessages + ChainWithTransactions;
|
||||
/// Messages from the `SourceChain` are dispatched on this chain.
|
||||
type TargetChain: ChainWithMessages + ChainWithTransactions;
|
||||
|
||||
/// How receive messages proof call is built?
|
||||
type ReceiveMessagesProofCallBuilder: ReceiveMessagesProofCallBuilder<Self>;
|
||||
/// How receive messages delivery proof call is built?
|
||||
type ReceiveMessagesDeliveryProofCallBuilder: ReceiveMessagesDeliveryProofCallBuilder<Self>;
|
||||
}
|
||||
|
||||
/// Adapter that allows all `SubstrateMessageLane` to act as `MessageLane`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct MessageLaneAdapter<P: SubstrateMessageLane> {
|
||||
_phantom: PhantomData<P>,
|
||||
}
|
||||
|
||||
impl<P: SubstrateMessageLane> MessageLane for MessageLaneAdapter<P> {
|
||||
const SOURCE_NAME: &'static str = P::SourceChain::NAME;
|
||||
const TARGET_NAME: &'static str = P::TargetChain::NAME;
|
||||
|
||||
type MessagesProof = SubstrateMessagesProof<P::SourceChain>;
|
||||
type MessagesReceivingProof = SubstrateMessagesDeliveryProof<P::TargetChain>;
|
||||
|
||||
type SourceChainBalance = BalanceOf<P::SourceChain>;
|
||||
type SourceHeaderNumber = BlockNumberOf<P::SourceChain>;
|
||||
type SourceHeaderHash = HashOf<P::SourceChain>;
|
||||
|
||||
type TargetHeaderNumber = BlockNumberOf<P::TargetChain>;
|
||||
type TargetHeaderHash = HashOf<P::TargetChain>;
|
||||
}
|
||||
|
||||
/// Substrate <-> Substrate messages relay parameters.
|
||||
pub struct MessagesRelayParams<P: SubstrateMessageLane> {
|
||||
/// Messages source client.
|
||||
pub source_client: Client<P::SourceChain>,
|
||||
/// Source transaction params.
|
||||
pub source_transaction_params: TransactionParams<AccountKeyPairOf<P::SourceChain>>,
|
||||
/// Messages target client.
|
||||
pub target_client: Client<P::TargetChain>,
|
||||
/// Target transaction params.
|
||||
pub target_transaction_params: TransactionParams<AccountKeyPairOf<P::TargetChain>>,
|
||||
/// Optional on-demand source to target headers relay.
|
||||
pub source_to_target_headers_relay:
|
||||
Option<Arc<dyn OnDemandRelay<BlockNumberOf<P::SourceChain>>>>,
|
||||
/// Optional on-demand target to source headers relay.
|
||||
pub target_to_source_headers_relay:
|
||||
Option<Arc<dyn OnDemandRelay<BlockNumberOf<P::TargetChain>>>>,
|
||||
/// Identifier of lane that needs to be served.
|
||||
pub lane_id: LaneId,
|
||||
/// Metrics parameters.
|
||||
pub metrics_params: MetricsParams,
|
||||
}
|
||||
|
||||
/// Run Substrate-to-Substrate messages sync loop.
|
||||
pub async fn run<P: SubstrateMessageLane>(params: MessagesRelayParams<P>) -> anyhow::Result<()>
|
||||
where
|
||||
AccountIdOf<P::SourceChain>: From<<AccountKeyPairOf<P::SourceChain> as Pair>::Public>,
|
||||
AccountIdOf<P::TargetChain>: From<<AccountKeyPairOf<P::TargetChain> as Pair>::Public>,
|
||||
BalanceOf<P::SourceChain>: TryFrom<BalanceOf<P::TargetChain>>,
|
||||
{
|
||||
let source_client = params.source_client;
|
||||
let target_client = params.target_client;
|
||||
let relayer_id_at_source: AccountIdOf<P::SourceChain> =
|
||||
params.source_transaction_params.signer.public().into();
|
||||
|
||||
// 2/3 is reserved for proofs and tx overhead
|
||||
let max_messages_size_in_single_batch = P::TargetChain::max_extrinsic_size() / 3;
|
||||
// we don't know exact weights of the Polkadot runtime. So to guess weights we'll be using
|
||||
// weights from Rialto and then simply dividing it by x2.
|
||||
let (max_messages_in_single_batch, max_messages_weight_in_single_batch) =
|
||||
crate::messages_lane::select_delivery_transaction_limits::<
|
||||
<P::TargetChain as ChainWithMessages>::WeightInfo,
|
||||
>(
|
||||
P::TargetChain::max_extrinsic_weight(),
|
||||
P::SourceChain::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX,
|
||||
);
|
||||
let (max_messages_in_single_batch, max_messages_weight_in_single_batch) =
|
||||
(max_messages_in_single_batch / 2, max_messages_weight_in_single_batch / 2);
|
||||
|
||||
log::info!(
|
||||
target: "bridge",
|
||||
"Starting {} -> {} messages relay.\n\t\
|
||||
{} relayer account id: {:?}\n\t\
|
||||
Max messages in single transaction: {}\n\t\
|
||||
Max messages size in single transaction: {}\n\t\
|
||||
Max messages weight in single transaction: {}\n\t\
|
||||
Tx mortality: {:?} (~{}m)/{:?} (~{}m)",
|
||||
P::SourceChain::NAME,
|
||||
P::TargetChain::NAME,
|
||||
P::SourceChain::NAME,
|
||||
relayer_id_at_source,
|
||||
max_messages_in_single_batch,
|
||||
max_messages_size_in_single_batch,
|
||||
max_messages_weight_in_single_batch,
|
||||
params.source_transaction_params.mortality,
|
||||
transaction_stall_timeout(
|
||||
params.source_transaction_params.mortality,
|
||||
P::SourceChain::AVERAGE_BLOCK_INTERVAL,
|
||||
STALL_TIMEOUT,
|
||||
).as_secs_f64() / 60.0f64,
|
||||
params.target_transaction_params.mortality,
|
||||
transaction_stall_timeout(
|
||||
params.target_transaction_params.mortality,
|
||||
P::TargetChain::AVERAGE_BLOCK_INTERVAL,
|
||||
STALL_TIMEOUT,
|
||||
).as_secs_f64() / 60.0f64,
|
||||
);
|
||||
|
||||
messages_relay::message_lane_loop::run(
|
||||
messages_relay::message_lane_loop::Params {
|
||||
lane: params.lane_id,
|
||||
source_tick: P::SourceChain::AVERAGE_BLOCK_INTERVAL,
|
||||
target_tick: P::TargetChain::AVERAGE_BLOCK_INTERVAL,
|
||||
reconnect_delay: relay_utils::relay_loop::RECONNECT_DELAY,
|
||||
delivery_params: messages_relay::message_lane_loop::MessageDeliveryParams {
|
||||
max_unrewarded_relayer_entries_at_target:
|
||||
P::SourceChain::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX,
|
||||
max_unconfirmed_nonces_at_target:
|
||||
P::SourceChain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX,
|
||||
max_messages_in_single_batch,
|
||||
max_messages_weight_in_single_batch,
|
||||
max_messages_size_in_single_batch,
|
||||
},
|
||||
},
|
||||
SubstrateMessagesSource::<P>::new(
|
||||
source_client.clone(),
|
||||
target_client.clone(),
|
||||
params.lane_id,
|
||||
params.source_transaction_params,
|
||||
params.target_to_source_headers_relay,
|
||||
),
|
||||
SubstrateMessagesTarget::<P>::new(
|
||||
target_client,
|
||||
source_client,
|
||||
params.lane_id,
|
||||
relayer_id_at_source,
|
||||
params.target_transaction_params,
|
||||
params.source_to_target_headers_relay,
|
||||
),
|
||||
{
|
||||
GlobalMetrics::new()?.register_and_spawn(¶ms.metrics_params.registry)?;
|
||||
params.metrics_params
|
||||
},
|
||||
futures::future::pending(),
|
||||
)
|
||||
.await
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Different ways of building `receive_messages_proof` calls.
|
||||
pub trait ReceiveMessagesProofCallBuilder<P: SubstrateMessageLane> {
|
||||
/// Given messages proof, build call of `receive_messages_proof` function of bridge
|
||||
/// messages module at the target chain.
|
||||
fn build_receive_messages_proof_call(
|
||||
relayer_id_at_source: AccountIdOf<P::SourceChain>,
|
||||
proof: SubstrateMessagesProof<P::SourceChain>,
|
||||
messages_count: u32,
|
||||
dispatch_weight: Weight,
|
||||
trace_call: bool,
|
||||
) -> CallOf<P::TargetChain>;
|
||||
}
|
||||
|
||||
/// Building `receive_messages_proof` call when you have direct access to the target
|
||||
/// chain runtime.
|
||||
pub struct DirectReceiveMessagesProofCallBuilder<P, R, I> {
|
||||
_phantom: PhantomData<(P, R, I)>,
|
||||
}
|
||||
|
||||
impl<P, R, I> ReceiveMessagesProofCallBuilder<P> for DirectReceiveMessagesProofCallBuilder<P, R, I>
|
||||
where
|
||||
P: SubstrateMessageLane,
|
||||
R: BridgeMessagesConfig<I, InboundRelayer = AccountIdOf<P::SourceChain>>,
|
||||
I: 'static,
|
||||
R::SourceHeaderChain: bp_messages::target_chain::SourceHeaderChain<
|
||||
MessagesProof = FromBridgedChainMessagesProof<HashOf<P::SourceChain>>,
|
||||
>,
|
||||
CallOf<P::TargetChain>: From<BridgeMessagesCall<R, I>> + GetDispatchInfo,
|
||||
{
|
||||
fn build_receive_messages_proof_call(
|
||||
relayer_id_at_source: AccountIdOf<P::SourceChain>,
|
||||
proof: SubstrateMessagesProof<P::SourceChain>,
|
||||
messages_count: u32,
|
||||
dispatch_weight: Weight,
|
||||
trace_call: bool,
|
||||
) -> CallOf<P::TargetChain> {
|
||||
let call: CallOf<P::TargetChain> = BridgeMessagesCall::<R, I>::receive_messages_proof {
|
||||
relayer_id_at_bridged_chain: relayer_id_at_source,
|
||||
proof: proof.1,
|
||||
messages_count,
|
||||
dispatch_weight,
|
||||
}
|
||||
.into();
|
||||
if trace_call {
|
||||
// this trace isn't super-accurate, because limits are for transactions and we
|
||||
// have a call here, but it provides required information
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"Prepared {} -> {} messages delivery call. Weight: {}/{}, size: {}/{}",
|
||||
P::SourceChain::NAME,
|
||||
P::TargetChain::NAME,
|
||||
call.get_dispatch_info().weight,
|
||||
P::TargetChain::max_extrinsic_weight(),
|
||||
call.encode().len(),
|
||||
P::TargetChain::max_extrinsic_size(),
|
||||
);
|
||||
}
|
||||
call
|
||||
}
|
||||
}
|
||||
|
||||
/// Macro that generates `ReceiveMessagesProofCallBuilder` implementation for the case when
|
||||
/// you only have an access to the mocked version of target chain runtime. In this case you
|
||||
/// should provide "name" of the call variant for the bridge messages calls and the "name" of
|
||||
/// the variant for the `receive_messages_proof` call within that first option.
|
||||
#[rustfmt::skip]
|
||||
#[macro_export]
|
||||
macro_rules! generate_mocked_receive_message_proof_call_builder {
|
||||
($pipeline:ident, $mocked_builder:ident, $bridge_messages:path, $receive_messages_proof:path) => {
|
||||
pub struct $mocked_builder;
|
||||
|
||||
impl $crate::messages_lane::ReceiveMessagesProofCallBuilder<$pipeline>
|
||||
for $mocked_builder
|
||||
{
|
||||
fn build_receive_messages_proof_call(
|
||||
relayer_id_at_source: relay_substrate_client::AccountIdOf<
|
||||
<$pipeline as $crate::messages_lane::SubstrateMessageLane>::SourceChain
|
||||
>,
|
||||
proof: $crate::messages_source::SubstrateMessagesProof<
|
||||
<$pipeline as $crate::messages_lane::SubstrateMessageLane>::SourceChain
|
||||
>,
|
||||
messages_count: u32,
|
||||
dispatch_weight: Weight,
|
||||
_trace_call: bool,
|
||||
) -> relay_substrate_client::CallOf<
|
||||
<$pipeline as $crate::messages_lane::SubstrateMessageLane>::TargetChain
|
||||
> {
|
||||
$bridge_messages($receive_messages_proof(
|
||||
relayer_id_at_source,
|
||||
proof.1,
|
||||
messages_count,
|
||||
dispatch_weight,
|
||||
))
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Different ways of building `receive_messages_delivery_proof` calls.
|
||||
pub trait ReceiveMessagesDeliveryProofCallBuilder<P: SubstrateMessageLane> {
|
||||
/// Given messages delivery proof, build call of `receive_messages_delivery_proof` function of
|
||||
/// bridge messages module at the source chain.
|
||||
fn build_receive_messages_delivery_proof_call(
|
||||
proof: SubstrateMessagesDeliveryProof<P::TargetChain>,
|
||||
trace_call: bool,
|
||||
) -> CallOf<P::SourceChain>;
|
||||
}
|
||||
|
||||
/// Building `receive_messages_delivery_proof` call when you have direct access to the source
|
||||
/// chain runtime.
|
||||
pub struct DirectReceiveMessagesDeliveryProofCallBuilder<P, R, I> {
|
||||
_phantom: PhantomData<(P, R, I)>,
|
||||
}
|
||||
|
||||
impl<P, R, I> ReceiveMessagesDeliveryProofCallBuilder<P>
|
||||
for DirectReceiveMessagesDeliveryProofCallBuilder<P, R, I>
|
||||
where
|
||||
P: SubstrateMessageLane,
|
||||
R: BridgeMessagesConfig<I>,
|
||||
I: 'static,
|
||||
R::TargetHeaderChain: bp_messages::source_chain::TargetHeaderChain<
|
||||
R::OutboundPayload,
|
||||
R::AccountId,
|
||||
MessagesDeliveryProof = FromBridgedChainMessagesDeliveryProof<HashOf<P::TargetChain>>,
|
||||
>,
|
||||
CallOf<P::SourceChain>: From<BridgeMessagesCall<R, I>> + GetDispatchInfo,
|
||||
{
|
||||
fn build_receive_messages_delivery_proof_call(
|
||||
proof: SubstrateMessagesDeliveryProof<P::TargetChain>,
|
||||
trace_call: bool,
|
||||
) -> CallOf<P::SourceChain> {
|
||||
let call: CallOf<P::SourceChain> =
|
||||
BridgeMessagesCall::<R, I>::receive_messages_delivery_proof {
|
||||
proof: proof.1,
|
||||
relayers_state: proof.0,
|
||||
}
|
||||
.into();
|
||||
if trace_call {
|
||||
// this trace isn't super-accurate, because limits are for transactions and we
|
||||
// have a call here, but it provides required information
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"Prepared {} -> {} delivery confirmation transaction. Weight: {}/{}, size: {}/{}",
|
||||
P::TargetChain::NAME,
|
||||
P::SourceChain::NAME,
|
||||
call.get_dispatch_info().weight,
|
||||
P::SourceChain::max_extrinsic_weight(),
|
||||
call.encode().len(),
|
||||
P::SourceChain::max_extrinsic_size(),
|
||||
);
|
||||
}
|
||||
call
|
||||
}
|
||||
}
|
||||
|
||||
/// Macro that generates `ReceiveMessagesDeliveryProofCallBuilder` implementation for the case when
|
||||
/// you only have an access to the mocked version of source chain runtime. In this case you
|
||||
/// should provide "name" of the call variant for the bridge messages calls and the "name" of
|
||||
/// the variant for the `receive_messages_delivery_proof` call within that first option.
|
||||
#[rustfmt::skip]
|
||||
#[macro_export]
|
||||
macro_rules! generate_mocked_receive_message_delivery_proof_call_builder {
|
||||
($pipeline:ident, $mocked_builder:ident, $bridge_messages:path, $receive_messages_delivery_proof:path) => {
|
||||
pub struct $mocked_builder;
|
||||
|
||||
impl $crate::messages_lane::ReceiveMessagesDeliveryProofCallBuilder<$pipeline>
|
||||
for $mocked_builder
|
||||
{
|
||||
fn build_receive_messages_delivery_proof_call(
|
||||
proof: $crate::messages_target::SubstrateMessagesDeliveryProof<
|
||||
<$pipeline as $crate::messages_lane::SubstrateMessageLane>::TargetChain
|
||||
>,
|
||||
_trace_call: bool,
|
||||
) -> relay_substrate_client::CallOf<
|
||||
<$pipeline as $crate::messages_lane::SubstrateMessageLane>::SourceChain
|
||||
> {
|
||||
$bridge_messages($receive_messages_delivery_proof(proof.1, proof.0))
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Returns maximal number of messages and their maximal cumulative dispatch weight, based
|
||||
/// on given chain parameters.
|
||||
pub fn select_delivery_transaction_limits<W: pallet_bridge_messages::WeightInfoExt>(
|
||||
max_extrinsic_weight: Weight,
|
||||
max_unconfirmed_messages_at_inbound_lane: MessageNonce,
|
||||
) -> (MessageNonce, Weight) {
|
||||
// We may try to guess accurate value, based on maximal number of messages and per-message
|
||||
// weight overhead, but the relay loop isn't using this info in a super-accurate way anyway.
|
||||
// So just a rough guess: let's say 1/3 of max tx weight is for tx itself and the rest is
|
||||
// for messages dispatch.
|
||||
|
||||
// Another thing to keep in mind is that our runtimes (when this code was written) accept
|
||||
// messages with dispatch weight <= max_extrinsic_weight/2. So we can't reserve less than
|
||||
// that for dispatch.
|
||||
|
||||
let weight_for_delivery_tx = max_extrinsic_weight / 3;
|
||||
let weight_for_messages_dispatch = max_extrinsic_weight - weight_for_delivery_tx;
|
||||
|
||||
let delivery_tx_base_weight = W::receive_messages_proof_overhead() +
|
||||
W::receive_messages_proof_outbound_lane_state_overhead();
|
||||
let delivery_tx_weight_rest = weight_for_delivery_tx - delivery_tx_base_weight;
|
||||
|
||||
let max_number_of_messages = std::cmp::min(
|
||||
delivery_tx_weight_rest
|
||||
.min_components_checked_div(W::receive_messages_proof_messages_overhead(1))
|
||||
.unwrap_or(u64::MAX),
|
||||
max_unconfirmed_messages_at_inbound_lane,
|
||||
);
|
||||
|
||||
assert!(
|
||||
max_number_of_messages > 0,
|
||||
"Relay should fit at least one message in every delivery transaction",
|
||||
);
|
||||
assert!(
|
||||
weight_for_messages_dispatch.ref_time() >= max_extrinsic_weight.ref_time() / 2,
|
||||
"Relay shall be able to deliver messages with dispatch weight = max_extrinsic_weight / 2",
|
||||
);
|
||||
|
||||
(max_number_of_messages, weight_for_messages_dispatch)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use bp_runtime::Chain;
|
||||
|
||||
type RialtoToMillauMessagesWeights =
|
||||
pallet_bridge_messages::weights::BridgeWeight<rialto_runtime::Runtime>;
|
||||
|
||||
#[test]
|
||||
fn select_delivery_transaction_limits_works() {
|
||||
let (max_count, max_weight) =
|
||||
select_delivery_transaction_limits::<RialtoToMillauMessagesWeights>(
|
||||
bp_millau::Millau::max_extrinsic_weight(),
|
||||
bp_rialto::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX,
|
||||
);
|
||||
assert_eq!(
|
||||
(max_count, max_weight),
|
||||
// We don't actually care about these values, so feel free to update them whenever test
|
||||
// fails. The only thing to do before that is to ensure that new values looks sane:
|
||||
// i.e. weight reserved for messages dispatch allows dispatch of non-trivial messages.
|
||||
//
|
||||
// Any significant change in this values should attract additional attention.
|
||||
//
|
||||
// TODO: https://github.com/paritytech/parity-bridges-common/issues/1543 - remove `set_proof_size`
|
||||
(1024, Weight::from_ref_time(216_609_134_667).set_proof_size(217)),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
// 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/>.
|
||||
|
||||
//! Tools for supporting message lanes between two Substrate-based chains.
|
||||
|
||||
use crate::TaggedAccount;
|
||||
|
||||
use codec::Decode;
|
||||
use frame_system::AccountInfo;
|
||||
use pallet_balances::AccountData;
|
||||
use relay_substrate_client::{
|
||||
metrics::{FloatStorageValue, FloatStorageValueMetric},
|
||||
AccountIdOf, BalanceOf, Chain, ChainWithBalances, Client, Error as SubstrateError, IndexOf,
|
||||
};
|
||||
use relay_utils::metrics::{MetricsParams, StandaloneMetric};
|
||||
use sp_core::storage::StorageData;
|
||||
use sp_runtime::{FixedPointNumber, FixedU128};
|
||||
use std::{convert::TryFrom, fmt::Debug, marker::PhantomData};
|
||||
|
||||
/// Add relay accounts balance metrics.
|
||||
pub async fn add_relay_balances_metrics<C: ChainWithBalances>(
|
||||
client: Client<C>,
|
||||
metrics: &mut MetricsParams,
|
||||
relay_accounts: &Vec<TaggedAccount<AccountIdOf<C>>>,
|
||||
) -> anyhow::Result<()>
|
||||
where
|
||||
BalanceOf<C>: Into<u128> + std::fmt::Debug,
|
||||
{
|
||||
if relay_accounts.is_empty() {
|
||||
return Ok(())
|
||||
}
|
||||
|
||||
// if `tokenDecimals` is missing from system properties, we'll be using
|
||||
let token_decimals = client
|
||||
.token_decimals()
|
||||
.await?
|
||||
.map(|token_decimals| {
|
||||
log::info!(target: "bridge", "Read `tokenDecimals` for {}: {}", C::NAME, token_decimals);
|
||||
token_decimals
|
||||
})
|
||||
.unwrap_or_else(|| {
|
||||
// turns out it is normal not to have this property - e.g. when polkadot binary is
|
||||
// started using `polkadot-local` chain. Let's use minimal nominal here
|
||||
log::info!(target: "bridge", "Using default (zero) `tokenDecimals` value for {}", C::NAME);
|
||||
0
|
||||
});
|
||||
let token_decimals = u32::try_from(token_decimals).map_err(|e| {
|
||||
anyhow::format_err!(
|
||||
"Token decimals value ({}) of {} doesn't fit into u32: {:?}",
|
||||
token_decimals,
|
||||
C::NAME,
|
||||
e,
|
||||
)
|
||||
})?;
|
||||
|
||||
for account in relay_accounts {
|
||||
let relay_account_balance_metric = FloatStorageValueMetric::new(
|
||||
FreeAccountBalance::<C> { token_decimals, _phantom: Default::default() },
|
||||
client.clone(),
|
||||
C::account_info_storage_key(account.id()),
|
||||
format!("at_{}_relay_{}_balance", C::NAME, account.tag()),
|
||||
format!("Balance of the {} relay account at the {}", account.tag(), C::NAME),
|
||||
)?;
|
||||
relay_account_balance_metric.register_and_spawn(&metrics.registry)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adapter for `FloatStorageValueMetric` to decode account free balance.
|
||||
#[derive(Clone, Debug)]
|
||||
struct FreeAccountBalance<C> {
|
||||
token_decimals: u32,
|
||||
_phantom: PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<C> FloatStorageValue for FreeAccountBalance<C>
|
||||
where
|
||||
C: Chain,
|
||||
BalanceOf<C>: Into<u128>,
|
||||
{
|
||||
type Value = FixedU128;
|
||||
|
||||
fn decode(
|
||||
&self,
|
||||
maybe_raw_value: Option<StorageData>,
|
||||
) -> Result<Option<Self::Value>, SubstrateError> {
|
||||
maybe_raw_value
|
||||
.map(|raw_value| {
|
||||
AccountInfo::<IndexOf<C>, AccountData<BalanceOf<C>>>::decode(&mut &raw_value.0[..])
|
||||
.map_err(SubstrateError::ResponseParseFailed)
|
||||
.map(|account_data| {
|
||||
convert_to_token_balance(account_data.data.free.into(), self.token_decimals)
|
||||
})
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert from raw `u128` balance (nominated in smallest chain token units) to the float regular
|
||||
/// tokens value.
|
||||
fn convert_to_token_balance(balance: u128, token_decimals: u32) -> FixedU128 {
|
||||
FixedU128::from_inner(balance.saturating_mul(FixedU128::DIV / 10u128.pow(token_decimals)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn token_decimals_used_properly() {
|
||||
let plancks = 425_000_000_000;
|
||||
let token_decimals = 10;
|
||||
let dots = convert_to_token_balance(plancks, token_decimals);
|
||||
assert_eq!(dots, FixedU128::saturating_from_rational(425, 10));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,736 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Substrate client as Substrate messages source. The chain we connect to should have
|
||||
//! runtime that implements `<BridgedChainName>HeaderApi` to allow bridging with
|
||||
//! <BridgedName> chain.
|
||||
|
||||
use crate::{
|
||||
messages_lane::{
|
||||
MessageLaneAdapter, ReceiveMessagesDeliveryProofCallBuilder, SubstrateMessageLane,
|
||||
},
|
||||
messages_target::SubstrateMessagesDeliveryProof,
|
||||
on_demand::OnDemandRelay,
|
||||
TransactionParams,
|
||||
};
|
||||
|
||||
use async_std::sync::Arc;
|
||||
use async_trait::async_trait;
|
||||
use bp_messages::{
|
||||
storage_keys::{operating_mode_key, outbound_lane_data_key},
|
||||
InboundMessageDetails, LaneId, MessageNonce, MessagePayload, MessagesOperatingMode,
|
||||
OutboundLaneData, OutboundMessageDetails,
|
||||
};
|
||||
use bp_runtime::{BasicOperatingMode, HeaderIdProvider};
|
||||
use bridge_runtime_common::messages::target::FromBridgedChainMessagesProof;
|
||||
use codec::{Decode, Encode};
|
||||
use frame_support::weights::Weight;
|
||||
use messages_relay::{
|
||||
message_lane::{MessageLane, SourceHeaderIdOf, TargetHeaderIdOf},
|
||||
message_lane_loop::{
|
||||
ClientState, MessageDetails, MessageDetailsMap, MessageProofParameters, SourceClient,
|
||||
SourceClientState,
|
||||
},
|
||||
};
|
||||
use num_traits::Zero;
|
||||
use relay_substrate_client::{
|
||||
AccountIdOf, AccountKeyPairOf, BalanceOf, BlockNumberOf, Chain, ChainWithMessages, Client,
|
||||
Error as SubstrateError, HashOf, HeaderIdOf, IndexOf, SignParam, TransactionEra,
|
||||
TransactionTracker, UnsignedTransaction,
|
||||
};
|
||||
use relay_utils::{relay_loop::Client as RelayClient, HeaderId};
|
||||
use sp_core::{Bytes, Pair};
|
||||
use sp_runtime::{traits::Header as HeaderT, DeserializeOwned};
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
/// Intermediate message proof returned by the source Substrate node. Includes everything
|
||||
/// required to submit to the target node: cumulative dispatch weight of bundled messages and
|
||||
/// the proof itself.
|
||||
pub type SubstrateMessagesProof<C> = (Weight, FromBridgedChainMessagesProof<HashOf<C>>);
|
||||
type MessagesToRefine<'a> = Vec<(MessagePayload, &'a mut OutboundMessageDetails)>;
|
||||
|
||||
/// Substrate client as Substrate messages source.
|
||||
pub struct SubstrateMessagesSource<P: SubstrateMessageLane> {
|
||||
source_client: Client<P::SourceChain>,
|
||||
target_client: Client<P::TargetChain>,
|
||||
lane_id: LaneId,
|
||||
transaction_params: TransactionParams<AccountKeyPairOf<P::SourceChain>>,
|
||||
target_to_source_headers_relay: Option<Arc<dyn OnDemandRelay<BlockNumberOf<P::TargetChain>>>>,
|
||||
}
|
||||
|
||||
impl<P: SubstrateMessageLane> SubstrateMessagesSource<P> {
|
||||
/// Create new Substrate headers source.
|
||||
pub fn new(
|
||||
source_client: Client<P::SourceChain>,
|
||||
target_client: Client<P::TargetChain>,
|
||||
lane_id: LaneId,
|
||||
transaction_params: TransactionParams<AccountKeyPairOf<P::SourceChain>>,
|
||||
target_to_source_headers_relay: Option<
|
||||
Arc<dyn OnDemandRelay<BlockNumberOf<P::TargetChain>>>,
|
||||
>,
|
||||
) -> Self {
|
||||
SubstrateMessagesSource {
|
||||
source_client,
|
||||
target_client,
|
||||
lane_id,
|
||||
transaction_params,
|
||||
target_to_source_headers_relay,
|
||||
}
|
||||
}
|
||||
|
||||
/// Read outbound lane state from the on-chain storage at given block.
|
||||
async fn outbound_lane_data(
|
||||
&self,
|
||||
id: SourceHeaderIdOf<MessageLaneAdapter<P>>,
|
||||
) -> Result<Option<OutboundLaneData>, SubstrateError> {
|
||||
self.source_client
|
||||
.storage_value(
|
||||
outbound_lane_data_key(
|
||||
P::TargetChain::WITH_CHAIN_MESSAGES_PALLET_NAME,
|
||||
&self.lane_id,
|
||||
),
|
||||
Some(id.1),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Ensure that the messages pallet at source chain is active.
|
||||
async fn ensure_pallet_active(&self) -> Result<(), SubstrateError> {
|
||||
ensure_messages_pallet_active::<P::SourceChain, P::TargetChain>(&self.source_client).await
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: SubstrateMessageLane> Clone for SubstrateMessagesSource<P> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
source_client: self.source_client.clone(),
|
||||
target_client: self.target_client.clone(),
|
||||
lane_id: self.lane_id,
|
||||
transaction_params: self.transaction_params.clone(),
|
||||
target_to_source_headers_relay: self.target_to_source_headers_relay.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<P: SubstrateMessageLane> RelayClient for SubstrateMessagesSource<P> {
|
||||
type Error = SubstrateError;
|
||||
|
||||
async fn reconnect(&mut self) -> Result<(), SubstrateError> {
|
||||
self.source_client.reconnect().await?;
|
||||
self.target_client.reconnect().await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<P: SubstrateMessageLane> SourceClient<MessageLaneAdapter<P>> for SubstrateMessagesSource<P>
|
||||
where
|
||||
AccountIdOf<P::SourceChain>: From<<AccountKeyPairOf<P::SourceChain> as Pair>::Public>,
|
||||
{
|
||||
type TransactionTracker = TransactionTracker<P::SourceChain, Client<P::SourceChain>>;
|
||||
|
||||
async fn state(&self) -> Result<SourceClientState<MessageLaneAdapter<P>>, SubstrateError> {
|
||||
// we can't continue to deliver confirmations if source node is out of sync, because
|
||||
// it may have already received confirmations that we're going to deliver
|
||||
//
|
||||
// we can't continue to deliver messages if target node is out of sync, because
|
||||
// it may have already received (some of) messages that we're going to deliver
|
||||
self.source_client.ensure_synced().await?;
|
||||
self.target_client.ensure_synced().await?;
|
||||
// we can't relay confirmations if messages pallet at source chain is halted
|
||||
self.ensure_pallet_active().await?;
|
||||
|
||||
read_client_state(
|
||||
&self.source_client,
|
||||
Some(&self.target_client),
|
||||
P::TargetChain::BEST_FINALIZED_HEADER_ID_METHOD,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn latest_generated_nonce(
|
||||
&self,
|
||||
id: SourceHeaderIdOf<MessageLaneAdapter<P>>,
|
||||
) -> Result<(SourceHeaderIdOf<MessageLaneAdapter<P>>, MessageNonce), SubstrateError> {
|
||||
// lane data missing from the storage is fine until first message is sent
|
||||
let latest_generated_nonce = self
|
||||
.outbound_lane_data(id)
|
||||
.await?
|
||||
.map(|data| data.latest_generated_nonce)
|
||||
.unwrap_or(0);
|
||||
Ok((id, latest_generated_nonce))
|
||||
}
|
||||
|
||||
async fn latest_confirmed_received_nonce(
|
||||
&self,
|
||||
id: SourceHeaderIdOf<MessageLaneAdapter<P>>,
|
||||
) -> Result<(SourceHeaderIdOf<MessageLaneAdapter<P>>, MessageNonce), SubstrateError> {
|
||||
// lane data missing from the storage is fine until first message is sent
|
||||
let latest_received_nonce = self
|
||||
.outbound_lane_data(id)
|
||||
.await?
|
||||
.map(|data| data.latest_received_nonce)
|
||||
.unwrap_or(0);
|
||||
Ok((id, latest_received_nonce))
|
||||
}
|
||||
|
||||
async fn generated_message_details(
|
||||
&self,
|
||||
id: SourceHeaderIdOf<MessageLaneAdapter<P>>,
|
||||
nonces: RangeInclusive<MessageNonce>,
|
||||
) -> Result<MessageDetailsMap<BalanceOf<P::SourceChain>>, SubstrateError> {
|
||||
let mut out_msgs_details = self
|
||||
.source_client
|
||||
.typed_state_call::<_, Vec<_>>(
|
||||
P::TargetChain::TO_CHAIN_MESSAGE_DETAILS_METHOD.into(),
|
||||
(self.lane_id, *nonces.start(), *nonces.end()),
|
||||
Some(id.1),
|
||||
)
|
||||
.await?;
|
||||
validate_out_msgs_details::<P::SourceChain>(&out_msgs_details, nonces)?;
|
||||
|
||||
// prepare arguments of the inbound message details call (if we need it)
|
||||
let mut msgs_to_refine = vec![];
|
||||
for out_msg_details in out_msgs_details.iter_mut() {
|
||||
// in our current strategy all messages are supposed to be paid at the target chain
|
||||
|
||||
// for pay-at-target messages we may want to ask target chain for
|
||||
// refined dispatch weight
|
||||
let msg_key = bp_messages::storage_keys::message_key(
|
||||
P::TargetChain::WITH_CHAIN_MESSAGES_PALLET_NAME,
|
||||
&self.lane_id,
|
||||
out_msg_details.nonce,
|
||||
);
|
||||
let msg_payload: MessagePayload =
|
||||
self.source_client.storage_value(msg_key, Some(id.1)).await?.ok_or_else(|| {
|
||||
SubstrateError::Custom(format!(
|
||||
"Message to {} {:?}/{} is missing from runtime the storage of {} at {:?}",
|
||||
P::TargetChain::NAME,
|
||||
self.lane_id,
|
||||
out_msg_details.nonce,
|
||||
P::SourceChain::NAME,
|
||||
id,
|
||||
))
|
||||
})?;
|
||||
|
||||
msgs_to_refine.push((msg_payload, out_msg_details));
|
||||
}
|
||||
|
||||
for mut msgs_to_refine_batch in
|
||||
split_msgs_to_refine::<P::SourceChain, P::TargetChain>(self.lane_id, msgs_to_refine)?
|
||||
{
|
||||
let in_msgs_details = self
|
||||
.target_client
|
||||
.typed_state_call::<_, Vec<InboundMessageDetails>>(
|
||||
P::SourceChain::FROM_CHAIN_MESSAGE_DETAILS_METHOD.into(),
|
||||
(self.lane_id, &msgs_to_refine_batch),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
if in_msgs_details.len() != msgs_to_refine_batch.len() {
|
||||
return Err(SubstrateError::Custom(format!(
|
||||
"Call of {} at {} has returned {} entries instead of expected {}",
|
||||
P::SourceChain::FROM_CHAIN_MESSAGE_DETAILS_METHOD,
|
||||
P::TargetChain::NAME,
|
||||
in_msgs_details.len(),
|
||||
msgs_to_refine_batch.len(),
|
||||
)))
|
||||
}
|
||||
for ((_, out_msg_details), in_msg_details) in
|
||||
msgs_to_refine_batch.iter_mut().zip(in_msgs_details)
|
||||
{
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"Refined weight of {}->{} message {:?}/{}: at-source: {}, at-target: {}",
|
||||
P::SourceChain::NAME,
|
||||
P::TargetChain::NAME,
|
||||
self.lane_id,
|
||||
out_msg_details.nonce,
|
||||
out_msg_details.dispatch_weight,
|
||||
in_msg_details.dispatch_weight,
|
||||
);
|
||||
out_msg_details.dispatch_weight = in_msg_details.dispatch_weight;
|
||||
}
|
||||
}
|
||||
|
||||
let mut msgs_details_map = MessageDetailsMap::new();
|
||||
for out_msg_details in out_msgs_details {
|
||||
msgs_details_map.insert(
|
||||
out_msg_details.nonce,
|
||||
MessageDetails {
|
||||
dispatch_weight: out_msg_details.dispatch_weight,
|
||||
size: out_msg_details.size as _,
|
||||
reward: Zero::zero(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Ok(msgs_details_map)
|
||||
}
|
||||
|
||||
async fn prove_messages(
|
||||
&self,
|
||||
id: SourceHeaderIdOf<MessageLaneAdapter<P>>,
|
||||
nonces: RangeInclusive<MessageNonce>,
|
||||
proof_parameters: MessageProofParameters,
|
||||
) -> Result<
|
||||
(
|
||||
SourceHeaderIdOf<MessageLaneAdapter<P>>,
|
||||
RangeInclusive<MessageNonce>,
|
||||
<MessageLaneAdapter<P> as MessageLane>::MessagesProof,
|
||||
),
|
||||
SubstrateError,
|
||||
> {
|
||||
let mut storage_keys =
|
||||
Vec::with_capacity(nonces.end().saturating_sub(*nonces.start()) as usize + 1);
|
||||
let mut message_nonce = *nonces.start();
|
||||
while message_nonce <= *nonces.end() {
|
||||
let message_key = bp_messages::storage_keys::message_key(
|
||||
P::TargetChain::WITH_CHAIN_MESSAGES_PALLET_NAME,
|
||||
&self.lane_id,
|
||||
message_nonce,
|
||||
);
|
||||
storage_keys.push(message_key);
|
||||
message_nonce += 1;
|
||||
}
|
||||
if proof_parameters.outbound_state_proof_required {
|
||||
storage_keys.push(bp_messages::storage_keys::outbound_lane_data_key(
|
||||
P::TargetChain::WITH_CHAIN_MESSAGES_PALLET_NAME,
|
||||
&self.lane_id,
|
||||
));
|
||||
}
|
||||
|
||||
let proof = self
|
||||
.source_client
|
||||
.prove_storage(storage_keys, id.1)
|
||||
.await?
|
||||
.into_iter_nodes()
|
||||
.collect();
|
||||
let proof = FromBridgedChainMessagesProof {
|
||||
bridged_header_hash: id.1,
|
||||
storage_proof: proof,
|
||||
lane: self.lane_id,
|
||||
nonces_start: *nonces.start(),
|
||||
nonces_end: *nonces.end(),
|
||||
};
|
||||
Ok((id, nonces, (proof_parameters.dispatch_weight, proof)))
|
||||
}
|
||||
|
||||
async fn submit_messages_receiving_proof(
|
||||
&self,
|
||||
_generated_at_block: TargetHeaderIdOf<MessageLaneAdapter<P>>,
|
||||
proof: <MessageLaneAdapter<P> as MessageLane>::MessagesReceivingProof,
|
||||
) -> Result<Self::TransactionTracker, SubstrateError> {
|
||||
let genesis_hash = *self.source_client.genesis_hash();
|
||||
let transaction_params = self.transaction_params.clone();
|
||||
let (spec_version, transaction_version) =
|
||||
self.source_client.simple_runtime_version().await?;
|
||||
self.source_client
|
||||
.submit_and_watch_signed_extrinsic(
|
||||
self.transaction_params.signer.public().into(),
|
||||
SignParam::<P::SourceChain> {
|
||||
spec_version,
|
||||
transaction_version,
|
||||
genesis_hash,
|
||||
signer: self.transaction_params.signer.clone(),
|
||||
},
|
||||
move |best_block_id, transaction_nonce| {
|
||||
make_messages_delivery_proof_transaction::<P>(
|
||||
&transaction_params,
|
||||
best_block_id,
|
||||
transaction_nonce,
|
||||
proof,
|
||||
true,
|
||||
)
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn require_target_header_on_source(&self, id: TargetHeaderIdOf<MessageLaneAdapter<P>>) {
|
||||
if let Some(ref target_to_source_headers_relay) = self.target_to_source_headers_relay {
|
||||
target_to_source_headers_relay.require_more_headers(id.0).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ensure that the messages pallet at source chain is active.
|
||||
pub(crate) async fn ensure_messages_pallet_active<AtChain, WithChain>(
|
||||
client: &Client<AtChain>,
|
||||
) -> Result<(), SubstrateError>
|
||||
where
|
||||
AtChain: ChainWithMessages,
|
||||
WithChain: ChainWithMessages,
|
||||
{
|
||||
let operating_mode = client
|
||||
.storage_value(operating_mode_key(WithChain::WITH_CHAIN_MESSAGES_PALLET_NAME), None)
|
||||
.await?;
|
||||
let is_halted =
|
||||
operating_mode == Some(MessagesOperatingMode::Basic(BasicOperatingMode::Halted));
|
||||
if is_halted {
|
||||
Err(SubstrateError::BridgePalletIsHalted)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Make messages delivery proof transaction from given proof.
|
||||
fn make_messages_delivery_proof_transaction<P: SubstrateMessageLane>(
|
||||
source_transaction_params: &TransactionParams<AccountKeyPairOf<P::SourceChain>>,
|
||||
source_best_block_id: HeaderIdOf<P::SourceChain>,
|
||||
transaction_nonce: IndexOf<P::SourceChain>,
|
||||
proof: SubstrateMessagesDeliveryProof<P::TargetChain>,
|
||||
trace_call: bool,
|
||||
) -> Result<UnsignedTransaction<P::SourceChain>, SubstrateError> {
|
||||
let call =
|
||||
P::ReceiveMessagesDeliveryProofCallBuilder::build_receive_messages_delivery_proof_call(
|
||||
proof, trace_call,
|
||||
);
|
||||
Ok(UnsignedTransaction::new(call.into(), transaction_nonce)
|
||||
.era(TransactionEra::new(source_best_block_id, source_transaction_params.mortality)))
|
||||
}
|
||||
|
||||
/// Read best blocks from given client.
|
||||
///
|
||||
/// This function assumes that the chain that is followed by the `self_client` has
|
||||
/// bridge GRANDPA pallet deployed and it provides `best_finalized_header_id_method_name`
|
||||
/// runtime API to read the best finalized Bridged chain header.
|
||||
///
|
||||
/// If `peer_client` is `None`, the value of `actual_best_finalized_peer_at_best_self` will
|
||||
/// always match the `best_finalized_peer_at_best_self`.
|
||||
pub async fn read_client_state<SelfChain, PeerChain>(
|
||||
self_client: &Client<SelfChain>,
|
||||
peer_client: Option<&Client<PeerChain>>,
|
||||
best_finalized_header_id_method_name: &str,
|
||||
) -> Result<ClientState<HeaderIdOf<SelfChain>, HeaderIdOf<PeerChain>>, SubstrateError>
|
||||
where
|
||||
SelfChain: Chain,
|
||||
SelfChain::Header: DeserializeOwned,
|
||||
SelfChain::Index: DeserializeOwned,
|
||||
PeerChain: Chain,
|
||||
{
|
||||
// let's read our state first: we need best finalized header hash on **this** chain
|
||||
let self_best_finalized_header_hash = self_client.best_finalized_header_hash().await?;
|
||||
let self_best_finalized_header =
|
||||
self_client.header_by_hash(self_best_finalized_header_hash).await?;
|
||||
let self_best_finalized_id = self_best_finalized_header.id();
|
||||
|
||||
// now let's read our best header on **this** chain
|
||||
let self_best_header = self_client.best_header().await?;
|
||||
let self_best_hash = self_best_header.hash();
|
||||
let self_best_id = self_best_header.id();
|
||||
|
||||
// now let's read id of best finalized peer header at our best finalized block
|
||||
let peer_on_self_best_finalized_id =
|
||||
best_finalized_peer_header_at_self::<SelfChain, PeerChain>(
|
||||
self_client,
|
||||
self_best_hash,
|
||||
best_finalized_header_id_method_name,
|
||||
)
|
||||
.await?;
|
||||
|
||||
// read actual header, matching the `peer_on_self_best_finalized_id` from the peer chain
|
||||
let actual_peer_on_self_best_finalized_id = match peer_client {
|
||||
Some(peer_client) => {
|
||||
let actual_peer_on_self_best_finalized =
|
||||
peer_client.header_by_number(peer_on_self_best_finalized_id.0).await?;
|
||||
actual_peer_on_self_best_finalized.id()
|
||||
},
|
||||
None => peer_on_self_best_finalized_id,
|
||||
};
|
||||
|
||||
Ok(ClientState {
|
||||
best_self: self_best_id,
|
||||
best_finalized_self: self_best_finalized_id,
|
||||
best_finalized_peer_at_best_self: peer_on_self_best_finalized_id,
|
||||
actual_best_finalized_peer_at_best_self: actual_peer_on_self_best_finalized_id,
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads best `PeerChain` header known to the `SelfChain` using provided runtime API method.
|
||||
///
|
||||
/// Method is supposed to be the `<PeerChain>FinalityApi::best_finalized()` method.
|
||||
pub async fn best_finalized_peer_header_at_self<SelfChain, PeerChain>(
|
||||
self_client: &Client<SelfChain>,
|
||||
at_self_hash: HashOf<SelfChain>,
|
||||
best_finalized_header_id_method_name: &str,
|
||||
) -> Result<HeaderIdOf<PeerChain>, SubstrateError>
|
||||
where
|
||||
SelfChain: Chain,
|
||||
PeerChain: Chain,
|
||||
{
|
||||
// now let's read id of best finalized peer header at our best finalized block
|
||||
let encoded_best_finalized_peer_on_self = self_client
|
||||
.state_call(
|
||||
best_finalized_header_id_method_name.into(),
|
||||
Bytes(Vec::new()),
|
||||
Some(at_self_hash),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Option::<HeaderId<HashOf<PeerChain>, BlockNumberOf<PeerChain>>>::decode(
|
||||
&mut &encoded_best_finalized_peer_on_self.0[..],
|
||||
)
|
||||
.map_err(SubstrateError::ResponseParseFailed)?
|
||||
.map(Ok)
|
||||
.unwrap_or(Err(SubstrateError::BridgePalletIsNotInitialized))
|
||||
}
|
||||
|
||||
fn validate_out_msgs_details<C: Chain>(
|
||||
out_msgs_details: &[OutboundMessageDetails],
|
||||
nonces: RangeInclusive<MessageNonce>,
|
||||
) -> Result<(), SubstrateError> {
|
||||
let make_missing_nonce_error = |expected_nonce| {
|
||||
Err(SubstrateError::Custom(format!(
|
||||
"Missing nonce {} in message_details call result. Expected all nonces from {:?}",
|
||||
expected_nonce, nonces,
|
||||
)))
|
||||
};
|
||||
|
||||
if out_msgs_details.len() > nonces.clone().count() {
|
||||
return Err(SubstrateError::Custom(
|
||||
"More messages than requested returned by the message_details call.".into(),
|
||||
))
|
||||
}
|
||||
|
||||
// Check if last nonce is missing. The loop below is not checking this.
|
||||
if out_msgs_details.is_empty() && !nonces.is_empty() {
|
||||
return make_missing_nonce_error(*nonces.end())
|
||||
}
|
||||
|
||||
let mut nonces_iter = nonces.clone().rev().peekable();
|
||||
let mut out_msgs_details_iter = out_msgs_details.iter().rev();
|
||||
while let Some((out_msg_details, &nonce)) = out_msgs_details_iter.next().zip(nonces_iter.peek())
|
||||
{
|
||||
nonces_iter.next();
|
||||
if out_msg_details.nonce != nonce {
|
||||
// Some nonces are missing from the middle/tail of the range. This is critical error.
|
||||
return make_missing_nonce_error(nonce)
|
||||
}
|
||||
}
|
||||
|
||||
// Check if some nonces from the beginning of the range are missing. This may happen if
|
||||
// some messages were already pruned from the source node. This is not a critical error
|
||||
// and will be auto-resolved by messages lane (and target node).
|
||||
if nonces_iter.peek().is_some() {
|
||||
log::info!(
|
||||
target: "bridge",
|
||||
"Some messages are missing from the {} node: {:?}. Target node may be out of sync?",
|
||||
C::NAME,
|
||||
nonces_iter.rev().collect::<Vec<_>>(),
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn split_msgs_to_refine<Source: Chain + ChainWithMessages, Target: Chain>(
|
||||
lane_id: LaneId,
|
||||
msgs_to_refine: MessagesToRefine,
|
||||
) -> Result<Vec<MessagesToRefine>, SubstrateError> {
|
||||
let max_batch_size = Target::max_extrinsic_size() as usize;
|
||||
let mut batches = vec![];
|
||||
|
||||
let mut current_msgs_batch = msgs_to_refine;
|
||||
while !current_msgs_batch.is_empty() {
|
||||
let mut next_msgs_batch = vec![];
|
||||
while (lane_id, ¤t_msgs_batch).encoded_size() > max_batch_size {
|
||||
if current_msgs_batch.len() <= 1 {
|
||||
return Err(SubstrateError::Custom(format!(
|
||||
"Call of {} at {} can't be executed even if only one message is supplied. \
|
||||
max_extrinsic_size(): {}",
|
||||
Source::FROM_CHAIN_MESSAGE_DETAILS_METHOD,
|
||||
Target::NAME,
|
||||
Target::max_extrinsic_size(),
|
||||
)))
|
||||
}
|
||||
|
||||
if let Some(msg) = current_msgs_batch.pop() {
|
||||
next_msgs_batch.insert(0, msg);
|
||||
}
|
||||
}
|
||||
|
||||
batches.push(current_msgs_batch);
|
||||
current_msgs_batch = next_msgs_batch;
|
||||
}
|
||||
|
||||
Ok(batches)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use bp_runtime::Chain as ChainBase;
|
||||
use relay_rialto_client::Rialto;
|
||||
use relay_rococo_client::Rococo;
|
||||
use relay_wococo_client::Wococo;
|
||||
|
||||
fn message_details_from_rpc(
|
||||
nonces: RangeInclusive<MessageNonce>,
|
||||
) -> Vec<OutboundMessageDetails> {
|
||||
nonces
|
||||
.into_iter()
|
||||
.map(|nonce| bp_messages::OutboundMessageDetails {
|
||||
nonce,
|
||||
dispatch_weight: Weight::zero(),
|
||||
size: 0,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_out_msgs_details_succeeds_if_no_messages_are_missing() {
|
||||
assert!(
|
||||
validate_out_msgs_details::<Wococo>(&message_details_from_rpc(1..=3), 1..=3,).is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_out_msgs_details_succeeds_if_head_messages_are_missing() {
|
||||
assert!(
|
||||
validate_out_msgs_details::<Wococo>(&message_details_from_rpc(2..=3), 1..=3,).is_ok()
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_out_msgs_details_fails_if_mid_messages_are_missing() {
|
||||
let mut message_details_from_rpc = message_details_from_rpc(1..=3);
|
||||
message_details_from_rpc.remove(1);
|
||||
assert!(matches!(
|
||||
validate_out_msgs_details::<Wococo>(&message_details_from_rpc, 1..=3,),
|
||||
Err(SubstrateError::Custom(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_out_msgs_details_map_fails_if_tail_messages_are_missing() {
|
||||
assert!(matches!(
|
||||
validate_out_msgs_details::<Wococo>(&message_details_from_rpc(1..=2), 1..=3,),
|
||||
Err(SubstrateError::Custom(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_out_msgs_details_fails_if_all_messages_are_missing() {
|
||||
assert!(matches!(
|
||||
validate_out_msgs_details::<Wococo>(&[], 1..=3),
|
||||
Err(SubstrateError::Custom(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_out_msgs_details_fails_if_more_messages_than_nonces() {
|
||||
assert!(matches!(
|
||||
validate_out_msgs_details::<Wococo>(&message_details_from_rpc(1..=5), 2..=5,),
|
||||
Err(SubstrateError::Custom(_))
|
||||
));
|
||||
}
|
||||
|
||||
fn check_split_msgs_to_refine(
|
||||
payload_sizes: Vec<usize>,
|
||||
expected_batches: Result<Vec<usize>, ()>,
|
||||
) {
|
||||
let mut out_msgs_details = vec![];
|
||||
for (idx, _) in payload_sizes.iter().enumerate() {
|
||||
out_msgs_details.push(OutboundMessageDetails {
|
||||
nonce: idx as MessageNonce,
|
||||
dispatch_weight: Weight::zero(),
|
||||
size: 0,
|
||||
});
|
||||
}
|
||||
|
||||
let mut msgs_to_refine = vec![];
|
||||
for (&payload_size, out_msg_details) in
|
||||
payload_sizes.iter().zip(out_msgs_details.iter_mut())
|
||||
{
|
||||
let payload = vec![1u8; payload_size];
|
||||
msgs_to_refine.push((payload, out_msg_details));
|
||||
}
|
||||
|
||||
let maybe_batches = split_msgs_to_refine::<Rialto, Rococo>([0, 0, 0, 0], msgs_to_refine);
|
||||
match expected_batches {
|
||||
Ok(expected_batches) => {
|
||||
let batches = maybe_batches.unwrap();
|
||||
let mut idx = 0;
|
||||
assert_eq!(batches.len(), expected_batches.len());
|
||||
for (batch, &expected_batch_size) in batches.iter().zip(expected_batches.iter()) {
|
||||
assert_eq!(batch.len(), expected_batch_size);
|
||||
for msg_to_refine in batch {
|
||||
assert_eq!(msg_to_refine.0.len(), payload_sizes[idx]);
|
||||
idx += 1;
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(_) => {
|
||||
matches!(maybe_batches, Err(SubstrateError::Custom(_)));
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_split_msgs_to_refine() {
|
||||
let max_extrinsic_size = Rococo::max_extrinsic_size() as usize;
|
||||
|
||||
// Check that an error is returned when one of the messages is too big.
|
||||
check_split_msgs_to_refine(vec![max_extrinsic_size], Err(()));
|
||||
check_split_msgs_to_refine(vec![50, 100, max_extrinsic_size, 200], Err(()));
|
||||
|
||||
// Otherwise check that the split is valid.
|
||||
check_split_msgs_to_refine(vec![100, 200, 300, 400], Ok(vec![4]));
|
||||
check_split_msgs_to_refine(
|
||||
vec![
|
||||
50,
|
||||
100,
|
||||
max_extrinsic_size - 500,
|
||||
500,
|
||||
1000,
|
||||
1500,
|
||||
max_extrinsic_size - 3500,
|
||||
5000,
|
||||
10000,
|
||||
],
|
||||
Ok(vec![3, 4, 2]),
|
||||
);
|
||||
check_split_msgs_to_refine(
|
||||
vec![
|
||||
50,
|
||||
100,
|
||||
max_extrinsic_size - 150,
|
||||
500,
|
||||
1000,
|
||||
1500,
|
||||
max_extrinsic_size - 3000,
|
||||
5000,
|
||||
10000,
|
||||
],
|
||||
Ok(vec![2, 1, 3, 1, 2]),
|
||||
);
|
||||
check_split_msgs_to_refine(
|
||||
vec![
|
||||
5000,
|
||||
10000,
|
||||
max_extrinsic_size - 3500,
|
||||
500,
|
||||
1000,
|
||||
1500,
|
||||
max_extrinsic_size - 500,
|
||||
50,
|
||||
100,
|
||||
],
|
||||
Ok(vec![2, 4, 3]),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Substrate client as Substrate messages target. The chain we connect to should have
|
||||
//! runtime that implements `<BridgedChainName>HeaderApi` to allow bridging with
|
||||
//! <BridgedName> chain.
|
||||
|
||||
use crate::{
|
||||
messages_lane::{MessageLaneAdapter, ReceiveMessagesProofCallBuilder, SubstrateMessageLane},
|
||||
messages_source::{ensure_messages_pallet_active, read_client_state, SubstrateMessagesProof},
|
||||
on_demand::OnDemandRelay,
|
||||
TransactionParams,
|
||||
};
|
||||
|
||||
use async_std::sync::Arc;
|
||||
use async_trait::async_trait;
|
||||
use bp_messages::{
|
||||
storage_keys::inbound_lane_data_key, total_unrewarded_messages, InboundLaneData, LaneId,
|
||||
MessageNonce, UnrewardedRelayersState,
|
||||
};
|
||||
use bridge_runtime_common::messages::source::FromBridgedChainMessagesDeliveryProof;
|
||||
use messages_relay::{
|
||||
message_lane::{MessageLane, SourceHeaderIdOf, TargetHeaderIdOf},
|
||||
message_lane_loop::{NoncesSubmitArtifacts, TargetClient, TargetClientState},
|
||||
};
|
||||
use relay_substrate_client::{
|
||||
AccountIdOf, AccountKeyPairOf, BalanceOf, BlockNumberOf, Chain, ChainWithMessages, Client,
|
||||
Error as SubstrateError, HashOf, HeaderIdOf, IndexOf, SignParam, TransactionEra,
|
||||
TransactionTracker, UnsignedTransaction,
|
||||
};
|
||||
use relay_utils::relay_loop::Client as RelayClient;
|
||||
use sp_core::Pair;
|
||||
use std::{collections::VecDeque, convert::TryFrom, ops::RangeInclusive};
|
||||
|
||||
/// Message receiving proof returned by the target Substrate node.
|
||||
pub type SubstrateMessagesDeliveryProof<C> =
|
||||
(UnrewardedRelayersState, FromBridgedChainMessagesDeliveryProof<HashOf<C>>);
|
||||
|
||||
/// Substrate client as Substrate messages target.
|
||||
pub struct SubstrateMessagesTarget<P: SubstrateMessageLane> {
|
||||
target_client: Client<P::TargetChain>,
|
||||
source_client: Client<P::SourceChain>,
|
||||
lane_id: LaneId,
|
||||
relayer_id_at_source: AccountIdOf<P::SourceChain>,
|
||||
transaction_params: TransactionParams<AccountKeyPairOf<P::TargetChain>>,
|
||||
source_to_target_headers_relay: Option<Arc<dyn OnDemandRelay<BlockNumberOf<P::SourceChain>>>>,
|
||||
}
|
||||
|
||||
impl<P: SubstrateMessageLane> SubstrateMessagesTarget<P> {
|
||||
/// Create new Substrate headers target.
|
||||
pub fn new(
|
||||
target_client: Client<P::TargetChain>,
|
||||
source_client: Client<P::SourceChain>,
|
||||
lane_id: LaneId,
|
||||
relayer_id_at_source: AccountIdOf<P::SourceChain>,
|
||||
transaction_params: TransactionParams<AccountKeyPairOf<P::TargetChain>>,
|
||||
source_to_target_headers_relay: Option<
|
||||
Arc<dyn OnDemandRelay<BlockNumberOf<P::SourceChain>>>,
|
||||
>,
|
||||
) -> Self {
|
||||
SubstrateMessagesTarget {
|
||||
target_client,
|
||||
source_client,
|
||||
lane_id,
|
||||
relayer_id_at_source,
|
||||
transaction_params,
|
||||
source_to_target_headers_relay,
|
||||
}
|
||||
}
|
||||
|
||||
/// Read inbound lane state from the on-chain storage at given block.
|
||||
async fn inbound_lane_data(
|
||||
&self,
|
||||
id: TargetHeaderIdOf<MessageLaneAdapter<P>>,
|
||||
) -> Result<Option<InboundLaneData<AccountIdOf<P::SourceChain>>>, SubstrateError> {
|
||||
self.target_client
|
||||
.storage_value(
|
||||
inbound_lane_data_key(
|
||||
P::SourceChain::WITH_CHAIN_MESSAGES_PALLET_NAME,
|
||||
&self.lane_id,
|
||||
),
|
||||
Some(id.1),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Ensure that the messages pallet at target chain is active.
|
||||
async fn ensure_pallet_active(&self) -> Result<(), SubstrateError> {
|
||||
ensure_messages_pallet_active::<P::TargetChain, P::SourceChain>(&self.target_client).await
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: SubstrateMessageLane> Clone for SubstrateMessagesTarget<P> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
target_client: self.target_client.clone(),
|
||||
source_client: self.source_client.clone(),
|
||||
lane_id: self.lane_id,
|
||||
relayer_id_at_source: self.relayer_id_at_source.clone(),
|
||||
transaction_params: self.transaction_params.clone(),
|
||||
source_to_target_headers_relay: self.source_to_target_headers_relay.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<P: SubstrateMessageLane> RelayClient for SubstrateMessagesTarget<P> {
|
||||
type Error = SubstrateError;
|
||||
|
||||
async fn reconnect(&mut self) -> Result<(), SubstrateError> {
|
||||
self.target_client.reconnect().await?;
|
||||
self.source_client.reconnect().await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<P: SubstrateMessageLane> TargetClient<MessageLaneAdapter<P>> for SubstrateMessagesTarget<P>
|
||||
where
|
||||
AccountIdOf<P::TargetChain>: From<<AccountKeyPairOf<P::TargetChain> as Pair>::Public>,
|
||||
BalanceOf<P::SourceChain>: TryFrom<BalanceOf<P::TargetChain>>,
|
||||
{
|
||||
type TransactionTracker = TransactionTracker<P::TargetChain, Client<P::TargetChain>>;
|
||||
|
||||
async fn state(&self) -> Result<TargetClientState<MessageLaneAdapter<P>>, SubstrateError> {
|
||||
// we can't continue to deliver confirmations if source node is out of sync, because
|
||||
// it may have already received confirmations that we're going to deliver
|
||||
//
|
||||
// we can't continue to deliver messages if target node is out of sync, because
|
||||
// it may have already received (some of) messages that we're going to deliver
|
||||
self.source_client.ensure_synced().await?;
|
||||
self.target_client.ensure_synced().await?;
|
||||
// we can't relay messages if messages pallet at target chain is halted
|
||||
self.ensure_pallet_active().await?;
|
||||
|
||||
read_client_state(
|
||||
&self.target_client,
|
||||
Some(&self.source_client),
|
||||
P::SourceChain::BEST_FINALIZED_HEADER_ID_METHOD,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn latest_received_nonce(
|
||||
&self,
|
||||
id: TargetHeaderIdOf<MessageLaneAdapter<P>>,
|
||||
) -> Result<(TargetHeaderIdOf<MessageLaneAdapter<P>>, MessageNonce), SubstrateError> {
|
||||
// lane data missing from the storage is fine until first message is received
|
||||
let latest_received_nonce = self
|
||||
.inbound_lane_data(id)
|
||||
.await?
|
||||
.map(|data| data.last_delivered_nonce())
|
||||
.unwrap_or(0);
|
||||
Ok((id, latest_received_nonce))
|
||||
}
|
||||
|
||||
async fn latest_confirmed_received_nonce(
|
||||
&self,
|
||||
id: TargetHeaderIdOf<MessageLaneAdapter<P>>,
|
||||
) -> Result<(TargetHeaderIdOf<MessageLaneAdapter<P>>, MessageNonce), SubstrateError> {
|
||||
// lane data missing from the storage is fine until first message is received
|
||||
let last_confirmed_nonce = self
|
||||
.inbound_lane_data(id)
|
||||
.await?
|
||||
.map(|data| data.last_confirmed_nonce)
|
||||
.unwrap_or(0);
|
||||
Ok((id, last_confirmed_nonce))
|
||||
}
|
||||
|
||||
async fn unrewarded_relayers_state(
|
||||
&self,
|
||||
id: TargetHeaderIdOf<MessageLaneAdapter<P>>,
|
||||
) -> Result<(TargetHeaderIdOf<MessageLaneAdapter<P>>, UnrewardedRelayersState), SubstrateError>
|
||||
{
|
||||
let inbound_lane_data = self.inbound_lane_data(id).await?;
|
||||
let last_delivered_nonce =
|
||||
inbound_lane_data.as_ref().map(|data| data.last_delivered_nonce()).unwrap_or(0);
|
||||
let relayers = inbound_lane_data.map(|data| data.relayers).unwrap_or_else(VecDeque::new);
|
||||
let unrewarded_relayers_state = bp_messages::UnrewardedRelayersState {
|
||||
unrewarded_relayer_entries: relayers.len() as _,
|
||||
messages_in_oldest_entry: relayers
|
||||
.front()
|
||||
.map(|entry| 1 + entry.messages.end - entry.messages.begin)
|
||||
.unwrap_or(0),
|
||||
total_messages: total_unrewarded_messages(&relayers).unwrap_or(MessageNonce::MAX),
|
||||
last_delivered_nonce,
|
||||
};
|
||||
Ok((id, unrewarded_relayers_state))
|
||||
}
|
||||
|
||||
async fn prove_messages_receiving(
|
||||
&self,
|
||||
id: TargetHeaderIdOf<MessageLaneAdapter<P>>,
|
||||
) -> Result<
|
||||
(
|
||||
TargetHeaderIdOf<MessageLaneAdapter<P>>,
|
||||
<MessageLaneAdapter<P> as MessageLane>::MessagesReceivingProof,
|
||||
),
|
||||
SubstrateError,
|
||||
> {
|
||||
let (id, relayers_state) = self.unrewarded_relayers_state(id).await?;
|
||||
let inbound_data_key = bp_messages::storage_keys::inbound_lane_data_key(
|
||||
P::SourceChain::WITH_CHAIN_MESSAGES_PALLET_NAME,
|
||||
&self.lane_id,
|
||||
);
|
||||
let proof = self
|
||||
.target_client
|
||||
.prove_storage(vec![inbound_data_key], id.1)
|
||||
.await?
|
||||
.into_iter_nodes()
|
||||
.collect();
|
||||
let proof = FromBridgedChainMessagesDeliveryProof {
|
||||
bridged_header_hash: id.1,
|
||||
storage_proof: proof,
|
||||
lane: self.lane_id,
|
||||
};
|
||||
Ok((id, (relayers_state, proof)))
|
||||
}
|
||||
|
||||
async fn submit_messages_proof(
|
||||
&self,
|
||||
_generated_at_header: SourceHeaderIdOf<MessageLaneAdapter<P>>,
|
||||
nonces: RangeInclusive<MessageNonce>,
|
||||
proof: <MessageLaneAdapter<P> as MessageLane>::MessagesProof,
|
||||
) -> Result<NoncesSubmitArtifacts<Self::TransactionTracker>, SubstrateError> {
|
||||
let genesis_hash = *self.target_client.genesis_hash();
|
||||
let transaction_params = self.transaction_params.clone();
|
||||
let relayer_id_at_source = self.relayer_id_at_source.clone();
|
||||
let nonces_clone = nonces.clone();
|
||||
let (spec_version, transaction_version) =
|
||||
self.target_client.simple_runtime_version().await?;
|
||||
let tx_tracker = self
|
||||
.target_client
|
||||
.submit_and_watch_signed_extrinsic(
|
||||
self.transaction_params.signer.public().into(),
|
||||
SignParam::<P::TargetChain> {
|
||||
spec_version,
|
||||
transaction_version,
|
||||
genesis_hash,
|
||||
signer: self.transaction_params.signer.clone(),
|
||||
},
|
||||
move |best_block_id, transaction_nonce| {
|
||||
make_messages_delivery_transaction::<P>(
|
||||
&transaction_params,
|
||||
best_block_id,
|
||||
transaction_nonce,
|
||||
relayer_id_at_source,
|
||||
nonces_clone,
|
||||
proof,
|
||||
true,
|
||||
)
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
Ok(NoncesSubmitArtifacts { nonces, tx_tracker })
|
||||
}
|
||||
|
||||
async fn require_source_header_on_target(&self, id: SourceHeaderIdOf<MessageLaneAdapter<P>>) {
|
||||
if let Some(ref source_to_target_headers_relay) = self.source_to_target_headers_relay {
|
||||
source_to_target_headers_relay.require_more_headers(id.0).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Make messages delivery transaction from given proof.
|
||||
fn make_messages_delivery_transaction<P: SubstrateMessageLane>(
|
||||
target_transaction_params: &TransactionParams<AccountKeyPairOf<P::TargetChain>>,
|
||||
target_best_block_id: HeaderIdOf<P::TargetChain>,
|
||||
transaction_nonce: IndexOf<P::TargetChain>,
|
||||
relayer_id_at_source: AccountIdOf<P::SourceChain>,
|
||||
nonces: RangeInclusive<MessageNonce>,
|
||||
proof: SubstrateMessagesProof<P::SourceChain>,
|
||||
trace_call: bool,
|
||||
) -> Result<UnsignedTransaction<P::TargetChain>, SubstrateError> {
|
||||
let messages_count = nonces.end() - nonces.start() + 1;
|
||||
let dispatch_weight = proof.0;
|
||||
let call = P::ReceiveMessagesProofCallBuilder::build_receive_messages_proof_call(
|
||||
relayer_id_at_source,
|
||||
proof,
|
||||
messages_count as _,
|
||||
dispatch_weight,
|
||||
trace_call,
|
||||
);
|
||||
Ok(UnsignedTransaction::new(call.into(), transaction_nonce)
|
||||
.era(TransactionEra::new(target_best_block_id, target_transaction_params.mortality)))
|
||||
}
|
||||
@@ -0,0 +1,457 @@
|
||||
// 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/>.
|
||||
|
||||
//! On-demand Substrate -> Substrate header finality relay.
|
||||
|
||||
use async_std::sync::{Arc, Mutex};
|
||||
use async_trait::async_trait;
|
||||
use bp_header_chain::ConsensusLogReader;
|
||||
use futures::{select, FutureExt};
|
||||
use num_traits::{One, Zero};
|
||||
use sp_runtime::traits::Header;
|
||||
|
||||
use finality_relay::{FinalitySyncParams, TargetClient as FinalityTargetClient};
|
||||
use relay_substrate_client::{AccountIdOf, AccountKeyPairOf, BlockNumberOf, Chain, Client};
|
||||
use relay_utils::{
|
||||
metrics::MetricsParams, relay_loop::Client as RelayClient, FailedClient, MaybeConnectionError,
|
||||
STALL_TIMEOUT,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
finality::{
|
||||
engine::Engine,
|
||||
source::{RequiredHeaderNumberRef, SubstrateFinalitySource},
|
||||
target::SubstrateFinalityTarget,
|
||||
SubstrateFinalitySyncPipeline, RECENT_FINALITY_PROOFS_LIMIT,
|
||||
},
|
||||
on_demand::OnDemandRelay,
|
||||
TransactionParams,
|
||||
};
|
||||
|
||||
/// On-demand Substrate <-> Substrate header finality relay.
|
||||
///
|
||||
/// This relay may be requested to sync more headers, whenever some other relay (e.g. messages
|
||||
/// relay) needs it to continue its regular work. When enough headers are relayed, on-demand stops
|
||||
/// syncing headers.
|
||||
#[derive(Clone)]
|
||||
pub struct OnDemandHeadersRelay<SourceChain: Chain> {
|
||||
/// Relay task name.
|
||||
relay_task_name: String,
|
||||
/// Shared reference to maximal required finalized header number.
|
||||
required_header_number: RequiredHeaderNumberRef<SourceChain>,
|
||||
}
|
||||
|
||||
impl<SourceChain: Chain> OnDemandHeadersRelay<SourceChain> {
|
||||
/// Create new on-demand headers relay.
|
||||
pub fn new<P: SubstrateFinalitySyncPipeline<SourceChain = SourceChain>>(
|
||||
source_client: Client<P::SourceChain>,
|
||||
target_client: Client<P::TargetChain>,
|
||||
target_transaction_params: TransactionParams<AccountKeyPairOf<P::TargetChain>>,
|
||||
only_mandatory_headers: bool,
|
||||
) -> Self
|
||||
where
|
||||
AccountIdOf<P::TargetChain>:
|
||||
From<<AccountKeyPairOf<P::TargetChain> as sp_core::Pair>::Public>,
|
||||
{
|
||||
let required_header_number = Arc::new(Mutex::new(Zero::zero()));
|
||||
let this = OnDemandHeadersRelay {
|
||||
relay_task_name: on_demand_headers_relay_name::<P::SourceChain, P::TargetChain>(),
|
||||
required_header_number: required_header_number.clone(),
|
||||
};
|
||||
async_std::task::spawn(async move {
|
||||
background_task::<P>(
|
||||
source_client,
|
||||
target_client,
|
||||
target_transaction_params,
|
||||
only_mandatory_headers,
|
||||
required_header_number,
|
||||
)
|
||||
.await;
|
||||
});
|
||||
|
||||
this
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<SourceChain: Chain> OnDemandRelay<BlockNumberOf<SourceChain>>
|
||||
for OnDemandHeadersRelay<SourceChain>
|
||||
{
|
||||
async fn require_more_headers(&self, required_header: BlockNumberOf<SourceChain>) {
|
||||
let mut required_header_number = self.required_header_number.lock().await;
|
||||
if required_header > *required_header_number {
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"[{}] More {} headers required. Going to sync up to the {}",
|
||||
self.relay_task_name,
|
||||
SourceChain::NAME,
|
||||
required_header,
|
||||
);
|
||||
|
||||
*required_header_number = required_header;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Background task that is responsible for starting headers relay.
|
||||
async fn background_task<P: SubstrateFinalitySyncPipeline>(
|
||||
source_client: Client<P::SourceChain>,
|
||||
target_client: Client<P::TargetChain>,
|
||||
target_transaction_params: TransactionParams<AccountKeyPairOf<P::TargetChain>>,
|
||||
only_mandatory_headers: bool,
|
||||
required_header_number: RequiredHeaderNumberRef<P::SourceChain>,
|
||||
) where
|
||||
AccountIdOf<P::TargetChain>: From<<AccountKeyPairOf<P::TargetChain> as sp_core::Pair>::Public>,
|
||||
{
|
||||
let relay_task_name = on_demand_headers_relay_name::<P::SourceChain, P::TargetChain>();
|
||||
let target_transactions_mortality = target_transaction_params.mortality;
|
||||
let mut finality_source = SubstrateFinalitySource::<P>::new(
|
||||
source_client.clone(),
|
||||
Some(required_header_number.clone()),
|
||||
);
|
||||
let mut finality_target =
|
||||
SubstrateFinalityTarget::new(target_client.clone(), target_transaction_params);
|
||||
let mut latest_non_mandatory_at_source = Zero::zero();
|
||||
|
||||
let mut restart_relay = true;
|
||||
let finality_relay_task = futures::future::Fuse::terminated();
|
||||
futures::pin_mut!(finality_relay_task);
|
||||
|
||||
loop {
|
||||
select! {
|
||||
_ = async_std::task::sleep(P::TargetChain::AVERAGE_BLOCK_INTERVAL).fuse() => {},
|
||||
_ = finality_relay_task => {
|
||||
// this should never happen in practice given the current code
|
||||
restart_relay = true;
|
||||
},
|
||||
}
|
||||
|
||||
// read best finalized source header number from source
|
||||
let best_finalized_source_header_at_source =
|
||||
best_finalized_source_header_at_source(&finality_source, &relay_task_name).await;
|
||||
if matches!(best_finalized_source_header_at_source, Err(ref e) if e.is_connection_error()) {
|
||||
relay_utils::relay_loop::reconnect_failed_client(
|
||||
FailedClient::Source,
|
||||
relay_utils::relay_loop::RECONNECT_DELAY,
|
||||
&mut finality_source,
|
||||
&mut finality_target,
|
||||
)
|
||||
.await;
|
||||
continue
|
||||
}
|
||||
|
||||
// read best finalized source header number from target
|
||||
let best_finalized_source_header_at_target =
|
||||
best_finalized_source_header_at_target::<P>(&finality_target, &relay_task_name).await;
|
||||
if matches!(best_finalized_source_header_at_target, Err(ref e) if e.is_connection_error()) {
|
||||
relay_utils::relay_loop::reconnect_failed_client(
|
||||
FailedClient::Target,
|
||||
relay_utils::relay_loop::RECONNECT_DELAY,
|
||||
&mut finality_source,
|
||||
&mut finality_target,
|
||||
)
|
||||
.await;
|
||||
continue
|
||||
}
|
||||
|
||||
// submit mandatory header if some headers are missing
|
||||
let best_finalized_source_header_at_source_fmt =
|
||||
format!("{best_finalized_source_header_at_source:?}");
|
||||
let best_finalized_source_header_at_target_fmt =
|
||||
format!("{best_finalized_source_header_at_target:?}");
|
||||
let required_header_number_value = *required_header_number.lock().await;
|
||||
let mandatory_scan_range = mandatory_headers_scan_range::<P::SourceChain>(
|
||||
best_finalized_source_header_at_source.ok(),
|
||||
best_finalized_source_header_at_target.ok(),
|
||||
required_header_number_value,
|
||||
)
|
||||
.await;
|
||||
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"[{}] Mandatory headers scan range: ({:?}, {:?}, {:?}) -> {:?}",
|
||||
relay_task_name,
|
||||
required_header_number_value,
|
||||
best_finalized_source_header_at_source_fmt,
|
||||
best_finalized_source_header_at_target_fmt,
|
||||
mandatory_scan_range,
|
||||
);
|
||||
|
||||
if let Some(mandatory_scan_range) = mandatory_scan_range {
|
||||
let relay_mandatory_header_result = relay_mandatory_header_from_range(
|
||||
&finality_source,
|
||||
&required_header_number,
|
||||
best_finalized_source_header_at_target_fmt,
|
||||
(
|
||||
std::cmp::max(mandatory_scan_range.0, latest_non_mandatory_at_source),
|
||||
mandatory_scan_range.1,
|
||||
),
|
||||
&relay_task_name,
|
||||
)
|
||||
.await;
|
||||
match relay_mandatory_header_result {
|
||||
Ok(true) => (),
|
||||
Ok(false) => {
|
||||
// there are no (or we don't need to relay them) mandatory headers in the range
|
||||
// => to avoid scanning the same headers over and over again, remember that
|
||||
latest_non_mandatory_at_source = mandatory_scan_range.1;
|
||||
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"[{}] No mandatory {} headers in the range {:?}",
|
||||
relay_task_name,
|
||||
P::SourceChain::NAME,
|
||||
mandatory_scan_range,
|
||||
);
|
||||
},
|
||||
Err(e) => {
|
||||
log::warn!(
|
||||
target: "bridge",
|
||||
"[{}] Failed to scan mandatory {} headers range ({:?}): {:?}",
|
||||
relay_task_name,
|
||||
P::SourceChain::NAME,
|
||||
mandatory_scan_range,
|
||||
e,
|
||||
);
|
||||
|
||||
if e.is_connection_error() {
|
||||
relay_utils::relay_loop::reconnect_failed_client(
|
||||
FailedClient::Source,
|
||||
relay_utils::relay_loop::RECONNECT_DELAY,
|
||||
&mut finality_source,
|
||||
&mut finality_target,
|
||||
)
|
||||
.await;
|
||||
continue
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// start/restart relay
|
||||
if restart_relay {
|
||||
let stall_timeout = relay_substrate_client::transaction_stall_timeout(
|
||||
target_transactions_mortality,
|
||||
P::TargetChain::AVERAGE_BLOCK_INTERVAL,
|
||||
STALL_TIMEOUT,
|
||||
);
|
||||
|
||||
log::info!(
|
||||
target: "bridge",
|
||||
"[{}] Starting on-demand headers relay task\n\t\
|
||||
Only mandatory headers: {}\n\t\
|
||||
Tx mortality: {:?} (~{}m)\n\t\
|
||||
Stall timeout: {:?}",
|
||||
relay_task_name,
|
||||
only_mandatory_headers,
|
||||
target_transactions_mortality,
|
||||
stall_timeout.as_secs_f64() / 60.0f64,
|
||||
stall_timeout,
|
||||
);
|
||||
|
||||
finality_relay_task.set(
|
||||
finality_relay::run(
|
||||
finality_source.clone(),
|
||||
finality_target.clone(),
|
||||
FinalitySyncParams {
|
||||
tick: std::cmp::max(
|
||||
P::SourceChain::AVERAGE_BLOCK_INTERVAL,
|
||||
P::TargetChain::AVERAGE_BLOCK_INTERVAL,
|
||||
),
|
||||
recent_finality_proofs_limit: RECENT_FINALITY_PROOFS_LIMIT,
|
||||
stall_timeout,
|
||||
only_mandatory_headers,
|
||||
},
|
||||
MetricsParams::disabled(),
|
||||
futures::future::pending(),
|
||||
)
|
||||
.fuse(),
|
||||
);
|
||||
|
||||
restart_relay = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `Some()` with inclusive range of headers which must be scanned for mandatory headers
|
||||
/// and the first of such headers must be submitted to the target node.
|
||||
async fn mandatory_headers_scan_range<C: Chain>(
|
||||
best_finalized_source_header_at_source: Option<C::BlockNumber>,
|
||||
best_finalized_source_header_at_target: Option<C::BlockNumber>,
|
||||
required_header_number: BlockNumberOf<C>,
|
||||
) -> Option<(C::BlockNumber, C::BlockNumber)> {
|
||||
// if we have been unable to read header number from the target, then let's assume
|
||||
// that it is the same as required header number. Otherwise we risk submitting
|
||||
// unneeded transactions
|
||||
let best_finalized_source_header_at_target =
|
||||
best_finalized_source_header_at_target.unwrap_or(required_header_number);
|
||||
|
||||
// if we have been unable to read header number from the source, then let's assume
|
||||
// that it is the same as at the target
|
||||
let best_finalized_source_header_at_source =
|
||||
best_finalized_source_header_at_source.unwrap_or(best_finalized_source_header_at_target);
|
||||
|
||||
// if relay is already asked to sync more headers than we have at source, don't do anything yet
|
||||
if required_header_number >= best_finalized_source_header_at_source {
|
||||
return None
|
||||
}
|
||||
|
||||
Some((
|
||||
best_finalized_source_header_at_target + One::one(),
|
||||
best_finalized_source_header_at_source,
|
||||
))
|
||||
}
|
||||
|
||||
/// Try to find mandatory header in the inclusive headers range and, if one is found, ask to relay
|
||||
/// it.
|
||||
///
|
||||
/// Returns `true` if header was found and (asked to be) relayed and `false` otherwise.
|
||||
async fn relay_mandatory_header_from_range<P: SubstrateFinalitySyncPipeline>(
|
||||
finality_source: &SubstrateFinalitySource<P>,
|
||||
required_header_number: &RequiredHeaderNumberRef<P::SourceChain>,
|
||||
best_finalized_source_header_at_target: String,
|
||||
range: (BlockNumberOf<P::SourceChain>, BlockNumberOf<P::SourceChain>),
|
||||
relay_task_name: &str,
|
||||
) -> Result<bool, relay_substrate_client::Error> {
|
||||
// search for mandatory header first
|
||||
let mandatory_source_header_number =
|
||||
find_mandatory_header_in_range(finality_source, range).await?;
|
||||
|
||||
// if there are no mandatory headers - we have nothing to do
|
||||
let mandatory_source_header_number = match mandatory_source_header_number {
|
||||
Some(mandatory_source_header_number) => mandatory_source_header_number,
|
||||
None => return Ok(false),
|
||||
};
|
||||
|
||||
// `find_mandatory_header` call may take a while => check if `required_header_number` is still
|
||||
// less than our `mandatory_source_header_number` before logging anything
|
||||
let mut required_header_number = required_header_number.lock().await;
|
||||
if *required_header_number >= mandatory_source_header_number {
|
||||
return Ok(false)
|
||||
}
|
||||
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"[{}] Too many {} headers missing at target ({} vs {}). Going to sync up to the mandatory {}",
|
||||
relay_task_name,
|
||||
P::SourceChain::NAME,
|
||||
best_finalized_source_header_at_target,
|
||||
range.1,
|
||||
mandatory_source_header_number,
|
||||
);
|
||||
|
||||
*required_header_number = mandatory_source_header_number;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Read best finalized source block number from source client.
|
||||
///
|
||||
/// Returns `None` if we have failed to read the number.
|
||||
async fn best_finalized_source_header_at_source<P: SubstrateFinalitySyncPipeline>(
|
||||
finality_source: &SubstrateFinalitySource<P>,
|
||||
relay_task_name: &str,
|
||||
) -> Result<BlockNumberOf<P::SourceChain>, relay_substrate_client::Error> {
|
||||
finality_source.on_chain_best_finalized_block_number().await.map_err(|error| {
|
||||
log::error!(
|
||||
target: "bridge",
|
||||
"[{}] Failed to read best finalized source header from source: {:?}",
|
||||
relay_task_name,
|
||||
error,
|
||||
);
|
||||
|
||||
error
|
||||
})
|
||||
}
|
||||
|
||||
/// Read best finalized source block number from target client.
|
||||
///
|
||||
/// Returns `None` if we have failed to read the number.
|
||||
async fn best_finalized_source_header_at_target<P: SubstrateFinalitySyncPipeline>(
|
||||
finality_target: &SubstrateFinalityTarget<P>,
|
||||
relay_task_name: &str,
|
||||
) -> Result<BlockNumberOf<P::SourceChain>, <SubstrateFinalityTarget<P> as RelayClient>::Error>
|
||||
where
|
||||
AccountIdOf<P::TargetChain>: From<<AccountKeyPairOf<P::TargetChain> as sp_core::Pair>::Public>,
|
||||
{
|
||||
finality_target
|
||||
.best_finalized_source_block_id()
|
||||
.await
|
||||
.map_err(|error| {
|
||||
log::error!(
|
||||
target: "bridge",
|
||||
"[{}] Failed to read best finalized source header from target: {:?}",
|
||||
relay_task_name,
|
||||
error,
|
||||
);
|
||||
|
||||
error
|
||||
})
|
||||
.map(|id| id.0)
|
||||
}
|
||||
|
||||
/// Read first mandatory header in given inclusive range.
|
||||
///
|
||||
/// Returns `Ok(None)` if there were no mandatory headers in the range.
|
||||
async fn find_mandatory_header_in_range<P: SubstrateFinalitySyncPipeline>(
|
||||
finality_source: &SubstrateFinalitySource<P>,
|
||||
range: (BlockNumberOf<P::SourceChain>, BlockNumberOf<P::SourceChain>),
|
||||
) -> Result<Option<BlockNumberOf<P::SourceChain>>, relay_substrate_client::Error> {
|
||||
let mut current = range.0;
|
||||
while current <= range.1 {
|
||||
let header = finality_source.client().header_by_number(current).await?;
|
||||
if <P::FinalityEngine as Engine<P::SourceChain>>::ConsensusLogReader::schedules_authorities_change(
|
||||
header.digest(),
|
||||
) {
|
||||
return Ok(Some(current))
|
||||
}
|
||||
|
||||
current += One::one();
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// On-demand headers relay task name.
|
||||
fn on_demand_headers_relay_name<SourceChain: Chain, TargetChain: Chain>() -> String {
|
||||
format!("{}-to-{}-on-demand-headers", SourceChain::NAME, TargetChain::NAME)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
type TestChain = relay_rococo_client::Rococo;
|
||||
|
||||
const AT_SOURCE: Option<bp_rococo::BlockNumber> = Some(10);
|
||||
const AT_TARGET: Option<bp_rococo::BlockNumber> = Some(1);
|
||||
|
||||
#[async_std::test]
|
||||
async fn mandatory_headers_scan_range_selects_range_if_some_headers_are_missing() {
|
||||
assert_eq!(
|
||||
mandatory_headers_scan_range::<TestChain>(AT_SOURCE, AT_TARGET, 0,).await,
|
||||
Some((AT_TARGET.unwrap() + 1, AT_SOURCE.unwrap())),
|
||||
);
|
||||
}
|
||||
|
||||
#[async_std::test]
|
||||
async fn mandatory_headers_scan_range_selects_nothing_if_already_queued() {
|
||||
assert_eq!(
|
||||
mandatory_headers_scan_range::<TestChain>(AT_SOURCE, AT_TARGET, AT_SOURCE.unwrap(),)
|
||||
.await,
|
||||
None,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// 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/>.
|
||||
|
||||
//! Types and functions intended to ease adding of new Substrate -> Substrate
|
||||
//! on-demand pipelines.
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
pub mod headers;
|
||||
pub mod parachains;
|
||||
|
||||
/// On-demand headers relay that is relaying finalizing headers only when requested.
|
||||
#[async_trait]
|
||||
pub trait OnDemandRelay<SourceHeaderNumber>: Send + Sync {
|
||||
/// Ask relay to relay source header with given number to the target chain.
|
||||
///
|
||||
/// Depending on implementation, on-demand relay may also relay `required_header` ancestors
|
||||
/// (e.g. if they're mandatory), or its descendants. The request is considered complete if
|
||||
/// the best avbailable header at the target chain has number that is larger than or equal
|
||||
/// to the `required_header`.
|
||||
async fn require_more_headers(&self, required_header: SourceHeaderNumber);
|
||||
}
|
||||
@@ -0,0 +1,704 @@
|
||||
// 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/>.
|
||||
|
||||
//! On-demand Substrate -> Substrate parachain finality relay.
|
||||
|
||||
use crate::{
|
||||
messages_source::best_finalized_peer_header_at_self,
|
||||
on_demand::OnDemandRelay,
|
||||
parachains::{
|
||||
source::ParachainsSource, target::ParachainsTarget, ParachainsPipelineAdapter,
|
||||
SubstrateParachainsPipeline,
|
||||
},
|
||||
TransactionParams,
|
||||
};
|
||||
|
||||
use async_std::{
|
||||
channel::{unbounded, Receiver, Sender},
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use bp_polkadot_core::parachains::ParaHash;
|
||||
use bp_runtime::HeaderIdProvider;
|
||||
use futures::{select, FutureExt};
|
||||
use num_traits::Zero;
|
||||
use pallet_bridge_parachains::{RelayBlockHash, RelayBlockHasher, RelayBlockNumber};
|
||||
use parachains_relay::parachains_loop::{AvailableHeader, ParachainSyncParams, TargetClient};
|
||||
use relay_substrate_client::{
|
||||
AccountIdOf, AccountKeyPairOf, BlockNumberOf, Chain, Client, Error as SubstrateError, HashOf,
|
||||
};
|
||||
use relay_utils::{
|
||||
metrics::MetricsParams, relay_loop::Client as RelayClient, FailedClient, HeaderId,
|
||||
};
|
||||
use std::fmt::Debug;
|
||||
|
||||
/// On-demand Substrate <-> Substrate parachain finality relay.
|
||||
///
|
||||
/// This relay may be requested to sync more parachain headers, whenever some other relay
|
||||
/// (e.g. messages relay) needs it to continue its regular work. When enough parachain headers
|
||||
/// are relayed, on-demand stops syncing headers.
|
||||
#[derive(Clone)]
|
||||
pub struct OnDemandParachainsRelay<SourceParachain: Chain> {
|
||||
/// Relay task name.
|
||||
relay_task_name: String,
|
||||
/// Channel used to communicate with background task and ask for relay of parachain heads.
|
||||
required_header_number_sender: Sender<BlockNumberOf<SourceParachain>>,
|
||||
}
|
||||
|
||||
impl<SourceParachain: Chain> OnDemandParachainsRelay<SourceParachain> {
|
||||
/// Create new on-demand parachains relay.
|
||||
///
|
||||
/// Note that the argument is the source relay chain client, not the parachain client.
|
||||
/// That's because parachain finality is determined by the relay chain and we don't
|
||||
/// need to connect to the parachain itself here.
|
||||
pub fn new<P: SubstrateParachainsPipeline<SourceParachain = SourceParachain>>(
|
||||
source_relay_client: Client<P::SourceRelayChain>,
|
||||
target_client: Client<P::TargetChain>,
|
||||
target_transaction_params: TransactionParams<AccountKeyPairOf<P::TargetChain>>,
|
||||
on_demand_source_relay_to_target_headers: Arc<
|
||||
dyn OnDemandRelay<BlockNumberOf<P::SourceRelayChain>>,
|
||||
>,
|
||||
) -> Self
|
||||
where
|
||||
P::SourceParachain: Chain<Hash = ParaHash>,
|
||||
P::SourceRelayChain:
|
||||
Chain<BlockNumber = RelayBlockNumber, Hash = RelayBlockHash, Hasher = RelayBlockHasher>,
|
||||
AccountIdOf<P::TargetChain>:
|
||||
From<<AccountKeyPairOf<P::TargetChain> as sp_core::Pair>::Public>,
|
||||
{
|
||||
let (required_header_number_sender, required_header_number_receiver) = unbounded();
|
||||
let this = OnDemandParachainsRelay {
|
||||
relay_task_name: on_demand_parachains_relay_name::<SourceParachain, P::TargetChain>(),
|
||||
required_header_number_sender,
|
||||
};
|
||||
async_std::task::spawn(async move {
|
||||
background_task::<P>(
|
||||
source_relay_client,
|
||||
target_client,
|
||||
target_transaction_params,
|
||||
on_demand_source_relay_to_target_headers,
|
||||
required_header_number_receiver,
|
||||
)
|
||||
.await;
|
||||
});
|
||||
|
||||
this
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<SourceParachain> OnDemandRelay<BlockNumberOf<SourceParachain>>
|
||||
for OnDemandParachainsRelay<SourceParachain>
|
||||
where
|
||||
SourceParachain: Chain,
|
||||
{
|
||||
async fn require_more_headers(&self, required_header: BlockNumberOf<SourceParachain>) {
|
||||
if let Err(e) = self.required_header_number_sender.send(required_header).await {
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"[{}] Failed to request {} header {:?}: {:?}",
|
||||
self.relay_task_name,
|
||||
SourceParachain::NAME,
|
||||
required_header,
|
||||
e,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Background task that is responsible for starting parachain headers relay.
|
||||
async fn background_task<P: SubstrateParachainsPipeline>(
|
||||
source_relay_client: Client<P::SourceRelayChain>,
|
||||
target_client: Client<P::TargetChain>,
|
||||
target_transaction_params: TransactionParams<AccountKeyPairOf<P::TargetChain>>,
|
||||
on_demand_source_relay_to_target_headers: Arc<
|
||||
dyn OnDemandRelay<BlockNumberOf<P::SourceRelayChain>>,
|
||||
>,
|
||||
required_parachain_header_number_receiver: Receiver<BlockNumberOf<P::SourceParachain>>,
|
||||
) where
|
||||
P::SourceParachain: Chain<Hash = ParaHash>,
|
||||
P::SourceRelayChain:
|
||||
Chain<BlockNumber = RelayBlockNumber, Hash = RelayBlockHash, Hasher = RelayBlockHasher>,
|
||||
AccountIdOf<P::TargetChain>: From<<AccountKeyPairOf<P::TargetChain> as sp_core::Pair>::Public>,
|
||||
{
|
||||
let relay_task_name = on_demand_parachains_relay_name::<P::SourceParachain, P::TargetChain>();
|
||||
let target_transactions_mortality = target_transaction_params.mortality;
|
||||
|
||||
let mut relay_state = RelayState::Idle;
|
||||
let mut required_parachain_header_number = Zero::zero();
|
||||
let required_para_header_number_ref = Arc::new(Mutex::new(AvailableHeader::Unavailable));
|
||||
|
||||
let mut restart_relay = true;
|
||||
let parachains_relay_task = futures::future::Fuse::terminated();
|
||||
futures::pin_mut!(parachains_relay_task);
|
||||
|
||||
let mut parachains_source = ParachainsSource::<P>::new(
|
||||
source_relay_client.clone(),
|
||||
required_para_header_number_ref.clone(),
|
||||
);
|
||||
let mut parachains_target =
|
||||
ParachainsTarget::<P>::new(target_client.clone(), target_transaction_params.clone());
|
||||
|
||||
loop {
|
||||
select! {
|
||||
new_required_parachain_header_number = required_parachain_header_number_receiver.recv().fuse() => {
|
||||
let new_required_parachain_header_number = match new_required_parachain_header_number {
|
||||
Ok(new_required_parachain_header_number) => new_required_parachain_header_number,
|
||||
Err(e) => {
|
||||
log::error!(
|
||||
target: "bridge",
|
||||
"[{}] Background task has exited with error: {:?}",
|
||||
relay_task_name,
|
||||
e,
|
||||
);
|
||||
|
||||
return;
|
||||
},
|
||||
};
|
||||
|
||||
// keep in mind that we are not updating `required_para_header_number_ref` here, because
|
||||
// then we'll be submitting all previous headers as well (while required relay headers are
|
||||
// delivered) and we want to avoid that (to reduce cost)
|
||||
required_parachain_header_number = std::cmp::max(
|
||||
required_parachain_header_number,
|
||||
new_required_parachain_header_number,
|
||||
);
|
||||
},
|
||||
_ = async_std::task::sleep(P::TargetChain::AVERAGE_BLOCK_INTERVAL).fuse() => {},
|
||||
_ = parachains_relay_task => {
|
||||
// this should never happen in practice given the current code
|
||||
restart_relay = true;
|
||||
},
|
||||
}
|
||||
|
||||
// the workflow of the on-demand parachains relay is:
|
||||
//
|
||||
// 1) message relay (or any other dependent relay) sees new message at parachain header
|
||||
// `PH`;
|
||||
//
|
||||
// 2) it sees that the target chain does not know `PH`;
|
||||
//
|
||||
// 3) it asks on-demand parachains relay to relay `PH` to the target chain;
|
||||
//
|
||||
// Phase#1: relaying relay chain header
|
||||
//
|
||||
// 4) on-demand parachains relay waits for GRANDPA-finalized block of the source relay chain
|
||||
// `RH` that is storing `PH` or its descendant. Let it be `PH'`;
|
||||
// 5) it asks on-demand headers relay to relay `RH` to the target chain;
|
||||
// 6) it waits until `RH` (or its descendant) is relayed to the target chain;
|
||||
//
|
||||
// Phase#2: relaying parachain header
|
||||
//
|
||||
// 7) on-demand parachains relay sets `ParachainsSource::maximal_header_number` to the
|
||||
// `PH'.number()`.
|
||||
// 8) parachains finality relay sees that the parachain head has been
|
||||
// updated and relays `PH'` to the target chain.
|
||||
|
||||
// select headers to relay
|
||||
let relay_data = read_relay_data(
|
||||
¶chains_source,
|
||||
¶chains_target,
|
||||
required_parachain_header_number,
|
||||
)
|
||||
.await;
|
||||
match relay_data {
|
||||
Ok(relay_data) => {
|
||||
let prev_relay_state = relay_state;
|
||||
relay_state = select_headers_to_relay(&relay_data, relay_state);
|
||||
log::trace!(
|
||||
target: "bridge",
|
||||
"[{}] Selected new relay state: {:?} using old state {:?} and data {:?}",
|
||||
relay_task_name,
|
||||
relay_state,
|
||||
prev_relay_state,
|
||||
relay_data,
|
||||
);
|
||||
},
|
||||
Err(failed_client) => {
|
||||
relay_utils::relay_loop::reconnect_failed_client(
|
||||
failed_client,
|
||||
relay_utils::relay_loop::RECONNECT_DELAY,
|
||||
&mut parachains_source,
|
||||
&mut parachains_target,
|
||||
)
|
||||
.await;
|
||||
continue
|
||||
},
|
||||
}
|
||||
|
||||
// we have selected our new 'state' => let's notify our source clients about our new
|
||||
// requirements
|
||||
match relay_state {
|
||||
RelayState::Idle => (),
|
||||
RelayState::RelayingRelayHeader(required_relay_header) => {
|
||||
on_demand_source_relay_to_target_headers
|
||||
.require_more_headers(required_relay_header)
|
||||
.await;
|
||||
},
|
||||
RelayState::RelayingParaHeader(required_para_header) => {
|
||||
*required_para_header_number_ref.lock().await =
|
||||
AvailableHeader::Available(required_para_header);
|
||||
},
|
||||
}
|
||||
|
||||
// start/restart relay
|
||||
if restart_relay {
|
||||
let stall_timeout = relay_substrate_client::transaction_stall_timeout(
|
||||
target_transactions_mortality,
|
||||
P::TargetChain::AVERAGE_BLOCK_INTERVAL,
|
||||
relay_utils::STALL_TIMEOUT,
|
||||
);
|
||||
|
||||
log::info!(
|
||||
target: "bridge",
|
||||
"[{}] Starting on-demand-parachains relay task\n\t\
|
||||
Tx mortality: {:?} (~{}m)\n\t\
|
||||
Stall timeout: {:?}",
|
||||
relay_task_name,
|
||||
target_transactions_mortality,
|
||||
stall_timeout.as_secs_f64() / 60.0f64,
|
||||
stall_timeout,
|
||||
);
|
||||
|
||||
parachains_relay_task.set(
|
||||
parachains_relay::parachains_loop::run(
|
||||
parachains_source.clone(),
|
||||
parachains_target.clone(),
|
||||
ParachainSyncParams {
|
||||
parachains: vec![P::SOURCE_PARACHAIN_PARA_ID.into()],
|
||||
stall_timeout: std::time::Duration::from_secs(60),
|
||||
strategy: parachains_relay::parachains_loop::ParachainSyncStrategy::Any,
|
||||
},
|
||||
MetricsParams::disabled(),
|
||||
futures::future::pending(),
|
||||
)
|
||||
.fuse(),
|
||||
);
|
||||
|
||||
restart_relay = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// On-demand parachains relay task name.
|
||||
fn on_demand_parachains_relay_name<SourceChain: Chain, TargetChain: Chain>() -> String {
|
||||
format!("{}-to-{}-on-demand-parachain", SourceChain::NAME, TargetChain::NAME)
|
||||
}
|
||||
|
||||
/// On-demand relay state.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum RelayState<ParaHash, ParaNumber, RelayNumber> {
|
||||
/// On-demand relay is not doing anything.
|
||||
Idle,
|
||||
/// Relaying given relay header to relay given parachain header later.
|
||||
RelayingRelayHeader(RelayNumber),
|
||||
/// Relaying given parachain header.
|
||||
RelayingParaHeader(HeaderId<ParaHash, ParaNumber>),
|
||||
}
|
||||
|
||||
/// Data gathered from source and target clients, used by on-demand relay.
|
||||
#[derive(Debug)]
|
||||
struct RelayData<ParaHash, ParaNumber, RelayNumber> {
|
||||
/// Parachain header number that is required at the target chain.
|
||||
pub required_para_header: ParaNumber,
|
||||
/// Parachain header number, known to the target chain.
|
||||
pub para_header_at_target: Option<ParaNumber>,
|
||||
/// Parachain header id, known to the source (relay) chain.
|
||||
pub para_header_at_source: Option<HeaderId<ParaHash, ParaNumber>>,
|
||||
/// Parachain header, that is available at the source relay chain at `relay_header_at_target`
|
||||
/// block.
|
||||
pub para_header_at_relay_header_at_target: Option<HeaderId<ParaHash, ParaNumber>>,
|
||||
/// Relay header number at the source chain.
|
||||
pub relay_header_at_source: RelayNumber,
|
||||
/// Relay header number at the target chain.
|
||||
pub relay_header_at_target: RelayNumber,
|
||||
}
|
||||
|
||||
/// Read required data from source and target clients.
|
||||
async fn read_relay_data<P: SubstrateParachainsPipeline>(
|
||||
source: &ParachainsSource<P>,
|
||||
target: &ParachainsTarget<P>,
|
||||
required_header_number: BlockNumberOf<P::SourceParachain>,
|
||||
) -> Result<
|
||||
RelayData<
|
||||
HashOf<P::SourceParachain>,
|
||||
BlockNumberOf<P::SourceParachain>,
|
||||
BlockNumberOf<P::SourceRelayChain>,
|
||||
>,
|
||||
FailedClient,
|
||||
>
|
||||
where
|
||||
ParachainsTarget<P>:
|
||||
TargetClient<ParachainsPipelineAdapter<P>> + RelayClient<Error = SubstrateError>,
|
||||
{
|
||||
let map_target_err = |e| {
|
||||
log::error!(
|
||||
target: "bridge",
|
||||
"[{}] Failed to read relay data from {} client: {:?}",
|
||||
on_demand_parachains_relay_name::<P::SourceParachain, P::TargetChain>(),
|
||||
P::TargetChain::NAME,
|
||||
e,
|
||||
);
|
||||
FailedClient::Target
|
||||
};
|
||||
let map_source_err = |e| {
|
||||
log::error!(
|
||||
target: "bridge",
|
||||
"[{}] Failed to read relay data from {} client: {:?}",
|
||||
on_demand_parachains_relay_name::<P::SourceParachain, P::TargetChain>(),
|
||||
P::SourceRelayChain::NAME,
|
||||
e,
|
||||
);
|
||||
FailedClient::Source
|
||||
};
|
||||
|
||||
let best_target_block_hash = target.best_block().await.map_err(map_target_err)?.1;
|
||||
let para_header_at_target =
|
||||
best_finalized_peer_header_at_self::<P::TargetChain, P::SourceParachain>(
|
||||
target.client(),
|
||||
best_target_block_hash,
|
||||
P::SourceParachain::BEST_FINALIZED_HEADER_ID_METHOD,
|
||||
)
|
||||
.await;
|
||||
// if there are no parachain heads at the target (`BridgePalletIsNotInitialized`), we'll need
|
||||
// to submit at least one. Otherwise the pallet will be treated as uninitialized and messages
|
||||
// sync will stall.
|
||||
let para_header_at_target = match para_header_at_target {
|
||||
Ok(para_header_at_target) => Some(para_header_at_target.0),
|
||||
Err(SubstrateError::BridgePalletIsNotInitialized) => None,
|
||||
Err(e) => return Err(map_target_err(e)),
|
||||
};
|
||||
|
||||
let best_finalized_relay_header =
|
||||
source.client().best_finalized_header().await.map_err(map_source_err)?;
|
||||
let best_finalized_relay_block_id = best_finalized_relay_header.id();
|
||||
let para_header_at_source = source
|
||||
.on_chain_para_head_id(best_finalized_relay_block_id, P::SOURCE_PARACHAIN_PARA_ID.into())
|
||||
.await
|
||||
.map_err(map_source_err)?;
|
||||
|
||||
let relay_header_at_source = best_finalized_relay_block_id.0;
|
||||
let relay_header_at_target =
|
||||
best_finalized_peer_header_at_self::<P::TargetChain, P::SourceRelayChain>(
|
||||
target.client(),
|
||||
best_target_block_hash,
|
||||
P::SourceRelayChain::BEST_FINALIZED_HEADER_ID_METHOD,
|
||||
)
|
||||
.await
|
||||
.map_err(map_target_err)?;
|
||||
|
||||
let para_header_at_relay_header_at_target = source
|
||||
.on_chain_para_head_id(relay_header_at_target, P::SOURCE_PARACHAIN_PARA_ID.into())
|
||||
.await
|
||||
.map_err(map_source_err)?;
|
||||
|
||||
Ok(RelayData {
|
||||
required_para_header: required_header_number,
|
||||
para_header_at_target,
|
||||
para_header_at_source,
|
||||
relay_header_at_source,
|
||||
relay_header_at_target: relay_header_at_target.0,
|
||||
para_header_at_relay_header_at_target,
|
||||
})
|
||||
}
|
||||
|
||||
/// Select relay and parachain headers that need to be relayed.
|
||||
fn select_headers_to_relay<ParaHash, ParaNumber, RelayNumber>(
|
||||
data: &RelayData<ParaHash, ParaNumber, RelayNumber>,
|
||||
mut state: RelayState<ParaHash, ParaNumber, RelayNumber>,
|
||||
) -> RelayState<ParaHash, ParaNumber, RelayNumber>
|
||||
where
|
||||
ParaHash: Clone,
|
||||
ParaNumber: Copy + PartialOrd + Zero,
|
||||
RelayNumber: Copy + Debug + Ord,
|
||||
{
|
||||
// Process the `RelayingRelayHeader` state.
|
||||
if let &RelayState::RelayingRelayHeader(relay_header_number) = &state {
|
||||
if data.relay_header_at_target < relay_header_number {
|
||||
// The required relay header hasn't yet been relayed. Ask / wait for it.
|
||||
return state
|
||||
}
|
||||
|
||||
// We may switch to `RelayingParaHeader` if parachain head is available.
|
||||
state = data
|
||||
.para_header_at_relay_header_at_target
|
||||
.clone()
|
||||
.map_or(RelayState::Idle, RelayState::RelayingParaHeader);
|
||||
}
|
||||
|
||||
// Process the `RelayingParaHeader` state.
|
||||
if let RelayState::RelayingParaHeader(para_header_id) = &state {
|
||||
let para_header_at_target_or_zero = data.para_header_at_target.unwrap_or_else(Zero::zero);
|
||||
if para_header_at_target_or_zero < para_header_id.0 {
|
||||
// The required parachain header hasn't yet been relayed. Ask / wait for it.
|
||||
return state
|
||||
}
|
||||
}
|
||||
|
||||
// if we haven't read para head from the source, we can't yet do anything
|
||||
let para_header_at_source = match data.para_header_at_source {
|
||||
Some(ref para_header_at_source) => para_header_at_source.clone(),
|
||||
None => return RelayState::Idle,
|
||||
};
|
||||
|
||||
// if we have parachain head at the source, but no parachain heads at the target, we'll need
|
||||
// to deliver at least one parachain head
|
||||
let (required_para_header, para_header_at_target) = match data.para_header_at_target {
|
||||
Some(para_header_at_target) => (data.required_para_header, para_header_at_target),
|
||||
None => (para_header_at_source.0, Zero::zero()),
|
||||
};
|
||||
|
||||
// if we have already satisfied our "customer", do nothing
|
||||
if required_para_header <= para_header_at_target {
|
||||
return RelayState::Idle
|
||||
}
|
||||
|
||||
// if required header is not available even at the source chain, let's wait
|
||||
if required_para_header > para_header_at_source.0 {
|
||||
return RelayState::Idle
|
||||
}
|
||||
|
||||
// we will always try to sync latest parachain/relay header, even if we've been asked for some
|
||||
// its ancestor
|
||||
|
||||
// we need relay chain header first
|
||||
if data.relay_header_at_target < data.relay_header_at_source {
|
||||
return RelayState::RelayingRelayHeader(data.relay_header_at_source)
|
||||
}
|
||||
|
||||
// if all relay headers synced, we may start directly with parachain header
|
||||
RelayState::RelayingParaHeader(para_header_at_source)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn relay_waits_for_relay_header_to_be_delivered() {
|
||||
assert_eq!(
|
||||
select_headers_to_relay(
|
||||
&RelayData {
|
||||
required_para_header: 90,
|
||||
para_header_at_target: Some(50),
|
||||
para_header_at_source: Some(HeaderId(110, 110)),
|
||||
relay_header_at_source: 800,
|
||||
relay_header_at_target: 700,
|
||||
para_header_at_relay_header_at_target: Some(HeaderId(100, 100)),
|
||||
},
|
||||
RelayState::RelayingRelayHeader(750),
|
||||
),
|
||||
RelayState::RelayingRelayHeader(750),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relay_starts_relaying_requested_para_header_after_relay_header_is_delivered() {
|
||||
assert_eq!(
|
||||
select_headers_to_relay(
|
||||
&RelayData {
|
||||
required_para_header: 90,
|
||||
para_header_at_target: Some(50),
|
||||
para_header_at_source: Some(HeaderId(110, 110)),
|
||||
relay_header_at_source: 800,
|
||||
relay_header_at_target: 750,
|
||||
para_header_at_relay_header_at_target: Some(HeaderId(100, 100)),
|
||||
},
|
||||
RelayState::RelayingRelayHeader(750),
|
||||
),
|
||||
RelayState::RelayingParaHeader(HeaderId(100, 100)),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relay_selects_better_para_header_after_better_relay_header_is_delivered() {
|
||||
assert_eq!(
|
||||
select_headers_to_relay(
|
||||
&RelayData {
|
||||
required_para_header: 90,
|
||||
para_header_at_target: Some(50),
|
||||
para_header_at_source: Some(HeaderId(110, 110)),
|
||||
relay_header_at_source: 800,
|
||||
relay_header_at_target: 780,
|
||||
para_header_at_relay_header_at_target: Some(HeaderId(105, 105)),
|
||||
},
|
||||
RelayState::RelayingRelayHeader(750),
|
||||
),
|
||||
RelayState::RelayingParaHeader(HeaderId(105, 105)),
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn relay_waits_for_para_header_to_be_delivered() {
|
||||
assert_eq!(
|
||||
select_headers_to_relay(
|
||||
&RelayData {
|
||||
required_para_header: 90,
|
||||
para_header_at_target: Some(50),
|
||||
para_header_at_source: Some(HeaderId(110, 110)),
|
||||
relay_header_at_source: 800,
|
||||
relay_header_at_target: 780,
|
||||
para_header_at_relay_header_at_target: Some(HeaderId(105, 105)),
|
||||
},
|
||||
RelayState::RelayingParaHeader(HeaderId(105, 105)),
|
||||
),
|
||||
RelayState::RelayingParaHeader(HeaderId(105, 105)),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relay_stays_idle_if_required_para_header_is_already_delivered() {
|
||||
assert_eq!(
|
||||
select_headers_to_relay(
|
||||
&RelayData {
|
||||
required_para_header: 90,
|
||||
para_header_at_target: Some(105),
|
||||
para_header_at_source: Some(HeaderId(110, 110)),
|
||||
relay_header_at_source: 800,
|
||||
relay_header_at_target: 780,
|
||||
para_header_at_relay_header_at_target: Some(HeaderId(105, 105)),
|
||||
},
|
||||
RelayState::Idle,
|
||||
),
|
||||
RelayState::Idle,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relay_waits_for_required_para_header_to_appear_at_source_1() {
|
||||
assert_eq!(
|
||||
select_headers_to_relay(
|
||||
&RelayData {
|
||||
required_para_header: 120,
|
||||
para_header_at_target: Some(105),
|
||||
para_header_at_source: None,
|
||||
relay_header_at_source: 800,
|
||||
relay_header_at_target: 780,
|
||||
para_header_at_relay_header_at_target: Some(HeaderId(105, 105)),
|
||||
},
|
||||
RelayState::Idle,
|
||||
),
|
||||
RelayState::Idle,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relay_waits_for_required_para_header_to_appear_at_source_2() {
|
||||
assert_eq!(
|
||||
select_headers_to_relay(
|
||||
&RelayData {
|
||||
required_para_header: 120,
|
||||
para_header_at_target: Some(105),
|
||||
para_header_at_source: Some(HeaderId(110, 110)),
|
||||
relay_header_at_source: 800,
|
||||
relay_header_at_target: 780,
|
||||
para_header_at_relay_header_at_target: Some(HeaderId(105, 105)),
|
||||
},
|
||||
RelayState::Idle,
|
||||
),
|
||||
RelayState::Idle,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relay_starts_relaying_relay_header_when_new_para_header_is_requested() {
|
||||
assert_eq!(
|
||||
select_headers_to_relay(
|
||||
&RelayData {
|
||||
required_para_header: 120,
|
||||
para_header_at_target: Some(105),
|
||||
para_header_at_source: Some(HeaderId(125, 125)),
|
||||
relay_header_at_source: 800,
|
||||
relay_header_at_target: 780,
|
||||
para_header_at_relay_header_at_target: Some(HeaderId(105, 105)),
|
||||
},
|
||||
RelayState::Idle,
|
||||
),
|
||||
RelayState::RelayingRelayHeader(800),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relay_starts_relaying_para_header_when_new_para_header_is_requested() {
|
||||
assert_eq!(
|
||||
select_headers_to_relay(
|
||||
&RelayData {
|
||||
required_para_header: 120,
|
||||
para_header_at_target: Some(105),
|
||||
para_header_at_source: Some(HeaderId(125, 125)),
|
||||
relay_header_at_source: 800,
|
||||
relay_header_at_target: 800,
|
||||
para_header_at_relay_header_at_target: Some(HeaderId(125, 125)),
|
||||
},
|
||||
RelayState::Idle,
|
||||
),
|
||||
RelayState::RelayingParaHeader(HeaderId(125, 125)),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relay_goes_idle_when_parachain_is_deregistered() {
|
||||
assert_eq!(
|
||||
select_headers_to_relay::<i32, _, _>(
|
||||
&RelayData {
|
||||
required_para_header: 120,
|
||||
para_header_at_target: Some(105),
|
||||
para_header_at_source: None,
|
||||
relay_header_at_source: 800,
|
||||
relay_header_at_target: 800,
|
||||
para_header_at_relay_header_at_target: None,
|
||||
},
|
||||
RelayState::RelayingRelayHeader(800),
|
||||
),
|
||||
RelayState::Idle,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relay_starts_relaying_first_parachain_header() {
|
||||
assert_eq!(
|
||||
select_headers_to_relay::<i32, _, _>(
|
||||
&RelayData {
|
||||
required_para_header: 0,
|
||||
para_header_at_target: None,
|
||||
para_header_at_source: Some(HeaderId(125, 125)),
|
||||
relay_header_at_source: 800,
|
||||
relay_header_at_target: 800,
|
||||
para_header_at_relay_header_at_target: Some(HeaderId(125, 125)),
|
||||
},
|
||||
RelayState::Idle,
|
||||
),
|
||||
RelayState::RelayingParaHeader(HeaderId(125, 125)),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relay_starts_relaying_relay_header_to_relay_first_parachain_header() {
|
||||
assert_eq!(
|
||||
select_headers_to_relay::<i32, _, _>(
|
||||
&RelayData {
|
||||
required_para_header: 0,
|
||||
para_header_at_target: None,
|
||||
para_header_at_source: Some(HeaderId(125, 125)),
|
||||
relay_header_at_source: 800,
|
||||
relay_header_at_target: 700,
|
||||
para_header_at_relay_header_at_target: Some(HeaderId(125, 125)),
|
||||
},
|
||||
RelayState::Idle,
|
||||
),
|
||||
RelayState::RelayingRelayHeader(800),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
// 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/>.
|
||||
|
||||
//! Types and functions intended to ease adding of new Substrate -> Substrate
|
||||
//! parachain finality proofs synchronization pipelines.
|
||||
|
||||
use async_trait::async_trait;
|
||||
use bp_polkadot_core::parachains::{ParaHash, ParaHeadsProof, ParaId};
|
||||
use pallet_bridge_parachains::{
|
||||
Call as BridgeParachainsCall, Config as BridgeParachainsConfig, RelayBlockHash,
|
||||
RelayBlockHasher, RelayBlockNumber,
|
||||
};
|
||||
use parachains_relay::ParachainsPipeline;
|
||||
use relay_substrate_client::{CallOf, Chain, ChainWithTransactions, HeaderIdOf, RelayChain};
|
||||
use std::{fmt::Debug, marker::PhantomData};
|
||||
|
||||
pub mod source;
|
||||
pub mod target;
|
||||
|
||||
/// Substrate -> Substrate parachain finality proofs synchronization pipeline.
|
||||
///
|
||||
/// This is currently restricted to the single parachain, because it is how it
|
||||
/// will be used (at least) initially.
|
||||
#[async_trait]
|
||||
pub trait SubstrateParachainsPipeline: 'static + Clone + Debug + Send + Sync {
|
||||
/// Headers of this parachain are submitted to the `Self::TargetChain`.
|
||||
type SourceParachain: Chain;
|
||||
/// Relay chain that is storing headers of `Self::SourceParachain`.
|
||||
type SourceRelayChain: RelayChain;
|
||||
/// Target chain where `Self::SourceParachain` headers are submitted.
|
||||
type TargetChain: ChainWithTransactions;
|
||||
|
||||
/// How submit parachains heads call is built?
|
||||
type SubmitParachainHeadsCallBuilder: SubmitParachainHeadsCallBuilder<Self>;
|
||||
|
||||
/// Id of the `Self::SourceParachain`, used for registration in `Self::SourceRelayChain`.
|
||||
const SOURCE_PARACHAIN_PARA_ID: u32;
|
||||
}
|
||||
|
||||
/// Adapter that allows all `SubstrateParachainsPipeline` to act as `ParachainsPipeline`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ParachainsPipelineAdapter<P: SubstrateParachainsPipeline> {
|
||||
_phantom: PhantomData<P>,
|
||||
}
|
||||
|
||||
impl<P: SubstrateParachainsPipeline> ParachainsPipeline for ParachainsPipelineAdapter<P> {
|
||||
type SourceChain = P::SourceRelayChain;
|
||||
type TargetChain = P::TargetChain;
|
||||
}
|
||||
|
||||
/// Different ways of building `submit_parachain_heads` calls.
|
||||
pub trait SubmitParachainHeadsCallBuilder<P: SubstrateParachainsPipeline>:
|
||||
'static + Send + Sync
|
||||
{
|
||||
/// Given parachains and their heads proof, build call of `submit_parachain_heads`
|
||||
/// function of bridge parachains module at the target chain.
|
||||
fn build_submit_parachain_heads_call(
|
||||
at_relay_block: HeaderIdOf<P::SourceRelayChain>,
|
||||
parachains: Vec<(ParaId, ParaHash)>,
|
||||
parachain_heads_proof: ParaHeadsProof,
|
||||
) -> CallOf<P::TargetChain>;
|
||||
}
|
||||
|
||||
/// Building `submit_parachain_heads` call when you have direct access to the target
|
||||
/// chain runtime.
|
||||
pub struct DirectSubmitParachainHeadsCallBuilder<P, R, I> {
|
||||
_phantom: PhantomData<(P, R, I)>,
|
||||
}
|
||||
|
||||
impl<P, R, I> SubmitParachainHeadsCallBuilder<P> for DirectSubmitParachainHeadsCallBuilder<P, R, I>
|
||||
where
|
||||
P: SubstrateParachainsPipeline,
|
||||
P::SourceRelayChain: Chain<Hash = RelayBlockHash, BlockNumber = RelayBlockNumber>,
|
||||
R: BridgeParachainsConfig<I> + Send + Sync,
|
||||
I: 'static + Send + Sync,
|
||||
R::BridgedChain: bp_runtime::Chain<
|
||||
BlockNumber = RelayBlockNumber,
|
||||
Hash = RelayBlockHash,
|
||||
Hasher = RelayBlockHasher,
|
||||
>,
|
||||
CallOf<P::TargetChain>: From<BridgeParachainsCall<R, I>>,
|
||||
{
|
||||
fn build_submit_parachain_heads_call(
|
||||
at_relay_block: HeaderIdOf<P::SourceRelayChain>,
|
||||
parachains: Vec<(ParaId, ParaHash)>,
|
||||
parachain_heads_proof: ParaHeadsProof,
|
||||
) -> CallOf<P::TargetChain> {
|
||||
BridgeParachainsCall::<R, I>::submit_parachain_heads {
|
||||
at_relay_block: (at_relay_block.0, at_relay_block.1),
|
||||
parachains,
|
||||
parachain_heads_proof,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
// 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/>.
|
||||
|
||||
//! Parachain heads source.
|
||||
|
||||
use crate::parachains::{ParachainsPipelineAdapter, SubstrateParachainsPipeline};
|
||||
|
||||
use async_std::sync::{Arc, Mutex};
|
||||
use async_trait::async_trait;
|
||||
use bp_parachains::parachain_head_storage_key_at_source;
|
||||
use bp_polkadot_core::parachains::{ParaHash, ParaHead, ParaHeadsProof, ParaId};
|
||||
use bp_runtime::HeaderIdProvider;
|
||||
use codec::Decode;
|
||||
use parachains_relay::{
|
||||
parachains_loop::{AvailableHeader, SourceClient},
|
||||
parachains_loop_metrics::ParachainsLoopMetrics,
|
||||
};
|
||||
use relay_substrate_client::{
|
||||
Chain, Client, Error as SubstrateError, HeaderIdOf, HeaderOf, RelayChain,
|
||||
};
|
||||
use relay_utils::relay_loop::Client as RelayClient;
|
||||
|
||||
/// Shared updatable reference to the maximal parachain header id that we want to sync from the
|
||||
/// source.
|
||||
pub type RequiredHeaderIdRef<C> = Arc<Mutex<AvailableHeader<HeaderIdOf<C>>>>;
|
||||
|
||||
/// Substrate client as parachain heads source.
|
||||
#[derive(Clone)]
|
||||
pub struct ParachainsSource<P: SubstrateParachainsPipeline> {
|
||||
client: Client<P::SourceRelayChain>,
|
||||
max_head_id: RequiredHeaderIdRef<P::SourceParachain>,
|
||||
}
|
||||
|
||||
impl<P: SubstrateParachainsPipeline> ParachainsSource<P> {
|
||||
/// Creates new parachains source client.
|
||||
pub fn new(
|
||||
client: Client<P::SourceRelayChain>,
|
||||
max_head_id: RequiredHeaderIdRef<P::SourceParachain>,
|
||||
) -> Self {
|
||||
ParachainsSource { client, max_head_id }
|
||||
}
|
||||
|
||||
/// Returns reference to the underlying RPC client.
|
||||
pub fn client(&self) -> &Client<P::SourceRelayChain> {
|
||||
&self.client
|
||||
}
|
||||
|
||||
/// Return decoded head of given parachain.
|
||||
pub async fn on_chain_para_head_id(
|
||||
&self,
|
||||
at_block: HeaderIdOf<P::SourceRelayChain>,
|
||||
para_id: ParaId,
|
||||
) -> Result<Option<HeaderIdOf<P::SourceParachain>>, SubstrateError> {
|
||||
let storage_key =
|
||||
parachain_head_storage_key_at_source(P::SourceRelayChain::PARAS_PALLET_NAME, para_id);
|
||||
let para_head = self.client.raw_storage_value(storage_key, Some(at_block.1)).await?;
|
||||
let para_head = para_head.map(|h| ParaHead::decode(&mut &h.0[..])).transpose()?;
|
||||
let para_head = match para_head {
|
||||
Some(para_head) => para_head,
|
||||
None => return Ok(None),
|
||||
};
|
||||
let para_head: HeaderOf<P::SourceParachain> = Decode::decode(&mut ¶_head.0[..])?;
|
||||
Ok(Some(para_head.id()))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<P: SubstrateParachainsPipeline> RelayClient for ParachainsSource<P> {
|
||||
type Error = SubstrateError;
|
||||
|
||||
async fn reconnect(&mut self) -> Result<(), SubstrateError> {
|
||||
self.client.reconnect().await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<P: SubstrateParachainsPipeline> SourceClient<ParachainsPipelineAdapter<P>>
|
||||
for ParachainsSource<P>
|
||||
where
|
||||
P::SourceParachain: Chain<Hash = ParaHash>,
|
||||
{
|
||||
async fn ensure_synced(&self) -> Result<bool, Self::Error> {
|
||||
match self.client.ensure_synced().await {
|
||||
Ok(_) => Ok(true),
|
||||
Err(SubstrateError::ClientNotSynced(_)) => Ok(false),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
async fn parachain_head(
|
||||
&self,
|
||||
at_block: HeaderIdOf<P::SourceRelayChain>,
|
||||
metrics: Option<&ParachainsLoopMetrics>,
|
||||
para_id: ParaId,
|
||||
) -> Result<AvailableHeader<ParaHash>, Self::Error> {
|
||||
// we don't need to support many parachains now
|
||||
if para_id.0 != P::SOURCE_PARACHAIN_PARA_ID {
|
||||
return Err(SubstrateError::Custom(format!(
|
||||
"Parachain id {} is not matching expected {}",
|
||||
para_id.0,
|
||||
P::SOURCE_PARACHAIN_PARA_ID,
|
||||
)))
|
||||
}
|
||||
|
||||
let mut para_head_id = AvailableHeader::Missing;
|
||||
if let Some(on_chain_para_head_id) = self.on_chain_para_head_id(at_block, para_id).await? {
|
||||
// Never return head that is larger than requested. This way we'll never sync
|
||||
// headers past `max_header_id`.
|
||||
para_head_id = match *self.max_head_id.lock().await {
|
||||
AvailableHeader::Unavailable => AvailableHeader::Unavailable,
|
||||
AvailableHeader::Missing => {
|
||||
// `max_header_id` is not set. There is no limit.
|
||||
AvailableHeader::Available(on_chain_para_head_id)
|
||||
},
|
||||
AvailableHeader::Available(max_head_id) => {
|
||||
// We report at most `max_header_id`.
|
||||
AvailableHeader::Available(std::cmp::min(on_chain_para_head_id, max_head_id))
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
if let (Some(metrics), AvailableHeader::Available(para_head_id)) = (metrics, para_head_id) {
|
||||
metrics.update_best_parachain_block_at_source(para_id, para_head_id.0);
|
||||
}
|
||||
|
||||
Ok(para_head_id.map(|para_head_id| para_head_id.1))
|
||||
}
|
||||
|
||||
async fn prove_parachain_heads(
|
||||
&self,
|
||||
at_block: HeaderIdOf<P::SourceRelayChain>,
|
||||
parachains: &[ParaId],
|
||||
) -> Result<(ParaHeadsProof, Vec<ParaHash>), Self::Error> {
|
||||
let parachain = ParaId(P::SOURCE_PARACHAIN_PARA_ID);
|
||||
if parachains != [parachain] {
|
||||
return Err(SubstrateError::Custom(format!(
|
||||
"Trying to prove unexpected parachains {:?}. Expected {:?}",
|
||||
parachains, parachain,
|
||||
)))
|
||||
}
|
||||
|
||||
let parachain = parachains[0];
|
||||
let storage_key =
|
||||
parachain_head_storage_key_at_source(P::SourceRelayChain::PARAS_PALLET_NAME, parachain);
|
||||
let parachain_heads_proof = self
|
||||
.client
|
||||
.prove_storage(vec![storage_key.clone()], at_block.1)
|
||||
.await?
|
||||
.into_iter_nodes()
|
||||
.collect();
|
||||
|
||||
// why we're reading parachain head here once again (it has already been read at the
|
||||
// `parachain_head`)? that's because `parachain_head` sometimes returns obsolete parachain
|
||||
// head and loop sometimes asks to prove this obsolete head and gets other (actual) head
|
||||
// instead
|
||||
//
|
||||
// => since we want to provide proper hashes in our `submit_parachain_heads` call, we're
|
||||
// rereading actual value here
|
||||
let parachain_head = self
|
||||
.client
|
||||
.raw_storage_value(storage_key, Some(at_block.1))
|
||||
.await?
|
||||
.map(|h| ParaHead::decode(&mut &h.0[..]))
|
||||
.transpose()?
|
||||
.ok_or_else(|| {
|
||||
SubstrateError::Custom(format!(
|
||||
"Failed to read expected parachain {:?} head at {:?}",
|
||||
parachain, at_block
|
||||
))
|
||||
})?;
|
||||
let parachain_head_hash = parachain_head.hash();
|
||||
|
||||
Ok((ParaHeadsProof(parachain_heads_proof), vec![parachain_head_hash]))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
// 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/>.
|
||||
|
||||
//! Parachain heads target.
|
||||
|
||||
use crate::{
|
||||
parachains::{
|
||||
ParachainsPipelineAdapter, SubmitParachainHeadsCallBuilder, SubstrateParachainsPipeline,
|
||||
},
|
||||
TransactionParams,
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use bp_parachains::{BestParaHeadHash, ImportedParaHeadsKeyProvider, ParasInfoKeyProvider};
|
||||
use bp_polkadot_core::parachains::{ParaHash, ParaHeadsProof, ParaId};
|
||||
use bp_runtime::HeaderIdProvider;
|
||||
use codec::Decode;
|
||||
use parachains_relay::{
|
||||
parachains_loop::TargetClient, parachains_loop_metrics::ParachainsLoopMetrics,
|
||||
};
|
||||
use relay_substrate_client::{
|
||||
AccountIdOf, AccountKeyPairOf, BlockNumberOf, Chain, Client, Error as SubstrateError, HashOf,
|
||||
HeaderIdOf, HeaderOf, RelayChain, SignParam, TransactionEra, TransactionTracker,
|
||||
UnsignedTransaction,
|
||||
};
|
||||
use relay_utils::{relay_loop::Client as RelayClient, HeaderId};
|
||||
use sp_core::{Bytes, Pair};
|
||||
use sp_runtime::traits::Header as HeaderT;
|
||||
|
||||
/// Substrate client as parachain heads source.
|
||||
pub struct ParachainsTarget<P: SubstrateParachainsPipeline> {
|
||||
client: Client<P::TargetChain>,
|
||||
transaction_params: TransactionParams<AccountKeyPairOf<P::TargetChain>>,
|
||||
}
|
||||
|
||||
impl<P: SubstrateParachainsPipeline> ParachainsTarget<P> {
|
||||
/// Creates new parachains target client.
|
||||
pub fn new(
|
||||
client: Client<P::TargetChain>,
|
||||
transaction_params: TransactionParams<AccountKeyPairOf<P::TargetChain>>,
|
||||
) -> Self {
|
||||
ParachainsTarget { client, transaction_params }
|
||||
}
|
||||
|
||||
/// Returns reference to the underlying RPC client.
|
||||
pub fn client(&self) -> &Client<P::TargetChain> {
|
||||
&self.client
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: SubstrateParachainsPipeline> Clone for ParachainsTarget<P> {
|
||||
fn clone(&self) -> Self {
|
||||
ParachainsTarget {
|
||||
client: self.client.clone(),
|
||||
transaction_params: self.transaction_params.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<P: SubstrateParachainsPipeline> RelayClient for ParachainsTarget<P> {
|
||||
type Error = SubstrateError;
|
||||
|
||||
async fn reconnect(&mut self) -> Result<(), SubstrateError> {
|
||||
self.client.reconnect().await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<P> TargetClient<ParachainsPipelineAdapter<P>> for ParachainsTarget<P>
|
||||
where
|
||||
P: SubstrateParachainsPipeline,
|
||||
AccountIdOf<P::TargetChain>: From<<AccountKeyPairOf<P::TargetChain> as Pair>::Public>,
|
||||
{
|
||||
type TransactionTracker = TransactionTracker<P::TargetChain, Client<P::TargetChain>>;
|
||||
|
||||
async fn best_block(&self) -> Result<HeaderIdOf<P::TargetChain>, Self::Error> {
|
||||
let best_header = self.client.best_header().await?;
|
||||
let best_id = best_header.id();
|
||||
|
||||
Ok(best_id)
|
||||
}
|
||||
|
||||
async fn best_finalized_source_block(
|
||||
&self,
|
||||
at_block: &HeaderIdOf<P::TargetChain>,
|
||||
) -> Result<HeaderIdOf<P::SourceRelayChain>, Self::Error> {
|
||||
let encoded_best_finalized_source_block = self
|
||||
.client
|
||||
.state_call(
|
||||
P::SourceRelayChain::BEST_FINALIZED_HEADER_ID_METHOD.into(),
|
||||
Bytes(Vec::new()),
|
||||
Some(at_block.1),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Option::<HeaderId<HashOf<P::SourceRelayChain>, BlockNumberOf<P::SourceRelayChain>>>::decode(
|
||||
&mut &encoded_best_finalized_source_block.0[..],
|
||||
)
|
||||
.map_err(SubstrateError::ResponseParseFailed)?
|
||||
.map(Ok)
|
||||
.unwrap_or(Err(SubstrateError::BridgePalletIsNotInitialized))
|
||||
}
|
||||
|
||||
async fn parachain_head(
|
||||
&self,
|
||||
at_block: HeaderIdOf<P::TargetChain>,
|
||||
metrics: Option<&ParachainsLoopMetrics>,
|
||||
para_id: ParaId,
|
||||
) -> Result<Option<BestParaHeadHash>, Self::Error> {
|
||||
let best_para_head_hash: Option<BestParaHeadHash> = self
|
||||
.client
|
||||
.storage_map_value::<ParasInfoKeyProvider>(
|
||||
P::SourceRelayChain::PARACHAINS_FINALITY_PALLET_NAME,
|
||||
¶_id,
|
||||
Some(at_block.1),
|
||||
)
|
||||
.await?
|
||||
.map(|para_info| para_info.best_head_hash);
|
||||
|
||||
if let (Some(metrics), Some(best_para_head_hash)) = (metrics, &best_para_head_hash) {
|
||||
let imported_para_head = self
|
||||
.client
|
||||
.storage_double_map_value::<ImportedParaHeadsKeyProvider>(
|
||||
P::SourceRelayChain::PARACHAINS_FINALITY_PALLET_NAME,
|
||||
¶_id,
|
||||
&best_para_head_hash.head_hash,
|
||||
Some(at_block.1),
|
||||
)
|
||||
.await
|
||||
.and_then(|maybe_encoded_head| match maybe_encoded_head {
|
||||
Some(encoded_head) =>
|
||||
HeaderOf::<P::SourceParachain>::decode(&mut &encoded_head.0[..])
|
||||
.map(Some)
|
||||
.map_err(Self::Error::ResponseParseFailed),
|
||||
None => Ok(None),
|
||||
})
|
||||
.map_err(|e| {
|
||||
log::error!(
|
||||
target: "bridge-metrics",
|
||||
"Failed to read or decode {} parachain header at {}: {:?}. Metric will have obsolete value",
|
||||
P::SourceParachain::NAME,
|
||||
P::TargetChain::NAME,
|
||||
e,
|
||||
);
|
||||
e
|
||||
})
|
||||
.unwrap_or(None);
|
||||
if let Some(imported_para_head) = imported_para_head {
|
||||
metrics
|
||||
.update_best_parachain_block_at_target(para_id, *imported_para_head.number());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(best_para_head_hash)
|
||||
}
|
||||
|
||||
async fn submit_parachain_heads_proof(
|
||||
&self,
|
||||
at_relay_block: HeaderIdOf<P::SourceRelayChain>,
|
||||
updated_parachains: Vec<(ParaId, ParaHash)>,
|
||||
proof: ParaHeadsProof,
|
||||
) -> Result<Self::TransactionTracker, Self::Error> {
|
||||
let genesis_hash = *self.client.genesis_hash();
|
||||
let transaction_params = self.transaction_params.clone();
|
||||
let (spec_version, transaction_version) = self.client.simple_runtime_version().await?;
|
||||
let call = P::SubmitParachainHeadsCallBuilder::build_submit_parachain_heads_call(
|
||||
at_relay_block,
|
||||
updated_parachains,
|
||||
proof,
|
||||
);
|
||||
self.client
|
||||
.submit_and_watch_signed_extrinsic(
|
||||
self.transaction_params.signer.public().into(),
|
||||
SignParam::<P::TargetChain> {
|
||||
spec_version,
|
||||
transaction_version,
|
||||
genesis_hash,
|
||||
signer: transaction_params.signer,
|
||||
},
|
||||
move |best_block_id, transaction_nonce| {
|
||||
Ok(UnsignedTransaction::new(call.into(), transaction_nonce)
|
||||
.era(TransactionEra::new(best_block_id, transaction_params.mortality)))
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
name = "messages-relay"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
async-std = { version = "1.6.5", features = ["attributes"] }
|
||||
async-trait = "0.1"
|
||||
futures = "0.3.5"
|
||||
hex = "0.4"
|
||||
log = "0.4.17"
|
||||
num-traits = "0.2"
|
||||
parking_lot = "0.11.0"
|
||||
|
||||
# Bridge Dependencies
|
||||
|
||||
bp-messages = { path = "../../primitives/messages" }
|
||||
bp-runtime = { path = "../../primitives/runtime" }
|
||||
finality-relay = { path = "../finality" }
|
||||
relay-utils = { path = "../utils" }
|
||||
|
||||
sp-arithmetic = { git = "https://github.com/paritytech/substrate", branch = "master" }
|
||||
@@ -0,0 +1,37 @@
|
||||
// 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/>.
|
||||
|
||||
//! Relaying [`pallet-bridge-messages`](../pallet_bridge_messages/index.html) application specific
|
||||
//! data. Message lane allows sending arbitrary messages between bridged chains. This
|
||||
//! module provides entrypoint that starts reading messages from given message lane
|
||||
//! of source chain and submits proof-of-message-at-source-chain transactions to the
|
||||
//! target chain. Additionally, proofs-of-messages-delivery are sent back from the
|
||||
//! target chain to the source chain.
|
||||
|
||||
// required for futures::select!
|
||||
#![recursion_limit = "1024"]
|
||||
#![warn(missing_docs)]
|
||||
|
||||
mod metrics;
|
||||
|
||||
pub mod message_lane;
|
||||
pub mod message_lane_loop;
|
||||
|
||||
mod message_race_delivery;
|
||||
mod message_race_limits;
|
||||
mod message_race_loop;
|
||||
mod message_race_receiving;
|
||||
mod message_race_strategy;
|
||||
Loaded 100 of 357 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user