From a336379aa56a52d887516ae1098d97229a3ef8f8 Mon Sep 17 00:00:00 2001 From: m0mchil Date: Thu, 10 Jul 2014 22:44:28 +0300 Subject: [PATCH 01/20] trezor plugin --- gui/qt/main_window.py | 2 +- gui/qt/password_dialog.py | 6 +- lib/transaction.py | 2 +- plugins/trezor.py | 322 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 327 insertions(+), 5 deletions(-) create mode 100644 plugins/trezor.py diff --git a/gui/qt/main_window.py b/gui/qt/main_window.py index b5276620..bfdb6473 100644 --- a/gui/qt/main_window.py +++ b/gui/qt/main_window.py @@ -1058,7 +1058,7 @@ class ElectrumWindow(QMainWindow): return # call hook to see if plugin needs gui interaction - run_hook('send_tx', tx) + run_hook('send_tx', tx, self.wallet) # sign the tx def sign_thread(): diff --git a/gui/qt/password_dialog.py b/gui/qt/password_dialog.py index d56f09ef..0a713d4a 100644 --- a/gui/qt/password_dialog.py +++ b/gui/qt/password_dialog.py @@ -23,7 +23,7 @@ from util import * -def make_password_dialog(self, wallet, msg): +def make_password_dialog(self, wallet, msg, new_pass=True): self.pw = QLineEdit() self.pw.setEchoMode(2) @@ -58,8 +58,8 @@ def make_password_dialog(self, wallet, msg): if wallet and wallet.use_encryption: grid.addWidget(QLabel(_('Password')), 0, 0) grid.addWidget(self.pw, 0, 1) - - grid.addWidget(QLabel(_('New Password')), 1, 0) + + grid.addWidget(QLabel(_('New Password' if new_pass else 'Password')), 1, 0) grid.addWidget(self.new_pw, 1, 1) grid.addWidget(QLabel(_('Confirm Password')), 2, 0) diff --git a/lib/transaction.py b/lib/transaction.py index f15aa237..99e96ff9 100644 --- a/lib/transaction.py +++ b/lib/transaction.py @@ -439,7 +439,7 @@ def parse_input(vds): d = {} prevout_hash = hash_encode(vds.read_bytes(32)) prevout_n = vds.read_uint32() - scriptSig = vds.read_bytes(vds.read_compact_size()) + d['scriptSig'] = scriptSig = vds.read_bytes(vds.read_compact_size()) sequence = vds.read_uint32() if prevout_hash == '00'*32: d['is_coinbase'] = True diff --git a/plugins/trezor.py b/plugins/trezor.py new file mode 100644 index 00000000..b9c99932 --- /dev/null +++ b/plugins/trezor.py @@ -0,0 +1,322 @@ +from PyQt4.Qt import QMessageBox, QDialog, QVBoxLayout, QLabel +from binascii import unhexlify +from struct import pack +from sys import stderr + +from gui.qt.password_dialog import make_password_dialog, run_password_dialog +from gui.qt.util import ok_cancel_buttons +from lib.account import BIP32_Account +from lib.bitcoin import EncodeBase58Check +from lib.i18n import _ +from lib.plugins import BasePlugin +from lib.transaction import deserialize +from lib.wallet import NewWallet + + +try: + import cmdtr + from trezorlib.client import types + from trezorlib.client import proto, BaseClient, ProtocolMixin + from trezorlib.pinmatrix import PinMatrixWidget + from trezorlib.transport import ConnectionError + TREZOR = True +except: TREZOR = False + +def log(msg): + stderr.write("%s\n" % msg) + stderr.flush() + + +class Plugin(BasePlugin): + + def fullname(self): return 'Trezor Wallet' + + def description(self): return 'Provides support for Trezor hardware wallet\n\nRequires github.com/trezor/python-trezor' + + def __init__(self, gui, name): + BasePlugin.__init__(self, gui, name) + self._is_available = self._init() + + def _init(self): + return TREZOR + + def is_available(self): + return self._is_available + + def enable(self): + return BasePlugin.enable(self) + + def add_wallet_types(self, wallet_types): + wallet_types.append(('trezor', _("Trezor wallet"), TrezorWallet)) + + def send_tx(self, tx, wallet): + try: + wallet.sign_transaction(tx, None, None) + except Exception as e: + tx.error = str(e) + + +class TrezorWallet(NewWallet): + + def __init__(self, storage): + self.transport = None + self.client = None + + NewWallet.__init__(self, storage) + + self.seed = 'trezor' + + self.storage.put('gap_limit', 20, False) #obey BIP44 gap limit of 20 + + self.use_encryption = False + + self.storage.put('seed', self.seed, False) + self.storage.put('seed_version', self.seed_version, False) + self.storage.put('use_encryption', self.use_encryption, False) + + self.device_checked = False + + def get_action(self): + if not self.accounts: + return 'create_accounts' + + def can_create_accounts(self): + return True + + def is_watching_only(self): + return False + + def default_account(self): + return "44'/0'/0'" + + def get_client(self): + if not TREZOR: + raise Exception('please install github.com/trezor/python-trezor') + + if not self.client or self.client.bad: + self.transport = cmdtr.get_transport('usb', '') + self.client = QtGuiTrezorClient(self.transport) + self.client.set_tx_api(self) + #self.client.clear_session()# TODO Doesn't work with firmware 1.1, returns proto.Failure + self.client.bad = False + self.device_checked = False + self.proper_device = False + return self.client + + def account_id(self, i): + return "44'/0'/%d'"%i + + def address_id(self, address): + account_id, (change, address_index) = self.get_address_index(address) + return "%s/%d/%d" % (account_id, change, address_index) + + def create_accounts(self, password): + self.create_account('Main account', '') #name, empty password + + def make_account(self, account_id, password): + xpub = self.get_public_key(account_id) + self.add_master_public_key(account_id, xpub) + account = BIP32_Account({'xpub':xpub}) + return account + + def get_public_key(self, bip32_path): + address_n = self.get_client().expand_path(bip32_path) + res = self.get_client().get_public_node(address_n) + xpub = "0488B21E".decode('hex') + chr(res.depth) + self.i4b(res.fingerprint) + self.i4b(res.child_num) + res.chain_code + res.public_key + return EncodeBase58Check(xpub) + + def get_master_public_key(self): + if not self.mpk: + self.mpk = self.get_public_key("44'/0'") + return self.mpk + + def i4b(self, x): + return pack('I', x) + + def add_keypairs(self, tx, keypairs, password): + #do nothing - no priv keys available + pass + + def sign_transaction(self, tx, keypairs, password): + if tx.error or tx.is_complete(): + return + + if not self.check_proper_device(): + raise Exception('Wrong device or password') + + inputs = self.tx_inputs(tx) + outputs = self.tx_outputs(tx) + signed_tx = self.get_client().sign_tx('Bitcoin', inputs, outputs)[1] + raw = signed_tx.encode('hex') + tx.update(raw) + + def tx_inputs(self, tx): + inputs = [] + + for txinput in tx.inputs: + txinputtype = types.TxInputType() + address = txinput['address'] + try: + address_path = self.address_id(address) + address_n = self.get_client().expand_path(address_path) + txinputtype.address_n.extend(address_n) + except: pass + + if ('is_coinbase' in txinput and txinput['is_coinbase']): + prev_hash = "\0"*32 + prev_index = 0xffffffff # signed int -1 + else: + prev_hash = unhexlify(txinput['prevout_hash']) + prev_index = txinput['prevout_n'] + + txinputtype.prev_hash = prev_hash + txinputtype.prev_index = prev_index + + if 'scriptSig' in txinput: + script_sig = txinput['scriptSig'] + txinputtype.script_sig = script_sig + + if 'sequence' in txinput: + sequence = txinput['sequence'] + txinputtype.sequence = sequence + + inputs.append(txinputtype) + #TODO P2SH + return inputs + + def tx_outputs(self, tx): + outputs = [] + + for type, address, amount in tx.outputs: + txoutputtype = types.TxOutputType() + + if self.is_change(address): + address_path = self.address_id(address) + address_n = self.get_client().expand_path(address_path) + txoutputtype.address_n.extend(address_n) + else: + txoutputtype.address = address + + txoutputtype.amount = amount + + txoutputtype.script_type = types.PAYTOADDRESS + #TODO + #if output['is_p2sh']: + # txoutputtype.script_type = types.PAYTOSCRIPTHASH + + outputs.append(txoutputtype) + return outputs + + def electrum_tx_to_txtype(self, tx): + t = types.TransactionType() + d = deserialize(tx.raw) + t.version = d['version'] + t.lock_time = d['lockTime'] + + inputs = self.tx_inputs(tx) + t.inputs.extend(inputs) + + for vout in d['outputs']: + o = t.bin_outputs.add() + o.amount = vout['value'] + o.script_pubkey = vout['scriptPubKey'].decode('hex') + + return t + + def get_tx(self, tx_hash): + tx = self.transactions[tx_hash] + return self.electrum_tx_to_txtype(tx) + + def check_proper_device(self): + self.get_client().ping('t') + if not self.device_checked: + address = self.addresses(False, 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.device_checked = True + + if device_address != address: + self.proper_device = False + else: + self.proper_device = True + + return self.proper_device + + +class TrezorQtGuiMixin(object): + + def __init__(self, *args, **kwargs): + super(TrezorQtGuiMixin, self).__init__(*args, **kwargs) + + def callback_ButtonRequest(self, msg): + i = QMessageBox.question(None, _('Trezor'), _("Please check request on Trezor's screen"), _('OK'), _('Cancel')) + if i == 0: + return proto.ButtonAck() + return proto.Cancel() + + def callback_PinMatrixRequest(self, msg): + if msg.type == 1: + desc = 'old PIN' + elif msg.type == 2: + desc = 'new PIN' + elif msg.type == 3: + desc = 'new PIN again' + else: + desc = 'PIN' + + pin = self.pin_dialog(msg="Please enter Trezor %s" % desc) + if not pin: + return proto.Cancel() + return proto.PinMatrixAck(pin=pin) + + def callback_PassphraseRequest(self, msg): + confirmed, p, passphrase = self.password_dialog() + if not confirmed: + QMessageBox.critical(None, _('Error'), _("Password request canceled"), _('OK')) + return proto.Cancel() + if passphrase is None: + passphrase='' # Even blank string is valid Trezor passphrase + return proto.PassphraseAck(passphrase=passphrase) + + def callback_WordRequest(self, msg): + #TODO + log("Enter one word of mnemonic: ") + word = raw_input() + return proto.WordAck(word=word) + + def password_dialog(self, msg=None): + if not msg: + msg = _("Please enter your Trezor password") + else: + msg = _(msg) + d = QDialog() + d.setModal(1) + d.setLayout( make_password_dialog(d, None, msg, False) ) + return run_password_dialog(d, None, None) + + def pin_dialog(self, msg): + d = QDialog(None) + d.setModal(1) + d.setWindowTitle(_("Enter PIN")) + matrix = PinMatrixWidget() + + vbox = QVBoxLayout() + vbox.addWidget(QLabel(msg)) + vbox.addWidget(matrix) + vbox.addLayout(ok_cancel_buttons(d)) + d.setLayout(vbox) + + if not d.exec_(): return + return str(matrix.get_value()) + +if TREZOR: + class QtGuiTrezorClient(ProtocolMixin, TrezorQtGuiMixin, BaseClient): + def call_raw(self, msg): + try: + resp = BaseClient.call_raw(self, msg) + except ConnectionError: + self.bad = True + raise + + return resp From 26b13f4414e309b8fae2728edd7c7e52a7ecd062 Mon Sep 17 00:00:00 2001 From: m0mchil Date: Fri, 11 Jul 2014 09:05:03 +0300 Subject: [PATCH 02/20] proper i18n --- gui/qt/password_dialog.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/qt/password_dialog.py b/gui/qt/password_dialog.py index 0a713d4a..1c2d1318 100644 --- a/gui/qt/password_dialog.py +++ b/gui/qt/password_dialog.py @@ -59,7 +59,7 @@ def make_password_dialog(self, wallet, msg, new_pass=True): grid.addWidget(QLabel(_('Password')), 0, 0) grid.addWidget(self.pw, 0, 1) - grid.addWidget(QLabel(_('New Password' if new_pass else 'Password')), 1, 0) + grid.addWidget(QLabel(_('New Password') if new_pass else _('Password')), 1, 0) grid.addWidget(self.new_pw, 1, 1) grid.addWidget(QLabel(_('Confirm Password')), 2, 0) From ec295d1fbe33678186f39856f83109ba5e75b336 Mon Sep 17 00:00:00 2001 From: m0mchil Date: Fri, 11 Jul 2014 17:32:17 +0300 Subject: [PATCH 03/20] remove redundant i18n --- plugins/trezor.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/plugins/trezor.py b/plugins/trezor.py index b9c99932..46e6c1fc 100644 --- a/plugins/trezor.py +++ b/plugins/trezor.py @@ -288,8 +288,7 @@ class TrezorQtGuiMixin(object): def password_dialog(self, msg=None): if not msg: msg = _("Please enter your Trezor password") - else: - msg = _(msg) + d = QDialog() d.setModal(1) d.setLayout( make_password_dialog(d, None, msg, False) ) From 8a7f81a9de711e46c1156e587d24857d2e0f987c Mon Sep 17 00:00:00 2001 From: m0mchil Date: Fri, 11 Jul 2014 22:53:28 +0300 Subject: [PATCH 04/20] support for restore --- plugins/trezor.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/plugins/trezor.py b/plugins/trezor.py index 46e6c1fc..b0504be4 100644 --- a/plugins/trezor.py +++ b/plugins/trezor.py @@ -49,6 +49,11 @@ class Plugin(BasePlugin): def add_wallet_types(self, wallet_types): wallet_types.append(('trezor', _("Trezor wallet"), TrezorWallet)) + def installwizard_restore(self, wizard, storage): + wallet = TrezorWallet(storage) + wallet.create_accounts(None) + return wallet + def send_tx(self, tx, wallet): try: wallet.sign_transaction(tx, None, None) From e4a6a2962ee03e42ea80498521714aa0a5f64a59 Mon Sep 17 00:00:00 2001 From: m0mchil Date: Sat, 12 Jul 2014 00:28:26 +0300 Subject: [PATCH 05/20] enable trezor plugin if about to create/restore wallet --- plugins/trezor.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/plugins/trezor.py b/plugins/trezor.py index b0504be4..0798cb8e 100644 --- a/plugins/trezor.py +++ b/plugins/trezor.py @@ -36,6 +36,7 @@ class Plugin(BasePlugin): def __init__(self, gui, name): BasePlugin.__init__(self, gui, name) self._is_available = self._init() + self.wallet = None def _init(self): return TREZOR @@ -43,9 +44,24 @@ class Plugin(BasePlugin): def is_available(self): return self._is_available + def set_enabled(self, enabled): + self.wallet.storage.put('use_' + self.name, enabled) + + def is_enabled(self): + if not self.is_available(): + return False + + if not self.wallet: + return True + + return self.wallet.storage.get('use_' + self.name) is True + def enable(self): return BasePlugin.enable(self) + def load_wallet(self, wallet): + self.wallet = wallet + def add_wallet_types(self, wallet_types): wallet_types.append(('trezor', _("Trezor wallet"), TrezorWallet)) From 294de5504f7d758327a29f025d2a6a459a6a6acf Mon Sep 17 00:00:00 2001 From: m0mchil Date: Sat, 12 Jul 2014 20:17:48 +0300 Subject: [PATCH 06/20] restore values to allow fee check --- plugins/trezor.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/plugins/trezor.py b/plugins/trezor.py index 0798cb8e..8b850e2d 100644 --- a/plugins/trezor.py +++ b/plugins/trezor.py @@ -168,8 +168,11 @@ class TrezorWallet(NewWallet): inputs = self.tx_inputs(tx) outputs = self.tx_outputs(tx) signed_tx = self.get_client().sign_tx('Bitcoin', inputs, outputs)[1] + values = [i['value'] for i in tx.inputs] raw = signed_tx.encode('hex') tx.update(raw) + for i, txinput in enumerate(tx.inputs): + txinput['value'] = values[i] def tx_inputs(self, tx): inputs = [] From f518be434642244cbf2cb0541ffd4be9039f3c6a Mon Sep 17 00:00:00 2001 From: m0mchil Date: Sat, 12 Jul 2014 20:19:04 +0300 Subject: [PATCH 07/20] enable plugin for trezor wallet --- plugins/trezor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/trezor.py b/plugins/trezor.py index 8b850e2d..e9da4c2b 100644 --- a/plugins/trezor.py +++ b/plugins/trezor.py @@ -51,7 +51,7 @@ class Plugin(BasePlugin): if not self.is_available(): return False - if not self.wallet: + if not self.wallet or self.wallet.storage.get('wallet_type') == 'trezor': return True return self.wallet.storage.get('use_' + self.name) is True From 9f47762c12decec49688fcdb658586ae136db0bc Mon Sep 17 00:00:00 2001 From: slush0 Date: Fri, 18 Jul 2014 15:40:31 +0200 Subject: [PATCH 08/20] Fixes dependency to pinmatrix --- plugins/trezor.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/plugins/trezor.py b/plugins/trezor.py index e9da4c2b..5b305e34 100644 --- a/plugins/trezor.py +++ b/plugins/trezor.py @@ -17,10 +17,11 @@ try: import cmdtr from trezorlib.client import types from trezorlib.client import proto, BaseClient, ProtocolMixin - from trezorlib.pinmatrix import PinMatrixWidget + from trezorlib.qt.pinmatrix import PinMatrixWidget from trezorlib.transport import ConnectionError TREZOR = True -except: TREZOR = False +except ImportError: + TREZOR = False def log(msg): stderr.write("%s\n" % msg) From 801bcd69e85638742c67ad8e14a35d74e54da4f1 Mon Sep 17 00:00:00 2001 From: slush0 Date: Fri, 18 Jul 2014 15:47:09 +0200 Subject: [PATCH 09/20] Fix get_master_public_key, Label plugin now works --- plugins/trezor.py | 1 + 1 file changed, 1 insertion(+) diff --git a/plugins/trezor.py b/plugins/trezor.py index 5b305e34..523f8507 100644 --- a/plugins/trezor.py +++ b/plugins/trezor.py @@ -83,6 +83,7 @@ class TrezorWallet(NewWallet): def __init__(self, storage): self.transport = None self.client = None + self.mpk = None NewWallet.__init__(self, storage) From bb78873e241a6abc148c1e74691bce0e74bcbecb Mon Sep 17 00:00:00 2001 From: Pavol Rusnak Date: Mon, 21 Jul 2014 19:41:43 +0200 Subject: [PATCH 10/20] don't use internal cmdtr module in trezor plugin --- plugins/trezor.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/plugins/trezor.py b/plugins/trezor.py index 523f8507..7f9823e8 100644 --- a/plugins/trezor.py +++ b/plugins/trezor.py @@ -14,11 +14,11 @@ from lib.wallet import NewWallet try: - import cmdtr from trezorlib.client import types from trezorlib.client import proto, BaseClient, ProtocolMixin from trezorlib.qt.pinmatrix import PinMatrixWidget from trezorlib.transport import ConnectionError + from trezorlib.transport_hid import HidTransport TREZOR = True except ImportError: TREZOR = False @@ -117,7 +117,11 @@ class TrezorWallet(NewWallet): raise Exception('please install github.com/trezor/python-trezor') if not self.client or self.client.bad: - self.transport = cmdtr.get_transport('usb', '') + try: + d = HidTransport.enumerate()[0] + self.transport = HidTransport(d) + except: + raise Exception("Trezor not found") self.client = QtGuiTrezorClient(self.transport) self.client.set_tx_api(self) #self.client.clear_session()# TODO Doesn't work with firmware 1.1, returns proto.Failure From d5f08d657f5dda3d8f94e5cf1ac676db82a849cc Mon Sep 17 00:00:00 2001 From: m0mchil Date: Sun, 27 Jul 2014 14:57:23 +0300 Subject: [PATCH 11/20] passing wallet instance not needed anymore --- gui/qt/main_window.py | 2 +- plugins/trezor.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/gui/qt/main_window.py b/gui/qt/main_window.py index bfdb6473..b5276620 100644 --- a/gui/qt/main_window.py +++ b/gui/qt/main_window.py @@ -1058,7 +1058,7 @@ class ElectrumWindow(QMainWindow): return # call hook to see if plugin needs gui interaction - run_hook('send_tx', tx, self.wallet) + run_hook('send_tx', tx) # sign the tx def sign_thread(): diff --git a/plugins/trezor.py b/plugins/trezor.py index 7f9823e8..ecbdcbc0 100644 --- a/plugins/trezor.py +++ b/plugins/trezor.py @@ -71,9 +71,9 @@ class Plugin(BasePlugin): wallet.create_accounts(None) return wallet - def send_tx(self, tx, wallet): + def send_tx(self, tx): try: - wallet.sign_transaction(tx, None, None) + self.wallet.sign_transaction(tx, None, None) except Exception as e: tx.error = str(e) From ec833b43e97358536e4b95bfd13f09da27066e18 Mon Sep 17 00:00:00 2001 From: Michael Wozniak Date: Sat, 2 Aug 2014 14:52:28 -0400 Subject: [PATCH 12/20] update imports --- plugins/trezor.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/plugins/trezor.py b/plugins/trezor.py index ecbdcbc0..e98fae42 100644 --- a/plugins/trezor.py +++ b/plugins/trezor.py @@ -5,12 +5,12 @@ from sys import stderr from gui.qt.password_dialog import make_password_dialog, run_password_dialog from gui.qt.util import ok_cancel_buttons -from lib.account import BIP32_Account -from lib.bitcoin import EncodeBase58Check -from lib.i18n import _ -from lib.plugins import BasePlugin -from lib.transaction import deserialize -from lib.wallet import NewWallet +from electrum.account import BIP32_Account +from electrum.bitcoin import EncodeBase58Check +from electrum.i18n import _ +from electrum.plugins import BasePlugin +from electrum.transaction import deserialize +from electrum.wallet import NewWallet try: From 14f00609aabea2b8e805ccc28a9e3825c8c85e55 Mon Sep 17 00:00:00 2001 From: Michael Wozniak Date: Sat, 2 Aug 2014 20:09:29 -0400 Subject: [PATCH 13/20] update imports for gui --- plugins/trezor.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/trezor.py b/plugins/trezor.py index e98fae42..db78dc91 100644 --- a/plugins/trezor.py +++ b/plugins/trezor.py @@ -3,8 +3,8 @@ from binascii import unhexlify from struct import pack from sys import stderr -from gui.qt.password_dialog import make_password_dialog, run_password_dialog -from gui.qt.util import ok_cancel_buttons +from electrum_gui.qt.password_dialog import make_password_dialog, run_password_dialog +from electrum_gui.qt.util import ok_cancel_buttons from electrum.account import BIP32_Account from electrum.bitcoin import EncodeBase58Check from electrum.i18n import _ From 6206da00e06de133d2cad172d9c4dcc5a01911ef Mon Sep 17 00:00:00 2001 From: Michael Wozniak Date: Sat, 2 Aug 2014 23:18:02 -0400 Subject: [PATCH 14/20] update trezor plugin waiting dialog update waiting dialog so that ok/cancel doesn't need to be used on the GUI, only on the trezor device --- plugins/trezor.py | 49 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 44 insertions(+), 5 deletions(-) diff --git a/plugins/trezor.py b/plugins/trezor.py index db78dc91..fb777aaf 100644 --- a/plugins/trezor.py +++ b/plugins/trezor.py @@ -1,7 +1,8 @@ -from PyQt4.Qt import QMessageBox, QDialog, QVBoxLayout, QLabel +from PyQt4.Qt import QMessageBox, QDialog, QVBoxLayout, QLabel, QThread, SIGNAL, QObject from binascii import unhexlify from struct import pack from sys import stderr +from time import sleep from electrum_gui.qt.password_dialog import make_password_dialog, run_password_dialog from electrum_gui.qt.util import ok_cancel_buttons @@ -27,6 +28,8 @@ def log(msg): stderr.write("%s\n" % msg) stderr.flush() +gl_emitter = QObject() +window_open = False class Plugin(BasePlugin): @@ -174,6 +177,7 @@ class TrezorWallet(NewWallet): inputs = self.tx_inputs(tx) outputs = self.tx_outputs(tx) signed_tx = self.get_client().sign_tx('Bitcoin', inputs, outputs)[1] + gl_emitter.emit(SIGNAL('trezor_done')) values = [i['value'] for i in tx.inputs] raw = signed_tx.encode('hex') tx.update(raw) @@ -280,10 +284,16 @@ class TrezorQtGuiMixin(object): super(TrezorQtGuiMixin, self).__init__(*args, **kwargs) def callback_ButtonRequest(self, msg): - i = QMessageBox.question(None, _('Trezor'), _("Please check request on Trezor's screen"), _('OK'), _('Cancel')) - if i == 0: - return proto.ButtonAck() - return proto.Cancel() + if window_open: + gl_emitter.emit(SIGNAL('trezor_done')) + if msg.code == 3: + message = "Confirm transaction outputs on Trezor device to continue" + elif msg.code == 8: + message = "Confirm transaction fee on Trezor device to continue" + else: + message = "Check Trezor device to continue" + twd.start(message) + return proto.ButtonAck() def callback_PinMatrixRequest(self, msg): if msg.type == 1: @@ -339,6 +349,32 @@ class TrezorQtGuiMixin(object): if not d.exec_(): return return str(matrix.get_value()) +class TrezorWaitingDialog(QThread): + def __init__(self): + QThread.__init__(self) + + def start(self, message): + self.done = False + self.d = QDialog() + self.d.setModal(True) + self.d.setWindowTitle('Please Check Trezor Device') + l = QLabel(message) + vbox = QVBoxLayout(self.d) + vbox.addWidget(l) + self.d.show() + window_open = True + self.d.connect(gl_emitter, SIGNAL('trezor_done'), self.stop) + + def run(self): + while not self.done: + sleep(0.1) + + def stop(self): + self.d.hide() + window_open = False + self.done = True + + if TREZOR: class QtGuiTrezorClient(ProtocolMixin, TrezorQtGuiMixin, BaseClient): def call_raw(self, msg): @@ -349,3 +385,6 @@ if TREZOR: raise return resp + + twd = TrezorWaitingDialog() + From e9e8b7e960de1db0012fdc457a49fb69154240a1 Mon Sep 17 00:00:00 2001 From: Michael Wozniak Date: Sat, 2 Aug 2014 23:38:16 -0400 Subject: [PATCH 15/20] Clean up dialog code TODO: fix dialog for cancelled tx from Trezor --- plugins/trezor.py | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/plugins/trezor.py b/plugins/trezor.py index fb777aaf..d2410115 100644 --- a/plugins/trezor.py +++ b/plugins/trezor.py @@ -29,7 +29,6 @@ def log(msg): stderr.flush() gl_emitter = QObject() -window_open = False class Plugin(BasePlugin): @@ -284,8 +283,6 @@ class TrezorQtGuiMixin(object): super(TrezorQtGuiMixin, self).__init__(*args, **kwargs) def callback_ButtonRequest(self, msg): - if window_open: - gl_emitter.emit(SIGNAL('trezor_done')) if msg.code == 3: message = "Confirm transaction outputs on Trezor device to continue" elif msg.code == 8: @@ -352,9 +349,9 @@ class TrezorQtGuiMixin(object): class TrezorWaitingDialog(QThread): def __init__(self): QThread.__init__(self) + self.waiting = False def start(self, message): - self.done = False self.d = QDialog() self.d.setModal(True) self.d.setWindowTitle('Please Check Trezor Device') @@ -362,17 +359,13 @@ class TrezorWaitingDialog(QThread): vbox = QVBoxLayout(self.d) vbox.addWidget(l) self.d.show() - window_open = True - self.d.connect(gl_emitter, SIGNAL('trezor_done'), self.stop) - - def run(self): - while not self.done: - sleep(0.1) + if not self.waiting: + self.waiting = True + self.d.connect(gl_emitter, SIGNAL('trezor_done'), self.stop) def stop(self): self.d.hide() - window_open = False - self.done = True + self.waiting = False if TREZOR: From ef6ccf2bcd102390ddfd77c30f82eafb8859f028 Mon Sep 17 00:00:00 2001 From: Michael Wozniak Date: Sat, 2 Aug 2014 23:41:27 -0400 Subject: [PATCH 16/20] Fix dialog for cancelled TX on Trezor --- plugins/trezor.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/plugins/trezor.py b/plugins/trezor.py index d2410115..360eb78c 100644 --- a/plugins/trezor.py +++ b/plugins/trezor.py @@ -175,8 +175,12 @@ class TrezorWallet(NewWallet): inputs = self.tx_inputs(tx) outputs = self.tx_outputs(tx) - signed_tx = self.get_client().sign_tx('Bitcoin', inputs, outputs)[1] - gl_emitter.emit(SIGNAL('trezor_done')) + try: + signed_tx = self.get_client().sign_tx('Bitcoin', inputs, outputs)[1] + except Exception, e: + raise e + finally: + gl_emitter.emit(SIGNAL('trezor_done')) values = [i['value'] for i in tx.inputs] raw = signed_tx.encode('hex') tx.update(raw) From d2c1ebfc63b4e714af724f03ca27ca323f27090e Mon Sep 17 00:00:00 2001 From: Michael Wozniak Date: Sun, 3 Aug 2014 10:49:25 -0400 Subject: [PATCH 17/20] Remove extra variable that isn't needed --- plugins/trezor.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/plugins/trezor.py b/plugins/trezor.py index 360eb78c..2387cca7 100644 --- a/plugins/trezor.py +++ b/plugins/trezor.py @@ -1,4 +1,4 @@ -from PyQt4.Qt import QMessageBox, QDialog, QVBoxLayout, QLabel, QThread, SIGNAL, QObject +from PyQt4.Qt import QMessageBox, QDialog, QVBoxLayout, QLabel, QThread, SIGNAL from binascii import unhexlify from struct import pack from sys import stderr @@ -28,8 +28,6 @@ def log(msg): stderr.write("%s\n" % msg) stderr.flush() -gl_emitter = QObject() - class Plugin(BasePlugin): def fullname(self): return 'Trezor Wallet' @@ -180,7 +178,7 @@ class TrezorWallet(NewWallet): except Exception, e: raise e finally: - gl_emitter.emit(SIGNAL('trezor_done')) + twd.emit(SIGNAL('trezor_done')) values = [i['value'] for i in tx.inputs] raw = signed_tx.encode('hex') tx.update(raw) @@ -365,7 +363,7 @@ class TrezorWaitingDialog(QThread): self.d.show() if not self.waiting: self.waiting = True - self.d.connect(gl_emitter, SIGNAL('trezor_done'), self.stop) + self.d.connect(twd, SIGNAL('trezor_done'), self.stop) def stop(self): self.d.hide() From 017693fa572daae673471dc59eef756b9edee696 Mon Sep 17 00:00:00 2001 From: Michael Wozniak Date: Sun, 3 Aug 2014 17:37:26 -0400 Subject: [PATCH 18/20] Update trezor plugin for message signing --- plugins/trezor.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/plugins/trezor.py b/plugins/trezor.py index 2387cca7..848c5756 100644 --- a/plugins/trezor.py +++ b/plugins/trezor.py @@ -1,8 +1,10 @@ from PyQt4.Qt import QMessageBox, QDialog, QVBoxLayout, QLabel, QThread, SIGNAL +import PyQt4.QtCore as QtCore from binascii import unhexlify from struct import pack from sys import stderr from time import sleep +from base64 import b64encode from electrum_gui.qt.password_dialog import make_password_dialog, run_password_dialog from electrum_gui.qt.util import ok_cancel_buttons @@ -164,6 +166,21 @@ class TrezorWallet(NewWallet): #do nothing - no priv keys available pass + def sign_message(self, address, message, password): + try: + address_path = self.address_id(address) + address_n = self.get_client().expand_path(address_path) + except Exception, e: + raise + try: + msg_sig = self.get_client().sign_message('Bitcoin', address_n, message) + except Exception, e: + raise e + finally: + twd.emit(SIGNAL('trezor_done')) + b64_msg_sig = b64encode(msg_sig.signature) + return str(b64_msg_sig) + def sign_transaction(self, tx, keypairs, password): if tx.error or tx.is_complete(): return @@ -289,6 +306,8 @@ class TrezorQtGuiMixin(object): message = "Confirm transaction outputs on Trezor device to continue" elif msg.code == 8: message = "Confirm transaction fee on Trezor device to continue" + elif msg.code == 7: + message = "Confirm message to sign on Trezor device to continue" else: message = "Check Trezor device to continue" twd.start(message) @@ -355,8 +374,9 @@ class TrezorWaitingDialog(QThread): def start(self, message): self.d = QDialog() - self.d.setModal(True) + self.d.setModal(1) self.d.setWindowTitle('Please Check Trezor Device') + self.d.setWindowFlags(self.d.windowFlags() | QtCore.Qt.WindowStaysOnTopHint) l = QLabel(message) vbox = QVBoxLayout(self.d) vbox.addWidget(l) From 0c81010290ebf3d49dcaa8fbd8d01725b90c68b0 Mon Sep 17 00:00:00 2001 From: Michael Wozniak Date: Sun, 3 Aug 2014 19:10:20 -0400 Subject: [PATCH 19/20] Add decrypt function Not yet supported in Trezor device, so it currently returns an Unknown Message error --- plugins/trezor.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/plugins/trezor.py b/plugins/trezor.py index 848c5756..b25032a1 100644 --- a/plugins/trezor.py +++ b/plugins/trezor.py @@ -4,12 +4,12 @@ from binascii import unhexlify from struct import pack from sys import stderr from time import sleep -from base64 import b64encode +from base64 import b64encode, b64decode from electrum_gui.qt.password_dialog import make_password_dialog, run_password_dialog from electrum_gui.qt.util import ok_cancel_buttons from electrum.account import BIP32_Account -from electrum.bitcoin import EncodeBase58Check +from electrum.bitcoin import EncodeBase58Check, public_key_to_bc_address from electrum.i18n import _ from electrum.plugins import BasePlugin from electrum.transaction import deserialize @@ -166,6 +166,21 @@ class TrezorWallet(NewWallet): #do nothing - no priv keys available pass + def decrypt_message(self, pubkey, message, password): + try: + address = public_key_to_bc_address(pubkey.decode('hex')) + address_path = self.address_id(address) + address_n = self.get_client().expand_path(address_path) + except Exception, e: + raise e + try: + decrypted_msg = self.get_client().decrypt_message(address_n, b64decode(message)) + except Exception, e: + raise e + finally: + twd.emit(SIGNAL('trezor_done')) + return str(decrypted_msg) + def sign_message(self, address, message, password): try: address_path = self.address_id(address) From 638565bddb71630f0fe03e1b355261791aeeb662 Mon Sep 17 00:00:00 2001 From: ThomasV Date: Fri, 8 Aug 2014 18:29:08 +0200 Subject: [PATCH 20/20] fix get_public_key of trezor plugin --- plugins/trezor.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/trezor.py b/plugins/trezor.py index b25032a1..fe792823 100644 --- a/plugins/trezor.py +++ b/plugins/trezor.py @@ -150,8 +150,8 @@ class TrezorWallet(NewWallet): def get_public_key(self, bip32_path): address_n = self.get_client().expand_path(bip32_path) - res = self.get_client().get_public_node(address_n) - xpub = "0488B21E".decode('hex') + chr(res.depth) + self.i4b(res.fingerprint) + self.i4b(res.child_num) + res.chain_code + res.public_key + node = self.get_client().get_public_node(address_n).node + xpub = "0488B21E".decode('hex') + chr(node.depth) + self.i4b(node.fingerprint) + self.i4b(node.child_num) + node.chain_code + node.public_key return EncodeBase58Check(xpub) def get_master_public_key(self):