def sign_p2pkh(tx, i, priv, pub, hashtype = SIGHASH_ALL): assert isinstance(tx, dict) i = int(i) assert isinstance(priv, int) assert isinstance(pub, bytes) address = hashes.hash160(pub) prev_script = script.make_p2pkh(address) txhash = sighash(tx, i, prev_script, hashtype) sig = ecdsa.sign(txhash, priv) sig = ecdsa.serialize_sig(sig) + convert.int_to_byte(hashtype) tx["ins"][i]["script"] = script.serialize([sig, pub])
def derive_xpub(k, i): i = int(i) if i >= 2**31: raise Exception("Can't do private derivation on public key!") pub = k['pub'] pub_ser = ecdsa.serialize_pub(pub) hmacdata = pub_ser + convert.int_to_bytes(i, 4) I = hmac.new(k['chaincode'], hmacdata, hashlib.sha512).digest() return { 'depth': k['depth'] + 1, 'fingerprint': hashes.hash160(pub_ser)[:4], 'i': i, 'chaincode': I[32:], 'pub': ec.add(k['pub'], ecdsa.priv_to_pub(ecdsa.deserialize_priv(I[:32]))) }
def derive_xpriv(k, i): i = int(i) pub = ecdsa.priv_to_pub(k['priv']) pub_ser = ecdsa.serialize_pub(pub) priv_ser = ecdsa.serialize_priv(k['priv']) if i >= 2**31: hmacdata = b'\x00' + priv_ser + convert.int_to_bytes(i, 4) else: hmacdata = pub_ser + convert.int_to_bytes(i, 4) I = hmac.new(k['chaincode'], hmacdata, hashlib.sha512).digest() return { 'depth': k['depth'] + 1, 'fingerprint': hashes.hash160(pub_ser)[:4], 'i': i, 'chaincode': I[32:], 'priv': ec.add_scalar(k['priv'], ecdsa.deserialize_priv(I[:32])) }
def pub_to_addr(pub): assert isinstance(pub, bytes) return hash_to_addr(hashes.hash160(pub))