Skip to main content

nk_core/
json.rs

1//! Strict wire-JSON helpers shared by the event, filter and message
2//! visitors, plus the public [`JsonError`] wrapper.
3//!
4//! The wire profile: integers are plain JSON integers in
5//! `0..=2^53-1` (`1e3`, `1.0`, `-0` and negative spellings are rejected —
6//! `serde_json` itself reports them as floats or negatives), object keys
7//! are unique, and unknown fields are ignored.
8
9use alloc::borrow::Cow;
10use alloc::vec::Vec;
11use core::fmt;
12
13use serde::de::{Error as DeError, MapAccess, Visitor};
14use serde::{Deserialize, Deserializer};
15
16use crate::event::{Tag, Tags};
17use crate::limits::MAX_SAFE_INTEGER;
18
19/// A `serde_json` parse/validation failure, wrapped so no `serde_json`
20/// type leaks into the public API.
21///
22/// `Display` and [`core::error::Error::source`] both render the underlying
23/// parser message, which names the offending field.
24#[derive(Debug)]
25pub struct JsonError(serde_json::Error);
26
27impl fmt::Display for JsonError {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        self.0.fmt(f)
30    }
31}
32
33impl core::error::Error for JsonError {
34    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
35        Some(&self.0)
36    }
37}
38
39impl From<serde_json::Error> for JsonError {
40    fn from(error: serde_json::Error) -> Self {
41        Self(error)
42    }
43}
44
45/// The result type for `from_json` entry points.
46pub(crate) type Result<T> = core::result::Result<T, JsonError>;
47
48/// Records `key` in `seen`, failing on a duplicate object key — known and
49/// unknown keys share the one set (objects have unique keys).
50pub(crate) fn unique_key<'de, E: DeError>(
51    seen: &mut Vec<Cow<'de, str>>,
52    key: Cow<'de, str>,
53) -> core::result::Result<(), E> {
54    if seen.contains(&key) {
55        return Err(E::custom(alloc::format!("duplicate key `{key}`")));
56    }
57    seen.push(key);
58    Ok(())
59}
60
61/// Finalizes a required field: `None` → `missing_field`.
62pub(crate) fn required<T, E: DeError>(
63    slot: Option<T>,
64    field: &'static str,
65) -> core::result::Result<T, E> {
66    slot.ok_or_else(|| E::missing_field(field))
67}
68
69/// A wire integer in `0..=MAX`: only a plain non-negative JSON integer is
70/// accepted (`visit_u64`); floats, exponents, negatives and other types are
71/// deserialization errors.
72#[derive(Debug)]
73pub(crate) struct WireInt<const MAX: u64>(pub u64);
74
75struct IntVisitor {
76    max: u64,
77}
78
79impl Visitor<'_> for IntVisitor {
80    type Value = u64;
81
82    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        write!(f, "a non-negative integer of at most {}", self.max)
84    }
85
86    fn visit_u64<E: DeError>(self, value: u64) -> core::result::Result<u64, E> {
87        if value <= self.max {
88            Ok(value)
89        } else {
90            Err(E::custom("integer out of range"))
91        }
92    }
93}
94
95impl<'de, const MAX: u64> Deserialize<'de> for WireInt<MAX> {
96    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> core::result::Result<Self, D::Error> {
97        deserializer
98            .deserialize_any(IntVisitor { max: MAX })
99            .map(Self)
100    }
101}
102
103/// Deserializes a `0..=MAX_SAFE_INTEGER` wire integer for `Deserialize`
104/// field attributes.
105pub(crate) fn de_safe_int<'de, D: Deserializer<'de>>(
106    deserializer: D,
107) -> core::result::Result<u64, D::Error> {
108    deserializer.deserialize_any(IntVisitor {
109        max: MAX_SAFE_INTEGER,
110    })
111}
112
113/// A strict-lowercase wire hex string decoded into `N` bytes (events'
114/// `id`/`pubkey`/`sig`); `STRICT == false` accepts any case (filter
115/// `ids`/`authors`).
116#[derive(Debug)]
117pub(crate) struct WireHex<const N: usize, const STRICT: bool>(pub [u8; N]);
118
119struct HexVisitor<const N: usize, const STRICT: bool>;
120
121impl<const N: usize, const STRICT: bool> Visitor<'_> for HexVisitor<N, STRICT> {
122    type Value = [u8; N];
123
124    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125        write!(f, "a {}-character hex string", N * 2)
126    }
127
128    fn visit_str<E: DeError>(self, v: &str) -> core::result::Result<Self::Value, E> {
129        let decoded = if STRICT {
130            crate::hex::decode_wire::<N>(v)
131        } else {
132            crate::hex::decode_caller::<N>(v)
133        };
134        decoded.map_err(|_| E::custom("invalid hex"))
135    }
136}
137
138impl<'de, const N: usize, const STRICT: bool> Deserialize<'de> for WireHex<N, STRICT> {
139    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> core::result::Result<Self, D::Error> {
140        deserializer
141            .deserialize_any(HexVisitor::<N, STRICT>)
142            .map(Self)
143    }
144}
145
146/// A list of `N`-byte hex strings (`ids`, `authors`).
147#[derive(Debug)]
148pub(crate) struct WireHexList<const N: usize, const STRICT: bool>(pub Vec<[u8; N]>);
149
150impl<'de, const N: usize, const STRICT: bool> Deserialize<'de> for WireHexList<N, STRICT> {
151    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> core::result::Result<Self, D::Error> {
152        Vec::<WireHex<N, STRICT>>::deserialize(deserializer)
153            .map(|items| Self(items.into_iter().map(|item| item.0).collect()))
154    }
155}
156
157/// A `kinds` list (`0..=65535` elements).
158#[derive(Debug)]
159pub(crate) struct WireU16List(pub Vec<u16>);
160
161impl<'de> Deserialize<'de> for WireU16List {
162    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> core::result::Result<Self, D::Error> {
163        Vec::<WireInt<{ u16::MAX as u64 }>>::deserialize(deserializer).and_then(|items| {
164            items
165                .into_iter()
166                .map(|item| {
167                    u16::try_from(item.0).map_err(|_| D::Error::custom("kind out of range"))
168                })
169                .collect::<core::result::Result<Vec<u16>, D::Error>>()
170                .map(Self)
171        })
172    }
173}
174
175/// A `tags` field: a sequence of non-empty string sequences.
176#[derive(Debug)]
177pub(crate) struct WireTags(pub Tags);
178
179impl<'de> Deserialize<'de> for WireTags {
180    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> core::result::Result<Self, D::Error> {
181        Vec::<Tag>::deserialize(deserializer).map(|tags| Self(tags.into_iter().collect()))
182    }
183}
184
185/// Reads the next map key and rejects it as a duplicate before the value
186/// is read (unique keys only; the error fires on the key, not the value).
187pub(crate) fn next_key<'de, M: MapAccess<'de>>(
188    map: &mut M,
189    seen: &mut Vec<Cow<'de, str>>,
190) -> core::result::Result<Option<Cow<'de, str>>, M::Error> {
191    match map.next_key::<Cow<'de, str>>()? {
192        Some(key) => {
193            unique_key::<M::Error>(seen, Cow::clone(&key))?;
194            Ok(Some(key))
195        }
196        None => Ok(None),
197    }
198}
199
200#[cfg(test)]
201mod tests {
202    #![allow(clippy::unwrap_used, reason = "tests fail by panicking")]
203
204    use alloc::string::ToString;
205
206    use super::*;
207
208    #[test]
209    fn wire_int_accepts_only_plain_integers() {
210        assert_eq!(serde_json::from_str::<WireInt<5>>("5").unwrap().0, 5);
211        for bad in ["6", "-1", "-0", "1.0", "1e3", "\"5\"", "null", "true", "[]"] {
212            assert!(serde_json::from_str::<WireInt<5>>(bad).is_err(), "{bad}");
213        }
214        assert_eq!(
215            serde_json::from_str::<WireInt<{ MAX_SAFE_INTEGER }>>("9007199254740991")
216                .unwrap()
217                .0,
218            MAX_SAFE_INTEGER
219        );
220        assert!(serde_json::from_str::<WireInt<{ MAX_SAFE_INTEGER }>>("9007199254740992").is_err());
221    }
222
223    #[test]
224    fn wire_hex_respects_case_mode() {
225        assert_eq!(
226            serde_json::from_str::<WireHex<2, true>>("\"00ff\"")
227                .unwrap()
228                .0,
229            [0x00, 0xff]
230        );
231        assert!(serde_json::from_str::<WireHex<2, true>>("\"00FF\"").is_err());
232        assert_eq!(
233            serde_json::from_str::<WireHex<2, false>>("\"00FF\"")
234                .unwrap()
235                .0,
236            [0x00, 0xff]
237        );
238        assert!(serde_json::from_str::<WireHex<2, true>>("5").is_err());
239    }
240
241    #[test]
242    fn json_error_displays_and_sources_serde() {
243        let error = serde_json::from_str::<u64>("\"x\"")
244            .map_err(JsonError)
245            .unwrap_err();
246        let text = error.to_string();
247        assert_ne!(text.len(), 0);
248        assert!(core::error::Error::source(&error).is_some());
249    }
250}