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
// Copyright (c) 2022-2023 Yuki Kishimoto
// Distributed under the MIT software license

//! NIP33
//!
//! <https://github.com/nostr-protocol/nips/blob/master/33.md>

use alloc::string::{String, ToString};
use alloc::vec::Vec;

use bitcoin::bech32::{self, FromBase32, ToBase32, Variant};
use bitcoin::secp256k1::XOnlyPublicKey;

use crate::nips::nip19::{
    Error as Bech32Error, FromBech32, ToBech32, AUTHOR, KIND,
    PREFIX_BECH32_PARAMETERIZED_REPLACEABLE_EVENT, RELAY, SPECIAL,
};
use crate::{Kind, Tag, UncheckedUrl};

/// Parameterized Replaceable Event
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct ParameterizedReplaceableEvent {
    /// Kind
    pub kind: Kind,
    /// Public Key
    pub pubkey: XOnlyPublicKey,
    /// `d` tag identifier
    pub identifier: String,
    /// Relays
    pub relays: Vec<String>,
}

impl From<ParameterizedReplaceableEvent> for Tag {
    fn from(value: ParameterizedReplaceableEvent) -> Self {
        Self::A {
            kind: value.kind,
            public_key: value.pubkey,
            identifier: value.identifier,
            relay_url: value.relays.first().map(UncheckedUrl::from),
        }
    }
}

impl FromBech32 for ParameterizedReplaceableEvent {
    type Err = Bech32Error;
    fn from_bech32<S>(s: S) -> Result<Self, Self::Err>
    where
        S: Into<String>,
    {
        let (hrp, data, checksum) = bech32::decode(&s.into())?;

        if hrp != PREFIX_BECH32_PARAMETERIZED_REPLACEABLE_EVENT || checksum != Variant::Bech32 {
            return Err(Bech32Error::WrongPrefixOrVariant);
        }

        let mut data: Vec<u8> = Vec::from_base32(&data)?;

        let mut identifier: Option<String> = None;
        let mut pubkey: Option<XOnlyPublicKey> = None;
        let mut kind: Option<Kind> = None;
        let mut relays: Vec<String> = Vec::new();

        while !data.is_empty() {
            let t = data.first().ok_or(Bech32Error::TLV)?;
            let l = data.get(1).ok_or(Bech32Error::TLV)?;
            let l = *l as usize;

            let bytes = data.get(2..l + 2).ok_or(Bech32Error::TLV)?;

            match *t {
                SPECIAL => {
                    if identifier.is_none() {
                        identifier = Some(String::from_utf8(bytes.to_vec())?);
                    }
                }
                RELAY => {
                    relays.push(String::from_utf8(bytes.to_vec())?);
                }
                AUTHOR => {
                    if pubkey.is_none() {
                        pubkey = Some(XOnlyPublicKey::from_slice(bytes)?);
                    }
                }
                KIND => {
                    if kind.is_none() {
                        let k: u64 = u32::from_be_bytes(
                            bytes.try_into().map_err(|_| Bech32Error::TryFromSlice)?,
                        ) as u64;
                        kind = Some(Kind::from(k));
                    }
                }
                _ => (),
            };

            data.drain(..l + 2);
        }

        Ok(Self {
            kind: kind.ok_or_else(|| Bech32Error::FieldMissing("kind".to_string()))?,
            pubkey: pubkey.ok_or_else(|| Bech32Error::FieldMissing("pubkey".to_string()))?,
            identifier: identifier
                .ok_or_else(|| Bech32Error::FieldMissing("identifier".to_string()))?,
            relays,
        })
    }
}

impl ToBech32 for ParameterizedReplaceableEvent {
    type Err = Bech32Error;

    fn to_bech32(&self) -> Result<String, Self::Err> {
        let mut bytes: Vec<u8> = Vec::new();

        // Identifier
        bytes.extend([SPECIAL, self.identifier.len() as u8]);
        bytes.extend(self.identifier.as_bytes());

        for relay in self.relays.iter() {
            bytes.extend([RELAY, relay.len() as u8]);
            bytes.extend(relay.as_bytes());
        }

        // Author
        bytes.extend([AUTHOR, 32]);
        bytes.extend(self.pubkey.serialize());

        // Kind
        bytes.extend([KIND, 4]);
        bytes.extend(self.kind.as_u32().to_be_bytes());

        let data = bytes.to_base32();
        Ok(bech32::encode(
            PREFIX_BECH32_PARAMETERIZED_REPLACEABLE_EVENT,
            data,
            Variant::Bech32,
        )?)
    }
}