Skip to content

Commit

Permalink
Substrate relay guards (paritytech#470)
Browse files Browse the repository at this point in the history
* substrate relay guards

* checked time condition

* ChainWithBalances

* removed obsolete comment

* Update relays/substrate-client/src/chain.rs

Co-authored-by: Tomasz Drwięga <tomusdrw@users.noreply.github.com>

* trailing space

Co-authored-by: Tomasz Drwięga <tomusdrw@users.noreply.github.com>
  • Loading branch information
2 people authored and bkchr committed Apr 10, 2024
1 parent cc1da1b commit b027c81
Show file tree
Hide file tree
Showing 12 changed files with 498 additions and 20 deletions.
2 changes: 1 addition & 1 deletion bridges/primitives/runtime/src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use sp_runtime::traits::{
use sp_std::str::FromStr;

/// Minimal Substrate-based chain representation that may be used from no_std environment.
pub trait Chain {
pub trait Chain: Send + Sync + 'static {
/// A type that fulfills the abstract idea of what a Substrate block number is.
// Constraits come from the associated Number type of `sp_runtime::traits::Header`
// See here for more info:
Expand Down
1 change: 1 addition & 0 deletions bridges/relays/millau-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ millau-runtime = { path = "../../bin/millau/runtime" }

# Substrate Dependencies

frame-support = "2.0"
frame-system = "2.0"
pallet-transaction-payment = "2.0"
sp-core = "2.0"
Expand Down
19 changes: 17 additions & 2 deletions bridges/relays/millau-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,13 @@
use codec::Encode;
use headers_relay::sync_types::SourceHeader;
use relay_substrate_client::{Chain, ChainBase, Client, TransactionSignScheme};
use sp_core::Pair;
use relay_substrate_client::{Chain, ChainBase, ChainWithBalances, Client, TransactionSignScheme};
use sp_core::{storage::StorageKey, Pair};
use sp_runtime::{
generic::SignedPayload,
traits::{Header as HeaderT, IdentifyAccount},
};
use std::time::Duration;

/// Millau header id.
pub type HeaderId = relay_utils::HeaderId<millau_runtime::Hash, millau_runtime::BlockNumber>;
Expand All @@ -40,12 +41,26 @@ impl ChainBase for Millau {
}

impl Chain for Millau {
const NAME: &'static str = "Millau";
const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_secs(5);

type AccountId = millau_runtime::AccountId;
type Index = millau_runtime::Index;
type SignedBlock = millau_runtime::SignedBlock;
type Call = millau_runtime::Call;
}

impl ChainWithBalances for Millau {
type NativeBalance = millau_runtime::Balance;

fn account_info_storage_key(account_id: &Self::AccountId) -> StorageKey {
use frame_support::storage::generator::StorageMap;
StorageKey(frame_system::Account::<millau_runtime::Runtime>::storage_map_final_key(
account_id,
))
}
}

impl TransactionSignScheme for Millau {
type Chain = Millau;
type AccountKeyPair = sp_core::sr25519::Pair;
Expand Down
1 change: 1 addition & 0 deletions bridges/relays/rialto-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ rialto-runtime = { path = "../../bin/rialto/runtime" }
# Substrate Dependencies

frame-system = "2.0"
frame-support = "2.0"
pallet-transaction-payment = "2.0"
sp-core = "2.0"
sp-keyring = "2.0"
Expand Down
19 changes: 17 additions & 2 deletions bridges/relays/rialto-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,13 @@
use codec::Encode;
use headers_relay::sync_types::SourceHeader;
use relay_substrate_client::{Chain, ChainBase, Client, TransactionSignScheme};
use sp_core::Pair;
use relay_substrate_client::{Chain, ChainBase, ChainWithBalances, Client, TransactionSignScheme};
use sp_core::{storage::StorageKey, Pair};
use sp_runtime::{
generic::SignedPayload,
traits::{Header as HeaderT, IdentifyAccount},
};
use std::time::Duration;

pub use rialto_runtime::BridgeMillauCall;

Expand All @@ -42,12 +43,26 @@ impl ChainBase for Rialto {
}

impl Chain for Rialto {
const NAME: &'static str = "Rialto";
const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_secs(5);

type AccountId = rialto_runtime::AccountId;
type Index = rialto_runtime::Index;
type SignedBlock = rialto_runtime::SignedBlock;
type Call = rialto_runtime::Call;
}

impl ChainWithBalances for Rialto {
type NativeBalance = rialto_runtime::Balance;

fn account_info_storage_key(account_id: &Self::AccountId) -> StorageKey {
use frame_support::storage::generator::StorageMap;
StorageKey(frame_system::Account::<rialto_runtime::Runtime>::storage_map_final_key(
account_id,
))
}
}

impl TransactionSignScheme for Rialto {
type Chain = Rialto;
type AccountKeyPair = sp_core::sr25519::Pair;
Expand Down
8 changes: 7 additions & 1 deletion bridges/relays/substrate-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ edition = "2018"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"

[dependencies]
async-std = "1.6.5"
async-trait = "0.1.40"
codec = { package = "parity-scale-codec", version = "1.3.4" }
jsonrpsee = { git = "https://github.com/svyatonik/jsonrpsee.git", branch = "shared-client-in-rpc-api", default-features = false, features = ["ws"] }
log = "0.4.11"
num-traits = "0.2"
rand = "0.7"

# Bridge dependencies

Expand All @@ -22,6 +24,10 @@ relay-utils = { path = "../utils" }

frame-support = "2.0"
frame-system = "2.0"
pallet-balances = "2.0"
sp-core = "2.0"
sp-runtime = "2.0"
sp-std = "2.0"
sp-version = "2.0"

#[dev-dependencies]
futures = "0.3.7"
28 changes: 26 additions & 2 deletions bridges/relays/substrate-client/src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,24 @@ use crate::client::Client;
use bp_runtime::Chain as ChainBase;
use frame_support::Parameter;
use jsonrpsee::common::{DeserializeOwned, Serialize};
use sp_core::Pair;
use num_traits::{CheckedSub, Zero};
use sp_core::{storage::StorageKey, Pair};
use sp_runtime::{
generic::SignedBlock,
traits::{AtLeast32Bit, Dispatchable, MaybeDisplay, MaybeSerialize, MaybeSerializeDeserialize, Member},
Justification,
};
use sp_std::fmt::Debug;
use std::{fmt::Debug, time::Duration};

/// Substrate-based chain from minimal relay-client point of view.
pub trait Chain: ChainBase {
/// Chain name.
const NAME: &'static str;
/// Average block interval.
///
/// How often blocks are produced on that chain. It's suggested to set this value to match the block time of the chain.
const AVERAGE_BLOCK_INTERVAL: Duration;

/// The user account identifier type for the runtime.
type AccountId: Parameter + Member + MaybeSerializeDeserialize + Debug + MaybeDisplay + Ord + Default;
/// Account index (aka nonce) type. This stores the number of previous transactions associated
Expand All @@ -40,6 +48,16 @@ pub trait Chain: ChainBase {
type Call: Dispatchable + Debug;
}

/// Substrate-based chain with `frame_system::Trait::AccountData` set to
/// the `pallet_balances::AccountData<NativeBalance>`.
pub trait ChainWithBalances: Chain {
/// Balance of an account in native tokens.
type NativeBalance: Parameter + Member + DeserializeOwned + Clone + Copy + CheckedSub + PartialOrd + Zero;

/// Return runtime storage key for getting `frame_system::AccountInfo` of given account.
fn account_info_storage_key(account_id: &Self::AccountId) -> StorageKey;
}

/// Block with justification.
pub trait BlockWithJustification {
/// Return block justification, if known.
Expand All @@ -64,6 +82,12 @@ pub trait TransactionSignScheme {
) -> Self::SignedTransaction;
}

impl BlockWithJustification for () {
fn justification(&self) -> Option<&Justification> {
None
}
}

impl<Block> BlockWithJustification for SignedBlock<Block> {
fn justification(&self) -> Option<&Justification> {
self.justification.as_ref()
Expand Down
53 changes: 43 additions & 10 deletions bridges/relays/substrate-client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,21 @@

//! Substrate node client.
use crate::chain::Chain;
use crate::chain::{Chain, ChainWithBalances};
use crate::error::Error;
use crate::rpc::Substrate;
use crate::{ConnectionParams, Result};

use codec::Decode;
use frame_system::AccountInfo;
use jsonrpsee::common::DeserializeOwned;
use jsonrpsee::raw::RawClient;
use jsonrpsee::transport::ws::WsTransportClient;
use jsonrpsee::{client::Subscription, Client as RpcClient};
use num_traits::Zero;
use pallet_balances::AccountData;
use sp_core::Bytes;
use sp_version::RuntimeVersion;

const SUB_API_GRANDPA_AUTHORITIES: &str = "GrandpaApi_grandpa_authorities";

Expand Down Expand Up @@ -69,18 +74,17 @@ impl<C: Chain> Client<C> {
}
}

impl<C: Chain> Client<C>
where
C::Header: DeserializeOwned,
C::Index: DeserializeOwned,
{
impl<C: Chain> Client<C> {
/// Return hash of the genesis block.
pub fn genesis_hash(&self) -> &C::Hash {
&self.genesis_hash
}

/// Returns the best Substrate header.
pub async fn best_header(&self) -> Result<C::Header> {
pub async fn best_header(&self) -> Result<C::Header>
where
C::Header: DeserializeOwned,
{
Ok(Substrate::<C, _, _>::chain_get_header(&self.client, None).await?)
}

Expand All @@ -90,7 +94,10 @@ where
}

/// Get a Substrate header by its hash.
pub async fn header_by_hash(&self, block_hash: C::Hash) -> Result<C::Header> {
pub async fn header_by_hash(&self, block_hash: C::Hash) -> Result<C::Header>
where
C::Header: DeserializeOwned,
{
Ok(Substrate::<C, _, _>::chain_get_header(&self.client, block_hash).await?)
}

Expand All @@ -100,15 +107,41 @@ where
}

/// Get a Substrate header by its number.
pub async fn header_by_number(&self, block_number: C::BlockNumber) -> Result<C::Header> {
pub async fn header_by_number(&self, block_number: C::BlockNumber) -> Result<C::Header>
where
C::Header: DeserializeOwned,
{
let block_hash = Self::block_hash_by_number(self, block_number).await?;
Ok(Self::header_by_hash(self, block_hash).await?)
}

/// Return runtime version.
pub async fn runtime_version(&self) -> Result<RuntimeVersion> {
Ok(Substrate::<C, _, _>::runtime_version(&self.client).await?)
}

/// Return native tokens balance of the account.
pub async fn free_native_balance(&self, account: C::AccountId) -> Result<C::NativeBalance>
where
C: ChainWithBalances,
{
let storage_key = C::account_info_storage_key(&account);
let encoded_account_data = Substrate::<C, _, _>::get_storage(&self.client, storage_key)
.await?
.ok_or(Error::AccountDoesNotExist)?;
let decoded_account_data =
AccountInfo::<C::Index, AccountData<C::NativeBalance>>::decode(&mut &encoded_account_data.0[..])
.map_err(Error::ResponseParseFailed)?;
Ok(decoded_account_data.data.free)
}

/// Get the nonce of the given Substrate account.
///
/// Note: It's the caller's responsibility to make sure `account` is a valid ss58 address.
pub async fn next_account_index(&self, account: C::AccountId) -> Result<C::Index> {
pub async fn next_account_index(&self, account: C::AccountId) -> Result<C::Index>
where
C::Index: DeserializeOwned,
{
Ok(Substrate::<C, _, _>::system_account_next_index(&self.client, account).await?)
}

Expand Down
3 changes: 3 additions & 0 deletions bridges/relays/substrate-client/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ pub enum Error {
Request(RequestError),
/// The response from the server could not be SCALE decoded.
ResponseParseFailed(codec::Error),
/// Account does not exist on the chain.
AccountDoesNotExist,
}

impl From<WsNewDnsError> for Error {
Expand Down Expand Up @@ -66,6 +68,7 @@ impl ToString for Error {
Self::WsConnectionError(e) => e.to_string(),
Self::Request(e) => e.to_string(),
Self::ResponseParseFailed(e) => e.what().to_string(),
Self::AccountDoesNotExist => "Account does not exist on the chain".into(),
}
}
}
Loading

0 comments on commit b027c81

Please sign in to comment.