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("