1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use std::os::unix::net::UnixStream;
use std::path::{Path, PathBuf};
use std::time::Duration;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Deserializer, to_writer};
use super::{Request, Response};
use crate::error::Error;
#[derive(Debug)]
pub struct Client {
sockpath: PathBuf,
timeout: Option<Duration>,
}
impl Client {
pub fn new<P: AsRef<Path>>(sockpath: P) -> Client {
Client {
sockpath: sockpath.as_ref().to_path_buf(),
timeout: None,
}
}
pub fn set_timeout(&mut self, timeout: Option<Duration>) {
self.timeout = timeout;
}
pub fn send_request<S: Serialize, D: DeserializeOwned>(&self, method: &str, params: S) -> Result<Response<D>, Error> {
let mut stream = UnixStream::connect(&self.sockpath)?;
stream.set_read_timeout(self.timeout)?;
stream.set_write_timeout(self.timeout)?;
to_writer(&mut stream, &Request {
method,
params,
id: 0,
jsonrpc: "2.0",
})?;
let response: Response<D> = Deserializer::from_reader(&mut stream)
.into_iter()
.next()
.map_or(Err(Error::NoErrorOrResult), |res| Ok(res?))?;
if response.jsonrpc.as_ref().map_or(false, |version| version != "2.0") {
return Err(Error::VersionMismatch);
}
if response.id != 0 {
return Err(Error::NonceMismatch);
}
Ok(response)
}
}