mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-05-09 05:57:59 +00:00
Make chain && state RPCs async (#3480)
* chain+state RPCs are async now * wrapped too long lines * create full/light RPC impls from service * use ordering * post-merge fix
This commit is contained in:
committed by
Gavin Wood
parent
816e132cd7
commit
607ee0a4e4
@@ -0,0 +1,79 @@
|
||||
// Copyright 2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Blockchain API backend for full nodes.
|
||||
|
||||
use std::sync::Arc;
|
||||
use rpc::futures::future::result;
|
||||
|
||||
use api::Subscriptions;
|
||||
use client::{backend::Backend, CallExecutor, Client};
|
||||
use primitives::{H256, Blake2Hasher};
|
||||
use sr_primitives::{
|
||||
generic::{BlockId, SignedBlock},
|
||||
traits::{Block as BlockT},
|
||||
};
|
||||
|
||||
use super::{ChainBackend, client_err, error::FutureResult};
|
||||
|
||||
/// Blockchain API backend for full nodes. Reads all the data from local database.
|
||||
pub struct FullChain<B, E, Block: BlockT, RA> {
|
||||
/// Substrate client.
|
||||
client: Arc<Client<B, E, Block, RA>>,
|
||||
/// Current subscriptions.
|
||||
subscriptions: Subscriptions,
|
||||
}
|
||||
|
||||
impl<B, E, Block: BlockT, RA> FullChain<B, E, Block, RA> {
|
||||
/// Create new Chain API RPC handler.
|
||||
pub fn new(client: Arc<Client<B, E, Block, RA>>, subscriptions: Subscriptions) -> Self {
|
||||
Self {
|
||||
client,
|
||||
subscriptions,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<B, E, Block, RA> ChainBackend<B, E, Block, RA> for FullChain<B, E, Block, RA> where
|
||||
Block: BlockT<Hash=H256> + 'static,
|
||||
B: Backend<Block, Blake2Hasher> + Send + Sync + 'static,
|
||||
E: CallExecutor<Block, Blake2Hasher> + Send + Sync + 'static,
|
||||
RA: Send + Sync + 'static,
|
||||
{
|
||||
fn client(&self) -> &Arc<Client<B, E, Block, RA>> {
|
||||
&self.client
|
||||
}
|
||||
|
||||
fn subscriptions(&self) -> &Subscriptions {
|
||||
&self.subscriptions
|
||||
}
|
||||
|
||||
fn header(&self, hash: Option<Block::Hash>) -> FutureResult<Option<Block::Header>> {
|
||||
Box::new(result(self.client
|
||||
.header(&BlockId::Hash(self.unwrap_or_best(hash)))
|
||||
.map_err(client_err)
|
||||
))
|
||||
}
|
||||
|
||||
fn block(&self, hash: Option<Block::Hash>)
|
||||
-> FutureResult<Option<SignedBlock<Block>>>
|
||||
{
|
||||
Box::new(result(self.client
|
||||
.block(&BlockId::Hash(self.unwrap_or_best(hash)))
|
||||
.map_err(client_err)
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// Copyright 2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Blockchain API backend for light nodes.
|
||||
|
||||
use std::sync::Arc;
|
||||
use futures03::{future::ready, FutureExt, TryFutureExt};
|
||||
use rpc::futures::future::{result, Future, Either};
|
||||
|
||||
use api::Subscriptions;
|
||||
use client::{
|
||||
self, Client,
|
||||
light::{
|
||||
fetcher::{Fetcher, RemoteBodyRequest},
|
||||
blockchain::RemoteBlockchain,
|
||||
},
|
||||
};
|
||||
use primitives::{H256, Blake2Hasher};
|
||||
use sr_primitives::{
|
||||
generic::{BlockId, SignedBlock},
|
||||
traits::{Block as BlockT},
|
||||
};
|
||||
|
||||
use super::{ChainBackend, client_err, error::FutureResult};
|
||||
|
||||
/// Blockchain API backend for light nodes. Reads all the data from local
|
||||
/// database, if available, or fetches it from remote node otherwise.
|
||||
pub struct LightChain<B, E, Block: BlockT, RA, F> {
|
||||
/// Substrate client.
|
||||
client: Arc<Client<B, E, Block, RA>>,
|
||||
/// Current subscriptions.
|
||||
subscriptions: Subscriptions,
|
||||
/// Remote blockchain reference
|
||||
remote_blockchain: Arc<dyn RemoteBlockchain<Block>>,
|
||||
/// Remote fetcher reference.
|
||||
fetcher: Arc<F>,
|
||||
}
|
||||
|
||||
impl<B, E, Block: BlockT, RA, F: Fetcher<Block>> LightChain<B, E, Block, RA, F> {
|
||||
/// Create new Chain API RPC handler.
|
||||
pub fn new(
|
||||
client: Arc<Client<B, E, Block, RA>>,
|
||||
subscriptions: Subscriptions,
|
||||
remote_blockchain: Arc<dyn RemoteBlockchain<Block>>,
|
||||
fetcher: Arc<F>,
|
||||
) -> Self {
|
||||
Self {
|
||||
client,
|
||||
subscriptions,
|
||||
remote_blockchain,
|
||||
fetcher,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<B, E, Block, RA, F> ChainBackend<B, E, Block, RA> for LightChain<B, E, Block, RA, F> where
|
||||
Block: BlockT<Hash=H256> + 'static,
|
||||
B: client::backend::Backend<Block, Blake2Hasher> + Send + Sync + 'static,
|
||||
E: client::CallExecutor<Block, Blake2Hasher> + Send + Sync + 'static,
|
||||
RA: Send + Sync + 'static,
|
||||
F: Fetcher<Block> + Send + Sync + 'static,
|
||||
{
|
||||
fn client(&self) -> &Arc<Client<B, E, Block, RA>> {
|
||||
&self.client
|
||||
}
|
||||
|
||||
fn subscriptions(&self) -> &Subscriptions {
|
||||
&self.subscriptions
|
||||
}
|
||||
|
||||
fn header(&self, hash: Option<Block::Hash>) -> FutureResult<Option<Block::Header>> {
|
||||
let hash = self.unwrap_or_best(hash);
|
||||
|
||||
let fetcher = self.fetcher.clone();
|
||||
let maybe_header = client::light::blockchain::future_header(
|
||||
&*self.remote_blockchain,
|
||||
&*fetcher,
|
||||
BlockId::Hash(hash),
|
||||
);
|
||||
|
||||
Box::new(maybe_header.then(move |result|
|
||||
ready(result.map_err(client_err)),
|
||||
).boxed().compat())
|
||||
}
|
||||
|
||||
fn block(&self, hash: Option<Block::Hash>)
|
||||
-> FutureResult<Option<SignedBlock<Block>>>
|
||||
{
|
||||
let fetcher = self.fetcher.clone();
|
||||
let block = self.header(hash)
|
||||
.and_then(move |header| match header {
|
||||
Some(header) => Either::A(fetcher
|
||||
.remote_body(RemoteBodyRequest {
|
||||
header: header.clone(),
|
||||
retry_count: Default::default(),
|
||||
})
|
||||
.boxed()
|
||||
.compat()
|
||||
.map(move |body| Some(SignedBlock {
|
||||
block: Block::new(header, body),
|
||||
justification: None,
|
||||
}))
|
||||
.map_err(client_err)
|
||||
),
|
||||
None => Either::B(result(Ok(None))),
|
||||
});
|
||||
|
||||
Box::new(block)
|
||||
}
|
||||
}
|
||||
+210
-101
@@ -16,95 +16,181 @@
|
||||
|
||||
//! Substrate blockchain API.
|
||||
|
||||
mod chain_full;
|
||||
mod chain_light;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::sync::Arc;
|
||||
use futures03::{future, StreamExt as _, TryStreamExt as _};
|
||||
|
||||
use client::{self, Client, BlockchainEvents};
|
||||
use rpc::Result as RpcResult;
|
||||
use rpc::futures::{stream, Future, Sink, Stream};
|
||||
use api::Subscriptions;
|
||||
use jsonrpc_pubsub::{typed::Subscriber, SubscriptionId};
|
||||
use log::warn;
|
||||
use rpc::{
|
||||
Result as RpcResult,
|
||||
futures::{stream, Future, Sink, Stream},
|
||||
};
|
||||
|
||||
use api::Subscriptions;
|
||||
use client::{
|
||||
self, Client, BlockchainEvents,
|
||||
light::{fetcher::Fetcher, blockchain::RemoteBlockchain},
|
||||
};
|
||||
use jsonrpc_pubsub::{typed::Subscriber, SubscriptionId};
|
||||
use primitives::{H256, Blake2Hasher};
|
||||
use sr_primitives::generic::{BlockId, SignedBlock};
|
||||
use sr_primitives::traits::{Block as BlockT, Header, NumberFor};
|
||||
use self::error::{Error, Result};
|
||||
use sr_primitives::{
|
||||
generic::{BlockId, SignedBlock},
|
||||
traits::{Block as BlockT, Header, NumberFor},
|
||||
};
|
||||
|
||||
use self::error::{Result, Error, FutureResult};
|
||||
|
||||
pub use api::chain::*;
|
||||
|
||||
/// Chain API with subscriptions support.
|
||||
pub struct Chain<B, E, Block: BlockT, RA> {
|
||||
/// Substrate client.
|
||||
client: Arc<Client<B, E, Block, RA>>,
|
||||
/// Current subscriptions.
|
||||
subscriptions: Subscriptions,
|
||||
}
|
||||
/// Blockchain backend API
|
||||
trait ChainBackend<B, E, Block: BlockT, RA>: Send + Sync + 'static
|
||||
where
|
||||
Block: BlockT<Hash=H256> + 'static,
|
||||
B: client::backend::Backend<Block, Blake2Hasher> + Send + Sync + 'static,
|
||||
E: client::CallExecutor<Block, Blake2Hasher> + Send + Sync + 'static,
|
||||
{
|
||||
/// Get client reference.
|
||||
fn client(&self) -> &Arc<Client<B, E, Block, RA>>;
|
||||
|
||||
impl<B, E, Block: BlockT, RA> Chain<B, E, Block, RA> {
|
||||
/// Create new Chain API RPC handler.
|
||||
pub fn new(client: Arc<Client<B, E, Block, RA>>, subscriptions: Subscriptions) -> Self {
|
||||
Self {
|
||||
client,
|
||||
subscriptions,
|
||||
/// Get subscriptions reference.
|
||||
fn subscriptions(&self) -> &Subscriptions;
|
||||
|
||||
/// Tries to unwrap passed block hash, or uses best block hash otherwise.
|
||||
fn unwrap_or_best(&self, hash: Option<Block::Hash>) -> Block::Hash {
|
||||
match hash.into() {
|
||||
None => self.client().info().chain.best_hash,
|
||||
Some(hash) => hash,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<B, E, Block, RA> Chain<B, E, Block, RA> where
|
||||
Block: BlockT<Hash=H256> + 'static,
|
||||
B: client::backend::Backend<Block, Blake2Hasher> + Send + Sync + 'static,
|
||||
E: client::CallExecutor<Block, Blake2Hasher> + Send + Sync + 'static,
|
||||
RA: Send + Sync + 'static
|
||||
{
|
||||
fn unwrap_or_best(&self, hash: Option<Block::Hash>) -> Result<Block::Hash> {
|
||||
Ok(match hash.into() {
|
||||
None => self.client.info().chain.best_hash,
|
||||
Some(hash) => hash,
|
||||
/// Get header of a relay chain block.
|
||||
fn header(&self, hash: Option<Block::Hash>) -> FutureResult<Option<Block::Header>>;
|
||||
|
||||
/// Get header and body of a relay chain block.
|
||||
fn block(&self, hash: Option<Block::Hash>) -> FutureResult<Option<SignedBlock<Block>>>;
|
||||
|
||||
/// Get hash of the n-th block in the canon chain.
|
||||
///
|
||||
/// By default returns latest block hash.
|
||||
fn block_hash(
|
||||
&self,
|
||||
number: Option<number::NumberOrHex<NumberFor<Block>>>,
|
||||
) -> Result<Option<Block::Hash>> {
|
||||
Ok(match number {
|
||||
None => Some(self.client().info().chain.best_hash),
|
||||
Some(num_or_hex) => self.client()
|
||||
.header(&BlockId::number(num_or_hex.to_number()?))
|
||||
.map_err(client_err)?
|
||||
.map(|h| h.hash()),
|
||||
})
|
||||
}
|
||||
|
||||
fn subscribe_headers<F, G, S, ERR>(
|
||||
/// Get hash of the last finalized block in the canon chain.
|
||||
fn finalized_head(&self) -> Result<Block::Hash> {
|
||||
Ok(self.client().info().chain.finalized_hash)
|
||||
}
|
||||
|
||||
/// New head subscription
|
||||
fn subscribe_new_heads(
|
||||
&self,
|
||||
_metadata: crate::metadata::Metadata,
|
||||
subscriber: Subscriber<Block::Header>,
|
||||
best_block_hash: G,
|
||||
stream: F,
|
||||
) where
|
||||
F: FnOnce() -> S,
|
||||
G: FnOnce() -> Result<Option<Block::Hash>>,
|
||||
ERR: ::std::fmt::Debug,
|
||||
S: Stream<Item=Block::Header, Error=ERR> + Send + 'static,
|
||||
{
|
||||
self.subscriptions.add(subscriber, |sink| {
|
||||
// send current head right at the start.
|
||||
let header = best_block_hash()
|
||||
.and_then(|hash| self.header(hash.into()))
|
||||
.and_then(|header| {
|
||||
header.ok_or_else(|| "Best header missing.".to_owned().into())
|
||||
})
|
||||
.map_err(Into::into);
|
||||
) {
|
||||
subscribe_headers(
|
||||
self.client(),
|
||||
self.subscriptions(),
|
||||
subscriber,
|
||||
|| self.client().info().chain.best_hash,
|
||||
|| self.client().import_notification_stream()
|
||||
.filter(|notification| future::ready(notification.is_new_best))
|
||||
.map(|notification| Ok::<_, ()>(notification.header))
|
||||
.compat(),
|
||||
)
|
||||
}
|
||||
|
||||
// send further subscriptions
|
||||
let stream = stream()
|
||||
.map(|res| Ok(res))
|
||||
.map_err(|e| warn!("Block notification stream error: {:?}", e));
|
||||
/// Unsubscribe from new head subscription.
|
||||
fn unsubscribe_new_heads(
|
||||
&self,
|
||||
_metadata: Option<crate::metadata::Metadata>,
|
||||
id: SubscriptionId,
|
||||
) -> RpcResult<bool> {
|
||||
Ok(self.subscriptions().cancel(id))
|
||||
}
|
||||
|
||||
sink
|
||||
.sink_map_err(|e| warn!("Error sending notifications: {:?}", e))
|
||||
.send_all(
|
||||
stream::iter_result(vec![Ok(header)])
|
||||
.chain(stream)
|
||||
)
|
||||
// we ignore the resulting Stream (if the first stream is over we are unsubscribed)
|
||||
.map(|_| ())
|
||||
});
|
||||
/// New head subscription
|
||||
fn subscribe_finalized_heads(
|
||||
&self,
|
||||
_metadata: crate::metadata::Metadata,
|
||||
subscriber: Subscriber<Block::Header>,
|
||||
) {
|
||||
subscribe_headers(
|
||||
self.client(),
|
||||
self.subscriptions(),
|
||||
subscriber,
|
||||
|| self.client().info().chain.finalized_hash,
|
||||
|| self.client().finality_notification_stream()
|
||||
.map(|notification| Ok::<_, ()>(notification.header))
|
||||
.compat(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Unsubscribe from new head subscription.
|
||||
fn unsubscribe_finalized_heads(
|
||||
&self,
|
||||
_metadata: Option<crate::metadata::Metadata>,
|
||||
id: SubscriptionId,
|
||||
) -> RpcResult<bool> {
|
||||
Ok(self.subscriptions().cancel(id))
|
||||
}
|
||||
}
|
||||
|
||||
fn client_error(err: client::error::Error) -> Error {
|
||||
Error::Client(Box::new(err))
|
||||
/// Create new state API that works on full node.
|
||||
pub fn new_full<B, E, Block: BlockT, RA>(
|
||||
client: Arc<Client<B, E, Block, RA>>,
|
||||
subscriptions: Subscriptions,
|
||||
) -> Chain<B, E, Block, RA>
|
||||
where
|
||||
Block: BlockT<Hash=H256> + 'static,
|
||||
B: client::backend::Backend<Block, Blake2Hasher> + Send + Sync + 'static,
|
||||
E: client::CallExecutor<Block, Blake2Hasher> + Send + Sync + 'static + Clone,
|
||||
RA: Send + Sync + 'static,
|
||||
{
|
||||
Chain {
|
||||
backend: Box::new(self::chain_full::FullChain::new(client, subscriptions)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create new state API that works on light node.
|
||||
pub fn new_light<B, E, Block: BlockT, RA, F: Fetcher<Block>>(
|
||||
client: Arc<Client<B, E, Block, RA>>,
|
||||
subscriptions: Subscriptions,
|
||||
remote_blockchain: Arc<dyn RemoteBlockchain<Block>>,
|
||||
fetcher: Arc<F>,
|
||||
) -> Chain<B, E, Block, RA>
|
||||
where
|
||||
Block: BlockT<Hash=H256> + 'static,
|
||||
B: client::backend::Backend<Block, Blake2Hasher> + Send + Sync + 'static,
|
||||
E: client::CallExecutor<Block, Blake2Hasher> + Send + Sync + 'static + Clone,
|
||||
RA: Send + Sync + 'static,
|
||||
F: Send + Sync + 'static,
|
||||
{
|
||||
Chain {
|
||||
backend: Box::new(self::chain_light::LightChain::new(
|
||||
client,
|
||||
subscriptions,
|
||||
remote_blockchain,
|
||||
fetcher,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Chain API with subscriptions support.
|
||||
pub struct Chain<B, E, Block: BlockT, RA> {
|
||||
backend: Box<dyn ChainBackend<B, E, Block, RA>>,
|
||||
}
|
||||
|
||||
impl<B, E, Block, RA> ChainApi<NumberFor<Block>, Block::Hash, Block::Header, SignedBlock<Block>> for Chain<B, E, Block, RA> where
|
||||
@@ -115,58 +201,81 @@ impl<B, E, Block, RA> ChainApi<NumberFor<Block>, Block::Hash, Block::Header, Sig
|
||||
{
|
||||
type Metadata = crate::metadata::Metadata;
|
||||
|
||||
fn header(&self, hash: Option<Block::Hash>) -> Result<Option<Block::Header>> {
|
||||
let hash = self.unwrap_or_best(hash)?;
|
||||
Ok(self.client.header(&BlockId::Hash(hash)).map_err(client_error)?)
|
||||
fn header(&self, hash: Option<Block::Hash>) -> FutureResult<Option<Block::Header>> {
|
||||
self.backend.header(hash)
|
||||
}
|
||||
|
||||
fn block(&self, hash: Option<Block::Hash>)
|
||||
-> Result<Option<SignedBlock<Block>>>
|
||||
fn block(&self, hash: Option<Block::Hash>) -> FutureResult<Option<SignedBlock<Block>>>
|
||||
{
|
||||
let hash = self.unwrap_or_best(hash)?;
|
||||
Ok(self.client.block(&BlockId::Hash(hash)).map_err(client_error)?)
|
||||
self.backend.block(hash)
|
||||
}
|
||||
|
||||
fn block_hash(&self, number: Option<number::NumberOrHex<NumberFor<Block>>>) -> Result<Option<Block::Hash>> {
|
||||
Ok(match number {
|
||||
None => Some(self.client.info().chain.best_hash),
|
||||
Some(num_or_hex) => self.client
|
||||
.header(&BlockId::number(num_or_hex.to_number()?))
|
||||
.map_err(client_error)?
|
||||
.map(|h| h.hash()),
|
||||
})
|
||||
self.backend.block_hash(number)
|
||||
}
|
||||
|
||||
fn finalized_head(&self) -> Result<Block::Hash> {
|
||||
Ok(self.client.info().chain.finalized_hash)
|
||||
self.backend.finalized_head()
|
||||
}
|
||||
|
||||
fn subscribe_new_heads(&self, _metadata: Self::Metadata, subscriber: Subscriber<Block::Header>) {
|
||||
self.subscribe_headers(
|
||||
subscriber,
|
||||
|| self.block_hash(None.into()),
|
||||
|| self.client.import_notification_stream()
|
||||
.filter(|notification| future::ready(notification.is_new_best))
|
||||
.map(|notification| Ok::<_, ()>(notification.header))
|
||||
.compat(),
|
||||
)
|
||||
fn subscribe_new_heads(&self, metadata: Self::Metadata, subscriber: Subscriber<Block::Header>) {
|
||||
self.backend.subscribe_new_heads(metadata, subscriber)
|
||||
}
|
||||
|
||||
fn unsubscribe_new_heads(&self, _metadata: Option<Self::Metadata>, id: SubscriptionId) -> RpcResult<bool> {
|
||||
Ok(self.subscriptions.cancel(id))
|
||||
fn unsubscribe_new_heads(&self, metadata: Option<Self::Metadata>, id: SubscriptionId) -> RpcResult<bool> {
|
||||
self.backend.unsubscribe_new_heads(metadata, id)
|
||||
}
|
||||
|
||||
fn subscribe_finalized_heads(&self, _meta: Self::Metadata, subscriber: Subscriber<Block::Header>) {
|
||||
self.subscribe_headers(
|
||||
subscriber,
|
||||
|| Ok(Some(self.client.info().chain.finalized_hash)),
|
||||
|| self.client.finality_notification_stream()
|
||||
.map(|notification| Ok::<_, ()>(notification.header))
|
||||
.compat(),
|
||||
)
|
||||
fn subscribe_finalized_heads(&self, metadata: Self::Metadata, subscriber: Subscriber<Block::Header>) {
|
||||
self.backend.subscribe_finalized_heads(metadata, subscriber)
|
||||
}
|
||||
|
||||
fn unsubscribe_finalized_heads(&self, _metadata: Option<Self::Metadata>, id: SubscriptionId) -> RpcResult<bool> {
|
||||
Ok(self.subscriptions.cancel(id))
|
||||
fn unsubscribe_finalized_heads(&self, metadata: Option<Self::Metadata>, id: SubscriptionId) -> RpcResult<bool> {
|
||||
self.backend.unsubscribe_finalized_heads(metadata, id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Subscribe to new headers.
|
||||
fn subscribe_headers<B, E, Block, RA, F, G, S, ERR>(
|
||||
client: &Arc<Client<B, E, Block, RA>>,
|
||||
subscriptions: &Subscriptions,
|
||||
subscriber: Subscriber<Block::Header>,
|
||||
best_block_hash: G,
|
||||
stream: F,
|
||||
) where
|
||||
Block: BlockT<Hash=H256> + 'static,
|
||||
B: client::backend::Backend<Block, Blake2Hasher> + Send + Sync + 'static,
|
||||
E: client::CallExecutor<Block, Blake2Hasher> + Send + Sync + 'static,
|
||||
F: FnOnce() -> S,
|
||||
G: FnOnce() -> Block::Hash,
|
||||
ERR: ::std::fmt::Debug,
|
||||
S: Stream<Item=Block::Header, Error=ERR> + Send + 'static,
|
||||
{
|
||||
subscriptions.add(subscriber, |sink| {
|
||||
// send current head right at the start.
|
||||
let header = client.header(&BlockId::Hash(best_block_hash()))
|
||||
.map_err(client_err)
|
||||
.and_then(|header| {
|
||||
header.ok_or_else(|| "Best header missing.".to_owned().into())
|
||||
})
|
||||
.map_err(Into::into);
|
||||
|
||||
// send further subscriptions
|
||||
let stream = stream()
|
||||
.map(|res| Ok(res))
|
||||
.map_err(|e| warn!("Block notification stream error: {:?}", e));
|
||||
|
||||
sink
|
||||
.sink_map_err(|e| warn!("Error sending notifications: {:?}", e))
|
||||
.send_all(
|
||||
stream::iter_result(vec![Ok(header)])
|
||||
.chain(stream)
|
||||
)
|
||||
// we ignore the resulting Stream (if the first stream is over we are unsubscribed)
|
||||
.map(|_| ())
|
||||
});
|
||||
}
|
||||
|
||||
fn client_err(err: client::error::Error) -> Error {
|
||||
Error::Client(Box::new(err))
|
||||
}
|
||||
|
||||
@@ -27,13 +27,11 @@ fn should_return_header() {
|
||||
let core = ::tokio::runtime::Runtime::new().unwrap();
|
||||
let remote = core.executor();
|
||||
|
||||
let client = Chain {
|
||||
client: Arc::new(test_client::new()),
|
||||
subscriptions: Subscriptions::new(Arc::new(remote)),
|
||||
};
|
||||
let client = Arc::new(test_client::new());
|
||||
let api = new_full(client.clone(), Subscriptions::new(Arc::new(remote)));
|
||||
|
||||
assert_matches!(
|
||||
client.header(Some(client.client.genesis_hash()).into()),
|
||||
api.header(Some(client.genesis_hash()).into()).wait(),
|
||||
Ok(Some(ref x)) if x == &Header {
|
||||
parent_hash: H256::from_low_u64_be(0),
|
||||
number: 0,
|
||||
@@ -44,7 +42,7 @@ fn should_return_header() {
|
||||
);
|
||||
|
||||
assert_matches!(
|
||||
client.header(None.into()),
|
||||
api.header(None.into()).wait(),
|
||||
Ok(Some(ref x)) if x == &Header {
|
||||
parent_hash: H256::from_low_u64_be(0),
|
||||
number: 0,
|
||||
@@ -55,7 +53,7 @@ fn should_return_header() {
|
||||
);
|
||||
|
||||
assert_matches!(
|
||||
client.header(Some(H256::from_low_u64_be(5)).into()),
|
||||
api.header(Some(H256::from_low_u64_be(5)).into()).wait(),
|
||||
Ok(None)
|
||||
);
|
||||
}
|
||||
@@ -65,26 +63,24 @@ fn should_return_a_block() {
|
||||
let core = ::tokio::runtime::Runtime::new().unwrap();
|
||||
let remote = core.executor();
|
||||
|
||||
let api = Chain {
|
||||
client: Arc::new(test_client::new()),
|
||||
subscriptions: Subscriptions::new(Arc::new(remote)),
|
||||
};
|
||||
let client = Arc::new(test_client::new());
|
||||
let api = new_full(client.clone(), Subscriptions::new(Arc::new(remote)));
|
||||
|
||||
let block = api.client.new_block(Default::default()).unwrap().bake().unwrap();
|
||||
let block = client.new_block(Default::default()).unwrap().bake().unwrap();
|
||||
let block_hash = block.hash();
|
||||
api.client.import(BlockOrigin::Own, block).unwrap();
|
||||
client.import(BlockOrigin::Own, block).unwrap();
|
||||
|
||||
// Genesis block is not justified
|
||||
assert_matches!(
|
||||
api.block(Some(api.client.genesis_hash()).into()),
|
||||
api.block(Some(client.genesis_hash()).into()).wait(),
|
||||
Ok(Some(SignedBlock { justification: None, .. }))
|
||||
);
|
||||
|
||||
assert_matches!(
|
||||
api.block(Some(block_hash).into()),
|
||||
api.block(Some(block_hash).into()).wait(),
|
||||
Ok(Some(ref x)) if x.block == Block {
|
||||
header: Header {
|
||||
parent_hash: api.client.genesis_hash(),
|
||||
parent_hash: client.genesis_hash(),
|
||||
number: 1,
|
||||
state_root: x.block.header.state_root.clone(),
|
||||
extrinsics_root: "03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314".parse().unwrap(),
|
||||
@@ -95,10 +91,10 @@ fn should_return_a_block() {
|
||||
);
|
||||
|
||||
assert_matches!(
|
||||
api.block(None.into()),
|
||||
api.block(None.into()).wait(),
|
||||
Ok(Some(ref x)) if x.block == Block {
|
||||
header: Header {
|
||||
parent_hash: api.client.genesis_hash(),
|
||||
parent_hash: client.genesis_hash(),
|
||||
number: 1,
|
||||
state_root: x.block.header.state_root.clone(),
|
||||
extrinsics_root: "03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314".parse().unwrap(),
|
||||
@@ -109,7 +105,7 @@ fn should_return_a_block() {
|
||||
);
|
||||
|
||||
assert_matches!(
|
||||
api.block(Some(H256::from_low_u64_be(5)).into()),
|
||||
api.block(Some(H256::from_low_u64_be(5)).into()).wait(),
|
||||
Ok(None)
|
||||
);
|
||||
}
|
||||
@@ -119,40 +115,38 @@ fn should_return_block_hash() {
|
||||
let core = ::tokio::runtime::Runtime::new().unwrap();
|
||||
let remote = core.executor();
|
||||
|
||||
let client = Chain {
|
||||
client: Arc::new(test_client::new()),
|
||||
subscriptions: Subscriptions::new(Arc::new(remote)),
|
||||
};
|
||||
let client = Arc::new(test_client::new());
|
||||
let api = new_full(client.clone(), Subscriptions::new(Arc::new(remote)));
|
||||
|
||||
assert_matches!(
|
||||
client.block_hash(None.into()),
|
||||
Ok(Some(ref x)) if x == &client.client.genesis_hash()
|
||||
api.block_hash(None.into()),
|
||||
Ok(Some(ref x)) if x == &client.genesis_hash()
|
||||
);
|
||||
|
||||
|
||||
assert_matches!(
|
||||
client.block_hash(Some(0u64.into()).into()),
|
||||
Ok(Some(ref x)) if x == &client.client.genesis_hash()
|
||||
api.block_hash(Some(0u64.into()).into()),
|
||||
Ok(Some(ref x)) if x == &client.genesis_hash()
|
||||
);
|
||||
|
||||
assert_matches!(
|
||||
client.block_hash(Some(1u64.into()).into()),
|
||||
api.block_hash(Some(1u64.into()).into()),
|
||||
Ok(None)
|
||||
);
|
||||
|
||||
let block = client.client.new_block(Default::default()).unwrap().bake().unwrap();
|
||||
client.client.import(BlockOrigin::Own, block.clone()).unwrap();
|
||||
let block = client.new_block(Default::default()).unwrap().bake().unwrap();
|
||||
client.import(BlockOrigin::Own, block.clone()).unwrap();
|
||||
|
||||
assert_matches!(
|
||||
client.block_hash(Some(0u64.into()).into()),
|
||||
Ok(Some(ref x)) if x == &client.client.genesis_hash()
|
||||
api.block_hash(Some(0u64.into()).into()),
|
||||
Ok(Some(ref x)) if x == &client.genesis_hash()
|
||||
);
|
||||
assert_matches!(
|
||||
client.block_hash(Some(1u64.into()).into()),
|
||||
api.block_hash(Some(1u64.into()).into()),
|
||||
Ok(Some(ref x)) if x == &block.hash()
|
||||
);
|
||||
assert_matches!(
|
||||
client.block_hash(Some(::primitives::U256::from(1u64).into()).into()),
|
||||
api.block_hash(Some(::primitives::U256::from(1u64).into()).into()),
|
||||
Ok(Some(ref x)) if x == &block.hash()
|
||||
);
|
||||
}
|
||||
@@ -163,30 +157,28 @@ fn should_return_finalized_hash() {
|
||||
let core = ::tokio::runtime::Runtime::new().unwrap();
|
||||
let remote = core.executor();
|
||||
|
||||
let client = Chain {
|
||||
client: Arc::new(test_client::new()),
|
||||
subscriptions: Subscriptions::new(Arc::new(remote)),
|
||||
};
|
||||
let client = Arc::new(test_client::new());
|
||||
let api = new_full(client.clone(), Subscriptions::new(Arc::new(remote)));
|
||||
|
||||
assert_matches!(
|
||||
client.finalized_head(),
|
||||
Ok(ref x) if x == &client.client.genesis_hash()
|
||||
api.finalized_head(),
|
||||
Ok(ref x) if x == &client.genesis_hash()
|
||||
);
|
||||
|
||||
// import new block
|
||||
let builder = client.client.new_block(Default::default()).unwrap();
|
||||
client.client.import(BlockOrigin::Own, builder.bake().unwrap()).unwrap();
|
||||
let builder = client.new_block(Default::default()).unwrap();
|
||||
client.import(BlockOrigin::Own, builder.bake().unwrap()).unwrap();
|
||||
// no finalization yet
|
||||
assert_matches!(
|
||||
client.finalized_head(),
|
||||
Ok(ref x) if x == &client.client.genesis_hash()
|
||||
api.finalized_head(),
|
||||
Ok(ref x) if x == &client.genesis_hash()
|
||||
);
|
||||
|
||||
// finalize
|
||||
client.client.finalize_block(BlockId::number(1), None).unwrap();
|
||||
client.finalize_block(BlockId::number(1), None).unwrap();
|
||||
assert_matches!(
|
||||
client.finalized_head(),
|
||||
Ok(ref x) if x == &client.client.block_hash(1).unwrap().unwrap()
|
||||
api.finalized_head(),
|
||||
Ok(ref x) if x == &client.block_hash(1).unwrap().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -197,18 +189,16 @@ fn should_notify_about_latest_block() {
|
||||
let (subscriber, id, transport) = Subscriber::new_test("test");
|
||||
|
||||
{
|
||||
let api = Chain {
|
||||
client: Arc::new(test_client::new()),
|
||||
subscriptions: Subscriptions::new(Arc::new(remote)),
|
||||
};
|
||||
let client = Arc::new(test_client::new());
|
||||
let api = new_full(client.clone(), Subscriptions::new(Arc::new(remote)));
|
||||
|
||||
api.subscribe_new_heads(Default::default(), subscriber);
|
||||
|
||||
// assert id assigned
|
||||
assert_eq!(core.block_on(id), Ok(Ok(SubscriptionId::Number(1))));
|
||||
|
||||
let builder = api.client.new_block(Default::default()).unwrap();
|
||||
api.client.import(BlockOrigin::Own, builder.bake().unwrap()).unwrap();
|
||||
let builder = client.new_block(Default::default()).unwrap();
|
||||
client.import(BlockOrigin::Own, builder.bake().unwrap()).unwrap();
|
||||
}
|
||||
|
||||
// assert initial head sent.
|
||||
@@ -228,19 +218,17 @@ fn should_notify_about_finalized_block() {
|
||||
let (subscriber, id, transport) = Subscriber::new_test("test");
|
||||
|
||||
{
|
||||
let api = Chain {
|
||||
client: Arc::new(test_client::new()),
|
||||
subscriptions: Subscriptions::new(Arc::new(remote)),
|
||||
};
|
||||
let client = Arc::new(test_client::new());
|
||||
let api = new_full(client.clone(), Subscriptions::new(Arc::new(remote)));
|
||||
|
||||
api.subscribe_finalized_heads(Default::default(), subscriber);
|
||||
|
||||
// assert id assigned
|
||||
assert_eq!(core.block_on(id), Ok(Ok(SubscriptionId::Number(1))));
|
||||
|
||||
let builder = api.client.new_block(Default::default()).unwrap();
|
||||
api.client.import(BlockOrigin::Own, builder.bake().unwrap()).unwrap();
|
||||
api.client.finalize_block(BlockId::number(1), None).unwrap();
|
||||
let builder = client.new_block(Default::default()).unwrap();
|
||||
client.import(BlockOrigin::Own, builder.bake().unwrap()).unwrap();
|
||||
client.finalize_block(BlockId::number(1), None).unwrap();
|
||||
}
|
||||
|
||||
// assert initial head sent.
|
||||
|
||||
Reference in New Issue
Block a user