Exemple #1
0
 def __waitForDevices(self):
     devices = enumerate_devices()
     while not len(devices):
         sys.stderr.write("Please connect Trezor to computer and press Enter...")
         input()
         devices = enumerate_devices()
     return devices
Exemple #2
0
def wait_for_devices():
    devices = enumerate_devices()
    while not len(devices):
        sys.stderr.write("Please connect TREZOR to computer and press Enter...")
        input()
        devices = enumerate_devices()

    return devices
def wait_for_devices():
    devices = enumerate_devices()
    while not len(devices):
        sys.stderr.write("Please connect TREZOR to computer and press Enter...")
        input()
        devices = enumerate_devices()

    return devices
Exemple #4
0
def wait_for_devices() -> Sequence["Transport"]:
    devices = enumerate_devices()
    while not len(devices):
        sys.stderr.write(
            "Please connect Trezor to computer and press Enter...")
        input()
        devices = enumerate_devices()

    return devices
Exemple #5
0
def main():
    # List all debuggable TREZORs
    devices = [
        device for device in enumerate_devices()
        if hasattr(device, 'find_debug')
    ]

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

    # Use first connected device
    transport = devices[0]
    debug_transport = devices[0].find_debug()

    # Creates object for manipulating TREZOR
    client = TrezorClient(transport)
    debug = DebugLink(debug_transport)

    arg1 = int(sys.argv[1], 16)
    arg2 = int(sys.argv[2], 16)
    step = 0x400 if arg2 >= 0x400 else arg2

    f = open('memory.dat', 'wb')

    for addr in range(arg1, arg1 + arg2, step):
        mem = debug.memory_read(addr, step)
        f.write(mem)

    f.close()

    client.close()
Exemple #6
0
 def initDevice(self):
     printDbg("Initializing Trezor")
     with self.lock:
         self.status = 0
         devices = enumerate_devices()
         if not len(devices):
             # No device connected
             return
         # Use the first device for now
         d = devices[0]
         ui = TrezorUi()
         try:
             self.client = TrezorClient(d, ui)
         except IOError:
             raise Exception("TREZOR device is currently in use")
         printOK("Trezor HW device connected [v. %s.%s.%s]" %
                 (self.client.features.major_version,
                  self.client.features.minor_version,
                  self.client.features.patch_version))
         self.status = 1
         model = self.client.features.model or "1"
         if not self.checkModel(model):
             self.status = 3
             self.messages[
                 3] = "Wrong device model (%s) detected.\nLooking for model %s." % (
                     HW_devices[self.model][0], model)
             return
         required_version = MINIMUM_FIRMWARE_VERSION[model]
         printDbg("Current version is %s (minimum required: %s)" %
                  (str(self.client.version), str(required_version)))
         # Check device is unlocked
         bip32_path = parse_path(MPATH + "%d'/0/%d" % (0, 0))
         _ = btc.get_address(self.client, 'PIVX', bip32_path, False)
         self.status = 2
def main():
    # List all debuggable TREZORs
    devices = [device for device in enumerate_devices() if hasattr(device, 'find_debug')]

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

    # Use first connected device
    transport = devices[0]
    debug_transport = devices[0].find_debug()

    # Creates object for manipulating TREZOR
    client = TrezorClient(transport)
    debug = DebugLink(debug_transport)

    sector = int(sys.argv[1])
    f = open(sys.argv[2], "rb")
    content = f.read(sectorlens[sector])
    if (len(content) != sectorlens[sector]):
        print("Not enough bytes in file")
        return

    debug.flash_erase(sector)
    step = 0x400
    for offset in range(0, sectorlens[sector], step):
        debug.memory_write(sectoraddrs[sector] + offset, content[offset:offset + step], flash=True)
    client.close()
Exemple #8
0
def get_all_clients(ui_factory=None):
    if ui_factory is None:
        ui_factory = ClickUI

    return [
        TrezorClient(device, ui_factory()) for device in enumerate_devices()
    ]
def get_trezor_client() -> TrezorClient:
    """
    Wrapper to open connection to Trezor One

    Returns: 
        TrezorClient object
    """

    # List all connected TREZORs on USB
    devices = enumerate_devices()

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

    # Use first connected device
    #transport = devices[0]

    transport = get_transport()

    ui = ClickUI()
    # Creates object for manipulating TREZOR
    client = TrezorClient(transport, ui)

    return client
Exemple #10
0
def get_device():
    path = os.environ.get("TREZOR_PATH")
    if path:
        return get_transport(path)
    else:
        devices = enumerate_devices()
        for d in devices:
            if hasattr(d, "find_debug"):
                return d
        raise RuntimeError("No debuggable device found")
Exemple #11
0
def get_device():
    path = os.environ.get("TREZOR_PATH")
    if path:
        return get_transport(path)
    else:
        devices = enumerate_devices()
        for device in devices:
            if hasattr(device, "find_debug"):
                return device
        raise RuntimeError("No debuggable device found")
Exemple #12
0
def find_debug():
    for device in enumerate_devices():
        try:
            debug_transport = device.find_debug()
            debug = DebugLink(debug_transport, auto_interact=False)
            debug.open()
            return debug
        except Exception:
            continue
    else:
        print("No suitable Trezor device found")
        sys.exit(1)
def find_debug():
    for device in enumerate_devices():
        try:
            debug_transport = device.find_debug()
            debug = DebugLink(debug_transport, auto_interact=False)
            debug.open()
            return debug
        except Exception:
            continue
    else:
        print("No suitable Trezor device found")
        sys.exit(1)
Exemple #14
0
def get_device():
    path = os.environ.get("TREZOR_PATH")
    if path:
        transport = get_transport(path)
    else:
        devices = enumerate_devices()
        for device in devices:
            if hasattr(device, "find_debug"):
                transport = device
                break
        else:
            raise RuntimeError("No debuggable device found")
    env_interactive = int(os.environ.get("INTERACT", 0))
    try:
        return TrezorClientDebugLink(transport,
                                     auto_interact=not env_interactive)
    except Exception as e:
        raise RuntimeError("Failed to open debuglink for {}".format(
            transport.get_path())) from e
Exemple #15
0
def get_device():
    path = os.environ.get("TREZOR_PATH")
    if path:
        transport = get_transport(path)
    else:
        devices = enumerate_devices()
        for device in devices:
            if hasattr(device, "find_debug"):
                transport = device
                break
        else:
            raise RuntimeError("No debuggable device found")
    env_interactive = int(os.environ.get("INTERACT", 0))
    try:
        return TrezorClientDebugLink(transport, auto_interact=not env_interactive)
    except Exception as e:
        raise RuntimeError(
            "Failed to open debuglink for {}".format(transport.get_path())
        ) from e
Exemple #16
0
def get_device():
    path = os.environ.get("TREZOR_PATH")
    interact = int(os.environ.get("INTERACT", 0))
    if path:
        try:
            transport = get_transport(path)
            return TrezorClientDebugLink(transport, auto_interact=not interact)
        except Exception as e:
            raise RuntimeError("Failed to open debuglink for {}".format(path)) from e

    else:
        devices = enumerate_devices()
        for device in devices:
            try:
                return TrezorClientDebugLink(device, auto_interact=not interact)
            except Exception:
                pass
        else:
            raise RuntimeError("No debuggable device found")
def main():
    # List all debuggable TREZORs
    devices = [device for device in enumerate_devices() if hasattr(device, 'find_debug')]

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

    # Use first connected device
    transport = devices[0]
    debug_transport = devices[0].find_debug()

    # Creates object for manipulating TREZOR
    client = TrezorClient(transport)
    debug = DebugLink(debug_transport)

    debug.memory_write(int(sys.argv[1], 16), binascii.unhexlify(sys.argv[2]), flash=True)
    client.close()
Exemple #18
0
def _raw_client(request: pytest.FixtureRequest) -> Client:
    path = os.environ.get("TREZOR_PATH")
    interact = int(os.environ.get("INTERACT", 0))
    if path:
        try:
            transport = get_transport(path)
            return Client(transport, auto_interact=not interact)
        except Exception as e:
            request.session.shouldstop = "Failed to communicate with Trezor"
            raise RuntimeError(f"Failed to open debuglink for {path}") from e

    else:
        devices = enumerate_devices()
        for device in devices:
            try:
                return Client(device, auto_interact=not interact)
            except Exception:
                pass

        request.session.shouldstop = "Failed to communicate with Trezor"
        raise RuntimeError("No debuggable device found")
Exemple #19
0
def enumerate(password=''):
    results = []
    for dev in enumerate_devices():
        d_data = {}

        d_data['type'] = 'trezor'
        d_data['path'] = dev.get_path()

        try:
            client = TrezorClient(d_data['path'], password)
            if client.client.features.initialized:
                master_xpub = client.get_pubkey_at_path('m/0h')['xpub']
                d_data['fingerprint'] = get_xpub_fingerprint_hex(master_xpub)
            else:
                d_data['error'] = 'Not initialized'
            client.close()
        except Exception as e:
            d_data[
                'error'] = "Could not open client or get fingerprint information: " + str(
                    e)

        results.append(d_data)
    return results
Exemple #20
0
def load_client():
    devices = enumerate_devices()
    for device in devices:
        try:
            client = TrezorClientDebugLink(device)
            break
        except Exception:
            pass
    else:
        raise RuntimeError("No debuggable device found")

    wipe_device(client)
    debuglink.load_device_by_mnemonic(
        client,
        mnemonic=" ".join(["all"] * 12),
        pin=None,
        passphrase_protection=False,
        label="test",
        language="english",
    )
    client.clear_session()

    client.open()
    return client
Exemple #21
0
    "--autoconfirm",
    action="store_true",
    help="Automatically confirm everything on the device.",
)
parser.add_argument(
    "--testnet",
    action="store_true",
    help="Use BTC testnet instead of mainnet.",
)
args = parser.parse_args()

# Can choose autoconfirm everything on the device (in the device-tests-style)
# (Suitable for long/repetitive transactions)
if args.autoconfirm:
    print("Autoconfirming everything on the device.")
    for device in enumerate_devices():
        try:
            CLIENT = TrezorClientDebugLink(device, auto_interact=True)
            break
        except Exception:
            pass
    else:
        raise RuntimeError("Could not find device")
else:
    CLIENT = get_default_client()
# Choosing between Mainnet and Testnet
if args.testnet:
    COIN = "Testnet"
    URL = "https://tbtc1.trezor.io/api/tx-specific"
else:
    COIN = "Bitcoin"
Exemple #22
0
def trezor_test_suite(emulator, rpc, userpass):
    # Start the Trezor emulator
    emulator_proc = subprocess.Popen([emulator])
    # Wait for emulator to be up
    # From https://github.com/trezor/trezor-mcu/blob/master/script/wait_for_emulator.py
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.connect(('127.0.0.1', 21324))
    sock.settimeout(0)
    while True:
        try:
            sock.sendall(b"PINGPING")
            r = sock.recv(8)
            if r == b"PONGPONG":
                break
        except Exception:
            time.sleep(0.05)
    # Cleanup
    def cleanup_emulator():
        emulator_proc.kill()

    atexit.register(cleanup_emulator)

    # Setup the emulator
    for dev in enumerate_devices():
        # Find the udp transport, that's the emulator
        if isinstance(dev, UdpTransport):
            wirelink = dev
            break
    client = TrezorClientDebugLink(wirelink)
    device.wipe(client)
    load_device_by_mnemonic(
        client=client,
        mnemonic=
        'alcohol woman abuse must during monitor noble actual mixed trade anger aisle',
        pin='',
        passphrase_protection=False,
        label='test')  # From Trezor device tests

    class TrezorTestCase(unittest.TestCase):
        def __init__(self, client, methodName='runTest'):
            super(TrezorTestCase, self).__init__(methodName)
            self.client = client

        @staticmethod
        def parameterize(testclass, client):
            testloader = unittest.TestLoader()
            testnames = testloader.getTestCaseNames(testclass)
            suite = unittest.TestSuite()
            for name in testnames:
                suite.addTest(testclass(client, name))
            return suite

    # Trezor specific getxpub test because this requires device specific thing to set xprvs
    class TestTrezorGetxpub(TrezorTestCase):
        def test_getxpub(self):
            with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                   'data/bip32_vectors.json'),
                      encoding='utf-8') as f:
                vectors = json.load(f)
            for vec in vectors:
                with self.subTest(vector=vec):
                    # Setup with xprv
                    device.wipe(self.client)
                    load_device_by_xprv(client=self.client,
                                        xprv=vec['xprv'],
                                        pin='',
                                        passphrase_protection=False,
                                        label='test',
                                        language='english')

                    # Test getmasterxpub
                    gmxp_res = process_commands([
                        '-t', 'trezor', '-d', 'udp:127.0.0.1:21324',
                        'getmasterxpub'
                    ])
                    self.assertEqual(gmxp_res['xpub'], vec['master_xpub'])

                    # Test the path derivs
                    for path_vec in vec['vectors']:
                        gxp_res = process_commands([
                            '-t', 'trezor', '-d', 'udp:127.0.0.1:21324',
                            'getxpub', path_vec['path']
                        ])
                        self.assertEqual(gxp_res['xpub'], path_vec['xpub'])

    # Generic Device tests
    suite = unittest.TestSuite()
    suite.addTest(
        DeviceTestCase.parameterize(
            TestDeviceConnect, rpc, userpass, 'trezor', 'udp:127.0.0.1:21324',
            '95d8f670',
            'xpub6D1weXBcFAo8CqBbpP4TbH5sxQH8ZkqC5pDEvJ95rNNBZC9zrKmZP2fXMuve7ZRBe18pWQQsGg68jkq24mZchHwYENd8cCiSb71u3KD4AFH'
        ))
    suite.addTest(
        DeviceTestCase.parameterize(
            TestGetKeypool, rpc, userpass, 'trezor', 'udp:127.0.0.1:21324',
            '95d8f670',
            'xpub6D1weXBcFAo8CqBbpP4TbH5sxQH8ZkqC5pDEvJ95rNNBZC9zrKmZP2fXMuve7ZRBe18pWQQsGg68jkq24mZchHwYENd8cCiSb71u3KD4AFH'
        ))
    suite.addTest(
        DeviceTestCase.parameterize(
            TestSignTx, rpc, userpass, 'trezor', 'udp:127.0.0.1:21324',
            '95d8f670',
            'xpub6D1weXBcFAo8CqBbpP4TbH5sxQH8ZkqC5pDEvJ95rNNBZC9zrKmZP2fXMuve7ZRBe18pWQQsGg68jkq24mZchHwYENd8cCiSb71u3KD4AFH'
        ))
    suite.addTest(
        DeviceTestCase.parameterize(
            TestDisplayAddress, rpc, userpass, 'trezor', 'udp:127.0.0.1:21324',
            '95d8f670',
            'xpub6D1weXBcFAo8CqBbpP4TbH5sxQH8ZkqC5pDEvJ95rNNBZC9zrKmZP2fXMuve7ZRBe18pWQQsGg68jkq24mZchHwYENd8cCiSb71u3KD4AFH'
        ))
    suite.addTest(TrezorTestCase.parameterize(TestTrezorGetxpub, client))
    return suite
Exemple #23
0
def get_device_list(return_clients: bool = True, allow_bootloader_mode: bool = False) \
        -> Tuple[List[Dict], List[Exception]]:
    """
    :return: Tuple[List[Dict <{'client': MyTrezorClient, 'device_id': str, 'desc',: str, 'model': str}>],
                   List[Exception]]
    """
    ret_list = []
    exceptions: List[Exception] = []
    device_ids = []
    was_bootloader_mode = False

    devices = enumerate_devices()
    for d in devices:
        try:
            client = MyTrezorClient(d, ui=TrezorUi())

            if client.features.bootloader_mode:
                if was_bootloader_mode:
                    # in bootloader mode the device_id attribute isn't available, so for a given client object
                    # we are unable to distinguish between being the same device reached with the different
                    # transport and being another device
                    # for that reason, to avoid returning duplicate clients for the same device, we don't return
                    # more than one instance of a device in bootloader mod
                    client.close()
                    continue
                was_bootloader_mode = True

            if (not client.features.bootloader_mode or allow_bootloader_mode) and \
                (client.features.device_id not in device_ids or client.features.bootloader_mode):

                version = f'{client.features.major_version}.{client.features.minor_version}.' \
                          f'{client.features.patch_version}'
                if client.features.label:
                    desc = client.features.label
                else:
                    desc = '[UNNAMED]'
                desc = f'{desc} (ver: {version}, id: {client.features.device_id})'

                c = {
                    'client': client,
                    'device_id': client.features.device_id,
                    'desc': desc,
                    'model': client.features.model,
                    'bootloader_mode': client.features.bootloader_mode
                }

                ret_list.append(c)
                device_ids.append(client.features.device_id
                                  )  # beware: it's empty in bootloader mode
            else:
                # the same device is already connected using different connection medium
                client.close()
        except Exception as e:
            logging.warning(
                f'Cannot create Trezor client ({d.__class__.__name__}) due to the following error: '
                + str(e))
            exceptions.append(e)

    if not return_clients:
        for cli in ret_list:
            cli['client'].close()
            cli['client'] = None

    return ret_list, exceptions
Exemple #24
0
 def enumerate():
     return enumerate_devices()