Ejemplo n.º 1
0
def bip39(mnemonic_words, children):
    '''
    mnemonic_words: 12 word mnemonic.
    children: positive integer for num of address desired.
    FUTURE IMPLEMENT...
    - choose coin
    - return main account information
    '''
    mobj = mnemonic.Mnemonic("english")
    seed = mobj.to_seed(mnemonic_words)
    holder = {}
    if children < 0:
        raise ValueError('Children must be positive.')
    for child in range(children):
        bip32_root_key_obj = bip32utils.BIP32Key.fromEntropy(seed)
        bip32_child_key_obj = bip32_root_key_obj.ChildKey(
            44 + bip32utils.BIP32_HARDEN).ChildKey(
                0 + bip32utils.BIP32_HARDEN).ChildKey(
                    0 + bip32utils.BIP32_HARDEN).ChildKey(0).ChildKey(child)
        template = {
            'mnemonic_words': mnemonic_words,
            'bip32_root_key': bip32_root_key_obj.ExtendedKey(),
            'bip32_extended_private_key': bip32_child_key_obj.ExtendedKey(),
            'path': f"m/44'/0'/0'/{child}",
            'address': bip32_child_key_obj.Address(),
            'publickey':
            binascii.hexlify(bip32_child_key_obj.PublicKey()).decode(),
            'privatekey': bip32_child_key_obj.WalletImportFormat(),
            'coin': 'BTC'
        }
        holder[f'Child_{child}'] = template
        arq1.write("%s \n" % bip32_child_key_obj.WalletImportFormat())
        arq2.write("%s \n" % bip32_child_key_obj.Address())
        print(bip32_child_key_obj.WalletImportFormat())
Ejemplo n.º 2
0
 def create_seed(self):
     import mnemonic
     self.seed_type = 'standard'
     seed = mnemonic.Mnemonic('en').make_seed(self.seed_type)
     self.opt_bip39 = False
     f = lambda x: self.request_passphrase(seed, x)
     self.show_seed_dialog(run_next=f, seed_text=seed)
Ejemplo n.º 3
0
def bip39(mnemonic_words):
    mobj = mnemonic.Mnemonic("english")
    seed = mobj.to_seed(mnemonic_words)

    bip32_root_key_obj = bip32utils.BIP32Key.fromEntropy(seed)
    bip32_child_key_obj = bip32_root_key_obj.ChildKey(
        44 + bip32utils.BIP32_HARDEN).ChildKey(
            0 + bip32utils.BIP32_HARDEN).ChildKey(
                0 + bip32utils.BIP32_HARDEN).ChildKey(0).ChildKey(0)

    # return {
    #     'mnemonic_words': mnemonic_words,
    #     'bip32_root_key': bip32_root_key_obj.ExtendedKey(),
    #     'bip32_extended_private_key': bip32_child_key_obj.ExtendedKey(),
    #     'bip32_derivation_path': "m/44'/0'/0'/0",
    #     'bip32_derivation_addr': bip32_child_key_obj.Address(),
    #     'coin': 'BTC'
    # }

    return {
        'mnemonic_words': mnemonic_words,
        # 'bip32_root_key': bip32_root_key_obj.ExtendedKey(),
        # 'bip32_extended_private_key': bip32_child_key_obj.ExtendedKey(),
        # 'path': "m/44'/0'/0'/0",
        'addr': bip32_child_key_obj.Address(),
        'publickey':
        binascii.hexlify(bip32_child_key_obj.PublicKey()).decode(),
        'privatekey': bip32_child_key_obj.WalletImportFormat(),
        'coin': 'BTC'
    }
Ejemplo n.º 4
0
def handle_wallet_create(args):
    words = mnemonic.Mnemonic(args.language).generate()
    if create_wallet_with_mnemonic(args, words, False):
        print(
            'wallet', args.name, 'created,'
            ' please write down follwing mnemonic words in paper:')
        print(words)
Ejemplo n.º 5
0
def bip39(ss: str):
    mobj = mnemonic.Mnemonic("english")
    seed = bytes(ss, "utf-8")
    bip32_root_key_obj = bip32utils.BIP32Key.fromEntropy(seed)
    for i in range(10):
        bip32_child_key_obj = bip32_root_key_obj.ChildKey(
            44 + bip32utils.BIP32_HARDEN).ChildKey(
                0 + bip32utils.BIP32_HARDEN).ChildKey(
                    0 + bip32utils.BIP32_HARDEN).ChildKey(0).ChildKey(i)
        priv_key = {
            'seed': seed,
            'bip32_root_key': bip32_root_key_obj.ExtendedKey(),
            'bip32_extended_private_key': bip32_child_key_obj.ExtendedKey(),
            'path': "m/44'/0'/0'/{}".format(i),
            'addr': bip32_child_key_obj.Address(),
            'publickey':
            binascii.hexlify(bip32_child_key_obj.PublicKey()).decode(),
            'privatekey': bip32_child_key_obj.WalletImportFormat(),
            'coin': 'BTC'
        }
        if (priv_key["addr"] == match):
            print(priv_key)
            print(("BINGO" + "\n") * 64)

        print(priv_key['path'] + "\n" + priv_key['privatekey'] + "\n" +
              "*" * 64)
Ejemplo n.º 6
0
 def create_seed(self):
     import mnemonic
     self.seed_type = 'segwit' if bitcoin.TESTNET and self.config.get('segwit') else 'standard'
     seed = mnemonic.Mnemonic('en').make_seed(self.seed_type)
     self.opt_bip39 = False
     f = lambda x: self.request_passphrase(seed, x)
     self.show_seed_dialog(run_next=f, seed_text=seed)
Ejemplo n.º 7
0
def main():
    try:
        f = open(wordsfile)
        english = f.read().strip().split('\n')
        f.close()
    except:
        print("ERROR reading bip39 vocabulary")
        sys.exit()

    try:
        f = open(sequence)
        words = f.read().strip()
        f.close()
        if len(words.split(' ')) != 23:
            print("ERROR: it does not seem 23 words sequence")
            sys.exit()
    except:
        print("ERROR: error while reading your 23 words bip39 sequence")
        sys.exit()

    m = mnemonic.Mnemonic('english')
    clear()
    print("::Tested valid bip39 sequences::\n")
    for word in english:
        seq = "%s %s" % (words, word)
        if m.check(seq):
            print(seq)
Ejemplo n.º 8
0
def main_validate(seed_input, valid, seed_input_orig):
    """Checks for a valid bip39 seed from the given list of words."""
    from itertools import permutations
    #     print("Inside main_validate :", seed_input)
    m = mnemonic.Mnemonic('english')
    test = True
    subset = []
    for subset in permutations(seed_input, len(seed_input)):
        #	    print (' '.join(subset))
        #	    print (len(subset), len(seed_input))
        if len(subset) == len(seed_input):
            if m.check(' '.join(subset)):
                if subset != seed_input:
                    result = ' '.join(subset)
                    #			print (subset[0], seed_input_orig[0], subset[-1], seed_input_orig[-1])
                    if ((subset[0] == seed_input_orig[0])
                            and (subset[-1] == seed_input_orig[-1])):
                        # this conditional is because I know my original passphrase started with and end with the right word thus
                        # the correct crc.   I do not want to evaluate the other possiblilities to discover my correct passphrase
                        print(result)
                    valid = True
                else:
                    if subset == seed_input:
                        test = False
                        valid = False
                    print "There was a problem with the words you gave, maybe they are not on the bip39 word list or the number of words does not work."
                break  # found a valid one, stop looking.
    return seed_input
Ejemplo n.º 9
0
def InputRecoveryWords():
    print("\nPlease enter your Ledger Nano S recovery phrase now:")

    m = mnemonic.Mnemonic(language='english')

    recovery_words = []

    for i in range(24):
        while True:
            try:
                word = input("   word #%d: " % (i+1))
            except KeyboardInterrupt:
                return None

            if word == '':
                print("\nERROR: word #%d was empty!" % (i+1))
                continue

            try:
                m.wordlist.index(word)
            except ValueError:
                print("\nERROR: word '%s' is not in the BIP44 words list!" % (word))
                continue

            recovery_words.append(word)
            break

    return recovery_words
Ejemplo n.º 10
0
 def on_edit(self):
     may_clear_warning = not self.has_warning_message and self.editable
     if self._mnem is None:
         # cache the lang wordlist so it doesn't need to get loaded each time.
         # This speeds up seed_type_name and Mnemonic.check
         self._mnem = mnemonic.Mnemonic('english')
     words = self.get_seed()
     b = self.is_seed(words)
     if not self.is_bip39:
         t = mnemo.format_seed_type_name_for_ui(mnemo.seed_type_name(words))
         label = _('Seed Type') + ': ' + t if t else ''
         if t and may_clear_warning and 'bip39' in self.options:
             match_set = mnemo.autodetect_seed_type(words)
             if len(match_set) > 1 and mnemo.SeedType.BIP39 in match_set:
                 may_clear_warning = False
                 self.seed_warning.setText(
                     _('This seed is ambiguous and may also be interpreted as a <b>BIP39</b> seed.'
                       ) + '<br/><br/>' +
                     _('If you wish this seed to be interpreted as a BIP39 seed, '
                       'then use the Options button to force BIP39 interpretation of this seed.'
                       ))
     else:
         is_valid = self._mnem.check(words)
         status = 'valid' if is_valid else 'invalid'
         label = f'BIP39' + f' ({status})'
     self.seed_type_label.setText(label)
     self.parent.next_button.setEnabled(b)
     if may_clear_warning:
         self.seed_warning.setText('')
Ejemplo n.º 11
0
def gen_priv_and_seed():
    secret = -1
    while not is_secret_within_curve_range(secret):
        seed = mn.Mnemonic().make_seed()
        secret = get_secret_from_seed(seed)

    sk = SigningKey.from_secret_exponent(secret, curve=SECP256k1)
    return seed, sk
Ejemplo n.º 12
0
def is_bip39_seed(seed: str) -> bool:
    """Checks if `seed` is a valid BIP39 seed phrase (passes wordlist AND
    checksum tests)."""
    try:
        language = mnemonic.Mnemonic.detect_language(seed)
    except Exception:
        return False
    mnemo = mnemonic.Mnemonic(language)
    return mnemo.check(seed)
def generate_address(mnemonic_words):
    mobj = mnemonic.Mnemonic("english")
    seed = mobj.to_seed(mnemonic_words)
    bip32_root_key_obj = bip32utils.BIP32Key.fromEntropy(seed)
    bip32_child_key_obj = bip32_root_key_obj.ChildKey(
        44 + bip32utils.BIP32_HARDEN).ChildKey(
            0 + bip32utils.BIP32_HARDEN).ChildKey(
                0 + bip32utils.BIP32_HARDEN).ChildKey(0).ChildKey(0)
    return bip32_child_key_obj.Address()
def generate_private_key(mnemonic_words):
    mobj = mnemonic.Mnemonic("english")
    seed = mobj.to_seed(mnemonic_words)
    bip32_root_key_obj = bip32utils.BIP32Key.fromEntropy(seed)
    bip32_child_key_obj = bip32_root_key_obj.ChildKey(
        44 + bip32utils.BIP32_HARDEN).ChildKey(
            0 + bip32utils.BIP32_HARDEN).ChildKey(
                0 + bip32utils.BIP32_HARDEN).ChildKey(0).ChildKey(0)
    return bip32_child_key_obj.WalletImportFormat()
Ejemplo n.º 15
0
    def generate_mnemonic(strength=256, language="english"):
        """Generate a BIP39 type mnemonic. Requires `mnemonic <https://pypi.org/project/mnemonic>`_

        :param int strength: choose from 128, 160, 192, 224, 256
        :param str language: one of the installed word list languages
        :return: word list
        :rtype: str
        """
        m = mnemonic.Mnemonic(language)
        return m.generate(strength=strength)
Ejemplo n.º 16
0
def check_mnemonic(string, language='english'):
    """ Check menmonic: 

    Uses the python mnemonic library to check the supplied mnemonic is complies to the BIP-0039 standards

    Args:
        string(str): a list of mnemonic words seperated by spaces to be checked
        languge(str): a language to verify the mnemonic in , defaults to english
    """
    object = mnemonic.Mnemonic(language)
    return object.check(string)
Ejemplo n.º 17
0
def _check_mnemonic(seed):
    # check seed is valid bip39 mnemonic
    m = mnemonic.Mnemonic("english")
    if m.check(seed.strip()):
        seed = seed.strip()
        seed = m.normalize_string(seed).split(" ")
        seed = " ".join(seed)
    else:
        a = input("Seed is not a valid bip39 mnemonic are you sure you wish to continue (y/N): ")
        if a not in ("y", "Y"):
            sys.exit(EXIT_SEED_INVALID)
Ejemplo n.º 18
0
def main(testnet):
  print "This script is for restoring a new BTChip from a mnemonic seed."

  M = mnemonic.Mnemonic("english")
  wordlist = raw_input("Backup Mnemonic: ")
  passphrase = getpass.getpass("Backup Passphrase (Press enter if blank):")
  seed = binascii.hexlify(M.to_seed(wordlist, passphrase))
  print 'mnemonic : %s (%d words)' % (wordlist, len(wordlist.split(' ')))
  print 'seed     : %s (%d bits)\n' % (seed, len(seed) * 4)

  setup(bytearray(seed.decode('hex')), testnet)
Ejemplo n.º 19
0
    def make_hash(self):
        # mnemonic phrase for recovery
        m = mnemonic.Mnemonic('english')
        phrase = m.generate()

        # create short hash of phrase
        sha = hashlib.sha256(phrase)
        ripe = hashlib.new("ripemd160", sha.hexdigest())
        ripe = ripe.hexdigest()

        return (ripe, phrase)
Ejemplo n.º 20
0
def main():
    args = sys.argv[1:]
    for arg in args:
        print("// Path: m/44'/866'/0'")
        print("MnemonicToRistretto {")
        print(f"    phrase: \"{arg}\",")
        print("    account_index: 0,")

        mnemo = mnemonic.Mnemonic("english")
        master_seed = mnemo.to_seed(arg, "")

        # manually build the path to m/usage/cointype/acctidx
        # for us, usage is BIP-44, cointype is MobileCoin
        # m
        k, c = seed2hdnode(master_seed, b"ed25519 seed", 'ed25519')
        # m/44
        k, c = derive(k, c, 44 + privdev, 'ed25519')
        # m/44/866
        k, c = derive(k, c, 866 + privdev, 'ed25519')
        # m/44/866/0
        acct0, _c = derive(k, c, 0 + privdev, 'ed25519')

        kdf = hkdf.Hkdf(b"mobilecoin-ristretto255-view", acct0, hashlib.sha512)
        key = kdf.expand(length=64)

        print(f"    view_hex: \"{key.hex()}\",")

        kdf = hkdf.Hkdf(b"mobilecoin-ristretto255-spend", acct0,
                        hashlib.sha512)
        key = kdf.expand(length=64)

        print(f"    spend_hex: \"{key.hex()}\",")
        print("},")

        print("// Path: m/44'/866'/1'")
        print("MnemonicToRistretto {")
        print(f"    phrase: \"{arg}\",")
        print("    account_index: 1,")

        # m/44/866/1
        acct1, _c = derive(k, c, 1 + privdev, 'ed25519')

        kdf = hkdf.Hkdf(b"mobilecoin-ristretto255-view", acct1, hashlib.sha512)
        key = kdf.expand(length=64)

        print(f"    view_hex: \"{key.hex()}\",")

        kdf = hkdf.Hkdf(b"mobilecoin-ristretto255-spend", acct1,
                        hashlib.sha512)
        key = kdf.expand(length=64)

        print(f"    spend_hex: \"{key.hex()}\",")
        print("},")
Ejemplo n.º 21
0
def main():
    print __doc__

    comp = binascii.unhexlify(raw_input("Please enter computer-generated entropy (in hex): ").strip())
    trzr = binascii.unhexlify(raw_input("Please enter TREZOR-generated entropy (in hex): ").strip())
    word_count = int(raw_input("How many words your mnemonic has? "))

    strength = word_count * 32 / 3

    entropy = generate_entropy(strength, trzr, comp)

    words = mnemonic.Mnemonic('english').to_mnemonic(entropy)
    if not mnemonic.Mnemonic('english').check(words):
        print "Mnemonic is invalid"
        return

    if len(words.split(' ')) != word_count:
        print "Mnemonic length mismatch!"
        return

    print "Generated mnemonic is:", words
Ejemplo n.º 22
0
def main(testnet):
    print "This script is for setting up a new BTChip with a random mnemonic seed."

    M = mnemonic.Mnemonic("english")
    passphrase = getpass.getpass(
        "Backup Passphrase (optional, increases backup security): ")
    wordlist = M.generate(strength=256)
    seed = binascii.hexlify(M.to_seed(wordlist, passphrase))
    print 'mnemonic : %s (%d words)' % (wordlist, len(wordlist.split(' ')))
    print 'seed     : %s (%d bits)\n' % (seed, len(seed) * 4)

    setup(bytearray(seed.decode('hex')), testnet)
Ejemplo n.º 23
0
 def mnemonic_key(words, index=0, passphrase='', language='english'):
     m = mnemonic.Mnemonic(language)
     assert (m.check(words))
     for i in ['m', 44, 165, index]:
         if i == 'm':
             key = b'ed25519 seed'
             msg = m.to_seed(words, passphrase)
         else:
             i = i | 0x80000000
             msg = b'\x00' + sk + i.to_bytes(4, byteorder='big')
         h = hmac.new(key, msg, hashlib.sha512).digest()
         sk, key = h[:32], h[32:]
     return key_expand(sk.hex())
Ejemplo n.º 24
0
def main():
    m = mnemonic.Mnemonic(language='english').to_mnemonic(
        crypto.sha3_512(MNEMONIC_SEED)[:256 // 8])
    seed = mnemonic.Mnemonic.to_seed(m)

    print('Generating wallet...')
    w = bip44.ArculaBIP44(
        seed, WALLET_CONFIG)  # Create a BIP44 wallet with 3 accounts.

    # Faucet: https://coinfaucet.eu/en/bch-testnet/
    tx_hash = test_faucet_to_wallet(w)
    print('Waiting for the transaction to propagate...')
    time.sleep(3)
    wallet_to_test_faucet(w, tx_hash)
Ejemplo n.º 25
0
 def main_validate(self):
     """Checks for a valid bip39 seed from the given list of words."""
     self.result_label['text'] = ''
     seed_input = []
     seed_input = self.entry_seed.get().split()
     m = mnemonic.Mnemonic('english')
     for subset in itertools.permutations(seed_input, len(seed_input)):
         if len(subset) == len(seed_input):
             if m.check(' '.join(subset)):
                 if subset != seed_input:
                     self.result_label['text'] = ' '.join(subset)
                 else:
                     self.result_label['text'] = "There was a problem with the words you gave, maybe they are not on the bip39 word list or the number of words does not work."
                 break  # found a valid one, stop looking.
Ejemplo n.º 26
0
def main() -> None:
    print(__doc__)

    comp = bytes.fromhex(
        input("Please enter computer-generated entropy (in hex): ").strip())
    trzr = bytes.fromhex(
        input("Please enter Trezor-generated entropy (in hex): ").strip())
    word_count = int(input("How many words your mnemonic has? "))

    strength = word_count * 32 // 3

    entropy = generate_entropy(strength, trzr, comp)

    words = mnemonic.Mnemonic("english").to_mnemonic(entropy)
    if not mnemonic.Mnemonic("english").check(words):
        print("Mnemonic is invalid")
        return

    if len(words.split(" ")) != word_count:
        print("Mnemonic length mismatch!")
        return

    print("Generated mnemonic is:", words)
Ejemplo n.º 27
0
    def generate_12_word_wallet(self):
        """
        Function to generate a 12 word mnemonic.

        Execution of this function is as follows::

            generate_12_word_wallet()

        The expected return result for this function is as follows::

            venture consider cool fury front middle junk person suit assist garbage category

        :return: 12 word String that should be highly protected if storing any funds.
        """
        return mnemonic.Mnemonic(language="english").generate(strength=128)
Ejemplo n.º 28
0
    def generate_24_word_wallet(self):
        """
        Function to generate a 24 word mnemonic.

        Execution of this function is as follows::

            generate_24_word_wallet()

        The expected return result for this function is as follows::

            refuse flag merge fiction choose dream frown gauge need fabric once pizza actual armed reopen couple family fury reopen slush blue try focus minute

        :return: 24 word String that should be highly protected if storing any funds.
        """
        return mnemonic.Mnemonic(language="english").generate(strength=256)
Ejemplo n.º 29
0
def bip39(string_as_seed:str):
    mobj = mnemonic.Mnemonic("english")
    seed = bytes(string_as_seed,"utf-8")

    bip32_root_key_obj = bip32utils.BIP32Key.fromEntropy(seed)
    bip32_child_key_obj = bip32_root_key_obj.ChildKey(44 + bip32utils.BIP32_HARDEN).ChildKey(0 + bip32utils.BIP32_HARDEN).ChildKey(0 + bip32utils.BIP32_HARDEN).ChildKey(0).ChildKey(0)
    return {
            'seed': seed,
            'bip32_root_key': bip32_root_key_obj.ExtendedKey(),
            'bip32_extended_private_key': bip32_child_key_obj.ExtendedKey(),
            'path': "m/44'/0'/0'/0",
            'addr': bip32_child_key_obj.Address(),
            'publickey': binascii.hexlify(bip32_child_key_obj.PublicKey()).decode(),
            'privatekey': bip32_child_key_obj.WalletImportFormat(),
            'coin': 'BTC'
            })
Ejemplo n.º 30
0
def generate_wallet() -> Wallet:
    while True:
        phrase = mnemonic.Mnemonic(language="english").generate(strength=256)
        try:
            privkey = seed_to_privkey(phrase)
            break
        except hdwallets.BIP32DerivationError:
            pass
    pubkey = privkey_to_pubkey(privkey)
    address = pubkey_to_address(pubkey)
    return {
        "seed": phrase,
        "derivation_path": DEFAULT_DERIVATION_PATH,
        "private_key": privkey,
        "public_key": pubkey,
        "address": address,
    }