Example #1
0
    def get_client(self):
        if not TREZOR:
            give_error('please install github.com/trezor/python-trezor')

        if not self.client or self.client.bad:
            try:
                d = HidTransport.enumerate()[0]
                self.transport = HidTransport(d)
            except:
                give_error(
                    'Could not connect to your Trezor. Please verify the cable is connected and that no other app is using it.'
                )
            self.client = QtGuiTrezorClient(self.transport)
            self.client.handler = self.plugin.handler
            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
            if not self.atleast_version(1, 2, 1):
                give_error(
                    'Outdated Trezor firmware. Please update the firmware from https://www.mytrezor.com'
                )
        return self.client
Example #2
0
    def chooseDevice(self, devices):
        """
		Choose device from enumerated list. If there's only one Trezor,
		that will be chosen.

		If there are multiple Trezors, diplays a widget with list
		of Trezor devices to choose from.

		devices is a list of device
		A device is something like:
		in Py2:  ['0001:0008:00', '0001:0008:01']
		In Py3:  [b'0001:0008:00', b'0001:0008:01']

		@returns HidTransport object of selected device
		"""
        if not len(devices):
            raise RuntimeError(u"No Trezor connected!")

        if len(devices) == 1:
            try:
                return HidTransport(devices[0])
            except IOError:
                raise RuntimeError(u"Trezor is currently in use")

        # maps deviceId string to device label
        deviceMap = {}
        for device in devices:
            try:
                transport = HidTransport(device)
                client = QtTrezorClient(transport)
                label = client.features.label and client.features.label or "<no label>"
                client.close()

                deviceMap[device[0]] = label
            except IOError:
                # device in use, do not offer as choice
                continue

        if not deviceMap:
            raise RuntimeError(u"All connected Trezors are in use!")

        if self.readdevicestringfromstdin:
            print(u'Chose your Trezor device please. '
                  'Devices currently in use are not listed:')
            ii = 0
            for device in deviceMap:
                print('%d  %s' % (ii, deviceMap[device]))
                ii += 1
            ii -= 1
            while True:
                inputstr = input(u"Please provide the number of the device "
                                 "chosen: (%d-%d, Carriage return to quit) " %
                                 (0, ii))

                if inputstr == '':
                    raise RuntimeError(u"No Trezors device chosen! Quitting.")
                try:
                    inputint = int(inputstr)
                except Exception:
                    print(u'Wrong input. You must enter a number '
                          'between %d and %d. Try again.' % (0, ii))
                    continue
                if inputint < 0 or inputint > ii:
                    print(u'Wrong input. You must enter a number '
                          'between %d and %d. Try again.' % (0, ii))
                    continue
                break
            # Py2-vs-Py3: dictionaries are different in Py2 and Py3
            if sys.version_info[0] > 2:  # Py2-vs-Py3:
                deviceStr = list(deviceMap.keys())[ii]
            else:
                deviceStr = deviceMap.keys()[ii]
        else:
            dialog = TrezorChooserDialog(deviceMap)
            if not dialog.exec_():
                raise RuntimeError(u"No Trezors device chosen! Quitting.")
            deviceStr = dialog.chosenDeviceStr()
        return HidTransport([deviceStr, None])
Example #3
0
 def hid_transport(self, pair):
     from trezorlib.transport_hid import HidTransport
     return HidTransport(pair)
Example #4
0
def main():
    numinputs = 100
    sizeinputtx = 10

    # List all connected TREZORs on USB
    devices = HidTransport.enumerate()

    # Check whether we found any
    if len(devices) == 0:
        print('No TREZOR found')
        return

    # Use first connected device
    print(devices[0][0])
    # transport = BridgeTransport(devices[0][0])
    transport = HidTransport(devices[0])

    txstore = MyTxApiBitcoin()

    # Creates object for manipulating TREZOR
    client = TrezorClient(transport)
    # client.set_tx_api(TxApiTestnet)
    txstore.set_client(client)
    txstore.set_publickey(client.get_public_node(client.expand_path("44'/0'/0'")))
    print("creating input txs")
    txstore.create_inputs(numinputs, sizeinputtx)
    print("go")
    client.set_tx_api(txstore)
    # client.set_tx_api(MyTxApiBitcoin())

    # Print out TREZOR's features and settings
    print(client.features)

    # Get the first address of first BIP44 account
    # (should be the same address as shown in wallet.trezor.io)

    outputs = [
        proto_types.TxOutputType(
            amount=0,
            script_type=proto_types.PAYTOADDRESS,
            address='p2xtZoXeX5X8BP8JfFhQK2nD3emtjch7UeFm'
            # op_return_data=binascii.unhexlify('2890770995194662774cd192ee383b805e9a066e6a456be037727649228fb7f6')
            # address_n=client.expand_path("44'/0'/0'/0/35"),
            # address='3PUxV6Cc4udQZQsJhArVUzvvVoKC8ohkAj',
        ),
        # proto_types.TxOutputType(
        #     amount=0,
        #     script_type=proto_types.PAYTOOPRETURN,
        #     op_return_data=binascii.unhexlify('2890770995194662774cd192ee383b805e9a066e6a456be037727649228fb7f6')
        # ),
        # proto_types.TxOutputType(
        #     amount= 8120,
        #     script_type=proto_types.PAYTOADDRESS,
        #     address_n=client.expand_path("44'/1'/0'/1/0"),
        #     address='1PtCkQgyN6xHmXWzLmFFrDNA5vYhYLeNFZ',
        #     address='14KRxYgFc7Se8j7MDdrK5PTNv8meq4GivK',
        # ),
        # proto_types.TxOutputType(
        # amount= 18684 - 2000,
        # script_type=proto_types.PAYTOADDRESS,
        # address_n=client.expand_path("44'/0'/0'/0/7"),
        # # address='1PtCkQgyN6xHmXWzLmFFrDNA5vYhYLeNFZ',
        # # address='1s9TSqr3PHZdXGrYws59Uaf5SPqavH43z',
        # ),
        # proto_types.TxOutputType(
        # amount= 1000,
        # script_type=proto_types.PAYTOADDRESS,
        # # address_n=client.expand_path("44'/0'/0'/0/18"),
        # # address='1PtCkQgyN6xHmXWzLmFFrDNA5vYhYLeNFZ',
        # # address='1NcMqUvyWv1K3Zxwmx5sqfj7ZEmPCSdJFM',
        # ),
    ]

#    (signatures, serialized_tx) = client.sign_tx('Testnet', inputs, outputs)
    (signatures, serialized_tx) = client.sign_tx('Bitcoin', txstore.get_inputs(), txstore.get_outputs())
    print('Transaction:', binascii.hexlify(serialized_tx))

    client.close()
Example #5
0
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import QThread, SIGNAL

from pycoin.key.bip32 import Wallet

from trezorlib.client import TrezorClient
from trezorlib.transport_hid import HidTransport
import trezorlib

import mnemonic

from gui import Ui_MainWindow

devices = HidTransport.enumerate()
transport = HidTransport(devices[0])

client = TrezorClient(transport)

#netcode = "BTC"
#xpub = Wallet(False, netcode, node.chain_code, node.depth, unhexlify("%08x" % node.fingerprint), node.child_num)

#
# Wrap trezor functions in a with statement (using this) to show on the UI that
# interaction is required on the trezor
#

class TrezorWarning:

    def __init__(self):
        self.waiting = False
Example #6
0
    parsed_json = decryptStorage(full_path, encKey)

    #list entries
    entries = parsed_json['entries']
    printEntries(entries)

    entry_id = raw_input('Select entry number to decrypt: ')
    entry_id = str(entry_id)

    plain_nonce = getDecryptedNonce(entries[entry_id])

    pwdArr = entries[entry_id]['password']['data']
    pwdHex = ''.join([hex(x)[2:].zfill(2) for x in pwdArr])
    print 'password: '******'safe_note']['data']
    safeNoteHex = ''.join([hex(x)[2:].zfill(2) for x in safeNoteArr])
    print 'safe_note:', decryptEntryValue(plain_nonce, unhexlify(safeNoteHex))

    return


if __name__ == '__main__':
    try:
        # init TREZOR transport
        client = TrezorClient(HidTransport(HidTransport.enumerate()[0]))
    except:
        print 'TREZOR is not plugged in. Please, connect TREZOR and retry.'
    else:
        main()
Example #7
0
def get_client():
    devices = HidTransport.enumerate()   # List all connected TREZORs on USB
    if len(devices) == 0:                # Check whether we found any
        return None
    transport = HidTransport(devices[0]) # Use first connected device
    return TrezorClient(transport)       # Creates object for communicating with TREZOR
# chosen by the attacker without notifying the user for any transaction
# PoC TXs : bca17fb40c8c86e7c7acd0d3749af9e5c66575dce86db895b7e3301f7a4b2b84 -> b3c2b4a8e98d4494e9f303754a4e9477c1f6e1c1b7c4210bf53a4b2156bfbb99
# PoC Setup :
# client.load_device_by_mnemonic(mnemonic='alcohol woman abuse must during monitor noble actual mixed trade anger aisle', pin='', passphrase_protection=False, label='test', language='english')

# Cleared by https://github.com/trezor/trezor-mcu/commit/137a60ce017c402ac160258bcc4b5f7b5aba0560

from trezorlib import *
from trezorlib.client import TrezorClient
from trezorlib.transport_hid import HidTransport
import trezorlib.messages_pb2 as proto
import trezorlib.types_pb2 as types
import binascii

devices = HidTransport.enumerate()
client = TrezorClient(HidTransport(devices[0]))

client.transport.session_begin()
tx = proto.SignTx()
tx.inputs_count = 1
tx.outputs_count = 2
tx.coin_name = "Bitcoin"
res = client.call(tx)

if isinstance(res, proto.Failure):
    raise CallException("Signing failed")

if not isinstance(res, proto.TxRequest):
   raise CallException("Unexpected message")

dummyhdnode = types.HDNodeType(
Example #9
0
 def hid_transport(self, device):
     from trezorlib.transport_hid import HidTransport
     return HidTransport(device)