Skip to main content

heika_rest/
lib.rs

1//! Symbol の REST(catapult-rest)が返す JSON を読み、heika の型に変えて確かめる。
2//!
3//! HTTP は持たない。どのクライアントで取ってきたかは問わず、受け取った JSON を serde で読み、
4//! `TryFrom` で heika の型にする。REST の答えはそのまま信じず、組み直したバイト列から
5//! ハッシュや署名を求め直して、REST が一緒に返した値と合うかを確かめられる。
6//!
7//! 型と項目の名前は、symbol/symbol の `openapi/spec` に合わせる。
8
9use std::fmt;
10
11pub mod balance;
12pub mod block;
13pub mod finalization;
14pub mod merkle;
15pub mod node;
16pub mod send;
17pub mod state;
18pub mod statement;
19pub mod transaction;
20
21/// REST の JSON を heika の型にできなかった。
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum RestError {
24    /// 16進の文字列として読めないか、長さが違う
25    InvalidHex { field: &'static str },
26    /// 10進の数として読めないか、範囲を超えている
27    InvalidNumber { field: &'static str },
28    /// 決まった値のどれでもない
29    InvalidValue { field: &'static str },
30    /// 要る項目がない
31    Missing { field: &'static str },
32    /// 組み直したバイト列を、ブロックとして読めない
33    InvalidBlock(heika_block::BlockDecodeError),
34    /// 組み直したバイト列を、トランザクションとして読めない
35    InvalidTransaction(heika_transaction::DecodeError),
36    /// 状態の経路が根からつながらない
37    InvalidProof(heika_core::patricia::PatriciaProofError),
38    /// 状態の木のノードを読めない
39    InvalidTreeNodes(heika_core::patricia::TreeNodeDecodeError),
40    /// 組み直したものから求めた値が、REST が一緒に返した値と合わない
41    Mismatch { field: &'static str },
42}
43
44impl fmt::Display for RestError {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        match self {
47            Self::InvalidHex { field } => write!(f, "{field} を16進として読めません"),
48            Self::InvalidNumber { field } => write!(f, "{field} を数として読めません"),
49            Self::InvalidValue { field } => write!(f, "{field} の値を知りません"),
50            Self::Missing { field } => write!(f, "{field} がありません"),
51            Self::InvalidBlock(error) => write!(f, "ブロックとして読めません: {error}"),
52            Self::InvalidTransaction(error) => {
53                write!(f, "トランザクションとして読めません: {error}")
54            }
55            Self::InvalidProof(error) => write!(f, "状態の経路を確かめられません: {error}"),
56            Self::InvalidTreeNodes(error) => write!(f, "状態の木のノードを読めません: {error}"),
57            Self::Mismatch { field } => write!(
58                f,
59                "組み直したものから求めた値が、REST の {field} と合いません"
60            ),
61        }
62    }
63}
64
65impl std::error::Error for RestError {}
66
67/// バイト列を、REST と同じ大文字の16進にする。
68fn hex(bytes: &[u8]) -> String {
69    bytes.iter().map(|byte| format!("{byte:02X}")).collect()
70}
71
72/// 決まった長さの16進の文字列を読む。REST は大文字で返すが、小文字も受け付ける。
73fn hex_array<const N: usize>(text: &str, field: &'static str) -> Result<[u8; N], RestError> {
74    hex_vec(text, field)?
75        .try_into()
76        .map_err(|_| RestError::InvalidHex { field })
77}
78
79fn hex_vec(text: &str, field: &'static str) -> Result<Vec<u8>, RestError> {
80    let error = || RestError::InvalidHex { field };
81    if !text.len().is_multiple_of(2) {
82        return Err(error());
83    }
84    let digit = |byte: u8| (byte as char).to_digit(16).map(|value| value as u8);
85    text.as_bytes()
86        .chunks(2)
87        .map(|pair| Some(digit(pair[0])? << 4 | digit(pair[1])?))
88        .collect::<Option<_>>()
89        .ok_or_else(error)
90}
91
92/// REST が u64 を10進の文字列で返すものを読む。
93fn number(text: &str, field: &'static str) -> Result<u64, RestError> {
94    // 符号や空白は受け付けない
95    if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) {
96        return Err(RestError::InvalidNumber { field });
97    }
98    text.parse().map_err(|_| RestError::InvalidNumber { field })
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104
105    #[test]
106    fn reads_hex_in_either_case() {
107        assert_eq!(hex_array::<2>("0aFf", "x"), Ok([0x0A, 0xFF]));
108        assert_eq!(
109            hex_array::<2>("0aF", "x"),
110            Err(RestError::InvalidHex { field: "x" })
111        );
112        assert_eq!(
113            hex_array::<2>("0aFf00", "x"),
114            Err(RestError::InvalidHex { field: "x" })
115        );
116        assert_eq!(
117            hex_array::<1>("0g", "x"),
118            Err(RestError::InvalidHex { field: "x" })
119        );
120    }
121
122    #[test]
123    fn reads_u64_from_decimal_strings() {
124        assert_eq!(number("18446744073709551615", "x"), Ok(u64::MAX));
125        for text in ["", "-1", "+1", " 1", "18446744073709551616", "0x10"] {
126            assert_eq!(
127                number(text, "x"),
128                Err(RestError::InvalidNumber { field: "x" }),
129                "{text:?}"
130            );
131        }
132    }
133}