Skip to main content

stratum_node_core/
event.rs

1//! Nostr events (NIP-01): parsing, event-ID recomputation and BIP-340
2//! verification.
3
4use std::fmt;
5
6use serde::de::value::MapAccessDeserializer;
7use serde::de::{MapAccess, Visitor};
8use serde::{Deserialize, Deserializer, Serialize, Serializer};
9use sha2::{Digest, Sha256};
10
11use crate::did::DidNostr;
12use crate::encoding;
13use crate::id::{EventId, UnixTime};
14
15/// An event that has not been signed yet: kind, tags, content and creation
16/// time.
17///
18/// Sign it with [`NostrSecretKey::sign_event`](crate::NostrSecretKey::sign_event).
19///
20/// # Examples
21///
22/// ```
23/// use stratum_node_core::{NostrSecretKey, UnixTime, UnsignedEvent};
24///
25/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
26/// let key = NostrSecretKey::from_hex(&"01".repeat(32))?;
27/// let unsigned = UnsignedEvent::new(30078, UnixTime::from_secs(1_700_000_000))
28///     .with_tag(["d", "stratum/backup"])
29///     .with_content("{}");
30/// let event = key.sign_event(&unsigned, &[0u8; 32])?;
31/// assert_eq!(event.author(), key.public());
32/// assert_eq!(event.kind(), 30078);
33/// # Ok(())
34/// # }
35/// ```
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct UnsignedEvent {
38    kind: u16,
39    created_at: UnixTime,
40    tags: Vec<Vec<String>>,
41    content: String,
42}
43
44impl UnsignedEvent {
45    /// Starts an event of `kind` created at `created_at`, with no tags and
46    /// empty content.
47    pub fn new(kind: u16, created_at: UnixTime) -> Self {
48        Self {
49            kind,
50            created_at,
51            tags: Vec::new(),
52            content: String::new(),
53        }
54    }
55
56    /// Appends one tag, given as its elements in order.
57    ///
58    /// NIP-01 requires every tag to have at least one element. An empty tag
59    /// is kept here, but [`NostrSecretKey::sign_event`] refuses to sign the
60    /// event with [`SignError::EmptyTag`].
61    ///
62    /// [`NostrSecretKey::sign_event`]: crate::NostrSecretKey::sign_event
63    /// [`SignError::EmptyTag`]: crate::SignError::EmptyTag
64    #[must_use]
65    pub fn with_tag<I, S>(mut self, tag: I) -> Self
66    where
67        I: IntoIterator<Item = S>,
68        S: Into<String>,
69    {
70        self.tags.push(tag.into_iter().map(Into::into).collect());
71        self
72    }
73
74    /// Replaces the content.
75    #[must_use]
76    pub fn with_content(mut self, content: impl Into<String>) -> Self {
77        self.content = content.into();
78        self
79    }
80
81    /// Returns the event kind.
82    pub fn kind(&self) -> u16 {
83        self.kind
84    }
85
86    /// Returns the creation time.
87    pub fn created_at(&self) -> UnixTime {
88        self.created_at
89    }
90
91    /// Returns the tags in order.
92    pub fn tags(&self) -> &[Vec<String>] {
93        &self.tags
94    }
95
96    /// Returns the content.
97    pub fn content(&self) -> &str {
98        &self.content
99    }
100
101    /// Returns `true` when the content and tags avoid the control characters
102    /// this crate cannot serialise as NIP-01 requires.
103    pub(crate) fn is_supported_text(&self) -> bool {
104        is_supported_text(&self.tags, &self.content)
105    }
106
107    /// Returns `true` when some tag has no elements, which NIP-01 forbids.
108    pub(crate) fn has_empty_tag(&self) -> bool {
109        has_empty_tag(&self.tags)
110    }
111
112    /// Computes the NIP-01 event ID this event would have if signed by
113    /// `author`. The caller must have checked [`Self::is_supported_text`].
114    pub(crate) fn id_for(&self, author: &DidNostr) -> EventId {
115        compute_id(
116            author,
117            self.created_at,
118            self.kind,
119            &self.tags,
120            &self.content,
121        )
122    }
123
124    /// Attaches an author and a signature, without verifying them. Only the
125    /// signing path, which has just produced the signature, calls this.
126    pub(crate) fn into_signed(self, id: EventId, author: DidNostr, sig: [u8; 64]) -> SignedEvent {
127        SignedEvent {
128            id,
129            author,
130            created_at: self.created_at,
131            kind: self.kind,
132            tags: self.tags,
133            content: self.content,
134            sig,
135        }
136    }
137}
138
139/// A Nostr event whose event ID and BIP-340 signature have been verified.
140///
141/// The only ways to obtain one are [`SignedEvent::from_json`], serde
142/// deserialisation (which runs the same checks) and signing with
143/// [`NostrSecretKey::sign_event`](crate::NostrSecretKey::sign_event). Holding
144/// a `SignedEvent` therefore means its [`author`](Self::author) signed exactly
145/// these fields. Only the JSON object form is accepted: a positional array,
146/// unknown fields, duplicate fields and empty tags are rejected.
147///
148/// The serde implementations target self-describing formats such as JSON:
149/// deserialisation accepts only a map, so formats that write structs as bare
150/// sequences (bincode, postcard and similar) cannot read an event back.
151///
152/// Verification says nothing about freshness or single use; see
153/// [`verify_request`](crate::verify_request) for the HTTP profile.
154///
155/// # Character restriction
156///
157/// NIP-01 defines the event ID over a JSON serialisation that escapes only
158/// `"`, `\`, line feed, carriage return, tab, backspace and form feed, and
159/// writes every other character verbatim. This crate serialises the ID
160/// preimage with `serde_json`, which agrees with NIP-01 on all of those but
161/// writes the remaining control characters (U+0000 to U+001F other than the
162/// five named) as `\u00XX`. Rather than hand-write a second JSON encoder,
163/// this crate refuses to parse, or sign, any event whose `content` or tags
164/// contain one of those characters ([`ParseEventError::UnsupportedCharacter`],
165/// [`SignError::UnsupportedCharacter`](crate::SignError::UnsupportedCharacter)).
166/// Every other Unicode text, including U+007F and U+2028, is supported.
167///
168/// # Examples
169///
170/// ```
171/// use stratum_node_core::{NostrSecretKey, SignedEvent, UnixTime, UnsignedEvent};
172///
173/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
174/// let key = NostrSecretKey::from_hex(&"02".repeat(32))?;
175/// let event = key.sign_event(&UnsignedEvent::new(1, UnixTime::from_secs(1)), &[0u8; 32])?;
176/// let parsed = SignedEvent::from_json(event.to_json().as_bytes())?;
177/// assert_eq!(parsed, event);
178/// # Ok(())
179/// # }
180/// ```
181#[derive(Clone, PartialEq, Eq)]
182pub struct SignedEvent {
183    id: EventId,
184    author: DidNostr,
185    created_at: UnixTime,
186    kind: u16,
187    tags: Vec<Vec<String>>,
188    content: String,
189    sig: [u8; 64],
190}
191
192impl SignedEvent {
193    /// Parses NIP-01 event JSON and verifies its ID and signature.
194    ///
195    /// # Errors
196    ///
197    /// Returns a [`ParseEventError`] naming the first check that failed.
198    pub fn from_json(json: &[u8]) -> Result<Self, ParseEventError> {
199        ParsedEvent::from_json(json)?.verify()
200    }
201
202    /// Serialises the event as NIP-01 JSON with fields in the order `id`,
203    /// `pubkey`, `created_at`, `kind`, `tags`, `content`, `sig`.
204    ///
205    /// # Panics
206    ///
207    /// Does not panic: `serde_json` has no failure path for a struct of
208    /// strings, integers and string arrays.
209    pub fn to_json(&self) -> String {
210        serde_json::to_string(&self.to_raw())
211            .expect("serde_json cannot fail on strings, integers and string arrays")
212    }
213
214    /// Returns the event ID.
215    pub fn id(&self) -> EventId {
216        self.id
217    }
218
219    /// Returns the signer, from the event's `pubkey` field.
220    pub fn author(&self) -> DidNostr {
221        self.author
222    }
223
224    /// Returns the claimed creation time, as signed. It is not checked
225    /// against any clock here.
226    pub fn created_at(&self) -> UnixTime {
227        self.created_at
228    }
229
230    /// Returns the event kind.
231    pub fn kind(&self) -> u16 {
232        self.kind
233    }
234
235    /// Returns the tags in order.
236    pub fn tags(&self) -> &[Vec<String>] {
237        &self.tags
238    }
239
240    /// Returns the content.
241    pub fn content(&self) -> &str {
242        &self.content
243    }
244
245    /// Returns the 64-byte BIP-340 signature.
246    pub fn signature(&self) -> &[u8; 64] {
247        &self.sig
248    }
249
250    fn to_raw(&self) -> RawEvent {
251        RawEvent {
252            id: self.id.to_hex(),
253            pubkey: self.author.to_hex(),
254            created_at: self.created_at.as_secs(),
255            kind: self.kind,
256            tags: self.tags.clone(),
257            content: self.content.clone(),
258            sig: hex::encode(self.sig),
259        }
260    }
261}
262
263impl fmt::Debug for SignedEvent {
264    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265        f.debug_struct("SignedEvent")
266            .field("id", &self.id)
267            .field("author", &self.author)
268            .field("created_at", &self.created_at)
269            .field("kind", &self.kind)
270            .field("tags", &self.tags)
271            .field("content", &self.content)
272            .field("sig", &hex::encode(self.sig))
273            .finish()
274    }
275}
276
277impl Serialize for SignedEvent {
278    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
279        self.to_raw().serialize(serializer)
280    }
281}
282
283impl<'de> Deserialize<'de> for SignedEvent {
284    /// Deserialises and verifies, with the same checks as
285    /// [`SignedEvent::from_json`]. Only a map (a JSON object) is accepted.
286    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
287        let raw = deserialize_object(deserializer)?;
288        ParsedEvent::from_raw(raw)
289            .and_then(ParsedEvent::verify)
290            .map_err(serde::de::Error::custom)
291    }
292}
293
294/// An event that has passed every structural check but whose event ID and
295/// signature have not been checked yet.
296///
297/// Splitting parsing from verification lets a caller read the claimed author
298/// before spending a signature verification on it. [`ParsedEvent::verify`]
299/// runs the remaining checks in the same order [`SignedEvent::from_json`]
300/// always has, so the two paths report the same error for the same input.
301#[derive(Debug, Clone)]
302pub(crate) struct ParsedEvent {
303    claimed_id: [u8; 32],
304    author: DidNostr,
305    created_at: UnixTime,
306    kind: u16,
307    tags: Vec<Vec<String>>,
308    content: String,
309    sig: [u8; 64],
310}
311
312impl ParsedEvent {
313    /// Parses NIP-01 event JSON and applies the structural checks only.
314    pub(crate) fn from_json(json: &[u8]) -> Result<Self, ParseEventError> {
315        let mut deserializer = serde_json::Deserializer::from_slice(json);
316        let raw = deserialize_object(&mut deserializer)
317            .and_then(|raw| deserializer.end().map(|()| raw))
318            .map_err(|_| ParseEventError::MalformedJson)?;
319        Self::from_raw(raw)
320    }
321
322    /// Checks field encodings, the public key, empty tags and the supported
323    /// character set, in that order.
324    fn from_raw(raw: RawEvent) -> Result<Self, ParseEventError> {
325        let claimed_id =
326            encoding::decode_lower_hex::<32>(&raw.id).ok_or(ParseEventError::InvalidId)?;
327        let author = DidNostr::from_hex(&raw.pubkey).map_err(|_| ParseEventError::InvalidPubkey)?;
328        let sig =
329            encoding::decode_lower_hex::<64>(&raw.sig).ok_or(ParseEventError::InvalidSignature)?;
330        if has_empty_tag(&raw.tags) {
331            return Err(ParseEventError::EmptyTag);
332        }
333        if !is_supported_text(&raw.tags, &raw.content) {
334            return Err(ParseEventError::UnsupportedCharacter);
335        }
336        Ok(Self {
337            claimed_id,
338            author,
339            created_at: UnixTime::from_secs(raw.created_at),
340            kind: raw.kind,
341            tags: raw.tags,
342            content: raw.content,
343            sig,
344        })
345    }
346
347    /// Returns the author named by the `pubkey` field. Nothing shows yet that
348    /// this key signed the event.
349    pub(crate) fn claimed_author(&self) -> DidNostr {
350        self.author
351    }
352
353    /// Returns the event ID as the `id` field states it, not recomputed.
354    pub(crate) fn claimed_id(&self) -> EventId {
355        EventId::from_bytes(self.claimed_id)
356    }
357
358    /// Recomputes the event ID, compares it with the claimed one and verifies
359    /// the BIP-340 signature over it.
360    pub(crate) fn verify(self) -> Result<SignedEvent, ParseEventError> {
361        let id = compute_id(
362            &self.author,
363            self.created_at,
364            self.kind,
365            &self.tags,
366            &self.content,
367        );
368        if id.as_bytes() != &self.claimed_id {
369            return Err(ParseEventError::IdMismatch);
370        }
371        if !crate::schnorr::verify(self.author.as_bytes(), id.as_bytes(), &self.sig) {
372            return Err(ParseEventError::BadSignature);
373        }
374        Ok(SignedEvent {
375            id,
376            author: self.author,
377            created_at: self.created_at,
378            kind: self.kind,
379            tags: self.tags,
380            content: self.content,
381            sig: self.sig,
382        })
383    }
384}
385
386/// The reasons event JSON can fail to parse or verify.
387#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
388#[non_exhaustive]
389pub enum ParseEventError {
390    /// The input is not a single JSON object with exactly the seven NIP-01
391    /// fields of the right types. A positional array, duplicate and unknown
392    /// fields and trailing data are rejected, and `kind` must fit in 16 bits.
393    #[error("malformed event json")]
394    MalformedJson,
395    /// The `id` field is not 64 lowercase hexadecimal digits.
396    #[error("event id is not 64 lowercase hex digits")]
397    InvalidId,
398    /// The `pubkey` field is not 64 lowercase hex digits naming a valid
399    /// x-only point.
400    #[error("event pubkey is not a valid lowercase x-only public key")]
401    InvalidPubkey,
402    /// The `sig` field is not 128 lowercase hexadecimal digits.
403    #[error("event signature is not 128 lowercase hex digits")]
404    InvalidSignature,
405    /// A tag has no elements; NIP-01 requires at least one.
406    #[error("event has an empty tag")]
407    EmptyTag,
408    /// The content or a tag contains a control character outside the set
409    /// NIP-01 escapes by name; see
410    /// [`SignedEvent`](SignedEvent#character-restriction).
411    #[error("event text contains an unsupported control character")]
412    UnsupportedCharacter,
413    /// The `id` field is not the NIP-01 hash of the event.
414    #[error("event id does not match the event")]
415    IdMismatch,
416    /// The signature does not verify over the event ID with the `pubkey`.
417    #[error("event signature does not verify")]
418    BadSignature,
419}
420
421/// The wire shape of a NIP-01 event, used for both directions.
422///
423/// The derived `Deserialize` also accepts a positional sequence, so never call
424/// it directly: go through [`deserialize_object`], which hands it only a map.
425#[derive(Serialize, Deserialize)]
426#[serde(deny_unknown_fields)]
427struct RawEvent {
428    id: String,
429    pubkey: String,
430    created_at: u64,
431    kind: u16,
432    tags: Vec<Vec<String>>,
433    content: String,
434    sig: String,
435}
436
437/// Deserialises a [`RawEvent`] from a map only, refusing the positional
438/// sequence form serde derives for structs. The derived map visitor still
439/// rejects unknown, duplicate and missing fields.
440fn deserialize_object<'de, D: Deserializer<'de>>(deserializer: D) -> Result<RawEvent, D::Error> {
441    deserializer.deserialize_map(ObjectOnly)
442}
443
444/// The visitor behind [`deserialize_object`]: it implements `visit_map` and
445/// nothing else, so every other input shape is an `invalid_type` error.
446struct ObjectOnly;
447
448impl<'de> Visitor<'de> for ObjectOnly {
449    type Value = RawEvent;
450
451    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
452        f.write_str("a nip-01 event object")
453    }
454
455    fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<RawEvent, A::Error> {
456        RawEvent::deserialize(MapAccessDeserializer::new(map))
457    }
458}
459
460/// Returns `true` when some tag has no elements.
461fn has_empty_tag(tags: &[Vec<String>]) -> bool {
462    tags.iter().any(Vec::is_empty)
463}
464
465/// Returns `true` when no string contains a control character that
466/// `serde_json` escapes differently from NIP-01.
467fn is_supported_text(tags: &[Vec<String>], content: &str) -> bool {
468    std::iter::once(content)
469        .chain(tags.iter().flatten().map(String::as_str))
470        .all(|text| !text.chars().any(is_unsupported_char))
471}
472
473/// The control characters NIP-01 writes raw but `serde_json` writes as
474/// `\u00XX`: everything below U+0020 except `\b`, `\t`, `\n`, `\f` and `\r`.
475fn is_unsupported_char(c: char) -> bool {
476    c < '\u{20}' && !matches!(c, '\u{08}' | '\t' | '\n' | '\u{0c}' | '\r')
477}
478
479/// Computes `sha256([0, pubkey, created_at, kind, tags, content])` with the
480/// array serialised as compact JSON.
481fn compute_id(
482    author: &DidNostr,
483    created_at: UnixTime,
484    kind: u16,
485    tags: &[Vec<String>],
486    content: &str,
487) -> EventId {
488    let preimage = (
489        0u8,
490        author.to_hex(),
491        created_at.as_secs(),
492        kind,
493        tags,
494        content,
495    );
496    let bytes = serde_json::to_vec(&preimage)
497        .expect("serde_json cannot fail on strings, integers and string arrays");
498    EventId::from_bytes(Sha256::digest(&bytes).into())
499}
500
501#[cfg(test)]
502mod tests {
503    use super::*;
504
505    #[test]
506    fn named_escapes_match_nip01() {
507        let encoded = serde_json::to_string("\"\\\n\r\t\u{08}\u{0c}").expect("serialises");
508        assert_eq!(encoded, r#""\"\\\n\r\t\b\f""#, "serde_json named escapes");
509    }
510
511    #[test]
512    fn other_text_is_written_verbatim() {
513        let text = "é \u{7f} \u{2028} / <>";
514        let encoded = serde_json::to_string(text).expect("serialises");
515        assert_eq!(encoded, format!("\"{text}\""), "no escaping beyond NIP-01");
516    }
517
518    #[test]
519    fn unsupported_characters_are_exactly_the_unnamed_controls() {
520        let unsupported: Vec<u32> = (0u32..0x80)
521            .filter_map(char::from_u32)
522            .filter(|c| is_unsupported_char(*c))
523            .map(u32::from)
524            .collect();
525        let want: Vec<u32> = (0u32..0x20)
526            .filter(|c| ![0x08, 0x09, 0x0a, 0x0c, 0x0d].contains(c))
527            .collect();
528        assert_eq!(unsupported, want, "unsupported set");
529    }
530}