Latest headers Pub-Sub (#5655)
* Signer subscription. * Fixing RPC tests. * Block Headers eth-pubsub. * PubSub for light client. * Fixing tests. * Updating to proper jsonrpc version. * Update to correct tests. * Fixing tests.
This commit is contained in:
committed by
Arkadiy Paronyan
parent
92f5aa7e10
commit
f38cc8e182
153
rpc/src/v1/impls/eth_pubsub.rs
Normal file
153
rpc/src/v1/impls/eth_pubsub.rs
Normal file
@@ -0,0 +1,153 @@
|
||||
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity.
|
||||
|
||||
// Parity 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.
|
||||
|
||||
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Eth PUB-SUB rpc implementation.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use futures::{self, BoxFuture, Future};
|
||||
use jsonrpc_core::Error;
|
||||
use jsonrpc_macros::Trailing;
|
||||
use jsonrpc_macros::pubsub::{Sink, Subscriber};
|
||||
use jsonrpc_pubsub::SubscriptionId;
|
||||
|
||||
use v1::helpers::{errors, Subscribers};
|
||||
use v1::metadata::Metadata;
|
||||
use v1::traits::EthPubSub;
|
||||
use v1::types::{pubsub, RichHeader};
|
||||
|
||||
use ethcore::encoded;
|
||||
use ethcore::client::{BlockChainClient, ChainNotify, BlockId};
|
||||
use light::client::{LightChainClient, LightChainNotify};
|
||||
use parity_reactor::Remote;
|
||||
use util::{Mutex, H256, Bytes};
|
||||
|
||||
/// Eth PubSub implementation.
|
||||
pub struct EthPubSubClient<C> {
|
||||
handler: Arc<ChainNotificationHandler<C>>,
|
||||
heads_subscribers: Arc<Mutex<Subscribers<Sink<pubsub::Result>>>>,
|
||||
}
|
||||
|
||||
impl<C> EthPubSubClient<C> {
|
||||
/// Creates new `EthPubSubClient`.
|
||||
pub fn new(client: Arc<C>, remote: Remote) -> Self {
|
||||
let heads_subscribers = Arc::new(Mutex::new(Subscribers::default()));
|
||||
EthPubSubClient {
|
||||
handler: Arc::new(ChainNotificationHandler {
|
||||
client: client,
|
||||
remote: remote,
|
||||
heads_subscribers: heads_subscribers.clone(),
|
||||
}),
|
||||
heads_subscribers: heads_subscribers,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a chain notification handler.
|
||||
pub fn handler(&self) -> Arc<ChainNotificationHandler<C>> {
|
||||
self.handler.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// PubSub Notification handler.
|
||||
pub struct ChainNotificationHandler<C> {
|
||||
client: Arc<C>,
|
||||
remote: Remote,
|
||||
heads_subscribers: Arc<Mutex<Subscribers<Sink<pubsub::Result>>>>,
|
||||
}
|
||||
|
||||
impl<C> ChainNotificationHandler<C> {
|
||||
fn notify(&self, blocks: Vec<(encoded::Header, BTreeMap<String, String>)>) {
|
||||
for subscriber in self.heads_subscribers.lock().values() {
|
||||
for &(ref block, ref extra_info) in &blocks {
|
||||
self.remote.spawn(subscriber
|
||||
.notify(pubsub::Result::Header(RichHeader {
|
||||
inner: block.into(),
|
||||
extra_info: extra_info.clone(),
|
||||
}))
|
||||
.map(|_| ())
|
||||
.map_err(|e| warn!(target: "rpc", "Unable to send notification: {}", e))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: LightChainClient> LightChainNotify for ChainNotificationHandler<C> {
|
||||
fn new_headers(
|
||||
&self,
|
||||
headers: &[H256],
|
||||
) {
|
||||
let blocks = headers
|
||||
.iter()
|
||||
.filter_map(|hash| self.client.block_header(BlockId::Hash(*hash)))
|
||||
.map(|header| (header, Default::default()))
|
||||
.collect();
|
||||
|
||||
self.notify(blocks);
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: BlockChainClient> ChainNotify for ChainNotificationHandler<C> {
|
||||
fn new_blocks(
|
||||
&self,
|
||||
_imported: Vec<H256>,
|
||||
_invalid: Vec<H256>,
|
||||
enacted: Vec<H256>,
|
||||
_retracted: Vec<H256>,
|
||||
_sealed: Vec<H256>,
|
||||
// Block bytes.
|
||||
_proposed: Vec<Bytes>,
|
||||
_duration: u64,
|
||||
) {
|
||||
const EXTRA_INFO_PROOF: &'static str = "Object exists in in blockchain (fetched earlier), extra_info is always available if object exists; qed";
|
||||
let blocks = enacted
|
||||
.into_iter()
|
||||
.filter_map(|hash| self.client.block_header(BlockId::Hash(hash)))
|
||||
.map(|header| {
|
||||
let hash = header.hash();
|
||||
(header, self.client.block_extra_info(BlockId::Hash(hash)).expect(EXTRA_INFO_PROOF))
|
||||
})
|
||||
.collect();
|
||||
self.notify(blocks);
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: Send + Sync + 'static> EthPubSub for EthPubSubClient<C> {
|
||||
type Metadata = Metadata;
|
||||
|
||||
fn subscribe(
|
||||
&self,
|
||||
_meta: Metadata,
|
||||
subscriber: Subscriber<pubsub::Result>,
|
||||
kind: pubsub::Kind,
|
||||
params: Trailing<pubsub::Params>,
|
||||
) {
|
||||
match (kind, params.0) {
|
||||
(pubsub::Kind::NewHeads, pubsub::Params::None) => {
|
||||
self.heads_subscribers.lock().push(subscriber)
|
||||
},
|
||||
_ => {
|
||||
let _ = subscriber.reject(errors::unimplemented(None));
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn unsubscribe(&self, id: SubscriptionId) -> BoxFuture<bool, Error> {
|
||||
let res = self.heads_subscribers.lock().remove(&id).is_some();
|
||||
futures::future::ok(res).boxed()
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
mod eth;
|
||||
mod eth_filter;
|
||||
mod eth_pubsub;
|
||||
mod net;
|
||||
mod parity;
|
||||
mod parity_accounts;
|
||||
@@ -36,6 +37,7 @@ pub mod light;
|
||||
|
||||
pub use self::eth::{EthClient, EthClientOptions};
|
||||
pub use self::eth_filter::EthFilterClient;
|
||||
pub use self::eth_pubsub::EthPubSubClient;
|
||||
pub use self::net::NetClient;
|
||||
pub use self::parity::ParityClient;
|
||||
pub use self::parity_accounts::ParityAccountsClient;
|
||||
|
||||
@@ -48,7 +48,7 @@ use v1::types::{
|
||||
TransactionStats, LocalTransactionStatus,
|
||||
BlockNumber, ConsensusCapability, VersionInfo,
|
||||
OperationsInfo, DappId, ChainStatus,
|
||||
AccountInfo, HwAccountInfo, Header, RichHeader
|
||||
AccountInfo, HwAccountInfo, RichHeader
|
||||
};
|
||||
|
||||
/// Parity implementation.
|
||||
@@ -411,25 +411,7 @@ impl<C, M, S: ?Sized, U> Parity for ParityClient<C, M, S, U> where
|
||||
};
|
||||
|
||||
future::ok(RichHeader {
|
||||
inner: Header {
|
||||
hash: Some(encoded.hash().into()),
|
||||
size: Some(encoded.rlp().as_raw().len().into()),
|
||||
parent_hash: encoded.parent_hash().into(),
|
||||
uncles_hash: encoded.uncles_hash().into(),
|
||||
author: encoded.author().into(),
|
||||
miner: encoded.author().into(),
|
||||
state_root: encoded.state_root().into(),
|
||||
transactions_root: encoded.transactions_root().into(),
|
||||
receipts_root: encoded.receipts_root().into(),
|
||||
number: Some(encoded.number().into()),
|
||||
gas_used: encoded.gas_used().into(),
|
||||
gas_limit: encoded.gas_limit().into(),
|
||||
logs_bloom: encoded.log_bloom().into(),
|
||||
timestamp: encoded.timestamp().into(),
|
||||
difficulty: encoded.difficulty().into(),
|
||||
seal_fields: encoded.seal().into_iter().map(Into::into).collect(),
|
||||
extra_data: Bytes::new(encoded.extra_data()),
|
||||
},
|
||||
inner: encoded.into(),
|
||||
extra_info: client.block_extra_info(id).expect(EXTRA_INFO_PROOF),
|
||||
}).boxed()
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ pub mod traits;
|
||||
pub mod tests;
|
||||
pub mod types;
|
||||
|
||||
pub use self::traits::{Web3, Eth, EthFilter, EthSigning, Net, Parity, ParityAccounts, ParitySet, ParitySigning, PubSub, Signer, Personal, Traces, Rpc, SecretStore};
|
||||
pub use self::traits::{Web3, Eth, EthFilter, EthPubSub, EthSigning, Net, Parity, ParityAccounts, ParitySet, ParitySigning, PubSub, Signer, Personal, Traces, Rpc, SecretStore};
|
||||
pub use self::impls::*;
|
||||
pub use self::helpers::{SigningQueue, SignerService, ConfirmationsQueue, NetworkSettings, block_import, informant, dispatch};
|
||||
pub use self::metadata::Metadata;
|
||||
|
||||
104
rpc/src/v1/tests/mocked/eth_pubsub.rs
Normal file
104
rpc/src/v1/tests/mocked/eth_pubsub.rs
Normal file
@@ -0,0 +1,104 @@
|
||||
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity.
|
||||
|
||||
// Parity 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.
|
||||
|
||||
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use jsonrpc_core::MetaIoHandler;
|
||||
use jsonrpc_core::futures::{self, Stream, Future};
|
||||
use jsonrpc_pubsub::Session;
|
||||
|
||||
use v1::{EthPubSub, EthPubSubClient, Metadata};
|
||||
|
||||
use ethcore::client::{TestBlockChainClient, EachBlockWith, ChainNotify};
|
||||
use parity_reactor::EventLoop;
|
||||
|
||||
#[test]
|
||||
fn should_subscribe_to_new_heads() {
|
||||
// given
|
||||
let el = EventLoop::spawn();
|
||||
let mut client = TestBlockChainClient::new();
|
||||
// Insert some blocks
|
||||
client.add_blocks(3, EachBlockWith::Nothing);
|
||||
let h3 = client.block_hash_delta_minus(1);
|
||||
let h2 = client.block_hash_delta_minus(2);
|
||||
let h1 = client.block_hash_delta_minus(3);
|
||||
|
||||
let pubsub = EthPubSubClient::new(Arc::new(client), el.remote());
|
||||
let handler = pubsub.handler();
|
||||
let pubsub = pubsub.to_delegate();
|
||||
|
||||
let mut io = MetaIoHandler::default();
|
||||
io.extend_with(pubsub);
|
||||
|
||||
let mut metadata = Metadata::default();
|
||||
let (sender, receiver) = futures::sync::mpsc::channel(8);
|
||||
metadata.session = Some(Arc::new(Session::new(sender)));
|
||||
|
||||
// Subscribe
|
||||
let request = r#"{"jsonrpc": "2.0", "method": "eth_subscribe", "params": ["newHeads"], "id": 1}"#;
|
||||
let response = r#"{"jsonrpc":"2.0","result":1,"id":1}"#;
|
||||
assert_eq!(io.handle_request_sync(request, metadata.clone()), Some(response.to_owned()));
|
||||
|
||||
// Check notifications
|
||||
handler.new_blocks(vec![], vec![], vec![h1], vec![], vec![], vec![], 0);
|
||||
let (res, receiver) = receiver.into_future().wait().unwrap();
|
||||
let response = r#"{"jsonrpc":"2.0","method":"eth_subscription","params":{"result":{"author":"0x0000000000000000000000000000000000000000","difficulty":"0x1","extraData":"0x","gasLimit":"0xf4240","gasUsed":"0x0","hash":"0x3457d2fa2e3dd33c78ac681cf542e429becf718859053448748383af67e23218","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","miner":"0x0000000000000000000000000000000000000000","number":"0x1","parentHash":"0x0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303","receiptsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","sealFields":[],"sha3Uncles":"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347","size":"0x1c9","stateRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","timestamp":"0x0","transactionsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"},"subscription":1}}"#;
|
||||
assert_eq!(res, Some(response.into()));
|
||||
|
||||
// Notify about two blocks
|
||||
handler.new_blocks(vec![], vec![], vec![h2, h3], vec![], vec![], vec![], 0);
|
||||
|
||||
// Receive both
|
||||
let (res, receiver) = receiver.into_future().wait().unwrap();
|
||||
let response = r#"{"jsonrpc":"2.0","method":"eth_subscription","params":{"result":{"author":"0x0000000000000000000000000000000000000000","difficulty":"0x2","extraData":"0x","gasLimit":"0xf4240","gasUsed":"0x0","hash":"0x44e5ecf454ea99af9d8a8f2ca0daba96964c90de05db7a78f59b84ae9e749706","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","miner":"0x0000000000000000000000000000000000000000","number":"0x2","parentHash":"0x3457d2fa2e3dd33c78ac681cf542e429becf718859053448748383af67e23218","receiptsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","sealFields":[],"sha3Uncles":"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347","size":"0x1c9","stateRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","timestamp":"0x0","transactionsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"},"subscription":1}}"#;
|
||||
assert_eq!(res, Some(response.into()));
|
||||
let (res, receiver) = receiver.into_future().wait().unwrap();
|
||||
let response = r#"{"jsonrpc":"2.0","method":"eth_subscription","params":{"result":{"author":"0x0000000000000000000000000000000000000000","difficulty":"0x3","extraData":"0x","gasLimit":"0xf4240","gasUsed":"0x0","hash":"0xdf04a98bb0c6fa8441bd429822f65a46d0cb553f6bcef602b973e65c81497f8e","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","miner":"0x0000000000000000000000000000000000000000","number":"0x3","parentHash":"0x44e5ecf454ea99af9d8a8f2ca0daba96964c90de05db7a78f59b84ae9e749706","receiptsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","sealFields":[],"sha3Uncles":"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347","size":"0x1c9","stateRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","timestamp":"0x0","transactionsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"},"subscription":1}}"#;
|
||||
assert_eq!(res, Some(response.into()));
|
||||
|
||||
// And unsubscribe
|
||||
let request = r#"{"jsonrpc": "2.0", "method": "eth_unsubscribe", "params": [1], "id": 1}"#;
|
||||
let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#;
|
||||
assert_eq!(io.handle_request_sync(request, metadata), Some(response.to_owned()));
|
||||
|
||||
let (res, _receiver) = receiver.into_future().wait().unwrap();
|
||||
assert_eq!(res, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_return_unimplemented() {
|
||||
// given
|
||||
let el = EventLoop::spawn();
|
||||
let client = TestBlockChainClient::new();
|
||||
let pubsub = EthPubSubClient::new(Arc::new(client), el.remote());
|
||||
let pubsub = pubsub.to_delegate();
|
||||
|
||||
let mut io = MetaIoHandler::default();
|
||||
io.extend_with(pubsub);
|
||||
|
||||
let mut metadata = Metadata::default();
|
||||
let (sender, _receiver) = futures::sync::mpsc::channel(8);
|
||||
metadata.session = Some(Arc::new(Session::new(sender)));
|
||||
|
||||
// Subscribe
|
||||
let response = r#"{"jsonrpc":"2.0","error":{"code":-32000,"message":"This request is not implemented yet. Please create an issue on Github repo."},"id":1}"#;
|
||||
let request = r#"{"jsonrpc": "2.0", "method": "eth_subscribe", "params": ["newPendingTransactions"], "id": 1}"#;
|
||||
assert_eq!(io.handle_request_sync(request, metadata.clone()), Some(response.to_owned()));
|
||||
let request = r#"{"jsonrpc": "2.0", "method": "eth_subscribe", "params": ["logs"], "id": 1}"#;
|
||||
assert_eq!(io.handle_request_sync(request, metadata.clone()), Some(response.to_owned()));
|
||||
let request = r#"{"jsonrpc": "2.0", "method": "eth_subscribe", "params": ["syncing"], "id": 1}"#;
|
||||
assert_eq!(io.handle_request_sync(request, metadata.clone()), Some(response.to_owned()));
|
||||
}
|
||||
@@ -18,6 +18,7 @@
|
||||
//! method calls properly.
|
||||
|
||||
mod eth;
|
||||
mod eth_pubsub;
|
||||
mod manage_network;
|
||||
mod net;
|
||||
mod parity;
|
||||
|
||||
42
rpc/src/v1/traits/eth_pubsub.rs
Normal file
42
rpc/src/v1/traits/eth_pubsub.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity.
|
||||
|
||||
// Parity 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.
|
||||
|
||||
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Eth PUB-SUB rpc interface.
|
||||
|
||||
use jsonrpc_core::Error;
|
||||
use jsonrpc_macros::Trailing;
|
||||
use jsonrpc_macros::pubsub::Subscriber;
|
||||
use jsonrpc_pubsub::SubscriptionId;
|
||||
use futures::BoxFuture;
|
||||
|
||||
use v1::types::pubsub;
|
||||
|
||||
build_rpc_trait! {
|
||||
/// Eth PUB-SUB rpc interface.
|
||||
pub trait EthPubSub {
|
||||
type Metadata;
|
||||
|
||||
#[pubsub(name = "eth_subscription")] {
|
||||
/// Subscribe to Eth subscription.
|
||||
#[rpc(name = "eth_subscribe")]
|
||||
fn subscribe(&self, Self::Metadata, Subscriber<pubsub::Result>, pubsub::Kind, Trailing<pubsub::Params>);
|
||||
|
||||
/// Unsubscribe from existing Eth subscription.
|
||||
#[rpc(name = "eth_unsubscribe")]
|
||||
fn unsubscribe(&self, SubscriptionId) -> BoxFuture<bool, Error>;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
pub mod web3;
|
||||
pub mod eth;
|
||||
pub mod eth_pubsub;
|
||||
pub mod eth_signing;
|
||||
pub mod net;
|
||||
pub mod parity;
|
||||
@@ -33,6 +34,7 @@ pub mod secretstore;
|
||||
|
||||
pub use self::web3::Web3;
|
||||
pub use self::eth::{Eth, EthFilter};
|
||||
pub use self::eth_pubsub::EthPubSub;
|
||||
pub use self::eth_signing::EthSigning;
|
||||
pub use self::net::Net;
|
||||
pub use self::parity::Parity;
|
||||
|
||||
@@ -16,6 +16,9 @@
|
||||
|
||||
use std::ops::Deref;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use ethcore::encoded::Header as EthHeader;
|
||||
|
||||
use serde::{Serialize, Serializer};
|
||||
use serde::ser::Error;
|
||||
use v1::types::{Bytes, Transaction, H160, H256, H2048, U256};
|
||||
@@ -97,7 +100,7 @@ pub struct Block {
|
||||
}
|
||||
|
||||
/// Block header representation.
|
||||
#[derive(Debug, Serialize)]
|
||||
#[derive(Debug, Serialize, PartialEq, Eq)]
|
||||
pub struct Header {
|
||||
/// Hash of the block
|
||||
pub hash: Option<H256>,
|
||||
@@ -146,6 +149,36 @@ pub struct Header {
|
||||
pub size: Option<U256>,
|
||||
}
|
||||
|
||||
impl From<EthHeader> for Header {
|
||||
fn from(h: EthHeader) -> Self {
|
||||
(&h).into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<&'a EthHeader> for Header {
|
||||
fn from(h: &'a EthHeader) -> Self {
|
||||
Header {
|
||||
hash: Some(h.hash().into()),
|
||||
size: Some(h.rlp().as_raw().len().into()),
|
||||
parent_hash: h.parent_hash().into(),
|
||||
uncles_hash: h.uncles_hash().into(),
|
||||
author: h.author().into(),
|
||||
miner: h.author().into(),
|
||||
state_root: h.state_root().into(),
|
||||
transactions_root: h.transactions_root().into(),
|
||||
receipts_root: h.receipts_root().into(),
|
||||
number: Some(h.number().into()),
|
||||
gas_used: h.gas_used().into(),
|
||||
gas_limit: h.gas_limit().into(),
|
||||
logs_bloom: h.log_bloom().into(),
|
||||
timestamp: h.timestamp().into(),
|
||||
difficulty: h.difficulty().into(),
|
||||
seal_fields: h.seal().into_iter().map(Into::into).collect(),
|
||||
extra_data: h.extra_data().into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Block representation with additional info.
|
||||
pub type RichBlock = Rich<Block>;
|
||||
|
||||
@@ -153,7 +186,7 @@ pub type RichBlock = Rich<Block>;
|
||||
pub type RichHeader = Rich<Header>;
|
||||
|
||||
/// Value representation with additional info
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Rich<T> {
|
||||
/// Standard value.
|
||||
pub inner: T,
|
||||
|
||||
@@ -22,7 +22,7 @@ use ethcore::client::BlockId;
|
||||
use v1::types::{BlockNumber, H160, H256, Log};
|
||||
|
||||
/// Variadic value
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
|
||||
pub enum VariadicValue<T> where T: Deserialize {
|
||||
/// Single
|
||||
Single(T),
|
||||
@@ -53,7 +53,7 @@ pub type FilterAddress = VariadicValue<H160>;
|
||||
pub type Topic = VariadicValue<H256>;
|
||||
|
||||
/// Filter
|
||||
#[derive(Debug, PartialEq, Clone, Deserialize)]
|
||||
#[derive(Debug, PartialEq, Clone, Deserialize, Eq, Hash)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Filter {
|
||||
/// From Block
|
||||
|
||||
@@ -43,6 +43,8 @@ mod transaction_condition;
|
||||
mod uint;
|
||||
mod work;
|
||||
|
||||
pub mod pubsub;
|
||||
|
||||
pub use self::account_info::{AccountInfo, HwAccountInfo};
|
||||
pub use self::bytes::Bytes;
|
||||
pub use self::block::{RichBlock, Block, BlockTransactions, Header, RichHeader, Rich};
|
||||
|
||||
114
rpc/src/v1/types/pubsub.rs
Normal file
114
rpc/src/v1/types/pubsub.rs
Normal file
@@ -0,0 +1,114 @@
|
||||
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity.
|
||||
|
||||
// Parity 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.
|
||||
|
||||
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Pub-Sub types.
|
||||
|
||||
use serde::{Serialize, Serializer};
|
||||
use v1::types::{RichHeader, Filter};
|
||||
|
||||
/// Subscription result.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Result {
|
||||
/// New block header.
|
||||
Header(RichHeader),
|
||||
}
|
||||
|
||||
impl Serialize for Result {
|
||||
fn serialize<S>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error>
|
||||
where S: Serializer
|
||||
{
|
||||
match *self {
|
||||
Result::Header(ref header) => header.serialize(serializer),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Subscription kind.
|
||||
#[derive(Debug, Deserialize, PartialEq, Eq, Hash, Clone)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum Kind {
|
||||
/// New block headers subscription.
|
||||
#[serde(rename="newHeads")]
|
||||
NewHeads,
|
||||
/// Logs subscription.
|
||||
#[serde(rename="logs")]
|
||||
Logs,
|
||||
/// New Pending Transactions subscription.
|
||||
#[serde(rename="newPendingTransactions")]
|
||||
NewPendingTransactions,
|
||||
/// Node syncing status subscription.
|
||||
#[serde(rename="syncing")]
|
||||
Syncing,
|
||||
}
|
||||
|
||||
/// Subscription kind.
|
||||
#[derive(Debug, Deserialize, PartialEq, Eq, Hash, Clone)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum Params {
|
||||
/// No parameters passed.
|
||||
None,
|
||||
/// Log parameters.
|
||||
Logs(Filter),
|
||||
}
|
||||
|
||||
impl Default for Params {
|
||||
fn default() -> Self {
|
||||
Params::None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json;
|
||||
use super::{Result, Kind};
|
||||
use v1::types::{RichHeader, Header};
|
||||
|
||||
#[test]
|
||||
fn should_deserialize_kind() {
|
||||
assert_eq!(serde_json::from_str::<Kind>(r#""newHeads""#).unwrap(), Kind::NewHeads);
|
||||
assert_eq!(serde_json::from_str::<Kind>(r#""logs""#).unwrap(), Kind::Logs);
|
||||
assert_eq!(serde_json::from_str::<Kind>(r#""newPendingTransactions""#).unwrap(), Kind::NewPendingTransactions);
|
||||
assert_eq!(serde_json::from_str::<Kind>(r#""syncing""#).unwrap(), Kind::Syncing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_serialize_header() {
|
||||
let header = Result::Header(RichHeader {
|
||||
extra_info: Default::default(),
|
||||
inner: Header {
|
||||
hash: Some(Default::default()),
|
||||
parent_hash: Default::default(),
|
||||
uncles_hash: Default::default(),
|
||||
author: Default::default(),
|
||||
miner: Default::default(),
|
||||
state_root: Default::default(),
|
||||
transactions_root: Default::default(),
|
||||
receipts_root: Default::default(),
|
||||
number: Some(Default::default()),
|
||||
gas_used: Default::default(),
|
||||
gas_limit: Default::default(),
|
||||
extra_data: Default::default(),
|
||||
logs_bloom: Default::default(),
|
||||
timestamp: Default::default(),
|
||||
difficulty: Default::default(),
|
||||
seal_fields: vec![Default::default(), Default::default()],
|
||||
size: Some(69.into()),
|
||||
},
|
||||
});
|
||||
let expected = r#"{"author":"0x0000000000000000000000000000000000000000","difficulty":"0x0","extraData":"0x","gasLimit":"0x0","gasUsed":"0x0","hash":"0x0000000000000000000000000000000000000000000000000000000000000000","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","miner":"0x0000000000000000000000000000000000000000","number":"0x0","parentHash":"0x0000000000000000000000000000000000000000000000000000000000000000","receiptsRoot":"0x0000000000000000000000000000000000000000000000000000000000000000","sealFields":["0x","0x"],"sha3Uncles":"0x0000000000000000000000000000000000000000000000000000000000000000","size":"0x45","stateRoot":"0x0000000000000000000000000000000000000000000000000000000000000000","timestamp":"0x0","transactionsRoot":"0x0000000000000000000000000000000000000000000000000000000000000000"}"#;
|
||||
assert_eq!(serde_json::to_string(&header).unwrap(), expected);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user