forked from rust-bitcoin/rust-bech32
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
526 lines (466 loc) · 17 KB
/
lib.rs
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
// Written by Clark Moody and the rust-bitcoin developers.
// SPDX-License-Identifier: MIT
//! Encoding and decoding of the Bech32 format.
//!
//! Bech32 is an encoding scheme that is easy to use for humans and efficient to encode in QR codes.
//!
//! A Bech32 string consists of a human-readable part (HRP), a separator (the character `'1'`), and
//! a data part. A checksum at the end of the string provides error detection to prevent mistakes
//! when the string is written off or read out loud.
//!
//! The original description in [BIP-0173](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki)
//! has more details. See also [BIP-0350](https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki).
//!
//! FIXME write some examples
//!
#![cfg_attr(all(not(feature = "std"), not(test)), no_std)]
// Experimental features we need.
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
// Coding conventions
#![deny(missing_docs)]
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(any(test, feature = "std"))]
extern crate core;
#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::{string::String, vec::Vec};
use core::convert::Infallible;
use core::fmt;
use internals::write_err;
use crate::primitives::checksum::{Checksum, PackedNull};
use crate::primitives::gf32::{self, Fe32};
use crate::primitives::hrpstring::{self, Bech32Writer, WriteBase32, SEP};
pub use crate::primitives::hrpstring::{CheckBase32, FromBase32, ToBase32, Variant};
pub mod primitives;
/// The ASCII case of a string.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Case {
/// String is all lowercase ASCII characters and digits.
Lower,
/// String is all uppercase ASCII characters and digits.
Upper,
}
impl Default for Case {
fn default() -> Self { Case::Lower }
}
/// The "null checksum" used on bech32 strings for which we want to do no checksum checking
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum NoChecksum {}
/// The bech32 checksum algorithm, defined in BIP 173
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Bech32 {}
/// The bech32m checksum algorithm, defined in BIP 350
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Bech32m {}
/// TODO: Document this.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Codex32 {}
impl Checksum for NoChecksum {
type MidstateRepr = PackedNull;
const CHECKSUM_LENGTH: usize = 0;
const GENERATOR_SH: [PackedNull; 5] = [PackedNull; 5];
const TARGET_RESIDUE: PackedNull = PackedNull;
}
impl Checksum for Bech32 {
type MidstateRepr = u32;
const CHECKSUM_LENGTH: usize = 6;
// Copied from Bitcoin Core src/bech32.cpp
const GENERATOR_SH: [u32; 5] = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
const TARGET_RESIDUE: u32 = 1;
}
// Same as Bech32 except TARGET_RESIDUE is different
impl Checksum for Bech32m {
type MidstateRepr = u32;
const CHECKSUM_LENGTH: usize = 6;
// Copied from Bitcoin Core src/bech32.cpp
const GENERATOR_SH: [u32; 5] = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
const TARGET_RESIDUE: u32 = 0x2bc830a3;
}
impl Checksum for Codex32 {
type MidstateRepr = u128;
const CHECKSUM_LENGTH: usize = 13;
// Copied from BIP 93
const GENERATOR_SH: [u128; 5] = [
0x19dc500ce73fde210,
0x1bfae00def77fe529,
0x1fbd920fffe7bee52,
0x1739640bdeee3fdad,
0x07729a039cfc75f5a,
];
const TARGET_RESIDUE: u128 = 0x10ce0795c2fd1e62a;
}
/// FIXME figure out exact API here
pub fn bech32_verify(s: &str) -> Result<(), Error> {
let (hrp_string, witness_version) = hrpstring::Parsed::new_with_witness_version(s)?;
if witness_version == 0 {
hrp_string.validate_checksum::<Bech32>()
} else {
hrp_string.validate_checksum::<Bech32m>()
}
}
/// FIXME figure out exact API here
#[cfg(feature = "alloc")]
pub fn bech32_parse(s: &str) -> Result<Vec<u8>, Error> {
let (hrp_string, witness_version) = hrpstring::Parsed::new_with_witness_version(s)?;
if witness_version == 0 {
hrp_string.validate_checksum::<Bech32>()?;
Ok(hrp_string.data_iter::<Bech32>()?.collect())
} else {
hrp_string.validate_checksum::<Bech32m>()?;
Ok(hrp_string.data_iter::<Bech32m>()?.collect())
}
}
/// FIXME figure out exact API here
pub fn encode_as_iter<'d, Ck: Checksum + 'd>(
hrp: &'d str,
data: &'d [u8],
) -> Result<impl Iterator<Item = char> + 'd, Error> {
use primitives::iter::{ByteIterExt, Fe32IterExt};
let iter = data
.iter()
.copied() // iterate over bytes
.bytes_to_fes() // convert bytes to field elements in-line
.checksum::<Ck>()
.with_checksummed_hrp(hrp)
.hrp_chars(hrp)?;
Ok(iter)
}
/// Encode a bech32 payload to string.
#[cfg(feature = "alloc")]
pub fn encode<T: AsRef<[Fe32]>>(hrp: &str, data: T, variant: Variant) -> Result<String, Error> {
let mut buf = String::new();
encode_to_fmt(&mut buf, hrp, data, variant)?.unwrap();
Ok(buf)
}
/// Encode a bech32 payload to string without the checksum.
#[cfg(feature = "alloc")]
pub fn encode_without_checksum<T: AsRef<[Fe32]>>(hrp: &str, data: T) -> Result<String, Error> {
let mut buf = String::new();
encode_without_checksum_to_fmt(&mut buf, hrp, data)?.unwrap();
Ok(buf)
}
/// Encode a bech32 payload to an [fmt::Write].
/// This method is intended for implementing traits from [std::fmt].
#[cfg(feature = "alloc")]
pub fn encode_to_fmt<T: AsRef<[Fe32]>>(
fmt: &mut dyn fmt::Write,
hrp: &str,
data: T,
variant: Variant,
) -> Result<fmt::Result, Error> {
let (_case, hrp_lower) = hrpstring::check_and_lowercase(hrp)?;
match Bech32Writer::new(&hrp_lower, variant, fmt) {
Ok(mut writer) => {
Ok(writer.write(data.as_ref()).and_then(|_| {
// Finalize manually to avoid panic on drop if write fails
writer.finalize()
}))
}
Err(e) => Ok(Err(e)),
}
}
/// Encode a bech32 payload without a checksum to an [fmt::Write].
/// This method is intended for implementing traits from [std::fmt].
#[cfg(feature = "alloc")]
pub fn encode_without_checksum_to_fmt<T: AsRef<[Fe32]>>(
fmt: &mut dyn fmt::Write,
hrp: &str,
data: T,
) -> Result<fmt::Result, Error> {
let (_case, hrp_lower) = hrpstring::check_and_lowercase(hrp)?;
if let Err(e) = fmt.write_str(&hrp_lower) {
return Ok(Err(e));
}
if let Err(e) = fmt.write_char(SEP) {
return Ok(Err(e));
}
for b in data.as_ref() {
if let Err(e) = fmt.write_char(b.to_char()) {
return Ok(Err(e));
}
}
Ok(Ok(()))
}
/// Error types for Bech32 encoding / decoding.
#[derive(Debug)]
pub enum Error {
/// String does not contain the separator character.
MissingSeparator,
/// The checksum does not match the rest of the data.
InvalidChecksum,
/// The data or human-readable part is too long or too short.
InvalidLength,
/// Witness version is out of the range [0, 16] inclusive
InvalidWitnessVersion,
/// Some part of the string contains an invalid character.
InvalidChar(char),
/// The bit conversion failed due to a padding issue.
InvalidPadding,
/// The whole string must be of one case.
MixedCase,
/// Attempted to convert a value which overflows a `Fe32`.
Overflow,
/// Conversion to Fe32 failed.
TryFrom(TryFromIntError),
/// Field error.
Field(gf32::Error),
}
impl From<Infallible> for Error {
fn from(v: Infallible) -> Self { match v {} }
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use Error::*;
match *self {
MissingSeparator => write!(f, "missing human-readable separator, \"{}\"", SEP),
InvalidChecksum => write!(f, "invalid checksum"),
InvalidLength => write!(f, "invalid length"),
InvalidChar(n) => write!(f, "invalid character (code={})", n),
InvalidPadding => write!(f, "invalid padding"),
InvalidWitnessVersion => write!(f, "invalid witness version"),
MixedCase => write!(f, "mixed-case strings not allowed"),
TryFrom(ref e) => write_err!(f, "conversion to Fe32 failed"; e),
Overflow => write!(f, "attempted to convert a value which overflows a Fe32"),
Field(ref e) => crate::write_err!(f, "field error"; e),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
use Error::*;
match *self {
TryFrom(ref e) => Some(e),
Field(ref e) => Some(e),
MissingSeparator
| MixedCase
| InvalidChecksum
| InvalidLength
| InvalidChar(_)
| InvalidPadding
| InvalidWitnessVersion
| Overflow => None,
}
}
}
impl From<TryFromIntError> for Error {
fn from(e: TryFromIntError) -> Self { Error::TryFrom(e) }
}
impl From<gf32::Error> for Error {
fn from(e: gf32::Error) -> Self { Error::Field(e) }
}
/// Error return when `TryFrom<T>` fails for `T` -> `Fe32` conversion.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum TryFromIntError {
/// Attempted to convert a negative value to a `Fe32`.
NegOverflow,
/// Attempted to convert a value which overflows a `Fe32`.
PosOverflow,
}
impl fmt::Display for TryFromIntError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use TryFromIntError::*;
match *self {
NegOverflow => write!(f, "attempted to convert a negative value to a Fe32"),
PosOverflow => write!(f, "attempted to convert a value which overflows a Fe32"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for TryFromIntError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
use TryFromIntError::*;
match *self {
NegOverflow | PosOverflow => None,
}
}
}
// impl From<convert::Error> for Error {
// fn from(e: convert::Error) -> Self {
// Error::InvalidData(e)
// }
// }
#[cfg(test)]
mod tests {
use super::*;
pub fn check_iter_eq<I, J, T>(mut i: I, mut j: J)
where
I: Iterator<Item = T>,
J: Iterator<Item = T>,
T: PartialEq + fmt::Debug,
{
loop {
match (i.next(), j.next()) {
(Some(x), Some(y)) => assert_eq!(x, y),
(None, Some(y)) => panic!("second iterator yielded {:?}, first iterator empty", y),
(Some(x), None) => panic!("first iterator yielded {:?}, second iterator empty", x),
(None, None) => return,
}
}
}
#[test]
#[cfg(feature = "alloc")]
fn getters() {
let (hrp_string, witver) =
hrpstring::Parsed::new_with_witness_version("BC1SW50QA3JX3S").unwrap();
assert_eq!(hrp_string.hrp(), "BC");
assert_eq!(witver, 16);
assert_eq!(hrp_string.witness_version(), Some(16));
#[cfg(feature = "alloc")]
assert_eq!(hrp_string.hrp_lower(), "bc");
check_iter_eq(hrp_string.data_iter::<Bech32>().unwrap(), [0x75, 0x1e].iter().copied());
}
#[test]
#[cfg(feature = "alloc")]
fn valid_checksum() {
let valid_bech32 = [
"A12UEL5L",
"an83characterlonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1tt5tgs",
"abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw",
"11qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqc8247j",
"split1checkupstagehandshakeupstreamerranterredcaperred2y9e3w",
];
for s in valid_bech32 {
let hrps = hrpstring::Parsed::new(s).unwrap();
let data_iter = hrps.data_iter::<Bech32>().unwrap();
data_iter.count(); // consume whole iterator
}
let valid_bech32m = [
"A1LQFN3A",
"a1lqfn3a",
"an83characterlonghumanreadablepartthatcontainsthetheexcludedcharactersbioandnumber11sg7hg6",
"abcdef1l7aum6echk45nj3s0wdvt2fg8x9yrzpqzd3ryx",
"11llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllludsr8",
"split1checkupstagehandshakeupstreamerranterredcaperredlc445v",
"?1v759aa",
];
for s in valid_bech32m {
let hrps = hrpstring::Parsed::new(s).unwrap();
let data_iter = hrps.data_iter::<Bech32m>().unwrap();
data_iter.count(); // consume whole iterator
}
}
#[test]
#[cfg(feature = "alloc")]
fn invalid_strings() {
let pairs: Vec<(&str, Error)> = vec!(
(" 1nwldj5",
Error::InvalidChar(' ')),
("abc1\u{2192}axkwrx",
Error::InvalidChar('\u{2192}')),
("an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1569pvx",
Error::InvalidLength),
("pzry9x0s0muk",
Error::MissingSeparator),
("1pzry9x0s0muk",
Error::InvalidLength),
("x1b4n0q5v",
Error::InvalidChar('b')),
("ABC1DEFGOH",
Error::InvalidChar('O')),
("li1dgmt3",
Error::InvalidLength),
("de1lg7wt\u{ff}",
Error::InvalidChar('\u{ff}')),
("\u{20}1xj0phk",
Error::InvalidChar('\u{20}')),
("\u{7F}1g6xzxy",
Error::InvalidChar('\u{7F}')),
("an84characterslonghumanreadablepartthatcontainsthetheexcludedcharactersbioandnumber11d6pts4",
Error::InvalidLength),
("qyrz8wqd2c9m",
Error::MissingSeparator),
("1qyrz8wqd2c9m",
Error::InvalidLength),
("y1b0jsk6g",
Error::InvalidChar('b')),
("lt1igcx5c0",
Error::InvalidChar('i')),
("in1muywd",
Error::InvalidLength),
("mm1crxm3i",
Error::InvalidChar('i')),
("au1s5cgom",
Error::InvalidChar('o')),
("M1VUXWEZ",
Error::InvalidChecksum),
("16plkw9",
Error::InvalidLength),
("1p2gdwpf",
Error::InvalidLength),
("bc1p2",
Error::InvalidLength),
);
for p in pairs {
let (s, _expected_error) = p;
let data = hrpstring::Parsed::new(s).and_then(|s| s.validate_checksum::<Bech32>());
match data {
Ok(_) => panic!("Should be invalid: {:?}", s),
Err(e) => assert!(matches!(e, _expected_error), "testing input '{}'", s),
}
}
}
}
#[cfg(test)]
#[cfg(feature = "alloc")] // Note, all the unit tests currently require an allocator.
mod tests2 {
use super::*;
#[test]
#[cfg(feature = "alloc")]
fn write_with_checksum_on_drop() {
let hrp = "lntb";
let data = "Hello World!".as_bytes().to_base32();
let mut written_str = String::new();
{
let mut writer = Bech32Writer::new(hrp, Variant::Bech32, &mut written_str).unwrap();
writer.write(&data).unwrap();
}
let encoded_str = encode(hrp, data, Variant::Bech32).unwrap();
assert_eq!(encoded_str, written_str);
}
#[cfg(feature = "alloc")]
fn roundtrip_checksum<Ck: Checksum>() {
let hrp = "lnbc";
let data = b"Hello World!";
let mut char_iter = encode_as_iter::<Ck>(hrp, data).expect("failed to construct hrpstring");
let ckstring: String = char_iter.by_ref().collect();
for _ in 0..100 {
assert_eq!(char_iter.next(), None);
}
let decoded = hrpstring::Parsed::new(&ckstring).expect("failed to parse hrp string");
let mut dec_iter = decoded.data_iter::<Ck>().expect("failed to create data iterator");
let dec_data = dec_iter.by_ref().collect::<Vec<_>>();
assert_eq!(decoded.hrp(), hrp);
assert_eq!(dec_data, data);
for _ in 0..100 {
assert!(dec_iter.next().is_none());
}
}
#[test]
#[cfg(feature = "alloc")]
fn roundtrip() {
roundtrip_checksum::<NoChecksum>();
roundtrip_checksum::<Bech32>();
roundtrip_checksum::<Bech32m>();
}
#[test]
#[cfg(feature = "alloc")]
fn test_hrp_case() {
// Tests for issue with HRP case checking being ignored for encoding
let encoded_str = encode("HRP", [0x00, 0x00].to_base32(), Variant::Bech32).unwrap();
assert_eq!(encoded_str, "hrp1qqqq40atq3");
}
#[test]
fn test_encode() {
assert!(matches!(
encode("", vec![1u8, 2, 3, 4].check_base32().unwrap(), Variant::Bech32),
Err(Error::InvalidLength)
));
}
#[test]
fn bech32_sanity() { Bech32::sanity_check(); }
#[test]
fn bech32m_sanity() { Bech32m::sanity_check(); }
#[test]
fn codex32_sanity() { Codex32::sanity_check(); }
}