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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
use crate::module::RpcModule;
use crate::response;
use crate::AccessControl;
use crate::TEN_MB_SIZE_BYTES;
use anyhow::anyhow;
use futures_channel::mpsc;
use futures_util::stream::StreamExt;
use hyper::{
server::{conn::AddrIncoming, Builder as HyperBuilder},
service::{make_service_fn, service_fn},
Error as HyperError,
};
use jsonrpsee_types::error::{Error, GenericTransportError, RpcError};
use jsonrpsee_types::v2::request::{JsonRpcInvalidRequest, JsonRpcRequest};
use jsonrpsee_types::v2::{error::JsonRpcErrorCode, params::RpcParams};
use jsonrpsee_utils::{hyper_helpers::read_response_to_body, server::send_error};
use serde::Serialize;
use socket2::{Domain, Socket, Type};
use std::{
net::{SocketAddr, TcpListener},
sync::Arc,
};
pub struct Builder {
access_control: AccessControl,
max_request_body_size: u32,
keep_alive: bool,
}
impl Builder {
pub fn max_request_body_size(mut self, size: u32) -> Self {
self.max_request_body_size = size;
self
}
pub fn set_access_control(mut self, acl: AccessControl) -> Self {
self.access_control = acl;
self
}
pub fn keep_alive(mut self, keep_alive: bool) -> Self {
self.keep_alive = keep_alive;
self
}
pub fn build(self, addr: SocketAddr) -> anyhow::Result<Server> {
let domain = Domain::for_address(addr);
let socket = Socket::new(domain, Type::STREAM, None)?;
socket.set_nodelay(true)?;
socket.set_reuse_address(true)?;
socket.set_nonblocking(true)?;
socket.set_keepalive(self.keep_alive)?;
let address = addr.into();
socket.bind(&address)?;
socket.listen(128)?;
let listener: TcpListener = socket.into();
let local_addr = listener.local_addr().ok();
let listener = hyper::Server::from_tcp(listener)?;
Ok(Server {
listener,
local_addr,
root: RpcModule::new(),
access_control: self.access_control,
max_request_body_size: self.max_request_body_size,
})
}
}
impl Default for Builder {
fn default() -> Self {
Self { max_request_body_size: TEN_MB_SIZE_BYTES, access_control: AccessControl::default(), keep_alive: true }
}
}
pub struct Server {
listener: HyperBuilder<AddrIncoming>,
local_addr: Option<SocketAddr>,
root: RpcModule,
max_request_body_size: u32,
access_control: AccessControl,
}
impl Server {
pub fn register_method<F, R>(&mut self, method_name: &'static str, callback: F) -> Result<(), Error>
where
R: Serialize,
F: Fn(RpcParams) -> Result<R, RpcError> + Send + Sync + 'static,
{
self.root.register_method(method_name, callback)
}
pub fn register_module(&mut self, module: RpcModule) -> Result<(), Error> {
self.root.merge(module)
}
pub fn local_addr(&self) -> anyhow::Result<SocketAddr> {
self.local_addr.ok_or_else(|| anyhow!("Local address not found"))
}
pub async fn start(self) -> anyhow::Result<()> {
let methods = Arc::new(self.root.into_methods());
let max_request_body_size = self.max_request_body_size;
let access_control = self.access_control;
let make_service = make_service_fn(move |_| {
let methods = methods.clone();
let access_control = access_control.clone();
async move {
Ok::<_, HyperError>(service_fn(move |request| {
let methods = methods.clone();
let access_control = access_control.clone();
async move {
if let Err(e) = access_control_is_valid(&access_control, &request) {
return Ok::<_, HyperError>(e);
}
if let Err(e) = content_type_is_valid(&request) {
return Ok::<_, HyperError>(e);
}
let (parts, body) = request.into_parts();
let body = match read_response_to_body(&parts.headers, body, max_request_body_size).await {
Ok(body) => body,
Err(GenericTransportError::TooLarge) => {
return Ok::<_, HyperError>(response::too_large("The request was too large"))
}
Err(GenericTransportError::Inner(e)) => {
return Ok::<_, HyperError>(response::internal_error(e.to_string()))
}
};
let (tx, mut rx) = mpsc::unbounded();
match serde_json::from_slice::<JsonRpcRequest>(&body) {
Ok(req) => {
log::debug!("recv: {:?}", req);
let params = RpcParams::new(req.params.map(|params| params.get()));
if let Some(method) = methods.get(&*req.method) {
if let Err(err) = (method)(req.id, params, &tx, 0) {
log::error!("method_call: {} failed: {:?}", req.method, err);
}
} else {
send_error(req.id, &tx, JsonRpcErrorCode::MethodNotFound.into());
}
}
Err(_e) => {
let (id, code) = match serde_json::from_slice::<JsonRpcInvalidRequest>(&body) {
Ok(req) => (req.id, JsonRpcErrorCode::InvalidRequest),
Err(_) => (None, JsonRpcErrorCode::ParseError),
};
send_error(id, &tx, code.into());
}
};
let response = rx.next().await.expect("Sender is still alive managed by us above; qed");
log::debug!("send: {:?}", response);
Ok::<_, HyperError>(response::ok_response(response))
}
}))
}
});
let server = self.listener.serve(make_service);
server.await.map_err(Into::into)
}
}
fn access_control_is_valid(
access_control: &AccessControl,
request: &hyper::Request<hyper::Body>,
) -> Result<(), hyper::Response<hyper::Body>> {
if access_control.deny_host(request) {
return Err(response::host_not_allowed());
}
if access_control.deny_cors_origin(request) {
return Err(response::invalid_allow_origin());
}
if access_control.deny_cors_header(request) {
return Err(response::invalid_allow_headers());
}
Ok(())
}
fn content_type_is_valid(request: &hyper::Request<hyper::Body>) -> Result<(), hyper::Response<hyper::Body>> {
match *request.method() {
hyper::Method::POST if is_json(request.headers().get("content-type")) => Ok(()),
_ => Err(response::method_not_allowed()),
}
}
fn is_json(content_type: Option<&hyper::header::HeaderValue>) -> bool {
match content_type.and_then(|val| val.to_str().ok()) {
Some(ref content)
if content.eq_ignore_ascii_case("application/json")
|| content.eq_ignore_ascii_case("application/json; charset=utf-8")
|| content.eq_ignore_ascii_case("application/json;charset=utf-8") =>
{
true
}
_ => false,
}
}