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
#![recursion_limit = "256"]
#![deny(dead_code, missing_docs, warnings)]
#[macro_use]
extern crate amplify;
#[macro_use]
extern crate strict_encoding;
#[cfg(feature = "serde")]
#[macro_use]
extern crate serde_crate as serde;
use std::convert::{Infallible, TryFrom};
use std::fmt::{self, Debug, Formatter};
use std::str::FromStr;
use amplify::hex::ToHex;
use bech32::{FromBase32, ToBase32, Variant};
use bitcoin_hashes::{sha256t, Hash};
#[cfg(feature = "zip")]
use deflate::{write::DeflateEncoder, Compression};
#[cfg(feature = "serde")]
use serde::{
de::{Error as SerdeError, Unexpected, Visitor},
Deserializer, Serializer,
};
#[cfg(feature = "serde")]
use serde_with::{hex::Hex, As};
pub const HRP_ID: &str = "id";
pub const HRP_DATA: &str = "data";
#[cfg(feature = "zip")]
pub const HRP_ZIP: &str = "z";
#[cfg(feature = "zip")]
pub const RAW_DATA_ENCODING_DEFLATE: u8 = 1u8;
#[derive(Clone, PartialEq, Eq, Display, Debug, From, Error)]
#[display(doc_comments)]
pub enum Error {
#[from]
Bech32Error(::bech32::Error),
#[from]
NotStrictEncoded(strict_encoding::Error),
#[from]
NotBitcoinHash(bitcoin_hashes::Error),
WrongPrefix,
WrongVariant,
NoEncodingPrefix,
UnknownRawDataEncoding(u8),
DeflateEncoding,
InflateError(String),
}
impl From<Infallible> for Error {
fn from(_: Infallible) -> Self {
unreachable!("infalliable error in lnpbp_bech32 blob")
}
}
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate", transparent)
)]
#[derive(
Wrapper, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Default, Display,
From
)]
#[derive(StrictEncode, StrictDecode)]
#[wrap(
Index,
IndexMut,
IndexRange,
IndexFull,
IndexFrom,
IndexTo,
IndexInclusive
)]
#[display(Vec::bech32_data_string)]
pub struct Blob(
#[cfg_attr(feature = "serde", serde(with = "As::<Hex>"))] Vec<u8>,
);
impl AsRef<[u8]> for Blob {
fn as_ref(&self) -> &[u8] { &self.0 }
}
impl Debug for Blob {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "Blob({})", self.0.to_hex())
}
}
impl FromStr for Blob {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Blob::from_bech32_data_str(s)
}
}
pub trait ToBech32Payload {
fn to_bech32_payload(&self) -> Vec<u8>;
}
pub trait AsBech32Payload {
fn as_bech32_payload(&self) -> &[u8];
}
impl<T> AsBech32Payload for T
where
T: AsRef<[u8]>,
{
fn as_bech32_payload(&self) -> &[u8] { self.as_ref() }
}
pub trait FromBech32Payload
where
Self: Sized,
{
fn from_bech32_payload(payload: Vec<u8>) -> Result<Self, Error>;
}
impl<T> FromBech32Payload for T
where
T: TryFrom<Vec<u8>>,
Error: From<T::Error>,
{
fn from_bech32_payload(payload: Vec<u8>) -> Result<T, Error> {
Ok(T::try_from(payload)?)
}
}
pub trait ToBech32String {
fn to_bech32_string(&self) -> String;
}
pub trait FromBech32Str {
const HRP: &'static str;
fn from_bech32_str(s: &str) -> Result<Self, Error>
where
Self: Sized;
}
pub mod strategies {
use amplify::{Holder, Wrapper};
use strict_encoding::{StrictDecode, StrictEncode};
use super::*;
pub struct UsingStrictEncoding;
pub struct Wrapped;
#[cfg(feature = "zip")]
pub struct CompressedStrictEncoding;
pub trait Strategy {
const HRP: &'static str;
type Strategy;
}
impl<T> ToBech32String for T
where
T: Strategy + Clone,
Holder<T, <T as Strategy>::Strategy>: ToBech32String,
{
#[inline]
fn to_bech32_string(&self) -> String {
Holder::new(self.clone()).to_bech32_string()
}
}
impl<T> FromBech32Str for T
where
T: Strategy,
Holder<T, <T as Strategy>::Strategy>: FromBech32Str,
{
const HRP: &'static str = T::HRP;
#[inline]
fn from_bech32_str(s: &str) -> Result<Self, Error> {
Ok(Holder::from_bech32_str(s)?.into_inner())
}
}
impl<T> ToBech32String for Holder<T, Wrapped>
where
T: Wrapper,
T::Inner: ToBech32String,
{
#[inline]
fn to_bech32_string(&self) -> String {
self.as_inner().as_inner().to_bech32_string()
}
}
impl<T> FromBech32Str for Holder<T, Wrapped>
where
T: Wrapper + Strategy,
T::Inner: FromBech32Str,
{
const HRP: &'static str = T::HRP;
#[inline]
fn from_bech32_str(s: &str) -> Result<Self, Error> {
Ok(Self::new(T::from_inner(T::Inner::from_bech32_str(s)?)))
}
}
impl<T> ToBech32String for Holder<T, UsingStrictEncoding>
where
T: StrictEncode + Strategy,
{
#[inline]
fn to_bech32_string(&self) -> String {
let data = self
.as_inner()
.strict_serialize()
.expect("in-memory strict encoding failure");
::bech32::encode(T::HRP, data.to_base32(), Variant::Bech32m)
.unwrap_or_else(|_| s!("Error: wrong bech32 prefix"))
}
}
impl<T> FromBech32Str for Holder<T, UsingStrictEncoding>
where
T: StrictDecode + Strategy,
{
const HRP: &'static str = T::HRP;
#[inline]
fn from_bech32_str(s: &str) -> Result<Self, Error> {
let (hrp, data, variant) = ::bech32::decode(s)?;
if hrp.as_str() != Self::HRP {
return Err(Error::WrongPrefix);
}
if variant != Variant::Bech32m {
return Err(Error::WrongVariant);
}
Ok(Self::new(T::strict_deserialize(Vec::<u8>::from_base32(
&data,
)?)?))
}
}
}
pub use strategies::Strategy;
mod sealed {
use amplify::Wrapper;
use super::*;
pub trait HashType<Tag>: Wrapper<Inner = sha256t::Hash<Tag>>
where
Tag: sha256t::Tag,
{
}
pub trait ToPayload: ToBech32Payload {}
pub trait AsPayload: AsBech32Payload {}
pub trait FromPayload: FromBech32Payload {}
impl<T, Tag> HashType<Tag> for T
where
T: Wrapper<Inner = sha256t::Hash<Tag>>,
Tag: sha256t::Tag,
{
}
impl<T> ToPayload for T where T: ToBech32Payload {}
impl<T> AsPayload for T where T: AsBech32Payload {}
impl<T> FromPayload for T where T: FromBech32Payload {}
}
pub trait ToBech32DataString: sealed::ToPayload {
fn to_bech32_data_string(&self) -> String {
::bech32::encode(
HRP_DATA,
self.to_bech32_payload().to_base32(),
Variant::Bech32m,
)
.expect("HRP is hardcoded and can't fail")
}
}
impl<T> ToBech32DataString for T where T: sealed::ToPayload {}
pub trait Bech32DataString: sealed::AsPayload {
fn bech32_data_string(&self) -> String {
::bech32::encode(
HRP_DATA,
self.as_bech32_payload().to_base32(),
Variant::Bech32m,
)
.expect("HRP is hardcoded and can't fail")
}
}
impl<T> Bech32DataString for T where T: sealed::AsPayload {}
pub trait FromBech32DataStr
where
Self: Sized + sealed::FromPayload,
{
fn from_bech32_data_str(s: &str) -> Result<Self, Error> {
let (hrp, data, variant) = bech32::decode(s)?;
if hrp != HRP_DATA {
return Err(Error::WrongPrefix);
}
if variant != Variant::Bech32m {
return Err(Error::WrongVariant);
}
Self::from_bech32_payload(Vec::<u8>::from_base32(&data)?)
}
}
impl<T> FromBech32DataStr for T where T: sealed::FromPayload {}
#[doc(hidden)]
#[cfg(feature = "zip")]
pub mod zip {
use amplify::Holder;
use strict_encoding::{StrictDecode, StrictEncode};
use super::*;
fn payload_to_bech32_zip_string(hrp: &str, payload: &[u8]) -> String {
use std::io::Write;
let writer = vec![RAW_DATA_ENCODING_DEFLATE];
let mut encoder = DeflateEncoder::new(writer, Compression::Best);
encoder
.write_all(payload)
.expect("in-memory strict encoder failure");
let data = encoder.finish().expect("zip algorithm failure");
::bech32::encode(hrp, data.to_base32(), Variant::Bech32m)
.expect("HRP is hardcoded and can't fail")
}
fn bech32_zip_str_to_payload(hrp: &str, s: &str) -> Result<Vec<u8>, Error> {
let (prefix, data, version) = bech32::decode(s)?;
if prefix != hrp {
return Err(Error::WrongPrefix);
}
if version != Variant::Bech32m {
return Err(Error::WrongVariant);
}
let data = Vec::<u8>::from_base32(&data)?;
match *data[..].first().ok_or(Error::NoEncodingPrefix)? {
RAW_DATA_ENCODING_DEFLATE => {
let decoded = inflate::inflate_bytes(&data[1..])
.map_err(Error::InflateError)?;
Ok(decoded)
}
unknown_ver => Err(Error::UnknownRawDataEncoding(unknown_ver)),
}
}
pub trait ToBech32ZipString: sealed::ToPayload {
fn to_bech32_zip_string(&self) -> String {
payload_to_bech32_zip_string(HRP_ZIP, &self.to_bech32_payload())
}
}
impl<T> ToBech32ZipString for T where T: sealed::ToPayload {}
pub trait Bech32ZipString: sealed::AsPayload {
fn bech32_zip_string(&self) -> String {
payload_to_bech32_zip_string(HRP_ZIP, self.as_bech32_payload())
}
}
impl<T> Bech32ZipString for T where T: sealed::AsPayload {}
pub trait FromBech32ZipStr: sealed::FromPayload {
fn from_bech32_zip_str(s: &str) -> Result<Self, Error> {
Self::from_bech32_payload(bech32_zip_str_to_payload(HRP_ZIP, s)?)
}
}
impl<T> FromBech32ZipStr for T where T: sealed::FromPayload {}
impl<T> ToBech32String for Holder<T, strategies::CompressedStrictEncoding>
where
T: StrictEncode + Strategy,
{
#[inline]
fn to_bech32_string(&self) -> String {
let data = self
.as_inner()
.strict_serialize()
.expect("in-memory strict encoding failure");
payload_to_bech32_zip_string(T::HRP, &data)
}
}
impl<T> FromBech32Str for Holder<T, strategies::CompressedStrictEncoding>
where
T: StrictDecode + Strategy,
{
const HRP: &'static str = T::HRP;
#[inline]
fn from_bech32_str(s: &str) -> Result<Self, Error> {
Ok(Self::new(T::strict_deserialize(
bech32_zip_str_to_payload(Self::HRP, s)?,
)?))
}
}
}
#[cfg(feature = "zip")]
pub use zip::*;
pub trait ToBech32IdString<Tag>
where
Self: sealed::HashType<Tag>,
Tag: sha256t::Tag,
{
fn to_bech32_id_string(&self) -> String;
}
pub trait FromBech32IdStr<Tag>
where
Self: sealed::HashType<Tag> + Sized,
Tag: sha256t::Tag,
{
fn from_bech32_id_str(s: &str) -> Result<Self, Error>;
}
impl<T, Tag> ToBech32IdString<Tag> for T
where
Self: sealed::HashType<Tag>,
Tag: sha256t::Tag,
{
fn to_bech32_id_string(&self) -> String {
::bech32::encode(HRP_ID, self.to_inner().to_base32(), Variant::Bech32m)
.expect("HRP is hardcoded and can't fail")
}
}
impl<T, Tag> FromBech32IdStr<Tag> for T
where
Self: sealed::HashType<Tag>,
Tag: sha256t::Tag,
{
fn from_bech32_id_str(s: &str) -> Result<T, Error> {
let (hrp, id, variant) = ::bech32::decode(s)?;
if hrp != HRP_ID {
return Err(Error::WrongPrefix);
}
if variant != Variant::Bech32m {
return Err(Error::WrongVariant);
}
let vec = Vec::<u8>::from_base32(&id)?;
Ok(Self::from_inner(Self::Inner::from_slice(&vec)?))
}
}
#[cfg(feature = "serde")]
pub fn serialize<T, S>(data: &T, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
T: ToBech32String,
{
serializer.serialize_str(&data.to_bech32_string())
}
#[cfg(feature = "serde")]
pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where
D: Deserializer<'de>,
T: FromBech32Str,
{
deserializer.deserialize_str(Bech32Visitor::<T>(std::marker::PhantomData))
}
#[cfg(feature = "serde")]
struct Bech32Visitor<Value>(std::marker::PhantomData<Value>);
#[cfg(feature = "serde")]
impl<'de, ValueT> Visitor<'de> for Bech32Visitor<ValueT>
where
ValueT: FromBech32Str,
{
type Value = ValueT;
fn expecting(
&self,
formatter: &mut std::fmt::Formatter,
) -> std::fmt::Result {
formatter.write_str("a bech32m-encoded string")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: SerdeError,
{
Self::Value::from_bech32_str(v).map_err(|_| {
E::invalid_value(Unexpected::Str(v), &"valid bech32 string")
})
}
}