nula-core 0.2.2

Nostr protocol core: events, filters, keys, messages, NIP primitives.
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
687
688
689
//! Messages a relay sends to a client.
//!
//! Per [NIP-01], every relay-to-client message is a JSON array tagged by its
//! command. NIP-20 documents the [`MachineReadablePrefix`] applied to `OK`
//! and `CLOSED` reasons; this module exposes the parsed prefix so callers can
//! switch on it without re-parsing the wire string.
//!
//! [NIP-01]: https://github.com/nostr-protocol/nips/blob/master/01.md

use std::fmt;
use std::str::FromStr;

use serde::de::{self, SeqAccess, Visitor};
use serde::ser::{SerializeSeq, Serializer};
use serde::{Deserialize, Deserializer, Serialize};
use thiserror::Error;

use super::subscription_id::SubscriptionId;
use crate::event::{Event, EventId};

const TAG_EVENT: &str = "EVENT";
const TAG_OK: &str = "OK";
const TAG_EOSE: &str = "EOSE";
const TAG_CLOSED: &str = "CLOSED";
const TAG_NOTICE: &str = "NOTICE";
const TAG_AUTH: &str = "AUTH";
const TAG_COUNT: &str = "COUNT";
const TAG_NEG_MSG: &str = "NEG-MSG";
const TAG_NEG_ERR: &str = "NEG-ERR";

/// Errors raised when constructing a [`MachineReadablePrefix`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum MachineReadablePrefixError {
    /// The prefix string was not one of the known NIP-20 prefixes.
    #[error("unknown machine-readable prefix")]
    Unknown,
}

/// Standardised reason prefix used in `OK` / `CLOSED` reasons (NIP-20).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum MachineReadablePrefix {
    /// `duplicate:` — the relay already had the event.
    Duplicate,
    /// `pow:` — proof-of-work requirements were not met.
    Pow,
    /// `blocked:` — the author or pubkey is blocked by the relay.
    Blocked,
    /// `rate-limited:` — the client hit a rate limit.
    RateLimited,
    /// `invalid:` — the event failed validation.
    Invalid,
    /// `error:` — the relay encountered an internal error.
    Error,
    /// `restricted:` — the author lacks permission (e.g. NIP-42 not done).
    Restricted,
    /// `mute:` — an ephemeral event nobody was listening to (NIP-01 §OK
    /// examples).
    Mute,
    /// `auth-required:` — NIP-42 authentication is required.
    AuthRequired,
    /// `payment-required:` — paid relay; the client has not paid yet.
    PaymentRequired,
}

impl MachineReadablePrefix {
    /// Static wire string (without the trailing colon).
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Duplicate => "duplicate",
            Self::Pow => "pow",
            Self::Blocked => "blocked",
            Self::RateLimited => "rate-limited",
            Self::Invalid => "invalid",
            Self::Error => "error",
            Self::Restricted => "restricted",
            Self::Mute => "mute",
            Self::AuthRequired => "auth-required",
            Self::PaymentRequired => "payment-required",
        }
    }

    /// Try to extract the prefix from a NIP-20 reason such as `"pow: 24"`.
    /// Returns `None` if the string does not start with a known prefix
    /// followed by `:`.
    #[must_use]
    pub fn from_reason(reason: &str) -> Option<Self> {
        let (prefix, _rest) = reason.split_once(':')?;
        prefix.parse().ok()
    }
}

impl fmt::Display for MachineReadablePrefix {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for MachineReadablePrefix {
    type Err = MachineReadablePrefixError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let value = match s {
            "duplicate" => Self::Duplicate,
            "pow" => Self::Pow,
            "blocked" => Self::Blocked,
            "rate-limited" => Self::RateLimited,
            "invalid" => Self::Invalid,
            "error" => Self::Error,
            "restricted" => Self::Restricted,
            "mute" => Self::Mute,
            "auth-required" => Self::AuthRequired,
            "payment-required" => Self::PaymentRequired,
            _ => return Err(MachineReadablePrefixError::Unknown),
        };
        Ok(value)
    }
}

/// Errors raised when parsing a [`RelayMessage`].
#[derive(Debug, Clone, Error)]
#[non_exhaustive]
pub enum RelayMessageError {
    /// The wire array was empty.
    #[error("relay message must not be empty")]
    Empty,
    /// The message tag was not recognised.
    #[error("unknown relay message tag `{0}`")]
    UnknownTag(String),
    /// The message tag was recognised but the payload was malformed.
    #[error("malformed `{tag}` message: {reason}")]
    Malformed {
        /// The wire tag string.
        tag: &'static str,
        /// Human-readable explanation.
        reason: String,
    },
}

/// Messages sent from a relay to a client.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
#[allow(
    clippy::large_enum_variant,
    reason = "EVENT inherently carries a full Event while the control variants \
              (OK/EOSE/CLOSED/NOTICE/AUTH) are small; boxing it would add \
              allocation churn on the relay-send and pool-receive hot paths, \
              where EVENT is by far the most common message and is moved \
              straight into/out of the enum. rust-nostr makes the same \
              trade-off via a Cow<Event> EVENT variant."
)]
pub enum RelayMessage {
    /// A subscription event match.
    ///
    /// Wire form: `["EVENT", <subscription_id>, <event>]`.
    Event {
        /// Subscription identifier originally supplied by the client.
        subscription_id: SubscriptionId,
        /// The matched event.
        event: Event,
    },
    /// Acknowledgement for a published [`crate::Event`].
    ///
    /// Wire form: `["OK", <event_id>, <accepted>, <message>]`.
    Ok {
        /// Event id the relay is acknowledging.
        event_id: EventId,
        /// `true` if the event was accepted.
        accepted: bool,
        /// Human-readable reason. Use [`MachineReadablePrefix::from_reason`]
        /// to recover a structured reason.
        message: String,
    },
    /// End-of-stored-events sentinel: the relay has finished sending stored
    /// matches; future events arrive in real time.
    ///
    /// Wire form: `["EOSE", <subscription_id>]`.
    EndOfStoredEvents(SubscriptionId),
    /// The relay closed the subscription.
    ///
    /// Wire form: `["CLOSED", <subscription_id>, <reason>]`.
    Closed {
        /// Subscription identifier.
        subscription_id: SubscriptionId,
        /// Reason string. Use [`MachineReadablePrefix::from_reason`] to
        /// recover a structured reason.
        message: String,
    },
    /// A free-form notice intended for end-user display.
    ///
    /// Wire form: `["NOTICE", <message>]`.
    Notice(String),
    /// NIP-42 authentication challenge.
    ///
    /// Wire form: `["AUTH", <challenge>]`.
    Auth(String),
    /// Count reply for a previously issued `COUNT` request (NIP-45).
    ///
    /// Wire form: `["COUNT", <subscription_id>, {"count": <n>}]`.
    Count {
        /// Subscription identifier.
        subscription_id: SubscriptionId,
        /// Number of matching events.
        count: u64,
    },
    /// One step of an in-flight NIP-77 reconciliation, from the relay
    /// back to the client.
    ///
    /// Wire form: `["NEG-MSG", <subscription_id>, <message_hex>]`.
    NegMsg {
        /// Subscription identifier from the original `NEG-OPEN`.
        subscription_id: SubscriptionId,
        /// Reconciliation payload, lowercase hex-encoded.
        message: String,
    },
    /// Terminal error frame for a NIP-77 reconciliation session.
    ///
    /// Wire form: `["NEG-ERR", <subscription_id>, <reason>]`.
    NegErr {
        /// Subscription identifier the relay is failing.
        subscription_id: SubscriptionId,
        /// Reason string. Conventional prefixes (e.g.
        /// `"blocked: …"`) are observable via
        /// [`MachineReadablePrefix::from_reason`].
        message: String,
    },
}

impl Serialize for RelayMessage {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Event {
                subscription_id,
                event,
            } => {
                let mut seq = serializer.serialize_seq(Some(3))?;
                seq.serialize_element(TAG_EVENT)?;
                seq.serialize_element(subscription_id)?;
                seq.serialize_element(event)?;
                seq.end()
            }
            Self::Ok {
                event_id,
                accepted,
                message,
            } => {
                let mut seq = serializer.serialize_seq(Some(4))?;
                seq.serialize_element(TAG_OK)?;
                seq.serialize_element(event_id)?;
                seq.serialize_element(accepted)?;
                seq.serialize_element(message)?;
                seq.end()
            }
            Self::EndOfStoredEvents(id) => {
                let mut seq = serializer.serialize_seq(Some(2))?;
                seq.serialize_element(TAG_EOSE)?;
                seq.serialize_element(id)?;
                seq.end()
            }
            Self::Closed {
                subscription_id,
                message,
            } => {
                let mut seq = serializer.serialize_seq(Some(3))?;
                seq.serialize_element(TAG_CLOSED)?;
                seq.serialize_element(subscription_id)?;
                seq.serialize_element(message)?;
                seq.end()
            }
            Self::Notice(message) => {
                let mut seq = serializer.serialize_seq(Some(2))?;
                seq.serialize_element(TAG_NOTICE)?;
                seq.serialize_element(message)?;
                seq.end()
            }
            Self::Auth(challenge) => {
                let mut seq = serializer.serialize_seq(Some(2))?;
                seq.serialize_element(TAG_AUTH)?;
                seq.serialize_element(challenge)?;
                seq.end()
            }
            Self::Count {
                subscription_id,
                count,
            } => {
                #[derive(Serialize)]
                struct CountPayload {
                    count: u64,
                }

                let mut seq = serializer.serialize_seq(Some(3))?;
                seq.serialize_element(TAG_COUNT)?;
                seq.serialize_element(subscription_id)?;
                seq.serialize_element(&CountPayload { count: *count })?;
                seq.end()
            }
            Self::NegMsg {
                subscription_id,
                message,
            } => {
                let mut seq = serializer.serialize_seq(Some(3))?;
                seq.serialize_element(TAG_NEG_MSG)?;
                seq.serialize_element(subscription_id)?;
                seq.serialize_element(message)?;
                seq.end()
            }
            Self::NegErr {
                subscription_id,
                message,
            } => {
                let mut seq = serializer.serialize_seq(Some(3))?;
                seq.serialize_element(TAG_NEG_ERR)?;
                seq.serialize_element(subscription_id)?;
                seq.serialize_element(message)?;
                seq.end()
            }
        }
    }
}

impl<'de> Deserialize<'de> for RelayMessage {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct RelayVisitor;

        impl<'de> Visitor<'de> for RelayVisitor {
            type Value = RelayMessage;

            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("a Nostr relay message array")
            }

            fn visit_seq<A>(self, mut seq: A) -> Result<RelayMessage, A::Error>
            where
                A: SeqAccess<'de>,
            {
                let tag: String = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::custom(RelayMessageError::Empty))?;
                match tag.as_str() {
                    TAG_EVENT => decode_event(&mut seq),
                    TAG_OK => decode_ok(&mut seq),
                    TAG_EOSE => decode_eose(&mut seq),
                    TAG_CLOSED => decode_closed(&mut seq),
                    TAG_NOTICE => decode_notice(&mut seq),
                    TAG_AUTH => decode_auth(&mut seq),
                    TAG_COUNT => decode_count(&mut seq),
                    TAG_NEG_MSG => decode_neg_msg(&mut seq),
                    TAG_NEG_ERR => decode_neg_err(&mut seq),
                    other => Err(de::Error::custom(RelayMessageError::UnknownTag(
                        other.to_owned(),
                    ))),
                }
            }
        }

        deserializer.deserialize_seq(RelayVisitor)
    }
}

fn malformed<E: de::Error>(tag: &'static str, reason: &str) -> E {
    E::custom(RelayMessageError::Malformed {
        tag,
        reason: reason.to_owned(),
    })
}

fn decode_event<'de, A>(seq: &mut A) -> Result<RelayMessage, A::Error>
where
    A: SeqAccess<'de>,
{
    let subscription_id: SubscriptionId = seq
        .next_element()?
        .ok_or_else(|| malformed::<A::Error>(TAG_EVENT, "missing subscription id"))?;
    let event: Event = seq
        .next_element()?
        .ok_or_else(|| malformed::<A::Error>(TAG_EVENT, "missing event"))?;
    Ok(RelayMessage::Event {
        subscription_id,
        event,
    })
}

fn decode_ok<'de, A>(seq: &mut A) -> Result<RelayMessage, A::Error>
where
    A: SeqAccess<'de>,
{
    let event_id: EventId = seq
        .next_element()?
        .ok_or_else(|| malformed::<A::Error>(TAG_OK, "missing event id"))?;
    let accepted: bool = seq
        .next_element()?
        .ok_or_else(|| malformed::<A::Error>(TAG_OK, "missing accepted flag"))?;
    // NIP-01: "The 4th parameter MUST always be present, but MAY be an
    // empty string when the 3rd is true". An absent message is malformed.
    let message: String = seq
        .next_element()?
        .ok_or_else(|| malformed::<A::Error>(TAG_OK, "missing message"))?;
    Ok(RelayMessage::Ok {
        event_id,
        accepted,
        message,
    })
}

fn decode_eose<'de, A>(seq: &mut A) -> Result<RelayMessage, A::Error>
where
    A: SeqAccess<'de>,
{
    let id: SubscriptionId = seq
        .next_element()?
        .ok_or_else(|| malformed::<A::Error>(TAG_EOSE, "missing subscription id"))?;
    Ok(RelayMessage::EndOfStoredEvents(id))
}

fn decode_closed<'de, A>(seq: &mut A) -> Result<RelayMessage, A::Error>
where
    A: SeqAccess<'de>,
{
    let subscription_id: SubscriptionId = seq
        .next_element()?
        .ok_or_else(|| malformed::<A::Error>(TAG_CLOSED, "missing subscription id"))?;
    let message: String = seq.next_element()?.unwrap_or_default();
    Ok(RelayMessage::Closed {
        subscription_id,
        message,
    })
}

fn decode_notice<'de, A>(seq: &mut A) -> Result<RelayMessage, A::Error>
where
    A: SeqAccess<'de>,
{
    let message: String = seq
        .next_element()?
        .ok_or_else(|| malformed::<A::Error>(TAG_NOTICE, "missing message"))?;
    Ok(RelayMessage::Notice(message))
}

fn decode_auth<'de, A>(seq: &mut A) -> Result<RelayMessage, A::Error>
where
    A: SeqAccess<'de>,
{
    let challenge: String = seq
        .next_element()?
        .ok_or_else(|| malformed::<A::Error>(TAG_AUTH, "missing challenge"))?;
    Ok(RelayMessage::Auth(challenge))
}

fn decode_count<'de, A>(seq: &mut A) -> Result<RelayMessage, A::Error>
where
    A: SeqAccess<'de>,
{
    #[derive(Deserialize)]
    struct CountPayload {
        count: u64,
    }

    let subscription_id: SubscriptionId = seq
        .next_element()?
        .ok_or_else(|| malformed::<A::Error>(TAG_COUNT, "missing subscription id"))?;
    let payload: CountPayload = seq
        .next_element()?
        .ok_or_else(|| malformed::<A::Error>(TAG_COUNT, "missing count payload"))?;
    Ok(RelayMessage::Count {
        subscription_id,
        count: payload.count,
    })
}

fn decode_neg_msg<'de, A>(seq: &mut A) -> Result<RelayMessage, A::Error>
where
    A: SeqAccess<'de>,
{
    let subscription_id: SubscriptionId = seq
        .next_element()?
        .ok_or_else(|| malformed::<A::Error>(TAG_NEG_MSG, "missing subscription id"))?;
    let message: String = seq
        .next_element()?
        .ok_or_else(|| malformed::<A::Error>(TAG_NEG_MSG, "missing message"))?;
    Ok(RelayMessage::NegMsg {
        subscription_id,
        message,
    })
}

fn decode_neg_err<'de, A>(seq: &mut A) -> Result<RelayMessage, A::Error>
where
    A: SeqAccess<'de>,
{
    let subscription_id: SubscriptionId = seq
        .next_element()?
        .ok_or_else(|| malformed::<A::Error>(TAG_NEG_ERR, "missing subscription id"))?;
    let message: String = seq
        .next_element()?
        .ok_or_else(|| malformed::<A::Error>(TAG_NEG_ERR, "missing message"))?;
    Ok(RelayMessage::NegErr {
        subscription_id,
        message,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Keys;
    use crate::event::EventBuilder;

    fn keys() -> Keys {
        Keys::parse("0000000000000000000000000000000000000000000000000000000000000003").unwrap()
    }

    fn signed_event() -> Event {
        EventBuilder::text_note("hello")
            .sign_with_keys(&keys())
            .unwrap()
    }

    fn sub() -> SubscriptionId {
        SubscriptionId::new("sub-1").unwrap()
    }

    #[test]
    fn event_round_trip() {
        let msg = RelayMessage::Event {
            subscription_id: sub(),
            event: signed_event(),
        };
        let json = serde_json::to_string(&msg).unwrap();
        assert!(json.starts_with("[\"EVENT\",\"sub-1\","));
        let parsed: RelayMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, msg);
    }

    #[test]
    fn ok_round_trip_with_message() {
        let msg = RelayMessage::Ok {
            event_id: signed_event().id,
            accepted: false,
            message: "blocked: spam".to_owned(),
        };
        let json = serde_json::to_string(&msg).unwrap();
        let parsed: RelayMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, msg);
    }

    #[test]
    fn ok_with_empty_message_round_trip() {
        let msg = RelayMessage::Ok {
            event_id: signed_event().id,
            accepted: true,
            message: String::new(),
        };
        let json = serde_json::to_string(&msg).unwrap();
        let parsed: RelayMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, msg);
    }

    #[test]
    fn eose_round_trip() {
        let msg = RelayMessage::EndOfStoredEvents(sub());
        let json = serde_json::to_string(&msg).unwrap();
        assert_eq!(json, "[\"EOSE\",\"sub-1\"]");
        let parsed: RelayMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, msg);
    }

    #[test]
    fn closed_round_trip() {
        let msg = RelayMessage::Closed {
            subscription_id: sub(),
            message: "auth-required: please authenticate".to_owned(),
        };
        let json = serde_json::to_string(&msg).unwrap();
        let parsed: RelayMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, msg);
    }

    #[test]
    fn notice_round_trip() {
        let msg = RelayMessage::Notice("welcome".to_owned());
        let json = serde_json::to_string(&msg).unwrap();
        assert_eq!(json, "[\"NOTICE\",\"welcome\"]");
        let parsed: RelayMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, msg);
    }

    #[test]
    fn auth_challenge_round_trip() {
        let msg = RelayMessage::Auth("challenge-string".to_owned());
        let json = serde_json::to_string(&msg).unwrap();
        let parsed: RelayMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, msg);
    }

    #[test]
    fn count_round_trip() {
        let msg = RelayMessage::Count {
            subscription_id: sub(),
            count: 42,
        };
        let json = serde_json::to_string(&msg).unwrap();
        assert_eq!(json, "[\"COUNT\",\"sub-1\",{\"count\":42}]");
        let parsed: RelayMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, msg);
    }

    #[test]
    fn machine_readable_prefix_parses() {
        assert_eq!(
            MachineReadablePrefix::from_reason("blocked: spam"),
            Some(MachineReadablePrefix::Blocked)
        );
        assert_eq!(
            MachineReadablePrefix::from_reason("auth-required: please"),
            Some(MachineReadablePrefix::AuthRequired)
        );
        assert_eq!(
            MachineReadablePrefix::from_reason("mute: nobody listening"),
            Some(MachineReadablePrefix::Mute)
        );
        assert!(MachineReadablePrefix::from_reason("no prefix").is_none());
        assert!(MachineReadablePrefix::from_reason("unknown: thing").is_none());
    }

    #[test]
    fn ok_round_trips_mute_prefix() {
        let msg = RelayMessage::Ok {
            event_id: signed_event().id,
            accepted: false,
            message: "mute: nobody was listening".to_owned(),
        };
        let json = serde_json::to_string(&msg).unwrap();
        let parsed: RelayMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, msg);
    }

    #[test]
    fn ok_rejects_missing_message_per_nip01() {
        // NIP-01: "The 4th parameter MUST always be present"
        let json = format!(r#"["OK","{}",true]"#, signed_event().id.to_hex());
        let err = serde_json::from_str::<RelayMessage>(&json).unwrap_err();
        assert!(err.to_string().contains("missing message"));
    }

    #[test]
    fn unknown_tag_rejected() {
        let json = "[\"WAT\",\"x\"]";
        let err = serde_json::from_str::<RelayMessage>(json).unwrap_err();
        assert!(err.to_string().contains("unknown relay message tag"));
    }

    #[test]
    fn neg_msg_round_trip() {
        let msg = RelayMessage::NegMsg {
            subscription_id: sub(),
            message: "deadbeef".to_owned(),
        };
        let json = serde_json::to_string(&msg).unwrap();
        assert_eq!(json, "[\"NEG-MSG\",\"sub-1\",\"deadbeef\"]");
        let parsed: RelayMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, msg);
    }

    #[test]
    fn neg_err_round_trip() {
        let msg = RelayMessage::NegErr {
            subscription_id: sub(),
            message: "blocked: spam".to_owned(),
        };
        let json = serde_json::to_string(&msg).unwrap();
        let parsed: RelayMessage = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, msg);
    }

    #[test]
    fn neg_msg_missing_payload_rejected() {
        let json = "[\"NEG-MSG\",\"sub-1\"]";
        let err = serde_json::from_str::<RelayMessage>(json).unwrap_err();
        assert!(err.to_string().contains("missing message"));
    }
}