Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
migrate chain module to proc macro api
  • Loading branch information
niklasad1 committed Aug 22, 2021
commit 289888fedc057671329cc09b683655d39c0efb3e
63 changes: 61 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion client/rpc-api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ sc-chain-spec = { path = "../chain-spec", version = "4.0.0-dev" }
serde = { version = "1.0.126", features = ["derive"] }
serde_json = "1.0.41"

jsonrpsee = { git = "https://github.com/paritytech/jsonrpsee", branch = "na-proc-macros-generics", features = ["server"] }
jsonrpsee = { git = "https://github.com/paritytech/jsonrpsee", branch = "na-proc-macros-generics", features = ["full"] }

sc-transaction-pool-api = { version = "4.0.0-dev", path = "../transaction-pool/api" }
sp-rpc = { version = "4.0.0-dev", path = "../../primitives/rpc" }
Expand Down
39 changes: 39 additions & 0 deletions client/rpc-api/src/chain/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,43 @@

//! Substrate blockchain API.

use jsonrpsee::{proc_macros::rpc, types::JsonRpcResult};
use sp_rpc::{list::ListOrValue, number::NumberOrHex};

pub mod error;

#[rpc(client, server, namespace = "chain")]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why both client and server?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pub trait ChainApi<Number, Hash, Header, SignedBlock> {
/// Get header.
#[method(name = "getHeader")]
async fn header(&self, hash: Option<Hash>) -> JsonRpcResult<Option<Header>>;

/// Get header and body of a relay chain block.
#[method(name = "getBlock")]
async fn block(&self, hash: Option<Hash>) -> JsonRpcResult<Option<SignedBlock>>;

/// Get hash of the n-th block in the canon chain.
///
/// By default returns latest block hash.
#[method(name = "getBlockHash")]
fn block_hash(&self, hash: Option<ListOrValue<NumberOrHex>>) -> JsonRpcResult<ListOrValue<Option<Hash>>>;

/// Get hash of the last finalized block in the canon chain.
#[method(name = "getFinalizedHead")]
fn finalized_head(&self) -> JsonRpcResult<Hash>;

/// All head subscription
// TODO(): support alias: subscribeAllHeads.
#[subscription(name = "allHead", unsub = "unsubscribeAllHeads", item = Header)]
fn subscribe_all_heads(&self);

/// New head subscription
// TODO(): support alias in jsonrpsee subscribeNewHeads.
#[subscription(name = "newHead", unsub = "unsubscribeNewHeads", item = Header)]
fn subscribe_new_heads(&self);

/// Finalized head subscription
// TODO(): support alias in jsonrpsee subscribeFinalizedHeads/subscribeFinalisedHeads
#[subscription(name = "finalizedHead", unsub = "unsubscribeFinalizedHeads", item = Header)]
fn subscribe_finalized_heads(&self);
}
115 changes: 32 additions & 83 deletions client/rpc/src/chain/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,10 @@ use std::sync::Arc;

use crate::SubscriptionTaskExecutor;

use futures::FutureExt;
use jsonrpsee::{types::error::Error as JsonRpseeError, ws_server::SubscriptionSink, RpcModule};
use jsonrpsee::{
types::{async_trait, DeserializeOwned, Error as JsonRpseeError, JsonRpcResult},
SubscriptionSink,
};
use sc_client_api::{
light::{Fetcher, RemoteBlockchain},
BlockchainEvents,
Expand Down Expand Up @@ -154,92 +156,28 @@ pub struct Chain<Block: BlockT, Client> {
backend: Box<dyn ChainBackend<Client, Block>>,
}

impl<Block: BlockT, Client> Chain<Block, Client>
// TODO(niklasad1): check if those DeserializeOwned bounds are really required.
#[async_trait]
impl<Block, Client> ChainApiServer<NumberFor<Block>, Block::Hash, Block::Header, SignedBlock<Block>>
for Chain<Block, Client>
where
Client: BlockchainEvents<Block> + HeaderBackend<Block> + Send + Sync + 'static,
Block: BlockT + 'static,
<Block as BlockT>::Header: Unpin,
Block: BlockT + 'static + DeserializeOwned,
Block::Header: Unpin + DeserializeOwned,
Client: HeaderBackend<Block> + BlockchainEvents<Block> + 'static,
{
/// Convert a [`Chain`] to an [`RpcModule`]. Registers all the RPC methods available with the
/// RPC server.
pub fn into_rpc_module(self) -> Result<RpcModule<Self>, JsonRpseeError> {
let mut rpc_module = RpcModule::new(self);

rpc_module.register_async_method("chain_getHeader", |params, chain| {
let hash = params.one().ok();
async move { chain.header(hash).await.map_err(|e| JsonRpseeError::to_call_error(e)) }
.boxed()
})?;

rpc_module.register_async_method("chain_getBlock", |params, chain| {
let hash = params.one().ok();
async move { chain.block(hash).await.map_err(|e| JsonRpseeError::to_call_error(e)) }
.boxed()
})?;

rpc_module.register_method("chain_getBlockHash", |params, chain| {
let hash = params.one().ok();
chain.block_hash(hash).map_err(|e| JsonRpseeError::to_call_error(e))
})?;

rpc_module.register_alias("chain_getHead", "chain_getBlockHash")?;

rpc_module.register_method("chain_getFinalizedHead", |_, chain| {
chain.finalized_head().map_err(|e| JsonRpseeError::to_call_error(e))
})?;

rpc_module.register_alias("chain_getFinalisedHead", "chain_getFinalizedHead")?;

rpc_module.register_subscription(
"chain_allHead",
"chain_unsubscribeAllHeads",
|_params, sink, ctx| ctx.backend.subscribe_all_heads(sink).map_err(Into::into),
)?;

rpc_module.register_alias("chain_subscribeAllHeads", "chain_allHead")?;

rpc_module.register_subscription(
"chain_newHead",
"chain_unsubscribeNewHead",
|_params, sink, ctx| ctx.backend.subscribe_new_heads(sink).map_err(Into::into),
)?;

rpc_module.register_subscription(
"chain_finalizedHead",
"chain_unsubscribeFinalizedHeads",
|_params, sink, ctx| ctx.backend.subscribe_finalized_heads(sink).map_err(Into::into),
)?;

rpc_module.register_alias("chain_subscribeNewHead", "chain_newHead")?;
rpc_module.register_alias("chain_subscribeNewHeads", "chain_newHead")?;
rpc_module.register_alias("chain_unsubscribeNewHeads", "chain_unsubscribeNewHead")?;
rpc_module.register_alias("chain_subscribeFinalisedHeads", "chain_finalizedHead")?;
rpc_module.register_alias("chain_subscribeFinalizedHeads", "chain_finalizedHead")?;
rpc_module
.register_alias("chain_unsubscribeFinalisedHeads", "chain_unsubscribeFinalizedHeads")?;

Ok(rpc_module)
async fn header(&self, hash: Option<Block::Hash>) -> JsonRpcResult<Option<Block::Header>> {
self.backend.header(hash).await.map_err(Into::into)
}

/// TODO: document this
pub async fn header(&self, hash: Option<Block::Hash>) -> Result<Option<Block::Header>, Error> {
self.backend.header(hash).await
async fn block(&self, hash: Option<Block::Hash>) -> JsonRpcResult<Option<SignedBlock<Block>>> {
self.backend.block(hash).await.map_err(Into::into)
}

/// TODO: document this
async fn block(&self, hash: Option<Block::Hash>) -> Result<Option<SignedBlock<Block>>, Error> {
self.backend.block(hash).await
}

/// TODO: document this
fn block_hash(
&self,
number: Option<ListOrValue<NumberOrHex>>,
) -> Result<ListOrValue<Option<Block::Hash>>, Error> {
fn block_hash(&self, number: Option<ListOrValue<NumberOrHex>>) -> JsonRpcResult<ListOrValue<Option<Block::Hash>>> {
match number {
None => self.backend.block_hash(None).map(ListOrValue::Value),
None => self.backend.block_hash(None).map(ListOrValue::Value).map_err(Into::into),
Some(ListOrValue::Value(number)) =>
self.backend.block_hash(Some(number)).map(ListOrValue::Value),
self.backend.block_hash(Some(number)).map(ListOrValue::Value).map_err(Into::into),
Some(ListOrValue::List(list)) => Ok(ListOrValue::List(
list.into_iter()
.map(|number| self.backend.block_hash(Some(number)))
Expand All @@ -248,9 +186,20 @@ where
}
}

/// TODO: document this
fn finalized_head(&self) -> Result<Block::Hash, Error> {
self.backend.finalized_head()
fn finalized_head(&self) -> JsonRpcResult<Block::Hash> {
self.backend.finalized_head().map_err(Into::into)
}

fn subscribe_all_heads(&self, sink: SubscriptionSink) {
let _ = self.backend.subscribe_all_heads(sink);
}

fn subscribe_new_heads(&self, sink: SubscriptionSink) {
let _ = self.backend.subscribe_new_heads(sink);
}

fn subscribe_finalized_heads(&self, sink: SubscriptionSink) {
let _ = self.backend.subscribe_finalized_heads(sink);
}
}

Expand Down
9 changes: 3 additions & 6 deletions client/service/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ use sc_network::{
warp_request_handler::{self, RequestHandler as WarpSyncRequestHandler, WarpSyncProvider},
NetworkService,
};
use sc_rpc::{DenyUnsafe, SubscriptionTaskExecutor};
use sc_rpc::{DenyUnsafe, SubscriptionTaskExecutor, chain::ChainApiServer};
use sc_telemetry::{telemetry, ConnectionMessage, Telemetry, TelemetryHandle, SUBSTRATE_INFO};
use sc_transaction_pool_api::MaintainedTransactionPool;
use sp_api::{CallApiAt, ProvideRuntimeApi};
Expand Down Expand Up @@ -721,8 +721,7 @@ where
remote_blockchain.clone(),
on_demand.clone(),
)
.into_rpc_module()
.expect(UNIQUE_METHOD_NAMES_PROOF);
.into_rpc();
let (state, child_state) = sc_rpc::state::new_light(
client.clone(),
task_executor.clone(),
Expand All @@ -737,9 +736,7 @@ where
)
} else {
// Full nodes
let chain = sc_rpc::chain::new_full(client.clone(), task_executor.clone())
.into_rpc_module()
.expect(UNIQUE_METHOD_NAMES_PROOF);
let chain = sc_rpc::chain::new_full(client.clone(), task_executor.clone()).into_rpc();

let (state, child_state) = sc_rpc::state::new_full(
client.clone(),
Expand Down