smoldot 1.1.0

Primitives to build a client for Substrate-based blockchains
Documentation
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
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
// Smoldot
// Copyright (C) 2019-2022  Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0

// This program 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.

// This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.

//! Parse JSON-RPC method calls and notifications, and build responses messages.

use alloc::{borrow::Cow, string::String};

/// Parses a JSON-encoded RPC method call or notification.
pub fn parse_request(request_json: &'_ str) -> Result<Request<'_>, ParseError> {
    let serde_request: SerdeRequest = serde_json::from_str(request_json).map_err(ParseError)?;

    if let Some(id) = &serde_request.id {
        // Because of https://github.com/serde-rs/json/issues/742, we can't use ̀`&str`.
        #[allow(dead_code)] // Necessary to silence warnings about unused fields.
        #[derive(serde::Deserialize)]
        #[serde(deny_unknown_fields)]
        #[serde(untagged)]
        enum SerdeId<'a> {
            Num(u64),
            Str(Cow<'a, str>),
        }

        if let Err(err) = serde_json::from_str::<SerdeId>(id.get()) {
            return Err(ParseError(err));
        }
    }

    Ok(Request {
        id_json: serde_request.id.map(|v| v.get()),
        method: serde_request.method,
        params_json: serde_request.params.map(|p| p.get()),
    })
}

/// Parses a JSON-encoded RPC response.
pub fn parse_response(response_json: &'_ str) -> Result<Response<'_>, ParseError> {
    let error = match serde_json::from_str::<SerdeSuccess>(response_json) {
        Err(err) => err,
        Ok(SerdeSuccess {
            jsonrpc: _,
            id,
            result,
        }) => {
            // Because of https://github.com/serde-rs/json/issues/742, we can't use ̀`&str`.
            #[allow(dead_code)] // Necessary to silence warnings about unused fields.
            #[derive(serde::Deserialize)]
            #[serde(deny_unknown_fields)]
            #[serde(untagged)]
            enum SerdeId<'a> {
                Num(u64),
                Str(Cow<'a, str>),
            }

            if let Err(err) = serde_json::from_str::<SerdeId>(id.get()) {
                return Err(ParseError(err));
            }

            return Ok(Response::Success {
                id_json: id.get(),
                result_json: result.get(),
            });
        }
    };

    match serde_json::from_str::<SerdeFailure>(response_json) {
        Ok(SerdeFailure {
            jsonrpc: _,
            id,
            error:
                SerdeError {
                    code,
                    message,
                    data,
                },
        }) if id.get() != "null" => {
            // Because of https://github.com/serde-rs/json/issues/742, we can't use ̀`&str`.
            #[allow(dead_code)] // Necessary to silence warnings about unused fields.
            #[derive(serde::Deserialize)]
            #[serde(deny_unknown_fields)]
            #[serde(untagged)]
            enum SerdeId<'a> {
                Num(u64),
                Str(Cow<'a, str>),
            }

            if let Err(err) = serde_json::from_str::<SerdeId>(id.get()) {
                return Err(ParseError(err));
            }

            Ok(Response::Error {
                id_json: id.get(),
                error_code: code.to_num(),
                error_message: message,
                error_data_json: data.map(|d| d.get()),
            })
        }
        Ok(SerdeFailure {
            jsonrpc: _,
            id: _,
            error:
                SerdeError {
                    code,
                    message,
                    data,
                },
        }) => Ok(Response::ParseError {
            error_code: code.to_num(),
            error_message: message,
            error_data_json: data.map(|d| d.get()),
        }),
        Err(_) => Err(ParseError(error)),
    }
}

/// Builds a JSON request.
///
/// `method` must be the name of the method to request. `params_json` must be the JSON-formatted
/// object or array containing the parameters of the request.
///
/// # Panic
///
/// Panics if the [`Request::id_json`] or [`Request::params_json`] isn't valid JSON.
///
pub fn build_request(request: &Request) -> String {
    serde_json::to_string(&SerdeRequest {
        jsonrpc: SerdeVersion::V2,
        id: request.id_json.map(|id| serde_json::from_str(id).unwrap()),
        method: request.method,
        params: request
            .params_json
            .map(|p| serde_json::from_str(p).unwrap()),
    })
    .unwrap()
}

/// Decoded JSON-RPC request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Request<'a> {
    /// JSON-formatted identifier of the request. `None` for notifications.
    pub id_json: Option<&'a str>,
    /// Name of the method that is being called.
    pub method: &'a str,
    /// JSON-formatted list of parameters. `None` iff the `params` field is missing.
    pub params_json: Option<&'a str>,
}

/// Decoded JSON-RPC response.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Response<'a> {
    /// Successful request.
    Success {
        /// JSON-formatted identifier of the request the response corresponds to.
        id_json: &'a str,
        /// JSON-formatted result.
        result_json: &'a str,
    },

    /// Request has failed.
    Error {
        /// JSON-formatted identifier of the request the response corresponds to.
        id_json: &'a str,
        /// Integer indicating the nature of the error.
        ///
        /// See [the JSON-RPC specification](https://www.jsonrpc.org/specification#error_object)
        /// for reference.
        error_code: i64,
        /// Short description of the error.
        error_message: &'a str,
        /// JSON-formatted data associated with the response. `None` if omitted.
        error_data_json: Option<&'a str>,
    },

    /// The JSON-RPC server indicates that it couldn't parse a request.
    ParseError {
        /// Integer indicating the nature of the error.
        ///
        /// See [the JSON-RPC specification](https://www.jsonrpc.org/specification#error_object)
        /// for reference.
        error_code: i64,
        /// Short description of the error.
        error_message: &'a str,
        /// JSON-formatted data associated with the response. `None` if omitted.
        error_data_json: Option<&'a str>,
    },
}

impl<'a> Response<'a> {
    /// Utility function that returns `Some` if `self` is [`Response::Success`]. If `Some` is
    /// returned, it contains in order the JSON-formatted identifier of the request and the
    /// JSON-formatted content of the `result` field.
    pub fn into_success(self) -> Option<(&'a str, &'a str)> {
        if let Response::Success {
            id_json,
            result_json,
        } = self
        {
            Some((id_json, result_json))
        } else {
            None
        }
    }
}

/// Error while parsing a request.
#[derive(Debug, derive_more::Display, derive_more::Error)]
pub struct ParseError(serde_json::Error);

/// Builds a JSON response.
///
/// `id_json` must be the JSON-formatted identifier of the request, found in [`Request::id_json`].
/// `result_json` must be the JSON-formatted result of the request.
///
/// # Example
///
/// ```
/// # use smoldot::json_rpc::parse;
/// let result_json = parse::build_success_response("27", r#"[1, 2, {"foo":"bar"}]"#);
///
/// // Note that the output is guaranteed to be stable.
/// assert_eq!(result_json, r#"{"jsonrpc":"2.0","id":27,"result":[1, 2, {"foo":"bar"}]}"#);
/// ```
///
/// # Panic
///
/// Panics if `id_json` or `result_json` aren't valid JSON.
///
pub fn build_success_response(id_json: &str, result_json: &str) -> String {
    serde_json::to_string(&SerdeSuccess {
        jsonrpc: SerdeVersion::V2,
        id: serde_json::from_str(id_json).expect("invalid id_json"),
        result: serde_json::from_str(result_json).expect("invalid result_json"),
    })
    .unwrap()
}

/// Builds a JSON response.
///
/// `id_json` must be the JSON-formatted identifier of the request, found in [`Request::id_json`].
///
/// # Example
///
/// ```
/// # use smoldot::json_rpc::parse;
/// let _result_json = parse::build_error_response("43", parse::ErrorResponse::ParseError, None);
/// ```
///
/// # Panic
///
/// Panics if `id_json` or `data_json` aren't valid JSON.
/// Panics if the code in the [`ErrorResponse`] doesn't respect the rules documented under
/// certain variants.
///
pub fn build_error_response(
    id_json: &str,
    error: ErrorResponse,
    data_json: Option<&str>,
) -> String {
    let (code, message) = match error {
        ErrorResponse::ParseError => (
            SerdeErrorCode::ParseError,
            "Invalid JSON was received by the server.",
        ),
        ErrorResponse::InvalidRequest => (
            SerdeErrorCode::InvalidRequest,
            "The JSON sent is not a valid Request object.",
        ),
        ErrorResponse::MethodNotFound => (
            SerdeErrorCode::MethodNotFound,
            "The method does not exist / is not available.",
        ),
        ErrorResponse::InvalidParams(msg) => (
            SerdeErrorCode::InvalidParams,
            msg.unwrap_or("Invalid method parameter(s)."),
        ),
        ErrorResponse::InternalError => (SerdeErrorCode::InternalError, "Internal JSON-RPC error."),
        ErrorResponse::ServerError(n, msg) => {
            assert!((-32099..=-32000).contains(&n));
            (SerdeErrorCode::ServerError(n), msg)
        }
        ErrorResponse::ApplicationDefined(n, msg) => {
            assert!(!(-32768..=-32000).contains(&n));
            (SerdeErrorCode::MethodError(n), msg)
        }
    };

    serde_json::to_string(&SerdeFailure {
        jsonrpc: SerdeVersion::V2,
        id: serde_json::from_str(id_json).expect("invalid id_json"),
        error: SerdeError {
            code,
            message,
            data: data_json.map(|d| serde_json::from_str(d).expect("invalid result_json")),
        },
    })
    .unwrap()
}

/// Error that can be reported to the JSON-RPC client.
#[derive(Debug)]
pub enum ErrorResponse<'a> {
    /// Invalid JSON was received by the server.
    ParseError,

    /// The JSON sent is not a valid Request object.
    InvalidRequest,

    /// The method does not exist / is not available.
    MethodNotFound,

    /// Invalid method parameter(s).
    /// Optionally contains a custom message.
    InvalidParams(Option<&'a str>),

    /// Internal JSON-RPC error.
    InternalError,

    /// Other internal server error.
    /// Contains a more precise error code and a custom message.
    /// Error code must be in the range -32000 to -32099 included.
    ServerError(i64, &'a str),

    /// Method-specific error.
    /// Contains a more precise error code and a custom message.
    /// Error code must be outside of the range -32000 to -32700.
    ApplicationDefined(i64, &'a str),
}

/// Builds a JSON error response when a request couldn't be decoded.
///
/// # Example
///
/// ```
/// # use smoldot::json_rpc::parse;
/// let _result_json = parse::build_parse_error_response();
/// ```
///
/// # Panic
///
/// Panics if `id_json` or `data_json` aren't valid JSON.
/// Panics if the code in the [`ErrorResponse`] doesn't respect the rules documented under
/// certain variants.
///
pub fn build_parse_error_response() -> String {
    serde_json::to_string(&SerdeFailure {
        jsonrpc: SerdeVersion::V2,
        id: serde_json::from_str("null").unwrap(),
        error: SerdeError {
            code: SerdeErrorCode::ParseError,
            message: "Parse error",
            data: None,
        },
    })
    .unwrap()
}

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
struct SerdeRequest<'a> {
    jsonrpc: SerdeVersion,
    #[serde(borrow, skip_serializing_if = "Option::is_none")]
    id: Option<&'a serde_json::value::RawValue>,
    #[serde(borrow)]
    method: &'a str,
    #[serde(borrow)]
    params: Option<&'a serde_json::value::RawValue>,
}

#[derive(Debug, PartialEq, Clone, Copy, Hash, Eq)]
enum SerdeVersion {
    V2,
}

impl serde::Serialize for SerdeVersion {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match *self {
            SerdeVersion::V2 => "2.0".serialize(serializer),
        }
    }
}

impl<'a> serde::Deserialize<'a> for SerdeVersion {
    fn deserialize<D>(deserializer: D) -> Result<SerdeVersion, D::Error>
    where
        D: serde::Deserializer<'a>,
    {
        let string = <&str>::deserialize(deserializer)?;
        if string != "2.0" {
            return Err(serde::de::Error::custom("unknown version"));
        }
        Ok(SerdeVersion::V2)
    }
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct SerdeSuccess<'a> {
    jsonrpc: SerdeVersion,
    #[serde(borrow)]
    id: &'a serde_json::value::RawValue,
    #[serde(borrow)]
    result: &'a serde_json::value::RawValue,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct SerdeFailure<'a> {
    jsonrpc: SerdeVersion,
    #[serde(borrow)]
    id: &'a serde_json::value::RawValue,
    #[serde(borrow)]
    error: SerdeError<'a>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct SerdeError<'a> {
    code: SerdeErrorCode,
    #[serde(borrow)]
    message: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    data: Option<&'a serde_json::value::RawValue>,
}

#[derive(Debug, PartialEq, Clone)]
enum SerdeErrorCode {
    ParseError,
    InvalidRequest,
    MethodNotFound,
    InvalidParams,
    InternalError,
    ServerError(i64),
    MethodError(i64),
}

impl SerdeErrorCode {
    fn to_num(&self) -> i64 {
        match *self {
            SerdeErrorCode::ParseError => -32700,
            SerdeErrorCode::InvalidRequest => -32600,
            SerdeErrorCode::MethodNotFound => -32601,
            SerdeErrorCode::InvalidParams => -32602,
            SerdeErrorCode::InternalError => -32603,
            SerdeErrorCode::ServerError(code) => code,
            SerdeErrorCode::MethodError(code) => code,
        }
    }
}

impl<'a> serde::Deserialize<'a> for SerdeErrorCode {
    fn deserialize<D>(deserializer: D) -> Result<SerdeErrorCode, D::Error>
    where
        D: serde::Deserializer<'a>,
    {
        let code: i64 = serde::Deserialize::deserialize(deserializer)?;

        Ok(match code {
            -32700 => SerdeErrorCode::ParseError,
            -32600 => SerdeErrorCode::InvalidRequest,
            -32601 => SerdeErrorCode::MethodNotFound,
            -32602 => SerdeErrorCode::InvalidParams,
            -32603 => SerdeErrorCode::InternalError,
            -32099..=-32000 => SerdeErrorCode::ServerError(code),
            code => SerdeErrorCode::MethodError(code),
        })
    }
}

impl serde::Serialize for SerdeErrorCode {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_i64(self.to_num())
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn parse_request_basic_works() {
        let request = super::parse_request(
            r#"{"jsonrpc":"2.0","id":5,"method":"foo","params":[5,true, "hello"]}"#,
        )
        .unwrap();
        assert_eq!(request.id_json.unwrap(), "5");
        assert_eq!(request.method, "foo");
        assert_eq!(request.params_json, Some("[5,true, \"hello\"]"));
    }

    #[test]
    fn parse_response_basic_works() {
        let (id, result) = super::parse_response(r#"{"jsonrpc":"2.0","id":5,"result":true}"#)
            .unwrap()
            .into_success()
            .unwrap();
        assert_eq!(id, "5");
        assert_eq!(result, "true");
    }

    #[test]
    fn parse_error_response() {
        let response = super::parse_response(r#"{"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": "1"}"#)
            .unwrap();

        let super::Response::Error {
            id_json,
            error_code,
            error_message,
            error_data_json,
        } = response
        else {
            panic!()
        };
        assert_eq!(id_json, "\"1\"");
        assert_eq!(error_code, -32601);
        assert_eq!(error_message, "Method not found");
        assert!(error_data_json.is_none());
    }

    #[test]
    fn parse_parse_error_response() {
        let response = super::parse_response(r#"{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}"#)
            .unwrap();

        let super::Response::ParseError {
            error_code,
            error_message,
            error_data_json,
        } = response
        else {
            panic!()
        };
        assert_eq!(error_code, -32600);
        assert_eq!(error_message, "Invalid Request");
        assert!(error_data_json.is_none());
    }

    #[test]
    fn parse_request_missing_id() {
        let request =
            super::parse_request(r#"{"jsonrpc":"2.0","method":"foo","params":[]}"#).unwrap();
        assert!(request.id_json.is_none());
        assert_eq!(request.method, "foo");
        assert_eq!(request.params_json, Some("[]"));
    }

    #[test]
    fn parse_request_id_string() {
        let request =
            super::parse_request(r#"{"jsonrpc":"2.0","id":"hello","method":"foo","params":[]}"#)
                .unwrap();
        assert_eq!(request.id_json.unwrap(), "\"hello\"");
        assert_eq!(request.method, "foo");
        assert_eq!(request.params_json, Some("[]"));
    }

    #[test]
    fn parse_request_id_string_escaped() {
        let request =
            super::parse_request(r#"{"jsonrpc":"2.0","id":"extern:\"health-checker:0\"","method":"system_health","params":[]}"#)
                .unwrap();
        assert_eq!(request.id_json.unwrap(), r#""extern:\"health-checker:0\"""#);
        assert_eq!(request.method, "system_health");
        assert_eq!(request.params_json, Some("[]"));
    }

    #[test]
    fn parse_response_id_string_escaped() {
        let (id, result) = super::parse_response(
            r#"{"jsonrpc":"2.0","id":"extern:\"health-checker:0\"","result":[]}"#,
        )
        .unwrap()
        .into_success()
        .unwrap();
        assert_eq!(id, r#""extern:\"health-checker:0\"""#);
        assert_eq!(result, "[]");
    }

    #[test]
    fn request_missing_params() {
        let request = super::parse_request(r#"{"jsonrpc":"2.0","id":2,"method":"foo"}"#).unwrap();
        assert_eq!(request.id_json.unwrap(), r#"2"#);
        assert_eq!(request.method, "foo");
        assert_eq!(request.params_json, None);
    }

    #[test]
    fn parse_request_wrong_jsonrpc() {
        assert!(
            super::parse_request(r#"{"jsonrpc":"2.1","id":5,"method":"foo","params":[]}"#).is_err()
        );
    }

    #[test]
    fn parse_response_wrong_jsonrpc() {
        assert!(super::parse_response(r#"{"jsonrpc":"2.1","id":5,"result":null}"#).is_err());
    }

    #[test]
    fn parse_request_bad_id() {
        assert!(
            super::parse_request(r#"{"jsonrpc":"2.0","id":{},"method":"foo","params":[]}"#)
                .is_err()
        );
    }

    #[test]
    fn parse_response_missing_id() {
        assert!(
            super::parse_response(
                r#"{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"} }"#
            )
            .is_err()
        );
    }

    #[test]
    fn parse_response_bad_id_success() {
        assert!(super::parse_response(r#"{"jsonrpc":"2.0","id":{},"result":5}"#).is_err());
    }

    #[test]
    fn parse_response_bad_id_error() {
        assert!(super::parse_response(
            r#"{"jsonrpc":"2.0","id":{},"error": {"code": -32601, "message": "Method not found"}}"#
        )
        .is_err());
    }

    #[test]
    fn build_request() {
        let request = super::Request {
            id_json: Some("5"),
            method: "test",
            params_json: Some("{}"),
        };

        let encoded = super::build_request(&request);
        assert_eq!(super::parse_request(&encoded).unwrap(), request);
    }

    #[test]
    #[should_panic]
    fn build_request_panics_invalid_id() {
        super::build_request(&super::Request {
            id_json: Some("test"),
            method: "test",
            params_json: None,
        });
    }

    #[test]
    #[should_panic]
    fn build_request_panics_invalid_params() {
        super::build_request(&super::Request {
            id_json: Some("5"),
            method: "test",
            params_json: Some("invalid"),
        });
    }

    #[test]
    fn build_parse_error() {
        let response = super::build_parse_error_response();
        assert_eq!(
            response,
            "{\"jsonrpc\":\"2.0\",\"id\":null,\"error\":{\"code\":-32700,\"message\":\"Parse error\"}}"
        );
    }
}