def address_to_script(addr: str) -> bytes: """https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#segwit-address-format""" hrp, _ = bech32.bech32_decode(addr) if hrp not in [net['hrp'] for net in networks.values()]: raise Bech32DecodeError('Invalid human-readable part') witver, witprog = bech32.decode(hrp, addr) if not (0 <= witver <= 16): raise Bech32DecodeError('Invalid witness version') script = witness_byte(witver) + push(bytes(witprog)) return script
def _receive(self, value: int): """Creates an output that sends to this address""" addr_type = self.type() output = Output(value=value, script=b'') if addr_type == ADDRESS.P2PKH: address = base58.decode(self.address).rjust(25, b'\x00') keyhash = address[1:-4] output.script = OP.DUP.byte + OP.HASH160.byte + push( keyhash) + OP.EQUALVERIFY.byte + OP.CHECKSIG.byte elif addr_type == ADDRESS.P2SH: address = base58.decode(self.address).rjust(25, b'\x00') scripthash = address[1:-4] output.script = OP.HASH160.byte + push(scripthash) + OP.EQUAL.byte elif addr_type in (ADDRESS.P2WPKH, ADDRESS.P2WSH): witness_version, witness_program = bech32.decode( network('hrp'), self.address) output.script = OP(bytes_to_int( witness_byte(witness_version))).byte + push( bytes(witness_program)) else: raise ValidationError(f"Cannot create output of type {addr_type}") return output
witprog = sha256(script) return bech32.encode(network('hrp'), witver, witprog) 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) key_to_addr_versions = { ADDRESS.P2PKH: lambda pub: legacy_address(pub, version_byte=network('keyhash')), # 'P2WPKH': partial(pubkey_to_p2wpkh, version_byte=0x06, witver=0x00), # WAS REPLACED BY BIP 173 ADDRESS.P2WPKH_P2SH: lambda pub: legacy_address(witness_byte(witver=0) + push( hash160(pub.encode(compressed=True))), version_byte=network('scripthash')), ADDRESS.P2WPKH: partial(pubkey_to_bech32, witver=0x00), } script_to_addr_versions = { ADDRESS.P2SH: lambda script: legacy_address(script, version_byte=network('scripthash')), # 'P2WSH': partial(script_to_p2wsh, version_byte=0x0A, witver=0x00), # WAS REPLACED BY BIP 173 ADDRESS.P2WSH_P2SH: lambda script: legacy_address(witness_byte(witver=0) + push(sha256(script) ), version_byte=network('scripthash')), ADDRESS.P2WSH: