mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-26 00:41:09 +00:00
rpc: backpressured RPC server (bump jsonrpsee 0.20) (#1313)
This is a rather big change in jsonrpsee, the major things in this bump are: - Server backpressure (the subscription impls are modified to deal with that) - Allow custom error types / return types (remove jsonrpsee::core::Error and jsonrpee::core::CallError) - Bug fixes (graceful shutdown in particular not used by substrate anyway) - Less dependencies for the clients in particular - Return type requires Clone in method call responses - Moved to tokio channels - Async subscription API (not used in this PR) Major changes in this PR: - The subscriptions are now bounded and if subscription can't keep up with the server it is dropped - CLI: add parameter to configure the jsonrpc server bounded message buffer (default is 64) - Add our own subscription helper to deal with the unbounded streams in substrate The most important things in this PR to review is the added helpers functions in `substrate/client/rpc/src/utils.rs` and the rest is pretty much chore. Regarding the "bounded buffer limit" it may cause the server to handle the JSON-RPC calls slower than before. The message size limit is bounded by "--rpc-response-size" thus "by default 10MB * 64 = 640MB" but the subscription message size is not covered by this limit and could be capped as well. Hopefully the last release prior to 1.0, sorry in advance for a big PR Previous attempt: https://github.com/paritytech/substrate/pull/13992 Resolves https://github.com/paritytech/polkadot-sdk/issues/748, resolves https://github.com/paritytech/polkadot-sdk/issues/627
This commit is contained in:
@@ -24,32 +24,23 @@ mod utils;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::SubscriptionTaskExecutor;
|
||||
|
||||
use jsonrpsee::{
|
||||
core::{async_trait, server::rpc_module::SubscriptionSink, Error as JsonRpseeError, RpcResult},
|
||||
types::SubscriptionResult,
|
||||
use jsonrpsee::{core::async_trait, PendingSubscriptionSink};
|
||||
use sc_client_api::{
|
||||
Backend, BlockBackend, BlockchainEvents, ExecutorProvider, ProofProvider, StorageProvider,
|
||||
};
|
||||
|
||||
use sc_rpc_api::DenyUnsafe;
|
||||
use sp_api::{CallApiAt, Metadata, ProvideRuntimeApi};
|
||||
use sp_blockchain::{HeaderBackend, HeaderMetadata};
|
||||
use sp_core::{
|
||||
storage::{PrefixedStorageKey, StorageChangeSet, StorageData, StorageKey},
|
||||
Bytes,
|
||||
};
|
||||
use sp_runtime::traits::Block as BlockT;
|
||||
use sp_version::RuntimeVersion;
|
||||
use std::sync::Arc;
|
||||
|
||||
use sp_api::{CallApiAt, Metadata, ProvideRuntimeApi};
|
||||
|
||||
use self::error::Error;
|
||||
|
||||
use sc_client_api::{
|
||||
Backend, BlockBackend, BlockchainEvents, ExecutorProvider, ProofProvider, StorageProvider,
|
||||
};
|
||||
pub use sc_rpc_api::{child_state::*, state::*};
|
||||
use sp_blockchain::{HeaderBackend, HeaderMetadata};
|
||||
|
||||
const STORAGE_KEYS_PAGED_MAX_COUNT: u32 = 1000;
|
||||
|
||||
@@ -158,10 +149,15 @@ where
|
||||
) -> Result<sp_rpc::tracing::TraceBlockResponse, Error>;
|
||||
|
||||
/// New runtime version subscription
|
||||
fn subscribe_runtime_version(&self, sink: SubscriptionSink);
|
||||
fn subscribe_runtime_version(&self, pending: PendingSubscriptionSink);
|
||||
|
||||
/// New storage subscription
|
||||
fn subscribe_storage(&self, sink: SubscriptionSink, keys: Option<Vec<StorageKey>>);
|
||||
fn subscribe_storage(
|
||||
&self,
|
||||
pending: PendingSubscriptionSink,
|
||||
keys: Option<Vec<StorageKey>>,
|
||||
deny_unsafe: DenyUnsafe,
|
||||
);
|
||||
}
|
||||
|
||||
/// Create new state API that works on full node.
|
||||
@@ -207,7 +203,12 @@ where
|
||||
Block: BlockT + 'static,
|
||||
Client: Send + Sync + 'static,
|
||||
{
|
||||
fn call(&self, method: String, data: Bytes, block: Option<Block::Hash>) -> RpcResult<Bytes> {
|
||||
fn call(
|
||||
&self,
|
||||
method: String,
|
||||
data: Bytes,
|
||||
block: Option<Block::Hash>,
|
||||
) -> Result<Bytes, Error> {
|
||||
self.backend.call(block, method, data).map_err(Into::into)
|
||||
}
|
||||
|
||||
@@ -215,7 +216,7 @@ where
|
||||
&self,
|
||||
key_prefix: StorageKey,
|
||||
block: Option<Block::Hash>,
|
||||
) -> RpcResult<Vec<StorageKey>> {
|
||||
) -> Result<Vec<StorageKey>, Error> {
|
||||
self.backend.storage_keys(block, key_prefix).map_err(Into::into)
|
||||
}
|
||||
|
||||
@@ -223,7 +224,7 @@ where
|
||||
&self,
|
||||
key_prefix: StorageKey,
|
||||
block: Option<Block::Hash>,
|
||||
) -> RpcResult<Vec<(StorageKey, StorageData)>> {
|
||||
) -> Result<Vec<(StorageKey, StorageData)>, Error> {
|
||||
self.deny_unsafe.check_if_safe()?;
|
||||
self.backend.storage_pairs(block, key_prefix).map_err(Into::into)
|
||||
}
|
||||
@@ -234,12 +235,9 @@ where
|
||||
count: u32,
|
||||
start_key: Option<StorageKey>,
|
||||
block: Option<Block::Hash>,
|
||||
) -> RpcResult<Vec<StorageKey>> {
|
||||
) -> Result<Vec<StorageKey>, Error> {
|
||||
if count > STORAGE_KEYS_PAGED_MAX_COUNT {
|
||||
return Err(JsonRpseeError::from(Error::InvalidCount {
|
||||
value: count,
|
||||
max: STORAGE_KEYS_PAGED_MAX_COUNT,
|
||||
}))
|
||||
return Err(Error::InvalidCount { value: count, max: STORAGE_KEYS_PAGED_MAX_COUNT })
|
||||
}
|
||||
self.backend
|
||||
.storage_keys_paged(block, prefix, count, start_key)
|
||||
@@ -250,7 +248,7 @@ where
|
||||
&self,
|
||||
key: StorageKey,
|
||||
block: Option<Block::Hash>,
|
||||
) -> RpcResult<Option<StorageData>> {
|
||||
) -> Result<Option<StorageData>, Error> {
|
||||
self.backend.storage(block, key).map_err(Into::into)
|
||||
}
|
||||
|
||||
@@ -258,7 +256,7 @@ where
|
||||
&self,
|
||||
key: StorageKey,
|
||||
block: Option<Block::Hash>,
|
||||
) -> RpcResult<Option<Block::Hash>> {
|
||||
) -> Result<Option<Block::Hash>, Error> {
|
||||
self.backend.storage_hash(block, key).map_err(Into::into)
|
||||
}
|
||||
|
||||
@@ -266,18 +264,18 @@ where
|
||||
&self,
|
||||
key: StorageKey,
|
||||
block: Option<Block::Hash>,
|
||||
) -> RpcResult<Option<u64>> {
|
||||
) -> Result<Option<u64>, Error> {
|
||||
self.backend
|
||||
.storage_size(block, key, self.deny_unsafe)
|
||||
.await
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
fn metadata(&self, block: Option<Block::Hash>) -> RpcResult<Bytes> {
|
||||
fn metadata(&self, block: Option<Block::Hash>) -> Result<Bytes, Error> {
|
||||
self.backend.metadata(block).map_err(Into::into)
|
||||
}
|
||||
|
||||
fn runtime_version(&self, at: Option<Block::Hash>) -> RpcResult<RuntimeVersion> {
|
||||
fn runtime_version(&self, at: Option<Block::Hash>) -> Result<RuntimeVersion, Error> {
|
||||
self.backend.runtime_version(at).map_err(Into::into)
|
||||
}
|
||||
|
||||
@@ -286,7 +284,7 @@ where
|
||||
keys: Vec<StorageKey>,
|
||||
from: Block::Hash,
|
||||
to: Option<Block::Hash>,
|
||||
) -> RpcResult<Vec<StorageChangeSet<Block::Hash>>> {
|
||||
) -> Result<Vec<StorageChangeSet<Block::Hash>>, Error> {
|
||||
self.deny_unsafe.check_if_safe()?;
|
||||
self.backend.query_storage(from, to, keys).map_err(Into::into)
|
||||
}
|
||||
@@ -295,7 +293,7 @@ where
|
||||
&self,
|
||||
keys: Vec<StorageKey>,
|
||||
at: Option<Block::Hash>,
|
||||
) -> RpcResult<Vec<StorageChangeSet<Block::Hash>>> {
|
||||
) -> Result<Vec<StorageChangeSet<Block::Hash>>, Error> {
|
||||
self.backend.query_storage_at(keys, at).map_err(Into::into)
|
||||
}
|
||||
|
||||
@@ -303,7 +301,7 @@ where
|
||||
&self,
|
||||
keys: Vec<StorageKey>,
|
||||
block: Option<Block::Hash>,
|
||||
) -> RpcResult<ReadProof<Block::Hash>> {
|
||||
) -> Result<ReadProof<Block::Hash>, Error> {
|
||||
self.backend.read_proof(block, keys).map_err(Into::into)
|
||||
}
|
||||
|
||||
@@ -318,32 +316,19 @@ where
|
||||
targets: Option<String>,
|
||||
storage_keys: Option<String>,
|
||||
methods: Option<String>,
|
||||
) -> RpcResult<sp_rpc::tracing::TraceBlockResponse> {
|
||||
) -> Result<sp_rpc::tracing::TraceBlockResponse, Error> {
|
||||
self.deny_unsafe.check_if_safe()?;
|
||||
self.backend
|
||||
.trace_block(block, targets, storage_keys, methods)
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
fn subscribe_runtime_version(&self, sink: SubscriptionSink) -> SubscriptionResult {
|
||||
self.backend.subscribe_runtime_version(sink);
|
||||
Ok(())
|
||||
fn subscribe_runtime_version(&self, pending: PendingSubscriptionSink) {
|
||||
self.backend.subscribe_runtime_version(pending)
|
||||
}
|
||||
|
||||
fn subscribe_storage(
|
||||
&self,
|
||||
mut sink: SubscriptionSink,
|
||||
keys: Option<Vec<StorageKey>>,
|
||||
) -> SubscriptionResult {
|
||||
if keys.is_none() {
|
||||
if let Err(err) = self.deny_unsafe.check_if_safe() {
|
||||
let _ = sink.reject(JsonRpseeError::from(err));
|
||||
return Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
self.backend.subscribe_storage(sink, keys);
|
||||
Ok(())
|
||||
fn subscribe_storage(&self, pending: PendingSubscriptionSink, keys: Option<Vec<StorageKey>>) {
|
||||
self.backend.subscribe_storage(pending, keys, self.deny_unsafe)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -430,7 +415,7 @@ where
|
||||
storage_key: PrefixedStorageKey,
|
||||
key_prefix: StorageKey,
|
||||
block: Option<Block::Hash>,
|
||||
) -> RpcResult<Vec<StorageKey>> {
|
||||
) -> Result<Vec<StorageKey>, Error> {
|
||||
self.backend.storage_keys(block, storage_key, key_prefix).map_err(Into::into)
|
||||
}
|
||||
|
||||
@@ -441,7 +426,7 @@ where
|
||||
count: u32,
|
||||
start_key: Option<StorageKey>,
|
||||
block: Option<Block::Hash>,
|
||||
) -> RpcResult<Vec<StorageKey>> {
|
||||
) -> Result<Vec<StorageKey>, Error> {
|
||||
self.backend
|
||||
.storage_keys_paged(block, storage_key, prefix, count, start_key)
|
||||
.map_err(Into::into)
|
||||
@@ -452,7 +437,7 @@ where
|
||||
storage_key: PrefixedStorageKey,
|
||||
key: StorageKey,
|
||||
block: Option<Block::Hash>,
|
||||
) -> RpcResult<Option<StorageData>> {
|
||||
) -> Result<Option<StorageData>, Error> {
|
||||
self.backend.storage(block, storage_key, key).map_err(Into::into)
|
||||
}
|
||||
|
||||
@@ -461,7 +446,7 @@ where
|
||||
storage_key: PrefixedStorageKey,
|
||||
keys: Vec<StorageKey>,
|
||||
block: Option<Block::Hash>,
|
||||
) -> RpcResult<Vec<Option<StorageData>>> {
|
||||
) -> Result<Vec<Option<StorageData>>, Error> {
|
||||
self.backend.storage_entries(block, storage_key, keys).map_err(Into::into)
|
||||
}
|
||||
|
||||
@@ -470,7 +455,7 @@ where
|
||||
storage_key: PrefixedStorageKey,
|
||||
key: StorageKey,
|
||||
block: Option<Block::Hash>,
|
||||
) -> RpcResult<Option<Block::Hash>> {
|
||||
) -> Result<Option<Block::Hash>, Error> {
|
||||
self.backend.storage_hash(block, storage_key, key).map_err(Into::into)
|
||||
}
|
||||
|
||||
@@ -479,7 +464,7 @@ where
|
||||
storage_key: PrefixedStorageKey,
|
||||
key: StorageKey,
|
||||
block: Option<Block::Hash>,
|
||||
) -> RpcResult<Option<u64>> {
|
||||
) -> Result<Option<u64>, Error> {
|
||||
self.backend.storage_size(block, storage_key, key).map_err(Into::into)
|
||||
}
|
||||
|
||||
@@ -488,7 +473,7 @@ where
|
||||
child_storage_key: PrefixedStorageKey,
|
||||
keys: Vec<StorageKey>,
|
||||
block: Option<Block::Hash>,
|
||||
) -> RpcResult<ReadProof<Block::Hash>> {
|
||||
) -> Result<ReadProof<Block::Hash>, Error> {
|
||||
self.backend
|
||||
.read_child_proof(block, child_storage_key, keys)
|
||||
.map_err(Into::into)
|
||||
|
||||
@@ -25,13 +25,13 @@ use super::{
|
||||
error::{Error, Result},
|
||||
ChildStateBackend, StateBackend,
|
||||
};
|
||||
use crate::{DenyUnsafe, SubscriptionTaskExecutor};
|
||||
|
||||
use futures::{future, stream, FutureExt, StreamExt};
|
||||
use jsonrpsee::{
|
||||
core::{async_trait, Error as JsonRpseeError},
|
||||
SubscriptionSink,
|
||||
use crate::{
|
||||
utils::{pipe_from_stream, spawn_subscription_task},
|
||||
DenyUnsafe, SubscriptionTaskExecutor,
|
||||
};
|
||||
|
||||
use futures::{future, stream, StreamExt};
|
||||
use jsonrpsee::{core::async_trait, types::ErrorObject, PendingSubscriptionSink};
|
||||
use sc_client_api::{
|
||||
Backend, BlockBackend, BlockchainEvents, CallExecutor, ExecutorProvider, ProofProvider,
|
||||
StorageProvider,
|
||||
@@ -371,9 +371,7 @@ where
|
||||
.map_err(client_err)
|
||||
}
|
||||
|
||||
fn subscribe_runtime_version(&self, mut sink: SubscriptionSink) {
|
||||
let client = self.client.clone();
|
||||
|
||||
fn subscribe_runtime_version(&self, pending: PendingSubscriptionSink) {
|
||||
let initial = match self
|
||||
.block_or_best(None)
|
||||
.and_then(|block| self.client.runtime_version_at(block).map_err(Into::into))
|
||||
@@ -381,12 +379,13 @@ where
|
||||
{
|
||||
Ok(initial) => initial,
|
||||
Err(e) => {
|
||||
let _ = sink.reject(JsonRpseeError::from(e));
|
||||
spawn_subscription_task(&self.executor, pending.reject(e));
|
||||
return
|
||||
},
|
||||
};
|
||||
|
||||
let mut previous_version = initial.clone();
|
||||
let client = self.client.clone();
|
||||
|
||||
// A stream of new versions
|
||||
let version_stream = client
|
||||
@@ -406,24 +405,33 @@ where
|
||||
});
|
||||
|
||||
let stream = futures::stream::once(future::ready(initial)).chain(version_stream);
|
||||
|
||||
let fut = async move {
|
||||
sink.pipe_from_stream(stream).await;
|
||||
};
|
||||
|
||||
self.executor.spawn("substrate-rpc-subscription", Some("rpc"), fut.boxed());
|
||||
spawn_subscription_task(&self.executor, pipe_from_stream(pending, stream));
|
||||
}
|
||||
|
||||
fn subscribe_storage(&self, mut sink: SubscriptionSink, keys: Option<Vec<StorageKey>>) {
|
||||
fn subscribe_storage(
|
||||
&self,
|
||||
pending: PendingSubscriptionSink,
|
||||
keys: Option<Vec<StorageKey>>,
|
||||
deny_unsafe: DenyUnsafe,
|
||||
) {
|
||||
if keys.is_none() {
|
||||
if let Err(err) = deny_unsafe.check_if_safe() {
|
||||
spawn_subscription_task(&self.executor, pending.reject(ErrorObject::from(err)));
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
let stream = match self.client.storage_changes_notification_stream(keys.as_deref(), None) {
|
||||
Ok(stream) => stream,
|
||||
Err(blockchain_err) => {
|
||||
let _ = sink.reject(JsonRpseeError::from(Error::Client(Box::new(blockchain_err))));
|
||||
spawn_subscription_task(
|
||||
&self.executor,
|
||||
pending.reject(Error::Client(Box::new(blockchain_err))),
|
||||
);
|
||||
return
|
||||
},
|
||||
};
|
||||
|
||||
// initial values
|
||||
let initial = stream::iter(keys.map(|keys| {
|
||||
let block = self.client.info().best_hash;
|
||||
let changes = keys
|
||||
@@ -436,7 +444,6 @@ where
|
||||
StorageChangeSet { block, changes }
|
||||
}));
|
||||
|
||||
// let storage_stream = stream.map(|(block, changes)| StorageChangeSet {
|
||||
let storage_stream = stream.map(|storage_notif| StorageChangeSet {
|
||||
block: storage_notif.block,
|
||||
changes: storage_notif
|
||||
@@ -450,11 +457,7 @@ where
|
||||
.chain(storage_stream)
|
||||
.filter(|storage| future::ready(!storage.changes.is_empty()));
|
||||
|
||||
let fut = async move {
|
||||
sink.pipe_from_stream(stream).await;
|
||||
};
|
||||
|
||||
self.executor.spawn("substrate-rpc-subscription", Some("rpc"), fut.boxed());
|
||||
spawn_subscription_task(&self.executor, pipe_from_stream(pending, stream));
|
||||
}
|
||||
|
||||
fn trace_block(
|
||||
|
||||
@@ -21,10 +21,7 @@ use super::*;
|
||||
use crate::testing::{test_executor, timeout_secs};
|
||||
use assert_matches::assert_matches;
|
||||
use futures::executor;
|
||||
use jsonrpsee::{
|
||||
core::Error as RpcError,
|
||||
types::{error::CallError as RpcCallError, EmptyServerParams as EmptyParams, ErrorObject},
|
||||
};
|
||||
use jsonrpsee::core::{EmptyServerParams as EmptyParams, Error as RpcError};
|
||||
use sc_block_builder::BlockBuilderBuilder;
|
||||
use sc_rpc_api::DenyUnsafe;
|
||||
use sp_consensus::BlockOrigin;
|
||||
@@ -42,6 +39,14 @@ fn prefixed_storage_key() -> PrefixedStorageKey {
|
||||
child_info.prefixed_storage_key()
|
||||
}
|
||||
|
||||
fn init_logger() {
|
||||
use tracing_subscriber::{EnvFilter, FmtSubscriber};
|
||||
|
||||
let _ = FmtSubscriber::builder()
|
||||
.with_env_filter(EnvFilter::from_default_env())
|
||||
.try_init();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn should_return_storage() {
|
||||
const KEY: &[u8] = b":mock";
|
||||
@@ -200,22 +205,25 @@ async fn should_call_contract() {
|
||||
let genesis_hash = client.genesis_hash();
|
||||
let (client, _child) = new_full(client, test_executor(), DenyUnsafe::No);
|
||||
|
||||
use jsonrpsee::{core::Error, types::error::CallError};
|
||||
|
||||
assert_matches!(
|
||||
client.call("balanceOf".into(), Bytes(vec![1, 2, 3]), Some(genesis_hash).into()),
|
||||
Err(Error::Call(CallError::Failed(_)))
|
||||
Err(Error::Client(_))
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn should_notify_about_storage_changes() {
|
||||
init_logger();
|
||||
|
||||
let mut sub = {
|
||||
let mut client = Arc::new(substrate_test_runtime_client::new());
|
||||
let (api, _child) = new_full(client.clone(), test_executor(), DenyUnsafe::No);
|
||||
|
||||
let api_rpc = api.into_rpc();
|
||||
let sub = api_rpc.subscribe("state_subscribeStorage", EmptyParams::new()).await.unwrap();
|
||||
let sub = api_rpc
|
||||
.subscribe_unbounded("state_subscribeStorage", EmptyParams::new())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Cause a change:
|
||||
let mut builder = BlockBuilderBuilder::new(&*client)
|
||||
@@ -241,11 +249,12 @@ async fn should_notify_about_storage_changes() {
|
||||
// NOTE: previous versions of the subscription code used to return an empty value for the
|
||||
// "initial" storage change here
|
||||
assert_matches!(timeout_secs(1, sub.next::<StorageChangeSet<H256>>()).await, Ok(Some(_)));
|
||||
assert_matches!(timeout_secs(1, sub.next::<StorageChangeSet<H256>>()).await, Ok(None));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn should_send_initial_storage_changes_and_notifications() {
|
||||
init_logger();
|
||||
|
||||
let mut sub = {
|
||||
let mut client = Arc::new(substrate_test_runtime_client::new());
|
||||
let (api, _child) = new_full(client.clone(), test_executor(), DenyUnsafe::No);
|
||||
@@ -263,7 +272,10 @@ async fn should_send_initial_storage_changes_and_notifications() {
|
||||
|
||||
let api_rpc = api.into_rpc();
|
||||
let sub = api_rpc
|
||||
.subscribe("state_subscribeStorage", [[StorageKey(alice_balance_key)]])
|
||||
.subscribe_unbounded(
|
||||
"state_subscribeStorage",
|
||||
[[StorageKey(alice_balance_key.to_vec())]],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -288,9 +300,6 @@ async fn should_send_initial_storage_changes_and_notifications() {
|
||||
|
||||
assert_matches!(timeout_secs(1, sub.next::<StorageChangeSet<H256>>()).await, Ok(Some(_)));
|
||||
assert_matches!(timeout_secs(1, sub.next::<StorageChangeSet<H256>>()).await, Ok(Some(_)));
|
||||
|
||||
// No more messages to follow
|
||||
assert_matches!(timeout_secs(1, sub.next::<StorageChangeSet<H256>>()).await, Ok(None));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -393,108 +402,48 @@ async fn should_query_storage() {
|
||||
assert_eq!(result.unwrap(), expected);
|
||||
|
||||
// Inverted range.
|
||||
let result = api.query_storage(keys.clone(), block1_hash, Some(genesis_hash));
|
||||
|
||||
assert_eq!(
|
||||
result.map_err(|e| e.to_string()),
|
||||
Err(RpcError::Call(RpcCallError::Custom(ErrorObject::owned(
|
||||
4001,
|
||||
Error::InvalidBlockRange {
|
||||
from: format!("1 ({:?})", block1_hash),
|
||||
to: format!("0 ({:?})", genesis_hash),
|
||||
details: "from number > to number".to_owned(),
|
||||
}
|
||||
.to_string(),
|
||||
None::<()>,
|
||||
))))
|
||||
.map_err(|e| e.to_string())
|
||||
assert_matches!(
|
||||
api.query_storage(keys.clone(), block1_hash, Some(genesis_hash)),
|
||||
Err(Error::InvalidBlockRange { from, to, details }) if from == format!("1 ({:?})", block1_hash) && to == format!("0 ({:?})", genesis_hash) && details == "from number > to number".to_owned()
|
||||
);
|
||||
|
||||
let random_hash1 = H256::random();
|
||||
let random_hash2 = H256::random();
|
||||
|
||||
// Invalid second hash.
|
||||
let result = api.query_storage(keys.clone(), genesis_hash, Some(random_hash1));
|
||||
|
||||
assert_eq!(
|
||||
result.map_err(|e| e.to_string()),
|
||||
Err(RpcError::Call(RpcCallError::Custom(ErrorObject::owned(
|
||||
4001,
|
||||
Error::InvalidBlockRange {
|
||||
from: format!("{:?}", genesis_hash),
|
||||
to: format!("{:?}", Some(random_hash1)),
|
||||
details: format!(
|
||||
"UnknownBlock: Header was not found in the database: {:?}",
|
||||
random_hash1
|
||||
),
|
||||
}
|
||||
.to_string(),
|
||||
None::<()>,
|
||||
))))
|
||||
.map_err(|e| e.to_string())
|
||||
assert_matches!(
|
||||
api.query_storage(keys.clone(), genesis_hash, Some(random_hash1)),
|
||||
Err(Error::InvalidBlockRange { from, to, details }) if from == format!("{:?}", genesis_hash) && to == format!("{:?}", Some(random_hash1)) && details == format!(
|
||||
"UnknownBlock: Header was not found in the database: {:?}",
|
||||
random_hash1
|
||||
)
|
||||
);
|
||||
|
||||
// Invalid first hash with Some other hash.
|
||||
let result = api.query_storage(keys.clone(), random_hash1, Some(genesis_hash));
|
||||
|
||||
assert_eq!(
|
||||
result.map_err(|e| e.to_string()),
|
||||
Err(RpcError::Call(RpcCallError::Custom(ErrorObject::owned(
|
||||
4001,
|
||||
Error::InvalidBlockRange {
|
||||
from: format!("{:?}", random_hash1),
|
||||
to: format!("{:?}", Some(genesis_hash)),
|
||||
details: format!(
|
||||
"UnknownBlock: Header was not found in the database: {:?}",
|
||||
random_hash1
|
||||
),
|
||||
}
|
||||
.to_string(),
|
||||
None::<()>,
|
||||
))))
|
||||
.map_err(|e| e.to_string()),
|
||||
assert_matches!(
|
||||
api.query_storage(keys.clone(), random_hash1, Some(genesis_hash)),
|
||||
Err(Error::InvalidBlockRange { from, to, details }) if from == format!("{:?}", random_hash1) && to == format!("{:?}", Some(genesis_hash)) && details == format!(
|
||||
"UnknownBlock: Header was not found in the database: {:?}",
|
||||
random_hash1
|
||||
)
|
||||
);
|
||||
|
||||
// Invalid first hash with None.
|
||||
let result = api.query_storage(keys.clone(), random_hash1, None);
|
||||
|
||||
assert_eq!(
|
||||
result.map_err(|e| e.to_string()),
|
||||
Err(RpcError::Call(RpcCallError::Custom(ErrorObject::owned(
|
||||
4001,
|
||||
Error::InvalidBlockRange {
|
||||
from: format!("{:?}", random_hash1),
|
||||
to: format!("{:?}", Some(block2_hash)), // Best block hash.
|
||||
details: format!(
|
||||
"UnknownBlock: Header was not found in the database: {:?}",
|
||||
random_hash1
|
||||
),
|
||||
}
|
||||
.to_string(),
|
||||
None::<()>,
|
||||
))))
|
||||
.map_err(|e| e.to_string()),
|
||||
assert_matches!(
|
||||
api.query_storage(keys.clone(), random_hash1, None),
|
||||
Err(Error::InvalidBlockRange { from, to, details }) if from == format!("{:?}", random_hash1) && to == format!("{:?}", Some(block2_hash)) && details == format!(
|
||||
"UnknownBlock: Header was not found in the database: {:?}",
|
||||
random_hash1
|
||||
)
|
||||
);
|
||||
|
||||
// Both hashes invalid.
|
||||
let result = api.query_storage(keys.clone(), random_hash1, Some(random_hash2));
|
||||
|
||||
assert_eq!(
|
||||
result.map_err(|e| e.to_string()),
|
||||
Err(RpcError::Call(RpcCallError::Custom(ErrorObject::owned(
|
||||
4001,
|
||||
Error::InvalidBlockRange {
|
||||
from: format!("{:?}", random_hash1), // First hash not found.
|
||||
to: format!("{:?}", Some(random_hash2)),
|
||||
details: format!(
|
||||
"UnknownBlock: Header was not found in the database: {:?}",
|
||||
random_hash1
|
||||
),
|
||||
}
|
||||
.to_string(),
|
||||
None::<()>
|
||||
))))
|
||||
.map_err(|e| e.to_string()),
|
||||
assert_matches!(
|
||||
api.query_storage(keys.clone(), random_hash1, Some(random_hash2)),
|
||||
Err(Error::InvalidBlockRange { from, to, details }) if from == format!("{:?}", random_hash1) && to == format!("{:?}", Some(random_hash2)) && details == format!(
|
||||
"UnknownBlock: Header was not found in the database: {:?}",
|
||||
random_hash1
|
||||
)
|
||||
);
|
||||
|
||||
// single block range
|
||||
@@ -548,7 +497,7 @@ async fn should_notify_on_runtime_version_initially() {
|
||||
|
||||
let api_rpc = api.into_rpc();
|
||||
let sub = api_rpc
|
||||
.subscribe("state_subscribeRuntimeVersion", EmptyParams::new())
|
||||
.subscribe_unbounded("state_subscribeRuntimeVersion", EmptyParams::new())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -557,9 +506,6 @@ async fn should_notify_on_runtime_version_initially() {
|
||||
|
||||
// assert initial version sent.
|
||||
assert_matches!(timeout_secs(10, sub.next::<RuntimeVersion>()).await, Ok(Some(_)));
|
||||
|
||||
sub.close();
|
||||
assert_matches!(timeout_secs(10, sub.next::<RuntimeVersion>()).await, Ok(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -572,12 +518,14 @@ fn should_deserialize_storage_key() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn wildcard_storage_subscriptions_are_rpc_unsafe() {
|
||||
init_logger();
|
||||
|
||||
let client = Arc::new(substrate_test_runtime_client::new());
|
||||
let (api, _child) = new_full(client, test_executor(), DenyUnsafe::Yes);
|
||||
|
||||
let api_rpc = api.into_rpc();
|
||||
let err = api_rpc.subscribe("state_subscribeStorage", EmptyParams::new()).await;
|
||||
assert_matches!(err, Err(RpcError::Call(RpcCallError::Custom(e))) if e.message() == "RPC call is unsafe to be called externally");
|
||||
let err = api_rpc.subscribe_unbounded("state_subscribeStorage", EmptyParams::new()).await;
|
||||
assert_matches!(err, Err(RpcError::Call(e)) if e.message() == "RPC call is unsafe to be called externally");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -587,7 +535,7 @@ async fn concrete_storage_subscriptions_are_rpc_safe() {
|
||||
let api_rpc = api.into_rpc();
|
||||
|
||||
let key = StorageKey(STORAGE_KEY.to_vec());
|
||||
let sub = api_rpc.subscribe("state_subscribeStorage", [[key]]).await;
|
||||
let sub = api_rpc.subscribe_unbounded("state_subscribeStorage", [[key]]).await;
|
||||
|
||||
assert!(sub.is_ok());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user