import hashlib


def entropy_to_masterkey(entropy: bytes) -> bytes:
    """Derive master key from entropy.

    Algorithm is specified in:
    https://github.com/cardano-foundation/CIPs/blob/master/CIP-0003/Icarus.md

    Test vector from CIP-0003:
    >>> e = bytes.fromhex('46e62370a138a182a498b8e2885bc032379ddf38')
    >>> entropy_to_masterkey(e).hex()
    'c065afd2832cd8b087c4d9ab7011f481ee1e0721e78ea5dd609f3ab3f156d245d176bd\
8fd4ec60b4731c3918a2a72a0226c0cd119ec35b47e4d55884667f552a23f7fdcd4a10c6cd2\
c7393ac61d877873e248f417634aa3d812af327ffe9d620'

    Test wallets of PySeedRecover:
    >>> e = bytes.fromhex('7c7079e639eedf56920e134b606a49f8'
    ...                   '8ba21d42d0be517b8f29ecc6498c980b')
    >>> entropy_to_masterkey(e).hex()
    '00d370bf9e756fba12e7fa389a3551b97558b140267c88166136d4f0d2bea75c393f5e\
3e63e61578342fa8ab1313a7315693c5e679e3cf79f7fe8f13bf8ffe9c2a67ac173bbb2afd3\
4381905fa247c65c0d8eb66c42d2373d54bd5eef73e49da'
    >>> e = bytes.fromhex('7c7079e639eedf56920e134b606a49f8'
    ...                   '8ba21d42d0be517b8f29ecc6498c980f')
    >>> entropy_to_masterkey(e).hex()
    'b03595d980ab77fac0d95d0e563de43ad2978b2a22e8f0a14ad69a1964eddf5ed13ffc\
0e596edf974cb477cb08c5fc499efbaafa5103a2afa6094468759c1d1c694734296dd915dd1\
61df3703a3c1e0b4562fad0b67fdbf3fa7b819791cc5cac'
    """
    key = bytearray(hashlib.pbkdf2_hmac('sha512', b'', entropy, 4096, 96))
    key[0] &= 0b11111000
    key[31] &= 0b00011111
    key[31] |= 0b01000000
    return key