예제 #1
0
def main():
    parser = ArgumentParser()
    parser.add_argument("-m", dest="mnemonic", help="Set mnemonic", type=str)
    parser.add_argument("-p", dest="pin", help="Set pin", type=str)
    parser.add_argument("--passphrase",
                        dest="passphrase",
                        help="Enable passphrase",
                        action="store_true")
    parser.add_argument("--no-passphrase",
                        dest="passphrase",
                        help="Enable passphrase",
                        action="store_false")
    parser.set_defaults(passphrase=True)

    args = parser.parse_args()

    # Setup link
    wirelink = get_device()
    client = TrezorClientDebugLink(wirelink)
    client.open()
    device.wipe(client)

    debuglink.load_device_by_mnemonic(client,
                                      mnemonic=args.mnemonic,
                                      pin=args.pin,
                                      passphrase_protection=args.passphrase,
                                      label='test')

    print(args.mnemonic)
    print(client.features)
    client.close()
예제 #2
0
    def start(self):
        if self.process:
            if self.process.poll() is not None:
                # process has died, stop and start again
                self.stop()
            else:
                # process is running, no need to start again
                return

        self.process = self.launch_process()
        try:
            self.wait_until_ready()
        except TimeoutError:
            # Assuming that after the default 30-second timeout, the process is stuck
            self.process.kill()
            raise

        (self.profile_dir /
         "trezor.pid").write_text(str(self.process.pid) + "\n")
        (self.profile_dir / "trezor.port").write_text(str(self.port) + "\n")

        transport = self._get_transport()
        self.client = TrezorClientDebugLink(transport,
                                            auto_interact=self.debug)

        self.client.open()
    def start(self):
        env, args, cwd = self._get_params()
        self.process = subprocess.Popen(args,
                                        cwd=cwd,
                                        env=env,
                                        stdout=open(os.devnull, "w"))

        # wait until emulator is listening
        transport = UdpTransport("127.0.0.1:21324")
        transport.open()
        for _ in range(300):
            if transport._ping():
                break
            if self.process.poll() is not None:
                self._cleanup()
                raise RuntimeError("Emulator proces died")
            time.sleep(0.1)
        else:
            # could not connect after 300 attempts * 0.1s = 30s of waiting
            self._cleanup()
            raise RuntimeError("Can't connect to emulator")
        transport.close()

        self.client = TrezorClientDebugLink(transport)
        self.client.open()
        check_version(self.tag, self.client.version)
예제 #4
0
 def _connect(self):
     self.wirelink = get_transport(self.path)
     self.client = (
         TrezorClientDebugLink(self.wirelink)
         if self.debug
         else TrezorClient(self.wirelink, ui=ui.ClickUI())
     )
예제 #5
0
    def setup_method(self, method):
        wirelink = conftest.get_device()
        self.client = TrezorClientDebugLink(wirelink)
        # self.client.set_buttonwait(3)

        device.wipe(self.client)
        self.client.open()
예제 #6
0
def allow_unsafe() -> None:
    client = TrezorClientDebugLink(get_device())
    client.open()
    time.sleep(SLEEP)

    # T1 does not support PromptAlways
    if client.features.major_version == 1:
        safety_checks = messages.SafetyCheckLevel.PromptTemporarily
    else:
        safety_checks = messages.SafetyCheckLevel.PromptAlways

    # Some older devices do not support safety checks, so we know
    # the command will fail with a specific error message
    # T1 supports safety checks from 1.10.1 and T2 from 2.3.2
    try:
        device.apply_settings(client, safety_checks=safety_checks)
    except TrezorFailure as err:
        # Catching only specific error message, otherwise reraising the exception
        if "No setting provided" in str(err):
            log(
                f"Could not allow unsafe. Device does not support safety checks. Err: {err}",
                "red",
            )
        else:
            raise
    client.close()
예제 #7
0
    def __enter__(self):
        args = [self.executable]
        env = ENV
        if self.gen == "core":
            args += ["-m", "main"]
            # for firmware 2.1.2 and newer
            env["TREZOR_PROFILE_DIR"] = self.workdir.name
            # for firmware 2.1.1 and older
            env["TREZOR_PROFILE"] = self.workdir.name
        self.process = subprocess.Popen(args,
                                        cwd=self.workdir.name,
                                        env=env,
                                        stdout=open(os.devnull, "w"))
        # wait until emulator is listening
        for _ in range(300):
            try:
                time.sleep(0.1)
                transport = get_transport("udp:127.0.0.1:21324")
                break
            except TransportException:
                pass
            if self.process.poll() is not None:
                self._cleanup()
                raise RuntimeError("Emulator proces died")
        else:
            # could not connect after 300 attempts * 0.1s = 30s of waiting
            self._cleanup()
            raise RuntimeError("Can't connect to emulator")

        self.client = TrezorClientDebugLink(transport)
        self.client.open()
        check_version(self.tag, self.client.version)
        return self
예제 #8
0
    def start(self):
        if self.process:
            if self.process.poll() is not None:
                # process has died, stop and start again
                LOG.info("Starting from a stopped process.")
                self.stop()
            else:
                # process is running, no need to start again
                return

        self.process = self.launch_process()
        try:
            self.wait_until_ready()
        except TimeoutError:
            # Assuming that after the default 60-second timeout, the process is stuck
            LOG.warning("Emulator did not come up after {} seconds".format(
                EMULATOR_WAIT_TIME))
            self.process.kill()
            raise

        (self.profile_dir /
         "trezor.pid").write_text(str(self.process.pid) + "\n")
        (self.profile_dir / "trezor.port").write_text(str(self.port) + "\n")

        transport = self._get_transport()
        self.client = TrezorClientDebugLink(transport,
                                            auto_interact=self.debug)

        self.client.open()
예제 #9
0
def apply_settings(
    language: Optional[str] = None,
    label: Optional[str] = None,
    use_passphrase: Optional[bool] = None,
    homescreen: Optional[str] = None,
    auto_lock_delay_ms: Optional[int] = None,
    display_rotation: Optional[int] = None,
    passphrase_always_on_device: Optional[bool] = None,
    safety_checks: Optional[int] = None,
) -> None:
    """Forwards settings fields to be applied on a device.

    NOTE: does not handle the experimental_features argument,
      seems that it is not yet supported in latest trezorlib
    """
    # Homescreen needs to be bytes object, so if there,
    #   it should be encoded from the received string
    homescreen_bytes = homescreen.encode() if homescreen else None

    client = TrezorClientDebugLink(get_device())
    client.open()
    time.sleep(SLEEP)
    device.apply_settings(
        client,
        label=label,
        language=language,
        use_passphrase=use_passphrase,
        homescreen=homescreen_bytes,
        passphrase_always_on_device=passphrase_always_on_device,
        auto_lock_delay_ms=auto_lock_delay_ms,
        display_rotation=display_rotation,
        safety_checks=safety_checks,
    )
    client.close()
예제 #10
0
    def setup_method(self, method):
        wirelink = conftest.get_device()
        self.client = TrezorClientDebugLink(wirelink)
        self.client.set_tx_api(coins.tx_api["Bitcoin"])
        # self.client.set_buttonwait(3)

        device.wipe(self.client)
        self.client.transport.session_begin()
예제 #11
0
def client():
    wirelink = get_device()
    client = TrezorClientDebugLink(wirelink)
    wipe_device(client)

    client.open()
    yield client
    client.close()
예제 #12
0
def apply_settings(passphrase_always_on_device=None):
    client = TrezorClientDebugLink(get_device())
    client.open()
    time.sleep(SLEEP)
    device.apply_settings(
        client,
        passphrase_always_on_device=bool(passphrase_always_on_device),
    )
    client.close()
예제 #13
0
def allow_unsafe():
    client = TrezorClientDebugLink(get_device())
    # ignore for Legacy firmware, there is no such setting
    if client.features.major_version == 1:
        return
    client.open()
    time.sleep(SLEEP)
    device.apply_settings(client, safety_checks=1)  # TODO
    client.close()
예제 #14
0
def device_version():
    device = get_device()
    if not device:
        raise RuntimeError()
    client = TrezorClientDebugLink(device)
    if client.features.model == "T":
        return 2
    else:
        return 1
예제 #15
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")
예제 #16
0
def _raw_client(request):
    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:
            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 TrezorClientDebugLink(device,
                                             auto_interact=not interact)
            except Exception:
                pass

        request.session.shouldstop = "Failed to communicate with Trezor"
        raise RuntimeError("No debuggable device found")
예제 #17
0
def client():
    wirelink = get_device()
    client = TrezorClientDebugLink(wirelink)
    wipe_device(client)
    client.transport.session_begin()

    yield client

    client.transport.session_end()

    # XXX debuglink session must also be closed
    # client.close accomplishes that for now; going forward, there should
    # also be proper session handling for debuglink
    client.close()
예제 #18
0
    def __init__(self, path, password=''):
        super(TrezorClient, self).__init__(path, password)
        if path.startswith('udp'):
            logging.debug('Simulator found, using DebugLink')
            transport = get_transport(path)
            self.client = TrezorClientDebugLink(transport=transport)
        else:
            self.client = Trezor(transport=get_transport(path), ui=ClickUI())

        # if it wasn't able to find a client, throw an error
        if not self.client:
            raise IOError("no Device")

        self.password = password
        os.environ['PASSPHRASE'] = password
예제 #19
0
def setup_device(mnemonic,
                 pin,
                 passphrase_protection,
                 label,
                 needs_backup=None):
    # TODO:
    # - check if device is acquired otherwise throws "wrong previous session" from bridge
    client = TrezorClientDebugLink(get_device())
    client.open()
    debuglink.load_device(client,
                          mnemonic,
                          pin,
                          passphrase_protection,
                          label,
                          needs_backup=bool(needs_backup))
    client.close()
예제 #20
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
예제 #21
0
    def start(self):
        if self.process:
            if self.process.poll() is not None:
                # process has died, stop and start again
                self.stop()
            else:
                # process is running, no need to start again
                return

        self.process = self.launch_process()
        self.wait_until_ready()

        (self.profile_dir /
         "trezor.pid").write_text(str(self.process.pid) + "\n")
        (self.profile_dir / "trezor.port").write_text(str(self.port) + "\n")

        transport = self._get_transport()
        self.client = TrezorClientDebugLink(transport,
                                            auto_interact=self.debug)

        self.client.open()
예제 #22
0
def setup_device(
    mnemonic: str,
    pin: str,
    passphrase_protection: bool,
    label: str,
    needs_backup: bool = False,
) -> None:
    # TODO: check if device is acquired, otherwise throws
    #   "wrong previous session" from bridge
    client = TrezorClientDebugLink(get_device())
    client.open()
    time.sleep(SLEEP)
    debuglink.load_device(
        client,
        mnemonic,
        pin,
        passphrase_protection,
        label,
        needs_backup=needs_backup,
    )
    client.close()
 def __enter__(self):
     if self.tag.startswith("/"):  # full path+filename provided
         args = [self.tag]
     else:  # only gen+tag provided
         args = ["%s/trezor-emu-%s-%s" % (BINDIR, self.gen, self.tag)]
     env = ENV
     if self.gen == "core":
         args += ["-m", "main"]
         env["TREZOR_PROFILE_DIR"] = self.workdir.name
     self.process = subprocess.Popen(
         args, cwd=self.workdir.name, env=ENV, stdout=open(os.devnull, "w")
     )
     # wait until emulator is started
     while True:
         try:
             self.transport = get_transport("udp:127.0.0.1:21324")
         except TransportException:
             time.sleep(0.1)
             continue
         break
     self.client = TrezorClientDebugLink(self.transport)
     self.client.open()
     return self
예제 #24
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
예제 #25
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
예제 #26
0
async def amain():
    parser = argparse.ArgumentParser(description="Trezor address loader")

    parser.add_argument("--trezor-path",
                        dest="trezor_path",
                        default=None,
                        help="Trezor device path")
    parser.add_argument("--trezor-idx",
                        dest="trezor_idx",
                        default=None,
                        help="Trezor path idx")
    parser.add_argument("--pin",
                        dest="pin",
                        default="",
                        help="Trezor PIN protection")
    parser.add_argument(
        "--passphrase",
        dest="passphrase",
        default=False,
        action="store_const",
        const=True,
        help="Enable passphrase",
    )
    parser.add_argument(
        "--debug",
        dest="debug",
        default=False,
        action="store_const",
        const=True,
        help="Debug",
    )
    parser.add_argument(
        "--debug-link",
        dest="debug_link",
        default=False,
        action="store_const",
        const=True,
        help=
        "Debug link with Trezor. May skip some dialogs (e.g., passphrase entry)",
    )
    args = parser.parse_args()

    try:
        if args.debug:
            coloredlogs.install(level=logging.DEBUG, use_chroot=False)
        else:
            coloredlogs.install(level=logging.INFO, use_chroot=False)
    except Exception as e:
        pass

    debug_mode = args.debug_link
    if args.trezor_path:
        path = args.trezor_path
    elif args.trezor_idx:
        path = "bridge:web01" if args.trezor_idx == "usb" else "udp:127.0.0.1:21324"
    else:
        path = os.environ.get("TREZOR_PATH", "bridge:web01")

    wirelink = get_transport(path)
    client = (TrezorClientDebugLink(wirelink)
              if debug_mode else TrezorClient(wirelink, ui=ui.ClickUI()))

    # client.transport.session_begin()
    trezor_proxy = tmanager.Trezor(path=path, debug=args.debug_link)
    network_type = NetworkTypes.MAINNET
    agent = agent_lite.Agent(trezor_proxy, network_type=network_type)
    res = await agent.get_address()
    print(res)

    # client.transport.session_end()
    client.close()
    sys.exit(0)
예제 #27
0
def reset_device() -> None:
    client = TrezorClientDebugLink(get_device())
    client.open()
    time.sleep(SLEEP)
    device.reset(client, skip_backup=True, pin_protection=False)
    client.close()
예제 #28
0
def wipe_device() -> None:
    client = TrezorClientDebugLink(get_device())
    client.open()
    time.sleep(SLEEP)
    device.wipe(client)
    client.close()
예제 #29
0
    client.debug.press_yes()
    if old_pin is not None:
        # enter old pin
        yield
        client.debug.input(old_pin)
    # enter new pin
    yield
    client.debug.input(new_pin)
    # repeat new pin
    yield
    client.debug.input(new_pin)


if __name__ == "__main__":
    wirelink = get_device()
    client = TrezorClientDebugLink(wirelink)
    client.open()

    i = 0

    last_pin = None

    while True:
        # set private field
        device.apply_settings(client, use_passphrase=True)
        assert client.features.passphrase_protection is True
        device.apply_settings(client, use_passphrase=False)
        assert client.features.passphrase_protection is False

        # set public field
        label = "".join(
예제 #30
0
def main():
    parser = argparse.ArgumentParser(description="Trezor initializer")

    parser.add_argument("--trezor-path",
                        dest="trezor_path",
                        default=None,
                        help="Trezor device path")
    parser.add_argument("--trezor-idx",
                        dest="trezor_idx",
                        default=None,
                        help="Trezor path idx")
    parser.add_argument("--mnemonic-idx",
                        dest="mnemonic_idx",
                        default=0,
                        type=int,
                        help="Trezor mnemonic index (testing indices)")
    parser.add_argument("--mnemonic",
                        dest="mnemonic",
                        default=None,
                        help="Trezor mnemonic")
    parser.add_argument("--pin",
                        dest="pin",
                        default="",
                        help="Trezor PIN protection")
    parser.add_argument("--label",
                        dest="label",
                        default="",
                        help="Trezor label - on display")
    parser.add_argument("--language",
                        dest="language",
                        default="english",
                        help="Seed language")
    parser.add_argument(
        "--passphrase",
        dest="passphrase",
        default=False,
        action="store_const",
        const=True,
        help="Enable passphrase",
    )
    parser.add_argument(
        "--debug",
        dest="debug",
        default=False,
        action="store_const",
        const=True,
        help="Debug",
    )
    args = parser.parse_args()

    mnemonic12 = (
        "alcohol woman abuse must during monitor noble actual mixed trade anger aisle"
    )
    mnemonic24 = (
        "permit universe parent weapon amused modify essay borrow tobacco budget walnut "
        "lunch consider gallery ride amazing frog forget treat market chapter velvet useless topple"
    )

    debug_mode = args.debug
    if args.trezor_path:
        path = args.trezor_path
    elif args.trezor_idx:
        path = "bridge:web01" if args.trezor_idx == "usb" else "udp:127.0.0.1:21324"
    else:
        path = os.environ.get("TREZOR_PATH", "bridge:web01")

    mnemonic = mnemonic24 if args.mnemonic_idx == 1 else mnemonic12
    if args.mnemonic:
        mnemonic = mnemonic

    wirelink = get_transport(path)
    client = (TrezorClientDebugLink(wirelink)
              if debug_mode else TrezorClient(wirelink, ui=ui.ClickUI))
    client.transport.session_begin()

    device.wipe(client)
    debuglink.load_device_by_mnemonic(
        client=client,
        mnemonic=mnemonic,
        pin=args.pin,
        passphrase_protection=args.passphrase,
        label=args.label,
        language=args.language,
    )

    client.transport.session_end()
    client.close()