Merge pull request #1167 from ethcore/signer-rpc

Exposing RPC over Signer WebSockets
This commit is contained in:
Marek Kotewicz 2016-05-30 21:31:20 +02:00
commit 43348c1629
7 changed files with 141 additions and 51 deletions

1
Cargo.lock generated
View File

@ -356,6 +356,7 @@ dependencies = [
"env_logger 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "env_logger 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
"ethcore-rpc 1.2.0", "ethcore-rpc 1.2.0",
"ethcore-util 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)", "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-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)", "rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",

View File

@ -242,6 +242,11 @@ fn execute_client(conf: Configuration, spec: Spec, client_config: ClientConfig)
port: conf.args.flag_signer_port, port: conf.args.flag_signer_port,
}, signer::Dependencies { }, signer::Dependencies {
panic_handler: panic_handler.clone(), 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 // Register IO handler

View File

@ -15,6 +15,10 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>. // along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::sync::Arc; 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 util::panics::{PanicHandler, ForwardPanic};
use die::*; use die::*;
@ -32,36 +36,51 @@ pub struct Configuration {
pub struct Dependencies { pub struct Dependencies {
pub panic_handler: Arc<PanicHandler>, 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")] #[cfg(feature = "ethcore-signer")]
pub fn start(conf: Configuration, deps: Dependencies) -> Option<SignerServer> { fn do_start(conf: Configuration, deps: Dependencies) -> SignerServer {
if !conf.enabled { let addr = format!("127.0.0.1:{}", conf.port).parse().unwrap_or_else(|_| {
return None; 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 = {
let start_result = signer::Server::start(addr); 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, &deps.client, &deps.miner).to_delegate());
server.start(addr)
};
match start_result { match start_result {
Err(signer::ServerError::IoError(err)) => die_with_io_error("Trusted Signer", err), Err(signer::ServerError::IoError(err)) => die_with_io_error("Trusted Signer", err),
Err(e) => die!("Trusted Signer: {:?}", e), Err(e) => die!("Trusted Signer: {:?}", e),
Ok(server) => { Ok(server) => {
deps.panic_handler.forward_from(&server); deps.panic_handler.forward_from(&server);
Some(server) server
}, },
} }
} }
#[cfg(not(feature = "ethcore-signer"))] #[cfg(not(feature = "ethcore-signer"))]
pub fn start(conf: Configuration) -> Option<SignerServer> { fn do_start(conf: Configuration) -> ! {
if !conf.enabled {
return None;
}
die!("Your Parity version has been compiled without Trusted Signer support.") die!("Your Parity version has been compiled without Trusted Signer support.")
} }

View File

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

View File

@ -33,10 +33,11 @@
//! ``` //! ```
//! extern crate ethcore_signer; //! extern crate ethcore_signer;
//! //!
//! use ethcore_signer::Server; //! use ethcore_signer::ServerBuilder;
//! //!
//! fn main() { //! fn main() {
//! let _server = Server::start("127.0.0.1:8084".parse().unwrap()); //! let builder = ServerBuilder::new();
//! let _server = builder.start("127.0.0.1:8084".parse().unwrap()).unwrap();
//! } //! }
//! ``` //! ```
@ -50,6 +51,7 @@ extern crate rustc_serialize;
extern crate ethcore_util as util; extern crate ethcore_util as util;
extern crate ethcore_rpc as rpc; extern crate ethcore_rpc as rpc;
extern crate jsonrpc_core;
extern crate ws; extern crate ws;
mod signing_queue; mod signing_queue;

View File

@ -19,11 +19,14 @@
use ws; use ws;
use std; use std;
use std::thread; use std::thread;
use std::default::Default;
use std::ops::Drop; use std::ops::Drop;
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::net::SocketAddr; use std::net::SocketAddr;
use util::panics::{PanicHandler, OnPanicListener, MayPanic}; use util::panics::{PanicHandler, OnPanicListener, MayPanic};
use jsonrpc_core::{IoHandler, IoDelegate};
mod session;
/// Signer startup error /// Signer startup error
#[derive(Debug)] #[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. /// `WebSockets` server implementation.
pub struct Server { pub struct Server {
handle: Option<thread::JoinHandle<ws::WebSocket<Factory>>>, handle: Option<thread::JoinHandle<ws::WebSocket<session::Factory>>>,
broadcaster: ws::Sender, broadcaster: ws::Sender,
panic_handler: Arc<PanicHandler>, panic_handler: Arc<PanicHandler>,
} }
@ -53,7 +87,7 @@ pub struct Server {
impl Server { impl Server {
/// Starts a new `WebSocket` server in separate thread. /// Starts a new `WebSocket` server in separate thread.
/// Returns a `Server` handle which closes the server when droped. /// 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 config = {
let mut config = ws::Settings::default(); let mut config = ws::Settings::default();
config.max_connections = 5; config.max_connections = 5;
@ -62,10 +96,7 @@ impl Server {
}; };
// Create WebSocket // Create WebSocket
let session_id = Arc::new(AtomicUsize::new(1)); let ws = try!(ws::Builder::new().with_settings(config).build(session::Factory::new(handler)));
let ws = try!(ws::Builder::new().with_settings(config).build(Factory {
session_id: session_id,
}));
let panic_handler = PanicHandler::new_in_arc(); let panic_handler = PanicHandler::new_in_arc();
let ph = panic_handler.clone(); let ph = panic_handler.clone();
@ -98,31 +129,3 @@ impl Drop for Server {
self.handle.take().unwrap().join().unwrap(); 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(),
}
}
}