Bech32

1.2.0 · active · verified Wed Apr 15

The `bech32` Python library provides a reference implementation for the Bech32 and Segwit address encoding scheme (BIP-173). It offers functionalities for encoding binary data into human-readable Bech32 strings and decoding them back. The current version is 1.2.0, with an infrequent release cadence focused on maintaining the reference standard.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates encoding and decoding a Bitcoin Segwit v0 P2WPKH address using `bech32_encode` and `bech32_decode`. It highlights the essential `convertbits` utility for converting data between 8-bit bytes and 5-bit groups, which is critical for correct Bech32 implementation. Remember to handle potential `None` returns from `bech32_decode` and `convertbits`.

from bech32 import bech32_encode, bech32_decode, convertbits

# Example 1: Encoding a Segwit v0 P2WPKH address data (20-byte hash)
hrp = "bc"  # Human-Readable Part for Bitcoin mainnet
witness_version = 0 # Witness version 0
# Example 20-byte hash (in 8-bit groups)
data_8bit = [0x75, 0x1e, 0x76, 0xe8, 0x19, 0x91, 0x96, 0xd4, 0x54, 0x94,
             0x1c, 0x45, 0xd1, 0xb3, 0xa3, 0x23, 0xf1, 0x43, 0x3b, 0xd6]

# Convert 8-bit data to 5-bit groups, prepending witness version
# convertbits returns None if conversion fails
data_5bit = convertbits(data_8bit, 8, 5)
if data_5bit is None:
    print("Error converting data to 5-bit groups.")
    exit()

# The final data for encoding includes the witness version (0-31) and the converted 5-bit data
encoded_data = [witness_version] + data_5bit

# Encode to Bech32
bech32_address = bech32_encode(hrp, encoded_data)
print(f"Encoded Bech32 address: {bech32_address}")
# Expected: bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq

# Example 2: Decoding a Bech32 address
address_to_decode = "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq"
hrp_decoded, data_5bit_decoded = bech32_decode(address_to_decode)

if hrp_decoded is None or data_5bit_decoded is None:
    print(f"Error decoding address: {address_to_decode}")
else:
    print(f"Decoded HRP: {hrp_decoded}")
    print(f"Decoded Data (5-bit groups): {data_5bit_decoded}")

    # Extract witness version and program
    wit_version = data_5bit_decoded[0]
    wit_program_5bit = data_5bit_decoded[1:]

    # Convert 5-bit program back to 8-bit bytes
    wit_program_8bit = convertbits(wit_program_5bit, 5, 8, pad=False)

    if wit_program_8bit is None:
        print("Error converting 5-bit program to 8-bit bytes.")
    else:
        print(f"Witness Version: {wit_version}")
        print(f"Witness Program (8-bit hex): {bytes(wit_program_8bit).hex()}")

view raw JSON →