def bip32_crack(parent_xpub: bytes, child_xprv: bytes) -> bytes:
    parent_xpub = b58decode_check(parent_xpub, 78)
    assert parent_xpub[45] in (2, 3), "extended parent key is not a public one"

    child_xprv = b58decode_check(child_xprv, 78)
    assert child_xprv[45] == 0, "extended child key is not a private one"

    # check depth
    assert child_xprv[4] == parent_xpub[4]+1, "wrong child/parent depth relation"

    # check fingerprint
    Parent_bytes = parent_xpub[45:  ]
    assert child_xprv[ 5: 9] == h160(Parent_bytes)[:4], "not a child for the provided parent"

    # check normal derivation
    child_index  =  child_xprv[ 9:13]
    assert child_index[0] < 0x80, "hardened derivation"

    parent_xprv =   child_xprv[  : 4] # version
    parent_xprv += parent_xpub[ 4: 5] # depth
    parent_xprv += parent_xpub[ 5: 9] # parent pubkey fingerprint
    parent_xprv += parent_xpub[ 9:13] # child index

    parent_chain_code = parent_xpub[13:45]
    parent_xprv += parent_chain_code  # chain code

    h = HMAC(parent_chain_code, Parent_bytes + child_index, sha512).digest()
    offset = int.from_bytes(h[:32], 'big')
    child = int.from_bytes(child_xprv[46:], 'big')
    parent = (child - offset) % ec.n
    parent_bytes = b'\x00' + parent.to_bytes(32, 'big')
    parent_xprv += parent_bytes        # private key

    return b58encode_check(parent_xprv)
def bip32_derive(xkey: octets, path: str) -> bytes:
    """derive an extended key according to path like
       "m/44'/0'/1'/0/10" (absolute) or "./0/10" (relative)
    """

    indexes = []
    if isinstance(path, list):
        indexes = path
    elif isinstance(path, str):
        steps = path.split('/')
        if steps[0] not in {'m', '.'}:
            raise ValueError(f'Invalid derivation path: {path}')
        if steps[0] == 'm':
            decoded = b58decode_check(xkey, 78)
            t = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00'
            assert decoded[
                4:
                13] == t, "Trying to derive absolute path from non-master key"

        for step in steps[1:]:
            hardened = False
            if step[-1] == "'" or step[-1] == "H":
                hardened = True
                step = step[:-1]
            index = int(step)
            index += 0x80000000 if hardened else 0
            indexes.append(index)
    else:
        raise TypeError(
            "list of indexes or string like 'm/44'/0'/1'/0/10' expected")

    for index in indexes:
        xkey = bip32_ckd(xkey, index)

    return xkey
    def test_wif(self):
        # https://en.bitcoin.it/wiki/Wallet_import_format
        prvkey = 0xC28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D

        uncompressedKey = b'\x80' + prvkey.to_bytes(32, byteorder='big')
        uncompressedWIF = b'5HueCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbTLvyTJ'
        wif = b58encode_check(uncompressedKey)
        self.assertEqual(wif, uncompressedWIF)
        key = b58decode_check(uncompressedWIF)
        self.assertEqual(key, uncompressedKey)

        compressedKey = b'\x80' + prvkey.to_bytes(32,
                                                  byteorder='big') + b'\x01'
        compressedWIF = b'KwdMAjGmerYanjeui5SHS7JkmpZvVipYvB2LJGU1ZxJwYvP98617'
        wif = b58encode_check(compressedKey)
        self.assertEqual(wif, compressedWIF)
        key = b58decode_check(compressedWIF)
        self.assertEqual(key, compressedKey)

        # string
        compressedWIF = 'KwdMAjGmerYanjeui5SHS7JkmpZvVipYvB2LJGU1ZxJwYvP98617'
        key = b58decode_check(compressedWIF)
        self.assertEqual(key, compressedKey)

        # string with leading space
        compressedWIF = ' KwdMAjGmerYanjeui5SHS7JkmpZvVipYvB2LJGU1ZxJwYvP98617'
        b58decode_check(compressedWIF)
        self.assertEqual(key, compressedKey)

        # string with trailing space
        compressedWIF = 'KwdMAjGmerYanjeui5SHS7JkmpZvVipYvB2LJGU1ZxJwYvP98617 '
        b58decode_check(compressedWIF)
        self.assertEqual(key, compressedKey)
예제 #4
0
def address_from_xpub(xpub: bytes, version: Optional[bytes] = None):
    xpub = b58decode_check(xpub, 78)
    assert xpub[45] in (2, 3), "extended key is not a public one"
    # bitcoin: address version can be derived from xkey version
    # altcoin: address version cannot be derived from xkey version
    #          if xkey version bytes have not been specialized
    # FIXME use BIP44 here
    if version is None:
        xversion = xpub[:4]
        i = PUBLIC.index(xversion)
        version = ADDRESS[i]
    return address_from_pubkey(xpub[45:], version)
예제 #5
0
def prvkey_from_wif(wif: octets) -> Tuple[int, bool]:
    """Wallet Import Format to (bytes) private key"""

    payload = b58decode_check(wif)
    assert payload[0] == 0x80, "not a WIF"

    if len(payload) == ec.psize + 2:  # compressed WIF
        # must have a trailing 0x01
        assert payload[ec.psize + 1] == 0x01, "not a WIF"
        return octets2int(payload[1:-1]), True
    elif len(payload) == ec.psize + 1:  # uncompressed WIF
        return octets2int(payload[1:]), False

    raise ValueError("not a WIF")
예제 #6
0
def prvkey_from_wif(wif: WIF) -> bytes:
    """Wallet Import Format to (bytes) private key"""

    payload = b58decode_check(wif)
    assert payload[0] == 0x80, "not a WIF"

    if len(payload) == ec.bytesize + 2:   # compressed WIF
        # must have a trailing 0x01
        assert payload[ec.bytesize + 1] == 0x01, "not a WIF"
        return bytes_from_Scalar(ec, payload[1:-1]), True
    elif len(payload) == ec.bytesize + 1: # uncompressed WIF
        return bytes_from_Scalar(ec, payload[1:]), False

    raise ValueError("not a WIF")
예제 #7
0
def bip32_xpub_from_xprv(xprv: bytes) -> bytes:
    """Neutered Derivation (ND)
    
    Computation of the extended public key corresponding to an extended
    private key (“neutered” as it removes the ability to sign transactions)
    """
    xprv = b58decode_check(xprv, 78)
    assert xprv[45] == 0, "extended key is not a private one"

    i = PRIVATE.index(xprv[:4])

    # serialization data
    xpub = PUBLIC[i]  # version
    # unchanged serialization data
    xpub += xprv[4:5]  # depth
    xpub += xprv[5:9]  # parent pubkey fingerprint
    xpub += xprv[9:13]  # child index
    xpub += xprv[13:45]  # chain code

    p = xprv[46:]
    P = pointMultiply(ec, p, ec.G)
    xpub += bytes_from_Point(ec, P, True)  # public key
    return b58encode_check(xpub)
예제 #8
0
def hash160_from_address(addr: octets) -> bytes:
    payload = b58decode_check(addr, 21)
    # FIXME: this is mainnet only
    assert payload[0] == 0x00, "not an address"
    return payload[1:]
def bip32_ckd(xparentkey: octets, index: Union[octets, int]) -> bytes:
    """Child Key Derivation (CDK)

    Key derivation is normal if the extended parent key is public or
    child_index is less than 0x80000000.

    Key derivation is hardened if the extended parent key is private and
    child_index is not less than 0x80000000.
    """

    if isinstance(index, int):
        index = index.to_bytes(4, 'big')
    elif isinstance(index, str):  # hex string
        index = bytes.fromhex(index)

    if len(index) != 4:
        raise ValueError(f"a 4 bytes int is required, not {len(index)}")

    xparent = b58decode_check(xparentkey, 78)

    version = xparent[:4]

    # serialization data
    xkey = version  # version
    xkey += (xparent[4] + 1).to_bytes(1, 'big')  # (increased) depth

    if (version in PUBLIC):
        if xparent[45] not in (2, 3):  # not a compressed public key
            raise ValueError("version/key mismatch in extended parent key")
        Parent_bytes = xparent[45:]
        Parent = octets2point(ec, Parent_bytes)
        xkey += h160(Parent_bytes)[:4]  # parent pubkey fingerprint
        if index[0] >= 0x80:
            raise ValueError("no private/hardened derivation from pubkey")
        xkey += index  # child index
        parent_chain_code = xparent[13:45]  # normal derivation
        # actual extended key (key + chain code) derivation
        h = HMAC(parent_chain_code, Parent_bytes + index, sha512).digest()
        offset = int.from_bytes(h[:32], 'big')
        Offset = pointMult(ec, offset, ec.G)
        Child = ec.add(Parent, Offset)
        Child_bytes = point2octets(ec, Child, True)
        xkey += h[32:]  # chain code
        xkey += Child_bytes  # public key
    elif (version in PRIVATE):
        if xparent[45] != 0:  # not a private key
            raise ValueError("version/key mismatch in extended parent key")
        parent = int.from_bytes(xparent[46:], 'big')
        Parent = pointMult(ec, parent, ec.G)
        Parent_bytes = point2octets(ec, Parent, True)
        xkey += h160(Parent_bytes)[:4]  # parent pubkey fingerprint
        xkey += index  # child index
        # actual extended key (key + chain code) derivation
        parent_chain_code = xparent[13:45]
        if (index[0] < 0x80):  # normal derivation
            h = HMAC(parent_chain_code, Parent_bytes + index, sha512).digest()
        else:  # hardened derivation
            h = HMAC(parent_chain_code, xparent[45:] + index, sha512).digest()
        offset = int.from_bytes(h[:32], 'big')
        child = (parent + offset) % ec.n
        child_bytes = b'\x00' + child.to_bytes(32, 'big')
        xkey += h[32:]  # chain code
        xkey += child_bytes  # private key
    else:
        raise ValueError("invalid extended key version")

    return b58encode_check(xkey)
def bip32_child_index(xkey: octets) -> bytes:
    xkey = b58decode_check(xkey, 78)
    if xkey[4] == 0:
        raise ValueError("master key provided")
    return xkey[9:13]
예제 #11
0
def bip32_ckd(xparentkey: bytes, index: Union[bytes, int]) -> bytes:
    """Child Key Derivation (CDK)

    Key derivation is normal if the extended parent key is public or
    child_index is less than 0x80000000.
    
    Key derivation is hardened if the extended parent key is private and
    child_index is not less than 0x80000000.
    """

    if isinstance(index, int):
        index = index.to_bytes(4, 'big')
    elif isinstance(index, bytes):
        assert len(index) == 4
    else:
        raise TypeError("a 4 bytes int is required")

    xparent = b58decode_check(xparentkey, 78)

    version = xparent[:4]

    # serialization data
    xkey = version  # version
    xkey += (xparent[4] + 1).to_bytes(1, 'big')  # (increased) depth

    if (version in PUBLIC):
        assert xparent[45] in (2, 3), \
               "version/key mismatch in extended parent key"
        Parent_bytes = xparent[45:]
        Parent = tuple_from_Point(ec, Parent_bytes)
        xkey += h160(Parent_bytes)[:4]  # parent pubkey fingerprint
        assert index[0] < 0x80, \
               "no private/hardened derivation from pubkey"
        xkey += index  # child index
        parent_chain_code = xparent[13:45]  ## normal derivation
        # actual extended key (key + chain code) derivation
        h = HMAC(parent_chain_code, Parent_bytes + index, sha512).digest()
        offset = int.from_bytes(h[:32], 'big')
        Offset = ec.pointMultiply(offset, ec.G)
        Child = ec.pointAdd(Parent, Offset)
        Child_bytes = bytes_from_Point(ec, Child, True)
        xkey += h[32:]  # chain code
        xkey += Child_bytes  # public key
    elif (version in PRIVATE):
        assert xparent[45] == 0, "version/key mismatch in extended parent key"
        parent = int.from_bytes(xparent[46:], 'big')
        Parent = ec.pointMultiply(parent, ec.G)
        Parent_bytes = bytes_from_Point(ec, Parent, True)
        xkey += h160(Parent_bytes)[:4]  # parent pubkey fingerprint
        xkey += index  # child index
        # actual extended key (key + chain code) derivation
        parent_chain_code = xparent[13:45]
        if (index[0] < 0x80):  ## normal derivation
            h = HMAC(parent_chain_code, Parent_bytes + index, sha512).digest()
        else:  ## hardened derivation
            h = HMAC(parent_chain_code, xparent[45:] + index, sha512).digest()
        offset = int.from_bytes(h[:32], 'big')
        child = (parent + offset) % ec.order
        child_bytes = b'\x00' + child.to_bytes(32, 'big')
        xkey += h[32:]  # chain code
        xkey += child_bytes  # private key
    else:
        raise ValueError("invalid extended key version")

    return b58encode_check(xkey)
    def test_mainnet(self):
        # bitcoin core derivation style
        mprv = b'xprv9s21ZrQH143K2ZP8tyNiUtgoezZosUkw9hhir2JFzDhcUWKz8qFYk3cxdgSFoCMzt8E2Ubi1nXw71TLhwgCfzqFHfM5Snv4zboSebePRmLS'

        # m/0'/0'/463'
        addr1 = b'1DyfBWxhVLmrJ7keyiHeMbt7N3UdeGU4G5'
        indexes = [0x80000000, 0x80000000, 0x80000000 + 463]
        addr = address_from_xpub(
            bip32_xpub_from_xprv(bip32_derive(mprv, indexes)))
        self.assertEqual(addr, addr1)
        path = "m/0'/0'/463'"
        addr = address_from_xpub(bip32_xpub_from_xprv(bip32_derive(mprv,
                                                                   path)))
        self.assertEqual(addr, addr1)

        # m/0'/0'/267'
        addr2 = b'11x2mn59Qy43DjisZWQGRResjyQmgthki'
        indexes = [0x80000000, 0x80000000, 0x80000000 + 267]
        addr = address_from_xpub(
            bip32_xpub_from_xprv(bip32_derive(mprv, indexes)))
        self.assertEqual(addr, addr2)
        path = "m/0'/0'/267'"
        addr = address_from_xpub(bip32_xpub_from_xprv(bip32_derive(mprv,
                                                                   path)))
        self.assertEqual(addr, addr2)

        xkey_version = PRIVATE[0]
        seed = "bfc4cbaad0ff131aa97fa30a48d09ae7df914bcc083af1e07793cd0a7c61a03f65d622848209ad3366a419f4718a80ec9037df107d8d12c19b83202de00a40ad"
        seed = bytes.fromhex(seed)
        xprv = bip32_mprv_from_seed(seed, xkey_version)
        xpub = b'xpub661MyMwAqRbcFMYjmw8C6dJV97a4oLss6hb3v9wTQn2X48msQB61RCaLGtNhzgPCWPaJu7SvuB9EBSFCL43kTaFJC3owdaMka85uS154cEh'
        self.assertEqual(bip32_xpub_from_xprv(xprv), xpub)

        ind = [0, 0]
        addr = address_from_xpub(bip32_xpub_from_xprv(bip32_derive(xprv, ind)))
        self.assertEqual(addr, b'1FcfDbWwGs1PmyhMVpCAhoTfMnmSuptH6g')

        ind = [0, 1]
        addr = address_from_xpub(bip32_xpub_from_xprv(bip32_derive(xprv, ind)))
        self.assertEqual(addr, b'1K5GjYkZnPFvMDTGaQHTrVnd8wjmrtfR5x')

        ind = [0, 2]
        addr = address_from_xpub(bip32_xpub_from_xprv(bip32_derive(xprv, ind)))
        self.assertEqual(addr, b'1PQYX2uN7NYFd7Hq22ECMzfDcKhtrHmkfi')

        ind = [1, 0]
        addr = address_from_xpub(bip32_xpub_from_xprv(bip32_derive(xprv, ind)))
        self.assertEqual(addr, b'1BvSYpojWoWUeaMLnzbkK55v42DbizCoyq')

        ind = [1, 1]
        addr = address_from_xpub(bip32_xpub_from_xprv(bip32_derive(xprv, ind)))
        self.assertEqual(addr, b'1NXB59hF4QzYpFrB7o6usLBjbk2D3ZqxAL')

        ind = [1, 2]
        addr = address_from_xpub(bip32_xpub_from_xprv(bip32_derive(xprv, ind)))
        self.assertEqual(addr, b'16NLYkKtvYhW1Jp86tbocku3gxWcvitY1w')

        # version/key mismatch in extended parent key
        bmprv = b58decode_check(mprv)
        bad_mprv = b58encode_check(bmprv[0:45] + b'\x01' + bmprv[46:])
        self.assertRaises(ValueError, bip32_ckd, bad_mprv, 1)
        #bip32_ckd(bad_mprv, 1)

        # version/key mismatch in extended parent key
        mpub = bip32_xpub_from_xprv(mprv)
        bmpub = b58decode_check(mpub)
        bad_mpub = b58encode_check(bmpub[0:45] + b'\x00' + bmpub[46:])
        self.assertRaises(ValueError, bip32_ckd, bad_mpub, 1)
        #bip32_ckd(bad_mpub, 1)

        # no private/hardened derivation from pubkey
        self.assertRaises(ValueError, bip32_ckd, mpub, 0x80000000)
def hash_160_from_address(addr):
    return b58decode_check(addr)[1:21]
print("\n*** [7] Base58 encoding")
wif = b58encode(addr)
print(wif)
assert wif == b'KwdMAjGmerYanjeui5SHS7JkmpZvVipYvB2LJGU1ZxJwYvP98617', "failure"
assert b58encode_check(
    ExtKey
) == b'KwdMAjGmerYanjeui5SHS7JkmpZvVipYvB2LJGU1ZxJwYvP98617', "failure"

print("\n****** WIF to private key ******")

print("\n*** [1] Base58 WIF")
print(wif)
compressed = len(wif) - 51
print("compressed" if (compressed == 1) else "uncompressed")

print("\n*** [2] Base58 decoding")
addr = b58decode(wif)
print(addr.hex())

print("\n*** [3] Extended key (checksum verified)")
ExtKey, checksum = addr[:-4], addr[-4:]
verified = (sha256(sha256(ExtKey).digest()).digest()[:4] == checksum)
print(ExtKey.hex() + " (" + ("true" if verified else "false") + ")")
print(b58decode_check(wif).hex())

print("\n*** [4] Private key")
p2 = ExtKey[1:-1].hex() if compressed else ExtKey[1:].hex()
assert int(p2, 16) == p, "failure"
print(p2)