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
#![allow(missing_docs)]
use bech32::{self, FromBase32, ToBase32, Variant};
use bitcoin_hashes::Hash;
use secp256k1::{SecretKey, XOnlyPublicKey};
use crate::event::id::{self, EventId};
use crate::Kind;
pub const PREFIX_BECH32_SECRET_KEY: &str = "nsec";
pub const PREFIX_BECH32_PUBLIC_KEY: &str = "npub";
pub const PREFIX_BECH32_NOTE_ID: &str = "note";
pub const PREFIX_BECH32_CHANNEL: &str = "nchannel";
pub const PREFIX_BECH32_PROFILE: &str = "nprofile";
pub const PREFIX_BECH32_EVENT: &str = "nevent";
pub const PREFIX_BECH32_PARAMETERIZED_REPLACEABLE_EVENT: &str = "naddr";
pub const SPECIAL: u8 = 0;
pub const RELAY: u8 = 1;
pub const AUTHOR: u8 = 2;
pub const KIND: u8 = 3;
#[derive(Debug, Eq, PartialEq, thiserror::Error)]
pub enum Error {
#[error("wrong prefix or variant")]
WrongPrefixOrVariant,
#[error(transparent)]
Bech32(#[from] bech32::Error),
#[error("field missing: {0}")]
FieldMissing(String),
#[error("type-length-value error")]
TLV,
#[error(transparent)]
UTF8(#[from] std::string::FromUtf8Error),
#[error("impossible to perform conversion from slice")]
TryFromSlice,
#[error(transparent)]
Secp256k1(#[from] secp256k1::Error),
#[error(transparent)]
Hash(#[from] bitcoin_hashes::Error),
#[error(transparent)]
EventId(#[from] id::Error),
}
pub trait FromBech32: Sized {
type Err;
fn from_bech32<S>(s: S) -> Result<Self, Self::Err>
where
S: Into<String>;
}
impl FromBech32 for SecretKey {
type Err = Error;
fn from_bech32<S>(secret_key: S) -> Result<Self, Self::Err>
where
S: Into<String>,
{
let (hrp, data, checksum) = bech32::decode(&secret_key.into())?;
if hrp != PREFIX_BECH32_SECRET_KEY || checksum != Variant::Bech32 {
return Err(Error::WrongPrefixOrVariant);
}
let data = Vec::<u8>::from_base32(&data)?;
Ok(Self::from_slice(data.as_slice())?)
}
}
impl FromBech32 for XOnlyPublicKey {
type Err = Error;
fn from_bech32<S>(public_key: S) -> Result<Self, Self::Err>
where
S: Into<String>,
{
let (hrp, data, checksum) = bech32::decode(&public_key.into())?;
if hrp != PREFIX_BECH32_PUBLIC_KEY || checksum != Variant::Bech32 {
return Err(Error::WrongPrefixOrVariant);
}
let data = Vec::<u8>::from_base32(&data)?;
Ok(Self::from_slice(data.as_slice())?)
}
}
impl FromBech32 for EventId {
type Err = Error;
fn from_bech32<S>(hash: S) -> Result<Self, Self::Err>
where
S: Into<String>,
{
let (hrp, data, checksum) = bech32::decode(&hash.into())?;
if hrp != PREFIX_BECH32_NOTE_ID || checksum != Variant::Bech32 {
return Err(Error::WrongPrefixOrVariant);
}
let data = Vec::<u8>::from_base32(&data)?;
Ok(EventId::from_slice(data.as_slice())?)
}
}
pub trait ToBech32 {
type Err;
fn to_bech32(&self) -> Result<String, Self::Err>;
}
impl ToBech32 for XOnlyPublicKey {
type Err = Error;
fn to_bech32(&self) -> Result<String, Self::Err> {
let data = self.serialize().to_base32();
Ok(bech32::encode(
PREFIX_BECH32_PUBLIC_KEY,
data,
Variant::Bech32,
)?)
}
}
impl ToBech32 for SecretKey {
type Err = Error;
fn to_bech32(&self) -> Result<String, Self::Err> {
let data = self.secret_bytes().to_base32();
Ok(bech32::encode(
PREFIX_BECH32_SECRET_KEY,
data,
Variant::Bech32,
)?)
}
}
impl ToBech32 for EventId {
type Err = Error;
fn to_bech32(&self) -> Result<String, Self::Err> {
let data = self.to_base32();
Ok(bech32::encode(
PREFIX_BECH32_NOTE_ID,
data,
Variant::Bech32,
)?)
}
}
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
pub struct Nip19Event {
event_id: EventId,
relays: Vec<String>,
}
impl Nip19Event {
pub fn new<S>(event_id: EventId, relays: Vec<S>) -> Self
where
S: Into<String>,
{
Self {
event_id,
relays: relays.into_iter().map(|u| u.into()).collect(),
}
}
}
impl FromBech32 for Nip19Event {
type Err = Error;
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_EVENT || checksum != Variant::Bech32 {
return Err(Error::WrongPrefixOrVariant);
}
let mut data: Vec<u8> = Vec::from_base32(&data)?;
let mut event_id: Option<EventId> = None;
let mut relays: Vec<String> = Vec::new();
while !data.is_empty() {
let t = data.first().ok_or(Error::TLV)?;
let l = data.get(1).ok_or(Error::TLV)?;
let l = *l as usize;
let bytes = data.get(2..l + 2).ok_or(Error::TLV)?;
match *t {
SPECIAL => {
if event_id.is_none() {
event_id = Some(EventId::from_slice(bytes)?);
}
}
RELAY => {
relays.push(String::from_utf8(bytes.to_vec())?);
}
_ => (),
};
data.drain(..l + 2);
}
Ok(Self {
event_id: event_id.ok_or_else(|| Error::FieldMissing("event id".to_string()))?,
relays,
})
}
}
impl ToBech32 for Nip19Event {
type Err = Error;
fn to_bech32(&self) -> Result<String, Self::Err> {
let mut bytes: Vec<u8> = vec![SPECIAL, 32];
bytes.extend(self.event_id.inner().as_byte_array());
for relay in self.relays.iter() {
bytes.extend([RELAY, relay.len() as u8]);
bytes.extend(relay.as_bytes());
}
let data = bytes.to_base32();
Ok(bech32::encode(PREFIX_BECH32_EVENT, data, Variant::Bech32)?)
}
}
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
pub struct ParameterizedReplaceableEvent {
kind: Kind,
pubkey: XOnlyPublicKey,
identifier: String,
relays: Vec<String>,
}
impl FromBech32 for ParameterizedReplaceableEvent {
type Err = Error;
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(Error::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(Error::TLV)?;
let l = data.get(1).ok_or(Error::TLV)?;
let l = *l as usize;
let bytes = data.get(2..l + 2).ok_or(Error::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(|_| Error::TryFromSlice)?)
as u64;
kind = Some(Kind::from(k));
}
}
_ => (),
};
data.drain(..l + 2);
}
Ok(Self {
kind: kind.ok_or_else(|| Error::FieldMissing("kind".to_string()))?,
pubkey: pubkey.ok_or_else(|| Error::FieldMissing("pubkey".to_string()))?,
identifier: identifier.ok_or_else(|| Error::FieldMissing("identifier".to_string()))?,
relays,
})
}
}
impl ToBech32 for ParameterizedReplaceableEvent {
type Err = Error;
fn to_bech32(&self) -> Result<String, Self::Err> {
let mut bytes: Vec<u8> = Vec::new();
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());
}
bytes.extend([AUTHOR, 32]);
bytes.extend(self.pubkey.serialize());
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,
)?)
}
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use super::*;
use crate::Result;
#[test]
fn to_bech32_public_key() -> Result<()> {
let public_key = XOnlyPublicKey::from_str(
"aa4fc8665f5696e33db7e1a572e3b0f5b3d615837b0f362dcb1c8068b098c7b4",
)?;
assert_eq!(
"npub14f8usejl26twx0dhuxjh9cas7keav9vr0v8nvtwtrjqx3vycc76qqh9nsy".to_string(),
public_key.to_bech32()?
);
Ok(())
}
#[test]
fn to_bech32_secret_key() -> Result<()> {
let secret_key = SecretKey::from_str(
"9571a568a42b9e05646a349c783159b906b498119390df9a5a02667155128028",
)?;
assert_eq!(
"nsec1j4c6269y9w0q2er2xjw8sv2ehyrtfxq3jwgdlxj6qfn8z4gjsq5qfvfk99".to_string(),
secret_key.to_bech32()?
);
Ok(())
}
#[test]
fn to_bech32_note() -> Result<()> {
let event_id =
EventId::from_hex("d94a3f4dd87b9a3b0bed183b32e916fa29c8020107845d1752d72697fe5309a5")?;
assert_eq!(
"note1m99r7nwc0wdrkzldrqan96gklg5usqspq7z9696j6unf0ljnpxjspqfw99".to_string(),
event_id.to_bech32()?
);
Ok(())
}
}