Newer
Older
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
// Copyright 2019 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
use super::{Error, Id, JsonValue, Version};
use alloc::{
fmt,
string::{String, ToString as _},
vec,
vec::Vec,
};
use core::convert::TryFrom;
use serde::{Deserialize, Serialize};
/// JSONRPC response.
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
#[serde(untagged)]
pub enum Response {
/// Single response
Single(Output),
/// Response to batch request (batch of responses)
Batch(Vec<Output>),
/// Notification to an active subscription.
Notif(SubscriptionNotif),
}
impl fmt::Display for Response {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", serde_json::to_string(self).expect("Response valid JSON; qed"))
}
}
/// Successful response
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Success {
/// Protocol version
pub jsonrpc: Version,
/// Result
pub result: JsonValue,
/// Correlation id
pub id: Id,
}
/// Unsuccessful response
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Failure {
/// Protocol version
pub jsonrpc: Version,
/// Error
pub error: Error,
/// Correlation id
pub id: Id,
}
/// Represents output - failure or success
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
#[serde(untagged)]
pub enum Output {
/// Success
Success(Success),
/// Failure
Failure(Failure),
}
/// Server notification about something the client is subscribed to.
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SubscriptionNotif {
/// Protocol version
pub jsonrpc: Version,
/// A String containing the name of the method that was used for the subscription.
pub method: String,
/// Parameters of the notification.
pub params: SubscriptionNotifParams,
}
/// Field of a [`SubscriptionNotif`].
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SubscriptionNotifParams {
/// Subscription id, as communicated during the subscription.
pub subscription: SubscriptionId,
/// Actual data that the server wants to communicate to us.
pub result: JsonValue,
}
/// Id of a subscription, communicated by the server.
#[derive(Debug, PartialEq, Clone, Hash, Eq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
#[serde(untagged)]
pub enum SubscriptionId {
/// Numeric id
Num(u64),
/// String id
Str(String),
}
impl Output {
/// Creates new output given `Result`, `Id` and `Version`.
pub fn from(result: Result<JsonValue, Error>, id: Id, jsonrpc: Version) -> Self {
match result {
Ok(result) => Output::Success(Success { jsonrpc, result, id }),
Err(error) => Output::Failure(Failure { jsonrpc, error, id }),
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
}
}
/// Get the jsonrpc protocol version.
pub fn version(&self) -> Version {
match *self {
Output::Success(ref s) => s.jsonrpc,
Output::Failure(ref f) => f.jsonrpc,
}
}
/// Get the correlation id.
pub fn id(&self) -> &Id {
match *self {
Output::Success(ref s) => &s.id,
Output::Failure(ref f) => &f.id,
}
}
}
impl TryFrom<Output> for JsonValue {
type Error = Error;
fn try_from(output: Output) -> Result<JsonValue, Error> {
match output {
Output::Success(s) => Ok(s.result),
Output::Failure(f) => Err(f.error),
}
}
}
impl Response {
/// Creates new `Response` with given error and `Version`
pub fn from(error: impl Into<Error>, jsonrpc: Version) -> Self {
Failure { id: Id::Null, jsonrpc, error: error.into() }.into()
}
/// Deserialize `Response` from given JSON string.
///
/// This method will handle an empty string as empty batch response.
pub fn from_json(s: &str) -> Result<Self, serde_json::Error> {
if s.is_empty() {
Ok(Response::Batch(vec![]))
} else {
serde_json::from_str(s)
}
}
}
impl From<Failure> for Response {
fn from(failure: Failure) -> Self {
Response::Single(Output::Failure(failure))
}
}
impl From<Success> for Response {
fn from(success: Success) -> Self {
Response::Single(Output::Success(success))
}
}
impl SubscriptionId {
/// Turns the subscription ID into a string.
pub fn into_string(self) -> String {
match self {
SubscriptionId::Num(n) => n.to_string(),
SubscriptionId::Str(s) => s,
}
}
}
#[cfg(test)]
mod tests {
use super::{Error, Failure, Id, Output, Response, Success, Version};
use serde_json::Value;
#[test]
fn success_output_serialize() {
let so = Output::Success(Success { jsonrpc: Version::V2, result: Value::from(1), id: Id::Num(1) });
let serialized = serde_json::to_string(&so).unwrap();
assert_eq!(serialized, r#"{"jsonrpc":"2.0","result":1,"id":1}"#);
}
#[test]
fn success_output_deserialize() {
let dso = r#"{"jsonrpc":"2.0","result":1,"id":1}"#;
let deserialized: Output = serde_json::from_str(dso).unwrap();
assert_eq!(
deserialized,
Output::Success(Success { jsonrpc: Version::V2, result: Value::from(1), id: Id::Num(1) })
);
}
#[test]
fn failure_output_serialize() {
let fo = Output::Failure(Failure { jsonrpc: Version::V2, error: Error::parse_error(), id: Id::Num(1) });
let serialized = serde_json::to_string(&fo).unwrap();
assert_eq!(serialized, r#"{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error"},"id":1}"#);
}
#[test]
fn failure_output_deserialize() {
let dfo = r#"{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error"},"id":1}"#;
let deserialized: Output = serde_json::from_str(dfo).unwrap();
assert_eq!(
deserialized,
Output::Failure(Failure { jsonrpc: Version::V2, error: Error::parse_error(), id: Id::Num(1) })
);
}
#[test]
fn single_response_deserialize() {
let dsr = r#"{"jsonrpc":"2.0","result":1,"id":1}"#;
let deserialized: Response = serde_json::from_str(dsr).unwrap();
assert_eq!(
deserialized,
Response::Single(Output::Success(Success { jsonrpc: Version::V2, result: Value::from(1), id: Id::Num(1) }))
);
}
#[test]
fn batch_response_deserialize() {
let dbr = r#"[{"jsonrpc":"2.0","result":1,"id":1},{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error"},"id":1}]"#;
let deserialized: Response = serde_json::from_str(dbr).unwrap();
assert_eq!(
deserialized,
Response::Batch(vec![
Output::Success(Success { jsonrpc: Version::V2, result: Value::from(1), id: Id::Num(1) }),
Output::Failure(Failure { jsonrpc: Version::V2, error: Error::parse_error(), id: Id::Num(1) })
])
);
}
#[test]
fn handle_incorrect_responses() {
let dsr = r#"
{
"id": 2,
"jsonrpc": "2.0",
"result": "0x62d3776be72cc7fa62cad6fe8ed873d9bc7ca2ee576e400d987419a3f21079d5",
"error": {
"message": "VM Exception while processing transaction: revert",
"code": -32000,
"data": {}
}
}"#;
let deserialized: Result<Response, _> = serde_json::from_str(dsr);
assert!(deserialized.is_err(), "Expected error when deserializing invalid payload.");
}
#[test]
fn should_parse_empty_response_as_batch() {
let dsr = r#""#;
let deserialized1: Result<Response, _> = serde_json::from_str(dsr);
let deserialized2: Result<Response, _> = Response::from_json(dsr);
assert!(deserialized1.is_err(), "Empty string is not valid JSON, so we should get an error.");
assert_eq!(deserialized2.unwrap(), Response::Batch(vec![]));
}
}