Bitcoin::Crypto::Bech32 - Bitcoin's Bech32 implementation in Perl


        use Bitcoin::Crypto::Bech32 qw(:all);

        # witness version - a number from 0 to 16, packed into a byte
        my $version = pack "C", $Bitcoin::Crypto::Config::config{witness_version};

        # human readable part of the address - a string
        my $network_hrp = Bitcoin::Crypto::Network->get->segwit_hrp;

        # handles Bitcoin SegWit adresses
        my $segwit_address = encode_segwit($network_hrp, $version . $pubkeyhash);
        my $data_with_version = decode_segwit($segwit_address);

        # handles custom Bech32 encoding
        my $bech32str = encode_bech32("hello", pack "A*", "world"); # should start with hello1
        my $bytestr = decode_bech32($bech32str);


Implementation of Bech32 algorithm (BIP173 compatible)

The module has a couple of layers of encoding, namely:

  • base32, which handles the alphabet and 5-to-8 transformation (not exported)

  • bech32, which handles checksums and human-readable (HRP) parts

  • segwit, which handles segwit program numbering and validation

For Bech32-encoded SegWit addresses, use encode_segwit and decode_segwit. For custom uses of Bech32 (not in context of Bitcoin SegWit addresses), use encode_bech32 and decode_bech32.

If in doubt, use *_segwit functions, not *_bech32 functions!




Bech32 encoding / decoding valid for SegWit addresses. Does not validate the human readable part. These functions also perform segwit program validation, see Bitcoin::Crypto::Segwit. Encoding takes two arguments which are a human readable part and a byte string. Decoding takes bech32-encoded string. Returns the entire encoded data along with the segwit program version byte.



Basic bech32 encoding / decoding. Encoding takes two arguments which are a human readable part and a byte string. Decoding takes bech32-encoded string.

These methods are not meant to work with Bitcoin SegWit addresses, use encode_segwit and decode_segwit for that instead


Splits a bech32-encoded string into human-readable part and data part. Returns a list containing the two. Performs all validity checks on the input. Dies on every error.


This module throws an instance of Bitcoin::Crypto::Exception if it encounters an error. It can produce the following error types from the Bitcoin::Crypto::Exception namespace:

  • Bech32InputFormat - input was not suitable for bech32 operations due to invalid format

  • Bech32InputData - input was parsed with bech32 operations but contained invalid data

  • Bech32InputChecksum - checksum validation has failed