mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-12 04:11:07 +00:00
Extract RPC definitions from RPC crate. (#3502)
* Extract author API from the substrate-rpc crate. * Split out API from RPC. * Clean up naming. * Fix tests. * Shorten error translations. * Update Cargo.lock
This commit is contained in:
committed by
Svyatoslav Nikolsky
parent
4ff97bd856
commit
98f64b6b93
@@ -1,59 +0,0 @@
|
||||
// Copyright 2017-2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate 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.
|
||||
|
||||
// Substrate 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 Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
//! Error helpers for Chain RPC module.
|
||||
|
||||
use client;
|
||||
use crate::rpc;
|
||||
use crate::errors;
|
||||
|
||||
/// Chain RPC Result type.
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// Chain RPC errors.
|
||||
#[derive(Debug, derive_more::Display, derive_more::From)]
|
||||
pub enum Error {
|
||||
/// Client error.
|
||||
Client(client::error::Error),
|
||||
/// Other error type.
|
||||
Other(String),
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
match self {
|
||||
Error::Client(ref err) => Some(err),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Base error code for all chain errors.
|
||||
const BASE_ERROR: i64 = 3000;
|
||||
|
||||
impl From<Error> for rpc::Error {
|
||||
fn from(e: Error) -> Self {
|
||||
match e {
|
||||
Error::Other(message) => rpc::Error {
|
||||
code: rpc::ErrorCode::ServerError(BASE_ERROR + 1),
|
||||
message,
|
||||
data: None,
|
||||
},
|
||||
e => errors::internal(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,9 +16,6 @@
|
||||
|
||||
//! Substrate blockchain API.
|
||||
|
||||
pub mod error;
|
||||
pub mod number;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -26,79 +23,17 @@ use std::sync::Arc;
|
||||
use futures03::{future, StreamExt as _, TryStreamExt as _};
|
||||
|
||||
use client::{self, Client, BlockchainEvents};
|
||||
use crate::rpc::Result as RpcResult;
|
||||
use crate::rpc::futures::{stream, Future, Sink, Stream};
|
||||
use crate::subscriptions::Subscriptions;
|
||||
use jsonrpc_derive::rpc;
|
||||
use rpc::Result as RpcResult;
|
||||
use rpc::futures::{stream, Future, Sink, Stream};
|
||||
use api::Subscriptions;
|
||||
use jsonrpc_pubsub::{typed::Subscriber, SubscriptionId};
|
||||
use log::warn;
|
||||
use primitives::{H256, Blake2Hasher};
|
||||
use sr_primitives::generic::{BlockId, SignedBlock};
|
||||
use sr_primitives::traits::{Block as BlockT, Header, NumberFor};
|
||||
use self::error::Result;
|
||||
use self::error::{Error, Result};
|
||||
|
||||
pub use self::gen_client::Client as ChainClient;
|
||||
|
||||
/// Substrate blockchain API
|
||||
#[rpc]
|
||||
pub trait ChainApi<Number, Hash, Header, SignedBlock> {
|
||||
/// RPC metadata
|
||||
type Metadata;
|
||||
|
||||
/// Get header of a relay chain block.
|
||||
#[rpc(name = "chain_getHeader")]
|
||||
fn header(&self, hash: Option<Hash>) -> Result<Option<Header>>;
|
||||
|
||||
/// Get header and body of a relay chain block.
|
||||
#[rpc(name = "chain_getBlock")]
|
||||
fn block(&self, hash: Option<Hash>) -> Result<Option<SignedBlock>>;
|
||||
|
||||
/// Get hash of the n-th block in the canon chain.
|
||||
///
|
||||
/// By default returns latest block hash.
|
||||
#[rpc(name = "chain_getBlockHash", alias("chain_getHead"))]
|
||||
fn block_hash(&self, hash: Option<number::NumberOrHex<Number>>) -> Result<Option<Hash>>;
|
||||
|
||||
/// Get hash of the last finalized block in the canon chain.
|
||||
#[rpc(name = "chain_getFinalizedHead", alias("chain_getFinalisedHead"))]
|
||||
fn finalized_head(&self) -> Result<Hash>;
|
||||
|
||||
/// New head subscription
|
||||
#[pubsub(
|
||||
subscription = "chain_newHead",
|
||||
subscribe,
|
||||
name = "chain_subscribeNewHeads",
|
||||
alias("subscribe_newHead", "chain_subscribeNewHead")
|
||||
)]
|
||||
fn subscribe_new_heads(&self, metadata: Self::Metadata, subscriber: Subscriber<Header>);
|
||||
|
||||
/// Unsubscribe from new head subscription.
|
||||
#[pubsub(
|
||||
subscription = "chain_newHead",
|
||||
unsubscribe,
|
||||
name = "chain_unsubscribeNewHeads",
|
||||
alias("unsubscribe_newHead", "chain_unsubscribeNewHead")
|
||||
)]
|
||||
fn unsubscribe_new_heads(&self, metadata: Option<Self::Metadata>, id: SubscriptionId) -> RpcResult<bool>;
|
||||
|
||||
/// New head subscription
|
||||
#[pubsub(
|
||||
subscription = "chain_finalizedHead",
|
||||
subscribe,
|
||||
name = "chain_subscribeFinalizedHeads",
|
||||
alias("chain_subscribeFinalisedHeads")
|
||||
)]
|
||||
fn subscribe_finalized_heads(&self, metadata: Self::Metadata, subscriber: Subscriber<Header>);
|
||||
|
||||
/// Unsubscribe from new head subscription.
|
||||
#[pubsub(
|
||||
subscription = "chain_finalizedHead",
|
||||
unsubscribe,
|
||||
name = "chain_unsubscribeFinalizedHeads",
|
||||
alias("chain_unsubscribeFinalisedHeads")
|
||||
)]
|
||||
fn unsubscribe_finalized_heads(&self, metadata: Option<Self::Metadata>, id: SubscriptionId) -> RpcResult<bool>;
|
||||
}
|
||||
pub use api::chain::*;
|
||||
|
||||
/// Chain API with subscriptions support.
|
||||
pub struct Chain<B, E, Block: BlockT, RA> {
|
||||
@@ -168,6 +103,10 @@ impl<B, E, Block, RA> Chain<B, E, Block, RA> where
|
||||
}
|
||||
}
|
||||
|
||||
fn client_error(err: client::error::Error) -> Error {
|
||||
Error::Client(Box::new(err))
|
||||
}
|
||||
|
||||
impl<B, E, Block, RA> ChainApi<NumberFor<Block>, Block::Hash, Block::Header, SignedBlock<Block>> for Chain<B, E, Block, RA> where
|
||||
Block: BlockT<Hash=H256> + 'static,
|
||||
B: client::backend::Backend<Block, Blake2Hasher> + Send + Sync + 'static,
|
||||
@@ -178,20 +117,23 @@ impl<B, E, Block, RA> ChainApi<NumberFor<Block>, Block::Hash, Block::Header, Sig
|
||||
|
||||
fn header(&self, hash: Option<Block::Hash>) -> Result<Option<Block::Header>> {
|
||||
let hash = self.unwrap_or_best(hash)?;
|
||||
Ok(self.client.header(&BlockId::Hash(hash))?)
|
||||
Ok(self.client.header(&BlockId::Hash(hash)).map_err(client_error)?)
|
||||
}
|
||||
|
||||
fn block(&self, hash: Option<Block::Hash>)
|
||||
-> Result<Option<SignedBlock<Block>>>
|
||||
{
|
||||
let hash = self.unwrap_or_best(hash)?;
|
||||
Ok(self.client.block(&BlockId::Hash(hash))?)
|
||||
Ok(self.client.block(&BlockId::Hash(hash)).map_err(client_error)?)
|
||||
}
|
||||
|
||||
fn block_hash(&self, number: Option<number::NumberOrHex<NumberFor<Block>>>) -> Result<Option<Block::Hash>> {
|
||||
Ok(match number {
|
||||
None => Some(self.client.info().chain.best_hash),
|
||||
Some(num_or_hex) => self.client.header(&BlockId::number(num_or_hex.to_number()?))?.map(|h| h.hash()),
|
||||
Some(num_or_hex) => self.client
|
||||
.header(&BlockId::number(num_or_hex.to_number()?))
|
||||
.map_err(client_error)?
|
||||
.map(|h| h.hash()),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
// Copyright 2017-2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate 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.
|
||||
|
||||
// Substrate 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 Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Chain RPC Block number type.
|
||||
|
||||
use serde::{Serialize, Deserialize};
|
||||
use std::{convert::TryFrom, fmt::Debug};
|
||||
use primitives::U256;
|
||||
|
||||
/// RPC Block number type
|
||||
///
|
||||
/// We allow two representations of the block number as input.
|
||||
/// Either we deserialize to the type that is specified in the block type
|
||||
/// or we attempt to parse given hex value.
|
||||
/// We do that for consistency with the returned type, default generic header
|
||||
/// serializes block number as hex to avoid overflows in JavaScript.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum NumberOrHex<Number> {
|
||||
/// The original header number type of block.
|
||||
Number(Number),
|
||||
/// Hex representation of the block number.
|
||||
Hex(U256),
|
||||
}
|
||||
|
||||
impl<Number: TryFrom<u64> + From<u32> + Debug + PartialOrd> NumberOrHex<Number> {
|
||||
/// Attempts to convert into concrete block number.
|
||||
///
|
||||
/// Fails in case hex number is too big.
|
||||
pub fn to_number(self) -> Result<Number, String> {
|
||||
let num = match self {
|
||||
NumberOrHex::Number(n) => n,
|
||||
NumberOrHex::Hex(h) => {
|
||||
let l = h.low_u64();
|
||||
if U256::from(l) != h {
|
||||
return Err(format!("`{}` does not fit into u64 type; unsupported for now.", h))
|
||||
} else {
|
||||
Number::try_from(l)
|
||||
.map_err(|_| format!("`{}` does not fit into block number type.", h))?
|
||||
}
|
||||
},
|
||||
};
|
||||
// FIXME <2329>: Database seems to limit the block number to u32 for no reason
|
||||
if num > Number::from(u32::max_value()) {
|
||||
return Err(format!("`{:?}` > u32::max_value(), the max block number is u32.", num))
|
||||
}
|
||||
Ok(num)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl From<u64> for NumberOrHex<u64> {
|
||||
fn from(n: u64) -> Self {
|
||||
NumberOrHex::Number(n)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl<Number> From<U256> for NumberOrHex<Number> {
|
||||
fn from(n: U256) -> Self {
|
||||
NumberOrHex::Hex(n)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user