Example #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()
Example #2
0
    def test_load_device(self, client):
        with client:
            client.set_expected_responses(
                [proto.ButtonRequest(), proto.Success(), proto.Features()]
            )
            debuglink.load_device_by_mnemonic(
                client,
                "this is mnemonic",
                "1234",
                True,
                "label",
                "english",
                skip_checksum=True,
            )

        with pytest.raises(TrezorFailure):
            # This must fail, because device is already initialized
            # Using direct call because `load_device_by_mnemonic` has its own check
            client.call(
                proto.LoadDevice(
                    mnemonics="this is mnemonic",
                    pin="1234",
                    passphrase_protection=True,
                    language="english",
                    label="label",
                    skip_checksum=True,
                )
            )
    def test_sd_protect(self, client):

        # Disabling SD protection should fail
        with pytest.raises(TrezorFailure):
            device.sd_protect(client, proto.SdProtectOperationType.DISABLE)

        # Enable SD protection
        device.sd_protect(client, proto.SdProtectOperationType.ENABLE)

        # Enabling SD protection should fail
        with pytest.raises(TrezorFailure):
            device.sd_protect(client, proto.SdProtectOperationType.ENABLE)

        # Wipe
        device.wipe(client)
        debuglink.load_device_by_mnemonic(
            client,
            mnemonic=MNEMONIC12,
            pin="",
            passphrase_protection=False,
            label="test",
        )

        # Enable SD protection
        device.sd_protect(client, proto.SdProtectOperationType.ENABLE)

        # Refresh SD protection
        device.sd_protect(client, proto.SdProtectOperationType.REFRESH)

        # Disable SD protection
        device.sd_protect(client, proto.SdProtectOperationType.DISABLE)

        # Refreshing SD protection should fail
        with pytest.raises(TrezorFailure):
            device.sd_protect(client, proto.SdProtectOperationType.REFRESH)
Example #4
0
    def test_load_device(self):
        with self.client:
            self.client.set_expected_responses(
                [proto.ButtonRequest(),
                 proto.Success(),
                 proto.Features()])
            debuglink.load_device_by_mnemonic(
                self.client,
                "this is mnemonic",
                "1234",
                True,
                "label",
                "english",
                skip_checksum=True,
            )

        # This must fail, because device is already initialized
        with pytest.raises(Exception):
            debuglink.load_device_by_mnemonic(
                self.client,
                "this is mnemonic",
                "1234",
                True,
                "label",
                "english",
                skip_checksum=True,
            )
Example #5
0
def test_upgrade_load_pin(gen, tag):
    PIN = "1234"

    def asserts(client):
        assert client.features.pin_protection
        assert not client.features.passphrase_protection
        assert client.features.initialized
        assert client.features.label == LABEL
        client.use_pin_sequence([PIN])
        assert btc.get_address(client, "Bitcoin", PATH) == ADDRESS

    with EmulatorWrapper(gen, tag) as emu:
        debuglink.load_device_by_mnemonic(
            emu.client,
            mnemonic=MNEMONIC,
            pin=PIN,
            passphrase_protection=False,
            label=LABEL,
            language=LANGUAGE,
        )
        device_id = emu.client.features.device_id
        asserts(emu.client)
        storage = emu.get_storage()

    with EmulatorWrapper(gen, storage=storage) as emu:
        assert device_id == emu.client.features.device_id
        asserts(emu.client)
        assert emu.client.features.language == LANGUAGE
def test_upgrade_load(gen, from_tag, to_tag):
    def asserts(tag, client):
        assert not client.features.pin_protection
        assert not client.features.passphrase_protection
        assert client.features.initialized
        assert client.features.label == LABEL
        assert client.features.language == LANGUAGE
        assert btc.get_address(client, "Bitcoin", PATH) == ADDRESS

    with EmulatorWrapper(gen, from_tag) as emu:
        debuglink.load_device_by_mnemonic(
            emu.client,
            mnemonic=MNEMONIC,
            pin="",
            passphrase_protection=False,
            label=LABEL,
            language=LANGUAGE,
        )
        device_id = emu.client.features.device_id
        asserts(from_tag, emu.client)
        storage = emu.storage()

    with EmulatorWrapper(gen, to_tag, storage=storage) as emu:
        assert device_id == emu.client.features.device_id
        asserts(to_tag, emu.client)
    def test_load_device(self):
        with self.client:
            self.client.set_expected_responses(
                [proto.ButtonRequest(), proto.Success(), proto.Features()]
            )
            debuglink.load_device_by_mnemonic(
                self.client,
                "this is mnemonic",
                "1234",
                True,
                "label",
                "english",
                skip_checksum=True,
            )

        # This must fail, because device is already initialized
        with pytest.raises(Exception):
            debuglink.load_device_by_mnemonic(
                self.client,
                "this is mnemonic",
                "1234",
                True,
                "label",
                "english",
                skip_checksum=True,
            )
Example #8
0
 def test_load_device_slip39_advanced(self, client):
     debuglink.load_device_by_mnemonic(
         client,
         mnemonic=MNEMONIC_SLIP39_ADVANCED_20,
         pin="",
         passphrase_protection=False,
         label="test",
     )
     assert client.features.backup_type == BackupType.Slip39_Advanced
Example #9
0
 def test_load_device_slip39_basic(self, client):
     debuglink.load_device_by_mnemonic(
         client,
         mnemonic=MNEMONIC_SLIP39_BASIC_20_3of6,
         pin="",
         passphrase_protection=False,
         label="test",
     )
     assert client.features.backup_type == BackupType.Slip39_Basic
Example #10
0
 def wrapper(client, *args, **kwargs):
     debuglink.load_device_by_mnemonic(
         client,
         mnemonic=mnemonic,
         pin=pin,
         passphrase_protection=passphrase,
         label="test",
         language="english",
     )
     return function(client, *args, **kwargs)
Example #11
0
 def wrapper(client, *args, **kwargs):
     debuglink.load_device_by_mnemonic(
         client,
         mnemonic=mnemonic,
         pin=pin,
         passphrase_protection=passphrase,
         label="test",
         language="english",
     )
     return function(client, *args, **kwargs)
 def test_mnemonic(self, client):
     debuglink.load_device_by_mnemonic(
         client,
         mnemonic=MNEMONIC12,
         pin="",
         passphrase_protection=False,
         label="test",
     )
     mnemonic = client.debug.state().mnemonic_secret
     assert mnemonic == self.mnemonic12.encode()
Example #13
0
 def _setup_mnemonic(self, mnemonic=None, pin="", passphrase=False):
     if mnemonic is None:
         mnemonic = TrezorTest.mnemonic12
     debuglink.load_device_by_mnemonic(
         self.client,
         mnemonic=mnemonic,
         pin=pin,
         passphrase_protection=passphrase,
         label="test",
         language="english",
     )
Example #14
0
 def wrapper(client, *args, **kwargs):
     debuglink.load_device_by_mnemonic(
         client,
         mnemonic=mnemonic,
         pin=pin,
         passphrase_protection=passphrase,
         label="test",
         language="english",
     )
     if TREZOR_VERSION > 1 and passphrase:
         apply_settings(client, passphrase_source=PASSPHRASE_ON_HOST)
     return function(*args, client=client, **kwargs)
 def test_ripple_get_address_other(self):
     # data from https://github.com/you21979/node-ripple-bip32/blob/master/test/test.js
     debuglink.load_device_by_mnemonic(
         self.client,
         mnemonic="armed bundle pudding lazy strategy impulse where identify submit weekend physical antenna flight social acoustic absurd whip snack decide blur unfold fiction pumpkin athlete",
         pin="",
         passphrase_protection=False,
         label="test",
         language="english",
     )
     address = get_address(self.client, parse_path("m/44'/144'/0'/0/0"))
     assert address == "r4ocGE47gm4G4LkA9mriVHQqzpMLBTgnTY"
     address = get_address(self.client, parse_path("m/44'/144'/0'/0/1"))
     assert address == "rUt9ULSrUvfCmke8HTFU1szbmFpWzVbBXW"
 def test_ripple_get_address_other(self):
     # data from https://github.com/you21979/node-ripple-bip32/blob/master/test/test.js
     debuglink.load_device_by_mnemonic(
         self.client,
         mnemonic="armed bundle pudding lazy strategy impulse where identify submit weekend physical antenna flight social acoustic absurd whip snack decide blur unfold fiction pumpkin athlete",
         pin="",
         passphrase_protection=False,
         label="test",
         language="english",
     )
     address = get_address(self.client, parse_path("m/44'/144'/0'/0/0"))
     assert address == "r4ocGE47gm4G4LkA9mriVHQqzpMLBTgnTY"
     address = get_address(self.client, parse_path("m/44'/144'/0'/0/1"))
     assert address == "rUt9ULSrUvfCmke8HTFU1szbmFpWzVbBXW"
Example #17
0
 def _setup_mnemonic(self, mnemonic=None, pin="", passphrase=False):
     if mnemonic is None:
         mnemonic = TrezorTest.mnemonic12
     debuglink.load_device_by_mnemonic(
         self.client,
         mnemonic=mnemonic,
         pin=pin,
         passphrase_protection=passphrase,
         label="test",
         language="english",
     )
     if conftest.TREZOR_VERSION > 1 and passphrase:
         device.apply_settings(self.client,
                               passphrase_source=PASSPHRASE_ON_HOST)
    def test_load_device_1(self, client):
        debuglink.load_device_by_mnemonic(
            client,
            mnemonic=MNEMONIC12,
            pin="",
            passphrase_protection=False,
            label="test",
        )
        state = client.debug.state()
        assert state.mnemonic_secret == MNEMONIC12.encode()
        assert state.pin is None
        assert state.passphrase_protection is False

        address = btc.get_address(client, "Bitcoin", [])
        assert address == "1EfKbQupktEMXf4gujJ9kCFo83k1iMqwqK"
Example #19
0
 def _setup_mnemonic(self, mnemonic=None, pin="", passphrase=False, lock=True):
     if mnemonic is None:
         mnemonic = TrezorTest.mnemonic12
     debuglink.load_device_by_mnemonic(
         self.client,
         mnemonic=mnemonic,
         pin=pin,
         passphrase_protection=passphrase,
         label="test",
         language="english",
     )
     if conftest.TREZOR_VERSION == 1 and lock:
         # remove cached PIN (introduced via load_device)
         self.client.clear_session()
     if conftest.TREZOR_VERSION > 1 and passphrase:
         device.apply_settings(self.client, passphrase_source=PASSPHRASE_ON_HOST)
Example #20
0
 def _setup_mnemonic(self, mnemonic=None, pin="", passphrase=False, lock=True):
     if mnemonic is None:
         mnemonic = TrezorTest.mnemonic12
     debuglink.load_device_by_mnemonic(
         self.client,
         mnemonic=mnemonic,
         pin=pin,
         passphrase_protection=passphrase,
         label="test",
         language="english",
     )
     if conftest.TREZOR_VERSION == 1 and lock:
         # remove cached PIN (introduced via load_device)
         self.client.clear_session()
     if conftest.TREZOR_VERSION > 1 and passphrase:
         device.apply_settings(self.client, passphrase_source=PASSPHRASE_ON_HOST)
Example #21
0
    def test_load_device_2(self, client):
        debuglink.load_device_by_mnemonic(
            client,
            mnemonic=MNEMONIC12,
            pin="1234",
            passphrase_protection=True,
            label="test",
        )
        client.set_passphrase("passphrase")
        state = client.debug.state()
        assert state.mnemonic_secret == MNEMONIC12.encode()
        assert state.pin == "1234"
        assert state.passphrase_protection is True

        address = btc.get_address(client, "Bitcoin", [])
        assert address == "15fiTDFwZd2kauHYYseifGi9daH2wniDHH"
    def test_tron_getaddress(self):
        debuglink.load_device_by_mnemonic(
            self.client,
            mnemonic=
            "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",
            pin="",
            passphrase_protection=False,
            label="test",
            language="english",
        )

        assert (tron.get_address(self.client, parse_path("m/44'/195'/0'/0/0"))
                == "TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH")
        assert (tron.get_address(self.client, parse_path("m/44'/195'/1'/0/0"))
                == "TLrpNTBuCpGMrB9TyVwgEhNVRhtWEQPHh4")
        assert (tron.get_address(self.client, parse_path("m/44'/195'/2'/0/0"))
                == "TZJ9qkoxUB1SGdbtChgAjUphBmkJwAeBaW")
        assert (tron.get_address(self.client, parse_path("m/44'/195'/1'/0/1"))
                == "TUT9qMmtJtnjJhpazPaLraWSTaThhBpWyR")
Example #23
0
def test_upgrade_wipe_code(gen, tag):
    PIN = "1234"
    WIPE_CODE = "4321"

    def asserts(client):
        assert client.features.pin_protection
        assert not client.features.passphrase_protection
        assert client.features.initialized
        assert client.features.label == LABEL
        client.use_pin_sequence([PIN])
        assert btc.get_address(client, "Bitcoin", PATH) == ADDRESS

    with EmulatorWrapper(gen, tag) as emu:
        debuglink.load_device_by_mnemonic(
            emu.client,
            mnemonic=MNEMONIC,
            pin=PIN,
            passphrase_protection=False,
            label=LABEL,
            language=LANGUAGE,
        )

        # Set wipe code.
        emu.client.use_pin_sequence([PIN, WIPE_CODE, WIPE_CODE])
        device.change_wipe_code(emu.client)

        device_id = emu.client.features.device_id
        asserts(emu.client)
        storage = emu.get_storage()

    with EmulatorWrapper(gen, storage=storage) as emu:
        assert device_id == emu.client.features.device_id
        asserts(emu.client)
        assert emu.client.features.language == LANGUAGE

        # Check that wipe code is set by changing the PIN to it.
        emu.client.use_pin_sequence([PIN, WIPE_CODE, WIPE_CODE])
        with pytest.raises(
                exceptions.TrezorFailure,
                match="The new PIN must be different from your wipe code",
        ):
            return device.change_pin(emu.client)
Example #24
0
    def test_stellar_get_address_sep(self):
        # data from https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0005.md
        debuglink.load_device_by_mnemonic(
            self.client,
            mnemonic=
            "illness spike retreat truth genius clock brain pass fit cave bargain toe",
            pin="",
            passphrase_protection=False,
            label="test",
            language="english",
        )

        address = stellar.get_address(self.client,
                                      parse_path(stellar.DEFAULT_BIP32_PATH))
        assert address == "GDRXE2BQUC3AZNPVFSCEZ76NJ3WWL25FYFK6RGZGIEKWE4SOOHSUJUJ6"

        address = stellar.get_address(self.client,
                                      parse_path("m/44h/148h/1h"),
                                      show_display=True)
        assert address == "GBAW5XGWORWVFE2XTJYDTLDHXTY2Q2MO73HYCGB3XMFMQ562Q2W2GJQX"
    def test_stellar_get_address_sep(self):
        # data from https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0005.md
        debuglink.load_device_by_mnemonic(
            self.client,
            mnemonic="illness spike retreat truth genius clock brain pass fit cave bargain toe",
            pin="",
            passphrase_protection=False,
            label="test",
            language="english",
        )

        address = stellar.get_address(
            self.client, parse_path(stellar.DEFAULT_BIP32_PATH)
        )
        assert address == "GDRXE2BQUC3AZNPVFSCEZ76NJ3WWL25FYFK6RGZGIEKWE4SOOHSUJUJ6"

        address = stellar.get_address(
            self.client, parse_path("m/44h/148h/1h"), show_display=True
        )
        assert address == "GBAW5XGWORWVFE2XTJYDTLDHXTY2Q2MO73HYCGB3XMFMQ562Q2W2GJQX"
Example #26
0
def load_client():
    try:
        client = get_device()
    except RuntimeError:
        request.session.shouldstop = "No debuggable Trezor is available"
        pytest.fail("No debuggable Trezor is available")

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

    client.open()
    return client
Example #27
0
    def reinit_trezor(self):
        self.deinit()
        path = self.get_trezor_path()
        is_debug = not int(os.getenv('TREZOR_NDEBUG', 0))
        self.creds = self.get_trezor_creds(0)
        self.trezor_proxy = tmanager.Trezor(path=path, debug=is_debug)
        self.agent = agent_lite.Agent(self.trezor_proxy,
                                      network_type=monero.NetworkTypes.TESTNET)

        client = self.trezor_proxy.client
        if is_debug:
            client.open()
            device.wipe(client)
            debuglink.load_device_by_mnemonic(
                client=client,
                mnemonic=self.get_trezor_mnemonics()[0],
                pin="",
                passphrase_protection=False,
                label="ph4test",
                language="english",
            )
Example #28
0
def test_wipe(client):
    # Enable SD protection
    device.sd_protect(client, Op.ENABLE)
    assert client.features.sd_protection is True

    # Wipe device (this wipes internal storage)
    device.wipe(client)
    assert client.features.sd_protection is False

    # Restore device to working status
    debuglink.load_device_by_mnemonic(
        client, mnemonic=MNEMONIC12, pin=None, passphrase_protection=False, label="test"
    )
    assert client.features.sd_protection is False

    # Enable SD protection
    device.sd_protect(client, Op.ENABLE)
    assert client.features.sd_protection is True

    # Refresh SD protection
    device.sd_protect(client, Op.REFRESH)
Example #29
0
def test_upgrade_u2f(gen, tag):
    """Check U2F counter stayed the same after an upgrade."""
    with EmulatorWrapper(gen, tag) as emu:
        debuglink.load_device_by_mnemonic(
            emu.client,
            mnemonic=MNEMONIC,
            pin="",
            passphrase_protection=False,
            label=LABEL,
        )

        success = fido.set_counter(emu.client, 10)
        assert "U2F counter set" in success

        counter = fido.get_next_counter(emu.client)
        assert counter == 11
        storage = emu.get_storage()

    with EmulatorWrapper(gen, storage=storage) as emu:
        counter = fido.get_next_counter(emu.client)
        assert counter == 12
    def test_load_device_2(self, client):
        debuglink.load_device_by_mnemonic(
            client,
            mnemonic=MNEMONIC12,
            pin="1234",
            passphrase_protection=True,
            label="test",
        )
        if client.features.model == "T":
            device.apply_settings(client, passphrase_source=PASSPHRASE_ON_HOST)
        client.set_passphrase("passphrase")
        state = client.debug.state()
        assert state.mnemonic_secret == MNEMONIC12.encode()

        if client.features.model == "1":
            # we do not send PIN in DebugLinkState in Core
            assert state.pin == "1234"
        assert state.passphrase_protection is True

        address = btc.get_address(client, "Bitcoin", [])
        assert address == "15fiTDFwZd2kauHYYseifGi9daH2wniDHH"
Example #31
0
def client(request):
    client = get_device()
    wipe_device(client)

    client.open()

    # fmt: off
    setup_params = dict(
        uninitialized=False,
        mnemonic=" ".join(["all"] * 12),
        pin=None,
        passphrase=False,
    )
    # fmt: on

    marker = request.node.get_closest_marker("setup_client")
    if marker:
        setup_params.update(marker.kwargs)

    if not setup_params["uninitialized"]:
        if setup_params["pin"] is True:
            setup_params["pin"] = "1234"

        debuglink.load_device_by_mnemonic(
            client,
            mnemonic=setup_params["mnemonic"],
            pin=setup_params["pin"],
            passphrase_protection=setup_params["passphrase"],
            label="test",
            language="english",
        )
        client.clear_session()
        if setup_params["passphrase"] and client.features.model != "1":
            apply_settings(client, passphrase_source=PASSPHRASE_ON_HOST)

    yield client
    client.close()
Example #32
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
    def test_load_device_utf(self, client):
        words_nfkd = u"Pr\u030ci\u0301s\u030cerne\u030c z\u030clut\u030couc\u030cky\u0301 ku\u030an\u030c u\u0301pe\u030cl d\u030ca\u0301belske\u0301 o\u0301dy za\u0301ker\u030cny\u0301 uc\u030cen\u030c be\u030cz\u030ci\u0301 pode\u0301l zo\u0301ny u\u0301lu\u030a"
        words_nfc = u"P\u0159\xed\u0161ern\u011b \u017elu\u0165ou\u010dk\xfd k\u016f\u0148 \xfap\u011bl \u010f\xe1belsk\xe9 \xf3dy z\xe1ke\u0159n\xfd u\u010de\u0148 b\u011b\u017e\xed pod\xe9l z\xf3ny \xfal\u016f"
        words_nfkc = u"P\u0159\xed\u0161ern\u011b \u017elu\u0165ou\u010dk\xfd k\u016f\u0148 \xfap\u011bl \u010f\xe1belsk\xe9 \xf3dy z\xe1ke\u0159n\xfd u\u010de\u0148 b\u011b\u017e\xed pod\xe9l z\xf3ny \xfal\u016f"
        words_nfd = u"Pr\u030ci\u0301s\u030cerne\u030c z\u030clut\u030couc\u030cky\u0301 ku\u030an\u030c u\u0301pe\u030cl d\u030ca\u0301belske\u0301 o\u0301dy za\u0301ker\u030cny\u0301 uc\u030cen\u030c be\u030cz\u030ci\u0301 pode\u0301l zo\u0301ny u\u0301lu\u030a"

        passphrase_nfkd = (
            u"Neuve\u030cr\u030citelne\u030c bezpec\u030cne\u0301 hesli\u0301c\u030cko"
        )
        passphrase_nfc = (
            u"Neuv\u011b\u0159iteln\u011b bezpe\u010dn\xe9 hesl\xed\u010dko")
        passphrase_nfkc = (
            u"Neuv\u011b\u0159iteln\u011b bezpe\u010dn\xe9 hesl\xed\u010dko")
        passphrase_nfd = (
            u"Neuve\u030cr\u030citelne\u030c bezpec\u030cne\u0301 hesli\u0301c\u030cko"
        )

        device.wipe(client)
        debuglink.load_device_by_mnemonic(
            client,
            mnemonic=words_nfkd,
            pin="",
            passphrase_protection=True,
            label="test",
            language="english",
            skip_checksum=True,
        )
        if client.features.model == "T":
            device.apply_settings(client, passphrase_source=PASSPHRASE_ON_HOST)
        client.set_passphrase(passphrase_nfkd)
        address_nfkd = btc.get_address(client, "Bitcoin", [])

        device.wipe(client)
        debuglink.load_device_by_mnemonic(
            client,
            mnemonic=words_nfc,
            pin="",
            passphrase_protection=True,
            label="test",
            language="english",
            skip_checksum=True,
        )
        if client.features.model == "T":
            device.apply_settings(client, passphrase_source=PASSPHRASE_ON_HOST)
        client.set_passphrase(passphrase_nfc)
        address_nfc = btc.get_address(client, "Bitcoin", [])

        device.wipe(client)
        debuglink.load_device_by_mnemonic(
            client,
            mnemonic=words_nfkc,
            pin="",
            passphrase_protection=True,
            label="test",
            language="english",
            skip_checksum=True,
        )
        if client.features.model == "T":
            device.apply_settings(client, passphrase_source=PASSPHRASE_ON_HOST)
        client.set_passphrase(passphrase_nfkc)
        address_nfkc = btc.get_address(client, "Bitcoin", [])

        device.wipe(client)
        debuglink.load_device_by_mnemonic(
            client,
            mnemonic=words_nfd,
            pin="",
            passphrase_protection=True,
            label="test",
            language="english",
            skip_checksum=True,
        )
        if client.features.model == "T":
            device.apply_settings(client, passphrase_source=PASSPHRASE_ON_HOST)
        client.set_passphrase(passphrase_nfd)
        address_nfd = btc.get_address(client, "Bitcoin", [])

        assert address_nfkd == address_nfc
        assert address_nfkd == address_nfkc
        assert address_nfkd == address_nfd
Example #34
0
def client(request):
    """Client fixture.

    Every test function that requires a client instance will get it from here.
    If we can't connect to a debuggable device, the test will fail.
    If 'skip_t2' is used and TT is connected, the test is skipped. Vice versa with T1
    and 'skip_t1'.

    The client instance is wiped and preconfigured with "all all all..." mnemonic, no
    password and no pin. It is possible to customize this with the `setup_client`
    marker.

    To specify a custom mnemonic and/or custom pin and/or enable passphrase:

    @pytest.mark.setup_client(mnemonic=MY_MNEMONIC, pin="9999", passphrase=True)

    To receive a client instance that was not initialized:

    @pytest.mark.setup_client(uninitialized=True)
    """
    try:
        client = get_device()
    except RuntimeError:
        pytest.fail("No debuggable Trezor is available")

    if request.node.get_closest_marker(
            "skip_t2") and client.features.model == "T":
        pytest.skip("Test excluded on Trezor T")
    if request.node.get_closest_marker(
            "skip_t1") and client.features.model == "1":
        pytest.skip("Test excluded on Trezor 1")

    if (request.node.get_closest_marker("sd_card")
            and not client.features.sd_card_present):
        raise RuntimeError("This test requires SD card.\n"
                           "To skip all such tests, run:\n"
                           "  pytest -m 'not sd_card' <test path>")

    wipe_device(client)

    # fmt: off
    setup_params = dict(
        uninitialized=False,
        mnemonic=" ".join(["all"] * 12),
        pin=None,
        passphrase=False,
    )
    # fmt: on

    marker = request.node.get_closest_marker("setup_client")
    if marker:
        setup_params.update(marker.kwargs)

    if not setup_params["uninitialized"]:
        if setup_params["pin"] is True:
            setup_params["pin"] = "1234"

        debuglink.load_device_by_mnemonic(
            client,
            mnemonic=setup_params["mnemonic"],
            pin=setup_params["pin"],
            passphrase_protection=setup_params["passphrase"],
            label="test",
            language="english",
        )
        client.clear_session()
        if setup_params["passphrase"] and client.features.model != "1":
            apply_settings(client, passphrase_source=PASSPHRASE_ON_HOST)

    client.open()
    yield client
    client.close()
    def test_load_device_utf(self):
        words_nfkd = u"Pr\u030ci\u0301s\u030cerne\u030c z\u030clut\u030couc\u030cky\u0301 ku\u030an\u030c u\u0301pe\u030cl d\u030ca\u0301belske\u0301 o\u0301dy za\u0301ker\u030cny\u0301 uc\u030cen\u030c be\u030cz\u030ci\u0301 pode\u0301l zo\u0301ny u\u0301lu\u030a"
        words_nfc = u"P\u0159\xed\u0161ern\u011b \u017elu\u0165ou\u010dk\xfd k\u016f\u0148 \xfap\u011bl \u010f\xe1belsk\xe9 \xf3dy z\xe1ke\u0159n\xfd u\u010de\u0148 b\u011b\u017e\xed pod\xe9l z\xf3ny \xfal\u016f"
        words_nfkc = u"P\u0159\xed\u0161ern\u011b \u017elu\u0165ou\u010dk\xfd k\u016f\u0148 \xfap\u011bl \u010f\xe1belsk\xe9 \xf3dy z\xe1ke\u0159n\xfd u\u010de\u0148 b\u011b\u017e\xed pod\xe9l z\xf3ny \xfal\u016f"
        words_nfd = u"Pr\u030ci\u0301s\u030cerne\u030c z\u030clut\u030couc\u030cky\u0301 ku\u030an\u030c u\u0301pe\u030cl d\u030ca\u0301belske\u0301 o\u0301dy za\u0301ker\u030cny\u0301 uc\u030cen\u030c be\u030cz\u030ci\u0301 pode\u0301l zo\u0301ny u\u0301lu\u030a"

        passphrase_nfkd = (
            u"Neuve\u030cr\u030citelne\u030c bezpec\u030cne\u0301 hesli\u0301c\u030cko"
        )
        passphrase_nfc = (
            u"Neuv\u011b\u0159iteln\u011b bezpe\u010dn\xe9 hesl\xed\u010dko"
        )
        passphrase_nfkc = (
            u"Neuv\u011b\u0159iteln\u011b bezpe\u010dn\xe9 hesl\xed\u010dko"
        )
        passphrase_nfd = (
            u"Neuve\u030cr\u030citelne\u030c bezpec\u030cne\u0301 hesli\u0301c\u030cko"
        )

        device.wipe(self.client)
        debuglink.load_device_by_mnemonic(
            self.client,
            mnemonic=words_nfkd,
            pin="",
            passphrase_protection=True,
            label="test",
            language="english",
            skip_checksum=True,
        )
        self.client.set_passphrase(passphrase_nfkd)
        address_nfkd = btc.get_address(self.client, "Bitcoin", [])

        device.wipe(self.client)
        debuglink.load_device_by_mnemonic(
            self.client,
            mnemonic=words_nfc,
            pin="",
            passphrase_protection=True,
            label="test",
            language="english",
            skip_checksum=True,
        )
        self.client.set_passphrase(passphrase_nfc)
        address_nfc = btc.get_address(self.client, "Bitcoin", [])

        device.wipe(self.client)
        debuglink.load_device_by_mnemonic(
            self.client,
            mnemonic=words_nfkc,
            pin="",
            passphrase_protection=True,
            label="test",
            language="english",
            skip_checksum=True,
        )
        self.client.set_passphrase(passphrase_nfkc)
        address_nfkc = btc.get_address(self.client, "Bitcoin", [])

        device.wipe(self.client)
        debuglink.load_device_by_mnemonic(
            self.client,
            mnemonic=words_nfd,
            pin="",
            passphrase_protection=True,
            label="test",
            language="english",
            skip_checksum=True,
        )
        self.client.set_passphrase(passphrase_nfd)
        address_nfd = btc.get_address(self.client, "Bitcoin", [])

        assert address_nfkd == address_nfc
        assert address_nfkd == address_nfkc
        assert address_nfkd == address_nfd
Example #36
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