Expand description
Bech32 encoding and decoding library.
§What is Bech32?
Bech32 is a fast and user-friendly base 32 encoding format that includes a namespace and checksum. Bech32m is an update to Bech32 with an improved checksum algorithm.
A Bech32 string contains a human-readable part (HRP), an encoded data part, and a 6 character checksum. The data part and checksum are base 32-encoded with a user-friendly alphabet that only contains lowercase ASCII alphanumeric characters.
Here is an example Bech32m string:
hello1vehkc6mn27xpctBech32 and Bech32m are specified in BIP173 and BIP350, respectively.
§Library Features
- Bech32 (BIP173) and Bech32m (BIP350) support.
- Idiomatic encoding and decoding via the
DisplayandFromStrtraits. - Decode arbitrarily long strings.
- Streamed, allocation-free encoding to any writer.
- No external dependencies.
§Examples
Decode from string:
use pbech32::Bech32;
let s = "a1qypqxpq9mqr2hj"; // bech32m-encoded string
let got: Bech32 = s.parse()?; // decode string
assert_eq!(got.hrp.to_string(), "a"); // check human-readable part
assert_eq!(got.data, vec![1, 2, 3, 4, 5]); // check dataEncode to string:
use pbech32::{Bech32, Hrp, Scheme};
let scheme = Scheme::Bech32m; // checksum scheme
let hrp: Hrp = "a".parse()?; // human-readable part
let data = vec![1, 2, 3, 4, 5]; // data
let got = Bech32 { scheme, hrp, data }.to_string(); // encode as string
assert_eq!(got, "a1qypqxpq9mqr2hj"); // check resultDecoding a string verifies the checksum to catch mistakes:
use pbech32::{Bech32, Err};
let s = "a1wypqxpq9mqr2hj"; // string with error ("q" changed to "w")
let got = s.parse::<Bech32>(); // try to decode string
assert_eq!(got, Err(Err::InvalidChecksum)); // check resultEncode to a writer:
use std::io::Write;
use pbech32::{Encoder, Hrp, Scheme};
let mut vec: Vec<u8> = Vec::new(); // output vector
let hrp: Hrp = "hello".parse()?; // human readable part
let mut encoder = Encoder::new(&mut vec, Scheme::Bech32m, hrp)?; // create encoder
encoder.write_all(b"folks")?; // write data
encoder.flush()?; // flush encoder (REQUIRED)
let got = str::from_utf8(vec.as_ref())?; // convert output vector to string
assert_eq!(got, "hello1vehkc6mn27xpct"); // check resultMany error variants have a context field. Try to decode a string which has an invalid character at position 1:
use pbech32::{Bech32, Err};
let s = "a 1xxxxxx"; // string with invalid character at position 1
assert_eq!(s.parse::<Bech32>(), Err(Err::InvalidChar(1))); // check resultModules§
Structs§
- Bech32
- Parsed Bech32 structure.
- Encoder
- Stream Bech32-encoded data to a writer without allocation.
- Hrp
- Human-readable part (HRP) of Bech32 structure.
- RawBech32
- Parsed Bech32 structure with raw 5-bit
datafield.