// Copyright 2019-2020 Parity Technologies (UK) Ltd. // This file is part of Parity Bridges Common. // Parity Bridges Common is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity Bridges Common is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity Bridges Common. If not, see . //! Substrate node client. 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"; /// Opaque justifications subscription type. pub type JustificationsSubscription = Subscription; /// Opaque GRANDPA authorities set. pub type OpaqueGrandpaAuthoritiesSet = Vec; /// Substrate client type. /// /// Cloning Client is a cheap operation. #[derive(Clone)] pub struct Client { /// Substrate RPC client. client: RpcClient, /// Genesis block hash. genesis_hash: C::Hash, } impl std::fmt::Debug for Client { fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { fmt.debug_struct("Client") .field("genesis_hash", &self.genesis_hash) .finish() } } impl Client { /// Returns client that is able to call RPCs on Substrate node over websocket connection. pub async fn new(params: ConnectionParams) -> Result { let uri = format!("ws://{}:{}", params.host, params.port); let transport = WsTransportClient::new(&uri).await?; let raw_client = RawClient::new(transport); let client: RpcClient = raw_client.into(); let number: C::BlockNumber = Zero::zero(); let genesis_hash = Substrate::::chain_get_block_hash(&client, number).await?; Ok(Self { client, genesis_hash }) } } impl Client { /// 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 where C::Header: DeserializeOwned, { Ok(Substrate::::chain_get_header(&self.client, None).await?) } /// Get a Substrate block from its hash. pub async fn get_block(&self, block_hash: Option) -> Result { Ok(Substrate::::chain_get_block(&self.client, block_hash).await?) } /// Get a Substrate header by its hash. pub async fn header_by_hash(&self, block_hash: C::Hash) -> Result where C::Header: DeserializeOwned, { Ok(Substrate::::chain_get_header(&self.client, block_hash).await?) } /// Get a Substrate block hash by its number. pub async fn block_hash_by_number(&self, number: C::BlockNumber) -> Result { Ok(Substrate::::chain_get_block_hash(&self.client, number).await?) } /// Get a Substrate header by its number. pub async fn header_by_number(&self, block_number: C::BlockNumber) -> Result 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 { Ok(Substrate::::runtime_version(&self.client).await?) } /// Return native tokens balance of the account. pub async fn free_native_balance(&self, account: C::AccountId) -> Result where C: ChainWithBalances, { let storage_key = C::account_info_storage_key(&account); let encoded_account_data = Substrate::::get_storage(&self.client, storage_key) .await? .ok_or(Error::AccountDoesNotExist)?; let decoded_account_data = AccountInfo::>::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 { Ok(Substrate::::system_account_next_index(&self.client, account).await?) } /// Submit an extrinsic for inclusion in a block. /// /// Note: The given transaction does not need be SCALE encoded beforehand. pub async fn submit_extrinsic(&self, transaction: Bytes) -> Result { let tx_hash = Substrate::::author_submit_extrinsic(&self.client, transaction).await?; log::trace!(target: "bridge", "Sent transaction to Substrate node: {:?}", tx_hash); Ok(tx_hash) } /// Get the GRANDPA authority set at given block. pub async fn grandpa_authorities_set(&self, block: C::Hash) -> Result { let call = SUB_API_GRANDPA_AUTHORITIES.to_string(); let data = Bytes(Vec::new()); let encoded_response = Substrate::::state_call(&self.client, call, data, Some(block)).await?; let authority_list = encoded_response.0; Ok(authority_list) } /// Execute runtime call at given block. pub async fn state_call(&self, method: String, data: Bytes, at_block: Option) -> Result { Substrate::::state_call(&self.client, method, data, at_block) .await .map_err(Into::into) } /// Return new justifications stream. pub async fn subscribe_justifications(self) -> Result { Ok(self .client .subscribe( "grandpa_subscribeJustifications", jsonrpsee::common::Params::None, "grandpa_unsubscribeJustifications", ) .await?) } }