def test_bech32_decode(self): private, public = generate_keypair() witprog = hash160(public.encode(compressed=True)) address = bech32.encode(self.hrp, self.witver, witprog) wv, decoded = bech32.decode(self.hrp, address) self.assertEqual(wv, self.witver) self.assertEqual(bytes(decoded), bytes(witprog))
def test_p2wpkh(self): """https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#examples""" pubkey = PublicKey.from_hex( '0279BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798' ) self.assertEqual( bech32.encode(self.hrp, self.witver, hash160(pubkey.encode(compressed=True))), 'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4') address = pubkey_to_address(pubkey, version='P2WPKH') self.assertEqual(address, 'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4') self.assertEqual(address_type(address), ADDRESS.P2WPKH)
def get_address(script): """Extracts the address from a scriptPubkey""" script = hex_to_bytes(script) if isinstance(script, str) else script stype = get_type(script) if stype == TX.P2SH: data = script[2:22] version = network('scripthash') return hashed_payload_to_address(version + data) elif stype == TX.P2PKH: data = script[3:23] version = network('keyhash') return hashed_payload_to_address(version + data) elif stype in (TX.P2WSH, TX.P2WPKH): witver = version_byte(script) witprog = witness_program(script) return bech32.encode(network('hrp'), witver, witprog) elif stype == TX.P2PK: return "N/A" raise ValidationError(f"Unknown script type: {bytes_to_hex(script)}")
def pubkey_to_bech32(pub: PublicKey, witver: int) -> str: """https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#witness-program""" witprog = hash160(pub.encode(compressed=True)) return bech32.encode(network('hrp'), witver, witprog)
def script_to_bech32(script: bytes, witver: int) -> str: """https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#witness-program""" witprog = sha256(script) return bech32.encode(network('hrp'), witver, witprog)
def pubkey_to_bech32(pubkey, witver: int, hrp: str) -> str: """https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#witness-program""" witprog = hash160(pubkey) print('witness program:', witprog.hex()) address = bech32.encode(hrp, witver, witprog) print('address:', address)