mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-12 03:01:07 +00:00
Run cargo fmt on the whole code base (#9394)
* Run cargo fmt on the whole code base * Second run * Add CI check * Fix compilation * More unnecessary braces * Handle weights * Use --all * Use correct attributes... * Fix UI tests * AHHHHHHHHH * 🤦 * Docs * Fix compilation * 🤷 * Please stop * 🤦 x 2 * More * make rustfmt.toml consistent with polkadot Co-authored-by: André Silva <andrerfosilva@gmail.com>
This commit is contained in:
@@ -24,34 +24,39 @@ mod state_light;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use jsonrpc_pubsub::{manager::SubscriptionManager, typed::Subscriber, SubscriptionId};
|
||||
use rpc::{
|
||||
futures::{future::result, Future},
|
||||
Result as RpcResult,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
use jsonrpc_pubsub::{typed::Subscriber, SubscriptionId, manager::SubscriptionManager};
|
||||
use rpc::{Result as RpcResult, futures::{Future, future::result}};
|
||||
|
||||
use sc_rpc_api::{DenyUnsafe, state::ReadProof};
|
||||
use sc_client_api::light::{RemoteBlockchain, Fetcher};
|
||||
use sp_core::{Bytes, storage::{StorageKey, PrefixedStorageKey, StorageData, StorageChangeSet}};
|
||||
use sp_version::RuntimeVersion;
|
||||
use sc_client_api::light::{Fetcher, RemoteBlockchain};
|
||||
use sc_rpc_api::{state::ReadProof, DenyUnsafe};
|
||||
use sp_core::{
|
||||
storage::{PrefixedStorageKey, StorageChangeSet, StorageData, StorageKey},
|
||||
Bytes,
|
||||
};
|
||||
use sp_runtime::traits::Block as BlockT;
|
||||
use sp_version::RuntimeVersion;
|
||||
|
||||
use sp_api::{Metadata, ProvideRuntimeApi, CallApiAt};
|
||||
use sp_api::{CallApiAt, Metadata, ProvideRuntimeApi};
|
||||
|
||||
use self::error::{Error, FutureResult};
|
||||
|
||||
pub use sc_rpc_api::state::*;
|
||||
pub use sc_rpc_api::child_state::*;
|
||||
use sc_client_api::{
|
||||
ExecutorProvider, StorageProvider, BlockchainEvents, Backend, BlockBackend, ProofProvider
|
||||
Backend, BlockBackend, BlockchainEvents, ExecutorProvider, ProofProvider, StorageProvider,
|
||||
};
|
||||
use sp_blockchain::{HeaderMetadata, HeaderBackend};
|
||||
pub use sc_rpc_api::{child_state::*, state::*};
|
||||
use sp_blockchain::{HeaderBackend, HeaderMetadata};
|
||||
|
||||
const STORAGE_KEYS_PAGED_MAX_COUNT: u32 = 1000;
|
||||
|
||||
/// State backend API.
|
||||
pub trait StateBackend<Block: BlockT, Client>: Send + Sync + 'static
|
||||
where
|
||||
Block: BlockT + 'static,
|
||||
Client: Send + Sync + 'static,
|
||||
where
|
||||
Block: BlockT + 'static,
|
||||
Client: Send + Sync + 'static,
|
||||
{
|
||||
/// Call runtime method at given block.
|
||||
fn call(
|
||||
@@ -129,7 +134,7 @@ pub trait StateBackend<Block: BlockT, Client>: Send + Sync + 'static
|
||||
fn query_storage_at(
|
||||
&self,
|
||||
keys: Vec<StorageKey>,
|
||||
at: Option<Block::Hash>
|
||||
at: Option<Block::Hash>,
|
||||
) -> FutureResult<Vec<StorageChangeSet<Block::Hash>>>;
|
||||
|
||||
/// Returns proof of storage entries at a specific block's state.
|
||||
@@ -184,21 +189,30 @@ pub fn new_full<BE, Block: BlockT, Client>(
|
||||
deny_unsafe: DenyUnsafe,
|
||||
rpc_max_payload: Option<usize>,
|
||||
) -> (State<Block, Client>, ChildState<Block, Client>)
|
||||
where
|
||||
Block: BlockT + 'static,
|
||||
BE: Backend<Block> + 'static,
|
||||
Client: ExecutorProvider<Block> + StorageProvider<Block, BE> + ProofProvider<Block>
|
||||
+ HeaderMetadata<Block, Error = sp_blockchain::Error> + BlockchainEvents<Block>
|
||||
+ CallApiAt<Block> + HeaderBackend<Block>
|
||||
+ BlockBackend<Block> + ProvideRuntimeApi<Block> + Send + Sync + 'static,
|
||||
Client::Api: Metadata<Block>,
|
||||
where
|
||||
Block: BlockT + 'static,
|
||||
BE: Backend<Block> + 'static,
|
||||
Client: ExecutorProvider<Block>
|
||||
+ StorageProvider<Block, BE>
|
||||
+ ProofProvider<Block>
|
||||
+ HeaderMetadata<Block, Error = sp_blockchain::Error>
|
||||
+ BlockchainEvents<Block>
|
||||
+ CallApiAt<Block>
|
||||
+ HeaderBackend<Block>
|
||||
+ BlockBackend<Block>
|
||||
+ ProvideRuntimeApi<Block>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
Client::Api: Metadata<Block>,
|
||||
{
|
||||
let child_backend = Box::new(
|
||||
self::state_full::FullState::new(
|
||||
client.clone(), subscriptions.clone(), rpc_max_payload
|
||||
)
|
||||
);
|
||||
let backend = Box::new(self::state_full::FullState::new(client, subscriptions, rpc_max_payload));
|
||||
let child_backend = Box::new(self::state_full::FullState::new(
|
||||
client.clone(),
|
||||
subscriptions.clone(),
|
||||
rpc_max_payload,
|
||||
));
|
||||
let backend =
|
||||
Box::new(self::state_full::FullState::new(client, subscriptions, rpc_max_payload));
|
||||
(State { backend, deny_unsafe }, ChildState { backend: child_backend })
|
||||
}
|
||||
|
||||
@@ -210,27 +224,32 @@ pub fn new_light<BE, Block: BlockT, Client, F: Fetcher<Block>>(
|
||||
fetcher: Arc<F>,
|
||||
deny_unsafe: DenyUnsafe,
|
||||
) -> (State<Block, Client>, ChildState<Block, Client>)
|
||||
where
|
||||
Block: BlockT + 'static,
|
||||
BE: Backend<Block> + 'static,
|
||||
Client: ExecutorProvider<Block> + StorageProvider<Block, BE>
|
||||
+ HeaderMetadata<Block, Error = sp_blockchain::Error>
|
||||
+ ProvideRuntimeApi<Block> + HeaderBackend<Block> + BlockchainEvents<Block>
|
||||
+ Send + Sync + 'static,
|
||||
F: Send + Sync + 'static,
|
||||
where
|
||||
Block: BlockT + 'static,
|
||||
BE: Backend<Block> + 'static,
|
||||
Client: ExecutorProvider<Block>
|
||||
+ StorageProvider<Block, BE>
|
||||
+ HeaderMetadata<Block, Error = sp_blockchain::Error>
|
||||
+ ProvideRuntimeApi<Block>
|
||||
+ HeaderBackend<Block>
|
||||
+ BlockchainEvents<Block>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
F: Send + Sync + 'static,
|
||||
{
|
||||
let child_backend = Box::new(self::state_light::LightState::new(
|
||||
client.clone(),
|
||||
subscriptions.clone(),
|
||||
remote_blockchain.clone(),
|
||||
fetcher.clone(),
|
||||
client.clone(),
|
||||
subscriptions.clone(),
|
||||
remote_blockchain.clone(),
|
||||
fetcher.clone(),
|
||||
));
|
||||
|
||||
let backend = Box::new(self::state_light::LightState::new(
|
||||
client,
|
||||
subscriptions,
|
||||
remote_blockchain,
|
||||
fetcher,
|
||||
client,
|
||||
subscriptions,
|
||||
remote_blockchain,
|
||||
fetcher,
|
||||
));
|
||||
(State { backend, deny_unsafe }, ChildState { backend: child_backend })
|
||||
}
|
||||
@@ -243,9 +262,9 @@ pub struct State<Block, Client> {
|
||||
}
|
||||
|
||||
impl<Block, Client> StateApi<Block::Hash> for State<Block, Client>
|
||||
where
|
||||
Block: BlockT + 'static,
|
||||
Client: Send + Sync + 'static,
|
||||
where
|
||||
Block: BlockT + 'static,
|
||||
Client: Send + Sync + 'static,
|
||||
{
|
||||
type Metadata = crate::Metadata;
|
||||
|
||||
@@ -281,25 +300,35 @@ impl<Block, Client> StateApi<Block::Hash> for State<Block, Client>
|
||||
block: Option<Block::Hash>,
|
||||
) -> FutureResult<Vec<StorageKey>> {
|
||||
if count > STORAGE_KEYS_PAGED_MAX_COUNT {
|
||||
return Box::new(result(Err(
|
||||
Error::InvalidCount {
|
||||
value: count,
|
||||
max: STORAGE_KEYS_PAGED_MAX_COUNT,
|
||||
}
|
||||
)));
|
||||
return Box::new(result(Err(Error::InvalidCount {
|
||||
value: count,
|
||||
max: STORAGE_KEYS_PAGED_MAX_COUNT,
|
||||
})))
|
||||
}
|
||||
self.backend.storage_keys_paged(block, prefix, count, start_key)
|
||||
}
|
||||
|
||||
fn storage(&self, key: StorageKey, block: Option<Block::Hash>) -> FutureResult<Option<StorageData>> {
|
||||
fn storage(
|
||||
&self,
|
||||
key: StorageKey,
|
||||
block: Option<Block::Hash>,
|
||||
) -> FutureResult<Option<StorageData>> {
|
||||
self.backend.storage(block, key)
|
||||
}
|
||||
|
||||
fn storage_hash(&self, key: StorageKey, block: Option<Block::Hash>) -> FutureResult<Option<Block::Hash>> {
|
||||
fn storage_hash(
|
||||
&self,
|
||||
key: StorageKey,
|
||||
block: Option<Block::Hash>,
|
||||
) -> FutureResult<Option<Block::Hash>> {
|
||||
self.backend.storage_hash(block, key)
|
||||
}
|
||||
|
||||
fn storage_size(&self, key: StorageKey, block: Option<Block::Hash>) -> FutureResult<Option<u64>> {
|
||||
fn storage_size(
|
||||
&self,
|
||||
key: StorageKey,
|
||||
block: Option<Block::Hash>,
|
||||
) -> FutureResult<Option<u64>> {
|
||||
self.backend.storage_size(block, key)
|
||||
}
|
||||
|
||||
@@ -311,7 +340,7 @@ impl<Block, Client> StateApi<Block::Hash> for State<Block, Client>
|
||||
&self,
|
||||
keys: Vec<StorageKey>,
|
||||
from: Block::Hash,
|
||||
to: Option<Block::Hash>
|
||||
to: Option<Block::Hash>,
|
||||
) -> FutureResult<Vec<StorageChangeSet<Block::Hash>>> {
|
||||
if let Err(err) = self.deny_unsafe.check_if_safe() {
|
||||
return Box::new(result(Err(err.into())))
|
||||
@@ -323,12 +352,16 @@ impl<Block, Client> StateApi<Block::Hash> for State<Block, Client>
|
||||
fn query_storage_at(
|
||||
&self,
|
||||
keys: Vec<StorageKey>,
|
||||
at: Option<Block::Hash>
|
||||
at: Option<Block::Hash>,
|
||||
) -> FutureResult<Vec<StorageChangeSet<Block::Hash>>> {
|
||||
self.backend.query_storage_at(keys, at)
|
||||
}
|
||||
|
||||
fn read_proof(&self, keys: Vec<StorageKey>, block: Option<Block::Hash>) -> FutureResult<ReadProof<Block::Hash>> {
|
||||
fn read_proof(
|
||||
&self,
|
||||
keys: Vec<StorageKey>,
|
||||
block: Option<Block::Hash>,
|
||||
) -> FutureResult<ReadProof<Block::Hash>> {
|
||||
self.backend.read_proof(block, keys)
|
||||
}
|
||||
|
||||
@@ -336,12 +369,16 @@ impl<Block, Client> StateApi<Block::Hash> for State<Block, Client>
|
||||
&self,
|
||||
meta: Self::Metadata,
|
||||
subscriber: Subscriber<StorageChangeSet<Block::Hash>>,
|
||||
keys: Option<Vec<StorageKey>>
|
||||
keys: Option<Vec<StorageKey>>,
|
||||
) {
|
||||
self.backend.subscribe_storage(meta, subscriber, keys);
|
||||
}
|
||||
|
||||
fn unsubscribe_storage(&self, meta: Option<Self::Metadata>, id: SubscriptionId) -> RpcResult<bool> {
|
||||
fn unsubscribe_storage(
|
||||
&self,
|
||||
meta: Option<Self::Metadata>,
|
||||
id: SubscriptionId,
|
||||
) -> RpcResult<bool> {
|
||||
self.backend.unsubscribe_storage(meta, id)
|
||||
}
|
||||
|
||||
@@ -349,7 +386,11 @@ impl<Block, Client> StateApi<Block::Hash> for State<Block, Client>
|
||||
self.backend.runtime_version(at)
|
||||
}
|
||||
|
||||
fn subscribe_runtime_version(&self, meta: Self::Metadata, subscriber: Subscriber<RuntimeVersion>) {
|
||||
fn subscribe_runtime_version(
|
||||
&self,
|
||||
meta: Self::Metadata,
|
||||
subscriber: Subscriber<RuntimeVersion>,
|
||||
) {
|
||||
self.backend.subscribe_runtime_version(meta, subscriber);
|
||||
}
|
||||
|
||||
@@ -367,9 +408,10 @@ impl<Block, Client> StateApi<Block::Hash> for State<Block, Client>
|
||||
/// Note: requires the node to run with `--rpc-methods=Unsafe`.
|
||||
/// Note: requires runtimes compiled with wasm tracing support, `--features with-tracing`.
|
||||
fn trace_block(
|
||||
&self, block: Block::Hash,
|
||||
&self,
|
||||
block: Block::Hash,
|
||||
targets: Option<String>,
|
||||
storage_keys: Option<String>
|
||||
storage_keys: Option<String>,
|
||||
) -> FutureResult<sp_rpc::tracing::TraceBlockResponse> {
|
||||
if let Err(err) = self.deny_unsafe.check_if_safe() {
|
||||
return Box::new(result(Err(err.into())))
|
||||
@@ -381,9 +423,9 @@ impl<Block, Client> StateApi<Block::Hash> for State<Block, Client>
|
||||
|
||||
/// Child state backend API.
|
||||
pub trait ChildStateBackend<Block: BlockT, Client>: Send + Sync + 'static
|
||||
where
|
||||
Block: BlockT + 'static,
|
||||
Client: Send + Sync + 'static,
|
||||
where
|
||||
Block: BlockT + 'static,
|
||||
Client: Send + Sync + 'static,
|
||||
{
|
||||
/// Returns proof of storage for a child key entries at a specific block's state.
|
||||
fn read_child_proof(
|
||||
@@ -435,8 +477,7 @@ pub trait ChildStateBackend<Block: BlockT, Client>: Send + Sync + 'static
|
||||
storage_key: PrefixedStorageKey,
|
||||
key: StorageKey,
|
||||
) -> FutureResult<Option<u64>> {
|
||||
Box::new(self.storage(block, storage_key, key)
|
||||
.map(|x| x.map(|x| x.0.len() as u64)))
|
||||
Box::new(self.storage(block, storage_key, key).map(|x| x.map(|x| x.0.len() as u64)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -446,9 +487,9 @@ pub struct ChildState<Block, Client> {
|
||||
}
|
||||
|
||||
impl<Block, Client> ChildStateApi<Block::Hash> for ChildState<Block, Client>
|
||||
where
|
||||
Block: BlockT + 'static,
|
||||
Client: Send + Sync + 'static,
|
||||
where
|
||||
Block: BlockT + 'static,
|
||||
Client: Send + Sync + 'static,
|
||||
{
|
||||
type Metadata = crate::Metadata;
|
||||
|
||||
@@ -465,7 +506,7 @@ impl<Block, Client> ChildStateApi<Block::Hash> for ChildState<Block, Client>
|
||||
&self,
|
||||
storage_key: PrefixedStorageKey,
|
||||
key: StorageKey,
|
||||
block: Option<Block::Hash>
|
||||
block: Option<Block::Hash>,
|
||||
) -> FutureResult<Option<StorageData>> {
|
||||
self.backend.storage(block, storage_key, key)
|
||||
}
|
||||
@@ -474,7 +515,7 @@ impl<Block, Client> ChildStateApi<Block::Hash> for ChildState<Block, Client>
|
||||
&self,
|
||||
storage_key: PrefixedStorageKey,
|
||||
key_prefix: StorageKey,
|
||||
block: Option<Block::Hash>
|
||||
block: Option<Block::Hash>,
|
||||
) -> FutureResult<Vec<StorageKey>> {
|
||||
self.backend.storage_keys(block, storage_key, key_prefix)
|
||||
}
|
||||
@@ -494,7 +535,7 @@ impl<Block, Client> ChildStateApi<Block::Hash> for ChildState<Block, Client>
|
||||
&self,
|
||||
storage_key: PrefixedStorageKey,
|
||||
key: StorageKey,
|
||||
block: Option<Block::Hash>
|
||||
block: Option<Block::Hash>,
|
||||
) -> FutureResult<Option<Block::Hash>> {
|
||||
self.backend.storage_hash(block, storage_key, key)
|
||||
}
|
||||
@@ -503,11 +544,10 @@ impl<Block, Client> ChildStateApi<Block::Hash> for ChildState<Block, Client>
|
||||
&self,
|
||||
storage_key: PrefixedStorageKey,
|
||||
key: StorageKey,
|
||||
block: Option<Block::Hash>
|
||||
block: Option<Block::Hash>,
|
||||
) -> FutureResult<Option<u64>> {
|
||||
self.backend.storage_size(block, storage_key, key)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
fn client_err(err: sp_blockchain::Error) -> Error {
|
||||
|
||||
@@ -18,36 +18,49 @@
|
||||
|
||||
//! State API backend for full nodes.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::sync::Arc;
|
||||
use std::ops::Range;
|
||||
use futures::{future, StreamExt as _, TryStreamExt as _};
|
||||
use jsonrpc_pubsub::{manager::SubscriptionManager, typed::Subscriber, SubscriptionId};
|
||||
use log::warn;
|
||||
use jsonrpc_pubsub::{typed::Subscriber, SubscriptionId, manager::SubscriptionManager};
|
||||
use rpc::{Result as RpcResult, futures::{stream, Future, Sink, Stream, future::result}};
|
||||
use rpc::{
|
||||
futures::{future::result, stream, Future, Sink, Stream},
|
||||
Result as RpcResult,
|
||||
};
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
ops::Range,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use sc_rpc_api::state::ReadProof;
|
||||
use sp_blockchain::{
|
||||
Result as ClientResult, Error as ClientError, HeaderMetadata, CachedHeaderMetadata,
|
||||
HeaderBackend
|
||||
CachedHeaderMetadata, Error as ClientError, HeaderBackend, HeaderMetadata,
|
||||
Result as ClientResult,
|
||||
};
|
||||
use sp_core::{
|
||||
Bytes, storage::{well_known_keys, StorageKey, StorageData, StorageChangeSet,
|
||||
ChildInfo, ChildType, PrefixedStorageKey},
|
||||
storage::{
|
||||
well_known_keys, ChildInfo, ChildType, PrefixedStorageKey, StorageChangeSet, StorageData,
|
||||
StorageKey,
|
||||
},
|
||||
Bytes,
|
||||
};
|
||||
use sp_runtime::{
|
||||
generic::BlockId,
|
||||
traits::{Block as BlockT, CheckedSub, NumberFor, SaturatedConversion},
|
||||
};
|
||||
use sp_version::RuntimeVersion;
|
||||
use sp_runtime::{
|
||||
generic::BlockId, traits::{Block as BlockT, NumberFor, SaturatedConversion, CheckedSub},
|
||||
|
||||
use sp_api::{CallApiAt, Metadata, ProvideRuntimeApi};
|
||||
|
||||
use super::{
|
||||
client_err,
|
||||
error::{Error, FutureResult, Result},
|
||||
ChildStateBackend, StateBackend,
|
||||
};
|
||||
|
||||
use sp_api::{Metadata, ProvideRuntimeApi, CallApiAt};
|
||||
|
||||
use super::{StateBackend, ChildStateBackend, error::{FutureResult, Error, Result}, client_err};
|
||||
use std::marker::PhantomData;
|
||||
use sc_client_api::{
|
||||
Backend, BlockBackend, BlockchainEvents, CallExecutor, StorageProvider, ExecutorProvider,
|
||||
ProofProvider
|
||||
Backend, BlockBackend, BlockchainEvents, CallExecutor, ExecutorProvider, ProofProvider,
|
||||
StorageProvider,
|
||||
};
|
||||
use std::marker::PhantomData;
|
||||
|
||||
/// Ranges to query in state_queryStorage.
|
||||
struct QueryStorageRange<Block: BlockT> {
|
||||
@@ -72,11 +85,13 @@ pub struct FullState<BE, Block: BlockT, Client> {
|
||||
}
|
||||
|
||||
impl<BE, Block: BlockT, Client> FullState<BE, Block, Client>
|
||||
where
|
||||
BE: Backend<Block>,
|
||||
Client: StorageProvider<Block, BE> + HeaderBackend<Block> + BlockBackend<Block>
|
||||
+ HeaderMetadata<Block, Error = sp_blockchain::Error>,
|
||||
Block: BlockT + 'static,
|
||||
where
|
||||
BE: Backend<Block>,
|
||||
Client: StorageProvider<Block, BE>
|
||||
+ HeaderBackend<Block>
|
||||
+ BlockBackend<Block>
|
||||
+ HeaderMetadata<Block, Error = sp_blockchain::Error>,
|
||||
Block: BlockT + 'static,
|
||||
{
|
||||
/// Create new state API backend for full nodes.
|
||||
pub fn new(
|
||||
@@ -98,16 +113,23 @@ impl<BE, Block: BlockT, Client> FullState<BE, Block, Client>
|
||||
fn split_query_storage_range(
|
||||
&self,
|
||||
from: Block::Hash,
|
||||
to: Option<Block::Hash>
|
||||
to: Option<Block::Hash>,
|
||||
) -> Result<QueryStorageRange<Block>> {
|
||||
let to = self.block_or_best(to).map_err(|e| invalid_block::<Block>(from, to, e.to_string()))?;
|
||||
let to = self
|
||||
.block_or_best(to)
|
||||
.map_err(|e| invalid_block::<Block>(from, to, e.to_string()))?;
|
||||
|
||||
let invalid_block_err = |e: ClientError| invalid_block::<Block>(from, Some(to), e.to_string());
|
||||
let invalid_block_err =
|
||||
|e: ClientError| invalid_block::<Block>(from, Some(to), e.to_string());
|
||||
let from_meta = self.client.header_metadata(from).map_err(invalid_block_err)?;
|
||||
let to_meta = self.client.header_metadata(to).map_err(invalid_block_err)?;
|
||||
|
||||
if from_meta.number > to_meta.number {
|
||||
return Err(invalid_block_range(&from_meta, &to_meta, "from number > to number".to_owned()))
|
||||
return Err(invalid_block_range(
|
||||
&from_meta,
|
||||
&to_meta,
|
||||
"from number > to number".to_owned(),
|
||||
))
|
||||
}
|
||||
|
||||
// check if we can get from `to` to `from` by going through parent_hashes.
|
||||
@@ -116,28 +138,33 @@ impl<BE, Block: BlockT, Client> FullState<BE, Block, Client>
|
||||
let mut hashes = vec![to_meta.hash];
|
||||
let mut last = to_meta.clone();
|
||||
while last.number > from_number {
|
||||
let header_metadata = self.client
|
||||
let header_metadata = self
|
||||
.client
|
||||
.header_metadata(last.parent)
|
||||
.map_err(|e| invalid_block_range::<Block>(&last, &to_meta, e.to_string()))?;
|
||||
hashes.push(header_metadata.hash);
|
||||
last = header_metadata;
|
||||
}
|
||||
if last.hash != from_meta.hash {
|
||||
return Err(invalid_block_range(&from_meta, &to_meta, "from and to are on different forks".to_owned()))
|
||||
return Err(invalid_block_range(
|
||||
&from_meta,
|
||||
&to_meta,
|
||||
"from and to are on different forks".to_owned(),
|
||||
))
|
||||
}
|
||||
hashes.reverse();
|
||||
hashes
|
||||
};
|
||||
|
||||
// check if we can filter blocks-with-changes from some (sub)range using changes tries
|
||||
let changes_trie_range = self.client
|
||||
let changes_trie_range = self
|
||||
.client
|
||||
.max_key_changes_range(from_number, BlockId::Hash(to_meta.hash))
|
||||
.map_err(client_err)?;
|
||||
let filtered_range_begin = changes_trie_range
|
||||
.and_then(|(begin, _)| {
|
||||
// avoids a corner case where begin < from_number (happens when querying genesis)
|
||||
begin.checked_sub(&from_number).map(|x| x.saturated_into::<usize>())
|
||||
});
|
||||
let filtered_range_begin = changes_trie_range.and_then(|(begin, _)| {
|
||||
// avoids a corner case where begin < from_number (happens when querying genesis)
|
||||
begin.checked_sub(&from_number).map(|x| x.saturated_into::<usize>())
|
||||
});
|
||||
let (unfiltered_range, filtered_range) = split_range(hashes.len(), filtered_range_begin);
|
||||
|
||||
Ok(QueryStorageRange {
|
||||
@@ -158,7 +185,8 @@ impl<BE, Block: BlockT, Client> FullState<BE, Block, Client>
|
||||
) -> Result<()> {
|
||||
for block in range.unfiltered_range.start..range.unfiltered_range.end {
|
||||
let block_hash = range.hashes[block].clone();
|
||||
let mut block_changes = StorageChangeSet { block: block_hash.clone(), changes: Vec::new() };
|
||||
let mut block_changes =
|
||||
StorageChangeSet { block: block_hash.clone(), changes: Vec::new() };
|
||||
let id = BlockId::hash(block_hash);
|
||||
for key in keys {
|
||||
let (has_changed, data) = {
|
||||
@@ -191,30 +219,34 @@ impl<BE, Block: BlockT, Client> FullState<BE, Block, Client>
|
||||
let (begin, end) = match range.filtered_range {
|
||||
Some(ref filtered_range) => (
|
||||
range.first_number + filtered_range.start.saturated_into(),
|
||||
BlockId::Hash(range.hashes[filtered_range.end - 1].clone())
|
||||
BlockId::Hash(range.hashes[filtered_range.end - 1].clone()),
|
||||
),
|
||||
None => return Ok(()),
|
||||
};
|
||||
let mut changes_map: BTreeMap<NumberFor<Block>, StorageChangeSet<Block::Hash>> = BTreeMap::new();
|
||||
let mut changes_map: BTreeMap<NumberFor<Block>, StorageChangeSet<Block::Hash>> =
|
||||
BTreeMap::new();
|
||||
for key in keys {
|
||||
let mut last_block = None;
|
||||
let mut last_value = last_values.get(key).cloned().unwrap_or_default();
|
||||
let key_changes = self.client.key_changes(begin, end, None, key).map_err(client_err)?;
|
||||
for (block, _) in key_changes.into_iter().rev() {
|
||||
if last_block == Some(block) {
|
||||
continue;
|
||||
continue
|
||||
}
|
||||
|
||||
let block_hash = range.hashes[(block - range.first_number).saturated_into::<usize>()].clone();
|
||||
let block_hash =
|
||||
range.hashes[(block - range.first_number).saturated_into::<usize>()].clone();
|
||||
let id = BlockId::Hash(block_hash);
|
||||
let value_at_block = self.client.storage(&id, key).map_err(client_err)?;
|
||||
if last_value == value_at_block {
|
||||
continue;
|
||||
continue
|
||||
}
|
||||
|
||||
changes_map.entry(block)
|
||||
changes_map
|
||||
.entry(block)
|
||||
.or_insert_with(|| StorageChangeSet { block: block_hash, changes: Vec::new() })
|
||||
.changes.push((key.clone(), value_at_block.clone()));
|
||||
.changes
|
||||
.push((key.clone(), value_at_block.clone()));
|
||||
last_block = Some(block);
|
||||
last_value = value_at_block;
|
||||
}
|
||||
@@ -227,15 +259,22 @@ impl<BE, Block: BlockT, Client> FullState<BE, Block, Client>
|
||||
}
|
||||
}
|
||||
|
||||
impl<BE, Block, Client> StateBackend<Block, Client> for FullState<BE, Block, Client> where
|
||||
impl<BE, Block, Client> StateBackend<Block, Client> for FullState<BE, Block, Client>
|
||||
where
|
||||
Block: BlockT + 'static,
|
||||
BE: Backend<Block> + 'static,
|
||||
Client: ExecutorProvider<Block> + StorageProvider<Block, BE>
|
||||
+ ProofProvider<Block> + HeaderBackend<Block>
|
||||
+ HeaderMetadata<Block, Error = sp_blockchain::Error> + BlockchainEvents<Block>
|
||||
+ CallApiAt<Block> + ProvideRuntimeApi<Block>
|
||||
Client: ExecutorProvider<Block>
|
||||
+ StorageProvider<Block, BE>
|
||||
+ ProofProvider<Block>
|
||||
+ HeaderBackend<Block>
|
||||
+ HeaderMetadata<Block, Error = sp_blockchain::Error>
|
||||
+ BlockchainEvents<Block>
|
||||
+ CallApiAt<Block>
|
||||
+ ProvideRuntimeApi<Block>
|
||||
+ BlockBackend<Block>
|
||||
+ Send + Sync + 'static,
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
Client::Api: Metadata<Block>,
|
||||
{
|
||||
fn call(
|
||||
@@ -244,19 +283,21 @@ impl<BE, Block, Client> StateBackend<Block, Client> for FullState<BE, Block, Cli
|
||||
method: String,
|
||||
call_data: Bytes,
|
||||
) -> FutureResult<Bytes> {
|
||||
let r = self.block_or_best(block)
|
||||
.and_then(|block| self
|
||||
.client
|
||||
.executor()
|
||||
.call(
|
||||
&BlockId::Hash(block),
|
||||
&method,
|
||||
&*call_data,
|
||||
self.client.execution_extensions().strategies().other,
|
||||
None,
|
||||
)
|
||||
.map(Into::into)
|
||||
).map_err(client_err);
|
||||
let r = self
|
||||
.block_or_best(block)
|
||||
.and_then(|block| {
|
||||
self.client
|
||||
.executor()
|
||||
.call(
|
||||
&BlockId::Hash(block),
|
||||
&method,
|
||||
&*call_data,
|
||||
self.client.execution_extensions().strategies().other,
|
||||
None,
|
||||
)
|
||||
.map(Into::into)
|
||||
})
|
||||
.map_err(client_err);
|
||||
Box::new(result(r))
|
||||
}
|
||||
|
||||
@@ -268,7 +309,8 @@ impl<BE, Block, Client> StateBackend<Block, Client> for FullState<BE, Block, Cli
|
||||
Box::new(result(
|
||||
self.block_or_best(block)
|
||||
.and_then(|block| self.client.storage_keys(&BlockId::Hash(block), &prefix))
|
||||
.map_err(client_err)))
|
||||
.map_err(client_err),
|
||||
))
|
||||
}
|
||||
|
||||
fn storage_pairs(
|
||||
@@ -279,7 +321,8 @@ impl<BE, Block, Client> StateBackend<Block, Client> for FullState<BE, Block, Cli
|
||||
Box::new(result(
|
||||
self.block_or_best(block)
|
||||
.and_then(|block| self.client.storage_pairs(&BlockId::Hash(block), &prefix))
|
||||
.map_err(client_err)))
|
||||
.map_err(client_err),
|
||||
))
|
||||
}
|
||||
|
||||
fn storage_keys_paged(
|
||||
@@ -291,13 +334,16 @@ impl<BE, Block, Client> StateBackend<Block, Client> for FullState<BE, Block, Cli
|
||||
) -> FutureResult<Vec<StorageKey>> {
|
||||
Box::new(result(
|
||||
self.block_or_best(block)
|
||||
.and_then(|block|
|
||||
.and_then(|block| {
|
||||
self.client.storage_keys_iter(
|
||||
&BlockId::Hash(block), prefix.as_ref(), start_key.as_ref()
|
||||
&BlockId::Hash(block),
|
||||
prefix.as_ref(),
|
||||
start_key.as_ref(),
|
||||
)
|
||||
)
|
||||
})
|
||||
.map(|iter| iter.take(count as usize).collect())
|
||||
.map_err(client_err)))
|
||||
.map_err(client_err),
|
||||
))
|
||||
}
|
||||
|
||||
fn storage(
|
||||
@@ -308,7 +354,8 @@ impl<BE, Block, Client> StateBackend<Block, Client> for FullState<BE, Block, Cli
|
||||
Box::new(result(
|
||||
self.block_or_best(block)
|
||||
.and_then(|block| self.client.storage(&BlockId::Hash(block), &key))
|
||||
.map_err(client_err)))
|
||||
.map_err(client_err),
|
||||
))
|
||||
}
|
||||
|
||||
fn storage_size(
|
||||
@@ -328,7 +375,8 @@ impl<BE, Block, Client> StateBackend<Block, Client> for FullState<BE, Block, Cli
|
||||
}
|
||||
|
||||
Box::new(result(
|
||||
self.client.storage_pairs(&BlockId::Hash(block), &key)
|
||||
self.client
|
||||
.storage_pairs(&BlockId::Hash(block), &key)
|
||||
.map(|kv| {
|
||||
let item_sum = kv.iter().map(|(_, v)| v.0.len() as u64).sum::<u64>();
|
||||
if item_sum > 0 {
|
||||
@@ -337,7 +385,7 @@ impl<BE, Block, Client> StateBackend<Block, Client> for FullState<BE, Block, Cli
|
||||
None
|
||||
}
|
||||
})
|
||||
.map_err(client_err)
|
||||
.map_err(client_err),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -349,29 +397,26 @@ impl<BE, Block, Client> StateBackend<Block, Client> for FullState<BE, Block, Cli
|
||||
Box::new(result(
|
||||
self.block_or_best(block)
|
||||
.and_then(|block| self.client.storage_hash(&BlockId::Hash(block), &key))
|
||||
.map_err(client_err)))
|
||||
.map_err(client_err),
|
||||
))
|
||||
}
|
||||
|
||||
fn metadata(&self, block: Option<Block::Hash>) -> FutureResult<Bytes> {
|
||||
Box::new(result(
|
||||
self.block_or_best(block)
|
||||
.map_err(client_err)
|
||||
.and_then(|block|
|
||||
self.client.runtime_api().metadata(&BlockId::Hash(block))
|
||||
.map(Into::into)
|
||||
.map_err(|e| Error::Client(Box::new(e))))
|
||||
))
|
||||
Box::new(result(self.block_or_best(block).map_err(client_err).and_then(|block| {
|
||||
self.client
|
||||
.runtime_api()
|
||||
.metadata(&BlockId::Hash(block))
|
||||
.map(Into::into)
|
||||
.map_err(|e| Error::Client(Box::new(e)))
|
||||
})))
|
||||
}
|
||||
|
||||
fn runtime_version(&self, block: Option<Block::Hash>) -> FutureResult<RuntimeVersion> {
|
||||
Box::new(result(
|
||||
self.block_or_best(block)
|
||||
.map_err(client_err)
|
||||
.and_then(|block|
|
||||
self.client.runtime_version_at(&BlockId::Hash(block))
|
||||
.map_err(|e| Error::Client(Box::new(e)))
|
||||
)
|
||||
))
|
||||
Box::new(result(self.block_or_best(block).map_err(client_err).and_then(|block| {
|
||||
self.client
|
||||
.runtime_version_at(&BlockId::Hash(block))
|
||||
.map_err(|e| Error::Client(Box::new(e)))
|
||||
})))
|
||||
}
|
||||
|
||||
fn query_storage(
|
||||
@@ -394,7 +439,7 @@ impl<BE, Block, Client> StateBackend<Block, Client> for FullState<BE, Block, Cli
|
||||
fn query_storage_at(
|
||||
&self,
|
||||
keys: Vec<StorageKey>,
|
||||
at: Option<Block::Hash>
|
||||
at: Option<Block::Hash>,
|
||||
) -> FutureResult<Vec<StorageChangeSet<Block::Hash>>> {
|
||||
let at = at.unwrap_or_else(|| self.client.info().best_hash);
|
||||
self.query_storage(at, Some(at), keys)
|
||||
@@ -432,14 +477,12 @@ impl<BE, Block, Client> StateBackend<Block, Client> for FullState<BE, Block, Cli
|
||||
Ok(stream) => stream,
|
||||
Err(err) => {
|
||||
let _ = subscriber.reject(Error::from(client_err(err)).into());
|
||||
return;
|
||||
}
|
||||
return
|
||||
},
|
||||
};
|
||||
|
||||
self.subscriptions.add(subscriber, |sink| {
|
||||
let version = self.runtime_version(None.into())
|
||||
.map_err(Into::into)
|
||||
.wait();
|
||||
let version = self.runtime_version(None.into()).map_err(Into::into).wait();
|
||||
|
||||
let client = self.client.clone();
|
||||
let mut previous_version = version.clone();
|
||||
@@ -460,12 +503,8 @@ impl<BE, Block, Client> StateBackend<Block, Client> for FullState<BE, Block, Cli
|
||||
})
|
||||
.compat();
|
||||
|
||||
sink
|
||||
.sink_map_err(|e| warn!("Error sending notifications: {:?}", e))
|
||||
.send_all(
|
||||
stream::iter_result(vec![Ok(version)])
|
||||
.chain(stream)
|
||||
)
|
||||
sink.sink_map_err(|e| warn!("Error sending notifications: {:?}", e))
|
||||
.send_all(stream::iter_result(vec![Ok(version)]).chain(stream))
|
||||
// we ignore the resulting Stream (if the first stream is over we are unsubscribed)
|
||||
.map(|_| ())
|
||||
});
|
||||
@@ -486,45 +525,55 @@ impl<BE, Block, Client> StateBackend<Block, Client> for FullState<BE, Block, Cli
|
||||
keys: Option<Vec<StorageKey>>,
|
||||
) {
|
||||
let keys = Into::<Option<Vec<_>>>::into(keys);
|
||||
let stream = match self.client.storage_changes_notification_stream(
|
||||
keys.as_ref().map(|x| &**x),
|
||||
None
|
||||
) {
|
||||
let stream = match self
|
||||
.client
|
||||
.storage_changes_notification_stream(keys.as_ref().map(|x| &**x), None)
|
||||
{
|
||||
Ok(stream) => stream,
|
||||
Err(err) => {
|
||||
let _ = subscriber.reject(client_err(err).into());
|
||||
return;
|
||||
return
|
||||
},
|
||||
};
|
||||
|
||||
// initial values
|
||||
let initial = stream::iter_result(keys
|
||||
.map(|keys| {
|
||||
let initial = stream::iter_result(
|
||||
keys.map(|keys| {
|
||||
let block = self.client.info().best_hash;
|
||||
let changes = keys
|
||||
.into_iter()
|
||||
.map(|key| StateBackend::storage(self, Some(block.clone()).into(), key.clone())
|
||||
.map(|val| (key.clone(), val))
|
||||
.wait()
|
||||
.unwrap_or_else(|_| (key, None))
|
||||
)
|
||||
.map(|key| {
|
||||
StateBackend::storage(self, Some(block.clone()).into(), key.clone())
|
||||
.map(|val| (key.clone(), val))
|
||||
.wait()
|
||||
.unwrap_or_else(|_| (key, None))
|
||||
})
|
||||
.collect();
|
||||
vec![Ok(Ok(StorageChangeSet { block, changes }))]
|
||||
}).unwrap_or_default());
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
|
||||
self.subscriptions.add(subscriber, |sink| {
|
||||
let stream = stream
|
||||
.map(|(block, changes)| Ok::<_, ()>(Ok(StorageChangeSet {
|
||||
block,
|
||||
changes: changes.iter()
|
||||
.filter_map(|(o_sk, k, v)| if o_sk.is_none() {
|
||||
Some((k.clone(),v.cloned()))
|
||||
} else { None }).collect(),
|
||||
})))
|
||||
.map(|(block, changes)| {
|
||||
Ok::<_, ()>(Ok(StorageChangeSet {
|
||||
block,
|
||||
changes: changes
|
||||
.iter()
|
||||
.filter_map(|(o_sk, k, v)| {
|
||||
if o_sk.is_none() {
|
||||
Some((k.clone(), v.cloned()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
}))
|
||||
})
|
||||
.compat();
|
||||
|
||||
sink
|
||||
.sink_map_err(|e| warn!("Error sending notifications: {:?}", e))
|
||||
sink.sink_map_err(|e| warn!("Error sending notifications: {:?}", e))
|
||||
.send_all(initial.chain(stream))
|
||||
// we ignore the resulting Stream (if the first stream is over we are unsubscribed)
|
||||
.map(|_| ())
|
||||
@@ -553,21 +602,29 @@ impl<BE, Block, Client> StateBackend<Block, Client> for FullState<BE, Block, Cli
|
||||
self.rpc_max_payload,
|
||||
);
|
||||
Box::new(result(
|
||||
block_executor.trace_block()
|
||||
.map_err(|e| invalid_block::<Block>(block, None, e.to_string()))
|
||||
block_executor
|
||||
.trace_block()
|
||||
.map_err(|e| invalid_block::<Block>(block, None, e.to_string())),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl<BE, Block, Client> ChildStateBackend<Block, Client> for FullState<BE, Block, Client> where
|
||||
impl<BE, Block, Client> ChildStateBackend<Block, Client> for FullState<BE, Block, Client>
|
||||
where
|
||||
Block: BlockT + 'static,
|
||||
BE: Backend<Block> + 'static,
|
||||
Client: ExecutorProvider<Block> + StorageProvider<Block, BE>
|
||||
Client: ExecutorProvider<Block>
|
||||
+ StorageProvider<Block, BE>
|
||||
+ ProofProvider<Block>
|
||||
+ HeaderBackend<Block> + BlockBackend<Block>
|
||||
+ HeaderMetadata<Block, Error = sp_blockchain::Error> + BlockchainEvents<Block>
|
||||
+ CallApiAt<Block> + ProvideRuntimeApi<Block>
|
||||
+ Send + Sync + 'static,
|
||||
+ HeaderBackend<Block>
|
||||
+ BlockBackend<Block>
|
||||
+ HeaderMetadata<Block, Error = sp_blockchain::Error>
|
||||
+ BlockchainEvents<Block>
|
||||
+ CallApiAt<Block>
|
||||
+ ProvideRuntimeApi<Block>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
Client::Api: Metadata<Block>,
|
||||
{
|
||||
fn read_child_proof(
|
||||
@@ -580,7 +637,8 @@ impl<BE, Block, Client> ChildStateBackend<Block, Client> for FullState<BE, Block
|
||||
self.block_or_best(block)
|
||||
.and_then(|block| {
|
||||
let child_info = match ChildType::from_prefixed_key(&storage_key) {
|
||||
Some((ChildType::ParentKeyId, storage_key)) => ChildInfo::new_default(storage_key),
|
||||
Some((ChildType::ParentKeyId, storage_key)) =>
|
||||
ChildInfo::new_default(storage_key),
|
||||
None => return Err(sp_blockchain::Error::InvalidChildStorageKey),
|
||||
};
|
||||
self.client
|
||||
@@ -606,16 +664,14 @@ impl<BE, Block, Client> ChildStateBackend<Block, Client> for FullState<BE, Block
|
||||
self.block_or_best(block)
|
||||
.and_then(|block| {
|
||||
let child_info = match ChildType::from_prefixed_key(&storage_key) {
|
||||
Some((ChildType::ParentKeyId, storage_key)) => ChildInfo::new_default(storage_key),
|
||||
Some((ChildType::ParentKeyId, storage_key)) =>
|
||||
ChildInfo::new_default(storage_key),
|
||||
None => return Err(sp_blockchain::Error::InvalidChildStorageKey),
|
||||
};
|
||||
self.client.child_storage_keys(
|
||||
&BlockId::Hash(block),
|
||||
&child_info,
|
||||
&prefix,
|
||||
)
|
||||
self.client.child_storage_keys(&BlockId::Hash(block), &child_info, &prefix)
|
||||
})
|
||||
.map_err(client_err)))
|
||||
.map_err(client_err),
|
||||
))
|
||||
}
|
||||
|
||||
fn storage_keys_paged(
|
||||
@@ -630,15 +686,20 @@ impl<BE, Block, Client> ChildStateBackend<Block, Client> for FullState<BE, Block
|
||||
self.block_or_best(block)
|
||||
.and_then(|block| {
|
||||
let child_info = match ChildType::from_prefixed_key(&storage_key) {
|
||||
Some((ChildType::ParentKeyId, storage_key)) => ChildInfo::new_default(storage_key),
|
||||
Some((ChildType::ParentKeyId, storage_key)) =>
|
||||
ChildInfo::new_default(storage_key),
|
||||
None => return Err(sp_blockchain::Error::InvalidChildStorageKey),
|
||||
};
|
||||
self.client.child_storage_keys_iter(
|
||||
&BlockId::Hash(block), child_info, prefix.as_ref(), start_key.as_ref(),
|
||||
&BlockId::Hash(block),
|
||||
child_info,
|
||||
prefix.as_ref(),
|
||||
start_key.as_ref(),
|
||||
)
|
||||
})
|
||||
.map(|iter| iter.take(count as usize).collect())
|
||||
.map_err(client_err)))
|
||||
.map_err(client_err),
|
||||
))
|
||||
}
|
||||
|
||||
fn storage(
|
||||
@@ -651,16 +712,14 @@ impl<BE, Block, Client> ChildStateBackend<Block, Client> for FullState<BE, Block
|
||||
self.block_or_best(block)
|
||||
.and_then(|block| {
|
||||
let child_info = match ChildType::from_prefixed_key(&storage_key) {
|
||||
Some((ChildType::ParentKeyId, storage_key)) => ChildInfo::new_default(storage_key),
|
||||
Some((ChildType::ParentKeyId, storage_key)) =>
|
||||
ChildInfo::new_default(storage_key),
|
||||
None => return Err(sp_blockchain::Error::InvalidChildStorageKey),
|
||||
};
|
||||
self.client.child_storage(
|
||||
&BlockId::Hash(block),
|
||||
&child_info,
|
||||
&key,
|
||||
)
|
||||
self.client.child_storage(&BlockId::Hash(block), &child_info, &key)
|
||||
})
|
||||
.map_err(client_err)))
|
||||
.map_err(client_err),
|
||||
))
|
||||
}
|
||||
|
||||
fn storage_hash(
|
||||
@@ -673,23 +732,24 @@ impl<BE, Block, Client> ChildStateBackend<Block, Client> for FullState<BE, Block
|
||||
self.block_or_best(block)
|
||||
.and_then(|block| {
|
||||
let child_info = match ChildType::from_prefixed_key(&storage_key) {
|
||||
Some((ChildType::ParentKeyId, storage_key)) => ChildInfo::new_default(storage_key),
|
||||
Some((ChildType::ParentKeyId, storage_key)) =>
|
||||
ChildInfo::new_default(storage_key),
|
||||
None => return Err(sp_blockchain::Error::InvalidChildStorageKey),
|
||||
};
|
||||
self.client.child_storage_hash(
|
||||
&BlockId::Hash(block),
|
||||
&child_info,
|
||||
&key,
|
||||
)
|
||||
self.client.child_storage_hash(&BlockId::Hash(block), &child_info, &key)
|
||||
})
|
||||
.map_err(client_err)))
|
||||
.map_err(client_err),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits passed range into two subranges where:
|
||||
/// - first range has at least one element in it;
|
||||
/// - second range (optionally) starts at given `middle` element.
|
||||
pub(crate) fn split_range(size: usize, middle: Option<usize>) -> (Range<usize>, Option<Range<usize>>) {
|
||||
pub(crate) fn split_range(
|
||||
size: usize,
|
||||
middle: Option<usize>,
|
||||
) -> (Range<usize>, Option<Range<usize>>) {
|
||||
// check if we can filter blocks-with-changes from some (sub)range using changes tries
|
||||
let range2_begin = match middle {
|
||||
// some of required changes tries are pruned => use available tries
|
||||
@@ -714,21 +774,9 @@ fn invalid_block_range<B: BlockT>(
|
||||
) -> Error {
|
||||
let to_string = |h: &CachedHeaderMetadata<B>| format!("{} ({:?})", h.number, h.hash);
|
||||
|
||||
Error::InvalidBlockRange {
|
||||
from: to_string(from),
|
||||
to: to_string(to),
|
||||
details,
|
||||
}
|
||||
Error::InvalidBlockRange { from: to_string(from), to: to_string(to), details }
|
||||
}
|
||||
|
||||
fn invalid_block<B: BlockT>(
|
||||
from: B::Hash,
|
||||
to: Option<B::Hash>,
|
||||
details: String,
|
||||
) -> Error {
|
||||
Error::InvalidBlockRange {
|
||||
from: format!("{:?}", from),
|
||||
to: format!("{:?}", to),
|
||||
details,
|
||||
}
|
||||
fn invalid_block<B: BlockT>(from: B::Hash, to: Option<B::Hash>, details: String) -> Error {
|
||||
Error::InvalidBlockRange { from: format!("{:?}", from), to: format!("{:?}", to), details }
|
||||
}
|
||||
|
||||
@@ -18,45 +18,53 @@
|
||||
|
||||
//! State API backend for light nodes.
|
||||
|
||||
use std::{
|
||||
sync::Arc,
|
||||
collections::{HashSet, HashMap, hash_map::Entry},
|
||||
};
|
||||
use codec::Decode;
|
||||
use futures::{
|
||||
future::{ready, Either},
|
||||
channel::oneshot::{channel, Sender},
|
||||
FutureExt, TryFutureExt,
|
||||
StreamExt as _, TryStreamExt as _,
|
||||
future::{ready, Either},
|
||||
FutureExt, StreamExt as _, TryFutureExt, TryStreamExt as _,
|
||||
};
|
||||
use hash_db::Hasher;
|
||||
use jsonrpc_pubsub::{typed::Subscriber, SubscriptionId, manager::SubscriptionManager};
|
||||
use jsonrpc_pubsub::{manager::SubscriptionManager, typed::Subscriber, SubscriptionId};
|
||||
use log::warn;
|
||||
use parking_lot::Mutex;
|
||||
use rpc::{
|
||||
futures::{
|
||||
future::{result, Future},
|
||||
stream::Stream,
|
||||
Sink,
|
||||
},
|
||||
Result as RpcResult,
|
||||
futures::Sink,
|
||||
futures::future::{result, Future},
|
||||
futures::stream::Stream,
|
||||
};
|
||||
use std::{
|
||||
collections::{hash_map::Entry, HashMap, HashSet},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use sc_client_api::{
|
||||
light::{
|
||||
future_header, Fetcher, RemoteBlockchain, RemoteCallRequest, RemoteReadChildRequest,
|
||||
RemoteReadRequest,
|
||||
},
|
||||
BlockchainEvents,
|
||||
};
|
||||
use sc_rpc_api::state::ReadProof;
|
||||
use sp_blockchain::{Error as ClientError, HeaderBackend};
|
||||
use sc_client_api::{
|
||||
BlockchainEvents,
|
||||
light::{
|
||||
RemoteCallRequest, RemoteReadRequest, RemoteReadChildRequest,
|
||||
RemoteBlockchain, Fetcher, future_header,
|
||||
},
|
||||
};
|
||||
use sp_core::{
|
||||
storage::{PrefixedStorageKey, StorageChangeSet, StorageData, StorageKey},
|
||||
Bytes, OpaqueMetadata,
|
||||
storage::{StorageKey, PrefixedStorageKey, StorageData, StorageChangeSet},
|
||||
};
|
||||
use sp_runtime::{
|
||||
generic::BlockId,
|
||||
traits::{Block as BlockT, HashFor},
|
||||
};
|
||||
use sp_version::RuntimeVersion;
|
||||
use sp_runtime::{generic::BlockId, traits::{Block as BlockT, HashFor}};
|
||||
|
||||
use super::{StateBackend, ChildStateBackend, error::{FutureResult, Error}, client_err};
|
||||
use super::{
|
||||
client_err,
|
||||
error::{Error, FutureResult},
|
||||
ChildStateBackend, StateBackend,
|
||||
};
|
||||
|
||||
/// Storage data map of storage keys => (optional) storage value.
|
||||
type StorageMap = HashMap<StorageKey, Option<StorageData>>;
|
||||
@@ -77,11 +85,7 @@ trait SharedRequests<Hash, V>: Clone + Send + Sync {
|
||||
/// Tries to listen for already issued request, or issues request.
|
||||
///
|
||||
/// Returns true if requests has been issued.
|
||||
fn listen_request(
|
||||
&self,
|
||||
block: Hash,
|
||||
sender: Sender<Result<V, ()>>,
|
||||
) -> bool;
|
||||
fn listen_request(&self, block: Hash, sender: Sender<Result<V, ()>>) -> bool;
|
||||
|
||||
/// Returns (and forgets) all listeners for given request.
|
||||
fn on_response_received(&self, block: Hash) -> Vec<Sender<Result<V, ()>>>;
|
||||
@@ -97,12 +101,10 @@ struct StorageSubscriptions<Block: BlockT> {
|
||||
subscriptions_by_key: HashMap<StorageKey, HashSet<SubscriptionId>>,
|
||||
}
|
||||
|
||||
impl<Block: BlockT> SharedRequests<Block::Hash, StorageMap> for Arc<Mutex<StorageSubscriptions<Block>>> {
|
||||
fn listen_request(
|
||||
&self,
|
||||
block: Block::Hash,
|
||||
sender: Sender<Result<StorageMap, ()>>,
|
||||
) -> bool {
|
||||
impl<Block: BlockT> SharedRequests<Block::Hash, StorageMap>
|
||||
for Arc<Mutex<StorageSubscriptions<Block>>>
|
||||
{
|
||||
fn listen_request(&self, block: Block::Hash, sender: Sender<Result<StorageMap, ()>>) -> bool {
|
||||
let mut subscriptions = self.lock();
|
||||
let active_requests_at = subscriptions.active_requests.entry(block).or_default();
|
||||
active_requests_at.push(sender);
|
||||
@@ -117,15 +119,12 @@ impl<Block: BlockT> SharedRequests<Block::Hash, StorageMap> for Arc<Mutex<Storag
|
||||
/// Simple, maybe shared, subscription data that shares per block requests.
|
||||
type SimpleSubscriptions<Hash, V> = Arc<Mutex<HashMap<Hash, Vec<Sender<Result<V, ()>>>>>>;
|
||||
|
||||
impl<Hash, V> SharedRequests<Hash, V> for SimpleSubscriptions<Hash, V> where
|
||||
impl<Hash, V> SharedRequests<Hash, V> for SimpleSubscriptions<Hash, V>
|
||||
where
|
||||
Hash: Send + Eq + std::hash::Hash,
|
||||
V: Send,
|
||||
{
|
||||
fn listen_request(
|
||||
&self,
|
||||
block: Hash,
|
||||
sender: Sender<Result<V, ()>>,
|
||||
) -> bool {
|
||||
fn listen_request(&self, block: Hash, sender: Sender<Result<V, ()>>) -> bool {
|
||||
let mut subscriptions = self.lock();
|
||||
let active_requests_at = subscriptions.entry(block).or_default();
|
||||
active_requests_at.push(sender);
|
||||
@@ -138,9 +137,9 @@ impl<Hash, V> SharedRequests<Hash, V> for SimpleSubscriptions<Hash, V> where
|
||||
}
|
||||
|
||||
impl<Block: BlockT, F: Fetcher<Block> + 'static, Client> LightState<Block, F, Client>
|
||||
where
|
||||
Block: BlockT,
|
||||
Client: HeaderBackend<Block> + Send + Sync + 'static,
|
||||
where
|
||||
Block: BlockT,
|
||||
Client: HeaderBackend<Block> + Send + Sync + 'static,
|
||||
{
|
||||
/// Create new state API backend for light nodes.
|
||||
pub fn new(
|
||||
@@ -170,10 +169,10 @@ impl<Block: BlockT, F: Fetcher<Block> + 'static, Client> LightState<Block, F, Cl
|
||||
}
|
||||
|
||||
impl<Block, F, Client> StateBackend<Block, Client> for LightState<Block, F, Client>
|
||||
where
|
||||
Block: BlockT,
|
||||
Client: BlockchainEvents<Block> + HeaderBackend<Block> + Send + Sync + 'static,
|
||||
F: Fetcher<Block> + 'static
|
||||
where
|
||||
Block: BlockT,
|
||||
Client: BlockchainEvents<Block> + HeaderBackend<Block> + Send + Sync + 'static,
|
||||
F: Fetcher<Block> + 'static,
|
||||
{
|
||||
fn call(
|
||||
&self,
|
||||
@@ -181,13 +180,17 @@ impl<Block, F, Client> StateBackend<Block, Client> for LightState<Block, F, Clie
|
||||
method: String,
|
||||
call_data: Bytes,
|
||||
) -> FutureResult<Bytes> {
|
||||
Box::new(call(
|
||||
&*self.remote_blockchain,
|
||||
self.fetcher.clone(),
|
||||
self.block_or_best(block),
|
||||
method,
|
||||
call_data,
|
||||
).boxed().compat())
|
||||
Box::new(
|
||||
call(
|
||||
&*self.remote_blockchain,
|
||||
self.fetcher.clone(),
|
||||
self.block_or_best(block),
|
||||
method,
|
||||
call_data,
|
||||
)
|
||||
.boxed()
|
||||
.compat(),
|
||||
)
|
||||
}
|
||||
|
||||
fn storage_keys(
|
||||
@@ -216,11 +219,7 @@ impl<Block, F, Client> StateBackend<Block, Client> for LightState<Block, F, Clie
|
||||
Box::new(result(Err(client_err(ClientError::NotAvailableOnLightClient))))
|
||||
}
|
||||
|
||||
fn storage_size(
|
||||
&self,
|
||||
_: Option<Block::Hash>,
|
||||
_: StorageKey,
|
||||
) -> FutureResult<Option<u64>> {
|
||||
fn storage_size(&self, _: Option<Block::Hash>, _: StorageKey) -> FutureResult<Option<u64>> {
|
||||
Box::new(result(Err(client_err(ClientError::NotAvailableOnLightClient))))
|
||||
}
|
||||
|
||||
@@ -229,15 +228,21 @@ impl<Block, F, Client> StateBackend<Block, Client> for LightState<Block, F, Clie
|
||||
block: Option<Block::Hash>,
|
||||
key: StorageKey,
|
||||
) -> FutureResult<Option<StorageData>> {
|
||||
Box::new(storage(
|
||||
&*self.remote_blockchain,
|
||||
self.fetcher.clone(),
|
||||
self.block_or_best(block),
|
||||
vec![key.0.clone()],
|
||||
).boxed().compat().map(move |mut values| values
|
||||
.remove(&key)
|
||||
.expect("successful request has entries for all requested keys; qed")
|
||||
))
|
||||
Box::new(
|
||||
storage(
|
||||
&*self.remote_blockchain,
|
||||
self.fetcher.clone(),
|
||||
self.block_or_best(block),
|
||||
vec![key.0.clone()],
|
||||
)
|
||||
.boxed()
|
||||
.compat()
|
||||
.map(move |mut values| {
|
||||
values
|
||||
.remove(&key)
|
||||
.expect("successful request has entries for all requested keys; qed")
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
fn storage_hash(
|
||||
@@ -245,31 +250,38 @@ impl<Block, F, Client> StateBackend<Block, Client> for LightState<Block, F, Clie
|
||||
block: Option<Block::Hash>,
|
||||
key: StorageKey,
|
||||
) -> FutureResult<Option<Block::Hash>> {
|
||||
Box::new(StateBackend::storage(self, block, key)
|
||||
.and_then(|maybe_storage|
|
||||
result(Ok(maybe_storage.map(|storage| HashFor::<Block>::hash(&storage.0))))
|
||||
)
|
||||
)
|
||||
Box::new(StateBackend::storage(self, block, key).and_then(|maybe_storage| {
|
||||
result(Ok(maybe_storage.map(|storage| HashFor::<Block>::hash(&storage.0))))
|
||||
}))
|
||||
}
|
||||
|
||||
fn metadata(&self, block: Option<Block::Hash>) -> FutureResult<Bytes> {
|
||||
let metadata = self.call(block, "Metadata_metadata".into(), Bytes(Vec::new()))
|
||||
.and_then(|metadata| OpaqueMetadata::decode(&mut &metadata.0[..])
|
||||
.map(Into::into)
|
||||
.map_err(|decode_err| client_err(ClientError::CallResultDecode(
|
||||
"Unable to decode metadata",
|
||||
decode_err,
|
||||
))));
|
||||
let metadata =
|
||||
self.call(block, "Metadata_metadata".into(), Bytes(Vec::new()))
|
||||
.and_then(|metadata| {
|
||||
OpaqueMetadata::decode(&mut &metadata.0[..]).map(Into::into).map_err(
|
||||
|decode_err| {
|
||||
client_err(ClientError::CallResultDecode(
|
||||
"Unable to decode metadata",
|
||||
decode_err,
|
||||
))
|
||||
},
|
||||
)
|
||||
});
|
||||
|
||||
Box::new(metadata)
|
||||
}
|
||||
|
||||
fn runtime_version(&self, block: Option<Block::Hash>) -> FutureResult<RuntimeVersion> {
|
||||
Box::new(runtime_version(
|
||||
&*self.remote_blockchain,
|
||||
self.fetcher.clone(),
|
||||
self.block_or_best(block),
|
||||
).boxed().compat())
|
||||
Box::new(
|
||||
runtime_version(
|
||||
&*self.remote_blockchain,
|
||||
self.fetcher.clone(),
|
||||
self.block_or_best(block),
|
||||
)
|
||||
.boxed()
|
||||
.compat(),
|
||||
)
|
||||
}
|
||||
|
||||
fn query_storage(
|
||||
@@ -284,7 +296,7 @@ impl<Block, F, Client> StateBackend<Block, Client> for LightState<Block, F, Clie
|
||||
fn query_storage_at(
|
||||
&self,
|
||||
_keys: Vec<StorageKey>,
|
||||
_at: Option<Block::Hash>
|
||||
_at: Option<Block::Hash>,
|
||||
) -> FutureResult<Vec<StorageChangeSet<Block::Hash>>> {
|
||||
Box::new(result(Err(client_err(ClientError::NotAvailableOnLightClient))))
|
||||
}
|
||||
@@ -301,14 +313,14 @@ impl<Block, F, Client> StateBackend<Block, Client> for LightState<Block, F, Clie
|
||||
&self,
|
||||
_meta: crate::Metadata,
|
||||
subscriber: Subscriber<StorageChangeSet<Block::Hash>>,
|
||||
keys: Option<Vec<StorageKey>>
|
||||
keys: Option<Vec<StorageKey>>,
|
||||
) {
|
||||
let keys = match keys {
|
||||
Some(keys) if !keys.is_empty() => keys,
|
||||
_ => {
|
||||
warn!("Cannot subscribe to all keys on light client. Subscription rejected.");
|
||||
return;
|
||||
}
|
||||
return
|
||||
},
|
||||
};
|
||||
|
||||
let keys = keys.iter().cloned().collect::<HashSet<_>>();
|
||||
@@ -326,12 +338,10 @@ impl<Block, F, Client> StateBackend<Block, Client> for LightState<Block, F, Clie
|
||||
.import_notification_stream()
|
||||
.map(|notification| Ok::<_, ()>(notification.hash))
|
||||
.compat(),
|
||||
display_error(storage(
|
||||
&*remote_blockchain,
|
||||
fetcher.clone(),
|
||||
initial_block,
|
||||
initial_keys,
|
||||
).map(move |r| r.map(|r| (initial_block, r)))),
|
||||
display_error(
|
||||
storage(&*remote_blockchain, fetcher.clone(), initial_block, initial_keys)
|
||||
.map(move |r| r.map(|r| (initial_block, r))),
|
||||
),
|
||||
move |block| {
|
||||
// there'll be single request per block for all active subscriptions
|
||||
// with all subscribed keys
|
||||
@@ -342,12 +352,7 @@ impl<Block, F, Client> StateBackend<Block, Client> for LightState<Block, F, Clie
|
||||
.map(|k| k.0.clone())
|
||||
.collect();
|
||||
|
||||
storage(
|
||||
&*remote_blockchain,
|
||||
fetcher.clone(),
|
||||
block,
|
||||
keys,
|
||||
)
|
||||
storage(&*remote_blockchain, fetcher.clone(), block, keys)
|
||||
},
|
||||
move |block, old_value, new_value| {
|
||||
// let's only select keys which are valid for this subscription
|
||||
@@ -370,11 +375,10 @@ impl<Block, F, Client> StateBackend<Block, Client> for LightState<Block, F, Clie
|
||||
}),
|
||||
false => None,
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
sink
|
||||
.sink_map_err(|e| warn!("Error sending notifications: {:?}", e))
|
||||
sink.sink_map_err(|e| warn!("Error sending notifications: {:?}", e))
|
||||
.send_all(changes_stream.map(|changes| Ok(changes)))
|
||||
// we ignore the resulting Stream (if the first stream is over we are unsubscribed)
|
||||
.map(|_| ())
|
||||
@@ -382,7 +386,9 @@ impl<Block, F, Client> StateBackend<Block, Client> for LightState<Block, F, Clie
|
||||
|
||||
// remember keys associated with this subscription
|
||||
let mut storage_subscriptions = self.storage_subscriptions.lock();
|
||||
storage_subscriptions.keys_by_subscription.insert(subscription_id.clone(), keys.clone());
|
||||
storage_subscriptions
|
||||
.keys_by_subscription
|
||||
.insert(subscription_id.clone(), keys.clone());
|
||||
for key in keys {
|
||||
storage_subscriptions
|
||||
.subscriptions_by_key
|
||||
@@ -398,7 +404,7 @@ impl<Block, F, Client> StateBackend<Block, Client> for LightState<Block, F, Clie
|
||||
id: SubscriptionId,
|
||||
) -> RpcResult<bool> {
|
||||
if !self.subscriptions.cancel(id.clone()) {
|
||||
return Ok(false);
|
||||
return Ok(false)
|
||||
}
|
||||
|
||||
// forget subscription keys
|
||||
@@ -406,14 +412,16 @@ impl<Block, F, Client> StateBackend<Block, Client> for LightState<Block, F, Clie
|
||||
let keys = storage_subscriptions.keys_by_subscription.remove(&id);
|
||||
for key in keys.into_iter().flat_map(|keys| keys.into_iter()) {
|
||||
match storage_subscriptions.subscriptions_by_key.entry(key) {
|
||||
Entry::Vacant(_) => unreachable!("every key from keys_by_subscription has\
|
||||
corresponding entry in subscriptions_by_key; qed"),
|
||||
Entry::Vacant(_) => unreachable!(
|
||||
"every key from keys_by_subscription has\
|
||||
corresponding entry in subscriptions_by_key; qed"
|
||||
),
|
||||
Entry::Occupied(mut entry) => {
|
||||
entry.get_mut().remove(&id);
|
||||
if entry.get().is_empty() {
|
||||
entry.remove();
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -437,16 +445,11 @@ impl<Block, F, Client> StateBackend<Block, Client> for LightState<Block, F, Clie
|
||||
.import_notification_stream()
|
||||
.map(|notification| Ok::<_, ()>(notification.hash))
|
||||
.compat(),
|
||||
display_error(runtime_version(
|
||||
&*remote_blockchain,
|
||||
fetcher.clone(),
|
||||
initial_block,
|
||||
).map(move |r| r.map(|r| (initial_block, r)))),
|
||||
move |block| runtime_version(
|
||||
&*remote_blockchain,
|
||||
fetcher.clone(),
|
||||
block,
|
||||
display_error(
|
||||
runtime_version(&*remote_blockchain, fetcher.clone(), initial_block)
|
||||
.map(move |r| r.map(|r| (initial_block, r))),
|
||||
),
|
||||
move |block| runtime_version(&*remote_blockchain, fetcher.clone(), block),
|
||||
|_, old_version, new_version| {
|
||||
let version_differs = old_version
|
||||
.as_ref()
|
||||
@@ -456,11 +459,10 @@ impl<Block, F, Client> StateBackend<Block, Client> for LightState<Block, F, Clie
|
||||
true => Some(new_version.clone()),
|
||||
false => None,
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
sink
|
||||
.sink_map_err(|e| warn!("Error sending notifications: {:?}", e))
|
||||
sink.sink_map_err(|e| warn!("Error sending notifications: {:?}", e))
|
||||
.send_all(versions_stream.map(|version| Ok(version)))
|
||||
// we ignore the resulting Stream (if the first stream is over we are unsubscribed)
|
||||
.map(|_| ())
|
||||
@@ -486,10 +488,10 @@ impl<Block, F, Client> StateBackend<Block, Client> for LightState<Block, F, Clie
|
||||
}
|
||||
|
||||
impl<Block, F, Client> ChildStateBackend<Block, Client> for LightState<Block, F, Client>
|
||||
where
|
||||
Block: BlockT,
|
||||
Client: BlockchainEvents<Block> + HeaderBackend<Block> + Send + Sync + 'static,
|
||||
F: Fetcher<Block> + 'static
|
||||
where
|
||||
Block: BlockT,
|
||||
Client: BlockchainEvents<Block> + HeaderBackend<Block> + Send + Sync + 'static,
|
||||
F: Fetcher<Block> + 'static,
|
||||
{
|
||||
fn read_child_proof(
|
||||
&self,
|
||||
@@ -528,23 +530,34 @@ impl<Block, F, Client> ChildStateBackend<Block, Client> for LightState<Block, F,
|
||||
) -> FutureResult<Option<StorageData>> {
|
||||
let block = self.block_or_best(block);
|
||||
let fetcher = self.fetcher.clone();
|
||||
let child_storage = resolve_header(&*self.remote_blockchain, &*self.fetcher, block)
|
||||
.then(move |result| match result {
|
||||
Ok(header) => Either::Left(fetcher.remote_read_child(RemoteReadChildRequest {
|
||||
block,
|
||||
header,
|
||||
storage_key,
|
||||
keys: vec![key.0.clone()],
|
||||
retry_count: Default::default(),
|
||||
}).then(move |result| ready(result
|
||||
.map(|mut data| data
|
||||
.remove(&key.0)
|
||||
.expect("successful result has entry for all keys; qed")
|
||||
.map(StorageData)
|
||||
)
|
||||
.map_err(client_err)
|
||||
))),
|
||||
Err(error) => Either::Right(ready(Err(error))),
|
||||
let child_storage =
|
||||
resolve_header(&*self.remote_blockchain, &*self.fetcher, block).then(move |result| {
|
||||
match result {
|
||||
Ok(header) => Either::Left(
|
||||
fetcher
|
||||
.remote_read_child(RemoteReadChildRequest {
|
||||
block,
|
||||
header,
|
||||
storage_key,
|
||||
keys: vec![key.0.clone()],
|
||||
retry_count: Default::default(),
|
||||
})
|
||||
.then(move |result| {
|
||||
ready(
|
||||
result
|
||||
.map(|mut data| {
|
||||
data.remove(&key.0)
|
||||
.expect(
|
||||
"successful result has entry for all keys; qed",
|
||||
)
|
||||
.map(StorageData)
|
||||
})
|
||||
.map_err(client_err),
|
||||
)
|
||||
}),
|
||||
),
|
||||
Err(error) => Either::Right(ready(Err(error))),
|
||||
}
|
||||
});
|
||||
|
||||
Box::new(child_storage.boxed().compat())
|
||||
@@ -556,11 +569,11 @@ impl<Block, F, Client> ChildStateBackend<Block, Client> for LightState<Block, F,
|
||||
storage_key: PrefixedStorageKey,
|
||||
key: StorageKey,
|
||||
) -> FutureResult<Option<Block::Hash>> {
|
||||
Box::new(ChildStateBackend::storage(self, block, storage_key, key)
|
||||
.and_then(|maybe_storage|
|
||||
Box::new(ChildStateBackend::storage(self, block, storage_key, key).and_then(
|
||||
|maybe_storage| {
|
||||
result(Ok(maybe_storage.map(|storage| HashFor::<Block>::hash(&storage.0))))
|
||||
)
|
||||
)
|
||||
},
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -570,17 +583,17 @@ fn resolve_header<Block: BlockT, F: Fetcher<Block>>(
|
||||
fetcher: &F,
|
||||
block: Block::Hash,
|
||||
) -> impl std::future::Future<Output = Result<Block::Header, Error>> {
|
||||
let maybe_header = future_header(
|
||||
remote_blockchain,
|
||||
fetcher,
|
||||
BlockId::Hash(block),
|
||||
);
|
||||
let maybe_header = future_header(remote_blockchain, fetcher, BlockId::Hash(block));
|
||||
|
||||
maybe_header.then(move |result|
|
||||
ready(result.and_then(|maybe_header|
|
||||
maybe_header.ok_or_else(|| ClientError::UnknownBlock(format!("{}", block)))
|
||||
).map_err(client_err)),
|
||||
)
|
||||
maybe_header.then(move |result| {
|
||||
ready(
|
||||
result
|
||||
.and_then(|maybe_header| {
|
||||
maybe_header.ok_or_else(|| ClientError::UnknownBlock(format!("{}", block)))
|
||||
})
|
||||
.map_err(client_err),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Call runtime method at given block
|
||||
@@ -591,17 +604,20 @@ fn call<Block: BlockT, F: Fetcher<Block>>(
|
||||
method: String,
|
||||
call_data: Bytes,
|
||||
) -> impl std::future::Future<Output = Result<Bytes, Error>> {
|
||||
resolve_header(remote_blockchain, &*fetcher, block)
|
||||
.then(move |result| match result {
|
||||
Ok(header) => Either::Left(fetcher.remote_call(RemoteCallRequest {
|
||||
block,
|
||||
header,
|
||||
method,
|
||||
call_data: call_data.0,
|
||||
retry_count: Default::default(),
|
||||
}).then(|result| ready(result.map(Bytes).map_err(client_err)))),
|
||||
Err(error) => Either::Right(ready(Err(error))),
|
||||
})
|
||||
resolve_header(remote_blockchain, &*fetcher, block).then(move |result| match result {
|
||||
Ok(header) => Either::Left(
|
||||
fetcher
|
||||
.remote_call(RemoteCallRequest {
|
||||
block,
|
||||
header,
|
||||
method,
|
||||
call_data: call_data.0,
|
||||
retry_count: Default::default(),
|
||||
})
|
||||
.then(|result| ready(result.map(Bytes).map_err(client_err))),
|
||||
),
|
||||
Err(error) => Either::Right(ready(Err(error))),
|
||||
})
|
||||
}
|
||||
|
||||
/// Get runtime version at given block.
|
||||
@@ -610,17 +626,14 @@ fn runtime_version<Block: BlockT, F: Fetcher<Block>>(
|
||||
fetcher: Arc<F>,
|
||||
block: Block::Hash,
|
||||
) -> impl std::future::Future<Output = Result<RuntimeVersion, Error>> {
|
||||
call(
|
||||
remote_blockchain,
|
||||
fetcher,
|
||||
block,
|
||||
"Core_version".into(),
|
||||
Bytes(Vec::new()),
|
||||
call(remote_blockchain, fetcher, block, "Core_version".into(), Bytes(Vec::new())).then(
|
||||
|version| {
|
||||
ready(version.and_then(|version| {
|
||||
Decode::decode(&mut &version.0[..])
|
||||
.map_err(|e| client_err(ClientError::VersionInvalid(e.to_string())))
|
||||
}))
|
||||
},
|
||||
)
|
||||
.then(|version| ready(version.and_then(|version|
|
||||
Decode::decode(&mut &version.0[..])
|
||||
.map_err(|e| client_err(ClientError::VersionInvalid(e.to_string())))
|
||||
)))
|
||||
}
|
||||
|
||||
/// Get storage value at given key at given block.
|
||||
@@ -630,22 +643,30 @@ fn storage<Block: BlockT, F: Fetcher<Block>>(
|
||||
block: Block::Hash,
|
||||
keys: Vec<Vec<u8>>,
|
||||
) -> impl std::future::Future<Output = Result<HashMap<StorageKey, Option<StorageData>>, Error>> {
|
||||
resolve_header(remote_blockchain, &*fetcher, block)
|
||||
.then(move |result| match result {
|
||||
Ok(header) => Either::Left(fetcher.remote_read(RemoteReadRequest {
|
||||
block,
|
||||
header,
|
||||
keys,
|
||||
retry_count: Default::default(),
|
||||
}).then(|result| ready(result
|
||||
.map(|result| result
|
||||
.into_iter()
|
||||
.map(|(key, value)| (StorageKey(key), value.map(StorageData)))
|
||||
.collect()
|
||||
).map_err(client_err)
|
||||
))),
|
||||
Err(error) => Either::Right(ready(Err(error))),
|
||||
})
|
||||
resolve_header(remote_blockchain, &*fetcher, block).then(move |result| match result {
|
||||
Ok(header) => Either::Left(
|
||||
fetcher
|
||||
.remote_read(RemoteReadRequest {
|
||||
block,
|
||||
header,
|
||||
keys,
|
||||
retry_count: Default::default(),
|
||||
})
|
||||
.then(|result| {
|
||||
ready(
|
||||
result
|
||||
.map(|result| {
|
||||
result
|
||||
.into_iter()
|
||||
.map(|(key, value)| (StorageKey(key), value.map(StorageData)))
|
||||
.collect()
|
||||
})
|
||||
.map_err(client_err),
|
||||
)
|
||||
}),
|
||||
),
|
||||
Err(error) => Either::Right(ready(Err(error))),
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns subscription stream that issues request on every imported block and
|
||||
@@ -654,9 +675,11 @@ fn subscription_stream<
|
||||
Block,
|
||||
Requests,
|
||||
FutureBlocksStream,
|
||||
V, N,
|
||||
V,
|
||||
N,
|
||||
InitialRequestFuture,
|
||||
IssueRequest, IssueRequestFuture,
|
||||
IssueRequest,
|
||||
IssueRequestFuture,
|
||||
CompareValues,
|
||||
>(
|
||||
shared_requests: Requests,
|
||||
@@ -664,12 +687,14 @@ fn subscription_stream<
|
||||
initial_request: InitialRequestFuture,
|
||||
issue_request: IssueRequest,
|
||||
compare_values: CompareValues,
|
||||
) -> impl Stream<Item=N, Error=()> where
|
||||
) -> impl Stream<Item = N, Error = ()>
|
||||
where
|
||||
Block: BlockT,
|
||||
Requests: 'static + SharedRequests<Block::Hash, V>,
|
||||
FutureBlocksStream: Stream<Item=Block::Hash, Error=()>,
|
||||
FutureBlocksStream: Stream<Item = Block::Hash, Error = ()>,
|
||||
V: Send + 'static + Clone,
|
||||
InitialRequestFuture: std::future::Future<Output = Result<(Block::Hash, V), ()>> + Send + 'static,
|
||||
InitialRequestFuture:
|
||||
std::future::Future<Output = Result<(Block::Hash, V), ()>> + Send + 'static,
|
||||
IssueRequest: 'static + Fn(Block::Hash) -> IssueRequestFuture,
|
||||
IssueRequestFuture: std::future::Future<Output = Result<V, Error>> + Send + 'static,
|
||||
CompareValues: Fn(Block::Hash, Option<&V>, &V) -> Option<N>,
|
||||
@@ -678,33 +703,39 @@ fn subscription_stream<
|
||||
let previous_value = Arc::new(Mutex::new(None));
|
||||
|
||||
// prepare 'stream' of initial values
|
||||
let initial_value_stream = ignore_error(initial_request)
|
||||
.boxed()
|
||||
.compat()
|
||||
.into_stream();
|
||||
let initial_value_stream = ignore_error(initial_request).boxed().compat().into_stream();
|
||||
|
||||
// prepare stream of future values
|
||||
//
|
||||
// we do not want to stop stream if single request fails
|
||||
// (the warning should have been already issued by the request issuer)
|
||||
let future_values_stream = future_blocks_stream
|
||||
.and_then(move |block| ignore_error(maybe_share_remote_request::<Block, _, _, _, _>(
|
||||
shared_requests.clone(),
|
||||
block,
|
||||
&issue_request,
|
||||
).map(move |r| r.map(|v| (block, v)))).boxed().compat());
|
||||
let future_values_stream = future_blocks_stream.and_then(move |block| {
|
||||
ignore_error(
|
||||
maybe_share_remote_request::<Block, _, _, _, _>(
|
||||
shared_requests.clone(),
|
||||
block,
|
||||
&issue_request,
|
||||
)
|
||||
.map(move |r| r.map(|v| (block, v))),
|
||||
)
|
||||
.boxed()
|
||||
.compat()
|
||||
});
|
||||
|
||||
// now let's return changed values for selected blocks
|
||||
initial_value_stream
|
||||
.chain(future_values_stream)
|
||||
.filter_map(move |block_and_new_value| block_and_new_value.and_then(|(block, new_value)| {
|
||||
let mut previous_value = previous_value.lock();
|
||||
compare_values(block, previous_value.as_ref(), &new_value)
|
||||
.map(|notification_value| {
|
||||
*previous_value = Some(new_value);
|
||||
notification_value
|
||||
})
|
||||
}))
|
||||
.filter_map(move |block_and_new_value| {
|
||||
block_and_new_value.and_then(|(block, new_value)| {
|
||||
let mut previous_value = previous_value.lock();
|
||||
compare_values(block, previous_value.as_ref(), &new_value).map(
|
||||
|notification_value| {
|
||||
*previous_value = Some(new_value);
|
||||
notification_value
|
||||
},
|
||||
)
|
||||
})
|
||||
})
|
||||
.map_err(|_| ())
|
||||
}
|
||||
|
||||
@@ -714,7 +745,8 @@ fn maybe_share_remote_request<Block: BlockT, Requests, V, IssueRequest, IssueReq
|
||||
shared_requests: Requests,
|
||||
block: Block::Hash,
|
||||
issue_request: &IssueRequest,
|
||||
) -> impl std::future::Future<Output = Result<V, ()>> where
|
||||
) -> impl std::future::Future<Output = Result<V, ()>>
|
||||
where
|
||||
V: Clone,
|
||||
Requests: SharedRequests<Block::Hash, V>,
|
||||
IssueRequest: Fn(Block::Hash) -> IssueRequestFuture,
|
||||
@@ -725,55 +757,58 @@ fn maybe_share_remote_request<Block: BlockT, Requests, V, IssueRequest, IssueReq
|
||||
|
||||
// if that isn't the first request - just listen for existing request' response
|
||||
if !need_issue_request {
|
||||
return Either::Right(receiver.then(|r| ready(r.unwrap_or(Err(())))));
|
||||
return Either::Right(receiver.then(|r| ready(r.unwrap_or(Err(())))))
|
||||
}
|
||||
|
||||
// that is the first request - issue remote request + notify all listeners on
|
||||
// completion
|
||||
Either::Left(
|
||||
display_error(issue_request(block))
|
||||
.then(move |remote_result| {
|
||||
let listeners = shared_requests.on_response_received(block);
|
||||
// skip first element, because this future is the first element
|
||||
for receiver in listeners.into_iter().skip(1) {
|
||||
if let Err(_) = receiver.send(remote_result.clone()) {
|
||||
// we don't care if receiver has been dropped already
|
||||
}
|
||||
}
|
||||
Either::Left(display_error(issue_request(block)).then(move |remote_result| {
|
||||
let listeners = shared_requests.on_response_received(block);
|
||||
// skip first element, because this future is the first element
|
||||
for receiver in listeners.into_iter().skip(1) {
|
||||
if let Err(_) = receiver.send(remote_result.clone()) {
|
||||
// we don't care if receiver has been dropped already
|
||||
}
|
||||
}
|
||||
|
||||
ready(remote_result)
|
||||
})
|
||||
)
|
||||
ready(remote_result)
|
||||
}))
|
||||
}
|
||||
|
||||
/// Convert successful future result into Ok(result) and error into Err(()),
|
||||
/// displaying warning.
|
||||
fn display_error<F, T>(future: F) -> impl std::future::Future<Output=Result<T, ()>> where
|
||||
F: std::future::Future<Output=Result<T, Error>>
|
||||
fn display_error<F, T>(future: F) -> impl std::future::Future<Output = Result<T, ()>>
|
||||
where
|
||||
F: std::future::Future<Output = Result<T, Error>>,
|
||||
{
|
||||
future.then(|result| ready(result.or_else(|err| {
|
||||
future.then(|result| {
|
||||
ready(result.or_else(|err| {
|
||||
warn!("Remote request for subscription data has failed with: {:?}", err);
|
||||
Err(())
|
||||
})))
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
/// Convert successful future result into Ok(Some(result)) and error into Ok(None),
|
||||
/// displaying warning.
|
||||
fn ignore_error<F, T>(future: F) -> impl std::future::Future<Output=Result<Option<T>, ()>> where
|
||||
F: std::future::Future<Output=Result<T, ()>>
|
||||
fn ignore_error<F, T>(future: F) -> impl std::future::Future<Output = Result<Option<T>, ()>>
|
||||
where
|
||||
F: std::future::Future<Output = Result<T, ()>>,
|
||||
{
|
||||
future.then(|result| ready(match result {
|
||||
Ok(result) => Ok(Some(result)),
|
||||
Err(()) => Ok(None),
|
||||
}))
|
||||
future.then(|result| {
|
||||
ready(match result {
|
||||
Ok(result) => Ok(Some(result)),
|
||||
Err(()) => Ok(None),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use rpc::futures::stream::futures_ordered;
|
||||
use substrate_test_runtime_client::runtime::Block;
|
||||
use sp_core::H256;
|
||||
use super::*;
|
||||
use rpc::futures::stream::futures_ordered;
|
||||
use sp_core::H256;
|
||||
use substrate_test_runtime_client::runtime::Block;
|
||||
|
||||
#[test]
|
||||
fn subscription_stream_works() {
|
||||
@@ -789,13 +824,10 @@ mod tests {
|
||||
|_, old_value, new_value| match old_value == Some(new_value) {
|
||||
true => None,
|
||||
false => Some(new_value.clone()),
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
stream.collect().wait(),
|
||||
Ok(vec![100, 200])
|
||||
);
|
||||
assert_eq!(stream.collect().wait(), Ok(vec![100, 200]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -812,13 +844,10 @@ mod tests {
|
||||
|_, old_value, new_value| match old_value == Some(new_value) {
|
||||
true => None,
|
||||
false => Some(new_value.clone()),
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
stream.collect().wait(),
|
||||
Ok(vec![100, 200])
|
||||
);
|
||||
assert_eq!(stream.collect().wait(), Ok(vec![100, 200]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -828,10 +857,7 @@ mod tests {
|
||||
let shared_requests = SimpleSubscriptions::default();
|
||||
|
||||
// let's 'issue' requests for B1
|
||||
shared_requests.lock().insert(
|
||||
H256::from([1; 32]),
|
||||
vec![channel().0],
|
||||
);
|
||||
shared_requests.lock().insert(H256::from([1; 32]), vec![channel().0]);
|
||||
|
||||
// make sure that no additional requests are issued when we're asking for B1
|
||||
let _ = maybe_share_remote_request::<Block, _, _, _, UnreachableFuture>(
|
||||
|
||||
@@ -16,26 +16,20 @@
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
use super::*;
|
||||
use super::state_full::split_range;
|
||||
use self::error::Error;
|
||||
use super::{state_full::split_range, *};
|
||||
|
||||
use std::sync::Arc;
|
||||
use assert_matches::assert_matches;
|
||||
use futures01::stream::Stream;
|
||||
use sp_core::{storage::ChildInfo, ChangesTrieConfiguration};
|
||||
use sp_core::hash::H256;
|
||||
use sc_block_builder::BlockBuilderProvider;
|
||||
use sp_io::hashing::blake2_256;
|
||||
use substrate_test_runtime_client::{
|
||||
prelude::*,
|
||||
sp_consensus::BlockOrigin,
|
||||
runtime,
|
||||
};
|
||||
use sc_rpc_api::DenyUnsafe;
|
||||
use sp_runtime::generic::BlockId;
|
||||
use crate::testing::TaskExecutor;
|
||||
use futures::{executor, compat::Future01CompatExt};
|
||||
use assert_matches::assert_matches;
|
||||
use futures::{compat::Future01CompatExt, executor};
|
||||
use futures01::stream::Stream;
|
||||
use sc_block_builder::BlockBuilderProvider;
|
||||
use sc_rpc_api::DenyUnsafe;
|
||||
use sp_core::{hash::H256, storage::ChildInfo, ChangesTrieConfiguration};
|
||||
use sp_io::hashing::blake2_256;
|
||||
use sp_runtime::generic::BlockId;
|
||||
use std::sync::Arc;
|
||||
use substrate_test_runtime_client::{prelude::*, runtime, sp_consensus::BlockOrigin};
|
||||
|
||||
const STORAGE_KEY: &[u8] = b"child";
|
||||
|
||||
@@ -68,12 +62,18 @@ fn should_return_storage() {
|
||||
let key = StorageKey(KEY.to_vec());
|
||||
|
||||
assert_eq!(
|
||||
client.storage(key.clone(), Some(genesis_hash).into()).wait()
|
||||
.map(|x| x.map(|x| x.0.len())).unwrap().unwrap() as usize,
|
||||
client
|
||||
.storage(key.clone(), Some(genesis_hash).into())
|
||||
.wait()
|
||||
.map(|x| x.map(|x| x.0.len()))
|
||||
.unwrap()
|
||||
.unwrap() as usize,
|
||||
VALUE.len(),
|
||||
);
|
||||
assert_matches!(
|
||||
client.storage_hash(key.clone(), Some(genesis_hash).into()).wait()
|
||||
client
|
||||
.storage_hash(key.clone(), Some(genesis_hash).into())
|
||||
.wait()
|
||||
.map(|x| x.is_some()),
|
||||
Ok(true)
|
||||
);
|
||||
@@ -87,10 +87,13 @@ fn should_return_storage() {
|
||||
);
|
||||
assert_eq!(
|
||||
executor::block_on(
|
||||
child.storage(prefixed_storage_key(), key, Some(genesis_hash).into())
|
||||
child
|
||||
.storage(prefixed_storage_key(), key, Some(genesis_hash).into())
|
||||
.map(|x| x.map(|x| x.0.len()))
|
||||
.compat(),
|
||||
).unwrap().unwrap() as usize,
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap() as usize,
|
||||
CHILD_VALUE.len(),
|
||||
);
|
||||
}
|
||||
@@ -98,20 +101,17 @@ fn should_return_storage() {
|
||||
#[test]
|
||||
fn should_return_child_storage() {
|
||||
let child_info = ChildInfo::new_default(STORAGE_KEY);
|
||||
let client = Arc::new(substrate_test_runtime_client::TestClientBuilder::new()
|
||||
.add_child_storage(&child_info, "key", vec![42_u8])
|
||||
.build());
|
||||
let genesis_hash = client.genesis_hash();
|
||||
let (_client, child) = new_full(
|
||||
client,
|
||||
SubscriptionManager::new(Arc::new(TaskExecutor)),
|
||||
DenyUnsafe::No,
|
||||
None,
|
||||
let client = Arc::new(
|
||||
substrate_test_runtime_client::TestClientBuilder::new()
|
||||
.add_child_storage(&child_info, "key", vec![42_u8])
|
||||
.build(),
|
||||
);
|
||||
let genesis_hash = client.genesis_hash();
|
||||
let (_client, child) =
|
||||
new_full(client, SubscriptionManager::new(Arc::new(TaskExecutor)), DenyUnsafe::No, None);
|
||||
let child_key = prefixed_storage_key();
|
||||
let key = StorageKey(b"key".to_vec());
|
||||
|
||||
|
||||
assert_matches!(
|
||||
child.storage(
|
||||
child_key.clone(),
|
||||
@@ -121,36 +121,26 @@ fn should_return_child_storage() {
|
||||
Ok(Some(StorageData(ref d))) if d[0] == 42 && d.len() == 1
|
||||
);
|
||||
assert_matches!(
|
||||
child.storage_hash(
|
||||
child_key.clone(),
|
||||
key.clone(),
|
||||
Some(genesis_hash).into(),
|
||||
).wait().map(|x| x.is_some()),
|
||||
child
|
||||
.storage_hash(child_key.clone(), key.clone(), Some(genesis_hash).into(),)
|
||||
.wait()
|
||||
.map(|x| x.is_some()),
|
||||
Ok(true)
|
||||
);
|
||||
assert_matches!(
|
||||
child.storage_size(
|
||||
child_key.clone(),
|
||||
key.clone(),
|
||||
None,
|
||||
).wait(),
|
||||
Ok(Some(1))
|
||||
);
|
||||
assert_matches!(child.storage_size(child_key.clone(), key.clone(), None,).wait(), Ok(Some(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_call_contract() {
|
||||
let client = Arc::new(substrate_test_runtime_client::new());
|
||||
let genesis_hash = client.genesis_hash();
|
||||
let (client, _child) = new_full(
|
||||
client,
|
||||
SubscriptionManager::new(Arc::new(TaskExecutor)),
|
||||
DenyUnsafe::No,
|
||||
None,
|
||||
);
|
||||
let (client, _child) =
|
||||
new_full(client, SubscriptionManager::new(Arc::new(TaskExecutor)), DenyUnsafe::No, None);
|
||||
|
||||
assert_matches!(
|
||||
client.call("balanceOf".into(), Bytes(vec![1,2,3]), Some(genesis_hash).into()).wait(),
|
||||
client
|
||||
.call("balanceOf".into(), Bytes(vec![1, 2, 3]), Some(genesis_hash).into())
|
||||
.wait(),
|
||||
Err(Error::Client(_))
|
||||
)
|
||||
}
|
||||
@@ -171,18 +161,17 @@ fn should_notify_about_storage_changes() {
|
||||
api.subscribe_storage(Default::default(), subscriber, None.into());
|
||||
|
||||
// assert id assigned
|
||||
assert!(matches!(
|
||||
executor::block_on(id.compat()),
|
||||
Ok(Ok(SubscriptionId::String(_)))
|
||||
));
|
||||
assert!(matches!(executor::block_on(id.compat()), Ok(Ok(SubscriptionId::String(_)))));
|
||||
|
||||
let mut builder = client.new_block(Default::default()).unwrap();
|
||||
builder.push_transfer(runtime::Transfer {
|
||||
from: AccountKeyring::Alice.into(),
|
||||
to: AccountKeyring::Ferdie.into(),
|
||||
amount: 42,
|
||||
nonce: 0,
|
||||
}).unwrap();
|
||||
builder
|
||||
.push_transfer(runtime::Transfer {
|
||||
from: AccountKeyring::Alice.into(),
|
||||
to: AccountKeyring::Ferdie.into(),
|
||||
amount: 42,
|
||||
nonce: 0,
|
||||
})
|
||||
.unwrap();
|
||||
let block = builder.build().unwrap().block;
|
||||
executor::block_on(client.import(BlockOrigin::Own, block)).unwrap();
|
||||
}
|
||||
@@ -207,25 +196,27 @@ fn should_send_initial_storage_changes_and_notifications() {
|
||||
None,
|
||||
);
|
||||
|
||||
let alice_balance_key = blake2_256(&runtime::system::balance_of_key(AccountKeyring::Alice.into()));
|
||||
let alice_balance_key =
|
||||
blake2_256(&runtime::system::balance_of_key(AccountKeyring::Alice.into()));
|
||||
|
||||
api.subscribe_storage(Default::default(), subscriber, Some(vec![
|
||||
StorageKey(alice_balance_key.to_vec()),
|
||||
]).into());
|
||||
api.subscribe_storage(
|
||||
Default::default(),
|
||||
subscriber,
|
||||
Some(vec![StorageKey(alice_balance_key.to_vec())]).into(),
|
||||
);
|
||||
|
||||
// assert id assigned
|
||||
assert!(matches!(
|
||||
executor::block_on(id.compat()),
|
||||
Ok(Ok(SubscriptionId::String(_)))
|
||||
));
|
||||
assert!(matches!(executor::block_on(id.compat()), Ok(Ok(SubscriptionId::String(_)))));
|
||||
|
||||
let mut builder = client.new_block(Default::default()).unwrap();
|
||||
builder.push_transfer(runtime::Transfer {
|
||||
from: AccountKeyring::Alice.into(),
|
||||
to: AccountKeyring::Ferdie.into(),
|
||||
amount: 42,
|
||||
nonce: 0,
|
||||
}).unwrap();
|
||||
builder
|
||||
.push_transfer(runtime::Transfer {
|
||||
from: AccountKeyring::Alice.into(),
|
||||
to: AccountKeyring::Ferdie.into(),
|
||||
amount: 42,
|
||||
nonce: 0,
|
||||
})
|
||||
.unwrap();
|
||||
let block = builder.build().unwrap().block;
|
||||
executor::block_on(client.import(BlockOrigin::Own, block)).unwrap();
|
||||
}
|
||||
@@ -257,9 +248,13 @@ fn should_query_storage() {
|
||||
// fake change: None -> Some(value) -> Some(value)
|
||||
builder.push_storage_change(vec![2], Some(vec![2])).unwrap();
|
||||
// actual change: None -> Some(value) -> None
|
||||
builder.push_storage_change(vec![3], if nonce == 0 { Some(vec![3]) } else { None }).unwrap();
|
||||
builder
|
||||
.push_storage_change(vec![3], if nonce == 0 { Some(vec![3]) } else { None })
|
||||
.unwrap();
|
||||
// actual change: None -> Some(value)
|
||||
builder.push_storage_change(vec![4], if nonce == 0 { None } else { Some(vec![4]) }).unwrap();
|
||||
builder
|
||||
.push_storage_change(vec![4], if nonce == 0 { None } else { Some(vec![4]) })
|
||||
.unwrap();
|
||||
// actual change: Some(value1) -> Some(value2)
|
||||
builder.push_storage_change(vec![5], Some(vec![nonce as u8])).unwrap();
|
||||
let block = builder.build().unwrap().block;
|
||||
@@ -301,20 +296,12 @@ fn should_query_storage() {
|
||||
|
||||
// Query changes only up to block1
|
||||
let keys = (1..6).map(|k| StorageKey(vec![k])).collect::<Vec<_>>();
|
||||
let result = api.query_storage(
|
||||
keys.clone(),
|
||||
genesis_hash,
|
||||
Some(block1_hash).into(),
|
||||
);
|
||||
let result = api.query_storage(keys.clone(), genesis_hash, Some(block1_hash).into());
|
||||
|
||||
assert_eq!(result.wait().unwrap(), expected);
|
||||
|
||||
// Query all changes
|
||||
let result = api.query_storage(
|
||||
keys.clone(),
|
||||
genesis_hash,
|
||||
None.into(),
|
||||
);
|
||||
let result = api.query_storage(keys.clone(), genesis_hash, None.into());
|
||||
|
||||
expected.push(StorageChangeSet {
|
||||
block: block2_hash,
|
||||
@@ -327,20 +314,12 @@ fn should_query_storage() {
|
||||
assert_eq!(result.wait().unwrap(), expected);
|
||||
|
||||
// Query changes up to block2.
|
||||
let result = api.query_storage(
|
||||
keys.clone(),
|
||||
genesis_hash,
|
||||
Some(block2_hash),
|
||||
);
|
||||
let result = api.query_storage(keys.clone(), genesis_hash, Some(block2_hash));
|
||||
|
||||
assert_eq!(result.wait().unwrap(), expected);
|
||||
|
||||
// Inverted range.
|
||||
let result = api.query_storage(
|
||||
keys.clone(),
|
||||
block1_hash,
|
||||
Some(genesis_hash),
|
||||
);
|
||||
let result = api.query_storage(keys.clone(), block1_hash, Some(genesis_hash));
|
||||
|
||||
assert_eq!(
|
||||
result.wait().map_err(|e| e.to_string()),
|
||||
@@ -348,18 +327,15 @@ fn should_query_storage() {
|
||||
from: format!("1 ({:?})", block1_hash),
|
||||
to: format!("0 ({:?})", genesis_hash),
|
||||
details: "from number > to number".to_owned(),
|
||||
}).map_err(|e| e.to_string())
|
||||
})
|
||||
.map_err(|e| e.to_string())
|
||||
);
|
||||
|
||||
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),
|
||||
);
|
||||
let result = api.query_storage(keys.clone(), genesis_hash, Some(random_hash1));
|
||||
|
||||
assert_eq!(
|
||||
result.wait().map_err(|e| e.to_string()),
|
||||
@@ -367,15 +343,12 @@ fn should_query_storage() {
|
||||
from: format!("{:?}", genesis_hash),
|
||||
to: format!("{:?}", Some(random_hash1)),
|
||||
details: format!("UnknownBlock: header not found in db: {}", random_hash1),
|
||||
}).map_err(|e| e.to_string())
|
||||
})
|
||||
.map_err(|e| e.to_string())
|
||||
);
|
||||
|
||||
// Invalid first hash with Some other hash.
|
||||
let result = api.query_storage(
|
||||
keys.clone(),
|
||||
random_hash1,
|
||||
Some(genesis_hash),
|
||||
);
|
||||
let result = api.query_storage(keys.clone(), random_hash1, Some(genesis_hash));
|
||||
|
||||
assert_eq!(
|
||||
result.wait().map_err(|e| e.to_string()),
|
||||
@@ -383,15 +356,12 @@ fn should_query_storage() {
|
||||
from: format!("{:?}", random_hash1),
|
||||
to: format!("{:?}", Some(genesis_hash)),
|
||||
details: format!("UnknownBlock: header not found in db: {}", random_hash1),
|
||||
}).map_err(|e| e.to_string()),
|
||||
})
|
||||
.map_err(|e| e.to_string()),
|
||||
);
|
||||
|
||||
// Invalid first hash with None.
|
||||
let result = api.query_storage(
|
||||
keys.clone(),
|
||||
random_hash1,
|
||||
None,
|
||||
);
|
||||
let result = api.query_storage(keys.clone(), random_hash1, None);
|
||||
|
||||
assert_eq!(
|
||||
result.wait().map_err(|e| e.to_string()),
|
||||
@@ -399,15 +369,12 @@ fn should_query_storage() {
|
||||
from: format!("{:?}", random_hash1),
|
||||
to: format!("{:?}", Some(block2_hash)), // Best block hash.
|
||||
details: format!("UnknownBlock: header not found in db: {}", random_hash1),
|
||||
}).map_err(|e| e.to_string()),
|
||||
})
|
||||
.map_err(|e| e.to_string()),
|
||||
);
|
||||
|
||||
// Both hashes invalid.
|
||||
let result = api.query_storage(
|
||||
keys.clone(),
|
||||
random_hash1,
|
||||
Some(random_hash2),
|
||||
);
|
||||
let result = api.query_storage(keys.clone(), random_hash1, Some(random_hash2));
|
||||
|
||||
assert_eq!(
|
||||
result.wait().map_err(|e| e.to_string()),
|
||||
@@ -415,29 +382,25 @@ fn should_query_storage() {
|
||||
from: format!("{:?}", random_hash1), // First hash not found.
|
||||
to: format!("{:?}", Some(random_hash2)),
|
||||
details: format!("UnknownBlock: header not found in db: {}", random_hash1),
|
||||
}).map_err(|e| e.to_string()),
|
||||
})
|
||||
.map_err(|e| e.to_string()),
|
||||
);
|
||||
|
||||
// single block range
|
||||
let result = api.query_storage_at(
|
||||
keys.clone(),
|
||||
Some(block1_hash),
|
||||
);
|
||||
let result = api.query_storage_at(keys.clone(), Some(block1_hash));
|
||||
|
||||
assert_eq!(
|
||||
result.wait().unwrap(),
|
||||
vec![
|
||||
StorageChangeSet {
|
||||
block: block1_hash,
|
||||
changes: vec![
|
||||
(StorageKey(vec![1_u8]), None),
|
||||
(StorageKey(vec![2_u8]), Some(StorageData(vec![2_u8]))),
|
||||
(StorageKey(vec![3_u8]), Some(StorageData(vec![3_u8]))),
|
||||
(StorageKey(vec![4_u8]), None),
|
||||
(StorageKey(vec![5_u8]), Some(StorageData(vec![0_u8]))),
|
||||
]
|
||||
}
|
||||
]
|
||||
vec![StorageChangeSet {
|
||||
block: block1_hash,
|
||||
changes: vec![
|
||||
(StorageKey(vec![1_u8]), None),
|
||||
(StorageKey(vec![2_u8]), Some(StorageData(vec![2_u8]))),
|
||||
(StorageKey(vec![3_u8]), Some(StorageData(vec![3_u8]))),
|
||||
(StorageKey(vec![4_u8]), None),
|
||||
(StorageKey(vec![5_u8]), Some(StorageData(vec![0_u8]))),
|
||||
]
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -461,7 +424,6 @@ fn should_split_ranges() {
|
||||
assert_eq!(split_range(100, Some(99)), (0..99, Some(99..100)));
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn should_return_runtime_version() {
|
||||
let client = Arc::new(substrate_test_runtime_client::new());
|
||||
@@ -503,17 +465,13 @@ fn should_notify_on_runtime_version_initially() {
|
||||
api.subscribe_runtime_version(Default::default(), subscriber);
|
||||
|
||||
// assert id assigned
|
||||
assert!(matches!(
|
||||
executor::block_on(id.compat()),
|
||||
Ok(Ok(SubscriptionId::String(_)))
|
||||
));
|
||||
|
||||
assert!(matches!(executor::block_on(id.compat()), Ok(Ok(SubscriptionId::String(_)))));
|
||||
}
|
||||
|
||||
// assert initial version sent.
|
||||
let (notification, next) = executor::block_on(transport.into_future().compat()).unwrap();
|
||||
assert!(notification.is_some());
|
||||
// no more notifications on this channel
|
||||
// no more notifications on this channel
|
||||
assert_eq!(executor::block_on(next.into_future().compat()).unwrap().0, None);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user