Encodings

Bech32

BIP173 bech32 with a prefix and 5-bit words and a BCH checksum. With m it's BIP350 bech32m for Taproot
IDbech3213 / 20bech32 · 32 characters
Encoding / Bech32

Bech32

A BCH checksum that catches four typos.

Overhead
+62% on random bytes
Checksum
checked on decode
Standard
BIP173, BIP350 (Bech32m)
Used by
SegWit, Taproot, Lightning, Nostr, Cosmos
family 1 / 20

Sample

Out
hi1dpjkcmr0ypmk7unvvsssgdwk9f
Back
"hello world!" · prefix hi

Options

prefixstring
required
Human-readable part, such as bc, tb or npub
limitnumber
default 90
Longest result allowed; BIP173 sets 90, Lightning invoices need more
mboolean
default false
Bech32m, the BIP350 checksum of segwit v1 and later (Taproot)

Access

Importimport { bech32 } from "@agntn/encodings/bech32"
CLIencodings encode bech32 'hello world!' --prefix hi
Tryplayground with the sample above

A human-readable prefix, a 1, then 5-bit words and six characters of checksum. The checksum is a BCH code that catches any four wrong characters. Base58 never came close.

ts
encode("bech32", "gm", { prefix: "test" });  // "test1vaks69jerm"
decode("bech32", "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4");
// bytes: the 20-byte program, details: { prefix: "bc", witnessVersion: 0 }

A valid segwit v0 address comes back as its witness program. Anything else comes back as the bytes its words carry. A Nostr npub, say, or a Cosmos account. Mixed case is an error. Over 90 characters too, unless you raise limit. Lightning invoice? Raise it.

Checksums has the long version, segwit rules included.

Bech32m

Bech32 had one embarrassing flaw. End a string in p, add or drop q characters right before it, and the checksum still passed. BIP350 fixed it by changing one constant. That's bech32m, and m: true switches to it.

ts
decode("bech32", "bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqzk5jj0", { m: true });
// bytes: 79be667e…16f81798, details: { prefix: "bc", witnessVersion: 1 }

Taproot addresses, bc1p…, are bech32m. Version 0 stays on plain bech32. Read a v0 address with m and it fails. Read a Taproot one without it? checksum is bech32m's. Annoying? It's exactly the point.