Skip to main content

Crate pbech32

Crate pbech32 

Source
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:

hello1vehkc6mn27xpct

Bech32 and Bech32m are specified in BIP173 and BIP350, respectively.

§Library Features

§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 data

Encode 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 result

Decoding 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 result

Encode 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 result

Many 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 result

Modules§

bits
5-bit/8-bit data conversion functions.
checksum
BCH checksum functions.

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 data field.

Enums§

Err
String parse error.
Scheme
Bech32 variant.