nostr 0.44.3

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
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
// Copyright (c) 2022-2023 Yuki Kishimoto
// Copyright (c) 2023-2025 Rust Nostr Developers
// Distributed under the MIT software license

//! Tag

use alloc::string::{String, ToString};
use alloc::vec::{IntoIter, Vec};
#[cfg(not(feature = "std"))]
use core::cell::OnceCell;
use core::cmp::Ordering;
use core::fmt;
use core::hash::{Hash, Hasher};
#[cfg(feature = "std")]
use std::sync::OnceLock as OnceCell;

use serde::de::Error as DeserializerError;
use serde::ser::SerializeSeq;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

pub mod cow;
mod error;
pub mod kind;
pub mod list;
pub mod standard;

pub use self::cow::CowTag;
pub use self::error::Error;
pub use self::kind::TagKind;
pub use self::list::Tags;
pub use self::standard::TagStandard;
use super::id::EventId;
use crate::nips::nip01::Coordinate;
use crate::nips::nip10::Marker;
use crate::nips::nip56::Report;
use crate::nips::nip65::RelayMetadata;
use crate::types::Url;
use crate::{ImageDimensions, PublicKey, RelayUrl, SingleLetterTag, Timestamp};

/// Tag
#[derive(Clone)]
pub struct Tag {
    buf: Vec<String>,
    standardized: OnceCell<Option<TagStandard>>,
}

impl fmt::Debug for Tag {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Tag").field(&self.buf).finish()
    }
}

impl PartialEq for Tag {
    fn eq(&self, other: &Self) -> bool {
        self.buf == other.buf
    }
}

impl Eq for Tag {}

impl PartialOrd for Tag {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Tag {
    fn cmp(&self, other: &Self) -> Ordering {
        self.buf.cmp(&other.buf)
    }
}

impl Hash for Tag {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.buf.hash(state);
    }
}

impl Tag {
    #[inline]
    fn new(buf: Vec<String>, standardized: Option<TagStandard>) -> Self {
        Self {
            buf,
            standardized: OnceCell::from(standardized),
        }
    }

    #[inline]
    fn new_with_empty_cell(buf: Vec<String>) -> Self {
        Self {
            buf,
            standardized: OnceCell::new(),
        }
    }

    #[inline]
    fn erase_standardized(&mut self) {
        if self.standardized.get().is_some() {
            self.standardized = OnceCell::new();
        }
    }

    /// Parse tag
    ///
    /// Return error if the tag is empty!
    pub fn parse<I, S>(tag: I) -> Result<Self, Error>
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        // Collect
        let tag: Vec<String> = tag.into_iter().map(|v| v.into()).collect();

        // Check if it's empty
        if tag.is_empty() {
            return Err(Error::EmptyTag);
        }

        // Construct without an empty cell
        Ok(Self::new_with_empty_cell(tag))
    }

    /// Construct from standardized tag
    #[inline]
    pub fn from_standardized(standardized: TagStandard) -> Self {
        Self::new(standardized.clone().to_vec(), Some(standardized))
    }

    /// Construct from standardized tag without initialize cell (avoid a clone)
    #[inline]
    pub fn from_standardized_without_cell(standardized: TagStandard) -> Self {
        Self::new_with_empty_cell(standardized.to_vec())
    }

    /// Get tag kind
    #[inline]
    pub fn kind(&self) -> TagKind {
        // SAFETY: `buf` must not be empty, checked during parsing.
        let key: &str = &self.buf[0];
        TagKind::from(key)
    }

    /// Return the **first** tag value (index `1`), if exists.
    #[inline]
    pub fn content(&self) -> Option<&str> {
        self.buf.get(1).map(|s| s.as_str())
    }

    /// Get [SingleLetterTag]
    #[inline]
    pub fn single_letter_tag(&self) -> Option<SingleLetterTag> {
        match self.kind() {
            TagKind::SingleLetter(s) => Some(s),
            _ => None,
        }
    }

    /// Get reference of standardized tag
    #[inline]
    pub fn as_standardized(&self) -> Option<&TagStandard> {
        self.standardized
            .get_or_init(|| TagStandard::parse(self.as_slice()).ok())
            .as_ref()
    }

    /// Consume tag and get standardized tag
    #[inline]
    pub fn to_standardized(self) -> Option<TagStandard> {
        match self.standardized.into_inner() {
            Some(inner) => inner,
            None => TagStandard::parse(&self.buf).ok(),
        }
    }

    /// Get tag len
    #[inline]
    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> usize {
        self.buf.len()
    }

    /// Appends a value to the back of the [`Tag`].
    ///
    /// Check [`Vec::push`] doc to learn more.
    ///
    /// This erases the [`TagStandard`] cell, if any.
    pub fn push<S>(&mut self, value: S)
    where
        S: Into<String>,
    {
        // Erase indexes
        self.erase_standardized();

        // Append
        self.buf.push(value.into());
    }

    /// Removes the last value and returns it.
    /// If the [`Tag`] has only **one** value, returns `None`, since it can't be empty.
    ///
    /// Check [`Vec::pop`] doc to learn more.
    ///
    /// This erases the [`TagStandard`] cell, if any.
    pub fn pop(&mut self) -> Option<String> {
        // The tag must have at least one value!
        if self.buf.len() <= 1 {
            return None;
        }

        // Erase indexes
        self.erase_standardized();

        // Pop last item
        self.buf.pop()
    }

    /// Inserts a value at position `index` within the vector,
    /// shifting all other values after it to the right.
    ///
    /// The value at index `0` and `1` can't be empty.
    /// If an empty string is passed for those indexes, `false` is returned.
    ///
    /// Returns `true` if the value has been inserted or updated successfully.
    /// Returns `false` if `index > len`.
    ///
    /// Check [`Vec::insert`] doc to learn more.
    ///
    /// This erases the [`TagStandard`] cell, if any.
    pub fn insert<S>(&mut self, index: usize, value: S) -> bool
    where
        S: Into<String>,
    {
        // Check if `index` is bigger than collection len
        if index > self.buf.len() {
            return false;
        }

        let value: String = value.into();

        // Return false if the value is empty at position 0 or 1
        if (index == 0 || index == 1) && value.is_empty() {
            return false;
        }

        // Erase indexes
        self.erase_standardized();

        // Insert at position
        self.buf.insert(index, value);

        // Inserted successfully
        true
    }

    /// Extends the collection.
    ///
    /// Check [`Vec::extend`] doc to learn more.
    ///
    /// This erases the [`TagStandard`] cell, if any.
    pub fn extend<I, S>(&mut self, iter: I)
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        // Erase standardized tag
        self.erase_standardized();

        // Extend list
        self.buf.extend(iter.into_iter().map(|v| v.into()));
    }

    /// Get as slice of strings
    #[inline]
    pub fn as_slice(&self) -> &[String] {
        &self.buf
    }

    /// Consume tag and return array of strings
    #[inline]
    pub fn to_vec(self) -> Vec<String> {
        self.buf
    }

    /// Compose `["e", "<event-id">]`
    ///
    /// <https://github.com/nostr-protocol/nips/blob/master/01.md>
    #[inline]
    pub fn event(event_id: EventId) -> Self {
        Self::from_standardized_without_cell(TagStandard::event(event_id))
    }

    /// Compose `["p", "<public-key>"]` tag
    ///
    /// <https://github.com/nostr-protocol/nips/blob/master/01.md>
    #[inline]
    pub fn public_key(public_key: PublicKey) -> Self {
        Self::from_standardized_without_cell(TagStandard::public_key(public_key))
    }

    /// Compose `["d", "<identifier>"]` tag
    ///
    /// <https://github.com/nostr-protocol/nips/blob/master/01.md>
    #[inline]
    pub fn identifier<T>(identifier: T) -> Self
    where
        T: Into<String>,
    {
        Self::from_standardized_without_cell(TagStandard::Identifier(identifier.into()))
    }

    /// Compose `["a", "<coordinate>", "<optional-relay-url>"]` tag
    ///
    /// <https://github.com/nostr-protocol/nips/blob/master/01.md>
    #[inline]
    pub fn coordinate(coordinate: Coordinate, relay_url: Option<RelayUrl>) -> Self {
        Self::from_standardized_without_cell(TagStandard::Coordinate {
            coordinate,
            relay_url,
            uppercase: false,
        })
    }

    /// Compose `["nonce", "<nonce>", "<difficulty>"]` tag
    ///
    /// <https://github.com/nostr-protocol/nips/blob/master/13.md>
    #[inline]
    pub fn pow(nonce: u128, difficulty: u8) -> Self {
        Self::from_standardized_without_cell(TagStandard::POW { nonce, difficulty })
    }

    /// Construct `["client", "<name>"]` tag
    ///
    /// <https://github.com/nostr-protocol/nips/blob/master/89.md>
    pub fn client<S>(name: S) -> Self
    where
        S: Into<String>,
    {
        Self::from_standardized_without_cell(TagStandard::Client {
            name: name.into(),
            address: None,
        })
    }

    /// Compose `["expiration", "<timestamp>"]` tag
    ///
    /// <https://github.com/nostr-protocol/nips/blob/master/40.md>
    #[inline]
    pub fn expiration(timestamp: Timestamp) -> Self {
        Self::from_standardized_without_cell(TagStandard::Expiration(timestamp))
    }

    /// Compose `["e", "<event-id>", "<report>"]` tag
    ///
    /// <https://github.com/nostr-protocol/nips/blob/master/56.md>
    #[inline]
    pub fn event_report(event_id: EventId, report: Report) -> Self {
        Self::from_standardized_without_cell(TagStandard::EventReport(event_id, report))
    }

    /// Compose `["p", "<public-key>", "<report>"]` tag
    ///
    /// <https://github.com/nostr-protocol/nips/blob/master/56.md>
    #[inline]
    pub fn public_key_report(public_key: PublicKey, report: Report) -> Self {
        Self::from_standardized_without_cell(TagStandard::PublicKeyReport(public_key, report))
    }

    /// Compose `["r", "<relay-url>", "<metadata>"]` tag
    ///
    /// <https://github.com/nostr-protocol/nips/blob/master/65.md>
    #[inline]
    pub fn relay_metadata(relay_url: RelayUrl, metadata: Option<RelayMetadata>) -> Self {
        Self::from_standardized_without_cell(TagStandard::RelayMetadata {
            relay_url,
            metadata,
        })
    }

    /// Relay url
    ///
    /// JSON: `["relay", "<relay-url>"]`
    #[inline]
    pub fn relay(url: RelayUrl) -> Self {
        Self::from_standardized_without_cell(TagStandard::Relay(url))
    }

    /// Relay URLs
    ///
    /// JSON: `["relays", "<relay-url>", "<relay-url>"]`
    #[inline]
    pub fn relays<I>(urls: I) -> Self
    where
        I: IntoIterator<Item = RelayUrl>,
    {
        Self::from_standardized_without_cell(TagStandard::Relays(urls.into_iter().collect()))
    }

    /// All relays
    ///
    /// JSON: `["relay", "ALL_RELAYS"]`
    ///
    /// <https://github.com/nostr-protocol/nips/blob/master/62.md>
    #[inline]
    pub fn all_relays() -> Self {
        Self::from_standardized_without_cell(TagStandard::AllRelays)
    }

    /// Repository head
    ///
    /// JSON: `["HEAD", "<branch-name>"]`
    ///
    /// <https://github.com/nostr-protocol/nips/blob/master/34.md>
    #[inline]
    pub fn head<S>(branch_name: S) -> Self
    where
        S: Into<String>,
    {
        Self::from_standardized_without_cell(TagStandard::GitHead(branch_name.into()))
    }

    /// Compose `["t", "<hashtag>"]` tag
    ///
    /// This will convert the hashtag to lowercase.
    #[inline]
    pub fn hashtag<T>(hashtag: T) -> Self
    where
        T: AsRef<str>,
    {
        Self::from_standardized_without_cell(TagStandard::Hashtag(hashtag.as_ref().to_lowercase()))
    }

    /// Compose `["r", "<value>"]` tag
    #[inline]
    pub fn reference<T>(reference: T) -> Self
    where
        T: Into<String>,
    {
        Self::from_standardized_without_cell(TagStandard::Reference(reference.into()))
    }

    /// Compose `["title", "<title>"]` tag
    #[inline]
    pub fn title<T>(title: T) -> Self
    where
        T: Into<String>,
    {
        Self::from_standardized_without_cell(TagStandard::Title(title.into()))
    }

    /// Compose image tag
    #[inline]
    pub fn image(url: Url, dimensions: Option<ImageDimensions>) -> Self {
        Self::from_standardized_without_cell(TagStandard::Image(url, dimensions))
    }

    /// Compose `["description", "<description>"]` tag
    #[inline]
    pub fn description<T>(description: T) -> Self
    where
        T: Into<String>,
    {
        Self::from_standardized_without_cell(TagStandard::Description(description.into()))
    }

    /// Protected event
    ///
    /// <https://github.com/nostr-protocol/nips/blob/master/70.md>
    #[inline]
    pub fn protected() -> Self {
        Self::from_standardized_without_cell(TagStandard::Protected)
    }

    /// A short human-readable plaintext summary of what that event is about
    ///
    /// JSON: `["alt", "<summary>"]`
    ///
    /// <https://github.com/nostr-protocol/nips/blob/master/31.md>
    #[inline]
    pub fn alt<T>(summary: T) -> Self
    where
        T: Into<String>,
    {
        Self::from_standardized_without_cell(TagStandard::Alt(summary.into()))
    }

    /// Compose custom tag
    ///
    /// JSON: `["<kind>", "<value-1>", "<value-2>", ...]`
    pub fn custom<I, S>(kind: TagKind, values: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        // Compose tag
        let mut buf: Vec<String> = Vec::with_capacity(1);
        buf.push(kind.to_string());
        buf.extend(values.into_iter().map(|v| v.into()));

        // NOT USE `Self::new`!
        Self::new_with_empty_cell(buf)
    }

    /// Check if is a standard event tag with `root` marker
    pub fn is_root(&self) -> bool {
        matches!(
            self.as_standardized(),
            Some(TagStandard::Event {
                marker: Some(Marker::Root),
                ..
            })
        )
    }

    /// Check if is a standard event tag with `reply` marker
    pub fn is_reply(&self) -> bool {
        matches!(
            self.as_standardized(),
            Some(TagStandard::Event {
                marker: Some(Marker::Reply),
                ..
            })
        )
    }

    /// Check if it's a protected event tag
    ///
    /// <https://github.com/nostr-protocol/nips/blob/master/70.md>
    #[inline]
    pub fn is_protected(&self) -> bool {
        matches!(self.as_standardized(), Some(TagStandard::Protected))
    }
}

impl IntoIterator for Tag {
    type Item = String;
    type IntoIter = IntoIter<Self::Item>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.buf.into_iter()
    }
}

impl Serialize for Tag {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut seq = serializer.serialize_seq(Some(self.buf.len()))?;
        for element in self.buf.iter() {
            seq.serialize_element(&element)?;
        }
        seq.end()
    }
}

impl<'de> Deserialize<'de> for Tag {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        type Data = Vec<String>;
        let tag: Data = Data::deserialize(deserializer)?;
        Self::parse(tag).map_err(DeserializerError::custom)
    }
}

impl From<TagStandard> for Tag {
    fn from(standard: TagStandard) -> Self {
        Self::from_standardized_without_cell(standard)
    }
}

#[cfg(test)]
mod tests {
    use core::str::FromStr;

    use secp256k1::schnorr::Signature;

    use super::*;
    use crate::{Alphabet, Event, JsonUtil, Kind, Timestamp};

    #[test]
    fn test_parse_empty_tag() {
        assert_eq!(
            Tag::parse::<Vec<_>, String>(vec![]).unwrap_err(),
            Error::EmptyTag
        );
    }

    #[test]
    fn test_tag_match_standardized() {
        let tag: Tag = Tag::parse(["d", "bravery"]).unwrap();
        assert_eq!(
            tag.as_standardized(),
            Some(&TagStandard::Identifier(String::from("bravery")))
        );

        let tag: Tag = Tag::parse(["d", "test"]).unwrap();
        assert_eq!(
            tag.to_standardized(),
            Some(TagStandard::Identifier(String::from("test")))
        );
    }

    #[test]
    fn test_extract_tag_content() {
        let t: Tag = Tag::parse(["aaaaaa", "bbbbbb"]).unwrap();
        assert_eq!(t.content(), Some("bbbbbb"));

        // Test extract public key
        let t: Tag = Tag::parse([
            "custom-p",
            "f86c44a2de95d9149b51c6a29afeabba264c18e2fa7c49de93424a0c56947785",
        ])
        .unwrap();
        assert_eq!(
            t.content(),
            Some("f86c44a2de95d9149b51c6a29afeabba264c18e2fa7c49de93424a0c56947785")
        );

        // Test extract event ID
        let t: Tag = Tag::parse([
            "custom-e",
            "2be17aa3031bdcb006f0fce80c146dea9c1c0268b0af2398bb673365c6444d45",
        ])
        .unwrap();
        assert_eq!(
            t.content(),
            Some("2be17aa3031bdcb006f0fce80c146dea9c1c0268b0af2398bb673365c6444d45")
        );
    }

    #[test]
    fn test_tag_push() {
        let mut tag = Tag::parse(["d", "test"]).unwrap();
        tag.push("test2");
        assert_eq!(tag.len(), 3);
        assert_eq!(tag.to_vec(), ["d", "test", "test2"]);
    }

    #[test]
    fn test_tag_pop() {
        let mut tag = Tag::parse(["d", "test"]).unwrap();
        assert_eq!(tag.pop().unwrap(), "test");
        assert_eq!(tag.len(), 1);

        // Can't pop if the tag has only one value
        assert!(tag.pop().is_none());
        assert_eq!(tag.len(), 1);

        assert_eq!(tag.to_vec(), ["d"]);
    }

    #[test]
    fn test_tag_extend() {
        let mut tag = Tag::parse(["p", "pk"]).unwrap();
        tag.extend(["test", "test1"]);
        assert_eq!(tag.len(), 4);
        assert_eq!(tag.to_vec(), ["p", "pk", "test", "test1"]);
    }

    #[test]
    fn test_tag_insert() {
        let mut tag = Tag::parse(["p", "val", "relay", "other"]).unwrap();

        // Can't insert an empty value at index 0
        assert!(!tag.insert(0, ""));
        assert_eq!(tag.len(), 4);

        // Can't insert an empty value at index 1
        assert!(!tag.insert(1, ""));
        assert_eq!(tag.len(), 4);

        // Insert a value at index 1
        assert!(tag.insert(1, "pk"));
        assert_eq!(tag.len(), 5);

        assert_eq!(tag.to_vec(), ["p", "pk", "val", "relay", "other"]);
    }

    #[test]
    fn test_deserialize_tag_from_event() {
        // Got this fresh off the wire
        let event: &str = r#"{"id":"2be17aa3031bdcb006f0fce80c146dea9c1c0268b0af2398bb673365c6444d45","pubkey":"f86c44a2de95d9149b51c6a29afeabba264c18e2fa7c49de93424a0c56947785","created_at":1640839235,"kind":4,"tags":[["p","13adc511de7e1cfcf1c6b7f6365fb5a03442d7bcacf565ea57fa7770912c023d"]],"content":"uRuvYr585B80L6rSJiHocw==?iv=oh6LVqdsYYol3JfFnXTbPA==","sig":"a5d9290ef9659083c490b303eb7ee41356d8778ff19f2f91776c8dc4443388a64ffcf336e61af4c25c05ac3ae952d1ced889ed655b67790891222aaa15b99fdd"}"#;
        let event = Event::from_json(event).unwrap();
        let tag = event.tags.first().unwrap();

        assert_eq!(
            tag,
            &Tag::public_key(
                PublicKey::from_hex(
                    "13adc511de7e1cfcf1c6b7f6365fb5a03442d7bcacf565ea57fa7770912c023d"
                )
                .unwrap()
            )
        );
    }

    #[test]
    fn test_serialize_tag_to_event() {
        let public_key =
            PublicKey::from_hex("68d81165918100b7da43fc28f7d1fc12554466e1115886b9e7bb326f65ec4272")
                .unwrap();
        let event = Event::new(
            EventId::from_hex("378f145897eea948952674269945e88612420db35791784abf0616b4fed56ef7")
                .unwrap(),
            PublicKey::from_hex("79dff8f82963424e0bb02708a22e44b4980893e3a4be0fa3cb60a43b946764e3").unwrap(),
            Timestamp::from(1671739153),
            Kind::EncryptedDirectMessage,
            [Tag::public_key(public_key)],
            "8y4MRYrb4ztvXO2NmsHvUA==?iv=MplZo7oSdPfH/vdMC8Hmwg==",
            Signature::from_str("fd0954de564cae9923c2d8ee9ab2bf35bc19757f8e328a978958a2fcc950eaba0754148a203adec29b7b64080d0cf5a32bebedd768ea6eb421a6b751bb4584a8").unwrap()
        );

        let event_json: &str = r#"{"id":"378f145897eea948952674269945e88612420db35791784abf0616b4fed56ef7","pubkey":"79dff8f82963424e0bb02708a22e44b4980893e3a4be0fa3cb60a43b946764e3","created_at":1671739153,"kind":4,"tags":[["p","68d81165918100b7da43fc28f7d1fc12554466e1115886b9e7bb326f65ec4272"]],"content":"8y4MRYrb4ztvXO2NmsHvUA==?iv=MplZo7oSdPfH/vdMC8Hmwg==","sig":"fd0954de564cae9923c2d8ee9ab2bf35bc19757f8e328a978958a2fcc950eaba0754148a203adec29b7b64080d0cf5a32bebedd768ea6eb421a6b751bb4584a8"}"#;

        assert_eq!(&event.as_json(), event_json);
    }

    #[test]
    fn test_tag_custom() {
        assert_eq!(
            vec!["r", "wss://atlas.nostr.land", ""],
            Tag::custom(
                TagKind::SingleLetter(SingleLetterTag::lowercase(Alphabet::R)),
                ["wss://atlas.nostr.land", ""]
            )
            .to_vec()
        );

        assert_eq!(
            Tag::parse(["r", "wss://atlas.nostr.land", ""]).unwrap(),
            Tag::custom(
                TagKind::SingleLetter(SingleLetterTag::lowercase(Alphabet::R)),
                ["wss://atlas.nostr.land", ""]
            )
        );

        assert_eq!(
            vec![
                "r",
                "3dbee968d1ddcdf07521e246e405e1fbb549080f1f4ef4e42526c4528f124220",
                ""
            ],
            Tag::custom(
                TagKind::SingleLetter(SingleLetterTag::lowercase(Alphabet::R)),
                [
                    "3dbee968d1ddcdf07521e246e405e1fbb549080f1f4ef4e42526c4528f124220",
                    ""
                ]
            )
            .to_vec()
        );

        assert_eq!(
            Tag::parse([
                "r",
                "3dbee968d1ddcdf07521e246e405e1fbb549080f1f4ef4e42526c4528f124220",
                ""
            ])
            .unwrap(),
            Tag::custom(
                TagKind::SingleLetter(SingleLetterTag::lowercase(Alphabet::R)),
                [
                    "3dbee968d1ddcdf07521e246e405e1fbb549080f1f4ef4e42526c4528f124220",
                    ""
                ]
            )
        );

        assert_eq!(
            vec!["client", "rust-nostr"],
            Tag::custom(TagKind::Client, ["rust-nostr"]).to_vec()
        );

        assert_eq!(
            Tag::parse(["client", "nostr-sdk"]).unwrap(),
            Tag::custom(TagKind::Client, ["nostr-sdk"])
        );
    }

    #[test]
    fn test_hashtag() {
        assert_eq!(
            Tag::parse(["t", "Nostr"]).unwrap(),
            Tag::custom(TagKind::t(), ["Nostr"])
        );
        assert_eq!(Tag::hashtag("Nostr"), Tag::custom(TagKind::t(), ["nostr"]));
    }
}

#[cfg(bench)]
mod benches {
    use test::{black_box, Bencher};

    use super::*;

    #[bench]
    pub fn get_tag_kind(bh: &mut Bencher) {
        let tag = Tag::identifier("id");
        bh.iter(|| {
            black_box(tag.kind());
        });
    }

    #[bench]
    pub fn parse_p_tag(bh: &mut Bencher) {
        let tag = [
            "p",
            "13adc511de7e1cfcf1c6b7f6365fb5a03442d7bcacf565ea57fa7770912c023d",
        ];
        bh.iter(|| {
            black_box(Tag::parse(tag)).unwrap();
        });
    }

    #[bench]
    pub fn parse_p_standardized_tag(bh: &mut Bencher) {
        let tag = &[
            "p",
            "13adc511de7e1cfcf1c6b7f6365fb5a03442d7bcacf565ea57fa7770912c023d",
        ];
        bh.iter(|| {
            black_box(TagStandard::parse(tag)).unwrap();
        });
    }

    #[bench]
    pub fn parse_e_tag(bh: &mut Bencher) {
        let tag = [
            "e",
            "378f145897eea948952674269945e88612420db35791784abf0616b4fed56ef7",
            "wss://relay.damus.io",
        ];
        bh.iter(|| {
            black_box(Tag::parse(tag)).unwrap();
        });
    }

    #[bench]
    pub fn parse_e_standardized_tag(bh: &mut Bencher) {
        let tag = &[
            "e",
            "378f145897eea948952674269945e88612420db35791784abf0616b4fed56ef7",
            "wss://relay.damus.io",
        ];
        bh.iter(|| {
            black_box(TagStandard::parse(tag)).unwrap();
        });
    }

    #[bench]
    pub fn parse_a_tag(bh: &mut Bencher) {
        let tag = [
            "a",
            "30023:a695f6b60119d9521934a691347d9f78e8770b56da16bb255ee286ddf9fda919:ipsum",
            "wss://relay.nostr.org",
        ];
        bh.iter(|| {
            black_box(Tag::parse(tag)).unwrap();
        });
    }

    #[bench]
    pub fn parse_t_tag(bh: &mut Bencher) {
        let tag = ["t", "test"];
        bh.iter(|| {
            black_box(Tag::parse(tag)).unwrap();
        });
    }

    #[bench]
    pub fn parse_a_standardized_tag(bh: &mut Bencher) {
        let tag = &[
            "a",
            "30023:a695f6b60119d9521934a691347d9f78e8770b56da16bb255ee286ddf9fda919:ipsum",
            "wss://relay.nostr.org",
        ];
        bh.iter(|| {
            black_box(TagStandard::parse(tag)).unwrap();
        });
    }
}