Exemple #1
0
 def __init__(self, **kwargs):
     super(RestoreSeedDialog, self).__init__(**kwargs)
     self._test = kwargs['test']
     from electrum.mnemonic import Mnemonic
     from electrum.old_mnemonic import words as old_wordlist
     self.words = set(Mnemonic('en').wordlist).union(set(old_wordlist))
     self.ids.text_input_seed.text = ''
Exemple #2
0
 def get_xkeys(self, seed, t, passphrase, derivation):
     assert is_any_2fa_seed_type(t)
     xtype = 'standard' if t == '2fa' else 'p2wsh'
     bip32_seed = Mnemonic.mnemonic_to_seed(seed, passphrase)
     xprv, xpub = bip32_root(bip32_seed, xtype)
     xprv, xpub = bip32_private_derivation(xprv, "m/", derivation)
     return xprv, xpub
Exemple #3
0
 def get_xkeys(self, seed, passphrase, derivation):
     from electrum.mnemonic import Mnemonic
     from electrum.keystore import bip32_root, bip32_private_derivation
     bip32_seed = Mnemonic.mnemonic_to_seed(seed, passphrase)
     xprv, xpub = bip32_root(bip32_seed, 'standard')
     xprv, xpub = bip32_private_derivation(xprv, "m/", derivation)
     return xprv, xpub
Exemple #4
0
 def get_xkeys(self, seed, t, passphrase, derivation):
     assert is_any_2fa_seed_type(t)
     xtype = 'standard' if t == '2fa' else 'p2wsh'
     bip32_seed = Mnemonic.mnemonic_to_seed(seed, passphrase)
     xprv, xpub = bip32_root(bip32_seed, xtype)
     xprv, xpub = bip32_private_derivation(xprv, "m/", derivation)
     return xprv, xpub
Exemple #5
0
 def get_xkeys(self, seed, t, passphrase, derivation):
     assert is_any_2fa_seed_type(t)
     xtype = 'standard' if t == '2fa' else 'p2wsh'
     bip32_seed = Mnemonic.mnemonic_to_seed(seed, passphrase)
     rootnode = BIP32Node.from_rootseed(bip32_seed, xtype=xtype)
     child_node = rootnode.subkey_at_private_derivation(derivation)
     return child_node.to_xprv(), child_node.to_xpub()
Exemple #6
0
    def initialize_completer(self):
        if self.seed_type != 'slip39':
            bip39_english_list = Mnemonic('en').wordlist
            old_list = old_mnemonic.wordlist
            only_old_list = set(old_list) - set(bip39_english_list)
            self.wordlist = list(bip39_english_list) + list(
                only_old_list)  # concat both lists
            self.wordlist.sort()

            class CompleterDelegate(QStyledItemDelegate):
                def initStyleOption(self, option, index):
                    super().initStyleOption(option, index)
                    # Some people complained that due to merging the two word lists,
                    # it is difficult to restore from a metal backup, as they planned
                    # to rely on the "4 letter prefixes are unique in bip39 word list" property.
                    # So we color words that are only in old list.
                    if option.text in only_old_list:
                        # yellow bg looks ~ok on both light/dark theme, regardless if (un)selected
                        option.backgroundBrush = ColorScheme.YELLOW.as_color(
                            background=True)

            delegate = CompleterDelegate(self.seed_e)
        else:
            self.wordlist = list(slip39.get_wordlist())
            delegate = None

        self.completer = QCompleter(self.wordlist)
        if delegate:
            self.completer.popup().setItemDelegate(delegate)
        self.seed_e.set_completer(self.completer)
Exemple #7
0
 def get_xkeys(self, seed, passphrase, derivation):
     from electrum.mnemonic import Mnemonic
     from electrum.keystore import bip32_root, bip32_private_derivation
     bip32_seed = Mnemonic.mnemonic_to_seed(seed, passphrase)
     xprv, xpub = bip32_root(bip32_seed, 'standard')
     xprv, xpub = bip32_private_derivation(xprv, "m/", derivation)
     return xprv, xpub
Exemple #8
0
 def __init__(self, wizard, **kwargs):
     super(RestoreSeedDialog, self).__init__(wizard, **kwargs)
     self._test = kwargs['is_valid']
     from electrum.mnemonic import Mnemonic
     from electrum.old_mnemonic import words as old_wordlist
     self.words = set(Mnemonic('en').wordlist).union(set(old_wordlist))
     self.ids.text_input_seed.text = test_seed if is_test else ''
 def get_xkeys(self, seed, t, passphrase, derivation):
     assert is_any_2fa_seed_type(t)
     xtype = 'standard' if t == '2fa' else 'p2wsh'
     bip32_seed = Mnemonic.mnemonic_to_seed(seed, passphrase)
     rootnode = BIP32Node.from_rootseed(bip32_seed, xtype=xtype)
     child_node = rootnode.subkey_at_private_derivation(derivation)
     return child_node.to_xprv(), child_node.to_xpub()
Exemple #10
0
 def initialize_completer(self):
     english_list = Mnemonic('en').wordlist
     old_list = electrum.old_mnemonic.words
     self.wordlist = english_list + list(set(old_list) - set(english_list)) #concat both lists
     self.wordlist.sort()
     self.completer = QCompleter(self.wordlist)
     self.seed_e.set_completer(self.completer)
Exemple #11
0
 def __init__(self, wizard, **kwargs):
     super(RestoreSeedDialog, self).__init__(wizard, **kwargs)
     self._test = kwargs['test']
     from electrum.mnemonic import Mnemonic
     from electrum.old_mnemonic import words as old_wordlist
     self.words = set(Mnemonic('en').wordlist).union(set(old_wordlist))
     self.ids.text_input_seed.text = test_seed if is_test else ''
     self.message = _('Please type your seed phrase using the virtual keyboard.')
     self.title = _('Enter Seed')
Exemple #12
0
    def create_wallet(self, password=''):
        """
        Create a new bitcoin wallet.
        """
        self._logger.info("Creating wallet in %s", self.wallet_dir)

        if password is not None:
            try:
                self.set_wallet_password(password)
            except InitError:
                return fail(
                    RuntimeError(
                        "Cannot initialize the keychain, unable to unlock the wallet!"
                    ))
        self.wallet_password = password

        def run_on_thread(thread_method):
            # We are running code that writes to the wallet on a separate thread.
            # This is done because Electrum does not allow writing to a wallet from a daemon thread.
            wallet_thread = Thread(target=thread_method,
                                   name="ethereum-create-wallet")
            wallet_thread.setDaemon(False)
            wallet_thread.start()
            wallet_thread.join()

        seed = Mnemonic('en').make_seed()
        k = keystore.from_seed(seed, '')
        k.update_password(None, password)
        self.storage.put('keystore', k.dump())
        self.storage.put('wallet_type', 'standard')
        self.storage.set_password(password, bool(password))
        run_on_thread(self.storage.write)

        self.wallet = ElectrumWallet(self.storage)
        self.wallet.synchronize()
        run_on_thread(self.wallet.storage.write)
        self.created = True
        self.unlocked = True

        self.start_daemon()
        self.open_wallet()

        self._logger.info("Bitcoin wallet saved in '%s'",
                          self.wallet.storage.path)

        return succeed(None)
def from_seed(seed, passphrase, is_p2sh=False):
    t = seed_type(seed)
    if t == 'old':
        keystore = Old_KeyStore({})
        keystore.add_seed(seed)
    elif t in ['standard', 'segwit']:
        keystore = BIP32_KeyStore({})
        keystore.add_seed(seed)
        keystore.passphrase = passphrase
        bip32_seed = Mnemonic.mnemonic_to_seed(seed, passphrase)
        if t == 'standard':
            der = "m/"
            xtype = 'standard'
        else:
            der = "m/1'/" if is_p2sh else "m/0'/"
            xtype = 'p2wsh' if is_p2sh else 'p2wpkh'
        keystore.add_xprv_from_seed(bip32_seed, xtype, der)
    else:
        raise BitcoinException('Unexpected seed type {}'.format(repr(t)))
    return keystore
Exemple #14
0
def mk_electrum(file, mnemo, isBip39=False):
    if isBip39:
        bip39 = Bip39("english")
        seed = bip39.to_seed(mnemo)
        path = ACCT84
        type = "bip39"
        mnemo = None
    else:
        seed = Bip32.mnemonic_to_seed(mnemo, None)
        type = "segwit"
        path = "0H"

    net = btcnet("", "", "", **HW84)
    key = net.keys.bip32_seed(seed)
    xprv = key.subkey_for_path(path).hwif(as_private=True)
    xpub = key.subkey_for_path(path).hwif(as_private=False)

    wallet = mk_wallet(xprv, xpub, type=type, seed=mnemo)
    with open(file, "w+") as w:
        dump(wallet, w, indent=4)
Exemple #15
0
 def create_seed(self):
     from electrum.mnemonic import Mnemonic
     seed = Mnemonic('en').make_seed()
     self.opt_bip39 = False
     f = lambda x: self.request_passphrase(seed, x)
     self.show_seed_dialog(run_next=f, seed_text=seed)
Exemple #16
0
 def make_seed(self):
     return Mnemonic('english').make_seed(seed_type='2fa', num_bits=128)
Exemple #17
0
 def get_xkeys(self, seed, passphrase, derivation):
     bip32_seed = Mnemonic.mnemonic_to_seed(seed, passphrase)
     xprv, xpub = bip32_root(bip32_seed, 'standard')
     xprv, xpub = bip32_private_derivation(xprv, "m/", derivation)
     return xprv, xpub
    def on_edit(self):
        s = ' '.join(self.get_seed_words())
        b = self.is_seed(s)
        if self.seed_type == 'bip39':
            from electrum.keystore import bip39_is_checksum_valid
            from electrum.mnemonic import Wordlist, filenames

            lang = ''
            for type, file in filenames.items():
                word_list = Wordlist.from_file(file)
                is_checksum, is_wordlist = bip39_is_checksum_valid(s, wordlist=word_list)
                if is_wordlist:
                    lang = type
                    break

            status = ('checksum: ' + ('ok' if is_checksum else 'failed')) if is_wordlist else 'unknown wordlist'
            label = 'BIP39 - ' + lang + ' (%s)'%status
            if lang and lang != self.lang:
                if lang == 'en':
                    bip39_english_list = Mnemonic('en').wordlist
                    old_list = old_mnemonic.wordlist
                    only_old_list = set(old_list) - set(bip39_english_list)
                    self.wordlist = list(bip39_english_list) + list(only_old_list)  # concat both lists
                    self.wordlist.sort()
                    self.completer.model().setStringList(self.wordlist)
                    self.lang = 'en'
                else:
                    self.wordlist = list(Mnemonic(lang).wordlist)
                    self.wordlist.sort()
                    self.completer.model().setStringList(self.wordlist)
                    self.lang = lang

        elif self.seed_type == 'slip39':
            self.slip39_mnemonics[self.slip39_mnemonic_index] = s
            try:
                slip39.decode_mnemonic(s)
            except slip39.Slip39Error as e:
                share_status = str(e)
                current_mnemonic_invalid = True
            else:
                share_status = _('Valid.')
                current_mnemonic_invalid = False

            label = _('SLIP39 share') + ' #%d: %s' % (self.slip39_mnemonic_index + 1, share_status)

            # No need to process mnemonics if the current mnemonic remains invalid after editing.
            if not (self.slip39_current_mnemonic_invalid and current_mnemonic_invalid):
                self.slip39_seed, seed_status = slip39.process_mnemonics(self.slip39_mnemonics)
                self.seed_status.setText(seed_status)
            self.slip39_current_mnemonic_invalid = current_mnemonic_invalid

            b = self.slip39_seed is not None
            self.update_share_buttons()
        else:
            t = seed_type(s)
            label = _('Seed Type') + ': ' + t if t else ''

        self.seed_type_label.setText(label)
        self.parent.next_button.setEnabled(b)

        # disable suggestions if user already typed an unknown word
        for word in self.get_seed_words()[:-1]:
            if word not in self.wordlist:
                self.seed_e.disable_suggestions()
                return
        self.seed_e.enable_suggestions()
#!./venv/bin/python

from electrum import util
from electrum.mnemonic import Mnemonic

import sys

lines = [x.strip() for x in sys.stdin.readlines()]

words = ""
passw = ""
if len(lines) == 2:
    passw = lines[1]
if not (len(lines) in [1, 2]):
    print("wrong input")
    sys.exit(1)

words = lines[0]
print(util.bh2u(Mnemonic.mnemonic_to_seed(words, passw)))
Exemple #20
0
 def get_xkeys(self, seed, passphrase, derivation):
     bip32_seed = Mnemonic.mnemonic_to_seed(seed, passphrase)
     xprv, xpub = bip32_root(bip32_seed, 'standard')
     xprv, xpub = bip32_private_derivation(xprv, "m/", derivation)
     return xprv, xpub
Exemple #21
0
class RestoreSeedDialog(WizardDialog):

    message = StringProperty('')

    def __init__(self, **kwargs):
        super(RestoreSeedDialog, self).__init__(**kwargs)
        self._test = kwargs['test']
        from electrum.mnemonic import Mnemonic
        self.mnemonic = Mnemonic('en')

    def on_text(self, dt):
        self.ids.next.disabled = not bool(self._test(self.get_seed_text()))

        text = self.ids.text_input_seed.text
        if not text:
            last_word = ''
        elif text[-1] == ' ':
            last_word = ''
        else:
            last_word = text.split(' ')[-1]

        enable_space = False
        self.ids.suggestions.clear_widgets()
        suggestions = [x for x in self.mnemonic.get_suggestions(last_word)]
        if suggestions and len(suggestions) < 10:
            for w in suggestions:
                if w == last_word:
                    enable_space = True
                else:
                    b = WordButton(text=w)
                    self.ids.suggestions.add_widget(b)

        i = len(last_word)
        p = set()
        for x in suggestions:
            if len(x) > i: p.add(x[i])

        for line in [self.ids.line1, self.ids.line2, self.ids.line3]:
            for c in line.children:
                if isinstance(c, Button):
                    if c.text in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
                        c.disabled = (c.text.lower() not in p) and last_word
                    elif c.text == ' ':
                        c.disabled = not enable_space

    def on_word(self, w):
        text = self.get_seed_text()
        words = text.split(' ')
        words[-1] = w
        text = ' '.join(words)
        self.ids.text_input_seed.text = text + ' '
        self.ids.suggestions.clear_widgets()

    def get_seed_text(self):
        ti = self.ids.text_input_seed
        text = unicode(ti.text).strip()
        text = ' '.join(text.split())
        return text

    def update_text(self, c):
        c = c.lower()
        text = self.ids.text_input_seed.text
        if c == '<':
            text = text[:-1]
        else:
            text += c
        self.ids.text_input_seed.text = text

    def scan_seed(self):
        def on_complete(text):
            self.ids.text_input_seed.text = text

        app = App.get_running_app()
        app.scan_qr(on_complete)

    def on_parent(self, instance, value):
        if value:
            tis = self.ids.text_input_seed
            tis.focus = True
            #tis._keyboard.bind(on_key_down=self.on_key_down)
            self._back = _back = partial(self.ids.back.dispatch, 'on_release')
            app = App.get_running_app()

    def on_key_down(self, keyboard, keycode, key, modifiers):
        if keycode[0] in (13, 271):
            self.on_enter()
            return True

    def on_enter(self):
        #self._remove_keyboard()
        # press next
        next = self.ids.next
        if not next.disabled:
            next.dispatch('on_release')

    def _remove_keyboard(self):
        tis = self.ids.text_input_seed
        if tis._keyboard:
            tis._keyboard.unbind(on_key_down=self.on_key_down)
            tis.focus = False

    def close(self):
        #self._remove_keyboard()
        app = App.get_running_app()
        #if self._back in app.navigation_higherarchy:
        #    app.navigation_higherarchy.pop()
        #    self._back = None
        super(RestoreSeedDialog, self).close()
Exemple #22
0
 def __init__(self, **kwargs):
     super(RestoreSeedDialog, self).__init__(**kwargs)
     self._test = kwargs['test']
     from electrum.mnemonic import Mnemonic
     self.mnemonic = Mnemonic('en')
 def __init__(self, **kwargs):
     super(RestoreSeedDialog, self).__init__(**kwargs)
     self._test = kwargs['test']
     from electrum.mnemonic import Mnemonic
     self.mnemonic = Mnemonic('en')
class RestoreSeedDialog(WizardDialog):

    message = StringProperty('')

    def __init__(self, **kwargs):
        super(RestoreSeedDialog, self).__init__(**kwargs)
        self._test = kwargs['test']
        from electrum.mnemonic import Mnemonic
        self.mnemonic = Mnemonic('en')

    def on_text(self, dt):
        self.ids.next.disabled = not bool(self._test(self.get_seed_text()))

        text = self.ids.text_input_seed.text
        if not text:
            last_word = ''
        elif text[-1] == ' ':
            last_word = ''
        else:
            last_word = text.split(' ')[-1]

        enable_space = False
        self.ids.suggestions.clear_widgets()
        suggestions = [x for x in self.mnemonic.get_suggestions(last_word)]
        if suggestions and len(suggestions) < 10:
            for w in suggestions:
                if w == last_word:
                    enable_space = True
                else:
                    b = WordButton(text=w)
                    self.ids.suggestions.add_widget(b)

        i = len(last_word)
        p = set()
        for x in suggestions:
            if len(x)>i: p.add(x[i])

        for line in [self.ids.line1, self.ids.line2, self.ids.line3]:
            for c in line.children:
                if isinstance(c, Button):
                    if c.text in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
                        c.disabled = (c.text.lower() not in p) and last_word
                    elif c.text == ' ':
                        c.disabled = not enable_space

    def on_word(self, w):
        text = self.get_seed_text()
        words = text.split(' ')
        words[-1] = w
        text = ' '.join(words)
        self.ids.text_input_seed.text = text + ' '
        self.ids.suggestions.clear_widgets()

    def get_seed_text(self):
        ti = self.ids.text_input_seed
        text = unicode(ti.text).strip()
        text = ' '.join(text.split())
        return text

    def update_text(self, c):
        c = c.lower()
        text = self.ids.text_input_seed.text
        if c == '<':
            text = text[:-1]
        else:
            text += c
        self.ids.text_input_seed.text = text

    def scan_seed(self):
        def on_complete(text):
            self.ids.text_input_seed.text = text
        app = App.get_running_app()
        app.scan_qr(on_complete)

    def on_parent(self, instance, value):
        if value:
            tis = self.ids.text_input_seed
            tis.focus = True
            #tis._keyboard.bind(on_key_down=self.on_key_down)
            self._back = _back = partial(self.ids.back.dispatch,
                                         'on_release')
            app = App.get_running_app()

    def on_key_down(self, keyboard, keycode, key, modifiers):
        if keycode[0] in (13, 271):
            self.on_enter()
            return True

    def on_enter(self):
        #self._remove_keyboard()
        # press next
        next = self.ids.next
        if not next.disabled:
            next.dispatch('on_release')

    def _remove_keyboard(self):
        tis = self.ids.text_input_seed
        if tis._keyboard:
            tis._keyboard.unbind(on_key_down=self.on_key_down)
            tis.focus = False

    def close(self):
        #self._remove_keyboard()
        app = App.get_running_app()
        #if self._back in app.navigation_higherarchy:
        #    app.navigation_higherarchy.pop()
        #    self._back = None
        super(RestoreSeedDialog, self).close()
Exemple #25
0
 def create_seed(self):
     from electrum.mnemonic import Mnemonic
     seed = Mnemonic('en').make_seed()
     self.show_seed_dialog(run_next=self.confirm_seed, seed_text=seed)
 def make_seed(self, seed_type):
     if not is_any_2fa_seed_type(seed_type):
         raise Exception(f'unexpected seed type: {seed_type}')
     return Mnemonic('english').make_seed(seed_type=seed_type)
 def initialize_completer(self):
     english_list = Mnemonic('en').wordlist
     self.wordlist = english_list
     self.wordlist.sort()
     self.completer = QCompleter(self.wordlist)
     self.seed_e.set_completer(self.completer)
    words += str(sys.argv[i])
    i += 1
    if i >= numargs:
        break;
    words += " "

print "words supplied: " + words

#
# The resulting words must fit the criteria of generating a hash
# that starts with the SEED_PREFIX (01)
# We will add a number to this list of words that was supplied and 
# we will keep incrementing it until the criteria is satisfied.
#

mnemo = Mnemonic('en')

nonce = 0
while True:
    # Add the nonce if non zero
    if nonce == 0:
        words_to_hash = words
    else:
    	words_to_hash = words + " " + str(nonce)
    #
    # Generate the hash and take the first half of the hash since
    # mnemonic_encode expects 16 bytes seed
    #
    hash_obj = hashlib.sha256(words_to_hash)
    seed1 = hash_obj.hexdigest()
    seed2 = int(seed1[:34], 16)
Exemple #29
0
 def make_seed(self, seed_type):
     if not is_any_2fa_seed_type(seed_type):
         raise BaseException('unexpected seed type: {}'.format(seed_type))
     return Mnemonic('english').make_seed(seed_type=seed_type, num_bits=128)
Exemple #30
0
 def make_seed(self):
     return Mnemonic('english').make_seed(num_bits=256, prefix=SEED_PREFIX)
Exemple #31
0
def run_non_RPC(config):
    cmdname = config.get('cmd')

    storage = WalletStorage(config.get_wallet_path())
    if storage.file_exists():
        sys.exit("Error: Remove the existing wallet first!")

    def password_dialog():
        return prompt_password("Password (hit return if you do not wish to encrypt your wallet):")

    if cmdname == 'restore':
        text = config.get('text').strip()
        passphrase = config.get('passphrase', '')
        password = password_dialog() if keystore.is_private(text) else None
        if keystore.is_address_list(text):
            wallet = Imported_Wallet(storage)
            for x in text.split():
                wallet.import_address(x)
        elif keystore.is_private_key_list(text):
            k = keystore.Imported_KeyStore({})
            storage.put('keystore', k.dump())
            storage.put('use_encryption', bool(password))
            wallet = Imported_Wallet(storage)
            for x in text.split():
                wallet.import_private_key(x, password)
            storage.write()
        else:
            if keystore.is_seed(text):
                k = keystore.from_seed(text, passphrase, False)
            elif keystore.is_master_key(text):
                k = keystore.from_master_key(text)
            else:
                sys.exit("Error: Seed or key not recognized")
            if password:
                k.update_password(None, password)
            storage.put('keystore', k.dump())
            storage.put('wallet_type', 'standard')
            storage.put('use_encryption', bool(password))
            storage.write()
            wallet = Wallet(storage)
        if not config.get('offline'):
            network = Network(config)
            network.start()
            wallet.start_threads(network)
            print_msg("Recovering wallet...")
            wallet.synchronize()
            wallet.wait_until_synchronized()
            wallet.stop_threads()
            # note: we don't wait for SPV
            msg = "Recovery successful" if wallet.is_found() else "Found no history for this wallet"
        else:
            msg = "This wallet was restored offline. It may contain more addresses than displayed."
        print_msg(msg)

    elif cmdname == 'create':
        password = password_dialog()
        passphrase = config.get('passphrase', '')
        seed_type = 'segwit' if config.get('segwit') else 'standard'
        seed = Mnemonic('en').make_seed(seed_type)
        k = keystore.from_seed(seed, passphrase, False)
        storage.put('keystore', k.dump())
        storage.put('wallet_type', 'standard')
        wallet = Wallet(storage)
        wallet.update_password(None, password, True)
        wallet.synchronize()
        print_msg("Your wallet generation seed is:\n\"%s\"" % seed)
        print_msg("Please keep it in a safe place; if you lose it, you will not be able to restore your wallet.")

    wallet.storage.write()
    print_msg("Wallet saved in '%s'" % wallet.storage.path)
    sys.exit(0)