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) 2016-present The Bitcoin Core developers3# Distributed under the MIT software license, see the accompanying4# file COPYING or http://www.opensource.org/licenses/mit-license.php.5"""Encode and decode Bitcoin addresses.7- base58 P2PKH and P2SH addresses.8- bech32 segwit v0 P2WPKH and P2WSH addresses.9- bech32m segwit v1 P2TR addresses."""11import unittest13from .script import (14CScript,15OP_0,16OP_TRUE,17hash160,18hash256,19sha256,20taproot_construct,21)22from .util import assert_equal23from test_framework.script_util import (24keyhash_to_p2pkh_script,25program_to_witness_script,26scripthash_to_p2sh_script,27)28from test_framework.segwit_addr import (29decode_segwit_address,30encode_segwit_address,31)34ADDRESS_BCRT1_UNSPENDABLE = 'bcrt1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3xueyj'35ADDRESS_BCRT1_UNSPENDABLE_DESCRIPTOR = 'addr(bcrt1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3xueyj)#juyq9d97'36# Coins sent to this address can be spent with a witness stack of just OP_TRUE37ADDRESS_BCRT1_P2WSH_OP_TRUE = 'bcrt1qft5p2uhsdcdc3l2ua4ap5qqfg4pjaqlp250x7us7a8qqhrxrxfsqseac85'39b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'42def create_deterministic_address_bcrt1_p2tr_op_true(explicit_internal_key=None):43"""44Generates a deterministic bech32m address (segwit v1 output) that45can be spent with a witness stack of OP_TRUE and the control block46with internal public key (script-path spending).48Returns a tuple with the generated address and the TaprootInfo object.49"""50internal_key = explicit_internal_key or (1).to_bytes(32, 'big')51taproot_info = taproot_construct(internal_key, [("only-path", CScript([OP_TRUE]))])52address = output_key_to_p2tr(taproot_info.output_pubkey)53if explicit_internal_key is None:54assert_equal(address, 'bcrt1p9yfmy5h72durp7zrhlw9lf7jpwjgvwdg0jr0lqmmjtgg83266lqsekaqka')55return (address, taproot_info)58def byte_to_base58(b, version):59if isinstance(version, int):60version = bytes([version])61b = version + b # prepend version62b += hash256(b)[:4] # append checksum63value = int.from_bytes(b, 'big')64result = ''65while value > 0:66result = b58chars[value % 58] + result67value //= 5868while b[0] == 0:69result = b58chars[0] + result70b = b[1:]71return result74def base58_to_byte(s):75"""Converts a base58-encoded string to its data and version.77Throws if the base58 checksum is invalid."""78if not s:79return b''80n = 081for c in s:82n *= 5883assert c in b58chars84digit = b58chars.index(c)85n += digit86h = '%x' % n87if len(h) % 2:88h = '0' + h89res = n.to_bytes((n.bit_length() + 7) // 8, 'big')90pad = 091for c in s:92if c == b58chars[0]:93pad += 194else:95break96res = b'\x00' * pad + res98if hash256(res[:-4])[:4] != res[-4:]:99raise ValueError('Invalid Base58Check checksum')101return res[1:-4], int(res[0])104def keyhash_to_p2pkh(hash, main=False):105assert_equal(len(hash), 20)106version = 0 if main else 111107return byte_to_base58(hash, version)109def scripthash_to_p2sh(hash, main=False):110assert_equal(len(hash), 20)111version = 5 if main else 196112return byte_to_base58(hash, version)114def key_to_p2pkh(key, main=False):115key = check_key(key)116return keyhash_to_p2pkh(hash160(key), main)118def script_to_p2sh(script, main=False):119script = check_script(script)120return scripthash_to_p2sh(hash160(script), main)122def key_to_p2sh_p2wpkh(key, main=False):123key = check_key(key)124p2shscript = CScript([OP_0, hash160(key)])125return script_to_p2sh(p2shscript, main)127def program_to_witness(version, program, main=False):128if (type(program) is str):129program = bytes.fromhex(program)130assert 0 <= version <= 16131assert 2 <= len(program) <= 40132assert version > 0 or len(program) in [20, 32]133return encode_segwit_address("bc" if main else "bcrt", version, program)135def script_to_p2wsh(script, main=False):136script = check_script(script)137return program_to_witness(0, sha256(script), main)139def key_to_p2wpkh(key, main=False):140key = check_key(key)141return program_to_witness(0, hash160(key), main)143def script_to_p2sh_p2wsh(script, main=False):144script = check_script(script)145p2shscript = CScript([OP_0, sha256(script)])146return script_to_p2sh(p2shscript, main)148def output_key_to_p2tr(key, main=False):149assert_equal(len(key), 32)150return program_to_witness(1, key, main)152def p2a(main=False):153return program_to_witness(1, "4e73", main)155def check_key(key):156if (type(key) is str):157key = bytes.fromhex(key) # Assuming this is hex string158if (type(key) is bytes and (len(key) == 33 or len(key) == 65)):159return key160assert False162def check_script(script):163if (type(script) is str):164script = bytes.fromhex(script) # Assuming this is hex string165if (type(script) is bytes or type(script) is CScript):166return script167assert False170def bech32_to_bytes(address):171hrp = address.split('1')[0]172if hrp not in ['bc', 'tb', 'bcrt']:173return (None, None)174version, payload = decode_segwit_address(hrp, address)175if version is None:176return (None, None)177return version, bytearray(payload)180def address_to_scriptpubkey(address):181"""Converts a given address to the corresponding output script (scriptPubKey)."""182version, payload = bech32_to_bytes(address)183if version is not None:184return program_to_witness_script(version, payload) # testnet segwit scriptpubkey185payload, version = base58_to_byte(address)186if version == 111: # testnet pubkey hash187return keyhash_to_p2pkh_script(payload)188elif version == 196: # testnet script hash189return scripthash_to_p2sh_script(payload)190raise ValueError(f"Unsupported address type: {address}")193class TestFrameworkScript(unittest.TestCase):194def test_base58encodedecode(self):195def check_base58(data, version):196self.assertEqual(base58_to_byte(byte_to_base58(data, version)), (data, version))198check_base58(bytes.fromhex('1f8ea1702a7bd4941bca0941b852c4bbfedb2e05'), 111)199check_base58(bytes.fromhex('3a0b05f4d7f66c3ba7009f453530296c845cc9cf'), 111)200check_base58(bytes.fromhex('41c1eaf111802559bad61b60d62b1f897c63928a'), 111)201check_base58(bytes.fromhex('0041c1eaf111802559bad61b60d62b1f897c63928a'), 111)202check_base58(bytes.fromhex('000041c1eaf111802559bad61b60d62b1f897c63928a'), 111)203check_base58(bytes.fromhex('00000041c1eaf111802559bad61b60d62b1f897c63928a'), 111)204check_base58(bytes.fromhex('1f8ea1702a7bd4941bca0941b852c4bbfedb2e05'), 0)205check_base58(bytes.fromhex('3a0b05f4d7f66c3ba7009f453530296c845cc9cf'), 0)206check_base58(bytes.fromhex('41c1eaf111802559bad61b60d62b1f897c63928a'), 0)207check_base58(bytes.fromhex('0041c1eaf111802559bad61b60d62b1f897c63928a'), 0)208check_base58(bytes.fromhex('000041c1eaf111802559bad61b60d62b1f897c63928a'), 0)209check_base58(bytes.fromhex('00000041c1eaf111802559bad61b60d62b1f897c63928a'), 0)212def test_bech32_decode(self):213def check_bech32_decode(payload, version):214hrp = "tb"215self.assertEqual(bech32_to_bytes(encode_segwit_address(hrp, version, payload)), (version, payload))217check_bech32_decode(bytes.fromhex('36e3e2a33f328de12e4b43c515a75fba2632ecc3'), 0)218check_bech32_decode(bytes.fromhex('823e9790fc1d1782321140d4f4aa61aabd5e045b'), 0)219check_bech32_decode(bytes.fromhex('79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'), 1)220check_bech32_decode(bytes.fromhex('39cf8ebd95134f431c39db0220770bd127f5dd3cc103c988b7dcd577ae34e354'), 1)221check_bech32_decode(bytes.fromhex('708244006d27c757f6f1fc6f853b6ec26268b727866f7ce632886e34eb5839a3'), 1)222check_bech32_decode(bytes.fromhex('616211ab00dffe0adcb6ce258d6d3fd8cbd901e2'), 0)223check_bech32_decode(bytes.fromhex('b6a7c98b482d7fb21c9fa8e65692a0890410ff22'), 0)224check_bech32_decode(bytes.fromhex('f0c2109cb1008cfa7b5a09cc56f7267cd8e50929'), 0)
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.