Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1#!/usr/bin/env python32# Copyright (c) 2017 Pieter Wuille3# Distributed under the MIT software license, see the accompanying4# file COPYING or http://www.opensource.org/licenses/mit-license.php.5"""Reference implementation for Bech32/Bech32m and segwit addresses."""6import unittest7from enum import Enum9CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"10BECH32_CONST = 111BECH32M_CONST = 0x2bc830a313class Encoding(Enum):14"""Enumeration type to list the various supported encodings."""15BECH32 = 116BECH32M = 219def bech32_polymod(values):20"""Internal function that computes the Bech32 checksum."""21generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]22chk = 123for value in values:24top = chk >> 2525chk = (chk & 0x1ffffff) << 5 ^ value26for i in range(5):27chk ^= generator[i] if ((top >> i) & 1) else 028return chk31def bech32_hrp_expand(hrp):32"""Expand the HRP into values for checksum computation."""33return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp]36def bech32_verify_checksum(hrp, data):37"""Verify a checksum given HRP and converted data characters."""38check = bech32_polymod(bech32_hrp_expand(hrp) + data)39if check == BECH32_CONST:40return Encoding.BECH3241elif check == BECH32M_CONST:42return Encoding.BECH32M43else:44return None46def bech32_create_checksum(encoding, hrp, data):47"""Compute the checksum values given HRP and data."""48values = bech32_hrp_expand(hrp) + data49const = BECH32M_CONST if encoding == Encoding.BECH32M else BECH32_CONST50polymod = bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ const51return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]54def bech32_encode(encoding, hrp, data):55"""Compute a Bech32 or Bech32m string given HRP and data values."""56combined = data + bech32_create_checksum(encoding, hrp, data)57return hrp + '1' + ''.join([CHARSET[d] for d in combined])60def bech32_decode(bech):61"""Validate a Bech32/Bech32m string, and determine HRP and data."""62if ((any(ord(x) < 33 or ord(x) > 126 for x in bech)) or63(bech.lower() != bech and bech.upper() != bech)):64return (None, None, None)65bech = bech.lower()66pos = bech.rfind('1')67if pos < 1 or pos + 7 > len(bech) or len(bech) > 90:68return (None, None, None)69if not all(x in CHARSET for x in bech[pos+1:]):70return (None, None, None)71hrp = bech[:pos]72data = [CHARSET.find(x) for x in bech[pos+1:]]73encoding = bech32_verify_checksum(hrp, data)74if encoding is None:75return (None, None, None)76return (encoding, hrp, data[:-6])79def convertbits(data, frombits, tobits, pad=True):80"""General power-of-2 base conversion."""81acc = 082bits = 083ret = []84maxv = (1 << tobits) - 185max_acc = (1 << (frombits + tobits - 1)) - 186for value in data:87if value < 0 or (value >> frombits):88return None89acc = ((acc << frombits) | value) & max_acc90bits += frombits91while bits >= tobits:92bits -= tobits93ret.append((acc >> bits) & maxv)94if pad:95if bits:96ret.append((acc << (tobits - bits)) & maxv)97elif bits >= frombits or ((acc << (tobits - bits)) & maxv):98return None99return ret102def decode_segwit_address(hrp, addr):103"""Decode a segwit address."""104encoding, hrpgot, data = bech32_decode(addr)105if hrpgot != hrp:106return (None, None)107decoded = convertbits(data[1:], 5, 8, False)108if decoded is None or len(decoded) < 2 or len(decoded) > 40:109return (None, None)110if data[0] > 16:111return (None, None)112if data[0] == 0 and len(decoded) != 20 and len(decoded) != 32:113return (None, None)114if (data[0] == 0 and encoding != Encoding.BECH32) or (data[0] != 0 and encoding != Encoding.BECH32M):115return (None, None)116return (data[0], decoded)119def encode_segwit_address(hrp, witver, witprog):120"""Encode a segwit address."""121encoding = Encoding.BECH32 if witver == 0 else Encoding.BECH32M122ret = bech32_encode(encoding, hrp, [witver] + convertbits(witprog, 8, 5))123if decode_segwit_address(hrp, ret) == (None, None):124return None125return ret127class TestFrameworkScript(unittest.TestCase):128def test_segwit_encode_decode(self):129def test_python_bech32(addr):130hrp = addr[:4]131self.assertEqual(hrp, "bcrt")132(witver, witprog) = decode_segwit_address(hrp, addr)133self.assertEqual(encode_segwit_address(hrp, witver, witprog), addr)135# P2WPKH136test_python_bech32('bcrt1qthmht0k2qnh3wy7336z05lu2km7emzfpm3wg46')137# P2WSH138test_python_bech32('bcrt1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3xueyj')139test_python_bech32('bcrt1qft5p2uhsdcdc3l2ua4ap5qqfg4pjaqlp250x7us7a8qqhrxrxfsqseac85')140# P2TR141test_python_bech32('bcrt1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqc8gma6')
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.