Exposing RPC over websockets

This commit is contained in:
Tomasz Drwięga 2016-05-27 17:46:15 +02:00
parent cf19e38663
commit c4e2f65051
9 changed files with 140 additions and 51 deletions

1
Cargo.lock generated
View File

@ -354,6 +354,7 @@ dependencies = [
"env_logger 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
"ethcore-rpc 1.2.0",
"ethcore-util 1.2.0",
"jsonrpc-core 2.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",

View File

@ -244,6 +244,11 @@ fn execute_client(conf: Configuration, spec: Spec, client_config: ClientConfig)
port: conf.args.flag_signer_port,
}, signer::Dependencies {
panic_handler: panic_handler.clone(),
client: client.clone(),
sync: sync.clone(),
secret_store: account_service.clone(),
miner: miner.clone(),
external_miner: external_miner.clone(),
});
// Register IO handler

View File

@ -15,6 +15,10 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::sync::Arc;
use ethcore::client::Client;
use ethsync::EthSync;
use ethminer::{Miner, ExternalMiner};
use util::keys::store::AccountService;
use util::panics::{PanicHandler, ForwardPanic};
use die::*;
@ -32,36 +36,51 @@ pub struct Configuration {
pub struct Dependencies {
pub panic_handler: Arc<PanicHandler>,
pub client: Arc<Client>,
pub sync: Arc<EthSync>,
pub secret_store: Arc<AccountService>,
pub miner: Arc<Miner>,
pub external_miner: Arc<ExternalMiner>,
}
pub fn start(conf: Configuration, deps: Dependencies) -> Option<SignerServer> {
if !conf.enabled {
None
} else {
Some(do_start(conf, deps))
}
}
#[cfg(feature = "ethcore-signer")]
pub fn start(conf: Configuration, deps: Dependencies) -> Option<SignerServer> {
if !conf.enabled {
return None;
}
fn do_start(conf: Configuration, deps: Dependencies) -> SignerServer {
let addr = format!("127.0.0.1:{}", conf.port).parse().unwrap_or_else(|_| {
die!("Invalid port specified: {}", conf.port)
});
let addr = format!("127.0.0.1:{}", conf.port).parse().unwrap_or_else(|_| die!("Invalid port specified: {}", conf.port));
let start_result = signer::Server::start(addr);
let start_result = {
use ethcore_rpc::v1::*;
let server = signer::ServerBuilder::new();
server.add_delegate(Web3Client::new().to_delegate());
server.add_delegate(NetClient::new(&deps.sync).to_delegate());
server.add_delegate(EthClient::new(&deps.client, &deps.sync, &deps.secret_store, &deps.miner, &deps.external_miner).to_delegate());
server.add_delegate(EthFilterClient::new(&deps.client, &deps.miner).to_delegate());
server.add_delegate(PersonalClient::new(&deps.secret_store).to_delegate());
server.start(addr)
};
match start_result {
Err(signer::ServerError::IoError(err)) => die_with_io_error("Trusted Signer", err),
Err(e) => die!("Trusted Signer: {:?}", e),
Ok(server) => {
deps.panic_handler.forward_from(&server);
Some(server)
server
},
}
}
#[cfg(not(feature = "ethcore-signer"))]
pub fn start(conf: Configuration) -> !{
if !conf.enabled {
return None;
}
fn do_start(conf: Configuration) -> ! {
die!("Your Parity version has been compiled without Trusted Signer support.")
}

View File

@ -47,7 +47,7 @@ mod tests {
use serde_json;
use util::numbers::{U256};
use util::hash::Address;
use types::bytes::Bytes;
use v1::types::bytes::Bytes;
use super::*;
#[test]

View File

@ -16,6 +16,7 @@ syntex = "^0.32.0"
serde = "0.7.0"
serde_json = "0.7.0"
rustc-serialize = "0.3"
jsonrpc-core = "2.0"
log = "0.3"
env_logger = "0.3"
ws = "0.4.7"

View File

@ -50,6 +50,7 @@ extern crate rustc_serialize;
extern crate ethcore_util as util;
extern crate ethcore_rpc as rpc;
extern crate jsonrpc_core;
extern crate ws;
mod signing_queue;

View File

@ -45,7 +45,7 @@ mod test {
use std::collections::HashSet;
use util::hash::Address;
use util::numbers::U256;
use rpc::v1::types::transaction_request::TransactionRequest;
use rpc::v1::types::TransactionRequest;
use super::*;
#[test]

View File

@ -19,11 +19,14 @@
use ws;
use std;
use std::thread;
use std::default::Default;
use std::ops::Drop;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::net::SocketAddr;
use util::panics::{PanicHandler, OnPanicListener, MayPanic};
use jsonrpc_core::{IoHandler, IoDelegate};
mod session;
/// Signer startup error
#[derive(Debug)]
@ -43,9 +46,40 @@ impl From<ws::Error> for ServerError {
}
}
/// Builder for `WebSockets` server
pub struct ServerBuilder {
handler: Arc<IoHandler>,
}
impl Default for ServerBuilder {
fn default() -> Self {
ServerBuilder::new()
}
}
impl ServerBuilder {
/// Creates new `ServerBuilder`
pub fn new() -> Self {
ServerBuilder {
handler: Arc::new(IoHandler::new())
}
}
/// Adds rpc delegate
pub fn add_delegate<D>(&self, delegate: IoDelegate<D>) where D: Send + Sync + 'static {
self.handler.add_delegate(delegate);
}
/// Starts a new `WebSocket` server in separate thread.
/// Returns a `Server` handle which closes the server when droped.
pub fn start(self, addr: SocketAddr) -> Result<Server, ServerError> {
Server::start(addr, self.handler)
}
}
/// `WebSockets` server implementation.
pub struct Server {
handle: Option<thread::JoinHandle<ws::WebSocket<Factory>>>,
handle: Option<thread::JoinHandle<ws::WebSocket<session::Factory>>>,
broadcaster: ws::Sender,
panic_handler: Arc<PanicHandler>,
}
@ -53,7 +87,7 @@ pub struct Server {
impl Server {
/// Starts a new `WebSocket` server in separate thread.
/// Returns a `Server` handle which closes the server when droped.
pub fn start(addr: SocketAddr) -> Result<Server, ServerError> {
pub fn start(addr: SocketAddr, handler: Arc<IoHandler>) -> Result<Server, ServerError> {
let config = {
let mut config = ws::Settings::default();
config.max_connections = 5;
@ -62,10 +96,7 @@ impl Server {
};
// Create WebSocket
let session_id = Arc::new(AtomicUsize::new(1));
let ws = try!(ws::Builder::new().with_settings(config).build(Factory {
session_id: session_id,
}));
let ws = try!(ws::Builder::new().with_settings(config).build(session::Factory::new(handler)));
let panic_handler = PanicHandler::new_in_arc();
let ph = panic_handler.clone();
@ -98,31 +129,3 @@ impl Drop for Server {
self.handle.take().unwrap().join().unwrap();
}
}
struct Session {
id: usize,
out: ws::Sender,
}
impl ws::Handler for Session {
fn on_open(&mut self, _shake: ws::Handshake) -> ws::Result<()> {
try!(self.out.send(format!("Hello client no: {}. We are not implemented yet.", self.id)));
try!(self.out.close(ws::CloseCode::Normal));
Ok(())
}
}
struct Factory {
session_id: Arc<AtomicUsize>,
}
impl ws::Factory for Factory {
type Handler = Session;
fn connection_made(&mut self, sender: ws::Sender) -> Self::Handler {
Session {
id: self.session_id.fetch_add(1, Ordering::SeqCst),
out: sender,
}
}
}

View File

@ -0,0 +1,59 @@
// Copyright 2015, 2016 Ethcore (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/>.
//! Session handlers factory.
use ws;
use std::sync::Arc;
use jsonrpc_core::IoHandler;
pub struct Session {
out: ws::Sender,
handler: Arc<IoHandler>,
}
impl ws::Handler for Session {
fn on_message(&mut self, msg: ws::Message) -> ws::Result<()> {
let req = try!(msg.as_text());
match self.handler.handle_request(req) {
Some(res) => self.out.send(res),
None => Ok(()),
}
}
}
pub struct Factory {
handler: Arc<IoHandler>,
}
impl Factory {
pub fn new(handler: Arc<IoHandler>) -> Self {
Factory {
handler: handler,
}
}
}
impl ws::Factory for Factory {
type Handler = Session;
fn connection_made(&mut self, sender: ws::Sender) -> Self::Handler {
Session {
out: sender,
handler: self.handler.clone(),
}
}
}