2020-09-22 14:53:52 +02:00
|
|
|
// Copyright 2015-2020 Parity Technologies (UK) Ltd.
|
|
|
|
// This file is part of OpenEthereum.
|
2018-06-04 10:19:50 +02:00
|
|
|
|
2020-09-22 14:53:52 +02:00
|
|
|
// OpenEthereum is free software: you can redistribute it and/or modify
|
2018-06-04 10:19:50 +02:00
|
|
|
// 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.
|
|
|
|
|
2020-09-22 14:53:52 +02:00
|
|
|
// OpenEthereum is distributed in the hope that it will be useful,
|
2018-06-04 10:19:50 +02:00
|
|
|
// 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
|
2020-09-22 14:53:52 +02:00
|
|
|
// along with OpenEthereum. If not, see <http://www.gnu.org/licenses/>.
|
2018-06-04 10:19:50 +02:00
|
|
|
|
2016-09-20 12:19:07 +02:00
|
|
|
use std::{
|
|
|
|
collections::BTreeMap,
|
|
|
|
fmt::{Debug, Error as FmtError, Formatter},
|
|
|
|
io::{BufRead, BufReader},
|
|
|
|
sync::{
|
|
|
|
atomic::{AtomicUsize, Ordering},
|
2020-08-05 06:08:03 +02:00
|
|
|
Arc,
|
|
|
|
},
|
2016-09-20 12:19:07 +02:00
|
|
|
thread, time,
|
|
|
|
};
|
|
|
|
|
2017-08-31 11:35:41 +02:00
|
|
|
use hash::keccak;
|
2017-09-02 20:09:13 +02:00
|
|
|
use parking_lot::Mutex;
|
2016-09-20 12:19:07 +02:00
|
|
|
use std::{fs::File, path::PathBuf};
|
|
|
|
use url::Url;
|
|
|
|
|
2017-05-24 12:24:07 +02:00
|
|
|
use ws::ws::{
|
2016-11-02 17:14:05 +01:00
|
|
|
self, Error as WsError, ErrorKind as WsErrorKind, Handler, Handshake, Message, Request,
|
2016-12-13 12:17:01 +01:00
|
|
|
Result as WsResult, Sender,
|
2016-11-02 17:14:05 +01:00
|
|
|
};
|
2016-09-20 12:19:07 +02:00
|
|
|
|
2017-07-06 11:36:15 +02:00
|
|
|
use serde::de::DeserializeOwned;
|
2016-12-13 12:17:01 +01:00
|
|
|
use serde_json::{self as json, Error as JsonError, Value as JsonValue};
|
2016-09-20 12:19:07 +02:00
|
|
|
|
2017-10-05 12:35:01 +02:00
|
|
|
use futures::{done, oneshot, Canceled, Complete, Future};
|
2016-09-20 12:19:07 +02:00
|
|
|
|
2017-11-14 11:38:17 +01:00
|
|
|
use jsonrpc_core::{
|
2016-10-17 14:59:41 +02:00
|
|
|
request::MethodCall,
|
2016-12-15 19:31:26 +01:00
|
|
|
response::{Failure, Output, Success},
|
2017-11-14 11:38:17 +01:00
|
|
|
Error as JsonRpcError, Id, Params, Version,
|
2016-12-15 19:31:26 +01:00
|
|
|
};
|
2016-10-17 14:59:41 +02:00
|
|
|
|
2017-11-14 11:38:17 +01:00
|
|
|
use BoxFuture;
|
|
|
|
|
2016-09-20 12:19:07 +02:00
|
|
|
/// The actual websocket connection handler, passed into the
|
|
|
|
/// event loop of ws-rs
|
|
|
|
struct RpcHandler {
|
|
|
|
pending: Pending,
|
2016-10-17 14:59:41 +02:00
|
|
|
// Option is used here as temporary storage until connection
|
|
|
|
// is setup and the values are moved into the new `Rpc`
|
2016-09-20 12:19:07 +02:00
|
|
|
complete: Option<Complete<Result<Rpc, RpcError>>>,
|
|
|
|
auth_code: String,
|
|
|
|
out: Option<Sender>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl RpcHandler {
|
2016-11-02 15:55:03 +01:00
|
|
|
fn new(out: Sender, auth_code: String, complete: Complete<Result<Rpc, RpcError>>) -> Self {
|
2016-09-20 12:19:07 +02:00
|
|
|
RpcHandler {
|
|
|
|
out: Some(out),
|
|
|
|
auth_code: auth_code,
|
|
|
|
pending: Pending::new(),
|
|
|
|
complete: Some(complete),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Handler for RpcHandler {
|
2016-12-15 15:03:34 +01:00
|
|
|
fn build_request(&mut self, url: &Url) -> WsResult<Request> {
|
2016-09-20 12:19:07 +02:00
|
|
|
match Request::from_url(url) {
|
|
|
|
Ok(mut r) => {
|
2016-12-27 12:53:56 +01:00
|
|
|
let timestamp = time::UNIX_EPOCH
|
|
|
|
.elapsed()
|
2016-09-30 15:30:17 +02:00
|
|
|
.map_err(|err| WsError::new(WsErrorKind::Internal, format!("{}", err)))?;
|
|
|
|
let secs = timestamp.as_secs();
|
2017-08-31 11:35:41 +02:00
|
|
|
let hashed = keccak(format!("{}:{}", self.auth_code, secs));
|
2018-04-02 13:12:52 +02:00
|
|
|
let proto = format!("{:x}_{}", hashed, secs);
|
2016-09-20 12:19:07 +02:00
|
|
|
r.add_protocol(&proto);
|
|
|
|
Ok(r)
|
|
|
|
}
|
2016-11-02 17:14:05 +01:00
|
|
|
Err(e) => Err(WsError::new(WsErrorKind::Internal, format!("{}", e))),
|
2020-08-05 06:08:03 +02:00
|
|
|
}
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
2016-12-15 15:03:34 +01:00
|
|
|
fn on_error(&mut self, err: WsError) {
|
2016-09-30 15:30:17 +02:00
|
|
|
match self.complete.take() {
|
2017-03-22 07:02:14 +01:00
|
|
|
Some(c) => match c.send(Err(RpcError::WsError(err))) {
|
|
|
|
Ok(_) => {}
|
|
|
|
Err(_) => warn!(target: "rpc-client", "Unable to notify about error."),
|
|
|
|
},
|
|
|
|
None => warn!(target: "rpc-client", "unexpected error: {}", err),
|
2020-08-05 06:08:03 +02:00
|
|
|
}
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
2016-12-15 15:03:34 +01:00
|
|
|
fn on_open(&mut self, _: Handshake) -> WsResult<()> {
|
2016-09-30 15:30:17 +02:00
|
|
|
match (self.complete.take(), self.out.take()) {
|
|
|
|
(Some(c), Some(out)) => {
|
2017-03-22 07:02:14 +01:00
|
|
|
let res = c.send(Ok(Rpc {
|
2016-09-30 15:30:17 +02:00
|
|
|
out: out,
|
|
|
|
counter: AtomicUsize::new(0),
|
|
|
|
pending: self.pending.clone(),
|
|
|
|
}));
|
2017-03-22 07:02:14 +01:00
|
|
|
if let Err(_) = res {
|
|
|
|
warn!(target: "rpc-client", "Unable to open a connection.")
|
|
|
|
}
|
2016-09-30 15:30:17 +02:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
_ => {
|
2016-11-02 17:14:05 +01:00
|
|
|
let msg = format!("on_open called twice");
|
|
|
|
Err(WsError::new(WsErrorKind::Internal, msg))
|
2020-08-05 06:08:03 +02:00
|
|
|
}
|
2016-09-30 15:30:17 +02:00
|
|
|
}
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
2016-12-15 15:03:34 +01:00
|
|
|
fn on_message(&mut self, msg: Message) -> WsResult<()> {
|
2016-10-17 14:59:41 +02:00
|
|
|
let ret: Result<JsonValue, JsonRpcError>;
|
|
|
|
let response_id;
|
|
|
|
let string = &msg.to_string();
|
2016-12-15 19:31:26 +01:00
|
|
|
match json::from_str::<Output>(&string) {
|
|
|
|
Ok(Output::Success(Success {
|
|
|
|
result,
|
|
|
|
id: Id::Num(id),
|
|
|
|
..
|
|
|
|
})) => {
|
2016-10-17 14:59:41 +02:00
|
|
|
ret = Ok(result);
|
|
|
|
response_id = id as usize;
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
2016-12-15 19:31:26 +01:00
|
|
|
Ok(Output::Failure(Failure {
|
|
|
|
error,
|
|
|
|
id: Id::Num(id),
|
|
|
|
..
|
|
|
|
})) => {
|
2016-10-17 14:59:41 +02:00
|
|
|
ret = Err(error);
|
|
|
|
response_id = id as usize;
|
|
|
|
}
|
|
|
|
Err(e) => {
|
2016-11-02 17:14:05 +01:00
|
|
|
warn!(
|
|
|
|
target: "rpc-client",
|
|
|
|
"recieved invalid message: {}\n {:?}",
|
|
|
|
string,
|
|
|
|
e
|
|
|
|
);
|
2016-10-17 14:59:41 +02:00
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
_ => {
|
2016-11-02 17:14:05 +01:00
|
|
|
warn!(
|
|
|
|
target: "rpc-client",
|
|
|
|
"recieved invalid message: {}",
|
|
|
|
string
|
|
|
|
);
|
2016-10-17 14:59:41 +02:00
|
|
|
return Ok(());
|
2020-08-05 06:08:03 +02:00
|
|
|
}
|
2016-10-17 14:59:41 +02:00
|
|
|
}
|
2020-08-05 06:08:03 +02:00
|
|
|
|
2016-10-17 14:59:41 +02:00
|
|
|
match self.pending.remove(response_id) {
|
2017-03-22 07:02:14 +01:00
|
|
|
Some(c) => {
|
|
|
|
if let Err(_) = c.send(ret.map_err(|err| RpcError::JsonRpc(err))) {
|
|
|
|
warn!(target: "rpc-client", "Unable to send response.")
|
|
|
|
}
|
2020-08-05 06:08:03 +02:00
|
|
|
}
|
2016-11-02 17:14:05 +01:00
|
|
|
None => warn!(
|
|
|
|
target: "rpc-client",
|
|
|
|
"warning: unexpected id: {}",
|
|
|
|
response_id
|
|
|
|
),
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
|
|
|
Ok(())
|
2016-12-15 15:03:34 +01:00
|
|
|
}
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Keeping track of issued requests to be matched up with responses
|
|
|
|
#[derive(Clone)]
|
2016-11-02 17:14:05 +01:00
|
|
|
struct Pending(Arc<Mutex<BTreeMap<usize, Complete<Result<JsonValue, RpcError>>>>>);
|
2016-09-20 12:19:07 +02:00
|
|
|
|
|
|
|
impl Pending {
|
|
|
|
fn new() -> Self {
|
|
|
|
Pending(Arc::new(Mutex::new(BTreeMap::new())))
|
|
|
|
}
|
|
|
|
fn insert(&mut self, k: usize, v: Complete<Result<JsonValue, RpcError>>) {
|
2016-10-17 15:06:45 +02:00
|
|
|
self.0.lock().insert(k, v);
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
2016-11-02 17:14:05 +01:00
|
|
|
fn remove(&mut self, k: usize) -> Option<Complete<Result<JsonValue, RpcError>>> {
|
2016-10-17 15:06:45 +02:00
|
|
|
self.0.lock().remove(&k)
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_authcode(path: &PathBuf) -> Result<String, RpcError> {
|
2016-12-13 12:17:01 +01:00
|
|
|
if let Ok(fd) = File::open(path) {
|
|
|
|
if let Some(Ok(line)) = BufReader::new(fd).lines().next() {
|
|
|
|
let mut parts = line.split(';');
|
|
|
|
let token = parts.next();
|
2020-08-05 06:08:03 +02:00
|
|
|
|
2016-12-13 12:17:01 +01:00
|
|
|
if let Some(code) = token {
|
|
|
|
return Ok(code.into());
|
|
|
|
}
|
|
|
|
}
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
2016-12-13 12:17:01 +01:00
|
|
|
Err(RpcError::NoAuthCode)
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// The handle to the connection
|
|
|
|
pub struct Rpc {
|
|
|
|
out: Sender,
|
|
|
|
counter: AtomicUsize,
|
|
|
|
pending: Pending,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Rpc {
|
|
|
|
/// Blocking, returns a new initialized connection or RpcError
|
|
|
|
pub fn new(url: &str, authpath: &PathBuf) -> Result<Self, RpcError> {
|
2016-12-27 12:53:56 +01:00
|
|
|
let rpc = Self::connect(url, authpath).map(|rpc| rpc).wait()?;
|
2016-09-20 12:19:07 +02:00
|
|
|
rpc
|
|
|
|
}
|
2020-08-05 06:08:03 +02:00
|
|
|
|
2016-09-20 12:19:07 +02:00
|
|
|
/// Non-blocking, returns a future
|
2016-11-02 15:55:03 +01:00
|
|
|
pub fn connect(url: &str, authpath: &PathBuf) -> BoxFuture<Result<Self, RpcError>, Canceled> {
|
2016-09-20 12:19:07 +02:00
|
|
|
let (c, p) = oneshot::<Result<Self, RpcError>>();
|
|
|
|
match get_authcode(authpath) {
|
2017-10-05 12:35:01 +02:00
|
|
|
Err(e) => return Box::new(done(Ok(Err(e)))),
|
2016-09-20 12:19:07 +02:00
|
|
|
Ok(code) => {
|
|
|
|
let url = String::from(url);
|
2016-11-02 17:14:05 +01:00
|
|
|
// The ws::connect takes a FnMut closure, which means c cannot
|
|
|
|
// be moved into it, since it's consumed on complete.
|
2016-10-06 12:07:09 +02:00
|
|
|
// Therefore we wrap it in an option and pick it out once.
|
2016-09-30 15:30:17 +02:00
|
|
|
let mut once = Some(c);
|
2016-09-20 12:19:07 +02:00
|
|
|
thread::spawn(move || {
|
2016-09-30 15:30:17 +02:00
|
|
|
let conn = ws::connect(url, |out| {
|
2016-10-06 12:07:09 +02:00
|
|
|
// this will panic if the closure is called twice,
|
|
|
|
// which it should never be.
|
2016-11-02 17:14:05 +01:00
|
|
|
let c = once.take().expect("connection closure called only once");
|
2016-09-20 12:19:07 +02:00
|
|
|
RpcHandler::new(out, code.clone(), c)
|
2016-09-30 15:30:17 +02:00
|
|
|
});
|
|
|
|
match conn {
|
2016-09-20 12:19:07 +02:00
|
|
|
Err(err) => {
|
2016-09-30 15:30:17 +02:00
|
|
|
// since ws::connect is only called once, it cannot
|
|
|
|
// both fail and succeed.
|
2016-11-02 17:14:05 +01:00
|
|
|
let c = once.take().expect("connection closure called only once");
|
2017-03-22 07:02:14 +01:00
|
|
|
let _ = c.send(Err(RpcError::WsError(err)));
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
|
|
|
// c will complete on the `on_open` event in the Handler
|
|
|
|
_ => (),
|
|
|
|
}
|
|
|
|
});
|
2017-10-05 12:35:01 +02:00
|
|
|
Box::new(p)
|
2020-08-05 06:08:03 +02:00
|
|
|
}
|
|
|
|
}
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
2020-08-05 06:08:03 +02:00
|
|
|
|
2016-09-20 12:19:07 +02:00
|
|
|
/// Non-blocking, returns a future of the request response
|
2016-11-02 15:55:03 +01:00
|
|
|
pub fn request<T>(
|
|
|
|
&mut self,
|
|
|
|
method: &'static str,
|
|
|
|
params: Vec<JsonValue>,
|
|
|
|
) -> BoxFuture<Result<T, RpcError>, Canceled>
|
2017-07-06 11:36:15 +02:00
|
|
|
where
|
|
|
|
T: DeserializeOwned + Send + Sized,
|
|
|
|
{
|
2016-09-20 12:19:07 +02:00
|
|
|
let (c, p) = oneshot::<Result<JsonValue, RpcError>>();
|
2020-08-05 06:08:03 +02:00
|
|
|
|
2016-09-20 12:19:07 +02:00
|
|
|
let id = self.counter.fetch_add(1, Ordering::Relaxed);
|
|
|
|
self.pending.insert(id, c);
|
2020-08-05 06:08:03 +02:00
|
|
|
|
2016-10-17 14:59:41 +02:00
|
|
|
let request = MethodCall {
|
2017-01-18 12:54:35 +01:00
|
|
|
jsonrpc: Some(Version::V2),
|
2016-10-17 14:59:41 +02:00
|
|
|
method: method.to_owned(),
|
2018-10-22 09:40:50 +02:00
|
|
|
params: Params::Array(params),
|
2016-10-17 14:59:41 +02:00
|
|
|
id: Id::Num(id as u64),
|
|
|
|
};
|
2020-08-05 06:08:03 +02:00
|
|
|
|
2016-11-02 17:14:05 +01:00
|
|
|
let serialized = json::to_string(&request).expect("request is serializable");
|
2016-09-20 12:19:07 +02:00
|
|
|
let _ = self.out.send(serialized);
|
2020-08-05 06:08:03 +02:00
|
|
|
|
2017-10-05 12:35:01 +02:00
|
|
|
Box::new(p.map(|result| match result {
|
2016-09-20 12:19:07 +02:00
|
|
|
Ok(json) => {
|
2016-12-27 12:53:56 +01:00
|
|
|
let t: T = json::from_value(json)?;
|
2016-09-20 12:19:07 +02:00
|
|
|
Ok(t)
|
|
|
|
}
|
|
|
|
Err(err) => Err(err),
|
2017-10-05 12:35:01 +02:00
|
|
|
}))
|
2016-09-20 12:19:07 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub enum RpcError {
|
|
|
|
WrongVersion(String),
|
|
|
|
ParseError(JsonError),
|
|
|
|
MalformedResponse(String),
|
2016-10-17 14:59:41 +02:00
|
|
|
JsonRpc(JsonRpcError),
|
2016-09-20 12:19:07 +02:00
|
|
|
WsError(WsError),
|
|
|
|
Canceled(Canceled),
|
|
|
|
UnexpectedId,
|
|
|
|
NoAuthCode,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Debug for RpcError {
|
|
|
|
fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
|
2016-10-17 14:59:41 +02:00
|
|
|
match *self {
|
2016-09-20 12:19:07 +02:00
|
|
|
RpcError::WrongVersion(ref s) => write!(f, "Expected version 2.0, got {}", s),
|
|
|
|
RpcError::ParseError(ref err) => write!(f, "ParseError: {}", err),
|
|
|
|
RpcError::MalformedResponse(ref s) => write!(f, "Malformed response: {}", s),
|
2016-10-17 14:59:41 +02:00
|
|
|
RpcError::JsonRpc(ref json) => write!(f, "JsonRpc error: {:?}", json),
|
2016-09-20 12:19:07 +02:00
|
|
|
RpcError::WsError(ref s) => write!(f, "Websocket error: {}", s),
|
|
|
|
RpcError::Canceled(ref s) => write!(f, "Futures error: {:?}", s),
|
|
|
|
RpcError::UnexpectedId => write!(f, "Unexpected response id"),
|
|
|
|
RpcError::NoAuthCode => write!(f, "No authcodes available"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<JsonError> for RpcError {
|
|
|
|
fn from(err: JsonError) -> RpcError {
|
|
|
|
RpcError::ParseError(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<WsError> for RpcError {
|
|
|
|
fn from(err: WsError) -> RpcError {
|
|
|
|
RpcError::WsError(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<Canceled> for RpcError {
|
|
|
|
fn from(err: Canceled) -> RpcError {
|
|
|
|
RpcError::Canceled(err)
|
|
|
|
}
|
|
|
|
}
|