1use 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#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum RestError {
24 InvalidHex { field: &'static str },
26 InvalidNumber { field: &'static str },
28 InvalidValue { field: &'static str },
30 Missing { field: &'static str },
32 InvalidBlock(heika_block::BlockDecodeError),
34 InvalidTransaction(heika_transaction::DecodeError),
36 InvalidProof(heika_core::patricia::PatriciaProofError),
38 InvalidTreeNodes(heika_core::patricia::TreeNodeDecodeError),
40 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
67fn hex(bytes: &[u8]) -> String {
69 bytes.iter().map(|byte| format!("{byte:02X}")).collect()
70}
71
72fn 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
92fn number(text: &str, field: &'static str) -> Result<u64, RestError> {
94 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}