def redeem_script_to_address(txin_type, redeem_script): if txin_type == 'p2sh': return hash160_to_p2sh(hash_160(bfh(redeem_script))) elif txin_type == 'p2wsh': return script_to_p2wsh(redeem_script) elif txin_type == 'p2wsh-p2sh': scriptSig = p2wsh_nested_script(redeem_script) return hash160_to_p2sh(hash_160(bfh(scriptSig))) else: raise NotImplementedError(txin_type)
def pubkey_to_address(txin_type, pubkey): if txin_type == 'p2pkh': return public_key_to_p2pkh(bfh(pubkey)) elif txin_type == 'p2wpkh': return public_key_to_p2wpkh(bfh(pubkey)) elif txin_type == 'p2wpkh-p2sh': scriptSig = p2wpkh_nested_script(pubkey) return hash160_to_p2sh(hash_160(bfh(scriptSig))) else: raise NotImplementedError(txin_type)
def bip32_public_derivation(xpub, branch, sequence): xtype, depth, fingerprint, child_number, c, cK = deserialize_xpub(xpub) if not sequence.startswith(branch): raise ValueError('incompatible branch ({}) and sequence ({})'.format( branch, sequence)) sequence = sequence[len(branch):] for n in sequence.split('/'): if n == '': continue i = int(n) parent_cK = cK cK, c = CKD_pub(cK, c, i) depth += 1 fingerprint = hash_160(parent_cK)[0:4] child_number = bfh("%08X" % i) return serialize_xpub(xtype, c, cK, depth, fingerprint, child_number)
def bip32_private_derivation(xprv, branch, sequence): if not sequence.startswith(branch): raise ValueError('incompatible branch ({}) and sequence ({})'.format( branch, sequence)) if branch == sequence: return xprv, xpub_from_xprv(xprv) xtype, depth, fingerprint, child_number, c, k = deserialize_xprv(xprv) sequence = sequence[len(branch):] for n in sequence.split('/'): if n == '': continue i = int(n[:-1]) + BIP32_PRIME if n[-1] == "'" else int(n) parent_k = k k, c = CKD_priv(k, c, i) depth += 1 parent_cK = ecc.ECPrivkey(parent_k).get_public_key_bytes(compressed=True) fingerprint = hash_160(parent_cK)[0:4] child_number = bfh("%08X" % i) cK = ecc.ECPrivkey(k).get_public_key_bytes(compressed=True) xpub = serialize_xpub(xtype, c, cK, depth, fingerprint, child_number) xprv = serialize_xprv(xtype, c, k, depth, fingerprint, child_number) return xprv, xpub
def p2wpkh_nested_script(pubkey): pkh = bh2u(hash_160(bfh(pubkey))) return '00' + push_script(pkh)
def public_key_to_p2wpkh(public_key): return hash_to_segwit_addr(hash_160(public_key), witver=0)
def public_key_to_p2pkh(public_key: bytes) -> str: return hash160_to_p2pkh(hash_160(public_key))
def redeem_script_to_address(txin_type, redeem_script): if txin_type == 'p2sh': return hash160_to_p2sh(hash_160(bfh(redeem_script))) else: raise NotImplementedError(txin_type)