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        let mut deserializer = serde_json::Deserializer::from_slice(json);
200        let raw = deserialize_object(&mut deserializer)
201            .and_then(|raw| deserializer.end().map(|()| raw))
202            .map_err(|_| ParseEventError::MalformedJson)?;
203        Self::from_raw(raw)
204    }
205
206    /// Serialises the event as NIP-01 JSON with fields in the order `id`,
207    /// `pubkey`, `created_at`, `kind`, `tags`, `content`, `sig`.
208    ///
209    /// # Panics
210    ///
211    /// Does not panic: `serde_json` has no failure path for a struct of
212    /// strings, integers and string arrays.
213    pub fn to_json(&self) -> String {
214        serde_json::to_string(&self.to_raw())
215            .expect("serde_json cannot fail on strings, integers and string arrays")
216    }
217
218    /// Returns the event ID.
219    pub fn id(&self) -> EventId {
220        self.id
221    }
222
223    /// Returns the signer, from the event's `pubkey` field.
224    pub fn author(&self) -> DidNostr {
225        self.author
226    }
227
228    /// Returns the claimed creation time, as signed. It is not checked
229    /// against any clock here.
230    pub fn created_at(&self) -> UnixTime {
231        self.created_at
232    }
233
234    /// Returns the event kind.
235    pub fn kind(&self) -> u16 {
236        self.kind
237    }
238
239    /// Returns the tags in order.
240    pub fn tags(&self) -> &[Vec<String>] {
241        &self.tags
242    }
243
244    /// Returns the content.
245    pub fn content(&self) -> &str {
246        &self.content
247    }
248
249    /// Returns the 64-byte BIP-340 signature.
250    pub fn signature(&self) -> &[u8; 64] {
251        &self.sig
252    }
253
254    fn from_raw(raw: RawEvent) -> Result<Self, ParseEventError> {
255        let claimed_id =
256            encoding::decode_lower_hex::<32>(&raw.id).ok_or(ParseEventError::InvalidId)?;
257        let author = DidNostr::from_hex(&raw.pubkey).map_err(|_| ParseEventError::InvalidPubkey)?;
258        let sig =
259            encoding::decode_lower_hex::<64>(&raw.sig).ok_or(ParseEventError::InvalidSignature)?;
260        if has_empty_tag(&raw.tags) {
261            return Err(ParseEventError::EmptyTag);
262        }
263        if !is_supported_text(&raw.tags, &raw.content) {
264            return Err(ParseEventError::UnsupportedCharacter);
265        }
266        let created_at = UnixTime::from_secs(raw.created_at);
267        let id = compute_id(&author, created_at, raw.kind, &raw.tags, &raw.content);
268        if id.as_bytes() != &claimed_id {
269            return Err(ParseEventError::IdMismatch);
270        }
271        if !crate::schnorr::verify(author.as_bytes(), id.as_bytes(), &sig) {
272            return Err(ParseEventError::BadSignature);
273        }
274        Ok(Self {
275            id,
276            author,
277            created_at,
278            kind: raw.kind,
279            tags: raw.tags,
280            content: raw.content,
281            sig,
282        })
283    }
284
285    fn to_raw(&self) -> RawEvent {
286        RawEvent {
287            id: self.id.to_hex(),
288            pubkey: self.author.to_hex(),
289            created_at: self.created_at.as_secs(),
290            kind: self.kind,
291            tags: self.tags.clone(),
292            content: self.content.clone(),
293            sig: hex::encode(self.sig),
294        }
295    }
296}
297
298impl fmt::Debug for SignedEvent {
299    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
300        f.debug_struct("SignedEvent")
301            .field("id", &self.id)
302            .field("author", &self.author)
303            .field("created_at", &self.created_at)
304            .field("kind", &self.kind)
305            .field("tags", &self.tags)
306            .field("content", &self.content)
307            .field("sig", &hex::encode(self.sig))
308            .finish()
309    }
310}
311
312impl Serialize for SignedEvent {
313    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
314        self.to_raw().serialize(serializer)
315    }
316}
317
318impl<'de> Deserialize<'de> for SignedEvent {
319    /// Deserialises and verifies, with the same checks as
320    /// [`SignedEvent::from_json`]. Only a map (a JSON object) is accepted.
321    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
322        let raw = deserialize_object(deserializer)?;
323        Self::from_raw(raw).map_err(serde::de::Error::custom)
324    }
325}
326
327/// The reasons event JSON can fail to parse or verify.
328#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
329#[non_exhaustive]
330pub enum ParseEventError {
331    /// The input is not a single JSON object with exactly the seven NIP-01
332    /// fields of the right types. A positional array, duplicate and unknown
333    /// fields and trailing data are rejected, and `kind` must fit in 16 bits.
334    #[error("malformed event json")]
335    MalformedJson,
336    /// The `id` field is not 64 lowercase hexadecimal digits.
337    #[error("event id is not 64 lowercase hex digits")]
338    InvalidId,
339    /// The `pubkey` field is not 64 lowercase hex digits naming a valid
340    /// x-only point.
341    #[error("event pubkey is not a valid lowercase x-only public key")]
342    InvalidPubkey,
343    /// The `sig` field is not 128 lowercase hexadecimal digits.
344    #[error("event signature is not 128 lowercase hex digits")]
345    InvalidSignature,
346    /// A tag has no elements; NIP-01 requires at least one.
347    #[error("event has an empty tag")]
348    EmptyTag,
349    /// The content or a tag contains a control character outside the set
350    /// NIP-01 escapes by name; see
351    /// [`SignedEvent`](SignedEvent#character-restriction).
352    #[error("event text contains an unsupported control character")]
353    UnsupportedCharacter,
354    /// The `id` field is not the NIP-01 hash of the event.
355    #[error("event id does not match the event")]
356    IdMismatch,
357    /// The signature does not verify over the event ID with the `pubkey`.
358    #[error("event signature does not verify")]
359    BadSignature,
360}
361
362/// The wire shape of a NIP-01 event, used for both directions.
363///
364/// The derived `Deserialize` also accepts a positional sequence, so never call
365/// it directly: go through [`deserialize_object`], which hands it only a map.
366#[derive(Serialize, Deserialize)]
367#[serde(deny_unknown_fields)]
368struct RawEvent {
369    id: String,
370    pubkey: String,
371    created_at: u64,
372    kind: u16,
373    tags: Vec<Vec<String>>,
374    content: String,
375    sig: String,
376}
377
378/// Deserialises a [`RawEvent`] from a map only, refusing the positional
379/// sequence form serde derives for structs. The derived map visitor still
380/// rejects unknown, duplicate and missing fields.
381fn deserialize_object<'de, D: Deserializer<'de>>(deserializer: D) -> Result<RawEvent, D::Error> {
382    deserializer.deserialize_map(ObjectOnly)
383}
384
385/// The visitor behind [`deserialize_object`]: it implements `visit_map` and
386/// nothing else, so every other input shape is an `invalid_type` error.
387struct ObjectOnly;
388
389impl<'de> Visitor<'de> for ObjectOnly {
390    type Value = RawEvent;
391
392    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393        f.write_str("a nip-01 event object")
394    }
395
396    fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<RawEvent, A::Error> {
397        RawEvent::deserialize(MapAccessDeserializer::new(map))
398    }
399}
400
401/// Returns `true` when some tag has no elements.
402fn has_empty_tag(tags: &[Vec<String>]) -> bool {
403    tags.iter().any(Vec::is_empty)
404}
405
406/// Returns `true` when no string contains a control character that
407/// `serde_json` escapes differently from NIP-01.
408fn is_supported_text(tags: &[Vec<String>], content: &str) -> bool {
409    std::iter::once(content)
410        .chain(tags.iter().flatten().map(String::as_str))
411        .all(|text| !text.chars().any(is_unsupported_char))
412}
413
414/// The control characters NIP-01 writes raw but `serde_json` writes as
415/// `\u00XX`: everything below U+0020 except `\b`, `\t`, `\n`, `\f` and `\r`.
416fn is_unsupported_char(c: char) -> bool {
417    c < '\u{20}' && !matches!(c, '\u{08}' | '\t' | '\n' | '\u{0c}' | '\r')
418}
419
420/// Computes `sha256([0, pubkey, created_at, kind, tags, content])` with the
421/// array serialised as compact JSON.
422fn compute_id(
423    author: &DidNostr,
424    created_at: UnixTime,
425    kind: u16,
426    tags: &[Vec<String>],
427    content: &str,
428) -> EventId {
429    let preimage = (
430        0u8,
431        author.to_hex(),
432        created_at.as_secs(),
433        kind,
434        tags,
435        content,
436    );
437    let bytes = serde_json::to_vec(&preimage)
438        .expect("serde_json cannot fail on strings, integers and string arrays");
439    EventId::from_bytes(Sha256::digest(&bytes).into())
440}
441
442#[cfg(test)]
443mod tests {
444    use super::*;
445
446    #[test]
447    fn named_escapes_match_nip01() {
448        let encoded = serde_json::to_string("\"\\\n\r\t\u{08}\u{0c}").expect("serialises");
449        assert_eq!(encoded, r#""\"\\\n\r\t\b\f""#, "serde_json named escapes");
450    }
451
452    #[test]
453    fn other_text_is_written_verbatim() {
454        let text = "é \u{7f} \u{2028} / <>";
455        let encoded = serde_json::to_string(text).expect("serialises");
456        assert_eq!(encoded, format!("\"{text}\""), "no escaping beyond NIP-01");
457    }
458
459    #[test]
460    fn unsupported_characters_are_exactly_the_unnamed_controls() {
461        let unsupported: Vec<u32> = (0u32..0x80)
462            .filter_map(char::from_u32)
463            .filter(|c| is_unsupported_char(*c))
464            .map(u32::from)
465            .collect();
466        let want: Vec<u32> = (0u32..0x20)
467            .filter(|c| ![0x08, 0x09, 0x0a, 0x0c, 0x0d].contains(c))
468            .collect();
469        assert_eq!(unsupported, want, "unsupported set");
470    }
471}