URI: 
       tBetter install wizard - electrum - Electrum Bitcoin wallet
  HTML git clone https://git.parazyd.org/electrum
   DIR Log
   DIR Files
   DIR Refs
   DIR Submodules
       ---
   DIR commit 11d135b32d7c59782dbbd3327f65adfda1fdf1dd
   DIR parent e6dbe621c6976d4a57d3d16308d9ee8759af9ea2
  HTML Author: Neil Booth <kyuupichan@gmail.com>
       Date:   Thu, 31 Dec 2015 11:36:33 +0900
       
       Better install wizard
       
       Break out the workflow logic of the install wizard
       into a base class.  This means reimplementing with
       full support in a new GUI is now easy; you just provide
       ways to request passwords, show messages etc.  The API
       is fully documented in the base class.
       
       There are a couple of minor outstanding issues, including that
       tthe old messages shown when recovering a wallet are missing.
       I will come back to that.  Ledger wallet might be broken.
       
       Other improvements:
       
       The install wizard code is now easy to follow and understand.
       Hardware wallets can now be restored without any need for their
       accompanying libraries.
       Various bits of trustedcoin were broken and have been fixed.
       Many plugin hooks can be removed.  I have only started on this.
       
       Diffstat:
         M gui/qt/__init__.py                  |      59 +++++++------------------------
         M gui/qt/installwizard.py             |     445 ++++++++++---------------------
         M gui/qt/main_window.py               |      57 +++++++++++--------------------
         M gui/qt/password_dialog.py           |      72 ++++++++++++++++++-------------
         M lib/__init__.py                     |       1 +
         M lib/plugins.py                      |      41 ++++++++++++++++++++++---------
         M lib/simple_config.py                |       5 +++++
         M lib/wallet.py                       |      52 +++++++++++++++++--------------
         A lib/wizard.py                       |     285 +++++++++++++++++++++++++++++++
         M plugins/keepkey/cmdline.py          |       7 +------
         M plugins/keepkey/keepkey.py          |      20 +++++++++-----------
         M plugins/keepkey/qt.py               |       7 +++++--
         M plugins/trezor/client.py            |      34 ++++++++++++++++++++++++++++++-
         M plugins/trezor/cmdline.py           |      10 +---------
         M plugins/trezor/plugin.py            |      80 ++++++++++++++++----------------
         M plugins/trezor/qt.py                |       7 +++++--
         M plugins/trezor/qt_generic.py        |      76 ++++++++++++-------------------
         M plugins/trezor/trezor.py            |      20 +++++++++-----------
         M plugins/trustedcoin/qt.py           |      14 ++++++++++----
         M plugins/trustedcoin/trustedcoin.py  |     105 ++++++++++++-------------------
       
       20 files changed, 750 insertions(+), 647 deletions(-)
       ---
   DIR diff --git a/gui/qt/__init__.py b/gui/qt/__init__.py
       t@@ -130,70 +130,35 @@ class ElectrumGui(MessageBoxMixin):
                for window in self.windows:
                    window.close()
        
       -    def remove_from_recently_open(self, filename):
       -        recent = self.config.get('recently_open', [])
       -        if filename in recent:
       -            recent.remove(filename)
       -            self.config.set_key('recently_open', recent)
       -
       -    def load_wallet_file(self, filename):
       -        try:
       -            storage = WalletStorage(filename)
       -        except Exception as e:
       -            self.show_error(str(e))
       -            return
       -        if not storage.file_exists:
       -            self.remove_from_recently_open(filename)
       -            action = 'new'
       -        else:
       -            try:
       -                wallet = Wallet(storage)
       -            except BaseException as e:
       -                traceback.print_exc(file=sys.stdout)
       -                self.show_warning(str(e))
       -                return
       -            action = wallet.get_action()
       -
       -        if action is not None:
       -            return self.install_wizard(storage, action)
       -
       -        wallet.start_threads(self.network)
       -        return self.create_window_for_wallet(wallet)
       -
       -    def install_wizard(self, storage, action):
       -        wizard = InstallWizard(self, storage)
       -        wallet = wizard.run(action)
       -        return self.create_window_for_wallet(wallet)
       -
            def new_window(self, path, uri=None):
                # Use a signal as can be called from daemon thread
                self.app.emit(SIGNAL('new_window'), path, uri)
        
       -    def create_window_for_wallet(self, wallet):
       -        if not wallet:
       -            return
       +    def create_window_for_wallet(self, wallet, task):
                w = ElectrumWindow(self, wallet)
       -        w.connect_slots(self.timer)
       -        w.update_recently_visited(wallet.storage.path)
       -        # initial configuration
       -        if self.config.get('hide_gui') is True and self.tray.isVisible():
       -            w.hide()
       -        else:
       -            w.show()
                self.windows.append(w)
                self.build_tray_menu()
       +        if task:
       +            WaitingDialog(w, task[0], task[1])
       +        # FIXME: Remove in favour of the load_wallet hook
                run_hook('on_new_window', w)
                return w
        
            def start_new_window(self, path, uri):
       +        '''Raises the window for the wallet if it is open.  Otherwise
       +        opens the wallet and creates a new window for it.'''
                for w in self.windows:
                    if w.wallet.storage.path == path:
                        w.bring_to_top()
                        break
                else:
       -            w = self.load_wallet_file(path)
       +            wizard = InstallWizard(self.config, self.app, self.plugins)
       +            result = wizard.open_wallet(self.network, path)
       +            if not result:
       +                return
       +            w = self.create_window_for_wallet(*result)
        
       -        if uri and w:
       +        if uri:
                    w.pay_to_URI(uri)
        
                return w
   DIR diff --git a/gui/qt/installwizard.py b/gui/qt/installwizard.py
       t@@ -1,6 +1,4 @@
       -import re
       -import sys
       -import threading
       +from sys import stdout
        
        from PyQt4.QtGui import *
        from PyQt4.QtCore import *
       t@@ -8,23 +6,18 @@ import PyQt4.QtCore as QtCore
        
        import electrum
        from electrum.i18n import _
       -from electrum import Wallet
       -from electrum import bitcoin
       -from electrum import util
        
        import seed_dialog
        from network_dialog import NetworkDialog
        from util import *
       +from password_dialog import PasswordDialog
        
       -from electrum.plugins import always_hook, run_hook
       +from electrum.wallet import Wallet
        from electrum.mnemonic import prepare_seed
       -
       -MSG_ENTER_ANYTHING    = _("Please enter a seed phrase, a master key, a list of Bitcoin addresses, or a list of private keys")
       -MSG_SHOW_MPK          = _("Here is your master public key")
       -MSG_ENTER_MPK         = _("Please enter your master public key")
       -MSG_ENTER_SEED_OR_MPK = _("Please enter a seed phrase or a master key (xpub or xprv)")
       -MSG_VERIFY_SEED       = _("Your seed is important!") + "\n" + _("To make sure that you have properly saved your seed, please retype it here.")
       -
       +from electrum.wizard import (WizardBase, UserCancelled,
       +                             MSG_ENTER_PASSWORD, MSG_RESTORE_PASSPHRASE,
       +                             MSG_COSIGNER, MSG_ENTER_SEED_OR_MPK,
       +                             MSG_SHOW_MPK, MSG_VERIFY_SEED)
        
        class CosignWidget(QWidget):
            size = 120
       t@@ -62,22 +55,95 @@ class CosignWidget(QWidget):
        
        
        
       -class InstallWizard(WindowModalDialog, MessageBoxMixin):
       +class InstallWizard(WindowModalDialog, MessageBoxMixin, WizardBase):
        
       -    def __init__(self, gui_object, storage):
       -        title = 'Electrum' + '  -  ' + _('Install Wizard')
       +    def __init__(self, config, app, plugins):
       +        title = 'Electrum  -  ' + _('Install Wizard')
                WindowModalDialog.__init__(self, None, title=title)
       -        self.gui_object = gui_object
       -        self.app = gui_object.app
       -        self.config = gui_object.config
       -        self.network = gui_object.network
       -        self.storage = storage
       +        self.app = app
       +        self.config = config
       +        # Set for base base class
       +        self.plugins = plugins
       +        self.language_for_seed = config.get('language')
                self.setMinimumSize(575, 400)
                self.setMaximumSize(575, 400)
                self.connect(self, QtCore.SIGNAL('accept'), self.accept)
                self.stack = QStackedLayout()
                self.setLayout(self.stack)
        
       +    def open_wallet(self, *args):
       +        '''Wrap the base wizard implementation with try/except blocks
       +        to give a sensible error message to the user.'''
       +        wallet = None
       +        try:
       +            wallet = super(InstallWizard, self).open_wallet(*args)
       +        except UserCancelled:
       +            self.print_error("wallet creation cancelled by user")
       +        except Exception as e:
       +            traceback.print_exc(file=stdout)
       +            self.show_error(str(e))
       +        return wallet
       +
       +    def remove_from_recently_open(self, filename):
       +        self.config.remove_from_recently_open(filename)
       +
       +    # Called by plugins
       +    def confirm(self, msg, icon=None):
       +        '''Returns True or False'''
       +        vbox = QVBoxLayout()
       +        self.set_layout(vbox)
       +        if icon:
       +            logo = QLabel()
       +            logo.setPixmap(icon)
       +            vbox.addWidget(logo)
       +        label = QLabel(msg)
       +        label.setWordWrap(True)
       +        vbox.addWidget(label)
       +        vbox.addStretch(1)
       +        vbox.addLayout(Buttons(CancelButton(self, _("Cancel")),
       +                               OkButton(self, _("Next"))))
       +        if not self.exec_():
       +            raise UserCancelled
       +
       +    def show_and_verify_seed(self, seed, is_valid=None):
       +        """Show the user their seed.  Ask them to re-enter it.  Return
       +        True on success."""
       +        self.show_seed(seed)
       +        self.app.clipboard().clear()
       +        self.verify_seed(seed, is_valid)
       +
       +    def pw_dialog(self, msg, kind):
       +        dialog = PasswordDialog(self, None, msg, kind)
       +        accepted, p, pass_text = dialog.run()
       +        if not accepted:
       +            raise UserCancelled
       +        return pass_text
       +
       +    def request_passphrase(self, device_text, restore=True):
       +        """Request a passphrase for a wallet from the given device and
       +        confirm it.  restore is True if restoring a wallet.  Should return
       +        a unicode string."""
       +        if restore:
       +            msg = MSG_RESTORE_PASSPHRASE % device_text
       +        return unicode(self.pw_dialog(msg, PasswordDialog.PW_PASSPHRASE) or '')
       +
       +    def request_password(self, msg=None):
       +        """Request the user enter a new password and confirm it.  Return
       +        the password or None for no password."""
       +        return self.pw_dialog(msg or MSG_ENTER_PASSWORD, PasswordDialog.PW_NEW)
       +
       +    def query_hardware(self, choices, action):
       +        if action == 'create':
       +            msg = _('Select the hardware wallet to create')
       +        else:
       +            msg = _('Select the hardware wallet to restore')
       +        return self.choice(msg, choices)
       +
       +    def choose_server(self, network):
       +        # Show network dialog if config does not exist
       +        if self.config.get('server') is None:
       +            self.network_dialog(network)
       +
            def set_layout(self, layout):
                w = QWidget()
                w.setLayout(layout)
       t@@ -85,7 +151,9 @@ class InstallWizard(WindowModalDialog, MessageBoxMixin):
                self.stack.setCurrentWidget(w)
                self.show()
        
       -    def restore_or_create(self):
       +    def query_create_or_restore(self):
       +        """Returns a tuple (action, kind).  Action is one of user_actions,
       +        or None if cancelled.  kind is one of wallet_kinds."""
                vbox = QVBoxLayout()
        
                main_label = QLabel(_("Electrum could not find an existing wallet."))
       t@@ -120,14 +188,14 @@ class InstallWizard(WindowModalDialog, MessageBoxMixin):
        
                group2 = QButtonGroup()
        
       -        self.wallet_types = [
       +        wallet_types = [
                    ('standard',  _("Standard wallet")),
                    ('twofactor', _("Wallet with two-factor authentication")),
                    ('multisig',  _("Multi-signature wallet")),
                    ('hardware',  _("Hardware wallet")),
                ]
        
       -        for i, (wtype,name) in enumerate(self.wallet_types):
       +        for i, (wtype,name) in enumerate(wallet_types):
                    if not filter(lambda x:x[0]==wtype, electrum.wallet.wallet_types):
                        continue
                    button = QRadioButton(gb2)
       t@@ -146,51 +214,40 @@ class InstallWizard(WindowModalDialog, MessageBoxMixin):
                self.raise_()
        
                if not self.exec_():
       -            return None, None
       +            raise UserCancelled
        
                action = 'create' if b1.isChecked() else 'restore'
       -        wallet_type = self.wallet_types[group2.checkedId()][0]
       +        wallet_type = wallet_types[group2.checkedId()][0]
                return action, wallet_type
        
       -
       -    def verify_seed(self, seed, sid, func=None):
       -        r = self.enter_seed_dialog(MSG_VERIFY_SEED, sid, func)
       -        if not r:
       -            return
       -        if prepare_seed(r) != prepare_seed(seed):
       +    def verify_seed(self, seed, is_valid=None):
       +        while True:
       +            r = self.request_seed(MSG_VERIFY_SEED, is_valid)
       +            if prepare_seed(r) == prepare_seed(seed):
       +                return
                    self.show_error(_('Incorrect seed'))
       -            return False
       -        else:
       -            return True
       -
        
            def get_seed_text(self, seed_e):
                text = unicode(seed_e.toPlainText()).strip()
                text = ' '.join(text.split())
                return text
        
       -    def is_any(self, text):
       -        return Wallet.is_seed(text) or Wallet.is_old_mpk(text) or Wallet.is_xpub(text) or Wallet.is_xprv(text) or Wallet.is_address(text) or Wallet.is_private_key(text)
       -
       -    def is_mpk(self, text):
       -        return Wallet.is_xpub(text) or Wallet.is_old_mpk(text)
       -
       -    def enter_seed_dialog(self, msg, sid, func=None):
       -        if func is None:
       -            func = self.is_any
       -        vbox, seed_e = seed_dialog.enter_seed_box(msg, self, sid)
       +    def request_seed(self, msg, is_valid=None):
       +        is_valid = is_valid or Wallet.is_any
       +        vbox, seed_e = seed_dialog.enter_seed_box(msg, self)
                vbox.addStretch(1)
                button = OkButton(self, _('Next'))
                vbox.addLayout(Buttons(CancelButton(self), button))
                button.setEnabled(False)
       -        seed_e.textChanged.connect(lambda: button.setEnabled(func(self.get_seed_text(seed_e))))
       +        def set_enabled():
       +            button.setEnabled(is_valid(self.get_seed_text(seed_e)))
       +        seed_e.textChanged.connect(set_enabled)
                self.set_layout(vbox)
                if not self.exec_():
       -            return
       +            raise UserCancelled
                return self.get_seed_text(seed_e)
        
       -
       -    def multi_mpk_dialog(self, xpub_hot, n):
       +    def request_many(self, n, xpub_hot=None):
                vbox = QVBoxLayout()
                scroll = QScrollArea()
                scroll.setEnabled(True)
       t@@ -203,75 +260,45 @@ class InstallWizard(WindowModalDialog, MessageBoxMixin):
                innerVbox = QVBoxLayout()
                w.setLayout(innerVbox)
        
       -        vbox0 = seed_dialog.show_seed_box(MSG_SHOW_MPK, xpub_hot, 'hot')
       -        innerVbox.addLayout(vbox0)
                entries = []
       +        if xpub_hot:
       +            vbox0 = seed_dialog.show_seed_box(MSG_SHOW_MPK, xpub_hot, 'hot')
       +        else:
       +            vbox0, seed_e1 = seed_dialog.enter_seed_box(MSG_ENTER_SEED_OR_MPK, self, 'hot')
       +            entries.append(seed_e1)
       +        innerVbox.addLayout(vbox0)
       +
                for i in range(n):
       -            msg = _("Please enter the master public key of cosigner") + ' %d'%(i+1)
       +            if xpub_hot:
       +                msg = MSG_COSIGNER % (i + 1)
       +            else:
       +                msg = MSG_ENTER_SEED_OR_MPK
                    vbox2, seed_e2 = seed_dialog.enter_seed_box(msg, self, 'cold')
                    innerVbox.addLayout(vbox2)
                    entries.append(seed_e2)
       -        vbox.addStretch(1)
       -        button = OkButton(self, _('Next'))
       -        vbox.addLayout(Buttons(CancelButton(self), button))
       -        button.setEnabled(False)
       -        f = lambda: button.setEnabled( map(lambda e: Wallet.is_xpub(self.get_seed_text(e)), entries) == [True]*len(entries))
       -        for e in entries:
       -            e.textChanged.connect(f)
       -        self.set_layout(vbox)
       -        if not self.exec_():
       -            return
       -        return map(lambda e: self.get_seed_text(e), entries)
       -
       -
       -    def multi_seed_dialog(self, n):
       -        vbox = QVBoxLayout()
       -        scroll = QScrollArea()
       -        scroll.setEnabled(True)
       -        scroll.setWidgetResizable(True)
       -        vbox.addWidget(scroll)
       -
       -        w = QWidget()
       -        scroll.setWidget(w)
       -
       -        innerVbox = QVBoxLayout()
       -        w.setLayout(innerVbox)
        
       -        vbox1, seed_e1 = seed_dialog.enter_seed_box(MSG_ENTER_SEED_OR_MPK, self, 'hot')
       -        innerVbox.addLayout(vbox1)
       -        entries = [seed_e1]
       -        for i in range(n):
       -            vbox2, seed_e2 = seed_dialog.enter_seed_box(MSG_ENTER_SEED_OR_MPK, self, 'cold')
       -            innerVbox.addLayout(vbox2)
       -            entries.append(seed_e2)
                vbox.addStretch(1)
                button = OkButton(self, _('Next'))
                vbox.addLayout(Buttons(CancelButton(self), button))
                button.setEnabled(False)
       -        f = lambda: button.setEnabled( map(lambda e: self.is_any(self.get_seed_text(e)), entries) == [True]*len(entries))
       +        def get_texts():
       +            return [self.get_seed_text(entry) for entry in entries]
       +        def set_enabled():
       +            texts = get_texts()
       +            is_valid = Wallet.is_xpub if xpub_hot else Wallet.is_any
       +            all_valid = all(is_valid(text) for text in texts)
       +            if xpub_hot:
       +                texts.append(xpub_hot)
       +            has_dups = len(set(texts)) < len(texts)
       +            button.setEnabled(all_valid and not has_dups)
                for e in entries:
       -            e.textChanged.connect(f)
       +            e.textChanged.connect(set_enabled)
                self.set_layout(vbox)
                if not self.exec_():
       -            return
       -        return map(lambda e: self.get_seed_text(e), entries)
       -
       -
       -    def waiting_dialog(self, task, msg= _("Electrum is generating your addresses, please wait.")):
       -        def target():
       -            task()
       -            self.emit(QtCore.SIGNAL('accept'))
       -
       -        vbox = QVBoxLayout()
       -        self.waiting_label = QLabel(msg)
       -        vbox.addWidget(self.waiting_label)
       -        self.set_layout(vbox)
       -        t = threading.Thread(target = target)
       -        t.start()
       -        self.exec_()
       +            raise UserCancelled
       +        return get_texts()
        
       -
       -    def network_dialog(self):
       +    def network_dialog(self, network):
                grid = QGridLayout()
                grid.setSpacing(5)
                label = QLabel(_("Electrum communicates with remote servers to get information about your transactions and addresses. The servers all fulfil the same purpose only differing in hardware. In most cases you simply want to let Electrum pick one at random if you have a preference though feel free to select a server manually.") + "\n\n" \
       t@@ -296,31 +323,14 @@ class InstallWizard(WindowModalDialog, MessageBoxMixin):
                    return
        
                if b2.isChecked():
       -            return NetworkDialog(self.network, self.config, None).do_exec()
       +            NetworkDialog(network, self.config, None).do_exec()
                else:
                    self.config.set_key('auto_connect', True, True)
       -            self.network.auto_connect = True
       -            return
       +            network.auto_connect = True
        
       -
       -    def show_message(self, msg, icon=None):
       +    def choice(self, msg, choices):
                vbox = QVBoxLayout()
                self.set_layout(vbox)
       -        if icon:
       -            logo = QLabel()
       -            logo.setPixmap(icon)
       -            vbox.addWidget(logo)
       -        vbox.addWidget(QLabel(msg))
       -        vbox.addStretch(1)
       -        vbox.addLayout(Buttons(CloseButton(self)))
       -        if not self.exec_():
       -            return None
       -
       -
       -    def choice(self, title, msg, choices):
       -        vbox = QVBoxLayout()
       -        self.set_layout(vbox)
       -        vbox.addWidget(QLabel(title))
                gb2 = QGroupBox(msg)
                vbox.addWidget(gb2)
        
       t@@ -337,15 +347,15 @@ class InstallWizard(WindowModalDialog, MessageBoxMixin):
                    if i==0:
                        button.setChecked(True)
                vbox.addStretch(1)
       -        vbox.addLayout(Buttons(CancelButton(self), OkButton(self, _('Next'))))
       +        next_button = OkButton(self, _('Next'))
       +        next_button.setEnabled(bool(choices))
       +        vbox.addLayout(Buttons(CancelButton(self), next_button))
                if not self.exec_():
       -            return
       +            raise UserCancelled
                wallet_type = choices[group2.checkedId()][0]
                return wallet_type
        
       -
       -    def multisig_choice(self):
       -
       +    def query_multisig(self, action):
                vbox = QVBoxLayout()
                self.set_layout(vbox)
                vbox.addWidget(QLabel(_("Multi Signature Wallet")))
       t@@ -379,178 +389,15 @@ class InstallWizard(WindowModalDialog, MessageBoxMixin):
                vbox.addStretch(1)
                vbox.addLayout(Buttons(CancelButton(self), OkButton(self, _('Next'))))
                if not self.exec_():
       -            return
       +            raise UserCancelled
                m = int(m_edit.value())
                n = int(n_edit.value())
                wallet_type = '%dof%d'%(m,n)
                return wallet_type
        
       -    def show_seed(self, seed, sid):
       -        vbox = seed_dialog.show_seed_box_msg(seed, sid)
       +    def show_seed(self, seed):
       +        vbox = seed_dialog.show_seed_box_msg(seed, None)
                vbox.addLayout(Buttons(CancelButton(self), OkButton(self, _("Next"))))
                self.set_layout(vbox)
       -        return self.exec_()
       -
       -    def password_dialog(self):
       -        from password_dialog import PasswordDialog
       -        msg = _("Please choose a password to encrypt your wallet keys.\n"
       -                "Leave these fields empty if you want to disable encryption.")
       -        dialog = PasswordDialog(self, None, _("Choose a password"), msg, True)
       -        return dialog.run()[2]
       -
       -    def run(self, action):
       -        if self.storage.file_exists and action != 'new':
       -            path = self.storage.path
       -            msg = _("The file '%s' contains an incompletely created wallet.\n"
       -                    "Do you want to complete its creation now?") % path
       -            if not self.question(msg):
       -                if self.question(_("Do you want to delete '%s'?") % path):
       -                    os.remove(path)
       -                    self.show_warning(_('The file was removed'))
       -                    return
       -                return
       -        self.show()
       -        if action == 'new':
       -            action, wallet_type = self.restore_or_create()
       -        else:
       -            wallet_type = None
       -        try:
       -            wallet = self.run_wallet_type(action, wallet_type)
       -        except BaseException as e:
       -            traceback.print_exc(file=sys.stdout)
       -            self.show_error(str(e))
       -            return
       -        return wallet
       -
       -    def run_wallet_type(self, action, wallet_type):
       -        if action in ['create', 'restore']:
       -            if wallet_type == 'multisig':
       -                wallet_type = self.multisig_choice()
       -                if not wallet_type:
       -                    return
       -            elif wallet_type == 'hardware':
       -                hardware_wallets = []
       -                for item in electrum.wallet.wallet_types:
       -                    t, name, description, loader = item
       -                    if t == 'hardware':
       -                        try:
       -                            p = loader()
       -                        except:
       -                            util.print_error("cannot load plugin for:", name)
       -                            continue
       -                        if p:
       -                            hardware_wallets.append((name, description))
       -                wallet_type = self.choice(_("Hardware Wallet"), 'Select your hardware wallet', hardware_wallets)
       -
       -                if not wallet_type:
       -                    return
       -            elif wallet_type == 'twofactor':
       -                wallet_type = '2fa'
       -            if action == 'create':
       -                self.storage.put('wallet_type', wallet_type)
       -
       -        if action is None:
       -            return
       -
       -        if action == 'restore':
       -            wallet = self.restore(wallet_type)
       -            if not wallet:
       -                return
       -            action = None
       -        else:
       -            wallet = Wallet(self.storage)
       -            action = wallet.get_action()
       -            # fixme: password is only needed for multiple accounts
       -            password = None
       -
       -        # load wallet in plugins
       -        always_hook('installwizard_load_wallet', wallet, self)
       -
       -        while action is not None:
       -            util.print_error("installwizard:", wallet, action)
       -
       -            if action == 'create_seed':
       -                lang = self.config.get('language')
       -                seed = wallet.make_seed(lang)
       -                if not self.show_seed(seed, None):
       -                    return
       -                self.app.clipboard().clear()
       -                if not self.verify_seed(seed, None):
       -                    return
       -                password = self.password_dialog()
       -                wallet.add_seed(seed, password)
       -                wallet.create_master_keys(password)
       -
       -            elif action == 'add_cosigners':
       -                n = int(re.match('(\d+)of(\d+)', wallet.wallet_type).group(2))
       -                xpub1 = wallet.master_public_keys.get("x1/")
       -                r = self.multi_mpk_dialog(xpub1, n - 1)
       -                if not r:
       -                    return
       -                for i, xpub in enumerate(r):
       -                    wallet.add_master_public_key("x%d/"%(i+2), xpub)
       -
       -            elif action == 'create_accounts':
       -                wallet.create_main_account(password)
       -                self.waiting_dialog(wallet.synchronize)
       -
       -            else:
       -                f = always_hook('get_wizard_action', self, wallet, action)
       -                if not f:
       -                    raise BaseException('unknown wizard action', action)
       -                r = f(wallet, self)
       -                if not r:
       -                    return
       -
       -            # next action
       -            action = wallet.get_action()
       -
       -
       -        if self.network:
       -            # show network dialog if config does not exist
       -            if self.config.get('server') is None:
       -                self.network_dialog()
       -        else:
       -            self.show_warning(_('You are offline'))
       -
       -
       -        # start wallet threads
       -        wallet.start_threads(self.network)
       -
       -        if action == 'restore':
       -            self.waiting_dialog(lambda: wallet.wait_until_synchronized(self.waiting_label.setText))
       -            if self.network:
       -                msg = _("Recovery successful") if wallet.is_found() else _("No transactions found for this seed")
       -            else:
       -                msg = _("This wallet was restored offline. It may contain more addresses than displayed.")
       -            self.show_message(msg)
       -
       -        return wallet
       -
       -
       -
       -    def restore(self, t):
       -        if t == 'standard':
       -            text = self.enter_seed_dialog(MSG_ENTER_ANYTHING, None)
       -            if not text:
       -                return
       -            password = self.password_dialog() if Wallet.is_seed(text) or Wallet.is_xprv(text) or Wallet.is_private_key(text) else None
       -            wallet = Wallet.from_text(text, password, self.storage)
       -        elif re.match('(\d+)of(\d+)', t):
       -            n = int(re.match('(\d+)of(\d+)', t).group(2))
       -            key_list = self.multi_seed_dialog(n - 1)
       -            if not key_list:
       -                return
       -            password = self.password_dialog() if any(map(lambda x: Wallet.is_seed(x) or Wallet.is_xprv(x), key_list)) else None
       -            wallet = Wallet.from_multisig(key_list, password, self.storage, t)
       -        else:
       -            self.storage.put('wallet_type', t)
       -            # call the constructor to load the plugin (side effect)
       -            Wallet(self.storage)
       -            wallet = always_hook('installwizard_restore', self, self.storage)
       -            if not wallet:
       -                util.print_error("no wallet")
       -                return
       -        # create first keys offline
       -        self.waiting_dialog(wallet.synchronize)
       -        return wallet
       +        if not self.exec_():
       +            raise UserCancelled
   DIR diff --git a/gui/qt/main_window.py b/gui/qt/main_window.py
       t@@ -41,8 +41,8 @@ from electrum.util import block_explorer, block_explorer_info, block_explorer_UR
        from electrum.util import format_satoshis, format_satoshis_plain, format_time
        from electrum.util import PrintError, NotEnoughFunds, StoreDict
        from electrum import Transaction, mnemonic
       -from electrum import util, bitcoin, commands, Wallet
       -from electrum import SimpleConfig, COIN_CHOOSERS, WalletStorage
       +from electrum import util, bitcoin, commands
       +from electrum import SimpleConfig, COIN_CHOOSERS
        from electrum import Imported_Wallet, paymentrequest
        
        from amountedit import BTCAmountEdit, MyLineEdit, BTCkBEdit
       t@@ -173,8 +173,8 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, PrintError):
                self.fetch_alias()
                self.require_fee_update = False
                self.tx_notifications = []
       -        # load wallet
                self.load_wallet(wallet)
       +        self.connect_slots(gui_object.timer)
        
            def diagnostic_name(self):
                return "%s/%s" % (PrintError.diagnostic_name(self),
       t@@ -247,12 +247,8 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, PrintError):
        
            def load_wallet(self, wallet):
                self.wallet = wallet
       -        # backward compatibility
       -        self.update_wallet_format()
       +        self.update_recently_visited(wallet.storage.path)
                self.import_old_contacts()
       -        # address used to create a dummy transaction and estimate transaction fee
       -        a = self.wallet.addresses(False)
       -        self.dummy_address = a[0] if a else None
                self.accounts_expanded = self.wallet.storage.get('accounts_expanded',{})
                self.current_account = self.wallet.storage.get("current_account", None)
                self.history_list.update()
       t@@ -269,14 +265,17 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, PrintError):
                self.clear_receive_tab()
                self.receive_list.update()
                self.tabs.show()
       +        self.watching_only_changed()
        
       -        # set geometry
                try:
                    self.setGeometry(*self.wallet.storage.get("winpos-qt"))
                except:
                    self.setGeometry(100, 100, 840, 400)
       -        self.watching_only_changed()
       -        self.show()
       +
       +        if self.config.get('hide_gui') and self.gui_object.tray.isVisible():
       +            self.hide()
       +        else:
       +            self.show()
                run_hook('load_wallet', wallet, self)
                self.warn_if_watching_only()
        
       t@@ -311,19 +310,6 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, PrintError):
                            self.contacts[l] = ('address', k)
                    self.wallet.storage.put('contacts', None)
        
       -    def update_wallet_format(self):
       -        # convert old-format imported keys
       -        if self.wallet.imported_keys:
       -            password = self.password_dialog(_("Please enter your password in order to update imported keys")) if self.wallet.use_encryption else None
       -            try:
       -                self.wallet.convert_imported_keys(password)
       -            except Exception as e:
       -                traceback.print_exc(file=sys.stdout)
       -                self.show_message(str(e))
       -        # call synchronize to regenerate addresses in case we are offline
       -        if self.wallet.get_master_public_keys() and self.wallet.addresses() == []:
       -            self.wallet.synchronize()
       -
            def open_wallet(self):
                wallet_folder = self.get_wallet_folder()
                filename = unicode(QFileDialog.getOpenFileName(self, "Select your wallet file", wallet_folder))
       t@@ -347,14 +333,13 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, PrintError):
                    except (IOError, os.error), reason:
                        self.show_critical(_("Electrum was unable to copy your wallet file to the specified location.") + "\n" + str(reason), title=_("Unable to create backup"))
        
       -    def update_recently_visited(self, filename=None):
       +    def update_recently_visited(self, filename):
                recent = self.config.get('recently_open', [])
       -        if filename:
       -            if filename in recent:
       -                recent.remove(filename)
       -            recent.insert(0, filename)
       -            recent = recent[:5]
       -            self.config.set_key('recently_open', recent)
       +        if filename in recent:
       +            recent.remove(filename)
       +        recent.insert(0, filename)
       +        recent = recent[:5]
       +        self.config.set_key('recently_open', recent)
                self.recently_visited_menu.clear()
                for i, k in enumerate(sorted(recent)):
                    b = os.path.basename(k)
       t@@ -380,11 +365,10 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, PrintError):
                if not filename:
                    return
                full_path = os.path.join(wallet_folder, filename)
       -        storage = WalletStorage(full_path)
       -        if storage.file_exists:
       +        if os.path.exists(full_path):
                    self.show_critical(_("File exists"))
                    return
       -        self.gui_object.install_wizard(storage, 'new')
       +        self.gui_object.start_new_window(full_path, None)
        
            def init_menubar(self):
                menubar = QMenuBar()
       t@@ -396,7 +380,6 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, PrintError):
                file_menu.addAction(_("&Save Copy"), self.backup_wallet).setShortcut(QKeySequence.SaveAs)
                file_menu.addSeparator()
                file_menu.addAction(_("&Quit"), self.close)
       -        self.update_recently_visited()
        
                wallet_menu = menubar.addMenu(_("&Wallet"))
                wallet_menu.addAction(_("&New contact"), self.new_contact_dialog)
       t@@ -1088,7 +1071,7 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, PrintError):
                else:
                    fee = self.fee_e.get_amount() if freeze_fee else None
                    if not outputs:
       -                addr = self.payto_e.payto_address if self.payto_e.payto_address else self.dummy_address
       +                addr = self.payto_e.payto_address if self.payto_e.payto_address else None
                        outputs = [('address', addr, amount)]
                    try:
                        tx = self.wallet.make_unsigned_transaction(self.get_coins(), outputs, self.config, fee)
       t@@ -1853,7 +1836,7 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, PrintError):
                         'password. To disable wallet encryption, enter an empty new '
                         'password.') if self.wallet.use_encryption
                       else _('Your wallet keys are not encrypted'))
       -        d = PasswordDialog(self, self.wallet, _("Set Password"), msg, True)
       +        d = PasswordDialog(self, self.wallet, msg, PasswordDialog.PW_CHANGE)
                ok, password, new_password = d.run()
                if not ok:
                    return
   DIR diff --git a/gui/qt/password_dialog.py b/gui/qt/password_dialog.py
       t@@ -41,8 +41,11 @@ def check_password_strength(password):
        
        class PasswordDialog(WindowModalDialog):
        
       -    def __init__(self, parent, wallet, title, msg, new_pass):
       -        WindowModalDialog.__init__(self, parent, title)
       +    PW_NEW, PW_CHANGE, PW_PASSPHRASE = range(0, 3)
       +    titles = [_("Enter Password"), _("Change Password"), _("Enter Passphrase")]
       +
       +    def __init__(self, parent, wallet, msg, kind):
       +        WindowModalDialog.__init__(self, parent, self.titles[kind])
                self.wallet = wallet
        
                self.pw = QLineEdit()
       t@@ -51,41 +54,48 @@ class PasswordDialog(WindowModalDialog):
                self.new_pw.setEchoMode(2)
                self.conf_pw = QLineEdit()
                self.conf_pw.setEchoMode(2)
       +        self.kind = kind
        
                vbox = QVBoxLayout()
       -        label = QLabel(msg)
       +        label = QLabel(msg + "\n")
                label.setWordWrap(True)
        
                grid = QGridLayout()
                grid.setSpacing(8)
       -        grid.setColumnMinimumWidth(0, 70)
       -        grid.setColumnStretch(1,1)
       -
       -        logo = QLabel()
       -        logo.setAlignment(Qt.AlignCenter)
       -
       -        grid.addWidget(logo,  0, 0)
       -        grid.addWidget(label, 0, 1, 1, 2)
       -        vbox.addLayout(grid)
       -
       -        grid = QGridLayout()
       -        grid.setSpacing(8)
       -        grid.setColumnMinimumWidth(0, 250)
       +        grid.setColumnMinimumWidth(0, 150)
       +        grid.setColumnMinimumWidth(1, 100)
                grid.setColumnStretch(1,1)
        
       -        if wallet and wallet.use_encryption:
       -            grid.addWidget(QLabel(_('Password')), 0, 0)
       -            grid.addWidget(self.pw, 0, 1)
       -            lockfile = ":icons/lock.png"
       +        if kind == self.PW_PASSPHRASE:
       +            vbox.addWidget(label)
       +            msgs = [_('Passphrase:'), _('Confirm Passphrase:')]
                else:
       -            self.pw = None
       -            lockfile = ":icons/unlock.png"
       -        logo.setPixmap(QPixmap(lockfile).scaledToWidth(36))
       -
       -        grid.addWidget(QLabel(_('New Password') if new_pass else _('Password')), 1, 0)
       +            logo_grid = QGridLayout()
       +            logo_grid.setSpacing(8)
       +            logo_grid.setColumnMinimumWidth(0, 70)
       +            logo_grid.setColumnStretch(1,1)
       +
       +            logo = QLabel()
       +            logo.setAlignment(Qt.AlignCenter)
       +
       +            logo_grid.addWidget(logo,  0, 0)
       +            logo_grid.addWidget(label, 0, 1, 1, 2)
       +            vbox.addLayout(logo_grid)
       +
       +            m1 = _('New Password:') if kind == self.PW_NEW else _('Password:')
       +            msgs = [m1, _('Confirm Password:')]
       +            if wallet and wallet.use_encryption:
       +                grid.addWidget(QLabel(_('Current Password:')), 0, 0)
       +                grid.addWidget(self.pw, 0, 1)
       +                lockfile = ":icons/lock.png"
       +            else:
       +                lockfile = ":icons/unlock.png"
       +                logo.setPixmap(QPixmap(lockfile).scaledToWidth(36))
       +
       +        grid.addWidget(QLabel(msgs[0]), 1, 0)
                grid.addWidget(self.new_pw, 1, 1)
        
       -        grid.addWidget(QLabel(_('Confirm Password')), 2, 0)
       +        grid.addWidget(QLabel(msgs[1]), 2, 0)
                grid.addWidget(self.conf_pw, 2, 1)
                vbox.addLayout(grid)
        
       t@@ -120,8 +130,10 @@ class PasswordDialog(WindowModalDialog):
                if not self.exec_():
                    return False, None, None
        
       -        password = unicode(self.pw.text()) if self.pw else None
       -        new_password = unicode(self.new_pw.text())
       -        new_password2 = unicode(self.conf_pw.text())
       +        if self.kind == self.PW_CHANGE:
       +            old_password = unicode(self.pw.text()) or None
       +        else:
       +            old_password = None
       +        new_password = unicode(self.new_pw.text()) or None
        
       -        return True, password or None, new_password or None
       +        return True, old_password, new_password
   DIR diff --git a/lib/__init__.py b/lib/__init__.py
       t@@ -11,3 +11,4 @@ import transaction
        from transaction import Transaction
        from plugins import BasePlugin
        from commands import Commands, known_commands
       +import wizard as wizard
   DIR diff --git a/lib/plugins.py b/lib/plugins.py
       t@@ -26,6 +26,7 @@ import time
        from util import *
        from i18n import _
        from util import profiler, PrintError, DaemonThread
       +import wallet
        
        class Plugins(DaemonThread):
        
       t@@ -38,18 +39,21 @@ class Plugins(DaemonThread):
                else:
                    plugins = __import__('electrum_plugins')
                self.pkgpath = os.path.dirname(plugins.__file__)
       +        self.config = config
       +        self.hw_wallets = {}
                self.plugins = {}
                self.gui_name = gui_name
                self.descriptions = []
                for loader, name, ispkg in pkgutil.iter_modules([self.pkgpath]):
                    m = loader.find_module(name).load_module(name)
                    d = m.__dict__
       -            if gui_name not in d.get('available_for', []):
       +            gui_good = gui_name in d.get('available_for', [])
       +            details = d.get('registers_wallet_type')
       +            if details:
       +                self.register_plugin_wallet(name, gui_good, details)
       +            if not gui_good:
                        continue
                    self.descriptions.append(d)
       -            x = d.get('registers_wallet_type')
       -            if x:
       -                self.register_wallet_type(config, name, x)
                    if not d.get('requires_wallet_type') and config.get('use_' + name):
                        self.load_plugin(config, name)
        
       t@@ -100,16 +104,29 @@ class Plugins(DaemonThread):
                        return False
                return w.wallet_type in d.get('requires_wallet_type', [])
        
       -    def wallet_plugin_loader(self, config, name):
       -        if self.plugins.get(name) is None:
       -            self.load_plugin(config, name)
       +    def hardware_wallets(self, action):
       +        result = []
       +        for name, (gui_good, details) in self.hw_wallets.items():
       +            if gui_good:
       +                try:
       +                    p = self.wallet_plugin_loader(name)
       +                    if action == 'restore' or p.is_enabled():
       +                        result.append((details[1], details[2]))
       +                except:
       +                    self.print_error("cannot load plugin for:", name)
       +        return result
       +
       +    def register_plugin_wallet(self, name, gui_good, details):
       +        if details[0] == 'hardware':
       +            self.hw_wallets[name] = (gui_good, details)
       +        register = details + (lambda: self.wallet_plugin_loader(name),)
       +        wallet.wallet_types.append(register)
       +
       +    def wallet_plugin_loader(self, name):
       +        if not name in self.plugins:
       +            self.load_plugin(self.config, name)
                return self.plugins[name]
        
       -    def register_wallet_type(self, config, name, x):
       -        import wallet
       -        x += (lambda: self.wallet_plugin_loader(config, name),)
       -        wallet.wallet_types.append(x)
       -
            def run(self):
                jobs = [job for plugin in self.plugins.values()
                        for job in plugin.thread_jobs()]
   DIR diff --git a/lib/simple_config.py b/lib/simple_config.py
       t@@ -162,6 +162,11 @@ class SimpleConfig(object):
        
                return new_path
        
       +    def remove_from_recently_open(self, filename):
       +        recent = self.get('recently_open', [])
       +        if filename in recent:
       +            recent.remove(filename)
       +            self.set_key('recently_open', recent)
        
        
        def read_system_config(path=SYSTEM_CONFIG_PATH):
   DIR diff --git a/lib/wallet.py b/lib/wallet.py
       t@@ -205,6 +205,9 @@ class Abstract_Wallet(PrintError):
            def diagnostic_name(self):
                return self.basename()
        
       +    def set_use_encryption(self, use_encryption):
       +        self.use_encryption = use_encryption
       +        self.storage.put('use_encryption', use_encryption)
        
            @profiler
            def load_transactions(self):
       t@@ -310,6 +313,9 @@ class Abstract_Wallet(PrintError):
                if removed:
                    self.save_accounts()
        
       +    def create_main_account(self, password):
       +        pass
       +
            def synchronize(self):
                pass
        
       t@@ -1049,8 +1055,7 @@ class Abstract_Wallet(PrintError):
                        self.master_private_keys[k] = c
                    self.storage.put('master_private_keys', self.master_private_keys)
        
       -        self.use_encryption = (new_password != None)
       -        self.storage.put('use_encryption', self.use_encryption)
       +        self.set_use_encryption(new_password is not None)
        
            def is_frozen(self, addr):
                return addr in self.frozen_addresses
       t@@ -1112,15 +1117,16 @@ class Abstract_Wallet(PrintError):
                                _("Please wait..."),
                                _("Addresses generated:"),
                                len(self.addresses(True)))
       -                    apply(callback, (msg,))
       +                    callback(msg)
                        time.sleep(0.1)
                def wait_for_network():
                    while not self.network.is_connected():
                        if callback:
                            msg = "%s \n" % (_("Connecting..."))
       -                    apply(callback, (msg,))
       +                    callback(msg)
                        time.sleep(0.1)
       -        # wait until we are connected, because the user might have selected another server
       +        # wait until we are connected, because the user
       +        # might have selected another server
                if self.network:
                    wait_for_network()
                    wait_for_wallet()
       t@@ -1428,14 +1434,10 @@ class Deterministic_Wallet(Abstract_Wallet):
        
                self.seed_version, self.seed = self.format_seed(seed)
                if password:
       -            self.seed = pw_encode( self.seed, password)
       -            self.use_encryption = True
       -        else:
       -            self.use_encryption = False
       -
       +            self.seed = pw_encode(self.seed, password)
                self.storage.put('seed', self.seed)
                self.storage.put('seed_version', self.seed_version)
       -        self.storage.put('use_encryption', self.use_encryption)
       +        self.set_use_encryption(password is not None)
        
            def get_seed(self, password):
                return pw_decode(self.seed, password)
       t@@ -1527,8 +1529,6 @@ class Deterministic_Wallet(Abstract_Wallet):
            def get_action(self):
                if not self.get_master_public_key():
                    return 'create_seed'
       -        if not self.accounts:
       -            return 'create_accounts'
        
            def get_master_public_keys(self):
                out = {}
       t@@ -1632,8 +1632,7 @@ class BIP32_Simple_Wallet(BIP32_Wallet):
                self.add_master_private_key(self.root_name, xprv, password)
                self.add_master_public_key(self.root_name, xpub)
                self.add_account('0', account)
       -        self.use_encryption = (password != None)
       -        self.storage.put('use_encryption', self.use_encryption)
       +        self.set_use_encryption(password is not None)
        
            def create_xpub_wallet(self, xpub):
                account = BIP32_Account({'xpub':xpub})
       t@@ -1797,10 +1796,6 @@ class Multisig_Wallet(BIP32_Wallet, Mnemonic):
                for i in range(self.n):
                    if self.master_public_keys.get("x%d/"%(i+1)) is None:
                        return 'create_seed' if i == 0 else 'add_cosigners'
       -        if not self.accounts:
       -            return 'create_accounts'
       -
       -
        
        
        class OldWallet(Deterministic_Wallet):
       t@@ -1998,6 +1993,15 @@ class Wallet(object):
                        or Wallet.is_private_key(text))
        
            @staticmethod
       +    def multisig_type(wallet_type):
       +        '''If wallet_type is mofn multi-sig, return [m, n],
       +        otherwise return None.'''
       +        match = re.match('(\d+)of(\d+)', wallet_type)
       +        if match:
       +            match = [int(x) for x in match.group(1, 2)]
       +        return match
       +
       +    @staticmethod
            def from_seed(seed, password, storage):
                if is_old_seed(seed):
                    klass = OldWallet
       t@@ -2048,10 +2052,9 @@ class Wallet(object):
            def from_multisig(key_list, password, storage, wallet_type):
                storage.put('wallet_type', wallet_type)
                wallet = Multisig_Wallet(storage)
       -        key_list = sorted(key_list, key = lambda x: Wallet.is_xpub(x))
       +        key_list = sorted(key_list, key = Wallet.is_xpub)
                for i, text in enumerate(key_list):
       -            assert Wallet.is_seed(text) or Wallet.is_xprv(text) or Wallet.is_xpub(text)
       -            name = "x%d/"%(i+1)
       +            name = "x%d/" % (i+1)
                    if Wallet.is_xprv(text):
                        xpub = bitcoin.xpub_from_xprv(text)
                        wallet.add_master_public_key(name, xpub)
       t@@ -2064,8 +2067,9 @@ class Wallet(object):
                            wallet.create_master_keys(password)
                        else:
                            wallet.add_cosigner_seed(text, name, password)
       -        wallet.use_encryption = (password != None)
       -        wallet.storage.put('use_encryption', wallet.use_encryption)
       +            else:
       +                raise RunTimeError("Cannot handle text for multisig")
       +        wallet.set_use_encryption(password is not None)
                wallet.create_main_account(password)
                return wallet
        
   DIR diff --git a/lib/wizard.py b/lib/wizard.py
       t@@ -0,0 +1,285 @@
       +#!/usr/bin/env python
       +#
       +# Electrum - lightweight Bitcoin client
       +# Copyright (C) 2015 thomasv@gitorious, kyuupichan@gmail
       +#
       +# This program is free software: you can redistribute it and/or modify
       +# it under the terms of the GNU General Public License as published by
       +# the Free Software Foundation, either version 3 of the License, or
       +# (at your option) any later version.
       +#
       +# This program is distributed in the hope that it will be useful,
       +# but WITHOUT ANY WARRANTY; without even the implied warranty of
       +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
       +# GNU General Public License for more details.
       +#
       +# You should have received a copy of the GNU General Public License
       +# along with this program. If not, see <http://www.gnu.org/licenses/>.
       +
       +from electrum import WalletStorage
       +from electrum.plugins import run_hook
       +from util import PrintError
       +from wallet import Wallet
       +from i18n import _
       +
       +MSG_GENERATING_WAIT = _("Electrum is generating your addresses, please wait...")
       +MSG_ENTER_ANYTHING = _("Please enter a seed phrase, a master key, a list of "
       +                       "Bitcoin addresses, or a list of private keys")
       +MSG_ENTER_SEED_OR_MPK = _("Please enter a seed phrase or a master key (xpub or xprv):")
       +MSG_VERIFY_SEED = _("Your seed is important!\nTo make sure that you have properly saved your seed, please retype it here.")
       +MSG_COSIGNER = _("Please enter the master public key of cosigner #%d:")
       +MSG_SHOW_MPK = _("Here is your master public key:")
       +MSG_ENTER_PASSWORD = _("Choose a password to encrypt your wallet keys.  "
       +                       "Enter nothing if you want to disable encryption.")
       +MSG_RESTORE_PASSPHRASE = \
       +    _("Please enter the passphrase you used when creating your %s wallet.  "
       +      "Note this is NOT a password.  Enter nothing if you did not use "
       +      "one or are unsure.")
       +
       +class UserCancelled(Exception):
       +    pass
       +
       +class WizardBase(PrintError):
       +    '''Base class for gui-specific install wizards.'''
       +    user_actions = ('create', 'restore')
       +    wallet_kinds = ('standard', 'hardware', 'multisig', 'twofactor')
       +
       +    # Derived classes must set:
       +    #   self.language_for_seed
       +    #   self.plugins
       +
       +    def show_error(self, msg):
       +        raise NotImplementedError
       +
       +    def show_warning(self, msg):
       +        raise NotImplementedError
       +
       +    def remove_from_recently_open(self, filename):
       +        """Remove filename from the recently used list."""
       +        raise NotImplementedError
       +
       +    def query_create_or_restore(self):
       +        """Returns a tuple (action, kind).  Action is one of user_actions,
       +        kind is one of wallet_kinds."""
       +        raise NotImplementedError
       +
       +    def query_multisig(self, action):
       +        """Asks the user what kind of multisig wallet they want.  Returns a
       +        string like "2of3".  Action is 'create' or 'restore'."""
       +        raise NotImplementedError
       +
       +    def query_hardware(self, choices, action):
       +        """Asks the user what kind of hardware wallet they want from the given
       +        choices.  choices is a list of (wallet_type, translated
       +        description) tuples.  Action is 'create' or 'restore'.  Return
       +        the wallet type chosen."""
       +        raise NotImplementedError
       +
       +    def show_and_verify_seed(self, seed):
       +        """Show the user their seed.  Ask them to re-enter it.  Return
       +        True on success."""
       +        raise NotImplementedError
       +
       +    def request_passphrase(self, device_text, restore=True):
       +        """Request a passphrase for a wallet from the given device and
       +        confirm it.  restore is True if restoring a wallet.  Should return
       +        a unicode string."""
       +        raise NotImplementedError
       +
       +    def request_password(self, msg=None):
       +        """Request the user enter a new password and confirm it.  Return
       +        the password or None for no password."""
       +        raise NotImplementedError
       +
       +    def request_seed(self, msg, is_valid=None):
       +        """Request the user enter a seed.  Returns the seed the user entered.
       +        is_valid is a function that returns True if a seed is valid, for
       +        dynamic feedback.  If not provided, Wallet.is_any is used."""
       +        raise NotImplementedError
       +
       +    def request_many(self, n, xpub_hot=None):
       +        """If xpub_hot is provided, a new wallet is being created.  Request N
       +        master public keys for cosigners; xpub_hot is the master xpub
       +        key for the wallet.
       +
       +        If xpub_hot is None, request N cosigning master xpub keys,
       +        xprv keys, or seeds in order to perform wallet restore."""
       +        raise NotImplementedError
       +
       +    def choose_server(self, network):
       +        """Choose a server if one is not set in the config anyway."""
       +        raise NotImplementedError
       +
       +    def open_existing_wallet(self, storage, network):
       +        wallet = Wallet(storage)
       +        self.update_wallet_format(wallet)
       +        self.run_wallet_actions(wallet)
       +        wallet.start_threads(network)
       +        return wallet, None
       +
       +    def create_new_wallet(self, storage, network):
       +        action, wallet = self.create_or_restore(storage)
       +        self.run_wallet_actions(wallet)
       +
       +        if network:
       +            self.choose_server(network)
       +        else:
       +            self.show_warning(_('You are offline'))
       +
       +        def task():
       +            # Synchronize before starting the threads
       +            wallet.synchronize()
       +            wallet.start_threads(network)
       +# FIXME
       +#            if action == 'create':
       +#                msg = _('Wallet addresses generated.')
       +#            else:
       +#                wallet.wait_until_synchronized()
       +#                if network:
       +#                    if wallet.is_found():
       +#                        msg = _("Recovery successful")
       +#                    else:
       +#                        msg = _("No transactions found for this seed")
       +#                else:
       +#                    msg = _("This wallet was restored offline. It may "
       +#                            "contain more addresses than displayed.")
       +#            self.show_message(msg)
       +
       +        return wallet, (MSG_GENERATING_WAIT, task)
       +
       +
       +    def open_wallet(self, network, filename):
       +        '''The main entry point of the wizard.  Open a wallet from the given
       +        filename.  If the file doesn't exist launch the GUI-specific
       +        install wizard proper.'''
       +        storage = WalletStorage(filename)
       +        if storage.file_exists:
       +            return self.open_existing_wallet(storage, network)
       +        else:
       +            return self.create_new_wallet(storage, network)
       +
       +    def run_wallet_actions(self, wallet):
       +        if not wallet:
       +            return
       +        action = orig_action = wallet.get_action()
       +        while action:
       +            self.run_wallet_action(wallet, action)
       +            action = wallet.get_action()
       +        # Save the wallet after successful completion of actions.
       +        # It will be saved again once synchronized.
       +        if orig_action:
       +            wallet.storage.write()
       +
       +    def run_wallet_action(self, wallet, action):
       +        self.print_error("action %s on %s" % (action, wallet.basename()))
       +        # Run the action on the wallet plugin, if any, then the
       +        # wallet and finally ourselves
       +        calls = [(wallet.plugin, (wallet, self)),
       +                 (wallet, (wallet, )),
       +                 (self, (wallet, ))]
       +        calls = [(getattr(actor, action), args) for (actor, args) in calls
       +                 if hasattr(actor, action)]
       +        if not calls:
       +            raise RuntimeError("No handler found for %s action" % action)
       +        for method, args in calls:
       +            method(*args)
       +
       +    def create_or_restore(self, storage):
       +        '''After querying the user what they wish to do, create or restore
       +        a wallet and return it.'''
       +        self.remove_from_recently_open(storage.path)
       +
       +        action, kind = self.query_create_or_restore()
       +
       +        assert action in self.user_actions
       +        assert kind in self.wallet_kinds
       +
       +        if kind == 'multisig':
       +            wallet_type = self.query_multisig(action)
       +        elif kind == 'hardware':
       +            choices = self.plugins.hardware_wallets(action)
       +            wallet_type = self.query_hardware(choices, action)
       +        elif kind == 'twofactor':
       +            wallet_type = '2fa'
       +        else:
       +            wallet_type = 'standard'
       +
       +        if action == 'create':
       +            wallet = self.create_wallet(storage, wallet_type, kind)
       +        else:
       +            wallet = self.restore_wallet(storage, wallet_type, kind)
       +
       +        return action, wallet
       +
       +    def construct_wallet(self, storage, wallet_type):
       +        storage.put('wallet_type', wallet_type)
       +        return Wallet(storage)
       +
       +    def create_wallet(self, storage, wallet_type, kind):
       +        wallet = self.construct_wallet(storage, wallet_type)
       +        if kind == 'hardware':
       +            wallet.plugin.on_create_wallet(wallet, self)
       +        return wallet
       +
       +    def restore_wallet(self, storage, wallet_type, kind):
       +        if wallet_type == 'standard':
       +            return self.restore_standard_wallet(storage)
       +
       +        # Multisig?
       +        if kind == 'multisig':
       +            return self.restore_multisig_wallet(storage, wallet_type)
       +
       +        # Plugin (two-factor or hardware)
       +        wallet = self.construct_wallet(storage, wallet_type)
       +        return wallet.plugin.on_restore_wallet(wallet, self)
       +
       +    def restore_standard_wallet(self, storage):
       +        text = self.request_seed(MSG_ENTER_ANYTHING)
       +        need_password = Wallet.should_encrypt(text)
       +        password = self.request_password() if need_password else None
       +        return Wallet.from_text(text, password, storage)
       +
       +    def restore_multisig_wallet(self, storage, wallet_type):
       +        # FIXME: better handling of duplicate keys
       +        m, n = Wallet.multisig_type(wallet_type)
       +        key_list = self.request_many(n - 1)
       +        need_password = any(Wallet.should_encrypt(text) for text in key_list)
       +        password = self.request_password() if need_password else None
       +        return Wallet.from_multisig(key_list, password, storage, wallet_type)
       +
       +    def create_seed(self, wallet):
       +        '''The create_seed action creates a seed and then generates
       +        wallet account(s).'''
       +        seed = wallet.make_seed(self.language_for_seed)
       +        self.show_and_verify_seed(seed)
       +        password = self.request_password()
       +        wallet.add_seed(seed, password)
       +        wallet.create_master_keys(password)
       +        wallet.create_main_account(password)
       +
       +    def add_cosigners(self, wallet):
       +        # FIXME: better handling of duplicate keys
       +        m, n = Wallet.multisig_type(wallet.wallet_type)
       +        xpub1 = wallet.master_public_keys.get("x1/")
       +        xpubs = self.request_many(n - 1, xpub1)
       +        for i, xpub in enumerate(xpubs):
       +            wallet.add_master_public_key("x%d/" % (i + 2), xpub)
       +
       +    def update_wallet_format(self, wallet):
       +        # Backwards compatibility: convert old-format imported keys
       +        if wallet.imported_keys:
       +            msg = _("Please enter your password in order to update "
       +                    "imported keys")
       +            if wallet.use_encryption:
       +                password = self.request_password(msg)
       +            else:
       +                password = None
       +
       +            try:
       +                wallet.convert_imported_keys(password)
       +            except Exception as e:
       +                self.show_error(str(e))
       +
       +        # Call synchronize to regenerate addresses in case we're offline
       +        if wallet.get_master_public_keys() and not wallet.addresses():
       +            wallet.synchronize()
   DIR diff --git a/plugins/keepkey/cmdline.py b/plugins/keepkey/cmdline.py
       t@@ -1,6 +1,5 @@
        from keepkey import KeepKeyPlugin
        from electrum.util import print_msg
       -from electrum.plugins import hook
        
        class KeepKeyCmdLineHandler:
        
       t@@ -23,8 +22,4 @@ class KeepKeyCmdLineHandler:
                print_msg(msg)
        
        class Plugin(KeepKeyPlugin):
       -    @hook
       -    def cmdline_load_wallet(self, wallet):
       -        wallet.plugin = self
       -        if self.handler is None:
       -            self.handler = KeepKeyCmdLineHandler()
       +    handler = KeepKeyCmdLineHandler()
   DIR diff --git a/plugins/keepkey/keepkey.py b/plugins/keepkey/keepkey.py
       t@@ -1,12 +1,6 @@
        from plugins.trezor.client import trezor_client_class
        from plugins.trezor.plugin import TrezorCompatiblePlugin, TrezorCompatibleWallet
        
       -try:
       -    from keepkeylib.client import proto, BaseClient, ProtocolMixin
       -    KEEPKEY = True
       -except ImportError:
       -    KEEPKEY = False
       -
        
        class KeepKeyWallet(TrezorCompatibleWallet):
            wallet_type = 'keepkey'
       t@@ -14,12 +8,16 @@ class KeepKeyWallet(TrezorCompatibleWallet):
        
        
        class KeepKeyPlugin(TrezorCompatiblePlugin):
       -    client_class = trezor_client_class(ProtocolMixin, BaseClient, proto)
            firmware_URL = 'https://www.keepkey.com'
            libraries_URL = 'https://github.com/keepkey/python-keepkey'
       -    libraries_available = KEEPKEY
            minimum_firmware = (1, 0, 0)
            wallet_class = KeepKeyWallet
       -    import keepkeylib.ckd_public as ckd_public
       -    from keepkeylib.client import types
       -    from keepkeylib.transport_hid import HidTransport
       +    try:
       +        from keepkeylib.client import proto, BaseClient, ProtocolMixin
       +        client_class = trezor_client_class(ProtocolMixin, BaseClient, proto)
       +        import keepkeylib.ckd_public as ckd_public
       +        from keepkeylib.client import types
       +        from keepkeylib.transport_hid import HidTransport
       +        libraries_available = True
       +    except:
       +        libraries_available = False
   DIR diff --git a/plugins/keepkey/qt.py b/plugins/keepkey/qt.py
       t@@ -1,6 +1,9 @@
        from plugins.trezor.qt_generic import QtPlugin
       -from keepkeylib.qt.pinmatrix import PinMatrixWidget
       +
        
        class Plugin(QtPlugin):
       -    pin_matrix_widget_class = PinMatrixWidget
            icon_file = ":icons/keepkey.png"
       +
       +    def pin_matrix_widget_class():
       +        from keepkeylib.qt.pinmatrix import PinMatrixWidget
       +        return PinMatrixWidget
   DIR diff --git a/plugins/trezor/client.py b/plugins/trezor/client.py
       t@@ -70,10 +70,42 @@ def trezor_client_class(protocol_mixin, base_client, proto):
                    protocol_mixin.__init__(self, transport)
                    self.proto = proto
                    self.device = plugin.device
       -            self.handler = plugin.handler
       +            self.handler = None
       +            self.plugin = plugin
                    self.tx_api = plugin
                    self.bad = False
                    self.msg_code_override = None
       +            self.proper_device = False
       +            self.checked_device = False
       +
       +        def check_proper_device(self, wallet):
       +            try:
       +                self.ping('t')
       +            except BaseException as e:
       +                self.plugin.give_error(
       +                    __("%s device not detected.  Continuing in watching-only "
       +                       "mode.") % self.device + "\n\n" + str(e))
       +            if not self.is_proper_device(wallet):
       +                self.plugin.give_error(_('Wrong device or password'))
       +
       +        def is_proper_device(self, wallet):
       +            if not self.checked_device:
       +                addresses = wallet.addresses(False)
       +                if not addresses:   # Wallet being created?
       +                    return True
       +
       +                address = addresses[0]
       +                address_id = wallet.address_id(address)
       +                path = self.expand_path(address_id)
       +                self.checked_device = True
       +                try:
       +                    device_address = self.get_address('Bitcoin', path)
       +                    self.proper_device = (device_address == address)
       +                except:
       +                    self.proper_device = False
       +                wallet.proper_device = self.proper_device
       +
       +            return self.proper_device
        
                def change_label(self, label):
                    self.msg_code_override = 'label'
   DIR diff --git a/plugins/trezor/cmdline.py b/plugins/trezor/cmdline.py
       t@@ -1,6 +1,5 @@
        from trezor import TrezorPlugin
        from electrum.util import print_msg
       -from electrum.plugins import hook
        
        class TrezorCmdLineHandler:
        
       t@@ -24,11 +23,4 @@ class TrezorCmdLineHandler:
        
        
        class Plugin(TrezorPlugin):
       -
       -    @hook
       -    def cmdline_load_wallet(self, wallet):
       -        if type(wallet) != self.wallet_class:
       -            return
       -        wallet.plugin = self
       -        if self.handler is None:
       -            self.handler = TrezorCmdLineHandler()
       +    handler = TrezorCmdLineHandler()
   DIR diff --git a/plugins/trezor/plugin.py b/plugins/trezor/plugin.py
       t@@ -1,6 +1,7 @@
        import re
        from binascii import unhexlify
        from struct import pack
       +from unicodedata import normalize
        
        from electrum.account import BIP32_Account
        from electrum.bitcoin import (bc_address_to_hash_160, xpub_from_pubkey,
       t@@ -21,7 +22,6 @@ class TrezorCompatibleWallet(BIP44_Wallet):
        
            def __init__(self, storage):
                BIP44_Wallet.__init__(self, storage)
       -        self.checked_device = False
                self.proper_device = False
        
            def give_error(self, message):
       t@@ -29,8 +29,7 @@ class TrezorCompatibleWallet(BIP44_Wallet):
                raise Exception(message)
        
            def get_action(self):
       -        if not self.accounts:
       -            return 'create_accounts'
       +        pass
        
            def can_export(self):
                return False
       t@@ -43,7 +42,10 @@ class TrezorCompatibleWallet(BIP44_Wallet):
                return False
        
            def get_client(self):
       -        return self.plugin.get_client()
       +        return self.plugin.get_client(self)
       +
       +    def check_proper_device(self):
       +        return self.get_client().check_proper_device(self)
        
            def derive_xkeys(self, root, derivation, password):
                if self.master_public_keys.get(root):
       t@@ -81,7 +83,7 @@ class TrezorCompatibleWallet(BIP44_Wallet):
                except Exception as e:
                    self.give_error(e)
                finally:
       -            self.plugin.handler.stop()
       +            self.plugin.get_handler(self).stop()
                return msg_sig.signature
        
            def sign_transaction(self, tx, password):
       t@@ -112,34 +114,6 @@ class TrezorCompatibleWallet(BIP44_Wallet):
        
                self.plugin.sign_transaction(self, tx, prev_tx, xpub_path)
        
       -    def is_proper_device(self):
       -        self.get_client().ping('t')
       -
       -        if not self.checked_device:
       -            address = self.addresses(False)[0]
       -            address_id = self.address_id(address)
       -            n = self.get_client().expand_path(address_id)
       -            device_address = self.get_client().get_address('Bitcoin', n)
       -            self.checked_device = True
       -            self.proper_device = (device_address == address)
       -
       -        return self.proper_device
       -
       -    def check_proper_device(self):
       -        if not self.is_proper_device():
       -            self.give_error(_('Wrong device or password'))
       -
       -    def sanity_check(self):
       -        try:
       -            self.get_client().ping('t')
       -        except BaseException as e:
       -            return _("%s device not detected.  Continuing in watching-only "
       -                     "mode.") % self.device + "\n\n" + str(e)
       -
       -        if self.addresses() and not self.is_proper_device():
       -            return _("This wallet does not match your %s device") % self.device
       -
       -        return None
        
        class TrezorCompatiblePlugin(BasePlugin):
            # Derived classes provide:
       t@@ -151,8 +125,8 @@ class TrezorCompatiblePlugin(BasePlugin):
            def __init__(self, parent, config, name):
                BasePlugin.__init__(self, parent, config, name)
                self.device = self.wallet_class.device
       -        self.handler = None
                self.client = None
       +        self.wallet_class.plugin = self
        
            def constructor(self, s):
                return self.wallet_class(s)
       t@@ -171,9 +145,10 @@ class TrezorCompatiblePlugin(BasePlugin):
        
                devices = self.HidTransport.enumerate()
                if not devices:
       -            self.give_error(_('Could not connect to your %s. Please '
       -                              'verify the cable is connected and that no '
       -                              'other app is using it.' % self.device))
       +            self.give_error(_('Could not connect to your %s.  Verify the '
       +                              'cable is connected and that no other app is '
       +                              'using it.\nContinuing in watching-only mode.'
       +                              % self.device))
        
                transport = self.HidTransport(devices[0])
                client = self.client_class(transport, self)
       t@@ -183,7 +158,10 @@ class TrezorCompatiblePlugin(BasePlugin):
                                    % (self.device, self.firmware_URL))
                return client
        
       -    def get_client(self):
       +    def get_handler(self, wallet):
       +        return self.get_client(wallet).handler
       +
       +    def get_client(self, wallet=None):
                if not self.client or self.client.bad:
                    self.client = self.create_client()
        
       t@@ -192,6 +170,28 @@ class TrezorCompatiblePlugin(BasePlugin):
            def atleast_version(self, major, minor=0, patch=0):
                return self.get_client().atleast_version(major, minor, patch)
        
       +    @staticmethod
       +    def normalize_passphrase(self, passphrase):
       +        return normalize('NFKD', unicode(passphrase or ''))
       +
       +    def on_restore_wallet(self, wallet, wizard):
       +        assert isinstance(wallet, self.wallet_class)
       +
       +        msg = _("Enter the seed for your %s wallet:" % self.device)
       +        seed = wizard.request_seed(msg, is_valid = self.is_valid_seed)
       +
       +        # Restored wallets are not hardware wallets
       +        wallet_class = self.wallet_class.restore_wallet_class
       +        wallet.storage.put('wallet_type', wallet_class.wallet_type)
       +        wallet = wallet_class(wallet.storage)
       +
       +        passphrase = wizard.request_passphrase(self.device, restore=True)
       +        password = wizard.request_password()
       +        wallet.add_seed(seed, password)
       +        wallet.add_cosigner_seed(seed, 'x/', password, passphrase)
       +        wallet.create_main_account(password)
       +        return wallet
       +
            @hook
            def close_wallet(self, wallet):
                if self.client:
       t@@ -211,7 +211,7 @@ class TrezorCompatiblePlugin(BasePlugin):
                except Exception as e:
                    self.give_error(e)
                finally:
       -            self.handler.stop()
       +            self.get_handler(wallet).stop()
                raw = signed_tx.encode('hex')
                tx.update_signatures(raw)
        
       t@@ -228,7 +228,7 @@ class TrezorCompatiblePlugin(BasePlugin):
                except Exception as e:
                    self.give_error(e)
                finally:
       -            self.handler.stop()
       +            self.get_handler(wallet).stop()
        
            def tx_inputs(self, tx, for_sig=False):
                client = self.get_client()
   DIR diff --git a/plugins/trezor/qt.py b/plugins/trezor/qt.py
       t@@ -1,7 +1,10 @@
        from plugins.trezor.qt_generic import QtPlugin
       -from trezorlib.qt.pinmatrix import PinMatrixWidget
        
        
        class Plugin(QtPlugin):
       -    pin_matrix_widget_class = PinMatrixWidget
            icon_file = ":icons/trezor.png"
       +
       +    @staticmethod
       +    def pin_matrix_widget_class():
       +        from trezorlib.qt.pinmatrix import PinMatrixWidget
       +        return PinMatrixWidget
   DIR diff --git a/plugins/trezor/qt_generic.py b/plugins/trezor/qt_generic.py
       t@@ -1,11 +1,10 @@
        from functools import partial
       -from unicodedata import normalize
        import threading
        
        from PyQt4.Qt import QGridLayout, QInputDialog, QPushButton
        from PyQt4.Qt import QVBoxLayout, QLabel, SIGNAL
        from trezor import TrezorPlugin
       -from electrum_gui.qt.main_window import ElectrumWindow, StatusBarButton
       +from electrum_gui.qt.main_window import StatusBarButton
        from electrum_gui.qt.password_dialog import PasswordDialog
        from electrum_gui.qt.util import *
        
       t@@ -66,11 +65,12 @@ class QtHandler(PrintError):
        
            def passphrase_dialog(self, msg):
                self.dialog_stop()
       -        d = PasswordDialog(self.windows[-1], None, None, msg, False)
       -        confirmed, p, phrase = d.run()
       +        d = PasswordDialog(self.windows[-1], None, msg,
       +                           PasswordDialog.PW_PASSHPRASE)
       +        confirmed, p, passphrase = d.run()
                if confirmed:
       -            phrase = normalize('NFKD', unicode(phrase or ''))
       -        self.passphrase = phrase
       +            passphrase = TrezorPlugin.normalize_passphrase(passphrase)
       +        self.passphrase = passphrase
                self.done.set()
        
            def message_dialog(self, msg, cancel_callback):
       t@@ -104,52 +104,30 @@ class QtPlugin(TrezorPlugin):
            #   pin_matrix_widget_class
        
            def create_handler(self, window):
       -        return QtHandler(window, self.pin_matrix_widget_class, self.device)
       +        return QtHandler(window, self.pin_matrix_widget_class(), self.device)
        
            @hook
            def load_wallet(self, wallet, window):
                if type(wallet) != self.wallet_class:
                    return
       -        self.print_error("load_wallet")
       -        wallet.plugin = self
       -        self.button = StatusBarButton(QIcon(self.icon_file), self.device,
       -                                      partial(self.settings_dialog, window))
       -        if type(window) is ElectrumWindow:
       +        try:
       +            client = self.get_client(wallet)
       +            client.handler = self.create_handler(window)
       +            client.check_proper_device(wallet)
       +            self.button = StatusBarButton(QIcon(self.icon_file), self.device,
       +                                          partial(self.settings_dialog, window))
                    window.statusBar().addPermanentWidget(self.button)
       -        if self.handler is None:
       -            self.handler = self.create_handler(window)
       -        msg = wallet.sanity_check()
       -        if msg:
       -            window.show_error(msg)
       +        except Exception as e:
       +            window.show_error(str(e))
        
       -    @hook
       -    def installwizard_load_wallet(self, wallet, window):
       -        self.load_wallet(wallet, window)
       +    def on_create_wallet(self, wallet, wizard):
       +        client = self.get_client(wallet)
       +        client.handler = self.create_handler(wizard)
       +        wallet.create_main_account(None)
        
       -    @hook
       -    def installwizard_restore(self, wizard, storage):
       -        if storage.get('wallet_type') != self.wallet_class.wallet_type:
       -            return
       -        seed = wizard.enter_seed_dialog(_("Enter your %s seed") % self.device,
       -                                        None, func=lambda x: True)
       -        if not seed:
       -            return
       -        # Restored wallets are not hardware wallets
       -        wallet_class = self.wallet_class.restore_wallet_class
       -        storage.put('wallet_type', wallet_class.wallet_type)
       -        wallet = wallet_class(storage)
       -
       -        handler = self.create_handler(wizard)
       -        msg = "\n".join([_("Please enter your %s passphrase.") % self.device,
       -                         _("Press OK if you do not use one.")])
       -        passphrase = handler.get_passphrase(msg)
       -        if passphrase is None:
       -            return
       -        password = wizard.password_dialog()
       -        wallet.add_seed(seed, password)
       -        wallet.add_cosigner_seed(seed, 'x/', password, passphrase)
       -        wallet.create_main_account(password)
       -        return wallet
       +    @staticmethod
       +    def is_valid_seed(seed):
       +        return True
        
            @hook
            def receive_menu(self, menu, addrs, wallet):
       t@@ -162,6 +140,8 @@ class QtPlugin(TrezorPlugin):
        
            def settings_dialog(self, window):
        
       +        handler = self.get_client(window.wallet).handler
       +
                def rename():
                    title = _("Set Device Label")
                    msg = _("Enter new label:")
       t@@ -172,7 +152,7 @@ class QtPlugin(TrezorPlugin):
                    try:
                        client.change_label(new_label)
                    finally:
       -                self.handler.stop()
       +                handler.stop()
                    device_label.setText(new_label)
        
                def update_pin_info():
       t@@ -186,7 +166,7 @@ class QtPlugin(TrezorPlugin):
                    try:
                        client.set_pin(remove=remove)
                    finally:
       -                self.handler.stop()
       +                handler.stop()
                    update_pin_info()
        
                client = self.get_client()
       t@@ -234,8 +214,8 @@ class QtPlugin(TrezorPlugin):
                vbox.addLayout(Buttons(CloseButton(dialog)))
        
                dialog.setLayout(vbox)
       -        self.handler.push_window(dialog)
       +        handler.push_window(dialog)
                try:
                    dialog.exec_()
                finally:
       -            self.handler.pop_window()
       +            handler.pop_window()
   DIR diff --git a/plugins/trezor/trezor.py b/plugins/trezor/trezor.py
       t@@ -1,12 +1,6 @@
        from plugins.trezor.client import trezor_client_class
        from plugins.trezor.plugin import TrezorCompatiblePlugin, TrezorCompatibleWallet
        
       -try:
       -    from trezorlib.client import proto, BaseClient, ProtocolMixin
       -    TREZOR = True
       -except ImportError:
       -    TREZOR = False
       -
        
        class TrezorWallet(TrezorCompatibleWallet):
            wallet_type = 'trezor'
       t@@ -14,12 +8,16 @@ class TrezorWallet(TrezorCompatibleWallet):
        
        
        class TrezorPlugin(TrezorCompatiblePlugin):
       -    client_class = trezor_client_class(ProtocolMixin, BaseClient, proto)
            firmware_URL = 'https://www.mytrezor.com'
            libraries_URL = 'https://github.com/trezor/python-trezor'
       -    libraries_available = TREZOR
            minimum_firmware = (1, 2, 1)
            wallet_class = TrezorWallet
       -    import trezorlib.ckd_public as ckd_public
       -    from trezorlib.client import types
       -    from trezorlib.transport_hid import HidTransport
       +    try:
       +        from trezorlib.client import proto, BaseClient, ProtocolMixin
       +        client_class = trezor_client_class(ProtocolMixin, BaseClient, proto)
       +        import trezorlib.ckd_public as ckd_public
       +        from trezorlib.client import types
       +        from trezorlib.transport_hid import HidTransport
       +        libraries_available = True
       +    except ImportError:
       +        libraries_available = False
   DIR diff --git a/plugins/trustedcoin/qt.py b/plugins/trustedcoin/qt.py
       t@@ -18,6 +18,7 @@
        
        from functools import partial
        from threading import Thread
       +import re
        
        from PyQt4.QtGui import *
        from PyQt4.QtCore import *
       t@@ -28,8 +29,9 @@ from electrum_gui.qt.amountedit import AmountEdit
        from electrum_gui.qt.main_window import StatusBarButton
        from electrum.i18n import _
        from electrum.plugins import hook
       +from electrum import wizard
        
       -from trustedcoin import TrustedCoinPlugin, Wallet_2fa
       +from trustedcoin import TrustedCoinPlugin, Wallet_2fa, DISCLAIMER, server
        
        def need_server(wallet, tx):
            from electrum.account import BIP32_Account
       t@@ -90,6 +92,11 @@ class Plugin(TrustedCoinPlugin):
                return WaitingDialog(window, 'Getting billing information...', task,
                                     on_finished)
        
       +    def show_disclaimer(self, wallet, window):
       +        icon = QPixmap(':icons/trustedcoin.png')
       +        window.confirm('\n\n'.join(DISCLAIMER), icon=icon)
       +        self.set_enabled(wallet, True)
       +
            @hook
            def abort_send(self, window):
                wallet = window.wallet
       t@@ -225,10 +232,9 @@ class Plugin(TrustedCoinPlugin):
                email_e.setFocus(True)
        
                if not window.exec_():
       -            return
       +            raise wizard.UserCancelled
        
       -        email = str(email_e.text())
       -        return email
       +        return str(email_e.text())
        
        
            def setup_google_auth(self, window, _id, otp_secret):
   DIR diff --git a/plugins/trustedcoin/trustedcoin.py b/plugins/trustedcoin/trustedcoin.py
       t@@ -43,6 +43,24 @@ billing_xpub = "xpub6DTBdtBB8qUmH5c77v8qVGVoYk7WjJNpGvutqjLasNG1mbux6KsojaLrYf2s
        
        SEED_PREFIX = version.SEED_PREFIX_2FA
        
       +DISCLAIMER = [
       +    _("Two-factor authentication is a service provided by TrustedCoin.  "
       +      "It uses a multi-signature wallet, where you own 2 of 3 keys.  "
       +      "The third key is stored on a remote server that signs transactions on "
       +      "your behalf.  To use this service, you will need a smartphone with "
       +      "Google Authenticator installed."),
       +    _("A small fee will be charged on each transaction that uses the "
       +      "remote server.  You may check and modify your billing preferences "
       +      "once the installation is complete."),
       +    _("Note that your coins are not locked in this service.  You may withdraw "
       +      "your funds at any time and at no cost, without the remote server, by "
       +      "using the 'restore wallet' option with your wallet seed."),
       +    _("The next step will generate the seed of your wallet.  This seed will "
       +      "NOT be saved in your computer, and it must be stored on paper.  "
       +      "To be safe from malware, you may want to do this on an offline "
       +      "computer, and move your wallet later to an online computer."),
       +]
       +RESTORE_MSG = _("Enter the seed for your 2-factor wallet:")
        
        class TrustedCoinException(Exception):
            def __init__(self, message, status_code=0):
       t@@ -274,11 +292,15 @@ class TrustedCoinPlugin(BasePlugin):
        
            def __init__(self, parent, config, name):
                BasePlugin.__init__(self, parent, config, name)
       -        self.seed_func = lambda x: bitcoin.is_new_seed(x, SEED_PREFIX)
       +        Wallet_2fa.plugin = self
        
            def constructor(self, s):
                return Wallet_2fa(s)
        
       +    @staticmethod
       +    def is_valid_seed(seed):
       +        return bitcoin.is_new_seed(seed, SEED_PREFIX)
       +
            def is_available(self):
                return True
        
       t@@ -298,13 +320,9 @@ class TrustedCoinPlugin(BasePlugin):
        
            def create_extended_seed(self, wallet, window):
                seed = wallet.make_seed()
       -        if not window.show_seed(seed, None):
       -            return
       -
       -        if not window.verify_seed(seed, None, self.seed_func):
       -            return
       +        window.show_and_verify_seed(seed, is_valid=self.is_valid_seed)
        
       -        password = window.password_dialog()
       +        password = window.request_password()
                wallet.storage.put('seed_version', wallet.seed_version)
                wallet.storage.put('use_encryption', password is not None)
        
       t@@ -313,57 +331,29 @@ class TrustedCoinPlugin(BasePlugin):
                wallet.add_cosigner_seed(' '.join(words[0:n]), 'x1/', password)
                wallet.add_cosigner_xpub(' '.join(words[n:]), 'x2/')
        
       -        msg = [
       -            _('Your wallet file is:') + " %s"%os.path.abspath(wallet.storage.path),
       -            _('You need to be online in order to complete the creation of your wallet.'),
       -            _('If you generated your seed on an offline computer, click on "%s" to close this window, move your wallet file to an online computer and reopen it with Electrum.') % _('Close'),
       -            _('If you are online, click on "%s" to continue.') % _('Next')
       -        ]
       -        return window.question('\n\n'.join(msg), no_label=_('Close'), yes_label=_('Next'))
       +        wallet.storage.write()
        
       -
       -    def show_disclaimer(self, wallet, window):
                msg = [
       -            _("Two-factor authentication is a service provided by TrustedCoin.") + ' ',
       -            _("It uses a multi-signature wallet, where you own 2 of 3 keys.") + ' ',
       -            _("The third key is stored on a remote server that signs transactions on your behalf.") + ' ',
       -            _("To use this service, you will need a smartphone with Google Authenticator.") + '\n\n',
       -
       -            _("A small fee will be charged on each transaction that uses the remote server.") + ' ',
       -            _("You may check and modify your billing preferences once the installation is complete.") + '\n\n',
       -
       -            _("Note that your coins are not locked in this service.") + ' ',
       -            _("You may withdraw your funds at any time and at no cost, without the remote server, by using the 'restore wallet' option with your wallet seed.") + '\n\n',
       -
       -            _('The next step will generate the seed of your wallet.') + ' ',
       -            _('This seed will NOT be saved in your computer, and it must be stored on paper.') + ' ',
       -            _('To be safe from malware, you may want to do this on an offline computer, and move your wallet later to an online computer.')
       +            _("Your wallet file is: %s.")%os.path.abspath(wallet.storage.path),
       +            _("You need to be online in order to complete the creation of "
       +              "your wallet.  If you generated your seed on an offline "
       +              'computer, click on "%s" to close this window, move your '
       +              "wallet file to an online computer, and reopen it with "
       +              "Electrum.") % _('Cancel'),
       +            _('If you are online, click on "%s" to continue.') % _('Next')
                ]
       -        icon = QPixmap(':icons/trustedcoin.png')
       -        if not window.question(''.join(msg), icon=icon):
       -            return False
       -        self.set_enabled(wallet, True)
       -        return True
       +        msg = '\n\n'.join(msg)
       +        window.confirm(msg)
        
            @hook
            def do_clear(self, window):
                window.wallet.is_billing = False
        
       -    @hook
       -    def get_wizard_action(self, window, wallet, action):
       -        if hasattr(self, action):
       -            return getattr(self, action)
       +    def on_restore_wallet(self, wallet, wizard):
       +        assert isinstance(wallet, Wallet_2fa)
        
       -    @hook
       -    def installwizard_restore(self, window, storage):
       -        if storage.get('wallet_type') != '2fa':
       -            return
       -
       -        seed = window.enter_seed_dialog("Enter your seed", None, func=self.seed_func)
       -        if not seed:
       -            return
       -        wallet = Wallet_2fa(storage)
       -        password = window.password_dialog()
       +        seed = wizard.request_seed(RESTORE_MSG, is_valid=self.is_valid_seed)
       +        password = wizard.request_password()
        
                wallet.add_seed(seed, password)
                words = seed.split()
       t@@ -373,20 +363,10 @@ class TrustedCoinPlugin(BasePlugin):
        
                restore_third_key(wallet)
                wallet.create_main_account(password)
       -        # disable plugin
       -        self.set_enabled(wallet, False)
                return wallet
        
       -
            def create_remote_key(self, wallet, window):
       -        if wallet.storage.get('wallet_type') != '2fa':
       -            raise
       -            return
       -
                email = self.accept_terms_of_use(window)
       -        if not email:
       -            return
       -
                xpub_hot = wallet.master_public_keys["x1/"]
                xpub_cold = wallet.master_public_keys["x2/"]
        
       t@@ -422,8 +402,5 @@ class TrustedCoinPlugin(BasePlugin):
                        window.show_message(str(e))
                        return
        
       -        if not self.setup_google_auth(window, short_id, otp_secret):
       -            return
       -
       -        wallet.add_master_public_key('x3/', xpub3)
       -        return True
       +        if self.setup_google_auth(window, short_id, otp_secret):
       +            wallet.add_master_public_key('x3/', xpub3)