Skip to content

Commit

Permalink
jsonrpsee v0.20
Browse files Browse the repository at this point in the history
  • Loading branch information
niklasad1 committed Sep 22, 2023
1 parent e389988 commit 52b35cf
Show file tree
Hide file tree
Showing 108 changed files with 1,309 additions and 1,825 deletions.
236 changes: 140 additions & 96 deletions Cargo.lock

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -527,3 +527,6 @@ wasmi = { opt-level = 3 }
x25519-dalek = { opt-level = 3 }
yamux = { opt-level = 3 }
zeroize = { opt-level = 3 }

[patch.crates-io]
jsonrpsee = { git = "https://github.com/paritytech/jsonrpsee", branch = "master" }
2 changes: 1 addition & 1 deletion cumulus/client/relay-chain-interface/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,5 @@ sc-client-api = { path = "../../../substrate/client/api" }
futures = "0.3.28"
async-trait = "0.1.73"
thiserror = "1.0.48"
jsonrpsee-core = "0.16.2"
jsonrpsee-core = "0.20.1"
parity-scale-codec = "3.6.4"
2 changes: 1 addition & 1 deletion cumulus/client/relay-chain-rpc-interface/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ tokio-util = { version = "0.7.8", features = ["compat"] }
futures = "0.3.28"
futures-timer = "3.0.2"
parity-scale-codec = "3.6.4"
jsonrpsee = { version = "0.16.2", features = ["ws-client"] }
jsonrpsee = { version = "0.20", features = ["ws-client"] }
tracing = "0.1.37"
async-trait = "0.1.73"
url = "2.4.0"
Expand Down
16 changes: 10 additions & 6 deletions cumulus/client/relay-chain-rpc-interface/src/rpc_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,12 +200,16 @@ impl RelayChainRpcClient {
))
})?;

let value = rx.await.map_err(|err| {
RelayChainError::WorkerCommunicationError(format!(
"Unexpected channel close on RPC worker side: {}",
err
))
})??;
// TODO(niklasad1): fix this.
let value = rx
.await
.map_err(|err| {
RelayChainError::WorkerCommunicationError(format!(
"Unexpected channel close on RPC worker side: {}",
err
))
})?
.unwrap();

serde_json::from_value(value).map_err(|_| {
trace_error(&RelayChainError::GenericError("Unable to deserialize value".to_string()));
Expand Down
2 changes: 1 addition & 1 deletion cumulus/parachain-template/node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ clap = { version = "4.4.3", features = ["derive"] }
log = "0.4.20"
codec = { package = "parity-scale-codec", version = "3.0.0" }
serde = { version = "1.0.188", features = ["derive"] }
jsonrpsee = { version = "0.16.2", features = ["server"] }
jsonrpsee = { version = "0.20", features = ["server"] }
futures = "0.3.28"

# Local
Expand Down
2 changes: 1 addition & 1 deletion cumulus/polkadot-parachain/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ bridge-hub-rococo-runtime = { path = "../parachains/runtimes/bridge-hubs/bridge-
bridge-hub-kusama-runtime = { path = "../parachains/runtimes/bridge-hubs/bridge-hub-kusama" }
bridge-hub-polkadot-runtime = { path = "../parachains/runtimes/bridge-hubs/bridge-hub-polkadot" }
penpal-runtime = { path = "../parachains/runtimes/testing/penpal" }
jsonrpsee = { version = "0.16.2", features = ["server"] }
jsonrpsee = { version = "0.20", features = ["server"] }
parachains-common = { path = "../parachains/common" }

# Substrate
Expand Down
2 changes: 1 addition & 1 deletion cumulus/test/service/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ async-trait = "0.1.73"
clap = { version = "4.4.3", features = ["derive"] }
codec = { package = "parity-scale-codec", version = "3.0.0" }
criterion = { version = "0.5.1", features = [ "async_tokio" ] }
jsonrpsee = { version = "0.16.2", features = ["server"] }
jsonrpsee = { version = "0.20", features = ["server"] }
rand = "0.8.5"
serde = { version = "1.0.188", features = ["derive"] }
tokio = { version = "1.32.0", features = ["macros"] }
Expand Down
1 change: 1 addition & 0 deletions cumulus/test/service/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -774,6 +774,7 @@ pub fn node_config(
rpc_id_provider: None,
rpc_max_subs_per_conn: Default::default(),
rpc_port: 9945,
rpc_message_buffer_capacity: Default::default(),
prometheus_config: None,
telemetry_endpoints: None,
default_heap_pages: None,
Expand Down
1 change: 1 addition & 0 deletions polkadot/node/test/service/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ pub fn node_config(
rpc_id_provider: None,
rpc_max_subs_per_conn: Default::default(),
rpc_port: 9944,
rpc_message_buffer_capacity: Default::default(),
prometheus_config: None,
telemetry_endpoints: None,
default_heap_pages: None,
Expand Down
2 changes: 1 addition & 1 deletion polkadot/rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ edition.workspace = true
license.workspace = true

[dependencies]
jsonrpsee = { version = "0.16.2", features = ["server"] }
jsonrpsee = { version = "0.20", features = ["server"] }
polkadot-primitives = { path = "../primitives" }
sc-client-api = { path = "../../substrate/client/api" }
sp-blockchain = { path = "../../substrate/primitives/blockchain" }
Expand Down
8 changes: 6 additions & 2 deletions polkadot/xcm/xcm-builder/src/universal_exports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,9 @@ impl<Bridges: ExporterFor, Router: SendXcm, UniversalLocation: Get<InteriorMulti
let xcm = msg.take().ok_or(MissingArgument)?;

// find exporter
let Some((bridge, maybe_payment)) = Bridges::exporter_for(&remote_network, &remote_location, &xcm) else {
let Some((bridge, maybe_payment)) =
Bridges::exporter_for(&remote_network, &remote_location, &xcm)
else {
// We need to make sure that msg is not consumed in case of `NotApplicable`.
*msg = Some(xcm);
return Err(SendError::NotApplicable)
Expand Down Expand Up @@ -236,7 +238,9 @@ impl<Bridges: ExporterFor, Router: SendXcm, UniversalLocation: Get<InteriorMulti
let xcm = msg.take().ok_or(MissingArgument)?;

// find exporter
let Some((bridge, maybe_payment)) = Bridges::exporter_for(&remote_network, &remote_location, &xcm) else {
let Some((bridge, maybe_payment)) =
Bridges::exporter_for(&remote_network, &remote_location, &xcm)
else {
// We need to make sure that msg is not consumed in case of `NotApplicable`.
*msg = Some(xcm);
return Err(SendError::NotApplicable)
Expand Down
2 changes: 1 addition & 1 deletion substrate/bin/node-template/node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ frame-system = { path = "../../../frame/system" }
pallet-transaction-payment = { path = "../../../frame/transaction-payment", default-features = false}

# These dependencies are used for the node template's RPCs
jsonrpsee = { version = "0.16.2", features = ["server"] }
jsonrpsee = { version = "0.20", features = ["server"] }
sp-api = { path = "../../../primitives/api" }
sc-rpc-api = { path = "../../../client/rpc-api" }
sp-blockchain = { path = "../../../primitives/blockchain" }
Expand Down
2 changes: 1 addition & 1 deletion substrate/bin/node/cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ array-bytes = "6.1"
clap = { version = "4.4.3", features = ["derive"], optional = true }
codec = { package = "parity-scale-codec", version = "3.6.1" }
serde = { version = "1.0.188", features = ["derive"] }
jsonrpsee = { version = "0.16.2", features = ["server"] }
jsonrpsee = { version = "0.20", features = ["server"] }
futures = "0.3.21"
log = "0.4.17"
rand = "0.8"
Expand Down
1 change: 1 addition & 0 deletions substrate/bin/node/cli/benches/block_production.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ fn new_node(tokio_handle: Handle) -> node_cli::service::NewFullBase {
rpc_id_provider: Default::default(),
rpc_max_subs_per_conn: Default::default(),
rpc_port: 9944,
rpc_message_buffer_capacity: Default::default(),
prometheus_config: None,
telemetry_endpoints: None,
default_heap_pages: None,
Expand Down
1 change: 1 addition & 0 deletions substrate/bin/node/cli/benches/transaction_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ fn new_node(tokio_handle: Handle) -> node_cli::service::NewFullBase {
rpc_id_provider: Default::default(),
rpc_max_subs_per_conn: Default::default(),
rpc_port: 9944,
rpc_message_buffer_capacity: Default::default(),
prometheus_config: None,
telemetry_endpoints: None,
default_heap_pages: None,
Expand Down
2 changes: 1 addition & 1 deletion substrate/bin/node/rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ publish = false
targets = ["x86_64-unknown-linux-gnu"]

[dependencies]
jsonrpsee = { version = "0.16.2", features = ["server"] }
jsonrpsee = { version = "0.20", features = ["server"] }
node-primitives = { path = "../primitives" }
pallet-transaction-payment-rpc = { path = "../../../frame/transaction-payment/rpc" }
mmr-rpc = { path = "../../../client/merkle-mountain-range/rpc" }
Expand Down
13 changes: 12 additions & 1 deletion substrate/client/cli/src/commands/run_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use crate::{
},
CliConfiguration, PrometheusParams, RuntimeParams, TelemetryParams,
RPC_DEFAULT_MAX_CONNECTIONS, RPC_DEFAULT_MAX_REQUEST_SIZE_MB, RPC_DEFAULT_MAX_RESPONSE_SIZE_MB,
RPC_DEFAULT_MAX_SUBS_PER_CONN,
RPC_DEFAULT_MAX_SUBS_PER_CONN, RPC_DEFAULT_MESSAGE_CAPACITY_PER_CONN,
};
use clap::Parser;
use regex::Regex;
Expand Down Expand Up @@ -99,6 +99,17 @@ pub struct RunCmd {
#[arg(long, value_name = "COUNT", default_value_t = RPC_DEFAULT_MAX_CONNECTIONS)]
pub rpc_max_connections: u32,

/// The number of messages the RPC server is allowed to keep in memory.
///
/// If the buffer becomes full then the server will not process
/// new messages until the connected client start reading the
/// underlying messages.
///
/// This applies per connection which includes both
/// JSON-RPC methods calls and subscriptions.
#[arg(long, default_value_t = RPC_DEFAULT_MESSAGE_CAPACITY_PER_CONN)]
pub rpc_message_buffer_capacity_per_connection: u32,

/// Specify browser Origins allowed to access the HTTP & WS RPC servers.
/// A comma-separated list of origins (protocol://domain or special `null`
/// value). Value of `all` will disable origin validation. Default is to
Expand Down
11 changes: 10 additions & 1 deletion substrate/client/cli/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,11 @@ pub const RPC_DEFAULT_MAX_SUBS_PER_CONN: u32 = 1024;
pub const RPC_DEFAULT_MAX_REQUEST_SIZE_MB: u32 = 15;
/// The default max response size in MB.
pub const RPC_DEFAULT_MAX_RESPONSE_SIZE_MB: u32 = 15;
/// The default number of connection..
/// The default concurrent connection limit.
pub const RPC_DEFAULT_MAX_CONNECTIONS: u32 = 100;
/// The default number of messages the RPC server
/// is allowed to keep in memory per connection.
pub const RPC_DEFAULT_MESSAGE_CAPACITY_PER_CONN: u32 = 64;

/// Default configuration values used by Substrate
///
Expand Down Expand Up @@ -330,6 +333,11 @@ pub trait CliConfiguration<DCV: DefaultConfigurationValues = ()>: Sized {
Ok(RPC_DEFAULT_MAX_SUBS_PER_CONN)
}

/// The number of messages the RPC server is allowed to keep in memory per connection.
fn rpc_buffer_capacity_per_connection(&self) -> Result<u32> {
Ok(RPC_DEFAULT_MESSAGE_CAPACITY_PER_CONN)
}

/// Get the prometheus configuration (`None` if disabled)
///
/// By default this is `None`.
Expand Down Expand Up @@ -501,6 +509,7 @@ pub trait CliConfiguration<DCV: DefaultConfigurationValues = ()>: Sized {
rpc_id_provider: None,
rpc_max_subs_per_conn: self.rpc_max_subscriptions_per_connection()?,
rpc_port: DCV::rpc_listen_port(),
rpc_message_buffer_capacity: self.rpc_buffer_capacity_per_connection()?,
prometheus_config: self
.prometheus_config(DCV::prometheus_listen_port(), &chain_spec)?,
telemetry_endpoints,
Expand Down
1 change: 1 addition & 0 deletions substrate/client/cli/src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,7 @@ mod tests {
rpc_id_provider: Default::default(),
rpc_max_subs_per_conn: Default::default(),
rpc_port: 9944,
rpc_message_buffer_capacity: Default::default(),
prometheus_config: None,
telemetry_endpoints: None,
default_heap_pages: None,
Expand Down
2 changes: 1 addition & 1 deletion substrate/client/consensus/babe/rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ readme = "README.md"
targets = ["x86_64-unknown-linux-gnu"]

[dependencies]
jsonrpsee = { version = "0.16.2", features = ["client-core", "server", "macros"] }
jsonrpsee = { version = "0.20", features = ["client-core", "server", "macros"] }
futures = "0.3.21"
serde = { version = "1.0.188", features = ["derive"] }
thiserror = "1.0"
Expand Down
44 changes: 25 additions & 19 deletions substrate/client/consensus/babe/rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,15 @@ use std::{collections::HashMap, sync::Arc};

use futures::TryFutureExt;
use jsonrpsee::{
core::{async_trait, Error as JsonRpseeError, RpcResult},
core::async_trait,
proc_macros::rpc,
types::{error::CallError, ErrorObject},
types::{ErrorObject, ErrorObjectOwned},
};
use serde::{Deserialize, Serialize};

use sc_consensus_babe::{authorship, BabeWorkerHandle};
use sc_consensus_epochs::Epoch as EpochT;
use sc_rpc_api::DenyUnsafe;
use sc_rpc_api::{DenyUnsafe, UnsafeRpcError};
use sp_api::ProvideRuntimeApi;
use sp_application_crypto::AppCrypto;
use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata};
Expand All @@ -48,7 +48,7 @@ pub trait BabeApi {
/// Returns data about which slots (primary or secondary) can be claimed in the current epoch
/// with the keys in the keystore.
#[method(name = "babe_epochAuthorship")]
async fn epoch_authorship(&self) -> RpcResult<HashMap<AuthorityId, EpochAuthorship>>;
async fn epoch_authorship(&self) -> Result<HashMap<AuthorityId, EpochAuthorship>, Error>;
}

/// Provides RPC methods for interacting with Babe.
Expand Down Expand Up @@ -89,7 +89,7 @@ where
C::Api: BabeRuntimeApi<B>,
SC: SelectChain<B> + Clone + 'static,
{
async fn epoch_authorship(&self) -> RpcResult<HashMap<AuthorityId, EpochAuthorship>> {
async fn epoch_authorship(&self) -> Result<HashMap<AuthorityId, EpochAuthorship>, Error> {
self.deny_unsafe.check_if_safe()?;

let best_header = self.select_chain.best_chain().map_err(Error::SelectChain).await?;
Expand Down Expand Up @@ -147,7 +147,7 @@ where
}

/// Holds information about the `slot`'s that can be claimed by a given key.
#[derive(Default, Debug, Deserialize, Serialize)]
#[derive(Clone, Default, Debug, Deserialize, Serialize)]
pub struct EpochAuthorship {
/// the array of primary slots that can be claimed
primary: Vec<u64>,
Expand All @@ -166,20 +166,26 @@ pub enum Error {
/// Failed to fetch epoch data.
#[error("Failed to fetch epoch data")]
FetchEpoch,
/// Consensus error
#[error(transparent)]
Consensus(#[from] ConsensusError),
/// Errors that can be formatted as a String
#[error("{0}")]
StringError(String),
/// Call to an unsafe RPC was denied.
#[error(transparent)]
UnsafeRpcCalled(#[from] UnsafeRpcError),
}

impl From<Error> for JsonRpseeError {
impl From<Error> for ErrorObjectOwned {
fn from(error: Error) -> Self {
let error_code = match error {
Error::SelectChain(_) => 1,
Error::FetchEpoch => 2,
};

JsonRpseeError::Call(CallError::Custom(ErrorObject::owned(
BABE_ERROR + error_code,
error.to_string(),
Some(format!("{:?}", error)),
)))
match error {
Error::SelectChain(e) => ErrorObject::owned(BABE_ERROR + 1, e.to_string(), None::<()>),
Error::FetchEpoch => ErrorObject::owned(BABE_ERROR + 2, error.to_string(), None::<()>),
Error::Consensus(e) => ErrorObject::owned(BABE_ERROR + 3, e.to_string(), None::<()>),
Error::StringError(e) => ErrorObject::owned(BABE_ERROR + 4, e, None::<()>),
Error::UnsafeRpcCalled(e) => e.into(),
}
}
}

Expand Down Expand Up @@ -251,7 +257,7 @@ mod tests {
let api = babe_rpc.into_rpc();

let request = r#"{"jsonrpc":"2.0","method":"babe_epochAuthorship","params": [],"id":1}"#;
let (response, _) = api.raw_json_request(request).await.unwrap();
let (response, _) = api.raw_json_request(request, 1).await.unwrap();
let expected = r#"{"jsonrpc":"2.0","result":{"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY":{"primary":[0],"secondary":[1,2,4],"secondary_vrf":[]}},"id":1}"#;

assert_eq!(&response.result, expected);
Expand All @@ -263,7 +269,7 @@ mod tests {
let api = babe_rpc.into_rpc();

let request = r#"{"jsonrpc":"2.0","method":"babe_epochAuthorship","params":[],"id":1}"#;
let (response, _) = api.raw_json_request(request).await.unwrap();
let (response, _) = api.raw_json_request(request, 1).await.unwrap();
let expected = r#"{"jsonrpc":"2.0","error":{"code":-32601,"message":"RPC call is unsafe to be called externally"},"id":1}"#;

assert_eq!(&response.result, expected);
Expand Down
2 changes: 1 addition & 1 deletion substrate/client/consensus/beefy/rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ homepage = "https://substrate.io"
[dependencies]
codec = { package = "parity-scale-codec", version = "3.6.1", features = ["derive"] }
futures = "0.3.21"
jsonrpsee = { version = "0.16.2", features = ["client-core", "server", "macros"] }
jsonrpsee = { version = "0.20", features = ["client-core", "server", "macros"] }
log = "0.4"
parking_lot = "0.12.1"
serde = { version = "1.0.188", features = ["derive"] }
Expand Down
Loading

0 comments on commit 52b35cf

Please sign in to comment.