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,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
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user