nostr 0.45.0-alpha.1

Rust implementation of the Nostr protocol.
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
// Copyright (c) 2022-2023 Yuki Kishimoto
// Copyright (c) 2023-2025 Rust Nostr Developers
// Distributed under the MIT software license

//! NIP-88: Polls
//!
//! <https://github.com/nostr-protocol/nips/blob/master/88.md>

use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::fmt;
use core::num::ParseIntError;
use core::str::FromStr;

use super::util::{take_and_parse_from_str, take_relay_url, take_string, take_timestamp};
use crate::event::tag::{Tag, TagCodec, TagCodecError, impl_tag_codec_conversions};
use crate::types::url;
use crate::{Event, EventBuilder, EventId, Kind, RelayUrl, Timestamp};

const ENDS_AT: &str = "endsAt";
const POLL_TYPE: &str = "polltype";
const POLL_OPTION: &str = "option";
const POLL_RESPONSE: &str = "response";
const RELAY: &str = "relay";

/// NIP88 error
#[derive(Debug, PartialEq, Eq)]
pub enum Error {
    /// Url error
    Url(url::Error),
    /// Parse Int error
    ParseInt(ParseIntError),
    /// Codec error
    Codec(TagCodecError),
    /// Unknown poll type
    UnknownPollType,
}

impl core::error::Error for Error {}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Url(e) => e.fmt(f),
            Self::ParseInt(e) => e.fmt(f),
            Self::Codec(e) => e.fmt(f),
            Self::UnknownPollType => f.write_str("unknown poll type"),
        }
    }
}

impl From<url::Error> for Error {
    fn from(e: url::Error) -> Self {
        Self::Url(e)
    }
}

impl From<ParseIntError> for Error {
    fn from(e: ParseIntError) -> Self {
        Self::ParseInt(e)
    }
}

impl From<TagCodecError> for Error {
    fn from(e: TagCodecError) -> Self {
        Self::Codec(e)
    }
}

/// Poll type
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PollType {
    /// Single choice
    SingleChoice,
    /// Multiple choice
    MultipleChoice,
}

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

impl PollType {
    /// Get as `&str`
    pub fn as_str(&self) -> &str {
        match self {
            Self::SingleChoice => "singlechoice",
            Self::MultipleChoice => "multiplechoice",
        }
    }
}

impl FromStr for PollType {
    type Err = Error;

    fn from_str(poll_type: &str) -> Result<Self, Self::Err> {
        match poll_type {
            "singlechoice" => Ok(Self::SingleChoice),
            "multiplechoice" => Ok(Self::MultipleChoice),
            _ => Err(Error::UnknownPollType),
        }
    }
}

/// Poll option
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PollOption {
    /// Option ID
    pub id: String,
    /// Option label
    pub text: String,
}

/// Standardized NIP-88 tags
///
/// <https://github.com/nostr-protocol/nips/blob/master/88.md>
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Nip88Tag {
    /// Poll option
    PollOption(PollOption),
    /// Poll response
    PollResponse(String),
    /// Poll type
    PollType(PollType),
    /// Relay URL
    Relay(RelayUrl),
    /// Poll expiration timestamp
    PollEndsAt(Timestamp),
}

impl TagCodec for Nip88Tag {
    type Error = Error;

    fn parse<I, S>(tag: I) -> Result<Self, Self::Error>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let mut iter = tag.into_iter();
        let kind: S = iter.next().ok_or(TagCodecError::missing_tag_kind())?;

        match kind.as_ref() {
            POLL_OPTION => Ok(Self::PollOption(PollOption {
                id: take_string(&mut iter, "poll ID")?,
                text: take_string(&mut iter, "poll option text")?,
            })),
            POLL_RESPONSE => Ok(Self::PollResponse(take_string(&mut iter, "poll response")?)),
            POLL_TYPE => {
                let poll_type: PollType =
                    take_and_parse_from_str::<_, _, _, Error>(&mut iter, "poll type")?;
                Ok(Self::PollType(poll_type))
            }
            RELAY => {
                let relay: RelayUrl = take_relay_url::<_, _, Error>(&mut iter)?;
                Ok(Self::Relay(relay))
            }
            ENDS_AT => {
                let timestamp: Timestamp = take_timestamp::<_, _, Error>(&mut iter)?;
                Ok(Self::PollEndsAt(timestamp))
            }
            _ => Err(TagCodecError::Unknown.into()),
        }
    }

    fn to_tag(&self) -> Tag {
        match self {
            Self::PollOption(option) => Tag::new(vec![
                String::from(POLL_OPTION),
                option.id.clone(),
                option.text.clone(),
            ]),
            Self::PollResponse(response) => {
                Tag::new(vec![String::from(POLL_RESPONSE), response.clone()])
            }
            Self::PollType(poll_type) => {
                Tag::new(vec![String::from(POLL_TYPE), poll_type.to_string()])
            }
            Self::Relay(relay) => Tag::new(vec![String::from(RELAY), relay.to_string()]),
            Self::PollEndsAt(timestamp) => {
                Tag::new(vec![String::from(ENDS_AT), timestamp.to_string()])
            }
        }
    }
}

impl_tag_codec_conversions!(Nip88Tag);

/// Poll
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Poll {
    /// Poll title
    pub title: String,
    /// Poll type
    pub r#type: PollType,
    /// Poll options
    pub options: Vec<PollOption>,
    /// Relays
    pub relays: Vec<RelayUrl>,
    /// Optionally, when the poll ends
    pub ends_at: Option<Timestamp>,
}

impl Poll {
    /// Parse poll data from an [`Event`].
    pub fn from_event(event: &Event) -> Result<Self, Error> {
        let mut poll_type: PollType = PollType::SingleChoice;
        let mut options: Vec<PollOption> = Vec::new();
        let mut relays: Vec<RelayUrl> = Vec::new();
        let mut ends_at: Option<Timestamp> = None;

        for tag in event.tags.iter() {
            match Nip88Tag::try_from(tag) {
                Ok(Nip88Tag::PollType(value)) => poll_type = value,
                Ok(Nip88Tag::PollOption(option)) => options.push(option),
                Ok(Nip88Tag::Relay(url)) => relays.push(url),
                Ok(Nip88Tag::PollEndsAt(timestamp)) => ends_at = Some(timestamp),
                Ok(Nip88Tag::PollResponse(..)) | Err(Error::Codec(TagCodecError::Unknown)) => (),
                Err(Error::UnknownPollType)
                | Err(Error::Codec(TagCodecError::Missing("poll type"))) => (),
                Err(e) => return Err(e),
            }
        }

        Ok(Self {
            title: event.content.clone(),
            r#type: poll_type,
            options,
            relays,
            ends_at,
        })
    }

    #[allow(clippy::wrong_self_convention)]
    pub(crate) fn to_event_builder(self) -> EventBuilder {
        let mut tags: Vec<Tag> = Vec::with_capacity(1 + self.options.len() + self.relays.len());

        tags.push(Nip88Tag::PollType(self.r#type).to_tag());

        for option in self.options.into_iter() {
            tags.push(Nip88Tag::PollOption(option).to_tag());
        }

        for url in self.relays.into_iter() {
            tags.push(Nip88Tag::Relay(url).to_tag());
        }

        if let Some(timestamp) = self.ends_at {
            tags.push(Nip88Tag::PollEndsAt(timestamp).to_tag());
        }

        EventBuilder::new(Kind::Poll, self.title).tags(tags)
    }
}

/// Poll response
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PollResponse {
    /// Single choice
    SingleChoice {
        /// Event ID of poll event
        poll_id: EventId,
        /// Response
        response: String,
    },
    /// Multiple choice
    MultipleChoice {
        /// Event ID of poll event
        poll_id: EventId,
        /// Responses
        responses: Vec<String>,
    },
}

impl PollResponse {
    #[allow(clippy::wrong_self_convention)]
    pub(crate) fn to_event_builder(self) -> EventBuilder {
        let tags: Vec<Tag> = match self {
            Self::SingleChoice { poll_id, response } => {
                vec![
                    Tag::event(poll_id),
                    Nip88Tag::PollResponse(response).to_tag(),
                ]
            }
            Self::MultipleChoice { poll_id, responses } => {
                let mut tags: Vec<Tag> = Vec::with_capacity(1 + responses.len());

                tags.push(Tag::event(poll_id));

                for response in responses.into_iter() {
                    tags.push(Nip88Tag::PollResponse(response).to_tag());
                }

                tags
            }
        };

        EventBuilder::new(Kind::PollResponse, "").tags(tags)
    }
}

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

    #[test]
    fn test_poll_type() {
        // Serialization
        assert_eq!(PollType::SingleChoice.as_str(), "singlechoice");
        assert_eq!(PollType::MultipleChoice.as_str(), "multiplechoice");

        // Deserialization
        assert_eq!(
            PollType::from_str("singlechoice").unwrap(),
            PollType::SingleChoice
        );
        assert_eq!(
            PollType::from_str("multiplechoice").unwrap(),
            PollType::MultipleChoice
        );
        assert!(PollType::from_str("unknown").is_err());
    }

    #[test]
    fn test_standardized_poll_tags() {
        let option = Nip88Tag::parse(["option", "qj518h583", "Yay"]).unwrap();
        assert_eq!(
            option,
            Nip88Tag::PollOption(PollOption {
                id: "qj518h583".to_string(),
                text: "Yay".to_string(),
            })
        );
        assert_eq!(
            option.to_tag(),
            Tag::parse(["option", "qj518h583", "Yay"]).unwrap()
        );

        let poll_type = Nip88Tag::parse(["polltype", "multiplechoice"]).unwrap();
        assert_eq!(poll_type, Nip88Tag::PollType(PollType::MultipleChoice));
        assert_eq!(
            poll_type.to_tag(),
            Tag::parse(["polltype", "multiplechoice"]).unwrap()
        );

        let relay = RelayUrl::parse("wss://relay.damus.io").unwrap();
        let relay_tag = Nip88Tag::parse(["relay", "wss://relay.damus.io"]).unwrap();
        assert_eq!(relay_tag, Nip88Tag::Relay(relay.clone()));
        assert_eq!(
            relay_tag.to_tag(),
            Tag::parse(["relay", relay.as_str()]).unwrap()
        );

        let ends_at = Nip88Tag::parse(["endsAt", "1788888888"]).unwrap();
        assert_eq!(
            ends_at,
            Nip88Tag::PollEndsAt(Timestamp::from_secs(1788888888))
        );
        assert_eq!(
            ends_at.to_tag(),
            Tag::parse(["endsAt", "1788888888"]).unwrap()
        );

        let response = Nip88Tag::parse(["response", "qj518h583"]).unwrap();
        assert_eq!(response, Nip88Tag::PollResponse("qj518h583".to_string()));
        assert_eq!(
            response.to_tag(),
            Tag::parse(["response", "qj518h583"]).unwrap()
        );
    }

    #[test]
    fn test_poll_from_event() {
        let event = Event::from_json(r#"{
  "content": "Pineapple on pizza",
  "created_at": 1719888496,
  "id": "9d1b6b9562e66f2ecf35eb0a3c2decc736c47fddb13d6fb8f87185a153ea3634",
  "kind": 1068,
  "pubkey": "dee45a23c4f1d93f3a2043650c5081e4ac14a778e0acbef03de3768e4f81ac7b",
  "sig": "7fa93bf3c430eaef784b0dacc217d3cd5eff1c520e7ef5d961381bc0f014dde6286618048d924808e54d1be03f2f2c2f0f8b5c9c2082a4480caf45a565ca9797",
  "tags": [
    ["option", "qj518h583", "Yay"],
    ["option", "gga6cdnqj", "Nay"],
    ["relay", "wss://relay.damus.io"],
    ["relay", "wss://relay.example.com"],
    ["polltype", "multiplechoice"],
    ["endsAt", "1788888888"]
  ]
}"#).unwrap();

        let poll = Poll::from_event(&event).unwrap();
        assert_eq!(poll.title, "Pineapple on pizza");
        assert_eq!(poll.r#type, PollType::MultipleChoice);
        assert_eq!(
            poll.options,
            vec![
                PollOption {
                    id: "qj518h583".to_string(),
                    text: "Yay".to_string(),
                },
                PollOption {
                    id: "gga6cdnqj".to_string(),
                    text: "Nay".to_string(),
                }
            ]
        );
        assert_eq!(
            poll.relays,
            vec![
                RelayUrl::from_str("wss://relay.damus.io").unwrap(),
                RelayUrl::from_str("wss://relay.example.com").unwrap(),
            ]
        );
        assert_eq!(poll.ends_at, Some(Timestamp::from_secs(1788888888)));
    }

    #[test]
    fn test_poll_from_event_without_poll_type() {
        let event = Event::from_json(r#"{
  "content": "Pineapple on pizza",
  "created_at": 1719888496,
  "id": "9d1b6b9562e66f2ecf35eb0a3c2decc736c47fddb13d6fb8f87185a153ea3634",
  "kind": 1068,
  "pubkey": "dee45a23c4f1d93f3a2043650c5081e4ac14a778e0acbef03de3768e4f81ac7b",
  "sig": "7fa93bf3c430eaef784b0dacc217d3cd5eff1c520e7ef5d961381bc0f014dde6286618048d924808e54d1be03f2f2c2f0f8b5c9c2082a4480caf45a565ca9797",
  "tags": [
    ["option", "qj518h583", "Yay"]
  ]
}"#).unwrap();

        let poll = Poll::from_event(&event).unwrap();
        assert_eq!(poll.title, "Pineapple on pizza");
        assert_eq!(poll.r#type, PollType::SingleChoice);
        assert_eq!(
            poll.options,
            vec![PollOption {
                id: "qj518h583".to_string(),
                text: "Yay".to_string(),
            },]
        );
        assert!(poll.relays.is_empty());
        assert!(poll.ends_at.is_none());
    }

    #[test]
    fn test_poll_from_event_with_empty_poll_type() {
        let event = Event::from_json(r#"{
  "content": "Pineapple on pizza",
  "created_at": 1719888496,
  "id": "9d1b6b9562e66f2ecf35eb0a3c2decc736c47fddb13d6fb8f87185a153ea3634",
  "kind": 1068,
  "pubkey": "dee45a23c4f1d93f3a2043650c5081e4ac14a778e0acbef03de3768e4f81ac7b",
  "sig": "7fa93bf3c430eaef784b0dacc217d3cd5eff1c520e7ef5d961381bc0f014dde6286618048d924808e54d1be03f2f2c2f0f8b5c9c2082a4480caf45a565ca9797",
  "tags": [
    ["option", "qj518h583", "Yay"],
    ["polltype", ""]
  ]
}"#).unwrap();

        let poll = Poll::from_event(&event).unwrap();
        assert_eq!(poll.title, "Pineapple on pizza");
        assert_eq!(poll.r#type, PollType::SingleChoice);
        assert_eq!(
            poll.options,
            vec![PollOption {
                id: "qj518h583".to_string(),
                text: "Yay".to_string(),
            },]
        );
        assert!(poll.relays.is_empty());
        assert!(poll.ends_at.is_none());
    }

    #[test]
    fn test_poll_from_event_with_malformed_polltype_tag() {
        let event = Event::from_json(r#"{
  "content": "Pineapple on pizza",
  "created_at": 1719888496,
  "id": "9d1b6b9562e66f2ecf35eb0a3c2decc736c47fddb13d6fb8f87185a153ea3634",
  "kind": 1068,
  "pubkey": "dee45a23c4f1d93f3a2043650c5081e4ac14a778e0acbef03de3768e4f81ac7b",
  "sig": "7fa93bf3c430eaef784b0dacc217d3cd5eff1c520e7ef5d961381bc0f014dde6286618048d924808e54d1be03f2f2c2f0f8b5c9c2082a4480caf45a565ca9797",
  "tags": [
    ["option", "qj518h583", "Yay"],
    ["polltype"]
  ]
}"#).unwrap();

        let poll = Poll::from_event(&event).unwrap();
        assert_eq!(poll.title, "Pineapple on pizza");
        assert_eq!(poll.r#type, PollType::SingleChoice);
        assert_eq!(
            poll.options,
            vec![PollOption {
                id: "qj518h583".to_string(),
                text: "Yay".to_string(),
            },]
        );
        assert!(poll.relays.is_empty());
        assert!(poll.ends_at.is_none());
    }
}