Wednesday, June 3, 2026
HomeBitcoinLearn how to create a Bech32 tackle from a public key?

Learn how to create a Bech32 tackle from a public key?

import hashlib
from segwit_addr import bech32_decode # from BIP173 reference implementation (segwit_addr.py)

def sha256_bytes(hex_script):
return hashlib.sha256(bytes.fromhex(hex_script)).digest()

def decode_bech32_addr(addr):
hrp, information = bech32_decode(addr)
if hrp is None:
elevate ValueError(“Invalid bech32”)
witver = information[0]
# convert 5-bit teams again to bytes (use convertbits from BIP173 ref impl)
from segwit_addr import convertbits
prog = bytes(convertbits(information[1:], 5, 8, False))
return hrp, witver, prog

witness_script_hex = “522102d5795b4fc3965f6400d5ac75cbebe9c6eb4968a4d89631048e6eb85fa3909df12103191076965c4ebb8d43de56332aeee0763e2283784b737c5a1e9d95ef580cf42103cec1ee3b5fc3b02e7df812cbf7c0df6b88b20da6b9bf73a9f074d0a9b8eb6fbf53ae”
bech32_address = “bc1qgdjqv0av3q56jvd82tkdjpy7gdp9ut8tlqmgrpmv24sq90ecnvqqjwvw97”

prog_from_script = sha256_bytes(witness_script_hex)
hrp, witver, prog_from_addr = decode_bech32_addr(bech32_address)

print(“HRP:”, hrp)
print(“Witness model:”, witver)
print(“SHA256(witness_script):”, prog_from_script.hex())
print(“Decoded witness program:”, prog_from_addr.hex())
print(“Match:”, prog_from_script == prog_from_addr)bc1qgdjqv0av3q56jvd82tkdjpy7gdp9ut8tlqmgrpmv24sq90ecnvqqjwvw97

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments