From 1820f529fc94dfd82f2e6cf1bfcb9afa3d3b6c5d Mon Sep 17 00:00:00 2001 From: matejcik Date: Mon, 21 May 2018 14:28:53 +0200 Subject: [PATCH 01/37] trezorlib: shuffling things from client --- trezorctl | 16 ++-- trezorlib/client.py | 85 +++++-------------- .../test_msg_getpublickey_curve.py | 2 +- .../tests/device_tests/test_msg_signtx.py | 3 +- .../device_tests/test_msg_signtx_bcash.py | 4 +- .../device_tests/test_msg_signtx_bgold.py | 3 +- .../device_tests/test_msg_signtx_segwit.py | 3 +- trezorlib/tests/device_tests/test_multisig.py | 2 +- .../tests/device_tests/test_op_return.py | 3 +- .../tests/device_tests/test_protect_call.py | 4 +- trezorlib/tools.py | 63 ++++++++++++++ 11 files changed, 102 insertions(+), 86 deletions(-) diff --git a/trezorctl b/trezorctl index 37f5032ae7..2e85c79674 100755 --- a/trezorctl +++ b/trezorctl @@ -30,7 +30,7 @@ import logging import os import sys -from trezorlib.client import TrezorClient, CallException +from trezorlib.client import TrezorClient from trezorlib.transport import get_transport, enumerate_devices from trezorlib import coins from trezorlib import log @@ -250,12 +250,12 @@ def set_homescreen(connect, filename): elif filename.endswith('.toif'): img = open(filename, 'rb').read() if img[:8] != b'TOIf\x90\x00\x90\x00': - raise CallException(proto.FailureType.DataError, 'File is not a TOIF file with size of 144x144') + raise tools.CallException(proto.FailureType.DataError, 'File is not a TOIF file with size of 144x144') else: from PIL import Image im = Image.open(filename) if im.size != (128, 64): - raise CallException(proto.FailureType.DataError, 'Wrong size of the image') + raise tools.CallException(proto.FailureType.DataError, 'Wrong size of the image') im = im.convert('1') pix = im.load() img = bytearray(1024) @@ -297,7 +297,7 @@ def wipe_device(connect, bootloader): try: return connect().wipe_device() - except CallException as e: + except tools.CallException as e: click.echo('Action failed: {} {}'.format(*e.args)) sys.exit(3) @@ -314,7 +314,7 @@ def wipe_device(connect, bootloader): @click.pass_obj def load_device(connect, mnemonic, expand, xprv, pin, passphrase_protection, label, ignore_checksum, slip0014): if not mnemonic and not xprv and not slip0014: - raise CallException(proto.FailureType.DataError, 'Please provide mnemonic or xprv') + raise tools.CallException(proto.FailureType.DataError, 'Please provide mnemonic or xprv') client = connect() if mnemonic: @@ -474,7 +474,7 @@ def firmware_update(connect, filename, url, version, skip_check, fingerprint): try: return client.firmware_update(fp=io.BytesIO(fp)) - except CallException as e: + except tools.CallException as e: if e.args[0] in (proto.FailureType.FirmwareError, proto.FailureType.ActionCancelled): click.echo("Update aborted on device.") else: @@ -806,7 +806,7 @@ def ethereum_sign_tx(connect, host, chain_id, address, value, gas_limit, gas_pri if ' ' in value: value, unit = value.split(' ', 1) if unit.lower() not in ether_units: - raise CallException(proto.Failure.DataError, 'Unrecognized ether unit %r' % unit) + raise tools.CallException(proto.Failure.DataError, 'Unrecognized ether unit %r' % unit) value = int(value) * ether_units[unit.lower()] else: value = int(value) @@ -815,7 +815,7 @@ def ethereum_sign_tx(connect, host, chain_id, address, value, gas_limit, gas_pri if ' ' in gas_price: gas_price, unit = gas_price.split(' ', 1) if unit.lower() not in ether_units: - raise CallException(proto.Failure.DataError, 'Unrecognized gas price unit %r' % unit) + raise tools.CallException(proto.Failure.DataError, 'Unrecognized gas price unit %r' % unit) gas_price = int(gas_price) * ether_units[unit.lower()] else: gas_price = int(gas_price) diff --git a/trezorlib/client.py b/trezorlib/client.py index e8cc4d67a0..fbf44cd3b0 100644 --- a/trezorlib/client.py +++ b/trezorlib/client.py @@ -31,8 +31,8 @@ from . import messages as proto from . import tools from . import mapping from . import nem -from . import protobuf from . import stellar +from .tools import CallException, field, expect from .debuglink import DebugLink if sys.version_info.major < 3: @@ -79,69 +79,26 @@ def get_buttonrequest_value(code): return [k for k in dir(proto.ButtonRequestType) if getattr(proto.ButtonRequestType, k) == code][0] -class CallException(Exception): +class PinException(tools.CallException): pass -class PinException(CallException): - pass +class MovedTo: + """Deprecation redirector for methods that were formerly part of TrezorClient""" + def __init__(self, where): + self.where = where + self.name = where.__module__ + '.' + where.__name__ + def _deprecated_redirect(self, client, *args, **kwargs): + """Redirector for a deprecated method on TrezorClient""" + warnings.warn("Function has been moved to %s" % self.name, DeprecationWarning, stacklevel=2) + return self.where(client, *args, **kwargs) -class field: - # Decorator extracts single value from - # protobuf object. If the field is not - # present, raises an exception. - def __init__(self, field): - self.field = field - - def __call__(self, f): - @functools.wraps(f) - def wrapped_f(*args, **kwargs): - ret = f(*args, **kwargs) - return getattr(ret, self.field) - return wrapped_f - - -class expect: - # Decorator checks if the method - # returned one of expected protobuf messages - # or raises an exception - def __init__(self, *expected): - self.expected = expected - - def __call__(self, f): - @functools.wraps(f) - def wrapped_f(*args, **kwargs): - ret = f(*args, **kwargs) - if not isinstance(ret, self.expected): - raise RuntimeError("Got %s, expected %s" % (ret.__class__, self.expected)) - return ret - return wrapped_f - - -def session(f): - # Decorator wraps a BaseClient method - # with session activation / deactivation - @functools.wraps(f) - def wrapped_f(*args, **kwargs): - __tracebackhide__ = True # pytest traceback hiding - this function won't appear in tracebacks - client = args[0] - client.transport.session_begin() - try: - return f(*args, **kwargs) - finally: - client.transport.session_end() - return wrapped_f - - -def normalize_nfc(txt): - ''' - Normalize message to NFC and return bytes suitable for protobuf. - This seems to be bitcoin-qt standard of doing things. - ''' - if isinstance(txt, bytes): - txt = txt.decode('utf-8') - return unicodedata.normalize('NFC', txt).encode('utf-8') + def __get__(self, instance, cls): + if instance is None: + return self._deprecated_redirect + else: + return functools.partial(self._deprecated_redirect, instance) class BaseClient(object): @@ -158,13 +115,13 @@ class BaseClient(object): def cancel(self): self.transport.write(proto.Cancel()) - @session + @tools.session def call_raw(self, msg): __tracebackhide__ = True # pytest traceback hiding - this function won't appear in tracebacks self.transport.write(msg) return self.transport.read() - @session + @tools.session def call(self, msg): resp = self.call_raw(msg) handler_name = "callback_%s" % resp.__class__.__name__ @@ -183,7 +140,7 @@ class BaseClient(object): proto.FailureType.PinCancelled, proto.FailureType.PinExpected): raise PinException(msg.code, msg.message) - raise CallException(msg.code, msg.message) + raise tools.CallException(msg.code, msg.message) def register_message(self, msg): '''Allow application to register custom protobuf message type''' @@ -451,7 +408,7 @@ class ProtocolMixin(object): init_msg = proto.Initialize() if self.state is not None: init_msg.state = self.state - self.features = expect(proto.Features)(self.call)(init_msg) + self.features = tools.expect(proto.Features)(self.call)(init_msg) if str(self.features.vendor) not in self.VENDORS: raise RuntimeError("Unsupported device") @@ -465,7 +422,7 @@ class ProtocolMixin(object): @staticmethod def expand_path(n): - warnings.warn('expand_path is deprecated, use tools.parse_path', DeprecationWarning) + warnings.warn('expand_path is deprecated, use tools.parse_path', DeprecationWarning, stacklevel=2) return tools.parse_path(n) @expect(proto.PublicKey) diff --git a/trezorlib/tests/device_tests/test_msg_getpublickey_curve.py b/trezorlib/tests/device_tests/test_msg_getpublickey_curve.py index 489b4d20ca..a6d9550ea7 100644 --- a/trezorlib/tests/device_tests/test_msg_getpublickey_curve.py +++ b/trezorlib/tests/device_tests/test_msg_getpublickey_curve.py @@ -18,7 +18,7 @@ from binascii import hexlify import pytest from .common import TrezorTest -from trezorlib.client import CallException +from trezorlib.tools import CallException class TestMsgGetpublickeyCurve(TrezorTest): diff --git a/trezorlib/tests/device_tests/test_msg_signtx.py b/trezorlib/tests/device_tests/test_msg_signtx.py index 0ea9529fb8..ec0dfecd00 100644 --- a/trezorlib/tests/device_tests/test_msg_signtx.py +++ b/trezorlib/tests/device_tests/test_msg_signtx.py @@ -21,9 +21,8 @@ from .common import TrezorTest from .conftest import TREZOR_VERSION from trezorlib import messages as proto -from trezorlib.client import CallException -from trezorlib.tools import parse_path from trezorlib.tx_api import TxApiInsight +from trezorlib.tools import parse_path, CallException TxApiTestnet = TxApiInsight("insight_testnet") diff --git a/trezorlib/tests/device_tests/test_msg_signtx_bcash.py b/trezorlib/tests/device_tests/test_msg_signtx_bcash.py index 473fbada57..e9abbbac5f 100644 --- a/trezorlib/tests/device_tests/test_msg_signtx_bcash.py +++ b/trezorlib/tests/device_tests/test_msg_signtx_bcash.py @@ -21,9 +21,7 @@ from .common import TrezorTest from ..support.ckd_public import deserialize from trezorlib import coins from trezorlib import messages as proto -from trezorlib.client import CallException -from trezorlib.tools import parse_path - +from trezorlib.tools import parse_path, CallException TxApiBcash = coins.tx_api['Bcash'] diff --git a/trezorlib/tests/device_tests/test_msg_signtx_bgold.py b/trezorlib/tests/device_tests/test_msg_signtx_bgold.py index a6149addd5..27717a0938 100644 --- a/trezorlib/tests/device_tests/test_msg_signtx_bgold.py +++ b/trezorlib/tests/device_tests/test_msg_signtx_bgold.py @@ -21,8 +21,7 @@ from .common import TrezorTest from ..support.ckd_public import deserialize from trezorlib import coins from trezorlib import messages as proto -from trezorlib.client import CallException -from trezorlib.tools import parse_path +from trezorlib.tools import parse_path, CallException TxApiBitcoinGold = coins.tx_api["Bgold"] diff --git a/trezorlib/tests/device_tests/test_msg_signtx_segwit.py b/trezorlib/tests/device_tests/test_msg_signtx_segwit.py index f20d49cb2a..5c1f37efb7 100644 --- a/trezorlib/tests/device_tests/test_msg_signtx_segwit.py +++ b/trezorlib/tests/device_tests/test_msg_signtx_segwit.py @@ -22,9 +22,8 @@ from .conftest import TREZOR_VERSION from .common import TrezorTest from trezorlib import messages as proto -from trezorlib.client import CallException -from trezorlib.tools import parse_path from trezorlib.tx_api import TxApiInsight +from trezorlib.tools import parse_path, CallException TxApiTestnet = TxApiInsight("insight_testnet") diff --git a/trezorlib/tests/device_tests/test_multisig.py b/trezorlib/tests/device_tests/test_multisig.py index 3bbf903084..608d20925a 100644 --- a/trezorlib/tests/device_tests/test_multisig.py +++ b/trezorlib/tests/device_tests/test_multisig.py @@ -20,7 +20,7 @@ import pytest from .common import TrezorTest from ..support import ckd_public as bip32 from trezorlib import messages as proto -from trezorlib.client import CallException +from trezorlib.tools import CallException TXHASH_c6091a = unhexlify('c6091adf4c0c23982a35899a6e58ae11e703eacd7954f588ed4b9cdefc4dba52') diff --git a/trezorlib/tests/device_tests/test_op_return.py b/trezorlib/tests/device_tests/test_op_return.py index 4808585711..db13733946 100644 --- a/trezorlib/tests/device_tests/test_op_return.py +++ b/trezorlib/tests/device_tests/test_op_return.py @@ -20,8 +20,7 @@ import pytest from .common import TrezorTest from .conftest import TREZOR_VERSION from trezorlib import messages as proto -from trezorlib.client import CallException - +from trezorlib.tools import CallException TXHASH_d5f65e = unhexlify('d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882') diff --git a/trezorlib/tests/device_tests/test_protect_call.py b/trezorlib/tests/device_tests/test_protect_call.py index 447061643a..e1d73b2ab2 100644 --- a/trezorlib/tests/device_tests/test_protect_call.py +++ b/trezorlib/tests/device_tests/test_protect_call.py @@ -19,7 +19,9 @@ import pytest from .common import TrezorTest from trezorlib import messages as proto -from trezorlib.client import PinException, CallException +from trezorlib.client import PinException +from trezorlib.tools import CallException + # FIXME TODO Add passphrase tests diff --git a/trezorlib/tools.py b/trezorlib/tools.py index cd4c556720..43770d22e6 100644 --- a/trezorlib/tools.py +++ b/trezorlib/tools.py @@ -16,6 +16,7 @@ import hashlib import struct +import unicodedata from typing import NewType, List from .coins import slip44 @@ -159,3 +160,65 @@ def parse_path(nstr: str) -> Address: return list(str_to_harden(x) for x in n) except Exception: raise ValueError('Invalid BIP32 path', nstr) + + + +def normalize_nfc(txt): + ''' + Normalize message to NFC and return bytes suitable for protobuf. + This seems to be bitcoin-qt standard of doing things. + ''' + if isinstance(txt, bytes): + txt = txt.decode('utf-8') + return unicodedata.normalize('NFC', txt).encode('utf-8') + + +class CallException(Exception): + pass + + +class field: + # Decorator extracts single value from + # protobuf object. If the field is not + # present, raises an exception. + def __init__(self, field): + self.field = field + + def __call__(self, f): + @functools.wraps(f) + def wrapped_f(*args, **kwargs): + ret = f(*args, **kwargs) + return getattr(ret, self.field) + return wrapped_f + + +class expect: + # Decorator checks if the method + # returned one of expected protobuf messages + # or raises an exception + def __init__(self, *expected): + self.expected = expected + + def __call__(self, f): + @functools.wraps(f) + def wrapped_f(*args, **kwargs): + ret = f(*args, **kwargs) + if not isinstance(ret, self.expected): + raise RuntimeError("Got %s, expected %s" % (ret.__class__, self.expected)) + return ret + return wrapped_f + + +def session(f): + # Decorator wraps a BaseClient method + # with session activation / deactivation + @functools.wraps(f) + def wrapped_f(*args, **kwargs): + __tracebackhide__ = True # pytest traceback hiding - this function won't appear in tracebacks + client = args[0] + client.transport.session_begin() + try: + return f(*args, **kwargs) + finally: + client.transport.session_end() + return wrapped_f From f3a042db801135277376e65320b53674b517e4b3 Mon Sep 17 00:00:00 2001 From: matejcik Date: Wed, 13 Jun 2018 19:04:18 +0200 Subject: [PATCH 02/37] trezorlib: split out methods from ProtocolMixin --- trezorlib/btc.py | 170 +++++++++++ trezorlib/client.py | 673 ++++-------------------------------------- trezorlib/cosi.py | 18 ++ trezorlib/device.py | 208 +++++++++++++ trezorlib/ethereum.py | 69 +++++ trezorlib/firmware.py | 179 +++++++++++ trezorlib/lisk.py | 78 +++++ trezorlib/misc.py | 43 +++ trezorlib/nem.py | 25 ++ trezorlib/stellar.py | 47 +++ 10 files changed, 894 insertions(+), 616 deletions(-) create mode 100644 trezorlib/btc.py create mode 100644 trezorlib/ethereum.py create mode 100644 trezorlib/firmware.py create mode 100644 trezorlib/lisk.py create mode 100644 trezorlib/misc.py diff --git a/trezorlib/btc.py b/trezorlib/btc.py new file mode 100644 index 0000000000..fe981bf0cf --- /dev/null +++ b/trezorlib/btc.py @@ -0,0 +1,170 @@ +from . import messages as proto +from .tools import expect, field, CallException, normalize_nfc, session + +### Client functions ### + + +@expect(proto.PublicKey) +def get_public_node(client, n, ecdsa_curve_name=None, show_display=False, coin_name=None): + n = client._convert_prime(n) + return client.call(proto.GetPublicKey(address_n=n, ecdsa_curve_name=ecdsa_curve_name, show_display=show_display, coin_name=coin_name)) + + +@field('address') +@expect(proto.Address) +def get_address(client, coin_name, n, show_display=False, multisig=None, script_type=proto.InputScriptType.SPENDADDRESS): + n = client._convert_prime(n) + if multisig: + return client.call(proto.GetAddress(address_n=n, coin_name=coin_name, show_display=show_display, multisig=multisig, script_type=script_type)) + else: + return client.call(proto.GetAddress(address_n=n, coin_name=coin_name, show_display=show_display, script_type=script_type)) + + +@expect(proto.MessageSignature) +def sign_message(client, coin_name, n, message, script_type=proto.InputScriptType.SPENDADDRESS): + n = client._convert_prime(n) + message = normalize_nfc(message) + return client.call(proto.SignMessage(coin_name=coin_name, address_n=n, message=message, script_type=script_type)) + + +def verify_message(client, coin_name, address, signature, message): + message = normalize_nfc(message) + try: + resp = client.call(proto.VerifyMessage(address=address, signature=signature, message=message, coin_name=coin_name)) + except CallException as e: + resp = e + return isinstance(resp, proto.Success) + + +@expect(proto.EncryptedMessage) +def encrypt_message(client, pubkey, message, display_only, coin_name, n): + if coin_name and n: + n = client._convert_prime(n) + return client.call(proto.EncryptMessage(pubkey=pubkey, message=message, display_only=display_only, coin_name=coin_name, address_n=n)) + else: + return client.call(proto.EncryptMessage(pubkey=pubkey, message=message, display_only=display_only)) + + +@expect(proto.DecryptedMessage) +def decrypt_message(client, n, nonce, message, msg_hmac): + n = client._convert_prime(n) + return client.call(proto.DecryptMessage(address_n=n, nonce=nonce, message=message, hmac=msg_hmac)) + + +@session +def sign_tx(client, coin_name, inputs, outputs, version=None, lock_time=None, expiry=None, overwintered=None, debug_processor=None): + # start = time.time() + txes = client._prepare_sign_tx(inputs, outputs) + + # Prepare and send initial message + tx = proto.SignTx() + tx.inputs_count = len(inputs) + tx.outputs_count = len(outputs) + tx.coin_name = coin_name + if version is not None: + tx.version = version + if lock_time is not None: + tx.lock_time = lock_time + if expiry is not None: + tx.expiry = expiry + if overwintered is not None: + tx.overwintered = overwintered + res = client.call(tx) + + # Prepare structure for signatures + signatures = [None] * len(inputs) + serialized_tx = b'' + + counter = 0 + while True: + counter += 1 + + if isinstance(res, proto.Failure): + raise CallException("Signing failed") + + if not isinstance(res, proto.TxRequest): + raise CallException("Unexpected message") + + # If there's some part of signed transaction, let's add it + if res.serialized and res.serialized.serialized_tx: + # log("RECEIVED PART OF SERIALIZED TX (%d BYTES)" % len(res.serialized.serialized_tx)) + serialized_tx += res.serialized.serialized_tx + + if res.serialized and res.serialized.signature_index is not None: + if signatures[res.serialized.signature_index] is not None: + raise ValueError("Signature for index %d already filled" % res.serialized.signature_index) + signatures[res.serialized.signature_index] = res.serialized.signature + + if res.request_type == proto.RequestType.TXFINISHED: + # Device didn't ask for more information, finish workflow + break + + # Device asked for one more information, let's process it. + if not res.details.tx_hash: + current_tx = txes[None] + else: + current_tx = txes[bytes(res.details.tx_hash)] + + if res.request_type == proto.RequestType.TXMETA: + msg = proto.TransactionType() + msg.version = current_tx.version + msg.lock_time = current_tx.lock_time + msg.inputs_cnt = len(current_tx.inputs) + if res.details.tx_hash: + msg.outputs_cnt = len(current_tx.bin_outputs) + else: + msg.outputs_cnt = len(current_tx.outputs) + msg.extra_data_len = len(current_tx.extra_data) if current_tx.extra_data else 0 + res = client.call(proto.TxAck(tx=msg)) + continue + + elif res.request_type == proto.RequestType.TXINPUT: + msg = proto.TransactionType() + msg.inputs = [current_tx.inputs[res.details.request_index]] + if debug_processor is not None: + # msg needs to be deep copied so when it's modified + # the other messages stay intact + from copy import deepcopy + msg = deepcopy(msg) + # If debug_processor function is provided, + # pass thru it the request and prepared response. + # This is useful for tests, see test_msg_signtx + msg = debug_processor(res, msg) + + res = client.call(proto.TxAck(tx=msg)) + continue + + elif res.request_type == proto.RequestType.TXOUTPUT: + msg = proto.TransactionType() + if res.details.tx_hash: + msg.bin_outputs = [current_tx.bin_outputs[res.details.request_index]] + else: + msg.outputs = [current_tx.outputs[res.details.request_index]] + + if debug_processor is not None: + # msg needs to be deep copied so when it's modified + # the other messages stay intact + from copy import deepcopy + msg = deepcopy(msg) + # If debug_processor function is provided, + # pass thru it the request and prepared response. + # This is useful for tests, see test_msg_signtx + msg = debug_processor(res, msg) + + res = client.call(proto.TxAck(tx=msg)) + continue + + elif res.request_type == proto.RequestType.TXEXTRADATA: + o, l = res.details.extra_data_offset, res.details.extra_data_len + msg = proto.TransactionType() + msg.extra_data = current_tx.extra_data[o:o + l] + res = client.call(proto.TxAck(tx=msg)) + continue + + if None in signatures: + raise RuntimeError("Some signatures are missing!") + + # log("SIGNED IN %.03f SECONDS, CALLED %d MESSAGES, %d BYTES" % + # (time.time() - start, counter, len(serialized_tx))) + + return (signatures, serialized_tx) diff --git a/trezorlib/client.py b/trezorlib/client.py index fbf44cd3b0..c5604be3a1 100644 --- a/trezorlib/client.py +++ b/trezorlib/client.py @@ -28,11 +28,9 @@ import warnings from mnemonic import Mnemonic from . import messages as proto -from . import tools +from . import btc, cosi, device, ethereum, firmware, lisk, misc, nem, stellar from . import mapping -from . import nem -from . import stellar -from .tools import CallException, field, expect +from . import tools from .debuglink import DebugLink if sys.version_info.major < 3: @@ -412,9 +410,6 @@ class ProtocolMixin(object): if str(self.features.vendor) not in self.VENDORS: raise RuntimeError("Unsupported device") - def _get_local_entropy(self): - return os.urandom(32) - @staticmethod def _convert_prime(n: tools.Address) -> tools.Address: # Convert minus signs to uint32 with flag @@ -425,158 +420,8 @@ class ProtocolMixin(object): warnings.warn('expand_path is deprecated, use tools.parse_path', DeprecationWarning, stacklevel=2) return tools.parse_path(n) - @expect(proto.PublicKey) - def get_public_node(self, n, ecdsa_curve_name=None, show_display=False, coin_name=None): - n = self._convert_prime(n) - return self.call(proto.GetPublicKey(address_n=n, ecdsa_curve_name=ecdsa_curve_name, show_display=show_display, coin_name=coin_name)) - - @field('address') - @expect(proto.Address) - def get_address(self, coin_name, n, show_display=False, multisig=None, script_type=proto.InputScriptType.SPENDADDRESS): - n = self._convert_prime(n) - if multisig: - return self.call(proto.GetAddress(address_n=n, coin_name=coin_name, show_display=show_display, multisig=multisig, script_type=script_type)) - else: - return self.call(proto.GetAddress(address_n=n, coin_name=coin_name, show_display=show_display, script_type=script_type)) - - @field('address') - @expect(proto.EthereumAddress) - def ethereum_get_address(self, n, show_display=False, multisig=None): - n = self._convert_prime(n) - return self.call(proto.EthereumGetAddress(address_n=n, show_display=show_display)) - - @session - def ethereum_sign_tx(self, n, nonce, gas_price, gas_limit, to, value, data=None, chain_id=None, tx_type=None): - def int_to_big_endian(value): - return value.to_bytes((value.bit_length() + 7) // 8, 'big') - - n = self._convert_prime(n) - - msg = proto.EthereumSignTx( - address_n=n, - nonce=int_to_big_endian(nonce), - gas_price=int_to_big_endian(gas_price), - gas_limit=int_to_big_endian(gas_limit), - value=int_to_big_endian(value)) - - if to: - msg.to = to - - if data: - msg.data_length = len(data) - data, chunk = data[1024:], data[:1024] - msg.data_initial_chunk = chunk - - if chain_id: - msg.chain_id = chain_id - - if tx_type is not None: - msg.tx_type = tx_type - - response = self.call(msg) - - while response.data_length is not None: - data_length = response.data_length - data, chunk = data[data_length:], data[:data_length] - response = self.call(proto.EthereumTxAck(data_chunk=chunk)) - - return response.signature_v, response.signature_r, response.signature_s - - @expect(proto.EthereumMessageSignature) - def ethereum_sign_message(self, n, message): - n = self._convert_prime(n) - message = normalize_nfc(message) - return self.call(proto.EthereumSignMessage(address_n=n, message=message)) - - def ethereum_verify_message(self, address, signature, message): - message = normalize_nfc(message) - try: - resp = self.call(proto.EthereumVerifyMessage(address=address, signature=signature, message=message)) - except CallException as e: - resp = e - if isinstance(resp, proto.Success): - return True - return False - - # - # Lisk functions - # - - @field('address') - @expect(proto.LiskAddress) - def lisk_get_address(self, n, show_display=False): - n = self._convert_prime(n) - return self.call(proto.LiskGetAddress(address_n=n, show_display=show_display)) - - @expect(proto.LiskPublicKey) - def lisk_get_public_key(self, n, show_display=False): - n = self._convert_prime(n) - return self.call(proto.LiskGetPublicKey(address_n=n, show_display=show_display)) - - @expect(proto.LiskMessageSignature) - def lisk_sign_message(self, n, message): - n = self._convert_prime(n) - message = normalize_nfc(message) - return self.call(proto.LiskSignMessage(address_n=n, message=message)) - - def lisk_verify_message(self, pubkey, signature, message): - message = normalize_nfc(message) - try: - resp = self.call(proto.LiskVerifyMessage(signature=signature, public_key=pubkey, message=message)) - except CallException as e: - resp = e - return isinstance(resp, proto.Success) - - @expect(proto.LiskSignedTx) - def lisk_sign_tx(self, n, transaction): - n = self._convert_prime(n) - - def asset_to_proto(asset): - msg = proto.LiskTransactionAsset() - - if "votes" in asset: - msg.votes = asset["votes"] - if "data" in asset: - msg.data = asset["data"] - if "signature" in asset: - msg.signature = proto.LiskSignatureType() - msg.signature.public_key = binascii.unhexlify(asset["signature"]["publicKey"]) - if "delegate" in asset: - msg.delegate = proto.LiskDelegateType() - msg.delegate.username = asset["delegate"]["username"] - if "multisignature" in asset: - msg.multisignature = proto.LiskMultisignatureType() - msg.multisignature.min = asset["multisignature"]["min"] - msg.multisignature.life_time = asset["multisignature"]["lifetime"] - msg.multisignature.keys_group = asset["multisignature"]["keysgroup"] - return msg - - msg = proto.LiskTransactionCommon() - - msg.type = transaction["type"] - msg.fee = int(transaction["fee"]) # Lisk use strings for big numbers (javascript issue) - msg.amount = int(transaction["amount"]) # And we convert it back to number - msg.timestamp = transaction["timestamp"] - - if "recipientId" in transaction: - msg.recipient_id = transaction["recipientId"] - if "senderPublicKey" in transaction: - msg.sender_public_key = binascii.unhexlify(transaction["senderPublicKey"]) - if "requesterPublicKey" in transaction: - msg.requester_public_key = binascii.unhexlify(transaction["requesterPublicKey"]) - if "signature" in transaction: - msg.signature = binascii.unhexlify(transaction["signature"]) - - msg.asset = asset_to_proto(transaction["asset"]) - return self.call(proto.LiskSignTx(address_n=n, transaction=msg)) - - @field('entropy') - @expect(proto.Entropy) - def get_entropy(self, size): - return self.call(proto.GetEntropy(size=size)) - - @field('message') - @expect(proto.Success) + @tools.field('message') + @tools.expect(proto.Success) def ping(self, msg, button_protection=False, pin_protection=False, passphrase_protection=False): msg = proto.Ping(message=msg, button_protection=button_protection, @@ -587,128 +432,6 @@ class ProtocolMixin(object): def get_device_id(self): return self.features.device_id - @field('message') - @expect(proto.Success) - def apply_settings(self, label=None, language=None, use_passphrase=None, homescreen=None, passphrase_source=None, auto_lock_delay_ms=None): - settings = proto.ApplySettings() - if label is not None: - settings.label = label - if language: - settings.language = language - if use_passphrase is not None: - settings.use_passphrase = use_passphrase - if homescreen is not None: - settings.homescreen = homescreen - if passphrase_source is not None: - settings.passphrase_source = passphrase_source - if auto_lock_delay_ms is not None: - settings.auto_lock_delay_ms = auto_lock_delay_ms - - out = self.call(settings) - self.init_device() # Reload Features - return out - - @field('message') - @expect(proto.Success) - def apply_flags(self, flags): - out = self.call(proto.ApplyFlags(flags=flags)) - self.init_device() # Reload Features - return out - - @field('message') - @expect(proto.Success) - def clear_session(self): - return self.call(proto.ClearSession()) - - @field('message') - @expect(proto.Success) - def change_pin(self, remove=False): - ret = self.call(proto.ChangePin(remove=remove)) - self.init_device() # Re-read features - return ret - - @expect(proto.MessageSignature) - def sign_message(self, coin_name, n, message, script_type=proto.InputScriptType.SPENDADDRESS): - n = self._convert_prime(n) - message = normalize_nfc(message) - return self.call(proto.SignMessage(coin_name=coin_name, address_n=n, message=message, script_type=script_type)) - - @expect(proto.SignedIdentity) - def sign_identity(self, identity, challenge_hidden, challenge_visual, ecdsa_curve_name=None): - return self.call(proto.SignIdentity(identity=identity, challenge_hidden=challenge_hidden, challenge_visual=challenge_visual, ecdsa_curve_name=ecdsa_curve_name)) - - @expect(proto.ECDHSessionKey) - def get_ecdh_session_key(self, identity, peer_public_key, ecdsa_curve_name=None): - return self.call(proto.GetECDHSessionKey(identity=identity, peer_public_key=peer_public_key, ecdsa_curve_name=ecdsa_curve_name)) - - @expect(proto.CosiCommitment) - def cosi_commit(self, n, data): - n = self._convert_prime(n) - return self.call(proto.CosiCommit(address_n=n, data=data)) - - @expect(proto.CosiSignature) - def cosi_sign(self, n, data, global_commitment, global_pubkey): - n = self._convert_prime(n) - return self.call(proto.CosiSign(address_n=n, data=data, global_commitment=global_commitment, global_pubkey=global_pubkey)) - - @field('message') - @expect(proto.Success) - def set_u2f_counter(self, u2f_counter): - ret = self.call(proto.SetU2FCounter(u2f_counter=u2f_counter)) - return ret - - @field("address") - @expect(proto.NEMAddress) - def nem_get_address(self, n, network, show_display=False): - n = self._convert_prime(n) - return self.call(proto.NEMGetAddress(address_n=n, network=network, show_display=show_display)) - - @expect(proto.NEMSignedTx) - def nem_sign_tx(self, n, transaction): - n = self._convert_prime(n) - try: - msg = nem.create_sign_tx(transaction) - except ValueError as e: - raise CallException(e.args) - - assert msg.transaction is not None - msg.transaction.address_n = n - return self.call(msg) - - def verify_message(self, coin_name, address, signature, message): - message = normalize_nfc(message) - try: - resp = self.call(proto.VerifyMessage(address=address, signature=signature, message=message, coin_name=coin_name)) - except CallException as e: - resp = e - if isinstance(resp, proto.Success): - return True - return False - - @field('value') - @expect(proto.CipheredKeyValue) - def encrypt_keyvalue(self, n, key, value, ask_on_encrypt=True, ask_on_decrypt=True, iv=b''): - n = self._convert_prime(n) - return self.call(proto.CipherKeyValue(address_n=n, - key=key, - value=value, - encrypt=True, - ask_on_encrypt=ask_on_encrypt, - ask_on_decrypt=ask_on_decrypt, - iv=iv)) - - @field('value') - @expect(proto.CipheredKeyValue) - def decrypt_keyvalue(self, n, key, value, ask_on_encrypt=True, ask_on_decrypt=True, iv=b''): - n = self._convert_prime(n) - return self.call(proto.CipherKeyValue(address_n=n, - key=key, - value=value, - encrypt=False, - ask_on_encrypt=ask_on_encrypt, - ask_on_decrypt=ask_on_decrypt, - iv=iv)) - def _prepare_sign_tx(self, inputs, outputs): tx = proto.TransactionType() tx.inputs = inputs @@ -732,355 +455,73 @@ class ProtocolMixin(object): return txes - @session - def sign_tx(self, coin_name, inputs, outputs, version=None, lock_time=None, expiry=None, overwintered=None, debug_processor=None): + @tools.field('message') + @tools.expect(proto.Success) + def clear_session(self): + return self.call(proto.ClearSession()) - # start = time.time() - txes = self._prepare_sign_tx(inputs, outputs) - # Prepare and send initial message - tx = proto.SignTx() - tx.inputs_count = len(inputs) - tx.outputs_count = len(outputs) - tx.coin_name = coin_name - if version is not None: - tx.version = version - if lock_time is not None: - tx.lock_time = lock_time - if expiry is not None: - tx.expiry = expiry - if overwintered is not None: - tx.overwintered = overwintered - res = self.call(tx) + # Device functionality + self_test = MovedTo(device.self_test) - # Prepare structure for signatures - signatures = [None] * len(inputs) - serialized_tx = b'' + wipe_device = MovedTo(device.wipe_device) + recovery_device = MovedTo(device.recovery_device) + reset_device = MovedTo(device.reset_device) + backup_device = MovedTo(device.backup_device) - counter = 0 - while True: - counter += 1 + load_device_by_mnemonic = MovedTo(device.load_device_by_mnemonic) + load_device_by_xprv = MovedTo(device.load_device_by_xprv) - if isinstance(res, proto.Failure): - raise CallException("Signing failed") + set_u2f_counter = MovedTo(device.set_u2f_counter) - if not isinstance(res, proto.TxRequest): - raise CallException("Unexpected message") + apply_settings = MovedTo(device.apply_settings) + apply_flags = MovedTo(device.apply_flags) + change_pin = MovedTo(device.change_pin) - # If there's some part of signed transaction, let's add it - if res.serialized and res.serialized.serialized_tx: - # log("RECEIVED PART OF SERIALIZED TX (%d BYTES)" % len(res.serialized.serialized_tx)) - serialized_tx += res.serialized.serialized_tx + # Firmware functionality + firmware_update = MovedTo(firmware.update) - if res.serialized and res.serialized.signature_index is not None: - if signatures[res.serialized.signature_index] is not None: - raise ValueError("Signature for index %d already filled" % res.serialized.signature_index) - signatures[res.serialized.signature_index] = res.serialized.signature + # BTC-like functionality + get_public_node = MovedTo(btc.get_public_node) + get_address = MovedTo(btc.get_address) + sign_tx = MovedTo(btc.sign_tx) + sign_message = MovedTo(btc.sign_message) + verify_message = MovedTo(btc.verify_message) + encrypt_message = MovedTo(btc.encrypt_message) + decrypt_message = MovedTo(btc.decrypt_message) - if res.request_type == proto.RequestType.TXFINISHED: - # Device didn't ask for more information, finish workflow - break + # CoSi functionality + cosi_commit = MovedTo(cosi.commit) + cosi_sign = MovedTo(cosi.sign) - # Device asked for one more information, let's process it. - if not res.details.tx_hash: - current_tx = txes[None] - else: - current_tx = txes[bytes(res.details.tx_hash)] + # Ethereum functionality + ethereum_get_address = MovedTo(ethereum.get_address) + ethereum_sign_tx = MovedTo(ethereum.sign_tx) + ethereum_sign_message = MovedTo(ethereum.sign_message) + ethereum_verify_message = MovedTo(ethereum.verify_message) - if res.request_type == proto.RequestType.TXMETA: - msg = proto.TransactionType() - msg.version = current_tx.version - msg.lock_time = current_tx.lock_time - msg.inputs_cnt = len(current_tx.inputs) - if res.details.tx_hash: - msg.outputs_cnt = len(current_tx.bin_outputs) - else: - msg.outputs_cnt = len(current_tx.outputs) - msg.extra_data_len = len(current_tx.extra_data) if current_tx.extra_data else 0 - res = self.call(proto.TxAck(tx=msg)) - continue + # Lisk functionality + lisk_get_address = MovedTo(lisk.get_address) + lisk_get_public_key = MovedTo(lisk.get_public_key) + lisk_sign_message = MovedTo(lisk.sign_message) + lisk_verify_message = MovedTo(lisk.verify_message) + lisk_sign_tx = MovedTo(lisk.sign_tx) - elif res.request_type == proto.RequestType.TXINPUT: - msg = proto.TransactionType() - msg.inputs = [current_tx.inputs[res.details.request_index]] - if debug_processor is not None: - # msg needs to be deep copied so when it's modified - # the other messages stay intact - from copy import deepcopy - msg = deepcopy(msg) - # If debug_processor function is provided, - # pass thru it the request and prepared response. - # This is useful for tests, see test_msg_signtx - msg = debug_processor(res, msg) + # NEM functionality + nem_get_address = MovedTo(nem.get_address) + nem_sign_tx = MovedTo(nem.sign_tx) - res = self.call(proto.TxAck(tx=msg)) - continue + # Stellar functionality + stellar_get_public_key = MovedTo(stellar.get_public_key) + stellar_get_address = MovedTo(stellar.get_address) + stellar_sign_transaction = MovedTo(stellar.sign_tx) - elif res.request_type == proto.RequestType.TXOUTPUT: - msg = proto.TransactionType() - if res.details.tx_hash: - msg.bin_outputs = [current_tx.bin_outputs[res.details.request_index]] - else: - msg.outputs = [current_tx.outputs[res.details.request_index]] - - if debug_processor is not None: - # msg needs to be deep copied so when it's modified - # the other messages stay intact - from copy import deepcopy - msg = deepcopy(msg) - # If debug_processor function is provided, - # pass thru it the request and prepared response. - # This is useful for tests, see test_msg_signtx - msg = debug_processor(res, msg) - - res = self.call(proto.TxAck(tx=msg)) - continue - - elif res.request_type == proto.RequestType.TXEXTRADATA: - o, l = res.details.extra_data_offset, res.details.extra_data_len - msg = proto.TransactionType() - msg.extra_data = current_tx.extra_data[o:o + l] - res = self.call(proto.TxAck(tx=msg)) - continue - - if None in signatures: - raise RuntimeError("Some signatures are missing!") - - # log("SIGNED IN %.03f SECONDS, CALLED %d MESSAGES, %d BYTES" % - # (time.time() - start, counter, len(serialized_tx))) - - return (signatures, serialized_tx) - - @field('message') - @expect(proto.Success) - def wipe_device(self): - ret = self.call(proto.WipeDevice()) - self.init_device() - return ret - - @field('message') - @expect(proto.Success) - def recovery_device(self, word_count, passphrase_protection, pin_protection, label, language, type=proto.RecoveryDeviceType.ScrambledWords, expand=False, dry_run=False): - if self.features.initialized and not dry_run: - raise RuntimeError("Device is initialized already. Call wipe_device() and try again.") - - if word_count not in (12, 18, 24): - raise ValueError("Invalid word count. Use 12/18/24") - - self.recovery_matrix_first_pass = True - - self.expand = expand - if self.expand: - # optimization to load the wordlist once, instead of for each recovery word - self.mnemonic_wordlist = Mnemonic('english') - - res = self.call(proto.RecoveryDevice( - word_count=int(word_count), - passphrase_protection=bool(passphrase_protection), - pin_protection=bool(pin_protection), - label=label, - language=language, - enforce_wordlist=True, - type=type, - dry_run=dry_run)) - - self.init_device() - return res - - @field('message') - @expect(proto.Success) - @session - def reset_device(self, display_random, strength, passphrase_protection, pin_protection, label, language, u2f_counter=0, skip_backup=False): - if self.features.initialized: - raise RuntimeError("Device is initialized already. Call wipe_device() and try again.") - - # Begin with device reset workflow - msg = proto.ResetDevice(display_random=display_random, - strength=strength, - passphrase_protection=bool(passphrase_protection), - pin_protection=bool(pin_protection), - language=language, - label=label, - u2f_counter=u2f_counter, - skip_backup=bool(skip_backup)) - - resp = self.call(msg) - if not isinstance(resp, proto.EntropyRequest): - raise RuntimeError("Invalid response, expected EntropyRequest") - - external_entropy = self._get_local_entropy() - LOG.debug("Computer generated entropy: " + binascii.hexlify(external_entropy).decode()) - ret = self.call(proto.EntropyAck(entropy=external_entropy)) - self.init_device() - return ret - - @field('message') - @expect(proto.Success) - def backup_device(self): - ret = self.call(proto.BackupDevice()) - return ret - - @field('message') - @expect(proto.Success) - def load_device_by_mnemonic(self, mnemonic, pin, passphrase_protection, label, language='english', skip_checksum=False, expand=False): - # Convert mnemonic to UTF8 NKFD - mnemonic = Mnemonic.normalize_string(mnemonic) - - # Convert mnemonic to ASCII stream - mnemonic = mnemonic.encode('utf-8') - - m = Mnemonic('english') - - if expand: - mnemonic = m.expand(mnemonic) - - if not skip_checksum and not m.check(mnemonic): - raise ValueError("Invalid mnemonic checksum") - - if self.features.initialized: - raise RuntimeError("Device is initialized already. Call wipe_device() and try again.") - - resp = self.call(proto.LoadDevice(mnemonic=mnemonic, pin=pin, - passphrase_protection=passphrase_protection, - language=language, - label=label, - skip_checksum=skip_checksum)) - self.init_device() - return resp - - @field('message') - @expect(proto.Success) - def load_device_by_xprv(self, xprv, pin, passphrase_protection, label, language): - if self.features.initialized: - raise RuntimeError("Device is initialized already. Call wipe_device() and try again.") - - if xprv[0:4] not in ('xprv', 'tprv'): - raise ValueError("Unknown type of xprv") - - if not 100 < len(xprv) < 112: # yes this is correct in Python - raise ValueError("Invalid length of xprv") - - node = proto.HDNodeType() - data = binascii.hexlify(tools.b58decode(xprv, None)) - - if data[90:92] != b'00': - raise ValueError("Contain invalid private key") - - checksum = binascii.hexlify(tools.btc_hash(binascii.unhexlify(data[:156]))[:4]) - if checksum != data[156:]: - raise ValueError("Checksum doesn't match") - - # version 0488ade4 - # depth 00 - # fingerprint 00000000 - # child_num 00000000 - # chaincode 873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d508 - # privkey 00e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35 - # checksum e77e9d71 - - node.depth = int(data[8:10], 16) - node.fingerprint = int(data[10:18], 16) - node.child_num = int(data[18:26], 16) - node.chain_code = binascii.unhexlify(data[26:90]) - node.private_key = binascii.unhexlify(data[92:156]) # skip 0x00 indicating privkey - - resp = self.call(proto.LoadDevice(node=node, - pin=pin, - passphrase_protection=passphrase_protection, - language=language, - label=label)) - self.init_device() - return resp - - @session - def firmware_update(self, fp): - if self.features.bootloader_mode is False: - raise RuntimeError("Device must be in bootloader mode") - - data = fp.read() - - resp = self.call(proto.FirmwareErase(length=len(data))) - if isinstance(resp, proto.Failure) and resp.code == proto.FailureType.FirmwareError: - return False - - # TREZORv1 method - if isinstance(resp, proto.Success): - fingerprint = hashlib.sha256(data[256:]).hexdigest() - LOG.debug("Firmware fingerprint: " + fingerprint) - resp = self.call(proto.FirmwareUpload(payload=data)) - if isinstance(resp, proto.Success): - return True - elif isinstance(resp, proto.Failure) and resp.code == proto.FailureType.FirmwareError: - return False - raise RuntimeError("Unexpected result %s" % resp) - - # TREZORv2 method - if isinstance(resp, proto.FirmwareRequest): - import pyblake2 - while True: - payload = data[resp.offset:resp.offset + resp.length] - digest = pyblake2.blake2s(payload).digest() - resp = self.call(proto.FirmwareUpload(payload=payload, hash=digest)) - if isinstance(resp, proto.FirmwareRequest): - continue - elif isinstance(resp, proto.Success): - return True - elif isinstance(resp, proto.Failure) and resp.code == proto.FailureType.FirmwareError: - return False - raise RuntimeError("Unexpected result %s" % resp) - - raise RuntimeError("Unexpected message %s" % resp) - - @field('message') - @expect(proto.Success) - def self_test(self): - if self.features.bootloader_mode is False: - raise RuntimeError("Device must be in bootloader mode") - - return self.call(proto.SelfTest(payload=b'\x00\xFF\x55\xAA\x66\x99\x33\xCCABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\x00\xFF\x55\xAA\x66\x99\x33\xCC')) - - @field('public_key') - @expect(proto.StellarPublicKey) - def stellar_get_public_key(self, address_n, show_display=False): - return self.call(proto.StellarGetPublicKey(address_n=address_n, show_display=show_display)) - - @field('address') - @expect(proto.StellarAddress) - def stellar_get_address(self, address_n, show_display=False): - return self.call(proto.StellarGetAddress(address_n=address_n, show_display=show_display)) - - def stellar_sign_transaction(self, tx, operations, address_n, network_passphrase=None): - # default networkPassphrase to the public network - if network_passphrase is None: - network_passphrase = "Public Global Stellar Network ; September 2015" - - tx.network_passphrase = network_passphrase - tx.address_n = address_n - tx.num_operations = len(operations) - # Signing loop works as follows: - # - # 1. Start with tx (header information for the transaction) and operations (an array of operation protobuf messagess) - # 2. Send the tx header to the device - # 3. Receive a StellarTxOpRequest message - # 4. Send operations one by one until all operations have been sent. If there are more operations to sign, the device will send a StellarTxOpRequest message - # 5. The final message received will be StellarSignedTx which is returned from this method - resp = self.call(tx) - try: - while isinstance(resp, proto.StellarTxOpRequest): - resp = self.call(operations.pop(0)) - except IndexError: - # pop from empty list - raise CallException("Stellar.UnexpectedEndOfOperations", - "Reached end of operations without a signature.") from None - - if not isinstance(resp, proto.StellarSignedTx): - raise CallException(proto.FailureType.UnexpectedMessage, resp) - - if operations: - raise CallException("Stellar.UnprocessedOperations", - "Received a signature before processing all operations.") - - return resp + # Miscellaneous cryptography + get_entropy = MovedTo(misc.get_entropy) + sign_identity = MovedTo(misc.sign_identity) + get_ecdh_session_key = MovedTo(misc.get_ecdh_session_key) + encrypt_keyvalue = MovedTo(misc.encrypt_keyvalue) + decrypt_keyvalue = MovedTo(misc.decrypt_keyvalue) class TrezorClient(ProtocolMixin, TextUIMixin, BaseClient): diff --git a/trezorlib/cosi.py b/trezorlib/cosi.py index 4dc8f953e8..6ee9b90ac9 100644 --- a/trezorlib/cosi.py +++ b/trezorlib/cosi.py @@ -19,6 +19,9 @@ from functools import reduce import binascii from typing import Iterable, Tuple +from . import messages +from .tools import expect + from trezorlib import _ed25519 # XXX, these could be NewType's, but that would infect users of the cosi module with these types as well. @@ -86,3 +89,18 @@ def sign_with_privkey(digest: bytes, privkey: Ed25519PrivateKey, a = 2 ** (b - 2) + sum(2 ** i * _ed25519.bit(h, i) for i in range(3, b - 2)) S = (nonce + _ed25519.Hint(global_commit + global_pubkey + digest) * a) % _ed25519.l return Ed25519Signature(_ed25519.encodeint(S)) + + +### Client functions ### + + +@expect(messages.CosiCommitment) +def commit(client, n, data): + n = client._convert_prime(n) + return client.call(messages.CosiCommit(address_n=n, data=data)) + + +@expect(messages.CosiSignature) +def sign(client, n, data, global_commitment, global_pubkey): + n = client._convert_prime(n) + return client.call(messages.CosiSign(address_n=n, data=data, global_commitment=global_commitment, global_pubkey=global_pubkey)) diff --git a/trezorlib/device.py b/trezorlib/device.py index 6cbe7417f5..42a7411a5a 100644 --- a/trezorlib/device.py +++ b/trezorlib/device.py @@ -14,7 +14,14 @@ # You should have received a copy of the License along with this library. # If not, see . +import binascii +import os import warnings +from mnemonic import Mnemonic + +from . import messages as proto +from . import tools +from .tools import field, expect, session from .transport import enumerate_devices, get_transport @@ -35,3 +42,204 @@ class TrezorDevice: def find_by_path(cls, path): warnings.warn('TrezorDevice is deprecated.', DeprecationWarning) return get_transport(path, prefix_search=False) + + +@field('message') +@expect(proto.Success) +def apply_settings(client, label=None, language=None, use_passphrase=None, homescreen=None, passphrase_source=None, auto_lock_delay_ms=None): + settings = proto.ApplySettings() + if label is not None: + settings.label = label + if language: + settings.language = language + if use_passphrase is not None: + settings.use_passphrase = use_passphrase + if homescreen is not None: + settings.homescreen = homescreen + if passphrase_source is not None: + settings.passphrase_source = passphrase_source + if auto_lock_delay_ms is not None: + settings.auto_lock_delay_ms = auto_lock_delay_ms + + out = client.call(settings) + client.init_device() # Reload Features + return out + + +@field('message') +@expect(proto.Success) +def apply_flags(client, flags): + out = client.call(proto.ApplyFlags(flags=flags)) + client.init_device() # Reload Features + return out + + +@field('message') +@expect(proto.Success) +def change_pin(client, remove=False): + ret = client.call(proto.ChangePin(remove=remove)) + client.init_device() # Re-read features + return ret + + +@field('message') +@expect(proto.Success) +def set_u2f_counter(client, u2f_counter): + ret = client.call(proto.SetU2FCounter(u2f_counter=u2f_counter)) + return ret + + +@field('message') +@expect(proto.Success) +def wipe_device(client): + ret = client.call(proto.WipeDevice()) + client.init_device() + return ret + + +@field('message') +@expect(proto.Success) +def recovery_device(client, word_count, passphrase_protection, pin_protection, label, language, type=proto.RecoveryDeviceType.ScrambledWords, expand=False, dry_run=False): + if client.features.initialized and not dry_run: + raise RuntimeError("Device is initialized already. Call wipe_device() and try again.") + + if word_count not in (12, 18, 24): + raise ValueError("Invalid word count. Use 12/18/24") + + client.recovery_matrix_first_pass = True + + client.expand = expand + if client.expand: + # optimization to load the wordlist once, instead of for each recovery word + client.mnemonic_wordlist = Mnemonic('english') + + res = client.call(proto.RecoveryDevice( + word_count=int(word_count), + passphrase_protection=bool(passphrase_protection), + pin_protection=bool(pin_protection), + label=label, + language=language, + enforce_wordlist=True, + type=type, + dry_run=dry_run)) + + client.init_device() + return res + + +@field('message') +@expect(proto.Success) +@session +def reset_device(client, display_random, strength, passphrase_protection, pin_protection, label, language, u2f_counter=0, skip_backup=False): + if client.features.initialized: + raise RuntimeError("Device is initialized already. Call wipe_device() and try again.") + + # Begin with device reset workflow + msg = proto.ResetDevice(display_random=display_random, + strength=strength, + passphrase_protection=bool(passphrase_protection), + pin_protection=bool(pin_protection), + language=language, + label=label, + u2f_counter=u2f_counter, + skip_backup=bool(skip_backup)) + + resp = client.call(msg) + if not isinstance(resp, proto.EntropyRequest): + raise RuntimeError("Invalid response, expected EntropyRequest") + + external_entropy = os.urandom(32) + # LOG.debug("Computer generated entropy: " + binascii.hexlify(external_entropy).decode()) + ret = client.call(proto.EntropyAck(entropy=external_entropy)) + client.init_device() + return ret + + +@field('message') +@expect(proto.Success) +def backup_device(client): + ret = client.call(proto.BackupDevice()) + return ret + + +@field('message') +@expect(proto.Success) +def load_device_by_mnemonic(client, mnemonic, pin, passphrase_protection, label, language='english', skip_checksum=False, expand=False): + # Convert mnemonic to UTF8 NKFD + mnemonic = Mnemonic.normalize_string(mnemonic) + + # Convert mnemonic to ASCII stream + mnemonic = mnemonic.encode('utf-8') + + m = Mnemonic('english') + + if expand: + mnemonic = m.expand(mnemonic) + + if not skip_checksum and not m.check(mnemonic): + raise ValueError("Invalid mnemonic checksum") + + if client.features.initialized: + raise RuntimeError("Device is initialized already. Call wipe_device() and try again.") + + resp = client.call(proto.LoadDevice(mnemonic=mnemonic, pin=pin, + passphrase_protection=passphrase_protection, + language=language, + label=label, + skip_checksum=skip_checksum)) + client.init_device() + return resp + + +@field('message') +@expect(proto.Success) +def load_device_by_xprv(client, xprv, pin, passphrase_protection, label, language): + if client.features.initialized: + raise RuntimeError("Device is initialized already. Call wipe_device() and try again.") + + if xprv[0:4] not in ('xprv', 'tprv'): + raise ValueError("Unknown type of xprv") + + if not 100 < len(xprv) < 112: # yes this is correct in Python + raise ValueError("Invalid length of xprv") + + node = proto.HDNodeType() + data = binascii.hexlify(tools.b58decode(xprv, None)) + + if data[90:92] != b'00': + raise ValueError("Contain invalid private key") + + checksum = binascii.hexlify(tools.btc_hash(binascii.unhexlify(data[:156]))[:4]) + if checksum != data[156:]: + raise ValueError("Checksum doesn't match") + + # version 0488ade4 + # depth 00 + # fingerprint 00000000 + # child_num 00000000 + # chaincode 873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d508 + # privkey 00e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35 + # checksum e77e9d71 + + node.depth = int(data[8:10], 16) + node.fingerprint = int(data[10:18], 16) + node.child_num = int(data[18:26], 16) + node.chain_code = binascii.unhexlify(data[26:90]) + node.private_key = binascii.unhexlify(data[92:156]) # skip 0x00 indicating privkey + + resp = client.call(proto.LoadDevice(node=node, + pin=pin, + passphrase_protection=passphrase_protection, + language=language, + label=label)) + client.init_device() + return resp + + +@field('message') +@expect(proto.Success) +def self_test(client): + if client.features.bootloader_mode is False: + raise RuntimeError("Device must be in bootloader mode") + + return client.call(proto.SelfTest(payload=b'\x00\xFF\x55\xAA\x66\x99\x33\xCCABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\x00\xFF\x55\xAA\x66\x99\x33\xCC')) diff --git a/trezorlib/ethereum.py b/trezorlib/ethereum.py new file mode 100644 index 0000000000..963cce612f --- /dev/null +++ b/trezorlib/ethereum.py @@ -0,0 +1,69 @@ +from . import messages as proto +from .tools import field, expect, CallException, normalize_nfc, session + + +def int_to_big_endian(value): + return value.to_bytes((value.bit_length() + 7) // 8, 'big') + + +### Client functions ### + + +@field('address') +@expect(proto.EthereumAddress) +def get_address(client, n, show_display=False, multisig=None): + n = client._convert_prime(n) + return client.call(proto.EthereumGetAddress(address_n=n, show_display=show_display)) + + +@session +def sign_tx(client, n, nonce, gas_price, gas_limit, to, value, data=None, chain_id=None, tx_type=None): + n = client._convert_prime(n) + + msg = proto.EthereumSignTx( + address_n=n, + nonce=int_to_big_endian(nonce), + gas_price=int_to_big_endian(gas_price), + gas_limit=int_to_big_endian(gas_limit), + value=int_to_big_endian(value)) + + if to: + msg.to = to + + if data: + msg.data_length = len(data) + data, chunk = data[1024:], data[:1024] + msg.data_initial_chunk = chunk + + if chain_id: + msg.chain_id = chain_id + + if tx_type is not None: + msg.tx_type = tx_type + + response = client.call(msg) + + while response.data_length is not None: + data_length = response.data_length + data, chunk = data[data_length:], data[:data_length] + response = client.call(proto.EthereumTxAck(data_chunk=chunk)) + + return response.signature_v, response.signature_r, response.signature_s + + +@expect(proto.EthereumMessageSignature) +def sign_message(client, n, message): + n = client._convert_prime(n) + message = normalize_nfc(message) + return client.call(proto.EthereumSignMessage(address_n=n, message=message)) + + +def verify_message(client, address, signature, message): + message = normalize_nfc(message) + try: + resp = client.call(proto.EthereumVerifyMessage(address=address, signature=signature, message=message)) + except CallException as e: + resp = e + if isinstance(resp, proto.Success): + return True + return False diff --git a/trezorlib/firmware.py b/trezorlib/firmware.py new file mode 100644 index 0000000000..8f4a016934 --- /dev/null +++ b/trezorlib/firmware.py @@ -0,0 +1,179 @@ +import binascii +import construct as c +import hashlib +import pyblake2 + +from . import cosi +from . import messages as proto +from . import tools + + +Toif = c.Struct( + "magic" / c.Const(b"TOI"), + "format" / c.Enum(c.Byte, full_color=b"f", grayscale=b"g"), + "width" / c.Int16ul, + "height" / c.Int16ul, + "data" / c.Prefixed(c.Int32ul, c.GreedyBytes), +) + + +def bytes_not(data): + return bytes(~b & 0xff for b in data) + + +VendorTrust = c.Transformed(c.BitStruct( + "reserved" / c.Padding(9), + "show_vendor_string" / c.Flag, + "require_user_click" / c.Flag, + "red_background" / c.Flag, + "delay" / c.BitsInteger(4), +), bytes_not, 2, bytes_not, 2) + + +VendorHeader = c.Struct( + "_start_offset" / c.Tell, + "magic" / c.Const(b"TRZV"), + "_header_len" / c.Padding(4), + "expiry" / c.Int32ul, + "version" / c.Struct( + "major" / c.Int8ul, + "minor" / c.Int8ul, + ), + "vendor_sigs_required" / c.Int8ul, + "vendor_sigs_n" / c.Rebuild(c.Int8ul, c.len_(c.this.pubkeys)), + "vendor_trust" / VendorTrust, + "reserved" / c.Padding(14), + "pubkeys" / c.Bytes(32)[c.this.vendor_sigs_n], + "vendor_string" / c.Aligned(4, c.PascalString(c.Int8ul, "utf-8")), + "vendor_image" / Toif, + "_data_end_offset" / c.Tell, + + c.Padding(-(c.this._data_end_offset + 65) % 512), + "sigmask" / c.Byte, + "signature" / c.Bytes(64), + + "_end_offset" / c.Tell, + "header_len" / c.Pointer( + c.this._start_offset + 4, + c.Rebuild(c.Int32ul, c.this._end_offset - c.this._start_offset) + ), +) + + +VersionLong = c.Struct( + "major" / c.Int8ul, + "minor" / c.Int8ul, + "patch" / c.Int8ul, + "build" / c.Int8ul, +) + + +FirmwareHeader = c.Struct( + "_start_offset" / c.Tell, + "magic" / c.Const(b"TRZF"), + "_header_len" / c.Padding(4), + "expiry" / c.Int32ul, + "code_length" / c.Rebuild( + c.Int32ul, + lambda this: + len(this._.code) if "code" in this._ + else (this.code_length or 0)), + "version" / VersionLong, + "fix_version" / VersionLong, + "reserved" / c.Padding(8), + "hashes" / c.Bytes(32)[16], + + "reserved" / c.Padding(415), + "sigmask" / c.Byte, + "signature" / c.Bytes(64), + + "_end_offset" / c.Tell, + "header_len" / c.Pointer(c.this._start_offset + 4, c.Rebuild(c.Int32ul, c.this._end_offset - c.this._start_offset)), +) + + +Firmware = c.Struct( + "vendor_header" / VendorHeader, + "firmware_header" / FirmwareHeader, + "code" / c.Bytes(c.this.firmware_header.code_length), + c.Terminated, +) + + +def validate_firmware(filename): + with open(filename, "rb") as f: + data = f.read() + if data[:6] == b'54525a': + data = binascii.unhexlify(data) + + try: + fw = Firmware.parse(data) + except Exception as e: + raise ValueError("Invalid firmware image format") from e + + vendor = fw.vendor_header + header = fw.firmware_header + + print("Vendor header from {}, version {}.{}".format(vendor.vendor_string, vendor.version.major, vendor.version.minor)) + print("Firmware version {v.major}.{v.minor}.{v.patch} build {v.build}".format(v=header.version)) + + # rebuild header without signatures + stripped_header = header.copy() + stripped_header.sigmask = 0 + stripped_header.signature = b'\0' * 64 + header_bytes = FirmwareHeader.build(stripped_header) + digest = pyblake2.blake2s(header_bytes).digest() + + print("Fingerprint: {}".format(binascii.hexlify(digest).decode("ascii"))) + + global_pk = cosi.combine_keys(vendor.pubkeys[i] for i in range(8) if header.sigmask & (1 << i)) + + try: + cosi.verify(header.signature, digest, global_pk) + print("Signature OK") + except: + print("Signature FAILED") + raise + + +### Client functions ### + + +@tools.session +def update(client, fp): + if client.features.bootloader_mode is False: + raise RuntimeError("Device must be in bootloader mode") + + data = fp.read() + + resp = client.call(proto.FirmwareErase(length=len(data))) + if isinstance(resp, proto.Failure) and resp.code == proto.FailureType.FirmwareError: + return False + + # TREZORv1 method + if isinstance(resp, proto.Success): + fingerprint = hashlib.sha256(data[256:]).hexdigest() + # LOG.debug("Firmware fingerprint: " + fingerprint) + resp = client.call(proto.FirmwareUpload(payload=data)) + if isinstance(resp, proto.Success): + return True + elif isinstance(resp, proto.Failure) and resp.code == proto.FailureType.FirmwareError: + return False + raise RuntimeError("Unexpected result %s" % resp) + + # TREZORv2 method + if isinstance(resp, proto.FirmwareRequest): + import pyblake2 + while True: + payload = data[resp.offset:resp.offset + resp.length] + digest = pyblake2.blake2s(payload).digest() + resp = client.call(proto.FirmwareUpload(payload=payload, hash=digest)) + if isinstance(resp, proto.FirmwareRequest): + continue + elif isinstance(resp, proto.Success): + return True + elif isinstance(resp, proto.Failure) and resp.code == proto.FailureType.FirmwareError: + return False + raise RuntimeError("Unexpected result %s" % resp) + + raise RuntimeError("Unexpected message %s" % resp) diff --git a/trezorlib/lisk.py b/trezorlib/lisk.py new file mode 100644 index 0000000000..f5f9315c1f --- /dev/null +++ b/trezorlib/lisk.py @@ -0,0 +1,78 @@ +import binascii + +from . import messages as proto +from .tools import field, expect, CallException, normalize_nfc + + +@field('address') +@expect(proto.LiskAddress) +def get_address(client, n, show_display=False): + n = client._convert_prime(n) + return client.call(proto.LiskGetAddress(address_n=n, show_display=show_display)) + + +@expect(proto.LiskPublicKey) +def get_public_key(client, n, show_display=False): + n = client._convert_prime(n) + return client.call(proto.LiskGetPublicKey(address_n=n, show_display=show_display)) + + +@expect(proto.LiskMessageSignature) +def sign_message(client, n, message): + n = client._convert_prime(n) + message = normalize_nfc(message) + return client.call(proto.LiskSignMessage(address_n=n, message=message)) + + +def verify_message(client, pubkey, signature, message): + message = normalize_nfc(message) + try: + resp = client.call(proto.LiskVerifyMessage(signature=signature, public_key=pubkey, message=message)) + except CallException as e: + resp = e + return isinstance(resp, proto.Success) + + +def _asset_to_proto(asset): + msg = proto.LiskTransactionAsset() + + if "votes" in asset: + msg.votes = asset["votes"] + if "data" in asset: + msg.data = asset["data"] + if "signature" in asset: + msg.signature = proto.LiskSignatureType() + msg.signature.public_key = binascii.unhexlify(asset["signature"]["publicKey"]) + if "delegate" in asset: + msg.delegate = proto.LiskDelegateType() + msg.delegate.username = asset["delegate"]["username"] + if "multisignature" in asset: + msg.multisignature = proto.LiskMultisignatureType() + msg.multisignature.min = asset["multisignature"]["min"] + msg.multisignature.life_time = asset["multisignature"]["lifetime"] + msg.multisignature.keys_group = asset["multisignature"]["keysgroup"] + return msg + + +@expect(proto.LiskSignedTx) +def sign_tx(client, n, transaction): + n = client._convert_prime(n) + + msg = proto.LiskTransactionCommon() + + msg.type = transaction["type"] + msg.fee = int(transaction["fee"]) # Lisk use strings for big numbers (javascript issue) + msg.amount = int(transaction["amount"]) # And we convert it back to number + msg.timestamp = transaction["timestamp"] + + if "recipientId" in transaction: + msg.recipient_id = transaction["recipientId"] + if "senderPublicKey" in transaction: + msg.sender_public_key = binascii.unhexlify(transaction["senderPublicKey"]) + if "requesterPublicKey" in transaction: + msg.requester_public_key = binascii.unhexlify(transaction["requesterPublicKey"]) + if "signature" in transaction: + msg.signature = binascii.unhexlify(transaction["signature"]) + + msg.asset = _asset_to_proto(transaction["asset"]) + return client.call(proto.LiskSignTx(address_n=n, transaction=msg)) diff --git a/trezorlib/misc.py b/trezorlib/misc.py new file mode 100644 index 0000000000..4d543ccd52 --- /dev/null +++ b/trezorlib/misc.py @@ -0,0 +1,43 @@ +from . import messages as proto +from .tools import field, expect + + +@field('entropy') +@expect(proto.Entropy) +def get_entropy(client, size): + return client.call(proto.GetEntropy(size=size)) + + +@expect(proto.SignedIdentity) +def sign_identity(client, identity, challenge_hidden, challenge_visual, ecdsa_curve_name=None): + return client.call(proto.SignIdentity(identity=identity, challenge_hidden=challenge_hidden, challenge_visual=challenge_visual, ecdsa_curve_name=ecdsa_curve_name)) + +@expect(proto.ECDHSessionKey) +def get_ecdh_session_key(client, identity, peer_public_key, ecdsa_curve_name=None): + return client.call(proto.GetECDHSessionKey(identity=identity, peer_public_key=peer_public_key, ecdsa_curve_name=ecdsa_curve_name)) + + +@field('value') +@expect(proto.CipheredKeyValue) +def encrypt_keyvalue(client, n, key, value, ask_on_encrypt=True, ask_on_decrypt=True, iv=b''): + n = client._convert_prime(n) + return client.call(proto.CipherKeyValue(address_n=n, + key=key, + value=value, + encrypt=True, + ask_on_encrypt=ask_on_encrypt, + ask_on_decrypt=ask_on_decrypt, + iv=iv)) + +@field('value') +@expect(proto.CipheredKeyValue) +def decrypt_keyvalue(client, n, key, value, ask_on_encrypt=True, ask_on_decrypt=True, iv=b''): + n = client._convert_prime(n) + return client.call(proto.CipherKeyValue(address_n=n, + key=key, + value=value, + encrypt=False, + ask_on_encrypt=ask_on_encrypt, + ask_on_decrypt=ask_on_decrypt, + iv=iv)) + diff --git a/trezorlib/nem.py b/trezorlib/nem.py index 037aa3cb9c..570b47a636 100644 --- a/trezorlib/nem.py +++ b/trezorlib/nem.py @@ -17,6 +17,7 @@ import binascii import json from . import messages as proto +from .tools import expect, field, CallException TYPE_TRANSACTION_TRANSFER = 0x0101 TYPE_IMPORTANCE_TRANSFER = 0x0801 @@ -164,3 +165,27 @@ def create_sign_tx(transaction): raise ValueError("Unknown transaction type") return msg + + +### Client functions ### + + +@field("address") +@expect(proto.NEMAddress) +def get_address(client, n, network, show_display=False): + n = client._convert_prime(n) + return client.call(proto.NEMGetAddress(address_n=n, network=network, show_display=show_display)) + + +@expect(proto.NEMSignedTx) +def sign_tx(client, n, transaction): + n = client._convert_prime(n) + try: + msg = create_sign_tx(transaction) + except ValueError as e: + raise CallException(e.args) + + assert msg.transaction is not None + msg.transaction.address_n = n + return client.call(msg) + diff --git a/trezorlib/stellar.py b/trezorlib/stellar.py index 629d4b4206..7c05daf4ea 100644 --- a/trezorlib/stellar.py +++ b/trezorlib/stellar.py @@ -19,6 +19,7 @@ import struct import xdrlib from . import messages +from .tools import field, expect, CallException # Memo types MEMO_TYPE_NONE = 0 @@ -49,6 +50,7 @@ OP_BUMP_SEQUENCE = 11 DEFAULT_BIP32_PATH = "m/44h/148h/0h" # Stellar's BIP32 differs to Bitcoin's see https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0005.md +DEFAULT_NETWORK_PASSPHRASE = "Public Global Stellar Network ; September 2015" def address_from_public_key(pk_bytes): @@ -336,3 +338,48 @@ def _crc16_checksum(bytes): crc ^= polynomial return crc & 0xffff + + +### Client functions ### + + +@field('public_key') +@expect(messages.StellarPublicKey) +def get_public_key(client, address_n, show_display=False): + return client.call(messages.StellarGetPublicKey(address_n=address_n, show_display=show_display)) + + +@field('address') +@expect(messages.StellarAddress) +def get_address(client, address_n, show_display=False): + return client.call(messages.StellarGetAddress(address_n=address_n, show_display=show_display)) + + +def sign_tx(client, tx, operations, address_n, network_passphrase=DEFAULT_NETWORK_PASSPHRASE): + tx.network_passphrase = network_passphrase + tx.address_n = address_n + tx.num_operations = len(operations) + # Signing loop works as follows: + # + # 1. Start with tx (header information for the transaction) and operations (an array of operation protobuf messagess) + # 2. Send the tx header to the device + # 3. Receive a StellarTxOpRequest message + # 4. Send operations one by one until all operations have been sent. If there are more operations to sign, the device will send a StellarTxOpRequest message + # 5. The final message received will be StellarSignedTx which is returned from this method + resp = client.call(tx) + try: + while isinstance(resp, messages.StellarTxOpRequest): + resp = client.call(operations.pop(0)) + except IndexError: + # pop from empty list + raise CallException("Stellar.UnexpectedEndOfOperations", + "Reached end of operations without a signature.") from None + + if not isinstance(resp, messages.StellarSignedTx): + raise CallException(messages.FailureType.UnexpectedMessage, resp) + + if operations: + raise CallException("Stellar.UnprocessedOperations", + "Received a signature before processing all operations.") + + return resp From 46307cc4bae244acf8d4d100f71411bd684340e7 Mon Sep 17 00:00:00 2001 From: matejcik Date: Wed, 13 Jun 2018 19:04:36 +0200 Subject: [PATCH 03/37] trezorctl: use Stellar default network passphrase --- trezorctl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/trezorctl b/trezorctl index 2e85c79674..71afb30e13 100755 --- a/trezorctl +++ b/trezorctl @@ -1039,7 +1039,7 @@ def stellar_get_public_key(connect, address, show_display): @cli.command(help='Sign a base64-encoded transaction envelope') @click.option('-n', '--address', required=False, help="BIP32 path. Always use hardened paths and the m/44'/148'/ prefix", default=stellar.DEFAULT_BIP32_PATH) -@click.option('-n', '--network-passphrase', default='Public Global Stellar Network ; September 2015', required=False, help="Network passphrase (blank for public network). Testnet is: 'Test SDF Network ; September 2015'") +@click.option('-n', '--network-passphrase', default=stellar.DEFAULT_NETWORK_PASSPHRASE, required=False, help="Network passphrase (blank for public network). Testnet is: 'Test SDF Network ; September 2015'") @click.argument('b64envelope') @click.pass_obj def stellar_sign_transaction(connect, b64envelope, address, network_passphrase): From 23b58cc0cb12680663db53009a7134de3038a7ea Mon Sep 17 00:00:00 2001 From: matejcik Date: Wed, 13 Jun 2018 19:35:01 +0200 Subject: [PATCH 04/37] flake8: fix complaints --- .flake8 | 4 +++- trezorlib/client.py | 3 +-- trezorlib/device.py | 16 ++++++++-------- trezorlib/firmware.py | 2 +- trezorlib/misc.py | 27 ++++++++++++++------------- trezorlib/nem.py | 1 - trezorlib/tools.py | 1 - 7 files changed, 27 insertions(+), 27 deletions(-) diff --git a/.flake8 b/.flake8 index 5fd5447939..7d1af43a8a 100644 --- a/.flake8 +++ b/.flake8 @@ -19,4 +19,6 @@ ignore = # E722: do not use bare except E722, # E741: ambiguous variable name - E741 + E741, + ##### E266: too many leading '#' for block comment + E266, diff --git a/trezorlib/client.py b/trezorlib/client.py index c5604be3a1..940d993f13 100644 --- a/trezorlib/client.py +++ b/trezorlib/client.py @@ -460,7 +460,6 @@ class ProtocolMixin(object): def clear_session(self): return self.call(proto.ClearSession()) - # Device functionality self_test = MovedTo(device.self_test) @@ -516,7 +515,7 @@ class ProtocolMixin(object): stellar_get_address = MovedTo(stellar.get_address) stellar_sign_transaction = MovedTo(stellar.sign_tx) - # Miscellaneous cryptography + # Miscellaneous cryptographic functionality get_entropy = MovedTo(misc.get_entropy) sign_identity = MovedTo(misc.sign_identity) get_ecdh_session_key = MovedTo(misc.get_ecdh_session_key) diff --git a/trezorlib/device.py b/trezorlib/device.py index 42a7411a5a..df8a7cddfe 100644 --- a/trezorlib/device.py +++ b/trezorlib/device.py @@ -183,10 +183,10 @@ def load_device_by_mnemonic(client, mnemonic, pin, passphrase_protection, label, raise RuntimeError("Device is initialized already. Call wipe_device() and try again.") resp = client.call(proto.LoadDevice(mnemonic=mnemonic, pin=pin, - passphrase_protection=passphrase_protection, - language=language, - label=label, - skip_checksum=skip_checksum)) + passphrase_protection=passphrase_protection, + language=language, + label=label, + skip_checksum=skip_checksum)) client.init_device() return resp @@ -228,10 +228,10 @@ def load_device_by_xprv(client, xprv, pin, passphrase_protection, label, languag node.private_key = binascii.unhexlify(data[92:156]) # skip 0x00 indicating privkey resp = client.call(proto.LoadDevice(node=node, - pin=pin, - passphrase_protection=passphrase_protection, - language=language, - label=label)) + pin=pin, + passphrase_protection=passphrase_protection, + language=language, + label=label)) client.init_device() return resp diff --git a/trezorlib/firmware.py b/trezorlib/firmware.py index 8f4a016934..1072deae15 100644 --- a/trezorlib/firmware.py +++ b/trezorlib/firmware.py @@ -152,7 +152,7 @@ def update(client, fp): # TREZORv1 method if isinstance(resp, proto.Success): - fingerprint = hashlib.sha256(data[256:]).hexdigest() + # fingerprint = hashlib.sha256(data[256:]).hexdigest() # LOG.debug("Firmware fingerprint: " + fingerprint) resp = client.call(proto.FirmwareUpload(payload=data)) if isinstance(resp, proto.Success): diff --git a/trezorlib/misc.py b/trezorlib/misc.py index 4d543ccd52..c559453dd0 100644 --- a/trezorlib/misc.py +++ b/trezorlib/misc.py @@ -12,6 +12,7 @@ def get_entropy(client, size): def sign_identity(client, identity, challenge_hidden, challenge_visual, ecdsa_curve_name=None): return client.call(proto.SignIdentity(identity=identity, challenge_hidden=challenge_hidden, challenge_visual=challenge_visual, ecdsa_curve_name=ecdsa_curve_name)) + @expect(proto.ECDHSessionKey) def get_ecdh_session_key(client, identity, peer_public_key, ecdsa_curve_name=None): return client.call(proto.GetECDHSessionKey(identity=identity, peer_public_key=peer_public_key, ecdsa_curve_name=ecdsa_curve_name)) @@ -22,22 +23,22 @@ def get_ecdh_session_key(client, identity, peer_public_key, ecdsa_curve_name=Non def encrypt_keyvalue(client, n, key, value, ask_on_encrypt=True, ask_on_decrypt=True, iv=b''): n = client._convert_prime(n) return client.call(proto.CipherKeyValue(address_n=n, - key=key, - value=value, - encrypt=True, - ask_on_encrypt=ask_on_encrypt, - ask_on_decrypt=ask_on_decrypt, - iv=iv)) + key=key, + value=value, + encrypt=True, + ask_on_encrypt=ask_on_encrypt, + ask_on_decrypt=ask_on_decrypt, + iv=iv)) + @field('value') @expect(proto.CipheredKeyValue) def decrypt_keyvalue(client, n, key, value, ask_on_encrypt=True, ask_on_decrypt=True, iv=b''): n = client._convert_prime(n) return client.call(proto.CipherKeyValue(address_n=n, - key=key, - value=value, - encrypt=False, - ask_on_encrypt=ask_on_encrypt, - ask_on_decrypt=ask_on_decrypt, - iv=iv)) - + key=key, + value=value, + encrypt=False, + ask_on_encrypt=ask_on_encrypt, + ask_on_decrypt=ask_on_decrypt, + iv=iv)) diff --git a/trezorlib/nem.py b/trezorlib/nem.py index 570b47a636..4f7801fc3c 100644 --- a/trezorlib/nem.py +++ b/trezorlib/nem.py @@ -188,4 +188,3 @@ def sign_tx(client, n, transaction): assert msg.transaction is not None msg.transaction.address_n = n return client.call(msg) - diff --git a/trezorlib/tools.py b/trezorlib/tools.py index 43770d22e6..36f2358c7c 100644 --- a/trezorlib/tools.py +++ b/trezorlib/tools.py @@ -162,7 +162,6 @@ def parse_path(nstr: str) -> Address: raise ValueError('Invalid BIP32 path', nstr) - def normalize_nfc(txt): ''' Normalize message to NFC and return bytes suitable for protobuf. From 8f03bd01656794f0ff836492800894461cd9b35d Mon Sep 17 00:00:00 2001 From: matejcik Date: Thu, 14 Jun 2018 14:16:53 +0200 Subject: [PATCH 05/37] build: add Construct to requires, use package autodetection --- requirements.txt | 1 + setup.py | 1 + 2 files changed, 2 insertions(+) diff --git a/requirements.txt b/requirements.txt index ea29c3168a..f127fdc75d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,5 +4,6 @@ requests>=2.4.0 click>=6.2 pyblake2>=0.9.3 libusb1>=1.6.4 +construct>=2.9 pip>=6 typing>=3.0.0; python_version < '3.5' diff --git a/setup.py b/setup.py index 202b94a779..2ad32c9be0 100755 --- a/setup.py +++ b/setup.py @@ -20,6 +20,7 @@ install_requires = [ 'click>=6.2', 'pyblake2>=0.9.3', 'libusb1>=1.6.4', + 'construct>=2.9', ] CWD = os.path.dirname(os.path.realpath(__file__)) From 7e90e89e692bf406275bd45bf0d7885e07c9824a Mon Sep 17 00:00:00 2001 From: matejcik Date: Thu, 14 Jun 2018 14:57:20 +0200 Subject: [PATCH 06/37] client: get rid of TrezorClient._convert_prime --- trezorlib/btc.py | 5 ----- trezorlib/client.py | 5 ----- trezorlib/cosi.py | 2 -- trezorlib/ethereum.py | 4 ---- trezorlib/lisk.py | 5 ----- trezorlib/misc.py | 2 -- trezorlib/nem.py | 2 -- .../tests/device_tests/test_bip32_speed.py | 5 ++++- .../test_msg_ethereum_getaddress.py | 6 ++++-- .../tests/device_tests/test_msg_getaddress.py | 10 +++++----- .../device_tests/test_msg_getpublickey.py | 18 ++++++++++-------- .../test_msg_nem_signtx_mosaics_t2.py | 1 - 12 files changed, 23 insertions(+), 42 deletions(-) diff --git a/trezorlib/btc.py b/trezorlib/btc.py index fe981bf0cf..98502733ac 100644 --- a/trezorlib/btc.py +++ b/trezorlib/btc.py @@ -6,14 +6,12 @@ from .tools import expect, field, CallException, normalize_nfc, session @expect(proto.PublicKey) def get_public_node(client, n, ecdsa_curve_name=None, show_display=False, coin_name=None): - n = client._convert_prime(n) return client.call(proto.GetPublicKey(address_n=n, ecdsa_curve_name=ecdsa_curve_name, show_display=show_display, coin_name=coin_name)) @field('address') @expect(proto.Address) def get_address(client, coin_name, n, show_display=False, multisig=None, script_type=proto.InputScriptType.SPENDADDRESS): - n = client._convert_prime(n) if multisig: return client.call(proto.GetAddress(address_n=n, coin_name=coin_name, show_display=show_display, multisig=multisig, script_type=script_type)) else: @@ -22,7 +20,6 @@ def get_address(client, coin_name, n, show_display=False, multisig=None, script_ @expect(proto.MessageSignature) def sign_message(client, coin_name, n, message, script_type=proto.InputScriptType.SPENDADDRESS): - n = client._convert_prime(n) message = normalize_nfc(message) return client.call(proto.SignMessage(coin_name=coin_name, address_n=n, message=message, script_type=script_type)) @@ -39,7 +36,6 @@ def verify_message(client, coin_name, address, signature, message): @expect(proto.EncryptedMessage) def encrypt_message(client, pubkey, message, display_only, coin_name, n): if coin_name and n: - n = client._convert_prime(n) return client.call(proto.EncryptMessage(pubkey=pubkey, message=message, display_only=display_only, coin_name=coin_name, address_n=n)) else: return client.call(proto.EncryptMessage(pubkey=pubkey, message=message, display_only=display_only)) @@ -47,7 +43,6 @@ def encrypt_message(client, pubkey, message, display_only, coin_name, n): @expect(proto.DecryptedMessage) def decrypt_message(client, n, nonce, message, msg_hmac): - n = client._convert_prime(n) return client.call(proto.DecryptMessage(address_n=n, nonce=nonce, message=message, hmac=msg_hmac)) diff --git a/trezorlib/client.py b/trezorlib/client.py index 940d993f13..4d4780528d 100644 --- a/trezorlib/client.py +++ b/trezorlib/client.py @@ -410,11 +410,6 @@ class ProtocolMixin(object): if str(self.features.vendor) not in self.VENDORS: raise RuntimeError("Unsupported device") - @staticmethod - def _convert_prime(n: tools.Address) -> tools.Address: - # Convert minus signs to uint32 with flag - return [tools.H_(int(abs(x))) if x < 0 else x for x in n] - @staticmethod def expand_path(n): warnings.warn('expand_path is deprecated, use tools.parse_path', DeprecationWarning, stacklevel=2) diff --git a/trezorlib/cosi.py b/trezorlib/cosi.py index 6ee9b90ac9..73ca36d3c2 100644 --- a/trezorlib/cosi.py +++ b/trezorlib/cosi.py @@ -96,11 +96,9 @@ def sign_with_privkey(digest: bytes, privkey: Ed25519PrivateKey, @expect(messages.CosiCommitment) def commit(client, n, data): - n = client._convert_prime(n) return client.call(messages.CosiCommit(address_n=n, data=data)) @expect(messages.CosiSignature) def sign(client, n, data, global_commitment, global_pubkey): - n = client._convert_prime(n) return client.call(messages.CosiSign(address_n=n, data=data, global_commitment=global_commitment, global_pubkey=global_pubkey)) diff --git a/trezorlib/ethereum.py b/trezorlib/ethereum.py index 963cce612f..d0d16ce58f 100644 --- a/trezorlib/ethereum.py +++ b/trezorlib/ethereum.py @@ -12,14 +12,11 @@ def int_to_big_endian(value): @field('address') @expect(proto.EthereumAddress) def get_address(client, n, show_display=False, multisig=None): - n = client._convert_prime(n) return client.call(proto.EthereumGetAddress(address_n=n, show_display=show_display)) @session def sign_tx(client, n, nonce, gas_price, gas_limit, to, value, data=None, chain_id=None, tx_type=None): - n = client._convert_prime(n) - msg = proto.EthereumSignTx( address_n=n, nonce=int_to_big_endian(nonce), @@ -53,7 +50,6 @@ def sign_tx(client, n, nonce, gas_price, gas_limit, to, value, data=None, chain_ @expect(proto.EthereumMessageSignature) def sign_message(client, n, message): - n = client._convert_prime(n) message = normalize_nfc(message) return client.call(proto.EthereumSignMessage(address_n=n, message=message)) diff --git a/trezorlib/lisk.py b/trezorlib/lisk.py index f5f9315c1f..bc17a26518 100644 --- a/trezorlib/lisk.py +++ b/trezorlib/lisk.py @@ -7,19 +7,16 @@ from .tools import field, expect, CallException, normalize_nfc @field('address') @expect(proto.LiskAddress) def get_address(client, n, show_display=False): - n = client._convert_prime(n) return client.call(proto.LiskGetAddress(address_n=n, show_display=show_display)) @expect(proto.LiskPublicKey) def get_public_key(client, n, show_display=False): - n = client._convert_prime(n) return client.call(proto.LiskGetPublicKey(address_n=n, show_display=show_display)) @expect(proto.LiskMessageSignature) def sign_message(client, n, message): - n = client._convert_prime(n) message = normalize_nfc(message) return client.call(proto.LiskSignMessage(address_n=n, message=message)) @@ -56,8 +53,6 @@ def _asset_to_proto(asset): @expect(proto.LiskSignedTx) def sign_tx(client, n, transaction): - n = client._convert_prime(n) - msg = proto.LiskTransactionCommon() msg.type = transaction["type"] diff --git a/trezorlib/misc.py b/trezorlib/misc.py index c559453dd0..5a39dcffd9 100644 --- a/trezorlib/misc.py +++ b/trezorlib/misc.py @@ -21,7 +21,6 @@ def get_ecdh_session_key(client, identity, peer_public_key, ecdsa_curve_name=Non @field('value') @expect(proto.CipheredKeyValue) def encrypt_keyvalue(client, n, key, value, ask_on_encrypt=True, ask_on_decrypt=True, iv=b''): - n = client._convert_prime(n) return client.call(proto.CipherKeyValue(address_n=n, key=key, value=value, @@ -34,7 +33,6 @@ def encrypt_keyvalue(client, n, key, value, ask_on_encrypt=True, ask_on_decrypt= @field('value') @expect(proto.CipheredKeyValue) def decrypt_keyvalue(client, n, key, value, ask_on_encrypt=True, ask_on_decrypt=True, iv=b''): - n = client._convert_prime(n) return client.call(proto.CipherKeyValue(address_n=n, key=key, value=value, diff --git a/trezorlib/nem.py b/trezorlib/nem.py index 4f7801fc3c..cbfc911e8c 100644 --- a/trezorlib/nem.py +++ b/trezorlib/nem.py @@ -173,13 +173,11 @@ def create_sign_tx(transaction): @field("address") @expect(proto.NEMAddress) def get_address(client, n, network, show_display=False): - n = client._convert_prime(n) return client.call(proto.NEMGetAddress(address_n=n, network=network, show_display=show_display)) @expect(proto.NEMSignedTx) def sign_tx(client, n, transaction): - n = client._convert_prime(n) try: msg = create_sign_tx(transaction) except ValueError as e: diff --git a/trezorlib/tests/device_tests/test_bip32_speed.py b/trezorlib/tests/device_tests/test_bip32_speed.py index 54fbc717b3..946399289d 100644 --- a/trezorlib/tests/device_tests/test_bip32_speed.py +++ b/trezorlib/tests/device_tests/test_bip32_speed.py @@ -19,6 +19,8 @@ import pytest from .common import TrezorTest +from trezorlib.tools import H_ + class TestBip32Speed(TrezorTest): @@ -42,7 +44,8 @@ class TestBip32Speed(TrezorTest): for depth in range(8): start = time.time() - self.client.get_address('Bitcoin', range(-depth, 0)) + address_n = [H_(-i) for i in range(-depth, 0)] + self.client.get_address('Bitcoin', address_n) delay = time.time() - start expected = (depth + 1) * 0.26 print("DEPTH", depth, "EXPECTED DELAY", expected, "REAL DELAY", delay) diff --git a/trezorlib/tests/device_tests/test_msg_ethereum_getaddress.py b/trezorlib/tests/device_tests/test_msg_ethereum_getaddress.py index 37e62759e2..fb26777662 100644 --- a/trezorlib/tests/device_tests/test_msg_ethereum_getaddress.py +++ b/trezorlib/tests/device_tests/test_msg_ethereum_getaddress.py @@ -19,6 +19,8 @@ import pytest from .common import TrezorTest +from trezorlib.tools import H_ + @pytest.mark.ethereum class TestMsgEthereumGetaddress(TrezorTest): @@ -27,6 +29,6 @@ class TestMsgEthereumGetaddress(TrezorTest): self.setup_mnemonic_nopin_nopassphrase() assert hexlify(self.client.ethereum_get_address([])) == b'1d1c328764a41bda0492b66baa30c4a339ff85ef' assert hexlify(self.client.ethereum_get_address([1])) == b'437207ca3cf43bf2e47dea0756d736c5df4f597a' - assert hexlify(self.client.ethereum_get_address([0, -1])) == b'e5d96dfa07bcf1a3ae43677840c31394258861bf' - assert hexlify(self.client.ethereum_get_address([-9, 0])) == b'f68804ac9eca9483ab4241d3e4751590d2c05102' + assert hexlify(self.client.ethereum_get_address([0, H_(1)])) == b'e5d96dfa07bcf1a3ae43677840c31394258861bf' + assert hexlify(self.client.ethereum_get_address([H_(9), 0])) == b'f68804ac9eca9483ab4241d3e4751590d2c05102' assert hexlify(self.client.ethereum_get_address([0, 9999999])) == b'7a6366ecfcaf0d5dcc1539c171696c6cdd1eb8ed' diff --git a/trezorlib/tests/device_tests/test_msg_getaddress.py b/trezorlib/tests/device_tests/test_msg_getaddress.py index da92e4f56b..8acb4d4d2f 100644 --- a/trezorlib/tests/device_tests/test_msg_getaddress.py +++ b/trezorlib/tests/device_tests/test_msg_getaddress.py @@ -20,7 +20,7 @@ from .common import TrezorTest from ..support import ckd_public as bip32 from trezorlib import messages as proto -from trezorlib.tools import parse_path +from trezorlib.tools import parse_path, H_ class TestMsgGetaddress(TrezorTest): @@ -29,16 +29,16 @@ class TestMsgGetaddress(TrezorTest): self.setup_mnemonic_nopin_nopassphrase() assert self.client.get_address('Bitcoin', []) == '1EfKbQupktEMXf4gujJ9kCFo83k1iMqwqK' assert self.client.get_address('Bitcoin', [1]) == '1CK7SJdcb8z9HuvVft3D91HLpLC6KSsGb' - assert self.client.get_address('Bitcoin', [0, -1]) == '1JVq66pzRBvqaBRFeU9SPVvg3er4ZDgoMs' - assert self.client.get_address('Bitcoin', [-9, 0]) == '1F4YdQdL9ZQwvcNTuy5mjyQxXkyCfMcP2P' + assert self.client.get_address('Bitcoin', [0, H_(1)]) == '1JVq66pzRBvqaBRFeU9SPVvg3er4ZDgoMs' + assert self.client.get_address('Bitcoin', [H_(9), 0]) == '1F4YdQdL9ZQwvcNTuy5mjyQxXkyCfMcP2P' assert self.client.get_address('Bitcoin', [0, 9999999]) == '1GS8X3yc7ntzwGw9vXwj9wqmBWZkTFewBV' def test_ltc(self): self.setup_mnemonic_nopin_nopassphrase() assert self.client.get_address('Litecoin', []) == 'LYtGrdDeqYUQnTkr5sHT2DKZLG7Hqg7HTK' assert self.client.get_address('Litecoin', [1]) == 'LKRGNecThFP3Q6c5fosLVA53Z2hUDb1qnE' - assert self.client.get_address('Litecoin', [0, -1]) == 'LcinMK8pVrAtpz7Qpc8jfWzSFsDLgLYfG6' - assert self.client.get_address('Litecoin', [-9, 0]) == 'LZHVtcwAEDf1BR4d67551zUijyLUpDF9EX' + assert self.client.get_address('Litecoin', [0, H_(1)]) == 'LcinMK8pVrAtpz7Qpc8jfWzSFsDLgLYfG6' + assert self.client.get_address('Litecoin', [H_(9), 0]) == 'LZHVtcwAEDf1BR4d67551zUijyLUpDF9EX' assert self.client.get_address('Litecoin', [0, 9999999]) == 'Laf5nGHSCT94C5dK6fw2RxuXPiw2ZuRR9S' def test_tbtc(self): diff --git a/trezorlib/tests/device_tests/test_msg_getpublickey.py b/trezorlib/tests/device_tests/test_msg_getpublickey.py index e8e6847cc8..bb0792c4ef 100644 --- a/trezorlib/tests/device_tests/test_msg_getpublickey.py +++ b/trezorlib/tests/device_tests/test_msg_getpublickey.py @@ -17,6 +17,8 @@ from .common import TrezorTest from ..support import ckd_public as bip32 +from trezorlib.tools import H_ + class TestMsgGetpublickey(TrezorTest): @@ -26,10 +28,10 @@ class TestMsgGetpublickey(TrezorTest): assert self.client.get_public_node([], coin_name='Bitcoin').xpub == 'xpub661MyMwAqRbcF1zGijBb2K6x9YiJPh58xpcCeLvTxMX6spkY3PcpJ4ABcCyWfskq5DDxM3e6Ez5ePCqG5bnPUXR4wL8TZWyoDaUdiWW7bKy' assert bip32.serialize(self.client.get_public_node([1]).node, 0x0488B21E) == 'xpub68zNxjsTrV8y9AadThLW7dTAqEpZ7xBLFSyJ3X9pjTv6Njg6kxgjXJkzxq8u3ttnjBw1jupQHMP3gpGZzZqd1eh5S4GjkaMhPR18vMyUi8N' assert self.client.get_public_node([1], coin_name='Bitcoin').xpub == 'xpub68zNxjsTrV8y9AadThLW7dTAqEpZ7xBLFSyJ3X9pjTv6Njg6kxgjXJkzxq8u3ttnjBw1jupQHMP3gpGZzZqd1eh5S4GjkaMhPR18vMyUi8N' - assert bip32.serialize(self.client.get_public_node([0, -1]).node, 0x0488B21E) == 'xpub6A3FoZqYXj1AbW4thRwBh26YwZWbmoyjTaZwwxJjY1oKUpefLepL3RFS9DHKQrjAfxDrzDepYMDZPqXN6upQm3bHQ9xaXD5a3mqni3goF4v' - assert self.client.get_public_node([0, -1], coin_name='Bitcoin').xpub == 'xpub6A3FoZqYXj1AbW4thRwBh26YwZWbmoyjTaZwwxJjY1oKUpefLepL3RFS9DHKQrjAfxDrzDepYMDZPqXN6upQm3bHQ9xaXD5a3mqni3goF4v' - assert bip32.serialize(self.client.get_public_node([-9, 0]).node, 0x0488B21E) == 'xpub6A2h5mzLDfYginoD7q7wCWbq18wTbN9gducRr2w5NRTwdLeoT3cJSwefFqW7uXTpVFGtpUyDMBNYs3DNvvXx6NPjF9YEbUQrtxFSWnPtVrv' - assert self.client.get_public_node([-9, 0], coin_name='Bitcoin').xpub == 'xpub6A2h5mzLDfYginoD7q7wCWbq18wTbN9gducRr2w5NRTwdLeoT3cJSwefFqW7uXTpVFGtpUyDMBNYs3DNvvXx6NPjF9YEbUQrtxFSWnPtVrv' + assert bip32.serialize(self.client.get_public_node([0, H_(1)]).node, 0x0488B21E) == 'xpub6A3FoZqYXj1AbW4thRwBh26YwZWbmoyjTaZwwxJjY1oKUpefLepL3RFS9DHKQrjAfxDrzDepYMDZPqXN6upQm3bHQ9xaXD5a3mqni3goF4v' + assert self.client.get_public_node([0, H_(1)], coin_name='Bitcoin').xpub == 'xpub6A3FoZqYXj1AbW4thRwBh26YwZWbmoyjTaZwwxJjY1oKUpefLepL3RFS9DHKQrjAfxDrzDepYMDZPqXN6upQm3bHQ9xaXD5a3mqni3goF4v' + assert bip32.serialize(self.client.get_public_node([H_(9), 0]).node, 0x0488B21E) == 'xpub6A2h5mzLDfYginoD7q7wCWbq18wTbN9gducRr2w5NRTwdLeoT3cJSwefFqW7uXTpVFGtpUyDMBNYs3DNvvXx6NPjF9YEbUQrtxFSWnPtVrv' + assert self.client.get_public_node([H_(9), 0], coin_name='Bitcoin').xpub == 'xpub6A2h5mzLDfYginoD7q7wCWbq18wTbN9gducRr2w5NRTwdLeoT3cJSwefFqW7uXTpVFGtpUyDMBNYs3DNvvXx6NPjF9YEbUQrtxFSWnPtVrv' assert bip32.serialize(self.client.get_public_node([0, 9999999]).node, 0x0488B21E) == 'xpub6A3FoZqQEK6iwLZ4HFkqSo5fb35BH4bpjC4SPZ63prfLdGYPwYxEuC6o91bUvFFdMzKWe5rs3axHRUjxJaSvBnKKFtnfLwDACRxPxabsv2r' assert self.client.get_public_node([0, 9999999], coin_name='Bitcoin').xpub == 'xpub6A3FoZqQEK6iwLZ4HFkqSo5fb35BH4bpjC4SPZ63prfLdGYPwYxEuC6o91bUvFFdMzKWe5rs3axHRUjxJaSvBnKKFtnfLwDACRxPxabsv2r' @@ -39,10 +41,10 @@ class TestMsgGetpublickey(TrezorTest): assert self.client.get_public_node([], coin_name='Litecoin').xpub == 'Ltub2SSUS19CirucVPGDKDBatBDBEM2s9UbH66pBURfaKrMocCPLhQ7Z7hecy5VYLHA5fRdXwB2e61j2VJCNzVsqKTCVEU1vECjqi5EyczFX9xp' assert bip32.serialize(self.client.get_public_node([1]).node, 0x019DA462) == 'Ltub2VRVRP5VjvSyPXra4BLVyVZPv397sjhUNjBGsbtw6xko77JuQyBULxFSKheviJJ3KQLbL3Cx8P2RnudguTw4raUVjCACRG7jsumUptYx55C' assert self.client.get_public_node([1], coin_name='Litecoin').xpub == 'Ltub2VRVRP5VjvSyPXra4BLVyVZPv397sjhUNjBGsbtw6xko77JuQyBULxFSKheviJJ3KQLbL3Cx8P2RnudguTw4raUVjCACRG7jsumUptYx55C' - assert bip32.serialize(self.client.get_public_node([0, -1]).node, 0x019DA462) == 'Ltub2WUNGD3aRAKAqsLqHuwBYtCn2MqAXbVsarmvn33quWe2DCHTzfK4s4jsW5oM5G8RGAdSaM3NPNrwVvtV1ourbyNhhHr3BtqcYGc8caf5GoT' - assert self.client.get_public_node([0, -1], coin_name='Litecoin').xpub == 'Ltub2WUNGD3aRAKAqsLqHuwBYtCn2MqAXbVsarmvn33quWe2DCHTzfK4s4jsW5oM5G8RGAdSaM3NPNrwVvtV1ourbyNhhHr3BtqcYGc8caf5GoT' - assert bip32.serialize(self.client.get_public_node([-9, 0]).node, 0x019DA462) == 'Ltub2WToYRCN76rgyA59iK7w4Ni45wG2M9fpmBpQg7gBjvJeMiHc7473Gb96ci29Zvs55TgUQcMmCD1vy8aVqpdPwJB9YHRhGAAuPT1nRLLXmFu' - assert self.client.get_public_node([-9, 0], coin_name='Litecoin').xpub == 'Ltub2WToYRCN76rgyA59iK7w4Ni45wG2M9fpmBpQg7gBjvJeMiHc7473Gb96ci29Zvs55TgUQcMmCD1vy8aVqpdPwJB9YHRhGAAuPT1nRLLXmFu' + assert bip32.serialize(self.client.get_public_node([0, H_(1)]).node, 0x019DA462) == 'Ltub2WUNGD3aRAKAqsLqHuwBYtCn2MqAXbVsarmvn33quWe2DCHTzfK4s4jsW5oM5G8RGAdSaM3NPNrwVvtV1ourbyNhhHr3BtqcYGc8caf5GoT' + assert self.client.get_public_node([0, H_(1)], coin_name='Litecoin').xpub == 'Ltub2WUNGD3aRAKAqsLqHuwBYtCn2MqAXbVsarmvn33quWe2DCHTzfK4s4jsW5oM5G8RGAdSaM3NPNrwVvtV1ourbyNhhHr3BtqcYGc8caf5GoT' + assert bip32.serialize(self.client.get_public_node([H_(9), 0]).node, 0x019DA462) == 'Ltub2WToYRCN76rgyA59iK7w4Ni45wG2M9fpmBpQg7gBjvJeMiHc7473Gb96ci29Zvs55TgUQcMmCD1vy8aVqpdPwJB9YHRhGAAuPT1nRLLXmFu' + assert self.client.get_public_node([H_(9), 0], coin_name='Litecoin').xpub == 'Ltub2WToYRCN76rgyA59iK7w4Ni45wG2M9fpmBpQg7gBjvJeMiHc7473Gb96ci29Zvs55TgUQcMmCD1vy8aVqpdPwJB9YHRhGAAuPT1nRLLXmFu' assert bip32.serialize(self.client.get_public_node([0, 9999999]).node, 0x019DA462) == 'Ltub2WUNGD3S7kQjBhpzsjkqJfBtfqPk2r7xrUGRDdqACMW3MeBCbZSyiqbEVt7WaeesxCj6EDFQtcbfXa75DUYN2i6jZ2g81cyCgvijs9J2u2n' assert self.client.get_public_node([0, 9999999], coin_name='Litecoin').xpub == 'Ltub2WUNGD3S7kQjBhpzsjkqJfBtfqPk2r7xrUGRDdqACMW3MeBCbZSyiqbEVt7WaeesxCj6EDFQtcbfXa75DUYN2i6jZ2g81cyCgvijs9J2u2n' diff --git a/trezorlib/tests/device_tests/test_msg_nem_signtx_mosaics_t2.py b/trezorlib/tests/device_tests/test_msg_nem_signtx_mosaics_t2.py index 26d2c65638..dc5e771280 100644 --- a/trezorlib/tests/device_tests/test_msg_nem_signtx_mosaics_t2.py +++ b/trezorlib/tests/device_tests/test_msg_nem_signtx_mosaics_t2.py @@ -184,7 +184,6 @@ class TestMsgNEMSignTxMosaics(TrezorTest): def _nem_sign(self, num_of_swipes, test_suite): n = parse_path("m/44'/1'/0'/0'/0'") - n = self.client._convert_prime(n) msg = nem.create_sign_tx(test_suite) assert msg.transaction is not None msg.transaction.address_n = n From 00617817c3d64f5d71c417aae1385c507a879fe4 Mon Sep 17 00:00:00 2001 From: matejcik Date: Thu, 14 Jun 2018 16:09:19 +0200 Subject: [PATCH 07/37] trezorlib: disable encrypt/decrypt message functionality it is disabled in Trezors and its utility is unclear --- trezorctl | 56 ++++++++++++++++++++++----------------------- trezorlib/btc.py | 18 +++++++-------- trezorlib/client.py | 4 ++-- 3 files changed, 39 insertions(+), 39 deletions(-) diff --git a/trezorctl b/trezorctl index 71afb30e13..01afc1e355 100755 --- a/trezorctl +++ b/trezorctl @@ -716,36 +716,36 @@ def decrypt_keyvalue(connect, address, key, value): return client.decrypt_keyvalue(address_n, key, binascii.unhexlify(value)) -@cli.command(help='Encrypt message.') -@click.option('-c', '--coin', default='Bitcoin') -@click.option('-d', '--display-only', is_flag=True) -@click.option('-n', '--address', required=True, help="BIP-32 path, e.g. m/44'/0'/0'/0/0") -@click.argument('pubkey') -@click.argument('message') -@click.pass_obj -def encrypt_message(connect, coin, display_only, address, pubkey, message): - client = connect() - pubkey = binascii.unhexlify(pubkey) - address_n = tools.parse_path(address) - res = client.encrypt_message(pubkey, message, display_only, coin, address_n) - return { - 'nonce': binascii.hexlify(res.nonce), - 'message': binascii.hexlify(res.message), - 'hmac': binascii.hexlify(res.hmac), - 'payload': base64.b64encode(res.nonce + res.message + res.hmac), - } +# @cli.command(help='Encrypt message.') +# @click.option('-c', '--coin', default='Bitcoin') +# @click.option('-d', '--display-only', is_flag=True) +# @click.option('-n', '--address', required=True, help="BIP-32 path, e.g. m/44'/0'/0'/0/0") +# @click.argument('pubkey') +# @click.argument('message') +# @click.pass_obj +# def encrypt_message(connect, coin, display_only, address, pubkey, message): +# client = connect() +# pubkey = binascii.unhexlify(pubkey) +# address_n = tools.parse_path(address) +# res = client.encrypt_message(pubkey, message, display_only, coin, address_n) +# return { +# 'nonce': binascii.hexlify(res.nonce), +# 'message': binascii.hexlify(res.message), +# 'hmac': binascii.hexlify(res.hmac), +# 'payload': base64.b64encode(res.nonce + res.message + res.hmac), +# } -@cli.command(help='Decrypt message.') -@click.option('-n', '--address', required=True, help="BIP-32 path, e.g. m/44'/0'/0'/0/0") -@click.argument('payload') -@click.pass_obj -def decrypt_message(connect, address, payload): - client = connect() - address_n = tools.parse_path(address) - payload = base64.b64decode(payload) - nonce, message, msg_hmac = payload[:33], payload[33:-8], payload[-8:] - return client.decrypt_message(address_n, nonce, message, msg_hmac) +# @cli.command(help='Decrypt message.') +# @click.option('-n', '--address', required=True, help="BIP-32 path, e.g. m/44'/0'/0'/0/0") +# @click.argument('payload') +# @click.pass_obj +# def decrypt_message(connect, address, payload): +# client = connect() +# address_n = tools.parse_path(address) +# payload = base64.b64decode(payload) +# nonce, message, msg_hmac = payload[:33], payload[33:-8], payload[-8:] +# return client.decrypt_message(address_n, nonce, message, msg_hmac) # diff --git a/trezorlib/btc.py b/trezorlib/btc.py index 98502733ac..4b72de5682 100644 --- a/trezorlib/btc.py +++ b/trezorlib/btc.py @@ -33,17 +33,17 @@ def verify_message(client, coin_name, address, signature, message): return isinstance(resp, proto.Success) -@expect(proto.EncryptedMessage) -def encrypt_message(client, pubkey, message, display_only, coin_name, n): - if coin_name and n: - return client.call(proto.EncryptMessage(pubkey=pubkey, message=message, display_only=display_only, coin_name=coin_name, address_n=n)) - else: - return client.call(proto.EncryptMessage(pubkey=pubkey, message=message, display_only=display_only)) +# @expect(proto.EncryptedMessage) +# def encrypt_message(client, pubkey, message, display_only, coin_name, n): +# if coin_name and n: +# return client.call(proto.EncryptMessage(pubkey=pubkey, message=message, display_only=display_only, coin_name=coin_name, address_n=n)) +# else: +# return client.call(proto.EncryptMessage(pubkey=pubkey, message=message, display_only=display_only)) -@expect(proto.DecryptedMessage) -def decrypt_message(client, n, nonce, message, msg_hmac): - return client.call(proto.DecryptMessage(address_n=n, nonce=nonce, message=message, hmac=msg_hmac)) +# @expect(proto.DecryptedMessage) +# def decrypt_message(client, n, nonce, message, msg_hmac): +# return client.call(proto.DecryptMessage(address_n=n, nonce=nonce, message=message, hmac=msg_hmac)) @session diff --git a/trezorlib/client.py b/trezorlib/client.py index 4d4780528d..8e9eb004e6 100644 --- a/trezorlib/client.py +++ b/trezorlib/client.py @@ -481,8 +481,8 @@ class ProtocolMixin(object): sign_tx = MovedTo(btc.sign_tx) sign_message = MovedTo(btc.sign_message) verify_message = MovedTo(btc.verify_message) - encrypt_message = MovedTo(btc.encrypt_message) - decrypt_message = MovedTo(btc.decrypt_message) + # encrypt_message = MovedTo(btc.encrypt_message) + # decrypt_message = MovedTo(btc.decrypt_message) # CoSi functionality cosi_commit = MovedTo(cosi.commit) From 7083eb7a5cdf34377cf5cf2b87d996692a70f728 Mon Sep 17 00:00:00 2001 From: matejcik Date: Mon, 25 Jun 2018 17:51:09 +0200 Subject: [PATCH 08/37] trezorlib: drop @field decorator its function is replaced by @expect(field="name") -- it doesn't make sense to use @field without @expect anyway --- trezorlib/btc.py | 7 ++----- trezorlib/client.py | 6 ++---- trezorlib/device.py | 35 ++++++++++++----------------------- trezorlib/ethereum.py | 5 ++--- trezorlib/lisk.py | 5 ++--- trezorlib/misc.py | 11 ++++------- trezorlib/nem.py | 5 ++--- trezorlib/stellar.py | 8 +++----- trezorlib/tools.py | 26 ++++++++------------------ 9 files changed, 37 insertions(+), 71 deletions(-) diff --git a/trezorlib/btc.py b/trezorlib/btc.py index 4b72de5682..bc266d4902 100644 --- a/trezorlib/btc.py +++ b/trezorlib/btc.py @@ -1,7 +1,5 @@ from . import messages as proto -from .tools import expect, field, CallException, normalize_nfc, session - -### Client functions ### +from .tools import expect, CallException, normalize_nfc, session @expect(proto.PublicKey) @@ -9,8 +7,7 @@ def get_public_node(client, n, ecdsa_curve_name=None, show_display=False, coin_n return client.call(proto.GetPublicKey(address_n=n, ecdsa_curve_name=ecdsa_curve_name, show_display=show_display, coin_name=coin_name)) -@field('address') -@expect(proto.Address) +@expect(proto.Address, field="address") def get_address(client, coin_name, n, show_display=False, multisig=None, script_type=proto.InputScriptType.SPENDADDRESS): if multisig: return client.call(proto.GetAddress(address_n=n, coin_name=coin_name, show_display=show_display, multisig=multisig, script_type=script_type)) diff --git a/trezorlib/client.py b/trezorlib/client.py index 8e9eb004e6..d1277c3d30 100644 --- a/trezorlib/client.py +++ b/trezorlib/client.py @@ -415,8 +415,7 @@ class ProtocolMixin(object): warnings.warn('expand_path is deprecated, use tools.parse_path', DeprecationWarning, stacklevel=2) return tools.parse_path(n) - @tools.field('message') - @tools.expect(proto.Success) + @tools.expect(proto.Success, field="message") def ping(self, msg, button_protection=False, pin_protection=False, passphrase_protection=False): msg = proto.Ping(message=msg, button_protection=button_protection, @@ -450,8 +449,7 @@ class ProtocolMixin(object): return txes - @tools.field('message') - @tools.expect(proto.Success) + @tools.expect(proto.Success, field="message") def clear_session(self): return self.call(proto.ClearSession()) diff --git a/trezorlib/device.py b/trezorlib/device.py index df8a7cddfe..b5577b5f89 100644 --- a/trezorlib/device.py +++ b/trezorlib/device.py @@ -21,7 +21,7 @@ from mnemonic import Mnemonic from . import messages as proto from . import tools -from .tools import field, expect, session +from .tools import expect, session from .transport import enumerate_devices, get_transport @@ -44,8 +44,7 @@ class TrezorDevice: return get_transport(path, prefix_search=False) -@field('message') -@expect(proto.Success) +@expect(proto.Success, field="message") def apply_settings(client, label=None, language=None, use_passphrase=None, homescreen=None, passphrase_source=None, auto_lock_delay_ms=None): settings = proto.ApplySettings() if label is not None: @@ -66,39 +65,34 @@ def apply_settings(client, label=None, language=None, use_passphrase=None, homes return out -@field('message') -@expect(proto.Success) +@expect(proto.Success, field="message") def apply_flags(client, flags): out = client.call(proto.ApplyFlags(flags=flags)) client.init_device() # Reload Features return out -@field('message') -@expect(proto.Success) +@expect(proto.Success, field="message") def change_pin(client, remove=False): ret = client.call(proto.ChangePin(remove=remove)) client.init_device() # Re-read features return ret -@field('message') -@expect(proto.Success) +@expect(proto.Success, field="message") def set_u2f_counter(client, u2f_counter): ret = client.call(proto.SetU2FCounter(u2f_counter=u2f_counter)) return ret -@field('message') -@expect(proto.Success) +@expect(proto.Success, field="message") def wipe_device(client): ret = client.call(proto.WipeDevice()) client.init_device() return ret -@field('message') -@expect(proto.Success) +@expect(proto.Success, field="message") def recovery_device(client, word_count, passphrase_protection, pin_protection, label, language, type=proto.RecoveryDeviceType.ScrambledWords, expand=False, dry_run=False): if client.features.initialized and not dry_run: raise RuntimeError("Device is initialized already. Call wipe_device() and try again.") @@ -127,8 +121,7 @@ def recovery_device(client, word_count, passphrase_protection, pin_protection, l return res -@field('message') -@expect(proto.Success) +@expect(proto.Success, field="message") @session def reset_device(client, display_random, strength, passphrase_protection, pin_protection, label, language, u2f_counter=0, skip_backup=False): if client.features.initialized: @@ -155,15 +148,13 @@ def reset_device(client, display_random, strength, passphrase_protection, pin_pr return ret -@field('message') -@expect(proto.Success) +@expect(proto.Success, field="message") def backup_device(client): ret = client.call(proto.BackupDevice()) return ret -@field('message') -@expect(proto.Success) +@expect(proto.Success, field="message") def load_device_by_mnemonic(client, mnemonic, pin, passphrase_protection, label, language='english', skip_checksum=False, expand=False): # Convert mnemonic to UTF8 NKFD mnemonic = Mnemonic.normalize_string(mnemonic) @@ -191,8 +182,7 @@ def load_device_by_mnemonic(client, mnemonic, pin, passphrase_protection, label, return resp -@field('message') -@expect(proto.Success) +@expect(proto.Success, field="message") def load_device_by_xprv(client, xprv, pin, passphrase_protection, label, language): if client.features.initialized: raise RuntimeError("Device is initialized already. Call wipe_device() and try again.") @@ -236,8 +226,7 @@ def load_device_by_xprv(client, xprv, pin, passphrase_protection, label, languag return resp -@field('message') -@expect(proto.Success) +@expect(proto.Success, field="message") def self_test(client): if client.features.bootloader_mode is False: raise RuntimeError("Device must be in bootloader mode") diff --git a/trezorlib/ethereum.py b/trezorlib/ethereum.py index d0d16ce58f..41a147f710 100644 --- a/trezorlib/ethereum.py +++ b/trezorlib/ethereum.py @@ -1,5 +1,5 @@ from . import messages as proto -from .tools import field, expect, CallException, normalize_nfc, session +from .tools import expect, CallException, normalize_nfc, session def int_to_big_endian(value): @@ -9,8 +9,7 @@ def int_to_big_endian(value): ### Client functions ### -@field('address') -@expect(proto.EthereumAddress) +@expect(proto.EthereumAddress, field="address") def get_address(client, n, show_display=False, multisig=None): return client.call(proto.EthereumGetAddress(address_n=n, show_display=show_display)) diff --git a/trezorlib/lisk.py b/trezorlib/lisk.py index bc17a26518..6d7b777810 100644 --- a/trezorlib/lisk.py +++ b/trezorlib/lisk.py @@ -1,11 +1,10 @@ import binascii from . import messages as proto -from .tools import field, expect, CallException, normalize_nfc +from .tools import expect, CallException, normalize_nfc -@field('address') -@expect(proto.LiskAddress) +@expect(proto.LiskAddress, field="address") def get_address(client, n, show_display=False): return client.call(proto.LiskGetAddress(address_n=n, show_display=show_display)) diff --git a/trezorlib/misc.py b/trezorlib/misc.py index 5a39dcffd9..eb1b0157ae 100644 --- a/trezorlib/misc.py +++ b/trezorlib/misc.py @@ -1,9 +1,8 @@ from . import messages as proto -from .tools import field, expect +from .tools import expect -@field('entropy') -@expect(proto.Entropy) +@expect(proto.Entropy, field="entropy") def get_entropy(client, size): return client.call(proto.GetEntropy(size=size)) @@ -18,8 +17,7 @@ def get_ecdh_session_key(client, identity, peer_public_key, ecdsa_curve_name=Non return client.call(proto.GetECDHSessionKey(identity=identity, peer_public_key=peer_public_key, ecdsa_curve_name=ecdsa_curve_name)) -@field('value') -@expect(proto.CipheredKeyValue) +@expect(proto.CipheredKeyValue, field="value") def encrypt_keyvalue(client, n, key, value, ask_on_encrypt=True, ask_on_decrypt=True, iv=b''): return client.call(proto.CipherKeyValue(address_n=n, key=key, @@ -30,8 +28,7 @@ def encrypt_keyvalue(client, n, key, value, ask_on_encrypt=True, ask_on_decrypt= iv=iv)) -@field('value') -@expect(proto.CipheredKeyValue) +@expect(proto.CipheredKeyValue, field="value") def decrypt_keyvalue(client, n, key, value, ask_on_encrypt=True, ask_on_decrypt=True, iv=b''): return client.call(proto.CipherKeyValue(address_n=n, key=key, diff --git a/trezorlib/nem.py b/trezorlib/nem.py index cbfc911e8c..ee4ca1e446 100644 --- a/trezorlib/nem.py +++ b/trezorlib/nem.py @@ -17,7 +17,7 @@ import binascii import json from . import messages as proto -from .tools import expect, field, CallException +from .tools import expect, CallException TYPE_TRANSACTION_TRANSFER = 0x0101 TYPE_IMPORTANCE_TRANSFER = 0x0801 @@ -170,8 +170,7 @@ def create_sign_tx(transaction): ### Client functions ### -@field("address") -@expect(proto.NEMAddress) +@expect(proto.NEMAddress, field="address") def get_address(client, n, network, show_display=False): return client.call(proto.NEMGetAddress(address_n=n, network=network, show_display=show_display)) diff --git a/trezorlib/stellar.py b/trezorlib/stellar.py index 7c05daf4ea..d8635c4a64 100644 --- a/trezorlib/stellar.py +++ b/trezorlib/stellar.py @@ -19,7 +19,7 @@ import struct import xdrlib from . import messages -from .tools import field, expect, CallException +from .tools import expect, CallException # Memo types MEMO_TYPE_NONE = 0 @@ -343,14 +343,12 @@ def _crc16_checksum(bytes): ### Client functions ### -@field('public_key') -@expect(messages.StellarPublicKey) +@expect(messages.StellarPublicKey, field="public_key") def get_public_key(client, address_n, show_display=False): return client.call(messages.StellarGetPublicKey(address_n=address_n, show_display=show_display)) -@field('address') -@expect(messages.StellarAddress) +@expect(messages.StellarAddress, field="address") def get_address(client, address_n, show_display=False): return client.call(messages.StellarGetAddress(address_n=address_n, show_display=show_display)) diff --git a/trezorlib/tools.py b/trezorlib/tools.py index 36f2358c7c..41675d98b2 100644 --- a/trezorlib/tools.py +++ b/trezorlib/tools.py @@ -157,7 +157,7 @@ def parse_path(nstr: str) -> Address: return int(x) try: - return list(str_to_harden(x) for x in n) + return [str_to_harden(x) for x in n] except Exception: raise ValueError('Invalid BIP32 path', nstr) @@ -176,27 +176,13 @@ class CallException(Exception): pass -class field: - # Decorator extracts single value from - # protobuf object. If the field is not - # present, raises an exception. - def __init__(self, field): - self.field = field - - def __call__(self, f): - @functools.wraps(f) - def wrapped_f(*args, **kwargs): - ret = f(*args, **kwargs) - return getattr(ret, self.field) - return wrapped_f - - class expect: # Decorator checks if the method # returned one of expected protobuf messages # or raises an exception - def __init__(self, *expected): + def __init__(self, expected, field=None): self.expected = expected + self.field = field def __call__(self, f): @functools.wraps(f) @@ -204,7 +190,11 @@ class expect: ret = f(*args, **kwargs) if not isinstance(ret, self.expected): raise RuntimeError("Got %s, expected %s" % (ret.__class__, self.expected)) - return ret + if self.field is not None: + return getattr(ret, self.field) + else: + return ret + return wrapped_f From a3d560529c99f484d2ce8f7e6132fcfcc654da7c Mon Sep 17 00:00:00 2001 From: matejcik Date: Mon, 6 Aug 2018 16:15:44 +0200 Subject: [PATCH 09/37] trezorlib: post-merge updates --- trezorlib/btc.py | 13 ------------- trezorlib/client.py | 2 -- trezorlib/ripple.py | 7 ++----- .../device_tests/test_msg_ripple_get_address.py | 3 +-- .../tests/device_tests/test_msg_ripple_sign_tx.py | 3 +-- .../device_tests/test_msg_stellar_get_address.py | 3 +-- .../device_tests/test_msg_stellar_get_public_key.py | 3 +-- trezorlib/tools.py | 1 + 8 files changed, 7 insertions(+), 28 deletions(-) diff --git a/trezorlib/btc.py b/trezorlib/btc.py index bc266d4902..f99ea885e0 100644 --- a/trezorlib/btc.py +++ b/trezorlib/btc.py @@ -30,19 +30,6 @@ def verify_message(client, coin_name, address, signature, message): return isinstance(resp, proto.Success) -# @expect(proto.EncryptedMessage) -# def encrypt_message(client, pubkey, message, display_only, coin_name, n): -# if coin_name and n: -# return client.call(proto.EncryptMessage(pubkey=pubkey, message=message, display_only=display_only, coin_name=coin_name, address_n=n)) -# else: -# return client.call(proto.EncryptMessage(pubkey=pubkey, message=message, display_only=display_only)) - - -# @expect(proto.DecryptedMessage) -# def decrypt_message(client, n, nonce, message, msg_hmac): -# return client.call(proto.DecryptMessage(address_n=n, nonce=nonce, message=message, hmac=msg_hmac)) - - @session def sign_tx(client, coin_name, inputs, outputs, version=None, lock_time=None, expiry=None, overwintered=None, debug_processor=None): # start = time.time() diff --git a/trezorlib/client.py b/trezorlib/client.py index d1277c3d30..577559c8a6 100644 --- a/trezorlib/client.py +++ b/trezorlib/client.py @@ -479,8 +479,6 @@ class ProtocolMixin(object): sign_tx = MovedTo(btc.sign_tx) sign_message = MovedTo(btc.sign_message) verify_message = MovedTo(btc.verify_message) - # encrypt_message = MovedTo(btc.encrypt_message) - # decrypt_message = MovedTo(btc.decrypt_message) # CoSi functionality cosi_commit = MovedTo(cosi.commit) diff --git a/trezorlib/ripple.py b/trezorlib/ripple.py index 6f1c38802e..d66227d215 100644 --- a/trezorlib/ripple.py +++ b/trezorlib/ripple.py @@ -18,13 +18,10 @@ import base64 import struct from . import messages -from . import tools -from .client import field -from .client import expect +from .tools import expect -@field('address') -@expect(messages.RippleAddress) +@expect(messages.RippleAddress, field="address") def get_address(client, address_n, show_display=False): return client.call( messages.RippleGetAddress( diff --git a/trezorlib/tests/device_tests/test_msg_ripple_get_address.py b/trezorlib/tests/device_tests/test_msg_ripple_get_address.py index ac43065f96..8c1e1c2da0 100644 --- a/trezorlib/tests/device_tests/test_msg_ripple_get_address.py +++ b/trezorlib/tests/device_tests/test_msg_ripple_get_address.py @@ -19,9 +19,8 @@ import pytest from .common import TrezorTest from .conftest import TREZOR_VERSION from binascii import hexlify -from trezorlib.client import CallException from trezorlib.ripple import get_address -from trezorlib.tools import parse_path +from trezorlib.tools import parse_path, CallException @pytest.mark.ripple diff --git a/trezorlib/tests/device_tests/test_msg_ripple_sign_tx.py b/trezorlib/tests/device_tests/test_msg_ripple_sign_tx.py index 43f64c7b7f..ce04eb34e5 100644 --- a/trezorlib/tests/device_tests/test_msg_ripple_sign_tx.py +++ b/trezorlib/tests/device_tests/test_msg_ripple_sign_tx.py @@ -21,8 +21,7 @@ from .conftest import TREZOR_VERSION from binascii import unhexlify from trezorlib import messages from trezorlib import ripple -from trezorlib.client import CallException -from trezorlib.tools import parse_path +from trezorlib.tools import parse_path, CallException @pytest.mark.ripple diff --git a/trezorlib/tests/device_tests/test_msg_stellar_get_address.py b/trezorlib/tests/device_tests/test_msg_stellar_get_address.py index f07b32ff53..16de53daf3 100644 --- a/trezorlib/tests/device_tests/test_msg_stellar_get_address.py +++ b/trezorlib/tests/device_tests/test_msg_stellar_get_address.py @@ -21,8 +21,7 @@ from .conftest import TREZOR_VERSION from binascii import hexlify from trezorlib import stellar from trezorlib import messages as proto -from trezorlib.client import CallException -from trezorlib.tools import parse_path +from trezorlib.tools import parse_path, CallException @pytest.mark.stellar diff --git a/trezorlib/tests/device_tests/test_msg_stellar_get_public_key.py b/trezorlib/tests/device_tests/test_msg_stellar_get_public_key.py index 1442d97958..f1837d399c 100644 --- a/trezorlib/tests/device_tests/test_msg_stellar_get_public_key.py +++ b/trezorlib/tests/device_tests/test_msg_stellar_get_public_key.py @@ -21,8 +21,7 @@ from .conftest import TREZOR_VERSION from binascii import hexlify from trezorlib import stellar from trezorlib import messages -from trezorlib.client import CallException -from trezorlib.tools import parse_path +from trezorlib.tools import parse_path, CallException @pytest.mark.stellar diff --git a/trezorlib/tools.py b/trezorlib/tools.py index 41675d98b2..ee015c42ff 100644 --- a/trezorlib/tools.py +++ b/trezorlib/tools.py @@ -14,6 +14,7 @@ # You should have received a copy of the License along with this library. # If not, see . +import functools import hashlib import struct import unicodedata From 65d8adb0be8152100d4a81b60ad0e0ba31cb2fa3 Mon Sep 17 00:00:00 2001 From: matejcik Date: Fri, 10 Aug 2018 13:32:50 +0200 Subject: [PATCH 10/37] trezorlib: rename device.*_device to device.* --- trezorlib/client.py | 8 ++++---- trezorlib/device.py | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/trezorlib/client.py b/trezorlib/client.py index 577559c8a6..94858c5492 100644 --- a/trezorlib/client.py +++ b/trezorlib/client.py @@ -456,10 +456,10 @@ class ProtocolMixin(object): # Device functionality self_test = MovedTo(device.self_test) - wipe_device = MovedTo(device.wipe_device) - recovery_device = MovedTo(device.recovery_device) - reset_device = MovedTo(device.reset_device) - backup_device = MovedTo(device.backup_device) + wipe_device = MovedTo(device.wipe) + recovery_device = MovedTo(device.recover) + reset_device = MovedTo(device.reset) + backup_device = MovedTo(device.backup) load_device_by_mnemonic = MovedTo(device.load_device_by_mnemonic) load_device_by_xprv = MovedTo(device.load_device_by_xprv) diff --git a/trezorlib/device.py b/trezorlib/device.py index b5577b5f89..080355ddbc 100644 --- a/trezorlib/device.py +++ b/trezorlib/device.py @@ -86,14 +86,14 @@ def set_u2f_counter(client, u2f_counter): @expect(proto.Success, field="message") -def wipe_device(client): +def wipe(client): ret = client.call(proto.WipeDevice()) client.init_device() return ret @expect(proto.Success, field="message") -def recovery_device(client, word_count, passphrase_protection, pin_protection, label, language, type=proto.RecoveryDeviceType.ScrambledWords, expand=False, dry_run=False): +def recover(client, word_count, passphrase_protection, pin_protection, label, language, type=proto.RecoveryDeviceType.ScrambledWords, expand=False, dry_run=False): if client.features.initialized and not dry_run: raise RuntimeError("Device is initialized already. Call wipe_device() and try again.") @@ -123,7 +123,7 @@ def recovery_device(client, word_count, passphrase_protection, pin_protection, l @expect(proto.Success, field="message") @session -def reset_device(client, display_random, strength, passphrase_protection, pin_protection, label, language, u2f_counter=0, skip_backup=False): +def reset(client, display_random, strength, passphrase_protection, pin_protection, label, language, u2f_counter=0, skip_backup=False): if client.features.initialized: raise RuntimeError("Device is initialized already. Call wipe_device() and try again.") @@ -149,7 +149,7 @@ def reset_device(client, display_random, strength, passphrase_protection, pin_pr @expect(proto.Success, field="message") -def backup_device(client): +def backup(client): ret = client.call(proto.BackupDevice()) return ret From d5dee0c89790d26cd1633836af7bd02e52a3bb43 Mon Sep 17 00:00:00 2001 From: matejcik Date: Fri, 10 Aug 2018 13:33:14 +0200 Subject: [PATCH 11/37] trezorlib: move mostly-debug methods from device to debuglink --- trezorlib/client.py | 12 +++--- trezorlib/debuglink.py | 86 +++++++++++++++++++++++++++++++++++++++++- trezorlib/device.py | 80 --------------------------------------- 3 files changed, 91 insertions(+), 87 deletions(-) diff --git a/trezorlib/client.py b/trezorlib/client.py index 94858c5492..aad06ca73c 100644 --- a/trezorlib/client.py +++ b/trezorlib/client.py @@ -31,7 +31,7 @@ from . import messages as proto from . import btc, cosi, device, ethereum, firmware, lisk, misc, nem, stellar from . import mapping from . import tools -from .debuglink import DebugLink +from . import debuglink if sys.version_info.major < 3: raise Exception("Trezorlib does not support Python 2 anymore.") @@ -273,7 +273,7 @@ class DebugLinkMixin(object): self.debug.close() def set_debuglink(self, debug_transport): - self.debug = DebugLink(debug_transport) + self.debug = debuglink.DebugLink(debug_transport) def set_buttonwait(self, secs): self.button_wait = secs @@ -454,15 +454,15 @@ class ProtocolMixin(object): return self.call(proto.ClearSession()) # Device functionality - self_test = MovedTo(device.self_test) - wipe_device = MovedTo(device.wipe) recovery_device = MovedTo(device.recover) reset_device = MovedTo(device.reset) backup_device = MovedTo(device.backup) - load_device_by_mnemonic = MovedTo(device.load_device_by_mnemonic) - load_device_by_xprv = MovedTo(device.load_device_by_xprv) + # debugging + load_device_by_mnemonic = MovedTo(debuglink.load_device_by_mnemonic) + load_device_by_xprv = MovedTo(debuglink.load_device_by_xprv) + self_test = MovedTo(debuglink.self_test) set_u2f_counter = MovedTo(device.set_u2f_counter) diff --git a/trezorlib/debuglink.py b/trezorlib/debuglink.py index 84aa8a6033..9847e04632 100644 --- a/trezorlib/debuglink.py +++ b/trezorlib/debuglink.py @@ -14,9 +14,13 @@ # You should have received a copy of the License along with this library. # If not, see . -from __future__ import print_function +import binascii + +from mnemonic import Mnemonic from . import messages as proto +from . import tools +from .tools import expect def pin_info(pin): @@ -138,3 +142,83 @@ class DebugLink(object): def flash_erase(self, sector): self._call(proto.DebugLinkFlashErase(sector=sector), nowait=True) + + +@expect(proto.Success, field="message") +def load_device_by_mnemonic(client, mnemonic, pin, passphrase_protection, label, language='english', skip_checksum=False, expand=False): + # Convert mnemonic to UTF8 NKFD + mnemonic = Mnemonic.normalize_string(mnemonic) + + # Convert mnemonic to ASCII stream + mnemonic = mnemonic.encode('utf-8') + + m = Mnemonic('english') + + if expand: + mnemonic = m.expand(mnemonic) + + if not skip_checksum and not m.check(mnemonic): + raise ValueError("Invalid mnemonic checksum") + + if client.features.initialized: + raise RuntimeError("Device is initialized already. Call wipe_device() and try again.") + + resp = client.call(proto.LoadDevice(mnemonic=mnemonic, pin=pin, + passphrase_protection=passphrase_protection, + language=language, + label=label, + skip_checksum=skip_checksum)) + client.init_device() + return resp + + +@expect(proto.Success, field="message") +def load_device_by_xprv(client, xprv, pin, passphrase_protection, label, language): + if client.features.initialized: + raise RuntimeError("Device is initialized already. Call wipe_device() and try again.") + + if xprv[0:4] not in ('xprv', 'tprv'): + raise ValueError("Unknown type of xprv") + + if not 100 < len(xprv) < 112: # yes this is correct in Python + raise ValueError("Invalid length of xprv") + + node = proto.HDNodeType() + data = binascii.hexlify(tools.b58decode(xprv, None)) + + if data[90:92] != b'00': + raise ValueError("Contain invalid private key") + + checksum = binascii.hexlify(tools.btc_hash(binascii.unhexlify(data[:156]))[:4]) + if checksum != data[156:]: + raise ValueError("Checksum doesn't match") + + # version 0488ade4 + # depth 00 + # fingerprint 00000000 + # child_num 00000000 + # chaincode 873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d508 + # privkey 00e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35 + # checksum e77e9d71 + + node.depth = int(data[8:10], 16) + node.fingerprint = int(data[10:18], 16) + node.child_num = int(data[18:26], 16) + node.chain_code = binascii.unhexlify(data[26:90]) + node.private_key = binascii.unhexlify(data[92:156]) # skip 0x00 indicating privkey + + resp = client.call(proto.LoadDevice(node=node, + pin=pin, + passphrase_protection=passphrase_protection, + language=language, + label=label)) + client.init_device() + return resp + + +@expect(proto.Success, field="message") +def self_test(client): + if client.features.bootloader_mode is False: + raise RuntimeError("Device must be in bootloader mode") + + return client.call(proto.SelfTest(payload=b'\x00\xFF\x55\xAA\x66\x99\x33\xCCABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\x00\xFF\x55\xAA\x66\x99\x33\xCC')) diff --git a/trezorlib/device.py b/trezorlib/device.py index 080355ddbc..e8e3c1b5f2 100644 --- a/trezorlib/device.py +++ b/trezorlib/device.py @@ -152,83 +152,3 @@ def reset(client, display_random, strength, passphrase_protection, pin_protectio def backup(client): ret = client.call(proto.BackupDevice()) return ret - - -@expect(proto.Success, field="message") -def load_device_by_mnemonic(client, mnemonic, pin, passphrase_protection, label, language='english', skip_checksum=False, expand=False): - # Convert mnemonic to UTF8 NKFD - mnemonic = Mnemonic.normalize_string(mnemonic) - - # Convert mnemonic to ASCII stream - mnemonic = mnemonic.encode('utf-8') - - m = Mnemonic('english') - - if expand: - mnemonic = m.expand(mnemonic) - - if not skip_checksum and not m.check(mnemonic): - raise ValueError("Invalid mnemonic checksum") - - if client.features.initialized: - raise RuntimeError("Device is initialized already. Call wipe_device() and try again.") - - resp = client.call(proto.LoadDevice(mnemonic=mnemonic, pin=pin, - passphrase_protection=passphrase_protection, - language=language, - label=label, - skip_checksum=skip_checksum)) - client.init_device() - return resp - - -@expect(proto.Success, field="message") -def load_device_by_xprv(client, xprv, pin, passphrase_protection, label, language): - if client.features.initialized: - raise RuntimeError("Device is initialized already. Call wipe_device() and try again.") - - if xprv[0:4] not in ('xprv', 'tprv'): - raise ValueError("Unknown type of xprv") - - if not 100 < len(xprv) < 112: # yes this is correct in Python - raise ValueError("Invalid length of xprv") - - node = proto.HDNodeType() - data = binascii.hexlify(tools.b58decode(xprv, None)) - - if data[90:92] != b'00': - raise ValueError("Contain invalid private key") - - checksum = binascii.hexlify(tools.btc_hash(binascii.unhexlify(data[:156]))[:4]) - if checksum != data[156:]: - raise ValueError("Checksum doesn't match") - - # version 0488ade4 - # depth 00 - # fingerprint 00000000 - # child_num 00000000 - # chaincode 873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d508 - # privkey 00e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35 - # checksum e77e9d71 - - node.depth = int(data[8:10], 16) - node.fingerprint = int(data[10:18], 16) - node.child_num = int(data[18:26], 16) - node.chain_code = binascii.unhexlify(data[26:90]) - node.private_key = binascii.unhexlify(data[92:156]) # skip 0x00 indicating privkey - - resp = client.call(proto.LoadDevice(node=node, - pin=pin, - passphrase_protection=passphrase_protection, - language=language, - label=label)) - client.init_device() - return resp - - -@expect(proto.Success, field="message") -def self_test(client): - if client.features.bootloader_mode is False: - raise RuntimeError("Device must be in bootloader mode") - - return client.call(proto.SelfTest(payload=b'\x00\xFF\x55\xAA\x66\x99\x33\xCCABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\x00\xFF\x55\xAA\x66\x99\x33\xCC')) From c0ef1ec53502a95c09ca52a6a4658a3900cf6d48 Mon Sep 17 00:00:00 2001 From: matejcik Date: Fri, 10 Aug 2018 14:04:58 +0200 Subject: [PATCH 12/37] tests: use new API --- trezorlib/tests/device_tests/common.py | 45 ++++++++----- trezorlib/tests/device_tests/test_basic.py | 3 +- .../tests/device_tests/test_bip32_speed.py | 13 ++-- trezorlib/tests/device_tests/test_cosi.py | 28 ++++---- .../device_tests/test_msg_applysettings.py | 17 ++--- .../device_tests/test_msg_cipherkeyvalue.py | 33 +++++----- .../test_msg_ethereum_getaddress.py | 11 ++-- .../test_msg_ethereum_signmessage.py | 3 +- .../device_tests/test_msg_ethereum_signtx.py | 40 +++++++---- .../test_msg_ethereum_signtx_eip155.py | 4 +- .../test_msg_ethereum_verifymessage.py | 4 +- .../tests/device_tests/test_msg_getaddress.py | 41 ++++++------ .../test_msg_getaddress_segwit.py | 13 ++-- .../test_msg_getaddress_segwit_native.py | 15 +++-- .../device_tests/test_msg_getaddress_show.py | 11 ++-- .../test_msg_getecdhsessionkey.py | 7 +- .../tests/device_tests/test_msg_getentropy.py | 3 +- .../device_tests/test_msg_getpublickey.py | 45 ++++++------- .../test_msg_getpublickey_curve.py | 19 +++--- .../device_tests/test_msg_lisk_getaddress.py | 9 +-- .../test_msg_lisk_getpublickey.py | 3 +- .../device_tests/test_msg_lisk_signmessage.py | 5 +- .../device_tests/test_msg_lisk_signtx.py | 13 ++-- .../test_msg_lisk_verifymessage.py | 9 ++- .../tests/device_tests/test_msg_loaddevice.py | 31 +++++---- .../device_tests/test_msg_loaddevice_xprv.py | 10 +-- .../device_tests/test_msg_nem_getaddress.py | 5 +- .../test_msg_nem_signtx_mosaics.py | 8 +-- .../test_msg_nem_signtx_mosaics_t2.py | 2 +- .../test_msg_nem_signtx_multisig.py | 10 +-- .../test_msg_nem_signtx_others.py | 4 +- .../test_msg_nem_signtx_transfers.py | 14 ++-- .../device_tests/test_msg_recoverydevice.py | 3 +- .../test_msg_recoverydevice_t2.py | 3 +- .../device_tests/test_msg_resetdevice.py | 3 +- .../device_tests/test_msg_resetdevice_t2.py | 3 +- .../test_msg_ripple_get_address.py | 4 +- .../device_tests/test_msg_signidentity.py | 9 +-- .../device_tests/test_msg_signmessage.py | 13 ++-- .../test_msg_signmessage_segwit.py | 11 ++-- .../test_msg_signmessage_segwit_native.py | 11 ++-- .../tests/device_tests/test_msg_signtx.py | 35 +++++----- .../device_tests/test_msg_signtx_bcash.py | 23 +++---- .../device_tests/test_msg_signtx_bgold.py | 23 +++---- .../device_tests/test_msg_signtx_decred.py | 9 +-- .../device_tests/test_msg_signtx_segwit.py | 15 +++-- .../test_msg_signtx_segwit_native.py | 35 +++++----- .../device_tests/test_msg_signtx_zcash.py | 3 +- .../test_msg_stellar_get_address.py | 16 +++-- .../test_msg_stellar_get_public_key.py | 4 +- .../test_msg_stellar_sign_transaction.py | 14 ++-- .../device_tests/test_msg_verifymessage.py | 66 ++++++++++++------- .../test_msg_verifymessage_segwit.py | 30 +++++---- .../test_msg_verifymessage_segwit_native.py | 30 +++++---- .../tests/device_tests/test_msg_wipedevice.py | 3 +- trezorlib/tests/device_tests/test_multisig.py | 9 +-- .../device_tests/test_multisig_change.py | 17 ++--- .../tests/device_tests/test_op_return.py | 5 +- .../device_tests/test_protection_levels.py | 35 +++++----- trezorlib/tests/device_tests/test_zerosig.py | 5 +- 60 files changed, 517 insertions(+), 398 deletions(-) diff --git a/trezorlib/tests/device_tests/common.py b/trezorlib/tests/device_tests/common.py index 525c9b6360..4917e5ae43 100644 --- a/trezorlib/tests/device_tests/common.py +++ b/trezorlib/tests/device_tests/common.py @@ -21,12 +21,23 @@ from . import conftest from trezorlib import coins from trezorlib import tx_api from trezorlib.client import TrezorClientDebugLink +from trezorlib import debuglink +from trezorlib import device tests_dir = os.path.dirname(os.path.abspath(__file__)) tx_api.cache_dir = os.path.join(tests_dir, '../txcache') class TrezorTest: + # 1 2 3 4 5 6 7 8 9 10 11 12 + mnemonic12 = 'alcohol woman abuse must during monitor noble actual mixed trade anger aisle' + mnemonic18 = 'owner little vague addict embark decide pink prosper true fork panda embody mixture exchange choose canoe electric jewel' + mnemonic24 = 'dignity pass list indicate nasty swamp pool script soccer toe leaf photo multiply desk host tomato cradle drill spread actor shine dismiss champion exotic' + mnemonic_all = ' '.join(['all'] * 12) + + pin4 = '1234' + pin6 = '789456' + pin8 = '45678978' def setup_method(self, method): wirelink = conftest.get_device() @@ -36,37 +47,39 @@ class TrezorTest: self.client.set_tx_api(coins.tx_api['Bitcoin']) # self.client.set_buttonwait(3) - # 1 2 3 4 5 6 7 8 9 10 11 12 - self.mnemonic12 = 'alcohol woman abuse must during monitor noble actual mixed trade anger aisle' - self.mnemonic18 = 'owner little vague addict embark decide pink prosper true fork panda embody mixture exchange choose canoe electric jewel' - self.mnemonic24 = 'dignity pass list indicate nasty swamp pool script soccer toe leaf photo multiply desk host tomato cradle drill spread actor shine dismiss champion exotic' - self.mnemonic_all = ' '.join(['all'] * 12) - - self.pin4 = '1234' - self.pin6 = '789456' - self.pin8 = '45678978' - - self.client.wipe_device() + device.wipe(self.client) self.client.transport.session_begin() def teardown_method(self, method): self.client.transport.session_end() self.client.close() + 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", + ) + def setup_mnemonic_allallall(self): - self.client.load_device_by_mnemonic(mnemonic=self.mnemonic_all, pin='', passphrase_protection=False, label='test', language='english') + self._setup_mnemonic(mnemonic=TrezorTest.mnemonic_all) def setup_mnemonic_nopin_nopassphrase(self): - self.client.load_device_by_mnemonic(mnemonic=self.mnemonic12, pin='', passphrase_protection=False, label='test', language='english') + self._setup_mnemonic() def setup_mnemonic_nopin_passphrase(self): - self.client.load_device_by_mnemonic(mnemonic=self.mnemonic12, pin='', passphrase_protection=True, label='test', language='english') + self._setup_mnemonic(passphrase=True) def setup_mnemonic_pin_nopassphrase(self): - self.client.load_device_by_mnemonic(mnemonic=self.mnemonic12, pin=self.pin4, passphrase_protection=False, label='test', language='english') + self._setup_mnemonic(pin=TrezorTest.pin4) def setup_mnemonic_pin_passphrase(self): - self.client.load_device_by_mnemonic(mnemonic=self.mnemonic12, pin=self.pin4, passphrase_protection=True, label='test', language='english') + self._setup_mnemonic(pin=TrezorTest.pin4, passphrase=True) def generate_entropy(strength, internal_entropy, external_entropy): diff --git a/trezorlib/tests/device_tests/test_basic.py b/trezorlib/tests/device_tests/test_basic.py index 0d9d4ac80b..e3203e059e 100644 --- a/trezorlib/tests/device_tests/test_basic.py +++ b/trezorlib/tests/device_tests/test_basic.py @@ -17,6 +17,7 @@ from .common import TrezorTest from trezorlib import messages +from trezorlib import device class TestBasic(TrezorTest): @@ -43,7 +44,7 @@ class TestBasic(TrezorTest): def test_device_id_different(self): id1 = self.client.get_device_id() - self.client.wipe_device() + device.wipe(self.client) id2 = self.client.get_device_id() # Device ID must be fresh after every reset diff --git a/trezorlib/tests/device_tests/test_bip32_speed.py b/trezorlib/tests/device_tests/test_bip32_speed.py index 946399289d..001e6fae5e 100644 --- a/trezorlib/tests/device_tests/test_bip32_speed.py +++ b/trezorlib/tests/device_tests/test_bip32_speed.py @@ -20,6 +20,7 @@ import pytest from .common import TrezorTest from trezorlib.tools import H_ +from trezorlib import btc class TestBip32Speed(TrezorTest): @@ -27,11 +28,11 @@ class TestBip32Speed(TrezorTest): def test_public_ckd(self): self.setup_mnemonic_nopin_nopassphrase() - self.client.get_address('Bitcoin', []) # to compute root node via BIP39 + btc.get_address(self.client, 'Bitcoin', []) # to compute root node via BIP39 for depth in range(8): start = time.time() - self.client.get_address('Bitcoin', range(depth)) + btc.get_address(self.client, 'Bitcoin', range(depth)) delay = time.time() - start expected = (depth + 1) * 0.26 print("DEPTH", depth, "EXPECTED DELAY", expected, "REAL DELAY", delay) @@ -40,12 +41,12 @@ class TestBip32Speed(TrezorTest): def test_private_ckd(self): self.setup_mnemonic_nopin_nopassphrase() - self.client.get_address('Bitcoin', []) # to compute root node via BIP39 + btc.get_address(self.client, 'Bitcoin', []) # to compute root node via BIP39 for depth in range(8): start = time.time() address_n = [H_(-i) for i in range(-depth, 0)] - self.client.get_address('Bitcoin', address_n) + btc.get_address(self.client, 'Bitcoin', address_n) delay = time.time() - start expected = (depth + 1) * 0.26 print("DEPTH", depth, "EXPECTED DELAY", expected, "REAL DELAY", delay) @@ -57,12 +58,12 @@ class TestBip32Speed(TrezorTest): start = time.time() for x in range(10): - self.client.get_address('Bitcoin', [x, 2, 3, 4, 5, 6, 7, 8]) + btc.get_address(self.client, 'Bitcoin', [x, 2, 3, 4, 5, 6, 7, 8]) nocache_time = time.time() - start start = time.time() for x in range(10): - self.client.get_address('Bitcoin', [1, 2, 3, 4, 5, 6, 7, x]) + btc.get_address(self.client, 'Bitcoin', [1, 2, 3, 4, 5, 6, 7, x]) cache_time = time.time() - start print("NOCACHE TIME", nocache_time) diff --git a/trezorlib/tests/device_tests/test_cosi.py b/trezorlib/tests/device_tests/test_cosi.py index 698d512b01..162ef76236 100644 --- a/trezorlib/tests/device_tests/test_cosi.py +++ b/trezorlib/tests/device_tests/test_cosi.py @@ -31,9 +31,9 @@ class TestCosi(TrezorTest): digest = sha256(b'this is a message').digest() - c0 = self.client.cosi_commit(parse_path("10018'/0'"), digest) - c1 = self.client.cosi_commit(parse_path("10018'/1'"), digest) - c2 = self.client.cosi_commit(parse_path("10018'/2'"), digest) + c0 = cosi.commit(self.client, parse_path("10018'/0'"), digest) + c1 = cosi.commit(self.client, parse_path("10018'/1'"), digest) + c2 = cosi.commit(self.client, parse_path("10018'/2'"), digest) assert c0.pubkey != c1.pubkey assert c0.pubkey != c2.pubkey @@ -45,9 +45,9 @@ class TestCosi(TrezorTest): digestb = sha256(b'this is a different message').digest() - c0b = self.client.cosi_commit(parse_path("10018'/0'"), digestb) - c1b = self.client.cosi_commit(parse_path("10018'/1'"), digestb) - c2b = self.client.cosi_commit(parse_path("10018'/2'"), digestb) + c0b = cosi.commit(self.client, parse_path("10018'/0'"), digestb) + c1b = cosi.commit(self.client, parse_path("10018'/1'"), digestb) + c2b = cosi.commit(self.client, parse_path("10018'/2'"), digestb) assert c0.pubkey == c0b.pubkey assert c1.pubkey == c1b.pubkey @@ -62,16 +62,16 @@ class TestCosi(TrezorTest): digest = sha256(b'this is a message').digest() - c0 = self.client.cosi_commit(parse_path("10018'/0'"), digest) - c1 = self.client.cosi_commit(parse_path("10018'/1'"), digest) - c2 = self.client.cosi_commit(parse_path("10018'/2'"), digest) + c0 = cosi.commit(self.client, parse_path("10018'/0'"), digest) + c1 = cosi.commit(self.client, parse_path("10018'/1'"), digest) + c2 = cosi.commit(self.client, parse_path("10018'/2'"), digest) global_pk = cosi.combine_keys([c0.pubkey, c1.pubkey, c2.pubkey]) global_R = cosi.combine_keys([c0.commitment, c1.commitment, c2.commitment]) - sig0 = self.client.cosi_sign(parse_path("10018'/0'"), digest, global_R, global_pk) - sig1 = self.client.cosi_sign(parse_path("10018'/1'"), digest, global_R, global_pk) - sig2 = self.client.cosi_sign(parse_path("10018'/2'"), digest, global_R, global_pk) + sig0 = cosi.sign(self.client, parse_path("10018'/0'"), digest, global_R, global_pk) + sig1 = cosi.sign(self.client, parse_path("10018'/1'"), digest, global_R, global_pk) + sig2 = cosi.sign(self.client, parse_path("10018'/2'"), digest, global_R, global_pk) sig = cosi.combine_sig(global_R, [sig0.signature, sig1.signature, sig2.signature]) @@ -81,7 +81,7 @@ class TestCosi(TrezorTest): self.setup_mnemonic_pin_passphrase() digest = sha256(b'this is not a pipe').digest() - remote_commit = self.client.cosi_commit(parse_path("10018'/0'"), digest) + remote_commit = cosi.commit(self.client, parse_path("10018'/0'"), digest) local_privkey = sha256(b'private key').digest()[:32] local_pubkey = cosi.pubkey_from_privkey(local_privkey) @@ -90,7 +90,7 @@ class TestCosi(TrezorTest): global_pk = cosi.combine_keys([remote_commit.pubkey, local_pubkey]) global_R = cosi.combine_keys([remote_commit.commitment, local_commitment]) - remote_sig = self.client.cosi_sign(parse_path("10018'/0'"), digest, global_R, global_pk) + remote_sig = cosi.sign(self.client, parse_path("10018'/0'"), digest, global_R, global_pk) local_sig = cosi.sign_with_privkey(digest, local_privkey, global_pk, local_nonce, global_R) sig = cosi.combine_sig(global_R, [remote_sig.signature, local_sig]) diff --git a/trezorlib/tests/device_tests/test_msg_applysettings.py b/trezorlib/tests/device_tests/test_msg_applysettings.py index 23238fc46a..f5541d6383 100644 --- a/trezorlib/tests/device_tests/test_msg_applysettings.py +++ b/trezorlib/tests/device_tests/test_msg_applysettings.py @@ -20,6 +20,7 @@ from .common import TrezorTest import time from trezorlib import messages as proto +from trezorlib import device class TestMsgApplysettings(TrezorTest): @@ -35,7 +36,7 @@ class TestMsgApplysettings(TrezorTest): proto.Features()]) if self.client.features.major_version >= 2: self.client.expected_responses.pop(0) # skip PinMatrixRequest - self.client.apply_settings(label='new label') + device.apply_settings(self.client, label='new label') assert self.client.features.label == 'new label' @@ -49,7 +50,7 @@ class TestMsgApplysettings(TrezorTest): proto.ButtonRequest(), proto.Success(), proto.Features()]) - self.client.apply_settings(language='nonexistent') + device.apply_settings(self.client, language='nonexistent') assert self.client.features.language == 'english' @@ -65,7 +66,7 @@ class TestMsgApplysettings(TrezorTest): proto.Features()]) if self.client.features.major_version >= 2: self.client.expected_responses.pop(0) # skip PinMatrixRequest - self.client.apply_settings(use_passphrase=True) + device.apply_settings(self.client, use_passphrase=True) assert self.client.features.passphrase_protection is True @@ -73,7 +74,7 @@ class TestMsgApplysettings(TrezorTest): self.client.set_expected_responses([proto.ButtonRequest(), proto.Success(), proto.Features()]) - self.client.apply_settings(use_passphrase=False) + device.apply_settings(self.client, use_passphrase=False) assert self.client.features.passphrase_protection is False @@ -81,7 +82,7 @@ class TestMsgApplysettings(TrezorTest): self.client.set_expected_responses([proto.ButtonRequest(), proto.Success(), proto.Features()]) - self.client.apply_settings(use_passphrase=True) + device.apply_settings(self.client, use_passphrase=True) assert self.client.features.passphrase_protection is True @@ -96,7 +97,7 @@ class TestMsgApplysettings(TrezorTest): proto.ButtonRequest(), proto.Success(), proto.Features()]) - self.client.apply_settings(homescreen=img) + device.apply_settings(self.client, homescreen=img) @pytest.mark.skip_t2 def test_apply_auto_lock_delay(self): @@ -107,7 +108,7 @@ class TestMsgApplysettings(TrezorTest): proto.ButtonRequest(), proto.Success(), proto.Features()]) - self.client.apply_settings(auto_lock_delay_ms=int(10e3)) # 10 secs + device.apply_settings(self.client, auto_lock_delay_ms=int(10e3)) # 10 secs time.sleep(0.1) # sleep less than auto-lock delay with self.client: @@ -135,7 +136,7 @@ class TestMsgApplysettings(TrezorTest): proto.Success(), proto.Features()]) # Note: the actual delay will be 10 secs (see above). - self.client.apply_settings(auto_lock_delay_ms=int(1e3)) + device.apply_settings(self.client, auto_lock_delay_ms=int(1e3)) time.sleep(0.1) # sleep less than auto-lock delay with self.client: diff --git a/trezorlib/tests/device_tests/test_msg_cipherkeyvalue.py b/trezorlib/tests/device_tests/test_msg_cipherkeyvalue.py index f9c92a82d0..5527580453 100644 --- a/trezorlib/tests/device_tests/test_msg_cipherkeyvalue.py +++ b/trezorlib/tests/device_tests/test_msg_cipherkeyvalue.py @@ -18,6 +18,7 @@ from binascii import hexlify, unhexlify import pytest from .common import TrezorTest +from trezorlib import misc class TestMsgCipherkeyvalue(TrezorTest): @@ -26,64 +27,64 @@ class TestMsgCipherkeyvalue(TrezorTest): self.setup_mnemonic_nopin_nopassphrase() # different ask values - res = self.client.encrypt_keyvalue([0, 1, 2], b"test", b"testing message!", ask_on_encrypt=True, ask_on_decrypt=True) + res = misc.encrypt_keyvalue(self.client, [0, 1, 2], b"test", b"testing message!", ask_on_encrypt=True, ask_on_decrypt=True) assert hexlify(res) == b'676faf8f13272af601776bc31bc14e8f' - res = self.client.encrypt_keyvalue([0, 1, 2], b"test", b"testing message!", ask_on_encrypt=True, ask_on_decrypt=False) + res = misc.encrypt_keyvalue(self.client, [0, 1, 2], b"test", b"testing message!", ask_on_encrypt=True, ask_on_decrypt=False) assert hexlify(res) == b'5aa0fbcb9d7fa669880745479d80c622' - res = self.client.encrypt_keyvalue([0, 1, 2], b"test", b"testing message!", ask_on_encrypt=False, ask_on_decrypt=True) + res = misc.encrypt_keyvalue(self.client, [0, 1, 2], b"test", b"testing message!", ask_on_encrypt=False, ask_on_decrypt=True) assert hexlify(res) == b'958d4f63269b61044aaedc900c8d6208' - res = self.client.encrypt_keyvalue([0, 1, 2], b"test", b"testing message!", ask_on_encrypt=False, ask_on_decrypt=False) + res = misc.encrypt_keyvalue(self.client, [0, 1, 2], b"test", b"testing message!", ask_on_encrypt=False, ask_on_decrypt=False) assert hexlify(res) == b'e0cf0eb0425947000eb546cc3994bc6c' # different key - res = self.client.encrypt_keyvalue([0, 1, 2], b"test2", b"testing message!", ask_on_encrypt=True, ask_on_decrypt=True) + res = misc.encrypt_keyvalue(self.client, [0, 1, 2], b"test2", b"testing message!", ask_on_encrypt=True, ask_on_decrypt=True) assert hexlify(res) == b'de247a6aa6be77a134bb3f3f925f13af' # different message - res = self.client.encrypt_keyvalue([0, 1, 2], b"test", b"testing message! it is different", ask_on_encrypt=True, ask_on_decrypt=True) + res = misc.encrypt_keyvalue(self.client, [0, 1, 2], b"test", b"testing message! it is different", ask_on_encrypt=True, ask_on_decrypt=True) assert hexlify(res) == b'676faf8f13272af601776bc31bc14e8f3ae1c88536bf18f1b44f1e4c2c4a613d' # different path - res = self.client.encrypt_keyvalue([0, 1, 3], b"test", b"testing message!", ask_on_encrypt=True, ask_on_decrypt=True) + res = misc.encrypt_keyvalue(self.client, [0, 1, 3], b"test", b"testing message!", ask_on_encrypt=True, ask_on_decrypt=True) assert hexlify(res) == b'b4811a9d492f5355a5186ddbfccaae7b' def test_decrypt(self): self.setup_mnemonic_nopin_nopassphrase() # different ask values - res = self.client.decrypt_keyvalue([0, 1, 2], b"test", unhexlify("676faf8f13272af601776bc31bc14e8f"), ask_on_encrypt=True, ask_on_decrypt=True) + res = misc.decrypt_keyvalue(self.client, [0, 1, 2], b"test", unhexlify("676faf8f13272af601776bc31bc14e8f"), ask_on_encrypt=True, ask_on_decrypt=True) assert res == b'testing message!' - res = self.client.decrypt_keyvalue([0, 1, 2], b"test", unhexlify("5aa0fbcb9d7fa669880745479d80c622"), ask_on_encrypt=True, ask_on_decrypt=False) + res = misc.decrypt_keyvalue(self.client, [0, 1, 2], b"test", unhexlify("5aa0fbcb9d7fa669880745479d80c622"), ask_on_encrypt=True, ask_on_decrypt=False) assert res == b'testing message!' - res = self.client.decrypt_keyvalue([0, 1, 2], b"test", unhexlify("958d4f63269b61044aaedc900c8d6208"), ask_on_encrypt=False, ask_on_decrypt=True) + res = misc.decrypt_keyvalue(self.client, [0, 1, 2], b"test", unhexlify("958d4f63269b61044aaedc900c8d6208"), ask_on_encrypt=False, ask_on_decrypt=True) assert res == b'testing message!' - res = self.client.decrypt_keyvalue([0, 1, 2], b"test", unhexlify("e0cf0eb0425947000eb546cc3994bc6c"), ask_on_encrypt=False, ask_on_decrypt=False) + res = misc.decrypt_keyvalue(self.client, [0, 1, 2], b"test", unhexlify("e0cf0eb0425947000eb546cc3994bc6c"), ask_on_encrypt=False, ask_on_decrypt=False) assert res == b'testing message!' # different key - res = self.client.decrypt_keyvalue([0, 1, 2], b"test2", unhexlify("de247a6aa6be77a134bb3f3f925f13af"), ask_on_encrypt=True, ask_on_decrypt=True) + res = misc.decrypt_keyvalue(self.client, [0, 1, 2], b"test2", unhexlify("de247a6aa6be77a134bb3f3f925f13af"), ask_on_encrypt=True, ask_on_decrypt=True) assert res == b'testing message!' # different message - res = self.client.decrypt_keyvalue([0, 1, 2], b"test", unhexlify("676faf8f13272af601776bc31bc14e8f3ae1c88536bf18f1b44f1e4c2c4a613d"), ask_on_encrypt=True, ask_on_decrypt=True) + res = misc.decrypt_keyvalue(self.client, [0, 1, 2], b"test", unhexlify("676faf8f13272af601776bc31bc14e8f3ae1c88536bf18f1b44f1e4c2c4a613d"), ask_on_encrypt=True, ask_on_decrypt=True) assert res == b'testing message! it is different' # different path - res = self.client.decrypt_keyvalue([0, 1, 3], b"test", unhexlify("b4811a9d492f5355a5186ddbfccaae7b"), ask_on_encrypt=True, ask_on_decrypt=True) + res = misc.decrypt_keyvalue(self.client, [0, 1, 3], b"test", unhexlify("b4811a9d492f5355a5186ddbfccaae7b"), ask_on_encrypt=True, ask_on_decrypt=True) assert res == b'testing message!' def test_encrypt_badlen(self): self.setup_mnemonic_nopin_nopassphrase() with pytest.raises(Exception): - self.client.encrypt_keyvalue([0, 1, 2], b"test", b"testing") + misc.encrypt_keyvalue(self.client, [0, 1, 2], b"test", b"testing") def test_decrypt_badlen(self): self.setup_mnemonic_nopin_nopassphrase() with pytest.raises(Exception): - self.client.decrypt_keyvalue([0, 1, 2], b"test", b"testing") + misc.decrypt_keyvalue(self.client, [0, 1, 2], b"test", b"testing") diff --git a/trezorlib/tests/device_tests/test_msg_ethereum_getaddress.py b/trezorlib/tests/device_tests/test_msg_ethereum_getaddress.py index fb26777662..9e8e48bda5 100644 --- a/trezorlib/tests/device_tests/test_msg_ethereum_getaddress.py +++ b/trezorlib/tests/device_tests/test_msg_ethereum_getaddress.py @@ -20,6 +20,7 @@ import pytest from .common import TrezorTest from trezorlib.tools import H_ +from trezorlib import ethereum @pytest.mark.ethereum @@ -27,8 +28,8 @@ class TestMsgEthereumGetaddress(TrezorTest): def test_ethereum_getaddress(self): self.setup_mnemonic_nopin_nopassphrase() - assert hexlify(self.client.ethereum_get_address([])) == b'1d1c328764a41bda0492b66baa30c4a339ff85ef' - assert hexlify(self.client.ethereum_get_address([1])) == b'437207ca3cf43bf2e47dea0756d736c5df4f597a' - assert hexlify(self.client.ethereum_get_address([0, H_(1)])) == b'e5d96dfa07bcf1a3ae43677840c31394258861bf' - assert hexlify(self.client.ethereum_get_address([H_(9), 0])) == b'f68804ac9eca9483ab4241d3e4751590d2c05102' - assert hexlify(self.client.ethereum_get_address([0, 9999999])) == b'7a6366ecfcaf0d5dcc1539c171696c6cdd1eb8ed' + assert hexlify(ethereum.get_address(self.client, [])) == b'1d1c328764a41bda0492b66baa30c4a339ff85ef' + assert hexlify(ethereum.get_address(self.client, [1])) == b'437207ca3cf43bf2e47dea0756d736c5df4f597a' + assert hexlify(ethereum.get_address(self.client, [0, H_(1)])) == b'e5d96dfa07bcf1a3ae43677840c31394258861bf' + assert hexlify(ethereum.get_address(self.client, [H_(9), 0])) == b'f68804ac9eca9483ab4241d3e4751590d2c05102' + assert hexlify(ethereum.get_address(self.client, [0, 9999999])) == b'7a6366ecfcaf0d5dcc1539c171696c6cdd1eb8ed' diff --git a/trezorlib/tests/device_tests/test_msg_ethereum_signmessage.py b/trezorlib/tests/device_tests/test_msg_ethereum_signmessage.py index 55b1913590..41c122e20d 100644 --- a/trezorlib/tests/device_tests/test_msg_ethereum_signmessage.py +++ b/trezorlib/tests/device_tests/test_msg_ethereum_signmessage.py @@ -18,6 +18,7 @@ from binascii import hexlify import pytest from .common import TrezorTest +from trezorlib import ethereum @pytest.mark.ethereum @@ -33,6 +34,6 @@ class TestMsgEthereumSignmessage(TrezorTest): def test_sign(self): self.setup_mnemonic_nopin_nopassphrase() for msg, sig in self.VECTORS: - res = self.client.ethereum_sign_message(self.PATH, msg) + res = ethereum.sign_message(self.client, self.PATH, msg) assert hexlify(res.address) == self.ADDRESS assert hexlify(res.signature) == sig diff --git a/trezorlib/tests/device_tests/test_msg_ethereum_signtx.py b/trezorlib/tests/device_tests/test_msg_ethereum_signtx.py index 25d284a280..020b978055 100644 --- a/trezorlib/tests/device_tests/test_msg_ethereum_signtx.py +++ b/trezorlib/tests/device_tests/test_msg_ethereum_signtx.py @@ -19,6 +19,7 @@ import pytest from .common import TrezorTest from trezorlib import messages as proto +from trezorlib import ethereum @pytest.mark.ethereum @@ -43,7 +44,8 @@ class TestMsgEthereumSigntx(TrezorTest): data.extend(unhexlify('000000000000000000000000000000000000000000000000000000000bebc200')) # 200 000 000 in dec, divisibility of ADT = 9, trezor1 displays 0.2 ADT, Trezor T 200 000 000 Wei ADT - sig_v, sig_r, sig_s = self.client.ethereum_sign_tx( + sig_v, sig_r, sig_s = ethereum.sign_tx( + self.client, n=[0, 0], nonce=0, gas_price=20, @@ -78,7 +80,8 @@ class TestMsgEthereumSigntx(TrezorTest): data.extend(unhexlify('0000000000000000000000000000000000000000000000000000000000000123')) # since this token is unknown trezor should display "unknown token value" - sig_v, sig_r, sig_s = self.client.ethereum_sign_tx( + sig_v, sig_r, sig_s = ethereum.sign_tx( + self.client, n=[0, 0], nonce=0, gas_price=20, @@ -104,7 +107,8 @@ class TestMsgEthereumSigntx(TrezorTest): proto.EthereumTxRequest(data_length=None), # v,r,s checked with assert ]) - sig_v, sig_r, sig_s = self.client.ethereum_sign_tx( + sig_v, sig_r, sig_s = ethereum.sign_tx( + self.client, n=[0, 0], nonce=0, gas_price=20, @@ -123,7 +127,8 @@ class TestMsgEthereumSigntx(TrezorTest): proto.EthereumTxRequest(data_length=None), ]) - sig_v, sig_r, sig_s = self.client.ethereum_sign_tx( + sig_v, sig_r, sig_s = ethereum.sign_tx( + self.client, n=[0, 0], nonce=123456, gas_price=20000, @@ -145,7 +150,8 @@ class TestMsgEthereumSigntx(TrezorTest): proto.EthereumTxRequest(data_length=None), ]) - sig_v, sig_r, sig_s = self.client.ethereum_sign_tx( + sig_v, sig_r, sig_s = ethereum.sign_tx( + self.client, n=[0, 0], nonce=0, gas_price=20, @@ -169,7 +175,8 @@ class TestMsgEthereumSigntx(TrezorTest): proto.EthereumTxRequest(), ]) - sig_v, sig_r, sig_s = self.client.ethereum_sign_tx( + sig_v, sig_r, sig_s = ethereum.sign_tx( + self.client, n=[0, 0], nonce=123456, gas_price=20000, @@ -196,7 +203,8 @@ class TestMsgEthereumSigntx(TrezorTest): proto.EthereumTxRequest(), ]) - sig_v, sig_r, sig_s = self.client.ethereum_sign_tx( + sig_v, sig_r, sig_s = ethereum.sign_tx( + self.client, n=[0, 0], nonce=0, gas_price=20000, @@ -213,7 +221,8 @@ class TestMsgEthereumSigntx(TrezorTest): # contract creation without data should fail. with pytest.raises(Exception): - self.client.ethereum_sign_tx( + ethereum.sign_tx( + self.client, n=[0, 0], nonce=123456, gas_price=20000, @@ -234,7 +243,8 @@ class TestMsgEthereumSigntx(TrezorTest): proto.EthereumTxRequest(), ]) - sig_v, sig_r, sig_s = self.client.ethereum_sign_tx( + sig_v, sig_r, sig_s = ethereum.sign_tx( + self.client, n=[0, 0], nonce=0, gas_price=20000, @@ -249,7 +259,8 @@ class TestMsgEthereumSigntx(TrezorTest): def test_ethereum_sanity_checks(self): # gas overflow with pytest.raises(Exception): - self.client.ethereum_sign_tx( + ethereum.sign_tx( + self.client, n=[0, 0], nonce=123456, gas_price=0xffffffffffffffffffffffffffffffff, @@ -260,7 +271,8 @@ class TestMsgEthereumSigntx(TrezorTest): # no gas price with pytest.raises(Exception): - self.client.ethereum_sign_tx( + ethereum.sign_tx( + self.client, n=[0, 0], nonce=123456, gas_limit=10000, @@ -270,7 +282,8 @@ class TestMsgEthereumSigntx(TrezorTest): # no gas limit with pytest.raises(Exception): - self.client.ethereum_sign_tx( + ethereum.sign_tx( + self.client, n=[0, 0], nonce=123456, gas_price=10000, @@ -280,7 +293,8 @@ class TestMsgEthereumSigntx(TrezorTest): # no nonce with pytest.raises(Exception): - self.client.ethereum_sign_tx( + ethereum.sign_tx( + self.client, n=[0, 0], gas_price=10000, gas_limit=123456, diff --git a/trezorlib/tests/device_tests/test_msg_ethereum_signtx_eip155.py b/trezorlib/tests/device_tests/test_msg_ethereum_signtx_eip155.py index d34bd82ad3..da05adf004 100644 --- a/trezorlib/tests/device_tests/test_msg_ethereum_signtx_eip155.py +++ b/trezorlib/tests/device_tests/test_msg_ethereum_signtx_eip155.py @@ -19,6 +19,7 @@ import pytest from .common import TrezorTest from trezorlib import messages as proto +from trezorlib import ethereum @pytest.mark.ethereum @@ -162,7 +163,8 @@ class TestMsgEthereumSigntxChainId(TrezorTest): self.setup_mnemonic_allallall() for ci, n, sv, sr, ss, v, gl, d in VECTORS: - sig_v, sig_r, sig_s = self.client.ethereum_sign_tx( + sig_v, sig_r, sig_s = ethereum.sign_tx( + self.client, n=[0x80000000 | 44, 0x80000000 | 1, 0x80000000, 0, 0], nonce=n, gas_price=20000000000, diff --git a/trezorlib/tests/device_tests/test_msg_ethereum_verifymessage.py b/trezorlib/tests/device_tests/test_msg_ethereum_verifymessage.py index fd8ee20f57..3eae048c7c 100644 --- a/trezorlib/tests/device_tests/test_msg_ethereum_verifymessage.py +++ b/trezorlib/tests/device_tests/test_msg_ethereum_verifymessage.py @@ -19,6 +19,7 @@ from binascii import unhexlify import pytest from .common import TrezorTest +from trezorlib import ethereum @pytest.mark.ethereum @@ -33,7 +34,8 @@ class TestMsgEthereumVerifymessage(TrezorTest): def test_verify(self): self.setup_mnemonic_nopin_nopassphrase() for msg, sig in self.VECTORS: - res = self.client.ethereum_verify_message( + res = ethereum.verify_message( + self.client, unhexlify(self.ADDRESS), unhexlify(sig), msg diff --git a/trezorlib/tests/device_tests/test_msg_getaddress.py b/trezorlib/tests/device_tests/test_msg_getaddress.py index 8acb4d4d2f..d1d4f245ec 100644 --- a/trezorlib/tests/device_tests/test_msg_getaddress.py +++ b/trezorlib/tests/device_tests/test_msg_getaddress.py @@ -21,40 +21,41 @@ from ..support import ckd_public as bip32 from trezorlib import messages as proto from trezorlib.tools import parse_path, H_ +from trezorlib import btc class TestMsgGetaddress(TrezorTest): def test_btc(self): self.setup_mnemonic_nopin_nopassphrase() - assert self.client.get_address('Bitcoin', []) == '1EfKbQupktEMXf4gujJ9kCFo83k1iMqwqK' - assert self.client.get_address('Bitcoin', [1]) == '1CK7SJdcb8z9HuvVft3D91HLpLC6KSsGb' - assert self.client.get_address('Bitcoin', [0, H_(1)]) == '1JVq66pzRBvqaBRFeU9SPVvg3er4ZDgoMs' - assert self.client.get_address('Bitcoin', [H_(9), 0]) == '1F4YdQdL9ZQwvcNTuy5mjyQxXkyCfMcP2P' - assert self.client.get_address('Bitcoin', [0, 9999999]) == '1GS8X3yc7ntzwGw9vXwj9wqmBWZkTFewBV' + assert btc.get_address(self.client, 'Bitcoin', []) == '1EfKbQupktEMXf4gujJ9kCFo83k1iMqwqK' + assert btc.get_address(self.client, 'Bitcoin', [1]) == '1CK7SJdcb8z9HuvVft3D91HLpLC6KSsGb' + assert btc.get_address(self.client, 'Bitcoin', [0, H_(1)]) == '1JVq66pzRBvqaBRFeU9SPVvg3er4ZDgoMs' + assert btc.get_address(self.client, 'Bitcoin', [H_(9), 0]) == '1F4YdQdL9ZQwvcNTuy5mjyQxXkyCfMcP2P' + assert btc.get_address(self.client, 'Bitcoin', [0, 9999999]) == '1GS8X3yc7ntzwGw9vXwj9wqmBWZkTFewBV' def test_ltc(self): self.setup_mnemonic_nopin_nopassphrase() - assert self.client.get_address('Litecoin', []) == 'LYtGrdDeqYUQnTkr5sHT2DKZLG7Hqg7HTK' - assert self.client.get_address('Litecoin', [1]) == 'LKRGNecThFP3Q6c5fosLVA53Z2hUDb1qnE' - assert self.client.get_address('Litecoin', [0, H_(1)]) == 'LcinMK8pVrAtpz7Qpc8jfWzSFsDLgLYfG6' - assert self.client.get_address('Litecoin', [H_(9), 0]) == 'LZHVtcwAEDf1BR4d67551zUijyLUpDF9EX' - assert self.client.get_address('Litecoin', [0, 9999999]) == 'Laf5nGHSCT94C5dK6fw2RxuXPiw2ZuRR9S' + assert btc.get_address(self.client, 'Litecoin', []) == 'LYtGrdDeqYUQnTkr5sHT2DKZLG7Hqg7HTK' + assert btc.get_address(self.client, 'Litecoin', [1]) == 'LKRGNecThFP3Q6c5fosLVA53Z2hUDb1qnE' + assert btc.get_address(self.client, 'Litecoin', [0, H_(1)]) == 'LcinMK8pVrAtpz7Qpc8jfWzSFsDLgLYfG6' + assert btc.get_address(self.client, 'Litecoin', [H_(9), 0]) == 'LZHVtcwAEDf1BR4d67551zUijyLUpDF9EX' + assert btc.get_address(self.client, 'Litecoin', [0, 9999999]) == 'Laf5nGHSCT94C5dK6fw2RxuXPiw2ZuRR9S' def test_tbtc(self): self.setup_mnemonic_nopin_nopassphrase() - assert self.client.get_address('Testnet', [111, 42]) == 'moN6aN6NP1KWgnPSqzrrRPvx2x1UtZJssa' + assert btc.get_address(self.client, 'Testnet', [111, 42]) == 'moN6aN6NP1KWgnPSqzrrRPvx2x1UtZJssa' def test_bch(self): self.setup_mnemonic_allallall() - assert self.client.get_address('Bcash', parse_path("44'/145'/0'/0/0")) == 'bitcoincash:qr08q88p9etk89wgv05nwlrkm4l0urz4cyl36hh9sv' - assert self.client.get_address('Bcash', parse_path("44'/145'/0'/0/1")) == 'bitcoincash:qr23ajjfd9wd73l87j642puf8cad20lfmqdgwvpat4' - assert self.client.get_address('Bcash', parse_path("44'/145'/0'/1/0")) == 'bitcoincash:qzc5q87w069lzg7g3gzx0c8dz83mn7l02scej5aluw' + assert btc.get_address(self.client, 'Bcash', parse_path("44'/145'/0'/0/0")) == 'bitcoincash:qr08q88p9etk89wgv05nwlrkm4l0urz4cyl36hh9sv' + assert btc.get_address(self.client, 'Bcash', parse_path("44'/145'/0'/0/1")) == 'bitcoincash:qr23ajjfd9wd73l87j642puf8cad20lfmqdgwvpat4' + assert btc.get_address(self.client, 'Bcash', parse_path("44'/145'/0'/1/0")) == 'bitcoincash:qzc5q87w069lzg7g3gzx0c8dz83mn7l02scej5aluw' def test_bch_multisig(self): self.setup_mnemonic_allallall() xpubs = [] - for n in map(lambda index: self.client.get_public_node(parse_path("44'/145'/" + str(index) + "'")), range(1, 4)): + for n in map(lambda index: btc.get_public_node(self.client, parse_path("44'/145'/" + str(index) + "'")), range(1, 4)): xpubs.append(n.xpub) def getmultisig(chain, nr, signatures=[b'', b'', b''], xpubs=xpubs): @@ -64,20 +65,20 @@ class TestMsgGetaddress(TrezorTest): m=2, ) for nr in range(1, 4): - assert self.client.get_address('Bcash', parse_path("44'/145'/" + str(nr) + "'/0/0"), show_display=(nr == 1), multisig=getmultisig(0, 0)) == 'bitcoincash:pqguz4nqq64jhr5v3kvpq4dsjrkda75hwy86gq0qzw' - assert self.client.get_address('Bcash', parse_path("44'/145'/" + str(nr) + "'/1/0"), show_display=(nr == 1), multisig=getmultisig(1, 0)) == 'bitcoincash:pp6kcpkhua7789g2vyj0qfkcux3yvje7euhyhltn0a' + assert btc.get_address(self.client, 'Bcash', parse_path("44'/145'/" + str(nr) + "'/0/0"), show_display=(nr == 1), multisig=getmultisig(0, 0)) == 'bitcoincash:pqguz4nqq64jhr5v3kvpq4dsjrkda75hwy86gq0qzw' + assert btc.get_address(self.client, 'Bcash', parse_path("44'/145'/" + str(nr) + "'/1/0"), show_display=(nr == 1), multisig=getmultisig(1, 0)) == 'bitcoincash:pp6kcpkhua7789g2vyj0qfkcux3yvje7euhyhltn0a' def test_public_ckd(self): self.setup_mnemonic_nopin_nopassphrase() - node = self.client.get_public_node([]).node - node_sub1 = self.client.get_public_node([1]).node + node = btc.get_public_node(self.client, []).node + node_sub1 = btc.get_public_node(self.client, [1]).node node_sub2 = bip32.public_ckd(node, [1]) assert node_sub1.chain_code == node_sub2.chain_code assert node_sub1.public_key == node_sub2.public_key - address1 = self.client.get_address('Bitcoin', [1]) + address1 = btc.get_address(self.client, 'Bitcoin', [1]) address2 = bip32.get_address(node_sub2, 0) assert address2 == '1CK7SJdcb8z9HuvVft3D91HLpLC6KSsGb' diff --git a/trezorlib/tests/device_tests/test_msg_getaddress_segwit.py b/trezorlib/tests/device_tests/test_msg_getaddress_segwit.py index a5a0563452..79575c51d6 100644 --- a/trezorlib/tests/device_tests/test_msg_getaddress_segwit.py +++ b/trezorlib/tests/device_tests/test_msg_getaddress_segwit.py @@ -18,20 +18,21 @@ from .common import TrezorTest from ..support import ckd_public as bip32 from trezorlib import messages as proto from trezorlib.tools import parse_path +from trezorlib import btc class TestMsgGetaddressSegwit(TrezorTest): def test_show_segwit(self): self.setup_mnemonic_allallall() - assert self.client.get_address("Testnet", parse_path("49'/1'/0'/1/0"), True, None, script_type=proto.InputScriptType.SPENDP2SHWITNESS) == '2N1LGaGg836mqSQqiuUBLfcyGBhyZbremDX' - assert self.client.get_address("Testnet", parse_path("49'/1'/0'/0/0"), False, None, script_type=proto.InputScriptType.SPENDP2SHWITNESS) == '2N4Q5FhU2497BryFfUgbqkAJE87aKHUhXMp' - assert self.client.get_address("Testnet", parse_path("44'/1'/0'/0/0"), False, None, script_type=proto.InputScriptType.SPENDP2SHWITNESS) == '2N6UeBoqYEEnybg4cReFYDammpsyDw8R2Mc' - assert self.client.get_address("Testnet", parse_path("44'/1'/0'/0/0"), False, None, script_type=proto.InputScriptType.SPENDADDRESS) == 'mvbu1Gdy8SUjTenqerxUaZyYjmveZvt33q' + assert btc.get_address(self.client, "Testnet", parse_path("49'/1'/0'/1/0"), True, None, script_type=proto.InputScriptType.SPENDP2SHWITNESS) == '2N1LGaGg836mqSQqiuUBLfcyGBhyZbremDX' + assert btc.get_address(self.client, "Testnet", parse_path("49'/1'/0'/0/0"), False, None, script_type=proto.InputScriptType.SPENDP2SHWITNESS) == '2N4Q5FhU2497BryFfUgbqkAJE87aKHUhXMp' + assert btc.get_address(self.client, "Testnet", parse_path("44'/1'/0'/0/0"), False, None, script_type=proto.InputScriptType.SPENDP2SHWITNESS) == '2N6UeBoqYEEnybg4cReFYDammpsyDw8R2Mc' + assert btc.get_address(self.client, "Testnet", parse_path("44'/1'/0'/0/0"), False, None, script_type=proto.InputScriptType.SPENDADDRESS) == 'mvbu1Gdy8SUjTenqerxUaZyYjmveZvt33q' def test_show_multisig_3(self): self.setup_mnemonic_allallall() - nodes = map(lambda index: self.client.get_public_node(parse_path("999'/1'/%d'" % index)), range(1, 4)) + nodes = map(lambda index: btc.get_public_node(self.client, parse_path("999'/1'/%d'" % index)), range(1, 4)) multisig1 = proto.MultisigRedeemScriptType( pubkeys=list(map(lambda n: proto.HDNodePathType(node=bip32.deserialize(n.xpub), address_n=[2, 0]), nodes)), signatures=[b'', b'', b''], @@ -43,4 +44,4 @@ class TestMsgGetaddressSegwit(TrezorTest): # m=2, # ) for i in [1, 2, 3]: - assert self.client.get_address("Testnet", parse_path("999'/1'/%d'/2/0" % i), False, multisig1, script_type=proto.InputScriptType.SPENDP2SHWITNESS) == '2N2MxyAfifVhb3AMagisxaj3uij8bfXqf4Y' + assert btc.get_address(self.client, "Testnet", parse_path("999'/1'/%d'/2/0" % i), False, multisig1, script_type=proto.InputScriptType.SPENDP2SHWITNESS) == '2N2MxyAfifVhb3AMagisxaj3uij8bfXqf4Y' diff --git a/trezorlib/tests/device_tests/test_msg_getaddress_segwit_native.py b/trezorlib/tests/device_tests/test_msg_getaddress_segwit_native.py index d6c1d7f24e..e54ecbb6ef 100644 --- a/trezorlib/tests/device_tests/test_msg_getaddress_segwit_native.py +++ b/trezorlib/tests/device_tests/test_msg_getaddress_segwit_native.py @@ -18,20 +18,21 @@ from .common import TrezorTest from ..support import ckd_public as bip32 from trezorlib import messages as proto from trezorlib.tools import parse_path +from trezorlib import btc class TestMsgGetaddressSegwitNative(TrezorTest): def test_show_segwit(self): self.setup_mnemonic_allallall() - assert self.client.get_address("Testnet", parse_path("49'/1'/0'/0/0"), True, None, script_type=proto.InputScriptType.SPENDWITNESS) == 'tb1qqzv60m9ajw8drqulta4ld4gfx0rdh82un5s65s' - assert self.client.get_address("Testnet", parse_path("49'/1'/0'/1/0"), False, None, script_type=proto.InputScriptType.SPENDWITNESS) == 'tb1q694ccp5qcc0udmfwgp692u2s2hjpq5h407urtu' - assert self.client.get_address("Testnet", parse_path("44'/1'/0'/0/0"), False, None, script_type=proto.InputScriptType.SPENDWITNESS) == 'tb1q54un3q39sf7e7tlfq99d6ezys7qgc62a6rxllc' - assert self.client.get_address("Testnet", parse_path("44'/1'/0'/0/0"), False, None, script_type=proto.InputScriptType.SPENDADDRESS) == 'mvbu1Gdy8SUjTenqerxUaZyYjmveZvt33q' + assert btc.get_address(self.client, "Testnet", parse_path("49'/1'/0'/0/0"), True, None, script_type=proto.InputScriptType.SPENDWITNESS) == 'tb1qqzv60m9ajw8drqulta4ld4gfx0rdh82un5s65s' + assert btc.get_address(self.client, "Testnet", parse_path("49'/1'/0'/1/0"), False, None, script_type=proto.InputScriptType.SPENDWITNESS) == 'tb1q694ccp5qcc0udmfwgp692u2s2hjpq5h407urtu' + assert btc.get_address(self.client, "Testnet", parse_path("44'/1'/0'/0/0"), False, None, script_type=proto.InputScriptType.SPENDWITNESS) == 'tb1q54un3q39sf7e7tlfq99d6ezys7qgc62a6rxllc' + assert btc.get_address(self.client, "Testnet", parse_path("44'/1'/0'/0/0"), False, None, script_type=proto.InputScriptType.SPENDADDRESS) == 'mvbu1Gdy8SUjTenqerxUaZyYjmveZvt33q' def test_show_multisig_3(self): self.setup_mnemonic_allallall() - nodes = [self.client.get_public_node(parse_path("999'/1'/%d'" % index)) for index in range(1, 4)] + nodes = [btc.get_public_node(self.client, parse_path("999'/1'/%d'" % index)) for index in range(1, 4)] multisig1 = proto.MultisigRedeemScriptType( pubkeys=list(map(lambda n: proto.HDNodePathType(node=bip32.deserialize(n.xpub), address_n=[2, 0]), nodes)), signatures=[b'', b'', b''], @@ -43,5 +44,5 @@ class TestMsgGetaddressSegwitNative(TrezorTest): m=2, ) for i in [1, 2, 3]: - assert self.client.get_address("Testnet", parse_path("999'/1'/%d'/2/1" % i), False, multisig2, script_type=proto.InputScriptType.SPENDWITNESS) == 'tb1qch62pf820spe9mlq49ns5uexfnl6jzcezp7d328fw58lj0rhlhasge9hzy' - assert self.client.get_address("Testnet", parse_path("999'/1'/%d'/2/0" % i), False, multisig1, script_type=proto.InputScriptType.SPENDWITNESS) == 'tb1qr6xa5v60zyt3ry9nmfew2fk5g9y3gerkjeu6xxdz7qga5kknz2ssld9z2z' + assert btc.get_address(self.client, "Testnet", parse_path("999'/1'/%d'/2/1" % i), False, multisig2, script_type=proto.InputScriptType.SPENDWITNESS) == 'tb1qch62pf820spe9mlq49ns5uexfnl6jzcezp7d328fw58lj0rhlhasge9hzy' + assert btc.get_address(self.client, "Testnet", parse_path("999'/1'/%d'/2/0" % i), False, multisig1, script_type=proto.InputScriptType.SPENDWITNESS) == 'tb1qr6xa5v60zyt3ry9nmfew2fk5g9y3gerkjeu6xxdz7qga5kknz2ssld9z2z' diff --git a/trezorlib/tests/device_tests/test_msg_getaddress_show.py b/trezorlib/tests/device_tests/test_msg_getaddress_show.py index 5192b73297..360a9560ed 100644 --- a/trezorlib/tests/device_tests/test_msg_getaddress_show.py +++ b/trezorlib/tests/device_tests/test_msg_getaddress_show.py @@ -17,15 +17,16 @@ from .common import TrezorTest from ..support import ckd_public as bip32 from trezorlib import messages as proto +from trezorlib import btc class TestMsgGetaddressShow(TrezorTest): def test_show(self): self.setup_mnemonic_nopin_nopassphrase() - assert self.client.get_address('Bitcoin', [1], show_display=True) == '1CK7SJdcb8z9HuvVft3D91HLpLC6KSsGb' - assert self.client.get_address('Bitcoin', [2], show_display=True) == '15AeAhtNJNKyowK8qPHwgpXkhsokzLtUpG' - assert self.client.get_address('Bitcoin', [3], show_display=True) == '1CmzyJp9w3NafXMSEFH4SLYUPAVCSUrrJ5' + assert btc.get_address(self.client, 'Bitcoin', [1], show_display=True) == '1CK7SJdcb8z9HuvVft3D91HLpLC6KSsGb' + assert btc.get_address(self.client, 'Bitcoin', [2], show_display=True) == '15AeAhtNJNKyowK8qPHwgpXkhsokzLtUpG' + assert btc.get_address(self.client, 'Bitcoin', [3], show_display=True) == '1CmzyJp9w3NafXMSEFH4SLYUPAVCSUrrJ5' def test_show_multisig_3(self): self.setup_mnemonic_nopin_nopassphrase() @@ -42,7 +43,7 @@ class TestMsgGetaddressShow(TrezorTest): ) for i in [1, 2, 3]: - assert self.client.get_address('Bitcoin', [i], show_display=True, multisig=multisig) == '3E7GDtuHqnqPmDgwH59pVC7AvySiSkbibz' + assert btc.get_address(self.client, 'Bitcoin', [i], show_display=True, multisig=multisig) == '3E7GDtuHqnqPmDgwH59pVC7AvySiSkbibz' def test_show_multisig_15(self): self.setup_mnemonic_nopin_nopassphrase() @@ -60,4 +61,4 @@ class TestMsgGetaddressShow(TrezorTest): ) for i in range(15): - assert self.client.get_address('Bitcoin', [i], show_display=True, multisig=multisig) == '3QaKF8zobqcqY8aS6nxCD5ZYdiRfL3RCmU' + assert btc.get_address(self.client, 'Bitcoin', [i], show_display=True, multisig=multisig) == '3QaKF8zobqcqY8aS6nxCD5ZYdiRfL3RCmU' diff --git a/trezorlib/tests/device_tests/test_msg_getecdhsessionkey.py b/trezorlib/tests/device_tests/test_msg_getecdhsessionkey.py index 988128c439..db1c95f27b 100644 --- a/trezorlib/tests/device_tests/test_msg_getecdhsessionkey.py +++ b/trezorlib/tests/device_tests/test_msg_getecdhsessionkey.py @@ -18,6 +18,7 @@ from binascii import unhexlify from .common import TrezorTest from trezorlib import messages as proto +from trezorlib import misc class TestMsgGetECDHSessionKey(TrezorTest): @@ -29,13 +30,13 @@ class TestMsgGetECDHSessionKey(TrezorTest): identity = proto.IdentityType(proto='gpg', user='', host='Satoshi Nakamoto ', port='', path='', index=0) peer_public_key = unhexlify('0407f2c6e5becf3213c1d07df0cfbe8e39f70a8c643df7575e5c56859ec52c45ca950499c019719dae0fda04248d851e52cf9d66eeb211d89a77be40de22b6c89d') - result = self.client.get_ecdh_session_key(identity=identity, peer_public_key=peer_public_key, ecdsa_curve_name='secp256k1') + result = misc.get_ecdh_session_key(self.client, identity=identity, peer_public_key=peer_public_key, ecdsa_curve_name='secp256k1') assert result.session_key == unhexlify('0495e5d8c9e5cc09e7cf4908774f52decb381ce97f2fc9ba56e959c13f03f9f47a03dd151cbc908bc1db84d46e2c33e7bbb9daddc800f985244c924fd64adf6647') peer_public_key = unhexlify('04811a6c2bd2a547d0dd84747297fec47719e7c3f9b0024f027c2b237be99aac39a9230acbd163d0cb1524a0f5ea4bfed6058cec6f18368f72a12aa0c4d083ff64') - result = self.client.get_ecdh_session_key(identity=identity, peer_public_key=peer_public_key, ecdsa_curve_name='nist256p1') + result = misc.get_ecdh_session_key(self.client, identity=identity, peer_public_key=peer_public_key, ecdsa_curve_name='nist256p1') assert result.session_key == unhexlify('046d1f5c48af2cf2c57076ac2c9d7808db2086f614cb7b8107119ff2c6270cd209749809efe0196f01a0cc633788cef1f4a2bd650c99570d06962f923fca6d8fdf') peer_public_key = unhexlify('40a8cf4b6a64c4314e80f15a8ea55812bd735fbb365936a48b2d78807b575fa17a') - result = self.client.get_ecdh_session_key(identity=identity, peer_public_key=peer_public_key, ecdsa_curve_name='curve25519') + result = misc.get_ecdh_session_key(self.client, identity=identity, peer_public_key=peer_public_key, ecdsa_curve_name='curve25519') assert result.session_key == unhexlify('04e24516669e0b7d3d72e5129fddd07b6644c30915f5c8b7f1f62324afb3624311') diff --git a/trezorlib/tests/device_tests/test_msg_getentropy.py b/trezorlib/tests/device_tests/test_msg_getentropy.py index 0c30a987ff..fb65bbc6bc 100644 --- a/trezorlib/tests/device_tests/test_msg_getentropy.py +++ b/trezorlib/tests/device_tests/test_msg_getentropy.py @@ -16,6 +16,7 @@ import math from .common import TrezorTest +from trezorlib import misc import trezorlib.messages as proto @@ -40,6 +41,6 @@ class TestMsgGetentropy(TrezorTest): for l in [0, 1, 2, 3, 4, 5, 8, 9, 16, 17, 32, 33, 64, 65, 128, 129, 256, 257, 512, 513, 1024]: with self.client: self.client.set_expected_responses([proto.ButtonRequest(code=proto.ButtonRequestType.ProtectCall), proto.Entropy()]) - ent = self.client.get_entropy(l) + ent = misc.get_entropy(self.client, l) assert len(ent) == l print('entropy = ', entropy(ent)) diff --git a/trezorlib/tests/device_tests/test_msg_getpublickey.py b/trezorlib/tests/device_tests/test_msg_getpublickey.py index bb0792c4ef..4c5c01cb72 100644 --- a/trezorlib/tests/device_tests/test_msg_getpublickey.py +++ b/trezorlib/tests/device_tests/test_msg_getpublickey.py @@ -18,37 +18,38 @@ from .common import TrezorTest from ..support import ckd_public as bip32 from trezorlib.tools import H_ +from trezorlib import btc class TestMsgGetpublickey(TrezorTest): def test_btc(self): self.setup_mnemonic_nopin_nopassphrase() - assert bip32.serialize(self.client.get_public_node([]).node, 0x0488B21E) == 'xpub661MyMwAqRbcF1zGijBb2K6x9YiJPh58xpcCeLvTxMX6spkY3PcpJ4ABcCyWfskq5DDxM3e6Ez5ePCqG5bnPUXR4wL8TZWyoDaUdiWW7bKy' - assert self.client.get_public_node([], coin_name='Bitcoin').xpub == 'xpub661MyMwAqRbcF1zGijBb2K6x9YiJPh58xpcCeLvTxMX6spkY3PcpJ4ABcCyWfskq5DDxM3e6Ez5ePCqG5bnPUXR4wL8TZWyoDaUdiWW7bKy' - assert bip32.serialize(self.client.get_public_node([1]).node, 0x0488B21E) == 'xpub68zNxjsTrV8y9AadThLW7dTAqEpZ7xBLFSyJ3X9pjTv6Njg6kxgjXJkzxq8u3ttnjBw1jupQHMP3gpGZzZqd1eh5S4GjkaMhPR18vMyUi8N' - assert self.client.get_public_node([1], coin_name='Bitcoin').xpub == 'xpub68zNxjsTrV8y9AadThLW7dTAqEpZ7xBLFSyJ3X9pjTv6Njg6kxgjXJkzxq8u3ttnjBw1jupQHMP3gpGZzZqd1eh5S4GjkaMhPR18vMyUi8N' - assert bip32.serialize(self.client.get_public_node([0, H_(1)]).node, 0x0488B21E) == 'xpub6A3FoZqYXj1AbW4thRwBh26YwZWbmoyjTaZwwxJjY1oKUpefLepL3RFS9DHKQrjAfxDrzDepYMDZPqXN6upQm3bHQ9xaXD5a3mqni3goF4v' - assert self.client.get_public_node([0, H_(1)], coin_name='Bitcoin').xpub == 'xpub6A3FoZqYXj1AbW4thRwBh26YwZWbmoyjTaZwwxJjY1oKUpefLepL3RFS9DHKQrjAfxDrzDepYMDZPqXN6upQm3bHQ9xaXD5a3mqni3goF4v' - assert bip32.serialize(self.client.get_public_node([H_(9), 0]).node, 0x0488B21E) == 'xpub6A2h5mzLDfYginoD7q7wCWbq18wTbN9gducRr2w5NRTwdLeoT3cJSwefFqW7uXTpVFGtpUyDMBNYs3DNvvXx6NPjF9YEbUQrtxFSWnPtVrv' - assert self.client.get_public_node([H_(9), 0], coin_name='Bitcoin').xpub == 'xpub6A2h5mzLDfYginoD7q7wCWbq18wTbN9gducRr2w5NRTwdLeoT3cJSwefFqW7uXTpVFGtpUyDMBNYs3DNvvXx6NPjF9YEbUQrtxFSWnPtVrv' - assert bip32.serialize(self.client.get_public_node([0, 9999999]).node, 0x0488B21E) == 'xpub6A3FoZqQEK6iwLZ4HFkqSo5fb35BH4bpjC4SPZ63prfLdGYPwYxEuC6o91bUvFFdMzKWe5rs3axHRUjxJaSvBnKKFtnfLwDACRxPxabsv2r' - assert self.client.get_public_node([0, 9999999], coin_name='Bitcoin').xpub == 'xpub6A3FoZqQEK6iwLZ4HFkqSo5fb35BH4bpjC4SPZ63prfLdGYPwYxEuC6o91bUvFFdMzKWe5rs3axHRUjxJaSvBnKKFtnfLwDACRxPxabsv2r' + assert bip32.serialize(btc.get_public_node(self.client, []).node, 0x0488B21E) == 'xpub661MyMwAqRbcF1zGijBb2K6x9YiJPh58xpcCeLvTxMX6spkY3PcpJ4ABcCyWfskq5DDxM3e6Ez5ePCqG5bnPUXR4wL8TZWyoDaUdiWW7bKy' + assert btc.get_public_node(self.client, [], coin_name='Bitcoin').xpub == 'xpub661MyMwAqRbcF1zGijBb2K6x9YiJPh58xpcCeLvTxMX6spkY3PcpJ4ABcCyWfskq5DDxM3e6Ez5ePCqG5bnPUXR4wL8TZWyoDaUdiWW7bKy' + assert bip32.serialize(btc.get_public_node(self.client, [1]).node, 0x0488B21E) == 'xpub68zNxjsTrV8y9AadThLW7dTAqEpZ7xBLFSyJ3X9pjTv6Njg6kxgjXJkzxq8u3ttnjBw1jupQHMP3gpGZzZqd1eh5S4GjkaMhPR18vMyUi8N' + assert btc.get_public_node(self.client, [1], coin_name='Bitcoin').xpub == 'xpub68zNxjsTrV8y9AadThLW7dTAqEpZ7xBLFSyJ3X9pjTv6Njg6kxgjXJkzxq8u3ttnjBw1jupQHMP3gpGZzZqd1eh5S4GjkaMhPR18vMyUi8N' + assert bip32.serialize(btc.get_public_node(self.client, [0, H_(1)]).node, 0x0488B21E) == 'xpub6A3FoZqYXj1AbW4thRwBh26YwZWbmoyjTaZwwxJjY1oKUpefLepL3RFS9DHKQrjAfxDrzDepYMDZPqXN6upQm3bHQ9xaXD5a3mqni3goF4v' + assert btc.get_public_node(self.client, [0, H_(1)], coin_name='Bitcoin').xpub == 'xpub6A3FoZqYXj1AbW4thRwBh26YwZWbmoyjTaZwwxJjY1oKUpefLepL3RFS9DHKQrjAfxDrzDepYMDZPqXN6upQm3bHQ9xaXD5a3mqni3goF4v' + assert bip32.serialize(btc.get_public_node(self.client, [H_(9), 0]).node, 0x0488B21E) == 'xpub6A2h5mzLDfYginoD7q7wCWbq18wTbN9gducRr2w5NRTwdLeoT3cJSwefFqW7uXTpVFGtpUyDMBNYs3DNvvXx6NPjF9YEbUQrtxFSWnPtVrv' + assert btc.get_public_node(self.client, [H_(9), 0], coin_name='Bitcoin').xpub == 'xpub6A2h5mzLDfYginoD7q7wCWbq18wTbN9gducRr2w5NRTwdLeoT3cJSwefFqW7uXTpVFGtpUyDMBNYs3DNvvXx6NPjF9YEbUQrtxFSWnPtVrv' + assert bip32.serialize(btc.get_public_node(self.client, [0, 9999999]).node, 0x0488B21E) == 'xpub6A3FoZqQEK6iwLZ4HFkqSo5fb35BH4bpjC4SPZ63prfLdGYPwYxEuC6o91bUvFFdMzKWe5rs3axHRUjxJaSvBnKKFtnfLwDACRxPxabsv2r' + assert btc.get_public_node(self.client, [0, 9999999], coin_name='Bitcoin').xpub == 'xpub6A3FoZqQEK6iwLZ4HFkqSo5fb35BH4bpjC4SPZ63prfLdGYPwYxEuC6o91bUvFFdMzKWe5rs3axHRUjxJaSvBnKKFtnfLwDACRxPxabsv2r' def test_ltc(self): self.setup_mnemonic_nopin_nopassphrase() - assert bip32.serialize(self.client.get_public_node([]).node, 0x019DA462) == 'Ltub2SSUS19CirucVPGDKDBatBDBEM2s9UbH66pBURfaKrMocCPLhQ7Z7hecy5VYLHA5fRdXwB2e61j2VJCNzVsqKTCVEU1vECjqi5EyczFX9xp' - assert self.client.get_public_node([], coin_name='Litecoin').xpub == 'Ltub2SSUS19CirucVPGDKDBatBDBEM2s9UbH66pBURfaKrMocCPLhQ7Z7hecy5VYLHA5fRdXwB2e61j2VJCNzVsqKTCVEU1vECjqi5EyczFX9xp' - assert bip32.serialize(self.client.get_public_node([1]).node, 0x019DA462) == 'Ltub2VRVRP5VjvSyPXra4BLVyVZPv397sjhUNjBGsbtw6xko77JuQyBULxFSKheviJJ3KQLbL3Cx8P2RnudguTw4raUVjCACRG7jsumUptYx55C' - assert self.client.get_public_node([1], coin_name='Litecoin').xpub == 'Ltub2VRVRP5VjvSyPXra4BLVyVZPv397sjhUNjBGsbtw6xko77JuQyBULxFSKheviJJ3KQLbL3Cx8P2RnudguTw4raUVjCACRG7jsumUptYx55C' - assert bip32.serialize(self.client.get_public_node([0, H_(1)]).node, 0x019DA462) == 'Ltub2WUNGD3aRAKAqsLqHuwBYtCn2MqAXbVsarmvn33quWe2DCHTzfK4s4jsW5oM5G8RGAdSaM3NPNrwVvtV1ourbyNhhHr3BtqcYGc8caf5GoT' - assert self.client.get_public_node([0, H_(1)], coin_name='Litecoin').xpub == 'Ltub2WUNGD3aRAKAqsLqHuwBYtCn2MqAXbVsarmvn33quWe2DCHTzfK4s4jsW5oM5G8RGAdSaM3NPNrwVvtV1ourbyNhhHr3BtqcYGc8caf5GoT' - assert bip32.serialize(self.client.get_public_node([H_(9), 0]).node, 0x019DA462) == 'Ltub2WToYRCN76rgyA59iK7w4Ni45wG2M9fpmBpQg7gBjvJeMiHc7473Gb96ci29Zvs55TgUQcMmCD1vy8aVqpdPwJB9YHRhGAAuPT1nRLLXmFu' - assert self.client.get_public_node([H_(9), 0], coin_name='Litecoin').xpub == 'Ltub2WToYRCN76rgyA59iK7w4Ni45wG2M9fpmBpQg7gBjvJeMiHc7473Gb96ci29Zvs55TgUQcMmCD1vy8aVqpdPwJB9YHRhGAAuPT1nRLLXmFu' - assert bip32.serialize(self.client.get_public_node([0, 9999999]).node, 0x019DA462) == 'Ltub2WUNGD3S7kQjBhpzsjkqJfBtfqPk2r7xrUGRDdqACMW3MeBCbZSyiqbEVt7WaeesxCj6EDFQtcbfXa75DUYN2i6jZ2g81cyCgvijs9J2u2n' - assert self.client.get_public_node([0, 9999999], coin_name='Litecoin').xpub == 'Ltub2WUNGD3S7kQjBhpzsjkqJfBtfqPk2r7xrUGRDdqACMW3MeBCbZSyiqbEVt7WaeesxCj6EDFQtcbfXa75DUYN2i6jZ2g81cyCgvijs9J2u2n' + assert bip32.serialize(btc.get_public_node(self.client, []).node, 0x019DA462) == 'Ltub2SSUS19CirucVPGDKDBatBDBEM2s9UbH66pBURfaKrMocCPLhQ7Z7hecy5VYLHA5fRdXwB2e61j2VJCNzVsqKTCVEU1vECjqi5EyczFX9xp' + assert btc.get_public_node(self.client, [], coin_name='Litecoin').xpub == 'Ltub2SSUS19CirucVPGDKDBatBDBEM2s9UbH66pBURfaKrMocCPLhQ7Z7hecy5VYLHA5fRdXwB2e61j2VJCNzVsqKTCVEU1vECjqi5EyczFX9xp' + assert bip32.serialize(btc.get_public_node(self.client, [1]).node, 0x019DA462) == 'Ltub2VRVRP5VjvSyPXra4BLVyVZPv397sjhUNjBGsbtw6xko77JuQyBULxFSKheviJJ3KQLbL3Cx8P2RnudguTw4raUVjCACRG7jsumUptYx55C' + assert btc.get_public_node(self.client, [1], coin_name='Litecoin').xpub == 'Ltub2VRVRP5VjvSyPXra4BLVyVZPv397sjhUNjBGsbtw6xko77JuQyBULxFSKheviJJ3KQLbL3Cx8P2RnudguTw4raUVjCACRG7jsumUptYx55C' + assert bip32.serialize(btc.get_public_node(self.client, [0, H_(1)]).node, 0x019DA462) == 'Ltub2WUNGD3aRAKAqsLqHuwBYtCn2MqAXbVsarmvn33quWe2DCHTzfK4s4jsW5oM5G8RGAdSaM3NPNrwVvtV1ourbyNhhHr3BtqcYGc8caf5GoT' + assert btc.get_public_node(self.client, [0, H_(1)], coin_name='Litecoin').xpub == 'Ltub2WUNGD3aRAKAqsLqHuwBYtCn2MqAXbVsarmvn33quWe2DCHTzfK4s4jsW5oM5G8RGAdSaM3NPNrwVvtV1ourbyNhhHr3BtqcYGc8caf5GoT' + assert bip32.serialize(btc.get_public_node(self.client, [H_(9), 0]).node, 0x019DA462) == 'Ltub2WToYRCN76rgyA59iK7w4Ni45wG2M9fpmBpQg7gBjvJeMiHc7473Gb96ci29Zvs55TgUQcMmCD1vy8aVqpdPwJB9YHRhGAAuPT1nRLLXmFu' + assert btc.get_public_node(self.client, [H_(9), 0], coin_name='Litecoin').xpub == 'Ltub2WToYRCN76rgyA59iK7w4Ni45wG2M9fpmBpQg7gBjvJeMiHc7473Gb96ci29Zvs55TgUQcMmCD1vy8aVqpdPwJB9YHRhGAAuPT1nRLLXmFu' + assert bip32.serialize(btc.get_public_node(self.client, [0, 9999999]).node, 0x019DA462) == 'Ltub2WUNGD3S7kQjBhpzsjkqJfBtfqPk2r7xrUGRDdqACMW3MeBCbZSyiqbEVt7WaeesxCj6EDFQtcbfXa75DUYN2i6jZ2g81cyCgvijs9J2u2n' + assert btc.get_public_node(self.client, [0, 9999999], coin_name='Litecoin').xpub == 'Ltub2WUNGD3S7kQjBhpzsjkqJfBtfqPk2r7xrUGRDdqACMW3MeBCbZSyiqbEVt7WaeesxCj6EDFQtcbfXa75DUYN2i6jZ2g81cyCgvijs9J2u2n' def test_tbtc(self): self.setup_mnemonic_nopin_nopassphrase() - assert bip32.serialize(self.client.get_public_node([111, 42]).node, 0x043587CF) == 'tpubDAgixSyai5PWbc8N1mBkHDR5nLgAnHFtY7r4y5EzxqAxrt9YUDpZL3kaRoHVvCfrcwNo31c2isBP2uTHcZxEosuKbyJhCAbrvGoPuLUZ7Mz' - assert self.client.get_public_node([111, 42], coin_name='Testnet').xpub == 'tpubDAgixSyai5PWbc8N1mBkHDR5nLgAnHFtY7r4y5EzxqAxrt9YUDpZL3kaRoHVvCfrcwNo31c2isBP2uTHcZxEosuKbyJhCAbrvGoPuLUZ7Mz' + assert bip32.serialize(btc.get_public_node(self.client, [111, 42]).node, 0x043587CF) == 'tpubDAgixSyai5PWbc8N1mBkHDR5nLgAnHFtY7r4y5EzxqAxrt9YUDpZL3kaRoHVvCfrcwNo31c2isBP2uTHcZxEosuKbyJhCAbrvGoPuLUZ7Mz' + assert btc.get_public_node(self.client, [111, 42], coin_name='Testnet').xpub == 'tpubDAgixSyai5PWbc8N1mBkHDR5nLgAnHFtY7r4y5EzxqAxrt9YUDpZL3kaRoHVvCfrcwNo31c2isBP2uTHcZxEosuKbyJhCAbrvGoPuLUZ7Mz' diff --git a/trezorlib/tests/device_tests/test_msg_getpublickey_curve.py b/trezorlib/tests/device_tests/test_msg_getpublickey_curve.py index a6d9550ea7..500476ea96 100644 --- a/trezorlib/tests/device_tests/test_msg_getpublickey_curve.py +++ b/trezorlib/tests/device_tests/test_msg_getpublickey_curve.py @@ -19,30 +19,31 @@ import pytest from .common import TrezorTest from trezorlib.tools import CallException +from trezorlib import btc class TestMsgGetpublickeyCurve(TrezorTest): def test_default_curve(self): self.setup_mnemonic_nopin_nopassphrase() - assert hexlify(self.client.get_public_node([0x80000000 | 111, 42]).node.public_key).decode() == '02e7fcec053f0df94d88c86447970743e8a1979d242d09338dcf8687a9966f7fbc' - assert hexlify(self.client.get_public_node([0x80000000 | 111, 0x80000000 | 42]).node.public_key).decode() == '03ce7b690969d773ba9ed212464eb2b534b87b9b8a9383300bddabe1f093f79220' + assert hexlify(btc.get_public_node(self.client, [0x80000000 | 111, 42]).node.public_key).decode() == '02e7fcec053f0df94d88c86447970743e8a1979d242d09338dcf8687a9966f7fbc' + assert hexlify(btc.get_public_node(self.client, [0x80000000 | 111, 0x80000000 | 42]).node.public_key).decode() == '03ce7b690969d773ba9ed212464eb2b534b87b9b8a9383300bddabe1f093f79220' def test_secp256k1_curve(self): self.setup_mnemonic_nopin_nopassphrase() - assert hexlify(self.client.get_public_node([0x80000000 | 111, 42], ecdsa_curve_name='secp256k1').node.public_key).decode() == '02e7fcec053f0df94d88c86447970743e8a1979d242d09338dcf8687a9966f7fbc' - assert hexlify(self.client.get_public_node([0x80000000 | 111, 0x80000000 | 42], ecdsa_curve_name='secp256k1').node.public_key).decode() == '03ce7b690969d773ba9ed212464eb2b534b87b9b8a9383300bddabe1f093f79220' + assert hexlify(btc.get_public_node(self.client, [0x80000000 | 111, 42], ecdsa_curve_name='secp256k1').node.public_key).decode() == '02e7fcec053f0df94d88c86447970743e8a1979d242d09338dcf8687a9966f7fbc' + assert hexlify(btc.get_public_node(self.client, [0x80000000 | 111, 0x80000000 | 42], ecdsa_curve_name='secp256k1').node.public_key).decode() == '03ce7b690969d773ba9ed212464eb2b534b87b9b8a9383300bddabe1f093f79220' def test_nist256p1_curve(self): self.setup_mnemonic_nopin_nopassphrase() - assert hexlify(self.client.get_public_node([0x80000000 | 111, 42], ecdsa_curve_name='nist256p1').node.public_key).decode() == '02a9ce59b32bd64a70bc52aca96e5d09af65c6b9593ba2a60af8fccfe1437f2129' - assert hexlify(self.client.get_public_node([0x80000000 | 111, 0x80000000 | 42], ecdsa_curve_name='nist256p1').node.public_key).decode() == '026fe35d8afed67dbf0561a1d32922e8ad0cd0d86effbc82be970cbed7d9bab2c2' + assert hexlify(btc.get_public_node(self.client, [0x80000000 | 111, 42], ecdsa_curve_name='nist256p1').node.public_key).decode() == '02a9ce59b32bd64a70bc52aca96e5d09af65c6b9593ba2a60af8fccfe1437f2129' + assert hexlify(btc.get_public_node(self.client, [0x80000000 | 111, 0x80000000 | 42], ecdsa_curve_name='nist256p1').node.public_key).decode() == '026fe35d8afed67dbf0561a1d32922e8ad0cd0d86effbc82be970cbed7d9bab2c2' def test_ed25519_curve(self): self.setup_mnemonic_nopin_nopassphrase() # ed25519 curve does not support public derivation, so test only private derivation paths - assert hexlify(self.client.get_public_node([0x80000000 | 111, 0x80000000 | 42], ecdsa_curve_name='ed25519').node.public_key).decode() == '0069a14b478e508eab6e93303f4e6f5c50b8136627830f2ed5c3a835fc6c0ea2b7' - assert hexlify(self.client.get_public_node([0x80000000 | 111, 0x80000000 | 65535], ecdsa_curve_name='ed25519').node.public_key).decode() == '00514f73a05184458611b14c348fee4fd988d36cf3aee7207737861bac611de991' + assert hexlify(btc.get_public_node(self.client, [0x80000000 | 111, 0x80000000 | 42], ecdsa_curve_name='ed25519').node.public_key).decode() == '0069a14b478e508eab6e93303f4e6f5c50b8136627830f2ed5c3a835fc6c0ea2b7' + assert hexlify(btc.get_public_node(self.client, [0x80000000 | 111, 0x80000000 | 65535], ecdsa_curve_name='ed25519').node.public_key).decode() == '00514f73a05184458611b14c348fee4fd988d36cf3aee7207737861bac611de991' # test failure when using public derivation with pytest.raises(CallException): - self.client.get_public_node([0x80000000 | 111, 42], ecdsa_curve_name='ed25519') + btc.get_public_node(self.client, [0x80000000 | 111, 42], ecdsa_curve_name='ed25519') diff --git a/trezorlib/tests/device_tests/test_msg_lisk_getaddress.py b/trezorlib/tests/device_tests/test_msg_lisk_getaddress.py index 9ad64dc0bb..37376a6753 100644 --- a/trezorlib/tests/device_tests/test_msg_lisk_getaddress.py +++ b/trezorlib/tests/device_tests/test_msg_lisk_getaddress.py @@ -17,6 +17,7 @@ import pytest from .common import TrezorTest +from trezorlib import lisk @pytest.mark.lisk @@ -25,7 +26,7 @@ class TestMsgLiskGetaddress(TrezorTest): def test_lisk_getaddress(self): self.setup_mnemonic_nopin_nopassphrase() - assert self.client.lisk_get_address([2147483692, 2147483782]) == '1431530009238518937L' - assert self.client.lisk_get_address([2147483692, 2147483782, 2147483648]) == '17563781916205589679L' - assert self.client.lisk_get_address([2147483692, 2147483782, 2147483648, 2147483649]) == '1874186517773691964L' - assert self.client.lisk_get_address([2147483692, 2147483782, 2147484647, 2147484647]) == '16295203558710684671L' + assert lisk.get_address(self.client, [2147483692, 2147483782]) == '1431530009238518937L' + assert lisk.get_address(self.client, [2147483692, 2147483782, 2147483648]) == '17563781916205589679L' + assert lisk.get_address(self.client, [2147483692, 2147483782, 2147483648, 2147483649]) == '1874186517773691964L' + assert lisk.get_address(self.client, [2147483692, 2147483782, 2147484647, 2147484647]) == '16295203558710684671L' diff --git a/trezorlib/tests/device_tests/test_msg_lisk_getpublickey.py b/trezorlib/tests/device_tests/test_msg_lisk_getpublickey.py index 164d7a2d8d..9ade7cf2c9 100644 --- a/trezorlib/tests/device_tests/test_msg_lisk_getpublickey.py +++ b/trezorlib/tests/device_tests/test_msg_lisk_getpublickey.py @@ -18,6 +18,7 @@ from binascii import hexlify import pytest from .common import TrezorTest +from trezorlib import lisk @pytest.mark.lisk @@ -26,5 +27,5 @@ class TestMsgLiskGetPublicKey(TrezorTest): def test_lisk_get_public_key(self): self.setup_mnemonic_nopin_nopassphrase() - sig = self.client.lisk_get_public_key([2147483692, 2147483782, 2147483648, 2147483648]) + sig = lisk.get_public_key(self.client, [2147483692, 2147483782, 2147483648, 2147483648]) assert hexlify(sig.public_key) == b'eb56d7bbb5e8ea9269405f7a8527fe126023d1db2c973cfac6f760b60ae27294' diff --git a/trezorlib/tests/device_tests/test_msg_lisk_signmessage.py b/trezorlib/tests/device_tests/test_msg_lisk_signmessage.py index 8dd1cc8ad2..c1dfa25d9e 100644 --- a/trezorlib/tests/device_tests/test_msg_lisk_signmessage.py +++ b/trezorlib/tests/device_tests/test_msg_lisk_signmessage.py @@ -18,6 +18,7 @@ from binascii import hexlify import pytest from .common import TrezorTest +from trezorlib import lisk @pytest.mark.lisk @@ -26,12 +27,12 @@ class TestMsgLiskSignmessage(TrezorTest): def test_sign(self): self.setup_mnemonic_nopin_nopassphrase() - sig = self.client.lisk_sign_message([2147483692, 2147483782, 2147483648, 2147483648], 'This is an example of a signed message.') + sig = lisk.sign_message(self.client, [2147483692, 2147483782, 2147483648, 2147483648], 'This is an example of a signed message.') assert hexlify(sig.public_key) == b'eb56d7bbb5e8ea9269405f7a8527fe126023d1db2c973cfac6f760b60ae27294' assert hexlify(sig.signature) == b'7858ae7cd52ea6d4b17e800ca60144423db5560bfd618b663ffbf26ab66758563df45cbffae8463db22dc285dd94309083b8c807776085b97d05374d79867d05' def test_sign_long(self): self.setup_mnemonic_nopin_nopassphrase() - sig = self.client.lisk_sign_message([2147483692, 2147483782, 2147483648], 'VeryLongMessage!' * 64) + sig = lisk.sign_message(self.client, [2147483692, 2147483782, 2147483648], 'VeryLongMessage!' * 64) assert hexlify(sig.public_key) == b'8bca6b65a1a877767b746ea0b3c4310d404aa113df99c1b554e1802d70185ab5' assert hexlify(sig.signature) == b'458ca5896d0934866992268f7509b5e954d568b1251e20c19bd3149ee3c86ffb5a44d1c2a0abbb99a3ab4767272dbb0e419b4579e890a24919ebbbe6cc0f970f' diff --git a/trezorlib/tests/device_tests/test_msg_lisk_signtx.py b/trezorlib/tests/device_tests/test_msg_lisk_signtx.py index 69280a50a5..a45cb0b5e1 100644 --- a/trezorlib/tests/device_tests/test_msg_lisk_signtx.py +++ b/trezorlib/tests/device_tests/test_msg_lisk_signtx.py @@ -20,6 +20,7 @@ import pytest from .common import TrezorTest from trezorlib import messages as proto from trezorlib.tools import parse_path +from trezorlib import lisk PUBLIC_KEY = unhexlify('eb56d7bbb5e8ea9269405f7a8527fe126023d1db2c973cfac6f760b60ae27294') @@ -40,7 +41,7 @@ class TestMsgLiskSignTx(TrezorTest): ) ]) - self.client.lisk_sign_tx(parse_path("m/44'/134'/0'/0'"), { + lisk.sign_tx(self.client, parse_path("m/44'/134'/0'/0'"), { "amount": "10000000", "recipientId": "9971262264659915921L", "timestamp": 57525937, @@ -61,7 +62,7 @@ class TestMsgLiskSignTx(TrezorTest): ) ]) - self.client.lisk_sign_tx(parse_path("m/44'/134'/0'/0'"), { + lisk.sign_tx(self.client, parse_path("m/44'/134'/0'/0'"), { "amount": "10000000", "recipientId": "9971262264659915921L", "timestamp": 57525937, @@ -84,7 +85,7 @@ class TestMsgLiskSignTx(TrezorTest): ) ]) - self.client.lisk_sign_tx(parse_path("m/44'/134'/0'/0'"), { + lisk.sign_tx(self.client, parse_path("m/44'/134'/0'/0'"), { "amount": "0", "timestamp": 57525937, "type": 1, @@ -108,7 +109,7 @@ class TestMsgLiskSignTx(TrezorTest): ) ]) - self.client.lisk_sign_tx(parse_path("m/44'/134'/0'/0'"), { + lisk.sign_tx(self.client, parse_path("m/44'/134'/0'/0'"), { "amount": "0", "timestamp": 57525937, "type": 2, @@ -132,7 +133,7 @@ class TestMsgLiskSignTx(TrezorTest): ) ]) - self.client.lisk_sign_tx(parse_path("m/44'/134'/0'/0'"), { + lisk.sign_tx(self.client, parse_path("m/44'/134'/0'/0'"), { "amount": "0", "timestamp": 57525937, "type": 3, @@ -157,7 +158,7 @@ class TestMsgLiskSignTx(TrezorTest): ) ]) - self.client.lisk_sign_tx(parse_path("m/44'/134'/0'/0'"), { + lisk.sign_tx(self.client, parse_path("m/44'/134'/0'/0'"), { "amount": "0", "timestamp": 57525937, "type": 4, diff --git a/trezorlib/tests/device_tests/test_msg_lisk_verifymessage.py b/trezorlib/tests/device_tests/test_msg_lisk_verifymessage.py index 0a5b120080..d4018bd303 100644 --- a/trezorlib/tests/device_tests/test_msg_lisk_verifymessage.py +++ b/trezorlib/tests/device_tests/test_msg_lisk_verifymessage.py @@ -19,6 +19,7 @@ import pytest from .common import TrezorTest from trezorlib import messages as proto +from trezorlib import lisk @pytest.mark.lisk @@ -33,11 +34,12 @@ class TestMsgLiskVerifymessage(TrezorTest): proto.ButtonRequest(code=proto.ButtonRequestType.Other), proto.Success(message='Message verified') ]) - self.client.lisk_verify_message( + lisk.verify_message( + self.client, unhexlify('eb56d7bbb5e8ea9269405f7a8527fe126023d1db2c973cfac6f760b60ae27294'), unhexlify('7858ae7cd52ea6d4b17e800ca60144423db5560bfd618b663ffbf26ab66758563df45cbffae8463db22dc285dd94309083b8c807776085b97d05374d79867d05'), 'This is an example of a signed message.' - ) + ) def test_verify_long(self): self.setup_mnemonic_nopin_nopassphrase() @@ -47,7 +49,8 @@ class TestMsgLiskVerifymessage(TrezorTest): proto.ButtonRequest(code=proto.ButtonRequestType.Other), proto.Success(message='Message verified') ]) - self.client.lisk_verify_message( + lisk.verify_message( + self.client, unhexlify('8bca6b65a1a877767b746ea0b3c4310d404aa113df99c1b554e1802d70185ab5'), unhexlify('458ca5896d0934866992268f7509b5e954d568b1251e20c19bd3149ee3c86ffb5a44d1c2a0abbb99a3ab4767272dbb0e419b4579e890a24919ebbbe6cc0f970f'), 'VeryLongMessage!' * 64 diff --git a/trezorlib/tests/device_tests/test_msg_loaddevice.py b/trezorlib/tests/device_tests/test_msg_loaddevice.py index 4c097e366d..60ba94f45a 100644 --- a/trezorlib/tests/device_tests/test_msg_loaddevice.py +++ b/trezorlib/tests/device_tests/test_msg_loaddevice.py @@ -17,6 +17,9 @@ import pytest from .common import TrezorTest +from trezorlib import btc +from trezorlib import debuglink +from trezorlib import device @pytest.mark.skip_t2 @@ -33,7 +36,7 @@ class TestDeviceLoad(TrezorTest): passphrase_protection = self.client.debug.read_passphrase_protection() assert passphrase_protection is False - address = self.client.get_address('Bitcoin', []) + address = btc.get_address(self.client, 'Bitcoin', []) assert address == '1EfKbQupktEMXf4gujJ9kCFo83k1iMqwqK' def test_load_device_2(self): @@ -49,7 +52,7 @@ class TestDeviceLoad(TrezorTest): passphrase_protection = self.client.debug.read_passphrase_protection() assert passphrase_protection is True - address = self.client.get_address('Bitcoin', []) + address = btc.get_address(self.client, 'Bitcoin', []) assert address == '15fiTDFwZd2kauHYYseifGi9daH2wniDHH' def test_load_device_utf(self): @@ -63,25 +66,25 @@ class TestDeviceLoad(TrezorTest): 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' - self.client.wipe_device() - self.client.load_device_by_mnemonic(mnemonic=words_nfkd, pin='', passphrase_protection=True, label='test', language='english', skip_checksum=True) + 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 = self.client.get_address('Bitcoin', []) + address_nfkd = btc.get_address(self.client, 'Bitcoin', []) - self.client.wipe_device() - self.client.load_device_by_mnemonic(mnemonic=words_nfc, pin='', passphrase_protection=True, label='test', language='english', skip_checksum=True) + 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 = self.client.get_address('Bitcoin', []) + address_nfc = btc.get_address(self.client, 'Bitcoin', []) - self.client.wipe_device() - self.client.load_device_by_mnemonic(mnemonic=words_nfkc, pin='', passphrase_protection=True, label='test', language='english', skip_checksum=True) + 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 = self.client.get_address('Bitcoin', []) + address_nfkc = btc.get_address(self.client, 'Bitcoin', []) - self.client.wipe_device() - self.client.load_device_by_mnemonic(mnemonic=words_nfd, pin='', passphrase_protection=True, label='test', language='english', skip_checksum=True) + 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 = self.client.get_address('Bitcoin', []) + address_nfd = btc.get_address(self.client, 'Bitcoin', []) assert address_nfkd == address_nfc assert address_nfkd == address_nfkc diff --git a/trezorlib/tests/device_tests/test_msg_loaddevice_xprv.py b/trezorlib/tests/device_tests/test_msg_loaddevice_xprv.py index 2b397822a5..3fec436301 100644 --- a/trezorlib/tests/device_tests/test_msg_loaddevice_xprv.py +++ b/trezorlib/tests/device_tests/test_msg_loaddevice_xprv.py @@ -17,27 +17,29 @@ import pytest from .common import TrezorTest +from trezorlib import btc +from trezorlib import debuglink @pytest.mark.skip_t2 class TestDeviceLoadXprv(TrezorTest): def test_load_device_xprv_1(self): - self.client.load_device_by_xprv(xprv='xprv9s21ZrQH143K2JF8RafpqtKiTbsbaxEeUaMnNHsm5o6wCW3z8ySyH4UxFVSfZ8n7ESu7fgir8imbZKLYVBxFPND1pniTZ81vKfd45EHKX73', pin='', passphrase_protection=False, label='test', language='english') + debuglink.load_device_by_xprv(self.client, xprv='xprv9s21ZrQH143K2JF8RafpqtKiTbsbaxEeUaMnNHsm5o6wCW3z8ySyH4UxFVSfZ8n7ESu7fgir8imbZKLYVBxFPND1pniTZ81vKfd45EHKX73', pin='', passphrase_protection=False, label='test', language='english') passphrase_protection = self.client.debug.read_passphrase_protection() assert passphrase_protection is False - address = self.client.get_address('Bitcoin', []) + address = btc.get_address(self.client, 'Bitcoin', []) assert address == '128RdrAkJDmqasgvfRf6MC5VcX4HKqH4mR' def test_load_device_xprv_2(self): - self.client.load_device_by_xprv(xprv='xprv9s21ZrQH143K2JF8RafpqtKiTbsbaxEeUaMnNHsm5o6wCW3z8ySyH4UxFVSfZ8n7ESu7fgir8imbZKLYVBxFPND1pniTZ81vKfd45EHKX73', pin='', passphrase_protection=True, label='test', language='english') + debuglink.load_device_by_xprv(self.client, xprv='xprv9s21ZrQH143K2JF8RafpqtKiTbsbaxEeUaMnNHsm5o6wCW3z8ySyH4UxFVSfZ8n7ESu7fgir8imbZKLYVBxFPND1pniTZ81vKfd45EHKX73', pin='', passphrase_protection=True, label='test', language='english') self.client.set_passphrase('passphrase') passphrase_protection = self.client.debug.read_passphrase_protection() assert passphrase_protection is True - address = self.client.get_address('Bitcoin', []) + address = btc.get_address(self.client, 'Bitcoin', []) assert address == '1CHUbFa4wTTPYgkYaw2LHSd5D4qJjMU8ri' diff --git a/trezorlib/tests/device_tests/test_msg_nem_getaddress.py b/trezorlib/tests/device_tests/test_msg_nem_getaddress.py index 2b16dd9807..9ab5be75e9 100644 --- a/trezorlib/tests/device_tests/test_msg_nem_getaddress.py +++ b/trezorlib/tests/device_tests/test_msg_nem_getaddress.py @@ -18,6 +18,7 @@ import pytest from .common import TrezorTest from trezorlib.tools import parse_path +from trezorlib import nem @pytest.mark.nem @@ -25,5 +26,5 @@ class TestMsgNEMGetaddress(TrezorTest): def test_nem_getaddress(self): self.setup_mnemonic_nopin_nopassphrase() - assert self.client.nem_get_address(parse_path("m/44'/1'/0'/0'/0'"), 0x68) == "NB3JCHVARQNGDS3UVGAJPTFE22UQFGMCQGHUBWQN" - assert self.client.nem_get_address(parse_path("m/44'/1'/0'/0'/0'"), 0x98) == "TB3JCHVARQNGDS3UVGAJPTFE22UQFGMCQHSBNBMF" + assert nem.get_address(self.client, parse_path("m/44'/1'/0'/0'/0'"), 0x68) == "NB3JCHVARQNGDS3UVGAJPTFE22UQFGMCQGHUBWQN" + assert nem.get_address(self.client, parse_path("m/44'/1'/0'/0'/0'"), 0x98) == "TB3JCHVARQNGDS3UVGAJPTFE22UQFGMCQHSBNBMF" diff --git a/trezorlib/tests/device_tests/test_msg_nem_signtx_mosaics.py b/trezorlib/tests/device_tests/test_msg_nem_signtx_mosaics.py index e493ba32cd..1ab6b5437d 100644 --- a/trezorlib/tests/device_tests/test_msg_nem_signtx_mosaics.py +++ b/trezorlib/tests/device_tests/test_msg_nem_signtx_mosaics.py @@ -30,7 +30,7 @@ class TestMsgNEMSignTxMosaics(TrezorTest): def test_nem_signtx_mosaic_supply_change(self): self.setup_mnemonic_nopin_nopassphrase() - tx = self.client.nem_sign_tx(parse_path("m/44'/1'/0'/0'/0'"), { + tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { "timeStamp": 74649215, "fee": 2000000, "type": nem.TYPE_MOSAIC_SUPPLY_CHANGE, @@ -54,7 +54,7 @@ class TestMsgNEMSignTxMosaics(TrezorTest): def test_nem_signtx_mosaic_creation(self): self.setup_mnemonic_nopin_nopassphrase() - tx = self.client.nem_sign_tx(parse_path("m/44'/1'/0'/0'/0'"), { + tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { "timeStamp": 74649215, "fee": 2000000, "type": nem.TYPE_MOSAIC_CREATION, @@ -81,7 +81,7 @@ class TestMsgNEMSignTxMosaics(TrezorTest): def test_nem_signtx_mosaic_creation_properties(self): self.setup_mnemonic_nopin_nopassphrase() - tx = self.client.nem_sign_tx(parse_path("m/44'/1'/0'/0'/0'"), { + tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { "timeStamp": 74649215, "fee": 2000000, "type": nem.TYPE_MOSAIC_CREATION, @@ -125,7 +125,7 @@ class TestMsgNEMSignTxMosaics(TrezorTest): def test_nem_signtx_mosaic_creation_levy(self): self.setup_mnemonic_nopin_nopassphrase() - tx = self.client.nem_sign_tx(parse_path("m/44'/1'/0'/0'/0'"), { + tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { "timeStamp": 74649215, "fee": 2000000, "type": nem.TYPE_MOSAIC_CREATION, diff --git a/trezorlib/tests/device_tests/test_msg_nem_signtx_mosaics_t2.py b/trezorlib/tests/device_tests/test_msg_nem_signtx_mosaics_t2.py index dc5e771280..adf1f56ef4 100644 --- a/trezorlib/tests/device_tests/test_msg_nem_signtx_mosaics_t2.py +++ b/trezorlib/tests/device_tests/test_msg_nem_signtx_mosaics_t2.py @@ -33,7 +33,7 @@ class TestMsgNEMSignTxMosaics(TrezorTest): self.setup_mnemonic_nopin_nopassphrase() with self.client: - tx = self.client.nem_sign_tx(parse_path("m/44'/1'/0'/0'/0'"), { + tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { "timeStamp": 74649215, "fee": 2000000, "type": nem.TYPE_MOSAIC_SUPPLY_CHANGE, diff --git a/trezorlib/tests/device_tests/test_msg_nem_signtx_multisig.py b/trezorlib/tests/device_tests/test_msg_nem_signtx_multisig.py index c646d48a40..6b265698bc 100644 --- a/trezorlib/tests/device_tests/test_msg_nem_signtx_multisig.py +++ b/trezorlib/tests/device_tests/test_msg_nem_signtx_multisig.py @@ -30,7 +30,7 @@ class TestMsgNEMSignTxMultisig(TrezorTest): def test_nem_signtx_aggregate_modification(self): self.setup_mnemonic_nopin_nopassphrase() - tx = self.client.nem_sign_tx(parse_path("m/44'/1'/0'/0'/0'"), { + tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { "timeStamp": 74649215, "fee": 2000000, "type": nem.TYPE_AGGREGATE_MODIFICATION, @@ -54,7 +54,7 @@ class TestMsgNEMSignTxMultisig(TrezorTest): def test_nem_signtx_multisig(self): self.setup_mnemonic_nopin_nopassphrase() - tx = self.client.nem_sign_tx(parse_path("m/44'/1'/0'/0'/0'"), { + tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { "timeStamp": 1, "fee": 10000, "type": nem.TYPE_MULTISIG, @@ -79,7 +79,7 @@ class TestMsgNEMSignTxMultisig(TrezorTest): assert hexlify(tx.data) == b'04100000010000980100000020000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b40620841027000000000000ff5f74049900000001010000010000980200000020000000c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f87844983a000000000000320901002800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324a80841e000000000025000000010000001d000000746573745f6e656d5f7472616e73616374696f6e5f7472616e73666572' assert hexlify(tx.signature) == b'0cab2fddf2f02b5d7201675b9a71869292fe25ed33a366c7d2cbea7676fed491faaa03310079b7e17884b6ba2e3ea21c4f728d1cca8f190b8288207f6514820a' - tx = self.client.nem_sign_tx(parse_path("m/44'/1'/0'/0'/0'"), { + tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { "timeStamp": 74649215, "fee": 150, "type": nem.TYPE_MULTISIG, @@ -107,7 +107,7 @@ class TestMsgNEMSignTxMultisig(TrezorTest): def test_nem_signtx_multisig_signer(self): self.setup_mnemonic_nopin_nopassphrase() - tx = self.client.nem_sign_tx(parse_path("m/44'/1'/0'/0'/0'"), { + tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { "timeStamp": 333, "fee": 200, "type": nem.TYPE_MULTISIG_SIGNATURE, @@ -132,7 +132,7 @@ class TestMsgNEMSignTxMultisig(TrezorTest): assert hexlify(tx.data) == b'02100000010000984d01000020000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b4062084c800000000000000bc010000240000002000000087923cd4805f3babe6b5af9cbb2b08be4458e39531618aed73c911f160c8e38528000000544444324354364c514c49595135364b49584933454e544d36454b3344343450354b5a50464d4b32' assert hexlify(tx.signature) == b'286358a16ae545bff798feab93a713440c7c2f236d52ac0e995669d17a1915b0903667c97fa04418eccb42333cba95b19bccc8ac1faa8224dcfaeb41890ae807' - tx = self.client.nem_sign_tx(parse_path("m/44'/1'/0'/0'/0'"), { + tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { "timeStamp": 900000, "fee": 200000, "type": nem.TYPE_MULTISIG_SIGNATURE, diff --git a/trezorlib/tests/device_tests/test_msg_nem_signtx_others.py b/trezorlib/tests/device_tests/test_msg_nem_signtx_others.py index d191712e0c..18052c2ee3 100644 --- a/trezorlib/tests/device_tests/test_msg_nem_signtx_others.py +++ b/trezorlib/tests/device_tests/test_msg_nem_signtx_others.py @@ -31,7 +31,7 @@ class TestMsgNEMSignTxOther(TrezorTest): self.setup_mnemonic_nopin_nopassphrase() with self.client: - tx = self.client.nem_sign_tx(parse_path("m/44'/1'/0'/0'/0'"), { + tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { "timeStamp": 12349215, "fee": 9900, "type": nem.TYPE_IMPORTANCE_TRANSFER, @@ -52,7 +52,7 @@ class TestMsgNEMSignTxOther(TrezorTest): self.setup_mnemonic_nopin_nopassphrase() - tx = self.client.nem_sign_tx(parse_path("m/44'/1'/0'/0'/0'"), { + tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { "timeStamp": 74649215, "fee": 2000000, "type": nem.TYPE_PROVISION_NAMESPACE, diff --git a/trezorlib/tests/device_tests/test_msg_nem_signtx_transfers.py b/trezorlib/tests/device_tests/test_msg_nem_signtx_transfers.py index 19352cea96..6159aaaa91 100644 --- a/trezorlib/tests/device_tests/test_msg_nem_signtx_transfers.py +++ b/trezorlib/tests/device_tests/test_msg_nem_signtx_transfers.py @@ -46,7 +46,7 @@ class TestMsgNEMSignTx(TrezorTest): proto.NEMSignedTx(), ]) - tx = self.client.nem_sign_tx(parse_path("m/44'/1'/0'/0'/0'"), { + tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { "timeStamp": 74649215, "amount": 2000000, "fee": 2000000, @@ -77,7 +77,7 @@ class TestMsgNEMSignTx(TrezorTest): proto.NEMSignedTx(), ]) - tx = self.client.nem_sign_tx(parse_path("m/44'/1'/0'/0'/0'"), { + tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { "timeStamp": 74649215, "amount": 2000000, "fee": 2000000, @@ -103,7 +103,7 @@ class TestMsgNEMSignTx(TrezorTest): def test_nem_signtx_xem_as_mosaic(self): self.setup_mnemonic_nopin_nopassphrase() - tx = self.client.nem_sign_tx(parse_path("m/44'/1'/0'/0'/0'"), { + tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { "timeStamp": 76809215, "amount": 5000000, "fee": 1000000, @@ -131,7 +131,7 @@ class TestMsgNEMSignTx(TrezorTest): def test_nem_signtx_unknown_mosaic(self): self.setup_mnemonic_nopin_nopassphrase() - tx = self.client.nem_sign_tx(parse_path("m/44'/1'/0'/0'/0'"), { + tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { "timeStamp": 76809215, "amount": 2000000, "fee": 1000000, @@ -160,7 +160,7 @@ class TestMsgNEMSignTx(TrezorTest): self.setup_mnemonic_nopin_nopassphrase() - tx = self.client.nem_sign_tx(parse_path("m/44'/1'/0'/0'/0'"), { + tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { "timeStamp": 76809215, "amount": 3000000, "fee": 1000000, @@ -189,7 +189,7 @@ class TestMsgNEMSignTx(TrezorTest): self.setup_mnemonic_nopin_nopassphrase() - tx = self.client.nem_sign_tx(parse_path("m/44'/1'/0'/0'/0'"), { + tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { "timeStamp": 76809215, "amount": 2000000, "fee": 1000000, @@ -217,7 +217,7 @@ class TestMsgNEMSignTx(TrezorTest): def test_nem_signtx_multiple_mosaics(self): self.setup_mnemonic_nopin_nopassphrase() - tx = self.client.nem_sign_tx(parse_path("m/44'/1'/0'/0'/0'"), { + tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { "timeStamp": 76809215, "amount": 2000000, "fee": 1000000, diff --git a/trezorlib/tests/device_tests/test_msg_recoverydevice.py b/trezorlib/tests/device_tests/test_msg_recoverydevice.py index c95e981143..cdabc18f1c 100644 --- a/trezorlib/tests/device_tests/test_msg_recoverydevice.py +++ b/trezorlib/tests/device_tests/test_msg_recoverydevice.py @@ -18,6 +18,7 @@ import pytest from .common import TrezorTest from trezorlib import messages as proto +from trezorlib import device @pytest.mark.skip_t2 @@ -189,4 +190,4 @@ class TestMsgRecoverydevice(TrezorTest): def test_already_initialized(self): self.setup_mnemonic_nopin_nopassphrase() with pytest.raises(Exception): - self.client.recovery_device(12, False, False, 'label', 'english') + device.recover(self.client, 12, False, False, 'label', 'english') diff --git a/trezorlib/tests/device_tests/test_msg_recoverydevice_t2.py b/trezorlib/tests/device_tests/test_msg_recoverydevice_t2.py index 73ad3f805e..43304ea3c1 100644 --- a/trezorlib/tests/device_tests/test_msg_recoverydevice_t2.py +++ b/trezorlib/tests/device_tests/test_msg_recoverydevice_t2.py @@ -20,6 +20,7 @@ import pytest from .common import TrezorTest from trezorlib import messages as proto +from trezorlib import device @pytest.mark.skip_t1 @@ -100,4 +101,4 @@ class TestMsgRecoverydeviceT2(TrezorTest): def test_already_initialized(self): self.setup_mnemonic_nopin_nopassphrase() with pytest.raises(Exception): - self.client.recovery_device(12, False, False, 'label', 'english') + device.recover(self.client, 12, False, False, 'label', 'english') diff --git a/trezorlib/tests/device_tests/test_msg_resetdevice.py b/trezorlib/tests/device_tests/test_msg_resetdevice.py index 47f6c5f611..784e5730d6 100644 --- a/trezorlib/tests/device_tests/test_msg_resetdevice.py +++ b/trezorlib/tests/device_tests/test_msg_resetdevice.py @@ -19,6 +19,7 @@ import pytest from .common import TrezorTest, generate_entropy from trezorlib import messages as proto +from trezorlib import device from mnemonic import Mnemonic @@ -203,4 +204,4 @@ class TestMsgResetDevice(TrezorTest): def test_already_initialized(self): self.setup_mnemonic_nopin_nopassphrase() with pytest.raises(Exception): - self.client.reset_device(False, 128, True, True, 'label', 'english') + device.reset(self.client, False, 128, True, True, 'label', 'english') diff --git a/trezorlib/tests/device_tests/test_msg_resetdevice_t2.py b/trezorlib/tests/device_tests/test_msg_resetdevice_t2.py index d363c5cd1b..4236950e83 100644 --- a/trezorlib/tests/device_tests/test_msg_resetdevice_t2.py +++ b/trezorlib/tests/device_tests/test_msg_resetdevice_t2.py @@ -20,6 +20,7 @@ import pytest from .common import TrezorTest, generate_entropy from trezorlib import messages as proto +from trezorlib import device from mnemonic import Mnemonic @@ -203,4 +204,4 @@ class TestMsgResetDeviceT2(TrezorTest): def test_already_initialized(self): self.setup_mnemonic_nopin_nopassphrase() with pytest.raises(Exception): - self.client.reset_device(False, 128, True, True, 'label', 'english') + device.reset(self.client, False, 128, True, True, 'label', 'english') diff --git a/trezorlib/tests/device_tests/test_msg_ripple_get_address.py b/trezorlib/tests/device_tests/test_msg_ripple_get_address.py index 8c1e1c2da0..ed4d420a07 100644 --- a/trezorlib/tests/device_tests/test_msg_ripple_get_address.py +++ b/trezorlib/tests/device_tests/test_msg_ripple_get_address.py @@ -21,6 +21,7 @@ from .conftest import TREZOR_VERSION from binascii import hexlify from trezorlib.ripple import get_address from trezorlib.tools import parse_path, CallException +from trezorlib import debuglink @pytest.mark.ripple @@ -41,7 +42,8 @@ class TestMsgRippleGetAddress(TrezorTest): def test_ripple_get_address_other(self): # data from https://github.com/you21979/node-ripple-bip32/blob/master/test/test.js - self.client.load_device_by_mnemonic( + 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, diff --git a/trezorlib/tests/device_tests/test_msg_signidentity.py b/trezorlib/tests/device_tests/test_msg_signidentity.py index 583340ce0d..efc8db2864 100644 --- a/trezorlib/tests/device_tests/test_msg_signidentity.py +++ b/trezorlib/tests/device_tests/test_msg_signidentity.py @@ -20,6 +20,7 @@ from binascii import hexlify, unhexlify from .common import TrezorTest from trezorlib import messages as proto +from trezorlib import misc def check_path(identity): @@ -56,7 +57,7 @@ class TestMsgSignidentity(TrezorTest): # hash : d0e2389d4c8394a9f3e32de01104bf6e8db2d9e2bb0905d60fffa5a18fd696db # path : m/2147483661/2637750992/2845082444/3761103859/4005495825 identity = proto.IdentityType(proto='https', user='satoshi', host='bitcoin.org', port='', path='/login', index=0) - sig = self.client.sign_identity(identity, hidden, visual) + sig = misc.sign_identity(self.client, identity, hidden, visual) assert sig.address == '17F17smBTX9VTZA9Mj8LM5QGYNZnmziCjL' assert hexlify(sig.public_key) == b'023a472219ad3327b07c18273717bb3a40b39b743756bf287fbd5fa9d263237f45' assert hexlify(sig.signature) == b'20f2d1a42d08c3a362be49275c3ffeeaa415fc040971985548b9f910812237bb41770bf2c8d488428799fbb7e52c11f1a3404011375e4080e077e0e42ab7a5ba02' @@ -65,7 +66,7 @@ class TestMsgSignidentity(TrezorTest): # hash : 79a6b53831c6ff224fb283587adc4ebae8fb0d734734a46c876838f52dff53f3 # path : m/2147483661/3098912377/2734671409/3632509519/3125730426 identity = proto.IdentityType(proto='ftp', user='satoshi', host='bitcoin.org', port='2323', path='/pub', index=3) - sig = self.client.sign_identity(identity, hidden, visual) + sig = misc.sign_identity(self.client, identity, hidden, visual) assert sig.address == '1KAr6r5qF2kADL8bAaRQBjGKYEGxn9WrbS' assert hexlify(sig.public_key) == b'0266cf12d2ba381c5fd797da0d64f59c07a6f1b034ad276cca6bf2729e92b20d9c' assert hexlify(sig.signature) == b'20bbd12dc657d534fc0f7e40186e22c447e0866a016f654f380adffa9a84e9faf412a1bb0ae908296537838cf91145e77da08681c63d07b7dca40728b9e6cb17cf' @@ -74,7 +75,7 @@ class TestMsgSignidentity(TrezorTest): # hash : 5fa612f558a1a3b1fb7f010b2ea0a25cb02520a0ffa202ce74a92fc6145da5f3 # path : m/2147483661/4111640159/2980290904/2332131323/3701645358 identity = proto.IdentityType(proto='ssh', user='satoshi', host='bitcoin.org', port='', path='', index=47) - sig = self.client.sign_identity(identity, hidden, visual, ecdsa_curve_name='nist256p1') + sig = misc.sign_identity(self.client, identity, hidden, visual, ecdsa_curve_name='nist256p1') assert sig.address is None assert hexlify(sig.public_key) == b'0373f21a3da3d0e96fc2189f81dd826658c3d76b2d55bd1da349bc6c3573b13ae4' assert hexlify(sig.signature) == b'005122cebabb852cdd32103b602662afa88e54c0c0c1b38d7099c64dcd49efe908288114e66ed2d8c82f23a70b769a4db723173ec53840c08aafb840d3f09a18d3' @@ -83,7 +84,7 @@ class TestMsgSignidentity(TrezorTest): # hash : 5fa612f558a1a3b1fb7f010b2ea0a25cb02520a0ffa202ce74a92fc6145da5f3 # path : m/2147483661/4111640159/2980290904/2332131323/3701645358 identity = proto.IdentityType(proto='ssh', user='satoshi', host='bitcoin.org', port='', path='', index=47) - sig = self.client.sign_identity(identity, hidden, visual, ecdsa_curve_name='ed25519') + sig = misc.sign_identity(self.client, identity, hidden, visual, ecdsa_curve_name='ed25519') assert sig.address is None assert hexlify(sig.public_key) == b'000fac2a491e0f5b871dc48288a4cae551bac5cb0ed19df0764d6e721ec5fade18' assert hexlify(sig.signature) == b'00f05e5085e666429de397c70a081932654369619c0bd2a6579ea6c1ef2af112ef79998d6c862a16b932d44b1ac1b83c8cbcd0fbda228274fde9e0d0ca6e9cb709' diff --git a/trezorlib/tests/device_tests/test_msg_signmessage.py b/trezorlib/tests/device_tests/test_msg_signmessage.py index e86824a718..1db56bd669 100644 --- a/trezorlib/tests/device_tests/test_msg_signmessage.py +++ b/trezorlib/tests/device_tests/test_msg_signmessage.py @@ -17,31 +17,32 @@ from binascii import hexlify from .common import TrezorTest +from trezorlib import btc class TestMsgSignmessage(TrezorTest): def test_sign(self): self.setup_mnemonic_nopin_nopassphrase() - sig = self.client.sign_message('Bitcoin', [0], "This is an example of a signed message.") + sig = btc.sign_message(self.client, 'Bitcoin', [0], "This is an example of a signed message.") assert sig.address == '14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e' assert hexlify(sig.signature) == b'209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80' def test_sign_testnet(self): self.setup_mnemonic_nopin_nopassphrase() - sig = self.client.sign_message('Testnet', [0], "This is an example of a signed message.") + sig = btc.sign_message(self.client, 'Testnet', [0], "This is an example of a signed message.") assert sig.address == 'mirio8q3gtv7fhdnmb3TpZ4EuafdzSs7zL' assert hexlify(sig.signature) == b'209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80' def test_sign_bch(self): self.setup_mnemonic_nopin_nopassphrase() - sig = self.client.sign_message('Bcash', [0], "This is an example of a signed message.") + sig = btc.sign_message(self.client, 'Bcash', [0], "This is an example of a signed message.") assert sig.address == 'bitcoincash:qqj22md58nm09vpwsw82fyletkxkq36zxyxh322pru' assert hexlify(sig.signature) == b'209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80' def test_sign_long(self): self.setup_mnemonic_nopin_nopassphrase() - sig = self.client.sign_message('Bitcoin', [0], "VeryLongMessage!" * 64) + sig = btc.sign_message(self.client, 'Bitcoin', [0], "VeryLongMessage!" * 64) assert sig.address == '14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e' assert hexlify(sig.signature) == b'205ff795c29aef7538f8b3bdb2e8add0d0722ad630a140b6aefd504a5a895cbd867cbb00981afc50edd0398211e8d7c304bb8efa461181bc0afa67ea4a720a89ed' @@ -51,10 +52,10 @@ class TestMsgSignmessage(TrezorTest): 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' - sig_nfkd = self.client.sign_message('Bitcoin', [0], words_nfkd) + sig_nfkd = btc.sign_message(self.client, 'Bitcoin', [0], words_nfkd) assert sig_nfkd.address == '14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e' assert hexlify(sig_nfkd.signature) == b'20d0ec02ed8da8df23e7fe9e680e7867cc290312fe1c970749d8306ddad1a1eda41c6a771b13d495dd225b13b0a9d0f915a984ee3d0703f92287bf8009fbb9f7d6' - sig_nfc = self.client.sign_message('Bitcoin', [0], words_nfc) + sig_nfc = btc.sign_message(self.client, 'Bitcoin', [0], words_nfc) assert sig_nfc.address == '14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e' assert hexlify(sig_nfc.signature) == b'20d0ec02ed8da8df23e7fe9e680e7867cc290312fe1c970749d8306ddad1a1eda41c6a771b13d495dd225b13b0a9d0f915a984ee3d0703f92287bf8009fbb9f7d6' diff --git a/trezorlib/tests/device_tests/test_msg_signmessage_segwit.py b/trezorlib/tests/device_tests/test_msg_signmessage_segwit.py index e7981c2edf..4f537be3ed 100644 --- a/trezorlib/tests/device_tests/test_msg_signmessage_segwit.py +++ b/trezorlib/tests/device_tests/test_msg_signmessage_segwit.py @@ -18,25 +18,26 @@ from binascii import hexlify from .common import TrezorTest from trezorlib import messages as proto +from trezorlib import btc class TestMsgSignmessageSegwit(TrezorTest): def test_sign(self): self.setup_mnemonic_nopin_nopassphrase() - sig = self.client.sign_message('Bitcoin', [0], "This is an example of a signed message.", script_type=proto.InputScriptType.SPENDP2SHWITNESS) + sig = btc.sign_message(self.client, 'Bitcoin', [0], "This is an example of a signed message.", script_type=proto.InputScriptType.SPENDP2SHWITNESS) assert sig.address == '3CwYaeWxhpXXiHue3ciQez1DLaTEAXcKa1' assert hexlify(sig.signature) == b'249e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80' def test_sign_testnet(self): self.setup_mnemonic_nopin_nopassphrase() - sig = self.client.sign_message('Testnet', [0], "This is an example of a signed message.", script_type=proto.InputScriptType.SPENDP2SHWITNESS) + sig = btc.sign_message(self.client, 'Testnet', [0], "This is an example of a signed message.", script_type=proto.InputScriptType.SPENDP2SHWITNESS) assert sig.address == '2N4VkePSzKH2sv5YBikLHGvzUYvfPxV6zS9' assert hexlify(sig.signature) == b'249e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80' def test_sign_long(self): self.setup_mnemonic_nopin_nopassphrase() - sig = self.client.sign_message('Bitcoin', [0], "VeryLongMessage!" * 64, script_type=proto.InputScriptType.SPENDP2SHWITNESS) + sig = btc.sign_message(self.client, 'Bitcoin', [0], "VeryLongMessage!" * 64, script_type=proto.InputScriptType.SPENDP2SHWITNESS) assert sig.address == '3CwYaeWxhpXXiHue3ciQez1DLaTEAXcKa1' assert hexlify(sig.signature) == b'245ff795c29aef7538f8b3bdb2e8add0d0722ad630a140b6aefd504a5a895cbd867cbb00981afc50edd0398211e8d7c304bb8efa461181bc0afa67ea4a720a89ed' @@ -46,10 +47,10 @@ class TestMsgSignmessageSegwit(TrezorTest): 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' - sig_nfkd = self.client.sign_message('Bitcoin', [0], words_nfkd, script_type=proto.InputScriptType.SPENDP2SHWITNESS) + sig_nfkd = btc.sign_message(self.client, 'Bitcoin', [0], words_nfkd, script_type=proto.InputScriptType.SPENDP2SHWITNESS) assert sig_nfkd.address == '3CwYaeWxhpXXiHue3ciQez1DLaTEAXcKa1' assert hexlify(sig_nfkd.signature) == b'24d0ec02ed8da8df23e7fe9e680e7867cc290312fe1c970749d8306ddad1a1eda41c6a771b13d495dd225b13b0a9d0f915a984ee3d0703f92287bf8009fbb9f7d6' - sig_nfc = self.client.sign_message('Bitcoin', [0], words_nfc, script_type=proto.InputScriptType.SPENDP2SHWITNESS) + sig_nfc = btc.sign_message(self.client, 'Bitcoin', [0], words_nfc, script_type=proto.InputScriptType.SPENDP2SHWITNESS) assert sig_nfc.address == '3CwYaeWxhpXXiHue3ciQez1DLaTEAXcKa1' assert hexlify(sig_nfc.signature) == b'24d0ec02ed8da8df23e7fe9e680e7867cc290312fe1c970749d8306ddad1a1eda41c6a771b13d495dd225b13b0a9d0f915a984ee3d0703f92287bf8009fbb9f7d6' diff --git a/trezorlib/tests/device_tests/test_msg_signmessage_segwit_native.py b/trezorlib/tests/device_tests/test_msg_signmessage_segwit_native.py index 748f9f98a8..b5afd6071d 100644 --- a/trezorlib/tests/device_tests/test_msg_signmessage_segwit_native.py +++ b/trezorlib/tests/device_tests/test_msg_signmessage_segwit_native.py @@ -18,25 +18,26 @@ from binascii import hexlify from .common import TrezorTest from trezorlib import messages as proto +from trezorlib import btc class TestMsgSignmessageSegwitNative(TrezorTest): def test_sign(self): self.setup_mnemonic_nopin_nopassphrase() - sig = self.client.sign_message('Bitcoin', [0], "This is an example of a signed message.", script_type=proto.InputScriptType.SPENDWITNESS) + sig = btc.sign_message(self.client, 'Bitcoin', [0], "This is an example of a signed message.", script_type=proto.InputScriptType.SPENDWITNESS) assert sig.address == 'bc1qyjjkmdpu7metqt5r36jf872a34syws33s82q2j' assert hexlify(sig.signature) == b'289e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80' def test_sign_testnet(self): self.setup_mnemonic_nopin_nopassphrase() - sig = self.client.sign_message('Testnet', [0], "This is an example of a signed message.", script_type=proto.InputScriptType.SPENDWITNESS) + sig = btc.sign_message(self.client, 'Testnet', [0], "This is an example of a signed message.", script_type=proto.InputScriptType.SPENDWITNESS) assert sig.address == 'tb1qyjjkmdpu7metqt5r36jf872a34syws336p3n3p' assert hexlify(sig.signature) == b'289e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80' def test_sign_long(self): self.setup_mnemonic_nopin_nopassphrase() - sig = self.client.sign_message('Bitcoin', [0], "VeryLongMessage!" * 64, script_type=proto.InputScriptType.SPENDWITNESS) + sig = btc.sign_message(self.client, 'Bitcoin', [0], "VeryLongMessage!" * 64, script_type=proto.InputScriptType.SPENDWITNESS) assert sig.address == 'bc1qyjjkmdpu7metqt5r36jf872a34syws33s82q2j' assert hexlify(sig.signature) == b'285ff795c29aef7538f8b3bdb2e8add0d0722ad630a140b6aefd504a5a895cbd867cbb00981afc50edd0398211e8d7c304bb8efa461181bc0afa67ea4a720a89ed' @@ -46,10 +47,10 @@ class TestMsgSignmessageSegwitNative(TrezorTest): 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' - sig_nfkd = self.client.sign_message('Bitcoin', [0], words_nfkd, script_type=proto.InputScriptType.SPENDWITNESS) + sig_nfkd = btc.sign_message(self.client, 'Bitcoin', [0], words_nfkd, script_type=proto.InputScriptType.SPENDWITNESS) assert sig_nfkd.address == 'bc1qyjjkmdpu7metqt5r36jf872a34syws33s82q2j' assert hexlify(sig_nfkd.signature) == b'28d0ec02ed8da8df23e7fe9e680e7867cc290312fe1c970749d8306ddad1a1eda41c6a771b13d495dd225b13b0a9d0f915a984ee3d0703f92287bf8009fbb9f7d6' - sig_nfc = self.client.sign_message('Bitcoin', [0], words_nfc, script_type=proto.InputScriptType.SPENDWITNESS) + sig_nfc = btc.sign_message(self.client, 'Bitcoin', [0], words_nfc, script_type=proto.InputScriptType.SPENDWITNESS) assert sig_nfc.address == 'bc1qyjjkmdpu7metqt5r36jf872a34syws33s82q2j' assert hexlify(sig_nfc.signature) == b'28d0ec02ed8da8df23e7fe9e680e7867cc290312fe1c970749d8306ddad1a1eda41c6a771b13d495dd225b13b0a9d0f915a984ee3d0703f92287bf8009fbb9f7d6' diff --git a/trezorlib/tests/device_tests/test_msg_signtx.py b/trezorlib/tests/device_tests/test_msg_signtx.py index ec0dfecd00..49360f2ff2 100644 --- a/trezorlib/tests/device_tests/test_msg_signtx.py +++ b/trezorlib/tests/device_tests/test_msg_signtx.py @@ -23,6 +23,7 @@ from .conftest import TREZOR_VERSION from trezorlib import messages as proto from trezorlib.tx_api import TxApiInsight from trezorlib.tools import parse_path, CallException +from trezorlib import btc TxApiTestnet = TxApiInsight("insight_testnet") @@ -78,7 +79,7 @@ class TestMsgSigntx(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, ], [out1, ]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Bitcoin', [inp1, ], [out1, ]) # Accepted by network: tx fd79435246dee76b2f159d2db08032d666c95adc544de64c8c49f474df4a7fee assert hexlify(serialized_tx) == b'010000000182488650ef25a58fef6788bd71b8212038d7f2bbe4750bc7bcb44701e85ef6d5000000006b4830450221009a0b7be0d4ed3146ee262b42202841834698bb3ee39c24e7437df208b8b7077102202b79ab1e7736219387dffe8d615bbdba87e11477104b867ef47afed1a5ede7810121023230848585885f63803a0a8aecdd6538792d5c539215c91698e315bf0253b43dffffffff0160cc0500000000001976a914de9b2a8da088824e8fe51debea566617d851537888ac00000000' @@ -127,7 +128,7 @@ class TestMsgSigntx(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Testnet', [inp1, ], [out1, out2]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [inp1, ], [out1, out2]) assert hexlify(serialized_tx) == b'0100000001cd3b93f5b24ae190ce5141235091cd93fbb2908e24e5b9ff6776aec11b0e04e5000000006b483045022100eba3bbcbb82ab1ebac88a394e8fb53b0263dadbb3e8072f0a21ee62818c911060220686a9b7f306d028b54a228b5c47cc6c27b1d01a3b0770440bcc64d55d8bace2c0121030e669acac1f280d1ddf441cd2ba5e97417bf2689e4bbec86df4f831bf9f7ffd0ffffffff021023cb01000000001976a91485eb47fe98f349065d6f044e27a4ac541af79ee288aca0bb0d00000000001976a9143d3cca567e00a04819742b21a696a67da796498b88ac00000000' @@ -177,7 +178,7 @@ class TestMsgSigntx(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Testnet', [inp1, ], [out1, out2]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [inp1, ], [out1, out2]) assert hexlify(serialized_tx) == b'0100000001549d2977998f899a63c0a9da30dedb2841e33fef561097b05822eccbc7f3906f010000006a47304402205ea68e9d52d4be14420ccecf7f2e11489d49b86bedb79ee99b5e9b7188884150022056219cb3384a5df8048cca286a9533403dbda1571afd84b51379cdaee6a6dea80121023230848585885f63803a0a8aecdd6538792d5c539215c91698e315bf0253b43dffffffff020084d717000000001976a9140223b1a09138753c9cb0baf95a0a62c82711567a88ac0065cd1d000000001976a9142db345c36563122e2fd0f5485fb7ea9bbf7cb5a288ac00000000' @@ -223,7 +224,7 @@ class TestMsgSigntx(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, ], [out1, out2]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Bitcoin', [inp1, ], [out1, out2]) assert hexlify(serialized_tx) == b'01000000016d20f69067ad1ffd50ee7c0f377dde2c932ccb03e84b5659732da99c20f1f650010000006a47304402203429bd3ce7b38c5c1e8a15340edd79ced41a2939aae62e259d2e3d18e0c5ee7602201b83b10ebc4d6dcee3f9eb42ba8f1ef8a059a05397e0c1b9223d1565a3e6ec01012102a7a079c1ef9916b289c2ff21a992c808d0de3dfcf8a9f163205c5c9e21f55d5cffffffff0230750000000000001976a914954820f1de627a703596ac0396f986d958e3de4c88ac10270000000000001976a91405427736705cfbfaff76b1cff48283707fb1037088ac00000000' @@ -281,7 +282,7 @@ class TestMsgSigntx(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=2)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, ], [out1, out2, out3]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Bitcoin', [inp1, ], [out1, out2, out3]) assert hexlify(serialized_tx) == b'010000000182488650ef25a58fef6788bd71b8212038d7f2bbe4750bc7bcb44701e85ef6d5000000006b483045022100e695e2c530c7c0fc32e6b79b7cff56a7f70a8c9da787534f46b4204070f914fc02207b0879a81408a11e23b11d4c7965c62b5fc6d5c2d92340f5ee2da7b40e99314a0121023230848585885f63803a0a8aecdd6538792d5c539215c91698e315bf0253b43dffffffff0300650400000000001976a914de9b2a8da088824e8fe51debea566617d851537888ace02e0000000000001976a9141fe1d337fb81afca42818051e12fd18245d1b17288ac80380100000000001976a9140223b1a09138753c9cb0baf95a0a62c82711567a88ac00000000' @@ -349,7 +350,7 @@ class TestMsgSigntx(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, inp2], [out1, out2]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Bitcoin', [inp1, inp2], [out1, out2]) # Accepted by network: tx c63e24ed820c5851b60c54613fbc4bcb37df6cd49b4c96143e99580a472f79fb assert hexlify(serialized_tx) == b'01000000021c032e5715d1da8115a2fe4f57699e15742fe113b0d2d1ca3b594649d322bec6010000006b483045022100f773c403b2f85a5c1d6c9c4ad69c43de66930fff4b1bc818eb257af98305546a0220443bde4be439f276a6ce793664b463580e210ec6c9255d68354449ac0443c76501210338d78612e990f2eea0c426b5e48a8db70b9d7ed66282b3b26511e0b1c75515a6ffffffff6ea42cd8d9c8e5441c4c5f85bfe50311078730d2881494f11f4d2257777a4958010000006b48304502210090cff1c1911e771605358a8cddd5ae94c7b60cc96e50275908d9bf9d6367c79f02202bfa72e10260a146abd59d0526e1335bacfbb2b4401780e9e3a7441b0480c8da0121038caebd6f753bbbd2bb1f3346a43cd32140648583673a31d62f2dfb56ad0ab9e3ffffffff02a0860100000000001976a9142f4490d5263906e4887ca2996b9e207af3e7824088aca0860100000000001976a914812c13d97f9159e54e326b481b8f88a73df8507a88ac00000000' @@ -441,7 +442,7 @@ class TestMsgSigntx(TrezorTest): ] + [ proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, inp2], outputs) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Bitcoin', [inp1, inp2], outputs) if cnt == 255: assert hexlify(serialized_tx) == b'0100000002fb792f470a58993e14964c9bd46cdf37cb4bbc3f61540cb651580c82ed243ec6010000006b483045022100969da46f94a81f34f3717b014e0c3e1826eda1b0022ec2f9ce39f3d750ab9235022026da269770993211a1503413566a339bbb4389a482fffcf8e1f76713fc3b94f5012103477b9f0f34ae85434ce795f0c5e1e90c9420e5b5fad084d7cce9a487b94a7902ffffffffe56582d2119100cb1d3da8232291e053f71e25fb669c87b32a667749959ea239010000006a473044022052e1419bb237b9db400ab5e3df16db6355619d545fde9030924a360763ae9ad40220704beab04d72ecaeb42eca7d98faca7a0941e65f2e1341f183be2b83e6b09e1c012103477b9f0f34ae85434ce795f0c5e1e90c9420e5b5fad084d7cce9a487b94a7902fffffffffdff00' + b'd8270000000000001976a914f0a2b64e56ee2ff57126232f84af6e3a41d4055088ac' * cnt + b'00000000' @@ -481,7 +482,7 @@ class TestMsgSigntx(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, ], [out1, ]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Bitcoin', [inp1, ], [out1, ]) assert hexlify(serialized_tx) == b'0100000001a6cab19c507e547ec87c1f3074d8fdd8379e90e6d5af7929f52c30b46e417015000000006b483045022100dc3531da7feb261575f03b5b9bbb35edc7f73bb081c92538827105de4102737002200161e34395f6a8ee93979200cb974fa75ccef6d7c14021511cf468eece90d6450121023230848585885f63803a0a8aecdd6538792d5c539215c91698e315bf0253b43dffffffff01d018ee05000000001976a914de9b2a8da088824e8fe51debea566617d851537888ac00000000' @@ -517,7 +518,7 @@ class TestMsgSigntx(TrezorTest): ]) with pytest.raises(CallException) as exc: - self.client.sign_tx('Bitcoin', [inp1, ], [out1, ]) + btc.sign_tx(self.client, 'Bitcoin', [inp1, ], [out1, ]) assert exc.value.args[0] == proto.FailureType.NotEnoughFunds def test_p2sh(self): @@ -551,7 +552,7 @@ class TestMsgSigntx(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, ], [out1, ]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Bitcoin', [inp1, ], [out1, ]) # Accepted by network: tx 8cc1f4adf7224ce855cf535a5104594a0004cb3b640d6714fdb00b9128832dd5 assert hexlify(serialized_tx) == b'0100000001a3fb2d38322c3b327e54005cebc0686d52fcdf536e53bb5ef481a7de8056aa54010000006b4830450221009e020b0390ccad533b73b552f8a99a9d827212c558e4f755503674d07c92ad4502202d606f7316990e0461c51d4add25054f19c697aa3e3c2ced4d568f0b2c57e62f0121023230848585885f63803a0a8aecdd6538792d5c539215c91698e315bf0253b43dffffffff0170f305000000000017a9147f844bdb0b8fd54b64e3d16c85dc1170f1ff97c18700000000' @@ -616,14 +617,14 @@ class TestMsgSigntx(TrezorTest): return msg # Test if the transaction can be signed normally - (_, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, inp2], [out1, out2]) + (_, serialized_tx) = btc.sign_tx(self.client, 'Bitcoin', [inp1, inp2], [out1, out2]) # Accepted by network: tx c63e24ed820c5851b60c54613fbc4bcb37df6cd49b4c96143e99580a472f79fb assert hexlify(serialized_tx) == b'01000000021c032e5715d1da8115a2fe4f57699e15742fe113b0d2d1ca3b594649d322bec6010000006b483045022100f773c403b2f85a5c1d6c9c4ad69c43de66930fff4b1bc818eb257af98305546a0220443bde4be439f276a6ce793664b463580e210ec6c9255d68354449ac0443c76501210338d78612e990f2eea0c426b5e48a8db70b9d7ed66282b3b26511e0b1c75515a6ffffffff6ea42cd8d9c8e5441c4c5f85bfe50311078730d2881494f11f4d2257777a4958010000006b48304502210090cff1c1911e771605358a8cddd5ae94c7b60cc96e50275908d9bf9d6367c79f02202bfa72e10260a146abd59d0526e1335bacfbb2b4401780e9e3a7441b0480c8da0121038caebd6f753bbbd2bb1f3346a43cd32140648583673a31d62f2dfb56ad0ab9e3ffffffff02a0860100000000001976a9142f4490d5263906e4887ca2996b9e207af3e7824088aca0860100000000001976a914812c13d97f9159e54e326b481b8f88a73df8507a88ac00000000' # Now run the attack, must trigger the exception with pytest.raises(CallException) as exc: - self.client.sign_tx('Bitcoin', [inp1, inp2], [out1, out2], debug_processor=attack_processor) + btc.sign_tx(self.client, 'Bitcoin', [inp1, inp2], [out1, out2], debug_processor=attack_processor) assert exc.value.args[0] in (proto.FailureType.ProcessError, proto.FailureType.DataError) assert exc.value.args[1].endswith('Transaction has changed during signing') @@ -677,7 +678,7 @@ class TestMsgSigntx(TrezorTest): return msg # Test if the transaction can be signed normally - (_, serialized_tx) = self.client.sign_tx('Testnet', [inp1], [out1, out2]) + (_, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [inp1], [out1, out2]) assert hexlify(serialized_tx) == b'0100000001243e15b53cc553d93ec4e27e16984adc3d885ef107c613a7577fea47f5dadcd2010000006a47304402207d517dcb6b823bba4d252da096795a7f914d0c477aee26e554ba61653c45608a02202cba1e805c586c830472f399510be5d42c2fcfd67b8a6b0690cbe8a3e6e475e801210364430c9122948e525e2f1c6d88f00f47679274f0810fd8c63754954f310995c1ffffffff02a0860100000000001976a914b3cc67f3349974d0f1b50e9bb5dfdf226f888fa088ac18555907000000001976a91485a3f5b0d23cdd61f5f8e1eb8c9ca0890dd15a9788ac00000000' @@ -698,7 +699,7 @@ class TestMsgSigntx(TrezorTest): ]) # Now run the attack, must trigger the exception with pytest.raises(CallException) as exc: - self.client.sign_tx('Testnet', [inp1], [out1, out2], debug_processor=attack_processor) + btc.sign_tx(self.client, 'Testnet', [inp1], [out1, out2], debug_processor=attack_processor) assert exc.value.args[0] == proto.FailureType.ProcessError if TREZOR_VERSION == 1: @@ -741,7 +742,7 @@ class TestMsgSigntx(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Testnet', [inp1, ], [out1, ]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [inp1, ], [out1, ]) # Accepted by network: tx assert hexlify(serialized_tx) == b'010000000136825bfdb78c8ede226c7c4f25a018e99a2c061d63c7fb425fca7c7d6721dad6000000006a473044022047845c366eb24f40be315c7815a154513c444c7989eb80f7ce7ff6aeb703d26a022007c1f5efadf67c5889634fd7ac39a7ce78bffac291673e8772ecd8389c901d9f01210338d78612e990f2eea0c426b5e48a8db70b9d7ed66282b3b26511e0b1c75515a6ffffffff01c6100795000000001976a9143d2496e67f5f57a924353da42d4725b318e7a8ea88ac00000000' @@ -803,7 +804,7 @@ class TestMsgSigntx(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - self.client.sign_tx('Testnet', [inp1, ], [out1, out_change1, out_change2]) + btc.sign_tx(self.client, 'Testnet', [inp1, ], [out1, out_change1, out_change2]) def test_change_on_main_chain_allowed(self): self.setup_mnemonic_allallall() @@ -854,4 +855,4 @@ class TestMsgSigntx(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - self.client.sign_tx('Testnet', [inp1, ], [out1, out_change]) + btc.sign_tx(self.client, 'Testnet', [inp1, ], [out1, out_change]) diff --git a/trezorlib/tests/device_tests/test_msg_signtx_bcash.py b/trezorlib/tests/device_tests/test_msg_signtx_bcash.py index e9abbbac5f..32978b8687 100644 --- a/trezorlib/tests/device_tests/test_msg_signtx_bcash.py +++ b/trezorlib/tests/device_tests/test_msg_signtx_bcash.py @@ -22,6 +22,7 @@ from ..support.ckd_public import deserialize from trezorlib import coins from trezorlib import messages as proto from trezorlib.tools import parse_path, CallException +from trezorlib import btc TxApiBcash = coins.tx_api['Bcash'] @@ -61,7 +62,7 @@ class TestMsgSigntxBch(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Bcash', [inp1], [out1, out2]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Bcash', [inp1], [out1, out2]) assert hexlify(serialized_tx) == b'0100000001781a716b1e15b41b07157933e5d777392a75bf87132650cb2e7d46fb8dc237bc000000006a473044022061aee4f17abe044d5df8c52c9ffd3b84e5a29743517e488b20ecf1ae0b3e4d3a02206bb84c55e407f3b684ff8d9bea0a3409cfd865795a19d10b3d3c31f12795c34a412103a020b36130021a0f037c1d1a02042e325c0cb666d6478c1afdcd9d913b9ef080ffffffff0272ee1c00000000001976a914b1401fce7e8bf123c88a0467e0ed11e3b9fbef5488acec1e0100000000001976a914d51eca49695cdf47e7f4b55507893e3ad53fe9d888ac00000000' @@ -101,7 +102,7 @@ class TestMsgSigntxBch(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Bcash', [inp1, inp2], [out1]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Bcash', [inp1, inp2], [out1]) assert hexlify(serialized_tx) == b'01000000022c06cf6f215c5cbfd7caa8e71b1b32630cabf1f816a4432815b037b277852e50000000006a47304402207a2a955f1cb3dc5f03f2c82934f55654882af4e852e5159639f6349e9386ec4002205fb8419dce4e648eae8f67bc4e369adfb130a87d2ea2d668f8144213b12bb457412103174c61e9c5362507e8061e28d2c0ce3d4df4e73f3535ae0b12f37809e0f92d2dffffffff2c06cf6f215c5cbfd7caa8e71b1b32630cabf1f816a4432815b037b277852e50010000006a473044022062151cf960b71823bbe68c7ed2c2a93ad1b9706a30255fddb02fcbe056d8c26102207bad1f0872bc5f0cfaf22e45c925c35d6c1466e303163b75cb7688038f1a5541412102595caf9aeb6ffdd0e82b150739a83297358b9a77564de382671056ad9e5b8c58ffffffff0170861d00000000001976a91434e9cec317896e818619ab7dc99d2305216ff4af88ac00000000' @@ -141,7 +142,7 @@ class TestMsgSigntxBch(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Bcash', [inp1, inp2], [out1]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Bcash', [inp1, inp2], [out1]) assert hexlify(serialized_tx) == b'01000000022c06cf6f215c5cbfd7caa8e71b1b32630cabf1f816a4432815b037b277852e50000000006a47304402207a2a955f1cb3dc5f03f2c82934f55654882af4e852e5159639f6349e9386ec4002205fb8419dce4e648eae8f67bc4e369adfb130a87d2ea2d668f8144213b12bb457412103174c61e9c5362507e8061e28d2c0ce3d4df4e73f3535ae0b12f37809e0f92d2dffffffff2c06cf6f215c5cbfd7caa8e71b1b32630cabf1f816a4432815b037b277852e50010000006a473044022062151cf960b71823bbe68c7ed2c2a93ad1b9706a30255fddb02fcbe056d8c26102207bad1f0872bc5f0cfaf22e45c925c35d6c1466e303163b75cb7688038f1a5541412102595caf9aeb6ffdd0e82b150739a83297358b9a77564de382671056ad9e5b8c58ffffffff0170861d00000000001976a91434e9cec317896e818619ab7dc99d2305216ff4af88ac00000000' @@ -208,7 +209,7 @@ class TestMsgSigntxBch(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - self.client.sign_tx('Bcash', [inp1, inp2], [out1]) + btc.sign_tx(self.client, 'Bcash', [inp1, inp2], [out1]) # now fails with self.client: @@ -224,7 +225,7 @@ class TestMsgSigntxBch(TrezorTest): ]) with pytest.raises(CallException) as exc: - self.client.sign_tx('Bcash', [inp1, inp2], [out1], debug_processor=attack_processor) + btc.sign_tx(self.client, 'Bcash', [inp1, inp2], [out1], debug_processor=attack_processor) assert exc.value.args[0] in (proto.FailureType.ProcessError, proto.FailureType.DataError) assert exc.value.args[1].endswith('Transaction has changed during signing') @@ -281,13 +282,13 @@ class TestMsgSigntxBch(TrezorTest): proto.Failure(code=proto.FailureType.ProcessError), ]) with pytest.raises(CallException): - self.client.sign_tx('Bcash', [inp1], [out1, out2], debug_processor=attack_processor) + btc.sign_tx(self.client, 'Bcash', [inp1], [out1, out2], debug_processor=attack_processor) def test_send_bch_multisig_wrongchange(self): self.setup_mnemonic_allallall() self.client.set_tx_api(TxApiBcash) xpubs = [] - for n in map(lambda index: self.client.get_public_node(parse_path("44'/145'/" + str(index) + "'")), range(1, 4)): + for n in map(lambda index: btc.get_public_node(self.client, parse_path("44'/145'/" + str(index) + "'")), range(1, 4)): xpubs.append(n.xpub) def getmultisig(chain, nr, signatures=[b'', b'', b''], xpubs=xpubs): @@ -332,7 +333,7 @@ class TestMsgSigntxBch(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures1, serialized_tx) = self.client.sign_tx('Bcash', [inp1], [out1]) + (signatures1, serialized_tx) = btc.sign_tx(self.client, 'Bcash', [inp1], [out1]) assert hexlify(signatures1[0]) == b'3044022052ccf022b3684ecce9f961ce8828387b97267c86bedf0ce16a24bf014e62e42c022035d315ddbeeef7ab3456bd09aed8b625ea58852216b60e4b84ba9f85827d305c' assert hexlify(serialized_tx) == b'01000000015f3d291cae106548f3be5ed0f4cbedc65668fa881d60347ab0d512df10af8cf601000000fc00473044022052ccf022b3684ecce9f961ce8828387b97267c86bedf0ce16a24bf014e62e42c022035d315ddbeeef7ab3456bd09aed8b625ea58852216b60e4b84ba9f85827d305c4147304402207274b5a4d15e75f3df7319a375557b0efba9b27bc63f9f183a17da95a6125c94022000efac57629f1522e2d3958430e2ef073b0706cfac06cce492651b79858f09ae414c69522103d62b2af2272bbd67cbe30eeaf4226c7f2d57d2a0ed1aab5ab736fb40bb2f5ffe21036d5e0d7ca3589465711eec91436249d7234d3a994c219024fc75cec98fc02ae221024f58378a69b68e89301a6ff882116e0fa35446ec9bfd86532eeb05941ec1f8c853aeffffffff01d85900000000000017a9140bb11de6558871f49fc241341992ece9986f7c5c8700000000' @@ -340,7 +341,7 @@ class TestMsgSigntxBch(TrezorTest): self.setup_mnemonic_allallall() self.client.set_tx_api(TxApiBcash) xpubs = [] - for n in map(lambda index: self.client.get_public_node(parse_path("44'/145'/" + str(index) + "'")), range(1, 4)): + for n in map(lambda index: btc.get_public_node(self.client, parse_path("44'/145'/" + str(index) + "'")), range(1, 4)): xpubs.append(n.xpub) def getmultisig(chain, nr, signatures=[b'', b'', b''], xpubs=xpubs): @@ -381,7 +382,7 @@ class TestMsgSigntxBch(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures1, serialized_tx) = self.client.sign_tx('Bcash', [inp1], [out1, out2]) + (signatures1, serialized_tx) = btc.sign_tx(self.client, 'Bcash', [inp1], [out1, out2]) assert hexlify(signatures1[0]) == b'3045022100bcb1a7134a13025a06052546ee1c6ac3640a0abd2d130190ed13ed7fcb43e9cd02207c381478e2ee123c850425bfbf6d3c691230eb37e333832cb32a1ed3f2cd9e85' @@ -408,7 +409,7 @@ class TestMsgSigntxBch(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures1, serialized_tx) = self.client.sign_tx('Bcash', [inp1], [out1, out2]) + (signatures1, serialized_tx) = btc.sign_tx(self.client, 'Bcash', [inp1], [out1, out2]) assert hexlify(signatures1[0]) == b'3045022100f1153636371ba1f84389460e1265a8fa296569bc18e117c31f4e8f0fc0650c01022022932cc84766ff0c0f65ed9633ad311ae90d4c8fe71f5e1890b1e8f74dd516fa' assert hexlify(serialized_tx) == b'0100000001a07660b10df9868df9393c9cf8962bc34f48cb2cea53b0865d2324bab8b96d8b00000000fdfe0000483045022100f1153636371ba1f84389460e1265a8fa296569bc18e117c31f4e8f0fc0650c01022022932cc84766ff0c0f65ed9633ad311ae90d4c8fe71f5e1890b1e8f74dd516fa41483045022100bcb1a7134a13025a06052546ee1c6ac3640a0abd2d130190ed13ed7fcb43e9cd02207c381478e2ee123c850425bfbf6d3c691230eb37e333832cb32a1ed3f2cd9e85414c69522102fcf63419c319ce1a42d69120a3599d6da8c5dd4caf2888220eccde5a1ff7c5d021036d7d5ef79370b7fabe2c058698a20219e97fc70868e65ecdd6b37cc18e8a88bd2103505dc649dab8cd1655a4c0daf0ec5f955881c9d7011478ea881fac11cab1e49953aeffffffff02c05d0000000000001976a91400741952f6a6eab5394f366db5cc5a54b0c2429f88acc05d00000000000017a914756c06d7e77de3950a6124f026d8e1a2464b3ecf8700000000' diff --git a/trezorlib/tests/device_tests/test_msg_signtx_bgold.py b/trezorlib/tests/device_tests/test_msg_signtx_bgold.py index 27717a0938..d3423629d9 100644 --- a/trezorlib/tests/device_tests/test_msg_signtx_bgold.py +++ b/trezorlib/tests/device_tests/test_msg_signtx_bgold.py @@ -22,6 +22,7 @@ from ..support.ckd_public import deserialize from trezorlib import coins from trezorlib import messages as proto from trezorlib.tools import parse_path, CallException +from trezorlib import btc TxApiBitcoinGold = coins.tx_api["Bgold"] @@ -61,7 +62,7 @@ class TestMsgSigntxBitcoinGold(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Bgold', [inp1], [out1, out2]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Bgold', [inp1], [out1, out2]) assert hexlify(serialized_tx) == b'010000000185c9dd4ae1071affd77d90b9d03c1b5fdd7c62cf30a9bb8230ad766cf06b5225000000006b483045022100963904da0731b71ce468afd45366dd80fbff566ec0d39c1161ab85d17459c7ca02202f5c24a7a7272d98b14a3f5bc000c7cde8ac0eb773f20f4c3131518186cc98854121023bd0ec4022d12d0106c5b7308a25572953ba1951f576f691354a7b147ee0cc1fffffffff0272ee1c00000000001976a9141c82b9c11f193ad82413caadc0955730572b50ae88acec1e0100000000001976a914ea5f904d195079a350b534db4446433b3cec222e88ac00000000' @@ -100,7 +101,7 @@ class TestMsgSigntxBitcoinGold(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Bgold', [inp1, inp2], [out1]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Bgold', [inp1, inp2], [out1]) assert hexlify(serialized_tx) == b'010000000285c9dd4ae1071affd77d90b9d03c1b5fdd7c62cf30a9bb8230ad766cf06b5225000000006b483045022100928852076c9fab160c07564cd54691af1cbc37fb28f0b7bee7299c7925ef62f0022058856387afecc6508f2f04ecdfd292a13026a5b2107ebdd2cc789bdf8820d552412102a6c3998d0d4e5197ff41aab5c53580253b3b91f583f4c31f7624be7dc83ce15fffffffff18fba85125ef7ccb651b5c79d920e0984a18430028f9e7db6e0e841b46c277db010000006b483045022100faa2f4f01cc95e680349a093923aae0aa2ea01429873555aa8a84bf630ef33a002204c3f4bf567e2d20540c0f71dc278481d6ccb6b95acda2a2f87ce521c79d6b872412102d54a7e5733b1635e5e9442943f48179b1700206b2d1925250ba10f1c86878be8ffffffff0170861d00000000001976a914ea5f904d195079a350b534db4446433b3cec222e88ac00000000' @@ -156,13 +157,13 @@ class TestMsgSigntxBitcoinGold(TrezorTest): proto.Failure(code=proto.FailureType.ProcessError), ]) with pytest.raises(CallException): - self.client.sign_tx('Bgold', [inp1], [out1, out2], debug_processor=attack_processor) + btc.sign_tx(self.client, 'Bgold', [inp1], [out1, out2], debug_processor=attack_processor) def test_send_bch_multisig_change(self): self.setup_mnemonic_allallall() self.client.set_tx_api(TxApiBitcoinGold) xpubs = [] - for n in map(lambda index: self.client.get_public_node(parse_path("44'/156'/" + str(index) + "'")), range(1, 4)): + for n in map(lambda index: btc.get_public_node(self.client, parse_path("44'/156'/" + str(index) + "'")), range(1, 4)): xpubs.append(n.xpub) def getmultisig(chain, nr, signatures=[b'', b'', b''], xpubs=xpubs): @@ -203,7 +204,7 @@ class TestMsgSigntxBitcoinGold(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures1, serialized_tx) = self.client.sign_tx('Bgold', [inp1], [out1, out2]) + (signatures1, serialized_tx) = btc.sign_tx(self.client, 'Bgold', [inp1], [out1, out2]) assert hexlify(signatures1[0]) == b'3045022100b1594f3b186d0dedbf61e53a1c407b1e0747098b7375941df85af045040f578e022013ba1893eb9e2fd854dd07073a83b261cf4beba76f66b07742e462b4088a7e4a' @@ -230,7 +231,7 @@ class TestMsgSigntxBitcoinGold(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures1, serialized_tx) = self.client.sign_tx('Bgold', [inp1], [out1, out2]) + (signatures1, serialized_tx) = btc.sign_tx(self.client, 'Bgold', [inp1], [out1, out2]) assert hexlify(signatures1[0]) == b'3044022006da8dbd14e6656ac8dcb956f4c0498574e88680eaeceb2cbafd8d2b2329d8cc02200972d076d444c5ff8f2ab18e14d8249ab661cb9c53335039bedcde037a40d747' assert hexlify(serialized_tx) == b'010000000185c9dd4ae1071affd77d90b9d03c1b5fdd7c62cf30a9bb8230ad766cf06b522500000000fdfd0000473044022006da8dbd14e6656ac8dcb956f4c0498574e88680eaeceb2cbafd8d2b2329d8cc02200972d076d444c5ff8f2ab18e14d8249ab661cb9c53335039bedcde037a40d74741483045022100b1594f3b186d0dedbf61e53a1c407b1e0747098b7375941df85af045040f578e022013ba1893eb9e2fd854dd07073a83b261cf4beba76f66b07742e462b4088a7e4a414c69522102290e6649574d17938c1ecb959ae92954f9ee48e1bd5b73f35ea931a3ab8a6087210379e0107b173e2c143426760627128c5eea3f862e8df92f3c2558eeeae4e347842103ff1746ca7dcf9e5c2eea9a73779b7c5bafed549f45cf3638a94cdf1e89c7f28f53aeffffffff02c05d0000000000001976a914ea5f904d195079a350b534db4446433b3cec222e88acc05d00000000000017a91445e917e46815d2b38d3f1cf072e63dd4f3b7a7e38700000000' @@ -269,7 +270,7 @@ class TestMsgSigntxBitcoinGold(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Bgold', [inp1], [out1, out2]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Bgold', [inp1], [out1, out2]) assert hexlify(serialized_tx) == b'0100000000010185c9dd4ae1071affd77d90b9d03c1b5fdd7c62cf30a9bb8230ad766cf06b52250000000017160014b5355d001e720d8f4513da00ff2bba4dcf9d39fcffffffff02e0aebb00000000001976a914ea5f904d195079a350b534db4446433b3cec222e88ac3df39f06000000001976a914a8f757819ec6779409f45788f7b4a0e8f51ec50488ac02473044022073fcbf2876f073f78923ab427f14de5b2a0fbeb313a9b2b650b3567061f242a702202f45fc22c501108ff6222afe3aca7da9d8c7dc860f9cda335bef31fa184e7bef412102ecea08b559fc5abd009acf77cfae13fa8a3b1933e3e031956c65c12cec8ca3e300000000' @@ -306,7 +307,7 @@ class TestMsgSigntxBitcoinGold(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Bgold', [inp1], [out1, out2]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Bgold', [inp1], [out1, out2]) # print(hexlify(serialized_tx)) # assert False @@ -315,7 +316,7 @@ class TestMsgSigntxBitcoinGold(TrezorTest): def test_send_multisig_1(self): self.setup_mnemonic_allallall() self.client.set_tx_api(TxApiBitcoinGold) - nodes = map(lambda index: self.client.get_public_node(parse_path("999'/1'/%d'" % index)), range(1, 4)) + nodes = map(lambda index: btc.get_public_node(self.client, parse_path("999'/1'/%d'" % index)), range(1, 4)) multisig = proto.MultisigRedeemScriptType( pubkeys=list(map(lambda n: proto.HDNodePathType(node=deserialize(n.xpub), address_n=[2, 0]), nodes)), signatures=[b'', b'', b''], @@ -346,7 +347,7 @@ class TestMsgSigntxBitcoinGold(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures1, _) = self.client.sign_tx('Bgold', [inp1], [out1]) + (signatures1, _) = btc.sign_tx(self.client, 'Bgold', [inp1], [out1]) # store signature inp1.multisig.signatures[0] = signatures1[0] # sign with third key @@ -361,6 +362,6 @@ class TestMsgSigntxBitcoinGold(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures2, serialized_tx) = self.client.sign_tx('Bgold', [inp1], [out1]) + (signatures2, serialized_tx) = btc.sign_tx(self.client, 'Bgold', [inp1], [out1]) assert hexlify(serialized_tx) == b'0100000000010185c9dd4ae1071affd77d90b9d03c1b5fdd7c62cf30a9bb8230ad766cf06b522501000000232200201e8dda334f11171190b3da72e526d441491464769679a319a2f011da5ad312a1ffffffff01887d1800000000001976a914ea5f904d195079a350b534db4446433b3cec222e88ac0400483045022100e728485c8337f9a09ebbf36edc0fef10f8bcf5c1ba601b7d8ba43a9250a898f002206b9e3401c297f9ab9afb7f1be59bb342db53b5b65aff7c557e3109679697df0f41473044022062ea69ecdc07d0dadc1971fbda50a629a56dd30f431db26327428f4992601ce602204a1c8ab9c7d81c36cb6f819109a26f9baaa9607b8d37bff5e24eee6fab4a04e441695221038e81669c085a5846e68e03875113ddb339ecbb7cb11376d4163bca5dc2e2a0c1210348c5c3be9f0e6cf1954ded1c0475beccc4d26aaa9d0cce2dd902538ff1018a112103931140ebe0fbbb7df0be04ed032a54e9589e30339ba7bbb8b0b71b15df1294da53ae00000000' diff --git a/trezorlib/tests/device_tests/test_msg_signtx_decred.py b/trezorlib/tests/device_tests/test_msg_signtx_decred.py index 7662834bf5..cff4bf227b 100644 --- a/trezorlib/tests/device_tests/test_msg_signtx_decred.py +++ b/trezorlib/tests/device_tests/test_msg_signtx_decred.py @@ -22,6 +22,7 @@ from .common import TrezorTest from trezorlib import coins from trezorlib import messages as proto from trezorlib.tools import parse_path +from trezorlib import btc TxApiDecredTestnet = coins.tx_api['Decred Testnet'] @@ -72,7 +73,7 @@ class TestMsgSigntxDecred(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx("Decred Testnet", [inp1], [out1]) + (signatures, serialized_tx) = btc.sign_tx(self.client, "Decred Testnet", [inp1], [out1]) # Accepted by network: 5e6e3500a333c53c02f523db5f1a9b17538a8850b4c2c24ecb9b7ba48059b970 assert serialized_tx == unhexlify("0100000001edd579e9462ee0e80127a817e0500d4f942a4cf8f2d6530e0c0a9ab3f04862e10100000000ffffffff01802b530b0000000000001976a914819d291a2f7fbf770e784bfd78b5ce92c58e95ea88ac000000000000000001000000000000000000000000ffffffff6b483045022100bad68486491e449a731513805c129201d7f65601d6f07c97fda0588453c97d22022013e9ef59657ae4f344ac4f0db2b7a23dbfcdb51ebeb85277146ac189e547d3f7012102f5a745afb96077c071e4d19911a5d3d024faa1314ee8688bc6eec39751d0818f") @@ -148,7 +149,7 @@ class TestMsgSigntxDecred(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=2)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx("Decred Testnet", [inp1, inp2, inp3], [out1, out2]) + (signatures, serialized_tx) = btc.sign_tx(self.client, "Decred Testnet", [inp1, inp2, inp3], [out1, out2]) # Accepted by network: c5ff767141a162b665acf775fcc35b60ff622fbe21a21e0a6609ed768c3737f4 assert serialized_tx == unhexlify("010000000370b95980a47b9bcb4ec2c2b450888a53179b1a5fdb23f5023cc533a300356e5e0000000000ffffffff74bc93bcfce18aff2e522d6822817522e2815a00175b2eae59ef20d20f5bf9cc0100000000ffffffff13317ab453832deabd684d2302eed42580c28ba3e715db66a731a8723eef95f30000000000ffffffff02d86c341d0000000000001976a9143eb656115197956125365348c542e37b6d3d259988ac00e1f5050000000000001976a9146748ebb8694c069742ee69eab2159c33c7f57d2b88ac000000000000000003000000000000000000000000ffffffff6b483045022100d91237a32b8968e1d3316b76f045cc18fed12736aebd570dd023a61826279cc102204222b133189762368d3398d11eb9a6843a67de11d70ac58426a28b605fa102b1012102f5a745afb96077c071e4d19911a5d3d024faa1314ee8688bc6eec39751d0818f000000000000000000000000ffffffff69463043021f7cf9b0b180f3fcde8d3d036d81e575e368d6ab5c8c6a2ffef47c06a0170023022036b964bf26ff276c58862dfacafa93216618832d6240f16b6100a9d10d5eb753012102f5a745afb96077c071e4d19911a5d3d024faa1314ee8688bc6eec39751d0818f000000000000000000000000ffffffff6b48304502210098f3a0cc17c3383f5998c542950b5cccb1175cc94b8d0343f420dc64abe9a50e0220507974c6ef0761925634fe3e13ec458b8cd3e42856828d584d4a5d39cc4d0f890121022c6099c7af8124d58e97beefc85c529dcfb3865794d46ec04095e70872e32a2e") @@ -158,7 +159,7 @@ class TestMsgSigntxDecred(TrezorTest): self.client.set_tx_api(TxApiDecredTestnet) paths = [parse_path("m/48'/1'/%d'" % index) for index in range(3)] - nodes = [self.client.get_public_node(address_n, coin_name="Decred Testnet").node for address_n in paths] + nodes = [btc.get_public_node(self.client, address_n, coin_name="Decred Testnet").node for address_n in paths] signatures = [ [b'', b'', b''], @@ -235,7 +236,7 @@ class TestMsgSigntxDecred(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signature, serialized_tx) = self.client.sign_tx("Decred Testnet", [inp1, inp2], [out1, out2]) + (signature, serialized_tx) = btc.sign_tx(self.client, "Decred Testnet", [inp1, inp2], [out1, out2]) signatures[0][index] = signature[0] signatures[1][index] = signature[1] diff --git a/trezorlib/tests/device_tests/test_msg_signtx_segwit.py b/trezorlib/tests/device_tests/test_msg_signtx_segwit.py index 5c1f37efb7..e823af10fd 100644 --- a/trezorlib/tests/device_tests/test_msg_signtx_segwit.py +++ b/trezorlib/tests/device_tests/test_msg_signtx_segwit.py @@ -24,6 +24,7 @@ from .common import TrezorTest from trezorlib import messages as proto from trezorlib.tx_api import TxApiInsight from trezorlib.tools import parse_path, CallException +from trezorlib import btc TxApiTestnet = TxApiInsight("insight_testnet") @@ -65,7 +66,7 @@ class TestMsgSigntxSegwit(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Testnet', [inp1], [out1, out2]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [inp1], [out1, out2]) assert hexlify(serialized_tx) == b'0100000000010137c361fb8f2d9056ba8c98c5611930fcb48cacfdd0fe2e0449d83eea982f91200000000017160014d16b8c0680c61fc6ed2e407455715055e41052f5ffffffff02e0aebb00000000001976a91414fdede0ddc3be652a0ce1afbc1b509a55b6b94888ac3df39f060000000017a91458b53ea7f832e8f096e896b8713a8c6df0e892ca8702483045022100ccd253bfdf8a5593cd7b6701370c531199f0f05a418cd547dfc7da3f21515f0f02203fa08a0753688871c220648f9edadbdb98af42e5d8269364a326572cf703895b012103e7bfe10708f715e8538c92d46ca50db6f657bbc455b7494e6a0303ccdb868b7900000000' @@ -103,14 +104,14 @@ class TestMsgSigntxSegwit(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Testnet', [inp1], [out1, out2]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [inp1], [out1, out2]) assert hexlify(serialized_tx) == b'0100000000010137c361fb8f2d9056ba8c98c5611930fcb48cacfdd0fe2e0449d83eea982f91200000000017160014d16b8c0680c61fc6ed2e407455715055e41052f5ffffffff02e0aebb00000000001976a91414fdede0ddc3be652a0ce1afbc1b509a55b6b94888ac3df39f060000000017a91458b53ea7f832e8f096e896b8713a8c6df0e892ca8702483045022100ccd253bfdf8a5593cd7b6701370c531199f0f05a418cd547dfc7da3f21515f0f02203fa08a0753688871c220648f9edadbdb98af42e5d8269364a326572cf703895b012103e7bfe10708f715e8538c92d46ca50db6f657bbc455b7494e6a0303ccdb868b7900000000' def test_send_multisig_1(self): self.setup_mnemonic_allallall() self.client.set_tx_api(TxApiTestnet) - nodes = map(lambda index: self.client.get_public_node(parse_path("999'/1'/%d'" % index)), range(1, 4)) + nodes = map(lambda index: btc.get_public_node(self.client, parse_path("999'/1'/%d'" % index)), range(1, 4)) multisig = proto.MultisigRedeemScriptType( pubkeys=list(map(lambda n: proto.HDNodePathType(node=deserialize(n.xpub), address_n=[2, 0]), nodes)), signatures=[b'', b'', b''], @@ -141,7 +142,7 @@ class TestMsgSigntxSegwit(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures1, _) = self.client.sign_tx('Testnet', [inp1], [out1]) + (signatures1, _) = btc.sign_tx(self.client, 'Testnet', [inp1], [out1]) # store signature inp1.multisig.signatures[0] = signatures1[0] # sign with third key @@ -156,7 +157,7 @@ class TestMsgSigntxSegwit(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures2, serialized_tx) = self.client.sign_tx('Testnet', [inp1], [out1]) + (signatures2, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [inp1], [out1]) assert hexlify(serialized_tx) == b'01000000000101be0210025c5be68a473f6a38bf53b53bc88d5c46567616026dc056e72b92319c01000000232200201e8dda334f11171190b3da72e526d441491464769679a319a2f011da5ad312a1ffffffff01887d1800000000001976a91414fdede0ddc3be652a0ce1afbc1b509a55b6b94888ac040047304402205b44c20cf2681690edaaf7cd2e30d4704124dd8b7eb1fb7f459d3906c3c374a602205ca359b6544ce2c101c979899c782f7d141c3b0454ea69202b1fb4c09d3b715701473044022052fafa64022554ae436dbf781e550bf0d326fef31eea1438350b3ff1940a180102202851bd19203b7fe8582a9ef52e82aa9f61cd52d4bcedfe6dcc0cf782468e6a8e01695221038e81669c085a5846e68e03875113ddb339ecbb7cb11376d4163bca5dc2e2a0c1210348c5c3be9f0e6cf1954ded1c0475beccc4d26aaa9d0cce2dd902538ff1018a112103931140ebe0fbbb7df0be04ed032a54e9589e30339ba7bbb8b0b71b15df1294da53ae00000000' @@ -222,7 +223,7 @@ class TestMsgSigntxSegwit(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Testnet', [inp1], [out1, out2]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [inp1], [out1, out2]) assert hexlify(serialized_tx) == b'0100000000010137c361fb8f2d9056ba8c98c5611930fcb48cacfdd0fe2e0449d83eea982f91200000000017160014d16b8c0680c61fc6ed2e407455715055e41052f5ffffffff02e0aebb00000000001976a91414fdede0ddc3be652a0ce1afbc1b509a55b6b94888ac3df39f060000000017a914dae9e09a7fc3bbe5a716fffec1bbb340b82a4fb9870248304502210099b5c4f8fd4402c9c0136fee5f711137d64fc9f14587e01bfa7798f5428f845d0220253e21c98f5b1b64efae69bc2ea9799c5620a43450baa6762a0c3cf4fdc886e5012103e7bfe10708f715e8538c92d46ca50db6f657bbc455b7494e6a0303ccdb868b7900000000' @@ -238,7 +239,7 @@ class TestMsgSigntxSegwit(TrezorTest): proto.Failure(code=proto.FailureType.ProcessError), ]) with pytest.raises(CallException) as exc: - self.client.sign_tx('Testnet', [inp1], [out1, out2], debug_processor=attack_processor) + btc.sign_tx(self.client, 'Testnet', [inp1], [out1, out2], debug_processor=attack_processor) assert exc.value.args[0] == proto.FailureType.ProcessError if TREZOR_VERSION == 1: assert exc.value.args[1].endswith("Failed to compile input") diff --git a/trezorlib/tests/device_tests/test_msg_signtx_segwit_native.py b/trezorlib/tests/device_tests/test_msg_signtx_segwit_native.py index 4851afb831..66034e5c44 100644 --- a/trezorlib/tests/device_tests/test_msg_signtx_segwit_native.py +++ b/trezorlib/tests/device_tests/test_msg_signtx_segwit_native.py @@ -21,6 +21,7 @@ from ..support.ckd_public import deserialize from trezorlib import messages as proto from trezorlib.tools import parse_path from trezorlib.tx_api import TxApiInsight +from trezorlib import btc TxApiTestnet = TxApiInsight("insight_testnet") @@ -62,7 +63,7 @@ class TestMsgSigntxSegwitNative(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Testnet', [inp1], [out1, out2]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [inp1], [out1, out2]) assert hexlify(serialized_tx) == b'0100000000010137c361fb8f2d9056ba8c98c5611930fcb48cacfdd0fe2e0449d83eea982f91200000000017160014d16b8c0680c61fc6ed2e407455715055e41052f5ffffffff02e0aebb00000000001600140099a7ecbd938ed1839f5f6bf6d50933c6db9d5c3df39f060000000017a91458b53ea7f832e8f096e896b8713a8c6df0e892ca8702483045022100bd3d8b8ad35c094e01f6282277300e575f1021678fc63ec3f9945d6e35670da3022052e26ef0dd5f3741c9d5939d1dec5464c15ab5f2c85245e70a622df250d4eb7c012103e7bfe10708f715e8538c92d46ca50db6f657bbc455b7494e6a0303ccdb868b7900000000' @@ -100,7 +101,7 @@ class TestMsgSigntxSegwitNative(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Testnet', [inp1], [out1, out2]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [inp1], [out1, out2]) assert hexlify(serialized_tx) == b'0100000000010137c361fb8f2d9056ba8c98c5611930fcb48cacfdd0fe2e0449d83eea982f91200000000017160014d16b8c0680c61fc6ed2e407455715055e41052f5ffffffff02e0aebb00000000001600140099a7ecbd938ed1839f5f6bf6d50933c6db9d5c3df39f060000000017a91458b53ea7f832e8f096e896b8713a8c6df0e892ca8702483045022100bd3d8b8ad35c094e01f6282277300e575f1021678fc63ec3f9945d6e35670da3022052e26ef0dd5f3741c9d5939d1dec5464c15ab5f2c85245e70a622df250d4eb7c012103e7bfe10708f715e8538c92d46ca50db6f657bbc455b7494e6a0303ccdb868b7900000000' @@ -139,7 +140,7 @@ class TestMsgSigntxSegwitNative(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Testnet', [inp1], [out1, out2]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [inp1], [out1, out2]) assert hexlify(serialized_tx) == b'010000000001018a44999c07bba32df1cacdc50987944e68e3205b4429438fdde35c76024614090000000000ffffffff02404b4c000000000017a9147a55d61848e77ca266e79a39bfc85c580a6426c987a8386f0000000000160014d16b8c0680c61fc6ed2e407455715055e41052f502483045022100a7ca8f097525f9044e64376dc0a0f5d4aeb8d15d66808ba97979a0475b06b66502200597c8ebcef63e047f9aeef1a8001d3560470cf896c12f6990eec4faec599b950121033add1f0e8e3c3136f7428dd4a4de1057380bd311f5b0856e2269170b4ffa65bf00000000' @@ -177,7 +178,7 @@ class TestMsgSigntxSegwitNative(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Testnet', [inp1], [out1, out2]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [inp1], [out1, out2]) assert hexlify(serialized_tx) == b'010000000001018a44999c07bba32df1cacdc50987944e68e3205b4429438fdde35c76024614090000000000ffffffff02404b4c000000000017a9147a55d61848e77ca266e79a39bfc85c580a6426c987a8386f0000000000160014d16b8c0680c61fc6ed2e407455715055e41052f502483045022100a7ca8f097525f9044e64376dc0a0f5d4aeb8d15d66808ba97979a0475b06b66502200597c8ebcef63e047f9aeef1a8001d3560470cf896c12f6990eec4faec599b950121033add1f0e8e3c3136f7428dd4a4de1057380bd311f5b0856e2269170b4ffa65bf00000000' @@ -238,7 +239,7 @@ class TestMsgSigntxSegwitNative(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Testnet', [inp1, inp2], [out1, out2, out3]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [inp1, inp2], [out1, out2, out3]) # 0e480a97c7a545c85e101a2f13c9af0e115d43734e1448f0cac3e55fe8e7399d assert hexlify(serialized_tx) == b'010000000001028a44999c07bba32df1cacdc50987944e68e3205b4429438fdde35c76024614090100000017160014d16b8c0680c61fc6ed2e407455715055e41052f5ffffffff7b010c5faeb41cc5c253121b6bf69bf1a7c5867cd7f2d91569fea0ecd311b8650100000000ffffffff03e0aebb0000000000160014a579388225827d9f2fe9014add644487808c695d00cdb7020000000017a91491233e24a9bf8dbb19c1187ad876a9380c12e787870d859b03000000001976a914a579388225827d9f2fe9014add644487808c695d88ac02483045022100ead79ee134f25bb585b48aee6284a4bb14e07f03cc130253e83450d095515e5202201e161e9402c8b26b666f2b67e5b668a404ef7e57858ae9a6a68c3837e65fdc69012103e7bfe10708f715e8538c92d46ca50db6f657bbc455b7494e6a0303ccdb868b7902483045022100b4099ec4c7b3123795b3c080a86f4b745f3784eb3f77de79bef1d8da319cbee5022039766865d448a4a3e435a95d0df3ff56ebc6532bf538988a7e8a679b40ec41b6012103e7bfe10708f715e8538c92d46ca50db6f657bbc455b7494e6a0303ccdb868b7900000000' @@ -246,7 +247,7 @@ class TestMsgSigntxSegwitNative(TrezorTest): def test_send_multisig_1(self): self.setup_mnemonic_allallall() self.client.set_tx_api(TxApiTestnet) - nodes = [self.client.get_public_node(parse_path("999'/1'/%d'" % index)) for index in range(1, 4)] + nodes = [btc.get_public_node(self.client, parse_path("999'/1'/%d'" % index)) for index in range(1, 4)] multisig = proto.MultisigRedeemScriptType( pubkeys=list(map(lambda n: proto.HDNodePathType(node=deserialize(n.xpub), address_n=[2, 0]), nodes)), signatures=[b'', b'', b''], @@ -279,7 +280,7 @@ class TestMsgSigntxSegwitNative(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures1, _) = self.client.sign_tx('Testnet', [inp1], [out1]) + (signatures1, _) = btc.sign_tx(self.client, 'Testnet', [inp1], [out1]) # store signature inp1.multisig.signatures[0] = signatures1[0] # sign with third key @@ -294,7 +295,7 @@ class TestMsgSigntxSegwitNative(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures2, serialized_tx) = self.client.sign_tx('Testnet', [inp1], [out1]) + (signatures2, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [inp1], [out1]) # f41cbedd8becee05a830f418d13aa665125464547db5c7a6cd28f21639fe1228 assert hexlify(serialized_tx) == b'01000000000101be0210025c5be68a473f6a38bf53b53bc88d5c46567616026dc056e72b92319c01000000232200201e8dda334f11171190b3da72e526d441491464769679a319a2f011da5ad312a1ffffffff01887d180000000000220020c5f4a0a4ea7c0392efe0a9670a73264cffa90b19107cd8a8e9750ff93c77fdfb0400483045022100a9b681f324ff4cf419ab06820d07248cc4e359c77334bf448ae7b5cdf3995ddf022039811f91f55b602368b4ba08a217b82bfd62d1a97dc635deb1457e7cfcc1550b0147304402201ad86a795c3d26881d696fa0a0619c24c4d505718132a82965cc2a609c9d8798022067cd490ce1366cde77e307ced5b13040bbc04991619ea6f49e06cece9a83268b01695221038e81669c085a5846e68e03875113ddb339ecbb7cb11376d4163bca5dc2e2a0c1210348c5c3be9f0e6cf1954ded1c0475beccc4d26aaa9d0cce2dd902538ff1018a112103931140ebe0fbbb7df0be04ed032a54e9589e30339ba7bbb8b0b71b15df1294da53ae00000000' @@ -302,7 +303,7 @@ class TestMsgSigntxSegwitNative(TrezorTest): def test_send_multisig_2(self): self.setup_mnemonic_allallall() self.client.set_tx_api(TxApiTestnet) - nodes = [self.client.get_public_node(parse_path("999'/1'/%d'" % index)) for index in range(1, 4)] + nodes = [btc.get_public_node(self.client, parse_path("999'/1'/%d'" % index)) for index in range(1, 4)] multisig = proto.MultisigRedeemScriptType( pubkeys=list(map(lambda n: proto.HDNodePathType(node=deserialize(n.xpub), address_n=[2, 1]), nodes)), signatures=[b'', b'', b''], @@ -335,7 +336,7 @@ class TestMsgSigntxSegwitNative(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures1, _) = self.client.sign_tx('Testnet', [inp1], [out1]) + (signatures1, _) = btc.sign_tx(self.client, 'Testnet', [inp1], [out1]) # store signature inp1.multisig.signatures[1] = signatures1[0] # sign with first key @@ -350,7 +351,7 @@ class TestMsgSigntxSegwitNative(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures2, serialized_tx) = self.client.sign_tx('Testnet', [inp1], [out1]) + (signatures2, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [inp1], [out1]) # c9348040bbc2024e12dcb4a0b4806b0398646b91acf314da028c3f03dd0179fc assert hexlify(serialized_tx) == b'010000000001012812fe3916f228cda6c7b57d5464541265a63ad118f430a805eeec8bddbe1cf40000000000ffffffff01a0791800000000002200201e8dda334f11171190b3da72e526d441491464769679a319a2f011da5ad312a10400483045022100cc97f21a7cabc543a9b4ac52424e8f7e420622903f2417a1c08a6af68058ec4a02200baca0b222fc825078d94e8e1b55f174c4828bed16697e4281cda2a0c799eecf01473044022009b8058dc30fa7a13310dd8f1a99c4341c4cd95f771c5a41c4381f956e2344c102205e829c560c0184fd4b4db8971f99711e2a87409afa4df0840b4f12a87b2c8afc0169522102740ec30d0af8591a0dd4a3e3b274e57f3f73bdc0638a9603f9ee6ade0475ba57210311aada919974e882abf0c67b5c0fba00000b26997312ca00345027d22359443021029382591271a79d4b12365fa27c67fad3753150d8eaa987e5a12dc5ba1bb2fa1653ae00000000' @@ -358,7 +359,7 @@ class TestMsgSigntxSegwitNative(TrezorTest): def test_send_multisig_3_change(self): self.setup_mnemonic_allallall() self.client.set_tx_api(TxApiTestnet) - nodes = [self.client.get_public_node(parse_path("999'/1'/%d'" % index)) for index in range(1, 4)] + nodes = [btc.get_public_node(self.client, parse_path("999'/1'/%d'" % index)) for index in range(1, 4)] multisig = proto.MultisigRedeemScriptType( pubkeys=list(map(lambda n: proto.HDNodePathType(node=deserialize(n.xpub), address_n=[2, 0]), nodes)), signatures=[b'', b'', b''], @@ -396,7 +397,7 @@ class TestMsgSigntxSegwitNative(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures1, _) = self.client.sign_tx('Testnet', [inp1], [out1]) + (signatures1, _) = btc.sign_tx(self.client, 'Testnet', [inp1], [out1]) # store signature inp1.multisig.signatures[0] = signatures1[0] # sign with third key @@ -411,7 +412,7 @@ class TestMsgSigntxSegwitNative(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures2, serialized_tx) = self.client.sign_tx('Testnet', [inp1], [out1]) + (signatures2, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [inp1], [out1]) # 31bc1c88ce6ae337a6b3057a16d5bad0b561ad1dfc047d0a7fbb8814668f91e5 assert hexlify(serialized_tx) == b'01000000000101fc7901dd033f8c02da14f3ac916b6498036b80b4a0b4dc124e02c2bb408034c90000000000ffffffff01b87518000000000017a914a8655acf68f785125561158b0f4db9b5d0044047870400473044022057b571986c07f8ccb231811334ad06ee6f87b722495def2e9511c1da46f3433202207b6e95bdd99e7fc7d319486437cb930d40a4af3cd753c4cb960b330badbf7f35014730440220517ecc6d0a2544276921d8fc2077aec4285ab83b1b21f5eb73cdb6187a0583e4022043fb5ab942f8981c04a54c66a57c4d291fad8514d4a8afea09f01f2db7a8f32901695221038e81669c085a5846e68e03875113ddb339ecbb7cb11376d4163bca5dc2e2a0c1210348c5c3be9f0e6cf1954ded1c0475beccc4d26aaa9d0cce2dd902538ff1018a112103931140ebe0fbbb7df0be04ed032a54e9589e30339ba7bbb8b0b71b15df1294da53ae00000000' @@ -419,7 +420,7 @@ class TestMsgSigntxSegwitNative(TrezorTest): def test_send_multisig_4_change(self): self.setup_mnemonic_allallall() self.client.set_tx_api(TxApiTestnet) - nodes = [self.client.get_public_node(parse_path("999'/1'/%d'" % index)) for index in range(1, 4)] + nodes = [btc.get_public_node(self.client, parse_path("999'/1'/%d'" % index)) for index in range(1, 4)] multisig = proto.MultisigRedeemScriptType( pubkeys=list(map(lambda n: proto.HDNodePathType(node=deserialize(n.xpub), address_n=[1, 1]), nodes)), signatures=[b'', b'', b''], @@ -457,7 +458,7 @@ class TestMsgSigntxSegwitNative(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures1, _) = self.client.sign_tx('Testnet', [inp1], [out1]) + (signatures1, _) = btc.sign_tx(self.client, 'Testnet', [inp1], [out1]) # store signature inp1.multisig.signatures[0] = signatures1[0] # sign with third key @@ -472,7 +473,7 @@ class TestMsgSigntxSegwitNative(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures2, serialized_tx) = self.client.sign_tx('Testnet', [inp1], [out1]) + (signatures2, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [inp1], [out1]) # c0bf56060a109624b4635222696d94a7d533cacea1b3f8245417a4348c045829 assert hexlify(serialized_tx) == b'01000000000101e5918f661488bb7f0a7d04fc1dad61b5d0bad5167a05b3a637e36ace881cbc3100000000232200205b9824093eaf5cdcf8247c00dc0b557a7720957828fcde8384ac11f80a91f403ffffffff01d071180000000000220020e77caf5fbef07b1e461475c02afd4aed877693263d69c81e14617304349b629a040047304402204832553b0da1009da496881e58e8e2e41010cfe5c0161623048093f1b1a817b7022020dad8bf887acf574af80bfe4b39cd24e95019fd5e6b8ae967471e21ddc67354014830450221009e5d60847e7275edcf4619ed8ee462c56a042eef75d17da2d44e6b13d78e50e50220665195492900ef87a5eb8a924fa0ac9afc4fc75ca704ff356dc3a213979970c80169522103f4040006e3561b3e76c6d4113225c84748ab9d55ffd23f9578ab4c18fb0c3b9721020975f2e6922897ff6b80da6412a8d6ebd67e33c9611d081656a53ef967964e5021026b0546f23a6ce6b756c2c30b4176ce6f1c3268744f7aca82668d5116c4f764e453ae00000000' diff --git a/trezorlib/tests/device_tests/test_msg_signtx_zcash.py b/trezorlib/tests/device_tests/test_msg_signtx_zcash.py index 1bb1b13e02..d0d218be77 100644 --- a/trezorlib/tests/device_tests/test_msg_signtx_zcash.py +++ b/trezorlib/tests/device_tests/test_msg_signtx_zcash.py @@ -22,6 +22,7 @@ from .common import TrezorTest from trezorlib import coins from trezorlib import messages as proto from trezorlib.tools import parse_path +from trezorlib import btc TxApiZcashTestnet = coins.tx_api['Zcash Testnet'] @@ -62,7 +63,7 @@ class TestMsgSigntxZcash(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Zcash Testnet', [inp1, ], [out1, ], version=3, overwintered=True) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Zcash Testnet', [inp1, ], [out1, ], version=3, overwintered=True) # Accepted by network: tx eda9b772c47f0c29310759960e0081c98707aa67a0a2738bcc71439fcf360675 assert hexlify(serialized_tx) == b'030000807082c40301dc754d63eff4698ee321476872519c53f14cfe58c9425c7ee464c206461ef5aa010000006a47304402207e45f303b4e42be824513855eb21653e1d2749cd94dcd0f0613d3f85d4efd1e20220699ffbdbcad889af7ede5ce9febf7a5ef8f5619b2464824529974c400cffaebc0121030e669acac1f280d1ddf441cd2ba5e97417bf2689e4bbec86df4f831bf9f7ffd0ffffffff016c9be111000000001976a9145b157a678a10021243307e4bb58f36375aa80e1088ac000000000000000000' diff --git a/trezorlib/tests/device_tests/test_msg_stellar_get_address.py b/trezorlib/tests/device_tests/test_msg_stellar_get_address.py index 16de53daf3..1a6385528c 100644 --- a/trezorlib/tests/device_tests/test_msg_stellar_get_address.py +++ b/trezorlib/tests/device_tests/test_msg_stellar_get_address.py @@ -22,6 +22,7 @@ from binascii import hexlify from trezorlib import stellar from trezorlib import messages as proto from trezorlib.tools import parse_path, CallException +from trezorlib import debuglink @pytest.mark.stellar @@ -30,30 +31,31 @@ class TestMsgStellarGetAddress(TrezorTest): def test_stellar_get_address(self): self.setup_mnemonic_nopin_nopassphrase() - address = self.client.stellar_get_address(parse_path(stellar.DEFAULT_BIP32_PATH)) + address = stellar.get_address(self.client, parse_path(stellar.DEFAULT_BIP32_PATH)) assert address == 'GAK5MSF74TJW6GLM7NLTL76YZJKM2S4CGP3UH4REJHPHZ4YBZW2GSBPW' def test_stellar_get_address_sep(self): # data from https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0005.md - self.client.load_device_by_mnemonic( + 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 = self.client.stellar_get_address(parse_path(stellar.DEFAULT_BIP32_PATH)) + address = stellar.get_address(self.client, parse_path(stellar.DEFAULT_BIP32_PATH)) assert address == 'GDRXE2BQUC3AZNPVFSCEZ76NJ3WWL25FYFK6RGZGIEKWE4SOOHSUJUJ6' - address = self.client.stellar_get_address(parse_path("m/44h/148h/1h"), show_display=True) + address = stellar.get_address(self.client, parse_path("m/44h/148h/1h"), show_display=True) assert address == 'GBAW5XGWORWVFE2XTJYDTLDHXTY2Q2MO73HYCGB3XMFMQ562Q2W2GJQX' def test_stellar_get_address_get_pubkey(self): self.setup_mnemonic_nopin_nopassphrase() - pubkey = self.client.stellar_get_public_key(parse_path(stellar.DEFAULT_BIP32_PATH)) + pubkey = stellar.get_public_key(self.client, parse_path(stellar.DEFAULT_BIP32_PATH)) # GAK5MSF74TJW6GLM7NLTL76YZJKM2S4CGP3UH4REJHPHZ4YBZW2GSBPW - address = self.client.stellar_get_address(parse_path(stellar.DEFAULT_BIP32_PATH)) + address = stellar.get_address(self.client, parse_path(stellar.DEFAULT_BIP32_PATH)) assert stellar.address_from_public_key(pubkey) == address @@ -61,7 +63,7 @@ class TestMsgStellarGetAddress(TrezorTest): self.setup_mnemonic_nopin_nopassphrase() with pytest.raises(CallException) as exc: - self.client.stellar_get_address(parse_path('m/0/1')) + stellar.get_address(self.client, parse_path('m/0/1')) if TREZOR_VERSION == 1: assert exc.value.args[0] == proto.FailureType.ProcessError diff --git a/trezorlib/tests/device_tests/test_msg_stellar_get_public_key.py b/trezorlib/tests/device_tests/test_msg_stellar_get_public_key.py index f1837d399c..0c28998472 100644 --- a/trezorlib/tests/device_tests/test_msg_stellar_get_public_key.py +++ b/trezorlib/tests/device_tests/test_msg_stellar_get_public_key.py @@ -31,7 +31,7 @@ class TestMsgStellarGetPublicKey(TrezorTest): self.setup_mnemonic_nopin_nopassphrase() # GAK5MSF74TJW6GLM7NLTL76YZJKM2S4CGP3UH4REJHPHZ4YBZW2GSBPW - response = self.client.stellar_get_public_key(parse_path(stellar.DEFAULT_BIP32_PATH), show_display=True) + response = stellar.get_public_key(self.client, parse_path(stellar.DEFAULT_BIP32_PATH), show_display=True) assert hexlify(response) == b'15d648bfe4d36f196cfb5735ffd8ca54cd4b8233f743f22449de7cf301cdb469' assert stellar.address_from_public_key(response) == 'GAK5MSF74TJW6GLM7NLTL76YZJKM2S4CGP3UH4REJHPHZ4YBZW2GSBPW' @@ -39,7 +39,7 @@ class TestMsgStellarGetPublicKey(TrezorTest): self.setup_mnemonic_nopin_nopassphrase() with pytest.raises(CallException) as exc: - self.client.stellar_get_public_key(parse_path('m/0/1')) + stellar.get_public_key(self.client, parse_path('m/0/1')) if TREZOR_VERSION == 1: assert exc.value.args[0] == messages.FailureType.ProcessError diff --git a/trezorlib/tests/device_tests/test_msg_stellar_sign_transaction.py b/trezorlib/tests/device_tests/test_msg_stellar_sign_transaction.py index e66de3160c..12bc2830c9 100644 --- a/trezorlib/tests/device_tests/test_msg_stellar_sign_transaction.py +++ b/trezorlib/tests/device_tests/test_msg_stellar_sign_transaction.py @@ -69,7 +69,7 @@ class TestMsgStellarSignTransaction(TrezorTest): op.bump_to = 0x7fffffffffffffff tx = self._create_msg() - response = self.client.stellar_sign_transaction(tx, [op], self.ADDRESS_N, self.NETWORK_PASSPHRASE) + response = stellar.sign_tx(self.client, tx, [op], self.ADDRESS_N, self.NETWORK_PASSPHRASE) assert b64encode(response.signature) == b'ZMIfHWhpyXdg40PzwOtkcXYnbZIO12Qy0WvkGqoYpb7jyWbG2HQCG7dgWhCoU5K81pvZTA2pMwiPjMwCXA//Bg==' def test_sign_tx_account_merge_op(self): @@ -80,7 +80,7 @@ class TestMsgStellarSignTransaction(TrezorTest): tx = self._create_msg() - response = self.client.stellar_sign_transaction(tx, [op], self.ADDRESS_N, self.NETWORK_PASSPHRASE) + response = stellar.sign_tx(self.client, tx, [op], self.ADDRESS_N, self.NETWORK_PASSPHRASE) assert hexlify(response.public_key) == b'15d648bfe4d36f196cfb5735ffd8ca54cd4b8233f743f22449de7cf301cdb469' assert b64encode(response.signature) == b'2R3Pj89U+dWrqy7otUrLLjtANjAg0lmBQL8E+89Po0Y94oqZkauP8j3WE7+/z7vF6XvAMLoOdqRYkUzr2oh7Dg==' @@ -95,7 +95,7 @@ class TestMsgStellarSignTransaction(TrezorTest): tx = self._create_msg() - response = self.client.stellar_sign_transaction(tx, [op], self.ADDRESS_N, self.NETWORK_PASSPHRASE) + response = stellar.sign_tx(self.client, tx, [op], self.ADDRESS_N, self.NETWORK_PASSPHRASE) assert b64encode(response.signature) == b'vrRYqkM4b54NrDR05UrW7ZHU7CNcidV0fn+bk9dqOW1bCbmX3YfeRbk2Tf1aea8nr9SD0sfBhtrDpdyxUenjBw==' @@ -109,7 +109,7 @@ class TestMsgStellarSignTransaction(TrezorTest): tx = self._create_msg() - response = self.client.stellar_sign_transaction(tx, [op], self.ADDRESS_N, self.NETWORK_PASSPHRASE) + response = stellar.sign_tx(self.client, tx, [op], self.ADDRESS_N, self.NETWORK_PASSPHRASE) assert b64encode(response.signature) == b'pDc6ghKCLNoYbt3h4eBw+533237m0BB0Jp/d/TxJCA83mF3o5Fr4l5vwAWBR62hdTWAP9MhVluY0cd5i54UwDg==' @@ -124,7 +124,7 @@ class TestMsgStellarSignTransaction(TrezorTest): op.asset = proto.StellarAssetType(1, 'X', 'GAUYJFQCYIHFQNS7CI6BFWD2DSSFKDIQZUQ3BLQODDKE4PSW7VVBKENC') tx = self._create_msg() - response = self.client.stellar_sign_transaction(tx, [op], self.ADDRESS_N, self.NETWORK_PASSPHRASE) + response = stellar.sign_tx(self.client, tx, [op], self.ADDRESS_N, self.NETWORK_PASSPHRASE) assert b64encode(response.signature) == b'ArZydOtXU2whoRuSjJLFIWPSIsq3AbsncJZ+THF24CRSriVWw5Fy/dHrDlUOu4fzU28I6osDMeI39aWezg5tDw==' @@ -139,7 +139,7 @@ class TestMsgStellarSignTransaction(TrezorTest): op.asset = proto.StellarAssetType(2, 'ABCDEFGHIJKL', 'GAUYJFQCYIHFQNS7CI6BFWD2DSSFKDIQZUQ3BLQODDKE4PSW7VVBKENC') tx = self._create_msg() - response = self.client.stellar_sign_transaction(tx, [op], self.ADDRESS_N, self.NETWORK_PASSPHRASE) + response = stellar.sign_tx(self.client, tx, [op], self.ADDRESS_N, self.NETWORK_PASSPHRASE) assert b64encode(response.signature) == b'QZIP4XKPfe4OpZtuJiyrMZBX9YBzvGpHGcngdgFfHn2kcdONreF384/pCF80xfEnGm8grKaoOnUEKxqcMKvxAA==' @@ -151,7 +151,7 @@ class TestMsgStellarSignTransaction(TrezorTest): op.inflation_destination_account = 'GAFXTC5OV5XQD66T7WGOB2HUVUC3ZVJDJMBDPTVQYV3G3K7TUHC6CLBR' tx = self._create_msg() - response = self.client.stellar_sign_transaction(tx, [op], self.ADDRESS_N, self.NETWORK_PASSPHRASE) + response = stellar.sign_tx(self.client, tx, [op], self.ADDRESS_N, self.NETWORK_PASSPHRASE) assert b64encode(response.signature) == b'dveWhKY8x7b0YqGHWH6Fo1SskxaHP11NXd2n6oHKGiv+T/LqB+CCzbmJA0tplZ+0HNPJbHD7L3Bsg/y462qLDA==' diff --git a/trezorlib/tests/device_tests/test_msg_verifymessage.py b/trezorlib/tests/device_tests/test_msg_verifymessage.py index 80ee934e51..9f887b97d8 100644 --- a/trezorlib/tests/device_tests/test_msg_verifymessage.py +++ b/trezorlib/tests/device_tests/test_msg_verifymessage.py @@ -17,13 +17,15 @@ from binascii import unhexlify from .common import TrezorTest +from trezorlib import btc class TestMsgVerifymessage(TrezorTest): def test_message_long(self): self.setup_mnemonic_nopin_nopassphrase() - ret = self.client.verify_message( + ret = btc.verify_message( + self.client, 'Bitcoin', '14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e', unhexlify('205ff795c29aef7538f8b3bdb2e8add0d0722ad630a140b6aefd504a5a895cbd867cbb00981afc50edd0398211e8d7c304bb8efa461181bc0afa67ea4a720a89ed'), @@ -33,46 +35,51 @@ class TestMsgVerifymessage(TrezorTest): def test_message_testnet(self): self.setup_mnemonic_nopin_nopassphrase() - ret = self.client.verify_message( + ret = btc.verify_message( + self.client, 'Testnet', 'mirio8q3gtv7fhdnmb3TpZ4EuafdzSs7zL', unhexlify('209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80'), 'This is an example of a signed message.' - ) + ) assert ret is True def test_message_verify(self): self.setup_mnemonic_nopin_nopassphrase() # uncompressed pubkey - OK - res = self.client.verify_message( + res = btc.verify_message( + self.client, 'Bitcoin', '1JwSSubhmg6iPtRjtyqhUYYH7bZg3Lfy1T', unhexlify('1ba77e01a9e17ba158b962cfef5f13dfed676ffc2b4bada24e58f784458b52b97421470d001d53d5880cf5e10e76f02be3e80bf21e18398cbd41e8c3b4af74c8c2'), 'This is an example of a signed message.' - ) + ) assert res is True # uncompressed pubkey - FAIL - wrong sig - res = self.client.verify_message( + res = btc.verify_message( + self.client, 'Bitcoin', '1JwSSubhmg6iPtRjtyqhUYYH7bZg3Lfy1T', unhexlify('1ba77e01a9e17ba158b962cfef5f13dfed676ffc2b4bada24e58f784458b52b97421470d001d53d5880cf5e10e76f02be3e80bf21e18398cbd41e8c3b4af74c800'), 'This is an example of a signed message.' - ) + ) assert res is False # uncompressed pubkey - FAIL - wrong msg - res = self.client.verify_message( + res = btc.verify_message( + self.client, 'Bitcoin', '1JwSSubhmg6iPtRjtyqhUYYH7bZg3Lfy1T', unhexlify('1ba77e01a9e17ba158b962cfef5f13dfed676ffc2b4bada24e58f784458b52b97421470d001d53d5880cf5e10e76f02be3e80bf21e18398cbd41e8c3b4af74c8c2'), 'This is an example of a signed message!' - ) + ) assert res is False # compressed pubkey - OK - res = self.client.verify_message( + res = btc.verify_message( + self.client, 'Bitcoin', '1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8', unhexlify('1f44e3e461f7ca9f57c472ce1a28214df1de1dadefb6551a32d1907b80c74d5a1fbfd6daaba12dd8cb06699ce3f6941fbe0f3957b5802d13076181046e741eaaaf'), @@ -80,16 +87,18 @@ class TestMsgVerifymessage(TrezorTest): assert res is True # compressed pubkey - FAIL - wrong sig - res = self.client.verify_message( + res = btc.verify_message( + self.client, 'Bitcoin', '1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8', unhexlify('1f44e3e461f7ca9f57c472ce1a28214df1de1dadefb6551a32d1907b80c74d5a1fbfd6daaba12dd8cb06699ce3f6941fbe0f3957b5802d13076181046e741eaa00'), 'This is an example of a signed message.' - ) + ) assert res is False # compressed pubkey - FAIL - wrong msg - res = self.client.verify_message( + res = btc.verify_message( + self.client, 'Bitcoin', '1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8', unhexlify('1f44e3e461f7ca9f57c472ce1a28214df1de1dadefb6551a32d1907b80c74d5a1fbfd6daaba12dd8cb06699ce3f6941fbe0f3957b5802d13076181046e741eaaaf'), @@ -97,51 +106,56 @@ class TestMsgVerifymessage(TrezorTest): assert res is False # trezor pubkey - OK - res = self.client.verify_message( + res = btc.verify_message( + self.client, 'Bitcoin', '14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e', unhexlify('209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80'), 'This is an example of a signed message.' - ) + ) assert res is True # trezor pubkey - FAIL - wrong sig - res = self.client.verify_message( + res = btc.verify_message( + self.client, 'Bitcoin', '14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e', unhexlify('209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be00'), 'This is an example of a signed message.' - ) + ) assert res is False # trezor pubkey - FAIL - wrong msg - res = self.client.verify_message( + res = btc.verify_message( + self.client, 'Bitcoin', '14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e', unhexlify('209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80'), 'This is an example of a signed message!' - ) + ) assert res is False def test_message_verify_bcash(self): self.setup_mnemonic_nopin_nopassphrase() - res = self.client.verify_message( + res = btc.verify_message( + self.client, 'Bcash', 'bitcoincash:qqj22md58nm09vpwsw82fyletkxkq36zxyxh322pru', unhexlify('209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80'), 'This is an example of a signed message.' - ) + ) assert res is True def test_verify_bitcoind(self): self.setup_mnemonic_nopin_nopassphrase() - res = self.client.verify_message( + res = btc.verify_message( + self.client, 'Bitcoin', '1KzXE97kV7DrpxCViCN3HbGbiKhzzPM7TQ', unhexlify('1cc694f0f23901dfe3603789142f36a3fc582d0d5c0ec7215cf2ccd641e4e37228504f3d4dc3eea28bbdbf5da27c49d4635c097004d9f228750ccd836a8e1460c0'), u'\u017elu\u0165ou\u010dk\xfd k\u016f\u0148 \xfap\u011bl \u010f\xe1belsk\xe9 \xf3dy' - ) + ) assert res is True @@ -151,14 +165,16 @@ class TestMsgVerifymessage(TrezorTest): 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' - res_nfkd = self.client.verify_message( + res_nfkd = btc.verify_message( + self.client, 'Bitcoin', '14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e', unhexlify('20d0ec02ed8da8df23e7fe9e680e7867cc290312fe1c970749d8306ddad1a1eda41c6a771b13d495dd225b13b0a9d0f915a984ee3d0703f92287bf8009fbb9f7d6'), words_nfkd ) - res_nfc = self.client.verify_message( + res_nfc = btc.verify_message( + self.client, 'Bitcoin', '14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e', unhexlify('20d0ec02ed8da8df23e7fe9e680e7867cc290312fe1c970749d8306ddad1a1eda41c6a771b13d495dd225b13b0a9d0f915a984ee3d0703f92287bf8009fbb9f7d6'), diff --git a/trezorlib/tests/device_tests/test_msg_verifymessage_segwit.py b/trezorlib/tests/device_tests/test_msg_verifymessage_segwit.py index ff0bdf78ef..142a132d9b 100644 --- a/trezorlib/tests/device_tests/test_msg_verifymessage_segwit.py +++ b/trezorlib/tests/device_tests/test_msg_verifymessage_segwit.py @@ -17,13 +17,15 @@ from binascii import unhexlify from .common import TrezorTest +from trezorlib import btc class TestMsgVerifymessageSegwit(TrezorTest): def test_message_long(self): self.setup_mnemonic_nopin_nopassphrase() - ret = self.client.verify_message( + ret = btc.verify_message( + self.client, 'Bitcoin', '3CwYaeWxhpXXiHue3ciQez1DLaTEAXcKa1', unhexlify('245ff795c29aef7538f8b3bdb2e8add0d0722ad630a140b6aefd504a5a895cbd867cbb00981afc50edd0398211e8d7c304bb8efa461181bc0afa67ea4a720a89ed'), @@ -33,42 +35,46 @@ class TestMsgVerifymessageSegwit(TrezorTest): def test_message_testnet(self): self.setup_mnemonic_nopin_nopassphrase() - ret = self.client.verify_message( + ret = btc.verify_message( + self.client, 'Testnet', '2N4VkePSzKH2sv5YBikLHGvzUYvfPxV6zS9', unhexlify('249e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80'), 'This is an example of a signed message.' - ) + ) assert ret is True def test_message_verify(self): self.setup_mnemonic_nopin_nopassphrase() # trezor pubkey - OK - res = self.client.verify_message( + res = btc.verify_message( + self.client, 'Bitcoin', '3CwYaeWxhpXXiHue3ciQez1DLaTEAXcKa1', unhexlify('249e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80'), 'This is an example of a signed message.' - ) + ) assert res is True # trezor pubkey - FAIL - wrong sig - res = self.client.verify_message( + res = btc.verify_message( + self.client, 'Bitcoin', '3CwYaeWxhpXXiHue3ciQez1DLaTEAXcKa1', unhexlify('249e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be00'), 'This is an example of a signed message.' - ) + ) assert res is False # trezor pubkey - FAIL - wrong msg - res = self.client.verify_message( + res = btc.verify_message( + self.client, 'Bitcoin', '3CwYaeWxhpXXiHue3ciQez1DLaTEAXcKa1', unhexlify('249e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80'), 'This is an example of a signed message!' - ) + ) assert res is False def test_verify_utf(self): @@ -77,14 +83,16 @@ class TestMsgVerifymessageSegwit(TrezorTest): 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' - res_nfkd = self.client.verify_message( + res_nfkd = btc.verify_message( + self.client, 'Bitcoin', '3CwYaeWxhpXXiHue3ciQez1DLaTEAXcKa1', unhexlify('24d0ec02ed8da8df23e7fe9e680e7867cc290312fe1c970749d8306ddad1a1eda41c6a771b13d495dd225b13b0a9d0f915a984ee3d0703f92287bf8009fbb9f7d6'), words_nfkd ) - res_nfc = self.client.verify_message( + res_nfc = btc.verify_message( + self.client, 'Bitcoin', '3CwYaeWxhpXXiHue3ciQez1DLaTEAXcKa1', unhexlify('24d0ec02ed8da8df23e7fe9e680e7867cc290312fe1c970749d8306ddad1a1eda41c6a771b13d495dd225b13b0a9d0f915a984ee3d0703f92287bf8009fbb9f7d6'), diff --git a/trezorlib/tests/device_tests/test_msg_verifymessage_segwit_native.py b/trezorlib/tests/device_tests/test_msg_verifymessage_segwit_native.py index 750019339f..e091e0a5c8 100644 --- a/trezorlib/tests/device_tests/test_msg_verifymessage_segwit_native.py +++ b/trezorlib/tests/device_tests/test_msg_verifymessage_segwit_native.py @@ -17,13 +17,15 @@ from binascii import unhexlify from .common import TrezorTest +from trezorlib import btc class TestMsgVerifymessageSegwitNative(TrezorTest): def test_message_long(self): self.setup_mnemonic_nopin_nopassphrase() - ret = self.client.verify_message( + ret = btc.verify_message( + self.client, 'Bitcoin', 'bc1qyjjkmdpu7metqt5r36jf872a34syws33s82q2j', unhexlify('285ff795c29aef7538f8b3bdb2e8add0d0722ad630a140b6aefd504a5a895cbd867cbb00981afc50edd0398211e8d7c304bb8efa461181bc0afa67ea4a720a89ed'), @@ -33,42 +35,46 @@ class TestMsgVerifymessageSegwitNative(TrezorTest): def test_message_testnet(self): self.setup_mnemonic_nopin_nopassphrase() - ret = self.client.verify_message( + ret = btc.verify_message( + self.client, 'Testnet', 'tb1qyjjkmdpu7metqt5r36jf872a34syws336p3n3p', unhexlify('289e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80'), 'This is an example of a signed message.' - ) + ) assert ret is True def test_message_verify(self): self.setup_mnemonic_nopin_nopassphrase() # trezor pubkey - OK - res = self.client.verify_message( + res = btc.verify_message( + self.client, 'Bitcoin', 'bc1qyjjkmdpu7metqt5r36jf872a34syws33s82q2j', unhexlify('289e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80'), 'This is an example of a signed message.' - ) + ) assert res is True # trezor pubkey - FAIL - wrong sig - res = self.client.verify_message( + res = btc.verify_message( + self.client, 'Bitcoin', 'bc1qyjjkmdpu7metqt5r36jf872a34syws33s82q2j', unhexlify('289e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be00'), 'This is an example of a signed message.' - ) + ) assert res is False # trezor pubkey - FAIL - wrong msg - res = self.client.verify_message( + res = btc.verify_message( + self.client, 'Bitcoin', 'bc1qyjjkmdpu7metqt5r36jf872a34syws33s82q2j', unhexlify('289e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80'), 'This is an example of a signed message!' - ) + ) assert res is False def test_verify_utf(self): @@ -77,14 +83,16 @@ class TestMsgVerifymessageSegwitNative(TrezorTest): 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' - res_nfkd = self.client.verify_message( + res_nfkd = btc.verify_message( + self.client, 'Bitcoin', 'bc1qyjjkmdpu7metqt5r36jf872a34syws33s82q2j', unhexlify('28d0ec02ed8da8df23e7fe9e680e7867cc290312fe1c970749d8306ddad1a1eda41c6a771b13d495dd225b13b0a9d0f915a984ee3d0703f92287bf8009fbb9f7d6'), words_nfkd ) - res_nfc = self.client.verify_message( + res_nfc = btc.verify_message( + self.client, 'Bitcoin', 'bc1qyjjkmdpu7metqt5r36jf872a34syws33s82q2j', unhexlify('28d0ec02ed8da8df23e7fe9e680e7867cc290312fe1c970749d8306ddad1a1eda41c6a771b13d495dd225b13b0a9d0f915a984ee3d0703f92287bf8009fbb9f7d6'), diff --git a/trezorlib/tests/device_tests/test_msg_wipedevice.py b/trezorlib/tests/device_tests/test_msg_wipedevice.py index 2b428dd919..ef727e7790 100644 --- a/trezorlib/tests/device_tests/test_msg_wipedevice.py +++ b/trezorlib/tests/device_tests/test_msg_wipedevice.py @@ -17,6 +17,7 @@ from .common import TrezorTest from trezorlib import messages as proto +from trezorlib import device class TestMsgWipedevice(TrezorTest): @@ -30,7 +31,7 @@ class TestMsgWipedevice(TrezorTest): assert features.passphrase_protection is True device_id = features.device_id - self.client.wipe_device() + device.wipe(self.client) features = self.client.call_raw(proto.Initialize()) assert features.initialized is False diff --git a/trezorlib/tests/device_tests/test_multisig.py b/trezorlib/tests/device_tests/test_multisig.py index 608d20925a..b9b2e43951 100644 --- a/trezorlib/tests/device_tests/test_multisig.py +++ b/trezorlib/tests/device_tests/test_multisig.py @@ -21,6 +21,7 @@ from .common import TrezorTest from ..support import ckd_public as bip32 from trezorlib import messages as proto from trezorlib.tools import CallException +from trezorlib import btc TXHASH_c6091a = unhexlify('c6091adf4c0c23982a35899a6e58ae11e703eacd7954f588ed4b9cdefc4dba52') @@ -101,7 +102,7 @@ class TestMultisig(TrezorTest): ]) # Now we have first signature - (signatures1, _) = self.client.sign_tx('Bitcoin', [inp1, ], [out1, ]) + (signatures1, _) = btc.sign_tx(self.client, 'Bitcoin', [inp1, ], [out1, ]) assert hexlify(signatures1[0]) == b'3045022100985cc1ba316d140eb4b2d4028d8cd1c451f87bff8ff679858732e516ad04cd3402207af6edda99972af0baa7702a3b7448517c8242e7bca669f6861771cdd16ee058' @@ -142,7 +143,7 @@ class TestMultisig(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures2, serialized_tx) = self.client.sign_tx('Bitcoin', [inp3, ], [out1, ]) + (signatures2, serialized_tx) = btc.sign_tx(self.client, 'Bitcoin', [inp3, ], [out1, ]) assert hexlify(signatures2[0]) == b'3045022100f5428fe0531b3095675b40d87cab607ee036fac823b22e8dcec35b65aff6e52b022032129b4577ff923d321a1c70db5a6cec5bcc142cb2c51901af8b989cced23e0d' @@ -197,7 +198,7 @@ class TestMultisig(TrezorTest): ) with self.client: - (sig, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, ], [out1, ]) + (sig, serialized_tx) = btc.sign_tx(self.client, 'Bitcoin', [inp1, ], [out1, ]) signatures[x] = sig[0] # Accepted as tx id dd320786d1f58c095be0509dc56b277b6de8f2fb5517f519c6e6708414e3300b @@ -248,7 +249,7 @@ class TestMultisig(TrezorTest): ) with pytest.raises(CallException) as exc: - self.client.sign_tx('Bitcoin', [inp1, ], [out1, ]) + btc.sign_tx(self.client, 'Bitcoin', [inp1, ], [out1, ]) assert exc.value.args[0] == proto.FailureType.DataError assert exc.value.args[1].endswith('Pubkey not found in multisig script') diff --git a/trezorlib/tests/device_tests/test_multisig_change.py b/trezorlib/tests/device_tests/test_multisig_change.py index f41f121659..5a6c205c26 100644 --- a/trezorlib/tests/device_tests/test_multisig_change.py +++ b/trezorlib/tests/device_tests/test_multisig_change.py @@ -21,6 +21,7 @@ from ..support import ckd_public as bip32 from trezorlib import messages as proto from trezorlib.tools import parse_path from trezorlib.tx_api import TxApiInsight +from trezorlib import btc TxApiTestnet = TxApiInsight("insight_testnet") @@ -181,7 +182,7 @@ class TestMultisigChange(TrezorTest): with self.client: self.client.set_expected_responses(self._responses(self.inp1, self.inp2)) - (_, serialized_tx) = self.client.sign_tx('Testnet', [self.inp1, self.inp2, ], [out1, out2, ]) + (_, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [self.inp1, self.inp2, ], [out1, out2, ]) assert hexlify(serialized_tx) == b'0100000002e53cf4e3fcd37f8c439286ce636476e1faeebf86bbb2f228a6b78d1b47c8c61601000000b400473044022064f13801744a6c21b694f62cdb5d834e852f13ecf85ed4d0a56ba279571c24e3022010fab4cb05bdd7b24c8376dda4f62a418548eea6eb483e58675fa06e0d5c642c014c69522103dc07026aacb5918dac4e09f9da8290d0ae22161699636c22cace78082116a7792103e70db185fad69c2971f0107a42930e5d82a9ed3a11b922a96fdfc4124b63e54c2103f3fe007a1e34ac76c1a2528e9149f90f9f93739929797afab6a8e18d682fa71053aeffffffff185315ae8050e18efa70d6ca96378a1194f57e2b102511f68b3a1414ee340cd800000000b4004730440220727b2522268f913acd213c507d7801b146e5b6cef666ad44b769c26d6c762e4d022021c0c2e9e8298dee2a490d956f7ab1b2d3160c1e37a50cc6d19a5e62eb484fc9014c6952210297ad8a5df42f9e362ef37d9a4ddced89d8f7a143690649aa0d0ff049c7daca842103ed1fd93989595d7ad4b488efd05a22c0239482c9a20923f2f214a38e54f6c41a2103f91460d79e4e463d7d90cb75254bcd62b515a99a950574c721efdc5f711dff3553aeffffffff02005a6202000000001976a9149b139230e4fe91c05a37ec334dc8378f3dbe377088ac00639f02000000001976a914b0d05a10926a7925508febdbab9a5bd4cda8c8f688ac00000000' @@ -203,7 +204,7 @@ class TestMultisigChange(TrezorTest): with self.client: self.client.set_expected_responses(self._responses(self.inp1, self.inp2, change=2)) - (_, serialized_tx) = self.client.sign_tx('Testnet', [self.inp1, self.inp2, ], [out1, out2, ]) + (_, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [self.inp1, self.inp2, ], [out1, out2, ]) assert hexlify(serialized_tx) == b'0100000002e53cf4e3fcd37f8c439286ce636476e1faeebf86bbb2f228a6b78d1b47c8c61601000000b400473044022064f13801744a6c21b694f62cdb5d834e852f13ecf85ed4d0a56ba279571c24e3022010fab4cb05bdd7b24c8376dda4f62a418548eea6eb483e58675fa06e0d5c642c014c69522103dc07026aacb5918dac4e09f9da8290d0ae22161699636c22cace78082116a7792103e70db185fad69c2971f0107a42930e5d82a9ed3a11b922a96fdfc4124b63e54c2103f3fe007a1e34ac76c1a2528e9149f90f9f93739929797afab6a8e18d682fa71053aeffffffff185315ae8050e18efa70d6ca96378a1194f57e2b102511f68b3a1414ee340cd800000000b4004730440220727b2522268f913acd213c507d7801b146e5b6cef666ad44b769c26d6c762e4d022021c0c2e9e8298dee2a490d956f7ab1b2d3160c1e37a50cc6d19a5e62eb484fc9014c6952210297ad8a5df42f9e362ef37d9a4ddced89d8f7a143690649aa0d0ff049c7daca842103ed1fd93989595d7ad4b488efd05a22c0239482c9a20923f2f214a38e54f6c41a2103f91460d79e4e463d7d90cb75254bcd62b515a99a950574c721efdc5f711dff3553aeffffffff02005a6202000000001976a9149b139230e4fe91c05a37ec334dc8378f3dbe377088ac00639f02000000001976a914b0d05a10926a7925508febdbab9a5bd4cda8c8f688ac00000000' @@ -225,7 +226,7 @@ class TestMultisigChange(TrezorTest): with self.client: self.client.set_expected_responses(self._responses(self.inp1, self.inp2, change=1)) - (_, serialized_tx) = self.client.sign_tx('Testnet', [self.inp1, self.inp2, ], [out1, out2, ]) + (_, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [self.inp1, self.inp2, ], [out1, out2, ]) assert hexlify(serialized_tx) == b'0100000002e53cf4e3fcd37f8c439286ce636476e1faeebf86bbb2f228a6b78d1b47c8c61601000000b400473044022064f13801744a6c21b694f62cdb5d834e852f13ecf85ed4d0a56ba279571c24e3022010fab4cb05bdd7b24c8376dda4f62a418548eea6eb483e58675fa06e0d5c642c014c69522103dc07026aacb5918dac4e09f9da8290d0ae22161699636c22cace78082116a7792103e70db185fad69c2971f0107a42930e5d82a9ed3a11b922a96fdfc4124b63e54c2103f3fe007a1e34ac76c1a2528e9149f90f9f93739929797afab6a8e18d682fa71053aeffffffff185315ae8050e18efa70d6ca96378a1194f57e2b102511f68b3a1414ee340cd800000000b4004730440220727b2522268f913acd213c507d7801b146e5b6cef666ad44b769c26d6c762e4d022021c0c2e9e8298dee2a490d956f7ab1b2d3160c1e37a50cc6d19a5e62eb484fc9014c6952210297ad8a5df42f9e362ef37d9a4ddced89d8f7a143690649aa0d0ff049c7daca842103ed1fd93989595d7ad4b488efd05a22c0239482c9a20923f2f214a38e54f6c41a2103f91460d79e4e463d7d90cb75254bcd62b515a99a950574c721efdc5f711dff3553aeffffffff02005a6202000000001976a9149b139230e4fe91c05a37ec334dc8378f3dbe377088ac00639f02000000001976a914b0d05a10926a7925508febdbab9a5bd4cda8c8f688ac00000000' @@ -247,7 +248,7 @@ class TestMultisigChange(TrezorTest): with self.client: self.client.set_expected_responses(self._responses(self.inp1, self.inp2)) - (_, serialized_tx) = self.client.sign_tx('Testnet', [self.inp1, self.inp2, ], [out1, out2, ]) + (_, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [self.inp1, self.inp2, ], [out1, out2, ]) assert hexlify(serialized_tx) == b'0100000002e53cf4e3fcd37f8c439286ce636476e1faeebf86bbb2f228a6b78d1b47c8c61601000000b400473044022059394e0dfcb2d2f4a6108703f801545ca5a820c0ac6a1859d0a3854813de55fa02207b6a57d70b82932ff58163336c461653a2dc82c78ed8157159e5178ac7325390014c69522103dc07026aacb5918dac4e09f9da8290d0ae22161699636c22cace78082116a7792103e70db185fad69c2971f0107a42930e5d82a9ed3a11b922a96fdfc4124b63e54c2103f3fe007a1e34ac76c1a2528e9149f90f9f93739929797afab6a8e18d682fa71053aeffffffff185315ae8050e18efa70d6ca96378a1194f57e2b102511f68b3a1414ee340cd800000000b40047304402205a911685f5b974b2fc4a19d5ce056218773a4d20b5eaae2c2f9594929308182002201e03449f5a8813ec19f408bf1b6f4f334886d6fcf9920e300fd7678ef0724f81014c6952210297ad8a5df42f9e362ef37d9a4ddced89d8f7a143690649aa0d0ff049c7daca842103ed1fd93989595d7ad4b488efd05a22c0239482c9a20923f2f214a38e54f6c41a2103f91460d79e4e463d7d90cb75254bcd62b515a99a950574c721efdc5f711dff3553aeffffffff02005a62020000000017a91466528dd543f94d162c8111d2ec248d25ba9b90948700639f020000000017a914f1fc92c0aed1712911c70a2e09ac15ff0922652f8700000000' @@ -280,7 +281,7 @@ class TestMultisigChange(TrezorTest): with self.client: self.client.set_expected_responses(self._responses(self.inp1, self.inp2, change=1)) - (_, serialized_tx) = self.client.sign_tx('Testnet', [self.inp1, self.inp2, ], [out1, out2, ]) + (_, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [self.inp1, self.inp2, ], [out1, out2, ]) assert hexlify(serialized_tx) == b'0100000002e53cf4e3fcd37f8c439286ce636476e1faeebf86bbb2f228a6b78d1b47c8c61601000000b400473044022059394e0dfcb2d2f4a6108703f801545ca5a820c0ac6a1859d0a3854813de55fa02207b6a57d70b82932ff58163336c461653a2dc82c78ed8157159e5178ac7325390014c69522103dc07026aacb5918dac4e09f9da8290d0ae22161699636c22cace78082116a7792103e70db185fad69c2971f0107a42930e5d82a9ed3a11b922a96fdfc4124b63e54c2103f3fe007a1e34ac76c1a2528e9149f90f9f93739929797afab6a8e18d682fa71053aeffffffff185315ae8050e18efa70d6ca96378a1194f57e2b102511f68b3a1414ee340cd800000000b40047304402205a911685f5b974b2fc4a19d5ce056218773a4d20b5eaae2c2f9594929308182002201e03449f5a8813ec19f408bf1b6f4f334886d6fcf9920e300fd7678ef0724f81014c6952210297ad8a5df42f9e362ef37d9a4ddced89d8f7a143690649aa0d0ff049c7daca842103ed1fd93989595d7ad4b488efd05a22c0239482c9a20923f2f214a38e54f6c41a2103f91460d79e4e463d7d90cb75254bcd62b515a99a950574c721efdc5f711dff3553aeffffffff02005a62020000000017a91466528dd543f94d162c8111d2ec248d25ba9b90948700639f020000000017a914f1fc92c0aed1712911c70a2e09ac15ff0922652f8700000000' @@ -313,7 +314,7 @@ class TestMultisigChange(TrezorTest): with self.client: self.client.set_expected_responses(self._responses(self.inp1, self.inp2, change=2)) - (_, serialized_tx) = self.client.sign_tx('Testnet', [self.inp1, self.inp2, ], [out1, out2, ]) + (_, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [self.inp1, self.inp2, ], [out1, out2, ]) assert hexlify(serialized_tx) == b'0100000002e53cf4e3fcd37f8c439286ce636476e1faeebf86bbb2f228a6b78d1b47c8c61601000000b400473044022059394e0dfcb2d2f4a6108703f801545ca5a820c0ac6a1859d0a3854813de55fa02207b6a57d70b82932ff58163336c461653a2dc82c78ed8157159e5178ac7325390014c69522103dc07026aacb5918dac4e09f9da8290d0ae22161699636c22cace78082116a7792103e70db185fad69c2971f0107a42930e5d82a9ed3a11b922a96fdfc4124b63e54c2103f3fe007a1e34ac76c1a2528e9149f90f9f93739929797afab6a8e18d682fa71053aeffffffff185315ae8050e18efa70d6ca96378a1194f57e2b102511f68b3a1414ee340cd800000000b40047304402205a911685f5b974b2fc4a19d5ce056218773a4d20b5eaae2c2f9594929308182002201e03449f5a8813ec19f408bf1b6f4f334886d6fcf9920e300fd7678ef0724f81014c6952210297ad8a5df42f9e362ef37d9a4ddced89d8f7a143690649aa0d0ff049c7daca842103ed1fd93989595d7ad4b488efd05a22c0239482c9a20923f2f214a38e54f6c41a2103f91460d79e4e463d7d90cb75254bcd62b515a99a950574c721efdc5f711dff3553aeffffffff02005a62020000000017a91466528dd543f94d162c8111d2ec248d25ba9b90948700639f020000000017a914f1fc92c0aed1712911c70a2e09ac15ff0922652f8700000000' @@ -346,7 +347,7 @@ class TestMultisigChange(TrezorTest): with self.client: self.client.set_expected_responses(self._responses(self.inp1, self.inp2)) - (_, serialized_tx) = self.client.sign_tx('Testnet', [self.inp1, self.inp2, ], [out1, out2, ]) + (_, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [self.inp1, self.inp2, ], [out1, out2, ]) assert hexlify(serialized_tx) == b'0100000002e53cf4e3fcd37f8c439286ce636476e1faeebf86bbb2f228a6b78d1b47c8c61601000000b40047304402207f9992cc0230527faf54ec6bd233307db82bc8fac039dcee418bc6feb4e96a3a02206bb4cb157ad27c123277328a877572563a45d70b844d9ab07cc42238112f8c2a014c69522103dc07026aacb5918dac4e09f9da8290d0ae22161699636c22cace78082116a7792103e70db185fad69c2971f0107a42930e5d82a9ed3a11b922a96fdfc4124b63e54c2103f3fe007a1e34ac76c1a2528e9149f90f9f93739929797afab6a8e18d682fa71053aeffffffff185315ae8050e18efa70d6ca96378a1194f57e2b102511f68b3a1414ee340cd800000000b400473044022078a41bfa87d72d6ba810d84bf568b5a29acf8b851ba6c3a8dbff079b34a7feb0022037b770c776db0b6c883c38a684a121b90a59ed1958774cbf64de70e53e29639f014c6952210297ad8a5df42f9e362ef37d9a4ddced89d8f7a143690649aa0d0ff049c7daca842103ed1fd93989595d7ad4b488efd05a22c0239482c9a20923f2f214a38e54f6c41a2103f91460d79e4e463d7d90cb75254bcd62b515a99a950574c721efdc5f711dff3553aeffffffff02005a62020000000017a91466528dd543f94d162c8111d2ec248d25ba9b90948700639f020000000017a914e6a3e2fbadb7f559f8d20c46aceae78c96fcf1d18700000000' @@ -379,6 +380,6 @@ class TestMultisigChange(TrezorTest): with self.client: self.client.set_expected_responses(self._responses(self.inp1, self.inp3)) - (_, serialized_tx) = self.client.sign_tx('Testnet', [self.inp1, self.inp3, ], [out1, out2, ]) + (_, serialized_tx) = btc.sign_tx(self.client, 'Testnet', [self.inp1, self.inp3, ], [out1, out2, ]) assert hexlify(serialized_tx) == b'0100000002e53cf4e3fcd37f8c439286ce636476e1faeebf86bbb2f228a6b78d1b47c8c61601000000b500483045022100d907b9339951c96ef4515ef7aff8b3c28c4c8c5875d7421aa1de9f3a94e3508302205cdc311a6c91dfbb74f1a9a940a994a65dbfb0cf6dedcaaaeee839e0b8fd016d014c69522103dc07026aacb5918dac4e09f9da8290d0ae22161699636c22cace78082116a7792103e70db185fad69c2971f0107a42930e5d82a9ed3a11b922a96fdfc4124b63e54c2103f3fe007a1e34ac76c1a2528e9149f90f9f93739929797afab6a8e18d682fa71053aeffffffff39f756d82082b580b0d69ae8798ff10a981820ccfe1ab149a708a37bc26d94b000000000b500483045022100fdad4a47d15f47cc364fe0cbed11b1ced1f9ef210bc1bd413ec4384f630c63720220752e4f09ea4e5e6623f5ebe89b3983ec6e5702f63f9bce696f10b2d594d23532014c6952210297ad8a5df42f9e362ef37d9a4ddced89d8f7a143690649aa0d0ff049c7daca842103b6321a1194e5cc47b6b7edc3f67a096e6f71ccb72440f84f390b6e98df0ea8ec2103f91460d79e4e463d7d90cb75254bcd62b515a99a950574c721efdc5f711dff3553aeffffffff02005a62020000000017a91466528dd543f94d162c8111d2ec248d25ba9b90948740d2df030000000017a914f1fc92c0aed1712911c70a2e09ac15ff0922652f8700000000' diff --git a/trezorlib/tests/device_tests/test_op_return.py b/trezorlib/tests/device_tests/test_op_return.py index db13733946..5247a027cc 100644 --- a/trezorlib/tests/device_tests/test_op_return.py +++ b/trezorlib/tests/device_tests/test_op_return.py @@ -21,6 +21,7 @@ from .common import TrezorTest from .conftest import TREZOR_VERSION from trezorlib import messages as proto from trezorlib.tools import CallException +from trezorlib import btc TXHASH_d5f65e = unhexlify('d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882') @@ -71,7 +72,7 @@ class TestOpReturn(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - (signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, ], [out1, out2]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Bitcoin', [inp1, ], [out1, out2]) assert hexlify(serialized_tx) == b'010000000182488650ef25a58fef6788bd71b8212038d7f2bbe4750bc7bcb44701e85ef6d5000000006a4730440220187b7b9c340a32fc8445418ad11fb3827d2e8bac7d730e1c9ad800353e7ba62f02206c0c5820ba8882c82923a39aee8d36d6d32e13daed73f7a3d6199de5f8e7ddfd0121023230848585885f63803a0a8aecdd6538792d5c539215c91698e315bf0253b43dffffffff0260cc0500000000001976a914de9b2a8da088824e8fe51debea566617d851537888ac00000000000000001c6a1a74657374206f6620746865206f705f72657475726e206461746100000000' @@ -106,7 +107,7 @@ class TestOpReturn(TrezorTest): ]) with pytest.raises(CallException) as exc: - self.client.sign_tx('Bitcoin', [inp1], [out1]) + btc.sign_tx(self.client, 'Bitcoin', [inp1], [out1]) if TREZOR_VERSION == 1: assert exc.value.args[0] == proto.FailureType.ProcessError diff --git a/trezorlib/tests/device_tests/test_protection_levels.py b/trezorlib/tests/device_tests/test_protection_levels.py index b6ff5a4d5e..1ec34f81a1 100644 --- a/trezorlib/tests/device_tests/test_protection_levels.py +++ b/trezorlib/tests/device_tests/test_protection_levels.py @@ -19,6 +19,10 @@ import pytest from .common import TrezorTest from trezorlib import messages as proto +from trezorlib import btc +from trezorlib import debuglink +from trezorlib import device +from trezorlib import misc TXHASH_d5f65e = unhexlify('d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882') @@ -42,7 +46,7 @@ class TestProtectionLevels(TrezorTest): proto.Success(), proto.Features() ]) # TrezorClient reinitializes device - self.client.apply_settings(label='nazdar') + device.apply_settings(self.client, label='nazdar') def test_change_pin(self): with self.client: @@ -55,7 +59,7 @@ class TestProtectionLevels(TrezorTest): proto.Success(), proto.Features() ]) - self.client.change_pin() + device.change_pin(self.client) def test_ping(self): with self.client: @@ -75,7 +79,7 @@ class TestProtectionLevels(TrezorTest): proto.ButtonRequest(), proto.Entropy() ]) - self.client.get_entropy(10) + misc.get_entropy(self.client, 10) def test_get_public_key(self): with self.client: @@ -85,7 +89,7 @@ class TestProtectionLevels(TrezorTest): proto.PassphraseRequest(), proto.PublicKey() ]) - self.client.get_public_node([]) + btc.get_public_node(self.client, []) def test_get_address(self): with self.client: @@ -95,7 +99,7 @@ class TestProtectionLevels(TrezorTest): proto.PassphraseRequest(), proto.Address() ]) - self.client.get_address('Bitcoin', []) + btc.get_address(self.client, 'Bitcoin', []) def test_wipe_device(self): with self.client: @@ -105,27 +109,27 @@ class TestProtectionLevels(TrezorTest): proto.Success(), proto.Features() ]) - self.client.wipe_device() + device.wipe(self.client) def test_load_device(self): with self.client: self.client.set_expected_responses([proto.ButtonRequest(), proto.Success(), proto.Features()]) - self.client.load_device_by_mnemonic('this is mnemonic', '1234', True, 'label', 'english', skip_checksum=True) + 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): - self.client.load_device_by_mnemonic('this is mnemonic', '1234', True, 'label', 'english', skip_checksum=True) + debuglink.load_device_by_mnemonic(self.client, 'this is mnemonic', '1234', True, 'label', 'english', skip_checksum=True) def test_reset_device(self): with self.client: self.client.set_expected_responses([proto.EntropyRequest()] + [proto.ButtonRequest()] * 24 + [proto.Success(), proto.Features()]) - self.client.reset_device(False, 128, True, False, 'label', 'english') + device.reset(self.client, False, 128, True, False, 'label', 'english') # This must fail, because device is already initialized with pytest.raises(Exception): - self.client.reset_device(False, 128, True, False, 'label', 'english') + device.reset(self.client, False, 128, True, False, 'label', 'english') def test_recovery_device(self): with self.client: @@ -134,11 +138,11 @@ class TestProtectionLevels(TrezorTest): [proto.ButtonRequest()] + [proto.WordRequest()] * 24 + [proto.Success(), proto.Features()]) - self.client.recovery_device(12, False, False, 'label', 'english') + device.recover(self.client, 12, False, False, 'label', 'english') # This must fail, because device is already initialized with pytest.raises(Exception): - self.client.recovery_device(12, False, False, 'label', 'english') + device.recover(self.client, 12, False, False, 'label', 'english') def test_sign_message(self): with self.client: @@ -149,13 +153,14 @@ class TestProtectionLevels(TrezorTest): proto.PassphraseRequest(), proto.MessageSignature() ]) - self.client.sign_message('Bitcoin', [], 'testing message') + btc.sign_message(self.client, 'Bitcoin', [], 'testing message') def test_verify_message(self): with self.client: self.setup_mnemonic_pin_passphrase() self.client.set_expected_responses([proto.ButtonRequest(), proto.ButtonRequest(), proto.Success()]) - self.client.verify_message( + btc.verify_message( + self.client, 'Bitcoin', '14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e', unhexlify('209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80'), @@ -194,7 +199,7 @@ class TestProtectionLevels(TrezorTest): proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXFINISHED), ]) - self.client.sign_tx('Bitcoin', [inp1, ], [out1, ]) + btc.sign_tx(self.client, 'Bitcoin', [inp1, ], [out1, ]) # def test_firmware_erase(self): # pass diff --git a/trezorlib/tests/device_tests/test_zerosig.py b/trezorlib/tests/device_tests/test_zerosig.py index 3e18727bce..32456862db 100644 --- a/trezorlib/tests/device_tests/test_zerosig.py +++ b/trezorlib/tests/device_tests/test_zerosig.py @@ -18,6 +18,7 @@ from binascii import unhexlify from .common import TrezorTest from trezorlib import messages as proto +from trezorlib import btc TXHASH_d5f65e = unhexlify('d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882') @@ -75,7 +76,7 @@ class TestZerosig(TrezorTest): script_type=proto.OutputScriptType.PAYTOADDRESS, ) - (signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, ], [out1, ]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Bitcoin', [inp1, ], [out1, ]) siglen = serialized_tx[44] # TREZOR must strip leading zero from signature @@ -98,7 +99,7 @@ class TestZerosig(TrezorTest): script_type=proto.OutputScriptType.PAYTOADDRESS, ) - (signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, ], [out1, ]) + (signatures, serialized_tx) = btc.sign_tx(self.client, 'Bitcoin', [inp1, ], [out1, ]) siglen = serialized_tx[44] # TREZOR must strip leading zero from signature From 4b4469b9f4a92134de0443fe4f7b9cbe979a816c Mon Sep 17 00:00:00 2001 From: matejcik Date: Fri, 10 Aug 2018 14:37:49 +0200 Subject: [PATCH 13/37] tests: clean up usage of hardening constants --- .../test_msg_ethereum_signtx_eip155.py | 3 ++- .../test_msg_getpublickey_curve.py | 20 +++++++++---------- .../device_tests/test_msg_lisk_getaddress.py | 10 ++++++---- .../test_msg_lisk_getpublickey.py | 4 +++- .../device_tests/test_msg_lisk_signmessage.py | 11 ++++++---- .../device_tests/test_msg_signidentity.py | 3 ++- .../tests/device_tests/test_msg_signtx.py | 4 ++-- .../device_tests/test_msg_signtx_bcash.py | 6 +++--- .../device_tests/test_msg_signtx_bgold.py | 8 ++++---- .../device_tests/test_msg_signtx_segwit.py | 6 +++--- .../test_msg_signtx_segwit_native.py | 14 ++++++------- .../device_tests/test_multisig_change.py | 16 +++++++-------- 12 files changed, 57 insertions(+), 48 deletions(-) diff --git a/trezorlib/tests/device_tests/test_msg_ethereum_signtx_eip155.py b/trezorlib/tests/device_tests/test_msg_ethereum_signtx_eip155.py index da05adf004..9f4290d3f3 100644 --- a/trezorlib/tests/device_tests/test_msg_ethereum_signtx_eip155.py +++ b/trezorlib/tests/device_tests/test_msg_ethereum_signtx_eip155.py @@ -20,6 +20,7 @@ import pytest from .common import TrezorTest from trezorlib import messages as proto from trezorlib import ethereum +from trezorlib.tools import H_ @pytest.mark.ethereum @@ -165,7 +166,7 @@ class TestMsgEthereumSigntxChainId(TrezorTest): for ci, n, sv, sr, ss, v, gl, d in VECTORS: sig_v, sig_r, sig_s = ethereum.sign_tx( self.client, - n=[0x80000000 | 44, 0x80000000 | 1, 0x80000000, 0, 0], + n=[H_(44), H_(1), H_(0), 0, 0], nonce=n, gas_price=20000000000, gas_limit=gl, diff --git a/trezorlib/tests/device_tests/test_msg_getpublickey_curve.py b/trezorlib/tests/device_tests/test_msg_getpublickey_curve.py index 500476ea96..23f4064a6a 100644 --- a/trezorlib/tests/device_tests/test_msg_getpublickey_curve.py +++ b/trezorlib/tests/device_tests/test_msg_getpublickey_curve.py @@ -18,7 +18,7 @@ from binascii import hexlify import pytest from .common import TrezorTest -from trezorlib.tools import CallException +from trezorlib.tools import CallException, H_ from trezorlib import btc @@ -26,24 +26,24 @@ class TestMsgGetpublickeyCurve(TrezorTest): def test_default_curve(self): self.setup_mnemonic_nopin_nopassphrase() - assert hexlify(btc.get_public_node(self.client, [0x80000000 | 111, 42]).node.public_key).decode() == '02e7fcec053f0df94d88c86447970743e8a1979d242d09338dcf8687a9966f7fbc' - assert hexlify(btc.get_public_node(self.client, [0x80000000 | 111, 0x80000000 | 42]).node.public_key).decode() == '03ce7b690969d773ba9ed212464eb2b534b87b9b8a9383300bddabe1f093f79220' + assert hexlify(btc.get_public_node(self.client, [H_(111), 42]).node.public_key).decode() == '02e7fcec053f0df94d88c86447970743e8a1979d242d09338dcf8687a9966f7fbc' + assert hexlify(btc.get_public_node(self.client, [H_(111), H_(42)]).node.public_key).decode() == '03ce7b690969d773ba9ed212464eb2b534b87b9b8a9383300bddabe1f093f79220' def test_secp256k1_curve(self): self.setup_mnemonic_nopin_nopassphrase() - assert hexlify(btc.get_public_node(self.client, [0x80000000 | 111, 42], ecdsa_curve_name='secp256k1').node.public_key).decode() == '02e7fcec053f0df94d88c86447970743e8a1979d242d09338dcf8687a9966f7fbc' - assert hexlify(btc.get_public_node(self.client, [0x80000000 | 111, 0x80000000 | 42], ecdsa_curve_name='secp256k1').node.public_key).decode() == '03ce7b690969d773ba9ed212464eb2b534b87b9b8a9383300bddabe1f093f79220' + assert hexlify(btc.get_public_node(self.client, [H_(111), 42], ecdsa_curve_name='secp256k1').node.public_key).decode() == '02e7fcec053f0df94d88c86447970743e8a1979d242d09338dcf8687a9966f7fbc' + assert hexlify(btc.get_public_node(self.client, [H_(111), H_(42)], ecdsa_curve_name='secp256k1').node.public_key).decode() == '03ce7b690969d773ba9ed212464eb2b534b87b9b8a9383300bddabe1f093f79220' def test_nist256p1_curve(self): self.setup_mnemonic_nopin_nopassphrase() - assert hexlify(btc.get_public_node(self.client, [0x80000000 | 111, 42], ecdsa_curve_name='nist256p1').node.public_key).decode() == '02a9ce59b32bd64a70bc52aca96e5d09af65c6b9593ba2a60af8fccfe1437f2129' - assert hexlify(btc.get_public_node(self.client, [0x80000000 | 111, 0x80000000 | 42], ecdsa_curve_name='nist256p1').node.public_key).decode() == '026fe35d8afed67dbf0561a1d32922e8ad0cd0d86effbc82be970cbed7d9bab2c2' + assert hexlify(btc.get_public_node(self.client, [H_(111), 42], ecdsa_curve_name='nist256p1').node.public_key).decode() == '02a9ce59b32bd64a70bc52aca96e5d09af65c6b9593ba2a60af8fccfe1437f2129' + assert hexlify(btc.get_public_node(self.client, [H_(111), H_(42)], ecdsa_curve_name='nist256p1').node.public_key).decode() == '026fe35d8afed67dbf0561a1d32922e8ad0cd0d86effbc82be970cbed7d9bab2c2' def test_ed25519_curve(self): self.setup_mnemonic_nopin_nopassphrase() # ed25519 curve does not support public derivation, so test only private derivation paths - assert hexlify(btc.get_public_node(self.client, [0x80000000 | 111, 0x80000000 | 42], ecdsa_curve_name='ed25519').node.public_key).decode() == '0069a14b478e508eab6e93303f4e6f5c50b8136627830f2ed5c3a835fc6c0ea2b7' - assert hexlify(btc.get_public_node(self.client, [0x80000000 | 111, 0x80000000 | 65535], ecdsa_curve_name='ed25519').node.public_key).decode() == '00514f73a05184458611b14c348fee4fd988d36cf3aee7207737861bac611de991' + assert hexlify(btc.get_public_node(self.client, [H_(111), H_(42)], ecdsa_curve_name='ed25519').node.public_key).decode() == '0069a14b478e508eab6e93303f4e6f5c50b8136627830f2ed5c3a835fc6c0ea2b7' + assert hexlify(btc.get_public_node(self.client, [H_(111), H_(65535)], ecdsa_curve_name='ed25519').node.public_key).decode() == '00514f73a05184458611b14c348fee4fd988d36cf3aee7207737861bac611de991' # test failure when using public derivation with pytest.raises(CallException): - btc.get_public_node(self.client, [0x80000000 | 111, 42], ecdsa_curve_name='ed25519') + btc.get_public_node(self.client, [H_(111), 42], ecdsa_curve_name='ed25519') diff --git a/trezorlib/tests/device_tests/test_msg_lisk_getaddress.py b/trezorlib/tests/device_tests/test_msg_lisk_getaddress.py index 37376a6753..5b6c661505 100644 --- a/trezorlib/tests/device_tests/test_msg_lisk_getaddress.py +++ b/trezorlib/tests/device_tests/test_msg_lisk_getaddress.py @@ -18,7 +18,9 @@ import pytest from .common import TrezorTest from trezorlib import lisk +from trezorlib.tools import parse_path +LISK_PATH = parse_path("m/44h/134h/0h/1h") @pytest.mark.lisk @pytest.mark.skip_t1 @@ -26,7 +28,7 @@ class TestMsgLiskGetaddress(TrezorTest): def test_lisk_getaddress(self): self.setup_mnemonic_nopin_nopassphrase() - assert lisk.get_address(self.client, [2147483692, 2147483782]) == '1431530009238518937L' - assert lisk.get_address(self.client, [2147483692, 2147483782, 2147483648]) == '17563781916205589679L' - assert lisk.get_address(self.client, [2147483692, 2147483782, 2147483648, 2147483649]) == '1874186517773691964L' - assert lisk.get_address(self.client, [2147483692, 2147483782, 2147484647, 2147484647]) == '16295203558710684671L' + assert lisk.get_address(self.client, LISK_PATH[:2]) == '1431530009238518937L' + assert lisk.get_address(self.client, LISK_PATH[:3]) == '17563781916205589679L' + assert lisk.get_address(self.client, LISK_PATH) == '1874186517773691964L' + assert lisk.get_address(self.client, parse_path("m/44h/134h/999h/999h")) == '16295203558710684671L' diff --git a/trezorlib/tests/device_tests/test_msg_lisk_getpublickey.py b/trezorlib/tests/device_tests/test_msg_lisk_getpublickey.py index 9ade7cf2c9..87316ea6be 100644 --- a/trezorlib/tests/device_tests/test_msg_lisk_getpublickey.py +++ b/trezorlib/tests/device_tests/test_msg_lisk_getpublickey.py @@ -19,7 +19,9 @@ import pytest from .common import TrezorTest from trezorlib import lisk +from trezorlib.tools import parse_path +LISK_PATH = parse_path("m/44h/134h/0h/0h") @pytest.mark.lisk @pytest.mark.skip_t1 @@ -27,5 +29,5 @@ class TestMsgLiskGetPublicKey(TrezorTest): def test_lisk_get_public_key(self): self.setup_mnemonic_nopin_nopassphrase() - sig = lisk.get_public_key(self.client, [2147483692, 2147483782, 2147483648, 2147483648]) + sig = lisk.get_public_key(self.client, LISK_PATH) assert hexlify(sig.public_key) == b'eb56d7bbb5e8ea9269405f7a8527fe126023d1db2c973cfac6f760b60ae27294' diff --git a/trezorlib/tests/device_tests/test_msg_lisk_signmessage.py b/trezorlib/tests/device_tests/test_msg_lisk_signmessage.py index c1dfa25d9e..02084e7a0f 100644 --- a/trezorlib/tests/device_tests/test_msg_lisk_signmessage.py +++ b/trezorlib/tests/device_tests/test_msg_lisk_signmessage.py @@ -19,6 +19,9 @@ import pytest from .common import TrezorTest from trezorlib import lisk +from trezorlib.tools import parse_path + +LISK_PATH = parse_path("m/44h/134h/0h/0h") @pytest.mark.lisk @@ -27,12 +30,12 @@ class TestMsgLiskSignmessage(TrezorTest): def test_sign(self): self.setup_mnemonic_nopin_nopassphrase() - sig = lisk.sign_message(self.client, [2147483692, 2147483782, 2147483648, 2147483648], 'This is an example of a signed message.') + sig = lisk.sign_message(self.client, LISK_PATH, 'This is an example of a signed message.') assert hexlify(sig.public_key) == b'eb56d7bbb5e8ea9269405f7a8527fe126023d1db2c973cfac6f760b60ae27294' assert hexlify(sig.signature) == b'7858ae7cd52ea6d4b17e800ca60144423db5560bfd618b663ffbf26ab66758563df45cbffae8463db22dc285dd94309083b8c807776085b97d05374d79867d05' def test_sign_long(self): self.setup_mnemonic_nopin_nopassphrase() - sig = lisk.sign_message(self.client, [2147483692, 2147483782, 2147483648], 'VeryLongMessage!' * 64) - assert hexlify(sig.public_key) == b'8bca6b65a1a877767b746ea0b3c4310d404aa113df99c1b554e1802d70185ab5' - assert hexlify(sig.signature) == b'458ca5896d0934866992268f7509b5e954d568b1251e20c19bd3149ee3c86ffb5a44d1c2a0abbb99a3ab4767272dbb0e419b4579e890a24919ebbbe6cc0f970f' + sig = lisk.sign_message(self.client, LISK_PATH, 'VeryLongMessage!' * 64) + assert hexlify(sig.public_key) == b'eb56d7bbb5e8ea9269405f7a8527fe126023d1db2c973cfac6f760b60ae27294' + assert hexlify(sig.signature) == b'19c26f4b6f2ecf2feef57d22237cf97eb7862fdc2fb8c303878843f5dd728191f7837cf8d0ed41f8e470b15181223a3a5131881add9c22b2453b01be4edef104' diff --git a/trezorlib/tests/device_tests/test_msg_signidentity.py b/trezorlib/tests/device_tests/test_msg_signidentity.py index efc8db2864..0296775ac6 100644 --- a/trezorlib/tests/device_tests/test_msg_signidentity.py +++ b/trezorlib/tests/device_tests/test_msg_signidentity.py @@ -21,6 +21,7 @@ from .common import TrezorTest from trezorlib import messages as proto from trezorlib import misc +from trezorlib.tools import H_ def check_path(identity): @@ -41,7 +42,7 @@ def check_path(identity): m.update(uri) print('hash:', m.hexdigest()) (a, b, c, d, _, _, _, _) = struct.unpack('<8I', m.digest()) - address_n = [0x80000000 | 13, 0x80000000 | a, 0x80000000 | b, 0x80000000 | c, 0x80000000 | d] + address_n = [H_(13), H_(a), H_(b), H_(c), H_(d)] print('path:', 'm/' + '/'.join([str(x) for x in address_n])) diff --git a/trezorlib/tests/device_tests/test_msg_signtx.py b/trezorlib/tests/device_tests/test_msg_signtx.py index 49360f2ff2..09ba053ad3 100644 --- a/trezorlib/tests/device_tests/test_msg_signtx.py +++ b/trezorlib/tests/device_tests/test_msg_signtx.py @@ -22,7 +22,7 @@ from .conftest import TREZOR_VERSION from trezorlib import messages as proto from trezorlib.tx_api import TxApiInsight -from trezorlib.tools import parse_path, CallException +from trezorlib.tools import parse_path, CallException, H_ from trezorlib import btc TxApiTestnet = TxApiInsight("insight_testnet") @@ -673,7 +673,7 @@ class TestMsgSigntx(TrezorTest): if not run_attack: return msg - msg.inputs[0].address_n[2] = 12345 + 0x80000000 + msg.inputs[0].address_n[2] = H_(12345) run_attack = False return msg diff --git a/trezorlib/tests/device_tests/test_msg_signtx_bcash.py b/trezorlib/tests/device_tests/test_msg_signtx_bcash.py index 32978b8687..5816cf6f26 100644 --- a/trezorlib/tests/device_tests/test_msg_signtx_bcash.py +++ b/trezorlib/tests/device_tests/test_msg_signtx_bcash.py @@ -21,7 +21,7 @@ from .common import TrezorTest from ..support.ckd_public import deserialize from trezorlib import coins from trezorlib import messages as proto -from trezorlib.tools import parse_path, CallException +from trezorlib.tools import parse_path, CallException, H_ from trezorlib import btc TxApiBcash = coins.tx_api['Bcash'] @@ -268,7 +268,7 @@ class TestMsgSigntxBch(TrezorTest): if attack_ctr <= 1: return msg - msg.inputs[0].address_n[2] = 1 + 0x80000000 + msg.inputs[0].address_n[2] = H_(1) return msg with self.client: @@ -395,7 +395,7 @@ class TestMsgSigntxBch(TrezorTest): prev_index=0, script_type=proto.InputScriptType.SPENDMULTISIG, ) - out2.address_n[2] = 1 + 0x80000000 + out2.address_n[2] = H_(1) with self.client: self.client.set_expected_responses([ diff --git a/trezorlib/tests/device_tests/test_msg_signtx_bgold.py b/trezorlib/tests/device_tests/test_msg_signtx_bgold.py index d3423629d9..9229a6cc54 100644 --- a/trezorlib/tests/device_tests/test_msg_signtx_bgold.py +++ b/trezorlib/tests/device_tests/test_msg_signtx_bgold.py @@ -21,7 +21,7 @@ from .common import TrezorTest from ..support.ckd_public import deserialize from trezorlib import coins from trezorlib import messages as proto -from trezorlib.tools import parse_path, CallException +from trezorlib.tools import parse_path, CallException, H_ from trezorlib import btc TxApiBitcoinGold = coins.tx_api["Bgold"] @@ -143,7 +143,7 @@ class TestMsgSigntxBitcoinGold(TrezorTest): if attack_ctr <= 1: return msg - msg.inputs[0].address_n[2] = 1 + 0x80000000 + msg.inputs[0].address_n[2] = H_(1) return msg with self.client: @@ -217,7 +217,7 @@ class TestMsgSigntxBitcoinGold(TrezorTest): prev_index=0, script_type=proto.InputScriptType.SPENDMULTISIG, ) - out2.address_n[2] = 1 + 0x80000000 + out2.address_n[2] = H_(1) with self.client: self.client.set_expected_responses([ @@ -351,7 +351,7 @@ class TestMsgSigntxBitcoinGold(TrezorTest): # store signature inp1.multisig.signatures[0] = signatures1[0] # sign with third key - inp1.address_n[2] = 0x80000003 + inp1.address_n[2] = H_(3) self.client.set_expected_responses([ proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=0)), diff --git a/trezorlib/tests/device_tests/test_msg_signtx_segwit.py b/trezorlib/tests/device_tests/test_msg_signtx_segwit.py index e823af10fd..a4146689fd 100644 --- a/trezorlib/tests/device_tests/test_msg_signtx_segwit.py +++ b/trezorlib/tests/device_tests/test_msg_signtx_segwit.py @@ -23,7 +23,7 @@ from .common import TrezorTest from trezorlib import messages as proto from trezorlib.tx_api import TxApiInsight -from trezorlib.tools import parse_path, CallException +from trezorlib.tools import parse_path, CallException, H_ from trezorlib import btc TxApiTestnet = TxApiInsight("insight_testnet") @@ -146,7 +146,7 @@ class TestMsgSigntxSegwit(TrezorTest): # store signature inp1.multisig.signatures[0] = signatures1[0] # sign with third key - inp1.address_n[2] = 0x80000003 + inp1.address_n[2] = H_(3) self.client.set_expected_responses([ proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=0)), @@ -204,7 +204,7 @@ class TestMsgSigntxSegwit(TrezorTest): if not run_attack: return msg - msg.inputs[0].address_n[2] = 12345 + 0x80000000 + msg.inputs[0].address_n[2] = H_(12345) run_attack = False return msg diff --git a/trezorlib/tests/device_tests/test_msg_signtx_segwit_native.py b/trezorlib/tests/device_tests/test_msg_signtx_segwit_native.py index 66034e5c44..16db190275 100644 --- a/trezorlib/tests/device_tests/test_msg_signtx_segwit_native.py +++ b/trezorlib/tests/device_tests/test_msg_signtx_segwit_native.py @@ -19,7 +19,7 @@ from binascii import hexlify, unhexlify from .common import TrezorTest from ..support.ckd_public import deserialize from trezorlib import messages as proto -from trezorlib.tools import parse_path +from trezorlib.tools import parse_path, H_ from trezorlib.tx_api import TxApiInsight from trezorlib import btc @@ -284,7 +284,7 @@ class TestMsgSigntxSegwitNative(TrezorTest): # store signature inp1.multisig.signatures[0] = signatures1[0] # sign with third key - inp1.address_n[2] = 0x80000003 + inp1.address_n[2] = H_(3) self.client.set_expected_responses([ proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=0)), @@ -340,7 +340,7 @@ class TestMsgSigntxSegwitNative(TrezorTest): # store signature inp1.multisig.signatures[1] = signatures1[0] # sign with first key - inp1.address_n[2] = 0x80000001 + inp1.address_n[2] = H_(1) self.client.set_expected_responses([ proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=0)), @@ -401,8 +401,8 @@ class TestMsgSigntxSegwitNative(TrezorTest): # store signature inp1.multisig.signatures[0] = signatures1[0] # sign with third key - inp1.address_n[2] = 0x80000003 - out1.address_n[2] = 0x80000003 + inp1.address_n[2] = H_(3) + out1.address_n[2] = H_(3) self.client.set_expected_responses([ proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=0)), @@ -462,8 +462,8 @@ class TestMsgSigntxSegwitNative(TrezorTest): # store signature inp1.multisig.signatures[0] = signatures1[0] # sign with third key - inp1.address_n[2] = 0x80000003 - out1.address_n[2] = 0x80000003 + inp1.address_n[2] = H_(3) + out1.address_n[2] = H_(3) self.client.set_expected_responses([ proto.TxRequest(request_type=proto.RequestType.TXINPUT, details=proto.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto.RequestType.TXOUTPUT, details=proto.TxRequestDetailsType(request_index=0)), diff --git a/trezorlib/tests/device_tests/test_multisig_change.py b/trezorlib/tests/device_tests/test_multisig_change.py index 5a6c205c26..60e90faa0b 100644 --- a/trezorlib/tests/device_tests/test_multisig_change.py +++ b/trezorlib/tests/device_tests/test_multisig_change.py @@ -19,7 +19,7 @@ from binascii import hexlify, unhexlify from .common import TrezorTest from ..support import ckd_public as bip32 from trezorlib import messages as proto -from trezorlib.tools import parse_path +from trezorlib.tools import parse_path, H_ from trezorlib.tx_api import TxApiInsight from trezorlib import btc @@ -98,7 +98,7 @@ class TestMultisigChange(TrezorTest): # 2N9W4z9AhAPaHghtqVQPbaTAGHdbrhKeBQw inp1 = proto.TxInputType( - address_n=[45 | 0x80000000, 0, 0, 0], + address_n=[H_(45), 0, 0, 0], prev_hash=unhexlify('16c6c8471b8db7a628f2b2bb86bfeefae1766463ce8692438c7fd3fce3f43ce5'), prev_index=1, script_type=proto.InputScriptType.SPENDMULTISIG, @@ -107,7 +107,7 @@ class TestMultisigChange(TrezorTest): # 2NDBG6QXQLtnQ3jRGkrqo53BiCeXfQXLdj4 inp2 = proto.TxInputType( - address_n=[45 | 0x80000000, 0, 0, 1], + address_n=[H_(45), 0, 0, 1], prev_hash=unhexlify('d80c34ee14143a8bf61125102b7ef594118a3796cad670fa8ee15080ae155318'), prev_index=0, script_type=proto.InputScriptType.SPENDMULTISIG, @@ -116,7 +116,7 @@ class TestMultisigChange(TrezorTest): # 2MvwPWfp2XPU3S1cMwgEMKBPUw38VP5SBE4 inp3 = proto.TxInputType( - address_n=[45 | 0x80000000, 0, 0, 1], + address_n=[H_(45), 0, 0, 1], prev_hash=unhexlify('b0946dc27ba308a749b11afecc2018980af18f79e89ad6b080b58220d856f739'), prev_index=0, script_type=proto.InputScriptType.SPENDMULTISIG, @@ -267,7 +267,7 @@ class TestMultisigChange(TrezorTest): ) out1 = proto.TxOutputType( - address_n=[0x80000000 | 45, 0, 1, 0], + address_n=[H_(45), 0, 1, 0], multisig=multisig_out1, amount=40000000, script_type=proto.OutputScriptType.PAYTOMULTISIG @@ -306,7 +306,7 @@ class TestMultisigChange(TrezorTest): ) out2 = proto.TxOutputType( - address_n=[0x80000000 | 45, 0, 1, 1], + address_n=[H_(45), 0, 1, 1], multisig=multisig_out2, amount=44000000, script_type=proto.OutputScriptType.PAYTOMULTISIG @@ -339,7 +339,7 @@ class TestMultisigChange(TrezorTest): ) out2 = proto.TxOutputType( - address_n=[0x80000000 | 45, 0, 1, 0], + address_n=[H_(45), 0, 1, 0], multisig=multisig_out2, amount=44000000, script_type=proto.OutputScriptType.PAYTOMULTISIG @@ -366,7 +366,7 @@ class TestMultisigChange(TrezorTest): ) out1 = proto.TxOutputType( - address_n=[0x80000000 | 45, 0, 1, 0], + address_n=[H_(45), 0, 1, 0], multisig=multisig_out1, amount=40000000, script_type=proto.OutputScriptType.PAYTOMULTISIG From 045ad85ecde6658b1855a51ca0347954aa59f95d Mon Sep 17 00:00:00 2001 From: matejcik Date: Fri, 10 Aug 2018 15:18:26 +0200 Subject: [PATCH 14/37] trezorctl: use new API --- trezorctl | 111 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 64 insertions(+), 47 deletions(-) diff --git a/trezorctl b/trezorctl index f42ba7dab8..1e68a25321 100755 --- a/trezorctl +++ b/trezorctl @@ -35,10 +35,21 @@ from trezorlib.transport import get_transport, enumerate_devices from trezorlib import coins from trezorlib import log from trezorlib import messages as proto +from trezorlib import ( + btc, + cosi, + debuglink, + device, + ethereum, + firmware, + lisk, + misc, + nem, + ripple, + stellar, +) from trezorlib import protobuf -from trezorlib import stellar from trezorlib import tools -from trezorlib import ripple class ChoiceType(click.Choice): @@ -164,7 +175,7 @@ def clear_session(connect): @click.argument('size', type=int) @click.pass_obj def get_entropy(connect, size): - return binascii.hexlify(connect().get_entropy(size)) + return binascii.hexlify(misc.get_entropy(connect(), size)) @cli.command(help='Retrieve device features and settings.') @@ -182,33 +193,33 @@ def get_features(connect): @click.option('-r', '--remove', is_flag=True) @click.pass_obj def change_pin(connect, remove): - return connect().change_pin(remove) + return device.change_pin(connect(), remove) @cli.command(help='Enable passphrase.') @click.pass_obj def enable_passphrase(connect): - return connect().apply_settings(use_passphrase=True) + return device.apply_settings(connect(), use_passphrase=True) @cli.command(help='Disable passphrase.') @click.pass_obj def disable_passphrase(connect): - return connect().apply_settings(use_passphrase=False) + return device.apply_settings(connect(), use_passphrase=False) @cli.command(help='Set new device label.') @click.option('-l', '--label') @click.pass_obj def set_label(connect, label): - return connect().apply_settings(label=label) + return device.apply_settings(connect(), label=label) @cli.command(help='Set passphrase source.') @click.argument('source', type=int) @click.pass_obj def set_passphrase_source(connect, source): - return connect().apply_settings(passphrase_source=source) + return device.apply_settings(connect(), passphrase_source=source) @cli.command(help='Set auto-lock delay (in seconds).') @@ -225,7 +236,7 @@ def set_auto_lock_delay(connect, delay): seconds = float(value) * units[unit] else: seconds = float(delay) # assume seconds if no unit is specified - return connect().apply_settings(auto_lock_delay_ms=int(seconds * 1000)) + return device.apply_settings(connect(), auto_lock_delay_ms=int(seconds * 1000)) @cli.command(help='Set device flags.') @@ -239,7 +250,7 @@ def set_flags(connect, flags): flags = int(flags, 16) else: flags = int(flags) - return connect().apply_flags(flags=flags) + return device.apply_flags(connect(), flags=flags) @cli.command(help='Set new homescreen.') @@ -266,14 +277,14 @@ def set_homescreen(connect, filename): o = (i + j * 128) img[o // 8] |= (1 << (7 - o % 8)) img = bytes(img) - return connect().apply_settings(homescreen=img) + return device.apply_settings(connect(), homescreen=img) @cli.command(help='Set U2F counter.') @click.argument('counter', type=int) @click.pass_obj def set_u2f_counter(connect, counter): - return connect().set_u2f_counter(counter) + return device.set_u2f_counter(connect(), counter) @cli.command(help='Reset device to factory defaults and remove all private data.') @@ -297,7 +308,7 @@ def wipe_device(connect, bootloader): click.echo('Wiping user data! Please confirm the action on your device ...') try: - return connect().wipe_device() + return device.wipe(connect()) except tools.CallException as e: click.echo('Action failed: {} {}'.format(*e.args)) sys.exit(3) @@ -319,7 +330,8 @@ def load_device(connect, mnemonic, expand, xprv, pin, passphrase_protection, lab client = connect() if mnemonic: - return client.load_device_by_mnemonic( + return debuglink.load_device_by_mnemonic( + client, mnemonic, pin, passphrase_protection, @@ -329,20 +341,22 @@ def load_device(connect, mnemonic, expand, xprv, pin, passphrase_protection, lab expand ) if xprv: - return client.load_device_by_xprv( + return debuglink.load_device_by_xprv( + client, xprv, pin, passphrase_protection, label, 'english' - ) + ) if slip0014: - return client.load_device_by_mnemonic( + return debuglink.load_device_by_mnemonic( + client, ' '.join(['all'] * 12), pin, passphrase_protection, 'SLIP-0014' - ) + ) @cli.command(help='Start safe recovery workflow.') @@ -355,7 +369,8 @@ def load_device(connect, mnemonic, expand, xprv, pin, passphrase_protection, lab @click.option('-d', '--dry-run', is_flag=True) @click.pass_obj def recovery_device(connect, words, expand, pin_protection, passphrase_protection, label, rec_type, dry_run): - return connect().recovery_device( + return device.recover( + connect(), int(words), passphrase_protection, pin_protection, @@ -377,7 +392,8 @@ def recovery_device(connect, words, expand, pin_protection, passphrase_protectio @click.option('-s', '--skip-backup', is_flag=True) @click.pass_obj def reset_device(connect, entropy, strength, passphrase_protection, pin_protection, label, u2f_counter, skip_backup): - return connect().reset_device( + return device.reset( + connect(), entropy, int(strength), passphrase_protection, @@ -392,7 +408,7 @@ def reset_device(connect, entropy, strength, passphrase_protection, pin_protecti @cli.command(help='Perform device seed backup.') @click.pass_obj def backup_device(connect): - return connect().backup_device() + return device.backup(connect()) # @@ -474,7 +490,7 @@ def firmware_update(connect, filename, url, version, skip_check, fingerprint): click.echo('If asked, please confirm the action on your device ...') try: - return client.firmware_update(fp=io.BytesIO(fp)) + return firmware.update(client, fp=io.BytesIO(fp)) except tools.CallException as e: if e.args[0] in (proto.FailureType.FirmwareError, proto.FailureType.ActionCancelled): click.echo("Update aborted on device.") @@ -486,7 +502,7 @@ def firmware_update(connect, filename, url, version, skip_check, fingerprint): @cli.command(help='Perform a self-test.') @click.pass_obj def self_test(connect): - return connect().self_test() + return debuglink.self_test(connect()) # @@ -503,7 +519,7 @@ def self_test(connect): def get_address(connect, coin, address, script_type, show_display): client = connect() address_n = tools.parse_path(address) - return client.get_address(coin, address_n, show_display, script_type=script_type) + return btc.get_address(client, coin, address_n, show_display, script_type=script_type) @cli.command(help='Get public node of given path.') @@ -515,7 +531,7 @@ def get_address(connect, coin, address, script_type, show_display): def get_public_node(connect, coin, address, curve, show_display): client = connect() address_n = tools.parse_path(address) - result = client.get_public_node(address_n, ecdsa_curve_name=curve, show_display=show_display, coin_name=coin) + result = btc.get_public_node(client, address_n, ecdsa_curve_name=curve, show_display=show_display, coin_name=coin) return { 'node': { 'depth': result.node.depth, @@ -622,7 +638,7 @@ def sign_tx(connect, coin): tx_version = click.prompt('Transaction version', type=int, default=2) tx_locktime = click.prompt('Transaction locktime', type=int, default=0) - _, serialized_tx = client.sign_tx(coin, inputs, outputs, tx_version, tx_locktime) + _, serialized_tx = btc.sign_tx(client, coin, inputs, outputs, tx_version, tx_locktime) client.close() @@ -654,7 +670,7 @@ def sign_message(connect, coin, address, message, script_type): 'p2shsegwit': proto.InputScriptType.SPENDP2SHWITNESS, } script_type = typemap[script_type] - res = client.sign_message(coin, address_n, message, script_type) + res = btc.sign_message(client, coin, address_n, message, script_type) return { 'message': message, 'address': res.address, @@ -670,7 +686,7 @@ def sign_message(connect, coin, address, message, script_type): @click.pass_obj def verify_message(connect, coin, address, signature, message): signature = base64.b64decode(signature) - return connect().verify_message(coin, address, signature, message) + return btc.verify_message(connect(), coin, address, signature, message) @cli.command(help='Sign message with Ethereum address.') @@ -680,7 +696,7 @@ def verify_message(connect, coin, address, signature, message): def ethereum_sign_message(connect, address, message): client = connect() address_n = tools.parse_path(address) - ret = client.ethereum_sign_message(address_n, message) + ret = ethereum.sign_message(client, address_n, message) output = { 'message': message, 'address': '0x%s' % binascii.hexlify(ret.address).decode(), @@ -704,7 +720,7 @@ def ethereum_decode_hex(value): def ethereum_verify_message(connect, address, signature, message): address = ethereum_decode_hex(address) signature = ethereum_decode_hex(signature) - return connect().ethereum_verify_message(address, signature, message) + return ethereum.verify_message(connect(), address, signature, message) @cli.command(help='Encrypt value by given key and path.') @@ -715,7 +731,7 @@ def ethereum_verify_message(connect, address, signature, message): def encrypt_keyvalue(connect, address, key, value): client = connect() address_n = tools.parse_path(address) - res = client.encrypt_keyvalue(address_n, key, value.encode()) + res = misc.encrypt_keyvalue(client, address_n, key, value.encode()) return binascii.hexlify(res) @@ -727,7 +743,7 @@ def encrypt_keyvalue(connect, address, key, value): def decrypt_keyvalue(connect, address, key, value): client = connect() address_n = tools.parse_path(address) - return client.decrypt_keyvalue(address_n, key, binascii.unhexlify(value)) + return misc.decrypt_keyvalue(client, address_n, key, binascii.unhexlify(value)) # @cli.command(help='Encrypt message.') @@ -774,7 +790,7 @@ def decrypt_keyvalue(connect, address, key, value): def ethereum_get_address(connect, address, show_display): client = connect() address_n = tools.parse_path(address) - address = client.ethereum_get_address(address_n, show_display) + address = ethereum.get_address(client, address_n, show_display) return '0x%s' % binascii.hexlify(address).decode() @@ -841,7 +857,7 @@ def ethereum_sign_tx(connect, host, chain_id, address, value, gas_limit, gas_pri client = connect() address_n = tools.parse_path(address) - address = '0x%s' % (binascii.hexlify(client.ethereum_get_address(address_n)).decode()) + address = '0x%s' % (binascii.hexlify(ethereum.get_address(client, address_n)).decode()) if gas_price is None or gas_limit is None or nonce is None or publish: host, port = host.split(':') @@ -864,7 +880,8 @@ def ethereum_sign_tx(connect, host, chain_id, address, value, gas_limit, gas_pri if nonce is None: nonce = eth.eth_getTransactionCount(address) - sig = client.ethereum_sign_tx( + sig = ethereum.sign_tx( + client, n=address_n, tx_type=tx_type, nonce=nonce, @@ -903,7 +920,7 @@ def ethereum_sign_tx(connect, host, chain_id, address, value, gas_limit, gas_pri def nem_get_address(connect, address, network, show_display): client = connect() address_n = tools.parse_path(address) - return client.nem_get_address(address_n, network, show_display) + return nem.get_address(client, address_n, network, show_display) @cli.command(help='Sign (and optionally broadcast) NEM transaction.') @@ -914,7 +931,7 @@ def nem_get_address(connect, address, network, show_display): def nem_sign_tx(connect, address, file, broadcast): client = connect() address_n = tools.parse_path(address) - transaction = client.nem_sign_tx(address_n, json.load(file)) + transaction = nem.sign_tx(client, address_n, json.load(file)) payload = { "data": binascii.hexlify(transaction.data).decode(), @@ -940,7 +957,7 @@ def nem_sign_tx(connect, address, file, broadcast): def lisk_get_address(connect, address, show_display): client = connect() address_n = tools.parse_path(address) - return client.lisk_get_address(address_n, show_display) + return lisk.get_address(client, address_n, show_display) @cli.command(help='Get Lisk public key for specified path.') @@ -950,7 +967,7 @@ def lisk_get_address(connect, address, show_display): def lisk_get_public_key(connect, address, show_display): client = connect() address_n = tools.parse_path(address) - res = client.lisk_get_public_key(address_n, show_display) + res = lisk.get_public_key(client, address_n, show_display) output = { "public_key": binascii.hexlify(res.public_key).decode() } @@ -965,7 +982,7 @@ def lisk_get_public_key(connect, address, show_display): def lisk_sign_tx(connect, address, file): client = connect() address_n = tools.parse_path(address) - transaction = client.lisk_sign_tx(address_n, json.load(file)) + transaction = lisk.sign_tx(client, address_n, json.load(file)) payload = { "signature": binascii.hexlify(transaction.signature).decode() @@ -981,7 +998,7 @@ def lisk_sign_tx(connect, address, file): def lisk_sign_message(connect, address, message): client = connect() address_n = client.expand_path(address) - res = client.lisk_sign_message(address_n, message) + res = lisk.sign_message(client, address_n, message) output = { "message": message, "public_key": binascii.hexlify(res.public_key).decode(), @@ -998,7 +1015,7 @@ def lisk_sign_message(connect, address, message): def lisk_verify_message(connect, pubkey, signature, message): signature = bytes.fromhex(signature) pubkey = bytes.fromhex(pubkey) - return connect().lisk_verify_message(pubkey, signature, message) + return lisk.verify_message(connect(), pubkey, signature, message) # @@ -1013,7 +1030,7 @@ def lisk_verify_message(connect, pubkey, signature, message): def cosi_commit(connect, address, data): client = connect() address_n = tools.parse_path(address) - return client.cosi_commit(address_n, binascii.unhexlify(data)) + return cosi.commit(client, address_n, binascii.unhexlify(data)) @cli.command(help='Ask device to sign using CoSi.') @@ -1025,7 +1042,7 @@ def cosi_commit(connect, address, data): def cosi_sign(connect, address, data, global_commitment, global_pubkey): client = connect() address_n = tools.parse_path(address) - return client.cosi_sign(address_n, binascii.unhexlify(data), binascii.unhexlify(global_commitment), binascii.unhexlify(global_pubkey)) + return cosi.sign(client, address_n, binascii.unhexlify(data), binascii.unhexlify(global_commitment), binascii.unhexlify(global_pubkey)) # @@ -1038,7 +1055,7 @@ def cosi_sign(connect, address, data, global_commitment, global_pubkey): def stellar_get_address(connect, address, show_display): client = connect() address_n = tools.parse_path(address) - return client.stellar_get_address(address_n, show_display) + return stellar.get_address(client, address_n, show_display) @cli.command(help='Get Stellar public key') @@ -1048,7 +1065,7 @@ def stellar_get_address(connect, address, show_display): def stellar_get_public_key(connect, address, show_display): client = connect() address_n = tools.parse_path(address) - return binascii.hexlify(client.stellar_get_public_key(address_n, show_display)) + return binascii.hexlify(stellar.get_public_key(client, address_n, show_display)) @cli.command(help='Sign a base64-encoded transaction envelope') @@ -1060,7 +1077,7 @@ def stellar_sign_transaction(connect, b64envelope, address, network_passphrase): client = connect() address_n = tools.parse_path(address) tx, operations = stellar.parse_transaction_bytes(base64.b64decode(b64envelope)) - resp = client.stellar_sign_transaction(tx, operations, address_n, network_passphrase) + resp = stellar.sign_tx(client, tx, operations, address_n, network_passphrase) return base64.b64encode(resp.signature) From 6029a98414faf2619272e03891709c3db40db306 Mon Sep 17 00:00:00 2001 From: matejcik Date: Fri, 10 Aug 2018 15:18:34 +0200 Subject: [PATCH 15/37] debuglink: fix bug in self_test bootloader detection --- trezorlib/debuglink.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/trezorlib/debuglink.py b/trezorlib/debuglink.py index 9847e04632..660c0c78f5 100644 --- a/trezorlib/debuglink.py +++ b/trezorlib/debuglink.py @@ -218,7 +218,7 @@ def load_device_by_xprv(client, xprv, pin, passphrase_protection, label, languag @expect(proto.Success, field="message") def self_test(client): - if client.features.bootloader_mode is False: + if client.features.bootloader_mode is not True: raise RuntimeError("Device must be in bootloader mode") return client.call(proto.SelfTest(payload=b'\x00\xFF\x55\xAA\x66\x99\x33\xCCABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\x00\xFF\x55\xAA\x66\x99\x33\xCC')) From ca608d0a9833093d3d6e2e5be86a5863b7caa3cd Mon Sep 17 00:00:00 2001 From: matejcik Date: Fri, 10 Aug 2018 15:24:21 +0200 Subject: [PATCH 16/37] flake8: fix complaints (for the last time, hopefully) --- .flake8 | 2 ++ trezorctl | 4 ++-- .../device_tests/test_msg_lisk_getaddress.py | 1 + .../test_msg_lisk_getpublickey.py | 1 + .../test_msg_lisk_verifymessage.py | 2 +- .../device_tests/test_msg_verifymessage.py | 20 +++++++++---------- .../test_msg_verifymessage_segwit.py | 8 ++++---- .../test_msg_verifymessage_segwit_native.py | 8 ++++---- 8 files changed, 25 insertions(+), 21 deletions(-) diff --git a/.flake8 b/.flake8 index 7d1af43a8a..60680fc2b1 100644 --- a/.flake8 +++ b/.flake8 @@ -22,3 +22,5 @@ ignore = E741, ##### E266: too many leading '#' for block comment E266, + # W503 line break before binary operator + W503, diff --git a/trezorctl b/trezorctl index 1e68a25321..e4242a5e6c 100755 --- a/trezorctl +++ b/trezorctl @@ -348,7 +348,7 @@ def load_device(connect, mnemonic, expand, xprv, pin, passphrase_protection, lab passphrase_protection, label, 'english' - ) + ) if slip0014: return debuglink.load_device_by_mnemonic( client, @@ -356,7 +356,7 @@ def load_device(connect, mnemonic, expand, xprv, pin, passphrase_protection, lab pin, passphrase_protection, 'SLIP-0014' - ) + ) @cli.command(help='Start safe recovery workflow.') diff --git a/trezorlib/tests/device_tests/test_msg_lisk_getaddress.py b/trezorlib/tests/device_tests/test_msg_lisk_getaddress.py index 5b6c661505..9a30e910ab 100644 --- a/trezorlib/tests/device_tests/test_msg_lisk_getaddress.py +++ b/trezorlib/tests/device_tests/test_msg_lisk_getaddress.py @@ -22,6 +22,7 @@ from trezorlib.tools import parse_path LISK_PATH = parse_path("m/44h/134h/0h/1h") + @pytest.mark.lisk @pytest.mark.skip_t1 class TestMsgLiskGetaddress(TrezorTest): diff --git a/trezorlib/tests/device_tests/test_msg_lisk_getpublickey.py b/trezorlib/tests/device_tests/test_msg_lisk_getpublickey.py index 87316ea6be..7eb8dde9a4 100644 --- a/trezorlib/tests/device_tests/test_msg_lisk_getpublickey.py +++ b/trezorlib/tests/device_tests/test_msg_lisk_getpublickey.py @@ -23,6 +23,7 @@ from trezorlib.tools import parse_path LISK_PATH = parse_path("m/44h/134h/0h/0h") + @pytest.mark.lisk @pytest.mark.skip_t1 class TestMsgLiskGetPublicKey(TrezorTest): diff --git a/trezorlib/tests/device_tests/test_msg_lisk_verifymessage.py b/trezorlib/tests/device_tests/test_msg_lisk_verifymessage.py index d4018bd303..8fccd3ff89 100644 --- a/trezorlib/tests/device_tests/test_msg_lisk_verifymessage.py +++ b/trezorlib/tests/device_tests/test_msg_lisk_verifymessage.py @@ -39,7 +39,7 @@ class TestMsgLiskVerifymessage(TrezorTest): unhexlify('eb56d7bbb5e8ea9269405f7a8527fe126023d1db2c973cfac6f760b60ae27294'), unhexlify('7858ae7cd52ea6d4b17e800ca60144423db5560bfd618b663ffbf26ab66758563df45cbffae8463db22dc285dd94309083b8c807776085b97d05374d79867d05'), 'This is an example of a signed message.' - ) + ) def test_verify_long(self): self.setup_mnemonic_nopin_nopassphrase() diff --git a/trezorlib/tests/device_tests/test_msg_verifymessage.py b/trezorlib/tests/device_tests/test_msg_verifymessage.py index 9f887b97d8..154fc5791b 100644 --- a/trezorlib/tests/device_tests/test_msg_verifymessage.py +++ b/trezorlib/tests/device_tests/test_msg_verifymessage.py @@ -41,7 +41,7 @@ class TestMsgVerifymessage(TrezorTest): 'mirio8q3gtv7fhdnmb3TpZ4EuafdzSs7zL', unhexlify('209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80'), 'This is an example of a signed message.' - ) + ) assert ret is True def test_message_verify(self): @@ -54,7 +54,7 @@ class TestMsgVerifymessage(TrezorTest): '1JwSSubhmg6iPtRjtyqhUYYH7bZg3Lfy1T', unhexlify('1ba77e01a9e17ba158b962cfef5f13dfed676ffc2b4bada24e58f784458b52b97421470d001d53d5880cf5e10e76f02be3e80bf21e18398cbd41e8c3b4af74c8c2'), 'This is an example of a signed message.' - ) + ) assert res is True # uncompressed pubkey - FAIL - wrong sig @@ -64,7 +64,7 @@ class TestMsgVerifymessage(TrezorTest): '1JwSSubhmg6iPtRjtyqhUYYH7bZg3Lfy1T', unhexlify('1ba77e01a9e17ba158b962cfef5f13dfed676ffc2b4bada24e58f784458b52b97421470d001d53d5880cf5e10e76f02be3e80bf21e18398cbd41e8c3b4af74c800'), 'This is an example of a signed message.' - ) + ) assert res is False # uncompressed pubkey - FAIL - wrong msg @@ -74,7 +74,7 @@ class TestMsgVerifymessage(TrezorTest): '1JwSSubhmg6iPtRjtyqhUYYH7bZg3Lfy1T', unhexlify('1ba77e01a9e17ba158b962cfef5f13dfed676ffc2b4bada24e58f784458b52b97421470d001d53d5880cf5e10e76f02be3e80bf21e18398cbd41e8c3b4af74c8c2'), 'This is an example of a signed message!' - ) + ) assert res is False # compressed pubkey - OK @@ -93,7 +93,7 @@ class TestMsgVerifymessage(TrezorTest): '1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8', unhexlify('1f44e3e461f7ca9f57c472ce1a28214df1de1dadefb6551a32d1907b80c74d5a1fbfd6daaba12dd8cb06699ce3f6941fbe0f3957b5802d13076181046e741eaa00'), 'This is an example of a signed message.' - ) + ) assert res is False # compressed pubkey - FAIL - wrong msg @@ -112,7 +112,7 @@ class TestMsgVerifymessage(TrezorTest): '14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e', unhexlify('209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80'), 'This is an example of a signed message.' - ) + ) assert res is True # trezor pubkey - FAIL - wrong sig @@ -122,7 +122,7 @@ class TestMsgVerifymessage(TrezorTest): '14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e', unhexlify('209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be00'), 'This is an example of a signed message.' - ) + ) assert res is False # trezor pubkey - FAIL - wrong msg @@ -132,7 +132,7 @@ class TestMsgVerifymessage(TrezorTest): '14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e', unhexlify('209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80'), 'This is an example of a signed message!' - ) + ) assert res is False def test_message_verify_bcash(self): @@ -143,7 +143,7 @@ class TestMsgVerifymessage(TrezorTest): 'bitcoincash:qqj22md58nm09vpwsw82fyletkxkq36zxyxh322pru', unhexlify('209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80'), 'This is an example of a signed message.' - ) + ) assert res is True def test_verify_bitcoind(self): @@ -155,7 +155,7 @@ class TestMsgVerifymessage(TrezorTest): '1KzXE97kV7DrpxCViCN3HbGbiKhzzPM7TQ', unhexlify('1cc694f0f23901dfe3603789142f36a3fc582d0d5c0ec7215cf2ccd641e4e37228504f3d4dc3eea28bbdbf5da27c49d4635c097004d9f228750ccd836a8e1460c0'), u'\u017elu\u0165ou\u010dk\xfd k\u016f\u0148 \xfap\u011bl \u010f\xe1belsk\xe9 \xf3dy' - ) + ) assert res is True diff --git a/trezorlib/tests/device_tests/test_msg_verifymessage_segwit.py b/trezorlib/tests/device_tests/test_msg_verifymessage_segwit.py index 142a132d9b..ae328e72ee 100644 --- a/trezorlib/tests/device_tests/test_msg_verifymessage_segwit.py +++ b/trezorlib/tests/device_tests/test_msg_verifymessage_segwit.py @@ -41,7 +41,7 @@ class TestMsgVerifymessageSegwit(TrezorTest): '2N4VkePSzKH2sv5YBikLHGvzUYvfPxV6zS9', unhexlify('249e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80'), 'This is an example of a signed message.' - ) + ) assert ret is True def test_message_verify(self): @@ -54,7 +54,7 @@ class TestMsgVerifymessageSegwit(TrezorTest): '3CwYaeWxhpXXiHue3ciQez1DLaTEAXcKa1', unhexlify('249e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80'), 'This is an example of a signed message.' - ) + ) assert res is True # trezor pubkey - FAIL - wrong sig @@ -64,7 +64,7 @@ class TestMsgVerifymessageSegwit(TrezorTest): '3CwYaeWxhpXXiHue3ciQez1DLaTEAXcKa1', unhexlify('249e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be00'), 'This is an example of a signed message.' - ) + ) assert res is False # trezor pubkey - FAIL - wrong msg @@ -74,7 +74,7 @@ class TestMsgVerifymessageSegwit(TrezorTest): '3CwYaeWxhpXXiHue3ciQez1DLaTEAXcKa1', unhexlify('249e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80'), 'This is an example of a signed message!' - ) + ) assert res is False def test_verify_utf(self): diff --git a/trezorlib/tests/device_tests/test_msg_verifymessage_segwit_native.py b/trezorlib/tests/device_tests/test_msg_verifymessage_segwit_native.py index e091e0a5c8..31d2c600ae 100644 --- a/trezorlib/tests/device_tests/test_msg_verifymessage_segwit_native.py +++ b/trezorlib/tests/device_tests/test_msg_verifymessage_segwit_native.py @@ -41,7 +41,7 @@ class TestMsgVerifymessageSegwitNative(TrezorTest): 'tb1qyjjkmdpu7metqt5r36jf872a34syws336p3n3p', unhexlify('289e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80'), 'This is an example of a signed message.' - ) + ) assert ret is True def test_message_verify(self): @@ -54,7 +54,7 @@ class TestMsgVerifymessageSegwitNative(TrezorTest): 'bc1qyjjkmdpu7metqt5r36jf872a34syws33s82q2j', unhexlify('289e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80'), 'This is an example of a signed message.' - ) + ) assert res is True # trezor pubkey - FAIL - wrong sig @@ -64,7 +64,7 @@ class TestMsgVerifymessageSegwitNative(TrezorTest): 'bc1qyjjkmdpu7metqt5r36jf872a34syws33s82q2j', unhexlify('289e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be00'), 'This is an example of a signed message.' - ) + ) assert res is False # trezor pubkey - FAIL - wrong msg @@ -74,7 +74,7 @@ class TestMsgVerifymessageSegwitNative(TrezorTest): 'bc1qyjjkmdpu7metqt5r36jf872a34syws33s82q2j', unhexlify('289e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80'), 'This is an example of a signed message!' - ) + ) assert res is False def test_verify_utf(self): From 5259146a0b585b640fda0f0eb44a7123bb84210d Mon Sep 17 00:00:00 2001 From: matejcik Date: Fri, 10 Aug 2018 15:48:39 +0200 Subject: [PATCH 17/37] style: remove unused imports with autoflake --- trezorctl | 1 - trezorlib/client.py | 2 -- trezorlib/cosi.py | 1 - trezorlib/device.py | 2 -- trezorlib/firmware.py | 1 - trezorlib/log.py | 2 +- trezorlib/mapping.py | 1 - trezorlib/protocol_v1.py | 2 +- trezorlib/ripple.py | 2 -- .../tests/device_tests/test_msg_ethereum_signtx_eip155.py | 1 - trezorlib/tests/device_tests/test_msg_getaddress.py | 1 - trezorlib/tests/device_tests/test_msg_ripple_get_address.py | 3 +-- trezorlib/tests/device_tests/test_msg_stellar_get_address.py | 1 - .../tests/device_tests/test_msg_stellar_sign_transaction.py | 3 +-- trezorlib/tests/device_tests/test_protect_call.py | 1 - trezorlib/tests/support/ckd_public.py | 1 - trezorlib/transport/__init__.py | 2 +- trezorlib/transport/bridge.py | 1 - trezorlib/transport/hid.py | 1 - trezorlib/transport/udp.py | 2 -- trezorlib/transport/webusb.py | 1 - 21 files changed, 5 insertions(+), 27 deletions(-) diff --git a/trezorctl b/trezorctl index e4242a5e6c..cb65ea3286 100755 --- a/trezorctl +++ b/trezorctl @@ -26,7 +26,6 @@ import click import hashlib import io import json -import logging import os import sys diff --git a/trezorlib/client.py b/trezorlib/client.py index aad06ca73c..7b1e14fdc5 100644 --- a/trezorlib/client.py +++ b/trezorlib/client.py @@ -20,8 +20,6 @@ import os import sys import time import binascii -import hashlib -import unicodedata import getpass import warnings diff --git a/trezorlib/cosi.py b/trezorlib/cosi.py index 73ca36d3c2..e2a95f363a 100644 --- a/trezorlib/cosi.py +++ b/trezorlib/cosi.py @@ -14,7 +14,6 @@ # You should have received a copy of the License along with this library. # If not, see . -import sys from functools import reduce import binascii from typing import Iterable, Tuple diff --git a/trezorlib/device.py b/trezorlib/device.py index e8e3c1b5f2..ad6ea54118 100644 --- a/trezorlib/device.py +++ b/trezorlib/device.py @@ -14,13 +14,11 @@ # You should have received a copy of the License along with this library. # If not, see . -import binascii import os import warnings from mnemonic import Mnemonic from . import messages as proto -from . import tools from .tools import expect, session from .transport import enumerate_devices, get_transport diff --git a/trezorlib/firmware.py b/trezorlib/firmware.py index 1072deae15..905c9bc88a 100644 --- a/trezorlib/firmware.py +++ b/trezorlib/firmware.py @@ -1,6 +1,5 @@ import binascii import construct as c -import hashlib import pyblake2 from . import cosi diff --git a/trezorlib/log.py b/trezorlib/log.py index 69b8097284..1bc4f192a3 100644 --- a/trezorlib/log.py +++ b/trezorlib/log.py @@ -15,7 +15,7 @@ # If not, see . import logging -from typing import Set, Type, Optional +from typing import Optional from . import protobuf diff --git a/trezorlib/mapping.py b/trezorlib/mapping.py index 514465476f..5d39ea8ca6 100644 --- a/trezorlib/mapping.py +++ b/trezorlib/mapping.py @@ -15,7 +15,6 @@ # If not, see . from . import messages -from . import protobuf map_type_to_class = {} map_class_to_type = {} diff --git a/trezorlib/protocol_v1.py b/trezorlib/protocol_v1.py index 09167b9eb3..592f4f2300 100644 --- a/trezorlib/protocol_v1.py +++ b/trezorlib/protocol_v1.py @@ -19,7 +19,7 @@ from __future__ import absolute_import from io import BytesIO import logging import struct -from typing import Tuple, Type +from typing import Tuple from . import mapping from . import protobuf diff --git a/trezorlib/ripple.py b/trezorlib/ripple.py index d66227d215..3f18837f1b 100644 --- a/trezorlib/ripple.py +++ b/trezorlib/ripple.py @@ -14,8 +14,6 @@ # You should have received a copy of the License along with this library. # If not, see . -import base64 -import struct from . import messages from .tools import expect diff --git a/trezorlib/tests/device_tests/test_msg_ethereum_signtx_eip155.py b/trezorlib/tests/device_tests/test_msg_ethereum_signtx_eip155.py index 9f4290d3f3..c3942111b4 100644 --- a/trezorlib/tests/device_tests/test_msg_ethereum_signtx_eip155.py +++ b/trezorlib/tests/device_tests/test_msg_ethereum_signtx_eip155.py @@ -18,7 +18,6 @@ from binascii import unhexlify, hexlify import pytest from .common import TrezorTest -from trezorlib import messages as proto from trezorlib import ethereum from trezorlib.tools import H_ diff --git a/trezorlib/tests/device_tests/test_msg_getaddress.py b/trezorlib/tests/device_tests/test_msg_getaddress.py index d1d4f245ec..7ab8fbce0b 100644 --- a/trezorlib/tests/device_tests/test_msg_getaddress.py +++ b/trezorlib/tests/device_tests/test_msg_getaddress.py @@ -14,7 +14,6 @@ # You should have received a copy of the License along with this library. # If not, see . -import pytest from .common import TrezorTest from ..support import ckd_public as bip32 diff --git a/trezorlib/tests/device_tests/test_msg_ripple_get_address.py b/trezorlib/tests/device_tests/test_msg_ripple_get_address.py index ed4d420a07..d4fabe0144 100644 --- a/trezorlib/tests/device_tests/test_msg_ripple_get_address.py +++ b/trezorlib/tests/device_tests/test_msg_ripple_get_address.py @@ -18,9 +18,8 @@ import pytest from .common import TrezorTest from .conftest import TREZOR_VERSION -from binascii import hexlify from trezorlib.ripple import get_address -from trezorlib.tools import parse_path, CallException +from trezorlib.tools import parse_path from trezorlib import debuglink diff --git a/trezorlib/tests/device_tests/test_msg_stellar_get_address.py b/trezorlib/tests/device_tests/test_msg_stellar_get_address.py index 1a6385528c..e8c16e065c 100644 --- a/trezorlib/tests/device_tests/test_msg_stellar_get_address.py +++ b/trezorlib/tests/device_tests/test_msg_stellar_get_address.py @@ -18,7 +18,6 @@ import pytest from .common import TrezorTest from .conftest import TREZOR_VERSION -from binascii import hexlify from trezorlib import stellar from trezorlib import messages as proto from trezorlib.tools import parse_path, CallException diff --git a/trezorlib/tests/device_tests/test_msg_stellar_sign_transaction.py b/trezorlib/tests/device_tests/test_msg_stellar_sign_transaction.py index 12bc2830c9..f6dc26f7b1 100644 --- a/trezorlib/tests/device_tests/test_msg_stellar_sign_transaction.py +++ b/trezorlib/tests/device_tests/test_msg_stellar_sign_transaction.py @@ -48,8 +48,7 @@ from base64 import b64encode from .common import TrezorTest -from .conftest import TREZOR_VERSION -from binascii import hexlify, unhexlify +from binascii import hexlify from trezorlib import messages as proto from trezorlib import stellar from trezorlib.tools import parse_path diff --git a/trezorlib/tests/device_tests/test_protect_call.py b/trezorlib/tests/device_tests/test_protect_call.py index e1d73b2ab2..891890f7de 100644 --- a/trezorlib/tests/device_tests/test_protect_call.py +++ b/trezorlib/tests/device_tests/test_protect_call.py @@ -20,7 +20,6 @@ import pytest from .common import TrezorTest from trezorlib import messages as proto from trezorlib.client import PinException -from trezorlib.tools import CallException # FIXME TODO Add passphrase tests diff --git a/trezorlib/tests/support/ckd_public.py b/trezorlib/tests/support/ckd_public.py index b49cb5e5fb..4dc7a89567 100644 --- a/trezorlib/tests/support/ckd_public.py +++ b/trezorlib/tests/support/ckd_public.py @@ -17,7 +17,6 @@ import struct import hmac import hashlib -import sys import ecdsa from ecdsa.util import string_to_number, number_to_string diff --git a/trezorlib/transport/__init__.py b/trezorlib/transport/__init__.py index 4dbd369761..e26d561e34 100644 --- a/trezorlib/transport/__init__.py +++ b/trezorlib/transport/__init__.py @@ -17,7 +17,7 @@ import importlib import logging -from typing import Iterable, Type, List, Set +from typing import Iterable, Type LOG = logging.getLogger(__name__) diff --git a/trezorlib/transport/bridge.py b/trezorlib/transport/bridge.py index 15ded6b1d4..b225acc034 100644 --- a/trezorlib/transport/bridge.py +++ b/trezorlib/transport/bridge.py @@ -21,7 +21,6 @@ from io import BytesIO import struct from .. import mapping -from .. import messages from .. import protobuf from . import Transport, TransportException diff --git a/trezorlib/transport/hid.py b/trezorlib/transport/hid.py index 8a20c41326..9e509e3834 100644 --- a/trezorlib/transport/hid.py +++ b/trezorlib/transport/hid.py @@ -16,7 +16,6 @@ import time import hid -import os import sys from ..protocol_v1 import ProtocolV1 diff --git a/trezorlib/transport/udp.py b/trezorlib/transport/udp.py index 7943a23285..25b4f81106 100644 --- a/trezorlib/transport/udp.py +++ b/trezorlib/transport/udp.py @@ -14,11 +14,9 @@ # You should have received a copy of the License along with this library. # If not, see . -import os import socket from ..protocol_v1 import ProtocolV1 -from ..protocol_v2 import ProtocolV2 from . import Transport, TransportException diff --git a/trezorlib/transport/webusb.py b/trezorlib/transport/webusb.py index 23e81d5e96..6db2e22978 100644 --- a/trezorlib/transport/webusb.py +++ b/trezorlib/transport/webusb.py @@ -15,7 +15,6 @@ # If not, see . import time -import os import atexit import usb1 import sys From 8226742ea34f136b698f2dc3896075a2ba8ca383 Mon Sep 17 00:00:00 2001 From: matejcik Date: Fri, 10 Aug 2018 16:04:35 +0200 Subject: [PATCH 18/37] tools: drop signtest, it doesn't work and is messing with stylecheck --- tools/signtest.py | 233 ---------------------------------------------- 1 file changed, 233 deletions(-) delete mode 100755 tools/signtest.py diff --git a/tools/signtest.py b/tools/signtest.py deleted file mode 100755 index 90feb7a4aa..0000000000 --- a/tools/signtest.py +++ /dev/null @@ -1,233 +0,0 @@ -#!/usr/bin/env python -import binascii -import os -import random -import trezorlib.messages_pb2 as proto -import trezorlib.types_pb2 as proto_types -import trezorlib.tools as tools -import trezorlib.ckd_public as bip32 - -import hashlib -from trezorlib.client import TrezorClient -from trezorlib.tx_api import TxApiTestnet -from trezorlib.tx_api import TxApiBitcoin -from trezorlib.transport import get_transport - - -# This script has survived unmodified through several significant changes -# of the trezorlib library. While we want to have something like this, -# we're waiting on a couple more changes in order to implement this a little more cleanly. -# Wait for trezorlib v1.0. -raise Exception("This code is too old to run. Sorry.") - - -def hash160(x): - h = hashlib.new("ripemd160") - h.update(hashlib.sha256(x).digest()) - return h.digest() - - -def pack_varint(x): - if (x < 0xfd): - return chr(x) - else: - return '\xfd' + chr(x & 0xff) + chr((x >> 8) & 0xff) - - -def int_to_string(x, pad): - result = ['\x00'] * pad - while x > 0: - pad -= 1 - ordinal = x & 0xFF - result[pad] = (chr(ordinal)) - x >>= 8 - return ''.join(result) - - -def string_to_int(s): - result = 0 - for c in s: - if not isinstance(c, int): - c = ord(c) - result = (result << 8) + c - return result - - -class MyTxApiBitcoin(object): - - def set_publickey(self, node): - self.node = node.node - - def set_client(self, client): - self.client = client - - def serialize_tx(self, tx): - ser = '' - ser = ser + int_to_string(tx.version, 4)[::-1] - ser = ser + pack_varint(len(tx.inputs)) - for i in tx.inputs: - ser = ser + i.prev_hash[::-1] - ser = ser + int_to_string(i.prev_index, 4)[::-1] - ser = ser + pack_varint(len(i.script_sig)) + i.script_sig - ser = ser + int_to_string(i.sequence, 4)[::-1] - ser = ser + pack_varint(len(tx.bin_outputs)) - for o in tx.bin_outputs: - ser = ser + int_to_string(o.amount, 8)[::-1] - ser = ser + pack_varint(len(o.script_pubkey)) + o.script_pubkey - ser = ser + int_to_string(tx.lock_time, 4)[::-1] - return ser - - def create_inputs(self, numinputs, txsize): - idx = 0 - sum = 0 - self.inputs = [] - self.txs = {} - for nr in range(numinputs): - t = proto_types.TransactionType() - t.version = 1 - t.lock_time = 0 - i = t.inputs.add() - i.prev_hash = os.urandom(32) - i.prev_index = random.randint(0, 4) - i.script_sig = os.urandom(100) - i.sequence = 0xffffffff - if nr % 50 == 0: - print(nr) - myout = random.randint(0, txsize - 1) - segwit = random.randint(0, 2) - for vout in range(txsize): - o = t.bin_outputs.add() - o.amount = random.randint(10000, 1000000) - if vout == myout: - amount = o.amount - sum = sum + o.amount - node = self.node - path = [0, idx] - node = bip32.public_ckd(node, path) - idx = idx + 1 - pubkey = tools.hash_160(node.public_key) - else: - pubkey = os.urandom(20) - if segwit == 2: - # p2sh segwit - o.script_pubkey = b'\xa9\x14' + hash160(b'\x00\x14' + pubkey) + b'\x87' - elif segwit == 1: - o.script_pubkey = b'\x00\x14' + pubkey - else: - o.script_pubkey = b'\x76\xa9\x14' + pubkey + b'\x88\xac' - - txser = self.serialize_tx(t) - txhash = tools.btc_hash(txser)[::-1] - self.inputs.append( - proto_types.TxInputType( - address_n=self.client.expand_path("44'/0'/0'/0/%d" % idx), - script_type=( - proto_types.SPENDWITNESS if segwit == 1 else - proto_types.SPENDP2SHWITNESS if segwit == 2 else - proto_types.SPENDADDRESS - ), - prev_hash=txhash, - prev_index=myout, - amount=amount if segwit > 0 else 0 - )) - # print(binascii.hexlify(txser)) - # print(binascii.hexlify(txhash)) - self.txs[binascii.hexlify(txhash)] = t - - self.outputs = [ - proto_types.TxOutputType( - amount=sum, - script_type=proto_types.PAYTOADDRESS, - address_n=self.client.expand_path("44'/0'/0'/1/0") - )] - - def get_inputs(self): - return self.inputs - - def get_outputs(self): - return self.outputs - - def get_tx(self, txhash): - t = self.txs[txhash] - # print(t) - return t - - -def main(): - numinputs = 100 - sizeinputtx = 10 - - # Use first connected device - try: - transport = get_transport() - except Exception as e: - print(e) - return - - print(transport) - - 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() - - -if __name__ == '__main__': - main() From 29f928e4f288084398436e0b3a4f899ccda577d6 Mon Sep 17 00:00:00 2001 From: matejcik Date: Fri, 10 Aug 2018 16:05:14 +0200 Subject: [PATCH 19/37] style: bare excepts, left-over bad imports --- tools/encfs_aes_getpass.py | 4 +--- tools/mem_flashblock.py | 1 - tools/rng_entropy_collector.py | 1 - trezorctl | 4 ++-- trezorlib/cosi.py | 4 ++-- trezorlib/ethereum.py | 2 +- trezorlib/firmware.py | 4 ++-- trezorlib/nem.py | 2 +- trezorlib/protocol_v1.py | 4 +--- trezorlib/protocol_v2.py | 8 +++----- trezorlib/qt/pinmatrix.py | 3 +-- trezorlib/stellar.py | 2 +- trezorlib/transport/bridge.py | 2 +- trezorlib/transport/udp.py | 2 +- trezorlib/tx_api.py | 6 +++--- 15 files changed, 20 insertions(+), 29 deletions(-) diff --git a/tools/encfs_aes_getpass.py b/tools/encfs_aes_getpass.py index 31a526f0d4..56c8314e8a 100755 --- a/tools/encfs_aes_getpass.py +++ b/tools/encfs_aes_getpass.py @@ -1,6 +1,4 @@ #!/usr/bin/env python3 -from __future__ import print_function - ''' Use TREZOR as a hardware key for opening EncFS filesystem! @@ -62,7 +60,7 @@ def choose_device(devices): try: device_id = int(input()) return devices[device_id] - except: + except Exception: raise ValueError("Invalid choice, exiting...") diff --git a/tools/mem_flashblock.py b/tools/mem_flashblock.py index 6de4f7a8af..1df65deade 100755 --- a/tools/mem_flashblock.py +++ b/tools/mem_flashblock.py @@ -2,7 +2,6 @@ from trezorlib.debuglink import DebugLink from trezorlib.client import TrezorClient from trezorlib.transport import enumerate_devices -import binascii import sys sectoraddrs = [0x8000000, 0x8004000, 0x8008000, 0x800c000, diff --git a/tools/rng_entropy_collector.py b/tools/rng_entropy_collector.py index 1f4dcbcde4..421ecd59c9 100755 --- a/tools/rng_entropy_collector.py +++ b/tools/rng_entropy_collector.py @@ -4,7 +4,6 @@ # that has DEBUG_RNG == 1 as that will disable the user button # push confirmation -from __future__ import print_function import io import sys from trezorlib.client import TrezorClient diff --git a/trezorctl b/trezorctl index cb65ea3286..c1c30d0bca 100755 --- a/trezorctl +++ b/trezorctl @@ -96,10 +96,10 @@ def cli(ctx, path, verbose, is_json): def get_device(): try: device = get_transport(path, prefix_search=False) - except: + except Exception: try: device = get_transport(path, prefix_search=True) - except: + except Exception: click.echo("Failed to find a TREZOR device.") if path is not None: click.echo("Using path: {}".format(path)) diff --git a/trezorlib/cosi.py b/trezorlib/cosi.py index e2a95f363a..216f275174 100644 --- a/trezorlib/cosi.py +++ b/trezorlib/cosi.py @@ -21,7 +21,7 @@ from typing import Iterable, Tuple from . import messages from .tools import expect -from trezorlib import _ed25519 +from . import _ed25519 # XXX, these could be NewType's, but that would infect users of the cosi module with these types as well. # Unsure if we want that. @@ -90,7 +90,7 @@ def sign_with_privkey(digest: bytes, privkey: Ed25519PrivateKey, return Ed25519Signature(_ed25519.encodeint(S)) -### Client functions ### +# ====== Client functions ====== # @expect(messages.CosiCommitment) diff --git a/trezorlib/ethereum.py b/trezorlib/ethereum.py index 41a147f710..fcf1d91b5b 100644 --- a/trezorlib/ethereum.py +++ b/trezorlib/ethereum.py @@ -6,7 +6,7 @@ def int_to_big_endian(value): return value.to_bytes((value.bit_length() + 7) // 8, 'big') -### Client functions ### +# ====== Client functions ====== # @expect(proto.EthereumAddress, field="address") diff --git a/trezorlib/firmware.py b/trezorlib/firmware.py index 905c9bc88a..779ca1408a 100644 --- a/trezorlib/firmware.py +++ b/trezorlib/firmware.py @@ -130,12 +130,12 @@ def validate_firmware(filename): try: cosi.verify(header.signature, digest, global_pk) print("Signature OK") - except: + except Exception: print("Signature FAILED") raise -### Client functions ### +# ====== Client functions ====== # @tools.session diff --git a/trezorlib/nem.py b/trezorlib/nem.py index ee4ca1e446..c72e421828 100644 --- a/trezorlib/nem.py +++ b/trezorlib/nem.py @@ -167,7 +167,7 @@ def create_sign_tx(transaction): return msg -### Client functions ### +# ====== Client functions ====== # @expect(proto.NEMAddress, field="address") diff --git a/trezorlib/protocol_v1.py b/trezorlib/protocol_v1.py index 592f4f2300..fe2cf796ea 100644 --- a/trezorlib/protocol_v1.py +++ b/trezorlib/protocol_v1.py @@ -14,8 +14,6 @@ # You should have received a copy of the License along with this library. # If not, see . -from __future__ import absolute_import - from io import BytesIO import logging import struct @@ -79,7 +77,7 @@ class ProtocolV1: try: headerlen = struct.calcsize('>HL') msg_type, datalen = struct.unpack('>HL', chunk[3:3 + headerlen]) - except: + except Exception: raise RuntimeError('Cannot parse header') data = chunk[3 + headerlen:] diff --git a/trezorlib/protocol_v2.py b/trezorlib/protocol_v2.py index a9474ee217..97934767bf 100644 --- a/trezorlib/protocol_v2.py +++ b/trezorlib/protocol_v2.py @@ -14,8 +14,6 @@ # You should have received a copy of the License along with this library. # If not, see . -from __future__ import absolute_import - from io import BytesIO import logging import struct @@ -110,7 +108,7 @@ class ProtocolV2: try: headerlen = struct.calcsize('>BLLL') magic, session, msg_type, datalen = struct.unpack('>BLLL', chunk[:headerlen]) - except: + except Exception: raise RuntimeError('Cannot parse header') if magic != 0x01: raise RuntimeError('Unexpected magic character') @@ -122,7 +120,7 @@ class ProtocolV2: try: headerlen = struct.calcsize('>BLL') magic, session, sequence = struct.unpack('>BLL', chunk[:headerlen]) - except: + except Exception: raise RuntimeError('Cannot parse header') if magic != 0x02: raise RuntimeError('Unexpected magic characters') @@ -134,7 +132,7 @@ class ProtocolV2: try: headerlen = struct.calcsize('>BL') magic, session = struct.unpack('>BL', chunk[:headerlen]) - except: + except Exception: raise RuntimeError('Cannot parse header') if magic != 0x03: raise RuntimeError('Unexpected magic character') diff --git a/trezorlib/qt/pinmatrix.py b/trezorlib/qt/pinmatrix.py index 3603b589d0..e6850cf0cb 100644 --- a/trezorlib/qt/pinmatrix.py +++ b/trezorlib/qt/pinmatrix.py @@ -14,7 +14,6 @@ # You should have received a copy of the License along with this library. # If not, see . -from __future__ import print_function import sys import math @@ -22,7 +21,7 @@ try: from PyQt4.QtGui import (QPushButton, QLineEdit, QSizePolicy, QRegExpValidator, QLabel, QApplication, QWidget, QGridLayout, QVBoxLayout, QHBoxLayout) from PyQt4.QtCore import QObject, SIGNAL, QRegExp, Qt, QT_VERSION_STR -except: +except ImportError: from PyQt5.QtWidgets import (QPushButton, QLineEdit, QSizePolicy, QLabel, QApplication, QWidget, QGridLayout, QVBoxLayout, QHBoxLayout) from PyQt5.QtGui import QRegExpValidator diff --git a/trezorlib/stellar.py b/trezorlib/stellar.py index 62e0803130..803246d8bd 100644 --- a/trezorlib/stellar.py +++ b/trezorlib/stellar.py @@ -338,7 +338,7 @@ def _crc16_checksum(bytes): return crc & 0xffff -### Client functions ### +# ====== Client functions ====== # @expect(messages.StellarPublicKey, field="public_key") diff --git a/trezorlib/transport/bridge.py b/trezorlib/transport/bridge.py index b225acc034..98c03647f8 100644 --- a/trezorlib/transport/bridge.py +++ b/trezorlib/transport/bridge.py @@ -59,7 +59,7 @@ class BridgeTransport(Transport): if r.status_code != 200: raise TransportException('trezord: Could not enumerate devices' + get_error(r)) return [BridgeTransport(dev) for dev in r.json()] - except: + except Exception: return [] def open(self): diff --git a/trezorlib/transport/udp.py b/trezorlib/transport/udp.py index 25b4f81106..02a1fdda28 100644 --- a/trezorlib/transport/udp.py +++ b/trezorlib/transport/udp.py @@ -95,7 +95,7 @@ class UdpTransport(Transport): try: self.socket.sendall(b'PINGPING') resp = self.socket.recv(8) - except: + except Exception: pass return resp == b'PONGPONG' diff --git a/trezorlib/tx_api.py b/trezorlib/tx_api.py index f72ad63ab9..c827c86ca4 100644 --- a/trezorlib/tx_api.py +++ b/trezorlib/tx_api.py @@ -52,7 +52,7 @@ class TxApi(object): try: # looking into cache first j = json.load(open(cache_file), parse_float=str) return j - except: + except Exception: pass if not self.url: @@ -62,12 +62,12 @@ class TxApi(object): url = self.get_url(resource, resourceid) r = requests.get(url, headers={'User-agent': 'Mozilla/5.0'}) j = r.json(parse_float=str) - except: + except Exception: raise RuntimeError('URL error: %s' % url) if cache_dir and cache_file: try: # saving into cache json.dump(j, open(cache_file, 'w')) - except: + except Exception: pass return j From ae5341c1bd01c2ef998d2443fa6498c27c943fad Mon Sep 17 00:00:00 2001 From: matejcik Date: Fri, 10 Aug 2018 16:08:30 +0200 Subject: [PATCH 20/37] style: common config for flake8 and isort --- .flake8 | 26 -------------------------- setup.cfg | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 26 deletions(-) delete mode 100644 .flake8 create mode 100644 setup.cfg diff --git a/.flake8 b/.flake8 deleted file mode 100644 index 60680fc2b1..0000000000 --- a/.flake8 +++ /dev/null @@ -1,26 +0,0 @@ -[flake8] -filename = - *.py, - ./trezorctl -exclude = - .tox/, - build/, - dist/, - vendor/, -ignore = - # F401: module imported but unused - F401, - # E241: multiple spaces after ':' - E241, - # E402: module level import not at top of file - E402, - # E501: line too long - E501, - # E722: do not use bare except - E722, - # E741: ambiguous variable name - E741, - ##### E266: too many leading '#' for block comment - E266, - # W503 line break before binary operator - W503, diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000000..bbeaa43f4e --- /dev/null +++ b/setup.cfg @@ -0,0 +1,33 @@ +[flake8] +filename = + *.py, + ./trezorctl +exclude = + .tox/, + build/, + dist/, + vendor/, + trezorlib/messages/__init__.py +ignore = + # E203 whitespace before ':' + E203, + # E221: multiple spaces before operator + E221, + # E241: multiple spaces after ':' + E241, + # E402: module level import not at top of file + E402, + # E501: line too long + E501, + # E741 ambiguous variable name + E741, + # W503: line break before binary operator + W503 + +[isort] +multi_line_output = 3 +include_trailing_comma = True +force_grid_wrap = 0 +combine_as_imports = True +line_length = 88 +not_skip=__init__.py From e336f578af60c7f34e1fe72825a330c03c425de3 Mon Sep 17 00:00:00 2001 From: matejcik Date: Mon, 13 Aug 2018 15:38:04 +0200 Subject: [PATCH 21/37] device_tests: update test_msg_getentropy to new style --- .../tests/device_tests/test_msg_getentropy.py | 38 ++++++++++--------- 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/trezorlib/tests/device_tests/test_msg_getentropy.py b/trezorlib/tests/device_tests/test_msg_getentropy.py index fb65bbc6bc..9711414be9 100644 --- a/trezorlib/tests/device_tests/test_msg_getentropy.py +++ b/trezorlib/tests/device_tests/test_msg_getentropy.py @@ -15,32 +15,34 @@ # If not, see . import math -from .common import TrezorTest -from trezorlib import misc -import trezorlib.messages as proto +import pytest + +from trezorlib import messages as m, misc + +ENTROPY_LENGTHS_POW2 = [2 ** l for l in range(10)] +ENTROPY_LENGTHS_POW2_1 = [2 ** l + 1 for l in range(10)] + +ENTROPY_LENGTHS = ENTROPY_LENGTHS_POW2 + ENTROPY_LENGTHS_POW2_1 def entropy(data): counts = {} for c in data: - if c in counts: - counts[c] += 1 - else: - counts[c] = 1 + counts[c] = counts.get(c, 0) + 1 e = 0 - for _, v in counts.items(): - p = 1.0 * v / len(data) + for v in counts.values(): + p = v / len(data) e -= p * math.log(p, 256) return e -class TestMsgGetentropy(TrezorTest): - - def test_entropy(self): - for l in [0, 1, 2, 3, 4, 5, 8, 9, 16, 17, 32, 33, 64, 65, 128, 129, 256, 257, 512, 513, 1024]: - with self.client: - self.client.set_expected_responses([proto.ButtonRequest(code=proto.ButtonRequestType.ProtectCall), proto.Entropy()]) - ent = misc.get_entropy(self.client, l) - assert len(ent) == l - print('entropy = ', entropy(ent)) +@pytest.mark.parametrize("entropy_length", ENTROPY_LENGTHS) +def test_entropy(client, entropy_length): + with client: + client.set_expected_responses( + [m.ButtonRequest(code=m.ButtonRequestType.ProtectCall), m.Entropy()] + ) + ent = misc.get_entropy(client, entropy_length) + assert len(ent) == entropy_length + print("{} bytes: entropy = {}".format(entropy_length, entropy(ent))) From 3d3e9b67b45990ae227f99525bb6469d141ee26d Mon Sep 17 00:00:00 2001 From: matejcik Date: Mon, 13 Aug 2018 18:21:24 +0200 Subject: [PATCH 22/37] style: apply black/isort --- trezorctl | 890 +++++++---- trezorlib/_ed25519.py | 16 +- trezorlib/btc.py | 89 +- trezorlib/ckd_public.py | 4 +- trezorlib/client.py | 176 ++- trezorlib/coins.py | 24 +- trezorlib/cosi.py | 44 +- trezorlib/debuglink.py | 72 +- trezorlib/device.py | 93 +- trezorlib/ethereum.py | 26 +- trezorlib/firmware.py | 53 +- trezorlib/lisk.py | 12 +- trezorlib/log.py | 13 +- trezorlib/mapping.py | 16 +- trezorlib/misc.py | 65 +- trezorlib/nem.py | 33 +- trezorlib/protobuf.py | 55 +- trezorlib/protocol_v1.py | 38 +- trezorlib/protocol_v2.py | 76 +- trezorlib/qt/pinmatrix.py | 80 +- trezorlib/ripple.py | 13 +- trezorlib/stellar.py | 79 +- trezorlib/tests/device_tests/common.py | 37 +- trezorlib/tests/device_tests/conftest.py | 31 +- trezorlib/tests/device_tests/test_basic.py | 10 +- .../tests/device_tests/test_bip32_speed.py | 20 +- trezorlib/tests/device_tests/test_cancel.py | 45 +- trezorlib/tests/device_tests/test_cosi.py | 32 +- .../tests/device_tests/test_debuglink.py | 10 +- .../device_tests/test_msg_applysettings.py | 125 +- .../tests/device_tests/test_msg_changepin.py | 7 +- .../device_tests/test_msg_cipherkeyvalue.py | 164 +- .../device_tests/test_msg_clearsession.py | 73 +- .../test_msg_ethereum_getaddress.py | 33 +- .../test_msg_ethereum_signmessage.py | 16 +- .../device_tests/test_msg_ethereum_signtx.py | 319 ++-- .../test_msg_ethereum_signtx_eip155.py | 6 +- .../test_msg_ethereum_verifymessage.py | 20 +- .../tests/device_tests/test_msg_getaddress.py | 125 +- .../test_msg_getaddress_segwit.py | 87 +- .../test_msg_getaddress_segwit_native.py | 108 +- .../device_tests/test_msg_getaddress_show.py | 52 +- .../test_msg_getecdhsessionkey.py | 59 +- .../device_tests/test_msg_getpublickey.py | 133 +- .../test_msg_getpublickey_curve.py | 73 +- .../device_tests/test_msg_lisk_getaddress.py | 15 +- .../test_msg_lisk_getpublickey.py | 10 +- .../device_tests/test_msg_lisk_signmessage.py | 31 +- .../device_tests/test_msg_lisk_signtx.py | 274 ++-- .../test_msg_lisk_verifymessage.py | 50 +- .../tests/device_tests/test_msg_loaddevice.py | 87 +- .../device_tests/test_msg_loaddevice_xprv.py | 33 +- .../device_tests/test_msg_nem_getaddress.py | 16 +- .../test_msg_nem_signtx_mosaics.py | 244 ++- .../test_msg_nem_signtx_mosaics_t2.py | 159 +- .../test_msg_nem_signtx_multisig.py | 254 +-- .../test_msg_nem_signtx_others.py | 80 +- .../test_msg_nem_signtx_transfers.py | 405 ++--- trezorlib/tests/device_tests/test_msg_ping.py | 70 +- .../device_tests/test_msg_recoverydevice.py | 77 +- .../test_msg_recoverydevice_dryrun.py | 28 +- .../test_msg_recoverydevice_t2.py | 53 +- .../device_tests/test_msg_resetdevice.py | 84 +- .../test_msg_resetdevice_skipbackup.py | 56 +- .../device_tests/test_msg_resetdevice_t2.py | 71 +- .../test_msg_ripple_get_address.py | 27 +- .../device_tests/test_msg_ripple_sign_tx.py | 110 +- .../device_tests/test_msg_signidentity.py | 107 +- .../device_tests/test_msg_signmessage.py | 68 +- .../test_msg_signmessage_segwit.py | 84 +- .../test_msg_signmessage_segwit_native.py | 84 +- .../tests/device_tests/test_msg_signtx.py | 1368 +++++++++++++---- .../device_tests/test_msg_signtx_bcash.py | 588 +++++-- .../device_tests/test_msg_signtx_bgold.py | 562 +++++-- .../device_tests/test_msg_signtx_decred.py | 347 ++++- .../device_tests/test_msg_signtx_segwit.py | 368 +++-- .../test_msg_signtx_segwit_native.py | 820 +++++++--- .../device_tests/test_msg_signtx_zcash.py | 70 +- .../test_msg_stellar_get_address.py | 49 +- .../test_msg_stellar_get_public_key.py | 30 +- .../test_msg_stellar_sign_transaction.py | 114 +- .../device_tests/test_msg_verifymessage.py | 160 +- .../test_msg_verifymessage_segwit.py | 78 +- .../test_msg_verifymessage_segwit_native.py | 78 +- .../tests/device_tests/test_msg_wipedevice.py | 6 +- trezorlib/tests/device_tests/test_multisig.py | 224 ++- .../device_tests/test_multisig_change.py | 335 ++-- .../tests/device_tests/test_op_return.py | 159 +- .../tests/device_tests/test_protect_call.py | 21 +- .../device_tests/test_protection_levels.py | 244 +-- trezorlib/tests/device_tests/test_zerosig.py | 21 +- trezorlib/tests/support/ckd_public.py | 43 +- trezorlib/tests/unit_tests/test_ckd_public.py | 12 +- trezorlib/tests/unit_tests/test_cosi.py | 93 +- trezorlib/tests/unit_tests/test_nem.py | 14 +- trezorlib/tests/unit_tests/test_protobuf.py | 29 +- trezorlib/tests/unit_tests/test_stellar.py | 177 ++- trezorlib/tests/unit_tests/test_transport.py | 2 +- trezorlib/tests/unit_tests/test_tx_api.py | 67 +- trezorlib/tools.py | 49 +- trezorlib/transport/__init__.py | 37 +- trezorlib/transport/bridge.py | 74 +- trezorlib/transport/hid.py | 46 +- trezorlib/transport/udp.py | 28 +- trezorlib/transport/webusb.py | 37 +- trezorlib/tx_api.py | 81 +- 106 files changed, 8503 insertions(+), 4057 deletions(-) diff --git a/trezorctl b/trezorctl index c1c30d0bca..07888023b4 100755 --- a/trezorctl +++ b/trezorctl @@ -61,22 +61,28 @@ class ChoiceType(click.Choice): return self.typemap[value] -CHOICE_RECOVERY_DEVICE_TYPE = ChoiceType({ - 'scrambled': proto.RecoveryDeviceType.ScrambledWords, - 'matrix': proto.RecoveryDeviceType.Matrix, -}) +CHOICE_RECOVERY_DEVICE_TYPE = ChoiceType( + { + "scrambled": proto.RecoveryDeviceType.ScrambledWords, + "matrix": proto.RecoveryDeviceType.Matrix, + } +) -CHOICE_INPUT_SCRIPT_TYPE = ChoiceType({ - 'address': proto.InputScriptType.SPENDADDRESS, - 'segwit': proto.InputScriptType.SPENDWITNESS, - 'p2shsegwit': proto.InputScriptType.SPENDP2SHWITNESS, -}) +CHOICE_INPUT_SCRIPT_TYPE = ChoiceType( + { + "address": proto.InputScriptType.SPENDADDRESS, + "segwit": proto.InputScriptType.SPENDWITNESS, + "p2shsegwit": proto.InputScriptType.SPENDP2SHWITNESS, + } +) -CHOICE_OUTPUT_SCRIPT_TYPE = ChoiceType({ - 'address': proto.OutputScriptType.PAYTOADDRESS, - 'segwit': proto.OutputScriptType.PAYTOWITNESS, - 'p2shsegwit': proto.OutputScriptType.PAYTOP2SHWITNESS, -}) +CHOICE_OUTPUT_SCRIPT_TYPE = ChoiceType( + { + "address": proto.OutputScriptType.PAYTOADDRESS, + "segwit": proto.OutputScriptType.PAYTOWITNESS, + "p2shsegwit": proto.OutputScriptType.PAYTOP2SHWITNESS, + } +) def enable_logging(): @@ -84,10 +90,17 @@ def enable_logging(): log.OMITTED_MESSAGES.add(proto.Features) -@click.group(context_settings={'max_content_width': 400}) -@click.option('-p', '--path', help='Select device by specific path.', default=os.environ.get('TREZOR_PATH')) -@click.option('-v', '--verbose', is_flag=True, help='Show communication messages.') -@click.option('-j', '--json', 'is_json', is_flag=True, help='Print result as JSON object') +@click.group(context_settings={"max_content_width": 400}) +@click.option( + "-p", + "--path", + help="Select device by specific path.", + default=os.environ.get("TREZOR_PATH"), +) +@click.option("-v", "--verbose", is_flag=True, help="Show communication messages.") +@click.option( + "-j", "--json", "is_json", is_flag=True, help="Print result as JSON object" +) @click.pass_context def cli(ctx, path, verbose, is_json): if verbose: @@ -124,9 +137,9 @@ def print_result(res, path, verbose, is_json): for k, v in res.items(): if isinstance(v, dict): for kk, vv in v.items(): - click.echo('%s.%s: %s' % (k, kk, vv)) + click.echo("%s.%s: %s" % (k, kk, vv)) else: - click.echo('%s: %s' % (k, v)) + click.echo("%s: %s" % (k, v)) elif isinstance(res, protobuf.MessageType): click.echo(protobuf.format_message(res)) else: @@ -138,14 +151,15 @@ def print_result(res, path, verbose, is_json): # -@cli.command(name='list', help='List connected TREZOR devices.') +@cli.command(name="list", help="List connected TREZOR devices.") def ls(): return enumerate_devices() -@cli.command(help='Show version of trezorctl/trezorlib.') +@cli.command(help="Show version of trezorctl/trezorlib.") def version(): from trezorlib import __version__ as VERSION + return VERSION @@ -154,30 +168,35 @@ def version(): # -@cli.command(help='Send ping message.') -@click.argument('message') -@click.option('-b', '--button-protection', is_flag=True) -@click.option('-p', '--pin-protection', is_flag=True) -@click.option('-r', '--passphrase-protection', is_flag=True) +@cli.command(help="Send ping message.") +@click.argument("message") +@click.option("-b", "--button-protection", is_flag=True) +@click.option("-p", "--pin-protection", is_flag=True) +@click.option("-r", "--passphrase-protection", is_flag=True) @click.pass_obj def ping(connect, message, button_protection, pin_protection, passphrase_protection): - return connect().ping(message, button_protection=button_protection, pin_protection=pin_protection, passphrase_protection=passphrase_protection) + return connect().ping( + message, + button_protection=button_protection, + pin_protection=pin_protection, + passphrase_protection=passphrase_protection, + ) -@cli.command(help='Clear session (remove cached PIN, passphrase, etc.).') +@cli.command(help="Clear session (remove cached PIN, passphrase, etc.).") @click.pass_obj def clear_session(connect): return connect().clear_session() -@cli.command(help='Get example entropy.') -@click.argument('size', type=int) +@cli.command(help="Get example entropy.") +@click.argument("size", type=int) @click.pass_obj def get_entropy(connect, size): return binascii.hexlify(misc.get_entropy(connect(), size)) -@cli.command(help='Retrieve device features and settings.') +@cli.command(help="Retrieve device features and settings.") @click.pass_obj def get_features(connect): return connect().features @@ -188,49 +207,45 @@ def get_features(connect): # -@cli.command(help='Change new PIN or remove existing.') -@click.option('-r', '--remove', is_flag=True) +@cli.command(help="Change new PIN or remove existing.") +@click.option("-r", "--remove", is_flag=True) @click.pass_obj def change_pin(connect, remove): return device.change_pin(connect(), remove) -@cli.command(help='Enable passphrase.') +@cli.command(help="Enable passphrase.") @click.pass_obj def enable_passphrase(connect): return device.apply_settings(connect(), use_passphrase=True) -@cli.command(help='Disable passphrase.') +@cli.command(help="Disable passphrase.") @click.pass_obj def disable_passphrase(connect): return device.apply_settings(connect(), use_passphrase=False) -@cli.command(help='Set new device label.') -@click.option('-l', '--label') +@cli.command(help="Set new device label.") +@click.option("-l", "--label") @click.pass_obj def set_label(connect, label): return device.apply_settings(connect(), label=label) -@cli.command(help='Set passphrase source.') -@click.argument('source', type=int) +@cli.command(help="Set passphrase source.") +@click.argument("source", type=int) @click.pass_obj def set_passphrase_source(connect, source): return device.apply_settings(connect(), passphrase_source=source) -@cli.command(help='Set auto-lock delay (in seconds).') -@click.argument('delay', type=str) +@cli.command(help="Set auto-lock delay (in seconds).") +@click.argument("delay", type=str) @click.pass_obj def set_auto_lock_delay(connect, delay): value, unit = delay[:-1], delay[-1:] - units = { - 's': 1, - 'm': 60, - 'h': 3600, - } + units = {"s": 1, "m": 60, "h": 3600} if unit in units: seconds = float(value) * units[unit] else: @@ -238,94 +253,123 @@ def set_auto_lock_delay(connect, delay): return device.apply_settings(connect(), auto_lock_delay_ms=int(seconds * 1000)) -@cli.command(help='Set device flags.') -@click.argument('flags') +@cli.command(help="Set device flags.") +@click.argument("flags") @click.pass_obj def set_flags(connect, flags): flags = flags.lower() - if flags.startswith('0b'): + if flags.startswith("0b"): flags = int(flags, 2) - elif flags.startswith('0x'): + elif flags.startswith("0x"): flags = int(flags, 16) else: flags = int(flags) return device.apply_flags(connect(), flags=flags) -@cli.command(help='Set new homescreen.') -@click.option('-f', '--filename', default=None) +@cli.command(help="Set new homescreen.") +@click.option("-f", "--filename", default=None) @click.pass_obj def set_homescreen(connect, filename): if filename is None: - img = b'\x00' - elif filename.endswith('.toif'): - img = open(filename, 'rb').read() - if img[:8] != b'TOIf\x90\x00\x90\x00': - raise tools.CallException(proto.FailureType.DataError, 'File is not a TOIF file with size of 144x144') + img = b"\x00" + elif filename.endswith(".toif"): + img = open(filename, "rb").read() + if img[:8] != b"TOIf\x90\x00\x90\x00": + raise tools.CallException( + proto.FailureType.DataError, + "File is not a TOIF file with size of 144x144", + ) else: from PIL import Image + im = Image.open(filename) if im.size != (128, 64): - raise tools.CallException(proto.FailureType.DataError, 'Wrong size of the image') - im = im.convert('1') + raise tools.CallException( + proto.FailureType.DataError, "Wrong size of the image" + ) + im = im.convert("1") pix = im.load() img = bytearray(1024) for j in range(64): for i in range(128): if pix[i, j]: - o = (i + j * 128) - img[o // 8] |= (1 << (7 - o % 8)) + o = i + j * 128 + img[o // 8] |= 1 << (7 - o % 8) img = bytes(img) return device.apply_settings(connect(), homescreen=img) -@cli.command(help='Set U2F counter.') -@click.argument('counter', type=int) +@cli.command(help="Set U2F counter.") +@click.argument("counter", type=int) @click.pass_obj def set_u2f_counter(connect, counter): return device.set_u2f_counter(connect(), counter) -@cli.command(help='Reset device to factory defaults and remove all private data.') -@click.option('-b', '--bootloader', help='Wipe device in bootloader mode. This also erases the firmware.', is_flag=True) +@cli.command(help="Reset device to factory defaults and remove all private data.") +@click.option( + "-b", + "--bootloader", + help="Wipe device in bootloader mode. This also erases the firmware.", + is_flag=True, +) @click.pass_obj def wipe_device(connect, bootloader): client = connect() if bootloader: if not client.features.bootloader_mode: - click.echo('Please switch your device to bootloader mode.') + click.echo("Please switch your device to bootloader mode.") sys.exit(1) else: - click.echo('Wiping user data and firmware! Please confirm the action on your device ...') + click.echo( + "Wiping user data and firmware! Please confirm the action on your device ..." + ) else: if client.features.bootloader_mode: - click.echo('Your device is in bootloader mode. This operation would also erase firmware.') - click.echo('Specify "--bootloader" if that is what you want, or disconnect and reconnect device in normal mode.') - click.echo('Aborting.') + click.echo( + "Your device is in bootloader mode. This operation would also erase firmware." + ) + click.echo( + 'Specify "--bootloader" if that is what you want, or disconnect and reconnect device in normal mode.' + ) + click.echo("Aborting.") sys.exit(1) else: - click.echo('Wiping user data! Please confirm the action on your device ...') + click.echo("Wiping user data! Please confirm the action on your device ...") try: return device.wipe(connect()) except tools.CallException as e: - click.echo('Action failed: {} {}'.format(*e.args)) + click.echo("Action failed: {} {}".format(*e.args)) sys.exit(3) -@cli.command(help='Load custom configuration to the device.') -@click.option('-m', '--mnemonic') -@click.option('-e', '--expand', is_flag=True) -@click.option('-x', '--xprv') -@click.option('-p', '--pin', default='') -@click.option('-r', '--passphrase-protection', is_flag=True) -@click.option('-l', '--label', default='') -@click.option('-i', '--ignore-checksum', is_flag=True) -@click.option('-s', '--slip0014', is_flag=True) +@cli.command(help="Load custom configuration to the device.") +@click.option("-m", "--mnemonic") +@click.option("-e", "--expand", is_flag=True) +@click.option("-x", "--xprv") +@click.option("-p", "--pin", default="") +@click.option("-r", "--passphrase-protection", is_flag=True) +@click.option("-l", "--label", default="") +@click.option("-i", "--ignore-checksum", is_flag=True) +@click.option("-s", "--slip0014", is_flag=True) @click.pass_obj -def load_device(connect, mnemonic, expand, xprv, pin, passphrase_protection, label, ignore_checksum, slip0014): +def load_device( + connect, + mnemonic, + expand, + xprv, + pin, + passphrase_protection, + label, + ignore_checksum, + slip0014, +): if not mnemonic and not xprv and not slip0014: - raise tools.CallException(proto.FailureType.DataError, 'Please provide mnemonic or xprv') + raise tools.CallException( + proto.FailureType.DataError, "Please provide mnemonic or xprv" + ) client = connect() if mnemonic: @@ -335,62 +379,75 @@ def load_device(connect, mnemonic, expand, xprv, pin, passphrase_protection, lab pin, passphrase_protection, label, - 'english', + "english", ignore_checksum, - expand + expand, ) if xprv: return debuglink.load_device_by_xprv( - client, - xprv, - pin, - passphrase_protection, - label, - 'english' + client, xprv, pin, passphrase_protection, label, "english" ) if slip0014: return debuglink.load_device_by_mnemonic( - client, - ' '.join(['all'] * 12), - pin, - passphrase_protection, - 'SLIP-0014' + client, " ".join(["all"] * 12), pin, passphrase_protection, "SLIP-0014" ) -@cli.command(help='Start safe recovery workflow.') -@click.option('-w', '--words', type=click.Choice(['12', '18', '24']), default='24') -@click.option('-e', '--expand', is_flag=True) -@click.option('-p', '--pin-protection', is_flag=True) -@click.option('-r', '--passphrase-protection', is_flag=True) -@click.option('-l', '--label') -@click.option('-t', '--type', 'rec_type', type=CHOICE_RECOVERY_DEVICE_TYPE, default='scrambled') -@click.option('-d', '--dry-run', is_flag=True) +@cli.command(help="Start safe recovery workflow.") +@click.option("-w", "--words", type=click.Choice(["12", "18", "24"]), default="24") +@click.option("-e", "--expand", is_flag=True) +@click.option("-p", "--pin-protection", is_flag=True) +@click.option("-r", "--passphrase-protection", is_flag=True) +@click.option("-l", "--label") +@click.option( + "-t", "--type", "rec_type", type=CHOICE_RECOVERY_DEVICE_TYPE, default="scrambled" +) +@click.option("-d", "--dry-run", is_flag=True) @click.pass_obj -def recovery_device(connect, words, expand, pin_protection, passphrase_protection, label, rec_type, dry_run): +def recovery_device( + connect, + words, + expand, + pin_protection, + passphrase_protection, + label, + rec_type, + dry_run, +): return device.recover( connect(), int(words), passphrase_protection, pin_protection, label, - 'english', + "english", rec_type, expand, - dry_run + dry_run, ) -@cli.command(help='Perform device setup and generate new seed.') -@click.option('-e', '--entropy', is_flag=True) -@click.option('-t', '--strength', type=click.Choice(['128', '192', '256']), default='256') -@click.option('-r', '--passphrase-protection', is_flag=True) -@click.option('-p', '--pin-protection', is_flag=True) -@click.option('-l', '--label') -@click.option('-u', '--u2f-counter', default=0) -@click.option('-s', '--skip-backup', is_flag=True) +@cli.command(help="Perform device setup and generate new seed.") +@click.option("-e", "--entropy", is_flag=True) +@click.option( + "-t", "--strength", type=click.Choice(["128", "192", "256"]), default="256" +) +@click.option("-r", "--passphrase-protection", is_flag=True) +@click.option("-p", "--pin-protection", is_flag=True) +@click.option("-l", "--label") +@click.option("-u", "--u2f-counter", default=0) +@click.option("-s", "--skip-backup", is_flag=True) @click.pass_obj -def reset_device(connect, entropy, strength, passphrase_protection, pin_protection, label, u2f_counter, skip_backup): +def reset_device( + connect, + entropy, + strength, + passphrase_protection, + pin_protection, + label, + u2f_counter, + skip_backup, +): return device.reset( connect(), entropy, @@ -398,13 +455,13 @@ def reset_device(connect, entropy, strength, passphrase_protection, pin_protecti passphrase_protection, pin_protection, label, - 'english', + "english", u2f_counter, - skip_backup + skip_backup, ) -@cli.command(help='Perform device seed backup.') +@cli.command(help="Perform device seed backup.") @click.pass_obj def backup_device(connect): return device.backup(connect()) @@ -415,12 +472,12 @@ def backup_device(connect): # -@cli.command(help='Upload new firmware to device (must be in bootloader mode).') -@click.option('-f', '--filename') -@click.option('-u', '--url') -@click.option('-v', '--version') -@click.option('-s', '--skip-check', is_flag=True) -@click.option('--fingerprint', help='Expected firmware fingerprint in hex') +@cli.command(help="Upload new firmware to device (must be in bootloader mode).") +@click.option("-f", "--filename") +@click.option("-u", "--url") +@click.option("-v", "--version") +@click.option("-s", "--skip-check", is_flag=True) +@click.option("--fingerprint", help="Expected firmware fingerprint in hex") @click.pass_obj def firmware_update(connect, filename, url, version, skip_check, fingerprint): if sum(bool(x) for x in (filename, url, version)) > 1: @@ -435,22 +492,28 @@ def firmware_update(connect, filename, url, version, skip_check, fingerprint): firmware_version = client.features.major_version if filename: - fp = open(filename, 'rb').read() + fp = open(filename, "rb").read() elif url: import requests - click.echo('Downloading from', url) + + click.echo("Downloading from", url) r = requests.get(url) fp = r.content else: import requests - r = requests.get('https://wallet.trezor.io/data/firmware/{}/releases.json'.format(firmware_version)) + + r = requests.get( + "https://wallet.trezor.io/data/firmware/{}/releases.json".format( + firmware_version + ) + ) releases = r.json() def version_func(r): - return r['version'] + return r["version"] def version_string(r): - return '.'.join(map(str, version_func(r))) + return ".".join(map(str, version_func(r))) if version: try: @@ -460,19 +523,19 @@ def firmware_update(connect, filename, url, version, skip_check, fingerprint): sys.exit(1) else: release = max(releases, key=version_func) - click.echo('Fetching version: %s' % version_string(release)) + click.echo("Fetching version: %s" % version_string(release)) if not fingerprint: - fingerprint = release['fingerprint'] - url = 'https://wallet.trezor.io/' + release['url'] - click.echo('Downloading from %s' % url) + fingerprint = release["fingerprint"] + url = "https://wallet.trezor.io/" + release["url"] + click.echo("Downloading from %s" % url) r = requests.get(url) fp = r.content if not skip_check: - if fp[:8] == b'54525a52' or fp[:8] == b'54525a56': + if fp[:8] == b"54525a52" or fp[:8] == b"54525a56": fp = binascii.unhexlify(fp) - if fp[:4] != b'TRZR' and fp[:4] != b'TRZV': + if fp[:4] != b"TRZR" and fp[:4] != b"TRZV": click.echo("Trezor firmware header expected.") sys.exit(2) @@ -486,19 +549,22 @@ def firmware_update(connect, filename, url, version, skip_check, fingerprint): click.echo("Fingerprints do not match, aborting.") sys.exit(5) - click.echo('If asked, please confirm the action on your device ...') + click.echo("If asked, please confirm the action on your device ...") try: return firmware.update(client, fp=io.BytesIO(fp)) except tools.CallException as e: - if e.args[0] in (proto.FailureType.FirmwareError, proto.FailureType.ActionCancelled): + if e.args[0] in ( + proto.FailureType.FirmwareError, + proto.FailureType.ActionCancelled, + ): click.echo("Update aborted on device.") else: click.echo("Update failed: {} {}".format(*e.args)) sys.exit(3) -@cli.command(help='Perform a self-test.') +@cli.command(help="Perform a self-test.") @click.pass_obj def self_test(connect): return debuglink.self_test(connect()) @@ -509,37 +575,47 @@ def self_test(connect): # -@cli.command(help='Get address for specified path.') -@click.option('-c', '--coin', default='Bitcoin') -@click.option('-n', '--address', required=True, help="BIP-32 path, e.g. m/44'/0'/0'/0/0") -@click.option('-t', '--script-type', type=CHOICE_INPUT_SCRIPT_TYPE, default='address') -@click.option('-d', '--show-display', is_flag=True) +@cli.command(help="Get address for specified path.") +@click.option("-c", "--coin", default="Bitcoin") +@click.option( + "-n", "--address", required=True, help="BIP-32 path, e.g. m/44'/0'/0'/0/0" +) +@click.option("-t", "--script-type", type=CHOICE_INPUT_SCRIPT_TYPE, default="address") +@click.option("-d", "--show-display", is_flag=True) @click.pass_obj def get_address(connect, coin, address, script_type, show_display): client = connect() address_n = tools.parse_path(address) - return btc.get_address(client, coin, address_n, show_display, script_type=script_type) + return btc.get_address( + client, coin, address_n, show_display, script_type=script_type + ) -@cli.command(help='Get public node of given path.') -@click.option('-c', '--coin', default='Bitcoin') -@click.option('-n', '--address', required=True, help="BIP-32 path, e.g. m/44'/0'/0'") -@click.option('-e', '--curve') -@click.option('-d', '--show-display', is_flag=True) +@cli.command(help="Get public node of given path.") +@click.option("-c", "--coin", default="Bitcoin") +@click.option("-n", "--address", required=True, help="BIP-32 path, e.g. m/44'/0'/0'") +@click.option("-e", "--curve") +@click.option("-d", "--show-display", is_flag=True) @click.pass_obj def get_public_node(connect, coin, address, curve, show_display): client = connect() address_n = tools.parse_path(address) - result = btc.get_public_node(client, address_n, ecdsa_curve_name=curve, show_display=show_display, coin_name=coin) + result = btc.get_public_node( + client, + address_n, + ecdsa_curve_name=curve, + show_display=show_display, + coin_name=coin, + ) return { - 'node': { - 'depth': result.node.depth, - 'fingerprint': "%08x" % result.node.fingerprint, - 'child_num': result.node.child_num, - 'chain_code': binascii.hexlify(result.node.chain_code), - 'public_key': binascii.hexlify(result.node.public_key), + "node": { + "depth": result.node.depth, + "fingerprint": "%08x" % result.node.fingerprint, + "child_num": result.node.child_num, + "chain_code": binascii.hexlify(result.node.chain_code), + "public_key": binascii.hexlify(result.node.public_key), }, - 'xpub': result.xpub + "xpub": result.xpub, } @@ -547,8 +623,9 @@ def get_public_node(connect, coin, address, curve, show_display): # Signing options # -@cli.command(help='Sign transaction.') -@click.option('-c', '--coin', default='Bitcoin') + +@cli.command(help="Sign transaction.") +@click.option("-c", "--coin", default="Bitcoin") # @click.option('-n', '--address', required=True, help="BIP-32 path, e.g. m/44'/0'/0'/0/0") # @click.option('-t', '--script-type', type=CHOICE_INPUT_SCRIPT_TYPE, default='address') # @click.option('-o', '--output', required=True, help='Transaction output') @@ -560,92 +637,128 @@ def sign_tx(connect, coin): txapi = coins.tx_api[coin] else: click.echo('Coin "%s" is not recognized.' % coin, err=True) - click.echo('Supported coin types: %s' % ', '.join(coins.tx_api.keys()), err=True) + click.echo( + "Supported coin types: %s" % ", ".join(coins.tx_api.keys()), err=True + ) sys.exit(1) client.set_tx_api(txapi) def default_script_type(address_n): - script_type = 'address' + script_type = "address" if address_n is None: pass elif address_n[0] == tools.H_(49): - script_type = 'p2shsegwit' + script_type = "p2shsegwit" return script_type def outpoint(s): - txid, vout = s.split(':') + txid, vout = s.split(":") return binascii.unhexlify(txid), int(vout) inputs = [] while True: click.echo() - prev = click.prompt('Previous output to spend (txid:vout)', type=outpoint, default='') + prev = click.prompt( + "Previous output to spend (txid:vout)", type=outpoint, default="" + ) if not prev: break prev_hash, prev_index = prev - address_n = click.prompt('BIP-32 path to derive the key', type=tools.parse_path) - amount = click.prompt('Input amount (satoshis)', type=int, default=0) - sequence = click.prompt('Sequence Number to use (RBF opt-in enabled by default)', type=int, default=0xfffffffd) - script_type = click.prompt('Input type', type=CHOICE_INPUT_SCRIPT_TYPE, default=default_script_type(address_n)) - script_type = script_type if isinstance(script_type, int) else CHOICE_INPUT_SCRIPT_TYPE.typemap[script_type] + address_n = click.prompt("BIP-32 path to derive the key", type=tools.parse_path) + amount = click.prompt("Input amount (satoshis)", type=int, default=0) + sequence = click.prompt( + "Sequence Number to use (RBF opt-in enabled by default)", + type=int, + default=0xfffffffd, + ) + script_type = click.prompt( + "Input type", + type=CHOICE_INPUT_SCRIPT_TYPE, + default=default_script_type(address_n), + ) + script_type = ( + script_type + if isinstance(script_type, int) + else CHOICE_INPUT_SCRIPT_TYPE.typemap[script_type] + ) if txapi.bip115: - prev_output = txapi.get_tx(binascii.hexlify(prev_hash).decode("utf-8")).bin_outputs[prev_index] + prev_output = txapi.get_tx( + binascii.hexlify(prev_hash).decode("utf-8") + ).bin_outputs[prev_index] prev_blockhash = prev_output.block_hash prev_blockheight = prev_output.block_height - inputs.append(proto.TxInputType( - address_n=address_n, - prev_hash=prev_hash, - prev_index=prev_index, - amount=amount, - script_type=script_type, - sequence=sequence, - prev_block_hash_bip115=prev_blockhash, - prev_block_height_bip115=prev_blockheight, - )) + inputs.append( + proto.TxInputType( + address_n=address_n, + prev_hash=prev_hash, + prev_index=prev_index, + amount=amount, + script_type=script_type, + sequence=sequence, + prev_block_hash_bip115=prev_blockhash, + prev_block_height_bip115=prev_blockheight, + ) + ) if txapi.bip115: current_block_height = txapi.current_height() - block_height = current_block_height - 300 # Zencash recommendation for the better protection + block_height = ( + current_block_height - 300 + ) # Zencash recommendation for the better protection block_hash = txapi.get_block_hash(block_height) outputs = [] while True: click.echo() - address = click.prompt('Output address (for non-change output)', default='') + address = click.prompt("Output address (for non-change output)", default="") if address: address_n = None else: address = None - address_n = click.prompt('BIP-32 path (for change output)', type=tools.parse_path, default='') + address_n = click.prompt( + "BIP-32 path (for change output)", type=tools.parse_path, default="" + ) if not address_n: break - amount = click.prompt('Amount to spend (satoshis)', type=int) - script_type = click.prompt('Output type', type=CHOICE_OUTPUT_SCRIPT_TYPE, default=default_script_type(address_n)) - script_type = script_type if isinstance(script_type, int) else CHOICE_OUTPUT_SCRIPT_TYPE.typemap[script_type] - outputs.append(proto.TxOutputType( - address_n=address_n, - address=address, - amount=amount, - script_type=script_type, - block_hash_bip115=block_hash[::-1], # Blockhash passed in reverse order - block_height_bip115=block_height - )) + amount = click.prompt("Amount to spend (satoshis)", type=int) + script_type = click.prompt( + "Output type", + type=CHOICE_OUTPUT_SCRIPT_TYPE, + default=default_script_type(address_n), + ) + script_type = ( + script_type + if isinstance(script_type, int) + else CHOICE_OUTPUT_SCRIPT_TYPE.typemap[script_type] + ) + outputs.append( + proto.TxOutputType( + address_n=address_n, + address=address, + amount=amount, + script_type=script_type, + block_hash_bip115=block_hash[::-1], # Blockhash passed in reverse order + block_height_bip115=block_height, + ) + ) - tx_version = click.prompt('Transaction version', type=int, default=2) - tx_locktime = click.prompt('Transaction locktime', type=int, default=0) + tx_version = click.prompt("Transaction version", type=int, default=2) + tx_locktime = click.prompt("Transaction locktime", type=int, default=0) - _, serialized_tx = btc.sign_tx(client, coin, inputs, outputs, tx_version, tx_locktime) + _, serialized_tx = btc.sign_tx( + client, coin, inputs, outputs, tx_version, tx_locktime + ) client.close() click.echo() - click.echo('Signed Transaction:') + click.echo("Signed Transaction:") click.echo(binascii.hexlify(serialized_tx)) click.echo() - click.echo('Use the following form to broadcast it to the network:') + click.echo("Use the following form to broadcast it to the network:") click.echo(txapi.pushtx_url) @@ -654,67 +767,76 @@ def sign_tx(connect, coin): # -@cli.command(help='Sign message using address of given path.') -@click.option('-c', '--coin', default='Bitcoin') -@click.option('-n', '--address', required=True, help="BIP-32 path, e.g. m/44'/0'/0'/0/0") -@click.option('-t', '--script-type', type=click.Choice(['address', 'segwit', 'p2shsegwit']), default='address') -@click.argument('message') +@cli.command(help="Sign message using address of given path.") +@click.option("-c", "--coin", default="Bitcoin") +@click.option( + "-n", "--address", required=True, help="BIP-32 path, e.g. m/44'/0'/0'/0/0" +) +@click.option( + "-t", + "--script-type", + type=click.Choice(["address", "segwit", "p2shsegwit"]), + default="address", +) +@click.argument("message") @click.pass_obj def sign_message(connect, coin, address, message, script_type): client = connect() address_n = tools.parse_path(address) typemap = { - 'address': proto.InputScriptType.SPENDADDRESS, - 'segwit': proto.InputScriptType.SPENDWITNESS, - 'p2shsegwit': proto.InputScriptType.SPENDP2SHWITNESS, + "address": proto.InputScriptType.SPENDADDRESS, + "segwit": proto.InputScriptType.SPENDWITNESS, + "p2shsegwit": proto.InputScriptType.SPENDP2SHWITNESS, } script_type = typemap[script_type] res = btc.sign_message(client, coin, address_n, message, script_type) return { - 'message': message, - 'address': res.address, - 'signature': base64.b64encode(res.signature) + "message": message, + "address": res.address, + "signature": base64.b64encode(res.signature), } -@cli.command(help='Verify message.') -@click.option('-c', '--coin', default='Bitcoin') -@click.argument('address') -@click.argument('signature') -@click.argument('message') +@cli.command(help="Verify message.") +@click.option("-c", "--coin", default="Bitcoin") +@click.argument("address") +@click.argument("signature") +@click.argument("message") @click.pass_obj def verify_message(connect, coin, address, signature, message): signature = base64.b64decode(signature) return btc.verify_message(connect(), coin, address, signature, message) -@cli.command(help='Sign message with Ethereum address.') -@click.option('-n', '--address', required=True, help="BIP-32 path, e.g. m/44'/60'/0'/0/0") -@click.argument('message') +@cli.command(help="Sign message with Ethereum address.") +@click.option( + "-n", "--address", required=True, help="BIP-32 path, e.g. m/44'/60'/0'/0/0" +) +@click.argument("message") @click.pass_obj def ethereum_sign_message(connect, address, message): client = connect() address_n = tools.parse_path(address) ret = ethereum.sign_message(client, address_n, message) output = { - 'message': message, - 'address': '0x%s' % binascii.hexlify(ret.address).decode(), - 'signature': '0x%s' % binascii.hexlify(ret.signature).decode() + "message": message, + "address": "0x%s" % binascii.hexlify(ret.address).decode(), + "signature": "0x%s" % binascii.hexlify(ret.signature).decode(), } return output def ethereum_decode_hex(value): - if value.startswith('0x') or value.startswith('0X'): + if value.startswith("0x") or value.startswith("0X"): return binascii.unhexlify(value[2:]) else: return binascii.unhexlify(value) -@cli.command(help='Verify message signed with Ethereum address.') -@click.argument('address') -@click.argument('signature') -@click.argument('message') +@cli.command(help="Verify message signed with Ethereum address.") +@click.argument("address") +@click.argument("signature") +@click.argument("message") @click.pass_obj def ethereum_verify_message(connect, address, signature, message): address = ethereum_decode_hex(address) @@ -722,10 +844,10 @@ def ethereum_verify_message(connect, address, signature, message): return ethereum.verify_message(connect(), address, signature, message) -@cli.command(help='Encrypt value by given key and path.') -@click.option('-n', '--address', required=True, help="BIP-32 path, e.g. m/10016'/0") -@click.argument('key') -@click.argument('value') +@cli.command(help="Encrypt value by given key and path.") +@click.option("-n", "--address", required=True, help="BIP-32 path, e.g. m/10016'/0") +@click.argument("key") +@click.argument("value") @click.pass_obj def encrypt_keyvalue(connect, address, key, value): client = connect() @@ -734,10 +856,10 @@ def encrypt_keyvalue(connect, address, key, value): return binascii.hexlify(res) -@cli.command(help='Decrypt value by given key and path.') -@click.option('-n', '--address', required=True, help="BIP-32 path, e.g. m/10016'/0") -@click.argument('key') -@click.argument('value') +@cli.command(help="Decrypt value by given key and path.") +@click.option("-n", "--address", required=True, help="BIP-32 path, e.g. m/10016'/0") +@click.argument("key") +@click.argument("value") @click.pass_obj def decrypt_keyvalue(connect, address, key, value): client = connect() @@ -782,34 +904,72 @@ def decrypt_keyvalue(connect, address, key, value): # -@cli.command(help='Get Ethereum address in hex encoding.') -@click.option('-n', '--address', required=True, help="BIP-32 path, e.g. m/44'/60'/0'/0/0") -@click.option('-d', '--show-display', is_flag=True) +@cli.command(help="Get Ethereum address in hex encoding.") +@click.option( + "-n", "--address", required=True, help="BIP-32 path, e.g. m/44'/60'/0'/0/0" +) +@click.option("-d", "--show-display", is_flag=True) @click.pass_obj def ethereum_get_address(connect, address, show_display): client = connect() address_n = tools.parse_path(address) address = ethereum.get_address(client, address_n, show_display) - return '0x%s' % binascii.hexlify(address).decode() + return "0x%s" % binascii.hexlify(address).decode() -@cli.command(help='Sign (and optionally publish) Ethereum transaction. Use TO as destination address or set TO to "" for contract creation.') -@click.option('-a', '--host', default='localhost:8545', help='RPC port of ethereum node for automatic gas/nonce estimation and publishing') -@click.option('-c', '--chain-id', type=int, help='EIP-155 chain id (replay protection)') -@click.option('-n', '--address', required=True, help="BIP-32 path to source address, e.g., m/44'/60'/0'/0/0") -@click.option('-v', '--value', default='0', help='Ether amount to transfer, e.g. "100 milliether"') -@click.option('-g', '--gas-limit', type=int, help='Gas limit - Required for offline signing') -@click.option('-t', '--gas-price', help='Gas price, e.g. "20 nanoether" - Required for offline signing') -@click.option('-i', '--nonce', type=int, help='Transaction counter - Required for offline signing') -@click.option('-d', '--data', default='', help='Data as hex string, e.g. 0x12345678') -@click.option('-p', '--publish', is_flag=True, help='Publish transaction via RPC') -@click.option('-x', '--tx-type', type=int, help='TX type (used only for Wanchain)') -@click.argument('to') +@cli.command( + help='Sign (and optionally publish) Ethereum transaction. Use TO as destination address or set TO to "" for contract creation.' +) +@click.option( + "-a", + "--host", + default="localhost:8545", + help="RPC port of ethereum node for automatic gas/nonce estimation and publishing", +) +@click.option("-c", "--chain-id", type=int, help="EIP-155 chain id (replay protection)") +@click.option( + "-n", + "--address", + required=True, + help="BIP-32 path to source address, e.g., m/44'/60'/0'/0/0", +) +@click.option( + "-v", "--value", default="0", help='Ether amount to transfer, e.g. "100 milliether"' +) +@click.option( + "-g", "--gas-limit", type=int, help="Gas limit - Required for offline signing" +) +@click.option( + "-t", + "--gas-price", + help='Gas price, e.g. "20 nanoether" - Required for offline signing', +) +@click.option( + "-i", "--nonce", type=int, help="Transaction counter - Required for offline signing" +) +@click.option("-d", "--data", default="", help="Data as hex string, e.g. 0x12345678") +@click.option("-p", "--publish", is_flag=True, help="Publish transaction via RPC") +@click.option("-x", "--tx-type", type=int, help="TX type (used only for Wanchain)") +@click.argument("to") @click.pass_obj -def ethereum_sign_tx(connect, host, chain_id, address, value, gas_limit, gas_price, nonce, data, publish, to, tx_type): +def ethereum_sign_tx( + connect, + host, + chain_id, + address, + value, + gas_limit, + gas_price, + nonce, + data, + publish, + to, + tx_type, +): from ethjsonrpc import EthJsonRpc import rlp + # fmt: off ether_units = { 'wei': 1, 'kwei': 1000, @@ -831,20 +991,25 @@ def ethereum_sign_tx(connect, host, chain_id, address, value, gas_limit, gas_pri 'ether': 1000000000000000000, 'eth': 1000000000000000000, } + # fmt: on - if ' ' in value: - value, unit = value.split(' ', 1) + if " " in value: + value, unit = value.split(" ", 1) if unit.lower() not in ether_units: - raise tools.CallException(proto.Failure.DataError, 'Unrecognized ether unit %r' % unit) + raise tools.CallException( + proto.Failure.DataError, "Unrecognized ether unit %r" % unit + ) value = int(value) * ether_units[unit.lower()] else: value = int(value) if gas_price is not None: - if ' ' in gas_price: - gas_price, unit = gas_price.split(' ', 1) + if " " in gas_price: + gas_price, unit = gas_price.split(" ", 1) if unit.lower() not in ether_units: - raise tools.CallException(proto.Failure.DataError, 'Unrecognized gas price unit %r' % unit) + raise tools.CallException( + proto.Failure.DataError, "Unrecognized gas price unit %r" % unit + ) gas_price = int(gas_price) * ether_units[unit.lower()] else: gas_price = int(gas_price) @@ -856,14 +1021,16 @@ def ethereum_sign_tx(connect, host, chain_id, address, value, gas_limit, gas_pri client = connect() address_n = tools.parse_path(address) - address = '0x%s' % (binascii.hexlify(ethereum.get_address(client, address_n)).decode()) + address = "0x%s" % ( + binascii.hexlify(ethereum.get_address(client, address_n)).decode() + ) if gas_price is None or gas_limit is None or nonce is None or publish: - host, port = host.split(':') + host, port = host.split(":") eth = EthJsonRpc(host, int(port)) if not data: - data = '' + data = "" data = ethereum_decode_hex(data) if gas_price is None: @@ -873,8 +1040,9 @@ def ethereum_sign_tx(connect, host, chain_id, address, value, gas_limit, gas_pri gas_limit = eth.eth_estimateGas( to_address=to, from_address=address, - value=('0x%x' % value), - data='0x%s' % (binascii.hexlify(data).decode())) + value=("0x%x" % value), + data="0x%s" % (binascii.hexlify(data).decode()), + ) if nonce is None: nonce = eth.eth_getTransactionCount(address) @@ -889,21 +1057,24 @@ def ethereum_sign_tx(connect, host, chain_id, address, value, gas_limit, gas_pri to=to_address, value=value, data=data, - chain_id=chain_id) + chain_id=chain_id, + ) if tx_type is None: transaction = rlp.encode( - (nonce, gas_price, gas_limit, to_address, value, data) + sig) + (nonce, gas_price, gas_limit, to_address, value, data) + sig + ) else: transaction = rlp.encode( - (tx_type, nonce, gas_price, gas_limit, to_address, value, data) + sig) - tx_hex = '0x%s' % binascii.hexlify(transaction).decode() + (tx_type, nonce, gas_price, gas_limit, to_address, value, data) + sig + ) + tx_hex = "0x%s" % binascii.hexlify(transaction).decode() if publish: tx_hash = eth.eth_sendRawTransaction(tx_hex) - return 'Transaction published with ID: %s' % tx_hash + return "Transaction published with ID: %s" % tx_hash else: - return 'Signed raw transaction: %s' % tx_hex + return "Signed raw transaction: %s" % tx_hex # @@ -911,10 +1082,12 @@ def ethereum_sign_tx(connect, host, chain_id, address, value, gas_limit, gas_pri # -@cli.command(help='Get NEM address for specified path.') -@click.option('-n', '--address', required=True, help="BIP-32 path, e.g. m/44'/0'/43'/0/0") -@click.option('-N', '--network', type=int, default=0x68) -@click.option('-d', '--show-display', is_flag=True) +@cli.command(help="Get NEM address for specified path.") +@click.option( + "-n", "--address", required=True, help="BIP-32 path, e.g. m/44'/0'/43'/0/0" +) +@click.option("-N", "--network", type=int, default=0x68) +@click.option("-d", "--show-display", is_flag=True) @click.pass_obj def nem_get_address(connect, address, network, show_display): client = connect() @@ -922,10 +1095,16 @@ def nem_get_address(connect, address, network, show_display): return nem.get_address(client, address_n, network, show_display) -@cli.command(help='Sign (and optionally broadcast) NEM transaction.') -@click.option('-n', '--address', help='BIP-32 path to signing key') -@click.option('-f', '--file', type=click.File('r'), default='-', help='Transaction in NIS (RequestPrepareAnnounce) format') -@click.option('-b', '--broadcast', help='NIS to announce transaction to') +@cli.command(help="Sign (and optionally broadcast) NEM transaction.") +@click.option("-n", "--address", help="BIP-32 path to signing key") +@click.option( + "-f", + "--file", + type=click.File("r"), + default="-", + help="Transaction in NIS (RequestPrepareAnnounce) format", +) +@click.option("-b", "--broadcast", help="NIS to announce transaction to") @click.pass_obj def nem_sign_tx(connect, address, file, broadcast): client = connect() @@ -934,12 +1113,15 @@ def nem_sign_tx(connect, address, file, broadcast): payload = { "data": binascii.hexlify(transaction.data).decode(), - "signature": binascii.hexlify(transaction.signature).decode() + "signature": binascii.hexlify(transaction.signature).decode(), } if broadcast: import requests - return requests.post("{}/transaction/announce".format(broadcast), json=payload).json() + + return requests.post( + "{}/transaction/announce".format(broadcast), json=payload + ).json() else: return payload @@ -949,9 +1131,11 @@ def nem_sign_tx(connect, address, file, broadcast): # -@cli.command(help='Get Lisk address for specified path.') -@click.option('-n', '--address', required=True, help="BIP-32 path, e.g. m/44'/134'/0'/0'") -@click.option('-d', '--show-display', is_flag=True) +@cli.command(help="Get Lisk address for specified path.") +@click.option( + "-n", "--address", required=True, help="BIP-32 path, e.g. m/44'/134'/0'/0'" +) +@click.option("-d", "--show-display", is_flag=True) @click.pass_obj def lisk_get_address(connect, address, show_display): client = connect() @@ -959,23 +1143,30 @@ def lisk_get_address(connect, address, show_display): return lisk.get_address(client, address_n, show_display) -@cli.command(help='Get Lisk public key for specified path.') -@click.option('-n', '--address', required=True, help="BIP-32 path, e.g. m/44'/134'/0'/0'") -@click.option('-d', '--show-display', is_flag=True) +@cli.command(help="Get Lisk public key for specified path.") +@click.option( + "-n", "--address", required=True, help="BIP-32 path, e.g. m/44'/134'/0'/0'" +) +@click.option("-d", "--show-display", is_flag=True) @click.pass_obj def lisk_get_public_key(connect, address, show_display): client = connect() address_n = tools.parse_path(address) res = lisk.get_public_key(client, address_n, show_display) - output = { - "public_key": binascii.hexlify(res.public_key).decode() - } + output = {"public_key": binascii.hexlify(res.public_key).decode()} return output -@cli.command(help='Sign Lisk transaction.') -@click.option('-n', '--address', required=True, help="BIP-32 path to signing key, e.g. m/44'/134'/0'/0'") -@click.option('-f', '--file', type=click.File('r'), default='-', help='Transaction in JSON format') +@cli.command(help="Sign Lisk transaction.") +@click.option( + "-n", + "--address", + required=True, + help="BIP-32 path to signing key, e.g. m/44'/134'/0'/0'", +) +@click.option( + "-f", "--file", type=click.File("r"), default="-", help="Transaction in JSON format" +) # @click.option('-b', '--broadcast', help='Broadcast Lisk transaction') @click.pass_obj def lisk_sign_tx(connect, address, file): @@ -983,16 +1174,16 @@ def lisk_sign_tx(connect, address, file): address_n = tools.parse_path(address) transaction = lisk.sign_tx(client, address_n, json.load(file)) - payload = { - "signature": binascii.hexlify(transaction.signature).decode() - } + payload = {"signature": binascii.hexlify(transaction.signature).decode()} return payload -@cli.command(help='Sign message with Lisk address.') -@click.option('-n', '--address', required=True, help="BIP-32 path, e.g. m/44'/134'/0'/0'") -@click.argument('message') +@cli.command(help="Sign message with Lisk address.") +@click.option( + "-n", "--address", required=True, help="BIP-32 path, e.g. m/44'/134'/0'/0'" +) +@click.argument("message") @click.pass_obj def lisk_sign_message(connect, address, message): client = connect() @@ -1001,15 +1192,15 @@ def lisk_sign_message(connect, address, message): output = { "message": message, "public_key": binascii.hexlify(res.public_key).decode(), - "signature": binascii.hexlify(res.signature).decode() + "signature": binascii.hexlify(res.signature).decode(), } return output -@cli.command(help='Verify message signed with Lisk address.') -@click.argument('pubkey') -@click.argument('signature') -@click.argument('message') +@cli.command(help="Verify message signed with Lisk address.") +@click.argument("pubkey") +@click.argument("signature") +@click.argument("message") @click.pass_obj def lisk_verify_message(connect, pubkey, signature, message): signature = bytes.fromhex(signature) @@ -1022,9 +1213,11 @@ def lisk_verify_message(connect, pubkey, signature, message): # -@cli.command(help='Ask device to commit to CoSi signing.') -@click.option('-n', '--address', required=True, help="BIP-32 path, e.g. m/44'/0'/0'/0/0") -@click.argument('data') +@cli.command(help="Ask device to commit to CoSi signing.") +@click.option( + "-n", "--address", required=True, help="BIP-32 path, e.g. m/44'/0'/0'/0/0" +) +@click.argument("data") @click.pass_obj def cosi_commit(connect, address, data): client = connect() @@ -1032,24 +1225,38 @@ def cosi_commit(connect, address, data): return cosi.commit(client, address_n, binascii.unhexlify(data)) -@cli.command(help='Ask device to sign using CoSi.') -@click.option('-n', '--address', required=True, help="BIP-32 path, e.g. m/44'/0'/0'/0/0") -@click.argument('data') -@click.argument('global_commitment') -@click.argument('global_pubkey') +@cli.command(help="Ask device to sign using CoSi.") +@click.option( + "-n", "--address", required=True, help="BIP-32 path, e.g. m/44'/0'/0'/0/0" +) +@click.argument("data") +@click.argument("global_commitment") +@click.argument("global_pubkey") @click.pass_obj def cosi_sign(connect, address, data, global_commitment, global_pubkey): client = connect() address_n = tools.parse_path(address) - return cosi.sign(client, address_n, binascii.unhexlify(data), binascii.unhexlify(global_commitment), binascii.unhexlify(global_pubkey)) + return cosi.sign( + client, + address_n, + binascii.unhexlify(data), + binascii.unhexlify(global_commitment), + binascii.unhexlify(global_pubkey), + ) # # Stellar functions # -@cli.command(help='Get Stellar public address') -@click.option('-n', '--address', required=False, help="BIP32 path. Always use hardened paths and the m/44'/148'/ prefix", default=stellar.DEFAULT_BIP32_PATH) -@click.option('-d', '--show-display', is_flag=True) +@cli.command(help="Get Stellar public address") +@click.option( + "-n", + "--address", + required=False, + help="BIP32 path. Always use hardened paths and the m/44'/148'/ prefix", + default=stellar.DEFAULT_BIP32_PATH, +) +@click.option("-d", "--show-display", is_flag=True) @click.pass_obj def stellar_get_address(connect, address, show_display): client = connect() @@ -1057,9 +1264,15 @@ def stellar_get_address(connect, address, show_display): return stellar.get_address(client, address_n, show_display) -@cli.command(help='Get Stellar public key') -@click.option('-n', '--address', required=False, help="BIP32 path. Always use hardened paths and the m/44'/148'/ prefix", default=stellar.DEFAULT_BIP32_PATH) -@click.option('-d', '--show-display', is_flag=True) +@cli.command(help="Get Stellar public key") +@click.option( + "-n", + "--address", + required=False, + help="BIP32 path. Always use hardened paths and the m/44'/148'/ prefix", + default=stellar.DEFAULT_BIP32_PATH, +) +@click.option("-d", "--show-display", is_flag=True) @click.pass_obj def stellar_get_public_key(connect, address, show_display): client = connect() @@ -1067,10 +1280,22 @@ def stellar_get_public_key(connect, address, show_display): return binascii.hexlify(stellar.get_public_key(client, address_n, show_display)) -@cli.command(help='Sign a base64-encoded transaction envelope') -@click.option('-n', '--address', required=False, help="BIP32 path. Always use hardened paths and the m/44'/148'/ prefix", default=stellar.DEFAULT_BIP32_PATH) -@click.option('-n', '--network-passphrase', default=stellar.DEFAULT_NETWORK_PASSPHRASE, required=False, help="Network passphrase (blank for public network). Testnet is: 'Test SDF Network ; September 2015'") -@click.argument('b64envelope') +@cli.command(help="Sign a base64-encoded transaction envelope") +@click.option( + "-n", + "--address", + required=False, + help="BIP32 path. Always use hardened paths and the m/44'/148'/ prefix", + default=stellar.DEFAULT_BIP32_PATH, +) +@click.option( + "-n", + "--network-passphrase", + default=stellar.DEFAULT_NETWORK_PASSPHRASE, + required=False, + help="Network passphrase (blank for public network). Testnet is: 'Test SDF Network ; September 2015'", +) +@click.argument("b64envelope") @click.pass_obj def stellar_sign_transaction(connect, b64envelope, address, network_passphrase): client = connect() @@ -1084,9 +1309,11 @@ def stellar_sign_transaction(connect, b64envelope, address, network_passphrase): # # Ripple functions # -@cli.command(help='Get Ripple address') -@click.option('-n', '--address', required=True, help="BIP-32 path to key, e.g. m/44'/144'/0'/0/0") -@click.option('-d', '--show-display', is_flag=True) +@cli.command(help="Get Ripple address") +@click.option( + "-n", "--address", required=True, help="BIP-32 path to key, e.g. m/44'/144'/0'/0/0" +) +@click.option("-d", "--show-display", is_flag=True) @click.pass_obj def ripple_get_address(connect, address, show_display): client = connect() @@ -1094,9 +1321,13 @@ def ripple_get_address(connect, address, show_display): return ripple.get_address(client, address_n, show_display) -@cli.command(help='Sign Ripple transaction') -@click.option('-n', '--address', required=True, help="BIP-32 path to key, e.g. m/44'/144'/0'/0/0") -@click.option('-f', '--file', type=click.File('r'), default='-', help='Transaction in JSON format') +@cli.command(help="Sign Ripple transaction") +@click.option( + "-n", "--address", required=True, help="BIP-32 path to key, e.g. m/44'/144'/0'/0/0" +) +@click.option( + "-f", "--file", type=click.File("r"), default="-", help="Transaction in JSON format" +) @click.pass_obj def ripple_sign_tx(connect, address, file): client = connect() @@ -1110,10 +1341,11 @@ def ripple_sign_tx(connect, address, file): click.echo("Serialized tx including the signature:") click.echo(binascii.hexlify(result.serialized_tx)) + # # Main # -if __name__ == '__main__': +if __name__ == "__main__": cli() # pylint: disable=E1120 diff --git a/trezorlib/_ed25519.py b/trezorlib/_ed25519.py index 7470dea1a4..5e013e5bea 100644 --- a/trezorlib/_ed25519.py +++ b/trezorlib/_ed25519.py @@ -2,7 +2,7 @@ # modified for Python 3 by Jochen Hoenicke import hashlib -from typing import Tuple, NewType +from typing import NewType, Tuple Point = NewType("Point", Tuple[int, int]) @@ -17,7 +17,7 @@ def H(m: bytes) -> bytes: def expmod(b: int, e: int, m: int) -> int: if e < 0: - raise ValueError('negative exponent') + raise ValueError("negative exponent") if e == 0: return 1 t = expmod(b, e >> 1, m) ** 2 % m @@ -123,18 +123,18 @@ def decodepoint(s: bytes) -> Point: x = q - x P = Point((x, y)) if not isoncurve(P): - raise ValueError('decoding point that is not on curve') + raise ValueError("decoding point that is not on curve") return P def checkvalid(s: bytes, m: bytes, pk: bytes) -> None: if len(s) != b >> 2: - raise ValueError('signature length is wrong') + raise ValueError("signature length is wrong") if len(pk) != b >> 3: - raise ValueError('public-key length is wrong') - R = decodepoint(s[0:b >> 3]) + raise ValueError("public-key length is wrong") + R = decodepoint(s[0 : b >> 3]) A = decodepoint(pk) - S = decodeint(s[b >> 3:b >> 2]) + S = decodeint(s[b >> 3 : b >> 2]) h = Hint(encodepoint(R) + pk + m) if scalarmult(B, S) != edwards(R, scalarmult(A, h)): - raise ValueError('signature does not pass verification') + raise ValueError("signature does not pass verification") diff --git a/trezorlib/btc.py b/trezorlib/btc.py index f99ea885e0..a6e3b82642 100644 --- a/trezorlib/btc.py +++ b/trezorlib/btc.py @@ -1,37 +1,91 @@ from . import messages as proto -from .tools import expect, CallException, normalize_nfc, session +from .tools import CallException, expect, normalize_nfc, session @expect(proto.PublicKey) -def get_public_node(client, n, ecdsa_curve_name=None, show_display=False, coin_name=None): - return client.call(proto.GetPublicKey(address_n=n, ecdsa_curve_name=ecdsa_curve_name, show_display=show_display, coin_name=coin_name)) +def get_public_node( + client, n, ecdsa_curve_name=None, show_display=False, coin_name=None +): + return client.call( + proto.GetPublicKey( + address_n=n, + ecdsa_curve_name=ecdsa_curve_name, + show_display=show_display, + coin_name=coin_name, + ) + ) @expect(proto.Address, field="address") -def get_address(client, coin_name, n, show_display=False, multisig=None, script_type=proto.InputScriptType.SPENDADDRESS): +def get_address( + client, + coin_name, + n, + show_display=False, + multisig=None, + script_type=proto.InputScriptType.SPENDADDRESS, +): if multisig: - return client.call(proto.GetAddress(address_n=n, coin_name=coin_name, show_display=show_display, multisig=multisig, script_type=script_type)) + return client.call( + proto.GetAddress( + address_n=n, + coin_name=coin_name, + show_display=show_display, + multisig=multisig, + script_type=script_type, + ) + ) else: - return client.call(proto.GetAddress(address_n=n, coin_name=coin_name, show_display=show_display, script_type=script_type)) + return client.call( + proto.GetAddress( + address_n=n, + coin_name=coin_name, + show_display=show_display, + script_type=script_type, + ) + ) @expect(proto.MessageSignature) -def sign_message(client, coin_name, n, message, script_type=proto.InputScriptType.SPENDADDRESS): +def sign_message( + client, coin_name, n, message, script_type=proto.InputScriptType.SPENDADDRESS +): message = normalize_nfc(message) - return client.call(proto.SignMessage(coin_name=coin_name, address_n=n, message=message, script_type=script_type)) + return client.call( + proto.SignMessage( + coin_name=coin_name, address_n=n, message=message, script_type=script_type + ) + ) def verify_message(client, coin_name, address, signature, message): message = normalize_nfc(message) try: - resp = client.call(proto.VerifyMessage(address=address, signature=signature, message=message, coin_name=coin_name)) + resp = client.call( + proto.VerifyMessage( + address=address, + signature=signature, + message=message, + coin_name=coin_name, + ) + ) except CallException as e: resp = e return isinstance(resp, proto.Success) @session -def sign_tx(client, coin_name, inputs, outputs, version=None, lock_time=None, expiry=None, overwintered=None, debug_processor=None): +def sign_tx( + client, + coin_name, + inputs, + outputs, + version=None, + lock_time=None, + expiry=None, + overwintered=None, + debug_processor=None, +): # start = time.time() txes = client._prepare_sign_tx(inputs, outputs) @@ -52,7 +106,7 @@ def sign_tx(client, coin_name, inputs, outputs, version=None, lock_time=None, ex # Prepare structure for signatures signatures = [None] * len(inputs) - serialized_tx = b'' + serialized_tx = b"" counter = 0 while True: @@ -71,7 +125,10 @@ def sign_tx(client, coin_name, inputs, outputs, version=None, lock_time=None, ex if res.serialized and res.serialized.signature_index is not None: if signatures[res.serialized.signature_index] is not None: - raise ValueError("Signature for index %d already filled" % res.serialized.signature_index) + raise ValueError( + "Signature for index %d already filled" + % res.serialized.signature_index + ) signatures[res.serialized.signature_index] = res.serialized.signature if res.request_type == proto.RequestType.TXFINISHED: @@ -93,7 +150,9 @@ def sign_tx(client, coin_name, inputs, outputs, version=None, lock_time=None, ex msg.outputs_cnt = len(current_tx.bin_outputs) else: msg.outputs_cnt = len(current_tx.outputs) - msg.extra_data_len = len(current_tx.extra_data) if current_tx.extra_data else 0 + msg.extra_data_len = ( + len(current_tx.extra_data) if current_tx.extra_data else 0 + ) res = client.call(proto.TxAck(tx=msg)) continue @@ -104,6 +163,7 @@ def sign_tx(client, coin_name, inputs, outputs, version=None, lock_time=None, ex # msg needs to be deep copied so when it's modified # the other messages stay intact from copy import deepcopy + msg = deepcopy(msg) # If debug_processor function is provided, # pass thru it the request and prepared response. @@ -124,6 +184,7 @@ def sign_tx(client, coin_name, inputs, outputs, version=None, lock_time=None, ex # msg needs to be deep copied so when it's modified # the other messages stay intact from copy import deepcopy + msg = deepcopy(msg) # If debug_processor function is provided, # pass thru it the request and prepared response. @@ -136,7 +197,7 @@ def sign_tx(client, coin_name, inputs, outputs, version=None, lock_time=None, ex elif res.request_type == proto.RequestType.TXEXTRADATA: o, l = res.details.extra_data_offset, res.details.extra_data_len msg = proto.TransactionType() - msg.extra_data = current_tx.extra_data[o:o + l] + msg.extra_data = current_tx.extra_data[o : o + l] res = client.call(proto.TxAck(tx=msg)) continue diff --git a/trezorlib/ckd_public.py b/trezorlib/ckd_public.py index ddb13983fa..0bb1ea9c16 100644 --- a/trezorlib/ckd_public.py +++ b/trezorlib/ckd_public.py @@ -16,6 +16,6 @@ import warnings -warnings.warn("ckd_public module is deprecated and will be removed", DeprecationWarning) - from .tests.support.ckd_public import * # noqa + +warnings.warn("ckd_public module is deprecated and will be removed", DeprecationWarning) diff --git a/trezorlib/client.py b/trezorlib/client.py index 7b1e14fdc5..2f64a4984e 100644 --- a/trezorlib/client.py +++ b/trezorlib/client.py @@ -14,22 +14,32 @@ # You should have received a copy of the License along with this library. # If not, see . +import binascii import functools +import getpass import logging import os import sys import time -import binascii -import getpass import warnings from mnemonic import Mnemonic -from . import messages as proto -from . import btc, cosi, device, ethereum, firmware, lisk, misc, nem, stellar -from . import mapping -from . import tools -from . import debuglink +from . import ( + btc, + cosi, + debuglink, + device, + ethereum, + firmware, + lisk, + mapping, + messages as proto, + misc, + nem, + stellar, + tools, +) if sys.version_info.major < 3: raise Exception("Trezorlib does not support Python 2 anymore.") @@ -42,6 +52,7 @@ LOG = logging.getLogger(__name__) try: import termios import tty + # POSIX system. Create and return a getch that manipulates the tty. # On Windows, termios will fail to import. @@ -55,6 +66,7 @@ try: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch + except ImportError: # Windows system. # Use msvcrt's getch function. @@ -67,12 +79,16 @@ except ImportError: # skip special keys: read the scancode and repeat msvcrt.getch() continue - return key.decode('latin1') + return key.decode("latin1") def get_buttonrequest_value(code): # Converts integer code to its string representation of ButtonRequestType - return [k for k in dir(proto.ButtonRequestType) if getattr(proto.ButtonRequestType, k) == code][0] + return [ + k + for k in dir(proto.ButtonRequestType) + if getattr(proto.ButtonRequestType, k) == code + ][0] class PinException(tools.CallException): @@ -81,13 +97,18 @@ class PinException(tools.CallException): class MovedTo: """Deprecation redirector for methods that were formerly part of TrezorClient""" + def __init__(self, where): self.where = where - self.name = where.__module__ + '.' + where.__name__ + self.name = where.__module__ + "." + where.__name__ def _deprecated_redirect(self, client, *args, **kwargs): """Redirector for a deprecated method on TrezorClient""" - warnings.warn("Function has been moved to %s" % self.name, DeprecationWarning, stacklevel=2) + warnings.warn( + "Function has been moved to %s" % self.name, + DeprecationWarning, + stacklevel=2, + ) return self.where(client, *args, **kwargs) def __get__(self, instance, cls): @@ -113,7 +134,7 @@ class BaseClient(object): @tools.session def call_raw(self, msg): - __tracebackhide__ = True # pytest traceback hiding - this function won't appear in tracebacks + __tracebackhide__ = True # for pytest # pylint: disable=W0612 self.transport.write(msg) return self.transport.read() @@ -126,20 +147,25 @@ class BaseClient(object): if handler is not None: msg = handler(resp) if msg is None: - raise ValueError("Callback %s must return protobuf message, not None" % handler) + raise ValueError( + "Callback %s must return protobuf message, not None" % handler + ) resp = self.call(msg) return resp def callback_Failure(self, msg): - if msg.code in (proto.FailureType.PinInvalid, - proto.FailureType.PinCancelled, proto.FailureType.PinExpected): + if msg.code in ( + proto.FailureType.PinInvalid, + proto.FailureType.PinCancelled, + proto.FailureType.PinExpected, + ): raise PinException(msg.code, msg.message) raise tools.CallException(msg.code, msg.message) def register_message(self, msg): - '''Allow application to register custom protobuf message type''' + """Allow application to register custom protobuf message type""" mapping.register_message(msg) @@ -164,21 +190,27 @@ class TextUIMixin(object): def callback_RecoveryMatrix(self, msg): if self.recovery_matrix_first_pass: self.recovery_matrix_first_pass = False - self.print("Use the numeric keypad to describe positions. For the word list use only left and right keys.") + self.print( + "Use the numeric keypad to describe positions. For the word list use only left and right keys." + ) self.print("Use backspace to correct an entry. The keypad layout is:") self.print(" 7 8 9 7 | 9") self.print(" 4 5 6 4 | 6") self.print(" 1 2 3 1 | 3") while True: character = getch() - if character in ('\x03', '\x04'): + if character in ("\x03", "\x04"): return proto.Cancel() - if character in ('\x08', '\x7f'): - return proto.WordAck(word='\x08') + if character in ("\x08", "\x7f"): + return proto.WordAck(word="\x08") # ignore middle column if only 6 keys requested. - if msg.type == proto.WordRequestType.Matrix6 and character in ('2', '5', '8'): + if msg.type == proto.WordRequestType.Matrix6 and character in ( + "2", + "5", + "8", + ): continue if character.isdigit(): @@ -186,22 +218,24 @@ class TextUIMixin(object): def callback_PinMatrixRequest(self, msg): if msg.type == proto.PinMatrixRequestType.Current: - desc = 'current PIN' + desc = "current PIN" elif msg.type == proto.PinMatrixRequestType.NewFirst: - desc = 'new PIN' + desc = "new PIN" elif msg.type == proto.PinMatrixRequestType.NewSecond: - desc = 'new PIN again' + desc = "new PIN again" else: - desc = 'PIN' + desc = "PIN" - self.print("Use the numeric keypad to describe number positions. The layout is:") + self.print( + "Use the numeric keypad to describe number positions. The layout is:" + ) self.print(" 7 8 9") self.print(" 4 5 6") self.print(" 1 2 3") self.print("Please enter %s: " % desc) - pin = getpass.getpass('') + pin = getpass.getpass("") if not pin.isdigit(): - raise ValueError('Non-numerical PIN provided') + raise ValueError("Non-numerical PIN provided") return proto.PinMatrixAck(pin=pin) def callback_PassphraseRequest(self, msg): @@ -214,9 +248,9 @@ class TextUIMixin(object): return proto.PassphraseAck(passphrase=passphrase) self.print("Passphrase required: ") - passphrase = getpass.getpass('') + passphrase = getpass.getpass("") self.print("Confirm your Passphrase: ") - if passphrase == getpass.getpass(''): + if passphrase == getpass.getpass(""): passphrase = Mnemonic.normalize_string(passphrase) return proto.PassphraseAck(passphrase=passphrase) else: @@ -227,8 +261,7 @@ class TextUIMixin(object): return proto.PassphraseStateAck() def callback_WordRequest(self, msg): - if msg.type in (proto.WordRequestType.Matrix9, - proto.WordRequestType.Matrix6): + if msg.type in (proto.WordRequestType.Matrix9, proto.WordRequestType.Matrix6): return self.callback_RecoveryMatrix(msg) self.print("Enter one word of mnemonic: ") word = input() @@ -247,7 +280,7 @@ class DebugLinkMixin(object): # of unit testing, because it will fail to work # without special DebugLink interface provided # by the device. - DEBUG = LOG.getChild('debug_link').debug + DEBUG = LOG.getChild("debug_link").debug def __init__(self, *args, **kwargs): super(DebugLinkMixin, self).__init__(*args, **kwargs) @@ -263,7 +296,7 @@ class DebugLinkMixin(object): self.expected_responses = None # Use blank passphrase - self.set_passphrase('') + self.set_passphrase("") def close(self): super(DebugLinkMixin, self).close() @@ -291,8 +324,10 @@ class DebugLinkMixin(object): # return isinstance(value, TypeError) # Evaluate missed responses in 'with' statement if self.expected_responses is not None and len(self.expected_responses): - raise RuntimeError("Some of expected responses didn't come from device: %s" % - [repr(x) for x in self.expected_responses]) + raise RuntimeError( + "Some of expected responses didn't come from device: %s" + % [repr(x) for x in self.expected_responses] + ) # Cleanup self.expected_responses = None @@ -311,13 +346,14 @@ class DebugLinkMixin(object): self.passphrase = Mnemonic.normalize_string(passphrase) def set_mnemonic(self, mnemonic): - self.mnemonic = Mnemonic.normalize_string(mnemonic).split(' ') + self.mnemonic = Mnemonic.normalize_string(mnemonic).split(" ") def call_raw(self, msg): - __tracebackhide__ = True # pytest traceback hiding - this function won't appear in tracebacks + __tracebackhide__ = True # for pytest # pylint: disable=W0612 if SCREENSHOT and self.debug: from PIL import Image + layout = self.debug.read_layout() im = Image.new("RGB", (128, 64)) pix = im.load() @@ -326,7 +362,7 @@ class DebugLinkMixin(object): rx, ry = 127 - x, 63 - y if (ord(layout[rx + (ry / 8) * 128]) & (1 << (ry % 8))) > 0: pix[x, y] = (255, 255, 255) - im.save('scr%05d.png' % self.screenshot_id) + im.save("scr%05d.png" % self.screenshot_id) self.screenshot_id += 1 resp = super(DebugLinkMixin, self).call_raw(msg) @@ -334,25 +370,31 @@ class DebugLinkMixin(object): return resp def _check_request(self, msg): - __tracebackhide__ = True # pytest traceback hiding - this function won't appear in tracebacks + __tracebackhide__ = True # for pytest # pylint: disable=W0612 if self.expected_responses is not None: try: expected = self.expected_responses.pop(0) except IndexError: - raise AssertionError(proto.FailureType.UnexpectedMessage, - "Got %s, but no message has been expected" % repr(msg)) + raise AssertionError( + proto.FailureType.UnexpectedMessage, + "Got %s, but no message has been expected" % repr(msg), + ) if msg.__class__ != expected.__class__: - raise AssertionError(proto.FailureType.UnexpectedMessage, - "Expected %s, got %s" % (repr(expected), repr(msg))) + raise AssertionError( + proto.FailureType.UnexpectedMessage, + "Expected %s, got %s" % (repr(expected), repr(msg)), + ) for field, value in expected.__dict__.items(): if value is None or value == []: continue if getattr(msg, field) != value: - raise AssertionError(proto.FailureType.UnexpectedMessage, - "Expected %s, got %s" % (repr(expected), repr(msg))) + raise AssertionError( + proto.FailureType.UnexpectedMessage, + "Expected %s, got %s" % (repr(expected), repr(msg)), + ) def callback_ButtonRequest(self, msg): self.DEBUG("ButtonRequest code: " + get_buttonrequest_value(msg.code)) @@ -368,7 +410,7 @@ class DebugLinkMixin(object): if self.pin_correct: pin = self.debug.read_pin_encoded() else: - pin = '444222' + pin = "444222" return proto.PinMatrixAck(pin=pin) def callback_PassphraseRequest(self, msg): @@ -380,7 +422,7 @@ class DebugLinkMixin(object): def callback_WordRequest(self, msg): (word, pos) = self.debug.read_recovery_word() - if word != '': + if word != "": return proto.WordAck(word=word) if pos != 0: return proto.WordAck(word=self.mnemonic[pos - 1]) @@ -389,7 +431,7 @@ class DebugLinkMixin(object): class ProtocolMixin(object): - VENDORS = ('bitcointrezor.com', 'trezor.io') + VENDORS = ("bitcointrezor.com", "trezor.io") def __init__(self, state=None, *args, **kwargs): super(ProtocolMixin, self).__init__(*args, **kwargs) @@ -410,15 +452,27 @@ class ProtocolMixin(object): @staticmethod def expand_path(n): - warnings.warn('expand_path is deprecated, use tools.parse_path', DeprecationWarning, stacklevel=2) + warnings.warn( + "expand_path is deprecated, use tools.parse_path", + DeprecationWarning, + stacklevel=2, + ) return tools.parse_path(n) @tools.expect(proto.Success, field="message") - def ping(self, msg, button_protection=False, pin_protection=False, passphrase_protection=False): - msg = proto.Ping(message=msg, - button_protection=button_protection, - pin_protection=pin_protection, - passphrase_protection=passphrase_protection) + def ping( + self, + msg, + button_protection=False, + pin_protection=False, + passphrase_protection=False, + ): + msg = proto.Ping( + message=msg, + button_protection=button_protection, + pin_protection=pin_protection, + passphrase_protection=passphrase_protection, + ) return self.call(msg) def get_device_id(self): @@ -435,14 +489,18 @@ class ProtocolMixin(object): if inp.prev_hash in txes: continue - if inp.script_type in (proto.InputScriptType.SPENDP2SHWITNESS, - proto.InputScriptType.SPENDWITNESS): + if inp.script_type in ( + proto.InputScriptType.SPENDP2SHWITNESS, + proto.InputScriptType.SPENDWITNESS, + ): continue if not self.tx_api: - raise RuntimeError('TX_API not defined') + raise RuntimeError("TX_API not defined") - prev_tx = self.tx_api.get_tx(binascii.hexlify(inp.prev_hash).decode('utf-8')) + prev_tx = self.tx_api.get_tx( + binascii.hexlify(inp.prev_hash).decode("utf-8") + ) txes[inp.prev_hash] = prev_tx return txes diff --git a/trezorlib/coins.py b/trezorlib/coins.py index 741b9bcf41..d81c7e98ba 100644 --- a/trezorlib/coins.py +++ b/trezorlib/coins.py @@ -14,12 +14,12 @@ # You should have received a copy of the License along with this library. # If not, see . -import os.path import json +import os.path from .tx_api import TxApiInsight -COINS_JSON = os.path.join(os.path.dirname(__file__), 'coins.json') +COINS_JSON = os.path.join(os.path.dirname(__file__), "coins.json") def _load_coins_json(): @@ -35,24 +35,26 @@ def _load_coins_json(): def _insight_for_coin(coin): - url = next(iter(coin['blockbook'] + coin['bitcore']), None) + url = next(iter(coin["blockbook"] + coin["bitcore"]), None) if not url: return None - zcash = coin['coin_name'].lower().startswith('zcash') - bip115 = coin['bip115'] - network = 'insight_{}'.format(coin['coin_name'].lower().replace(' ', '_')) + zcash = coin["coin_name"].lower().startswith("zcash") + bip115 = coin["bip115"] + network = "insight_{}".format(coin["coin_name"].lower().replace(" ", "_")) return TxApiInsight(network=network, url=url, zcash=zcash, bip115=bip115) # exported variables -__all__ = ['by_name', 'slip44', 'tx_api'] +__all__ = ["by_name", "slip44", "tx_api"] try: by_name = _load_coins_json() except Exception as e: raise ImportError("Failed to load coins.json. Check your installation.") from e -slip44 = {name: coin['slip44'] for name, coin in by_name.items()} -tx_api = {name: _insight_for_coin(coin) - for name, coin in by_name.items() - if coin["blockbook"] or coin["bitcore"]} +slip44 = {name: coin["slip44"] for name, coin in by_name.items()} +tx_api = { + name: _insight_for_coin(coin) + for name, coin in by_name.items() + if coin["blockbook"] or coin["bitcore"] +} diff --git a/trezorlib/cosi.py b/trezorlib/cosi.py index 216f275174..fd3af68847 100644 --- a/trezorlib/cosi.py +++ b/trezorlib/cosi.py @@ -14,15 +14,13 @@ # You should have received a copy of the License along with this library. # If not, see . -from functools import reduce import binascii +from functools import reduce from typing import Iterable, Tuple -from . import messages +from . import _ed25519, messages from .tools import expect -from . import _ed25519 - # XXX, these could be NewType's, but that would infect users of the cosi module with these types as well. # Unsure if we want that. Ed25519PrivateKey = bytes @@ -37,7 +35,9 @@ def combine_keys(pks: Iterable[Ed25519PublicPoint]) -> Ed25519PublicPoint: return Ed25519PublicPoint(_ed25519.encodepoint(combine)) -def combine_sig(global_R: Ed25519PublicPoint, sigs: Iterable[Ed25519Signature]) -> Ed25519Signature: +def combine_sig( + global_R: Ed25519PublicPoint, sigs: Iterable[Ed25519Signature] +) -> Ed25519Signature: """Combine a list of signatures into a single CoSi signature.""" S = [_ed25519.decodeint(si) for si in sigs] s = sum(S) % _ed25519.l @@ -45,7 +45,9 @@ def combine_sig(global_R: Ed25519PublicPoint, sigs: Iterable[Ed25519Signature]) return Ed25519Signature(sig) -def get_nonce(sk: Ed25519PrivateKey, data: bytes, ctr: int = 0) -> Tuple[int, Ed25519PublicPoint]: +def get_nonce( + sk: Ed25519PrivateKey, data: bytes, ctr: int = 0 +) -> Tuple[int, Ed25519PublicPoint]: """Calculate CoSi nonces for given data. These differ from Ed25519 deterministic nonces in that there is a counter appended at end. @@ -58,12 +60,18 @@ def get_nonce(sk: Ed25519PrivateKey, data: bytes, ctr: int = 0) -> Tuple[int, Ed """ h = _ed25519.H(sk) b = _ed25519.b - r = _ed25519.Hint(bytes([h[i] for i in range(b >> 3, b >> 2)]) + data + binascii.unhexlify('%08x' % ctr)) + r = _ed25519.Hint( + bytes([h[i] for i in range(b >> 3, b >> 2)]) + + data + + binascii.unhexlify("%08x" % ctr) + ) R = _ed25519.scalarmult(_ed25519.B, r) return r, Ed25519PublicPoint(_ed25519.encodepoint(R)) -def verify(signature: Ed25519Signature, digest: bytes, pub_key: Ed25519PublicPoint) -> None: +def verify( + signature: Ed25519Signature, digest: bytes, pub_key: Ed25519PublicPoint +) -> None: """Verify Ed25519 signature. Raise exception if the signature is invalid.""" # XXX this *might* change to bool function _ed25519.checkvalid(signature, digest, pub_key) @@ -76,10 +84,13 @@ def pubkey_from_privkey(privkey: Ed25519PrivateKey) -> Ed25519PublicPoint: return Ed25519PublicPoint(_ed25519.publickey(privkey)) -def sign_with_privkey(digest: bytes, privkey: Ed25519PrivateKey, - global_pubkey: Ed25519PublicPoint, - nonce: int, - global_commit: Ed25519PublicPoint) -> Ed25519Signature: +def sign_with_privkey( + digest: bytes, + privkey: Ed25519PrivateKey, + global_pubkey: Ed25519PublicPoint, + nonce: int, + global_commit: Ed25519PublicPoint, +) -> Ed25519Signature: """Create a CoSi signature of `digest` with the supplied private key. This function needs to know the global public key and global commitment. """ @@ -100,4 +111,11 @@ def commit(client, n, data): @expect(messages.CosiSignature) def sign(client, n, data, global_commitment, global_pubkey): - return client.call(messages.CosiSign(address_n=n, data=data, global_commitment=global_commitment, global_pubkey=global_pubkey)) + return client.call( + messages.CosiSign( + address_n=n, + data=data, + global_commitment=global_commitment, + global_pubkey=global_pubkey, + ) + ) diff --git a/trezorlib/debuglink.py b/trezorlib/debuglink.py index 660c0c78f5..b25282b2b2 100644 --- a/trezorlib/debuglink.py +++ b/trezorlib/debuglink.py @@ -18,8 +18,7 @@ import binascii from mnemonic import Mnemonic -from . import messages as proto -from . import tools +from . import messages as proto, tools from .tools import expect @@ -69,7 +68,7 @@ class DebugLink(object): # We have to encode that into encoded pin, # because application must send back positions # on keypad, not a real PIN. - pin_encoded = ''.join([str(matrix.index(p) + 1) for p in pin]) + pin_encoded = "".join([str(matrix.index(p) + 1) for p in pin]) print("Encoded PIN:", pin_encoded) return pin_encoded @@ -138,21 +137,33 @@ class DebugLink(object): return obj.memory def memory_write(self, address, memory, flash=False): - self._call(proto.DebugLinkMemoryWrite(address=address, memory=memory, flash=flash), nowait=True) + self._call( + proto.DebugLinkMemoryWrite(address=address, memory=memory, flash=flash), + nowait=True, + ) def flash_erase(self, sector): self._call(proto.DebugLinkFlashErase(sector=sector), nowait=True) @expect(proto.Success, field="message") -def load_device_by_mnemonic(client, mnemonic, pin, passphrase_protection, label, language='english', skip_checksum=False, expand=False): +def load_device_by_mnemonic( + client, + mnemonic, + pin, + passphrase_protection, + label, + language="english", + skip_checksum=False, + expand=False, +): # Convert mnemonic to UTF8 NKFD mnemonic = Mnemonic.normalize_string(mnemonic) # Convert mnemonic to ASCII stream - mnemonic = mnemonic.encode('utf-8') + mnemonic = mnemonic.encode("utf-8") - m = Mnemonic('english') + m = Mnemonic("english") if expand: mnemonic = m.expand(mnemonic) @@ -161,13 +172,20 @@ def load_device_by_mnemonic(client, mnemonic, pin, passphrase_protection, label, raise ValueError("Invalid mnemonic checksum") if client.features.initialized: - raise RuntimeError("Device is initialized already. Call wipe_device() and try again.") + raise RuntimeError( + "Device is initialized already. Call wipe_device() and try again." + ) - resp = client.call(proto.LoadDevice(mnemonic=mnemonic, pin=pin, - passphrase_protection=passphrase_protection, - language=language, - label=label, - skip_checksum=skip_checksum)) + resp = client.call( + proto.LoadDevice( + mnemonic=mnemonic, + pin=pin, + passphrase_protection=passphrase_protection, + language=language, + label=label, + skip_checksum=skip_checksum, + ) + ) client.init_device() return resp @@ -175,9 +193,11 @@ def load_device_by_mnemonic(client, mnemonic, pin, passphrase_protection, label, @expect(proto.Success, field="message") def load_device_by_xprv(client, xprv, pin, passphrase_protection, label, language): if client.features.initialized: - raise RuntimeError("Device is initialized already. Call wipe_device() and try again.") + raise RuntimeError( + "Device is initialized already. Call wipe_device() and try again." + ) - if xprv[0:4] not in ('xprv', 'tprv'): + if xprv[0:4] not in ("xprv", "tprv"): raise ValueError("Unknown type of xprv") if not 100 < len(xprv) < 112: # yes this is correct in Python @@ -186,7 +206,7 @@ def load_device_by_xprv(client, xprv, pin, passphrase_protection, label, languag node = proto.HDNodeType() data = binascii.hexlify(tools.b58decode(xprv, None)) - if data[90:92] != b'00': + if data[90:92] != b"00": raise ValueError("Contain invalid private key") checksum = binascii.hexlify(tools.btc_hash(binascii.unhexlify(data[:156]))[:4]) @@ -207,11 +227,15 @@ def load_device_by_xprv(client, xprv, pin, passphrase_protection, label, languag node.chain_code = binascii.unhexlify(data[26:90]) node.private_key = binascii.unhexlify(data[92:156]) # skip 0x00 indicating privkey - resp = client.call(proto.LoadDevice(node=node, - pin=pin, - passphrase_protection=passphrase_protection, - language=language, - label=label)) + resp = client.call( + proto.LoadDevice( + node=node, + pin=pin, + passphrase_protection=passphrase_protection, + language=language, + label=label, + ) + ) client.init_device() return resp @@ -221,4 +245,8 @@ def self_test(client): if client.features.bootloader_mode is not True: raise RuntimeError("Device must be in bootloader mode") - return client.call(proto.SelfTest(payload=b'\x00\xFF\x55\xAA\x66\x99\x33\xCCABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\x00\xFF\x55\xAA\x66\x99\x33\xCC')) + return client.call( + proto.SelfTest( + payload=b"\x00\xFF\x55\xAA\x66\x99\x33\xCCABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\x00\xFF\x55\xAA\x66\x99\x33\xCC" + ) + ) diff --git a/trezorlib/device.py b/trezorlib/device.py index ad6ea54118..0cdb8d847b 100644 --- a/trezorlib/device.py +++ b/trezorlib/device.py @@ -16,34 +16,42 @@ import os import warnings + from mnemonic import Mnemonic from . import messages as proto from .tools import expect, session - from .transport import enumerate_devices, get_transport class TrezorDevice: - ''' + """ This class is deprecated. (There is no reason for it to exist in the first place, it is nothing but a collection of two functions.) Instead, please use functions from the ``trezorlib.transport`` module. - ''' + """ @classmethod def enumerate(cls): - warnings.warn('TrezorDevice is deprecated.', DeprecationWarning) + warnings.warn("TrezorDevice is deprecated.", DeprecationWarning) return enumerate_devices() @classmethod def find_by_path(cls, path): - warnings.warn('TrezorDevice is deprecated.', DeprecationWarning) + warnings.warn("TrezorDevice is deprecated.", DeprecationWarning) return get_transport(path, prefix_search=False) @expect(proto.Success, field="message") -def apply_settings(client, label=None, language=None, use_passphrase=None, homescreen=None, passphrase_source=None, auto_lock_delay_ms=None): +def apply_settings( + client, + label=None, + language=None, + use_passphrase=None, + homescreen=None, + passphrase_source=None, + auto_lock_delay_ms=None, +): settings = proto.ApplySettings() if label is not None: settings.label = label @@ -91,9 +99,21 @@ def wipe(client): @expect(proto.Success, field="message") -def recover(client, word_count, passphrase_protection, pin_protection, label, language, type=proto.RecoveryDeviceType.ScrambledWords, expand=False, dry_run=False): +def recover( + client, + word_count, + passphrase_protection, + pin_protection, + label, + language, + type=proto.RecoveryDeviceType.ScrambledWords, + expand=False, + dry_run=False, +): if client.features.initialized and not dry_run: - raise RuntimeError("Device is initialized already. Call wipe_device() and try again.") + raise RuntimeError( + "Device is initialized already. Call wipe_device() and try again." + ) if word_count not in (12, 18, 24): raise ValueError("Invalid word count. Use 12/18/24") @@ -103,17 +123,20 @@ def recover(client, word_count, passphrase_protection, pin_protection, label, la client.expand = expand if client.expand: # optimization to load the wordlist once, instead of for each recovery word - client.mnemonic_wordlist = Mnemonic('english') + client.mnemonic_wordlist = Mnemonic("english") - res = client.call(proto.RecoveryDevice( - word_count=int(word_count), - passphrase_protection=bool(passphrase_protection), - pin_protection=bool(pin_protection), - label=label, - language=language, - enforce_wordlist=True, - type=type, - dry_run=dry_run)) + res = client.call( + proto.RecoveryDevice( + word_count=int(word_count), + passphrase_protection=bool(passphrase_protection), + pin_protection=bool(pin_protection), + label=label, + language=language, + enforce_wordlist=True, + type=type, + dry_run=dry_run, + ) + ) client.init_device() return res @@ -121,19 +144,33 @@ def recover(client, word_count, passphrase_protection, pin_protection, label, la @expect(proto.Success, field="message") @session -def reset(client, display_random, strength, passphrase_protection, pin_protection, label, language, u2f_counter=0, skip_backup=False): +def reset( + client, + display_random, + strength, + passphrase_protection, + pin_protection, + label, + language, + u2f_counter=0, + skip_backup=False, +): if client.features.initialized: - raise RuntimeError("Device is initialized already. Call wipe_device() and try again.") + raise RuntimeError( + "Device is initialized already. Call wipe_device() and try again." + ) # Begin with device reset workflow - msg = proto.ResetDevice(display_random=display_random, - strength=strength, - passphrase_protection=bool(passphrase_protection), - pin_protection=bool(pin_protection), - language=language, - label=label, - u2f_counter=u2f_counter, - skip_backup=bool(skip_backup)) + msg = proto.ResetDevice( + display_random=display_random, + strength=strength, + passphrase_protection=bool(passphrase_protection), + pin_protection=bool(pin_protection), + language=language, + label=label, + u2f_counter=u2f_counter, + skip_backup=bool(skip_backup), + ) resp = client.call(msg) if not isinstance(resp, proto.EntropyRequest): diff --git a/trezorlib/ethereum.py b/trezorlib/ethereum.py index fcf1d91b5b..86aabed745 100644 --- a/trezorlib/ethereum.py +++ b/trezorlib/ethereum.py @@ -1,9 +1,9 @@ from . import messages as proto -from .tools import expect, CallException, normalize_nfc, session +from .tools import CallException, expect, normalize_nfc, session def int_to_big_endian(value): - return value.to_bytes((value.bit_length() + 7) // 8, 'big') + return value.to_bytes((value.bit_length() + 7) // 8, "big") # ====== Client functions ====== # @@ -15,13 +15,25 @@ def get_address(client, n, show_display=False, multisig=None): @session -def sign_tx(client, n, nonce, gas_price, gas_limit, to, value, data=None, chain_id=None, tx_type=None): +def sign_tx( + client, + n, + nonce, + gas_price, + gas_limit, + to, + value, + data=None, + chain_id=None, + tx_type=None, +): msg = proto.EthereumSignTx( address_n=n, nonce=int_to_big_endian(nonce), gas_price=int_to_big_endian(gas_price), gas_limit=int_to_big_endian(gas_limit), - value=int_to_big_endian(value)) + value=int_to_big_endian(value), + ) if to: msg.to = to @@ -56,7 +68,11 @@ def sign_message(client, n, message): def verify_message(client, address, signature, message): message = normalize_nfc(message) try: - resp = client.call(proto.EthereumVerifyMessage(address=address, signature=signature, message=message)) + resp = client.call( + proto.EthereumVerifyMessage( + address=address, signature=signature, message=message + ) + ) except CallException as e: resp = e if isinstance(resp, proto.Success): diff --git a/trezorlib/firmware.py b/trezorlib/firmware.py index 779ca1408a..92f95d8584 100644 --- a/trezorlib/firmware.py +++ b/trezorlib/firmware.py @@ -1,12 +1,16 @@ import binascii + import construct as c import pyblake2 -from . import cosi -from . import messages as proto -from . import tools +from . import cosi, messages as proto, tools +def bytes_not(data): + return bytes(~b & 0xff for b in data) + + +# fmt: off Toif = c.Struct( "magic" / c.Const(b"TOI"), "format" / c.Enum(c.Byte, full_color=b"f", grayscale=b"g"), @@ -16,10 +20,6 @@ Toif = c.Struct( ) -def bytes_not(data): - return bytes(~b & 0xff for b in data) - - VendorTrust = c.Transformed(c.BitStruct( "reserved" / c.Padding(9), "show_vendor_string" / c.Flag, @@ -87,7 +87,10 @@ FirmwareHeader = c.Struct( "signature" / c.Bytes(64), "_end_offset" / c.Tell, - "header_len" / c.Pointer(c.this._start_offset + 4, c.Rebuild(c.Int32ul, c.this._end_offset - c.this._start_offset)), + "header_len" / c.Pointer( + c.this._start_offset + 4, + c.Rebuild(c.Int32ul, c.this._end_offset - c.this._start_offset) + ), ) @@ -97,12 +100,13 @@ Firmware = c.Struct( "code" / c.Bytes(c.this.firmware_header.code_length), c.Terminated, ) +# fmt: on def validate_firmware(filename): with open(filename, "rb") as f: data = f.read() - if data[:6] == b'54525a': + if data[:6] == b"54525a": data = binascii.unhexlify(data) try: @@ -113,19 +117,29 @@ def validate_firmware(filename): vendor = fw.vendor_header header = fw.firmware_header - print("Vendor header from {}, version {}.{}".format(vendor.vendor_string, vendor.version.major, vendor.version.minor)) - print("Firmware version {v.major}.{v.minor}.{v.patch} build {v.build}".format(v=header.version)) + print( + "Vendor header from {}, version {}.{}".format( + vendor.vendor_string, vendor.version.major, vendor.version.minor + ) + ) + print( + "Firmware version {v.major}.{v.minor}.{v.patch} build {v.build}".format( + v=header.version + ) + ) # rebuild header without signatures stripped_header = header.copy() stripped_header.sigmask = 0 - stripped_header.signature = b'\0' * 64 + stripped_header.signature = b"\0" * 64 header_bytes = FirmwareHeader.build(stripped_header) digest = pyblake2.blake2s(header_bytes).digest() print("Fingerprint: {}".format(binascii.hexlify(digest).decode("ascii"))) - global_pk = cosi.combine_keys(vendor.pubkeys[i] for i in range(8) if header.sigmask & (1 << i)) + global_pk = cosi.combine_keys( + vendor.pubkeys[i] for i in range(8) if header.sigmask & (1 << i) + ) try: cosi.verify(header.signature, digest, global_pk) @@ -156,22 +170,29 @@ def update(client, fp): resp = client.call(proto.FirmwareUpload(payload=data)) if isinstance(resp, proto.Success): return True - elif isinstance(resp, proto.Failure) and resp.code == proto.FailureType.FirmwareError: + elif ( + isinstance(resp, proto.Failure) + and resp.code == proto.FailureType.FirmwareError + ): return False raise RuntimeError("Unexpected result %s" % resp) # TREZORv2 method if isinstance(resp, proto.FirmwareRequest): import pyblake2 + while True: - payload = data[resp.offset:resp.offset + resp.length] + payload = data[resp.offset : resp.offset + resp.length] digest = pyblake2.blake2s(payload).digest() resp = client.call(proto.FirmwareUpload(payload=payload, hash=digest)) if isinstance(resp, proto.FirmwareRequest): continue elif isinstance(resp, proto.Success): return True - elif isinstance(resp, proto.Failure) and resp.code == proto.FailureType.FirmwareError: + elif ( + isinstance(resp, proto.Failure) + and resp.code == proto.FailureType.FirmwareError + ): return False raise RuntimeError("Unexpected result %s" % resp) diff --git a/trezorlib/lisk.py b/trezorlib/lisk.py index 6d7b777810..c20b783a3a 100644 --- a/trezorlib/lisk.py +++ b/trezorlib/lisk.py @@ -1,7 +1,7 @@ import binascii from . import messages as proto -from .tools import expect, CallException, normalize_nfc +from .tools import CallException, expect, normalize_nfc @expect(proto.LiskAddress, field="address") @@ -23,7 +23,11 @@ def sign_message(client, n, message): def verify_message(client, pubkey, signature, message): message = normalize_nfc(message) try: - resp = client.call(proto.LiskVerifyMessage(signature=signature, public_key=pubkey, message=message)) + resp = client.call( + proto.LiskVerifyMessage( + signature=signature, public_key=pubkey, message=message + ) + ) except CallException as e: resp = e return isinstance(resp, proto.Success) @@ -55,7 +59,9 @@ def sign_tx(client, n, transaction): msg = proto.LiskTransactionCommon() msg.type = transaction["type"] - msg.fee = int(transaction["fee"]) # Lisk use strings for big numbers (javascript issue) + msg.fee = int( + transaction["fee"] + ) # Lisk use strings for big numbers (javascript issue) msg.amount = int(transaction["amount"]) # And we convert it back to number msg.timestamp = transaction["timestamp"] diff --git a/trezorlib/log.py b/trezorlib/log.py index 1bc4f192a3..f8ac86e95a 100644 --- a/trezorlib/log.py +++ b/trezorlib/log.py @@ -23,14 +23,15 @@ OMITTED_MESSAGES = set() # type: Set[Type[protobuf.MessageType]] class PrettyProtobufFormatter(logging.Formatter): - def format(self, record: logging.LogRecord) -> str: time = self.formatTime(record) - message = '[{time}] {source} {level}: {msg}'.format( - time=time, level=record.levelname.upper(), + message = "[{time}] {source} {level}: {msg}".format( + time=time, + level=record.levelname.upper(), source=record.name, - msg=super().format(record)) - if hasattr(record, 'protobuf'): + msg=super().format(record), + ) + if hasattr(record, "protobuf"): if type(record.protobuf) in OMITTED_MESSAGES: message += " ({} bytes)".format(record.protobuf.ByteSize()) else: @@ -45,6 +46,6 @@ def enable_debug_output(handler: Optional[logging.Handler] = None): formatter = PrettyProtobufFormatter() handler.setFormatter(formatter) - logger = logging.getLogger('trezorlib') + logger = logging.getLogger("trezorlib") logger.setLevel(logging.DEBUG) logger.addHandler(handler) diff --git a/trezorlib/mapping.py b/trezorlib/mapping.py index 5d39ea8ca6..11c94cb06e 100644 --- a/trezorlib/mapping.py +++ b/trezorlib/mapping.py @@ -22,24 +22,30 @@ map_class_to_type = {} def build_map(): for msg_name in dir(messages.MessageType): - if msg_name.startswith('__'): + if msg_name.startswith("__"): continue try: msg_class = getattr(messages, msg_name) except AttributeError: - raise ValueError("Implementation of protobuf message '%s' is missing" % msg_name) + raise ValueError( + "Implementation of protobuf message '%s' is missing" % msg_name + ) if msg_class.MESSAGE_WIRE_TYPE != getattr(messages.MessageType, msg_name): - raise ValueError("Inconsistent wire type and MessageType record for '%s'" % msg_class) + raise ValueError( + "Inconsistent wire type and MessageType record for '%s'" % msg_class + ) register_message(msg_class) def register_message(msg_class): if msg_class.MESSAGE_WIRE_TYPE in map_type_to_class: - raise Exception("Message for wire type %s is already registered by %s" % - (msg_class.MESSAGE_WIRE_TYPE, get_class(msg_class.MESSAGE_WIRE_TYPE))) + raise Exception( + "Message for wire type %s is already registered by %s" + % (msg_class.MESSAGE_WIRE_TYPE, get_class(msg_class.MESSAGE_WIRE_TYPE)) + ) map_class_to_type[msg_class] = msg_class.MESSAGE_WIRE_TYPE map_type_to_class[msg_class.MESSAGE_WIRE_TYPE] = msg_class diff --git a/trezorlib/misc.py b/trezorlib/misc.py index eb1b0157ae..354bd7d361 100644 --- a/trezorlib/misc.py +++ b/trezorlib/misc.py @@ -8,32 +8,59 @@ def get_entropy(client, size): @expect(proto.SignedIdentity) -def sign_identity(client, identity, challenge_hidden, challenge_visual, ecdsa_curve_name=None): - return client.call(proto.SignIdentity(identity=identity, challenge_hidden=challenge_hidden, challenge_visual=challenge_visual, ecdsa_curve_name=ecdsa_curve_name)) +def sign_identity( + client, identity, challenge_hidden, challenge_visual, ecdsa_curve_name=None +): + return client.call( + proto.SignIdentity( + identity=identity, + challenge_hidden=challenge_hidden, + challenge_visual=challenge_visual, + ecdsa_curve_name=ecdsa_curve_name, + ) + ) @expect(proto.ECDHSessionKey) def get_ecdh_session_key(client, identity, peer_public_key, ecdsa_curve_name=None): - return client.call(proto.GetECDHSessionKey(identity=identity, peer_public_key=peer_public_key, ecdsa_curve_name=ecdsa_curve_name)) + return client.call( + proto.GetECDHSessionKey( + identity=identity, + peer_public_key=peer_public_key, + ecdsa_curve_name=ecdsa_curve_name, + ) + ) @expect(proto.CipheredKeyValue, field="value") -def encrypt_keyvalue(client, n, key, value, ask_on_encrypt=True, ask_on_decrypt=True, iv=b''): - return client.call(proto.CipherKeyValue(address_n=n, - key=key, - value=value, - encrypt=True, - ask_on_encrypt=ask_on_encrypt, - ask_on_decrypt=ask_on_decrypt, - iv=iv)) +def encrypt_keyvalue( + client, n, key, value, ask_on_encrypt=True, ask_on_decrypt=True, iv=b"" +): + return client.call( + proto.CipherKeyValue( + address_n=n, + key=key, + value=value, + encrypt=True, + ask_on_encrypt=ask_on_encrypt, + ask_on_decrypt=ask_on_decrypt, + iv=iv, + ) + ) @expect(proto.CipheredKeyValue, field="value") -def decrypt_keyvalue(client, n, key, value, ask_on_encrypt=True, ask_on_decrypt=True, iv=b''): - return client.call(proto.CipherKeyValue(address_n=n, - key=key, - value=value, - encrypt=False, - ask_on_encrypt=ask_on_encrypt, - ask_on_decrypt=ask_on_decrypt, - iv=iv)) +def decrypt_keyvalue( + client, n, key, value, ask_on_encrypt=True, ask_on_decrypt=True, iv=b"" +): + return client.call( + proto.CipherKeyValue( + address_n=n, + key=key, + value=value, + encrypt=False, + ask_on_encrypt=ask_on_encrypt, + ask_on_decrypt=ask_on_decrypt, + iv=iv, + ) + ) diff --git a/trezorlib/nem.py b/trezorlib/nem.py index c72e421828..bb872a8919 100644 --- a/trezorlib/nem.py +++ b/trezorlib/nem.py @@ -16,8 +16,9 @@ import binascii import json + from . import messages as proto -from .tools import expect, CallException +from .tools import CallException, expect TYPE_TRANSACTION_TRANSFER = 0x0101 TYPE_IMPORTANCE_TRANSFER = 0x0801 @@ -54,21 +55,27 @@ def create_transfer(transaction): msg.public_key = binascii.unhexlify(transaction["message"]["publicKey"]) if "mosaics" in transaction: - msg.mosaics = [proto.NEMMosaic( - namespace=mosaic["mosaicId"]["namespaceId"], - mosaic=mosaic["mosaicId"]["name"], - quantity=mosaic["quantity"], - ) for mosaic in transaction["mosaics"]] + msg.mosaics = [ + proto.NEMMosaic( + namespace=mosaic["mosaicId"]["namespaceId"], + mosaic=mosaic["mosaicId"]["name"], + quantity=mosaic["quantity"], + ) + for mosaic in transaction["mosaics"] + ] return msg def create_aggregate_modification(transactions): msg = proto.NEMAggregateModification() - msg.modifications = [proto.NEMCosignatoryModification( - type=modification["modificationType"], - public_key=binascii.unhexlify(modification["cosignatoryAccount"]), - ) for modification in transactions["modifications"]] + msg.modifications = [ + proto.NEMCosignatoryModification( + type=modification["modificationType"], + public_key=binascii.unhexlify(modification["cosignatoryAccount"]), + ) + for modification in transactions["modifications"] + ] if "minCosignatories" in transactions: msg.relative_change = transactions["minCosignatories"]["relativeChange"] @@ -141,7 +148,7 @@ def create_importance_transfer(transaction): def create_sign_tx(transaction): msg = proto.NEMSignTx() msg.transaction = create_transaction_common(transaction) - msg.cosigning = (transaction["type"] == TYPE_MULTISIG_SIGNATURE) + msg.cosigning = transaction["type"] == TYPE_MULTISIG_SIGNATURE if transaction["type"] in (TYPE_MULTISIG_SIGNATURE, TYPE_MULTISIG): transaction = transaction["otherTrans"] @@ -172,7 +179,9 @@ def create_sign_tx(transaction): @expect(proto.NEMAddress, field="address") def get_address(client, n, network, show_display=False): - return client.call(proto.NEMGetAddress(address_n=n, network=network, show_display=show_display)) + return client.call( + proto.NEMGetAddress(address_n=n, network=network, show_display=show_display) + ) @expect(proto.NEMSignedTx) diff --git a/trezorlib/protobuf.py b/trezorlib/protobuf.py index e761354196..76e751482d 100644 --- a/trezorlib/protobuf.py +++ b/trezorlib/protobuf.py @@ -89,6 +89,7 @@ def dump_uvarint(writer, n): # But this is harder in Python because we don't natively know the bit size of the number. # So we have to branch on whether the number is negative. + def sint_to_uint(sint): res = sint << 1 if sint < 0: @@ -134,8 +135,7 @@ class MessageType: self._fill_missing() def __eq__(self, rhs): - return (self.__class__ is rhs.__class__ and - self.__dict__ == rhs.__dict__) + return self.__class__ is rhs.__class__ and self.__dict__ == rhs.__dict__ def __repr__(self): d = {} @@ -143,16 +143,16 @@ class MessageType: if value is None or value == []: continue d[key] = value - return '<%s: %s>' % (self.__class__.__name__, d) + return "<%s: %s>" % (self.__class__.__name__, d) def __iter__(self): return self.__dict__.__iter__() def __getattr__(self, attr): - if attr.startswith('_add_'): + if attr.startswith("_add_"): return self._additem(attr[5:]) - if attr.startswith('_extend_'): + if attr.startswith("_extend_"): return self._extenditem(attr[8:]) raise AttributeError(attr) @@ -208,7 +208,6 @@ class MessageType: class LimitedReader: - def __init__(self, reader, limit): self.reader = reader self.limit = limit @@ -223,7 +222,6 @@ class LimitedReader: class CountingWriter: - def __init__(self): self.size = 0 @@ -331,7 +329,7 @@ def dump_message(writer, msg): elif ftype is UnicodeType: if not isinstance(svalue, bytes): - svalue = svalue.encode('utf-8') + svalue = svalue.encode("utf-8") dump_uvarint(writer, len(svalue)) writer.write(svalue) @@ -346,12 +344,13 @@ def dump_message(writer, msg): raise TypeError -def format_message(pb: MessageType, - indent: int = 0, - sep: str = ' ' * 4, - truncate_after: Optional[int] = 256, - truncate_to: Optional[int] = 64) -> str: - +def format_message( + pb: MessageType, + indent: int = 0, + sep: str = " " * 4, + truncate_after: Optional[int] = 256, + truncate_to: Optional[int] = 64, +) -> str: def mostly_printable(bytes): if not bytes: return True @@ -369,33 +368,33 @@ def format_message(pb: MessageType, return repr(value) # long list, one line per entry - lines = ['[', level + ']'] - lines[1:1] = [leadin + pformat_value(x, indent + 1) + ',' for x in value] - return '\n'.join(lines) + lines = ["[", level + "]"] + lines[1:1] = [leadin + pformat_value(x, indent + 1) + "," for x in value] + return "\n".join(lines) if isinstance(value, dict): - lines = ['{'] + lines = ["{"] for key, val in sorted(value.items()): if val is None or val == []: continue - lines.append(leadin + key + ': ' + pformat_value(val, indent + 1) + ',') - lines.append(level + '}') - return '\n'.join(lines) + lines.append(leadin + key + ": " + pformat_value(val, indent + 1) + ",") + lines.append(level + "}") + return "\n".join(lines) if isinstance(value, (bytes, bytearray)): length = len(value) - suffix = '' + suffix = "" if truncate_after and length > truncate_after: - suffix = '...' - value = value[:truncate_to or 0] + suffix = "..." + value = value[: truncate_to or 0] if mostly_printable(value): output = repr(value) else: - output = '0x' + binascii.hexlify(value).decode('ascii') - return '{} bytes {}{}'.format(length, output, suffix) + output = "0x" + binascii.hexlify(value).decode("ascii") + return "{} bytes {}{}".format(length, output, suffix) return repr(value) - return '{name} ({size} bytes) {content}'.format( + return "{name} ({size} bytes) {content}".format( name=pb.__class__.__name__, size=pb.ByteSize(), - content=pformat_value(pb.__dict__, indent) + content=pformat_value(pb.__dict__, indent), ) diff --git a/trezorlib/protocol_v1.py b/trezorlib/protocol_v1.py index fe2cf796ea..8b9ede3fd1 100644 --- a/trezorlib/protocol_v1.py +++ b/trezorlib/protocol_v1.py @@ -14,13 +14,12 @@ # You should have received a copy of the License along with this library. # If not, see . -from io import BytesIO import logging import struct +from io import BytesIO from typing import Tuple -from . import mapping -from . import protobuf +from . import mapping, protobuf from .transport import Transport REPLEN = 64 @@ -29,7 +28,6 @@ LOG = logging.getLogger(__name__) class ProtocolV1: - def session_begin(self, transport: Transport) -> None: pass @@ -37,8 +35,10 @@ class ProtocolV1: pass def write(self, transport: Transport, msg: protobuf.MessageType) -> None: - LOG.debug("sending message: {}".format(msg.__class__.__name__), - extra={'protobuf': msg}) + LOG.debug( + "sending message: {}".format(msg.__class__.__name__), + extra={"protobuf": msg}, + ) data = BytesIO() protobuf.dump_message(data, msg) ser = data.getvalue() @@ -47,8 +47,8 @@ class ProtocolV1: while data: # Report ID, data padded to 63 bytes - chunk = b'?' + data[:REPLEN - 1] - chunk = chunk.ljust(REPLEN, b'\x00') + chunk = b"?" + data[: REPLEN - 1] + chunk = chunk.ljust(REPLEN, b"\x00") transport.write_chunk(chunk) data = data[63:] @@ -67,23 +67,25 @@ class ProtocolV1: # Parse to protobuf msg = protobuf.load_message(data, mapping.get_class(msg_type)) - LOG.debug("received message: {}".format(msg.__class__.__name__), - extra={'protobuf': msg}) + LOG.debug( + "received message: {}".format(msg.__class__.__name__), + extra={"protobuf": msg}, + ) return msg def parse_first(self, chunk: bytes) -> Tuple[int, int, bytes]: - if chunk[:3] != b'?##': - raise RuntimeError('Unexpected magic characters') + if chunk[:3] != b"?##": + raise RuntimeError("Unexpected magic characters") try: - headerlen = struct.calcsize('>HL') - msg_type, datalen = struct.unpack('>HL', chunk[3:3 + headerlen]) + headerlen = struct.calcsize(">HL") + msg_type, datalen = struct.unpack(">HL", chunk[3 : 3 + headerlen]) except Exception: - raise RuntimeError('Cannot parse header') + raise RuntimeError("Cannot parse header") - data = chunk[3 + headerlen:] + data = chunk[3 + headerlen :] return msg_type, datalen, data def parse_next(self, chunk: bytes) -> bytes: - if chunk[:1] != b'?': - raise RuntimeError('Unexpected magic characters') + if chunk[:1] != b"?": + raise RuntimeError("Unexpected magic characters") return chunk[1:] diff --git a/trezorlib/protocol_v2.py b/trezorlib/protocol_v2.py index 97934767bf..a41b7313af 100644 --- a/trezorlib/protocol_v2.py +++ b/trezorlib/protocol_v2.py @@ -14,13 +14,12 @@ # You should have received a copy of the License along with this library. # If not, see . -from io import BytesIO import logging import struct +from io import BytesIO from typing import Tuple -from . import mapping -from . import protobuf +from . import mapping, protobuf from .transport import Transport REPLEN = 64 @@ -29,13 +28,12 @@ LOG = logging.getLogger(__name__) class ProtocolV2: - def __init__(self) -> None: self.session = None def session_begin(self, transport: Transport) -> None: - chunk = struct.pack('>B', 0x03) - chunk = chunk.ljust(REPLEN, b'\x00') + chunk = struct.pack(">B", 0x03) + chunk = chunk.ljust(REPLEN, b"\x00") transport.write_chunk(chunk) resp = transport.read_chunk() self.session = self.parse_session_open(resp) @@ -44,46 +42,50 @@ class ProtocolV2: def session_end(self, transport: Transport) -> None: if not self.session: return - chunk = struct.pack('>BL', 0x04, self.session) - chunk = chunk.ljust(REPLEN, b'\x00') + chunk = struct.pack(">BL", 0x04, self.session) + chunk = chunk.ljust(REPLEN, b"\x00") transport.write_chunk(chunk) resp = transport.read_chunk() - (magic, ) = struct.unpack('>B', resp[:1]) + (magic,) = struct.unpack(">B", resp[:1]) if magic != 0x04: - raise RuntimeError('Expected session close') + raise RuntimeError("Expected session close") LOG.debug("[session {}] session ended".format(self.session)) self.session = None def write(self, transport: Transport, msg: protobuf.MessageType) -> None: if not self.session: - raise RuntimeError('Missing session for v2 protocol') + raise RuntimeError("Missing session for v2 protocol") - LOG.debug("[session {}] sending message: {}".format(self.session, msg.__class__.__name__), - extra={'protobuf': msg}) + LOG.debug( + "[session {}] sending message: {}".format( + self.session, msg.__class__.__name__ + ), + extra={"protobuf": msg}, + ) # Serialize whole message data = BytesIO() protobuf.dump_message(data, msg) data = data.getvalue() - dataheader = struct.pack('>LL', mapping.get_type(msg), len(data)) + dataheader = struct.pack(">LL", mapping.get_type(msg), len(data)) data = dataheader + data seq = -1 # Write it out while data: if seq < 0: - repheader = struct.pack('>BL', 0x01, self.session) + repheader = struct.pack(">BL", 0x01, self.session) else: - repheader = struct.pack('>BLL', 0x02, self.session, seq) + repheader = struct.pack(">BLL", 0x02, self.session, seq) datalen = REPLEN - len(repheader) chunk = repheader + data[:datalen] - chunk = chunk.ljust(REPLEN, b'\x00') + chunk = chunk.ljust(REPLEN, b"\x00") transport.write_chunk(chunk) data = data[datalen:] seq += 1 def read(self, transport: Transport) -> protobuf.MessageType: if not self.session: - raise RuntimeError('Missing session for v2 protocol') + raise RuntimeError("Missing session for v2 protocol") # Read header with first part of message data chunk = transport.read_chunk() @@ -100,40 +102,46 @@ class ProtocolV2: # Parse to protobuf msg = protobuf.load_message(data, mapping.get_class(msg_type)) - LOG.debug("[session {}] received message: {}".format(self.session, msg.__class__.__name__), - extra={'protobuf': msg}) + LOG.debug( + "[session {}] received message: {}".format( + self.session, msg.__class__.__name__ + ), + extra={"protobuf": msg}, + ) return msg def parse_first(self, chunk: bytes) -> Tuple[int, int, bytes]: try: - headerlen = struct.calcsize('>BLLL') - magic, session, msg_type, datalen = struct.unpack('>BLLL', chunk[:headerlen]) + headerlen = struct.calcsize(">BLLL") + magic, session, msg_type, datalen = struct.unpack( + ">BLLL", chunk[:headerlen] + ) except Exception: - raise RuntimeError('Cannot parse header') + raise RuntimeError("Cannot parse header") if magic != 0x01: - raise RuntimeError('Unexpected magic character') + raise RuntimeError("Unexpected magic character") if session != self.session: - raise RuntimeError('Session id mismatch') + raise RuntimeError("Session id mismatch") return msg_type, datalen, chunk[headerlen:] def parse_next(self, chunk: bytes) -> bytes: try: - headerlen = struct.calcsize('>BLL') - magic, session, sequence = struct.unpack('>BLL', chunk[:headerlen]) + headerlen = struct.calcsize(">BLL") + magic, session, sequence = struct.unpack(">BLL", chunk[:headerlen]) except Exception: - raise RuntimeError('Cannot parse header') + raise RuntimeError("Cannot parse header") if magic != 0x02: - raise RuntimeError('Unexpected magic characters') + raise RuntimeError("Unexpected magic characters") if session != self.session: - raise RuntimeError('Session id mismatch') + raise RuntimeError("Session id mismatch") return chunk[headerlen:] def parse_session_open(self, chunk: bytes) -> int: try: - headerlen = struct.calcsize('>BL') - magic, session = struct.unpack('>BL', chunk[:headerlen]) + headerlen = struct.calcsize(">BL") + magic, session = struct.unpack(">BL", chunk[:headerlen]) except Exception: - raise RuntimeError('Cannot parse header') + raise RuntimeError("Cannot parse header") if magic != 0x03: - raise RuntimeError('Unexpected magic character') + raise RuntimeError("Unexpected magic character") return session diff --git a/trezorlib/qt/pinmatrix.py b/trezorlib/qt/pinmatrix.py index e6850cf0cb..19ae2db624 100644 --- a/trezorlib/qt/pinmatrix.py +++ b/trezorlib/qt/pinmatrix.py @@ -14,16 +14,35 @@ # You should have received a copy of the License along with this library. # If not, see . -import sys import math +import sys try: - from PyQt4.QtGui import (QPushButton, QLineEdit, QSizePolicy, QRegExpValidator, QLabel, - QApplication, QWidget, QGridLayout, QVBoxLayout, QHBoxLayout) + from PyQt4.QtGui import ( + QPushButton, + QLineEdit, + QSizePolicy, + QRegExpValidator, + QLabel, + QApplication, + QWidget, + QGridLayout, + QVBoxLayout, + QHBoxLayout, + ) from PyQt4.QtCore import QObject, SIGNAL, QRegExp, Qt, QT_VERSION_STR except ImportError: - from PyQt5.QtWidgets import (QPushButton, QLineEdit, QSizePolicy, QLabel, - QApplication, QWidget, QGridLayout, QVBoxLayout, QHBoxLayout) + from PyQt5.QtWidgets import ( + QPushButton, + QLineEdit, + QSizePolicy, + QLabel, + QApplication, + QWidget, + QGridLayout, + QVBoxLayout, + QHBoxLayout, + ) from PyQt5.QtGui import QRegExpValidator from PyQt5.QtCore import QRegExp, Qt from PyQt5.Qt import QT_VERSION_STR @@ -31,16 +50,16 @@ except ImportError: class PinButton(QPushButton): def __init__(self, password, encoded_value): - super(PinButton, self).__init__('?') + super(PinButton, self).__init__("?") self.password = password self.encoded_value = encoded_value - if QT_VERSION_STR >= '5': + if QT_VERSION_STR >= "5": self.clicked.connect(self._pressed) - elif QT_VERSION_STR >= '4': - QObject.connect(self, SIGNAL('clicked()'), self._pressed) + elif QT_VERSION_STR >= "4": + QObject.connect(self, SIGNAL("clicked()"), self._pressed) else: - raise RuntimeError('Unsupported Qt version') + raise RuntimeError("Unsupported Qt version") def _pressed(self): self.password.setText(self.password.text() + str(self.encoded_value)) @@ -48,26 +67,29 @@ class PinButton(QPushButton): class PinMatrixWidget(QWidget): - ''' + """ Displays widget with nine blank buttons and password box. Encodes button clicks into sequence of numbers for passing into PinAck messages of TREZOR. show_strength=True may be useful for entering new PIN - ''' + """ + def __init__(self, show_strength=True, parent=None): super(PinMatrixWidget, self).__init__(parent) self.password = QLineEdit() - self.password.setValidator(QRegExpValidator(QRegExp('[1-9]+'), None)) + self.password.setValidator(QRegExpValidator(QRegExp("[1-9]+"), None)) self.password.setEchoMode(QLineEdit.Password) - if QT_VERSION_STR >= '5': + if QT_VERSION_STR >= "5": self.password.textChanged.connect(self._password_changed) - elif QT_VERSION_STR >= '4': - QObject.connect(self.password, SIGNAL('textChanged(QString)'), self._password_changed) + elif QT_VERSION_STR >= "4": + QObject.connect( + self.password, SIGNAL("textChanged(QString)"), self._password_changed + ) else: - raise RuntimeError('Unsupported Qt version') + raise RuntimeError("Unsupported Qt version") self.strength = QLabel() self.strength.setMinimumWidth(75) @@ -95,16 +117,16 @@ class PinMatrixWidget(QWidget): def _set_strength(self, strength): if strength < 3000: - self.strength.setText('weak') + self.strength.setText("weak") self.strength.setStyleSheet("QLabel { color : #d00; }") elif strength < 60000: - self.strength.setText('fine') + self.strength.setText("fine") self.strength.setStyleSheet("QLabel { color : #db0; }") elif strength < 360000: - self.strength.setText('strong') + self.strength.setText("strong") self.strength.setStyleSheet("QLabel { color : #0a0; }") else: - self.strength.setText('ULTIMATE') + self.strength.setText("ULTIMATE") self.strength.setStyleSheet("QLabel { color : #000; font-weight: bold;}") def _password_changed(self, password): @@ -119,10 +141,10 @@ class PinMatrixWidget(QWidget): return self.password.text() -if __name__ == '__main__': - ''' +if __name__ == "__main__": + """ Demo application showing PinMatrix widget in action - ''' + """ app = QApplication(sys.argv) matrix = PinMatrixWidget() @@ -132,13 +154,13 @@ if __name__ == '__main__': print("Possible button combinations:", matrix.get_strength()) sys.exit() - ok = QPushButton('OK') - if QT_VERSION_STR >= '5': + ok = QPushButton("OK") + if QT_VERSION_STR >= "5": ok.clicked.connect(clicked) - elif QT_VERSION_STR >= '4': - QObject.connect(ok, SIGNAL('clicked()'), clicked) + elif QT_VERSION_STR >= "4": + QObject.connect(ok, SIGNAL("clicked()"), clicked) else: - raise RuntimeError('Unsupported Qt version') + raise RuntimeError("Unsupported Qt version") vbox = QVBoxLayout() vbox.addWidget(matrix) diff --git a/trezorlib/ripple.py b/trezorlib/ripple.py index 3f18837f1b..6de8eca585 100644 --- a/trezorlib/ripple.py +++ b/trezorlib/ripple.py @@ -18,12 +18,14 @@ from . import messages from .tools import expect +REQUIRED_FIELDS = ("Fee", "Sequence", "TransactionType", "Amount", "Destination") + @expect(messages.RippleAddress, field="address") def get_address(client, address_n, show_display=False): return client.call( - messages.RippleGetAddress( - address_n=address_n, show_display=show_display)) + messages.RippleGetAddress(address_n=address_n, show_display=show_display) + ) @expect(messages.RippleSignedTx) @@ -33,8 +35,8 @@ def sign_tx(client, address_n, msg: messages.RippleSignTx): def create_sign_tx_msg(transaction) -> messages.RippleSignTx: - if not all(transaction.get(k) for k in ("Fee", "Sequence", "TransactionType", "Amount", "Destination")): - raise ValueError("Some of the required fields missing (Fee, Sequence, TransactionType, Amount, Destination") + if not all(transaction.get(k) for k in REQUIRED_FIELDS): + raise ValueError("Some of the required fields missing") if transaction["TransactionType"] != "Payment": raise ValueError("Only Payment transaction type is supported") @@ -49,6 +51,5 @@ def create_sign_tx_msg(transaction) -> messages.RippleSignTx: def _create_payment(transaction) -> messages.RipplePayment: return messages.RipplePayment( - amount=transaction.get("Amount"), - destination=transaction.get("Destination") + amount=transaction.get("Amount"), destination=transaction.get("Destination") ) diff --git a/trezorlib/stellar.py b/trezorlib/stellar.py index 803246d8bd..06af866f09 100644 --- a/trezorlib/stellar.py +++ b/trezorlib/stellar.py @@ -19,7 +19,7 @@ import struct import xdrlib from . import messages -from .tools import expect, CallException +from .tools import CallException, expect # Memo types MEMO_TYPE_NONE = 0 @@ -65,7 +65,7 @@ def address_from_public_key(pk_bytes): # checksum final_bytes.extend(struct.pack(" max_timebound or tx.timebounds_start < 0: - raise ValueError("Starting timebound out of range (must be between 0 and " + max_timebound) + raise ValueError( + "Starting timebound out of range (must be between 0 and " + + max_timebound + ) if tx.timebounds_end > max_timebound or tx.timebounds_end < 0: - raise ValueError("Ending timebound out of range (must be between 0 and " + max_timebound) + raise ValueError( + "Ending timebound out of range (must be between 0 and " + max_timebound + ) # memo type determines what optional fields are set tx.memo_type = unpacker.unpack_uint() @@ -117,7 +124,7 @@ def parse_transaction_bytes(tx_bytes): tx.num_operations = unpacker.unpack_uint() operations = [] - for i in range(tx.num_operations): + for _ in range(tx.num_operations): operations.append(_parse_operation_bytes(unpacker)) return tx, operations @@ -140,7 +147,7 @@ def _parse_operation_bytes(unpacker): return messages.StellarCreateAccountOp( source_account=source_account, new_account=_xdr_read_address(unpacker), - starting_balance=unpacker.unpack_hyper() + starting_balance=unpacker.unpack_hyper(), ) if type == OP_PAYMENT: @@ -148,7 +155,7 @@ def _parse_operation_bytes(unpacker): source_account=source_account, destination_account=_xdr_read_address(unpacker), asset=_xdr_read_asset(unpacker), - amount=unpacker.unpack_hyper() + amount=unpacker.unpack_hyper(), ) if type == OP_PATH_PAYMENT: @@ -159,11 +166,11 @@ def _parse_operation_bytes(unpacker): destination_account=_xdr_read_address(unpacker), destination_asset=_xdr_read_asset(unpacker), destination_amount=unpacker.unpack_hyper(), - paths=[] + paths=[], ) num_paths = unpacker.unpack_uint() - for i in range(num_paths): + for _ in range(num_paths): op.paths.append(_xdr_read_asset(unpacker)) return op @@ -176,7 +183,7 @@ def _parse_operation_bytes(unpacker): amount=unpacker.unpack_hyper(), price_n=unpacker.unpack_uint(), price_d=unpacker.unpack_uint(), - offer_id=unpacker.unpack_uhyper() + offer_id=unpacker.unpack_uhyper(), ) if type == OP_CREATE_PASSIVE_OFFER: @@ -186,13 +193,11 @@ def _parse_operation_bytes(unpacker): buying_asset=_xdr_read_asset(unpacker), amount=unpacker.unpack_hyper(), price_n=unpacker.unpack_uint(), - price_d=unpacker.unpack_uint() + price_d=unpacker.unpack_uint(), ) if type == OP_SET_OPTIONS: - op = messages.StellarSetOptionsOp( - source_account=source_account - ) + op = messages.StellarSetOptionsOp(source_account=source_account) # Inflation destination if unpacker.unpack_bool(): @@ -238,14 +243,14 @@ def _parse_operation_bytes(unpacker): return messages.StellarChangeTrustOp( source_account=source_account, asset=_xdr_read_asset(unpacker), - limit=unpacker.unpack_uhyper() + limit=unpacker.unpack_uhyper(), ) if type == OP_ALLOW_TRUST: op = messages.StellarAllowTrustOp( source_account=source_account, trusted_account=_xdr_read_address(unpacker), - asset_type=unpacker.unpack_uint() + asset_type=unpacker.unpack_uint(), ) if op.asset_type == ASSET_TYPE_ALPHA4: @@ -260,15 +265,14 @@ def _parse_operation_bytes(unpacker): if type == OP_ACCOUNT_MERGE: return messages.StellarAccountMergeOp( source_account=source_account, - destination_account=_xdr_read_address(unpacker) + destination_account=_xdr_read_address(unpacker), ) # Inflation is not implemented since anyone can submit this operation to the network if type == OP_MANAGE_DATA: op = messages.StellarManageDataOp( - source_account=source_account, - key=unpacker.unpack_string(), + source_account=source_account, key=unpacker.unpack_string() ) # Only set value if the field is present @@ -281,8 +285,7 @@ def _parse_operation_bytes(unpacker): # see: https://github.com/stellar/stellar-core/blob/master/src/xdr/Stellar-transaction.x#L269 if type == OP_BUMP_SEQUENCE: return messages.StellarBumpSequenceOp( - source_account=source_account, - bump_to=unpacker.unpack_uhyper() + source_account=source_account, bump_to=unpacker.unpack_uhyper() ) raise ValueError("Unknown operation type: " + str(type)) @@ -290,9 +293,7 @@ def _parse_operation_bytes(unpacker): def _xdr_read_asset(unpacker): """Reads a stellar Asset from unpacker""" - asset = messages.StellarAssetType( - type=unpacker.unpack_uint() - ) + asset = messages.StellarAssetType(type=unpacker.unpack_uint()) if asset.type == ASSET_TYPE_ALPHA4: asset.code = unpacker.unpack_fstring(4) @@ -329,8 +330,8 @@ def _crc16_checksum(bytes): for byte in bytes: for i in range(8): - bit = ((byte >> (7 - i) & 1) == 1) - c15 = ((crc >> 15 & 1) == 1) + bit = (byte >> (7 - i) & 1) == 1 + c15 = (crc >> 15 & 1) == 1 crc <<= 1 if c15 ^ bit: crc ^= polynomial @@ -343,15 +344,21 @@ def _crc16_checksum(bytes): @expect(messages.StellarPublicKey, field="public_key") def get_public_key(client, address_n, show_display=False): - return client.call(messages.StellarGetPublicKey(address_n=address_n, show_display=show_display)) + return client.call( + messages.StellarGetPublicKey(address_n=address_n, show_display=show_display) + ) @expect(messages.StellarAddress, field="address") def get_address(client, address_n, show_display=False): - return client.call(messages.StellarGetAddress(address_n=address_n, show_display=show_display)) + return client.call( + messages.StellarGetAddress(address_n=address_n, show_display=show_display) + ) -def sign_tx(client, tx, operations, address_n, network_passphrase=DEFAULT_NETWORK_PASSPHRASE): +def sign_tx( + client, tx, operations, address_n, network_passphrase=DEFAULT_NETWORK_PASSPHRASE +): tx.network_passphrase = network_passphrase tx.address_n = address_n tx.num_operations = len(operations) @@ -368,14 +375,18 @@ def sign_tx(client, tx, operations, address_n, network_passphrase=DEFAULT_NETWOR resp = client.call(operations.pop(0)) except IndexError: # pop from empty list - raise CallException("Stellar.UnexpectedEndOfOperations", - "Reached end of operations without a signature.") from None + raise CallException( + "Stellar.UnexpectedEndOfOperations", + "Reached end of operations without a signature.", + ) from None if not isinstance(resp, messages.StellarSignedTx): raise CallException(messages.FailureType.UnexpectedMessage, resp) if operations: - raise CallException("Stellar.UnprocessedOperations", - "Received a signature before processing all operations.") + raise CallException( + "Stellar.UnprocessedOperations", + "Received a signature before processing all operations.", + ) return resp diff --git a/trezorlib/tests/device_tests/common.py b/trezorlib/tests/device_tests/common.py index 4917e5ae43..67cc79ec68 100644 --- a/trezorlib/tests/device_tests/common.py +++ b/trezorlib/tests/device_tests/common.py @@ -16,35 +16,34 @@ import os +from trezorlib import coins, debuglink, device, tx_api +from trezorlib.client import TrezorClientDebugLink + from . import conftest -from trezorlib import coins -from trezorlib import tx_api -from trezorlib.client import TrezorClientDebugLink -from trezorlib import debuglink -from trezorlib import device - tests_dir = os.path.dirname(os.path.abspath(__file__)) -tx_api.cache_dir = os.path.join(tests_dir, '../txcache') +tx_api.cache_dir = os.path.join(tests_dir, "../txcache") class TrezorTest: + # fmt: off # 1 2 3 4 5 6 7 8 9 10 11 12 - mnemonic12 = 'alcohol woman abuse must during monitor noble actual mixed trade anger aisle' - mnemonic18 = 'owner little vague addict embark decide pink prosper true fork panda embody mixture exchange choose canoe electric jewel' - mnemonic24 = 'dignity pass list indicate nasty swamp pool script soccer toe leaf photo multiply desk host tomato cradle drill spread actor shine dismiss champion exotic' - mnemonic_all = ' '.join(['all'] * 12) + mnemonic12 = "alcohol woman abuse must during monitor noble actual mixed trade anger aisle" + mnemonic18 = "owner little vague addict embark decide pink prosper true fork panda embody mixture exchange choose canoe electric jewel" + mnemonic24 = "dignity pass list indicate nasty swamp pool script soccer toe leaf photo multiply desk host tomato cradle drill spread actor shine dismiss champion exotic" + mnemonic_all = " ".join(["all"] * 12) + # fmt: on - pin4 = '1234' - pin6 = '789456' - pin8 = '45678978' + pin4 = "1234" + pin6 = "789456" + pin8 = "45678978" def setup_method(self, method): wirelink = conftest.get_device() debuglink = wirelink.find_debug() self.client = TrezorClientDebugLink(wirelink) self.client.set_debuglink(debuglink) - self.client.set_tx_api(coins.tx_api['Bitcoin']) + self.client.set_tx_api(coins.tx_api["Bitcoin"]) # self.client.set_buttonwait(3) device.wipe(self.client) @@ -54,7 +53,7 @@ class TrezorTest: self.client.transport.session_end() self.client.close() - def _setup_mnemonic(self, mnemonic=None, pin='', passphrase=False): + def _setup_mnemonic(self, mnemonic=None, pin="", passphrase=False): if mnemonic is None: mnemonic = TrezorTest.mnemonic12 debuglink.load_device_by_mnemonic( @@ -83,10 +82,10 @@ class TrezorTest: def generate_entropy(strength, internal_entropy, external_entropy): - ''' + """ strength - length of produced seed. One of 128, 192, 256 random - binary stream of random data from external HRNG - ''' + """ import hashlib if strength not in (128, 192, 256): @@ -105,7 +104,7 @@ def generate_entropy(strength, internal_entropy, external_entropy): raise ValueError("External entropy too short") entropy = hashlib.sha256(internal_entropy + external_entropy).digest() - entropy_stripped = entropy[:strength // 8] + entropy_stripped = entropy[: strength // 8] if len(entropy_stripped) * 8 != strength: raise ValueError("Entropy length mismatch") diff --git a/trezorlib/tests/device_tests/conftest.py b/trezorlib/tests/device_tests/conftest.py index ecca700208..18b5189a24 100644 --- a/trezorlib/tests/device_tests/conftest.py +++ b/trezorlib/tests/device_tests/conftest.py @@ -24,7 +24,7 @@ from trezorlib import log, coins def get_device(): - path = os.environ.get('TREZOR_PATH') + path = os.environ.get("TREZOR_PATH") return get_transport(path) @@ -48,7 +48,7 @@ def client(): debuglink = wirelink.find_debug() client = TrezorClientDebugLink(wirelink) client.set_debuglink(debuglink) - client.set_tx_api(coins.tx_api['Bitcoin']) + client.set_tx_api(coins.tx_api["Bitcoin"]) client.wipe_device() client.transport.session_begin() @@ -62,29 +62,41 @@ def client(): client.close() -def setup_client(mnemonic=None, pin='', passphrase=False): +def setup_client(mnemonic=None, pin="", passphrase=False): if mnemonic is None: - mnemonic = ' '.join(['all'] * 12) + mnemonic = " ".join(["all"] * 12) if pin is True: - pin = '1234' + pin = "1234" def client_decorator(function): @functools.wraps(function) def wrapper(client, *args, **kwargs): - client.load_device_by_mnemonic(mnemonic=mnemonic, pin=pin, passphrase_protection=passphrase, label='test', language='english') + client.load_device_by_mnemonic( + mnemonic=mnemonic, + pin=pin, + passphrase_protection=passphrase, + label="test", + language="english", + ) return function(client, *args, **kwargs) + return wrapper return client_decorator def pytest_configure(config): - if config.getoption('verbose'): + if config.getoption("verbose"): log.enable_debug_output() def pytest_addoption(parser): - parser.addini("run_xfail", "List of markers that will run even if marked as xfail", "args", []) + parser.addini( + "run_xfail", + "List of markers that will run even tests that are marked as xfail", + "args", + [], + ) def pytest_runtest_setup(item): @@ -105,7 +117,8 @@ def pytest_runtest_setup(item): pytest.skip("Test excluded on Trezor 1") xfail = item.get_marker("xfail") - run_xfail = any(item.get_marker(marker) for marker in item.config.getini("run_xfail")) + runxfail_markers = item.config.getini("run_xfail") + run_xfail = any(item.get_marker(marker) for marker in runxfail_markers) if xfail and run_xfail: # Deep hack: pytest's private _evalxfail helper determines whether the test should xfail or not. # The helper caches its result even before this hook runs. diff --git a/trezorlib/tests/device_tests/test_basic.py b/trezorlib/tests/device_tests/test_basic.py index e3203e059e..707dc014b8 100644 --- a/trezorlib/tests/device_tests/test_basic.py +++ b/trezorlib/tests/device_tests/test_basic.py @@ -14,22 +14,20 @@ # You should have received a copy of the License along with this library. # If not, see . -from .common import TrezorTest +from trezorlib import device, messages -from trezorlib import messages -from trezorlib import device +from .common import TrezorTest class TestBasic(TrezorTest): - def test_features(self): f0 = self.client.features f1 = self.client.call(messages.Initialize()) assert f0 == f1 def test_ping(self): - ping = self.client.call(messages.Ping(message='ahoj!')) - assert ping == messages.Success(message='ahoj!') + ping = self.client.call(messages.Ping(message="ahoj!")) + assert ping == messages.Success(message="ahoj!") def test_device_id_same(self): id1 = self.client.get_device_id() diff --git a/trezorlib/tests/device_tests/test_bip32_speed.py b/trezorlib/tests/device_tests/test_bip32_speed.py index 001e6fae5e..b1aeeeaae6 100644 --- a/trezorlib/tests/device_tests/test_bip32_speed.py +++ b/trezorlib/tests/device_tests/test_bip32_speed.py @@ -15,24 +15,24 @@ # If not, see . import time + import pytest +from trezorlib import btc +from trezorlib.tools import H_ + from .common import TrezorTest -from trezorlib.tools import H_ -from trezorlib import btc - class TestBip32Speed(TrezorTest): - def test_public_ckd(self): self.setup_mnemonic_nopin_nopassphrase() - btc.get_address(self.client, 'Bitcoin', []) # to compute root node via BIP39 + btc.get_address(self.client, "Bitcoin", []) # to compute root node via BIP39 for depth in range(8): start = time.time() - btc.get_address(self.client, 'Bitcoin', range(depth)) + btc.get_address(self.client, "Bitcoin", range(depth)) delay = time.time() - start expected = (depth + 1) * 0.26 print("DEPTH", depth, "EXPECTED DELAY", expected, "REAL DELAY", delay) @@ -41,12 +41,12 @@ class TestBip32Speed(TrezorTest): def test_private_ckd(self): self.setup_mnemonic_nopin_nopassphrase() - btc.get_address(self.client, 'Bitcoin', []) # to compute root node via BIP39 + btc.get_address(self.client, "Bitcoin", []) # to compute root node via BIP39 for depth in range(8): start = time.time() address_n = [H_(-i) for i in range(-depth, 0)] - btc.get_address(self.client, 'Bitcoin', address_n) + btc.get_address(self.client, "Bitcoin", address_n) delay = time.time() - start expected = (depth + 1) * 0.26 print("DEPTH", depth, "EXPECTED DELAY", expected, "REAL DELAY", delay) @@ -58,12 +58,12 @@ class TestBip32Speed(TrezorTest): start = time.time() for x in range(10): - btc.get_address(self.client, 'Bitcoin', [x, 2, 3, 4, 5, 6, 7, 8]) + btc.get_address(self.client, "Bitcoin", [x, 2, 3, 4, 5, 6, 7, 8]) nocache_time = time.time() - start start = time.time() for x in range(10): - btc.get_address(self.client, 'Bitcoin', [1, 2, 3, 4, 5, 6, 7, x]) + btc.get_address(self.client, "Bitcoin", [1, 2, 3, 4, 5, 6, 7, x]) cache_time = time.time() - start print("NOCACHE TIME", nocache_time) diff --git a/trezorlib/tests/device_tests/test_cancel.py b/trezorlib/tests/device_tests/test_cancel.py index 1ac12dbd97..1259d67f9c 100644 --- a/trezorlib/tests/device_tests/test_cancel.py +++ b/trezorlib/tests/device_tests/test_cancel.py @@ -16,20 +16,24 @@ import pytest -from .conftest import setup_client import trezorlib.messages as m +from .conftest import setup_client + @setup_client() -@pytest.mark.parametrize("message", [ - m.Ping(message="hello", button_protection=True), - m.GetAddress( - address_n=[0], - coin_name="Bitcoin", - script_type=m.InputScriptType.SPENDADDRESS, - show_display=True - ), -]) +@pytest.mark.parametrize( + "message", + [ + m.Ping(message="hello", button_protection=True), + m.GetAddress( + address_n=[0], + coin_name="Bitcoin", + script_type=m.InputScriptType.SPENDADDRESS, + show_display=True, + ), + ], +) def test_cancel_message_via_cancel(client, message): resp = client.call_raw(message) assert isinstance(resp, m.ButtonRequest) @@ -44,15 +48,18 @@ def test_cancel_message_via_cancel(client, message): @setup_client() -@pytest.mark.parametrize("message", [ - m.Ping(message="hello", button_protection=True), - m.GetAddress( - address_n=[0], - coin_name="Bitcoin", - script_type=m.InputScriptType.SPENDADDRESS, - show_display=True - ), -]) +@pytest.mark.parametrize( + "message", + [ + m.Ping(message="hello", button_protection=True), + m.GetAddress( + address_n=[0], + coin_name="Bitcoin", + script_type=m.InputScriptType.SPENDADDRESS, + show_display=True, + ), + ], +) def test_cancel_message_via_initialize(client, message): resp = client.call_raw(message) assert isinstance(resp, m.ButtonRequest) diff --git a/trezorlib/tests/device_tests/test_cosi.py b/trezorlib/tests/device_tests/test_cosi.py index 162ef76236..c8117fd7e8 100644 --- a/trezorlib/tests/device_tests/test_cosi.py +++ b/trezorlib/tests/device_tests/test_cosi.py @@ -14,22 +14,22 @@ # You should have received a copy of the License along with this library. # If not, see . -import pytest from hashlib import sha256 -from .common import TrezorTest -from trezorlib import cosi +import pytest +from trezorlib import cosi from trezorlib.tools import parse_path +from .common import TrezorTest + @pytest.mark.skip_t2 class TestCosi(TrezorTest): - def test_cosi_commit(self): self.setup_mnemonic_pin_passphrase() - digest = sha256(b'this is a message').digest() + digest = sha256(b"this is a message").digest() c0 = cosi.commit(self.client, parse_path("10018'/0'"), digest) c1 = cosi.commit(self.client, parse_path("10018'/1'"), digest) @@ -43,7 +43,7 @@ class TestCosi(TrezorTest): assert c0.commitment != c2.commitment assert c1.commitment != c2.commitment - digestb = sha256(b'this is a different message').digest() + digestb = sha256(b"this is a different message").digest() c0b = cosi.commit(self.client, parse_path("10018'/0'"), digestb) c1b = cosi.commit(self.client, parse_path("10018'/1'"), digestb) @@ -60,7 +60,7 @@ class TestCosi(TrezorTest): def test_cosi_sign(self): self.setup_mnemonic_pin_passphrase() - digest = sha256(b'this is a message').digest() + digest = sha256(b"this is a message").digest() c0 = cosi.commit(self.client, parse_path("10018'/0'"), digest) c1 = cosi.commit(self.client, parse_path("10018'/1'"), digest) @@ -69,29 +69,37 @@ class TestCosi(TrezorTest): global_pk = cosi.combine_keys([c0.pubkey, c1.pubkey, c2.pubkey]) global_R = cosi.combine_keys([c0.commitment, c1.commitment, c2.commitment]) + # fmt: off sig0 = cosi.sign(self.client, parse_path("10018'/0'"), digest, global_R, global_pk) sig1 = cosi.sign(self.client, parse_path("10018'/1'"), digest, global_R, global_pk) sig2 = cosi.sign(self.client, parse_path("10018'/2'"), digest, global_R, global_pk) + # fmt: on - sig = cosi.combine_sig(global_R, [sig0.signature, sig1.signature, sig2.signature]) + sig = cosi.combine_sig( + global_R, [sig0.signature, sig1.signature, sig2.signature] + ) cosi.verify(sig, digest, global_pk) def test_cosi_compat(self): self.setup_mnemonic_pin_passphrase() - digest = sha256(b'this is not a pipe').digest() + digest = sha256(b"this is not a pipe").digest() remote_commit = cosi.commit(self.client, parse_path("10018'/0'"), digest) - local_privkey = sha256(b'private key').digest()[:32] + local_privkey = sha256(b"private key").digest()[:32] local_pubkey = cosi.pubkey_from_privkey(local_privkey) local_nonce, local_commitment = cosi.get_nonce(local_privkey, digest, 42) global_pk = cosi.combine_keys([remote_commit.pubkey, local_pubkey]) global_R = cosi.combine_keys([remote_commit.commitment, local_commitment]) - remote_sig = cosi.sign(self.client, parse_path("10018'/0'"), digest, global_R, global_pk) - local_sig = cosi.sign_with_privkey(digest, local_privkey, global_pk, local_nonce, global_R) + remote_sig = cosi.sign( + self.client, parse_path("10018'/0'"), digest, global_R, global_pk + ) + local_sig = cosi.sign_with_privkey( + digest, local_privkey, global_pk, local_nonce, global_R + ) sig = cosi.combine_sig(global_R, [remote_sig.signature, local_sig]) cosi.verify(sig, digest, global_pk) diff --git a/trezorlib/tests/device_tests/test_debuglink.py b/trezorlib/tests/device_tests/test_debuglink.py index 76f197f2d5..68f7a5e6da 100644 --- a/trezorlib/tests/device_tests/test_debuglink.py +++ b/trezorlib/tests/device_tests/test_debuglink.py @@ -16,13 +16,13 @@ import pytest -from .common import TrezorTest from trezorlib import messages as proto +from .common import TrezorTest + @pytest.mark.skip_t2 class TestDebuglink(TrezorTest): - def test_layout(self): layout = self.client.debug.read_layout() assert len(layout) == 1024 @@ -36,12 +36,12 @@ class TestDebuglink(TrezorTest): self.setup_mnemonic_pin_passphrase() # Manually trigger PinMatrixRequest - resp = self.client.call_raw(proto.Ping(message='test', pin_protection=True)) + resp = self.client.call_raw(proto.Ping(message="test", pin_protection=True)) assert isinstance(resp, proto.PinMatrixRequest) pin = self.client.debug.read_pin() - assert pin[0] == '1234' - assert pin[1] != '' + assert pin[0] == "1234" + assert pin[1] != "" pin_encoded = self.client.debug.read_pin_encoded() resp = self.client.call_raw(proto.PinMatrixAck(pin=pin_encoded)) diff --git a/trezorlib/tests/device_tests/test_msg_applysettings.py b/trezorlib/tests/device_tests/test_msg_applysettings.py index f5541d6383..050277d482 100644 --- a/trezorlib/tests/device_tests/test_msg_applysettings.py +++ b/trezorlib/tests/device_tests/test_msg_applysettings.py @@ -14,45 +14,52 @@ # You should have received a copy of the License along with this library. # If not, see . +import time + import pytest +from trezorlib import device, messages as proto + from .common import TrezorTest -import time -from trezorlib import messages as proto -from trezorlib import device - class TestMsgApplysettings(TrezorTest): - def test_apply_settings(self): self.setup_mnemonic_pin_passphrase() - assert self.client.features.label == 'test' + assert self.client.features.label == "test" with self.client: - self.client.set_expected_responses([proto.PinMatrixRequest(), - proto.ButtonRequest(), - proto.Success(), - proto.Features()]) + self.client.set_expected_responses( + [ + proto.PinMatrixRequest(), + proto.ButtonRequest(), + proto.Success(), + proto.Features(), + ] + ) if self.client.features.major_version >= 2: self.client.expected_responses.pop(0) # skip PinMatrixRequest - device.apply_settings(self.client, label='new label') + device.apply_settings(self.client, label="new label") - assert self.client.features.label == 'new label' + assert self.client.features.label == "new label" @pytest.mark.skip_t2 def test_invalid_language(self): self.setup_mnemonic_pin_passphrase() - assert self.client.features.language == 'english' + assert self.client.features.language == "english" with self.client: - self.client.set_expected_responses([proto.PinMatrixRequest(), - proto.ButtonRequest(), - proto.Success(), - proto.Features()]) - device.apply_settings(self.client, language='nonexistent') + self.client.set_expected_responses( + [ + proto.PinMatrixRequest(), + proto.ButtonRequest(), + proto.Success(), + proto.Features(), + ] + ) + device.apply_settings(self.client, language="nonexistent") - assert self.client.features.language == 'english' + assert self.client.features.language == "english" def test_apply_settings_passphrase(self): self.setup_mnemonic_pin_nopassphrase() @@ -60,10 +67,14 @@ class TestMsgApplysettings(TrezorTest): assert self.client.features.passphrase_protection is False with self.client: - self.client.set_expected_responses([proto.PinMatrixRequest(), - proto.ButtonRequest(), - proto.Success(), - proto.Features()]) + self.client.set_expected_responses( + [ + proto.PinMatrixRequest(), + proto.ButtonRequest(), + proto.Success(), + proto.Features(), + ] + ) if self.client.features.major_version >= 2: self.client.expected_responses.pop(0) # skip PinMatrixRequest device.apply_settings(self.client, use_passphrase=True) @@ -71,17 +82,17 @@ class TestMsgApplysettings(TrezorTest): assert self.client.features.passphrase_protection is True with self.client: - self.client.set_expected_responses([proto.ButtonRequest(), - proto.Success(), - proto.Features()]) + self.client.set_expected_responses( + [proto.ButtonRequest(), proto.Success(), proto.Features()] + ) device.apply_settings(self.client, use_passphrase=False) assert self.client.features.passphrase_protection is False with self.client: - self.client.set_expected_responses([proto.ButtonRequest(), - proto.Success(), - proto.Features()]) + self.client.set_expected_responses( + [proto.ButtonRequest(), proto.Success(), proto.Features()] + ) device.apply_settings(self.client, use_passphrase=True) assert self.client.features.passphrase_protection is True @@ -93,10 +104,14 @@ class TestMsgApplysettings(TrezorTest): img = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"\x00\x00\x00\x00\x04\x80\x00\x00\x00\x00\x00\x00\x00\x00\x04\x88\x02\x00\x00\x00\x02\x91\x00\x00\x00\x00\x00\x00\x80\x00\x00\x00\x00\x90@\x00\x11@\x00\x00\x00\x00\x00\x00\x08\x00\x10\x92\x12\x04\x00\x00\x05\x12D\x00\x00\x00\x00\x00 \x00\x00\x08\x00Q\x00\x00\x02\xc0\x00\x00\x00\x00\x00\x00\x00\x10\x02 \x01\x04J\x00)$\x00\x00\x00\x00\x80\x00\x00\x00\x00\x08\x10\xa1\x00\x00\x02\x81 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00\tP\x00\x00\x00\x00\x00\x00 \x00\x00\xa0\x00\xa0R \x12\x84\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\t\x08\x00\tP\x00\x00\x00\x00 \x00\x04 \x00\x80\x02\x00@\x02T\xc2 \x00\x00\x00\x00\x00\x00\x00\x10@\x00)\t@\n\xa0\x80\x00\x00\x00\x00\x00\x00\x00\x00\x10\x00\x80@\x14\xa9H\x04\x00\x00\x88@\x00\x00\x00\x00\x00\x02\x02$\x00\x15B@\x00\nP\x00\x00\x00\x00\x00\x80\x00\x00\x91\x01UP\x00\x00 \x02\x00\x00\x00\x00\x00\x00\x02\x08@ Z\xa5 \x00\x00\x80\x00\x00\x00\x00\x00\x00\x08\xa1%\x14*\xa0\x00\x00\x02\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00@\xaa\x91 \x00\x05E\x80\x00\x00\x00\x00\x00\x02*T\x05-D\x00\x00\x05 @\x00\x00\x00\x00\x00%@\x80\x11V\xa0\x88\x00\x05@\xb0\x00\x00\x00\x00\x00\x818$\x04\xabD \x00\x06\xa1T\x00\x00\x00\x00\x02\x03\xb8\x01R\xd5\x01\x00\x00\x05AP\x00\x00\x00\x00\x08\xadT\x00\x05j\xa4@\x00\x87ah\x00\x00\x00\x00\x02\x8d\xb8\x08\x00.\x01\x00\x00\x02\xa5\xa8\x10\x00\x00\x00*\xc1\xec \n\xaa\x88 \x02@\xf6\xd0\x02\x00\x00\x00\x0bB\xb6\x14@U"\x80\x00\x01{`\x00\x00\x00\x00M\xa3\xf8 \x15*\x00\x00\x00\x10n\xc0\x04\x00\x00\x02\x06\xc2\xa8)\x00\x96\x84\x80\x00\x00\x1b\x00\x00\x80@\x10\x87\xa7\xf0\x84\x10\xaa\x10\x00\x00D\x00\x00\x02 \x00\x8a\x06\xfa\xe0P\n-\x02@\x00\x12\x00\x00\x00\x00\x10@\x83\xdf\xa0\x00\x08\xaa@\x00\x00\x01H\x00\x05H\x04\x12\x01\xf7\x81P\x02T\t\x00\x00\x00 \x00\x00\x84\x10\x00\x00z\x00@)* \x00\x00\x01\n\xa0\x02 \x05\n\x00\x00\x05\x10\x84\xa8\x84\x80\x00\x00@\x14\x00\x92\x10\x80\x00\x04\x11@\tT\x00\x00\x00\x00\n@\x00\x08\x84@$\x00H\x00\x12Q\x02\x00\x00\x00\x00\x90\x02A\x12\xa8\n\xaa\x92\x10\x04\xa8\x10@\x00\x00\x04\x04\x00\x04I\x00\x04\x14H\x80"R\x01\x00\x00\x00!@\x00\x00$\xa0EB\x80\x08\x95hH\x00\x00\x00\x84\x10 \x05Z\x00\x00(\x00\x02\x00\xa1\x01\x00\x00\x04\x00@\x82\x00\xadH*\x92P\x00\xaaP\x00\x00\x00\x00\x11\x02\x01*\xad\x01\x00\x01\x01"\x11D\x08\x00\x00\x10\x80 \x00\x81W\x80J\x94\x04\x08\xa5 !\x00\x00\x00\x02\x00B*\xae\xa1\x00\x80\x10\x01\x08\xa4\x00\x00\x00\x00\x00\x84\x00\t[@"HA\x04E\x00\x84\x00\x00\x00\x10\x00\x01J\xd5\x82\x90\x02\x00!\x02\xa2\x00\x00\x00\x00\x00\x00\x00\x05~\xa0\x00 \x10\n)\x00\x11\x00\x00\x00\x00\x00\x00!U\x80\xa8\x88\x82\x80\x01\x00\x00\x00\x00\x00\x00H@\x11\xaa\xc0\x82\x00 *\n\x00\x00\x00\x00\x00\x00\x00\x00\n\xabb@ \x04\x00! \x84\x00\x00\x00\x00\x02@\xa5\x15A$\x04\x81(\n\x00\x00\x00\x00\x00\x00 \x01\x10\x02\xe0\x91\x02\x00\x00\x04\x00\x00\x00\x00\x00\x00\x01 \xa9\tQH@\x91 P\x00\x00\x00\x00\x00\x00\x08\x00\x00\xa0T\xa5\x00@\x80\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"\x00\x00\x00\x00\xa2\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00 T\xa0\t\x00\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00@\x02\xa0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00*\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x10\x00\x00\x10\x02\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\t\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00@\x04\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x08@\x10\x00\x00\x00\x00' with self.client: - self.client.set_expected_responses([proto.PinMatrixRequest(), - proto.ButtonRequest(), - proto.Success(), - proto.Features()]) + self.client.set_expected_responses( + [ + proto.PinMatrixRequest(), + proto.ButtonRequest(), + proto.Success(), + proto.Features(), + ] + ) device.apply_settings(self.client, homescreen=img) @pytest.mark.skip_t2 @@ -104,23 +119,28 @@ class TestMsgApplysettings(TrezorTest): self.setup_mnemonic_pin_passphrase() with self.client: - self.client.set_expected_responses([proto.PinMatrixRequest(), - proto.ButtonRequest(), - proto.Success(), - proto.Features()]) + self.client.set_expected_responses( + [ + proto.PinMatrixRequest(), + proto.ButtonRequest(), + proto.Success(), + proto.Features(), + ] + ) device.apply_settings(self.client, auto_lock_delay_ms=int(10e3)) # 10 secs time.sleep(0.1) # sleep less than auto-lock delay with self.client: # No PIN protection is required. self.client.set_expected_responses([proto.Success()]) - self.client.ping(msg='', pin_protection=True) + self.client.ping(msg="", pin_protection=True) time.sleep(10.1) # sleep more than auto-lock delay with self.client: - self.client.set_expected_responses([proto.PinMatrixRequest(), - proto.Success()]) - self.client.ping(msg='', pin_protection=True) + self.client.set_expected_responses( + [proto.PinMatrixRequest(), proto.Success()] + ) + self.client.ping(msg="", pin_protection=True) @pytest.mark.skip_t2 def test_apply_minimal_auto_lock_delay(self): @@ -131,10 +151,14 @@ class TestMsgApplysettings(TrezorTest): self.setup_mnemonic_pin_passphrase() with self.client: - self.client.set_expected_responses([proto.PinMatrixRequest(), - proto.ButtonRequest(), - proto.Success(), - proto.Features()]) + self.client.set_expected_responses( + [ + proto.PinMatrixRequest(), + proto.ButtonRequest(), + proto.Success(), + proto.Features(), + ] + ) # Note: the actual delay will be 10 secs (see above). device.apply_settings(self.client, auto_lock_delay_ms=int(1e3)) @@ -142,16 +166,17 @@ class TestMsgApplysettings(TrezorTest): with self.client: # No PIN protection is required. self.client.set_expected_responses([proto.Success()]) - self.client.ping(msg='', pin_protection=True) + self.client.ping(msg="", pin_protection=True) time.sleep(2) # sleep less than the minimal auto-lock delay with self.client: # No PIN protection is required. self.client.set_expected_responses([proto.Success()]) - self.client.ping(msg='', pin_protection=True) + self.client.ping(msg="", pin_protection=True) time.sleep(10.1) # sleep more than the minimal auto-lock delay with self.client: - self.client.set_expected_responses([proto.PinMatrixRequest(), - proto.Success()]) - self.client.ping(msg='', pin_protection=True) + self.client.set_expected_responses( + [proto.PinMatrixRequest(), proto.Success()] + ) + self.client.ping(msg="", pin_protection=True) diff --git a/trezorlib/tests/device_tests/test_msg_changepin.py b/trezorlib/tests/device_tests/test_msg_changepin.py index 85d5317b62..d9a27e326a 100644 --- a/trezorlib/tests/device_tests/test_msg_changepin.py +++ b/trezorlib/tests/device_tests/test_msg_changepin.py @@ -16,14 +16,13 @@ import pytest -from .common import TrezorTest - from trezorlib import messages as proto +from .common import TrezorTest + @pytest.mark.skip_t2 class TestMsgChangepin(TrezorTest): - def test_set_pin(self): self.setup_mnemonic_nopin_nopassphrase() features = self.client.call_raw(proto.Initialize()) @@ -206,7 +205,7 @@ class TestMsgChangepin(TrezorTest): # Send the PIN for second time, but with typo assert isinstance(ret, proto.PinMatrixRequest) - pin_encoded = self.client.debug.encode_pin(self.pin6 + '3') + pin_encoded = self.client.debug.encode_pin(self.pin6 + "3") ret = self.client.call_raw(proto.PinMatrixAck(pin=pin_encoded)) # Now it should fail, because pins are different diff --git a/trezorlib/tests/device_tests/test_msg_cipherkeyvalue.py b/trezorlib/tests/device_tests/test_msg_cipherkeyvalue.py index 5527580453..e1dfe872d6 100644 --- a/trezorlib/tests/device_tests/test_msg_cipherkeyvalue.py +++ b/trezorlib/tests/device_tests/test_msg_cipherkeyvalue.py @@ -15,69 +15,173 @@ # If not, see . from binascii import hexlify, unhexlify + import pytest -from .common import TrezorTest from trezorlib import misc +from .common import TrezorTest + class TestMsgCipherkeyvalue(TrezorTest): - def test_encrypt(self): self.setup_mnemonic_nopin_nopassphrase() # different ask values - res = misc.encrypt_keyvalue(self.client, [0, 1, 2], b"test", b"testing message!", ask_on_encrypt=True, ask_on_decrypt=True) - assert hexlify(res) == b'676faf8f13272af601776bc31bc14e8f' + res = misc.encrypt_keyvalue( + self.client, + [0, 1, 2], + b"test", + b"testing message!", + ask_on_encrypt=True, + ask_on_decrypt=True, + ) + assert hexlify(res) == b"676faf8f13272af601776bc31bc14e8f" - res = misc.encrypt_keyvalue(self.client, [0, 1, 2], b"test", b"testing message!", ask_on_encrypt=True, ask_on_decrypt=False) - assert hexlify(res) == b'5aa0fbcb9d7fa669880745479d80c622' + res = misc.encrypt_keyvalue( + self.client, + [0, 1, 2], + b"test", + b"testing message!", + ask_on_encrypt=True, + ask_on_decrypt=False, + ) + assert hexlify(res) == b"5aa0fbcb9d7fa669880745479d80c622" - res = misc.encrypt_keyvalue(self.client, [0, 1, 2], b"test", b"testing message!", ask_on_encrypt=False, ask_on_decrypt=True) - assert hexlify(res) == b'958d4f63269b61044aaedc900c8d6208' + res = misc.encrypt_keyvalue( + self.client, + [0, 1, 2], + b"test", + b"testing message!", + ask_on_encrypt=False, + ask_on_decrypt=True, + ) + assert hexlify(res) == b"958d4f63269b61044aaedc900c8d6208" - res = misc.encrypt_keyvalue(self.client, [0, 1, 2], b"test", b"testing message!", ask_on_encrypt=False, ask_on_decrypt=False) - assert hexlify(res) == b'e0cf0eb0425947000eb546cc3994bc6c' + res = misc.encrypt_keyvalue( + self.client, + [0, 1, 2], + b"test", + b"testing message!", + ask_on_encrypt=False, + ask_on_decrypt=False, + ) + assert hexlify(res) == b"e0cf0eb0425947000eb546cc3994bc6c" # different key - res = misc.encrypt_keyvalue(self.client, [0, 1, 2], b"test2", b"testing message!", ask_on_encrypt=True, ask_on_decrypt=True) - assert hexlify(res) == b'de247a6aa6be77a134bb3f3f925f13af' + res = misc.encrypt_keyvalue( + self.client, + [0, 1, 2], + b"test2", + b"testing message!", + ask_on_encrypt=True, + ask_on_decrypt=True, + ) + assert hexlify(res) == b"de247a6aa6be77a134bb3f3f925f13af" # different message - res = misc.encrypt_keyvalue(self.client, [0, 1, 2], b"test", b"testing message! it is different", ask_on_encrypt=True, ask_on_decrypt=True) - assert hexlify(res) == b'676faf8f13272af601776bc31bc14e8f3ae1c88536bf18f1b44f1e4c2c4a613d' + res = misc.encrypt_keyvalue( + self.client, + [0, 1, 2], + b"test", + b"testing message! it is different", + ask_on_encrypt=True, + ask_on_decrypt=True, + ) + assert ( + hexlify(res) + == b"676faf8f13272af601776bc31bc14e8f3ae1c88536bf18f1b44f1e4c2c4a613d" + ) # different path - res = misc.encrypt_keyvalue(self.client, [0, 1, 3], b"test", b"testing message!", ask_on_encrypt=True, ask_on_decrypt=True) - assert hexlify(res) == b'b4811a9d492f5355a5186ddbfccaae7b' + res = misc.encrypt_keyvalue( + self.client, + [0, 1, 3], + b"test", + b"testing message!", + ask_on_encrypt=True, + ask_on_decrypt=True, + ) + assert hexlify(res) == b"b4811a9d492f5355a5186ddbfccaae7b" def test_decrypt(self): self.setup_mnemonic_nopin_nopassphrase() # different ask values - res = misc.decrypt_keyvalue(self.client, [0, 1, 2], b"test", unhexlify("676faf8f13272af601776bc31bc14e8f"), ask_on_encrypt=True, ask_on_decrypt=True) - assert res == b'testing message!' + res = misc.decrypt_keyvalue( + self.client, + [0, 1, 2], + b"test", + unhexlify("676faf8f13272af601776bc31bc14e8f"), + ask_on_encrypt=True, + ask_on_decrypt=True, + ) + assert res == b"testing message!" - res = misc.decrypt_keyvalue(self.client, [0, 1, 2], b"test", unhexlify("5aa0fbcb9d7fa669880745479d80c622"), ask_on_encrypt=True, ask_on_decrypt=False) - assert res == b'testing message!' + res = misc.decrypt_keyvalue( + self.client, + [0, 1, 2], + b"test", + unhexlify("5aa0fbcb9d7fa669880745479d80c622"), + ask_on_encrypt=True, + ask_on_decrypt=False, + ) + assert res == b"testing message!" - res = misc.decrypt_keyvalue(self.client, [0, 1, 2], b"test", unhexlify("958d4f63269b61044aaedc900c8d6208"), ask_on_encrypt=False, ask_on_decrypt=True) - assert res == b'testing message!' + res = misc.decrypt_keyvalue( + self.client, + [0, 1, 2], + b"test", + unhexlify("958d4f63269b61044aaedc900c8d6208"), + ask_on_encrypt=False, + ask_on_decrypt=True, + ) + assert res == b"testing message!" - res = misc.decrypt_keyvalue(self.client, [0, 1, 2], b"test", unhexlify("e0cf0eb0425947000eb546cc3994bc6c"), ask_on_encrypt=False, ask_on_decrypt=False) - assert res == b'testing message!' + res = misc.decrypt_keyvalue( + self.client, + [0, 1, 2], + b"test", + unhexlify("e0cf0eb0425947000eb546cc3994bc6c"), + ask_on_encrypt=False, + ask_on_decrypt=False, + ) + assert res == b"testing message!" # different key - res = misc.decrypt_keyvalue(self.client, [0, 1, 2], b"test2", unhexlify("de247a6aa6be77a134bb3f3f925f13af"), ask_on_encrypt=True, ask_on_decrypt=True) - assert res == b'testing message!' + res = misc.decrypt_keyvalue( + self.client, + [0, 1, 2], + b"test2", + unhexlify("de247a6aa6be77a134bb3f3f925f13af"), + ask_on_encrypt=True, + ask_on_decrypt=True, + ) + assert res == b"testing message!" # different message - res = misc.decrypt_keyvalue(self.client, [0, 1, 2], b"test", unhexlify("676faf8f13272af601776bc31bc14e8f3ae1c88536bf18f1b44f1e4c2c4a613d"), ask_on_encrypt=True, ask_on_decrypt=True) - assert res == b'testing message! it is different' + res = misc.decrypt_keyvalue( + self.client, + [0, 1, 2], + b"test", + unhexlify( + "676faf8f13272af601776bc31bc14e8f3ae1c88536bf18f1b44f1e4c2c4a613d" + ), + ask_on_encrypt=True, + ask_on_decrypt=True, + ) + assert res == b"testing message! it is different" # different path - res = misc.decrypt_keyvalue(self.client, [0, 1, 3], b"test", unhexlify("b4811a9d492f5355a5186ddbfccaae7b"), ask_on_encrypt=True, ask_on_decrypt=True) - assert res == b'testing message!' + res = misc.decrypt_keyvalue( + self.client, + [0, 1, 3], + b"test", + unhexlify("b4811a9d492f5355a5186ddbfccaae7b"), + ask_on_encrypt=True, + ask_on_decrypt=True, + ) + assert res == b"testing message!" def test_encrypt_badlen(self): self.setup_mnemonic_nopin_nopassphrase() diff --git a/trezorlib/tests/device_tests/test_msg_clearsession.py b/trezorlib/tests/device_tests/test_msg_clearsession.py index d7051a8a30..e0c11c186c 100644 --- a/trezorlib/tests/device_tests/test_msg_clearsession.py +++ b/trezorlib/tests/device_tests/test_msg_clearsession.py @@ -16,38 +16,81 @@ import pytest -from .common import TrezorTest - from trezorlib import messages as proto +from .common import TrezorTest + @pytest.mark.skip_t2 class TestMsgClearsession(TrezorTest): - def test_clearsession(self): self.setup_mnemonic_pin_passphrase() with self.client: - self.client.set_expected_responses([proto.ButtonRequest(code=proto.ButtonRequestType.ProtectCall), proto.PinMatrixRequest(), proto.PassphraseRequest(), proto.Success()]) - res = self.client.ping('random data', button_protection=True, pin_protection=True, passphrase_protection=True) - assert res == 'random data' + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.ProtectCall), + proto.PinMatrixRequest(), + proto.PassphraseRequest(), + proto.Success(), + ] + ) + res = self.client.ping( + "random data", + button_protection=True, + pin_protection=True, + passphrase_protection=True, + ) + assert res == "random data" with self.client: # pin and passphrase are cached - self.client.set_expected_responses([proto.ButtonRequest(code=proto.ButtonRequestType.ProtectCall), proto.Success()]) - res = self.client.ping('random data', button_protection=True, pin_protection=True, passphrase_protection=True) - assert res == 'random data' + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.ProtectCall), + proto.Success(), + ] + ) + res = self.client.ping( + "random data", + button_protection=True, + pin_protection=True, + passphrase_protection=True, + ) + assert res == "random data" self.client.clear_session() # session cache is cleared with self.client: - self.client.set_expected_responses([proto.ButtonRequest(code=proto.ButtonRequestType.ProtectCall), proto.PinMatrixRequest(), proto.PassphraseRequest(), proto.Success()]) - res = self.client.ping('random data', button_protection=True, pin_protection=True, passphrase_protection=True) - assert res == 'random data' + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.ProtectCall), + proto.PinMatrixRequest(), + proto.PassphraseRequest(), + proto.Success(), + ] + ) + res = self.client.ping( + "random data", + button_protection=True, + pin_protection=True, + passphrase_protection=True, + ) + assert res == "random data" with self.client: # pin and passphrase are cached - self.client.set_expected_responses([proto.ButtonRequest(code=proto.ButtonRequestType.ProtectCall), proto.Success()]) - res = self.client.ping('random data', button_protection=True, pin_protection=True, passphrase_protection=True) - assert res == 'random data' + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.ProtectCall), + proto.Success(), + ] + ) + res = self.client.ping( + "random data", + button_protection=True, + pin_protection=True, + passphrase_protection=True, + ) + assert res == "random data" diff --git a/trezorlib/tests/device_tests/test_msg_ethereum_getaddress.py b/trezorlib/tests/device_tests/test_msg_ethereum_getaddress.py index 9e8e48bda5..a34156b6ae 100644 --- a/trezorlib/tests/device_tests/test_msg_ethereum_getaddress.py +++ b/trezorlib/tests/device_tests/test_msg_ethereum_getaddress.py @@ -15,21 +15,36 @@ # If not, see . from binascii import hexlify + import pytest -from .common import TrezorTest - -from trezorlib.tools import H_ from trezorlib import ethereum +from trezorlib.tools import H_ + +from .common import TrezorTest @pytest.mark.ethereum class TestMsgEthereumGetaddress(TrezorTest): - def test_ethereum_getaddress(self): self.setup_mnemonic_nopin_nopassphrase() - assert hexlify(ethereum.get_address(self.client, [])) == b'1d1c328764a41bda0492b66baa30c4a339ff85ef' - assert hexlify(ethereum.get_address(self.client, [1])) == b'437207ca3cf43bf2e47dea0756d736c5df4f597a' - assert hexlify(ethereum.get_address(self.client, [0, H_(1)])) == b'e5d96dfa07bcf1a3ae43677840c31394258861bf' - assert hexlify(ethereum.get_address(self.client, [H_(9), 0])) == b'f68804ac9eca9483ab4241d3e4751590d2c05102' - assert hexlify(ethereum.get_address(self.client, [0, 9999999])) == b'7a6366ecfcaf0d5dcc1539c171696c6cdd1eb8ed' + assert ( + hexlify(ethereum.get_address(self.client, [])) + == b"1d1c328764a41bda0492b66baa30c4a339ff85ef" + ) + assert ( + hexlify(ethereum.get_address(self.client, [1])) + == b"437207ca3cf43bf2e47dea0756d736c5df4f597a" + ) + assert ( + hexlify(ethereum.get_address(self.client, [0, H_(1)])) + == b"e5d96dfa07bcf1a3ae43677840c31394258861bf" + ) + assert ( + hexlify(ethereum.get_address(self.client, [H_(9), 0])) + == b"f68804ac9eca9483ab4241d3e4751590d2c05102" + ) + assert ( + hexlify(ethereum.get_address(self.client, [0, 9999999])) + == b"7a6366ecfcaf0d5dcc1539c171696c6cdd1eb8ed" + ) diff --git a/trezorlib/tests/device_tests/test_msg_ethereum_signmessage.py b/trezorlib/tests/device_tests/test_msg_ethereum_signmessage.py index 41c122e20d..4bee25bdaf 100644 --- a/trezorlib/tests/device_tests/test_msg_ethereum_signmessage.py +++ b/trezorlib/tests/device_tests/test_msg_ethereum_signmessage.py @@ -15,20 +15,28 @@ # If not, see . from binascii import hexlify + import pytest -from .common import TrezorTest from trezorlib import ethereum +from .common import TrezorTest + @pytest.mark.ethereum class TestMsgEthereumSignmessage(TrezorTest): PATH = [0] - ADDRESS = b'cb3864960e8db1a751212c580af27ee8867d688f' + ADDRESS = b"cb3864960e8db1a751212c580af27ee8867d688f" VECTORS = [ - ('This is an example of a signed message.', b'b7837058907192dbc9427bf57d93a0acca3816c92927a08be573b785f2d72dab65dad9c92fbe03a358acdb455eab2107b869945d11f4e353d9cc6ea957d08a871b'), - ('VeryLongMessage!' * 64, b'da2b73b0170479c2bfba3dd4839bf0d67732a44df8c873f3f3a2aca8a57d7bdc0b5d534f54c649e2d44135717001998b176d3cd1212366464db51f5838430fb31c'), + ( + "This is an example of a signed message.", + b"b7837058907192dbc9427bf57d93a0acca3816c92927a08be573b785f2d72dab65dad9c92fbe03a358acdb455eab2107b869945d11f4e353d9cc6ea957d08a871b", + ), + ( + "VeryLongMessage!" * 64, + b"da2b73b0170479c2bfba3dd4839bf0d67732a44df8c873f3f3a2aca8a57d7bdc0b5d534f54c649e2d44135717001998b176d3cd1212366464db51f5838430fb31c", + ), ] def test_sign(self): diff --git a/trezorlib/tests/device_tests/test_msg_ethereum_signtx.py b/trezorlib/tests/device_tests/test_msg_ethereum_signtx.py index 020b978055..e107edaa5e 100644 --- a/trezorlib/tests/device_tests/test_msg_ethereum_signtx.py +++ b/trezorlib/tests/device_tests/test_msg_ethereum_signtx.py @@ -14,34 +14,44 @@ # You should have received a copy of the License along with this library. # If not, see . -from binascii import unhexlify, hexlify +from binascii import hexlify, unhexlify + import pytest +from trezorlib import ethereum, messages as proto + from .common import TrezorTest -from trezorlib import messages as proto -from trezorlib import ethereum @pytest.mark.ethereum class TestMsgEthereumSigntx(TrezorTest): - def test_ethereum_signtx_known_erc20_token(self): self.setup_mnemonic_nopin_nopassphrase() with self.client: - self.client.set_expected_responses([ - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.EthereumTxRequest(data_length=None), - ]) + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.EthereumTxRequest(data_length=None), + ] + ) data = bytearray() # method id signalizing `transfer(address _to, uint256 _value)` function - data.extend(unhexlify('a9059cbb')) + data.extend(unhexlify("a9059cbb")) # 1st function argument (to - the receiver) - data.extend(unhexlify('000000000000000000000000574bbb36871ba6b78e27f4b4dcfb76ea0091880b')) + data.extend( + unhexlify( + "000000000000000000000000574bbb36871ba6b78e27f4b4dcfb76ea0091880b" + ) + ) # 2nd function argument (value - amount to be transferred) - data.extend(unhexlify('000000000000000000000000000000000000000000000000000000000bebc200')) + data.extend( + unhexlify( + "000000000000000000000000000000000000000000000000000000000bebc200" + ) + ) # 200 000 000 in dec, divisibility of ADT = 9, trezor1 displays 0.2 ADT, Trezor T 200 000 000 Wei ADT sig_v, sig_r, sig_s = ethereum.sign_tx( @@ -51,33 +61,50 @@ class TestMsgEthereumSigntx(TrezorTest): gas_price=20, gas_limit=20, # ADT token address - to=b'\xd0\xd6\xd6\xc5\xfe\x4a\x67\x7d\x34\x3c\xc4\x33\x53\x6b\xb7\x17\xba\xe1\x67\xdd', + to=b"\xd0\xd6\xd6\xc5\xfe\x4a\x67\x7d\x34\x3c\xc4\x33\x53\x6b\xb7\x17\xba\xe1\x67\xdd", chain_id=1, # value needs to be 0, token value is set in the contract (data) value=0, - data=data) + data=data, + ) # taken from T1 might not be 100% correct but still better than nothing - assert hexlify(sig_r) == b'75cf48fa173d8ceb68af9e4fb6b78ef69e6ed5e7679ba6f8e3e91d74b2fb0f96' - assert hexlify(sig_s) == b'65de4a8c35263b2cfff3954b12146e8e568aa67a1c2461d6865e74ef75c7e190' + assert ( + hexlify(sig_r) + == b"75cf48fa173d8ceb68af9e4fb6b78ef69e6ed5e7679ba6f8e3e91d74b2fb0f96" + ) + assert ( + hexlify(sig_s) + == b"65de4a8c35263b2cfff3954b12146e8e568aa67a1c2461d6865e74ef75c7e190" + ) def test_ethereum_signtx_unknown_erc20_token(self): self.setup_mnemonic_nopin_nopassphrase() with self.client: - self.client.set_expected_responses([ - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.EthereumTxRequest(data_length=None), - ]) + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.EthereumTxRequest(data_length=None), + ] + ) data = bytearray() # method id signalizing `transfer(address _to, uint256 _value)` function - data.extend(unhexlify('a9059cbb')) + data.extend(unhexlify("a9059cbb")) # 1st function argument (to - the receiver) - data.extend(unhexlify('000000000000000000000000574bbb36871ba6b78e27f4b4dcfb76ea0091880b')) + data.extend( + unhexlify( + "000000000000000000000000574bbb36871ba6b78e27f4b4dcfb76ea0091880b" + ) + ) # 2nd function argument (value - amount to be transferred) - data.extend(unhexlify('0000000000000000000000000000000000000000000000000000000000000123')) + data.extend( + unhexlify( + "0000000000000000000000000000000000000000000000000000000000000123" + ) + ) # since this token is unknown trezor should display "unknown token value" sig_v, sig_r, sig_s = ethereum.sign_tx( @@ -87,25 +114,34 @@ class TestMsgEthereumSigntx(TrezorTest): gas_price=20, gas_limit=20, # unknown token address (Grzegorz Brzęczyszczykiewicz Token) - to=b'\xfc\x6b\x5d\x6a\xf8\xa1\x32\x58\xf7\xcb\xd0\xd3\x9e\x11\xb3\x5e\x01\xa3\x2f\x93', + to=b"\xfc\x6b\x5d\x6a\xf8\xa1\x32\x58\xf7\xcb\xd0\xd3\x9e\x11\xb3\x5e\x01\xa3\x2f\x93", chain_id=1, # value needs to be 0, token value is set in the contract (data) value=0, - data=data) + data=data, + ) # taken from T1 might not be 100% correct but still better than nothing - assert hexlify(sig_r) == b'1707471fbf632e42d18144157aaf4cde101cd9aa9782ad8e30583cfc95ddeef6' - assert hexlify(sig_s) == b'3d2e52ba5904a4bf131abde3f79db826199f5d6f4d241d531d7e8a30a3b9cfd9' + assert ( + hexlify(sig_r) + == b"1707471fbf632e42d18144157aaf4cde101cd9aa9782ad8e30583cfc95ddeef6" + ) + assert ( + hexlify(sig_s) + == b"3d2e52ba5904a4bf131abde3f79db826199f5d6f4d241d531d7e8a30a3b9cfd9" + ) def test_ethereum_signtx_nodata(self): self.setup_mnemonic_nopin_nopassphrase() with self.client: - self.client.set_expected_responses([ - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.EthereumTxRequest(data_length=None), # v,r,s checked with assert - ]) + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.EthereumTxRequest(data_length=None), # v,r,s checked later + ] + ) sig_v, sig_r, sig_s = ethereum.sign_tx( self.client, @@ -113,19 +149,28 @@ class TestMsgEthereumSigntx(TrezorTest): nonce=0, gas_price=20, gas_limit=20, - to=unhexlify('1d1c328764a41bda0492b66baa30c4a339ff85ef'), - value=10) + to=unhexlify("1d1c328764a41bda0492b66baa30c4a339ff85ef"), + value=10, + ) assert sig_v == 27 - assert hexlify(sig_r) == b'9b61192a161d056c66cfbbd331edb2d783a0193bd4f65f49ee965f791d898f72' - assert hexlify(sig_s) == b'49c0bbe35131592c6ed5c871ac457feeb16a1493f64237387fab9b83c1a202f7' + assert ( + hexlify(sig_r) + == b"9b61192a161d056c66cfbbd331edb2d783a0193bd4f65f49ee965f791d898f72" + ) + assert ( + hexlify(sig_s) + == b"49c0bbe35131592c6ed5c871ac457feeb16a1493f64237387fab9b83c1a202f7" + ) with self.client: - self.client.set_expected_responses([ - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.EthereumTxRequest(data_length=None), - ]) + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.EthereumTxRequest(data_length=None), + ] + ) sig_v, sig_r, sig_s = ethereum.sign_tx( self.client, @@ -133,22 +178,31 @@ class TestMsgEthereumSigntx(TrezorTest): nonce=123456, gas_price=20000, gas_limit=20000, - to=unhexlify('1d1c328764a41bda0492b66baa30c4a339ff85ef'), - value=12345678901234567890) + to=unhexlify("1d1c328764a41bda0492b66baa30c4a339ff85ef"), + value=12345678901234567890, + ) assert sig_v == 28 - assert hexlify(sig_r) == b'6de597b8ec1b46501e5b159676e132c1aa78a95bd5892ef23560a9867528975a' - assert hexlify(sig_s) == b'6e33c4230b1ecf96a8dbb514b4aec0a6d6ba53f8991c8143f77812aa6daa993f' + assert ( + hexlify(sig_r) + == b"6de597b8ec1b46501e5b159676e132c1aa78a95bd5892ef23560a9867528975a" + ) + assert ( + hexlify(sig_s) + == b"6e33c4230b1ecf96a8dbb514b4aec0a6d6ba53f8991c8143f77812aa6daa993f" + ) def test_ethereum_signtx_data(self): self.setup_mnemonic_nopin_nopassphrase() with self.client: - self.client.set_expected_responses([ - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.EthereumTxRequest(data_length=None), - ]) + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.EthereumTxRequest(data_length=None), + ] + ) sig_v, sig_r, sig_s = ethereum.sign_tx( self.client, @@ -156,24 +210,38 @@ class TestMsgEthereumSigntx(TrezorTest): nonce=0, gas_price=20, gas_limit=20, - to=unhexlify('1d1c328764a41bda0492b66baa30c4a339ff85ef'), + to=unhexlify("1d1c328764a41bda0492b66baa30c4a339ff85ef"), value=10, - data=b'abcdefghijklmnop' * 16) + data=b"abcdefghijklmnop" * 16, + ) assert sig_v == 28 - assert hexlify(sig_r) == b'6da89ed8627a491bedc9e0382f37707ac4e5102e25e7a1234cb697cedb7cd2c0' - assert hexlify(sig_s) == b'691f73b145647623e2d115b208a7c3455a6a8a83e3b4db5b9c6d9bc75825038a' + assert ( + hexlify(sig_r) + == b"6da89ed8627a491bedc9e0382f37707ac4e5102e25e7a1234cb697cedb7cd2c0" + ) + assert ( + hexlify(sig_s) + == b"691f73b145647623e2d115b208a7c3455a6a8a83e3b4db5b9c6d9bc75825038a" + ) with self.client: - self.client.set_expected_responses([ - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.EthereumTxRequest(data_length=1024, signature_r=None, signature_s=None, signature_v=None), - proto.EthereumTxRequest(data_length=1024), - proto.EthereumTxRequest(data_length=1024), - proto.EthereumTxRequest(data_length=3), - proto.EthereumTxRequest(), - ]) + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.EthereumTxRequest( + data_length=1024, + signature_r=None, + signature_s=None, + signature_v=None, + ), + proto.EthereumTxRequest(data_length=1024), + proto.EthereumTxRequest(data_length=1024), + proto.EthereumTxRequest(data_length=3), + proto.EthereumTxRequest(), + ] + ) sig_v, sig_r, sig_s = ethereum.sign_tx( self.client, @@ -181,27 +249,41 @@ class TestMsgEthereumSigntx(TrezorTest): nonce=123456, gas_price=20000, gas_limit=20000, - to=unhexlify('1d1c328764a41bda0492b66baa30c4a339ff85ef'), + to=unhexlify("1d1c328764a41bda0492b66baa30c4a339ff85ef"), value=12345678901234567890, - data=b'ABCDEFGHIJKLMNOP' * 256 + b'!!!') + data=b"ABCDEFGHIJKLMNOP" * 256 + b"!!!", + ) assert sig_v == 28 - assert hexlify(sig_r) == b'4e90b13c45c6a9bf4aaad0e5427c3e62d76692b36eb727c78d332441b7400404' - assert hexlify(sig_s) == b'3ff236e7d05f0f9b1ee3d70599bb4200638f28388a8faf6bb36db9e04dc544be' + assert ( + hexlify(sig_r) + == b"4e90b13c45c6a9bf4aaad0e5427c3e62d76692b36eb727c78d332441b7400404" + ) + assert ( + hexlify(sig_s) + == b"3ff236e7d05f0f9b1ee3d70599bb4200638f28388a8faf6bb36db9e04dc544be" + ) def test_ethereum_signtx_message(self): self.setup_mnemonic_nopin_nopassphrase() with self.client: - self.client.set_expected_responses([ - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.EthereumTxRequest(data_length=1024, signature_r=None, signature_s=None, signature_v=None), - proto.EthereumTxRequest(data_length=1024), - proto.EthereumTxRequest(data_length=1024), - proto.EthereumTxRequest(data_length=3), - proto.EthereumTxRequest(), - ]) + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.EthereumTxRequest( + data_length=1024, + signature_r=None, + signature_s=None, + signature_v=None, + ), + proto.EthereumTxRequest(data_length=1024), + proto.EthereumTxRequest(data_length=1024), + proto.EthereumTxRequest(data_length=3), + proto.EthereumTxRequest(), + ] + ) sig_v, sig_r, sig_s = ethereum.sign_tx( self.client, @@ -209,12 +291,19 @@ class TestMsgEthereumSigntx(TrezorTest): nonce=0, gas_price=20000, gas_limit=20000, - to=unhexlify('1d1c328764a41bda0492b66baa30c4a339ff85ef'), + to=unhexlify("1d1c328764a41bda0492b66baa30c4a339ff85ef"), value=0, - data=b'ABCDEFGHIJKLMNOP' * 256 + b'!!!') + data=b"ABCDEFGHIJKLMNOP" * 256 + b"!!!", + ) assert sig_v == 28 - assert hexlify(sig_r) == b'070e9dafda4d9e733fa7b6747a75f8a4916459560efb85e3e73cd39f31aa160d' - assert hexlify(sig_s) == b'7842db33ef15c27049ed52741db41fe3238a6fa3a6a0888fcfb74d6917600e41' + assert ( + hexlify(sig_r) + == b"070e9dafda4d9e733fa7b6747a75f8a4916459560efb85e3e73cd39f31aa160d" + ) + assert ( + hexlify(sig_s) + == b"7842db33ef15c27049ed52741db41fe3238a6fa3a6a0888fcfb74d6917600e41" + ) def test_ethereum_signtx_newcontract(self): self.setup_mnemonic_nopin_nopassphrase() @@ -227,21 +316,28 @@ class TestMsgEthereumSigntx(TrezorTest): nonce=123456, gas_price=20000, gas_limit=20000, - to='', - value=12345678901234567890 + to="", + value=12345678901234567890, ) with self.client: - self.client.set_expected_responses([ - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.EthereumTxRequest(data_length=1024, signature_r=None, signature_s=None, signature_v=None), - proto.EthereumTxRequest(data_length=1024), - proto.EthereumTxRequest(data_length=1024), - proto.EthereumTxRequest(data_length=3), - proto.EthereumTxRequest(), - ]) + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.EthereumTxRequest( + data_length=1024, + signature_r=None, + signature_s=None, + signature_v=None, + ), + proto.EthereumTxRequest(data_length=1024), + proto.EthereumTxRequest(data_length=1024), + proto.EthereumTxRequest(data_length=3), + proto.EthereumTxRequest(), + ] + ) sig_v, sig_r, sig_s = ethereum.sign_tx( self.client, @@ -249,12 +345,19 @@ class TestMsgEthereumSigntx(TrezorTest): nonce=0, gas_price=20000, gas_limit=20000, - to='', + to="", value=12345678901234567890, - data=b'ABCDEFGHIJKLMNOP' * 256 + b'!!!') + data=b"ABCDEFGHIJKLMNOP" * 256 + b"!!!", + ) assert sig_v == 28 - assert hexlify(sig_r) == b'b401884c10ae435a2e792303b5fc257a09f94403b2883ad8c0ac7a7282f5f1f9' - assert hexlify(sig_s) == b'4742fc9e6a5fa8db3db15c2d856914a7f3daab21603a6c1ce9e9927482f8352e' + assert ( + hexlify(sig_r) + == b"b401884c10ae435a2e792303b5fc257a09f94403b2883ad8c0ac7a7282f5f1f9" + ) + assert ( + hexlify(sig_s) + == b"4742fc9e6a5fa8db3db15c2d856914a7f3daab21603a6c1ce9e9927482f8352e" + ) def test_ethereum_sanity_checks(self): # gas overflow @@ -265,8 +368,8 @@ class TestMsgEthereumSigntx(TrezorTest): nonce=123456, gas_price=0xffffffffffffffffffffffffffffffff, gas_limit=0xffffffffffffffffffffffffffffff, - to=unhexlify('1d1c328764a41bda0492b66baa30c4a339ff85ef'), - value=12345678901234567890 + to=unhexlify("1d1c328764a41bda0492b66baa30c4a339ff85ef"), + value=12345678901234567890, ) # no gas price @@ -276,8 +379,8 @@ class TestMsgEthereumSigntx(TrezorTest): n=[0, 0], nonce=123456, gas_limit=10000, - to=unhexlify('1d1c328764a41bda0492b66baa30c4a339ff85ef'), - value=12345678901234567890 + to=unhexlify("1d1c328764a41bda0492b66baa30c4a339ff85ef"), + value=12345678901234567890, ) # no gas limit @@ -287,8 +390,8 @@ class TestMsgEthereumSigntx(TrezorTest): n=[0, 0], nonce=123456, gas_price=10000, - to=unhexlify('1d1c328764a41bda0492b66baa30c4a339ff85ef'), - value=12345678901234567890 + to=unhexlify("1d1c328764a41bda0492b66baa30c4a339ff85ef"), + value=12345678901234567890, ) # no nonce @@ -298,6 +401,6 @@ class TestMsgEthereumSigntx(TrezorTest): n=[0, 0], gas_price=10000, gas_limit=123456, - to=unhexlify('1d1c328764a41bda0492b66baa30c4a339ff85ef'), - value=12345678901234567890 + to=unhexlify("1d1c328764a41bda0492b66baa30c4a339ff85ef"), + value=12345678901234567890, ) diff --git a/trezorlib/tests/device_tests/test_msg_ethereum_signtx_eip155.py b/trezorlib/tests/device_tests/test_msg_ethereum_signtx_eip155.py index c3942111b4..545c283be6 100644 --- a/trezorlib/tests/device_tests/test_msg_ethereum_signtx_eip155.py +++ b/trezorlib/tests/device_tests/test_msg_ethereum_signtx_eip155.py @@ -14,13 +14,15 @@ # You should have received a copy of the License along with this library. # If not, see . -from binascii import unhexlify, hexlify +from binascii import hexlify, unhexlify + import pytest -from .common import TrezorTest from trezorlib import ethereum from trezorlib.tools import H_ +from .common import TrezorTest + @pytest.mark.ethereum class TestMsgEthereumSigntxChainId(TrezorTest): diff --git a/trezorlib/tests/device_tests/test_msg_ethereum_verifymessage.py b/trezorlib/tests/device_tests/test_msg_ethereum_verifymessage.py index 3eae048c7c..3d951c3493 100644 --- a/trezorlib/tests/device_tests/test_msg_ethereum_verifymessage.py +++ b/trezorlib/tests/device_tests/test_msg_ethereum_verifymessage.py @@ -18,26 +18,30 @@ from binascii import unhexlify import pytest -from .common import TrezorTest from trezorlib import ethereum +from .common import TrezorTest + @pytest.mark.ethereum class TestMsgEthereumVerifymessage(TrezorTest): - ADDRESS = b'cb3864960e8db1a751212c580af27ee8867d688f' + ADDRESS = b"cb3864960e8db1a751212c580af27ee8867d688f" VECTORS = [ - ('This is an example of a signed message.', b'b7837058907192dbc9427bf57d93a0acca3816c92927a08be573b785f2d72dab65dad9c92fbe03a358acdb455eab2107b869945d11f4e353d9cc6ea957d08a871b'), - ('VeryLongMessage!' * 64, b'da2b73b0170479c2bfba3dd4839bf0d67732a44df8c873f3f3a2aca8a57d7bdc0b5d534f54c649e2d44135717001998b176d3cd1212366464db51f5838430fb31c'), + ( + "This is an example of a signed message.", + b"b7837058907192dbc9427bf57d93a0acca3816c92927a08be573b785f2d72dab65dad9c92fbe03a358acdb455eab2107b869945d11f4e353d9cc6ea957d08a871b", + ), + ( + "VeryLongMessage!" * 64, + b"da2b73b0170479c2bfba3dd4839bf0d67732a44df8c873f3f3a2aca8a57d7bdc0b5d534f54c649e2d44135717001998b176d3cd1212366464db51f5838430fb31c", + ), ] def test_verify(self): self.setup_mnemonic_nopin_nopassphrase() for msg, sig in self.VECTORS: res = ethereum.verify_message( - self.client, - unhexlify(self.ADDRESS), - unhexlify(sig), - msg + self.client, unhexlify(self.ADDRESS), unhexlify(sig), msg ) assert res is True diff --git a/trezorlib/tests/device_tests/test_msg_getaddress.py b/trezorlib/tests/device_tests/test_msg_getaddress.py index 7ab8fbce0b..635db7d3a1 100644 --- a/trezorlib/tests/device_tests/test_msg_getaddress.py +++ b/trezorlib/tests/device_tests/test_msg_getaddress.py @@ -15,57 +15,128 @@ # If not, see . -from .common import TrezorTest -from ..support import ckd_public as bip32 -from trezorlib import messages as proto +from trezorlib import btc, messages as proto +from trezorlib.tools import H_, parse_path -from trezorlib.tools import parse_path, H_ -from trezorlib import btc +from ..support import ckd_public as bip32 +from .common import TrezorTest class TestMsgGetaddress(TrezorTest): - def test_btc(self): self.setup_mnemonic_nopin_nopassphrase() - assert btc.get_address(self.client, 'Bitcoin', []) == '1EfKbQupktEMXf4gujJ9kCFo83k1iMqwqK' - assert btc.get_address(self.client, 'Bitcoin', [1]) == '1CK7SJdcb8z9HuvVft3D91HLpLC6KSsGb' - assert btc.get_address(self.client, 'Bitcoin', [0, H_(1)]) == '1JVq66pzRBvqaBRFeU9SPVvg3er4ZDgoMs' - assert btc.get_address(self.client, 'Bitcoin', [H_(9), 0]) == '1F4YdQdL9ZQwvcNTuy5mjyQxXkyCfMcP2P' - assert btc.get_address(self.client, 'Bitcoin', [0, 9999999]) == '1GS8X3yc7ntzwGw9vXwj9wqmBWZkTFewBV' + assert ( + btc.get_address(self.client, "Bitcoin", []) + == "1EfKbQupktEMXf4gujJ9kCFo83k1iMqwqK" + ) + assert ( + btc.get_address(self.client, "Bitcoin", [1]) + == "1CK7SJdcb8z9HuvVft3D91HLpLC6KSsGb" + ) + assert ( + btc.get_address(self.client, "Bitcoin", [0, H_(1)]) + == "1JVq66pzRBvqaBRFeU9SPVvg3er4ZDgoMs" + ) + assert ( + btc.get_address(self.client, "Bitcoin", [H_(9), 0]) + == "1F4YdQdL9ZQwvcNTuy5mjyQxXkyCfMcP2P" + ) + assert ( + btc.get_address(self.client, "Bitcoin", [0, 9999999]) + == "1GS8X3yc7ntzwGw9vXwj9wqmBWZkTFewBV" + ) def test_ltc(self): self.setup_mnemonic_nopin_nopassphrase() - assert btc.get_address(self.client, 'Litecoin', []) == 'LYtGrdDeqYUQnTkr5sHT2DKZLG7Hqg7HTK' - assert btc.get_address(self.client, 'Litecoin', [1]) == 'LKRGNecThFP3Q6c5fosLVA53Z2hUDb1qnE' - assert btc.get_address(self.client, 'Litecoin', [0, H_(1)]) == 'LcinMK8pVrAtpz7Qpc8jfWzSFsDLgLYfG6' - assert btc.get_address(self.client, 'Litecoin', [H_(9), 0]) == 'LZHVtcwAEDf1BR4d67551zUijyLUpDF9EX' - assert btc.get_address(self.client, 'Litecoin', [0, 9999999]) == 'Laf5nGHSCT94C5dK6fw2RxuXPiw2ZuRR9S' + assert ( + btc.get_address(self.client, "Litecoin", []) + == "LYtGrdDeqYUQnTkr5sHT2DKZLG7Hqg7HTK" + ) + assert ( + btc.get_address(self.client, "Litecoin", [1]) + == "LKRGNecThFP3Q6c5fosLVA53Z2hUDb1qnE" + ) + assert ( + btc.get_address(self.client, "Litecoin", [0, H_(1)]) + == "LcinMK8pVrAtpz7Qpc8jfWzSFsDLgLYfG6" + ) + assert ( + btc.get_address(self.client, "Litecoin", [H_(9), 0]) + == "LZHVtcwAEDf1BR4d67551zUijyLUpDF9EX" + ) + assert ( + btc.get_address(self.client, "Litecoin", [0, 9999999]) + == "Laf5nGHSCT94C5dK6fw2RxuXPiw2ZuRR9S" + ) def test_tbtc(self): self.setup_mnemonic_nopin_nopassphrase() - assert btc.get_address(self.client, 'Testnet', [111, 42]) == 'moN6aN6NP1KWgnPSqzrrRPvx2x1UtZJssa' + assert ( + btc.get_address(self.client, "Testnet", [111, 42]) + == "moN6aN6NP1KWgnPSqzrrRPvx2x1UtZJssa" + ) def test_bch(self): self.setup_mnemonic_allallall() - assert btc.get_address(self.client, 'Bcash', parse_path("44'/145'/0'/0/0")) == 'bitcoincash:qr08q88p9etk89wgv05nwlrkm4l0urz4cyl36hh9sv' - assert btc.get_address(self.client, 'Bcash', parse_path("44'/145'/0'/0/1")) == 'bitcoincash:qr23ajjfd9wd73l87j642puf8cad20lfmqdgwvpat4' - assert btc.get_address(self.client, 'Bcash', parse_path("44'/145'/0'/1/0")) == 'bitcoincash:qzc5q87w069lzg7g3gzx0c8dz83mn7l02scej5aluw' + assert ( + btc.get_address(self.client, "Bcash", parse_path("44'/145'/0'/0/0")) + == "bitcoincash:qr08q88p9etk89wgv05nwlrkm4l0urz4cyl36hh9sv" + ) + assert ( + btc.get_address(self.client, "Bcash", parse_path("44'/145'/0'/0/1")) + == "bitcoincash:qr23ajjfd9wd73l87j642puf8cad20lfmqdgwvpat4" + ) + assert ( + btc.get_address(self.client, "Bcash", parse_path("44'/145'/0'/1/0")) + == "bitcoincash:qzc5q87w069lzg7g3gzx0c8dz83mn7l02scej5aluw" + ) def test_bch_multisig(self): self.setup_mnemonic_allallall() xpubs = [] - for n in map(lambda index: btc.get_public_node(self.client, parse_path("44'/145'/" + str(index) + "'")), range(1, 4)): + for n in map( + lambda index: btc.get_public_node( + self.client, parse_path("44'/145'/" + str(index) + "'") + ), + range(1, 4), + ): xpubs.append(n.xpub) - def getmultisig(chain, nr, signatures=[b'', b'', b''], xpubs=xpubs): + def getmultisig(chain, nr, signatures=[b"", b"", b""], xpubs=xpubs): return proto.MultisigRedeemScriptType( - pubkeys=list(map(lambda xpub: proto.HDNodePathType(node=bip32.deserialize(xpub), address_n=[chain, nr]), xpubs)), + pubkeys=list( + map( + lambda xpub: proto.HDNodePathType( + node=bip32.deserialize(xpub), address_n=[chain, nr] + ), + xpubs, + ) + ), signatures=signatures, m=2, ) + for nr in range(1, 4): - assert btc.get_address(self.client, 'Bcash', parse_path("44'/145'/" + str(nr) + "'/0/0"), show_display=(nr == 1), multisig=getmultisig(0, 0)) == 'bitcoincash:pqguz4nqq64jhr5v3kvpq4dsjrkda75hwy86gq0qzw' - assert btc.get_address(self.client, 'Bcash', parse_path("44'/145'/" + str(nr) + "'/1/0"), show_display=(nr == 1), multisig=getmultisig(1, 0)) == 'bitcoincash:pp6kcpkhua7789g2vyj0qfkcux3yvje7euhyhltn0a' + assert ( + btc.get_address( + self.client, + "Bcash", + parse_path("44'/145'/" + str(nr) + "'/0/0"), + show_display=(nr == 1), + multisig=getmultisig(0, 0), + ) + == "bitcoincash:pqguz4nqq64jhr5v3kvpq4dsjrkda75hwy86gq0qzw" + ) + assert ( + btc.get_address( + self.client, + "Bcash", + parse_path("44'/145'/" + str(nr) + "'/1/0"), + show_display=(nr == 1), + multisig=getmultisig(1, 0), + ) + == "bitcoincash:pp6kcpkhua7789g2vyj0qfkcux3yvje7euhyhltn0a" + ) def test_public_ckd(self): self.setup_mnemonic_nopin_nopassphrase() @@ -77,8 +148,8 @@ class TestMsgGetaddress(TrezorTest): assert node_sub1.chain_code == node_sub2.chain_code assert node_sub1.public_key == node_sub2.public_key - address1 = btc.get_address(self.client, 'Bitcoin', [1]) + address1 = btc.get_address(self.client, "Bitcoin", [1]) address2 = bip32.get_address(node_sub2, 0) - assert address2 == '1CK7SJdcb8z9HuvVft3D91HLpLC6KSsGb' + assert address2 == "1CK7SJdcb8z9HuvVft3D91HLpLC6KSsGb" assert address1 == address2 diff --git a/trezorlib/tests/device_tests/test_msg_getaddress_segwit.py b/trezorlib/tests/device_tests/test_msg_getaddress_segwit.py index 79575c51d6..e505ea6252 100644 --- a/trezorlib/tests/device_tests/test_msg_getaddress_segwit.py +++ b/trezorlib/tests/device_tests/test_msg_getaddress_segwit.py @@ -14,28 +14,79 @@ # You should have received a copy of the License along with this library. # If not, see . -from .common import TrezorTest -from ..support import ckd_public as bip32 -from trezorlib import messages as proto +from trezorlib import btc, messages as proto from trezorlib.tools import parse_path -from trezorlib import btc + +from ..support import ckd_public as bip32 +from .common import TrezorTest class TestMsgGetaddressSegwit(TrezorTest): - def test_show_segwit(self): self.setup_mnemonic_allallall() - assert btc.get_address(self.client, "Testnet", parse_path("49'/1'/0'/1/0"), True, None, script_type=proto.InputScriptType.SPENDP2SHWITNESS) == '2N1LGaGg836mqSQqiuUBLfcyGBhyZbremDX' - assert btc.get_address(self.client, "Testnet", parse_path("49'/1'/0'/0/0"), False, None, script_type=proto.InputScriptType.SPENDP2SHWITNESS) == '2N4Q5FhU2497BryFfUgbqkAJE87aKHUhXMp' - assert btc.get_address(self.client, "Testnet", parse_path("44'/1'/0'/0/0"), False, None, script_type=proto.InputScriptType.SPENDP2SHWITNESS) == '2N6UeBoqYEEnybg4cReFYDammpsyDw8R2Mc' - assert btc.get_address(self.client, "Testnet", parse_path("44'/1'/0'/0/0"), False, None, script_type=proto.InputScriptType.SPENDADDRESS) == 'mvbu1Gdy8SUjTenqerxUaZyYjmveZvt33q' + assert ( + btc.get_address( + self.client, + "Testnet", + parse_path("49'/1'/0'/1/0"), + True, + None, + script_type=proto.InputScriptType.SPENDP2SHWITNESS, + ) + == "2N1LGaGg836mqSQqiuUBLfcyGBhyZbremDX" + ) + assert ( + btc.get_address( + self.client, + "Testnet", + parse_path("49'/1'/0'/0/0"), + False, + None, + script_type=proto.InputScriptType.SPENDP2SHWITNESS, + ) + == "2N4Q5FhU2497BryFfUgbqkAJE87aKHUhXMp" + ) + assert ( + btc.get_address( + self.client, + "Testnet", + parse_path("44'/1'/0'/0/0"), + False, + None, + script_type=proto.InputScriptType.SPENDP2SHWITNESS, + ) + == "2N6UeBoqYEEnybg4cReFYDammpsyDw8R2Mc" + ) + assert ( + btc.get_address( + self.client, + "Testnet", + parse_path("44'/1'/0'/0/0"), + False, + None, + script_type=proto.InputScriptType.SPENDADDRESS, + ) + == "mvbu1Gdy8SUjTenqerxUaZyYjmveZvt33q" + ) def test_show_multisig_3(self): self.setup_mnemonic_allallall() - nodes = map(lambda index: btc.get_public_node(self.client, parse_path("999'/1'/%d'" % index)), range(1, 4)) + nodes = map( + lambda index: btc.get_public_node( + self.client, parse_path("999'/1'/%d'" % index) + ), + range(1, 4), + ) multisig1 = proto.MultisigRedeemScriptType( - pubkeys=list(map(lambda n: proto.HDNodePathType(node=bip32.deserialize(n.xpub), address_n=[2, 0]), nodes)), - signatures=[b'', b'', b''], + pubkeys=list( + map( + lambda n: proto.HDNodePathType( + node=bip32.deserialize(n.xpub), address_n=[2, 0] + ), + nodes, + ) + ), + signatures=[b"", b"", b""], m=2, ) # multisig2 = proto.MultisigRedeemScriptType( @@ -44,4 +95,14 @@ class TestMsgGetaddressSegwit(TrezorTest): # m=2, # ) for i in [1, 2, 3]: - assert btc.get_address(self.client, "Testnet", parse_path("999'/1'/%d'/2/0" % i), False, multisig1, script_type=proto.InputScriptType.SPENDP2SHWITNESS) == '2N2MxyAfifVhb3AMagisxaj3uij8bfXqf4Y' + assert ( + btc.get_address( + self.client, + "Testnet", + parse_path("999'/1'/%d'/2/0" % i), + False, + multisig1, + script_type=proto.InputScriptType.SPENDP2SHWITNESS, + ) + == "2N2MxyAfifVhb3AMagisxaj3uij8bfXqf4Y" + ) diff --git a/trezorlib/tests/device_tests/test_msg_getaddress_segwit_native.py b/trezorlib/tests/device_tests/test_msg_getaddress_segwit_native.py index e54ecbb6ef..8b025cc0c0 100644 --- a/trezorlib/tests/device_tests/test_msg_getaddress_segwit_native.py +++ b/trezorlib/tests/device_tests/test_msg_getaddress_segwit_native.py @@ -14,35 +14,111 @@ # You should have received a copy of the License along with this library. # If not, see . -from .common import TrezorTest -from ..support import ckd_public as bip32 -from trezorlib import messages as proto +from trezorlib import btc, messages as proto from trezorlib.tools import parse_path -from trezorlib import btc + +from ..support import ckd_public as bip32 +from .common import TrezorTest class TestMsgGetaddressSegwitNative(TrezorTest): - def test_show_segwit(self): self.setup_mnemonic_allallall() - assert btc.get_address(self.client, "Testnet", parse_path("49'/1'/0'/0/0"), True, None, script_type=proto.InputScriptType.SPENDWITNESS) == 'tb1qqzv60m9ajw8drqulta4ld4gfx0rdh82un5s65s' - assert btc.get_address(self.client, "Testnet", parse_path("49'/1'/0'/1/0"), False, None, script_type=proto.InputScriptType.SPENDWITNESS) == 'tb1q694ccp5qcc0udmfwgp692u2s2hjpq5h407urtu' - assert btc.get_address(self.client, "Testnet", parse_path("44'/1'/0'/0/0"), False, None, script_type=proto.InputScriptType.SPENDWITNESS) == 'tb1q54un3q39sf7e7tlfq99d6ezys7qgc62a6rxllc' - assert btc.get_address(self.client, "Testnet", parse_path("44'/1'/0'/0/0"), False, None, script_type=proto.InputScriptType.SPENDADDRESS) == 'mvbu1Gdy8SUjTenqerxUaZyYjmveZvt33q' + assert ( + btc.get_address( + self.client, + "Testnet", + parse_path("49'/1'/0'/0/0"), + True, + None, + script_type=proto.InputScriptType.SPENDWITNESS, + ) + == "tb1qqzv60m9ajw8drqulta4ld4gfx0rdh82un5s65s" + ) + assert ( + btc.get_address( + self.client, + "Testnet", + parse_path("49'/1'/0'/1/0"), + False, + None, + script_type=proto.InputScriptType.SPENDWITNESS, + ) + == "tb1q694ccp5qcc0udmfwgp692u2s2hjpq5h407urtu" + ) + assert ( + btc.get_address( + self.client, + "Testnet", + parse_path("44'/1'/0'/0/0"), + False, + None, + script_type=proto.InputScriptType.SPENDWITNESS, + ) + == "tb1q54un3q39sf7e7tlfq99d6ezys7qgc62a6rxllc" + ) + assert ( + btc.get_address( + self.client, + "Testnet", + parse_path("44'/1'/0'/0/0"), + False, + None, + script_type=proto.InputScriptType.SPENDADDRESS, + ) + == "mvbu1Gdy8SUjTenqerxUaZyYjmveZvt33q" + ) def test_show_multisig_3(self): self.setup_mnemonic_allallall() - nodes = [btc.get_public_node(self.client, parse_path("999'/1'/%d'" % index)) for index in range(1, 4)] + nodes = [ + btc.get_public_node(self.client, parse_path("999'/1'/%d'" % index)) + for index in range(1, 4) + ] multisig1 = proto.MultisigRedeemScriptType( - pubkeys=list(map(lambda n: proto.HDNodePathType(node=bip32.deserialize(n.xpub), address_n=[2, 0]), nodes)), - signatures=[b'', b'', b''], + pubkeys=list( + map( + lambda n: proto.HDNodePathType( + node=bip32.deserialize(n.xpub), address_n=[2, 0] + ), + nodes, + ) + ), + signatures=[b"", b"", b""], m=2, ) multisig2 = proto.MultisigRedeemScriptType( - pubkeys=list(map(lambda n: proto.HDNodePathType(node=bip32.deserialize(n.xpub), address_n=[2, 1]), nodes)), - signatures=[b'', b'', b''], + pubkeys=list( + map( + lambda n: proto.HDNodePathType( + node=bip32.deserialize(n.xpub), address_n=[2, 1] + ), + nodes, + ) + ), + signatures=[b"", b"", b""], m=2, ) for i in [1, 2, 3]: - assert btc.get_address(self.client, "Testnet", parse_path("999'/1'/%d'/2/1" % i), False, multisig2, script_type=proto.InputScriptType.SPENDWITNESS) == 'tb1qch62pf820spe9mlq49ns5uexfnl6jzcezp7d328fw58lj0rhlhasge9hzy' - assert btc.get_address(self.client, "Testnet", parse_path("999'/1'/%d'/2/0" % i), False, multisig1, script_type=proto.InputScriptType.SPENDWITNESS) == 'tb1qr6xa5v60zyt3ry9nmfew2fk5g9y3gerkjeu6xxdz7qga5kknz2ssld9z2z' + assert ( + btc.get_address( + self.client, + "Testnet", + parse_path("999'/1'/%d'/2/1" % i), + False, + multisig2, + script_type=proto.InputScriptType.SPENDWITNESS, + ) + == "tb1qch62pf820spe9mlq49ns5uexfnl6jzcezp7d328fw58lj0rhlhasge9hzy" + ) + assert ( + btc.get_address( + self.client, + "Testnet", + parse_path("999'/1'/%d'/2/0" % i), + False, + multisig1, + script_type=proto.InputScriptType.SPENDWITNESS, + ) + == "tb1qr6xa5v60zyt3ry9nmfew2fk5g9y3gerkjeu6xxdz7qga5kknz2ssld9z2z" + ) diff --git a/trezorlib/tests/device_tests/test_msg_getaddress_show.py b/trezorlib/tests/device_tests/test_msg_getaddress_show.py index 360a9560ed..53729fb7ff 100644 --- a/trezorlib/tests/device_tests/test_msg_getaddress_show.py +++ b/trezorlib/tests/device_tests/test_msg_getaddress_show.py @@ -14,51 +14,71 @@ # You should have received a copy of the License along with this library. # If not, see . -from .common import TrezorTest +from trezorlib import btc, messages as proto + from ..support import ckd_public as bip32 -from trezorlib import messages as proto -from trezorlib import btc +from .common import TrezorTest class TestMsgGetaddressShow(TrezorTest): - def test_show(self): self.setup_mnemonic_nopin_nopassphrase() - assert btc.get_address(self.client, 'Bitcoin', [1], show_display=True) == '1CK7SJdcb8z9HuvVft3D91HLpLC6KSsGb' - assert btc.get_address(self.client, 'Bitcoin', [2], show_display=True) == '15AeAhtNJNKyowK8qPHwgpXkhsokzLtUpG' - assert btc.get_address(self.client, 'Bitcoin', [3], show_display=True) == '1CmzyJp9w3NafXMSEFH4SLYUPAVCSUrrJ5' + assert ( + btc.get_address(self.client, "Bitcoin", [1], show_display=True) + == "1CK7SJdcb8z9HuvVft3D91HLpLC6KSsGb" + ) + assert ( + btc.get_address(self.client, "Bitcoin", [2], show_display=True) + == "15AeAhtNJNKyowK8qPHwgpXkhsokzLtUpG" + ) + assert ( + btc.get_address(self.client, "Bitcoin", [3], show_display=True) + == "1CmzyJp9w3NafXMSEFH4SLYUPAVCSUrrJ5" + ) def test_show_multisig_3(self): self.setup_mnemonic_nopin_nopassphrase() - node = bip32.deserialize('xpub661MyMwAqRbcF1zGijBb2K6x9YiJPh58xpcCeLvTxMX6spkY3PcpJ4ABcCyWfskq5DDxM3e6Ez5ePCqG5bnPUXR4wL8TZWyoDaUdiWW7bKy') + node = bip32.deserialize( + "xpub661MyMwAqRbcF1zGijBb2K6x9YiJPh58xpcCeLvTxMX6spkY3PcpJ4ABcCyWfskq5DDxM3e6Ez5ePCqG5bnPUXR4wL8TZWyoDaUdiWW7bKy" + ) multisig = proto.MultisigRedeemScriptType( pubkeys=[ proto.HDNodePathType(node=node, address_n=[1]), proto.HDNodePathType(node=node, address_n=[2]), - proto.HDNodePathType(node=node, address_n=[3]) + proto.HDNodePathType(node=node, address_n=[3]), ], - signatures=[b'', b'', b''], + signatures=[b"", b"", b""], m=2, ) for i in [1, 2, 3]: - assert btc.get_address(self.client, 'Bitcoin', [i], show_display=True, multisig=multisig) == '3E7GDtuHqnqPmDgwH59pVC7AvySiSkbibz' + assert ( + btc.get_address( + self.client, "Bitcoin", [i], show_display=True, multisig=multisig + ) + == "3E7GDtuHqnqPmDgwH59pVC7AvySiSkbibz" + ) def test_show_multisig_15(self): self.setup_mnemonic_nopin_nopassphrase() - node = bip32.deserialize('xpub661MyMwAqRbcF1zGijBb2K6x9YiJPh58xpcCeLvTxMX6spkY3PcpJ4ABcCyWfskq5DDxM3e6Ez5ePCqG5bnPUXR4wL8TZWyoDaUdiWW7bKy') + node = bip32.deserialize( + "xpub661MyMwAqRbcF1zGijBb2K6x9YiJPh58xpcCeLvTxMX6spkY3PcpJ4ABcCyWfskq5DDxM3e6Ez5ePCqG5bnPUXR4wL8TZWyoDaUdiWW7bKy" + ) pubs = [] for x in range(15): pubs.append(proto.HDNodePathType(node=node, address_n=[x])) multisig = proto.MultisigRedeemScriptType( - pubkeys=pubs, - signatures=[b''] * 15, - m=15, + pubkeys=pubs, signatures=[b""] * 15, m=15 ) for i in range(15): - assert btc.get_address(self.client, 'Bitcoin', [i], show_display=True, multisig=multisig) == '3QaKF8zobqcqY8aS6nxCD5ZYdiRfL3RCmU' + assert ( + btc.get_address( + self.client, "Bitcoin", [i], show_display=True, multisig=multisig + ) + == "3QaKF8zobqcqY8aS6nxCD5ZYdiRfL3RCmU" + ) diff --git a/trezorlib/tests/device_tests/test_msg_getecdhsessionkey.py b/trezorlib/tests/device_tests/test_msg_getecdhsessionkey.py index db1c95f27b..febc80a821 100644 --- a/trezorlib/tests/device_tests/test_msg_getecdhsessionkey.py +++ b/trezorlib/tests/device_tests/test_msg_getecdhsessionkey.py @@ -16,27 +16,60 @@ from binascii import unhexlify +from trezorlib import messages as proto, misc + from .common import TrezorTest -from trezorlib import messages as proto -from trezorlib import misc class TestMsgGetECDHSessionKey(TrezorTest): - def test_ecdh(self): self.setup_mnemonic_nopin_nopassphrase() # URI : gpg://Satoshi Nakamoto - identity = proto.IdentityType(proto='gpg', user='', host='Satoshi Nakamoto ', port='', path='', index=0) + identity = proto.IdentityType( + proto="gpg", + user="", + host="Satoshi Nakamoto ", + port="", + path="", + index=0, + ) - peer_public_key = unhexlify('0407f2c6e5becf3213c1d07df0cfbe8e39f70a8c643df7575e5c56859ec52c45ca950499c019719dae0fda04248d851e52cf9d66eeb211d89a77be40de22b6c89d') - result = misc.get_ecdh_session_key(self.client, identity=identity, peer_public_key=peer_public_key, ecdsa_curve_name='secp256k1') - assert result.session_key == unhexlify('0495e5d8c9e5cc09e7cf4908774f52decb381ce97f2fc9ba56e959c13f03f9f47a03dd151cbc908bc1db84d46e2c33e7bbb9daddc800f985244c924fd64adf6647') + peer_public_key = unhexlify( + "0407f2c6e5becf3213c1d07df0cfbe8e39f70a8c643df7575e5c56859ec52c45ca950499c019719dae0fda04248d851e52cf9d66eeb211d89a77be40de22b6c89d" + ) + result = misc.get_ecdh_session_key( + self.client, + identity=identity, + peer_public_key=peer_public_key, + ecdsa_curve_name="secp256k1", + ) + assert result.session_key == unhexlify( + "0495e5d8c9e5cc09e7cf4908774f52decb381ce97f2fc9ba56e959c13f03f9f47a03dd151cbc908bc1db84d46e2c33e7bbb9daddc800f985244c924fd64adf6647" + ) - peer_public_key = unhexlify('04811a6c2bd2a547d0dd84747297fec47719e7c3f9b0024f027c2b237be99aac39a9230acbd163d0cb1524a0f5ea4bfed6058cec6f18368f72a12aa0c4d083ff64') - result = misc.get_ecdh_session_key(self.client, identity=identity, peer_public_key=peer_public_key, ecdsa_curve_name='nist256p1') - assert result.session_key == unhexlify('046d1f5c48af2cf2c57076ac2c9d7808db2086f614cb7b8107119ff2c6270cd209749809efe0196f01a0cc633788cef1f4a2bd650c99570d06962f923fca6d8fdf') + peer_public_key = unhexlify( + "04811a6c2bd2a547d0dd84747297fec47719e7c3f9b0024f027c2b237be99aac39a9230acbd163d0cb1524a0f5ea4bfed6058cec6f18368f72a12aa0c4d083ff64" + ) + result = misc.get_ecdh_session_key( + self.client, + identity=identity, + peer_public_key=peer_public_key, + ecdsa_curve_name="nist256p1", + ) + assert result.session_key == unhexlify( + "046d1f5c48af2cf2c57076ac2c9d7808db2086f614cb7b8107119ff2c6270cd209749809efe0196f01a0cc633788cef1f4a2bd650c99570d06962f923fca6d8fdf" + ) - peer_public_key = unhexlify('40a8cf4b6a64c4314e80f15a8ea55812bd735fbb365936a48b2d78807b575fa17a') - result = misc.get_ecdh_session_key(self.client, identity=identity, peer_public_key=peer_public_key, ecdsa_curve_name='curve25519') - assert result.session_key == unhexlify('04e24516669e0b7d3d72e5129fddd07b6644c30915f5c8b7f1f62324afb3624311') + peer_public_key = unhexlify( + "40a8cf4b6a64c4314e80f15a8ea55812bd735fbb365936a48b2d78807b575fa17a" + ) + result = misc.get_ecdh_session_key( + self.client, + identity=identity, + peer_public_key=peer_public_key, + ecdsa_curve_name="curve25519", + ) + assert result.session_key == unhexlify( + "04e24516669e0b7d3d72e5129fddd07b6644c30915f5c8b7f1f62324afb3624311" + ) diff --git a/trezorlib/tests/device_tests/test_msg_getpublickey.py b/trezorlib/tests/device_tests/test_msg_getpublickey.py index 4c5c01cb72..09b5dfcf66 100644 --- a/trezorlib/tests/device_tests/test_msg_getpublickey.py +++ b/trezorlib/tests/device_tests/test_msg_getpublickey.py @@ -14,42 +14,121 @@ # You should have received a copy of the License along with this library. # If not, see . -from .common import TrezorTest -from ..support import ckd_public as bip32 - -from trezorlib.tools import H_ from trezorlib import btc +from trezorlib.tools import H_ + +from ..support import ckd_public as bip32 +from .common import TrezorTest class TestMsgGetpublickey(TrezorTest): - def test_btc(self): self.setup_mnemonic_nopin_nopassphrase() - assert bip32.serialize(btc.get_public_node(self.client, []).node, 0x0488B21E) == 'xpub661MyMwAqRbcF1zGijBb2K6x9YiJPh58xpcCeLvTxMX6spkY3PcpJ4ABcCyWfskq5DDxM3e6Ez5ePCqG5bnPUXR4wL8TZWyoDaUdiWW7bKy' - assert btc.get_public_node(self.client, [], coin_name='Bitcoin').xpub == 'xpub661MyMwAqRbcF1zGijBb2K6x9YiJPh58xpcCeLvTxMX6spkY3PcpJ4ABcCyWfskq5DDxM3e6Ez5ePCqG5bnPUXR4wL8TZWyoDaUdiWW7bKy' - assert bip32.serialize(btc.get_public_node(self.client, [1]).node, 0x0488B21E) == 'xpub68zNxjsTrV8y9AadThLW7dTAqEpZ7xBLFSyJ3X9pjTv6Njg6kxgjXJkzxq8u3ttnjBw1jupQHMP3gpGZzZqd1eh5S4GjkaMhPR18vMyUi8N' - assert btc.get_public_node(self.client, [1], coin_name='Bitcoin').xpub == 'xpub68zNxjsTrV8y9AadThLW7dTAqEpZ7xBLFSyJ3X9pjTv6Njg6kxgjXJkzxq8u3ttnjBw1jupQHMP3gpGZzZqd1eh5S4GjkaMhPR18vMyUi8N' - assert bip32.serialize(btc.get_public_node(self.client, [0, H_(1)]).node, 0x0488B21E) == 'xpub6A3FoZqYXj1AbW4thRwBh26YwZWbmoyjTaZwwxJjY1oKUpefLepL3RFS9DHKQrjAfxDrzDepYMDZPqXN6upQm3bHQ9xaXD5a3mqni3goF4v' - assert btc.get_public_node(self.client, [0, H_(1)], coin_name='Bitcoin').xpub == 'xpub6A3FoZqYXj1AbW4thRwBh26YwZWbmoyjTaZwwxJjY1oKUpefLepL3RFS9DHKQrjAfxDrzDepYMDZPqXN6upQm3bHQ9xaXD5a3mqni3goF4v' - assert bip32.serialize(btc.get_public_node(self.client, [H_(9), 0]).node, 0x0488B21E) == 'xpub6A2h5mzLDfYginoD7q7wCWbq18wTbN9gducRr2w5NRTwdLeoT3cJSwefFqW7uXTpVFGtpUyDMBNYs3DNvvXx6NPjF9YEbUQrtxFSWnPtVrv' - assert btc.get_public_node(self.client, [H_(9), 0], coin_name='Bitcoin').xpub == 'xpub6A2h5mzLDfYginoD7q7wCWbq18wTbN9gducRr2w5NRTwdLeoT3cJSwefFqW7uXTpVFGtpUyDMBNYs3DNvvXx6NPjF9YEbUQrtxFSWnPtVrv' - assert bip32.serialize(btc.get_public_node(self.client, [0, 9999999]).node, 0x0488B21E) == 'xpub6A3FoZqQEK6iwLZ4HFkqSo5fb35BH4bpjC4SPZ63prfLdGYPwYxEuC6o91bUvFFdMzKWe5rs3axHRUjxJaSvBnKKFtnfLwDACRxPxabsv2r' - assert btc.get_public_node(self.client, [0, 9999999], coin_name='Bitcoin').xpub == 'xpub6A3FoZqQEK6iwLZ4HFkqSo5fb35BH4bpjC4SPZ63prfLdGYPwYxEuC6o91bUvFFdMzKWe5rs3axHRUjxJaSvBnKKFtnfLwDACRxPxabsv2r' + assert ( + bip32.serialize(btc.get_public_node(self.client, []).node, 0x0488B21E) + == "xpub661MyMwAqRbcF1zGijBb2K6x9YiJPh58xpcCeLvTxMX6spkY3PcpJ4ABcCyWfskq5DDxM3e6Ez5ePCqG5bnPUXR4wL8TZWyoDaUdiWW7bKy" + ) + assert ( + btc.get_public_node(self.client, [], coin_name="Bitcoin").xpub + == "xpub661MyMwAqRbcF1zGijBb2K6x9YiJPh58xpcCeLvTxMX6spkY3PcpJ4ABcCyWfskq5DDxM3e6Ez5ePCqG5bnPUXR4wL8TZWyoDaUdiWW7bKy" + ) + assert ( + bip32.serialize(btc.get_public_node(self.client, [1]).node, 0x0488B21E) + == "xpub68zNxjsTrV8y9AadThLW7dTAqEpZ7xBLFSyJ3X9pjTv6Njg6kxgjXJkzxq8u3ttnjBw1jupQHMP3gpGZzZqd1eh5S4GjkaMhPR18vMyUi8N" + ) + assert ( + btc.get_public_node(self.client, [1], coin_name="Bitcoin").xpub + == "xpub68zNxjsTrV8y9AadThLW7dTAqEpZ7xBLFSyJ3X9pjTv6Njg6kxgjXJkzxq8u3ttnjBw1jupQHMP3gpGZzZqd1eh5S4GjkaMhPR18vMyUi8N" + ) + assert ( + bip32.serialize( + btc.get_public_node(self.client, [0, H_(1)]).node, 0x0488B21E + ) + == "xpub6A3FoZqYXj1AbW4thRwBh26YwZWbmoyjTaZwwxJjY1oKUpefLepL3RFS9DHKQrjAfxDrzDepYMDZPqXN6upQm3bHQ9xaXD5a3mqni3goF4v" + ) + assert ( + btc.get_public_node(self.client, [0, H_(1)], coin_name="Bitcoin").xpub + == "xpub6A3FoZqYXj1AbW4thRwBh26YwZWbmoyjTaZwwxJjY1oKUpefLepL3RFS9DHKQrjAfxDrzDepYMDZPqXN6upQm3bHQ9xaXD5a3mqni3goF4v" + ) + assert ( + bip32.serialize( + btc.get_public_node(self.client, [H_(9), 0]).node, 0x0488B21E + ) + == "xpub6A2h5mzLDfYginoD7q7wCWbq18wTbN9gducRr2w5NRTwdLeoT3cJSwefFqW7uXTpVFGtpUyDMBNYs3DNvvXx6NPjF9YEbUQrtxFSWnPtVrv" + ) + assert ( + btc.get_public_node(self.client, [H_(9), 0], coin_name="Bitcoin").xpub + == "xpub6A2h5mzLDfYginoD7q7wCWbq18wTbN9gducRr2w5NRTwdLeoT3cJSwefFqW7uXTpVFGtpUyDMBNYs3DNvvXx6NPjF9YEbUQrtxFSWnPtVrv" + ) + assert ( + bip32.serialize( + btc.get_public_node(self.client, [0, 9999999]).node, 0x0488B21E + ) + == "xpub6A3FoZqQEK6iwLZ4HFkqSo5fb35BH4bpjC4SPZ63prfLdGYPwYxEuC6o91bUvFFdMzKWe5rs3axHRUjxJaSvBnKKFtnfLwDACRxPxabsv2r" + ) + assert ( + btc.get_public_node(self.client, [0, 9999999], coin_name="Bitcoin").xpub + == "xpub6A3FoZqQEK6iwLZ4HFkqSo5fb35BH4bpjC4SPZ63prfLdGYPwYxEuC6o91bUvFFdMzKWe5rs3axHRUjxJaSvBnKKFtnfLwDACRxPxabsv2r" + ) def test_ltc(self): self.setup_mnemonic_nopin_nopassphrase() - assert bip32.serialize(btc.get_public_node(self.client, []).node, 0x019DA462) == 'Ltub2SSUS19CirucVPGDKDBatBDBEM2s9UbH66pBURfaKrMocCPLhQ7Z7hecy5VYLHA5fRdXwB2e61j2VJCNzVsqKTCVEU1vECjqi5EyczFX9xp' - assert btc.get_public_node(self.client, [], coin_name='Litecoin').xpub == 'Ltub2SSUS19CirucVPGDKDBatBDBEM2s9UbH66pBURfaKrMocCPLhQ7Z7hecy5VYLHA5fRdXwB2e61j2VJCNzVsqKTCVEU1vECjqi5EyczFX9xp' - assert bip32.serialize(btc.get_public_node(self.client, [1]).node, 0x019DA462) == 'Ltub2VRVRP5VjvSyPXra4BLVyVZPv397sjhUNjBGsbtw6xko77JuQyBULxFSKheviJJ3KQLbL3Cx8P2RnudguTw4raUVjCACRG7jsumUptYx55C' - assert btc.get_public_node(self.client, [1], coin_name='Litecoin').xpub == 'Ltub2VRVRP5VjvSyPXra4BLVyVZPv397sjhUNjBGsbtw6xko77JuQyBULxFSKheviJJ3KQLbL3Cx8P2RnudguTw4raUVjCACRG7jsumUptYx55C' - assert bip32.serialize(btc.get_public_node(self.client, [0, H_(1)]).node, 0x019DA462) == 'Ltub2WUNGD3aRAKAqsLqHuwBYtCn2MqAXbVsarmvn33quWe2DCHTzfK4s4jsW5oM5G8RGAdSaM3NPNrwVvtV1ourbyNhhHr3BtqcYGc8caf5GoT' - assert btc.get_public_node(self.client, [0, H_(1)], coin_name='Litecoin').xpub == 'Ltub2WUNGD3aRAKAqsLqHuwBYtCn2MqAXbVsarmvn33quWe2DCHTzfK4s4jsW5oM5G8RGAdSaM3NPNrwVvtV1ourbyNhhHr3BtqcYGc8caf5GoT' - assert bip32.serialize(btc.get_public_node(self.client, [H_(9), 0]).node, 0x019DA462) == 'Ltub2WToYRCN76rgyA59iK7w4Ni45wG2M9fpmBpQg7gBjvJeMiHc7473Gb96ci29Zvs55TgUQcMmCD1vy8aVqpdPwJB9YHRhGAAuPT1nRLLXmFu' - assert btc.get_public_node(self.client, [H_(9), 0], coin_name='Litecoin').xpub == 'Ltub2WToYRCN76rgyA59iK7w4Ni45wG2M9fpmBpQg7gBjvJeMiHc7473Gb96ci29Zvs55TgUQcMmCD1vy8aVqpdPwJB9YHRhGAAuPT1nRLLXmFu' - assert bip32.serialize(btc.get_public_node(self.client, [0, 9999999]).node, 0x019DA462) == 'Ltub2WUNGD3S7kQjBhpzsjkqJfBtfqPk2r7xrUGRDdqACMW3MeBCbZSyiqbEVt7WaeesxCj6EDFQtcbfXa75DUYN2i6jZ2g81cyCgvijs9J2u2n' - assert btc.get_public_node(self.client, [0, 9999999], coin_name='Litecoin').xpub == 'Ltub2WUNGD3S7kQjBhpzsjkqJfBtfqPk2r7xrUGRDdqACMW3MeBCbZSyiqbEVt7WaeesxCj6EDFQtcbfXa75DUYN2i6jZ2g81cyCgvijs9J2u2n' + assert ( + bip32.serialize(btc.get_public_node(self.client, []).node, 0x019DA462) + == "Ltub2SSUS19CirucVPGDKDBatBDBEM2s9UbH66pBURfaKrMocCPLhQ7Z7hecy5VYLHA5fRdXwB2e61j2VJCNzVsqKTCVEU1vECjqi5EyczFX9xp" + ) + assert ( + btc.get_public_node(self.client, [], coin_name="Litecoin").xpub + == "Ltub2SSUS19CirucVPGDKDBatBDBEM2s9UbH66pBURfaKrMocCPLhQ7Z7hecy5VYLHA5fRdXwB2e61j2VJCNzVsqKTCVEU1vECjqi5EyczFX9xp" + ) + assert ( + bip32.serialize(btc.get_public_node(self.client, [1]).node, 0x019DA462) + == "Ltub2VRVRP5VjvSyPXra4BLVyVZPv397sjhUNjBGsbtw6xko77JuQyBULxFSKheviJJ3KQLbL3Cx8P2RnudguTw4raUVjCACRG7jsumUptYx55C" + ) + assert ( + btc.get_public_node(self.client, [1], coin_name="Litecoin").xpub + == "Ltub2VRVRP5VjvSyPXra4BLVyVZPv397sjhUNjBGsbtw6xko77JuQyBULxFSKheviJJ3KQLbL3Cx8P2RnudguTw4raUVjCACRG7jsumUptYx55C" + ) + assert ( + bip32.serialize( + btc.get_public_node(self.client, [0, H_(1)]).node, 0x019DA462 + ) + == "Ltub2WUNGD3aRAKAqsLqHuwBYtCn2MqAXbVsarmvn33quWe2DCHTzfK4s4jsW5oM5G8RGAdSaM3NPNrwVvtV1ourbyNhhHr3BtqcYGc8caf5GoT" + ) + assert ( + btc.get_public_node(self.client, [0, H_(1)], coin_name="Litecoin").xpub + == "Ltub2WUNGD3aRAKAqsLqHuwBYtCn2MqAXbVsarmvn33quWe2DCHTzfK4s4jsW5oM5G8RGAdSaM3NPNrwVvtV1ourbyNhhHr3BtqcYGc8caf5GoT" + ) + assert ( + bip32.serialize( + btc.get_public_node(self.client, [H_(9), 0]).node, 0x019DA462 + ) + == "Ltub2WToYRCN76rgyA59iK7w4Ni45wG2M9fpmBpQg7gBjvJeMiHc7473Gb96ci29Zvs55TgUQcMmCD1vy8aVqpdPwJB9YHRhGAAuPT1nRLLXmFu" + ) + assert ( + btc.get_public_node(self.client, [H_(9), 0], coin_name="Litecoin").xpub + == "Ltub2WToYRCN76rgyA59iK7w4Ni45wG2M9fpmBpQg7gBjvJeMiHc7473Gb96ci29Zvs55TgUQcMmCD1vy8aVqpdPwJB9YHRhGAAuPT1nRLLXmFu" + ) + assert ( + bip32.serialize( + btc.get_public_node(self.client, [0, 9999999]).node, 0x019DA462 + ) + == "Ltub2WUNGD3S7kQjBhpzsjkqJfBtfqPk2r7xrUGRDdqACMW3MeBCbZSyiqbEVt7WaeesxCj6EDFQtcbfXa75DUYN2i6jZ2g81cyCgvijs9J2u2n" + ) + assert ( + btc.get_public_node(self.client, [0, 9999999], coin_name="Litecoin").xpub + == "Ltub2WUNGD3S7kQjBhpzsjkqJfBtfqPk2r7xrUGRDdqACMW3MeBCbZSyiqbEVt7WaeesxCj6EDFQtcbfXa75DUYN2i6jZ2g81cyCgvijs9J2u2n" + ) def test_tbtc(self): self.setup_mnemonic_nopin_nopassphrase() - assert bip32.serialize(btc.get_public_node(self.client, [111, 42]).node, 0x043587CF) == 'tpubDAgixSyai5PWbc8N1mBkHDR5nLgAnHFtY7r4y5EzxqAxrt9YUDpZL3kaRoHVvCfrcwNo31c2isBP2uTHcZxEosuKbyJhCAbrvGoPuLUZ7Mz' - assert btc.get_public_node(self.client, [111, 42], coin_name='Testnet').xpub == 'tpubDAgixSyai5PWbc8N1mBkHDR5nLgAnHFtY7r4y5EzxqAxrt9YUDpZL3kaRoHVvCfrcwNo31c2isBP2uTHcZxEosuKbyJhCAbrvGoPuLUZ7Mz' + assert ( + bip32.serialize( + btc.get_public_node(self.client, [111, 42]).node, 0x043587CF + ) + == "tpubDAgixSyai5PWbc8N1mBkHDR5nLgAnHFtY7r4y5EzxqAxrt9YUDpZL3kaRoHVvCfrcwNo31c2isBP2uTHcZxEosuKbyJhCAbrvGoPuLUZ7Mz" + ) + assert ( + btc.get_public_node(self.client, [111, 42], coin_name="Testnet").xpub + == "tpubDAgixSyai5PWbc8N1mBkHDR5nLgAnHFtY7r4y5EzxqAxrt9YUDpZL3kaRoHVvCfrcwNo31c2isBP2uTHcZxEosuKbyJhCAbrvGoPuLUZ7Mz" + ) diff --git a/trezorlib/tests/device_tests/test_msg_getpublickey_curve.py b/trezorlib/tests/device_tests/test_msg_getpublickey_curve.py index 23f4064a6a..b3731b9043 100644 --- a/trezorlib/tests/device_tests/test_msg_getpublickey_curve.py +++ b/trezorlib/tests/device_tests/test_msg_getpublickey_curve.py @@ -15,35 +15,84 @@ # If not, see . from binascii import hexlify + import pytest -from .common import TrezorTest -from trezorlib.tools import CallException, H_ from trezorlib import btc +from trezorlib.tools import H_, CallException + +from .common import TrezorTest class TestMsgGetpublickeyCurve(TrezorTest): - def test_default_curve(self): self.setup_mnemonic_nopin_nopassphrase() - assert hexlify(btc.get_public_node(self.client, [H_(111), 42]).node.public_key).decode() == '02e7fcec053f0df94d88c86447970743e8a1979d242d09338dcf8687a9966f7fbc' - assert hexlify(btc.get_public_node(self.client, [H_(111), H_(42)]).node.public_key).decode() == '03ce7b690969d773ba9ed212464eb2b534b87b9b8a9383300bddabe1f093f79220' + assert ( + hexlify(btc.get_public_node(self.client, [H_(111), 42]).node.public_key) + == b"02e7fcec053f0df94d88c86447970743e8a1979d242d09338dcf8687a9966f7fbc" + ) + assert ( + hexlify(btc.get_public_node(self.client, [H_(111), H_(42)]).node.public_key) + == b"03ce7b690969d773ba9ed212464eb2b534b87b9b8a9383300bddabe1f093f79220" + ) def test_secp256k1_curve(self): self.setup_mnemonic_nopin_nopassphrase() - assert hexlify(btc.get_public_node(self.client, [H_(111), 42], ecdsa_curve_name='secp256k1').node.public_key).decode() == '02e7fcec053f0df94d88c86447970743e8a1979d242d09338dcf8687a9966f7fbc' - assert hexlify(btc.get_public_node(self.client, [H_(111), H_(42)], ecdsa_curve_name='secp256k1').node.public_key).decode() == '03ce7b690969d773ba9ed212464eb2b534b87b9b8a9383300bddabe1f093f79220' + assert ( + hexlify( + btc.get_public_node( + self.client, [H_(111), 42], ecdsa_curve_name="secp256k1" + ).node.public_key + ) + == b"02e7fcec053f0df94d88c86447970743e8a1979d242d09338dcf8687a9966f7fbc" + ) + assert ( + hexlify( + btc.get_public_node( + self.client, [H_(111), H_(42)], ecdsa_curve_name="secp256k1" + ).node.public_key + ) + == b"03ce7b690969d773ba9ed212464eb2b534b87b9b8a9383300bddabe1f093f79220" + ) def test_nist256p1_curve(self): self.setup_mnemonic_nopin_nopassphrase() - assert hexlify(btc.get_public_node(self.client, [H_(111), 42], ecdsa_curve_name='nist256p1').node.public_key).decode() == '02a9ce59b32bd64a70bc52aca96e5d09af65c6b9593ba2a60af8fccfe1437f2129' - assert hexlify(btc.get_public_node(self.client, [H_(111), H_(42)], ecdsa_curve_name='nist256p1').node.public_key).decode() == '026fe35d8afed67dbf0561a1d32922e8ad0cd0d86effbc82be970cbed7d9bab2c2' + assert ( + hexlify( + btc.get_public_node( + self.client, [H_(111), 42], ecdsa_curve_name="nist256p1" + ).node.public_key + ) + == b"02a9ce59b32bd64a70bc52aca96e5d09af65c6b9593ba2a60af8fccfe1437f2129" + ) + assert ( + hexlify( + btc.get_public_node( + self.client, [H_(111), H_(42)], ecdsa_curve_name="nist256p1" + ).node.public_key + ) + == b"026fe35d8afed67dbf0561a1d32922e8ad0cd0d86effbc82be970cbed7d9bab2c2" + ) def test_ed25519_curve(self): self.setup_mnemonic_nopin_nopassphrase() # ed25519 curve does not support public derivation, so test only private derivation paths - assert hexlify(btc.get_public_node(self.client, [H_(111), H_(42)], ecdsa_curve_name='ed25519').node.public_key).decode() == '0069a14b478e508eab6e93303f4e6f5c50b8136627830f2ed5c3a835fc6c0ea2b7' - assert hexlify(btc.get_public_node(self.client, [H_(111), H_(65535)], ecdsa_curve_name='ed25519').node.public_key).decode() == '00514f73a05184458611b14c348fee4fd988d36cf3aee7207737861bac611de991' + assert ( + hexlify( + btc.get_public_node( + self.client, [H_(111), H_(42)], ecdsa_curve_name="ed25519" + ).node.public_key + ) + == b"0069a14b478e508eab6e93303f4e6f5c50b8136627830f2ed5c3a835fc6c0ea2b7" + ) + assert ( + hexlify( + btc.get_public_node( + self.client, [H_(111), H_(65535)], ecdsa_curve_name="ed25519" + ).node.public_key + ) + == b"00514f73a05184458611b14c348fee4fd988d36cf3aee7207737861bac611de991" + ) # test failure when using public derivation with pytest.raises(CallException): - btc.get_public_node(self.client, [H_(111), 42], ecdsa_curve_name='ed25519') + btc.get_public_node(self.client, [H_(111), 42], ecdsa_curve_name="ed25519") diff --git a/trezorlib/tests/device_tests/test_msg_lisk_getaddress.py b/trezorlib/tests/device_tests/test_msg_lisk_getaddress.py index 9a30e910ab..5fb5bed6fd 100644 --- a/trezorlib/tests/device_tests/test_msg_lisk_getaddress.py +++ b/trezorlib/tests/device_tests/test_msg_lisk_getaddress.py @@ -16,20 +16,23 @@ import pytest -from .common import TrezorTest from trezorlib import lisk from trezorlib.tools import parse_path +from .common import TrezorTest + LISK_PATH = parse_path("m/44h/134h/0h/1h") @pytest.mark.lisk @pytest.mark.skip_t1 class TestMsgLiskGetaddress(TrezorTest): - def test_lisk_getaddress(self): self.setup_mnemonic_nopin_nopassphrase() - assert lisk.get_address(self.client, LISK_PATH[:2]) == '1431530009238518937L' - assert lisk.get_address(self.client, LISK_PATH[:3]) == '17563781916205589679L' - assert lisk.get_address(self.client, LISK_PATH) == '1874186517773691964L' - assert lisk.get_address(self.client, parse_path("m/44h/134h/999h/999h")) == '16295203558710684671L' + assert lisk.get_address(self.client, LISK_PATH[:2]) == "1431530009238518937L" + assert lisk.get_address(self.client, LISK_PATH[:3]) == "17563781916205589679L" + assert lisk.get_address(self.client, LISK_PATH) == "1874186517773691964L" + assert ( + lisk.get_address(self.client, parse_path("m/44h/134h/999h/999h")) + == "16295203558710684671L" + ) diff --git a/trezorlib/tests/device_tests/test_msg_lisk_getpublickey.py b/trezorlib/tests/device_tests/test_msg_lisk_getpublickey.py index 7eb8dde9a4..b27f4529ae 100644 --- a/trezorlib/tests/device_tests/test_msg_lisk_getpublickey.py +++ b/trezorlib/tests/device_tests/test_msg_lisk_getpublickey.py @@ -15,20 +15,24 @@ # If not, see . from binascii import hexlify + import pytest -from .common import TrezorTest from trezorlib import lisk from trezorlib.tools import parse_path +from .common import TrezorTest + LISK_PATH = parse_path("m/44h/134h/0h/0h") @pytest.mark.lisk @pytest.mark.skip_t1 class TestMsgLiskGetPublicKey(TrezorTest): - def test_lisk_get_public_key(self): self.setup_mnemonic_nopin_nopassphrase() sig = lisk.get_public_key(self.client, LISK_PATH) - assert hexlify(sig.public_key) == b'eb56d7bbb5e8ea9269405f7a8527fe126023d1db2c973cfac6f760b60ae27294' + assert ( + hexlify(sig.public_key) + == b"eb56d7bbb5e8ea9269405f7a8527fe126023d1db2c973cfac6f760b60ae27294" + ) diff --git a/trezorlib/tests/device_tests/test_msg_lisk_signmessage.py b/trezorlib/tests/device_tests/test_msg_lisk_signmessage.py index 02084e7a0f..b2bc54d395 100644 --- a/trezorlib/tests/device_tests/test_msg_lisk_signmessage.py +++ b/trezorlib/tests/device_tests/test_msg_lisk_signmessage.py @@ -15,27 +15,42 @@ # If not, see . from binascii import hexlify + import pytest -from .common import TrezorTest from trezorlib import lisk from trezorlib.tools import parse_path +from .common import TrezorTest + LISK_PATH = parse_path("m/44h/134h/0h/0h") @pytest.mark.lisk @pytest.mark.skip_t1 class TestMsgLiskSignmessage(TrezorTest): - def test_sign(self): self.setup_mnemonic_nopin_nopassphrase() - sig = lisk.sign_message(self.client, LISK_PATH, 'This is an example of a signed message.') - assert hexlify(sig.public_key) == b'eb56d7bbb5e8ea9269405f7a8527fe126023d1db2c973cfac6f760b60ae27294' - assert hexlify(sig.signature) == b'7858ae7cd52ea6d4b17e800ca60144423db5560bfd618b663ffbf26ab66758563df45cbffae8463db22dc285dd94309083b8c807776085b97d05374d79867d05' + sig = lisk.sign_message( + self.client, LISK_PATH, "This is an example of a signed message." + ) + assert ( + hexlify(sig.public_key) + == b"eb56d7bbb5e8ea9269405f7a8527fe126023d1db2c973cfac6f760b60ae27294" + ) + assert ( + hexlify(sig.signature) + == b"7858ae7cd52ea6d4b17e800ca60144423db5560bfd618b663ffbf26ab66758563df45cbffae8463db22dc285dd94309083b8c807776085b97d05374d79867d05" + ) def test_sign_long(self): self.setup_mnemonic_nopin_nopassphrase() - sig = lisk.sign_message(self.client, LISK_PATH, 'VeryLongMessage!' * 64) - assert hexlify(sig.public_key) == b'eb56d7bbb5e8ea9269405f7a8527fe126023d1db2c973cfac6f760b60ae27294' - assert hexlify(sig.signature) == b'19c26f4b6f2ecf2feef57d22237cf97eb7862fdc2fb8c303878843f5dd728191f7837cf8d0ed41f8e470b15181223a3a5131881add9c22b2453b01be4edef104' + sig = lisk.sign_message(self.client, LISK_PATH, "VeryLongMessage!" * 64) + assert ( + hexlify(sig.public_key) + == b"eb56d7bbb5e8ea9269405f7a8527fe126023d1db2c973cfac6f760b60ae27294" + ) + assert ( + hexlify(sig.signature) + == b"19c26f4b6f2ecf2feef57d22237cf97eb7862fdc2fb8c303878843f5dd728191f7837cf8d0ed41f8e470b15181223a3a5131881add9c22b2453b01be4edef104" + ) diff --git a/trezorlib/tests/device_tests/test_msg_lisk_signtx.py b/trezorlib/tests/device_tests/test_msg_lisk_signtx.py index a45cb0b5e1..116b41e60b 100644 --- a/trezorlib/tests/device_tests/test_msg_lisk_signtx.py +++ b/trezorlib/tests/device_tests/test_msg_lisk_signtx.py @@ -15,162 +15,206 @@ # If not, see . from binascii import unhexlify + import pytest -from .common import TrezorTest -from trezorlib import messages as proto +from trezorlib import lisk, messages as proto from trezorlib.tools import parse_path -from trezorlib import lisk -PUBLIC_KEY = unhexlify('eb56d7bbb5e8ea9269405f7a8527fe126023d1db2c973cfac6f760b60ae27294') +from .common import TrezorTest + +PUBLIC_KEY = unhexlify( + "eb56d7bbb5e8ea9269405f7a8527fe126023d1db2c973cfac6f760b60ae27294" +) @pytest.mark.lisk @pytest.mark.skip_t1 class TestMsgLiskSignTx(TrezorTest): - def test_lisk_sign_tx_send(self): self.setup_mnemonic_nopin_nopassphrase() with self.client: - self.client.set_expected_responses([ - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.ButtonRequest(code=proto.ButtonRequestType.ConfirmOutput), - proto.LiskSignedTx( - signature=unhexlify('b62717d581e5713bca60b758b661e6cfa091addc6caedd57534e06cda805943ee80797b9fb9a1e1b2bd584e292d2a7f832a4d1b3f15f00e1ee1b72de7e195a08') - ) - ]) + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.ButtonRequest(code=proto.ButtonRequestType.ConfirmOutput), + proto.LiskSignedTx( + signature=unhexlify( + "b62717d581e5713bca60b758b661e6cfa091addc6caedd57534e06cda805943ee80797b9fb9a1e1b2bd584e292d2a7f832a4d1b3f15f00e1ee1b72de7e195a08" + ) + ), + ] + ) - lisk.sign_tx(self.client, parse_path("m/44'/134'/0'/0'"), { - "amount": "10000000", - "recipientId": "9971262264659915921L", - "timestamp": 57525937, - "type": 0, - "fee": "10000000", - "asset": {} - }) + lisk.sign_tx( + self.client, + parse_path("m/44'/134'/0'/0'"), + { + "amount": "10000000", + "recipientId": "9971262264659915921L", + "timestamp": 57525937, + "type": 0, + "fee": "10000000", + "asset": {}, + }, + ) def test_lisk_sign_tx_send_with_data(self): self.setup_mnemonic_nopin_nopassphrase() with self.client: - self.client.set_expected_responses([ - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.ButtonRequest(code=proto.ButtonRequestType.ConfirmOutput), - proto.LiskSignedTx( - signature=unhexlify('5dd0dbb87ee46f3e985b1ef2df85cb0bec481e8601d150388f73e198cdd57a698eab076c7cd5b281fbb6a83dd3dc64d91a6eccd1614dffd46f101194ffa3a004') - ) - ]) + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.ButtonRequest(code=proto.ButtonRequestType.ConfirmOutput), + proto.LiskSignedTx( + signature=unhexlify( + "5dd0dbb87ee46f3e985b1ef2df85cb0bec481e8601d150388f73e198cdd57a698eab076c7cd5b281fbb6a83dd3dc64d91a6eccd1614dffd46f101194ffa3a004" + ) + ), + ] + ) - lisk.sign_tx(self.client, parse_path("m/44'/134'/0'/0'"), { - "amount": "10000000", - "recipientId": "9971262264659915921L", - "timestamp": 57525937, - "type": 0, - "fee": "20000000", - "asset": { - "data": "Test data" - } - }) + lisk.sign_tx( + self.client, + parse_path("m/44'/134'/0'/0'"), + { + "amount": "10000000", + "recipientId": "9971262264659915921L", + "timestamp": 57525937, + "type": 0, + "fee": "20000000", + "asset": {"data": "Test data"}, + }, + ) def test_lisk_sign_tx_second_signature(self): self.setup_mnemonic_nopin_nopassphrase() with self.client: - self.client.set_expected_responses([ - proto.ButtonRequest(code=proto.ButtonRequestType.PublicKey), - proto.ButtonRequest(code=proto.ButtonRequestType.ConfirmOutput), - proto.LiskSignedTx( - signature=unhexlify('f02bdc40a7599c21d29db4080ff1ff8934f76eedf5b0c4fa695c8a64af2f0b40a5c4f92db203863eebbbfad8f0611a23f451ed8bb711490234cdfb034728fd01') - ) - ]) + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.PublicKey), + proto.ButtonRequest(code=proto.ButtonRequestType.ConfirmOutput), + proto.LiskSignedTx( + signature=unhexlify( + "f02bdc40a7599c21d29db4080ff1ff8934f76eedf5b0c4fa695c8a64af2f0b40a5c4f92db203863eebbbfad8f0611a23f451ed8bb711490234cdfb034728fd01" + ) + ), + ] + ) - lisk.sign_tx(self.client, parse_path("m/44'/134'/0'/0'"), { - "amount": "0", - "timestamp": 57525937, - "type": 1, - "fee": "500000000", - "asset": { - "signature": { - "publicKey": "5d036a858ce89f844491762eb89e2bfbd50a4a0a0da658e4b2628b25b117ae09" - } - } - }) + lisk.sign_tx( + self.client, + parse_path("m/44'/134'/0'/0'"), + { + "amount": "0", + "timestamp": 57525937, + "type": 1, + "fee": "500000000", + "asset": { + "signature": { + "publicKey": "5d036a858ce89f844491762eb89e2bfbd50a4a0a0da658e4b2628b25b117ae09" + } + }, + }, + ) def test_lisk_sign_tx_delegate_registration(self): self.setup_mnemonic_nopin_nopassphrase() with self.client: - self.client.set_expected_responses([ - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.ButtonRequest(code=proto.ButtonRequestType.ConfirmOutput), - proto.LiskSignedTx( - signature=unhexlify('5ac02b2882b9d7d0f944e48baadc27de1296cc08c3533f7c8e380fbbb9fb4a6ac81b5dc57060d7d8c68912eea24eb6e39024801bccc0d55020e2052b0c2bb701') - ) - ]) + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.ButtonRequest(code=proto.ButtonRequestType.ConfirmOutput), + proto.LiskSignedTx( + signature=unhexlify( + "5ac02b2882b9d7d0f944e48baadc27de1296cc08c3533f7c8e380fbbb9fb4a6ac81b5dc57060d7d8c68912eea24eb6e39024801bccc0d55020e2052b0c2bb701" + ) + ), + ] + ) - lisk.sign_tx(self.client, parse_path("m/44'/134'/0'/0'"), { - "amount": "0", - "timestamp": 57525937, - "type": 2, - "fee": "2500000000", - "asset": { - "delegate": { - "username": "trezor_t" - } - } - }) + lisk.sign_tx( + self.client, + parse_path("m/44'/134'/0'/0'"), + { + "amount": "0", + "timestamp": 57525937, + "type": 2, + "fee": "2500000000", + "asset": {"delegate": {"username": "trezor_t"}}, + }, + ) def test_lisk_sign_tx_cast_votes(self): self.setup_mnemonic_nopin_nopassphrase() with self.client: - self.client.set_expected_responses([ - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.ButtonRequest(code=proto.ButtonRequestType.ConfirmOutput), - proto.LiskSignedTx( - signature=unhexlify('1d0599a8387edaa4a6d309b8a78accd1ceaff20ff9d87136b01cba0efbcb9781c13dc2b0bab5a1ea4f196d8dcc9dbdbd2d56dbffcc088fc77686b2e2c2fe560f') - ) - ]) + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.ButtonRequest(code=proto.ButtonRequestType.ConfirmOutput), + proto.LiskSignedTx( + signature=unhexlify( + "1d0599a8387edaa4a6d309b8a78accd1ceaff20ff9d87136b01cba0efbcb9781c13dc2b0bab5a1ea4f196d8dcc9dbdbd2d56dbffcc088fc77686b2e2c2fe560f" + ) + ), + ] + ) - lisk.sign_tx(self.client, parse_path("m/44'/134'/0'/0'"), { - "amount": "0", - "timestamp": 57525937, - "type": 3, - "fee": "100000000", - "asset": { - "votes": [ - "+b002f58531c074c7190714523eec08c48db8c7cfc0c943097db1a2e82ed87f84", - "-ec111c8ad482445cfe83d811a7edd1f1d2765079c99d7d958cca1354740b7614" - ] - } - }) + lisk.sign_tx( + self.client, + parse_path("m/44'/134'/0'/0'"), + { + "amount": "0", + "timestamp": 57525937, + "type": 3, + "fee": "100000000", + "asset": { + "votes": [ + "+b002f58531c074c7190714523eec08c48db8c7cfc0c943097db1a2e82ed87f84", + "-ec111c8ad482445cfe83d811a7edd1f1d2765079c99d7d958cca1354740b7614", + ] + }, + }, + ) def test_lisk_sign_tx_multisignature(self): self.setup_mnemonic_nopin_nopassphrase() with self.client: - self.client.set_expected_responses([ - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.ButtonRequest(code=proto.ButtonRequestType.ConfirmOutput), - proto.LiskSignedTx( - signature=unhexlify('88923866c2d500a6927715699ab41a0f58ea4b52e552d90e923bc24ac9da240f2328c93f9ce043a1da4937d4b61c7f57c02fc931f9824d06b24731e7be23c506') - ) - ]) + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.ButtonRequest(code=proto.ButtonRequestType.ConfirmOutput), + proto.LiskSignedTx( + signature=unhexlify( + "88923866c2d500a6927715699ab41a0f58ea4b52e552d90e923bc24ac9da240f2328c93f9ce043a1da4937d4b61c7f57c02fc931f9824d06b24731e7be23c506" + ) + ), + ] + ) - lisk.sign_tx(self.client, parse_path("m/44'/134'/0'/0'"), { - "amount": "0", - "timestamp": 57525937, - "type": 4, - "fee": "1500000000", - "asset": { - "multisignature": { - "min": 2, - "lifetime": 5, - "keysgroup": [ - "+5d036a858ce89f844491762eb89e2bfbd50a4a0a0da658e4b2628b25b117ae09", - "+922fbfdd596fa78269bbcadc67ec2a1cc15fc929a19c462169568d7a3df1a1aa" - ] - } - } - }) + lisk.sign_tx( + self.client, + parse_path("m/44'/134'/0'/0'"), + { + "amount": "0", + "timestamp": 57525937, + "type": 4, + "fee": "1500000000", + "asset": { + "multisignature": { + "min": 2, + "lifetime": 5, + "keysgroup": [ + "+5d036a858ce89f844491762eb89e2bfbd50a4a0a0da658e4b2628b25b117ae09", + "+922fbfdd596fa78269bbcadc67ec2a1cc15fc929a19c462169568d7a3df1a1aa", + ], + } + }, + }, + ) diff --git a/trezorlib/tests/device_tests/test_msg_lisk_verifymessage.py b/trezorlib/tests/device_tests/test_msg_lisk_verifymessage.py index 8fccd3ff89..03a83a0ed1 100644 --- a/trezorlib/tests/device_tests/test_msg_lisk_verifymessage.py +++ b/trezorlib/tests/device_tests/test_msg_lisk_verifymessage.py @@ -15,43 +15,55 @@ # If not, see . from binascii import unhexlify + import pytest +from trezorlib import lisk, messages as proto + from .common import TrezorTest -from trezorlib import messages as proto -from trezorlib import lisk @pytest.mark.lisk @pytest.mark.skip_t1 class TestMsgLiskVerifymessage(TrezorTest): - def test_verify(self): self.setup_mnemonic_nopin_nopassphrase() with self.client: - self.client.set_expected_responses([ - proto.ButtonRequest(code=proto.ButtonRequestType.Other), - proto.ButtonRequest(code=proto.ButtonRequestType.Other), - proto.Success(message='Message verified') - ]) + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.Other), + proto.ButtonRequest(code=proto.ButtonRequestType.Other), + proto.Success(message="Message verified"), + ] + ) lisk.verify_message( self.client, - unhexlify('eb56d7bbb5e8ea9269405f7a8527fe126023d1db2c973cfac6f760b60ae27294'), - unhexlify('7858ae7cd52ea6d4b17e800ca60144423db5560bfd618b663ffbf26ab66758563df45cbffae8463db22dc285dd94309083b8c807776085b97d05374d79867d05'), - 'This is an example of a signed message.' + unhexlify( + "eb56d7bbb5e8ea9269405f7a8527fe126023d1db2c973cfac6f760b60ae27294" + ), + unhexlify( + "7858ae7cd52ea6d4b17e800ca60144423db5560bfd618b663ffbf26ab66758563df45cbffae8463db22dc285dd94309083b8c807776085b97d05374d79867d05" + ), + "This is an example of a signed message.", ) def test_verify_long(self): self.setup_mnemonic_nopin_nopassphrase() with self.client: - self.client.set_expected_responses([ - proto.ButtonRequest(code=proto.ButtonRequestType.Other), - proto.ButtonRequest(code=proto.ButtonRequestType.Other), - proto.Success(message='Message verified') - ]) + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.Other), + proto.ButtonRequest(code=proto.ButtonRequestType.Other), + proto.Success(message="Message verified"), + ] + ) lisk.verify_message( self.client, - unhexlify('8bca6b65a1a877767b746ea0b3c4310d404aa113df99c1b554e1802d70185ab5'), - unhexlify('458ca5896d0934866992268f7509b5e954d568b1251e20c19bd3149ee3c86ffb5a44d1c2a0abbb99a3ab4767272dbb0e419b4579e890a24919ebbbe6cc0f970f'), - 'VeryLongMessage!' * 64 + unhexlify( + "8bca6b65a1a877767b746ea0b3c4310d404aa113df99c1b554e1802d70185ab5" + ), + unhexlify( + "458ca5896d0934866992268f7509b5e954d568b1251e20c19bd3149ee3c86ffb5a44d1c2a0abbb99a3ab4767272dbb0e419b4579e890a24919ebbbe6cc0f970f" + ), + "VeryLongMessage!" * 64, ) diff --git a/trezorlib/tests/device_tests/test_msg_loaddevice.py b/trezorlib/tests/device_tests/test_msg_loaddevice.py index 60ba94f45a..3100275039 100644 --- a/trezorlib/tests/device_tests/test_msg_loaddevice.py +++ b/trezorlib/tests/device_tests/test_msg_loaddevice.py @@ -16,10 +16,9 @@ import pytest +from trezorlib import btc, debuglink, device + from .common import TrezorTest -from trezorlib import btc -from trezorlib import debuglink -from trezorlib import device @pytest.mark.skip_t2 @@ -36,12 +35,12 @@ class TestDeviceLoad(TrezorTest): passphrase_protection = self.client.debug.read_passphrase_protection() assert passphrase_protection is False - address = btc.get_address(self.client, 'Bitcoin', []) - assert address == '1EfKbQupktEMXf4gujJ9kCFo83k1iMqwqK' + address = btc.get_address(self.client, "Bitcoin", []) + assert address == "1EfKbQupktEMXf4gujJ9kCFo83k1iMqwqK" def test_load_device_2(self): self.setup_mnemonic_pin_passphrase() - self.client.set_passphrase('passphrase') + self.client.set_passphrase("passphrase") mnemonic = self.client.debug.read_mnemonic() assert mnemonic == self.mnemonic12 @@ -52,39 +51,79 @@ class TestDeviceLoad(TrezorTest): passphrase_protection = self.client.debug.read_passphrase_protection() assert passphrase_protection is True - address = btc.get_address(self.client, 'Bitcoin', []) - assert address == '15fiTDFwZd2kauHYYseifGi9daH2wniDHH' + address = btc.get_address(self.client, "Bitcoin", []) + assert address == "15fiTDFwZd2kauHYYseifGi9daH2wniDHH" 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' + 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' + 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) + 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', []) + 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) + 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', []) + 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) + 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', []) + 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) + 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', []) + address_nfd = btc.get_address(self.client, "Bitcoin", []) assert address_nfkd == address_nfc assert address_nfkd == address_nfkc diff --git a/trezorlib/tests/device_tests/test_msg_loaddevice_xprv.py b/trezorlib/tests/device_tests/test_msg_loaddevice_xprv.py index 3fec436301..13e2978f68 100644 --- a/trezorlib/tests/device_tests/test_msg_loaddevice_xprv.py +++ b/trezorlib/tests/device_tests/test_msg_loaddevice_xprv.py @@ -16,30 +16,43 @@ import pytest +from trezorlib import btc, debuglink + from .common import TrezorTest -from trezorlib import btc -from trezorlib import debuglink @pytest.mark.skip_t2 class TestDeviceLoadXprv(TrezorTest): - def test_load_device_xprv_1(self): - debuglink.load_device_by_xprv(self.client, xprv='xprv9s21ZrQH143K2JF8RafpqtKiTbsbaxEeUaMnNHsm5o6wCW3z8ySyH4UxFVSfZ8n7ESu7fgir8imbZKLYVBxFPND1pniTZ81vKfd45EHKX73', pin='', passphrase_protection=False, label='test', language='english') + debuglink.load_device_by_xprv( + self.client, + xprv="xprv9s21ZrQH143K2JF8RafpqtKiTbsbaxEeUaMnNHsm5o6wCW3z8ySyH4UxFVSfZ8n7ESu7fgir8imbZKLYVBxFPND1pniTZ81vKfd45EHKX73", + pin="", + passphrase_protection=False, + label="test", + language="english", + ) passphrase_protection = self.client.debug.read_passphrase_protection() assert passphrase_protection is False - address = btc.get_address(self.client, 'Bitcoin', []) - assert address == '128RdrAkJDmqasgvfRf6MC5VcX4HKqH4mR' + address = btc.get_address(self.client, "Bitcoin", []) + assert address == "128RdrAkJDmqasgvfRf6MC5VcX4HKqH4mR" def test_load_device_xprv_2(self): - debuglink.load_device_by_xprv(self.client, xprv='xprv9s21ZrQH143K2JF8RafpqtKiTbsbaxEeUaMnNHsm5o6wCW3z8ySyH4UxFVSfZ8n7ESu7fgir8imbZKLYVBxFPND1pniTZ81vKfd45EHKX73', pin='', passphrase_protection=True, label='test', language='english') + debuglink.load_device_by_xprv( + self.client, + xprv="xprv9s21ZrQH143K2JF8RafpqtKiTbsbaxEeUaMnNHsm5o6wCW3z8ySyH4UxFVSfZ8n7ESu7fgir8imbZKLYVBxFPND1pniTZ81vKfd45EHKX73", + pin="", + passphrase_protection=True, + label="test", + language="english", + ) - self.client.set_passphrase('passphrase') + self.client.set_passphrase("passphrase") passphrase_protection = self.client.debug.read_passphrase_protection() assert passphrase_protection is True - address = btc.get_address(self.client, 'Bitcoin', []) - assert address == '1CHUbFa4wTTPYgkYaw2LHSd5D4qJjMU8ri' + address = btc.get_address(self.client, "Bitcoin", []) + assert address == "1CHUbFa4wTTPYgkYaw2LHSd5D4qJjMU8ri" diff --git a/trezorlib/tests/device_tests/test_msg_nem_getaddress.py b/trezorlib/tests/device_tests/test_msg_nem_getaddress.py index 9ab5be75e9..3b92e84daa 100644 --- a/trezorlib/tests/device_tests/test_msg_nem_getaddress.py +++ b/trezorlib/tests/device_tests/test_msg_nem_getaddress.py @@ -16,15 +16,21 @@ import pytest -from .common import TrezorTest -from trezorlib.tools import parse_path from trezorlib import nem +from trezorlib.tools import parse_path + +from .common import TrezorTest @pytest.mark.nem class TestMsgNEMGetaddress(TrezorTest): - def test_nem_getaddress(self): self.setup_mnemonic_nopin_nopassphrase() - assert nem.get_address(self.client, parse_path("m/44'/1'/0'/0'/0'"), 0x68) == "NB3JCHVARQNGDS3UVGAJPTFE22UQFGMCQGHUBWQN" - assert nem.get_address(self.client, parse_path("m/44'/1'/0'/0'/0'"), 0x98) == "TB3JCHVARQNGDS3UVGAJPTFE22UQFGMCQHSBNBMF" + assert ( + nem.get_address(self.client, parse_path("m/44'/1'/0'/0'/0'"), 0x68) + == "NB3JCHVARQNGDS3UVGAJPTFE22UQFGMCQGHUBWQN" + ) + assert ( + nem.get_address(self.client, parse_path("m/44'/1'/0'/0'/0'"), 0x98) + == "TB3JCHVARQNGDS3UVGAJPTFE22UQFGMCQHSBNBMF" + ) diff --git a/trezorlib/tests/device_tests/test_msg_nem_signtx_mosaics.py b/trezorlib/tests/device_tests/test_msg_nem_signtx_mosaics.py index 1ab6b5437d..c6c79f8420 100644 --- a/trezorlib/tests/device_tests/test_msg_nem_signtx_mosaics.py +++ b/trezorlib/tests/device_tests/test_msg_nem_signtx_mosaics.py @@ -14,162 +14,160 @@ # You should have received a copy of the License along with this library. # If not, see . -import pytest from binascii import hexlify -from .common import TrezorTest +import pytest + from trezorlib import nem from trezorlib.tools import parse_path +from .common import TrezorTest + # assertion data from T1 @pytest.mark.nem @pytest.mark.skip_t2 class TestMsgNEMSignTxMosaics(TrezorTest): - def test_nem_signtx_mosaic_supply_change(self): self.setup_mnemonic_nopin_nopassphrase() - tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { - "timeStamp": 74649215, - "fee": 2000000, - "type": nem.TYPE_MOSAIC_SUPPLY_CHANGE, - "deadline": 74735615, - "message": { + tx = nem.sign_tx( + self.client, + parse_path("m/44'/1'/0'/0'/0'"), + { + "timeStamp": 74649215, + "fee": 2000000, + "type": nem.TYPE_MOSAIC_SUPPLY_CHANGE, + "deadline": 74735615, + "message": {}, + "mosaicId": {"namespaceId": "hellom", "name": "Hello mosaic"}, + "supplyType": 1, + "delta": 1, + "version": (0x98 << 24), + "creationFeeSink": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", + "creationFee": 1500, }, - "mosaicId": { - "namespaceId": "hellom", - "name": "Hello mosaic" - }, - "supplyType": 1, - "delta": 1, - "version": (0x98 << 24), - "creationFeeSink": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", - "creationFee": 1500, - }) + ) - assert hexlify(tx.data) == b'02400000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f74041a0000000600000068656c6c6f6d0c00000048656c6c6f206d6f73616963010000000100000000000000' - assert hexlify(tx.signature) == b'928b03c4a69fff35ecf0912066ea705895b3028fad141197d7ea2b56f1eef2a2516455e6f35d318f6fa39e2bb40492ac4ae603260790f7ebc7ea69feb4ca4c0a' + assert ( + hexlify(tx.data) + == b"02400000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f74041a0000000600000068656c6c6f6d0c00000048656c6c6f206d6f73616963010000000100000000000000" + ) + assert ( + hexlify(tx.signature) + == b"928b03c4a69fff35ecf0912066ea705895b3028fad141197d7ea2b56f1eef2a2516455e6f35d318f6fa39e2bb40492ac4ae603260790f7ebc7ea69feb4ca4c0a" + ) def test_nem_signtx_mosaic_creation(self): self.setup_mnemonic_nopin_nopassphrase() - tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { - "timeStamp": 74649215, - "fee": 2000000, - "type": nem.TYPE_MOSAIC_CREATION, - "deadline": 74735615, - "message": { - }, - "mosaicDefinition": { - "id": { - "namespaceId": "hellom", - "name": "Hello mosaic" + tx = nem.sign_tx( + self.client, + parse_path("m/44'/1'/0'/0'/0'"), + { + "timeStamp": 74649215, + "fee": 2000000, + "type": nem.TYPE_MOSAIC_CREATION, + "deadline": 74735615, + "message": {}, + "mosaicDefinition": { + "id": {"namespaceId": "hellom", "name": "Hello mosaic"}, + "levy": {}, + "properties": {}, + "description": "lorem", }, - "levy": {}, - "properties": {}, - "description": "lorem" + "version": (0x98 << 24), + "creationFeeSink": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", + "creationFee": 1500, }, - "version": (0x98 << 24), - "creationFeeSink": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", - "creationFee": 1500, - }) + ) - assert hexlify(tx.data) == b'01400000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f7404c100000020000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b40620841a0000000600000068656c6c6f6d0c00000048656c6c6f206d6f73616963050000006c6f72656d04000000150000000c00000064697669736962696c6974790100000030160000000d000000696e697469616c537570706c7901000000301a0000000d000000737570706c794d757461626c650500000066616c7365190000000c0000007472616e7366657261626c650500000066616c7365000000002800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324adc05000000000000' - assert hexlify(tx.signature) == b'537adf4fd9bd5b46e204b2db0a435257a951ed26008305e0aa9e1201dafa4c306d7601a8dbacabf36b5137724386124958d53202015ab31fb3d0849dfed2df0e' + assert ( + hexlify(tx.data) + == b"01400000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f7404c100000020000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b40620841a0000000600000068656c6c6f6d0c00000048656c6c6f206d6f73616963050000006c6f72656d04000000150000000c00000064697669736962696c6974790100000030160000000d000000696e697469616c537570706c7901000000301a0000000d000000737570706c794d757461626c650500000066616c7365190000000c0000007472616e7366657261626c650500000066616c7365000000002800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324adc05000000000000" + ) + assert ( + hexlify(tx.signature) + == b"537adf4fd9bd5b46e204b2db0a435257a951ed26008305e0aa9e1201dafa4c306d7601a8dbacabf36b5137724386124958d53202015ab31fb3d0849dfed2df0e" + ) def test_nem_signtx_mosaic_creation_properties(self): self.setup_mnemonic_nopin_nopassphrase() - tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { - "timeStamp": 74649215, - "fee": 2000000, - "type": nem.TYPE_MOSAIC_CREATION, - "deadline": 74735615, - "message": { - }, - "mosaicDefinition": { - "id": { - "namespaceId": "hellom", - "name": "Hello mosaic" + tx = nem.sign_tx( + self.client, + parse_path("m/44'/1'/0'/0'/0'"), + { + "timeStamp": 74649215, + "fee": 2000000, + "type": nem.TYPE_MOSAIC_CREATION, + "deadline": 74735615, + "message": {}, + "mosaicDefinition": { + "id": {"namespaceId": "hellom", "name": "Hello mosaic"}, + "levy": {}, + "properties": [ + {"name": "divisibility", "value": "4"}, + {"name": "initialSupply", "value": "200"}, + {"name": "supplyMutable", "value": "false"}, + {"name": "transferable", "value": "true"}, + ], + "description": "lorem", }, - "levy": {}, - "properties": [ - { - "name": "divisibility", - "value": "4" - }, - { - "name": "initialSupply", - "value": "200" - }, - { - "name": "supplyMutable", - "value": "false" - }, - { - "name": "transferable", - "value": "true" - } - ], - "description": "lorem" + "version": (0x98 << 24), + "creationFeeSink": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", + "creationFee": 1500, }, - "version": (0x98 << 24), - "creationFeeSink": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", - "creationFee": 1500, - }) + ) - assert hexlify(tx.data) == b'01400000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f7404c200000020000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b40620841a0000000600000068656c6c6f6d0c00000048656c6c6f206d6f73616963050000006c6f72656d04000000150000000c00000064697669736962696c6974790100000034180000000d000000696e697469616c537570706c79030000003230301a0000000d000000737570706c794d757461626c650500000066616c7365180000000c0000007472616e7366657261626c650400000074727565000000002800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324adc05000000000000' - assert hexlify(tx.signature) == b'f17c859710060f2ea9a0ab740ef427431cf36bdc7d263570ca282bd66032e9f5737a921be9839429732e663be2bb74ccc16f34f5157ff2ef00a65796b54e800e' + assert ( + hexlify(tx.data) + == b"01400000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f7404c200000020000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b40620841a0000000600000068656c6c6f6d0c00000048656c6c6f206d6f73616963050000006c6f72656d04000000150000000c00000064697669736962696c6974790100000034180000000d000000696e697469616c537570706c79030000003230301a0000000d000000737570706c794d757461626c650500000066616c7365180000000c0000007472616e7366657261626c650400000074727565000000002800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324adc05000000000000" + ) + assert ( + hexlify(tx.signature) + == b"f17c859710060f2ea9a0ab740ef427431cf36bdc7d263570ca282bd66032e9f5737a921be9839429732e663be2bb74ccc16f34f5157ff2ef00a65796b54e800e" + ) def test_nem_signtx_mosaic_creation_levy(self): self.setup_mnemonic_nopin_nopassphrase() - tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { - "timeStamp": 74649215, - "fee": 2000000, - "type": nem.TYPE_MOSAIC_CREATION, - "deadline": 74735615, - "message": { - }, - "mosaicDefinition": { - "id": { - "namespaceId": "hellom", - "name": "Hello mosaic" + tx = nem.sign_tx( + self.client, + parse_path("m/44'/1'/0'/0'/0'"), + { + "timeStamp": 74649215, + "fee": 2000000, + "type": nem.TYPE_MOSAIC_CREATION, + "deadline": 74735615, + "message": {}, + "mosaicDefinition": { + "id": {"namespaceId": "hellom", "name": "Hello mosaic"}, + "properties": [ + {"name": "divisibility", "value": "4"}, + {"name": "initialSupply", "value": "200"}, + {"name": "supplyMutable", "value": "false"}, + {"name": "transferable", "value": "true"}, + ], + "levy": { + "type": 1, + "fee": 2, + "recipient": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", + "mosaicId": {"namespaceId": "hellom", "name": "Hello mosaic"}, + }, + "description": "lorem", }, - "properties": [ - { - "name": "divisibility", - "value": "4" - }, - { - "name": "initialSupply", - "value": "200" - }, - { - "name": "supplyMutable", - "value": "false" - }, - { - "name": "transferable", - "value": "true" - } - ], - "levy": { - "type": 1, - "fee": 2, - "recipient": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", - "mosaicId": { - "namespaceId": "hellom", - "name": "Hello mosaic" - }, - }, - "description": "lorem" + "version": (0x98 << 24), + "creationFeeSink": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", + "creationFee": 1500, }, - "version": (0x98 << 24), - "creationFeeSink": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", - "creationFee": 1500, - }) + ) - assert hexlify(tx.data) == b'01400000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f74041801000020000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b40620841a0000000600000068656c6c6f6d0c00000048656c6c6f206d6f73616963050000006c6f72656d04000000150000000c00000064697669736962696c6974790100000034180000000d000000696e697469616c537570706c79030000003230301a0000000d000000737570706c794d757461626c650500000066616c7365180000000c0000007472616e7366657261626c65040000007472756556000000010000002800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324a1a0000000600000068656c6c6f6d0c00000048656c6c6f206d6f7361696302000000000000002800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324adc05000000000000' - assert hexlify(tx.signature) == b'b87aac1ddf146d35e6a7f3451f57e2fe504ac559031e010a51261257c37bd50fcfa7b2939dd7a3203b54c4807d458475182f5d3dc135ec0d1d4a9cd42159fd0a' + assert ( + hexlify(tx.data) + == b"01400000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f74041801000020000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b40620841a0000000600000068656c6c6f6d0c00000048656c6c6f206d6f73616963050000006c6f72656d04000000150000000c00000064697669736962696c6974790100000034180000000d000000696e697469616c537570706c79030000003230301a0000000d000000737570706c794d757461626c650500000066616c7365180000000c0000007472616e7366657261626c65040000007472756556000000010000002800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324a1a0000000600000068656c6c6f6d0c00000048656c6c6f206d6f7361696302000000000000002800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324adc05000000000000" + ) + assert ( + hexlify(tx.signature) + == b"b87aac1ddf146d35e6a7f3451f57e2fe504ac559031e010a51261257c37bd50fcfa7b2939dd7a3203b54c4807d458475182f5d3dc135ec0d1d4a9cd42159fd0a" + ) diff --git a/trezorlib/tests/device_tests/test_msg_nem_signtx_mosaics_t2.py b/trezorlib/tests/device_tests/test_msg_nem_signtx_mosaics_t2.py index adf1f56ef4..2bec8cee53 100644 --- a/trezorlib/tests/device_tests/test_msg_nem_signtx_mosaics_t2.py +++ b/trezorlib/tests/device_tests/test_msg_nem_signtx_mosaics_t2.py @@ -14,45 +14,51 @@ # You should have received a copy of the License along with this library. # If not, see . -from binascii import hexlify -import pytest import time +from binascii import hexlify + +import pytest + +from trezorlib import messages as proto, nem +from trezorlib.tools import parse_path from .common import TrezorTest -from trezorlib import messages as proto -from trezorlib import nem -from trezorlib.tools import parse_path # assertion data from T1 @pytest.mark.nem @pytest.mark.skip_t1 class TestMsgNEMSignTxMosaics(TrezorTest): - def test_nem_signtx_mosaic_supply_change(self): self.setup_mnemonic_nopin_nopassphrase() with self.client: - tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { - "timeStamp": 74649215, - "fee": 2000000, - "type": nem.TYPE_MOSAIC_SUPPLY_CHANGE, - "deadline": 74735615, - "message": { + tx = nem.sign_tx( + self.client, + parse_path("m/44'/1'/0'/0'/0'"), + { + "timeStamp": 74649215, + "fee": 2000000, + "type": nem.TYPE_MOSAIC_SUPPLY_CHANGE, + "deadline": 74735615, + "message": {}, + "mosaicId": {"namespaceId": "hellom", "name": "Hello mosaic"}, + "supplyType": 1, + "delta": 1, + "version": (0x98 << 24), + "creationFeeSink": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", + "creationFee": 1500, }, - "mosaicId": { - "namespaceId": "hellom", - "name": "Hello mosaic" - }, - "supplyType": 1, - "delta": 1, - "version": (0x98 << 24), - "creationFeeSink": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", - "creationFee": 1500, - }) + ) - assert hexlify(tx.data) == b'02400000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f74041a0000000600000068656c6c6f6d0c00000048656c6c6f206d6f73616963010000000100000000000000' - assert hexlify(tx.signature) == b'928b03c4a69fff35ecf0912066ea705895b3028fad141197d7ea2b56f1eef2a2516455e6f35d318f6fa39e2bb40492ac4ae603260790f7ebc7ea69feb4ca4c0a' + assert ( + hexlify(tx.data) + == b"02400000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f74041a0000000600000068656c6c6f6d0c00000048656c6c6f206d6f73616963010000000100000000000000" + ) + assert ( + hexlify(tx.signature) + == b"928b03c4a69fff35ecf0912066ea705895b3028fad141197d7ea2b56f1eef2a2516455e6f35d318f6fa39e2bb40492ac4ae603260790f7ebc7ea69feb4ca4c0a" + ) def test_nem_signtx_mosaic_creation(self): self.setup_mnemonic_nopin_nopassphrase() @@ -62,16 +68,12 @@ class TestMsgNEMSignTxMosaics(TrezorTest): "fee": 2000000, "type": nem.TYPE_MOSAIC_CREATION, "deadline": 74735615, - "message": { - }, + "message": {}, "mosaicDefinition": { - "id": { - "namespaceId": "hellom", - "name": "Hello mosaic" - }, + "id": {"namespaceId": "hellom", "name": "Hello mosaic"}, "levy": {}, "properties": {}, - "description": "lorem" + "description": "lorem", }, "version": (0x98 << 24), "creationFeeSink": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", @@ -80,8 +82,14 @@ class TestMsgNEMSignTxMosaics(TrezorTest): # not using client.nem_sign_tx() because of swiping tx = self._nem_sign(2, test_suite) - assert hexlify(tx.data) == b'01400000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f7404c100000020000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b40620841a0000000600000068656c6c6f6d0c00000048656c6c6f206d6f73616963050000006c6f72656d04000000150000000c00000064697669736962696c6974790100000030160000000d000000696e697469616c537570706c7901000000301a0000000d000000737570706c794d757461626c650500000066616c7365190000000c0000007472616e7366657261626c650500000066616c7365000000002800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324adc05000000000000' - assert hexlify(tx.signature) == b'537adf4fd9bd5b46e204b2db0a435257a951ed26008305e0aa9e1201dafa4c306d7601a8dbacabf36b5137724386124958d53202015ab31fb3d0849dfed2df0e' + assert ( + hexlify(tx.data) + == b"01400000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f7404c100000020000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b40620841a0000000600000068656c6c6f6d0c00000048656c6c6f206d6f73616963050000006c6f72656d04000000150000000c00000064697669736962696c6974790100000030160000000d000000696e697469616c537570706c7901000000301a0000000d000000737570706c794d757461626c650500000066616c7365190000000c0000007472616e7366657261626c650500000066616c7365000000002800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324adc05000000000000" + ) + assert ( + hexlify(tx.signature) + == b"537adf4fd9bd5b46e204b2db0a435257a951ed26008305e0aa9e1201dafa4c306d7601a8dbacabf36b5137724386124958d53202015ab31fb3d0849dfed2df0e" + ) def test_nem_signtx_mosaic_creation_properties(self): self.setup_mnemonic_nopin_nopassphrase() @@ -91,33 +99,17 @@ class TestMsgNEMSignTxMosaics(TrezorTest): "fee": 2000000, "type": nem.TYPE_MOSAIC_CREATION, "deadline": 74735615, - "message": { - }, + "message": {}, "mosaicDefinition": { - "id": { - "namespaceId": "hellom", - "name": "Hello mosaic" - }, + "id": {"namespaceId": "hellom", "name": "Hello mosaic"}, "levy": {}, "properties": [ - { - "name": "divisibility", - "value": "4" - }, - { - "name": "initialSupply", - "value": "200" - }, - { - "name": "supplyMutable", - "value": "false" - }, - { - "name": "transferable", - "value": "true" - } + {"name": "divisibility", "value": "4"}, + {"name": "initialSupply", "value": "200"}, + {"name": "supplyMutable", "value": "false"}, + {"name": "transferable", "value": "true"}, ], - "description": "lorem" + "description": "lorem", }, "version": (0x98 << 24), "creationFeeSink": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", @@ -126,8 +118,14 @@ class TestMsgNEMSignTxMosaics(TrezorTest): # not using client.nem_sign_tx() because of swiping tx = self._nem_sign(2, test_suite) - assert hexlify(tx.data) == b'01400000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f7404c200000020000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b40620841a0000000600000068656c6c6f6d0c00000048656c6c6f206d6f73616963050000006c6f72656d04000000150000000c00000064697669736962696c6974790100000034180000000d000000696e697469616c537570706c79030000003230301a0000000d000000737570706c794d757461626c650500000066616c7365180000000c0000007472616e7366657261626c650400000074727565000000002800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324adc05000000000000' - assert hexlify(tx.signature) == b'f17c859710060f2ea9a0ab740ef427431cf36bdc7d263570ca282bd66032e9f5737a921be9839429732e663be2bb74ccc16f34f5157ff2ef00a65796b54e800e' + assert ( + hexlify(tx.data) + == b"01400000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f7404c200000020000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b40620841a0000000600000068656c6c6f6d0c00000048656c6c6f206d6f73616963050000006c6f72656d04000000150000000c00000064697669736962696c6974790100000034180000000d000000696e697469616c537570706c79030000003230301a0000000d000000737570706c794d757461626c650500000066616c7365180000000c0000007472616e7366657261626c650400000074727565000000002800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324adc05000000000000" + ) + assert ( + hexlify(tx.signature) + == b"f17c859710060f2ea9a0ab740ef427431cf36bdc7d263570ca282bd66032e9f5737a921be9839429732e663be2bb74ccc16f34f5157ff2ef00a65796b54e800e" + ) def test_nem_signtx_mosaic_creation_levy(self): self.setup_mnemonic_nopin_nopassphrase() @@ -137,41 +135,22 @@ class TestMsgNEMSignTxMosaics(TrezorTest): "fee": 2000000, "type": nem.TYPE_MOSAIC_CREATION, "deadline": 74735615, - "message": { - }, + "message": {}, "mosaicDefinition": { - "id": { - "namespaceId": "hellom", - "name": "Hello mosaic" - }, + "id": {"namespaceId": "hellom", "name": "Hello mosaic"}, "properties": [ - { - "name": "divisibility", - "value": "4" - }, - { - "name": "initialSupply", - "value": "200" - }, - { - "name": "supplyMutable", - "value": "false" - }, - { - "name": "transferable", - "value": "true" - } + {"name": "divisibility", "value": "4"}, + {"name": "initialSupply", "value": "200"}, + {"name": "supplyMutable", "value": "false"}, + {"name": "transferable", "value": "true"}, ], "levy": { "type": 1, "fee": 2, "recipient": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", - "mosaicId": { - "namespaceId": "hellom", - "name": "Hello mosaic" - }, + "mosaicId": {"namespaceId": "hellom", "name": "Hello mosaic"}, }, - "description": "lorem" + "description": "lorem", }, "version": (0x98 << 24), "creationFeeSink": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", @@ -179,8 +158,14 @@ class TestMsgNEMSignTxMosaics(TrezorTest): } tx = self._nem_sign(6, test_suite) - assert hexlify(tx.data) == b'01400000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f74041801000020000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b40620841a0000000600000068656c6c6f6d0c00000048656c6c6f206d6f73616963050000006c6f72656d04000000150000000c00000064697669736962696c6974790100000034180000000d000000696e697469616c537570706c79030000003230301a0000000d000000737570706c794d757461626c650500000066616c7365180000000c0000007472616e7366657261626c65040000007472756556000000010000002800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324a1a0000000600000068656c6c6f6d0c00000048656c6c6f206d6f7361696302000000000000002800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324adc05000000000000' - assert hexlify(tx.signature) == b'b87aac1ddf146d35e6a7f3451f57e2fe504ac559031e010a51261257c37bd50fcfa7b2939dd7a3203b54c4807d458475182f5d3dc135ec0d1d4a9cd42159fd0a' + assert ( + hexlify(tx.data) + == b"01400000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f74041801000020000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b40620841a0000000600000068656c6c6f6d0c00000048656c6c6f206d6f73616963050000006c6f72656d04000000150000000c00000064697669736962696c6974790100000034180000000d000000696e697469616c537570706c79030000003230301a0000000d000000737570706c794d757461626c650500000066616c7365180000000c0000007472616e7366657261626c65040000007472756556000000010000002800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324a1a0000000600000068656c6c6f6d0c00000048656c6c6f206d6f7361696302000000000000002800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324adc05000000000000" + ) + assert ( + hexlify(tx.signature) + == b"b87aac1ddf146d35e6a7f3451f57e2fe504ac559031e010a51261257c37bd50fcfa7b2939dd7a3203b54c4807d458475182f5d3dc135ec0d1d4a9cd42159fd0a" + ) def _nem_sign(self, num_of_swipes, test_suite): n = parse_path("m/44'/1'/0'/0'/0'") diff --git a/trezorlib/tests/device_tests/test_msg_nem_signtx_multisig.py b/trezorlib/tests/device_tests/test_msg_nem_signtx_multisig.py index 6b265698bc..65ade1c4e8 100644 --- a/trezorlib/tests/device_tests/test_msg_nem_signtx_multisig.py +++ b/trezorlib/tests/device_tests/test_msg_nem_signtx_multisig.py @@ -15,148 +15,190 @@ # If not, see . from binascii import hexlify + import pytest -from .common import TrezorTest +from trezorlib import nem from trezorlib.tools import parse_path -from trezorlib import nem +from .common import TrezorTest # assertion data from T1 @pytest.mark.nem class TestMsgNEMSignTxMultisig(TrezorTest): - def test_nem_signtx_aggregate_modification(self): self.setup_mnemonic_nopin_nopassphrase() - tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { - "timeStamp": 74649215, - "fee": 2000000, - "type": nem.TYPE_AGGREGATE_MODIFICATION, - "deadline": 74735615, - "message": { + tx = nem.sign_tx( + self.client, + parse_path("m/44'/1'/0'/0'/0'"), + { + "timeStamp": 74649215, + "fee": 2000000, + "type": nem.TYPE_AGGREGATE_MODIFICATION, + "deadline": 74735615, + "message": {}, + "modifications": [ + { + "modificationType": 1, # Add + "cosignatoryAccount": "c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f87844", + } + ], + "minCosignatories": {"relativeChange": 3}, + "version": (0x98 << 24), }, - "modifications": [ - { - "modificationType": 1, # Add - "cosignatoryAccount": "c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f87844" - }, - ], - "minCosignatories": { - "relativeChange": 3 - }, - "version": (0x98 << 24), - }) - assert hexlify(tx.data) == b'01100000020000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f740401000000280000000100000020000000c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f878440400000003000000' - assert hexlify(tx.signature) == b'1200e552d8732ce3eae96719731194abfc5a09d98f61bb35684f4eeaeff15b1bdf326ee7b1bbbe89d3f68c8e07ad3daf72e4c7f031094ad2236b97918ad98601' + ) + assert ( + hexlify(tx.data) + == b"01100000020000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f740401000000280000000100000020000000c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f878440400000003000000" + ) + assert ( + hexlify(tx.signature) + == b"1200e552d8732ce3eae96719731194abfc5a09d98f61bb35684f4eeaeff15b1bdf326ee7b1bbbe89d3f68c8e07ad3daf72e4c7f031094ad2236b97918ad98601" + ) def test_nem_signtx_multisig(self): self.setup_mnemonic_nopin_nopassphrase() - tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { - "timeStamp": 1, - "fee": 10000, - "type": nem.TYPE_MULTISIG, - "deadline": 74735615, - "otherTrans": { # simple transaction transfer - "timeStamp": 2, - "amount": 2000000, - "fee": 15000, - "recipient": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", - "type": nem.TYPE_TRANSACTION_TRANSFER, - "deadline": 67890, - "message": { - "payload": hexlify(b"test_nem_transaction_transfer"), - "type": 1, + tx = nem.sign_tx( + self.client, + parse_path("m/44'/1'/0'/0'/0'"), + { + "timeStamp": 1, + "fee": 10000, + "type": nem.TYPE_MULTISIG, + "deadline": 74735615, + "otherTrans": { # simple transaction transfer + "timeStamp": 2, + "amount": 2000000, + "fee": 15000, + "recipient": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", + "type": nem.TYPE_TRANSACTION_TRANSFER, + "deadline": 67890, + "message": { + "payload": hexlify(b"test_nem_transaction_transfer"), + "type": 1, + }, + "version": (0x98 << 24), + "signer": "c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f87844", }, "version": (0x98 << 24), - "signer": 'c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f87844', }, - "version": (0x98 << 24), - }) + ) - assert hexlify(tx.data) == b'04100000010000980100000020000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b40620841027000000000000ff5f74049900000001010000010000980200000020000000c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f87844983a000000000000320901002800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324a80841e000000000025000000010000001d000000746573745f6e656d5f7472616e73616374696f6e5f7472616e73666572' - assert hexlify(tx.signature) == b'0cab2fddf2f02b5d7201675b9a71869292fe25ed33a366c7d2cbea7676fed491faaa03310079b7e17884b6ba2e3ea21c4f728d1cca8f190b8288207f6514820a' + assert ( + hexlify(tx.data) + == b"04100000010000980100000020000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b40620841027000000000000ff5f74049900000001010000010000980200000020000000c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f87844983a000000000000320901002800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324a80841e000000000025000000010000001d000000746573745f6e656d5f7472616e73616374696f6e5f7472616e73666572" + ) + assert ( + hexlify(tx.signature) + == b"0cab2fddf2f02b5d7201675b9a71869292fe25ed33a366c7d2cbea7676fed491faaa03310079b7e17884b6ba2e3ea21c4f728d1cca8f190b8288207f6514820a" + ) - tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { - "timeStamp": 74649215, - "fee": 150, - "type": nem.TYPE_MULTISIG, - "deadline": 789, - "otherTrans": { - "timeStamp": 123456, - "fee": 2000, - "type": nem.TYPE_PROVISION_NAMESPACE, - "deadline": 100, - "message": { + tx = nem.sign_tx( + self.client, + parse_path("m/44'/1'/0'/0'/0'"), + { + "timeStamp": 74649215, + "fee": 150, + "type": nem.TYPE_MULTISIG, + "deadline": 789, + "otherTrans": { + "timeStamp": 123456, + "fee": 2000, + "type": nem.TYPE_PROVISION_NAMESPACE, + "deadline": 100, + "message": {}, + "newPart": "ABCDE", + "rentalFeeSink": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", + "rentalFee": 1500, + "parent": None, + "version": (0x98 << 24), + "signer": "c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f87844", }, - "newPart": "ABCDE", - "rentalFeeSink": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", - "rentalFee": 1500, - "parent": None, "version": (0x98 << 24), - "signer": 'c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f87844', }, - "version": (0x98 << 24), - }) + ) - assert hexlify(tx.data) == b'04100000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b40620849600000000000000150300007d000000012000000100009840e2010020000000c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f87844d007000000000000640000002800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324adc05000000000000050000004142434445ffffffff' - assert hexlify(tx.signature) == b'c915ca3332380925f4050301cdc62269cf29437ac5955321b18da34e570c7fdbb1aec2940a2a553a2a5c90950a4db3c8d3ef899c1a108582e0657f66fbbb0b04' + assert ( + hexlify(tx.data) + == b"04100000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b40620849600000000000000150300007d000000012000000100009840e2010020000000c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f87844d007000000000000640000002800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324adc05000000000000050000004142434445ffffffff" + ) + assert ( + hexlify(tx.signature) + == b"c915ca3332380925f4050301cdc62269cf29437ac5955321b18da34e570c7fdbb1aec2940a2a553a2a5c90950a4db3c8d3ef899c1a108582e0657f66fbbb0b04" + ) def test_nem_signtx_multisig_signer(self): self.setup_mnemonic_nopin_nopassphrase() - tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { - "timeStamp": 333, - "fee": 200, - "type": nem.TYPE_MULTISIG_SIGNATURE, - "deadline": 444, - "otherTrans": { # simple transaction transfer - "timeStamp": 555, - "amount": 2000000, - "fee": 2000000, - "recipient": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", - "type": nem.TYPE_TRANSACTION_TRANSFER, - "deadline": 666, - "message": { - "payload": hexlify(b"test_nem_transaction_transfer"), - "type": 1, + tx = nem.sign_tx( + self.client, + parse_path("m/44'/1'/0'/0'/0'"), + { + "timeStamp": 333, + "fee": 200, + "type": nem.TYPE_MULTISIG_SIGNATURE, + "deadline": 444, + "otherTrans": { # simple transaction transfer + "timeStamp": 555, + "amount": 2000000, + "fee": 2000000, + "recipient": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", + "type": nem.TYPE_TRANSACTION_TRANSFER, + "deadline": 666, + "message": { + "payload": hexlify(b"test_nem_transaction_transfer"), + "type": 1, + }, + "version": (0x98 << 24), + "signer": "c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f87844", }, "version": (0x98 << 24), - "signer": 'c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f87844', }, - "version": (0x98 << 24), - }) + ) - assert hexlify(tx.data) == b'02100000010000984d01000020000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b4062084c800000000000000bc010000240000002000000087923cd4805f3babe6b5af9cbb2b08be4458e39531618aed73c911f160c8e38528000000544444324354364c514c49595135364b49584933454e544d36454b3344343450354b5a50464d4b32' - assert hexlify(tx.signature) == b'286358a16ae545bff798feab93a713440c7c2f236d52ac0e995669d17a1915b0903667c97fa04418eccb42333cba95b19bccc8ac1faa8224dcfaeb41890ae807' + assert ( + hexlify(tx.data) + == b"02100000010000984d01000020000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b4062084c800000000000000bc010000240000002000000087923cd4805f3babe6b5af9cbb2b08be4458e39531618aed73c911f160c8e38528000000544444324354364c514c49595135364b49584933454e544d36454b3344343450354b5a50464d4b32" + ) + assert ( + hexlify(tx.signature) + == b"286358a16ae545bff798feab93a713440c7c2f236d52ac0e995669d17a1915b0903667c97fa04418eccb42333cba95b19bccc8ac1faa8224dcfaeb41890ae807" + ) - tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { - "timeStamp": 900000, - "fee": 200000, - "type": nem.TYPE_MULTISIG_SIGNATURE, - "deadline": 100, - "otherTrans": { # simple transaction transfer - "timeStamp": 101111, - "fee": 1000, - "type": nem.TYPE_MOSAIC_SUPPLY_CHANGE, - "deadline": 13123, - "message": { + tx = nem.sign_tx( + self.client, + parse_path("m/44'/1'/0'/0'/0'"), + { + "timeStamp": 900000, + "fee": 200000, + "type": nem.TYPE_MULTISIG_SIGNATURE, + "deadline": 100, + "otherTrans": { # simple transaction transfer + "timeStamp": 101111, + "fee": 1000, + "type": nem.TYPE_MOSAIC_SUPPLY_CHANGE, + "deadline": 13123, + "message": {}, + "mosaicId": {"namespaceId": "hellom", "name": "Hello mosaic"}, + "supplyType": 1, + "delta": 1, + "version": (0x98 << 24), + "creationFeeSink": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", + "creationFee": 1500, + "signer": "c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f87844", }, - "mosaicId": { - "namespaceId": "hellom", - "name": "Hello mosaic" - }, - "supplyType": 1, - "delta": 1, "version": (0x98 << 24), - "creationFeeSink": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", - "creationFee": 1500, - "signer": 'c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f87844', }, - "version": (0x98 << 24), - }) + ) - assert hexlify(tx.data) == b'0210000001000098a0bb0d0020000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b4062084400d030000000000640000002400000020000000c51395626a89a71c1ed785fb5974307a049b3b9e2165d56ed0302fe6b4f02a0128000000544444324354364c514c49595135364b49584933454e544d36454b3344343450354b5a50464d4b32' - assert hexlify(tx.signature) == b'32b1fdf788c4a90c01eedf5972b7709745831d620c13e1e97b0de6481837e162ee551573f2409822754ae940731909ec4b79cf836487e898df476adb10467506' + assert ( + hexlify(tx.data) + == b"0210000001000098a0bb0d0020000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b4062084400d030000000000640000002400000020000000c51395626a89a71c1ed785fb5974307a049b3b9e2165d56ed0302fe6b4f02a0128000000544444324354364c514c49595135364b49584933454e544d36454b3344343450354b5a50464d4b32" + ) + assert ( + hexlify(tx.signature) + == b"32b1fdf788c4a90c01eedf5972b7709745831d620c13e1e97b0de6481837e162ee551573f2409822754ae940731909ec4b79cf836487e898df476adb10467506" + ) diff --git a/trezorlib/tests/device_tests/test_msg_nem_signtx_others.py b/trezorlib/tests/device_tests/test_msg_nem_signtx_others.py index 18052c2ee3..a52bb6d0e8 100644 --- a/trezorlib/tests/device_tests/test_msg_nem_signtx_others.py +++ b/trezorlib/tests/device_tests/test_msg_nem_signtx_others.py @@ -15,56 +15,74 @@ # If not, see . from binascii import hexlify -import pytest -from .common import TrezorTest +import pytest from trezorlib import nem from trezorlib.tools import parse_path +from .common import TrezorTest + # assertion data from T1 @pytest.mark.nem class TestMsgNEMSignTxOther(TrezorTest): - def test_nem_signtx_importance_transfer(self): self.setup_mnemonic_nopin_nopassphrase() with self.client: - tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { - "timeStamp": 12349215, - "fee": 9900, - "type": nem.TYPE_IMPORTANCE_TRANSFER, - "deadline": 99, - "message": { + tx = nem.sign_tx( + self.client, + parse_path("m/44'/1'/0'/0'/0'"), + { + "timeStamp": 12349215, + "fee": 9900, + "type": nem.TYPE_IMPORTANCE_TRANSFER, + "deadline": 99, + "message": {}, + "importanceTransfer": { + "mode": 1, # activate + "publicKey": "c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f87844", + }, + "version": (0x98 << 24), }, - "importanceTransfer": { - "mode": 1, # activate - "publicKey": "c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f87844", - }, - "version": (0x98 << 24), - }) + ) - assert hexlify(tx.data) == b'01080000010000981f6fbc0020000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b4062084ac26000000000000630000000100000020000000c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f87844' - assert hexlify(tx.signature) == b'b6d9434ec5df80e65e6e45d7f0f3c579b4adfe8567c42d981b06e8ac368b1aad2b24eebecd5efd41f4497051fca8ea8a5e77636a79afc46ee1a8e0fe9e3ba90b' + assert ( + hexlify(tx.data) + == b"01080000010000981f6fbc0020000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b4062084ac26000000000000630000000100000020000000c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f87844" + ) + assert ( + hexlify(tx.signature) + == b"b6d9434ec5df80e65e6e45d7f0f3c579b4adfe8567c42d981b06e8ac368b1aad2b24eebecd5efd41f4497051fca8ea8a5e77636a79afc46ee1a8e0fe9e3ba90b" + ) def test_nem_signtx_provision_namespace(self): self.setup_mnemonic_nopin_nopassphrase() - tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { - "timeStamp": 74649215, - "fee": 2000000, - "type": nem.TYPE_PROVISION_NAMESPACE, - "deadline": 74735615, - "message": { + tx = nem.sign_tx( + self.client, + parse_path("m/44'/1'/0'/0'/0'"), + { + "timeStamp": 74649215, + "fee": 2000000, + "type": nem.TYPE_PROVISION_NAMESPACE, + "deadline": 74735615, + "message": {}, + "newPart": "ABCDE", + "rentalFeeSink": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", + "rentalFee": 1500, + "parent": None, + "version": (0x98 << 24), }, - "newPart": "ABCDE", - "rentalFeeSink": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", - "rentalFee": 1500, - "parent": None, - "version": (0x98 << 24), - }) + ) - assert hexlify(tx.data) == b'01200000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f74042800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324adc05000000000000050000004142434445ffffffff' - assert hexlify(tx.signature) == b'f047ae7987cd3a60c0d5ad123aba211185cb6266a7469dfb0491a0df6b5cd9c92b2e2b9f396cc2a3146ee185ba02df4f9e7fb238fe479917b3d274d97336640d' + assert ( + hexlify(tx.data) + == b"01200000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f74042800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324adc05000000000000050000004142434445ffffffff" + ) + assert ( + hexlify(tx.signature) + == b"f047ae7987cd3a60c0d5ad123aba211185cb6266a7469dfb0491a0df6b5cd9c92b2e2b9f396cc2a3146ee185ba02df4f9e7fb238fe479917b3d274d97336640d" + ) diff --git a/trezorlib/tests/device_tests/test_msg_nem_signtx_transfers.py b/trezorlib/tests/device_tests/test_msg_nem_signtx_transfers.py index 6159aaaa91..9db81cecd3 100644 --- a/trezorlib/tests/device_tests/test_msg_nem_signtx_transfers.py +++ b/trezorlib/tests/device_tests/test_msg_nem_signtx_transfers.py @@ -15,19 +15,18 @@ # If not, see . from binascii import hexlify, unhexlify + import pytest -from .common import TrezorTest - -from trezorlib import messages as proto -from trezorlib import nem +from trezorlib import messages as proto, nem from trezorlib.tools import parse_path +from .common import TrezorTest + # assertion data from T1 @pytest.mark.nem class TestMsgNEMSignTx(TrezorTest): - def test_nem_signtx_simple(self): # tx hash: 209368053ac61969b6838ceb7e31badeb622ed6aa42d6c58365c42ad1a11e19d signature = unhexlify( @@ -36,65 +35,83 @@ class TestMsgNEMSignTx(TrezorTest): self.setup_mnemonic_nopin_nopassphrase() with self.client: - self.client.set_expected_responses([ - # Confirm transfer and network fee - proto.ButtonRequest(code=proto.ButtonRequestType.ConfirmOutput), - # Unencrypted message - proto.ButtonRequest(code=proto.ButtonRequestType.ConfirmOutput), - # Confirm recipient - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.NEMSignedTx(), - ]) + self.client.set_expected_responses( + [ + # Confirm transfer and network fee + proto.ButtonRequest(code=proto.ButtonRequestType.ConfirmOutput), + # Unencrypted message + proto.ButtonRequest(code=proto.ButtonRequestType.ConfirmOutput), + # Confirm recipient + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.NEMSignedTx(), + ] + ) - tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { - "timeStamp": 74649215, - "amount": 2000000, - "fee": 2000000, - "recipient": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", - "type": nem.TYPE_TRANSACTION_TRANSFER, - "deadline": 74735615, - "message": { - "payload": hexlify(b"test_nem_transaction_transfer"), - "type": 1, + tx = nem.sign_tx( + self.client, + parse_path("m/44'/1'/0'/0'/0'"), + { + "timeStamp": 74649215, + "amount": 2000000, + "fee": 2000000, + "recipient": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", + "type": nem.TYPE_TRANSACTION_TRANSFER, + "deadline": 74735615, + "message": { + "payload": hexlify(b"test_nem_transaction_transfer"), + "type": 1, + }, + "version": (0x98 << 24), }, - "version": (0x98 << 24), - }) + ) - assert hexlify(tx.data) == b'01010000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f74042800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324a80841e000000000025000000010000001d000000746573745f6e656d5f7472616e73616374696f6e5f7472616e73666572' + assert ( + hexlify(tx.data) + == b"01010000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f74042800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324a80841e000000000025000000010000001d000000746573745f6e656d5f7472616e73616374696f6e5f7472616e73666572" + ) assert tx.signature == signature def test_nem_signtx_encrypted_payload(self): self.setup_mnemonic_nopin_nopassphrase() with self.client: - self.client.set_expected_responses([ - # Confirm transfer and network fee - proto.ButtonRequest(code=proto.ButtonRequestType.ConfirmOutput), - # Ask for encryption - proto.ButtonRequest(code=proto.ButtonRequestType.ConfirmOutput), - # Confirm recipient - proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), - proto.NEMSignedTx(), - ]) + self.client.set_expected_responses( + [ + # Confirm transfer and network fee + proto.ButtonRequest(code=proto.ButtonRequestType.ConfirmOutput), + # Ask for encryption + proto.ButtonRequest(code=proto.ButtonRequestType.ConfirmOutput), + # Confirm recipient + proto.ButtonRequest(code=proto.ButtonRequestType.SignTx), + proto.NEMSignedTx(), + ] + ) - tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { - "timeStamp": 74649215, - "amount": 2000000, - "fee": 2000000, - "recipient": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", - "type": nem.TYPE_TRANSACTION_TRANSFER, - "deadline": 74735615, - "message": { - # plain text is 32B long => cipher text is 48B - # as per PKCS#7 another block containing padding is added - "payload": hexlify(b"this message should be encrypted"), - "publicKey": "5a5e14c633d7d269302849d739d80344ff14db51d7bcda86045723f05c4e4541", - "type": 2, + tx = nem.sign_tx( + self.client, + parse_path("m/44'/1'/0'/0'/0'"), + { + "timeStamp": 74649215, + "amount": 2000000, + "fee": 2000000, + "recipient": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", + "type": nem.TYPE_TRANSACTION_TRANSFER, + "deadline": 74735615, + "message": { + # plain text is 32B long => cipher text is 48B + # as per PKCS#7 another block containing padding is added + "payload": hexlify(b"this message should be encrypted"), + "publicKey": "5a5e14c633d7d269302849d739d80344ff14db51d7bcda86045723f05c4e4541", + "type": 2, + }, + "version": (0x98 << 24), }, - "version": (0x98 << 24), - }) + ) - assert hexlify(tx.data[:124]) == b'01010000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f74042800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324a80841e0000000000680000000200000060000000' + assert ( + hexlify(tx.data[:124]) + == b"01010000010000987f0e730420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208480841e0000000000ff5f74042800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324a80841e0000000000680000000200000060000000" + ) # after 124th byte comes iv (16B) salt (32B) and encrypted payload (48B) assert len(tx.data[124:]) == 16 + 32 + 48 # because IV and salt are random (therefore the encrypted payload as well) those data can't be asserted @@ -103,170 +120,188 @@ class TestMsgNEMSignTx(TrezorTest): def test_nem_signtx_xem_as_mosaic(self): self.setup_mnemonic_nopin_nopassphrase() - tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { - "timeStamp": 76809215, - "amount": 5000000, - "fee": 1000000, - "recipient": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", - "type": nem.TYPE_TRANSACTION_TRANSFER, - "deadline": 76895615, - "version": (0x98 << 24), - "message": { + tx = nem.sign_tx( + self.client, + parse_path("m/44'/1'/0'/0'/0'"), + { + "timeStamp": 76809215, + "amount": 5000000, + "fee": 1000000, + "recipient": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", + "type": nem.TYPE_TRANSACTION_TRANSFER, + "deadline": 76895615, + "version": (0x98 << 24), + "message": {}, + "mosaics": [ + { + "mosaicId": {"namespaceId": "nem", "name": "xem"}, + "quantity": 9000000, + } + ], }, - "mosaics": [ - { - "mosaicId": { - "namespaceId": "nem", - "name": "xem", - }, - "quantity": 9000000, - }, - ], - }) + ) # trezor should display 45 XEM (multiplied by amount) - assert hexlify(tx.data) == b'0101000002000098ff03940420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208440420f00000000007f5595042800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324a404b4c000000000000000000010000001a0000000e000000030000006e656d0300000078656d4054890000000000' - assert hexlify(tx.signature) == b'7b25a84b65adb489ea55739f1ca2d83a0ae069c3c58d0ea075fc30bfe8f649519199ad2324ca229c6c3214191469f95326e99712124592cae7cd3a092c93ac0c' + assert ( + hexlify(tx.data) + == b"0101000002000098ff03940420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208440420f00000000007f5595042800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324a404b4c000000000000000000010000001a0000000e000000030000006e656d0300000078656d4054890000000000" + ) + assert ( + hexlify(tx.signature) + == b"7b25a84b65adb489ea55739f1ca2d83a0ae069c3c58d0ea075fc30bfe8f649519199ad2324ca229c6c3214191469f95326e99712124592cae7cd3a092c93ac0c" + ) def test_nem_signtx_unknown_mosaic(self): self.setup_mnemonic_nopin_nopassphrase() - tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { - "timeStamp": 76809215, - "amount": 2000000, - "fee": 1000000, - "recipient": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", - "type": nem.TYPE_TRANSACTION_TRANSFER, - "deadline": 76895615, - "version": (0x98 << 24), - "message": { + tx = nem.sign_tx( + self.client, + parse_path("m/44'/1'/0'/0'/0'"), + { + "timeStamp": 76809215, + "amount": 2000000, + "fee": 1000000, + "recipient": "TALICE2GMA34CXHD7XLJQ536NM5UNKQHTORNNT2J", + "type": nem.TYPE_TRANSACTION_TRANSFER, + "deadline": 76895615, + "version": (0x98 << 24), + "message": {}, + "mosaics": [ + { + "mosaicId": {"namespaceId": "xxx", "name": "aa"}, + "quantity": 3500000, + } + ], }, - "mosaics": [ - { - "mosaicId": { - "namespaceId": "xxx", - "name": "aa", - }, - "quantity": 3500000, - }, - ], - }) + ) # trezor should display warning about unknown mosaic and then dialog for 7000000 raw units of xxx.aa and 0 XEM - assert hexlify(tx.data) == b'0101000002000098ff03940420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208440420f00000000007f5595042800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324a80841e00000000000000000001000000190000000d00000003000000787878020000006161e067350000000000' - assert hexlify(tx.signature) == b'2f0280420eceb41ef9e5d94fa44ddda9cdc70b8f423ae18af577f6d85df64bb4aaf40cf24fc6eef47c63b0963611f8682348cecdc49a9b64eafcbe7afcb49102' + assert ( + hexlify(tx.data) + == b"0101000002000098ff03940420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208440420f00000000007f5595042800000054414c49434532474d4133344358484437584c4a513533364e4d35554e4b5148544f524e4e54324a80841e00000000000000000001000000190000000d00000003000000787878020000006161e067350000000000" + ) + assert ( + hexlify(tx.signature) + == b"2f0280420eceb41ef9e5d94fa44ddda9cdc70b8f423ae18af577f6d85df64bb4aaf40cf24fc6eef47c63b0963611f8682348cecdc49a9b64eafcbe7afcb49102" + ) def test_nem_signtx_known_mosaic(self): self.setup_mnemonic_nopin_nopassphrase() - tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { - "timeStamp": 76809215, - "amount": 3000000, - "fee": 1000000, - "recipient": "NDMYSLXI4L3FYUQWO4MJOVL6BSTJJXKDSZRMT4LT", - "type": nem.TYPE_TRANSACTION_TRANSFER, - "deadline": 76895615, - "version": (0x68 << 24), - "message": { + tx = nem.sign_tx( + self.client, + parse_path("m/44'/1'/0'/0'/0'"), + { + "timeStamp": 76809215, + "amount": 3000000, + "fee": 1000000, + "recipient": "NDMYSLXI4L3FYUQWO4MJOVL6BSTJJXKDSZRMT4LT", + "type": nem.TYPE_TRANSACTION_TRANSFER, + "deadline": 76895615, + "version": (0x68 << 24), + "message": {}, + "mosaics": [ + { + "mosaicId": {"namespaceId": "dim", "name": "token"}, + "quantity": 111000, + } + ], }, - "mosaics": [ - { - "mosaicId": { - "namespaceId": "dim", - "name": "token", - }, - "quantity": 111000, - }, - ], - }) + ) # trezor should display 0 XEM and 0.333 DIMTOK - assert hexlify(tx.data) == b'0101000002000068ff03940420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208440420f00000000007f559504280000004e444d59534c5849344c3346595551574f344d4a4f564c364253544a4a584b44535a524d54344c54c0c62d000000000000000000010000001c000000100000000300000064696d05000000746f6b656e98b1010000000000' - assert hexlify(tx.signature) == b'e7f14ef8c39727bfd257e109cd5acac31542f2e41f2e5deb258fc1db602b690eb1cabca41a627fe2adc51f3193db85c76b41c80bb60161eb8738ebf20b507104' + assert ( + hexlify(tx.data) + == b"0101000002000068ff03940420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208440420f00000000007f559504280000004e444d59534c5849344c3346595551574f344d4a4f564c364253544a4a584b44535a524d54344c54c0c62d000000000000000000010000001c000000100000000300000064696d05000000746f6b656e98b1010000000000" + ) + assert ( + hexlify(tx.signature) + == b"e7f14ef8c39727bfd257e109cd5acac31542f2e41f2e5deb258fc1db602b690eb1cabca41a627fe2adc51f3193db85c76b41c80bb60161eb8738ebf20b507104" + ) def test_nem_signtx_known_mosaic_with_levy(self): self.setup_mnemonic_nopin_nopassphrase() - tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { - "timeStamp": 76809215, - "amount": 2000000, - "fee": 1000000, - "recipient": "NDMYSLXI4L3FYUQWO4MJOVL6BSTJJXKDSZRMT4LT", - "type": nem.TYPE_TRANSACTION_TRANSFER, - "deadline": 76895615, - "version": (0x68 << 24), - "message": { + tx = nem.sign_tx( + self.client, + parse_path("m/44'/1'/0'/0'/0'"), + { + "timeStamp": 76809215, + "amount": 2000000, + "fee": 1000000, + "recipient": "NDMYSLXI4L3FYUQWO4MJOVL6BSTJJXKDSZRMT4LT", + "type": nem.TYPE_TRANSACTION_TRANSFER, + "deadline": 76895615, + "version": (0x68 << 24), + "message": {}, + "mosaics": [ + { + "mosaicId": {"namespaceId": "dim", "name": "coin"}, + "quantity": 222000, + } + ], }, - "mosaics": [ - { - "mosaicId": { - "namespaceId": "dim", - "name": "coin", - }, - "quantity": 222000, - }, - ], - }) + ) # trezor should display 0 XEM and 0.444 DIM and levy of 0.000444 DIM - assert hexlify(tx.data) == b'0101000002000068ff03940420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208440420f00000000007f559504280000004e444d59534c5849344c3346595551574f344d4a4f564c364253544a4a584b44535a524d54344c5480841e000000000000000000010000001b0000000f0000000300000064696d04000000636f696e3063030000000000' - assert hexlify(tx.signature) == b'd3222dd7b83d66bda0539827ac6f909d06e40350b5e5e893d6fa762f954e9bf7da61022ef04950e7b6dfa88a2278f2f8a1b21df2bc3af22b388cb3a90bf76f07' + assert ( + hexlify(tx.data) + == b"0101000002000068ff03940420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208440420f00000000007f559504280000004e444d59534c5849344c3346595551574f344d4a4f564c364253544a4a584b44535a524d54344c5480841e000000000000000000010000001b0000000f0000000300000064696d04000000636f696e3063030000000000" + ) + assert ( + hexlify(tx.signature) + == b"d3222dd7b83d66bda0539827ac6f909d06e40350b5e5e893d6fa762f954e9bf7da61022ef04950e7b6dfa88a2278f2f8a1b21df2bc3af22b388cb3a90bf76f07" + ) def test_nem_signtx_multiple_mosaics(self): self.setup_mnemonic_nopin_nopassphrase() - tx = nem.sign_tx(self.client, parse_path("m/44'/1'/0'/0'/0'"), { - "timeStamp": 76809215, - "amount": 2000000, - "fee": 1000000, - "recipient": "NDMYSLXI4L3FYUQWO4MJOVL6BSTJJXKDSZRMT4LT", - "type": nem.TYPE_TRANSACTION_TRANSFER, - "deadline": 76895615, - "version": (0x68 << 24), - "message": { + tx = nem.sign_tx( + self.client, + parse_path("m/44'/1'/0'/0'/0'"), + { + "timeStamp": 76809215, + "amount": 2000000, + "fee": 1000000, + "recipient": "NDMYSLXI4L3FYUQWO4MJOVL6BSTJJXKDSZRMT4LT", + "type": nem.TYPE_TRANSACTION_TRANSFER, + "deadline": 76895615, + "version": (0x68 << 24), + "message": {}, + "mosaics": [ + { + "mosaicId": {"namespaceId": "nem", "name": "xem"}, + "quantity": 3000000, + }, + { + "mosaicId": {"namespaceId": "abc", "name": "mosaic"}, + "quantity": 200, + }, + { + "mosaicId": {"namespaceId": "nem", "name": "xem"}, + "quantity": 30000, + }, + { + "mosaicId": {"namespaceId": "abc", "name": "mosaic"}, + "quantity": 2000000, + }, + { + "mosaicId": {"namespaceId": "breeze", "name": "breeze-token"}, + "quantity": 111000, + }, + ], }, - "mosaics": [ - { - "mosaicId": { - "namespaceId": "nem", - "name": "xem", - }, - "quantity": 3000000, - }, - { - "mosaicId": { - "namespaceId": "abc", - "name": "mosaic", - }, - "quantity": 200, - }, - { - "mosaicId": { - "namespaceId": "nem", - "name": "xem", - }, - "quantity": 30000, - }, - { - "mosaicId": { - "namespaceId": "abc", - "name": "mosaic", - }, - "quantity": 2000000, - }, - { - "mosaicId": { - "namespaceId": "breeze", - "name": "breeze-token", - }, - "quantity": 111000, - } - ] - }) + ) # trezor should display warning, 6.06 XEM, 4000400 raw units of abc.mosaic (mosaics are merged) # and 222000 BREEZE - assert hexlify(tx.data) == b'0101000002000068ff03940420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208440420f00000000007f559504280000004e444d59534c5849344c3346595551574f344d4a4f564c364253544a4a584b44535a524d54344c5480841e000000000000000000030000001d0000001100000003000000616263060000006d6f7361696348851e0000000000260000001a00000006000000627265657a650c000000627265657a652d746f6b656e98b10100000000001a0000000e000000030000006e656d0300000078656df03b2e0000000000' - assert hexlify(tx.signature) == b'b2b9319fca87a05bee17108edd9a8f78aeffef74bf6b4badc6da5d46e8ff4fe82e24bf69d8e6c4097d072adf39d0c753e7580f8afb21e3288ebfb7c4d84e470d' + assert ( + hexlify(tx.data) + == b"0101000002000068ff03940420000000edfd32f6e760648c032f9acb4b30d514265f6a5b5f8a7154f2618922b406208440420f00000000007f559504280000004e444d59534c5849344c3346595551574f344d4a4f564c364253544a4a584b44535a524d54344c5480841e000000000000000000030000001d0000001100000003000000616263060000006d6f7361696348851e0000000000260000001a00000006000000627265657a650c000000627265657a652d746f6b656e98b10100000000001a0000000e000000030000006e656d0300000078656df03b2e0000000000" + ) + assert ( + hexlify(tx.signature) + == b"b2b9319fca87a05bee17108edd9a8f78aeffef74bf6b4badc6da5d46e8ff4fe82e24bf69d8e6c4097d072adf39d0c753e7580f8afb21e3288ebfb7c4d84e470d" + ) diff --git a/trezorlib/tests/device_tests/test_msg_ping.py b/trezorlib/tests/device_tests/test_msg_ping.py index 369dc8830b..6a16197e4a 100644 --- a/trezorlib/tests/device_tests/test_msg_ping.py +++ b/trezorlib/tests/device_tests/test_msg_ping.py @@ -16,47 +16,77 @@ import pytest -from .common import TrezorTest - from trezorlib import messages as proto +from .common import TrezorTest + @pytest.mark.skip_t2 class TestMsgPing(TrezorTest): - def test_ping(self): self.setup_mnemonic_pin_passphrase() with self.client: self.client.set_expected_responses([proto.Success()]) - res = self.client.ping('random data') - assert res == 'random data' + res = self.client.ping("random data") + assert res == "random data" with self.client: - self.client.set_expected_responses([proto.ButtonRequest(code=proto.ButtonRequestType.ProtectCall), proto.Success()]) - res = self.client.ping('random data', button_protection=True) - assert res == 'random data' + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.ProtectCall), + proto.Success(), + ] + ) + res = self.client.ping("random data", button_protection=True) + assert res == "random data" with self.client: - self.client.set_expected_responses([proto.PinMatrixRequest(), proto.Success()]) - res = self.client.ping('random data', pin_protection=True) - assert res == 'random data' + self.client.set_expected_responses( + [proto.PinMatrixRequest(), proto.Success()] + ) + res = self.client.ping("random data", pin_protection=True) + assert res == "random data" with self.client: - self.client.set_expected_responses([proto.PassphraseRequest(), proto.Success()]) - res = self.client.ping('random data', passphrase_protection=True) - assert res == 'random data' + self.client.set_expected_responses( + [proto.PassphraseRequest(), proto.Success()] + ) + res = self.client.ping("random data", passphrase_protection=True) + assert res == "random data" def test_ping_caching(self): self.setup_mnemonic_pin_passphrase() with self.client: - self.client.set_expected_responses([proto.ButtonRequest(code=proto.ButtonRequestType.ProtectCall), proto.PinMatrixRequest(), proto.PassphraseRequest(), proto.Success()]) - res = self.client.ping('random data', button_protection=True, pin_protection=True, passphrase_protection=True) - assert res == 'random data' + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.ProtectCall), + proto.PinMatrixRequest(), + proto.PassphraseRequest(), + proto.Success(), + ] + ) + res = self.client.ping( + "random data", + button_protection=True, + pin_protection=True, + passphrase_protection=True, + ) + assert res == "random data" with self.client: # pin and passphrase are cached - self.client.set_expected_responses([proto.ButtonRequest(code=proto.ButtonRequestType.ProtectCall), proto.Success()]) - res = self.client.ping('random data', button_protection=True, pin_protection=True, passphrase_protection=True) - assert res == 'random data' + self.client.set_expected_responses( + [ + proto.ButtonRequest(code=proto.ButtonRequestType.ProtectCall), + proto.Success(), + ] + ) + res = self.client.ping( + "random data", + button_protection=True, + pin_protection=True, + passphrase_protection=True, + ) + assert res == "random data" diff --git a/trezorlib/tests/device_tests/test_msg_recoverydevice.py b/trezorlib/tests/device_tests/test_msg_recoverydevice.py index cdabc18f1c..ecb7eae552 100644 --- a/trezorlib/tests/device_tests/test_msg_recoverydevice.py +++ b/trezorlib/tests/device_tests/test_msg_recoverydevice.py @@ -16,22 +16,25 @@ import pytest +from trezorlib import device, messages as proto + from .common import TrezorTest -from trezorlib import messages as proto -from trezorlib import device @pytest.mark.skip_t2 class TestMsgRecoverydevice(TrezorTest): - def test_pin_passphrase(self): - mnemonic = self.mnemonic12.split(' ') - ret = self.client.call_raw(proto.RecoveryDevice(word_count=12, - passphrase_protection=True, - pin_protection=True, - label='label', - language='english', - enforce_wordlist=True)) + mnemonic = self.mnemonic12.split(" ") + ret = self.client.call_raw( + proto.RecoveryDevice( + word_count=12, + passphrase_protection=True, + pin_protection=True, + label="label", + language="english", + enforce_wordlist=True, + ) + ) # click through confirmation assert isinstance(ret, proto.ButtonRequest) @@ -88,13 +91,17 @@ class TestMsgRecoverydevice(TrezorTest): self.client.call_raw(proto.Cancel()) def test_nopin_nopassphrase(self): - mnemonic = self.mnemonic12.split(' ') - ret = self.client.call_raw(proto.RecoveryDevice(word_count=12, - passphrase_protection=False, - pin_protection=False, - label='label', - language='english', - enforce_wordlist=True)) + mnemonic = self.mnemonic12.split(" ") + ret = self.client.call_raw( + proto.RecoveryDevice( + word_count=12, + passphrase_protection=False, + pin_protection=False, + label="label", + language="english", + enforce_wordlist=True, + ) + ) # click through confirmation assert isinstance(ret, proto.ButtonRequest) @@ -138,12 +145,16 @@ class TestMsgRecoverydevice(TrezorTest): assert isinstance(resp, proto.Success) def test_word_fail(self): - ret = self.client.call_raw(proto.RecoveryDevice(word_count=12, - passphrase_protection=False, - pin_protection=False, - label='label', - language='english', - enforce_wordlist=True)) + ret = self.client.call_raw( + proto.RecoveryDevice( + word_count=12, + passphrase_protection=False, + pin_protection=False, + label="label", + language="english", + enforce_wordlist=True, + ) + ) # click through confirmation assert isinstance(ret, proto.ButtonRequest) @@ -154,19 +165,23 @@ class TestMsgRecoverydevice(TrezorTest): for _ in range(int(12 * 2)): (word, pos) = self.client.debug.read_recovery_word() if pos != 0: - ret = self.client.call_raw(proto.WordAck(word='kwyjibo')) + ret = self.client.call_raw(proto.WordAck(word="kwyjibo")) assert isinstance(ret, proto.Failure) break else: self.client.call_raw(proto.WordAck(word=word)) def test_pin_fail(self): - ret = self.client.call_raw(proto.RecoveryDevice(word_count=12, - passphrase_protection=True, - pin_protection=True, - label='label', - language='english', - enforce_wordlist=True)) + ret = self.client.call_raw( + proto.RecoveryDevice( + word_count=12, + passphrase_protection=True, + pin_protection=True, + label="label", + language="english", + enforce_wordlist=True, + ) + ) # click through confirmation assert isinstance(ret, proto.ButtonRequest) @@ -190,4 +205,4 @@ class TestMsgRecoverydevice(TrezorTest): def test_already_initialized(self): self.setup_mnemonic_nopin_nopassphrase() with pytest.raises(Exception): - device.recover(self.client, 12, False, False, 'label', 'english') + device.recover(self.client, 12, False, False, "label", "english") diff --git a/trezorlib/tests/device_tests/test_msg_recoverydevice_dryrun.py b/trezorlib/tests/device_tests/test_msg_recoverydevice_dryrun.py index e25f25798c..d9284e61c1 100644 --- a/trezorlib/tests/device_tests/test_msg_recoverydevice_dryrun.py +++ b/trezorlib/tests/device_tests/test_msg_recoverydevice_dryrun.py @@ -16,21 +16,25 @@ import pytest -from .common import TrezorTest from trezorlib import messages as proto +from .common import TrezorTest + @pytest.mark.skip_t2 class TestMsgRecoverydeviceDryrun(TrezorTest): - def recovery_loop(self, mnemonic, result): - ret = self.client.call_raw(proto.RecoveryDevice(word_count=12, - passphrase_protection=False, - pin_protection=False, - label='label', - language='english', - enforce_wordlist=True, - dry_run=True)) + ret = self.client.call_raw( + proto.RecoveryDevice( + word_count=12, + passphrase_protection=False, + pin_protection=False, + label="label", + language="english", + enforce_wordlist=True, + dry_run=True, + ) + ) fakes = 0 for _ in range(int(12 * 2)): @@ -54,15 +58,15 @@ class TestMsgRecoverydeviceDryrun(TrezorTest): def test_correct_notsame(self): self.setup_mnemonic_nopin_nopassphrase() - mnemonic = ['all'] * 12 + mnemonic = ["all"] * 12 self.recovery_loop(mnemonic, proto.Failure) def test_correct_same(self): self.setup_mnemonic_nopin_nopassphrase() - mnemonic = self.mnemonic12.split(' ') + mnemonic = self.mnemonic12.split(" ") self.recovery_loop(mnemonic, proto.Success) def test_incorrect(self): self.setup_mnemonic_nopin_nopassphrase() - mnemonic = ['stick'] * 12 + mnemonic = ["stick"] * 12 self.recovery_loop(mnemonic, proto.Failure) diff --git a/trezorlib/tests/device_tests/test_msg_recoverydevice_t2.py b/trezorlib/tests/device_tests/test_msg_recoverydevice_t2.py index 43304ea3c1..149388f13c 100644 --- a/trezorlib/tests/device_tests/test_msg_recoverydevice_t2.py +++ b/trezorlib/tests/device_tests/test_msg_recoverydevice_t2.py @@ -18,24 +18,28 @@ import time import pytest +from trezorlib import device, messages as proto + from .common import TrezorTest -from trezorlib import messages as proto -from trezorlib import device @pytest.mark.skip_t1 class TestMsgRecoverydeviceT2(TrezorTest): - def test_pin_passphrase(self): - mnemonic = self.mnemonic12.split(' ') - ret = self.client.call_raw(proto.RecoveryDevice( - passphrase_protection=True, - pin_protection=True, - label='label', - enforce_wordlist=True)) + mnemonic = self.mnemonic12.split(" ") + ret = self.client.call_raw( + proto.RecoveryDevice( + passphrase_protection=True, + pin_protection=True, + label="label", + enforce_wordlist=True, + ) + ) # Enter word count - assert ret == proto.ButtonRequest(code=proto.ButtonRequestType.MnemonicWordCount) + assert ret == proto.ButtonRequest( + code=proto.ButtonRequestType.MnemonicWordCount + ) self.client.debug.input(str(len(mnemonic))) ret = self.client.call_raw(proto.ButtonAck()) @@ -49,16 +53,16 @@ class TestMsgRecoverydeviceT2(TrezorTest): # Enter PIN for first time assert ret == proto.ButtonRequest(code=proto.ButtonRequestType.Other) - self.client.debug.input('654') + self.client.debug.input("654") ret = self.client.call_raw(proto.ButtonAck()) # Enter PIN for second time assert ret == proto.ButtonRequest(code=proto.ButtonRequestType.Other) - self.client.debug.input('654') + self.client.debug.input("654") ret = self.client.call_raw(proto.ButtonAck()) # Workflow succesfully ended - assert ret == proto.Success(message='Device recovered') + assert ret == proto.Success(message="Device recovered") # Mnemonic is the same self.client.init_device() @@ -68,15 +72,20 @@ class TestMsgRecoverydeviceT2(TrezorTest): assert self.client.features.passphrase_protection is True def test_nopin_nopassphrase(self): - mnemonic = self.mnemonic12.split(' ') - ret = self.client.call_raw(proto.RecoveryDevice( - passphrase_protection=False, - pin_protection=False, - label='label', - enforce_wordlist=True)) + mnemonic = self.mnemonic12.split(" ") + ret = self.client.call_raw( + proto.RecoveryDevice( + passphrase_protection=False, + pin_protection=False, + label="label", + enforce_wordlist=True, + ) + ) # Enter word count - assert ret == proto.ButtonRequest(code=proto.ButtonRequestType.MnemonicWordCount) + assert ret == proto.ButtonRequest( + code=proto.ButtonRequestType.MnemonicWordCount + ) self.client.debug.input(str(len(mnemonic))) ret = self.client.call_raw(proto.ButtonAck()) @@ -89,7 +98,7 @@ class TestMsgRecoverydeviceT2(TrezorTest): ret = self.client.transport.read() # Workflow succesfully ended - assert ret == proto.Success(message='Device recovered') + assert ret == proto.Success(message="Device recovered") # Mnemonic is the same self.client.init_device() @@ -101,4 +110,4 @@ class TestMsgRecoverydeviceT2(TrezorTest): def test_already_initialized(self): self.setup_mnemonic_nopin_nopassphrase() with pytest.raises(Exception): - device.recover(self.client, 12, False, False, 'label', 'english') + device.recover(self.client, 12, False, False, "label", "english") diff --git a/trezorlib/tests/device_tests/test_msg_resetdevice.py b/trezorlib/tests/device_tests/test_msg_resetdevice.py index 784e5730d6..3026f31e60 100644 --- a/trezorlib/tests/device_tests/test_msg_resetdevice.py +++ b/trezorlib/tests/device_tests/test_msg_resetdevice.py @@ -15,31 +15,31 @@ # If not, see . import pytest +from mnemonic import Mnemonic + +from trezorlib import device, messages as proto from .common import TrezorTest, generate_entropy -from trezorlib import messages as proto -from trezorlib import device -from mnemonic import Mnemonic - @pytest.mark.skip_t2 class TestMsgResetDevice(TrezorTest): - def test_reset_device(self): # No PIN, no passphrase - external_entropy = b'zlutoucky kun upel divoke ody' * 2 + external_entropy = b"zlutoucky kun upel divoke ody" * 2 strength = 128 - ret = self.client.call_raw(proto.ResetDevice( - display_random=False, - strength=strength, - passphrase_protection=False, - pin_protection=False, - language='english', - label='test' - )) + ret = self.client.call_raw( + proto.ResetDevice( + display_random=False, + strength=strength, + passphrase_protection=False, + pin_protection=False, + language="english", + label="test", + ) + ) # Provide entropy assert isinstance(ret, proto.EntropyRequest) @@ -48,7 +48,7 @@ class TestMsgResetDevice(TrezorTest): # Generate mnemonic locally entropy = generate_entropy(strength, internal_entropy, external_entropy) - expected_mnemonic = Mnemonic('english').to_mnemonic(entropy) + expected_mnemonic = Mnemonic("english").to_mnemonic(entropy) mnemonic = [] for _ in range(strength // 32 * 3): @@ -57,7 +57,7 @@ class TestMsgResetDevice(TrezorTest): self.client.debug.press_yes() self.client.call_raw(proto.ButtonAck()) - mnemonic = ' '.join(mnemonic) + mnemonic = " ".join(mnemonic) # Compare that device generated proper mnemonic for given entropies assert mnemonic == expected_mnemonic @@ -71,7 +71,7 @@ class TestMsgResetDevice(TrezorTest): assert isinstance(resp, proto.Success) - mnemonic = ' '.join(mnemonic) + mnemonic = " ".join(mnemonic) # Compare that second pass printed out the same mnemonic once again assert mnemonic == expected_mnemonic @@ -92,17 +92,19 @@ class TestMsgResetDevice(TrezorTest): assert isinstance(resp, proto.Success) def test_reset_device_pin(self): - external_entropy = b'zlutoucky kun upel divoke ody' * 2 + external_entropy = b"zlutoucky kun upel divoke ody" * 2 strength = 128 - ret = self.client.call_raw(proto.ResetDevice( - display_random=True, - strength=strength, - passphrase_protection=True, - pin_protection=True, - language='english', - label='test' - )) + ret = self.client.call_raw( + proto.ResetDevice( + display_random=True, + strength=strength, + passphrase_protection=True, + pin_protection=True, + language="english", + label="test", + ) + ) assert isinstance(ret, proto.ButtonRequest) self.client.debug.press_yes() @@ -111,12 +113,12 @@ class TestMsgResetDevice(TrezorTest): assert isinstance(ret, proto.PinMatrixRequest) # Enter PIN for first time - pin_encoded = self.client.debug.encode_pin('654') + pin_encoded = self.client.debug.encode_pin("654") ret = self.client.call_raw(proto.PinMatrixAck(pin=pin_encoded)) assert isinstance(ret, proto.PinMatrixRequest) # Enter PIN for second time - pin_encoded = self.client.debug.encode_pin('654') + pin_encoded = self.client.debug.encode_pin("654") ret = self.client.call_raw(proto.PinMatrixAck(pin=pin_encoded)) # Provide entropy @@ -126,7 +128,7 @@ class TestMsgResetDevice(TrezorTest): # Generate mnemonic locally entropy = generate_entropy(strength, internal_entropy, external_entropy) - expected_mnemonic = Mnemonic('english').to_mnemonic(entropy) + expected_mnemonic = Mnemonic("english").to_mnemonic(entropy) mnemonic = [] for _ in range(strength // 32 * 3): @@ -135,7 +137,7 @@ class TestMsgResetDevice(TrezorTest): self.client.debug.press_yes() self.client.call_raw(proto.ButtonAck()) - mnemonic = ' '.join(mnemonic) + mnemonic = " ".join(mnemonic) # Compare that device generated proper mnemonic for given entropies assert mnemonic == expected_mnemonic @@ -149,7 +151,7 @@ class TestMsgResetDevice(TrezorTest): assert isinstance(resp, proto.Success) - mnemonic = ' '.join(mnemonic) + mnemonic = " ".join(mnemonic) # Compare that second pass printed out the same mnemonic once again assert mnemonic == expected_mnemonic @@ -175,14 +177,16 @@ class TestMsgResetDevice(TrezorTest): # external_entropy = b'zlutoucky kun upel divoke ody' * 2 strength = 128 - ret = self.client.call_raw(proto.ResetDevice( - display_random=True, - strength=strength, - passphrase_protection=True, - pin_protection=True, - language='english', - label='test' - )) + ret = self.client.call_raw( + proto.ResetDevice( + display_random=True, + strength=strength, + passphrase_protection=True, + pin_protection=True, + language="english", + label="test", + ) + ) assert isinstance(ret, proto.ButtonRequest) self.client.debug.press_yes() @@ -204,4 +208,4 @@ class TestMsgResetDevice(TrezorTest): def test_already_initialized(self): self.setup_mnemonic_nopin_nopassphrase() with pytest.raises(Exception): - device.reset(self.client, False, 128, True, True, 'label', 'english') + device.reset(self.client, False, 128, True, True, "label", "english") diff --git a/trezorlib/tests/device_tests/test_msg_resetdevice_skipbackup.py b/trezorlib/tests/device_tests/test_msg_resetdevice_skipbackup.py index f47b6a4702..2c34831ce7 100644 --- a/trezorlib/tests/device_tests/test_msg_resetdevice_skipbackup.py +++ b/trezorlib/tests/device_tests/test_msg_resetdevice_skipbackup.py @@ -15,29 +15,31 @@ # If not, see . import pytest +from mnemonic import Mnemonic + +from trezorlib import messages as proto from .common import TrezorTest, generate_entropy -from trezorlib import messages as proto -from mnemonic import Mnemonic @pytest.mark.skip_t2 class TestMsgResetDeviceSkipbackup(TrezorTest): - def test_reset_device_skip_backup(self): - external_entropy = b'zlutoucky kun upel divoke ody' * 2 + external_entropy = b"zlutoucky kun upel divoke ody" * 2 strength = 128 - ret = self.client.call_raw(proto.ResetDevice( - display_random=False, - strength=strength, - passphrase_protection=False, - pin_protection=False, - language='english', - label='test', - skip_backup=True - )) + ret = self.client.call_raw( + proto.ResetDevice( + display_random=False, + strength=strength, + passphrase_protection=False, + pin_protection=False, + language="english", + label="test", + skip_backup=True, + ) + ) # Provide entropy assert isinstance(ret, proto.EntropyRequest) @@ -52,7 +54,7 @@ class TestMsgResetDeviceSkipbackup(TrezorTest): # Generate mnemonic locally entropy = generate_entropy(strength, internal_entropy, external_entropy) - expected_mnemonic = Mnemonic('english').to_mnemonic(entropy) + expected_mnemonic = Mnemonic("english").to_mnemonic(entropy) # start Backup workflow ret = self.client.call_raw(proto.BackupDevice()) @@ -64,7 +66,7 @@ class TestMsgResetDeviceSkipbackup(TrezorTest): self.client.debug.press_yes() self.client.call_raw(proto.ButtonAck()) - mnemonic = ' '.join(mnemonic) + mnemonic = " ".join(mnemonic) # Compare that device generated proper mnemonic for given entropies assert mnemonic == expected_mnemonic @@ -78,7 +80,7 @@ class TestMsgResetDeviceSkipbackup(TrezorTest): assert isinstance(resp, proto.Success) - mnemonic = ' '.join(mnemonic) + mnemonic = " ".join(mnemonic) # Compare that second pass printed out the same mnemonic once again assert mnemonic == expected_mnemonic @@ -89,18 +91,20 @@ class TestMsgResetDeviceSkipbackup(TrezorTest): def test_reset_device_skip_backup_break(self): - external_entropy = b'zlutoucky kun upel divoke ody' * 2 + external_entropy = b"zlutoucky kun upel divoke ody" * 2 strength = 128 - ret = self.client.call_raw(proto.ResetDevice( - display_random=False, - strength=strength, - passphrase_protection=False, - pin_protection=False, - language='english', - label='test', - skip_backup=True - )) + ret = self.client.call_raw( + proto.ResetDevice( + display_random=False, + strength=strength, + passphrase_protection=False, + pin_protection=False, + language="english", + label="test", + skip_backup=True, + ) + ) # Provide entropy assert isinstance(ret, proto.EntropyRequest) diff --git a/trezorlib/tests/device_tests/test_msg_resetdevice_t2.py b/trezorlib/tests/device_tests/test_msg_resetdevice_t2.py index 4236950e83..374988e09e 100644 --- a/trezorlib/tests/device_tests/test_msg_resetdevice_t2.py +++ b/trezorlib/tests/device_tests/test_msg_resetdevice_t2.py @@ -15,30 +15,31 @@ # If not, see . import time + import pytest +from mnemonic import Mnemonic + +from trezorlib import device, messages as proto from .common import TrezorTest, generate_entropy -from trezorlib import messages as proto -from trezorlib import device -from mnemonic import Mnemonic - @pytest.mark.skip_t1 class TestMsgResetDeviceT2(TrezorTest): - def test_reset_device(self): # No PIN, no passphrase, don't display random - external_entropy = b'zlutoucky kun upel divoke ody' * 2 + external_entropy = b"zlutoucky kun upel divoke ody" * 2 strength = 128 - ret = self.client.call_raw(proto.ResetDevice( - display_random=False, - strength=strength, - passphrase_protection=False, - pin_protection=False, - label='test' - )) + ret = self.client.call_raw( + proto.ResetDevice( + display_random=False, + strength=strength, + passphrase_protection=False, + pin_protection=False, + label="test", + ) + ) # Provide entropy assert isinstance(ret, proto.EntropyRequest) @@ -47,7 +48,7 @@ class TestMsgResetDeviceT2(TrezorTest): # Generate mnemonic locally entropy = generate_entropy(strength, internal_entropy, external_entropy) - expected_mnemonic = Mnemonic('english').to_mnemonic(entropy) + expected_mnemonic = Mnemonic("english").to_mnemonic(entropy) # Safety warning assert isinstance(ret, proto.ButtonRequest) @@ -69,7 +70,7 @@ class TestMsgResetDeviceT2(TrezorTest): words.extend(self.client.debug.read_reset_word().split()) # Compare that device generated proper mnemonic for given entropies - assert ' '.join(words) == expected_mnemonic + assert " ".join(words) == expected_mnemonic # Confirm the mnemonic self.client.debug.press_yes() @@ -99,24 +100,26 @@ class TestMsgResetDeviceT2(TrezorTest): def test_reset_device_pin(self): # PIN, passphrase, display random - external_entropy = b'zlutoucky kun upel divoke ody' * 2 + external_entropy = b"zlutoucky kun upel divoke ody" * 2 strength = 128 - ret = self.client.call_raw(proto.ResetDevice( - display_random=True, - strength=strength, - passphrase_protection=True, - pin_protection=True, - label='test' - )) + ret = self.client.call_raw( + proto.ResetDevice( + display_random=True, + strength=strength, + passphrase_protection=True, + pin_protection=True, + label="test", + ) + ) # Enter PIN for first time assert isinstance(ret, proto.ButtonRequest) - self.client.debug.input('654') + self.client.debug.input("654") ret = self.client.call_raw(proto.ButtonAck()) # Enter PIN for second time assert isinstance(ret, proto.ButtonRequest) - self.client.debug.input('654') + self.client.debug.input("654") ret = self.client.call_raw(proto.ButtonAck()) # Confirm entropy @@ -131,7 +134,7 @@ class TestMsgResetDeviceT2(TrezorTest): # Generate mnemonic locally entropy = generate_entropy(strength, internal_entropy, external_entropy) - expected_mnemonic = Mnemonic('english').to_mnemonic(entropy) + expected_mnemonic = Mnemonic("english").to_mnemonic(entropy) # Safety warning assert isinstance(ret, proto.ButtonRequest) @@ -153,7 +156,7 @@ class TestMsgResetDeviceT2(TrezorTest): words.extend(self.client.debug.read_reset_word().split()) # Compare that device generated proper mnemonic for given entropies - assert ' '.join(words) == expected_mnemonic + assert " ".join(words) == expected_mnemonic # Confirm the mnemonic self.client.debug.press_yes() @@ -183,20 +186,18 @@ class TestMsgResetDeviceT2(TrezorTest): def test_failed_pin(self): # external_entropy = b'zlutoucky kun upel divoke ody' * 2 strength = 128 - ret = self.client.call_raw(proto.ResetDevice( - strength=strength, - pin_protection=True, - label='test' - )) + ret = self.client.call_raw( + proto.ResetDevice(strength=strength, pin_protection=True, label="test") + ) # Enter PIN for first time assert isinstance(ret, proto.ButtonRequest) - self.client.debug.input('654') + self.client.debug.input("654") ret = self.client.call_raw(proto.ButtonAck()) # Enter PIN for second time assert isinstance(ret, proto.ButtonRequest) - self.client.debug.input('456') + self.client.debug.input("456") ret = self.client.call_raw(proto.ButtonAck()) assert isinstance(ret, proto.ButtonRequest) @@ -204,4 +205,4 @@ class TestMsgResetDeviceT2(TrezorTest): def test_already_initialized(self): self.setup_mnemonic_nopin_nopassphrase() with pytest.raises(Exception): - device.reset(self.client, False, 128, True, True, 'label', 'english') + device.reset(self.client, False, 128, True, True, "label", "english") diff --git a/trezorlib/tests/device_tests/test_msg_ripple_get_address.py b/trezorlib/tests/device_tests/test_msg_ripple_get_address.py index d4fabe0144..568e3fef52 100644 --- a/trezorlib/tests/device_tests/test_msg_ripple_get_address.py +++ b/trezorlib/tests/device_tests/test_msg_ripple_get_address.py @@ -16,39 +16,40 @@ import pytest -from .common import TrezorTest -from .conftest import TREZOR_VERSION +from trezorlib import debuglink from trezorlib.ripple import get_address from trezorlib.tools import parse_path -from trezorlib import debuglink + +from .common import TrezorTest +from .conftest import TREZOR_VERSION @pytest.mark.ripple @pytest.mark.skip_t1 # T1 support is not planned @pytest.mark.xfail(TREZOR_VERSION == 2, reason="T2 support is not yet finished") class TestMsgRippleGetAddress(TrezorTest): - def test_ripple_get_address(self): # data from https://iancoleman.io/bip39/#english self.setup_mnemonic_allallall() address = get_address(self.client, parse_path("m/44'/144'/0'/0/0")) - assert address == 'rNaqKtKrMSwpwZSzRckPf7S96DkimjkF4H' + assert address == "rNaqKtKrMSwpwZSzRckPf7S96DkimjkF4H" address = get_address(self.client, parse_path("m/44'/144'/0'/0/1")) - assert address == 'rBKz5MC2iXdoS3XgnNSYmF69K1Yo4NS3Ws' + assert address == "rBKz5MC2iXdoS3XgnNSYmF69K1Yo4NS3Ws" address = get_address(self.client, parse_path("m/44'/144'/1'/0/0")) - assert address == 'rJX2KwzaLJDyFhhtXKi3htaLfaUH2tptEX' + assert address == "rJX2KwzaLJDyFhhtXKi3htaLfaUH2tptEX" 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='', + 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') + label="test", + language="english", + ) address = get_address(self.client, parse_path("m/44'/144'/0'/0/0")) - assert address == 'r4ocGE47gm4G4LkA9mriVHQqzpMLBTgnTY' + assert address == "r4ocGE47gm4G4LkA9mriVHQqzpMLBTgnTY" address = get_address(self.client, parse_path("m/44'/144'/0'/0/1")) - assert address == 'rUt9ULSrUvfCmke8HTFU1szbmFpWzVbBXW' + assert address == "rUt9ULSrUvfCmke8HTFU1szbmFpWzVbBXW" diff --git a/trezorlib/tests/device_tests/test_msg_ripple_sign_tx.py b/trezorlib/tests/device_tests/test_msg_ripple_sign_tx.py index ce04eb34e5..1555d6405b 100644 --- a/trezorlib/tests/device_tests/test_msg_ripple_sign_tx.py +++ b/trezorlib/tests/device_tests/test_msg_ripple_sign_tx.py @@ -14,72 +14,94 @@ # You should have received a copy of the License along with this library. # If not, see . +from binascii import unhexlify + import pytest +from trezorlib import messages, ripple +from trezorlib.tools import CallException, parse_path + from .common import TrezorTest from .conftest import TREZOR_VERSION -from binascii import unhexlify -from trezorlib import messages -from trezorlib import ripple -from trezorlib.tools import parse_path, CallException @pytest.mark.ripple @pytest.mark.skip_t1 # T1 support is not planned @pytest.mark.xfail(TREZOR_VERSION == 2, reason="T2 support is not yet finished") class TestMsgRippleSignTx(TrezorTest): - def test_ripple_sign_simple_tx(self): self.setup_mnemonic_allallall() - msg = ripple.create_sign_tx_msg({ - "TransactionType": "Payment", - "Destination": "rBKz5MC2iXdoS3XgnNSYmF69K1Yo4NS3Ws", - "Amount": 100000000, - "Flags": 0x80000000, - "Fee": 100000, - "Sequence": 25, - }) + msg = ripple.create_sign_tx_msg( + { + "TransactionType": "Payment", + "Destination": "rBKz5MC2iXdoS3XgnNSYmF69K1Yo4NS3Ws", + "Amount": 100000000, + "Flags": 0x80000000, + "Fee": 100000, + "Sequence": 25, + } + ) resp = ripple.sign_tx(self.client, parse_path("m/44'/144'/0'/0/0"), msg) - assert resp.signature == unhexlify('3045022100e243ef623675eeeb95965c35c3e06d63a9fc68bb37e17dc87af9c0af83ec057e02206ca8aa5eaab8396397aef6d38d25710441faf7c79d292ee1d627df15ad9346c0') - assert resp.serialized_tx == unhexlify('12000022800000002400000019614000000005f5e1006840000000000186a0732102131facd1eab748d6cddc492f54b04e8c35658894f4add2232ebc5afe7521dbe474473045022100e243ef623675eeeb95965c35c3e06d63a9fc68bb37e17dc87af9c0af83ec057e02206ca8aa5eaab8396397aef6d38d25710441faf7c79d292ee1d627df15ad9346c081148fb40e1ffa5d557ce9851a535af94965e0dd098883147148ebebf7304ccdf1676fefcf9734cf1e780826') + assert resp.signature == unhexlify( + "3045022100e243ef623675eeeb95965c35c3e06d63a9fc68bb37e17dc87af9c0af83ec057e02206ca8aa5eaab8396397aef6d38d25710441faf7c79d292ee1d627df15ad9346c0" + ) + assert resp.serialized_tx == unhexlify( + "12000022800000002400000019614000000005f5e1006840000000000186a0732102131facd1eab748d6cddc492f54b04e8c35658894f4add2232ebc5afe7521dbe474473045022100e243ef623675eeeb95965c35c3e06d63a9fc68bb37e17dc87af9c0af83ec057e02206ca8aa5eaab8396397aef6d38d25710441faf7c79d292ee1d627df15ad9346c081148fb40e1ffa5d557ce9851a535af94965e0dd098883147148ebebf7304ccdf1676fefcf9734cf1e780826" + ) - msg = ripple.create_sign_tx_msg({ - "TransactionType": "Payment", - "Destination": "rNaqKtKrMSwpwZSzRckPf7S96DkimjkF4H", - "Amount": 1, - "Fee": 10, - "Sequence": 1, - }) + msg = ripple.create_sign_tx_msg( + { + "TransactionType": "Payment", + "Destination": "rNaqKtKrMSwpwZSzRckPf7S96DkimjkF4H", + "Amount": 1, + "Fee": 10, + "Sequence": 1, + } + ) resp = ripple.sign_tx(self.client, parse_path("m/44'/144'/0'/0/2"), msg) - assert resp.signature == unhexlify('3044022069900e6e578997fad5189981b74b16badc7ba8b9f1052694033fa2779113ddc002206c8006ada310edf099fb22c0c12073550c8fc73247b236a974c5f1144831dd5f') - assert resp.serialized_tx == unhexlify('1200002280000000240000000161400000000000000168400000000000000a732103dbed1e77cb91a005e2ec71afbccce5444c9be58276665a3859040f692de8fed274463044022069900e6e578997fad5189981b74b16badc7ba8b9f1052694033fa2779113ddc002206c8006ada310edf099fb22c0c12073550c8fc73247b236a974c5f1144831dd5f8114bdf86f3ae715ba346b7772ea0e133f48828b766483148fb40e1ffa5d557ce9851a535af94965e0dd0988') + assert resp.signature == unhexlify( + "3044022069900e6e578997fad5189981b74b16badc7ba8b9f1052694033fa2779113ddc002206c8006ada310edf099fb22c0c12073550c8fc73247b236a974c5f1144831dd5f" + ) + assert resp.serialized_tx == unhexlify( + "1200002280000000240000000161400000000000000168400000000000000a732103dbed1e77cb91a005e2ec71afbccce5444c9be58276665a3859040f692de8fed274463044022069900e6e578997fad5189981b74b16badc7ba8b9f1052694033fa2779113ddc002206c8006ada310edf099fb22c0c12073550c8fc73247b236a974c5f1144831dd5f8114bdf86f3ae715ba346b7772ea0e133f48828b766483148fb40e1ffa5d557ce9851a535af94965e0dd0988" + ) - msg = ripple.create_sign_tx_msg({ - "TransactionType": "Payment", - "Destination": "rNaqKtKrMSwpwZSzRckPf7S96DkimjkF4H", - "Amount": 100000009, - "Flags": 0, - "Fee": 100, - "Sequence": 100, - "LastLedgerSequence": 333111, - }) + msg = ripple.create_sign_tx_msg( + { + "TransactionType": "Payment", + "Destination": "rNaqKtKrMSwpwZSzRckPf7S96DkimjkF4H", + "Amount": 100000009, + "Flags": 0, + "Fee": 100, + "Sequence": 100, + "LastLedgerSequence": 333111, + } + ) resp = ripple.sign_tx(self.client, parse_path("m/44'/144'/0'/0/2"), msg) - assert resp.signature == unhexlify('30440220025a9cc2809527799e6ea5eb029488dc46c6632a8ca1ed7d3ca2d9211e80403a02202cfe8604e6c6d1d3c64246626cc1a1a9bd8a2163b969e561c6adda5dca8fc2a5') - assert resp.serialized_tx == unhexlify('12000022800000002400000064201b00051537614000000005f5e109684000000000000064732103dbed1e77cb91a005e2ec71afbccce5444c9be58276665a3859040f692de8fed2744630440220025a9cc2809527799e6ea5eb029488dc46c6632a8ca1ed7d3ca2d9211e80403a02202cfe8604e6c6d1d3c64246626cc1a1a9bd8a2163b969e561c6adda5dca8fc2a58114bdf86f3ae715ba346b7772ea0e133f48828b766483148fb40e1ffa5d557ce9851a535af94965e0dd0988') + assert resp.signature == unhexlify( + "30440220025a9cc2809527799e6ea5eb029488dc46c6632a8ca1ed7d3ca2d9211e80403a02202cfe8604e6c6d1d3c64246626cc1a1a9bd8a2163b969e561c6adda5dca8fc2a5" + ) + assert resp.serialized_tx == unhexlify( + "12000022800000002400000064201b00051537614000000005f5e109684000000000000064732103dbed1e77cb91a005e2ec71afbccce5444c9be58276665a3859040f692de8fed2744630440220025a9cc2809527799e6ea5eb029488dc46c6632a8ca1ed7d3ca2d9211e80403a02202cfe8604e6c6d1d3c64246626cc1a1a9bd8a2163b969e561c6adda5dca8fc2a58114bdf86f3ae715ba346b7772ea0e133f48828b766483148fb40e1ffa5d557ce9851a535af94965e0dd0988" + ) def test_ripple_sign_invalid_fee(self): self.setup_mnemonic_allallall() - msg = ripple.create_sign_tx_msg({ - "TransactionType": "Payment", - "Destination": "rNaqKtKrMSwpwZSzRckPf7S96DkimjkF4H", - "Amount": 1, - "Flags": 1, - "Fee": 1, - "Sequence": 1, - }) + msg = ripple.create_sign_tx_msg( + { + "TransactionType": "Payment", + "Destination": "rNaqKtKrMSwpwZSzRckPf7S96DkimjkF4H", + "Amount": 1, + "Flags": 1, + "Fee": 1, + "Sequence": 1, + } + ) with pytest.raises(CallException) as exc: ripple.sign_tx(self.client, parse_path("m/44'/144'/0'/0/2"), msg) assert exc.value.args[0] == messages.FailureType.ProcessError - assert exc.value.args[1].endswith('Fee must be in the range of 10 to 10,000 drops') + assert exc.value.args[1].endswith( + "Fee must be in the range of 10 to 10,000 drops" + ) diff --git a/trezorlib/tests/device_tests/test_msg_signidentity.py b/trezorlib/tests/device_tests/test_msg_signidentity.py index 0296775ac6..2bc4a0a8b1 100644 --- a/trezorlib/tests/device_tests/test_msg_signidentity.py +++ b/trezorlib/tests/device_tests/test_msg_signidentity.py @@ -17,75 +17,122 @@ import struct from binascii import hexlify, unhexlify -from .common import TrezorTest - -from trezorlib import messages as proto -from trezorlib import misc +from trezorlib import messages as proto, misc from trezorlib.tools import H_ +from .common import TrezorTest + def check_path(identity): from hashlib import sha256 + m = sha256() m.update(struct.pack("