Esempio n. 1
0
    def test_invalid_paths(self):
        seed = binascii.unhexlify(b"000102030405060708090a0b0c0d0e0f")

        for test in TEST_VECT_PATH_INVALID:
            self.assertEqual([], Bip32PathParser.Parse(test["path"], test["skip_master"]))

            # Try to derive an invalid path
            bip32 = Bip32.FromSeed(seed)
            self.assertRaises(Bip32PathError, bip32.DerivePath, test["path"])
            # Try to construct from an invalid path (Bip32.FromSeedAndPath does not skip master)
            if not test["skip_master"]:
                self.assertRaises(Bip32PathError, Bip32.FromSeedAndPath, b"", test["path"])
Esempio n. 2
0
    def test_from_seed_with_derive_path(self):
        for test in TEST_VECT_BIP32:
            # Create from seed
            bip32_ctx = Bip32.FromSeed(binascii.unhexlify(test["seed"]))
            # Test master key
            self.assertEqual(test["master"]["ex_pub"] , bip32_ctx.PublicKey().ToExtended())
            self.assertEqual(test["master"]["ex_priv"], bip32_ctx.PrivateKey().ToExtended())

            # Test derivation paths
            for chain in test["der_paths"]:
                # Update context
                bip32_from_path = bip32_ctx.DerivePath(chain["path"][2:])
                # Test keys
                self.assertEqual(chain["ex_pub"] , bip32_from_path.PublicKey().ToExtended())
                self.assertEqual(chain["ex_priv"], bip32_from_path.PrivateKey().ToExtended())
Esempio n. 3
0
    def test_from_seed_with_child_key(self):
        for test in TEST_BIP32_MAIN:
            # Create from seed
            bip32_ctx = Bip32.FromSeed(binascii.unhexlify(test["seed"]))
            # Test master key
            self.assertEqual(test["master"]["ex_pub"],
                             bip32_ctx.PublicKey().ToExtended())
            self.assertEqual(test["master"]["ex_priv"],
                             bip32_ctx.PrivateKey().ToExtended())

            # Test derivation paths
            for chain in test["der_paths"]:
                # Update context
                bip32_ctx = bip32_ctx.ChildKey(chain["index"])
                # Test keys
                self.assertEqual(chain["ex_pub"],
                                 bip32_ctx.PublicKey().ToExtended())
                self.assertEqual(chain["ex_priv"],
                                 bip32_ctx.PrivateKey().ToExtended())
Esempio n. 4
0
def mnemonic_to_private_key(mnemonic, network, pass_phrase=''):
    """Convert mnemonic (phrase) to a private key

    :param mnemonic: A phrase
    :type mnemonic: str
    :param network: testnet or mainnet
    :type mnemonic: str
    :param pass_phrase: A password
    :type pass_phrase: str
    :returns: private key
    """
    seed = mnemonic_to_seed(mnemonic, pass_phrase)
    bip32_ctx = Bip32.FromSeed(seed)
    HD_PATH = get_derive_path(
    ).testnet if network == "testnet" else get_derive_path().mainnet
    hd_path = HD_PATH[2:]

    bip32_ctx = bip32_ctx.DerivePath(hd_path)
    priv_key = bip32_ctx.PrivateKey().Raw().ToHex()
    return priv_key
Esempio n. 5
0
def generate_uuid(mnemonic, passphrase=""):
    # At this point the Cobo Vault hardware is directly using the (secret)
    # BIP39 mnemonic, converting it to a BIP39 seed value.  If one is using a
    # Shamir (SLIP39) mnemonic a different path is taken to generate these
    # seed bytes.
    seed_bytes = Bip39SeedGenerator(mnemonic).Generate(passphrase)

    # From this point onwards the code is identical whether a BIP39 or SLIP39
    # mnemonic.  The following extracts the BIP32 Root Key. This is still secret
    # data that we don't want leaking from the Cobo Vault hardware.
    bip32_root = Bip32.FromSeed(seed_bytes)

    # Given the BIP32 root key, derive a BIP32 extended (public/private) keypair,
    # using Cobo's BIP32 derivation path.  Note that this path is only used for
    # generating the 'UUID' used by the Cobo Vault (and app).  For coin-specific
    # (e.g. Bitcoin etc.) keys the Cobo Vault hardware and App use more typical
    # hardened paths that are commonly used -  E.g. m/49'/0'/0' for bitcoin,
    # m/44'/60'/0' for Ethereum, etc. Still secret data here!
    cobo_extend_key = (
        bip32_root.ChildKey(Bip32Utils.HardenIndex(44))
        .ChildKey(Bip32Utils.HardenIndex(1131373167))
        .ChildKey(Bip32Utils.HardenIndex(0))
    )

    # Up until this point the Cobo Vault hardware has been dealing with secret
    # information that should never be leaked outside the device, as doing so
    # would allow stealing of one's keys and thus cryptocurrency.  The next step
    # discards the private key information and extracts the public key only.  The
    # public key can be used to find all transactions associated with a wallet, but
    # it *cannot* be used to spend (or steal) cryptocurrency.
    public_key = cobo_extend_key.PublicKey().RawCompressed().ToHex()

    # After discarding the private (secret) key, compress the public key and remove
    # a couple bytes to produce the 'uuid'.
    uuid = public_key[2:]
    return uuid
from avaxpython import Config
from avaxpython.utils.formatting.encoding import Encoding
from bip_utils import Bip32
import  ref
import json

sample_wallet = next(generator.generate(1, Config.KEY_SIZE))
word_length = len(sample_wallet.split(" "))

if len(sys.argv) != word_length+1:
    print("Invalid phrase length provided. Got {} expected {}.".format(len(sys.argv)-1, word_length))
    exit(1)

seed = Mnemonic("english").to_seed(" ".join(sys.argv[1:]), passphrase="")

masterHdKey = Bip32.FromSeed(seed)
accountHdKey = Bip32.FromSeedAndPath(seed, WalletConfig.AVA_ACCOUNT_PATH)

# the first private key generated by an HD wallet seeded from this mnemonic phrase
firstHDKey = BIP32.derive_master_key(accountHdKey, '0/0')

masterKey = masterHdKey.PrivateKey().Raw().ToBytes()
accountKey = accountHdKey.PrivateKey().Raw().ToBytes()
firstKey = firstHDKey.PrivateKey().Raw().ToBytes()

enc = Encoding()
pkey_prefix = "PrivateKey-{}"

masterKeyEncoded = pkey_prefix.format(enc.Encode(masterKey))
accountKeyEncoded = pkey_prefix.format(enc.Encode(accountKey))
firstKeyEncoded = pkey_prefix.format(enc.Encode(firstKey))
Esempio n. 7
0
from bip_utils import Bip32, Bip39SeedGenerator
from binascii import hexlify

if len(sys.argv) < 2 or sys.argv[1] == "":
    print("No mnemonic given")
    exit(1)

mnemonic = sys.argv[1]

words = mnemonic.split(" ")
print("BIP39 mnemonic starts with: {} {} ...".format(words[0], words[1]))

seed_bytes = Bip39SeedGenerator(mnemonic).Generate()
print("BIP39 seed: {}".format(hexlify(seed_bytes).decode("utf-8")))

bip32 = Bip32.FromSeed(seed_bytes)
print("BIP32 root key: {}".format(bip32.PrivateKey().ToExtended()))

derivation_path = "m/44'/60'/0'/0"

extended = Bip32.FromSeedAndPath(seed_bytes, derivation_path)
print("BIP32 extended public key: {}".format(
    extended.PublicKey().ToExtended()))
print("BIP32 extended private key: {}".format(
    extended.PrivateKey().ToExtended()))

derived_0_path = f"{derivation_path}/0"
derived_0_address = extended.DerivePath("0")
print("Derived {} public key: {}".format(
    derived_0_path,
    derived_0_address.EcdsaPublicKey().RawCompressed().ToHex()))
Esempio n. 8
0
def key_from_seed(seed):
    """Return master private key from this seed"""
    bip32_ctx = Bip32.FromSeed(seed)

    return bip32_ctx