stratum-node-core 0.1.0-alpha.2

Zero-I/O core types for Stratum pod nodes: did:nostr principals, typed identifiers, a strict NIP-98 signed-request verifier and bootstrap claim bodies
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
//! Nostr events (NIP-01): parsing, event-ID recomputation and BIP-340
//! verification.

use std::fmt;

use serde::de::value::MapAccessDeserializer;
use serde::de::{MapAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use sha2::{Digest, Sha256};

use crate::did::DidNostr;
use crate::encoding;
use crate::id::{EventId, UnixTime};

/// An event that has not been signed yet: kind, tags, content and creation
/// time.
///
/// Sign it with [`NostrSecretKey::sign_event`](crate::NostrSecretKey::sign_event).
///
/// # Examples
///
/// ```
/// use stratum_node_core::{NostrSecretKey, UnixTime, UnsignedEvent};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let key = NostrSecretKey::from_hex(&"01".repeat(32))?;
/// let unsigned = UnsignedEvent::new(30078, UnixTime::from_secs(1_700_000_000))
///     .with_tag(["d", "stratum/backup"])
///     .with_content("{}");
/// let event = key.sign_event(&unsigned, &[0u8; 32])?;
/// assert_eq!(event.author(), key.public());
/// assert_eq!(event.kind(), 30078);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnsignedEvent {
    kind: u16,
    created_at: UnixTime,
    tags: Vec<Vec<String>>,
    content: String,
}

impl UnsignedEvent {
    /// Starts an event of `kind` created at `created_at`, with no tags and
    /// empty content.
    pub fn new(kind: u16, created_at: UnixTime) -> Self {
        Self {
            kind,
            created_at,
            tags: Vec::new(),
            content: String::new(),
        }
    }

    /// Appends one tag, given as its elements in order.
    ///
    /// NIP-01 requires every tag to have at least one element. An empty tag
    /// is kept here, but [`NostrSecretKey::sign_event`] refuses to sign the
    /// event with [`SignError::EmptyTag`].
    ///
    /// [`NostrSecretKey::sign_event`]: crate::NostrSecretKey::sign_event
    /// [`SignError::EmptyTag`]: crate::SignError::EmptyTag
    #[must_use]
    pub fn with_tag<I, S>(mut self, tag: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.tags.push(tag.into_iter().map(Into::into).collect());
        self
    }

    /// Replaces the content.
    #[must_use]
    pub fn with_content(mut self, content: impl Into<String>) -> Self {
        self.content = content.into();
        self
    }

    /// Returns the event kind.
    pub fn kind(&self) -> u16 {
        self.kind
    }

    /// Returns the creation time.
    pub fn created_at(&self) -> UnixTime {
        self.created_at
    }

    /// Returns the tags in order.
    pub fn tags(&self) -> &[Vec<String>] {
        &self.tags
    }

    /// Returns the content.
    pub fn content(&self) -> &str {
        &self.content
    }

    /// Returns `true` when the content and tags avoid the control characters
    /// this crate cannot serialise as NIP-01 requires.
    pub(crate) fn is_supported_text(&self) -> bool {
        is_supported_text(&self.tags, &self.content)
    }

    /// Returns `true` when some tag has no elements, which NIP-01 forbids.
    pub(crate) fn has_empty_tag(&self) -> bool {
        has_empty_tag(&self.tags)
    }

    /// Computes the NIP-01 event ID this event would have if signed by
    /// `author`. The caller must have checked [`Self::is_supported_text`].
    pub(crate) fn id_for(&self, author: &DidNostr) -> EventId {
        compute_id(
            author,
            self.created_at,
            self.kind,
            &self.tags,
            &self.content,
        )
    }

    /// Attaches an author and a signature, without verifying them. Only the
    /// signing path, which has just produced the signature, calls this.
    pub(crate) fn into_signed(self, id: EventId, author: DidNostr, sig: [u8; 64]) -> SignedEvent {
        SignedEvent {
            id,
            author,
            created_at: self.created_at,
            kind: self.kind,
            tags: self.tags,
            content: self.content,
            sig,
        }
    }
}

/// A Nostr event whose event ID and BIP-340 signature have been verified.
///
/// The only ways to obtain one are [`SignedEvent::from_json`], serde
/// deserialisation (which runs the same checks) and signing with
/// [`NostrSecretKey::sign_event`](crate::NostrSecretKey::sign_event). Holding
/// a `SignedEvent` therefore means its [`author`](Self::author) signed exactly
/// these fields. Only the JSON object form is accepted: a positional array,
/// unknown fields, duplicate fields and empty tags are rejected.
///
/// The serde implementations target self-describing formats such as JSON:
/// deserialisation accepts only a map, so formats that write structs as bare
/// sequences (bincode, postcard and similar) cannot read an event back.
///
/// Verification says nothing about freshness or single use; see
/// [`verify_request`](crate::verify_request) for the HTTP profile.
///
/// # Character restriction
///
/// NIP-01 defines the event ID over a JSON serialisation that escapes only
/// `"`, `\`, line feed, carriage return, tab, backspace and form feed, and
/// writes every other character verbatim. This crate serialises the ID
/// preimage with `serde_json`, which agrees with NIP-01 on all of those but
/// writes the remaining control characters (U+0000 to U+001F other than the
/// five named) as `\u00XX`. Rather than hand-write a second JSON encoder,
/// this crate refuses to parse, or sign, any event whose `content` or tags
/// contain one of those characters ([`ParseEventError::UnsupportedCharacter`],
/// [`SignError::UnsupportedCharacter`](crate::SignError::UnsupportedCharacter)).
/// Every other Unicode text, including U+007F and U+2028, is supported.
///
/// # Examples
///
/// ```
/// use stratum_node_core::{NostrSecretKey, SignedEvent, UnixTime, UnsignedEvent};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let key = NostrSecretKey::from_hex(&"02".repeat(32))?;
/// let event = key.sign_event(&UnsignedEvent::new(1, UnixTime::from_secs(1)), &[0u8; 32])?;
/// let parsed = SignedEvent::from_json(event.to_json().as_bytes())?;
/// assert_eq!(parsed, event);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, PartialEq, Eq)]
pub struct SignedEvent {
    id: EventId,
    author: DidNostr,
    created_at: UnixTime,
    kind: u16,
    tags: Vec<Vec<String>>,
    content: String,
    sig: [u8; 64],
}

impl SignedEvent {
    /// Parses NIP-01 event JSON and verifies its ID and signature.
    ///
    /// # Errors
    ///
    /// Returns a [`ParseEventError`] naming the first check that failed.
    pub fn from_json(json: &[u8]) -> Result<Self, ParseEventError> {
        ParsedEvent::from_json(json)?.verify()
    }

    /// Serialises the event as NIP-01 JSON with fields in the order `id`,
    /// `pubkey`, `created_at`, `kind`, `tags`, `content`, `sig`.
    ///
    /// # Panics
    ///
    /// Does not panic: `serde_json` has no failure path for a struct of
    /// strings, integers and string arrays.
    pub fn to_json(&self) -> String {
        serde_json::to_string(&self.to_raw())
            .expect("serde_json cannot fail on strings, integers and string arrays")
    }

    /// Returns the event ID.
    pub fn id(&self) -> EventId {
        self.id
    }

    /// Returns the signer, from the event's `pubkey` field.
    pub fn author(&self) -> DidNostr {
        self.author
    }

    /// Returns the claimed creation time, as signed. It is not checked
    /// against any clock here.
    pub fn created_at(&self) -> UnixTime {
        self.created_at
    }

    /// Returns the event kind.
    pub fn kind(&self) -> u16 {
        self.kind
    }

    /// Returns the tags in order.
    pub fn tags(&self) -> &[Vec<String>] {
        &self.tags
    }

    /// Returns the content.
    pub fn content(&self) -> &str {
        &self.content
    }

    /// Returns the 64-byte BIP-340 signature.
    pub fn signature(&self) -> &[u8; 64] {
        &self.sig
    }

    fn to_raw(&self) -> RawEvent {
        RawEvent {
            id: self.id.to_hex(),
            pubkey: self.author.to_hex(),
            created_at: self.created_at.as_secs(),
            kind: self.kind,
            tags: self.tags.clone(),
            content: self.content.clone(),
            sig: hex::encode(self.sig),
        }
    }
}

impl fmt::Debug for SignedEvent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SignedEvent")
            .field("id", &self.id)
            .field("author", &self.author)
            .field("created_at", &self.created_at)
            .field("kind", &self.kind)
            .field("tags", &self.tags)
            .field("content", &self.content)
            .field("sig", &hex::encode(self.sig))
            .finish()
    }
}

impl Serialize for SignedEvent {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.to_raw().serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for SignedEvent {
    /// Deserialises and verifies, with the same checks as
    /// [`SignedEvent::from_json`]. Only a map (a JSON object) is accepted.
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let raw = deserialize_object(deserializer)?;
        ParsedEvent::from_raw(raw)
            .and_then(ParsedEvent::verify)
            .map_err(serde::de::Error::custom)
    }
}

/// An event that has passed every structural check but whose event ID and
/// signature have not been checked yet.
///
/// Splitting parsing from verification lets a caller read the claimed author
/// before spending a signature verification on it. [`ParsedEvent::verify`]
/// runs the remaining checks in the same order [`SignedEvent::from_json`]
/// always has, so the two paths report the same error for the same input.
#[derive(Debug, Clone)]
pub(crate) struct ParsedEvent {
    claimed_id: [u8; 32],
    author: DidNostr,
    created_at: UnixTime,
    kind: u16,
    tags: Vec<Vec<String>>,
    content: String,
    sig: [u8; 64],
}

impl ParsedEvent {
    /// Parses NIP-01 event JSON and applies the structural checks only.
    pub(crate) fn from_json(json: &[u8]) -> Result<Self, ParseEventError> {
        let mut deserializer = serde_json::Deserializer::from_slice(json);
        let raw = deserialize_object(&mut deserializer)
            .and_then(|raw| deserializer.end().map(|()| raw))
            .map_err(|_| ParseEventError::MalformedJson)?;
        Self::from_raw(raw)
    }

    /// Checks field encodings, the public key, empty tags and the supported
    /// character set, in that order.
    fn from_raw(raw: RawEvent) -> Result<Self, ParseEventError> {
        let claimed_id =
            encoding::decode_lower_hex::<32>(&raw.id).ok_or(ParseEventError::InvalidId)?;
        let author = DidNostr::from_hex(&raw.pubkey).map_err(|_| ParseEventError::InvalidPubkey)?;
        let sig =
            encoding::decode_lower_hex::<64>(&raw.sig).ok_or(ParseEventError::InvalidSignature)?;
        if has_empty_tag(&raw.tags) {
            return Err(ParseEventError::EmptyTag);
        }
        if !is_supported_text(&raw.tags, &raw.content) {
            return Err(ParseEventError::UnsupportedCharacter);
        }
        Ok(Self {
            claimed_id,
            author,
            created_at: UnixTime::from_secs(raw.created_at),
            kind: raw.kind,
            tags: raw.tags,
            content: raw.content,
            sig,
        })
    }

    /// Returns the author named by the `pubkey` field. Nothing shows yet that
    /// this key signed the event.
    pub(crate) fn claimed_author(&self) -> DidNostr {
        self.author
    }

    /// Returns the event ID as the `id` field states it, not recomputed.
    pub(crate) fn claimed_id(&self) -> EventId {
        EventId::from_bytes(self.claimed_id)
    }

    /// Recomputes the event ID, compares it with the claimed one and verifies
    /// the BIP-340 signature over it.
    pub(crate) fn verify(self) -> Result<SignedEvent, ParseEventError> {
        let id = compute_id(
            &self.author,
            self.created_at,
            self.kind,
            &self.tags,
            &self.content,
        );
        if id.as_bytes() != &self.claimed_id {
            return Err(ParseEventError::IdMismatch);
        }
        if !crate::schnorr::verify(self.author.as_bytes(), id.as_bytes(), &self.sig) {
            return Err(ParseEventError::BadSignature);
        }
        Ok(SignedEvent {
            id,
            author: self.author,
            created_at: self.created_at,
            kind: self.kind,
            tags: self.tags,
            content: self.content,
            sig: self.sig,
        })
    }
}

/// The reasons event JSON can fail to parse or verify.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParseEventError {
    /// The input is not a single JSON object with exactly the seven NIP-01
    /// fields of the right types. A positional array, duplicate and unknown
    /// fields and trailing data are rejected, and `kind` must fit in 16 bits.
    #[error("malformed event json")]
    MalformedJson,
    /// The `id` field is not 64 lowercase hexadecimal digits.
    #[error("event id is not 64 lowercase hex digits")]
    InvalidId,
    /// The `pubkey` field is not 64 lowercase hex digits naming a valid
    /// x-only point.
    #[error("event pubkey is not a valid lowercase x-only public key")]
    InvalidPubkey,
    /// The `sig` field is not 128 lowercase hexadecimal digits.
    #[error("event signature is not 128 lowercase hex digits")]
    InvalidSignature,
    /// A tag has no elements; NIP-01 requires at least one.
    #[error("event has an empty tag")]
    EmptyTag,
    /// The content or a tag contains a control character outside the set
    /// NIP-01 escapes by name; see
    /// [`SignedEvent`](SignedEvent#character-restriction).
    #[error("event text contains an unsupported control character")]
    UnsupportedCharacter,
    /// The `id` field is not the NIP-01 hash of the event.
    #[error("event id does not match the event")]
    IdMismatch,
    /// The signature does not verify over the event ID with the `pubkey`.
    #[error("event signature does not verify")]
    BadSignature,
}

/// The wire shape of a NIP-01 event, used for both directions.
///
/// The derived `Deserialize` also accepts a positional sequence, so never call
/// it directly: go through [`deserialize_object`], which hands it only a map.
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawEvent {
    id: String,
    pubkey: String,
    created_at: u64,
    kind: u16,
    tags: Vec<Vec<String>>,
    content: String,
    sig: String,
}

/// Deserialises a [`RawEvent`] from a map only, refusing the positional
/// sequence form serde derives for structs. The derived map visitor still
/// rejects unknown, duplicate and missing fields.
fn deserialize_object<'de, D: Deserializer<'de>>(deserializer: D) -> Result<RawEvent, D::Error> {
    deserializer.deserialize_map(ObjectOnly)
}

/// The visitor behind [`deserialize_object`]: it implements `visit_map` and
/// nothing else, so every other input shape is an `invalid_type` error.
struct ObjectOnly;

impl<'de> Visitor<'de> for ObjectOnly {
    type Value = RawEvent;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("a nip-01 event object")
    }

    fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<RawEvent, A::Error> {
        RawEvent::deserialize(MapAccessDeserializer::new(map))
    }
}

/// Returns `true` when some tag has no elements.
fn has_empty_tag(tags: &[Vec<String>]) -> bool {
    tags.iter().any(Vec::is_empty)
}

/// Returns `true` when no string contains a control character that
/// `serde_json` escapes differently from NIP-01.
fn is_supported_text(tags: &[Vec<String>], content: &str) -> bool {
    std::iter::once(content)
        .chain(tags.iter().flatten().map(String::as_str))
        .all(|text| !text.chars().any(is_unsupported_char))
}

/// The control characters NIP-01 writes raw but `serde_json` writes as
/// `\u00XX`: everything below U+0020 except `\b`, `\t`, `\n`, `\f` and `\r`.
fn is_unsupported_char(c: char) -> bool {
    c < '\u{20}' && !matches!(c, '\u{08}' | '\t' | '\n' | '\u{0c}' | '\r')
}

/// Computes `sha256([0, pubkey, created_at, kind, tags, content])` with the
/// array serialised as compact JSON.
fn compute_id(
    author: &DidNostr,
    created_at: UnixTime,
    kind: u16,
    tags: &[Vec<String>],
    content: &str,
) -> EventId {
    let preimage = (
        0u8,
        author.to_hex(),
        created_at.as_secs(),
        kind,
        tags,
        content,
    );
    let bytes = serde_json::to_vec(&preimage)
        .expect("serde_json cannot fail on strings, integers and string arrays");
    EventId::from_bytes(Sha256::digest(&bytes).into())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn named_escapes_match_nip01() {
        let encoded = serde_json::to_string("\"\\\n\r\t\u{08}\u{0c}").expect("serialises");
        assert_eq!(encoded, r#""\"\\\n\r\t\b\f""#, "serde_json named escapes");
    }

    #[test]
    fn other_text_is_written_verbatim() {
        let text = "é \u{7f} \u{2028} / <>";
        let encoded = serde_json::to_string(text).expect("serialises");
        assert_eq!(encoded, format!("\"{text}\""), "no escaping beyond NIP-01");
    }

    #[test]
    fn unsupported_characters_are_exactly_the_unnamed_controls() {
        let unsupported: Vec<u32> = (0u32..0x80)
            .filter_map(char::from_u32)
            .filter(|c| is_unsupported_char(*c))
            .map(u32::from)
            .collect();
        let want: Vec<u32> = (0u32..0x20)
            .filter(|c| ![0x08, 0x09, 0x0a, 0x0c, 0x0d].contains(c))
            .collect();
        assert_eq!(unsupported, want, "unsupported set");
    }
}