Skip to main content

nk_core/message/
client.rs

1//! Client → relay messages (NIP-01 + NIP-42 AUTH + NIP-45 COUNT + NIP-77).
2
3use alloc::borrow::Cow;
4use alloc::string::String;
5use alloc::vec::Vec;
6use core::fmt;
7
8use serde::de::{Error as DeError, SeqAccess, Visitor};
9use serde::ser::SerializeSeq;
10use serde::{Deserialize, Deserializer, Serialize, Serializer};
11
12use super::{
13    Error, Result, SubscriptionId, end, event_item, filter_item, parse_neg_hex, read_type,
14    string_item, sub_id,
15};
16use crate::event::{Event, canonical};
17use crate::filter::Filter;
18
19/// Client → relay messages (NIP-01 + NIP-42 AUTH + NIP-45 COUNT + NIP-77).
20#[non_exhaustive]
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub enum ClientMessage<'a> {
23    /// `["EVENT", <event>]` — publish a signed event.
24    Event(Cow<'a, Event>),
25    /// `["REQ", <id>, <filter>, ...]` — open a subscription.
26    Req {
27        /// Subscription id.
28        subscription_id: Cow<'a, SubscriptionId>,
29        /// At least one filter on the wire; `encode` of an empty slice emits
30        /// `["REQ","<id>"]` unchanged.
31        filters: Cow<'a, [Filter]>,
32    },
33    /// `["COUNT", <id>, <filter>, ...]` — a NIP-45 count request.
34    Count {
35        /// Subscription id.
36        subscription_id: Cow<'a, SubscriptionId>,
37        /// Same rules as [`ClientMessage::Req::filters`].
38        filters: Cow<'a, [Filter]>,
39    },
40    /// `["CLOSE", <id>]` — close a subscription.
41    Close(Cow<'a, SubscriptionId>),
42    /// `["AUTH", <event>]` — a NIP-42 kind-22242 auth event.
43    Auth(Cow<'a, Event>),
44    /// `["NEG-OPEN", <id>, <filter>, <hex>]` — open a NIP-77 sync.
45    NegOpen {
46        /// Subscription id.
47        subscription_id: Cow<'a, SubscriptionId>,
48        /// The sync filter.
49        filter: Cow<'a, Filter>,
50        /// The initial negentropy message (non-empty, even-length hex).
51        message: Cow<'a, str>,
52    },
53    /// `["NEG-MSG", <id>, <hex>]` — continue a NIP-77 sync.
54    NegMsg {
55        /// Subscription id.
56        subscription_id: Cow<'a, SubscriptionId>,
57        /// The negentropy message (non-empty, even-length hex).
58        message: Cow<'a, str>,
59    },
60    /// `["NEG-CLOSE", <id>]` — end a NIP-77 sync.
61    NegClose(Cow<'a, SubscriptionId>),
62}
63
64const TYPES: &[&str] = &[
65    "EVENT",
66    "REQ",
67    "COUNT",
68    "CLOSE",
69    "AUTH",
70    "NEG-OPEN",
71    "NEG-MSG",
72    "NEG-CLOSE",
73];
74
75impl ClientMessage<'_> {
76    /// The canonical NIP-01 JSON wire form.
77    #[must_use]
78    pub fn to_json(&self) -> String {
79        let mut out = String::new();
80        match self {
81            Self::Event(event) => {
82                out.push_str("[\"EVENT\",");
83                canonical::write_signed(event, &mut out);
84                out.push(']');
85            }
86            Self::Req {
87                subscription_id,
88                filters,
89            }
90            | Self::Count {
91                subscription_id,
92                filters,
93            } => {
94                let kind = if matches!(self, Self::Req { .. }) {
95                    "REQ"
96                } else {
97                    "COUNT"
98                };
99                out.push_str("[\"");
100                out.push_str(kind);
101                out.push_str("\",");
102                canonical::push_json_string(subscription_id.as_str(), &mut out);
103                for filter in filters.iter() {
104                    out.push(',');
105                    filter.write_canonical(&mut out);
106                }
107                out.push(']');
108            }
109            Self::Close(subscription_id) => {
110                out.push_str("[\"CLOSE\",");
111                canonical::push_json_string(subscription_id.as_str(), &mut out);
112                out.push(']');
113            }
114            Self::Auth(event) => {
115                out.push_str("[\"AUTH\",");
116                canonical::write_signed(event, &mut out);
117                out.push(']');
118            }
119            Self::NegOpen {
120                subscription_id,
121                filter,
122                message,
123            } => {
124                out.push_str("[\"NEG-OPEN\",");
125                canonical::push_json_string(subscription_id.as_str(), &mut out);
126                out.push(',');
127                filter.write_canonical(&mut out);
128                out.push(',');
129                canonical::push_json_string(message, &mut out);
130                out.push(']');
131            }
132            Self::NegMsg {
133                subscription_id,
134                message,
135            } => {
136                out.push_str("[\"NEG-MSG\",");
137                canonical::push_json_string(subscription_id.as_str(), &mut out);
138                out.push(',');
139                canonical::push_json_string(message, &mut out);
140                out.push(']');
141            }
142            Self::NegClose(subscription_id) => {
143                out.push_str("[\"NEG-CLOSE\",");
144                canonical::push_json_string(subscription_id.as_str(), &mut out);
145                out.push(']');
146            }
147        }
148        out
149    }
150
151    /// Parses a client → relay JSON message.
152    ///
153    /// # Errors
154    ///
155    /// [`Error::InvalidJson`] when the text is not JSON,
156    /// [`Error::NotAMessageArray`] when it is not a non-empty array starting
157    /// with the type string, [`Error::UnknownType`] for an unrecognized
158    /// type, [`Error::InvalidMessage`] for wrong arity or field types,
159    /// [`Error::InvalidPayload`] when an embedded event or filter fails
160    /// wire validation, [`Error::InvalidSubscriptionId`] for a bad
161    /// subscription id, [`Error::ObsoleteNegOpen`] for the 5-element
162    /// `NEG-OPEN`, and [`Error::InvalidNegMessage`] for malformed NEG hex.
163    pub fn from_json(raw: &str) -> Result<ClientMessage<'static>> {
164        serde_json::from_str(raw).map_err(|e| Error::InvalidJson {
165            source: crate::json::JsonError::from(e),
166        })
167    }
168
169    /// Converts every borrowed field to owned, giving a `'static` message.
170    #[must_use]
171    pub fn into_owned(self) -> ClientMessage<'static> {
172        match self {
173            Self::Event(event) => ClientMessage::Event(Cow::Owned(event.into_owned())),
174            Self::Req {
175                subscription_id,
176                filters,
177            } => ClientMessage::Req {
178                subscription_id: Cow::Owned(subscription_id.into_owned()),
179                filters: Cow::Owned(filters.into_owned()),
180            },
181            Self::Count {
182                subscription_id,
183                filters,
184            } => ClientMessage::Count {
185                subscription_id: Cow::Owned(subscription_id.into_owned()),
186                filters: Cow::Owned(filters.into_owned()),
187            },
188            Self::Close(id) => ClientMessage::Close(Cow::Owned(id.into_owned())),
189            Self::Auth(event) => ClientMessage::Auth(Cow::Owned(event.into_owned())),
190            Self::NegOpen {
191                subscription_id,
192                filter,
193                message,
194            } => ClientMessage::NegOpen {
195                subscription_id: Cow::Owned(subscription_id.into_owned()),
196                filter: Cow::Owned(filter.into_owned()),
197                message: Cow::Owned(message.into_owned()),
198            },
199            Self::NegMsg {
200                subscription_id,
201                message,
202            } => ClientMessage::NegMsg {
203                subscription_id: Cow::Owned(subscription_id.into_owned()),
204                message: Cow::Owned(message.into_owned()),
205            },
206            Self::NegClose(id) => ClientMessage::NegClose(Cow::Owned(id.into_owned())),
207        }
208    }
209}
210
211impl Serialize for ClientMessage<'_> {
212    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
213    where
214        S: Serializer,
215    {
216        match self {
217            Self::Event(event) => {
218                let mut seq = serializer.serialize_seq(Some(2))?;
219                seq.serialize_element("EVENT")?;
220                seq.serialize_element(&**event)?;
221                seq.end()
222            }
223            Self::Req {
224                subscription_id,
225                filters,
226            }
227            | Self::Count {
228                subscription_id,
229                filters,
230            } => {
231                let ty = if matches!(self, Self::Req { .. }) {
232                    "REQ"
233                } else {
234                    "COUNT"
235                };
236                let mut seq = serializer.serialize_seq(Some(2 + filters.len()))?;
237                seq.serialize_element(ty)?;
238                seq.serialize_element(&**subscription_id)?;
239                for filter in filters.iter() {
240                    seq.serialize_element(filter)?;
241                }
242                seq.end()
243            }
244            Self::Close(subscription_id) => {
245                let mut seq = serializer.serialize_seq(Some(2))?;
246                seq.serialize_element("CLOSE")?;
247                seq.serialize_element(&**subscription_id)?;
248                seq.end()
249            }
250            Self::Auth(event) => {
251                let mut seq = serializer.serialize_seq(Some(2))?;
252                seq.serialize_element("AUTH")?;
253                seq.serialize_element(&**event)?;
254                seq.end()
255            }
256            Self::NegOpen {
257                subscription_id,
258                filter,
259                message,
260            } => {
261                let mut seq = serializer.serialize_seq(Some(4))?;
262                seq.serialize_element("NEG-OPEN")?;
263                seq.serialize_element(&**subscription_id)?;
264                seq.serialize_element(&**filter)?;
265                seq.serialize_element(&**message)?;
266                seq.end()
267            }
268            Self::NegMsg {
269                subscription_id,
270                message,
271            } => {
272                let mut seq = serializer.serialize_seq(Some(3))?;
273                seq.serialize_element("NEG-MSG")?;
274                seq.serialize_element(&**subscription_id)?;
275                seq.serialize_element(&**message)?;
276                seq.end()
277            }
278            Self::NegClose(subscription_id) => {
279                let mut seq = serializer.serialize_seq(Some(2))?;
280                seq.serialize_element("NEG-CLOSE")?;
281                seq.serialize_element(&**subscription_id)?;
282                seq.end()
283            }
284        }
285    }
286}
287
288impl<'de> Deserialize<'de> for ClientMessage<'static> {
289    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
290    where
291        D: Deserializer<'de>,
292    {
293        struct MessageVisitor;
294
295        impl<'de> Visitor<'de> for MessageVisitor {
296            type Value = ClientMessage<'static>;
297
298            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299                f.write_str("a client message array")
300            }
301
302            #[allow(
303                clippy::excessive_nesting,
304                reason = "a message is a labelled seq of variants"
305            )]
306            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
307                let ty = read_type(&mut seq, TYPES)?;
308                match ty {
309                    "EVENT" => {
310                        let event = event_item(&mut seq, ty)?;
311                        end(&mut seq, ty)?;
312                        Ok(ClientMessage::Event(Cow::Owned(event)))
313                    }
314                    "REQ" | "COUNT" => {
315                        let subscription_id = sub_id(&mut seq, ty)?;
316                        let mut filters = Vec::new();
317                        while let Some(filter) = seq.next_element::<Filter>()? {
318                            filters.push(filter);
319                        }
320                        if filters.is_empty() {
321                            return Err(DeError::custom(Error::InvalidMessage { ty }));
322                        }
323                        let filters = Cow::Owned(filters);
324                        Ok(if ty == "REQ" {
325                            ClientMessage::Req {
326                                subscription_id: Cow::Owned(subscription_id),
327                                filters,
328                            }
329                        } else {
330                            ClientMessage::Count {
331                                subscription_id: Cow::Owned(subscription_id),
332                                filters,
333                            }
334                        })
335                    }
336                    "CLOSE" => {
337                        let id = sub_id(&mut seq, ty)?;
338                        end(&mut seq, ty)?;
339                        Ok(ClientMessage::Close(Cow::Owned(id)))
340                    }
341                    "AUTH" => {
342                        let event = event_item(&mut seq, ty)?;
343                        end(&mut seq, ty)?;
344                        Ok(ClientMessage::Auth(Cow::Owned(event)))
345                    }
346                    "NEG-OPEN" => {
347                        let subscription_id = sub_id(&mut seq, ty)?;
348                        let filter = filter_item(&mut seq, ty)?;
349                        let message =
350                            parse_neg_hex(&string_item(&mut seq, ty)?).map_err(DeError::custom)?;
351                        if seq.next_element::<serde::de::IgnoredAny>()?.is_some() {
352                            return Err(DeError::custom(Error::ObsoleteNegOpen));
353                        }
354                        Ok(ClientMessage::NegOpen {
355                            subscription_id: Cow::Owned(subscription_id),
356                            filter: Cow::Owned(filter),
357                            message: Cow::Owned(message),
358                        })
359                    }
360                    "NEG-MSG" => {
361                        let subscription_id = sub_id(&mut seq, ty)?;
362                        let message =
363                            parse_neg_hex(&string_item(&mut seq, ty)?).map_err(DeError::custom)?;
364                        end(&mut seq, ty)?;
365                        Ok(ClientMessage::NegMsg {
366                            subscription_id: Cow::Owned(subscription_id),
367                            message: Cow::Owned(message),
368                        })
369                    }
370                    "NEG-CLOSE" => {
371                        let id = sub_id(&mut seq, ty)?;
372                        end(&mut seq, ty)?;
373                        Ok(ClientMessage::NegClose(Cow::Owned(id)))
374                    }
375                    _ => Err(DeError::custom(Error::InvalidMessage { ty })),
376                }
377            }
378        }
379
380        deserializer.deserialize_seq(MessageVisitor)
381    }
382}