diff --git a/.github/actions/build-sim/action.yml b/.github/actions/build-sim/action.yml index ebc6c9897..841b7406f 100644 --- a/.github/actions/build-sim/action.yml +++ b/.github/actions/build-sim/action.yml @@ -22,7 +22,7 @@ runs: -o Acquire::https::Timeout=30 ) timeout 5m sudo apt-get "${apt_options[@]}" update - timeout 30m sudo apt-get "${apt_options[@]}" install -y gcc-arm-linux-gnueabihf libsdl2-image-dev libslirp-dev libpcsclite-dev ninja-build libltdl-dev + timeout 30m sudo apt-get "${apt_options[@]}" install -y cmake patchelf libpng-dev gcc-12 gcc-13 gcc-arm-linux-gnueabihf libsdl2-image-dev libslirp-dev libpcsclite-dev ninja-build libltdl-dev pip install poetry uv wget https://github.com/protocolbuffers/protobuf/releases/download/v22.0/protoc-22.0-linux-x86_64.zip sudo unzip protoc-22.0-linux-x86_64.zip -d /usr/local diff --git a/.github/actions/test-device/action.yml b/.github/actions/test-device/action.yml index 2152d1343..a18f5405f 100644 --- a/.github/actions/test-device/action.yml +++ b/.github/actions/test-device/action.yml @@ -25,6 +25,18 @@ runs: run: | cd test; poetry run ./run_tests.py --${{ matrix.device }} --interface=${{ matrix.test.interface }} --device-only; cd .. + # TEMPORARY ANTI-EXFIL: execute against the companion firmware/Core forks. + - name: Test interactive anti-exfil + shell: bash + run: | + case "${{ matrix.device }}" in + ledger) anti_exfil_flags=(--ledger-anti-exfil-core) ;; + trezor-1|trezor-t|coldcard-edge|jade|bitbox02) anti_exfil_flags=(--anti-exfil) ;; + *) exit 0 ;; + esac + cd test + poetry run ./run_tests.py --${{ matrix.device }} --device-only --interface=${{ matrix.test.interface }} "${anti_exfil_flags[@]}" + - if: failure() shell: bash run: | diff --git a/.github/actions/test-dist/action.yml b/.github/actions/test-dist/action.yml index a517c0bb0..a11e2899f 100644 --- a/.github/actions/test-dist/action.yml +++ b/.github/actions/test-dist/action.yml @@ -60,6 +60,24 @@ runs: run: | cd test; poetry run ./run_tests.py --${{ matrix.device }} --interface=bindist --device-only; cd .. + # TEMPORARY ANTI-EXFIL: execute against the companion firmware/Core forks. + - name: Test interactive anti-exfil + shell: bash + run: | + case "${{ matrix.device }}" in + ledger) anti_exfil_flags=(--ledger-anti-exfil-core) ;; + trezor-1|trezor-t|coldcard-edge|jade|bitbox02) anti_exfil_flags=(--anti-exfil) ;; + *) exit 0 ;; + esac + interface=cli + runner=(./run_tests.py) + if [[ "${{ matrix.test.script }}" == Bindist ]]; then + interface=bindist + runner=(poetry run ./run_tests.py) + fi + cd test + "${runner[@]}" --${{ matrix.device }} --device-only --interface=${interface} "${anti_exfil_flags[@]}" + - if: failure() shell: bash run: | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cb66eea51..8af5fd738 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,6 +13,7 @@ concurrency: group: ${{ github.event_name != 'pull_request' && github.run_id || github.ref }} cancel-in-progress: true +# TEMPORARY ANTI-EXFIL: retain the tested GCC 12/13 simulator build host. env: LC_ALL: 'C.UTF-8' LANG: 'C.UTF-8' @@ -21,7 +22,7 @@ env: jobs: non-device-tests: name: Non-device tests - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 container: python:3.12 steps: - uses: actions/checkout@v7 @@ -36,7 +37,7 @@ jobs: lint: name: lint - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 container: python:3.12 steps: - uses: actions/checkout@v7 @@ -51,7 +52,7 @@ jobs: wine-builder: name: Wine builder - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v7 @@ -75,7 +76,7 @@ jobs: dist-builder: name: Dist builder - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v7 @@ -114,7 +115,7 @@ jobs: with: sim: trezor include: ${{ needs.prepare-sim-matrices.outputs.trezor }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 sim-builder-coldcard: name: Coldcard sim builder @@ -123,7 +124,7 @@ jobs: with: sim: coldcard include: ${{ needs.prepare-sim-matrices.outputs.coldcard }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 sim-builder-coldcard-edge: name: Coldcard Edge sim builder @@ -132,7 +133,7 @@ jobs: with: sim: coldcard-edge include: ${{ needs.prepare-sim-matrices.outputs.coldcard_edge }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 sim-builder-bitbox: name: Bitbox sim builder @@ -141,7 +142,7 @@ jobs: with: sim: bitbox include: ${{ needs.prepare-sim-matrices.outputs.bitbox }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 sim-builder-jade: name: Jade sim builder @@ -150,7 +151,7 @@ jobs: with: sim: jade include: ${{ needs.prepare-sim-matrices.outputs.jade }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 sim-builder-ledger: name: Ledger sim builder @@ -159,7 +160,7 @@ jobs: with: sim: ledger include: ${{ needs.prepare-sim-matrices.outputs.ledger }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 sim-builder-keepkey: name: Keepkey sim builder @@ -168,23 +169,23 @@ jobs: with: sim: keepkey include: ${{ needs.prepare-sim-matrices.outputs.keepkey }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 ledger-legacy-app-builder: name: Ledger Bitcoin Legacy App builder uses: ./.github/workflows/ledger-legacy-app-builder.yml with: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 ledger-app-builder: name: Ledger Bitcoin App builder uses: ./.github/workflows/ledger-app-builder.yml with: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 bitcoind-builder: name: bitcoind builder - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v7 - uses: ./.github/actions/build-bitcoind @@ -194,42 +195,42 @@ jobs: needs: [sim-builder-trezor, bitcoind-builder, dist-builder] with: device: trezor-1 - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 test-trezor-t: uses: ./.github/workflows/device-test.yml needs: [sim-builder-trezor, bitcoind-builder, dist-builder] with: device: trezor-t - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 test-ledger-legacy: uses: ./.github/workflows/device-test.yml needs: [sim-builder-ledger, ledger-legacy-app-builder, bitcoind-builder, dist-builder] with: device: ledger-legacy - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 test-ledger: uses: ./.github/workflows/device-test.yml needs: [sim-builder-ledger, ledger-app-builder, bitcoind-builder, dist-builder] with: device: ledger - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 test-coldcard: uses: ./.github/workflows/device-test.yml needs: [sim-builder-coldcard, bitcoind-builder, dist-builder] with: device: coldcard - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 test-coldcard-edge: uses: ./.github/workflows/device-test.yml needs: [sim-builder-coldcard-edge, bitcoind-builder, dist-builder] with: device: coldcard-edge - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 python_versions: '["3.14"]' test-bitbox01: @@ -237,25 +238,25 @@ jobs: needs: [sim-builder-bitbox, bitcoind-builder, dist-builder] with: device: bitbox01 - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 test-bitbox02: uses: ./.github/workflows/device-test.yml needs: [sim-builder-bitbox, bitcoind-builder, dist-builder] with: device: bitbox02 - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 test-jade: uses: ./.github/workflows/device-test.yml needs: [sim-builder-jade, bitcoind-builder, dist-builder] with: device: jade - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 test-keepkey: uses: ./.github/workflows/device-test.yml needs: [sim-builder-keepkey, bitcoind-builder, dist-builder] with: device: keepkey - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 diff --git a/.github/workflows/ledger-app-builder.yml b/.github/workflows/ledger-app-builder.yml index d2cab7345..b3897988b 100644 --- a/.github/workflows/ledger-app-builder.yml +++ b/.github/workflows/ledger-app-builder.yml @@ -11,12 +11,12 @@ jobs: build: name: Build Bitcoin App runs-on: ${{ inputs.runs-on }} - # app-bitcoin v2.5.0 targets SDK v26.5.0, provided by builder 5.3.17. + # app-bitcoin develop (2.5.1) is validated with SDK v26.5.0 in builder 5.3.17. container: ghcr.io/ledgerhq/ledger-app-builder/ledger-app-builder:5.3.17 steps: - run: | - # Pin to v2.5.0 - git clone --branch 2.5.0 --depth 1 https://github.com/LedgerHQ/app-bitcoin.git + # TEMPORARY ANTI-EXFIL: companion fork branch; restore upstream develop after integration. + git clone --branch 2026/10/taproot-anti-exfil https://github.com/Sjors/ledger-bitcoin-app.git app-bitcoin cd app-bitcoin make DEBUG=1 COIN=bitcoin_testnet BOLOS_SDK=$NANOX_SDK - uses: actions/upload-artifact@v7 diff --git a/.github/workflows/type-check.yml b/.github/workflows/type-check.yml index 7894fca82..a3a3cbf1c 100644 --- a/.github/workflows/type-check.yml +++ b/.github/workflows/type-check.yml @@ -23,6 +23,7 @@ jobs: hwilib/_bech32.py hwilib/_cli.py hwilib/commands.py + hwilib/anti_exfil.py hwilib/common.py hwilib/descriptor.py hwilib/devices/bitbox02.py diff --git a/docs/usage/anti-exfil.rst b/docs/usage/anti-exfil.rst new file mode 100644 index 000000000..d0b185245 --- /dev/null +++ b/docs/usage/anti-exfil.rst @@ -0,0 +1,112 @@ +Interactive Taproot anti-exfil +============================= + +This experimental interface implements the draft single-signer BIP340 anti-exfil +protocol. It requires matching device firmware. It supports Taproot key-path +inputs with ``SIGHASH_DEFAULT`` or ``SIGHASH_ALL``; it does not extend MuSig2, +FROST, or script-path signing. + +The host runs ``signtx`` twice. Each requested PSBT input carries proprietary +keys encoded as ``fc 02 61 65 ``. The identifier is ``ae``; +the output key is the 32-byte x-only Taproot output key, rather than its internal +key. Subtype 0 holds a 32-byte host commitment, subtype 1 a compressed 33-byte +device nonce, and subtype 2 the host's 32-byte entropy scalar. These experimental +keys are subject to change during specification review. + +In the first call the input contains only the host commitment. The device returns +its original nonce and no signature. The host checks and retains that response, +adds its entropy, and makes the second call. HWI verifies that the signature uses +the committed device nonce plus the host contribution and verifies the BIP340 +signature against the original transaction. A missing proof, early signature, +changed transaction, or unsupported device fails instead of returning an +unprotected result. The presence of these fields is an explicit protection +request; there is no fallback to ordinary signing. + +Successful protected replies from ``hwilib.commands.signtx`` and the CLI are +private host-local protocol messages. These boundaries validate the raw device +response, then copy only validated nonce receipts or verified target signatures +into the original host request. Original caller metadata and the anti-exfil +transcript are retained; unrelated metadata added, changed or removed by the +device is not forwarded. This handles device-controlled bytes from native PSBT +transports such as Jade and Coldcard; it assumes the application and HWI are +trusted parts of the same host. + +The trusted host must retain its original state and verify the device +contributions. A calling application may delegate these checks to the checked +``commands.signtx``/CLI boundary. Core additionally performs its own verification; +Core and HWI remain trusted components of the same host. Before exporting a +completed PSBT, the host must strip the anti-exfil fields and copy verified +signatures into its pristine PSBT. Low-level +``HardwareWalletClient.sign_tx`` and SDK calls expose transport results; direct +callers must perform ``anti_exfil.requests`` / ``anti_exfil.check_response`` and +the same original-PSBT reconstruction themselves. + +Generate host entropy with a cryptographically secure random generator and +reject zero or values at or above the secp256k1 group order. Never send the entropy +before receiving the device nonce. Keep the transcript private and retain the +same entropy and device commitment on retries. Do not automatically retry an +aborted exchange with fresh entropy. An ordinary ``signtx`` request without these +fields retains its existing behavior. + +Protected signing suppresses SDK/device logs only in the active signing context +and returns fixed device-error messages. Cancellation, unavailable-action and +connection categories remain distinguishable. Logs from unrelated application +threads keep their normal behavior. This also protects debug tracebacks from +chained SDK errors containing the nonce transcript. + +Library callers that construct and close clients themselves can include that +whole lifetime in ``hwilib.anti_exfil.private_operation()``. The ``signtx`` +command guards its device call; a surrounding scope also covers reconnect and +close diagnostics from a previous signing round. The CLI automatically covers +client initialization, signing and close when it recognizes an explicit +anti-exfil PSBT. Device errors use controlled messages throughout that lifetime, +including when ``--debug`` is enabled. A cleanup failure returns an error without +also returning the signing transcript. + +The first firmware integration uses the Ledger Bitcoin app with its draft +anti-exfil extension. Its round-1 nonce is transported with yield tag +``0xfffffffd``, followed by the input index, compressed nonce, and x-only key. +Stock firmware is not claimed to support this extension. + +To exercise matching firmware in Speculos, run from ``test/``:: + + python run_tests.py --ledger-anti-exfil --interface=library \ + --ledger-path=/absolute/path/to/speculos.py \ + --bitcoind=/absolute/path/to/bitcoind + +The opt-in test covers DEFAULT and ALL, deterministic commitment retries, +firmware rejection of mismatched openings, host verification, mempool acceptance, +broadcast, and confirmation. The normal non-device test suite includes shared +cryptographic vectors and rejection tests for malformed or malicious responses. + +To include the full Bitcoin Core host -> HWI subprocess -> Ledger path, add +``--ledger-anti-exfil-core`` and point ``--bitcoind`` at the matching Core build +with ``-signerantiexfil`` support. The test starts an independent node with that +setting enabled, creates an external-signer wallet, exercises +``walletprocesspsbt`` and ``send``, checks transcript removal, and confirms the +broadcast transaction. + +Trezor One and T firmware with the provisional ``BitcoinAntiExfil`` capability +uses the same PSBT transcript. The bridge carries it in optional Bitcoin input +fields and returns commitment receipts separately from signatures. The bridge +rejects protection requests before signing when firmware lacks that capability. + +Run either matching emulator's interactive suite using ``--anti-exfil`` with +``--trezor-1`` or ``--trezor-t`` and its corresponding path option. Run the +ordinary device suite separately without ``--anti-exfil``; it checks ordinary +signing as well as rejection on devices without the capability. + +The same ``--anti-exfil`` option selects the Jade or Coldcard Edge interactive +suite with ``--jade`` or ``--coldcard-edge`` and its corresponding path option. +Jade uses its native PSBT command and advertises ``JADE_TAPROOT_ANTI_EXFIL``. +Coldcard Edge carries the fields through its existing PSBT upload protocol and +requires the matching native ``libngu`` extension. Ordinary Coldcard firmware, +BitBox01, KeepKey, and the legacy Ledger app reject protection requests before +signing. Full device suites include this unsupported-device check. + +BitBox02's matching firmware and bundled SDK use an explicit invocation-wide +round and dedicated per-input Taproot fields in the streaming transaction API. +The driver and raw SDK require the advertised capability and do not reuse the +ECDSA anti-klepto channel for Schnorr. ``--bitbox02 --anti-exfil`` selects its +interactive suite. Released firmware is tested to reject the request before +starting a signing exchange. diff --git a/docs/usage/index.rst b/docs/usage/index.rst index 85a3f6caa..8b1394285 100644 --- a/docs/usage/index.rst +++ b/docs/usage/index.rst @@ -6,4 +6,5 @@ Usage installation cli-usage + anti-exfil api-usage diff --git a/hwilib/_cli.py b/hwilib/_cli.py index 52077ac08..70752612c 100644 --- a/hwilib/_cli.py +++ b/hwilib/_cli.py @@ -35,7 +35,8 @@ UNKNOWN_ERROR, ) from .hwwclient import HardwareWalletClient -from . import __version__ +from . import __version__, anti_exfil +from .psbt import PSBT import argparse import getpass @@ -261,6 +262,30 @@ def get_parser() -> HWIArgumentParser: return parser +def _protected_signtx(args: argparse.Namespace) -> Dict[str, Any]: + """Protect reconnect and cleanup diagnostics as well as the signing call.""" + result: Dict[str, Any] = {} + with handle_errors(result=result, debug=args.debug): + with anti_exfil.private_operation(): + if args.fingerprint or (args.device_type and not args.device_path): + client = find_device(args.password, args.device_type, args.fingerprint, args.expert, args.chain, args.allow_emulators) + if client is None: + return {"error": "Could not find device with specified fingerprint or type", "code": DEVICE_CONN_ERROR} + elif args.device_type and args.device_path: + client = get_client(args.device_type, args.device_path, args.password, args.expert, args.chain) + else: + return {"error": "You must specify a device type or fingerprint for all commands except enumerate", "code": NO_DEVICE_TYPE} + if client is None: + return {"error": "Unable to communicate with device", "code": UNKNOWN_ERROR} + try: + response = args.func(args, client) + finally: + client.close() + # Cleanup failures must not return an otherwise complete transcript. + result.update(response) + return result + + def process_commands(cli_args: List[str]) -> Any: parser = get_parser() @@ -305,6 +330,17 @@ def process_commands(cli_args: List[str]) -> Any: result = args.func(args) return result + if command == "signtx": + candidate = PSBT() + try: + candidate.deserialize(args.psbt) + except Exception: + # Let the ordinary path retain its existing parser diagnostics. + pass + else: + if anti_exfil.has_fields(candidate): + return _protected_signtx(args) + # Auto detect if we are using fingerprint or type to identify device if args.fingerprint or (args.device_type and not args.device_path): client = find_device(args.password, args.device_type, args.fingerprint, args.expert, args.chain, args.allow_emulators) diff --git a/hwilib/anti_exfil.py b/hwilib/anti_exfil.py new file mode 100644 index 000000000..54da9cb3f --- /dev/null +++ b/hwilib/anti_exfil.py @@ -0,0 +1,340 @@ +# Copyright (c) 2026 The HWI developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. + +"""Host verification for the draft interactive BIP340 anti-exfil protocol. + +Only single-signer Taproot key-path signatures with DEFAULT or ALL are supported. +The proprietary PSBT keys are experimental pending allocation by the BIP process. +All curve operations here process public data; signing belongs on the device. +""" + +from dataclasses import dataclass +from contextlib import contextmanager +from contextvars import ContextVar +from io import BytesIO +import hashlib +import logging +import struct +from typing import Dict, Iterator, List, Optional, Set, Union + +from ._serialize import deser_compact_size, ser_string +from .errors import ActionCanceledError, BadArgumentError, DeviceBusyError, DeviceConnectionError, DeviceFailureError, HWWError, UnavailableActionError +from .key import G, Point, n, p, point_add, point_mul +from .psbt import PSBT +from .tx import CTxOut + + +PREFIX = b"\xfc\x02ae" +HOST_COMMITMENT = 0 +SIGNER_NONCE = 1 +HOST_ENTROPY = 2 +HOST_TAG = "BIP-EXFIL/host" + + +_PRIVATE_LOGGING: ContextVar[bool] = ContextVar("hwi_anti_exfil_private_logging", default=False) + + +class _PrivateOperationFilter(logging.Filter): + def filter(self, record: logging.LogRecord) -> bool: + # Context-local state preserves records from unrelated threads/tasks. + # QueueHandlers are filtered before private records enter their queues. + return not _PRIVATE_LOGGING.get() + + +def _private_error(error: Exception) -> HWWError: + if isinstance(error, ActionCanceledError): + return ActionCanceledError("Anti-exfil signing canceled") + if isinstance(error, UnavailableActionError): + return UnavailableActionError("This device does not support interactive Taproot anti-exfil") + if isinstance(error, DeviceConnectionError): + return DeviceConnectionError("Anti-exfil device connection failed") + if isinstance(error, DeviceBusyError): + return DeviceBusyError("Anti-exfil device is busy") + if isinstance(error, BadArgumentError): + return BadArgumentError("Anti-exfil signer rejected the request") + return DeviceFailureError("Anti-exfil device operation failed") + + +@contextmanager +def private_operation(enabled: bool = True) -> Iterator[None]: + """Keep device diagnostics private in this protected signing context. + + SDK errors and transport/device logs can contain the complete transcript. + Filter the currently configured loggers/handlers, including lastResort, + without changing logging levels or muting unrelated application threads. + Library callers can include client construction and close in this scope. + """ + if not enabled: + yield + return + token = _PRIVATE_LOGGING.set(True) + private_filter = _PrivateOperationFilter() + loggers = [logging.getLogger()] + [ + logger for logger in list(logging.Logger.manager.loggerDict.values()) + if isinstance(logger, logging.Logger) + ] + targets: List[Union[logging.Logger, logging.Handler]] = list(loggers) + for logger in loggers: + targets.extend(logger.handlers) + if logging.lastResort is not None: + targets.append(logging.lastResort) + installed: List[Union[logging.Logger, logging.Handler]] = [] + seen: Set[int] = set() + try: + for target in targets: + if id(target) in seen: + continue + seen.add(id(target)) + target.addFilter(private_filter) + installed.append(target) + yield + except Exception as error: + # Suppress chained SDK errors too: --debug prints exception tracebacks. + raise _private_error(error) from None + finally: + for target in installed: + target.removeFilter(private_filter) + _PRIVATE_LOGGING.reset(token) + + +def has_fields(psbt: PSBT) -> bool: + """Recognize explicit protection before opening a CLI device connection.""" + mappings = [psbt.unknown] + [item.unknown for item in psbt.inputs] + [item.unknown for item in psbt.outputs] + return any(is_field(field) for mapping in mappings for field in mapping) + + +def tagged_hash(tag: str, data: bytes) -> bytes: + tag_hash = hashlib.sha256(tag.encode("ascii")).digest() + return hashlib.sha256(tag_hash + tag_hash + data).digest() + + +def is_field(encoded_key: bytes) -> bool: + """Recognize the ae namespace even when its CompactSize encoding is invalid.""" + stream = BytesIO(encoded_key) + try: + return deser_compact_size(stream) == 0xfc and deser_compact_size(stream) == 2 and stream.read(2) == b"ae" + except struct.error: + return False + + +def key(subtype: int, pubkey: bytes) -> bytes: + if subtype not in (HOST_COMMITMENT, SIGNER_NONCE, HOST_ENTROPY) or len(pubkey) != 32: + raise ValueError("Invalid anti-exfil key") + return PREFIX + bytes([subtype]) + pubkey + + +def host_commit(entropy: bytes) -> bytes: + if len(entropy) != 32 or not 0 < int.from_bytes(entropy, "big") < n: + raise ValueError("Anti-exfil entropy must be a nonzero scalar") + return tagged_hash(HOST_TAG, entropy) + + +def parse_point(encoded: bytes) -> Point: + if len(encoded) != 33 or encoded[0] not in (2, 3): + raise ValueError("Invalid compressed anti-exfil nonce") + x = int.from_bytes(encoded[1:], "big") + if x >= p: + raise ValueError("Anti-exfil nonce coordinate out of range") + y = pow((x ** 3 + 7) % p, (p + 1) // 4, p) + if y * y % p != (x ** 3 + 7) % p: + raise ValueError("Anti-exfil nonce is not on the curve") + if y & 1 != encoded[0] & 1: + y = p - y + return (x, y) + + +def verify_signature(pubkey: bytes, msg: bytes, signature: bytes) -> bool: + if len(pubkey) != 32 or len(msg) != 32 or len(signature) != 64: + return False + try: + point = parse_point(b"\x02" + pubkey) + except ValueError: + return False + r = int.from_bytes(signature[:32], "big") + s = int.from_bytes(signature[32:], "big") + if r >= p or s >= n: + return False + challenge = int.from_bytes(tagged_hash("BIP0340/challenge", signature[:32] + pubkey + msg), "big") % n + nonce = point_add(point_mul(G, s), point_mul(point, n - challenge)) + return nonce is not None and nonce[1] & 1 == 0 and nonce[0] == r + + +def host_verify(pubkey: bytes, msg: bytes, signature: bytes, entropy: bytes, signer_nonce: bytes) -> bool: + """Verify both the ordinary signature and the committed nonce relation.""" + try: + host_commit(entropy) + expected_nonce = point_add(parse_point(signer_nonce), point_mul(G, int.from_bytes(entropy, "big"))) + except ValueError: + return False + return ( + expected_nonce is not None + and len(signature) == 64 + and signature[:32] == expected_nonce[0].to_bytes(32, "big") + and verify_signature(pubkey, msg, signature) + ) + + +def get_utxo(psbt: PSBT, index: int) -> CTxOut: + psbt_in = psbt.inputs[index] + if psbt_in.non_witness_utxo is not None: + previous = psbt_in.non_witness_utxo + previous.rehash() + if previous.hash != psbt_in.prev_txid or psbt_in.prev_out is None or psbt_in.prev_out >= len(previous.vout): + raise BadArgumentError("Anti-exfil input has an incorrect previous transaction") + utxo = previous.vout[psbt_in.prev_out] + if psbt_in.witness_utxo is not None and psbt_in.witness_utxo.serialize() != utxo.serialize(): + raise BadArgumentError("Anti-exfil input UTXOs disagree") + return utxo + if psbt_in.witness_utxo is None: + raise BadArgumentError("Anti-exfil requires UTXO data for every input") + return psbt_in.witness_utxo + + +def signature_hash(psbt: PSBT, index: int, hash_type: int) -> bytes: + """BIP341 key-path signature message, without annex or ANYONECANPAY.""" + if hash_type not in (0, 1): + raise BadArgumentError("Anti-exfil only supports DEFAULT and ALL") + tx = psbt.get_unsigned_tx() + utxos = [get_utxo(psbt, i) for i in range(len(tx.vin))] + + def sha(data: bytes) -> bytes: + return hashlib.sha256(data).digest() + msg = bytes([0, hash_type]) + struct.pack(" Dict[int, Request]: + """Parse and validate explicit anti-exfil requests before device access.""" + if any(is_field(field) for mapping in [psbt.unknown] + [output.unknown for output in psbt.outputs] for field in mapping): + raise BadArgumentError("Anti-exfil fields are only allowed in PSBT input maps") + result = {} + round_number = None + for index, psbt_in in enumerate(psbt.inputs): + fields = {} + pubkey = None + for encoded_key, value in psbt_in.unknown.items(): + if not is_field(encoded_key): + continue + if not encoded_key.startswith(PREFIX) or len(encoded_key) != 37 or encoded_key[4] not in (0, 1, 2): + raise BadArgumentError("Malformed anti-exfil PSBT field") + if pubkey is not None and pubkey != encoded_key[5:]: + raise BadArgumentError("Only one anti-exfil signing key per input is supported") + pubkey = encoded_key[5:] + fields[encoded_key[4]] = value + if not fields: + continue + if HOST_COMMITMENT not in fields or len(fields[HOST_COMMITMENT]) != 32: + raise BadArgumentError("Anti-exfil host commitment is missing or invalid") + if psbt_in.tap_key_sig or psbt_in.tap_script_sigs or psbt_in.final_script_sig or not psbt_in.final_script_witness.is_null(): + raise BadArgumentError("Anti-exfil input already contains signatures or finalized data") + assert pubkey is not None + utxo = get_utxo(psbt, index) + if utxo.scriptPubKey != b"\x51\x20" + pubkey: + raise BadArgumentError("Anti-exfil key must be the Taproot output key") + try: + parse_point(b"\x02" + pubkey) + except ValueError as error: + raise BadArgumentError(str(error)) + signer_nonce = fields.get(SIGNER_NONCE) + entropy = fields.get(HOST_ENTROPY) + if entropy is None and signer_nonce is not None: + raise BadArgumentError("Anti-exfil nonce requires the host reveal") + current_round = 2 if entropy is not None else 1 + if round_number is not None and current_round != round_number: + raise BadArgumentError("Anti-exfil rounds cannot be mixed in one request") + round_number = current_round + try: + if signer_nonce is not None: + parse_point(signer_nonce) + if entropy is not None and (signer_nonce is None or host_commit(entropy) != fields[HOST_COMMITMENT]): + raise ValueError("Anti-exfil entropy does not open the host commitment") + except ValueError as error: + raise BadArgumentError(str(error)) + hash_type = psbt_in.sighash if psbt_in.sighash is not None else 0 + result[index] = Request(pubkey, fields[HOST_COMMITMENT], signer_nonce, entropy, hash_type, signature_hash(psbt, index, hash_type)) + return result + + +def check_response(original: PSBT, response: PSBT, expected: Dict[int, Request]) -> None: + """Fail closed on unsupported firmware or a changed anti-exfil transcript.""" + if not expected: + return + if any(is_field(field) for mapping in [response.unknown] + [output.unknown for output in response.outputs] for field in mapping): + raise DeviceFailureError("Anti-exfil signer returned a field outside its input map") + if original.version != response.version or original.get_unsigned_tx().serialize_without_witness() != response.get_unsigned_tx().serialize_without_witness(): + raise DeviceFailureError("Anti-exfil signer changed the transaction") + first_round = next(iter(expected.values())).entropy is None + if first_round and any( + after.tap_key_sig != before.tap_key_sig + or after.tap_script_sigs != before.tap_script_sigs + or after.partial_sigs != before.partial_sigs + or after.final_script_sig != before.final_script_sig + or after.final_script_witness.serialize() != before.final_script_witness.serialize() + for before, after in zip(original.inputs, response.inputs) + ): + raise DeviceFailureError("Anti-exfil commitment round returned signatures") + for index, (before, after) in enumerate(zip(original.inputs, response.inputs)): + for encoded_key in after.unknown: + if not is_field(encoded_key): + continue + target = expected.get(index) + if target is None or not encoded_key.startswith(PREFIX) or len(encoded_key) != 37 or encoded_key[4] not in (0, 1, 2) or encoded_key[5:] != target.pubkey: + raise DeviceFailureError("Anti-exfil signer returned an unexpected transcript field") + try: + if get_utxo(original, index).serialize() != get_utxo(response, index).serialize(): + raise DeviceFailureError("Anti-exfil signer changed input UTXO data") + except BadArgumentError as error: + raise DeviceFailureError(str(error)) + if after.sighash != before.sighash: + raise DeviceFailureError("Anti-exfil signer changed the declared sighash type") + if ( + after.partial_sigs != before.partial_sigs + or after.tap_script_sigs != before.tap_script_sigs + or after.final_script_sig != before.final_script_sig + or after.final_script_witness.serialize() != before.final_script_witness.serialize() + or (index not in expected and after.tap_key_sig != before.tap_key_sig) + ): + raise DeviceFailureError("Anti-exfil signer returned an unprotected signature") + for index, request in expected.items(): + after = response.inputs[index] + if after.unknown.get(key(HOST_COMMITMENT, request.pubkey)) != request.commitment: + raise DeviceFailureError("Anti-exfil signer changed the host commitment") + nonce = after.unknown.get(key(SIGNER_NONCE, request.pubkey)) + try: + if nonce is None: + raise ValueError("Anti-exfil nonce missing; device may not support anti-exfil") + parse_point(nonce) + except ValueError as error: + raise DeviceFailureError(str(error)) + if request.signer_nonce is not None and nonce != request.signer_nonce: + raise DeviceFailureError("Anti-exfil signer changed its nonce commitment") + if first_round: + if key(HOST_ENTROPY, request.pubkey) in after.unknown: + raise DeviceFailureError("Anti-exfil commitment round returned host entropy") + continue + if after.unknown.get(key(HOST_ENTROPY, request.pubkey)) != request.entropy: + raise DeviceFailureError("Anti-exfil signer changed host entropy") + signature = after.tap_key_sig + expected_length = 64 if request.hash_type == 0 else 65 + if len(signature) != expected_length or (expected_length == 65 and signature[-1] != request.hash_type): + raise DeviceFailureError("Anti-exfil signer returned an unexpected sighash type") + assert request.entropy is not None + if not host_verify(request.pubkey, request.message, signature[:64], request.entropy, nonce): + raise DeviceFailureError("Anti-exfil signature or nonce verification failed") diff --git a/hwilib/commands.py b/hwilib/commands.py index 7371a5356..1d0bad07f 100644 --- a/hwilib/commands.py +++ b/hwilib/commands.py @@ -18,6 +18,7 @@ For more information about the exceptions that those can raise, please see the specific client documentation. """ +import copy import importlib import logging import platform @@ -56,6 +57,7 @@ ) from .hwwclient import HardwareWalletClient from .psbt import PSBT +from . import anti_exfil from itertools import count from typing import ( @@ -204,8 +206,31 @@ def signtx( RegisteredDescriptor.deserialize(registration) for registration in registrations or [] } - result = client.sign_tx(tx, registered_descriptors).serialize() - return {"psbt": result, "signed": result != psbt} + expected = anti_exfil.requests(tx) + if expected: + with anti_exfil.private_operation(): + supported = client.can_sign_anti_exfil() + if not supported: + raise UnavailableActionError("This device does not support interactive Taproot anti-exfil") + original = copy.deepcopy(tx) if expected else tx + with anti_exfil.private_operation(bool(expected)): + signed_tx = client.sign_tx(tx, registered_descriptors) + anti_exfil.check_response(original, signed_tx, expected) + if expected: + # A valid proof does not authenticate unrelated signer metadata. Keep + # the host's PSBT and transcript, copying only the checked round result. + for index, request in expected.items(): + if request.entropy is None: + nonce_key = anti_exfil.key(anti_exfil.SIGNER_NONCE, request.pubkey) + original.inputs[index].unknown[nonce_key] = signed_tx.inputs[index].unknown[nonce_key] + else: + original.inputs[index].tap_key_sig = signed_tx.inputs[index].tap_key_sig + signed_tx = original + result = signed_tx.serialize() + signed = result != psbt + if expected and next(iter(expected.values())).entropy is None: + signed = False # A nonce commitment is not a signature. + return {"psbt": result, "signed": signed} def getxpub(client: HardwareWalletClient, path: str, expert: bool = False) -> Dict[str, Any]: """ diff --git a/hwilib/devices/bitbox02.py b/hwilib/devices/bitbox02.py index 94d64cb83..46ff0a25e 100644 --- a/hwilib/devices/bitbox02.py +++ b/hwilib/devices/bitbox02.py @@ -18,6 +18,7 @@ TypeVar, ) import base64 +import semver import builtins import sys import socket @@ -29,6 +30,7 @@ MultisigDescriptor, RegisteredDescriptor, ) +from .. import anti_exfil from ..hwwclient import HardwareWalletClient from ..key import ExtendedKey from .._script import ( @@ -609,6 +611,14 @@ def sign_tx( Transactions with legacy inputs are not supported. """ + ae_requests = anti_exfil.requests(psbt) + if ae_requests and registered_descriptors: + raise UnavailableActionError("BitBox02 anti-exfil currently requires BIP86 inputs") + if ae_requests and len(ae_requests) != len(psbt.inputs): + raise BadArgumentError("BitBox02 anti-exfil requires requests for every input") + if ae_requests and not self.can_sign_anti_exfil(): + raise UnavailableActionError("BitBox02 firmware does not support Taproot anti-exfil") + policy_script_config: Optional[bitbox02.btc.BTCScriptConfigWithKeypath] = None if registered_descriptors: if len(registered_descriptors) > 1: @@ -918,6 +928,15 @@ def script_config_from_utxo( ) assert psbt.tx_version is not None + ae_transport = { + index: bitbox02.btc.BTCTaprootAntiExfil( + host_commitment=request.commitment, + signer_nonce=request.signer_nonce or b"", + host_entropy=request.entropy or b"", + sighash=request.hash_type, + ) for index, request in ae_requests.items() + } + ae_nonces: Dict[int, bytes] = {} sigs = self.init().btc_sign( self._get_coin(), script_configs, @@ -925,8 +944,14 @@ def script_config_from_utxo( outputs=outputs, locktime=psbt.compute_lock_time(), version=psbt.tx_version, + taproot_anti_exfil=ae_transport, + anti_exfil_nonces=ae_nonces, ) + for index, nonce in ae_nonces.items(): + request = ae_requests[index] + psbt.inputs[index].unknown[anti_exfil.key(anti_exfil.SIGNER_NONCE, request.pubkey)] = nonce + for (_, sig), pubkey, psbt_in in zip(sigs, found_pubkeys, psbt.inputs): r, s = sig[:32], sig[32:64] @@ -1027,11 +1052,12 @@ def restore_device( def can_sign_taproot(self) -> bool: """ - The BitBox02 does not support Taproot yet. - - :returns: False, always + Taproot key-path signing is available in the supported firmware. """ - return False + return self.init().version >= semver.VersionInfo(9, 24, 0) + + def can_sign_anti_exfil(self) -> bool: + return self.init().device_info().get("taproot_anti_exfil") is True def _bip388_script_config(self, descriptor: Descriptor) -> bitbox02.btc.BTCScriptConfig: desc_keys = [] diff --git a/hwilib/devices/bitbox02_lib/bitbox02/bitbox02.py b/hwilib/devices/bitbox02_lib/bitbox02/bitbox02.py index 6c5876fa4..18ff41a6e 100644 --- a/hwilib/devices/bitbox02_lib/bitbox02/bitbox02.py +++ b/hwilib/devices/bitbox02_lib/bitbox02/bitbox02.py @@ -18,7 +18,7 @@ import sys import time from datetime import datetime -from typing import Optional, List, Dict, Tuple, Any, Generator, Union, Sequence +from typing import Mapping, Optional, List, Dict, Tuple, Any, Generator, Union, Sequence from typing_extensions import TypedDict import semver @@ -168,6 +168,7 @@ def device_info(self) -> Dict[str, Any]: response = self._msg_query(request, expected_response="device_info") result = { "name": response.device_info.name, + "taproot_anti_exfil": response.device_info.taproot_anti_exfil, "version": response.device_info.version, "initialized": response.device_info.initialized, "mnemonic_passphrase_enabled": response.device_info.mnemonic_passphrase_enabled, @@ -412,6 +413,8 @@ def btc_sign( version: int = 1, locktime: int = 0, format_unit: "btc.BTCSignInitRequest.FormatUnit.V" = btc.BTCSignInitRequest.FormatUnit.DEFAULT, + taproot_anti_exfil: Optional[Mapping[int, btc.BTCTaprootAntiExfil]] = None, + anti_exfil_nonces: Optional[Dict[int, bytes]] = None, output_script_configs: Optional[Sequence[btc.BTCScriptConfigWithKeypath]] = None, ) -> Sequence[Tuple[int, bytes]]: """ @@ -431,6 +434,8 @@ def btc_sign( (BTCOutputExternal) or an internal output for change (BTCOutputInternal). version, locktime: reserved for future use. format_unit: defines in which unit amounts will be displayed + taproot_anti_exfil: explicit per-input draft protocol requests; never mixed with ordinary signing. + anti_exfil_nonces: receives the public nonces for a commitment-only invocation. output_script_configs: script types for outputs belonging to the same keystore Returns: list of (input index, signature) tuples. Raises Bitbox02Exception with ERR_USER_ABORT on user abort. @@ -451,6 +456,15 @@ def btc_sign( sigs: List[Tuple[int, bytes]] = [] + ae_round = 0 + if taproot_anti_exfil: + if not self.device_info().get("taproot_anti_exfil"): + raise ValueError("Firmware does not support Taproot anti-exfil") + rounds = {2 if ae.host_entropy else 1 for ae in taproot_anti_exfil.values()} + if len(rounds) != 1 or set(taproot_anti_exfil) != set(range(len(inputs))): + raise ValueError("Taproot anti-exfil requires one round for every input") + ae_round = rounds.pop() + # Init request request = hww.Request() request.btc_sign_init.CopyFrom( @@ -463,6 +477,7 @@ def btc_sign( locktime=locktime, format_unit=format_unit, output_script_configs=output_script_configs, + taproot_anti_exfil_round=ae_round, ) ) next_response = self._msg_query(request, expected_response="btc_sign_next").btc_sign_next @@ -485,10 +500,15 @@ def btc_sign( ) ) - # Anti-Klepto protocol not supported yet for Schnorr signatures. + # The draft Taproot protocol is distinct from ECDSA anti-klepto. + ae = taproot_anti_exfil.get(input_index) if taproot_anti_exfil and is_inputs_pass2 else None + if ae is not None: + request.btc_sign_input.taproot_anti_exfil.CopyFrom(ae) + + # The ECDSA anti-klepto channel remains unchanged. input_is_schnorr = is_taproot(script_configs[tx_input["script_config_index"]]) perform_antiklepto = ( - supports_antiklepto and is_inputs_pass2 and not input_is_schnorr + supports_antiklepto and is_inputs_pass2 and not input_is_schnorr and ae is None ) if perform_antiklepto: @@ -526,8 +546,16 @@ def btc_sign( print(f"Antiklepto nonce verification PASSED for input {input_index}") if is_inputs_pass2: - assert next_response.has_signature - sigs.append((input_index, next_response.signature)) + if ae is not None and not ae.host_entropy: + if next_response.has_signature or len(next_response.taproot_anti_exfil_nonce) != 33: + raise RuntimeError("Invalid Taproot anti-exfil commitment response") + if anti_exfil_nonces is None: + raise RuntimeError("Missing Taproot anti-exfil nonce destination") + anti_exfil_nonces[input_index] = next_response.taproot_anti_exfil_nonce + else: + if not next_response.has_signature or next_response.taproot_anti_exfil_nonce: + raise RuntimeError("Invalid transaction signing response") + sigs.append((input_index, next_response.signature)) if input_index == len(inputs) - 1: is_inputs_pass2 = True diff --git a/hwilib/devices/bitbox02_lib/communication/generated/bitbox02_system_pb2.py b/hwilib/devices/bitbox02_lib/communication/generated/bitbox02_system_pb2.py index 1b519c92c..c215c0604 100644 --- a/hwilib/devices/bitbox02_lib/communication/generated/bitbox02_system_pb2.py +++ b/hwilib/devices/bitbox02_lib/communication/generated/bitbox02_system_pb2.py @@ -13,7 +13,7 @@ -DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x15\x62itbox02_system.proto\x12\x14shiftcrypto.bitbox02\"\x14\n\x12\x43heckSDCardRequest\"\'\n\x13\x43heckSDCardResponse\x12\x10\n\x08inserted\x18\x01 \x01(\x08\"\x13\n\x11\x44\x65viceInfoRequest\"\xd8\x02\n\x12\x44\x65viceInfoResponse\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x0binitialized\x18\x02 \x01(\x08\x12\x0f\n\x07version\x18\x03 \x01(\t\x12#\n\x1bmnemonic_passphrase_enabled\x18\x04 \x01(\x08\x12&\n\x1emonotonic_increments_remaining\x18\x05 \x01(\r\x12\x18\n\x10securechip_model\x18\x06 \x01(\t\x12J\n\tbluetooth\x18\x07 \x01(\x0b\x32\x32.shiftcrypto.bitbox02.DeviceInfoResponse.BluetoothH\x00\x88\x01\x01\x1aM\n\tBluetooth\x12\x15\n\rfirmware_hash\x18\x01 \x01(\x0c\x12\x18\n\x10\x66irmware_version\x18\x02 \x01(\t\x12\x0f\n\x07\x65nabled\x18\x03 \x01(\x08\x42\x0c\n\n_bluetooth\"\x9b\x01\n\x19InsertRemoveSDCardRequest\x12L\n\x06\x61\x63tion\x18\x01 \x01(\x0e\x32<.shiftcrypto.bitbox02.InsertRemoveSDCardRequest.SDCardAction\"0\n\x0cSDCardAction\x12\x0f\n\x0bREMOVE_CARD\x10\x00\x12\x0f\n\x0bINSERT_CARD\x10\x01\"\x0e\n\x0cResetRequest\",\n\x18SetDeviceLanguageRequest\x12\x10\n\x08language\x18\x01 \x01(\t\"$\n\x14SetDeviceNameRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"%\n\x12SetPasswordRequest\x12\x0f\n\x07\x65ntropy\x18\x01 \x01(\x0c\x62\x06proto3') +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x15bitbox02_system.proto\x12\x14shiftcrypto.bitbox02"\x14\n\x12CheckSDCardRequest"\'\n\x13CheckSDCardResponse\x12\x10\n\x08inserted\x18\x01 \x01(\x08"\x13\n\x11DeviceInfoRequest"\xf4\x02\n\x12DeviceInfoResponse\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x0binitialized\x18\x02 \x01(\x08\x12\x0f\n\x07version\x18\x03 \x01(\t\x12#\n\x1bmnemonic_passphrase_enabled\x18\x04 \x01(\x08\x12&\n\x1emonotonic_increments_remaining\x18\x05 \x01(\r\x12\x18\n\x10securechip_model\x18\x06 \x01(\t\x12J\n\tbluetooth\x18\x07 \x01(\x0b22.shiftcrypto.bitbox02.DeviceInfoResponse.BluetoothH\x00\x88\x01\x01\x12\x1a\n\x12taproot_anti_exfil\x18\n \x01(\x08\x1aM\n\tBluetooth\x12\x15\n\rfirmware_hash\x18\x01 \x01(\x0c\x12\x18\n\x10firmware_version\x18\x02 \x01(\t\x12\x0f\n\x07enabled\x18\x03 \x01(\x08B\x0c\n\n_bluetooth"\x9b\x01\n\x19InsertRemoveSDCardRequest\x12L\n\x06action\x18\x01 \x01(\x0e2<.shiftcrypto.bitbox02.InsertRemoveSDCardRequest.SDCardAction"0\n\x0cSDCardAction\x12\x0f\n\x0bREMOVE_CARD\x10\x00\x12\x0f\n\x0bINSERT_CARD\x10\x01"\x0e\n\x0cResetRequest",\n\x18SetDeviceLanguageRequest\x12\x10\n\x08language\x18\x01 \x01(\t"$\n\x14SetDeviceNameRequest\x12\x0c\n\x04name\x18\x01 \x01(\t"%\n\x12SetPasswordRequest\x12\x0f\n\x07entropy\x18\x01 \x01(\x0cb\x06proto3') _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'bitbox02_system_pb2', globals()) @@ -27,19 +27,19 @@ _DEVICEINFOREQUEST._serialized_start=110 _DEVICEINFOREQUEST._serialized_end=129 _DEVICEINFORESPONSE._serialized_start=132 - _DEVICEINFORESPONSE._serialized_end=476 - _DEVICEINFORESPONSE_BLUETOOTH._serialized_start=385 - _DEVICEINFORESPONSE_BLUETOOTH._serialized_end=462 - _INSERTREMOVESDCARDREQUEST._serialized_start=479 - _INSERTREMOVESDCARDREQUEST._serialized_end=634 - _INSERTREMOVESDCARDREQUEST_SDCARDACTION._serialized_start=586 - _INSERTREMOVESDCARDREQUEST_SDCARDACTION._serialized_end=634 - _RESETREQUEST._serialized_start=636 - _RESETREQUEST._serialized_end=650 - _SETDEVICELANGUAGEREQUEST._serialized_start=652 - _SETDEVICELANGUAGEREQUEST._serialized_end=696 - _SETDEVICENAMEREQUEST._serialized_start=698 - _SETDEVICENAMEREQUEST._serialized_end=734 - _SETPASSWORDREQUEST._serialized_start=736 - _SETPASSWORDREQUEST._serialized_end=773 + _DEVICEINFORESPONSE._serialized_end=504 + _DEVICEINFORESPONSE_BLUETOOTH._serialized_start=413 + _DEVICEINFORESPONSE_BLUETOOTH._serialized_end=490 + _INSERTREMOVESDCARDREQUEST._serialized_start=507 + _INSERTREMOVESDCARDREQUEST._serialized_end=662 + _INSERTREMOVESDCARDREQUEST_SDCARDACTION._serialized_start=614 + _INSERTREMOVESDCARDREQUEST_SDCARDACTION._serialized_end=662 + _RESETREQUEST._serialized_start=664 + _RESETREQUEST._serialized_end=678 + _SETDEVICELANGUAGEREQUEST._serialized_start=680 + _SETDEVICELANGUAGEREQUEST._serialized_end=724 + _SETDEVICENAMEREQUEST._serialized_start=726 + _SETDEVICENAMEREQUEST._serialized_end=762 + _SETPASSWORDREQUEST._serialized_start=764 + _SETPASSWORDREQUEST._serialized_end=801 # @@protoc_insertion_point(module_scope) diff --git a/hwilib/devices/bitbox02_lib/communication/generated/bitbox02_system_pb2.pyi b/hwilib/devices/bitbox02_lib/communication/generated/bitbox02_system_pb2.pyi index 8591bfebe..3a4ec7560 100644 --- a/hwilib/devices/bitbox02_lib/communication/generated/bitbox02_system_pb2.pyi +++ b/hwilib/devices/bitbox02_lib/communication/generated/bitbox02_system_pb2.pyi @@ -79,7 +79,7 @@ class DeviceInfoResponse(google.protobuf.message.Message): firmware_hash: builtins.bytes """Hash of the currently active Bluetooth firmware on the device.""" firmware_version: builtins.str - """Firmware version, formated as "major.minor.patch".""" + """Firmware version, formated as an unsigned integer "1", "2", etc.""" enabled: builtins.bool """True if Bluetooth is enabled""" def __init__( @@ -98,6 +98,7 @@ class DeviceInfoResponse(google.protobuf.message.Message): MONOTONIC_INCREMENTS_REMAINING_FIELD_NUMBER: builtins.int SECURECHIP_MODEL_FIELD_NUMBER: builtins.int BLUETOOTH_FIELD_NUMBER: builtins.int + TAPROOT_ANTI_EXFIL_FIELD_NUMBER: builtins.int name: builtins.str initialized: builtins.bool version: builtins.str @@ -105,6 +106,7 @@ class DeviceInfoResponse(google.protobuf.message.Message): monotonic_increments_remaining: builtins.int securechip_model: builtins.str """From v9.6.0: "ATECC608A" or "ATECC608B".""" + taproot_anti_exfil: builtins.bool @property def bluetooth(self) -> global___DeviceInfoResponse.Bluetooth: """Only present in Bluetooth-enabled devices.""" @@ -119,9 +121,10 @@ class DeviceInfoResponse(google.protobuf.message.Message): monotonic_increments_remaining: builtins.int = ..., securechip_model: builtins.str = ..., bluetooth: global___DeviceInfoResponse.Bluetooth | None = ..., + taproot_anti_exfil: builtins.bool = ..., ) -> None: ... def HasField(self, field_name: typing.Literal["_bluetooth", b"_bluetooth", "bluetooth", b"bluetooth"]) -> builtins.bool: ... - def ClearField(self, field_name: typing.Literal["_bluetooth", b"_bluetooth", "bluetooth", b"bluetooth", "initialized", b"initialized", "mnemonic_passphrase_enabled", b"mnemonic_passphrase_enabled", "monotonic_increments_remaining", b"monotonic_increments_remaining", "name", b"name", "securechip_model", b"securechip_model", "version", b"version"]) -> None: ... + def ClearField(self, field_name: typing.Literal["_bluetooth", b"_bluetooth", "bluetooth", b"bluetooth", "initialized", b"initialized", "mnemonic_passphrase_enabled", b"mnemonic_passphrase_enabled", "monotonic_increments_remaining", b"monotonic_increments_remaining", "name", b"name", "securechip_model", b"securechip_model", "taproot_anti_exfil", b"taproot_anti_exfil", "version", b"version"]) -> None: ... def WhichOneof(self, oneof_group: typing.Literal["_bluetooth", b"_bluetooth"]) -> typing.Literal["bluetooth"] | None: ... global___DeviceInfoResponse = DeviceInfoResponse diff --git a/hwilib/devices/bitbox02_lib/communication/generated/btc_pb2.py b/hwilib/devices/bitbox02_lib/communication/generated/btc_pb2.py index 111d577b4..9eb4b0f04 100644 --- a/hwilib/devices/bitbox02_lib/communication/generated/btc_pb2.py +++ b/hwilib/devices/bitbox02_lib/communication/generated/btc_pb2.py @@ -15,17 +15,17 @@ from . import antiklepto_pb2 as antiklepto__pb2 -DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\tbtc.proto\x12\x14shiftcrypto.bitbox02\x1a\x0c\x63ommon.proto\x1a\x10\x61ntiklepto.proto\"\xc6\x04\n\x0f\x42TCScriptConfig\x12G\n\x0bsimple_type\x18\x01 \x01(\x0e\x32\x30.shiftcrypto.bitbox02.BTCScriptConfig.SimpleTypeH\x00\x12\x42\n\x08multisig\x18\x02 \x01(\x0b\x32..shiftcrypto.bitbox02.BTCScriptConfig.MultisigH\x00\x12>\n\x06policy\x18\x03 \x01(\x0b\x32,.shiftcrypto.bitbox02.BTCScriptConfig.PolicyH\x00\x1a\xd9\x01\n\x08Multisig\x12\x11\n\tthreshold\x18\x01 \x01(\r\x12)\n\x05xpubs\x18\x02 \x03(\x0b\x32\x1a.shiftcrypto.bitbox02.XPub\x12\x16\n\x0eour_xpub_index\x18\x03 \x01(\r\x12N\n\x0bscript_type\x18\x04 \x01(\x0e\x32\x39.shiftcrypto.bitbox02.BTCScriptConfig.Multisig.ScriptType\"\'\n\nScriptType\x12\t\n\x05P2WSH\x10\x00\x12\x0e\n\nP2WSH_P2SH\x10\x01\x1aK\n\x06Policy\x12\x0e\n\x06policy\x18\x01 \x01(\t\x12\x31\n\x04keys\x18\x02 \x03(\x0b\x32#.shiftcrypto.bitbox02.KeyOriginInfo\"3\n\nSimpleType\x12\x0f\n\x0bP2WPKH_P2SH\x10\x00\x12\n\n\x06P2WPKH\x10\x01\x12\x08\n\x04P2TR\x10\x02\x42\x08\n\x06\x63onfig\"\xfc\x02\n\rBTCPubRequest\x12+\n\x04\x63oin\x18\x01 \x01(\x0e\x32\x1d.shiftcrypto.bitbox02.BTCCoin\x12\x0f\n\x07keypath\x18\x02 \x03(\r\x12\x41\n\txpub_type\x18\x03 \x01(\x0e\x32,.shiftcrypto.bitbox02.BTCPubRequest.XPubTypeH\x00\x12>\n\rscript_config\x18\x04 \x01(\x0b\x32%.shiftcrypto.bitbox02.BTCScriptConfigH\x00\x12\x0f\n\x07\x64isplay\x18\x05 \x01(\x08\"\x8e\x01\n\x08XPubType\x12\x08\n\x04TPUB\x10\x00\x12\x08\n\x04XPUB\x10\x01\x12\x08\n\x04YPUB\x10\x02\x12\x08\n\x04ZPUB\x10\x03\x12\x08\n\x04VPUB\x10\x04\x12\x08\n\x04UPUB\x10\x05\x12\x10\n\x0c\x43\x41PITAL_VPUB\x10\x06\x12\x10\n\x0c\x43\x41PITAL_ZPUB\x10\x07\x12\x10\n\x0c\x43\x41PITAL_UPUB\x10\x08\x12\x10\n\x0c\x43\x41PITAL_YPUB\x10\tB\x08\n\x06output\"k\n\x1a\x42TCScriptConfigWithKeypath\x12<\n\rscript_config\x18\x02 \x01(\x0b\x32%.shiftcrypto.bitbox02.BTCScriptConfig\x12\x0f\n\x07keypath\x18\x03 \x03(\r\"\xbf\x03\n\x12\x42TCSignInitRequest\x12+\n\x04\x63oin\x18\x01 \x01(\x0e\x32\x1d.shiftcrypto.bitbox02.BTCCoin\x12H\n\x0escript_configs\x18\x02 \x03(\x0b\x32\x30.shiftcrypto.bitbox02.BTCScriptConfigWithKeypath\x12\x0f\n\x07version\x18\x04 \x01(\r\x12\x12\n\nnum_inputs\x18\x05 \x01(\r\x12\x13\n\x0bnum_outputs\x18\x06 \x01(\r\x12\x10\n\x08locktime\x18\x07 \x01(\r\x12H\n\x0b\x66ormat_unit\x18\x08 \x01(\x0e\x32\x33.shiftcrypto.bitbox02.BTCSignInitRequest.FormatUnit\x12\'\n\x1f\x63ontains_silent_payment_outputs\x18\t \x01(\x08\x12O\n\x15output_script_configs\x18\n \x03(\x0b\x32\x30.shiftcrypto.bitbox02.BTCScriptConfigWithKeypath\"\"\n\nFormatUnit\x12\x0b\n\x07\x44\x45\x46\x41ULT\x10\x00\x12\x07\n\x03SAT\x10\x01\"\xc4\x03\n\x13\x42TCSignNextResponse\x12<\n\x04type\x18\x01 \x01(\x0e\x32..shiftcrypto.bitbox02.BTCSignNextResponse.Type\x12\r\n\x05index\x18\x02 \x01(\r\x12\x15\n\rhas_signature\x18\x03 \x01(\x08\x12\x11\n\tsignature\x18\x04 \x01(\x0c\x12\x12\n\nprev_index\x18\x05 \x01(\r\x12W\n\x1d\x61nti_klepto_signer_commitment\x18\x06 \x01(\x0b\x32\x30.shiftcrypto.bitbox02.AntiKleptoSignerCommitment\x12!\n\x19generated_output_pkscript\x18\x07 \x01(\x0c\x12!\n\x19silent_payment_dleq_proof\x18\x08 \x01(\x0c\"\x82\x01\n\x04Type\x12\t\n\x05INPUT\x10\x00\x12\n\n\x06OUTPUT\x10\x01\x12\x08\n\x04\x44ONE\x10\x02\x12\x0f\n\x0bPREVTX_INIT\x10\x03\x12\x10\n\x0cPREVTX_INPUT\x10\x04\x12\x11\n\rPREVTX_OUTPUT\x10\x05\x12\x0e\n\nHOST_NONCE\x10\x06\x12\x13\n\x0fPAYMENT_REQUEST\x10\x07\"\xea\x01\n\x13\x42TCSignInputRequest\x12\x13\n\x0bprevOutHash\x18\x01 \x01(\x0c\x12\x14\n\x0cprevOutIndex\x18\x02 \x01(\r\x12\x14\n\x0cprevOutValue\x18\x03 \x01(\x04\x12\x10\n\x08sequence\x18\x04 \x01(\r\x12\x0f\n\x07keypath\x18\x06 \x03(\r\x12\x1b\n\x13script_config_index\x18\x07 \x01(\r\x12R\n\x15host_nonce_commitment\x18\x08 \x01(\x0b\x32\x33.shiftcrypto.bitbox02.AntiKleptoHostNonceCommitment\"\x9f\x03\n\x14\x42TCSignOutputRequest\x12\x0c\n\x04ours\x18\x01 \x01(\x08\x12\x31\n\x04type\x18\x02 \x01(\x0e\x32#.shiftcrypto.bitbox02.BTCOutputType\x12\r\n\x05value\x18\x03 \x01(\x04\x12\x0f\n\x07payload\x18\x04 \x01(\x0c\x12\x0f\n\x07keypath\x18\x05 \x03(\r\x12\x1b\n\x13script_config_index\x18\x06 \x01(\r\x12\"\n\x15payment_request_index\x18\x07 \x01(\rH\x00\x88\x01\x01\x12P\n\x0esilent_payment\x18\x08 \x01(\x0b\x32\x38.shiftcrypto.bitbox02.BTCSignOutputRequest.SilentPayment\x12\'\n\x1aoutput_script_config_index\x18\t \x01(\rH\x01\x88\x01\x01\x1a \n\rSilentPayment\x12\x0f\n\x07\x61\x64\x64ress\x18\x01 \x01(\tB\x18\n\x16_payment_request_indexB\x1d\n\x1b_output_script_config_index\"\x99\x01\n\x1b\x42TCScriptConfigRegistration\x12+\n\x04\x63oin\x18\x01 \x01(\x0e\x32\x1d.shiftcrypto.bitbox02.BTCCoin\x12<\n\rscript_config\x18\x02 \x01(\x0b\x32%.shiftcrypto.bitbox02.BTCScriptConfig\x12\x0f\n\x07keypath\x18\x03 \x03(\r\"\x0c\n\nBTCSuccess\"m\n\"BTCIsScriptConfigRegisteredRequest\x12G\n\x0cregistration\x18\x01 \x01(\x0b\x32\x31.shiftcrypto.bitbox02.BTCScriptConfigRegistration\"<\n#BTCIsScriptConfigRegisteredResponse\x12\x15\n\ris_registered\x18\x01 \x01(\x08\"\xfc\x01\n\x1e\x42TCRegisterScriptConfigRequest\x12G\n\x0cregistration\x18\x01 \x01(\x0b\x32\x31.shiftcrypto.bitbox02.BTCScriptConfigRegistration\x12\x0c\n\x04name\x18\x02 \x01(\t\x12P\n\txpub_type\x18\x03 \x01(\x0e\x32=.shiftcrypto.bitbox02.BTCRegisterScriptConfigRequest.XPubType\"1\n\x08XPubType\x12\x11\n\rAUTO_ELECTRUM\x10\x00\x12\x12\n\x0e\x41UTO_XPUB_TPUB\x10\x01\"b\n\x14\x42TCPrevTxInitRequest\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x12\n\nnum_inputs\x18\x02 \x01(\r\x12\x13\n\x0bnum_outputs\x18\x03 \x01(\r\x12\x10\n\x08locktime\x18\x04 \x01(\r\"r\n\x15\x42TCPrevTxInputRequest\x12\x15\n\rprev_out_hash\x18\x01 \x01(\x0c\x12\x16\n\x0eprev_out_index\x18\x02 \x01(\r\x12\x18\n\x10signature_script\x18\x03 \x01(\x0c\x12\x10\n\x08sequence\x18\x04 \x01(\r\">\n\x16\x42TCPrevTxOutputRequest\x12\r\n\x05value\x18\x01 \x01(\x04\x12\x15\n\rpubkey_script\x18\x02 \x01(\x0c\"\xab\x02\n\x18\x42TCPaymentRequestRequest\x12\x16\n\x0erecipient_name\x18\x01 \x01(\t\x12\x42\n\x05memos\x18\x02 \x03(\x0b\x32\x33.shiftcrypto.bitbox02.BTCPaymentRequestRequest.Memo\x12\r\n\x05nonce\x18\x03 \x01(\x0c\x12\x14\n\x0ctotal_amount\x18\x04 \x01(\x04\x12\x11\n\tsignature\x18\x05 \x01(\x0c\x1a{\n\x04Memo\x12Q\n\ttext_memo\x18\x01 \x01(\x0b\x32<.shiftcrypto.bitbox02.BTCPaymentRequestRequest.Memo.TextMemoH\x00\x1a\x18\n\x08TextMemo\x12\x0c\n\x04note\x18\x01 \x01(\tB\x06\n\x04memo\"\xee\x01\n\x15\x42TCSignMessageRequest\x12+\n\x04\x63oin\x18\x01 \x01(\x0e\x32\x1d.shiftcrypto.bitbox02.BTCCoin\x12G\n\rscript_config\x18\x02 \x01(\x0b\x32\x30.shiftcrypto.bitbox02.BTCScriptConfigWithKeypath\x12\x0b\n\x03msg\x18\x03 \x01(\x0c\x12R\n\x15host_nonce_commitment\x18\x04 \x01(\x0b\x32\x33.shiftcrypto.bitbox02.AntiKleptoHostNonceCommitment\"+\n\x16\x42TCSignMessageResponse\x12\x11\n\tsignature\x18\x01 \x01(\x0c\"\x81\x05\n\nBTCRequest\x12_\n\x1bis_script_config_registered\x18\x01 \x01(\x0b\x32\x38.shiftcrypto.bitbox02.BTCIsScriptConfigRegisteredRequestH\x00\x12V\n\x16register_script_config\x18\x02 \x01(\x0b\x32\x34.shiftcrypto.bitbox02.BTCRegisterScriptConfigRequestH\x00\x12\x41\n\x0bprevtx_init\x18\x03 \x01(\x0b\x32*.shiftcrypto.bitbox02.BTCPrevTxInitRequestH\x00\x12\x43\n\x0cprevtx_input\x18\x04 \x01(\x0b\x32+.shiftcrypto.bitbox02.BTCPrevTxInputRequestH\x00\x12\x45\n\rprevtx_output\x18\x05 \x01(\x0b\x32,.shiftcrypto.bitbox02.BTCPrevTxOutputRequestH\x00\x12\x43\n\x0csign_message\x18\x06 \x01(\x0b\x32+.shiftcrypto.bitbox02.BTCSignMessageRequestH\x00\x12P\n\x14\x61ntiklepto_signature\x18\x07 \x01(\x0b\x32\x30.shiftcrypto.bitbox02.AntiKleptoSignatureRequestH\x00\x12I\n\x0fpayment_request\x18\x08 \x01(\x0b\x32..shiftcrypto.bitbox02.BTCPaymentRequestRequestH\x00\x42\t\n\x07request\"\x90\x03\n\x0b\x42TCResponse\x12\x33\n\x07success\x18\x01 \x01(\x0b\x32 .shiftcrypto.bitbox02.BTCSuccessH\x00\x12`\n\x1bis_script_config_registered\x18\x02 \x01(\x0b\x32\x39.shiftcrypto.bitbox02.BTCIsScriptConfigRegisteredResponseH\x00\x12>\n\tsign_next\x18\x03 \x01(\x0b\x32).shiftcrypto.bitbox02.BTCSignNextResponseH\x00\x12\x44\n\x0csign_message\x18\x04 \x01(\x0b\x32,.shiftcrypto.bitbox02.BTCSignMessageResponseH\x00\x12X\n\x1c\x61ntiklepto_signer_commitment\x18\x05 \x01(\x0b\x32\x30.shiftcrypto.bitbox02.AntiKleptoSignerCommitmentH\x00\x42\n\n\x08response*9\n\x07\x42TCCoin\x12\x07\n\x03\x42TC\x10\x00\x12\x08\n\x04TBTC\x10\x01\x12\x07\n\x03LTC\x10\x02\x12\x08\n\x04TLTC\x10\x03\x12\x08\n\x04RBTC\x10\x04*R\n\rBTCOutputType\x12\x0b\n\x07UNKNOWN\x10\x00\x12\t\n\x05P2PKH\x10\x01\x12\x08\n\x04P2SH\x10\x02\x12\n\n\x06P2WPKH\x10\x03\x12\t\n\x05P2WSH\x10\x04\x12\x08\n\x04P2TR\x10\x05\x62\x06proto3') +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\tbtc.proto\x12\x14shiftcrypto.bitbox02\x1a\x0c\x63ommon.proto\x1a\x10\x61ntiklepto.proto\"\xc6\x04\n\x0f\x42TCScriptConfig\x12G\n\x0bsimple_type\x18\x01 \x01(\x0e\x32\x30.shiftcrypto.bitbox02.BTCScriptConfig.SimpleTypeH\x00\x12\x42\n\x08multisig\x18\x02 \x01(\x0b\x32..shiftcrypto.bitbox02.BTCScriptConfig.MultisigH\x00\x12>\n\x06policy\x18\x03 \x01(\x0b\x32,.shiftcrypto.bitbox02.BTCScriptConfig.PolicyH\x00\x1a\xd9\x01\n\x08Multisig\x12\x11\n\tthreshold\x18\x01 \x01(\r\x12)\n\x05xpubs\x18\x02 \x03(\x0b\x32\x1a.shiftcrypto.bitbox02.XPub\x12\x16\n\x0eour_xpub_index\x18\x03 \x01(\r\x12N\n\x0bscript_type\x18\x04 \x01(\x0e\x32\x39.shiftcrypto.bitbox02.BTCScriptConfig.Multisig.ScriptType\"\'\n\nScriptType\x12\t\n\x05P2WSH\x10\x00\x12\x0e\n\nP2WSH_P2SH\x10\x01\x1aK\n\x06Policy\x12\x0e\n\x06policy\x18\x01 \x01(\t\x12\x31\n\x04keys\x18\x02 \x03(\x0b\x32#.shiftcrypto.bitbox02.KeyOriginInfo\"3\n\nSimpleType\x12\x0f\n\x0bP2WPKH_P2SH\x10\x00\x12\n\n\x06P2WPKH\x10\x01\x12\x08\n\x04P2TR\x10\x02\x42\x08\n\x06\x63onfig\"\xfc\x02\n\rBTCPubRequest\x12+\n\x04\x63oin\x18\x01 \x01(\x0e\x32\x1d.shiftcrypto.bitbox02.BTCCoin\x12\x0f\n\x07keypath\x18\x02 \x03(\r\x12\x41\n\txpub_type\x18\x03 \x01(\x0e\x32,.shiftcrypto.bitbox02.BTCPubRequest.XPubTypeH\x00\x12>\n\rscript_config\x18\x04 \x01(\x0b\x32%.shiftcrypto.bitbox02.BTCScriptConfigH\x00\x12\x0f\n\x07\x64isplay\x18\x05 \x01(\x08\"\x8e\x01\n\x08XPubType\x12\x08\n\x04TPUB\x10\x00\x12\x08\n\x04XPUB\x10\x01\x12\x08\n\x04YPUB\x10\x02\x12\x08\n\x04ZPUB\x10\x03\x12\x08\n\x04VPUB\x10\x04\x12\x08\n\x04UPUB\x10\x05\x12\x10\n\x0c\x43\x41PITAL_VPUB\x10\x06\x12\x10\n\x0c\x43\x41PITAL_ZPUB\x10\x07\x12\x10\n\x0c\x43\x41PITAL_UPUB\x10\x08\x12\x10\n\x0c\x43\x41PITAL_YPUB\x10\tB\x08\n\x06output\"\xdf\x01\n\x0f\x42TCXpubsRequest\x12+\n\x04\x63oin\x18\x01 \x01(\x0e\x32\x1d.shiftcrypto.bitbox02.BTCCoin\x12\x41\n\txpub_type\x18\x02 \x01(\x0e\x32..shiftcrypto.bitbox02.BTCXpubsRequest.XPubType\x12/\n\x08keypaths\x18\x03 \x03(\x0b\x32\x1d.shiftcrypto.bitbox02.Keypath\"+\n\x08XPubType\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x08\n\x04XPUB\x10\x01\x12\x08\n\x04TPUB\x10\x02\"k\n\x1a\x42TCScriptConfigWithKeypath\x12<\n\rscript_config\x18\x02 \x01(\x0b\x32%.shiftcrypto.bitbox02.BTCScriptConfig\x12\x0f\n\x07keypath\x18\x03 \x03(\r\"\xe1\x03\n\x12\x42TCSignInitRequest\x12+\n\x04\x63oin\x18\x01 \x01(\x0e\x32\x1d.shiftcrypto.bitbox02.BTCCoin\x12H\n\x0escript_configs\x18\x02 \x03(\x0b\x32\x30.shiftcrypto.bitbox02.BTCScriptConfigWithKeypath\x12\x0f\n\x07version\x18\x04 \x01(\r\x12\x12\n\nnum_inputs\x18\x05 \x01(\r\x12\x13\n\x0bnum_outputs\x18\x06 \x01(\r\x12\x10\n\x08locktime\x18\x07 \x01(\r\x12H\n\x0b\x66ormat_unit\x18\x08 \x01(\x0e\x32\x33.shiftcrypto.bitbox02.BTCSignInitRequest.FormatUnit\x12\'\n\x1f\x63ontains_silent_payment_outputs\x18\t \x01(\x08\x12O\n\x15output_script_configs\x18\n \x03(\x0b\x32\x30.shiftcrypto.bitbox02.BTCScriptConfigWithKeypath\x12 \n\x18taproot_anti_exfil_round\x18\x0b \x01(\r\"\"\n\nFormatUnit\x12\x0b\n\x07\x44\x45\x46\x41ULT\x10\x00\x12\x07\n\x03SAT\x10\x01\"\xe6\x03\n\x13\x42TCSignNextResponse\x12<\n\x04type\x18\x01 \x01(\x0e\x32..shiftcrypto.bitbox02.BTCSignNextResponse.Type\x12\r\n\x05index\x18\x02 \x01(\r\x12\x15\n\rhas_signature\x18\x03 \x01(\x08\x12\x11\n\tsignature\x18\x04 \x01(\x0c\x12\x12\n\nprev_index\x18\x05 \x01(\r\x12W\n\x1d\x61nti_klepto_signer_commitment\x18\x06 \x01(\x0b\x32\x30.shiftcrypto.bitbox02.AntiKleptoSignerCommitment\x12!\n\x19generated_output_pkscript\x18\x07 \x01(\x0c\x12!\n\x19silent_payment_dleq_proof\x18\x08 \x01(\x0c\x12 \n\x18taproot_anti_exfil_nonce\x18\t \x01(\x0c\"\x82\x01\n\x04Type\x12\t\n\x05INPUT\x10\x00\x12\n\n\x06OUTPUT\x10\x01\x12\x08\n\x04\x44ONE\x10\x02\x12\x0f\n\x0bPREVTX_INIT\x10\x03\x12\x10\n\x0cPREVTX_INPUT\x10\x04\x12\x11\n\rPREVTX_OUTPUT\x10\x05\x12\x0e\n\nHOST_NONCE\x10\x06\x12\x13\n\x0fPAYMENT_REQUEST\x10\x07\"k\n\x13\x42TCTaprootAntiExfil\x12\x17\n\x0fhost_commitment\x18\x01 \x01(\x0c\x12\x14\n\x0csigner_nonce\x18\x02 \x01(\x0c\x12\x14\n\x0chost_entropy\x18\x03 \x01(\x0c\x12\x0f\n\x07sighash\x18\x04 \x01(\r\"\xb1\x02\n\x13\x42TCSignInputRequest\x12\x13\n\x0bprevOutHash\x18\x01 \x01(\x0c\x12\x14\n\x0cprevOutIndex\x18\x02 \x01(\r\x12\x14\n\x0cprevOutValue\x18\x03 \x01(\x04\x12\x10\n\x08sequence\x18\x04 \x01(\r\x12\x0f\n\x07keypath\x18\x06 \x03(\r\x12\x1b\n\x13script_config_index\x18\x07 \x01(\r\x12R\n\x15host_nonce_commitment\x18\x08 \x01(\x0b\x32\x33.shiftcrypto.bitbox02.AntiKleptoHostNonceCommitment\x12\x45\n\x12taproot_anti_exfil\x18\t \x01(\x0b\x32).shiftcrypto.bitbox02.BTCTaprootAntiExfil\"\x9f\x03\n\x14\x42TCSignOutputRequest\x12\x0c\n\x04ours\x18\x01 \x01(\x08\x12\x31\n\x04type\x18\x02 \x01(\x0e\x32#.shiftcrypto.bitbox02.BTCOutputType\x12\r\n\x05value\x18\x03 \x01(\x04\x12\x0f\n\x07payload\x18\x04 \x01(\x0c\x12\x0f\n\x07keypath\x18\x05 \x03(\r\x12\x1b\n\x13script_config_index\x18\x06 \x01(\r\x12\"\n\x15payment_request_index\x18\x07 \x01(\rH\x00\x88\x01\x01\x12P\n\x0esilent_payment\x18\x08 \x01(\x0b\x32\x38.shiftcrypto.bitbox02.BTCSignOutputRequest.SilentPayment\x12\'\n\x1aoutput_script_config_index\x18\t \x01(\rH\x01\x88\x01\x01\x1a \n\rSilentPayment\x12\x0f\n\x07\x61\x64\x64ress\x18\x01 \x01(\tB\x18\n\x16_payment_request_indexB\x1d\n\x1b_output_script_config_index\"\x99\x01\n\x1b\x42TCScriptConfigRegistration\x12+\n\x04\x63oin\x18\x01 \x01(\x0e\x32\x1d.shiftcrypto.bitbox02.BTCCoin\x12<\n\rscript_config\x18\x02 \x01(\x0b\x32%.shiftcrypto.bitbox02.BTCScriptConfig\x12\x0f\n\x07keypath\x18\x03 \x03(\r\"\x0c\n\nBTCSuccess\"m\n\"BTCIsScriptConfigRegisteredRequest\x12G\n\x0cregistration\x18\x01 \x01(\x0b\x32\x31.shiftcrypto.bitbox02.BTCScriptConfigRegistration\"<\n#BTCIsScriptConfigRegisteredResponse\x12\x15\n\ris_registered\x18\x01 \x01(\x08\"\xfc\x01\n\x1e\x42TCRegisterScriptConfigRequest\x12G\n\x0cregistration\x18\x01 \x01(\x0b\x32\x31.shiftcrypto.bitbox02.BTCScriptConfigRegistration\x12\x0c\n\x04name\x18\x02 \x01(\t\x12P\n\txpub_type\x18\x03 \x01(\x0e\x32=.shiftcrypto.bitbox02.BTCRegisterScriptConfigRequest.XPubType\"1\n\x08XPubType\x12\x11\n\rAUTO_ELECTRUM\x10\x00\x12\x12\n\x0e\x41UTO_XPUB_TPUB\x10\x01\"b\n\x14\x42TCPrevTxInitRequest\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x12\n\nnum_inputs\x18\x02 \x01(\r\x12\x13\n\x0bnum_outputs\x18\x03 \x01(\r\x12\x10\n\x08locktime\x18\x04 \x01(\r\"r\n\x15\x42TCPrevTxInputRequest\x12\x15\n\rprev_out_hash\x18\x01 \x01(\x0c\x12\x16\n\x0eprev_out_index\x18\x02 \x01(\r\x12\x18\n\x10signature_script\x18\x03 \x01(\x0c\x12\x10\n\x08sequence\x18\x04 \x01(\r\">\n\x16\x42TCPrevTxOutputRequest\x12\r\n\x05value\x18\x01 \x01(\x04\x12\x15\n\rpubkey_script\x18\x02 \x01(\x0c\"\xab\x02\n\x18\x42TCPaymentRequestRequest\x12\x16\n\x0erecipient_name\x18\x01 \x01(\t\x12\x42\n\x05memos\x18\x02 \x03(\x0b\x32\x33.shiftcrypto.bitbox02.BTCPaymentRequestRequest.Memo\x12\r\n\x05nonce\x18\x03 \x01(\x0c\x12\x14\n\x0ctotal_amount\x18\x04 \x01(\x04\x12\x11\n\tsignature\x18\x05 \x01(\x0c\x1a{\n\x04Memo\x12Q\n\ttext_memo\x18\x01 \x01(\x0b\x32<.shiftcrypto.bitbox02.BTCPaymentRequestRequest.Memo.TextMemoH\x00\x1a\x18\n\x08TextMemo\x12\x0c\n\x04note\x18\x01 \x01(\tB\x06\n\x04memo\"\xee\x01\n\x15\x42TCSignMessageRequest\x12+\n\x04\x63oin\x18\x01 \x01(\x0e\x32\x1d.shiftcrypto.bitbox02.BTCCoin\x12G\n\rscript_config\x18\x02 \x01(\x0b\x32\x30.shiftcrypto.bitbox02.BTCScriptConfigWithKeypath\x12\x0b\n\x03msg\x18\x03 \x01(\x0c\x12R\n\x15host_nonce_commitment\x18\x04 \x01(\x0b\x32\x33.shiftcrypto.bitbox02.AntiKleptoHostNonceCommitment\"+\n\x16\x42TCSignMessageResponse\x12\x11\n\tsignature\x18\x01 \x01(\x0c\"\xb9\x05\n\nBTCRequest\x12_\n\x1bis_script_config_registered\x18\x01 \x01(\x0b\x32\x38.shiftcrypto.bitbox02.BTCIsScriptConfigRegisteredRequestH\x00\x12V\n\x16register_script_config\x18\x02 \x01(\x0b\x32\x34.shiftcrypto.bitbox02.BTCRegisterScriptConfigRequestH\x00\x12\x41\n\x0bprevtx_init\x18\x03 \x01(\x0b\x32*.shiftcrypto.bitbox02.BTCPrevTxInitRequestH\x00\x12\x43\n\x0cprevtx_input\x18\x04 \x01(\x0b\x32+.shiftcrypto.bitbox02.BTCPrevTxInputRequestH\x00\x12\x45\n\rprevtx_output\x18\x05 \x01(\x0b\x32,.shiftcrypto.bitbox02.BTCPrevTxOutputRequestH\x00\x12\x43\n\x0csign_message\x18\x06 \x01(\x0b\x32+.shiftcrypto.bitbox02.BTCSignMessageRequestH\x00\x12P\n\x14\x61ntiklepto_signature\x18\x07 \x01(\x0b\x32\x30.shiftcrypto.bitbox02.AntiKleptoSignatureRequestH\x00\x12I\n\x0fpayment_request\x18\x08 \x01(\x0b\x32..shiftcrypto.bitbox02.BTCPaymentRequestRequestH\x00\x12\x36\n\x05xpubs\x18\t \x01(\x0b\x32%.shiftcrypto.bitbox02.BTCXpubsRequestH\x00\x42\t\n\x07request\"\xc4\x03\n\x0b\x42TCResponse\x12\x33\n\x07success\x18\x01 \x01(\x0b\x32 .shiftcrypto.bitbox02.BTCSuccessH\x00\x12`\n\x1bis_script_config_registered\x18\x02 \x01(\x0b\x32\x39.shiftcrypto.bitbox02.BTCIsScriptConfigRegisteredResponseH\x00\x12>\n\tsign_next\x18\x03 \x01(\x0b\x32).shiftcrypto.bitbox02.BTCSignNextResponseH\x00\x12\x44\n\x0csign_message\x18\x04 \x01(\x0b\x32,.shiftcrypto.bitbox02.BTCSignMessageResponseH\x00\x12X\n\x1c\x61ntiklepto_signer_commitment\x18\x05 \x01(\x0b\x32\x30.shiftcrypto.bitbox02.AntiKleptoSignerCommitmentH\x00\x12\x32\n\x04pubs\x18\x06 \x01(\x0b\x32\".shiftcrypto.bitbox02.PubsResponseH\x00\x42\n\n\x08response*9\n\x07\x42TCCoin\x12\x07\n\x03\x42TC\x10\x00\x12\x08\n\x04TBTC\x10\x01\x12\x07\n\x03LTC\x10\x02\x12\x08\n\x04TLTC\x10\x03\x12\x08\n\x04RBTC\x10\x04*a\n\rBTCOutputType\x12\x0b\n\x07UNKNOWN\x10\x00\x12\t\n\x05P2PKH\x10\x01\x12\x08\n\x04P2SH\x10\x02\x12\n\n\x06P2WPKH\x10\x03\x12\t\n\x05P2WSH\x10\x04\x12\x08\n\x04P2TR\x10\x05\x12\r\n\tOP_RETURN\x10\x06\x62\x06proto3') _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'btc_pb2', globals()) if _descriptor._USE_C_DESCRIPTORS == False: DESCRIPTOR._options = None - _BTCCOIN._serialized_start=5217 - _BTCCOIN._serialized_end=5274 - _BTCOUTPUTTYPE._serialized_start=5276 - _BTCOUTPUTTYPE._serialized_end=5358 + _BTCCOIN._serialized_start=5799 + _BTCCOIN._serialized_end=5856 + _BTCOUTPUTTYPE._serialized_start=5858 + _BTCOUTPUTTYPE._serialized_end=5955 _BTCSCRIPTCONFIG._serialized_start=68 _BTCSCRIPTCONFIG._serialized_end=650 _BTCSCRIPTCONFIG_MULTISIG._serialized_start=293 @@ -40,52 +40,58 @@ _BTCPUBREQUEST._serialized_end=1033 _BTCPUBREQUEST_XPUBTYPE._serialized_start=881 _BTCPUBREQUEST_XPUBTYPE._serialized_end=1023 - _BTCSCRIPTCONFIGWITHKEYPATH._serialized_start=1035 - _BTCSCRIPTCONFIGWITHKEYPATH._serialized_end=1142 - _BTCSIGNINITREQUEST._serialized_start=1145 - _BTCSIGNINITREQUEST._serialized_end=1592 - _BTCSIGNINITREQUEST_FORMATUNIT._serialized_start=1558 - _BTCSIGNINITREQUEST_FORMATUNIT._serialized_end=1592 - _BTCSIGNNEXTRESPONSE._serialized_start=1595 - _BTCSIGNNEXTRESPONSE._serialized_end=2047 - _BTCSIGNNEXTRESPONSE_TYPE._serialized_start=1917 - _BTCSIGNNEXTRESPONSE_TYPE._serialized_end=2047 - _BTCSIGNINPUTREQUEST._serialized_start=2050 - _BTCSIGNINPUTREQUEST._serialized_end=2284 - _BTCSIGNOUTPUTREQUEST._serialized_start=2287 - _BTCSIGNOUTPUTREQUEST._serialized_end=2702 - _BTCSIGNOUTPUTREQUEST_SILENTPAYMENT._serialized_start=2613 - _BTCSIGNOUTPUTREQUEST_SILENTPAYMENT._serialized_end=2645 - _BTCSCRIPTCONFIGREGISTRATION._serialized_start=2705 - _BTCSCRIPTCONFIGREGISTRATION._serialized_end=2858 - _BTCSUCCESS._serialized_start=2860 - _BTCSUCCESS._serialized_end=2872 - _BTCISSCRIPTCONFIGREGISTEREDREQUEST._serialized_start=2874 - _BTCISSCRIPTCONFIGREGISTEREDREQUEST._serialized_end=2983 - _BTCISSCRIPTCONFIGREGISTEREDRESPONSE._serialized_start=2985 - _BTCISSCRIPTCONFIGREGISTEREDRESPONSE._serialized_end=3045 - _BTCREGISTERSCRIPTCONFIGREQUEST._serialized_start=3048 - _BTCREGISTERSCRIPTCONFIGREQUEST._serialized_end=3300 - _BTCREGISTERSCRIPTCONFIGREQUEST_XPUBTYPE._serialized_start=3251 - _BTCREGISTERSCRIPTCONFIGREQUEST_XPUBTYPE._serialized_end=3300 - _BTCPREVTXINITREQUEST._serialized_start=3302 - _BTCPREVTXINITREQUEST._serialized_end=3400 - _BTCPREVTXINPUTREQUEST._serialized_start=3402 - _BTCPREVTXINPUTREQUEST._serialized_end=3516 - _BTCPREVTXOUTPUTREQUEST._serialized_start=3518 - _BTCPREVTXOUTPUTREQUEST._serialized_end=3580 - _BTCPAYMENTREQUESTREQUEST._serialized_start=3583 - _BTCPAYMENTREQUESTREQUEST._serialized_end=3882 - _BTCPAYMENTREQUESTREQUEST_MEMO._serialized_start=3759 - _BTCPAYMENTREQUESTREQUEST_MEMO._serialized_end=3882 - _BTCPAYMENTREQUESTREQUEST_MEMO_TEXTMEMO._serialized_start=3850 - _BTCPAYMENTREQUESTREQUEST_MEMO_TEXTMEMO._serialized_end=3874 - _BTCSIGNMESSAGEREQUEST._serialized_start=3885 - _BTCSIGNMESSAGEREQUEST._serialized_end=4123 - _BTCSIGNMESSAGERESPONSE._serialized_start=4125 - _BTCSIGNMESSAGERESPONSE._serialized_end=4168 - _BTCREQUEST._serialized_start=4171 - _BTCREQUEST._serialized_end=4812 - _BTCRESPONSE._serialized_start=4815 - _BTCRESPONSE._serialized_end=5215 + _BTCXPUBSREQUEST._serialized_start=1036 + _BTCXPUBSREQUEST._serialized_end=1259 + _BTCXPUBSREQUEST_XPUBTYPE._serialized_start=1216 + _BTCXPUBSREQUEST_XPUBTYPE._serialized_end=1259 + _BTCSCRIPTCONFIGWITHKEYPATH._serialized_start=1261 + _BTCSCRIPTCONFIGWITHKEYPATH._serialized_end=1368 + _BTCSIGNINITREQUEST._serialized_start=1371 + _BTCSIGNINITREQUEST._serialized_end=1852 + _BTCSIGNINITREQUEST_FORMATUNIT._serialized_start=1818 + _BTCSIGNINITREQUEST_FORMATUNIT._serialized_end=1852 + _BTCSIGNNEXTRESPONSE._serialized_start=1855 + _BTCSIGNNEXTRESPONSE._serialized_end=2341 + _BTCSIGNNEXTRESPONSE_TYPE._serialized_start=2211 + _BTCSIGNNEXTRESPONSE_TYPE._serialized_end=2341 + _BTCTAPROOTANTIEXFIL._serialized_start=2343 + _BTCTAPROOTANTIEXFIL._serialized_end=2450 + _BTCSIGNINPUTREQUEST._serialized_start=2453 + _BTCSIGNINPUTREQUEST._serialized_end=2758 + _BTCSIGNOUTPUTREQUEST._serialized_start=2761 + _BTCSIGNOUTPUTREQUEST._serialized_end=3176 + _BTCSIGNOUTPUTREQUEST_SILENTPAYMENT._serialized_start=3087 + _BTCSIGNOUTPUTREQUEST_SILENTPAYMENT._serialized_end=3119 + _BTCSCRIPTCONFIGREGISTRATION._serialized_start=3179 + _BTCSCRIPTCONFIGREGISTRATION._serialized_end=3332 + _BTCSUCCESS._serialized_start=3334 + _BTCSUCCESS._serialized_end=3346 + _BTCISSCRIPTCONFIGREGISTEREDREQUEST._serialized_start=3348 + _BTCISSCRIPTCONFIGREGISTEREDREQUEST._serialized_end=3457 + _BTCISSCRIPTCONFIGREGISTEREDRESPONSE._serialized_start=3459 + _BTCISSCRIPTCONFIGREGISTEREDRESPONSE._serialized_end=3519 + _BTCREGISTERSCRIPTCONFIGREQUEST._serialized_start=3522 + _BTCREGISTERSCRIPTCONFIGREQUEST._serialized_end=3774 + _BTCREGISTERSCRIPTCONFIGREQUEST_XPUBTYPE._serialized_start=3725 + _BTCREGISTERSCRIPTCONFIGREQUEST_XPUBTYPE._serialized_end=3774 + _BTCPREVTXINITREQUEST._serialized_start=3776 + _BTCPREVTXINITREQUEST._serialized_end=3874 + _BTCPREVTXINPUTREQUEST._serialized_start=3876 + _BTCPREVTXINPUTREQUEST._serialized_end=3990 + _BTCPREVTXOUTPUTREQUEST._serialized_start=3992 + _BTCPREVTXOUTPUTREQUEST._serialized_end=4054 + _BTCPAYMENTREQUESTREQUEST._serialized_start=4057 + _BTCPAYMENTREQUESTREQUEST._serialized_end=4356 + _BTCPAYMENTREQUESTREQUEST_MEMO._serialized_start=4233 + _BTCPAYMENTREQUESTREQUEST_MEMO._serialized_end=4356 + _BTCPAYMENTREQUESTREQUEST_MEMO_TEXTMEMO._serialized_start=4324 + _BTCPAYMENTREQUESTREQUEST_MEMO_TEXTMEMO._serialized_end=4348 + _BTCSIGNMESSAGEREQUEST._serialized_start=4359 + _BTCSIGNMESSAGEREQUEST._serialized_end=4597 + _BTCSIGNMESSAGERESPONSE._serialized_start=4599 + _BTCSIGNMESSAGERESPONSE._serialized_end=4642 + _BTCREQUEST._serialized_start=4645 + _BTCREQUEST._serialized_end=5342 + _BTCRESPONSE._serialized_start=5345 + _BTCRESPONSE._serialized_end=5797 # @@protoc_insertion_point(module_scope) diff --git a/hwilib/devices/bitbox02_lib/communication/generated/btc_pb2.pyi b/hwilib/devices/bitbox02_lib/communication/generated/btc_pb2.pyi index acf1f548d..17862272b 100644 --- a/hwilib/devices/bitbox02_lib/communication/generated/btc_pb2.pyi +++ b/hwilib/devices/bitbox02_lib/communication/generated/btc_pb2.pyi @@ -70,6 +70,7 @@ class _BTCOutputTypeEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._ P2WPKH: _BTCOutputType.ValueType # 3 P2WSH: _BTCOutputType.ValueType # 4 P2TR: _BTCOutputType.ValueType # 5 + OP_RETURN: _BTCOutputType.ValueType # 6 class BTCOutputType(_BTCOutputType, metaclass=_BTCOutputTypeEnumTypeWrapper): ... @@ -79,6 +80,7 @@ P2SH: BTCOutputType.ValueType # 2 P2WPKH: BTCOutputType.ValueType # 3 P2WSH: BTCOutputType.ValueType # 4 P2TR: BTCOutputType.ValueType # 5 +OP_RETURN: BTCOutputType.ValueType # 6 global___BTCOutputType = BTCOutputType @typing.final @@ -263,6 +265,43 @@ class BTCPubRequest(google.protobuf.message.Message): global___BTCPubRequest = BTCPubRequest +@typing.final +class BTCXpubsRequest(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _XPubType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _XPubTypeEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[BTCXpubsRequest._XPubType.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + UNKNOWN: BTCXpubsRequest._XPubType.ValueType # 0 + XPUB: BTCXpubsRequest._XPubType.ValueType # 1 + TPUB: BTCXpubsRequest._XPubType.ValueType # 2 + + class XPubType(_XPubType, metaclass=_XPubTypeEnumTypeWrapper): ... + UNKNOWN: BTCXpubsRequest.XPubType.ValueType # 0 + XPUB: BTCXpubsRequest.XPubType.ValueType # 1 + TPUB: BTCXpubsRequest.XPubType.ValueType # 2 + + COIN_FIELD_NUMBER: builtins.int + XPUB_TYPE_FIELD_NUMBER: builtins.int + KEYPATHS_FIELD_NUMBER: builtins.int + coin: global___BTCCoin.ValueType + xpub_type: global___BTCXpubsRequest.XPubType.ValueType + @property + def keypaths(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[common_pb2.Keypath]: ... + def __init__( + self, + *, + coin: global___BTCCoin.ValueType = ..., + xpub_type: global___BTCXpubsRequest.XPubType.ValueType = ..., + keypaths: collections.abc.Iterable[common_pb2.Keypath] | None = ..., + ) -> None: ... + def ClearField(self, field_name: typing.Literal["coin", b"coin", "keypaths", b"keypaths", "xpub_type", b"xpub_type"]) -> None: ... + +global___BTCXpubsRequest = BTCXpubsRequest + @typing.final class BTCScriptConfigWithKeypath(google.protobuf.message.Message): DESCRIPTOR: google.protobuf.descriptor.Descriptor @@ -314,6 +353,7 @@ class BTCSignInitRequest(google.protobuf.message.Message): FORMAT_UNIT_FIELD_NUMBER: builtins.int CONTAINS_SILENT_PAYMENT_OUTPUTS_FIELD_NUMBER: builtins.int OUTPUT_SCRIPT_CONFIGS_FIELD_NUMBER: builtins.int + TAPROOT_ANTI_EXFIL_ROUND_FIELD_NUMBER: builtins.int coin: global___BTCCoin.ValueType version: builtins.int """must be 1 or 2""" @@ -323,6 +363,8 @@ class BTCSignInitRequest(google.protobuf.message.Message): """must be <500000000""" format_unit: global___BTCSignInitRequest.FormatUnit.ValueType contains_silent_payment_outputs: builtins.bool + taproot_anti_exfil_round: builtins.int + """0 ordinary, 1 commitment-only, 2 signing.""" @property def script_configs(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BTCScriptConfigWithKeypath]: """used script configs in inputs and changes""" @@ -345,8 +387,9 @@ class BTCSignInitRequest(google.protobuf.message.Message): format_unit: global___BTCSignInitRequest.FormatUnit.ValueType = ..., contains_silent_payment_outputs: builtins.bool = ..., output_script_configs: collections.abc.Iterable[global___BTCScriptConfigWithKeypath] | None = ..., + taproot_anti_exfil_round: builtins.int = ..., ) -> None: ... - def ClearField(self, field_name: typing.Literal["coin", b"coin", "contains_silent_payment_outputs", b"contains_silent_payment_outputs", "format_unit", b"format_unit", "locktime", b"locktime", "num_inputs", b"num_inputs", "num_outputs", b"num_outputs", "output_script_configs", b"output_script_configs", "script_configs", b"script_configs", "version", b"version"]) -> None: ... + def ClearField(self, field_name: typing.Literal["coin", b"coin", "contains_silent_payment_outputs", b"contains_silent_payment_outputs", "format_unit", b"format_unit", "locktime", b"locktime", "num_inputs", b"num_inputs", "num_outputs", b"num_outputs", "output_script_configs", b"output_script_configs", "script_configs", b"script_configs", "taproot_anti_exfil_round", b"taproot_anti_exfil_round", "version", b"version"]) -> None: ... global___BTCSignInitRequest = BTCSignInitRequest @@ -389,6 +432,7 @@ class BTCSignNextResponse(google.protobuf.message.Message): ANTI_KLEPTO_SIGNER_COMMITMENT_FIELD_NUMBER: builtins.int GENERATED_OUTPUT_PKSCRIPT_FIELD_NUMBER: builtins.int SILENT_PAYMENT_DLEQ_PROOF_FIELD_NUMBER: builtins.int + TAPROOT_ANTI_EXFIL_NONCE_FIELD_NUMBER: builtins.int type: global___BTCSignNextResponse.Type.ValueType index: builtins.int """index of the current input or output""" @@ -401,6 +445,8 @@ class BTCSignNextResponse(google.protobuf.message.Message): generated_output_pkscript: builtins.bytes """Generated output. The host *must* verify its correctness using `silent_payment_dleq_proof`.""" silent_payment_dleq_proof: builtins.bytes + taproot_anti_exfil_nonce: builtins.bytes + """33 bytes, and has_signature is false in round 1.""" @property def anti_klepto_signer_commitment(self) -> antiklepto_pb2.AntiKleptoSignerCommitment: ... def __init__( @@ -414,12 +460,43 @@ class BTCSignNextResponse(google.protobuf.message.Message): anti_klepto_signer_commitment: antiklepto_pb2.AntiKleptoSignerCommitment | None = ..., generated_output_pkscript: builtins.bytes = ..., silent_payment_dleq_proof: builtins.bytes = ..., + taproot_anti_exfil_nonce: builtins.bytes = ..., ) -> None: ... def HasField(self, field_name: typing.Literal["anti_klepto_signer_commitment", b"anti_klepto_signer_commitment"]) -> builtins.bool: ... - def ClearField(self, field_name: typing.Literal["anti_klepto_signer_commitment", b"anti_klepto_signer_commitment", "generated_output_pkscript", b"generated_output_pkscript", "has_signature", b"has_signature", "index", b"index", "prev_index", b"prev_index", "signature", b"signature", "silent_payment_dleq_proof", b"silent_payment_dleq_proof", "type", b"type"]) -> None: ... + def ClearField(self, field_name: typing.Literal["anti_klepto_signer_commitment", b"anti_klepto_signer_commitment", "generated_output_pkscript", b"generated_output_pkscript", "has_signature", b"has_signature", "index", b"index", "prev_index", b"prev_index", "signature", b"signature", "silent_payment_dleq_proof", b"silent_payment_dleq_proof", "taproot_anti_exfil_nonce", b"taproot_anti_exfil_nonce", "type", b"type"]) -> None: ... global___BTCSignNextResponse = BTCSignNextResponse +@typing.final +class BTCTaprootAntiExfil(google.protobuf.message.Message): + """Draft BIP-EXFIL, separate from the ECDSA anti-klepto wire protocol. + Empty nonce/entropy selects the commitment-only round. The second round + carries the original full compressed nonce and the host opening. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + HOST_COMMITMENT_FIELD_NUMBER: builtins.int + SIGNER_NONCE_FIELD_NUMBER: builtins.int + HOST_ENTROPY_FIELD_NUMBER: builtins.int + SIGHASH_FIELD_NUMBER: builtins.int + host_commitment: builtins.bytes + signer_nonce: builtins.bytes + host_entropy: builtins.bytes + sighash: builtins.int + """0 (DEFAULT) or 1 (ALL)""" + def __init__( + self, + *, + host_commitment: builtins.bytes = ..., + signer_nonce: builtins.bytes = ..., + host_entropy: builtins.bytes = ..., + sighash: builtins.int = ..., + ) -> None: ... + def ClearField(self, field_name: typing.Literal["host_commitment", b"host_commitment", "host_entropy", b"host_entropy", "sighash", b"sighash", "signer_nonce", b"signer_nonce"]) -> None: ... + +global___BTCTaprootAntiExfil = BTCTaprootAntiExfil + @typing.final class BTCSignInputRequest(google.protobuf.message.Message): DESCRIPTOR: google.protobuf.descriptor.Descriptor @@ -431,6 +508,7 @@ class BTCSignInputRequest(google.protobuf.message.Message): KEYPATH_FIELD_NUMBER: builtins.int SCRIPT_CONFIG_INDEX_FIELD_NUMBER: builtins.int HOST_NONCE_COMMITMENT_FIELD_NUMBER: builtins.int + TAPROOT_ANTI_EXFIL_FIELD_NUMBER: builtins.int prevOutHash: builtins.bytes prevOutIndex: builtins.int prevOutValue: builtins.int @@ -444,6 +522,8 @@ class BTCSignInputRequest(google.protobuf.message.Message): @property def host_nonce_commitment(self) -> antiklepto_pb2.AntiKleptoHostNonceCommitment: ... + @property + def taproot_anti_exfil(self) -> global___BTCTaprootAntiExfil: ... def __init__( self, *, @@ -454,9 +534,10 @@ class BTCSignInputRequest(google.protobuf.message.Message): keypath: collections.abc.Iterable[builtins.int] | None = ..., script_config_index: builtins.int = ..., host_nonce_commitment: antiklepto_pb2.AntiKleptoHostNonceCommitment | None = ..., + taproot_anti_exfil: global___BTCTaprootAntiExfil | None = ..., ) -> None: ... - def HasField(self, field_name: typing.Literal["host_nonce_commitment", b"host_nonce_commitment"]) -> builtins.bool: ... - def ClearField(self, field_name: typing.Literal["host_nonce_commitment", b"host_nonce_commitment", "keypath", b"keypath", "prevOutHash", b"prevOutHash", "prevOutIndex", b"prevOutIndex", "prevOutValue", b"prevOutValue", "script_config_index", b"script_config_index", "sequence", b"sequence"]) -> None: ... + def HasField(self, field_name: typing.Literal["host_nonce_commitment", b"host_nonce_commitment", "taproot_anti_exfil", b"taproot_anti_exfil"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["host_nonce_commitment", b"host_nonce_commitment", "keypath", b"keypath", "prevOutHash", b"prevOutHash", "prevOutIndex", b"prevOutIndex", "prevOutValue", b"prevOutValue", "script_config_index", b"script_config_index", "sequence", b"sequence", "taproot_anti_exfil", b"taproot_anti_exfil"]) -> None: ... global___BTCSignInputRequest = BTCSignInputRequest @@ -826,6 +907,7 @@ class BTCRequest(google.protobuf.message.Message): SIGN_MESSAGE_FIELD_NUMBER: builtins.int ANTIKLEPTO_SIGNATURE_FIELD_NUMBER: builtins.int PAYMENT_REQUEST_FIELD_NUMBER: builtins.int + XPUBS_FIELD_NUMBER: builtins.int @property def is_script_config_registered(self) -> global___BTCIsScriptConfigRegisteredRequest: ... @property @@ -842,6 +924,8 @@ class BTCRequest(google.protobuf.message.Message): def antiklepto_signature(self) -> antiklepto_pb2.AntiKleptoSignatureRequest: ... @property def payment_request(self) -> global___BTCPaymentRequestRequest: ... + @property + def xpubs(self) -> global___BTCXpubsRequest: ... def __init__( self, *, @@ -853,10 +937,11 @@ class BTCRequest(google.protobuf.message.Message): sign_message: global___BTCSignMessageRequest | None = ..., antiklepto_signature: antiklepto_pb2.AntiKleptoSignatureRequest | None = ..., payment_request: global___BTCPaymentRequestRequest | None = ..., + xpubs: global___BTCXpubsRequest | None = ..., ) -> None: ... - def HasField(self, field_name: typing.Literal["antiklepto_signature", b"antiklepto_signature", "is_script_config_registered", b"is_script_config_registered", "payment_request", b"payment_request", "prevtx_init", b"prevtx_init", "prevtx_input", b"prevtx_input", "prevtx_output", b"prevtx_output", "register_script_config", b"register_script_config", "request", b"request", "sign_message", b"sign_message"]) -> builtins.bool: ... - def ClearField(self, field_name: typing.Literal["antiklepto_signature", b"antiklepto_signature", "is_script_config_registered", b"is_script_config_registered", "payment_request", b"payment_request", "prevtx_init", b"prevtx_init", "prevtx_input", b"prevtx_input", "prevtx_output", b"prevtx_output", "register_script_config", b"register_script_config", "request", b"request", "sign_message", b"sign_message"]) -> None: ... - def WhichOneof(self, oneof_group: typing.Literal["request", b"request"]) -> typing.Literal["is_script_config_registered", "register_script_config", "prevtx_init", "prevtx_input", "prevtx_output", "sign_message", "antiklepto_signature", "payment_request"] | None: ... + def HasField(self, field_name: typing.Literal["antiklepto_signature", b"antiklepto_signature", "is_script_config_registered", b"is_script_config_registered", "payment_request", b"payment_request", "prevtx_init", b"prevtx_init", "prevtx_input", b"prevtx_input", "prevtx_output", b"prevtx_output", "register_script_config", b"register_script_config", "request", b"request", "sign_message", b"sign_message", "xpubs", b"xpubs"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["antiklepto_signature", b"antiklepto_signature", "is_script_config_registered", b"is_script_config_registered", "payment_request", b"payment_request", "prevtx_init", b"prevtx_init", "prevtx_input", b"prevtx_input", "prevtx_output", b"prevtx_output", "register_script_config", b"register_script_config", "request", b"request", "sign_message", b"sign_message", "xpubs", b"xpubs"]) -> None: ... + def WhichOneof(self, oneof_group: typing.Literal["request", b"request"]) -> typing.Literal["is_script_config_registered", "register_script_config", "prevtx_init", "prevtx_input", "prevtx_output", "sign_message", "antiklepto_signature", "payment_request", "xpubs"] | None: ... global___BTCRequest = BTCRequest @@ -869,6 +954,7 @@ class BTCResponse(google.protobuf.message.Message): SIGN_NEXT_FIELD_NUMBER: builtins.int SIGN_MESSAGE_FIELD_NUMBER: builtins.int ANTIKLEPTO_SIGNER_COMMITMENT_FIELD_NUMBER: builtins.int + PUBS_FIELD_NUMBER: builtins.int @property def success(self) -> global___BTCSuccess: ... @property @@ -879,6 +965,8 @@ class BTCResponse(google.protobuf.message.Message): def sign_message(self) -> global___BTCSignMessageResponse: ... @property def antiklepto_signer_commitment(self) -> antiklepto_pb2.AntiKleptoSignerCommitment: ... + @property + def pubs(self) -> common_pb2.PubsResponse: ... def __init__( self, *, @@ -887,9 +975,10 @@ class BTCResponse(google.protobuf.message.Message): sign_next: global___BTCSignNextResponse | None = ..., sign_message: global___BTCSignMessageResponse | None = ..., antiklepto_signer_commitment: antiklepto_pb2.AntiKleptoSignerCommitment | None = ..., + pubs: common_pb2.PubsResponse | None = ..., ) -> None: ... - def HasField(self, field_name: typing.Literal["antiklepto_signer_commitment", b"antiklepto_signer_commitment", "is_script_config_registered", b"is_script_config_registered", "response", b"response", "sign_message", b"sign_message", "sign_next", b"sign_next", "success", b"success"]) -> builtins.bool: ... - def ClearField(self, field_name: typing.Literal["antiklepto_signer_commitment", b"antiklepto_signer_commitment", "is_script_config_registered", b"is_script_config_registered", "response", b"response", "sign_message", b"sign_message", "sign_next", b"sign_next", "success", b"success"]) -> None: ... - def WhichOneof(self, oneof_group: typing.Literal["response", b"response"]) -> typing.Literal["success", "is_script_config_registered", "sign_next", "sign_message", "antiklepto_signer_commitment"] | None: ... + def HasField(self, field_name: typing.Literal["antiklepto_signer_commitment", b"antiklepto_signer_commitment", "is_script_config_registered", b"is_script_config_registered", "pubs", b"pubs", "response", b"response", "sign_message", b"sign_message", "sign_next", b"sign_next", "success", b"success"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["antiklepto_signer_commitment", b"antiklepto_signer_commitment", "is_script_config_registered", b"is_script_config_registered", "pubs", b"pubs", "response", b"response", "sign_message", b"sign_message", "sign_next", b"sign_next", "success", b"success"]) -> None: ... + def WhichOneof(self, oneof_group: typing.Literal["response", b"response"]) -> typing.Literal["success", "is_script_config_registered", "sign_next", "sign_message", "antiklepto_signer_commitment", "pubs"] | None: ... global___BTCResponse = BTCResponse diff --git a/hwilib/devices/bitbox02_lib/communication/generated/common_pb2.py b/hwilib/devices/bitbox02_lib/communication/generated/common_pb2.py index 3109f6e38..d0e55cfd5 100644 --- a/hwilib/devices/bitbox02_lib/communication/generated/common_pb2.py +++ b/hwilib/devices/bitbox02_lib/communication/generated/common_pb2.py @@ -13,7 +13,7 @@ -DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0c\x63ommon.proto\x12\x14shiftcrypto.bitbox02\"\x1a\n\x0bPubResponse\x12\x0b\n\x03pub\x18\x01 \x01(\t\"\x18\n\x16RootFingerprintRequest\".\n\x17RootFingerprintResponse\x12\x13\n\x0b\x66ingerprint\x18\x01 \x01(\x0c\"l\n\x04XPub\x12\r\n\x05\x64\x65pth\x18\x01 \x01(\x0c\x12\x1a\n\x12parent_fingerprint\x18\x02 \x01(\x0c\x12\x11\n\tchild_num\x18\x03 \x01(\r\x12\x12\n\nchain_code\x18\x04 \x01(\x0c\x12\x12\n\npublic_key\x18\x05 \x01(\x0c\"\x1a\n\x07Keypath\x12\x0f\n\x07keypath\x18\x01 \x03(\r\"d\n\rKeyOriginInfo\x12\x18\n\x10root_fingerprint\x18\x01 \x01(\x0c\x12\x0f\n\x07keypath\x18\x02 \x03(\r\x12(\n\x04xpub\x18\x03 \x01(\x0b\x32\x1a.shiftcrypto.bitbox02.XPubb\x06proto3') +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0c\x63ommon.proto\x12\x14shiftcrypto.bitbox02\"\x1a\n\x0bPubResponse\x12\x0b\n\x03pub\x18\x01 \x01(\t\"\x1c\n\x0cPubsResponse\x12\x0c\n\x04pubs\x18\x01 \x03(\t\"\x18\n\x16RootFingerprintRequest\".\n\x17RootFingerprintResponse\x12\x13\n\x0b\x66ingerprint\x18\x01 \x01(\x0c\"l\n\x04XPub\x12\r\n\x05\x64\x65pth\x18\x01 \x01(\x0c\x12\x1a\n\x12parent_fingerprint\x18\x02 \x01(\x0c\x12\x11\n\tchild_num\x18\x03 \x01(\r\x12\x12\n\nchain_code\x18\x04 \x01(\x0c\x12\x12\n\npublic_key\x18\x05 \x01(\x0c\"\x1a\n\x07Keypath\x12\x0f\n\x07keypath\x18\x01 \x03(\r\"d\n\rKeyOriginInfo\x12\x18\n\x10root_fingerprint\x18\x01 \x01(\x0c\x12\x0f\n\x07keypath\x18\x02 \x03(\r\x12(\n\x04xpub\x18\x03 \x01(\x0b\x32\x1a.shiftcrypto.bitbox02.XPubb\x06proto3') _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'common_pb2', globals()) @@ -22,14 +22,16 @@ DESCRIPTOR._options = None _PUBRESPONSE._serialized_start=38 _PUBRESPONSE._serialized_end=64 - _ROOTFINGERPRINTREQUEST._serialized_start=66 - _ROOTFINGERPRINTREQUEST._serialized_end=90 - _ROOTFINGERPRINTRESPONSE._serialized_start=92 - _ROOTFINGERPRINTRESPONSE._serialized_end=138 - _XPUB._serialized_start=140 - _XPUB._serialized_end=248 - _KEYPATH._serialized_start=250 - _KEYPATH._serialized_end=276 - _KEYORIGININFO._serialized_start=278 - _KEYORIGININFO._serialized_end=378 + _PUBSRESPONSE._serialized_start=66 + _PUBSRESPONSE._serialized_end=94 + _ROOTFINGERPRINTREQUEST._serialized_start=96 + _ROOTFINGERPRINTREQUEST._serialized_end=120 + _ROOTFINGERPRINTRESPONSE._serialized_start=122 + _ROOTFINGERPRINTRESPONSE._serialized_end=168 + _XPUB._serialized_start=170 + _XPUB._serialized_end=278 + _KEYPATH._serialized_start=280 + _KEYPATH._serialized_end=306 + _KEYORIGININFO._serialized_start=308 + _KEYORIGININFO._serialized_end=408 # @@protoc_insertion_point(module_scope) diff --git a/hwilib/devices/bitbox02_lib/communication/generated/common_pb2.pyi b/hwilib/devices/bitbox02_lib/communication/generated/common_pb2.pyi index 4e73c7e3e..4e65dfed1 100644 --- a/hwilib/devices/bitbox02_lib/communication/generated/common_pb2.pyi +++ b/hwilib/devices/bitbox02_lib/communication/generated/common_pb2.pyi @@ -40,6 +40,22 @@ class PubResponse(google.protobuf.message.Message): global___PubResponse = PubResponse +@typing.final +class PubsResponse(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PUBS_FIELD_NUMBER: builtins.int + @property + def pubs(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: ... + def __init__( + self, + *, + pubs: collections.abc.Iterable[builtins.str] | None = ..., + ) -> None: ... + def ClearField(self, field_name: typing.Literal["pubs", b"pubs"]) -> None: ... + +global___PubsResponse = PubsResponse + @typing.final class RootFingerprintRequest(google.protobuf.message.Message): DESCRIPTOR: google.protobuf.descriptor.Descriptor diff --git a/hwilib/devices/coldcard.py b/hwilib/devices/coldcard.py index 5d4eba985..f9f944b6e 100644 --- a/hwilib/devices/coldcard.py +++ b/hwilib/devices/coldcard.py @@ -16,6 +16,7 @@ WSHDescriptor, ) from ..hwwclient import HardwareWalletClient +from .. import anti_exfil from ..errors import ( ActionCanceledError, BadArgumentError, @@ -76,6 +77,8 @@ Callable, Optional, Set, + ParamSpec, + TypeVar, ) CC_SIMULATOR_SOCK = '/tmp/ckcc-simulator.sock' @@ -91,9 +94,13 @@ def _firmware_version_supports_psbt_v2(version: str) -> bool: return False -def coldcard_exception(f: Callable[..., Any]) -> Callable[..., Any]: +P = ParamSpec("P") +R = TypeVar("R") + + +def coldcard_exception(f: Callable[P, R]) -> Callable[P, R]: @wraps(f) - def func(*args: Any, **kwargs: Any) -> Any: + def func(*args: P.args, **kwargs: P.kwargs) -> R: try: return f(*args, **kwargs) except CCProtoError as e: @@ -110,7 +117,7 @@ class ColdcardClient(HardwareWalletClient): def __init__(self, path: str, password: Optional[str] = None, expert: bool = False, chain: Chain = Chain.MAIN) -> None: super(ColdcardClient, self).__init__(path, password, expert, chain) # Simulator hard coded pipe socket - if path == CC_SIMULATOR_SOCK: + if path == CC_SIMULATOR_SOCK or (path.startswith("/tmp/ckcc-simulator-") and path.endswith(".sock")): self.device = ColdcardDevice(sn=path) else: device = hid.device() @@ -120,7 +127,7 @@ def __init__(self, path: str, password: Optional[str] = None, expert: bool = Fal self._is_edge = None @property - def is_edge(self): + def is_edge(self) -> bool: """ Cached property, no need to ask device more than once :return: bool @@ -132,7 +139,7 @@ def is_edge(self): # silent fail, normal firmware is implied pass - return self._is_edge + return bool(self._is_edge) def _supports_psbt_v2(self) -> bool: if self.device.is_simulator or self.is_edge: @@ -279,6 +286,15 @@ def sign_tx( """ self.device.check_mitm() + if anti_exfil.requests(psbt): + if not self.is_edge: + raise UnavailableActionError("This device does not support interactive Taproot anti-exfil") + if registered_descriptors: + raise BadArgumentError("Coldcard anti-exfil currently requires a BIP86 wallet") + # One protected round per call. Do not run the policy fallback or + # ordinary multi-pass signing after receiving a nonce commitment. + return self._sign_tx_once(psbt) + # Get this devices master key fingerprint xpub = self.device.send_recv(CCProtocolPacker.get_xpub('m/0\''), timeout=None) master_fp = get_xpub_fingerprint(xpub) @@ -528,6 +544,10 @@ def toggle_passphrase(self) -> bool: """ raise UnavailableActionError('The Coldcard does not support toggling passphrase from the host') + def can_sign_anti_exfil(self) -> bool: + # Matching experimental firmware is required; the host checks its proof. + return self.is_edge + def can_sign_taproot(self) -> bool: """ Only COLDCARD EDGE support taproot. diff --git a/hwilib/devices/jade.py b/hwilib/devices/jade.py index 466b51216..b7beda240 100644 --- a/hwilib/devices/jade.py +++ b/hwilib/devices/jade.py @@ -26,6 +26,7 @@ MultisigDescriptor, RegisteredDescriptor, ) +from .. import anti_exfil from ..hwwclient import HardwareWalletClient from ..errors import ( ActionCanceledError, @@ -110,7 +111,8 @@ def _network(self) -> str: ADDRTYPES = {AddressType.LEGACY: 'pkh(k)', AddressType.WIT: 'wpkh(k)', - AddressType.SH_WIT: 'sh(wpkh(k))'} + AddressType.SH_WIT: 'sh(wpkh(k))', + AddressType.TAP: 'tr(k)'} MULTI_ADDRTYPES = {AddressType.LEGACY: 'sh(multi(k))', AddressType.WIT: 'wsh(multi(k))', @@ -139,6 +141,7 @@ def __init__(self, path: str, password: Optional[str] = None, expert: bool = Fal verinfo = self.jade.get_version_info() self.fw_version = semver.parse_version_info(verinfo['JADE_VERSION']) + self.taproot_anti_exfil = verinfo.get('JADE_TAPROOT_ANTI_EXFIL') is True uninitialized = verinfo['JADE_STATE'] not in ['READY', 'TEMP'] # Check minimum supported firmware version (ignore candidate/build parts) @@ -383,6 +386,10 @@ def sign_tx( """ Sign a transaction with the Blockstream Jade. """ + if any(anti_exfil.is_field(key) for psbt_in in psbt.inputs for key in psbt_in.unknown): + if not self.can_sign_anti_exfil(): + raise UnavailableActionError('Jade firmware does not support Taproot anti-exfil') + # registered_descriptors are intentionally unused because the descriptors were stored by register_descriptor. # Old firmware does not have native PSBT handling - use legacy method if self.PSBT_SUPPORTED_FW_VERSION > self.fw_version.finalize_version(): @@ -392,7 +399,7 @@ def sign_tx( psbt_b64 = psbt.serialize() psbt_bytes = base64.b64decode(psbt_b64.strip()) - # NOTE: sign_psbt() does not use AE signatures, so sticks with default (rfc6979) + # Native PSBT handling preserves the draft anti-exfil transcript fields. psbt_bytes = self.jade.sign_psbt(self._network(), psbt_bytes) psbt_b64 = base64.b64encode(psbt_bytes).decode() @@ -549,11 +556,13 @@ def toggle_passphrase(self) -> bool: @jade_exception def can_sign_taproot(self) -> bool: """ - Blockstream Jade does not currently support Taproot. - - :returns: False, always + Taproot key-path signing is supported from Jade 1.0.34. Require + 1.0.36, which fixes signing transactions with multiple Taproot inputs. """ - return False + return bool(self.fw_version.finalize_version() >= semver.VersionInfo(1, 0, 36)) + + def can_sign_anti_exfil(self) -> bool: + return self.taproot_anti_exfil @jade_exception def register_descriptor(self, name: str, descriptor: 'Descriptor') -> RegisteredDescriptor: diff --git a/hwilib/devices/ledger.py b/hwilib/devices/ledger.py index 87f87505f..0aee7300c 100644 --- a/hwilib/devices/ledger.py +++ b/hwilib/devices/ledger.py @@ -42,7 +42,7 @@ LegacyClient, TransportClient, ) -from .ledger_bitcoin.client_base import ApduException +from .ledger_bitcoin.client_base import AntiExfilNonce, ApduException, PartialSignature from .ledger_bitcoin.exception import NotSupportedError from .ledger_bitcoin.wallet import ( MultisigWallet, @@ -70,6 +70,7 @@ parse_multisig, ) from ..psbt import PSBT +from .. import anti_exfil import logging import re @@ -219,6 +220,8 @@ def legacy_sign_tx() -> PSBT: legacy_input_sigs = client.sign_psbt(psbt, wallet, None) for idx, partial_sig in legacy_input_sigs: + if not isinstance(partial_sig, PartialSignature): + raise DeviceFailureError("Legacy Ledger returned an unexpected signing result") psbt_in = psbt.inputs[idx] psbt_in.partial_sigs[partial_sig.pubkey] = partial_sig.signature return psbt @@ -378,7 +381,19 @@ def process_origin(origin: KeyOriginInfo) -> None: input_sigs = self.client.sign_psbt(psbt2, wallet, wallet_hmac) for idx, yielded in input_sigs: + if idx >= len(psbt2.inputs): + raise DeviceFailureError("Ledger returned an invalid input index") psbt_in = psbt2.inputs[idx] + if isinstance(yielded, AntiExfilNonce): + if anti_exfil.key(anti_exfil.HOST_COMMITMENT, yielded.pubkey) not in psbt_in.unknown: + raise DeviceFailureError("Ledger returned an unsolicited anti-exfil nonce") + nonce_key = anti_exfil.key(anti_exfil.SIGNER_NONCE, yielded.pubkey) + if nonce_key in psbt_in.unknown and psbt_in.unknown[nonce_key] != yielded.nonce: + raise DeviceFailureError("Ledger changed its anti-exfil nonce") + psbt_in.unknown[nonce_key] = yielded.nonce + continue + if not isinstance(yielded, PartialSignature): + raise DeviceFailureError("Ledger returned an unknown signing result") utxo = None if psbt_in.witness_utxo: @@ -401,6 +416,9 @@ def process_origin(origin: KeyOriginInfo) -> None: # Extract the sigs from psbt2 and put them into tx for sig_in, psbt_in in zip(psbt2.inputs, psbt.inputs): + for field_key, value in sig_in.unknown.items(): + if field_key.startswith(anti_exfil.PREFIX): + psbt_in.unknown[field_key] = value psbt_in.partial_sigs.update(sig_in.partial_sigs) psbt_in.tap_script_sigs.update(sig_in.tap_script_sigs) if len(sig_in.tap_key_sig) != 0 and len(psbt_in.tap_key_sig) == 0: @@ -596,6 +614,11 @@ def toggle_passphrase(self) -> bool: """ raise UnavailableActionError('The Ledger Nano S and X do not support toggling passphrase from the host') + def can_sign_anti_exfil(self) -> bool: + # Matching experimental firmware is required. Stock firmware cannot + # satisfy the host's nonce and signature checks. + return isinstance(self.client, NewClient) + @ledger_exception def can_sign_taproot(self) -> bool: """ diff --git a/hwilib/devices/ledger_bitcoin/client.py b/hwilib/devices/ledger_bitcoin/client.py index 406760b95..92cd8876e 100644 --- a/hwilib/devices/ledger_bitcoin/client.py +++ b/hwilib/devices/ledger_bitcoin/client.py @@ -5,7 +5,7 @@ from .command_builder import BitcoinCommandBuilder, BitcoinInsType from ...common import Chain from .client_command import ClientCommandInterpreter -from .client_base import Client, PartialSignature, SignPsbtYieldedObject, TransportClient +from .client_base import AntiExfilNonce, Client, PartialSignature, SignPsbtYieldedObject, TransportClient from .client_legacy import LegacyClient from .errors import UnknownDeviceError from .exception import DeviceException, NotSupportedError @@ -51,6 +51,13 @@ def _make_partial_signature(pubkey_augm: bytes, signature: bytes) -> PartialSign def _decode_signpsbt_yielded_value(res: bytes) -> Tuple[int, SignPsbtYieldedObject]: res_buffer = BytesIO(res) input_index_or_tag = read_varint(res_buffer) + if input_index_or_tag == 0xfffffffd: + input_index = read_varint(res_buffer) + nonce = res_buffer.read(33) + pubkey = res_buffer.read(32) + if len(nonce) != 33 or len(pubkey) != 32 or res_buffer.read(): + raise UnknownDeviceError("Invalid anti-exfil nonce response") + return input_index, AntiExfilNonce(pubkey=pubkey, nonce=nonce) # values follow an encoding without an explicit tag, where the # first element is the input index. All the signature types are implemented diff --git a/hwilib/devices/ledger_bitcoin/client_base.py b/hwilib/devices/ledger_bitcoin/client_base.py index a0a57af62..d6e7819fd 100644 --- a/hwilib/devices/ledger_bitcoin/client_base.py +++ b/hwilib/devices/ledger_bitcoin/client_base.py @@ -65,7 +65,14 @@ class PartialSignature: tapleaf_hash: Optional[bytes] = None -SignPsbtYieldedObject = Union[PartialSignature] +@dataclass(frozen=True) +class AntiExfilNonce: + """Original public nonce returned before the host entropy is revealed.""" + pubkey: bytes + nonce: bytes + + +SignPsbtYieldedObject = Union[PartialSignature, AntiExfilNonce] class Client: def __init__(self, transport_client: TransportClient, chain: Chain = Chain.MAIN) -> None: diff --git a/hwilib/devices/trezor.py b/hwilib/devices/trezor.py index fe175e4a1..b1a8efc0e 100644 --- a/hwilib/devices/trezor.py +++ b/hwilib/devices/trezor.py @@ -16,6 +16,7 @@ Tuple, Union, ) +from .. import anti_exfil as ae from ..descriptor import ( Descriptor, MultisigDescriptor, @@ -28,6 +29,7 @@ DeviceAlreadyInitError, DeviceAlreadyUnlockedError, DeviceConnectionError, + DeviceFailureError, DEVICE_NOT_INITIALIZED, DeviceNotReadyError, NoPasswordError, @@ -374,6 +376,13 @@ def sign_tx( """ if registered_descriptors: raise UnavailableActionError("The Trezor does not support BIP388 policy signing") + requested = ae.requests(psbt) + if requested and not self.can_sign_anti_exfil(): + raise UnavailableActionError("Device firmware does not support Taproot anti-exfil") + # The device's current transaction flow signs every internal input. Require + # all inputs to be targeted so no ordinary signature can escape this flow. + if requested and len(requested) != len(psbt.inputs): + raise BadArgumentError("Trezor anti-exfil requires targeting every input") self._check_unlocked() # Get this devices master key fingerprint @@ -507,6 +516,9 @@ def ignore_input() -> None: our_keys += 1 break + if input_num in requested and (not found or psbt_in.tap_merkle_root): + raise BadArgumentError("Trezor anti-exfil requires an owned BIP86 key-path input") + # Determine if we need to do more passes to sign everything if our_keys > passes: passes = our_keys @@ -524,6 +536,13 @@ def ignore_input() -> None: txinputtype.address_n = path_last_ours to_ignore.append(input_num) + if input_num in requested: + request = requested[input_num] + txinputtype.anti_exfil_host_commitment = request.commitment + txinputtype.anti_exfil_signer_nonce = request.signer_nonce + txinputtype.anti_exfil_host_entropy = request.entropy + txinputtype.anti_exfil_sighash = request.hash_type + # append to inputs inputs.append(txinputtype) @@ -629,6 +648,7 @@ def ignore_input() -> None: # Sign the transaction assert psbt.tx_version is not None + nonces: Dict[int, bytes] = {} signed_tx = btc.sign_tx( client=self.client, coin_name=self.coin_name, @@ -638,12 +658,25 @@ def ignore_input() -> None: version=psbt.tx_version, lock_time=psbt.compute_lock_time(), serialize=False, + anti_exfil_nonces=nonces if requested else None, ) # Each input has one signature for input_num, (psbt_in, sig) in py_enumerate(list(zip(psbt.inputs, signed_tx[0]))): if input_num in to_ignore: continue + if input_num in requested: + request = requested[input_num] + if request.entropy is None: + psbt_in.unknown[ae.key(ae.SIGNER_NONCE, request.pubkey)] = nonces[input_num] + else: + if sig is None: + raise BadArgumentError("Anti-exfil signature missing") + assert request.signer_nonce is not None + if not ae.host_verify(request.pubkey, request.message, sig, request.entropy, request.signer_nonce): + raise DeviceFailureError("Trezor anti-exfil signature proof failed") + psbt_in.tap_key_sig = sig + (b"\x01" if request.hash_type == 1 else b"") + continue for pubkey in psbt_in.hd_keypaths.keys(): fp = psbt_in.hd_keypaths[pubkey].fingerprint if fp == master_fp and pubkey not in psbt_in.partial_sigs: @@ -844,6 +877,11 @@ def toggle_passphrase(self) -> bool: print(PIN_MATRIX_DESCRIPTION, file=sys.stderr) return True + @trezor_exception + def can_sign_anti_exfil(self) -> bool: + self._prepare_device() + return messages.Capability.BitcoinAntiExfil in self.client.features.capabilities + @trezor_exception def can_sign_taproot(self) -> bool: """ diff --git a/hwilib/devices/trezorlib/btc.py b/hwilib/devices/trezorlib/btc.py index 1dff24880..f28642573 100644 --- a/hwilib/devices/trezorlib/btc.py +++ b/hwilib/devices/trezorlib/btc.py @@ -244,6 +244,7 @@ def sign_tx( details: Optional[messages.SignTx] = None, prev_txes: Optional[Dict[bytes, messages.TransactionType]] = None, preauthorized: bool = False, + anti_exfil_nonces: Optional[Dict[int, bytes]] = None, **kwargs: Any, ) -> Tuple[Sequence[Optional[bytes]], bytes]: """Sign a Bitcoin-like transaction. @@ -322,7 +323,19 @@ def copy_tx_meta(tx: messages.TransactionType) -> messages.TransactionType: if res.serialized.signature_index is not None: idx = res.serialized.signature_index + if not 0 <= idx < len(inputs): + raise ValueError("Invalid signature index") + nonce = res.serialized.anti_exfil_nonce + if nonce is not None: + if (anti_exfil_nonces is None or idx in anti_exfil_nonces or + inputs[idx].anti_exfil_host_commitment is None or + inputs[idx].anti_exfil_host_entropy is not None or + res.serialized.signature is not None or len(nonce) != 33): + raise ValueError("Unexpected anti-exfil nonce") + anti_exfil_nonces[idx] = nonce sig = res.serialized.signature + if sig is not None and inputs[idx].anti_exfil_host_commitment is not None and inputs[idx].anti_exfil_host_entropy is None: + raise ValueError("Anti-exfil commitment round returned a signature") if signatures[idx] is not None: raise ValueError(f"Signature for index {idx} already filled") signatures[idx] = sig @@ -374,7 +387,11 @@ def copy_tx_meta(tx: messages.TransactionType) -> messages.TransactionType: if not isinstance(res, messages.TxRequest): raise exceptions.TrezorException("Unexpected message") - for i, sig in zip(inputs, signatures): + for index, (i, sig) in enumerate(zip(inputs, signatures)): + if i.anti_exfil_host_commitment is not None and i.anti_exfil_host_entropy is None: + if anti_exfil_nonces is None or index not in anti_exfil_nonces or sig is not None: + raise exceptions.TrezorException("Anti-exfil nonce is missing") + continue if i.script_type != messages.InputScriptType.EXTERNAL and sig is None: raise exceptions.TrezorException("Some signatures are missing!") diff --git a/hwilib/devices/trezorlib/messages.py b/hwilib/devices/trezorlib/messages.py index 32ff489ad..7ca2590cc 100644 --- a/hwilib/devices/trezorlib/messages.py +++ b/hwilib/devices/trezorlib/messages.py @@ -184,6 +184,7 @@ class SafetyCheckLevel(IntEnum): class Capability(IntEnum): + BitcoinAntiExfil = 100 Bitcoin = 1 Bitcoin_like = 2 Binance = 3 @@ -712,6 +713,10 @@ class TxInput(protobuf.MessageType): 17: protobuf.Field("orig_index", "uint32", repeated=False, required=False), 18: protobuf.Field("decred_staking_spend", "DecredStakingSpendType", repeated=False, required=False), 19: protobuf.Field("script_pubkey", "bytes", repeated=False, required=False), + 100: protobuf.Field("anti_exfil_host_commitment", "bytes", repeated=False, required=False), + 101: protobuf.Field("anti_exfil_signer_nonce", "bytes", repeated=False, required=False), + 102: protobuf.Field("anti_exfil_host_entropy", "bytes", repeated=False, required=False), + 103: protobuf.Field("anti_exfil_sighash", "uint32", repeated=False, required=False), } def __init__( @@ -733,6 +738,10 @@ def __init__( orig_index: Optional["int"] = None, decred_staking_spend: Optional["DecredStakingSpendType"] = None, script_pubkey: Optional["bytes"] = None, + anti_exfil_host_commitment: Optional["bytes"] = None, + anti_exfil_signer_nonce: Optional["bytes"] = None, + anti_exfil_host_entropy: Optional["bytes"] = None, + anti_exfil_sighash: Optional["int"] = None, ) -> None: self.address_n = address_n if address_n is not None else [] self.prev_hash = prev_hash @@ -751,6 +760,11 @@ def __init__( self.decred_staking_spend = decred_staking_spend self.script_pubkey = script_pubkey + self.anti_exfil_host_commitment = anti_exfil_host_commitment + self.anti_exfil_signer_nonce = anti_exfil_signer_nonce + self.anti_exfil_host_entropy = anti_exfil_host_entropy + self.anti_exfil_sighash = anti_exfil_sighash + class TxOutput(protobuf.MessageType): MESSAGE_WIRE_TYPE = None @@ -1082,6 +1096,7 @@ class TxRequestSerializedType(protobuf.MessageType): 1: protobuf.Field("signature_index", "uint32", repeated=False, required=False), 2: protobuf.Field("signature", "bytes", repeated=False, required=False), 3: protobuf.Field("serialized_tx", "bytes", repeated=False, required=False), + 4: protobuf.Field("anti_exfil_nonce", "bytes", repeated=False, required=False), } def __init__( @@ -1090,11 +1105,14 @@ def __init__( signature_index: Optional["int"] = None, signature: Optional["bytes"] = None, serialized_tx: Optional["bytes"] = None, + anti_exfil_nonce: Optional["bytes"] = None, ) -> None: self.signature_index = signature_index self.signature = signature self.serialized_tx = serialized_tx + self.anti_exfil_nonce = anti_exfil_nonce + class TransactionType(protobuf.MessageType): MESSAGE_WIRE_TYPE = None @@ -1168,6 +1186,10 @@ class TxInputType(protobuf.MessageType): 17: protobuf.Field("orig_index", "uint32", repeated=False, required=False), 18: protobuf.Field("decred_staking_spend", "DecredStakingSpendType", repeated=False, required=False), 19: protobuf.Field("script_pubkey", "bytes", repeated=False, required=False), + 100: protobuf.Field("anti_exfil_host_commitment", "bytes", repeated=False, required=False), + 101: protobuf.Field("anti_exfil_signer_nonce", "bytes", repeated=False, required=False), + 102: protobuf.Field("anti_exfil_host_entropy", "bytes", repeated=False, required=False), + 103: protobuf.Field("anti_exfil_sighash", "uint32", repeated=False, required=False), } def __init__( @@ -1189,6 +1211,10 @@ def __init__( orig_index: Optional["int"] = None, decred_staking_spend: Optional["DecredStakingSpendType"] = None, script_pubkey: Optional["bytes"] = None, + anti_exfil_host_commitment: Optional["bytes"] = None, + anti_exfil_signer_nonce: Optional["bytes"] = None, + anti_exfil_host_entropy: Optional["bytes"] = None, + anti_exfil_sighash: Optional["int"] = None, ) -> None: self.address_n = address_n if address_n is not None else [] self.prev_hash = prev_hash @@ -1207,6 +1233,11 @@ def __init__( self.decred_staking_spend = decred_staking_spend self.script_pubkey = script_pubkey + self.anti_exfil_host_commitment = anti_exfil_host_commitment + self.anti_exfil_signer_nonce = anti_exfil_signer_nonce + self.anti_exfil_host_entropy = anti_exfil_host_entropy + self.anti_exfil_sighash = anti_exfil_sighash + class TxOutputBinType(protobuf.MessageType): MESSAGE_WIRE_TYPE = None diff --git a/hwilib/hwwclient.py b/hwilib/hwwclient.py index 32672327c..c3ec70aec 100644 --- a/hwilib/hwwclient.py +++ b/hwilib/hwwclient.py @@ -251,6 +251,14 @@ def toggle_passphrase(self) -> bool: raise NotImplementedError("The HardwareWalletClient base class " "does not implement this method") + def can_sign_anti_exfil(self) -> bool: + """Whether this client implements the draft interactive Taproot protocol. + + Firmware must still return a valid proof; this is not a substitute for + checking each response. Unsupported clients reject before signing. + """ + return False + def can_sign_taproot(self) -> bool: """ Whether the device has a version that can sign for Taproot inputs diff --git a/test/data/anti_exfil_vectors.json b/test/data/anti_exfil_vectors.json new file mode 100644 index 000000000..d9587f070 --- /dev/null +++ b/test/data/anti_exfil_vectors.json @@ -0,0 +1,90 @@ +[ + { + "index": 0, + "secret_key": "0000000000000000000000000000000000000000000000000000000000000001", + "public_key": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "message": "0000000000000000000000000000000000000000000000000000000000000000", + "host_nonce": "0000000000000000000000000000000000000000000000000000000000000001", + "host_commitment": "2547d8aa53b5e89d2bbe2a4d1853cfbae1d98105b57f03e6cf555c141776780a", + "signer_nonce": "0327ce12dc839961dcfdec901a3110809c0890aeb8a3527549ea7e54b5c0f93dac", + "signature": "7fe10d622cf4a75e39715e7fea452228788e27e766faad12a7e4525e779d23bbb94bc96ae14de5c4be23683bf284d8399d8b92943736b443086c356016626141", + "negated": true + }, + { + "index": 1, + "secret_key": "0000000000000000000000000000000000000000000000000000000000000003", + "public_key": "f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9", + "message": "0101010101010101010101010101010101010101010101010101010101010101", + "host_nonce": "0000000000000000000000000000000000000000000000000000000000000002", + "host_commitment": "0317de3d5927275e3dd18a99eb6e314e1f314322c385e1804c3cc0cf17570f96", + "signer_nonce": "02f8dd7048d09602edb02f6fbf743697d6aaab2927e42fcec2e44b706d9d120c42", + "signature": "0a531170e638dc06579794731ea3fea09d79bac7503ebc9ecd04f13d389d3ea70d45a151c85714d42faa504fd86edae959a2253c046e9b8d01034d3610fa2540", + "negated": false + }, + { + "index": 2, + "secret_key": "0000000000000000000000000000000000000000000000000000000000000006", + "public_key": "fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a1460297556", + "message": "0202020202020202020202020202020202020202020202020202020202020202", + "host_nonce": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140", + "host_commitment": "c6a415487f22d3eb78ac30ac560f632039ba9ed41f63390364262ea15278a193", + "signer_nonce": "02db71c56805915075a24af4fe0136d63e0efd3bbfd476e8b93f3c9565290c834b", + "signature": "9341a1c8dc62acd9b624e62d5dd442bf7e0cd92018c797d53c67bc3adab141e2df34807e965ddd487e69dd21cb3790eae74427f7d00d53a35066de1e22581567", + "negated": false + }, + { + "index": 3, + "secret_key": "000000000000000000000000000000000000000000000000000000000000001f", + "public_key": "6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4", + "message": "0303030303030303030303030303030303030303030303030303030303030303", + "host_nonce": "0000000000000000000000000000000000000000000000000000000000000100", + "host_commitment": "eaf14500f7bb699ca7f58bb00827fbf26e17f81770572ff2e87f2115296cdfad", + "signer_nonce": "02cfb27a17b532f5bf0870b766846d1c1b05a9390b0b523ef09d0f73c3463f7070", + "signature": "52a2955a27bd03713517e3342618c15eb36cc37d87eb63cd3f2d884c924d85cae05b5f2b63c217a551141b2f65a5acca15a8eec031b20241dc7a5b0b64e9189c", + "negated": true + }, + { + "index": 4, + "secret_key": "00000000000000000000000000000000000000000000000000000000deadbeef", + "public_key": "76d2fdf1302d1fa9556f4df94ec84cefba6d482e54f47c6c2a238c1baa560f0e", + "message": "0404040404040404040404040404040404040404040404040404040404040404", + "host_nonce": "0000000000000000000000000000000000000000000000000123456789abcdef", + "host_commitment": "1d601741395abb46e03cba6631f48c06a0051d8d7068df9697478eaf3ad96b04", + "signer_nonce": "02108d8a97497aa273bebb4706c1d88b146808809a8b5a42533a5bca9e161bd92a", + "signature": "fc1ee9154aa5541b64b5816fc4c897eb99af8b756e50a9a48d82fe2f64139fbbff8de3339f4d4a5376b79bb272f87a53127b71c3ae06343cc2044eecb96ffad3", + "negated": true + }, + { + "index": 5, + "secret_key": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140", + "public_key": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "message": "0505050505050505050505050505050505050505050505050505050505050505", + "host_nonce": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd036413f", + "host_commitment": "38ebca2170719ecc673123b1cc48d1d91fc3ec435b7187e0e59dcf2c428cb471", + "signer_nonce": "032a62d0682e9f557c9978b4e9f1696f0e3ffbb1af5640b879bb6630fc5a39ba53", + "signature": "49f4d4e4fa2e9c0eb3956df6389ec36337560e2a4f505cd7a3cf183d49665d0e7122e55538755d32016354b70a3aa0721bc384b3ad81fa2286d7ea13affdd1f6", + "negated": false + }, + { + "index": 6, + "secret_key": "000000000000000000000000000000000000000000000000000000000012d687", + "public_key": "8208f5abf04066bad1db9d46f8bcf5a6cc11d0558ab523e7bd3c0ec08bdb782f", + "message": "0606060606060606060606060606060606060606060606060606060606060606", + "host_nonce": "0000000000000000000000000000000000000000000000000000000000000011", + "host_commitment": "ef5fdf83feea1cb5bd266718149fdac62968d991352a39ed7f2c589c8c3aeb88", + "signer_nonce": "021f42904577acbd9e6e1b57f08630efe443b5bf707a9e2e7222650d5fe1129232", + "signature": "b078dd4e584adfd5ec8f04c08198a109597d8eda260e6b674df393ad9109d8902f9e0d7d868629d0349fd2ca3afd3da80d66a6af868fc9b010205b6cb6754817", + "negated": true + }, + { + "index": 7, + "secret_key": "0000000000000000000000000000000000000000000000000000000087654321", + "public_key": "5b151e6105c1cd768e2e70e1b8eb53910cce816f6e50614824177ee7ac4fc846", + "message": "0707070707070707070707070707070707070707070707070707070707070707", + "host_nonce": "0000000000000000000000000000000000000000000000000000000000abcdef", + "host_commitment": "a58864f76cb577c648398cd806964bd1c38de20d9773aaaa244ba990e2fb985e", + "signer_nonce": "034cdab88e1b055ed8572f03c4a44c031a7ea551bfa911311d64b62f7db4cb5e04", + "signature": "8a235e3cf29eda31b0f254c54d1e6e112eab3ec574cfacd1c36d5b25f7ee3400e985a6eaa45b0c171c8fbb2be231b26a4670247c734a4548b269a50976a4a865", + "negated": false + } +] diff --git a/test/data/coldcard-ubuntu24-mpy.patch b/test/data/coldcard-ubuntu24-mpy.patch new file mode 100644 index 000000000..9aea5b4ed --- /dev/null +++ b/test/data/coldcard-ubuntu24-mpy.patch @@ -0,0 +1,31 @@ +diff --git a/mpy-cross/Makefile b/mpy-cross/Makefile +index 971f2f81a..c6a7f5c9e 100644 +--- a/mpy-cross/Makefile ++++ b/mpy-cross/Makefile +@@ -19,5 +19,6 @@ INC += -I$(TOP) + # compiler settings + CWARN = -Wall -Werror + CWARN += -Wextra -Wno-unused-parameter -Wpointer-arith ++CWARN += -Wno-error=dangling-pointer -Wno-error=enum-int-mismatch + CFLAGS = $(INC) $(CWARN) -std=gnu99 $(CFLAGS_MOD) $(COPT) $(CFLAGS_EXTRA) + CFLAGS += -fdata-sections -ffunction-sections -fno-asynchronous-unwind-tables +diff --git a/ports/stm32/Makefile b/ports/stm32/Makefile +index 88faf70ba..ce3421a4c 100644 +--- a/ports/stm32/Makefile ++++ b/ports/stm32/Makefile +@@ -98,4 +98,5 @@ + CFLAGS += $(INC) -Wall -Wpointer-arith -Werror -Wdouble-promotion -Wfloat-conversion -std=gnu99 -nostdlib $(CFLAGS_MOD) $(CFLAGS_EXTRA) ++CFLAGS += -Wno-error=dangling-pointer + CFLAGS += -D$(CMSIS_MCU) + CFLAGS += $(CFLAGS_MCU_$(MCU_SERIES)) + CFLAGS += $(COPT) +diff --git a/ports/unix/Makefile b/ports/unix/Makefile +index 6a936a242..ae68fe11b 100644 +--- a/ports/unix/Makefile ++++ b/ports/unix/Makefile +@@ -40,4 +40,5 @@ INC += -I$(BUILD) + # compiler settings + CWARN = -Wall -Werror + CWARN += -Wextra -Wno-unused-parameter -Wpointer-arith -Wdouble-promotion -Wfloat-conversion ++CWARN += -Wno-error=dangling-pointer -Wno-error=enum-int-mismatch + CFLAGS += $(INC) $(CWARN) -std=gnu99 -DUNIX $(CFLAGS_MOD) $(COPT) -I$(VARIANT_DIR) $(CFLAGS_EXTRA) diff --git a/test/run_tests.py b/test/run_tests.py index 28d8f7a95..3deb86a20 100755 --- a/test/run_tests.py +++ b/test/run_tests.py @@ -4,6 +4,7 @@ import sys import unittest +from test_anti_exfil import TestAntiExfil from test_base58 import TestBase58 from test_bech32 import TestSegwitAddress from test_bip32 import TestBIP32 @@ -12,6 +13,7 @@ from test_device import Bitcoind from test_psbt import TestPSBT from test_trezor import trezor_test_suite +from test_trezor_anti_exfil_transport import TestTrezorAntiExfilTransport from test_ledger import ledger_test_suite from test_digitalbitbox import digitalbitbox_test_suite from test_keepkey import keepkey_test_suite @@ -74,16 +76,33 @@ parser.add_argument('--bitcoind', help='Path to bitcoind', default='work/bitcoin/build/bin/bitcoind') parser.add_argument('--interface', help='Which interface to send commands over', choices=['library', 'cli', 'bindist', 'stdin'], default='library') +parser.add_argument("--anti-exfil", help="Run only draft anti-exfil tests on selected supported devices (requires matching firmware)", action="store_true") +parser.add_argument("--ledger-anti-exfil-core", help="Also test Core-managed anti-exfil (requires bitcoind with -signerantiexfil)", action="store_true") +parser.add_argument("--ledger-anti-exfil", help="Run only draft Taproot anti-exfil Ledger tests (requires matching firmware)", action="store_true") + parser.add_argument("--device-only", help="Only run device tests", action="store_true") parser.set_defaults(trezor_1=None, trezor_t=None, coldcard=None, coldcard_edge=None, keepkey=None, bitbox01=None, ledger=None, ledger_legacy=None, jade=None, bitbox02=None) args = parser.parse_args() +if args.anti_exfil: + if not (args.trezor_1 or args.trezor_t or args.ledger or args.jade or args.coldcard_edge or args.bitbox02): + parser.error("--anti-exfil requires a supported device selection") + if args.all or args.coldcard or args.keepkey or args.bitbox01 or args.ledger_legacy: + parser.error("--anti-exfil was requested for a device without an interactive test suite") + args.device_only = True +if args.ledger_anti_exfil_core: + args.ledger_anti_exfil = True +if args.ledger_anti_exfil: + args.ledger = True + args.device_only = True # Run tests success = True suite = unittest.TestSuite() if not args.device_only: + suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(TestAntiExfil)) + suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(TestTrezorAntiExfilTransport)) suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(TestDescriptor)) suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(TestSegwitAddress)) suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(TestPSBT)) @@ -128,20 +147,20 @@ if success and args.coldcard: success &= coldcard_test_suite(args.coldcard_path, bitcoind, args.interface) if success and args.coldcard_edge: - success &= coldcard_test_suite(args.coldcard_edge_path, bitcoind, args.interface, is_edge=True) + success &= coldcard_test_suite(args.coldcard_edge_path, bitcoind, args.interface, is_edge=True, anti_exfil=args.anti_exfil) if success and args.trezor_1: - success &= trezor_test_suite(args.trezor_1_path, bitcoind, args.interface, '1') + success &= trezor_test_suite(args.trezor_1_path, bitcoind, args.interface, '1', anti_exfil=args.anti_exfil) if success and args.trezor_t: - success &= trezor_test_suite(args.trezor_t_path, bitcoind, args.interface, 't') + success &= trezor_test_suite(args.trezor_t_path, bitcoind, args.interface, 't', anti_exfil=args.anti_exfil) if success and args.keepkey: success &= keepkey_test_suite(args.keepkey_path, bitcoind, args.interface) if success and args.ledger: - success &= ledger_test_suite(args.ledger_path, bitcoind, args.interface, False) + success &= ledger_test_suite(args.ledger_path, bitcoind, args.interface, False, anti_exfil=args.ledger_anti_exfil or args.anti_exfil, anti_exfil_core=args.ledger_anti_exfil_core) if success and args.ledger_legacy: success &= ledger_test_suite(args.ledger_path, bitcoind, args.interface, True) if success and args.jade: - success &= jade_test_suite(args.jade_path, bitcoind, args.interface) + success &= jade_test_suite(args.jade_path, bitcoind, args.interface, anti_exfil=args.anti_exfil) if success and args.bitbox02: - success &= bitbox02_test_suite(args.bitbox02_path, bitcoind, args.interface) + success &= bitbox02_test_suite(args.bitbox02_path, bitcoind, args.interface, anti_exfil=args.anti_exfil) sys.exit(not success) diff --git a/test/setup_environment.sh b/test/setup_environment.sh index bec5755b3..677db267f 100755 --- a/test/setup_environment.sh +++ b/test/setup_environment.sh @@ -68,37 +68,43 @@ set -ex mkdir -p work cd work +# TEMPORARY ANTI-EXFIL: integration branches in Sjors's forks. +# Remove this block and restore upstream versions when the companion PRs land. +# Branch refs deliberately follow signing-only SHA changes before publication. +ANTI_EXFIL_REF="2026/10/taproot-anti-exfil" +TREZOR_REPOSITORY="https://github.com/Sjors/trezor-firmware.git" +JADE_REPOSITORY="https://github.com/Sjors/Jade.git" +BITBOX02_REPOSITORY="https://github.com/Sjors/bitbox02-firmware.git" +COLDCARD_EDGE_REPOSITORY="https://github.com/Sjors/firmware.git" +BITCOIN_REPOSITORY="https://github.com/Sjors/bitcoin.git" + # Pinned firmware versions -TREZOR_VERSION="core/v2.9.6" +TREZOR_VERSION="${ANTI_EXFIL_REF}" BITBOX01_VERSION="v7.1.0" -BITBOX02_VERSION="firmware/v9.24.0" +BITBOX02_VERSION="${ANTI_EXFIL_REF}" KEEPKEY_VERSION="v7.10.0" SPECULOS_VERSION="ed952a54801f59a71399462b5422976d84c817bb" # Requires Python >=3.10 (v0.25.11+) -JADE_VERSION="1.0.36" +JADE_VERSION="${ANTI_EXFIL_REF}" COLDCARD_VERSION="2026-07-31T0519-v5.6.0" -COLDCARD_EDGE_VERSION="2026-07-31T1609-v6.6.0X" +COLDCARD_EDGE_VERSION="${ANTI_EXFIL_REF}" if [[ -n ${build_trezor_1} || -n ${build_trezor_t} ]]; then + # TEMPORARY ANTI-EXFIL: build portable SDL3 libraries for current main. + source ../setup_trezor_sdl3.sh + build_trezor_sdl3 + # Clone trezor-firmware if it doesn't exist, or update it if it does if [ ! -d "trezor-firmware" ]; then - git clone --recursive --depth 1 --shallow-submodules --branch ${TREZOR_VERSION} https://github.com/trezor/trezor-firmware.git + git clone --recursive --shallow-submodules --branch ${TREZOR_VERSION} "${TREZOR_REPOSITORY}" cd trezor-firmware else cd trezor-firmware - git fetch - - # Determine if we need to pull. From https://stackoverflow.com/a/3278427 - UPSTREAM=${1:-'@{u}'} - LOCAL=$(git rev-parse @) - REMOTE=$(git rev-parse "$UPSTREAM") - BASE=$(git merge-base @ "$UPSTREAM") - - if [ $LOCAL = $REMOTE ]; then - echo "Up-to-date" - elif [ $LOCAL = $BASE ]; then - git pull - fi + git remote set-url origin "${TREZOR_REPOSITORY}" + git fetch --no-recurse-submodules origin "${TREZOR_VERSION}" + git checkout --detach FETCH_HEAD + git submodule sync --recursive + git submodule update --init --recursive fi # Remove .venv so that poetry can symlink everything correctly @@ -107,33 +113,29 @@ if [[ -n ${build_trezor_1} || -n ${build_trezor_t} ]]; then if [[ -n ${build_trezor_1} ]]; then # Build trezor one emulator. This is pretty fast, so rebuilding every time is ok # But there should be some caching that makes this faster - uv sync + uv sync --locked cd legacy export EMULATOR=1 TREZOR_TRANSPORT_V1=1 DEBUG_LINK=1 HEADLESS=1 export CC=gcc-12 uv run script/setup uv run script/cibuild + bundle_trezor_sdl3 firmware/trezor.elf libSDL3.so.0 # Delete any emulator.img file find . -name "emulator.img" -exec rm {} \; cd .. fi if [[ -n ${build_trezor_t} ]]; then - # Pin the Rust nightly to the one trezor-firmware ${TREZOR_VERSION} expects - # (see its shell.nix: rust-bin.nightly."2025-04-15"). The rolling "nightly" - # channel has drifted and newer nightlies reject the firmware's - # reexport_test_harness_main attribute with error E0658. - TREZOR_RUST_NIGHTLY="nightly-2025-04-15" - rustup toolchain install ${TREZOR_RUST_NIGHTLY} - rustup default ${TREZOR_RUST_NIGHTLY} - rustup component add rustfmt --toolchain ${TREZOR_RUST_NIGHTLY} - rustup component add rust-src --toolchain ${TREZOR_RUST_NIGHTLY}-x86_64-unknown-linux-gnu - # Build trezor t emulator. This is pretty fast, so rebuilding every time is ok - # But there should be some caching that makes this faster - git am ../../data/trezor-t-build.patch - uv sync + # Current main pins this in flake.nix; keep the host default unchanged. + TREZOR_RUST_NIGHTLY="nightly-2026-03-16" + rustup toolchain install "${TREZOR_RUST_NIGHTLY}" --profile minimal --component rustfmt --component rust-src + uv sync --locked cd core - uv run make build_unix + RUSTUP_TOOLCHAIN="${TREZOR_RUST_NIGHTLY}" uv run make build_unix TREZOR_MODEL=T2T1 PYOPT=0 + # Preserve the path used by HWI and emu.sh despite the xtask output move. + mkdir -p build/unix + cp build/artifacts/latest/firmware-emu build/unix/trezor-emu-core + bundle_trezor_sdl3 build/unix/trezor-emu-core libSDL3.so.0 libSDL3_image.so.0 # Delete any emulator.img file find . -name "trezor.flash" -exec rm {} \; cd .. @@ -147,19 +149,26 @@ if [[ -n ${build_coldcard} || -n ${build_coldcard_edge} ]]; then local coldcard_dir="$2" local coldcard_requirements="$3" local coldcard_multisig_patch="$4" + local coldcard_repository="${5:-https://github.com/Coldcard/firmware.git}" + local coldcard_mpy_patch="${PWD}/../data/coldcard-ubuntu24-mpy.patch" + # TEMPORARY ANTI-EXFIL: match the validated MicroPython compiler. + local CC=gcc-13 + export CC # Clone coldcard firmware if it doesn't exist, or update it if it does coldcard_setup_needed=false if [ ! -d "${coldcard_dir}" ]; then - git clone --depth 1 --branch "${coldcard_version}" https://github.com/Coldcard/firmware.git "${coldcard_dir}" + git clone --branch "${coldcard_version}" "${coldcard_repository}" "${coldcard_dir}" cd "${coldcard_dir}" # Simulator setup initializes the required nested dependencies. git submodule update --init coldcard_setup_needed=true else cd "${coldcard_dir}" - git fetch --tags origin - git checkout --force "${coldcard_version}" + git remote set-url origin "${coldcard_repository}" + git fetch --tags origin "${coldcard_version}" + git checkout --force FETCH_HEAD + git submodule sync --recursive git submodule update --init --force coldcard_setup_needed=true fi @@ -174,7 +183,11 @@ if [[ -n ${build_coldcard} || -n ${build_coldcard_edge} ]]; then if [ "$coldcard_setup_needed" == true ] ; then pushd ../external/micropython # Do not treat new warnings from Ubuntu 24.04's compiler as errors. - git apply ../../ubuntu24_mpy.patch + if [ -f ../../ubuntu24_mpy.patch ]; then + git apply ../../ubuntu24_mpy.patch + else + git apply "${coldcard_mpy_patch}" + fi popd pushd ../external/micropython/mpy-cross/ make @@ -194,7 +207,7 @@ if [[ -n ${build_coldcard} || -n ${build_coldcard_edge} ]]; then do_coldcard_firmware "${COLDCARD_VERSION}" firmware requirements.txt coldcard-multisig.patch fi if [[ -n ${build_coldcard_edge} ]]; then - do_coldcard_firmware "${COLDCARD_EDGE_VERSION}" firmware unix/requirements.txt coldcard-edge-multisig.patch + do_coldcard_firmware "${COLDCARD_EDGE_VERSION}" firmware unix/requirements.txt coldcard-edge-multisig.patch "${COLDCARD_EDGE_REPOSITORY}" fi fi @@ -322,26 +335,19 @@ if [[ -n ${build_jade} ]]; then # Clone Blockstream Jade firmware if it doesn't exist, or update it if it does if [ ! -d "jade" ]; then - git clone --recursive --branch ${JADE_VERSION} https://github.com/Blockstream/Jade.git ./jade + git clone --recursive --branch ${JADE_VERSION} "${JADE_REPOSITORY}" ./jade cd jade else cd jade - git fetch --tags --recurse-submodules - - # Determine if we need to pull. From https://stackoverflow.com/a/3278427 - UPSTREAM=${1:-'@{u}'} - LOCAL=$(git rev-parse @) - REMOTE=$(git rev-parse "$UPSTREAM") - BASE=$(git merge-base @ "$UPSTREAM") - - if [ $LOCAL = $REMOTE ]; then - echo "Jade master up-to-date" - elif [ $LOCAL = $BASE ]; then - git pull - fi - git submodule update --recursive --init + git remote set-url origin "${JADE_REPOSITORY}" + git fetch origin "${JADE_VERSION}" + git checkout --detach FETCH_HEAD + git submodule update --init --recursive fi + # TEMPORARY ANTI-EXFIL: ESP-IDF needs upstream tags for a SemVer version. + git fetch --tags https://github.com/Blockstream/Jade.git + # Deduce the relevant version of esp-idf to use ESP_IDF_BRANCH=$(grep "ARG ESP_IDF_BRANCH=" Dockerfile | cut -d\= -f2) ESP_IDF_COMMIT=$(grep "ARG ESP_IDF_COMMIT=" Dockerfile | cut -d\= -f2) @@ -424,25 +430,19 @@ fi if [[ -n ${build_bitbox02} ]]; then # Clone digital bitbox02 firmware if it doesn't exist, or update it if it does if [ ! -d "bitbox02-firmware" ]; then - git clone --recursive --branch ${BITBOX02_VERSION} https://github.com/BitBoxSwiss/bitbox02-firmware.git + git clone --recursive --branch ${BITBOX02_VERSION} "${BITBOX02_REPOSITORY}" cd bitbox02-firmware else cd bitbox02-firmware - git fetch - - # Determine if we need to pull. From https://stackoverflow.com/a/3278427 - UPSTREAM=${1:-'@{u}'} - LOCAL=$(git rev-parse @) - REMOTE=$(git rev-parse "$UPSTREAM") - BASE=$(git merge-base @ "$UPSTREAM") - - if [ $LOCAL = $REMOTE ]; then - echo "Up-to-date" - elif [ $LOCAL = $BASE ]; then - git pull - fi + git remote set-url origin "${BITBOX02_REPOSITORY}" + git fetch origin "${BITBOX02_VERSION}" + git checkout --detach FETCH_HEAD + git submodule update --init --recursive fi + # TEMPORARY ANTI-EXFIL: version generation needs upstream signed release tags. + git fetch --tags https://github.com/BitBoxSwiss/bitbox02-firmware.git + # Build the simulator. This is cached, but it is also fast CONTAINER_VERSION=$(cat .containerversion) docker pull shiftcrypto/firmware_v2:$CONTAINER_VERSION @@ -452,29 +452,15 @@ if [[ -n ${build_bitbox02} ]]; then fi if [[ -n ${build_bitcoind} ]]; then - # Clone bitcoind if it doesn't exist, or update it if it does - bitcoind_setup_needed=false + # TEMPORARY ANTI-EXFIL: Core's two-round host is needed by integration tests. if [ ! -d "bitcoin" ]; then - git clone https://github.com/bitcoin/bitcoin.git + git clone --single-branch --branch "${ANTI_EXFIL_REF}" "${BITCOIN_REPOSITORY}" bitcoin cd bitcoin - bitcoind_setup_needed=true else cd bitcoin - git reset --hard origin/master - git fetch - - # Determine if we need to pull. From https://stackoverflow.com/a/3278427 - UPSTREAM=${1:-'@{u}'} - LOCAL=$(git rev-parse @) - REMOTE=$(git rev-parse "$UPSTREAM") - BASE=$(git merge-base @ "$UPSTREAM") - - if [ $LOCAL = $REMOTE ]; then - echo "Up-to-date" - elif [ $LOCAL = $BASE ]; then - git pull - bitcoind_setup_needed=true - fi + git remote set-url origin "${BITCOIN_REPOSITORY}" + git fetch origin "${ANTI_EXFIL_REF}" + git checkout --detach FETCH_HEAD fi # Build bitcoind. This is super slow, but it is cached so it runs fairly quickly. diff --git a/test/setup_trezor_sdl3.sh b/test/setup_trezor_sdl3.sh new file mode 100644 index 000000000..07c7da15d --- /dev/null +++ b/test/setup_trezor_sdl3.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# TEMPORARY ANTI-EXFIL: current Trezor main needs SDL3, unavailable in Ubuntu 24.04. + +build_trezor_sdl3() { + local source_root="$PWD/trezor-sdl3" + TREZOR_SDL3_PREFIX="$source_root/prefix" + mkdir -p "$source_root" + + if [ ! -d "$source_root/SDL/.git" ]; then + git clone --depth 1 --branch release-3.4.2 https://github.com/libsdl-org/SDL.git "$source_root/SDL" + fi + test "$(git -C "$source_root/SDL" rev-parse HEAD)" = 683181b47cfabd293e3ea409f838915b8297a4fd + cmake -S "$source_root/SDL" -B "$source_root/SDL/build" -G Ninja \ + -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$TREZOR_SDL3_PREFIX" \ + -DCMAKE_INSTALL_LIBDIR=lib -DSDL_SHARED=ON -DSDL_STATIC=OFF \ + -DSDL_TESTS=OFF -DSDL_EXAMPLES=OFF -DSDL_UNIX_CONSOLE_BUILD=ON \ + -DSDL_X11=OFF -DSDL_WAYLAND=OFF -DSDL_AUDIO=OFF -DSDL_KMSDRM=OFF \ + -DSDL_OPENGL=OFF -DSDL_OPENGLES=OFF -DSDL_VULKAN=OFF + cmake --build "$source_root/SDL/build" --parallel 8 + cmake --install "$source_root/SDL/build" + + if [ ! -d "$source_root/SDL_image/.git" ]; then + git clone --depth 1 --branch release-3.4.0 https://github.com/libsdl-org/SDL_image.git "$source_root/SDL_image" + fi + test "$(git -C "$source_root/SDL_image" rev-parse HEAD)" = ad58ecfc27a1bd09e510ceff8bbbdb1094806476 + cmake -S "$source_root/SDL_image" -B "$source_root/SDL_image/build" -G Ninja \ + -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="$TREZOR_SDL3_PREFIX" \ + -DCMAKE_INSTALL_PREFIX="$TREZOR_SDL3_PREFIX" -DCMAKE_INSTALL_LIBDIR=lib \ + -DSDLIMAGE_VENDORED=OFF -DSDLIMAGE_AVIF=OFF -DSDLIMAGE_JXL=OFF \ + -DSDLIMAGE_WEBP=OFF -DSDLIMAGE_TIF=OFF -DSDLIMAGE_PNG_SHARED=OFF \ + -DSDLIMAGE_JPG_SHARED=OFF -DSDLIMAGE_SAMPLES=OFF -DSDLIMAGE_TESTS=OFF + cmake --build "$source_root/SDL_image/build" --parallel 8 + cmake --install "$source_root/SDL_image/build" + + export PKG_CONFIG_PATH="$TREZOR_SDL3_PREFIX/lib/pkgconfig${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}" +} + +bundle_trezor_sdl3() { + local binary="$1" + shift + local destination + destination="$(dirname "$binary")" + local library + for library in "$@"; do + cp -L "$TREZOR_SDL3_PREFIX/lib/$library" "$destination/$library" + patchelf --set-rpath '$ORIGIN' "$destination/$library" + done + patchelf --set-rpath '$ORIGIN' "$binary" +} diff --git a/test/test_anti_exfil.py b/test/test_anti_exfil.py new file mode 100644 index 000000000..6c095a8ac --- /dev/null +++ b/test/test_anti_exfil.py @@ -0,0 +1,722 @@ +#! /usr/bin/env python3 +# Copyright (c) 2026 The HWI developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. + +import copy +from contextlib import redirect_stderr +import json +import io +import logging +import threading +import traceback +from pathlib import Path +import unittest +from unittest.mock import Mock, patch + +from hwilib import anti_exfil as ae +from hwilib.commands import signtx +from hwilib.errors import ActionCanceledError, BadArgumentError, DeviceBusyError, DeviceConnectionError, DeviceFailureError, UnavailableActionError +from hwilib.key import G, KeyOriginInfo, n, point_mul, point_to_bytes +from hwilib.psbt import PSBT, PartiallySignedInput, PartiallySignedOutput +from hwilib.tx import COutPoint, CTransaction, CTxIn, CTxOut +from hwilib.devices.ledger_bitcoin.client import _decode_signpsbt_yielded_value +from hwilib.devices.ledger_bitcoin.client_base import AntiExfilNonce + + +def signer_nonce(secret, msg, commitment): + """Independent test-only reference signer. Never use for real keys.""" + point = point_mul(G, secret) + if point[1] & 1: + secret = n - secret + aux = ae.tagged_hash("BIP0340/aux", commitment) + masked = bytes(a ^ b for a, b in zip(secret.to_bytes(32, "big"), aux)) + nonce = int.from_bytes(ae.tagged_hash("BIP-EXFIL/nonce", masked + point[0].to_bytes(32, "big") + msg), "big") % n + if nonce == 0: + raise ValueError("Zero reference nonce") + return secret, nonce, point[0].to_bytes(32, "big") + + +def signer_commit(secret, msg, commitment): + _, nonce, _ = signer_nonce(secret, msg, commitment) + return point_to_bytes(point_mul(G, nonce)) + + +def sign(secret, msg, entropy): + secret, nonce, pubkey = signer_nonce(secret, msg, ae.host_commit(entropy)) + nonce = (nonce + int.from_bytes(entropy, "big")) % n + if nonce == 0: + raise ValueError("Zero final nonce") + point = point_mul(G, nonce) + if point[1] & 1: + nonce = n - nonce + r = point[0].to_bytes(32, "big") + challenge = int.from_bytes(ae.tagged_hash("BIP0340/challenge", r + pubkey + msg), "big") % n + return r + ((nonce + challenge * secret) % n).to_bytes(32, "big") + + +class ReferenceClient: + """Test signer with optional mutation of simulated device-controlled replies.""" + + def __init__(self, secret, mutate=None): + self.secret = secret + self.mutate = mutate + + def can_sign_anti_exfil(self): + return True + + def sign_tx(self, psbt, registrations=None): + result = copy.deepcopy(psbt) + for index, request in ae.requests(psbt).items(): + result.inputs[index].unknown[ae.key(ae.SIGNER_NONCE, request.pubkey)] = signer_commit(self.secret, request.message, request.commitment) + if request.entropy is not None: + signature = sign(self.secret, request.message, request.entropy) + result.inputs[index].tap_key_sig = signature + (bytes([request.hash_type]) if request.hash_type else b"") + if self.mutate: + self.mutate(result) + return result + + +class TestAntiExfil(unittest.TestCase): + def setUp(self): + self.secret = 3 + self.pubkey = point_mul(G, self.secret)[0].to_bytes(32, "big") + self.entropy = (5).to_bytes(32, "big") + tx = CTransaction() + tx.nVersion = 2 + tx.vin = [CTxIn(COutPoint(1, 0), nSequence=0xfffffffd)] + tx.vout = [CTxOut(90000, b"\x51\x20" + self.pubkey)] + self.psbt = PSBT(tx) + self.psbt.inputs = [PartiallySignedInput(0)] + self.psbt.outputs = [PartiallySignedOutput(0)] + self.psbt.cache_unsigned_tx_pieces() + self.psbt.inputs[0].witness_utxo = CTxOut(100000, b"\x51\x20" + self.pubkey) + self.psbt.inputs[0].unknown[ae.key(ae.HOST_COMMITMENT, self.pubkey)] = ae.host_commit(self.entropy) + + def round_one(self): + response = signtx(ReferenceClient(self.secret), self.psbt.serialize()) + self.assertFalse(response["signed"]) + result = PSBT() + result.deserialize(response["psbt"]) + return result + + def round_two_request(self): + result = self.round_one() + result.inputs[0].unknown[ae.key(ae.HOST_ENTROPY, self.pubkey)] = self.entropy + return result + + def test_unsupported_client_rejected_before_signing(self): + class UnsupportedClient(ReferenceClient): + def can_sign_anti_exfil(self): + return False + + def sign_tx(self, *args, **kwargs): + raise AssertionError("Unsupported signer was invoked") + + with self.assertRaises(UnavailableActionError): + signtx(UnsupportedClient(self.secret), self.psbt.serialize()) + + def test_bitbox02_capability_wire_field(self): + from hwilib.devices.bitbox02_lib.communication.generated import bitbox02_system_pb2 + + # Upstream uses field 8 for its password-stretching string. Neither that + # field nor the earlier draft's bool at field 8 advertises field 10. + for wire in (b"\x42\x04test", b"\x40\x01"): + with self.subTest(wire=wire): + response = bitbox02_system_pb2.DeviceInfoResponse.FromString(wire) + self.assertFalse(response.taproot_anti_exfil) + response = bitbox02_system_pb2.DeviceInfoResponse.FromString(b"\x42\x04test\x50\x01") + self.assertTrue(response.taproot_anti_exfil) + + def test_shared_vectors(self): + vectors = json.loads((Path(__file__).parent / "data/anti_exfil_vectors.json").read_text()) + for vector in vectors: + with self.subTest(index=vector["index"]): + secret = int(vector["secret_key"], 16) + message = bytes.fromhex(vector["message"]) + entropy = bytes.fromhex(vector["host_nonce"]) + commitment = bytes.fromhex(vector["host_commitment"]) + nonce = bytes.fromhex(vector["signer_nonce"]) + signature = bytes.fromhex(vector["signature"]) + self.assertEqual(ae.host_commit(entropy), commitment) + self.assertEqual(signer_commit(secret, message, commitment), nonce) + self.assertEqual(sign(secret, message, entropy), signature) + self.assertTrue(ae.host_verify(bytes.fromhex(vector["public_key"]), message, signature, entropy, nonce)) + + def test_interactive_roundtrip(self): + for version in (0, 2): + for hash_type in (None, 1): + with self.subTest(version=version, hash_type=hash_type): + request = copy.deepcopy(self.psbt) + if version == 2: + request.convert_to_v2() + request.inputs[0].sighash = hash_type + first = ReferenceClient(self.secret).sign_tx(request) + ae.check_response(request, first, ae.requests(request)) + self.assertFalse(first.inputs[0].tap_key_sig) + first.inputs[0].unknown[ae.key(ae.HOST_ENTROPY, self.pubkey)] = self.entropy + response = signtx(ReferenceClient(self.secret), first.serialize()) + result = PSBT() + result.deserialize(response["psbt"]) + self.assertEqual(result.get_unsigned_tx().serialize_without_witness(), request.get_unsigned_tx().serialize_without_witness()) + self.assertTrue(ae.verify_signature(self.pubkey, ae.signature_hash(request, 0, hash_type or 0), result.inputs[0].tap_key_sig[:64])) + + def test_missing_or_early_response(self): + def remove_nonce(result): + result.inputs[0].unknown.pop(ae.key(ae.SIGNER_NONCE, self.pubkey)) + + def add_signature(result): + result.inputs[0].tap_key_sig = bytes(64) + for mutation in (remove_nonce, add_signature): + with self.assertRaises(DeviceFailureError): + signtx(ReferenceClient(self.secret, mutation), self.psbt.serialize()) + + def test_changed_transaction(self): + def change_sequence(result): + result.tx.vin[0].nSequence ^= 1 + with self.assertRaisesRegex(DeviceFailureError, "changed the transaction"): + signtx(ReferenceClient(self.secret, change_sequence), self.psbt.serialize()) + + def test_commitment_and_nonce_mismatch(self): + request = self.round_two_request() + bad = copy.deepcopy(request) + bad.inputs[0].unknown[ae.key(ae.HOST_ENTROPY, self.pubkey)] = (6).to_bytes(32, "big") + with self.assertRaises(BadArgumentError): + ae.requests(bad) + bad = copy.deepcopy(request) + bad.inputs[0].unknown[ae.key(ae.SIGNER_NONCE, self.pubkey)] = point_to_bytes(point_mul(G, 7)) + with self.assertRaisesRegex(DeviceFailureError, "changed its nonce"): + signtx(ReferenceClient(self.secret), bad.serialize()) + + def test_invalid_signature_or_ignored_entropy(self): + request = self.round_two_request() + + def corrupt_signature(result): + signature = bytearray(result.inputs[0].tap_key_sig) + signature[40] ^= 1 + result.inputs[0].tap_key_sig = bytes(signature) + + def wrong_entropy(result): + result.inputs[0].tap_key_sig = sign(self.secret, ae.signature_hash(request, 0, 0), (6).to_bytes(32, "big")) + for mutation in (corrupt_signature, wrong_entropy): + with self.assertRaisesRegex(DeviceFailureError, "verification failed"): + signtx(ReferenceClient(self.secret, mutation), request.serialize()) + + def test_unprotected_extra_signature(self): + request = self.round_two_request() + + def add_unprotected(result): + result.inputs[0].tap_script_sigs[(self.pubkey, bytes(32))] = bytes(64) + + with self.assertRaisesRegex(DeviceFailureError, "unprotected signature"): + signtx(ReferenceClient(self.secret, add_unprotected), request.serialize()) + + def test_malformed_requests(self): + cases = [] + bad = copy.deepcopy(self.psbt) + bad.inputs[0].unknown[ae.key(ae.HOST_COMMITMENT, self.pubkey)] = bytes(31) + cases.append(bad) + bad = copy.deepcopy(self.psbt) + bad.inputs[0].sighash = 0x81 + cases.append(bad) + bad = copy.deepcopy(self.psbt) + bad.inputs[0].unknown[ae.key(ae.SIGNER_NONCE, self.pubkey)] = b"\x02" + bytes([0xff]) * 32 + cases.append(bad) + bad = copy.deepcopy(self.psbt) + bad.inputs[0].unknown[ae.PREFIX + b"\x03" + self.pubkey] = bytes(32) + cases.append(bad) + for case in cases: + with self.assertRaises(BadArgumentError): + ae.requests(case) + for entropy in (bytes(32), n.to_bytes(32, "big"), bytes(31)): + with self.assertRaises(ValueError): + ae.host_commit(entropy) + + def test_field_location_and_encoding(self): + field = ae.key(ae.HOST_COMMITMENT, self.pubkey) + for output_map in (False, True): + bad = copy.deepcopy(self.psbt) + mapping = bad.outputs[0].unknown if output_map else bad.unknown + mapping[field] = ae.host_commit(self.entropy) + with self.assertRaisesRegex(BadArgumentError, "only allowed in PSBT input"): + ae.requests(bad) + for malformed in (b"\xfc\xfd\x02\x00ae\x00" + self.pubkey, b"\xfd\xfc\x00\x02ae\x00" + self.pubkey): + bad = copy.deepcopy(self.psbt) + bad.inputs[0].unknown = {malformed: ae.host_commit(self.entropy)} + with self.assertRaisesRegex(BadArgumentError, "Malformed"): + ae.requests(bad) + + def outside_input(result): + result.unknown[field] = ae.host_commit(self.entropy) + + with self.assertRaisesRegex(DeviceFailureError, "outside its input map"): + signtx(ReferenceClient(self.secret, outside_input), self.psbt.serialize()) + + def test_nonce_sign_and_infinity(self): + nonce = point_to_bytes(point_mul(G, n - 5)) + self.assertFalse(ae.host_verify(self.pubkey, bytes(32), bytes(64), self.entropy, nonce)) + request = self.round_two_request() + response = ReferenceClient(self.secret).sign_tx(request) + signature = response.inputs[0].tap_key_sig + msg = ae.signature_hash(request, 0, 0) + nonce = request.inputs[0].unknown[ae.key(ae.SIGNER_NONCE, self.pubkey)] + self.assertTrue(ae.host_verify(self.pubkey, msg, signature, self.entropy, nonce)) + flipped = bytes([nonce[0] ^ 1]) + nonce[1:] + self.assertFalse(ae.host_verify(self.pubkey, msg, signature, self.entropy, flipped)) + + def multiple_input_request(self, version): + request = copy.deepcopy(self.psbt) + request.tx.vin.append(CTxIn(COutPoint(2, 0), nSequence=0xfffffffd)) + request.tx.vout[0].nValue = 190000 + request.inputs.append(PartiallySignedInput(0)) + request.cache_unsigned_tx_pieces() + request.inputs[1].witness_utxo = CTxOut(100000, b"\x51\x20" + self.pubkey) + entropies = [(5 + index).to_bytes(32, "big") for index in range(2)] + for index, entropy in enumerate(entropies): + request.inputs[index].unknown[ae.key(ae.HOST_COMMITMENT, self.pubkey)] = ae.host_commit(entropy) + if version == 2: + request.convert_to_v2() + return request, entropies + + def test_multiple_input_receipts(self): + for version in (0, 2): + with self.subTest(version=version): + request, entropies = self.multiple_input_request(version) + first_result = signtx(ReferenceClient(self.secret), request.serialize()) + self.assertFalse(first_result["signed"]) + first = PSBT() + first.deserialize(first_result["psbt"]) + for index, entropy in enumerate(entropies): + first.inputs[index].unknown[ae.key(ae.HOST_ENTROPY, self.pubkey)] = entropy + nonce_field = ae.key(ae.SIGNER_NONCE, self.pubkey) + self.assertNotEqual(first.inputs[0].unknown[nonce_field], first.inputs[1].unknown[nonce_field]) + response = signtx(ReferenceClient(self.secret), first.serialize()) + self.assertTrue(response["signed"]) + signed = PSBT() + signed.deserialize(response["psbt"]) + self.assertTrue(all(len(psbt_in.tap_key_sig) == 64 for psbt_in in signed.inputs)) + + def wrong_second_nonce(result): + result.inputs[1].unknown[nonce_field] = point_to_bytes(point_mul(G, 7)) + + def bad_second_signature(result): + signature = result.inputs[1].tap_key_sig + result.inputs[1].tap_key_sig = signature[:-1] + bytes([signature[-1] ^ 1]) + + def swap_nonces(result): + result.inputs[0].unknown[nonce_field], result.inputs[1].unknown[nonce_field] = result.inputs[1].unknown[nonce_field], result.inputs[0].unknown[nonce_field] + + def changed_second_utxo(result): + result.inputs[1].witness_utxo.nValue -= 1 + + for mutation in (wrong_second_nonce, bad_second_signature, swap_nonces, changed_second_utxo): + with self.subTest(mutation=mutation.__name__): + with self.assertRaises(DeviceFailureError): + signtx(ReferenceClient(self.secret, mutation), first.serialize()) + + def test_partial_input_targeting(self): + for version in (0, 2): + with self.subTest(version=version): + request, entropies = self.multiple_input_request(version) + request.inputs[1].unknown.clear() + first_result = signtx(ReferenceClient(self.secret), request.serialize()) + first = PSBT() + first.deserialize(first_result["psbt"]) + first.inputs[0].unknown[ae.key(ae.HOST_ENTROPY, self.pubkey)] = entropies[0] + response = signtx(ReferenceClient(self.secret), first.serialize()) + signed = PSBT() + signed.deserialize(response["psbt"]) + self.assertTrue(signed.inputs[0].tap_key_sig) + self.assertFalse(signed.inputs[1].tap_key_sig) + + def extra_signature(result): + message = ae.signature_hash(result, 1, 0) + result.inputs[1].tap_key_sig = sign(self.secret, message, (7).to_bytes(32, "big")) + + with self.assertRaisesRegex(DeviceFailureError, "unprotected signature"): + signtx(ReferenceClient(self.secret, extra_signature), first.serialize()) + + def test_only_validated_round_results_are_returned(self): + class InPlaceClient(ReferenceClient): + def sign_tx(self, psbt, registrations=None): + result = super().sign_tx(psbt, registrations) + psbt.__dict__.update(result.__dict__) + return psbt + + metadata_key = bytes.fromhex("fc017800") + added_key = bytes.fromhex("fc017801") + removed_key = bytes.fromhex("fc017802") + for version in (0, 2): + for hash_type in (None, 1): + for client_class in (ReferenceClient, InPlaceClient): + with self.subTest(version=version, sighash=hash_type, client=client_class.__name__): + request, _ = self.multiple_input_request(version) + request.inputs[1].unknown.clear() # An untargeted input. + request.inputs[1].tap_key_sig = bytes([42]) * 64 # Preserve its existing signature. + request.inputs[0].sighash = hash_type + request.xpub[bytes([2]) * 78] = KeyOriginInfo(bytes([1]) * 4, [1]) + for item in request.inputs + request.outputs: + item.tap_internal_key = self.pubkey + for mapping in [request.unknown] + [item.unknown for item in request.inputs + request.outputs]: + mapping[metadata_key] = b"original caller metadata" + mapping[removed_key] = b"retain even if signer removes it" + + def change_metadata(result): + # Exercise global, target/untargeted input and output + # proprietary maps, as well as recognized fields. + for mapping in [result.unknown] + [item.unknown for item in result.inputs + result.outputs]: + mapping[metadata_key] = b"signer-mutated metadata" + mapping[added_key] = b"signer-added seed leak" + del mapping[removed_key] + result.xpub.clear() + for item in result.inputs + result.outputs: + item.tap_internal_key = bytes([42]) * 32 + + for round_number in (1, 2): + with self.subTest(round=round_number): + expected = ReferenceClient(self.secret).sign_tx(request) + response = signtx(client_class(self.secret, change_metadata), request.serialize()) + self.assertEqual(response["psbt"], expected.serialize()) + self.assertEqual(response["signed"], round_number == 2) + if round_number == 1: + request = expected + request.inputs[0].unknown[ae.key(ae.HOST_ENTROPY, self.pubkey)] = self.entropy + else: + target = ae.requests(request)[0] + self.assertTrue(ae.host_verify( + target.pubkey, target.message, expected.inputs[0].tap_key_sig[:64], + target.entropy, target.signer_nonce)) + + def test_native_device_response_metadata(self): + import base64 + import hashlib + from hwilib.common import Chain + from hwilib.devices.coldcard import ColdcardClient + from hwilib.devices.jade import JadeClient + + # Keep the actual drivers and PSBT decoders: substitute only the bytes + # received from a malicious native-PSBT device, within a trusted HWI host. + for device in ("jade", "coldcard"): + for round_number in (1, 2): + for valid_proof in (True, False): + with self.subTest(device=device, round=round_number, valid_proof=valid_proof): + request = copy.deepcopy(self.psbt) if round_number == 1 else self.round_two_request() + metadata_key = bytes.fromhex("fc017800") + added_key = bytes.fromhex("fc017801") + for mapping in [request.unknown, request.inputs[0].unknown, request.outputs[0].unknown]: + mapping[metadata_key] = b"original host metadata" + expected = ReferenceClient(self.secret).sign_tx(request) + response = copy.deepcopy(expected) + for mapping in [response.unknown, response.inputs[0].unknown, response.outputs[0].unknown]: + mapping[metadata_key] = b"device-mutated metadata" + mapping[added_key] = b"device seed leak" + if not valid_proof: + if round_number == 1: + response.inputs[0].unknown[ae.key(ae.SIGNER_NONCE, self.pubkey)] = bytes(33) + else: + response.inputs[0].tap_key_sig = sign(self.secret, ae.signature_hash(request, 0, 0), (7).to_bytes(32, "big")) + request_bytes = base64.b64decode(request.serialize()) + response_bytes = base64.b64decode(response.serialize()) + if device == "jade": + client = JadeClient.__new__(JadeClient) + client.chain = Chain.TEST + client.fw_version = JadeClient.PSBT_SUPPORTED_FW_VERSION + client.taproot_anti_exfil = True + client.jade = Mock() + client.jade.sign_psbt.return_value = response_bytes + else: + client = ColdcardClient.__new__(ColdcardClient) + client._is_edge = True + client.device = Mock(is_simulator=False) + client.device.download_file.return_value = response_bytes + + def send_recv(command, **kwargs): + if command[:4] == b"upld": + return int.from_bytes(command[4:8], "little") + if command == b"sha2": + return hashlib.sha256(request_bytes).digest() + if command[:4] == b"stxn": + return None + if command == b"stok": + return len(response_bytes), hashlib.sha256(response_bytes).digest() + raise AssertionError("Unexpected Coldcard transport request") + + client.device.send_recv.side_effect = send_recv + with redirect_stderr(io.StringIO()), patch("hwilib.devices.coldcard.time.sleep"): + if valid_proof: + result = signtx(client, request.serialize()) + self.assertEqual(result["psbt"], expected.serialize()) + self.assertEqual(result["signed"], round_number == 2) + else: + with self.assertRaises(DeviceFailureError): + signtx(client, request.serialize()) + if device == "jade": + client.jade.sign_psbt.assert_called_once_with("testnet", request_bytes) + else: + client.device.download_file.assert_called_once_with( + len(response_bytes), hashlib.sha256(response_bytes).digest(), file_number=1) + + def test_raw_response_is_validated_before_copying(self): + for round_number in (1, 2): + request = self.psbt if round_number == 1 else self.round_two_request() + + def changed_commitment(result): + result.inputs[0].unknown[ae.key(ae.HOST_COMMITMENT, self.pubkey)] = bytes(32) + + def invalid_nonce(result): + result.inputs[0].unknown[ae.key(ae.SIGNER_NONCE, self.pubkey)] = bytes(33) + + def outside_input(result): + result.outputs[0].unknown[ae.key(ae.HOST_COMMITMENT, self.pubkey)] = bytes(32) + + def invalid_proof(result): + # Still an ordinary valid BIP340 signature in round two, but + # its nonce is unrelated to the original host contribution. + result.inputs[0].tap_key_sig = sign(self.secret, ae.signature_hash(request, 0, 0), (7).to_bytes(32, "big")) + + for mutation in (changed_commitment, invalid_nonce, outside_input, invalid_proof): + with self.subTest(round=round_number, mutation=mutation.__name__): + with self.assertRaises(DeviceFailureError): + signtx(ReferenceClient(self.secret, mutation), request.serialize()) + + def test_ordinary_signer_metadata_is_returned(self): + request = copy.deepcopy(self.psbt) + request.inputs[0].unknown.clear() + + def change_metadata(result): + for mapping in [result.unknown, result.inputs[0].unknown, result.outputs[0].unknown]: + mapping[bytes.fromhex("fc017800")] = b"ordinary signer metadata" + result.inputs[0].tap_key_sig = bytes(64) + + expected = ReferenceClient(self.secret, change_metadata).sign_tx(request) + response = signtx(ReferenceClient(self.secret, change_metadata), request.serialize()) + self.assertTrue(response["signed"]) + self.assertEqual(response["psbt"], expected.serialize()) + + def test_private_device_diagnostics(self): + import cbor2 + from hwilib.devices.jade import jade_exception + from hwilib.devices.jadepy.jade import JadeInterface, device_logger + from hwilib.devices.jadepy.jade_error import JadeError + + request = self.round_two_request() + nonce = request.inputs[0].unknown[ae.key(ae.SIGNER_NONCE, self.pubkey)].hex() + payload = "PRIVATE_TRANSCRIPT " + nonce + " " + self.entropy.hex() + + class ErrorClient(ReferenceClient): + @jade_exception + def sign_tx(self, psbt, registrations=None): + # Use the real SDK decoder's default-level device log path. + wire = cbor2.dumps({"log": ("E " + payload).encode()}) + wire += cbor2.dumps({"id": "1", "result": None}) + JadeInterface.read_cbor_message(io.BytesIO(wire)) + raise JadeError(JadeError.INTERNAL_ERROR, payload, None) + + output = io.StringIO() + handler = logging.StreamHandler(output) + old_handlers, old_level, old_propagate = device_logger.handlers[:], device_logger.level, device_logger.propagate + old_filters = device_logger.filters[:] + device_logger.handlers = [handler] + device_logger.setLevel(logging.WARNING) + device_logger.propagate = False + try: + with self.assertRaises(DeviceFailureError) as raised: + signtx(ErrorClient(self.secret), request.serialize()) + trace = io.StringIO() + traceback.print_exception(type(raised.exception), raised.exception, raised.exception.__traceback__, file=trace) + for private in ("PRIVATE_TRANSCRIPT", nonce, self.entropy.hex()): + self.assertNotIn(private, str(raised.exception)) + self.assertNotIn(private, trace.getvalue()) + self.assertNotIn(private, output.getvalue()) + self.assertTrue(raised.exception.__suppress_context__) + self.assertEqual(device_logger.filters, old_filters) + self.assertFalse(handler.filters) + device_logger.warning("logging restored") + self.assertIn("logging restored", output.getvalue()) + finally: + device_logger.handlers, device_logger.propagate = old_handlers, old_propagate + device_logger.setLevel(old_level) + + def test_private_logging_context(self): + logger = logging.getLogger("hwi.test.anti_exfil.logging") + output = io.StringIO() + handler = logging.StreamHandler(output) + old_handlers, old_level, old_propagate = logger.handlers[:], logger.level, logger.propagate + logger.handlers, logger.propagate = [handler], False + logger.setLevel(logging.WARNING) + try: + for fail in (False, True): + with self.subTest(failure=fail): + failed = False + try: + with ae.private_operation(): + logger.error("PRIVATE_TRANSCRIPT") + worker = threading.Thread(target=logger.warning, args=("unrelated application log",)) + worker.start() + worker.join() + # Nested signing scopes must not unmute the outer one. + with ae.private_operation(): + logger.error("PRIVATE_TRANSCRIPT") + logger.error("PRIVATE_TRANSCRIPT") + if fail: + raise RuntimeError("PRIVATE_TRANSCRIPT") + except DeviceFailureError as error: + failed = True + self.assertTrue(fail) + self.assertNotIn("PRIVATE_TRANSCRIPT", str(error)) + self.assertEqual(failed, fail) + logger.warning("logging restored") + self.assertNotIn("PRIVATE_TRANSCRIPT", output.getvalue()) + self.assertIn("unrelated application log", output.getvalue()) + self.assertIn("logging restored", output.getvalue()) + self.assertFalse(logger.filters) + self.assertFalse(handler.filters) + finally: + logger.handlers, logger.propagate = old_handlers, old_propagate + logger.setLevel(old_level) + + def test_private_last_resort_logging(self): + output = io.StringIO() + handler = logging.StreamHandler(output) + name = "hwi.test.anti_exfil.last_resort" + while name in logging.Logger.manager.loggerDict: + name += ".new" + with patch.object(logging, "lastResort", handler): + with ae.private_operation(): + # A newly imported SDK logger has no logger-level filter yet. + logger = logging.getLogger(name) + logger.propagate = False + logger.error("PRIVATE_TRANSCRIPT") + logger.error("logging restored") + self.assertNotIn("PRIVATE_TRANSCRIPT", output.getvalue()) + self.assertIn("logging restored", output.getvalue()) + self.assertFalse(handler.filters) + logger.propagate = True + + def test_private_error_categories(self): + for category in (ActionCanceledError, UnavailableActionError, DeviceConnectionError, DeviceBusyError, BadArgumentError): + class ErrorClient(ReferenceClient): + def sign_tx(self, psbt, registrations=None): + raise category("PRIVATE_TRANSCRIPT") + + with self.subTest(category=category.__name__): + with self.assertRaises(category) as raised: + signtx(ErrorClient(self.secret), self.psbt.serialize()) + self.assertNotIn("PRIVATE_TRANSCRIPT", str(raised.exception)) + self.assertEqual(raised.exception.get_code(), category("").get_code()) + + def test_ordinary_device_diagnostics(self): + class ErrorClient(ReferenceClient): + def sign_tx(self, psbt, registrations=None): + raise RuntimeError("ordinary SDK diagnostic") + + ordinary = copy.deepcopy(self.psbt) + ordinary.inputs[0].unknown.clear() + with self.assertRaisesRegex(RuntimeError, "ordinary SDK diagnostic"): + signtx(ErrorClient(self.secret), ordinary.serialize()) + + def test_cli_private_client_lifetime(self): + from hwilib import _cli + + request = self.round_two_request() + nonce = request.inputs[0].unknown[ae.key(ae.SIGNER_NONCE, self.pubkey)].hex() + payload = "PRIVATE_RECONNECT " + nonce + " " + self.entropy.hex() + logger = logging.getLogger("hwi.test.anti_exfil.cli") + output = io.StringIO() + handler = logging.StreamHandler(output) + old_handlers, old_level, old_propagate = logger.handlers[:], logger.level, logger.propagate + logger.handlers, logger.propagate = [handler], False + logger.setLevel(logging.WARNING) + try: + for selector in ("path", "fingerprint"): + for stage in ("success", "initialization", "signing", "close", "unsupported"): + calls = [] + + class Client(ReferenceClient): + def __init__(self, secret): + calls.append("initialization") + logger.error(payload) + if stage == "initialization": + raise RuntimeError(payload) + super().__init__(secret) + + def can_sign_anti_exfil(self): + return stage != "unsupported" + + def sign_tx(self, psbt, registrations=None): + logger.error(payload) + if stage == "signing": + raise RuntimeError(payload) + return super().sign_tx(psbt, registrations) + + def close(self): + calls.append("close") + logger.error(payload) + if stage == "close": + raise RuntimeError(payload) + + def factory(*args, **kwargs): + return Client(self.secret) + + args = ["--debug", "-t", "jade"] + args += ["-d", "private-test"] if selector == "path" else ["--fingerprint", "00000001"] + args += ["signtx", request.serialize()] + trace = io.StringIO() + with self.subTest(selector=selector, stage=stage): + with patch("hwilib._cli.get_client", factory), patch("hwilib._cli.find_device", factory), patch("hwilib._cli.logging.basicConfig"), redirect_stderr(trace): + result = _cli.process_commands(args) + if stage == "success": + self.assertNotIn("error", result) + self.assertTrue(result["signed"]) + else: + self.assertIn("error", result) + self.assertNotIn("psbt", result) + if stage == "unsupported": + self.assertEqual(result["code"], -9) + self.assertIn("does not support interactive Taproot anti-exfil", result["error"]) + if stage != "initialization": + self.assertEqual(calls[-1], "close") + for private in ("PRIVATE_RECONNECT", nonce, self.entropy.hex()): + self.assertNotIn(private, result.get("error", "")) + self.assertNotIn(private, trace.getvalue()) + self.assertNotIn(private, output.getvalue()) + logger.warning("logging restored") + self.assertIn("logging restored", output.getvalue()) + self.assertFalse(logger.filters) + self.assertFalse(handler.filters) + finally: + logger.handlers, logger.propagate = old_handlers, old_propagate + logger.setLevel(old_level) + + def test_cli_ordinary_device_diagnostics(self): + from hwilib import _cli + + class Client(ReferenceClient): + def sign_tx(self, psbt, registrations=None): + raise RuntimeError("ordinary SDK diagnostic") + + def close(self): + pass + + ordinary = copy.deepcopy(self.psbt) + ordinary.inputs[0].unknown.clear() + trace = io.StringIO() + with patch("hwilib._cli.get_client", return_value=Client(self.secret)), patch("hwilib._cli.logging.basicConfig"), redirect_stderr(trace): + result = _cli.process_commands(["--debug", "-t", "jade", "-d", "private-test", "signtx", ordinary.serialize()]) + self.assertEqual(result["error"], "ordinary SDK diagnostic") + self.assertIn("ordinary SDK diagnostic", trace.getvalue()) + + def test_ledger_nonce_yield(self): + nonce = signer_commit(self.secret, bytes(32), ae.host_commit(self.entropy)) + encoded = b"\xfe\xfd\xff\xff\xff\x03" + nonce + self.pubkey + index, receipt = _decode_signpsbt_yielded_value(encoded) + self.assertEqual(index, 3) + self.assertIsInstance(receipt, AntiExfilNonce) + self.assertEqual(receipt.nonce, nonce) + self.assertEqual(receipt.pubkey, self.pubkey) + with self.assertRaises(Exception): + _decode_signpsbt_yielded_value(encoded[:-1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/test_bitbox02.py b/test/test_bitbox02.py index 6dae9a907..463946132 100644 --- a/test/test_bitbox02.py +++ b/test/test_bitbox02.py @@ -6,10 +6,18 @@ import time import threading import unittest +from unittest import mock import sys import argparse from hwilib.devices.bitbox02 import Bitbox02Client +from hwilib import anti_exfil as ae +from hwilib.commands import get_client, signtx +from hwilib.common import Chain +from hwilib.errors import HWWError, UnavailableActionError +from hwilib.key import G, point_mul, point_to_bytes +from hwilib.psbt import PSBT, PartiallySignedInput, PartiallySignedOutput +from hwilib.tx import COutPoint, CTransaction, CTxIn, CTxOut from test_device import ( DeviceEmulator, @@ -39,7 +47,8 @@ def __init__(self, simulator): self.supports_ms_display = False self.supports_xpub_ms_display = False self.supports_unsorted_ms = False - self.supports_taproot = False + self.supports_taproot = True + self.supports_anti_exfil = True self.strict_bip48 = False self.include_xpubs = True self.supports_device_multiple_multisig = True @@ -112,15 +121,166 @@ def test_getxpub(self): self.assertEqual(result['chaincode'], '03b0d37df586659fb87145e1d28506e4e2d42777586568d61ecdf6c9e041a0a1') self.assertEqual(result['pubkey'], '03290b94a942a317c3846244f1eb6d67214326c8cfc6d940c823ace57ab818dbbd') -def bitbox02_test_suite(simulator, bitcoind, interface): +class TestBitBox02AntiExfilCapability(DeviceTestCase): + def test_released_firmware_refuses_anti_exfil(self): + # A real device capability query, followed by a valid protocol request. + # No signing RPC may reach firmware that doesn't advertise support. + client = get_client("bitbox02", self.emulator.path, chain=Chain.TEST) + try: + if client.can_sign_anti_exfil(): + self.skipTest("Firmware advertises the draft protocol") + pubkey = point_mul(G, 3)[0].to_bytes(32, "big") + transaction = CTransaction() + transaction.nVersion = 2 + transaction.vin = [CTxIn(COutPoint(1, 0), nSequence=0xfffffffd)] + transaction.vout = [CTxOut(90000, b"\x51\x20" + pubkey)] + request = PSBT(transaction) + request.inputs = [PartiallySignedInput(0)] + request.outputs = [PartiallySignedOutput(0)] + request.cache_unsigned_tx_pieces() + request.inputs[0].witness_utxo = CTxOut(100000, b"\x51\x20" + pubkey) + request.inputs[0].unknown[ae.key(ae.HOST_COMMITMENT, pubkey)] = ae.host_commit((5).to_bytes(32, "big")) + with mock.patch.object(client.init(), "btc_sign", side_effect=AssertionError("Signing RPC must not be called")): + with self.assertRaises(UnavailableActionError): + signtx(client, request.serialize()) + with self.assertRaises(UnavailableActionError): + client.sign_tx(request) + finally: + client.close() + + +class TestBitBox02AntiExfil(DeviceTestCase): + """Real native firmware signing; ordinary BitBox02 firmware must fail capability checks.""" + + def setUp(self): + super().setUp() + self.setup_wallets() + + def test_taproot_anti_exfil(self): + descriptors = self.do_command(self.dev_args + ["getkeypool", "--addr-type", "tap", "0", "10"]) + self.assertIsInstance(descriptors, list, descriptors) + self.assertTrue(all(result["success"] for result in self.wrpc.importdescriptors(descriptors))) + + for psbt_version, hash_type in ((0, None), (0, 1), (2, None), (2, 1)): + with self.subTest(version=psbt_version, sighash=hash_type): + addresses = [self.wrpc.getnewaddress("", "bech32m") for _ in range(2)] + txid = self.wpk_rpc.sendmany("", {address: 1 for address in addresses}) + self.wpk_rpc.generatetoaddress(1, self.wpk_rpc.getnewaddress()) + coins = [coin for coin in self.wrpc.listunspent() if coin["txid"] == txid] + self.assertEqual(len(coins), 2) + funded = self.wrpc.walletcreatefundedpsbt( + [{"txid": txid, "vout": coin["vout"]} for coin in coins], + [{self.wpk_rpc.getnewaddress(): 0.5}], 0, + {"add_inputs": False}, True, + ) + request = PSBT() + request.deserialize(funded["psbt"]) + if psbt_version == 2: + request.convert_to_v2() + self.assertEqual(len(request.inputs), 2) + pubkeys, entropies = [], [] + for index, psbt_in in enumerate(request.inputs): + psbt_in.sighash = hash_type + pubkey = ae.get_utxo(request, index).scriptPubKey[2:] + entropy = (5 + index + 2 * (hash_type or 0)).to_bytes(32, "big") + psbt_in.unknown[ae.key(ae.HOST_COMMITMENT, pubkey)] = ae.host_commit(entropy) + pubkeys.append(pubkey) + entropies.append(entropy) + unsigned = request.get_unsigned_tx().serialize_without_witness() + + first_result = self.do_command(self.dev_args + ["signtx", request.serialize()]) + self.assertNotIn("error", first_result, first_result) + self.assertFalse(first_result["signed"]) + first = PSBT() + first.deserialize(first_result["psbt"]) + nonces = [] + for index, pubkey in enumerate(pubkeys): + self.assertFalse(first.inputs[index].tap_key_sig) + nonce = first.inputs[index].unknown[ae.key(ae.SIGNER_NONCE, pubkey)] + self.assertEqual(len(nonce), 33) + nonces.append(nonce) + self.assertEqual(first.get_unsigned_tx().serialize_without_witness(), unsigned) + self.assertEqual(first.version, request.version) + # Reconnecting cannot change the committed nonce for the same session. + retry_result = self.do_command(self.dev_args + ["signtx", request.serialize()]) + self.assertNotIn("error", retry_result, retry_result) + retry = PSBT() + retry.deserialize(retry_result["psbt"]) + for index, pubkey in enumerate(pubkeys): + self.assertEqual(retry.inputs[index].unknown[ae.key(ae.SIGNER_NONCE, pubkey)], nonces[index]) + first.inputs[index].unknown[ae.key(ae.HOST_ENTROPY, pubkey)] = entropies[index] + + # Intercept a valid transport request after HWI's PSBT preflight. + # Thus malformed entropy/nonces/rounds are rejected by actual + # firmware rather than by the host parser. + for mutation in ("entropy", "nonce", "missing-request", "round", "sighash", "keypath", "early-request"): + client = get_client("bitbox02", self.emulator.path, chain=Chain.TEST) + try: + sdk = client.init() + original_query = sdk._msg_query + + def corrupt(request, *args, **kwargs): + if request.HasField("btc_sign_init") and mutation == "round": + request.btc_sign_init.taproot_anti_exfil_round = 1 + if request.HasField("btc_sign_input") and mutation == "early-request": + if not request.btc_sign_input.HasField("taproot_anti_exfil"): + request.btc_sign_input.taproot_anti_exfil.host_commitment = bytes(32) + if request.HasField("btc_sign_input") and request.btc_sign_input.HasField("taproot_anti_exfil"): + tx_input = request.btc_sign_input + if mutation == "entropy": + tx_input.taproot_anti_exfil.host_entropy = (11).to_bytes(32, "big") + elif mutation == "nonce": + tx_input.taproot_anti_exfil.signer_nonce = point_to_bytes(point_mul(G, 7)) + elif mutation == "missing-request": + tx_input.ClearField("taproot_anti_exfil") + elif mutation == "sighash": + tx_input.taproot_anti_exfil.sighash = 2 + elif mutation == "keypath": + tx_input.keypath[-1] += 1 + return original_query(request, *args, **kwargs) + with mock.patch.object(sdk, "_msg_query", side_effect=corrupt): + with self.assertRaises(HWWError): + client.sign_tx(first) + finally: + client.close() + + signed_result = self.do_command(self.dev_args + ["signtx", first.serialize()]) + self.assertNotIn("error", signed_result, signed_result) + signed = PSBT() + signed.deserialize(signed_result["psbt"]) + self.assertEqual(signed.get_unsigned_tx().serialize_without_witness(), unsigned) + self.assertEqual(signed.version, request.version) + for index, pubkey in enumerate(pubkeys): + signature = signed.inputs[index].tap_key_sig + self.assertEqual(len(signature), 64 if hash_type is None else 65) + self.assertTrue(ae.host_verify(pubkey, ae.signature_hash(request, index, hash_type or 0), + signature[:64], entropies[index], nonces[index])) + # Core v31 finalizes v0; verify v2 preservation before conversion. + if psbt_version == 2: + signed.convert_to_v0() + finalized = self.wrpc.finalizepsbt(signed.serialize()) + self.assertTrue(finalized["complete"]) + self.assertTrue(self.wrpc.testmempoolaccept([finalized["hex"]])[0]["allowed"]) + sent = self.wrpc.sendrawtransaction(finalized["hex"]) + self.wpk_rpc.generatetoaddress(1, self.wpk_rpc.getnewaddress()) + self.assertGreater(self.wrpc.gettransaction(sent)["confirmations"], 0) + + +def bitbox02_test_suite(simulator, bitcoind, interface, anti_exfil=False): dev_emulator = BitBox02Emulator(simulator) signtx_cases = [ - (["segwit"], [], False, False) + (["segwit"], [], False, False), + (["tap"], [], False, False) ] + if anti_exfil: + suite = DeviceTestCase.parameterize(TestBitBox02AntiExfil, bitcoind, emulator=dev_emulator, interface=interface) + return unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite).wasSuccessful() + # Generic Device tests suite = unittest.TestSuite() + suite.addTest(DeviceTestCase.parameterize(TestBitBox02AntiExfilCapability, bitcoind, emulator=dev_emulator, interface=interface)) suite.addTest(DeviceTestCase.parameterize(TestDeviceConnect, bitcoind, emulator=dev_emulator, interface=interface, detect_type=dev_emulator.type)) suite.addTest(DeviceTestCase.parameterize(TestGetKeypool, bitcoind, emulator=dev_emulator, interface=interface)) suite.addTest(DeviceTestCase.parameterize(TestGetDescriptors, bitcoind, emulator=dev_emulator, interface=interface)) diff --git a/test/test_coldcard.py b/test/test_coldcard.py index db978e41e..929a92eb7 100755 --- a/test/test_coldcard.py +++ b/test/test_coldcard.py @@ -2,6 +2,7 @@ import argparse import atexit +import copy import glob import os import signal @@ -12,6 +13,11 @@ from hwilib._cli import process_commands from hwilib import _bech32 as bech32 +from hwilib import anti_exfil as ae +from hwilib.commands import get_client +from hwilib.common import Chain +from hwilib.key import G, point_mul, point_to_bytes +from hwilib.psbt import PSBT from hwilib.devices.coldcard import _firmware_version_supports_psbt_v2 from test_device import ( Bitcoind, @@ -46,12 +52,13 @@ def test_psbt_v2_support(self): class ColdcardSimulator(DeviceEmulator): - def __init__(self, simulator, is_edge=False): + def __init__(self, simulator, is_edge=False, segregate=False): try: os.unlink("coldcard-emulator.stdout") except FileNotFoundError: pass self.simulator = simulator + self.segregate = segregate self.coldcard_log = None self.coldcard_proc = None self.type = "coldcard" @@ -63,6 +70,7 @@ def __init__(self, simulator, is_edge=False): self.supports_xpub_ms_display = False self.supports_unsorted_ms = False self.supports_taproot = is_edge + self.supports_anti_exfil = is_edge self.strict_bip48 = False self.include_xpubs = False self.supports_device_multiple_multisig = True @@ -72,23 +80,44 @@ def __init__(self, simulator, is_edge=False): def start(self): super().start() self.coldcard_log = open("coldcard-emulator.stdout", "a") + # A protected-only run uses the firmware's private socket and never + # probes other emulators via enumerate(). Full suites keep discovery. + if self.segregate: + readme = os.path.join(os.path.dirname(self.simulator), "work", "VirtDisk", "README.md") + if not os.path.exists(readme): + with open(readme, "w") as stream: + stream.write("Isolated simulator runtime\n") # Start the Coldcard simulator self.coldcard_proc = subprocess.Popen( [ "python3", os.path.basename(self.simulator), "--ms", "--headless" - ], + ] + (["--segregate"] if self.segregate else []), cwd=os.path.dirname(self.simulator), stdout=self.coldcard_log, preexec_fn=os.setsid ) + if self.segregate: + self.path = f"/tmp/ckcc-simulator-{self.coldcard_proc.pid}.sock" # Wait for simulator to be up + deadline = time.monotonic() + 60 while True: + if time.monotonic() > deadline: + self.stop() + raise RuntimeError("Coldcard simulator did not become ready") # Prevent CI from lingering until timeout: if self.coldcard_proc.poll() is not None: raise RuntimeError(f"coldcard simulator failed with exit code {self.coldcard_proc.poll()}") try: + if self.segregate: + client = get_client("coldcard", self.path, chain=Chain.TEST) + try: + if client.get_master_fingerprint().hex() == self.fingerprint: + break + finally: + client.close() + continue enum_res = process_commands(["--emulators", "enumerate"]) found = False for dev in enum_res: @@ -180,8 +209,108 @@ def test_display_taproot_address(self): expected_witness = bech32.decode('bcrt', expected) self.assertEqual(displayed_witness, expected_witness) -def coldcard_test_suite(simulator, bitcoind, interface, is_edge=False): - dev_emulator = ColdcardSimulator(simulator, is_edge) +class TestColdcardAntiExfil(DeviceTestCase): + """Opt-in tests requiring a Coldcard Edge firmware built with the draft protocol.""" + + def setUp(self): + super().setUp() + self.dev_args[self.dev_args.index("-d") + 1] = self.emulator.path + self.setup_wallets() + + def test_taproot_anti_exfil(self): + descriptors = self.do_command(self.dev_args + ["getkeypool", "--addr-type", "tap", "0", "5"]) + self.assertIsInstance(descriptors, list, descriptors) + self.assertTrue(all(result["success"] for result in self.wrpc.importdescriptors(descriptors))) + + for hash_type, version in ((None, 0), (0, 2), (1, 0), (1, 2)): + with self.subTest(sighash=hash_type, psbt_version=version): + address = self.wrpc.getnewaddress("", "bech32m") + txid = self.wpk_rpc.sendtoaddress(address, 1) + self.wpk_rpc.generatetoaddress(1, self.wpk_rpc.getnewaddress()) + coins = [coin for coin in self.wrpc.listunspent() if coin["txid"] == txid] + self.assertEqual(len(coins), 1) + funded = self.wrpc.walletcreatefundedpsbt( + [{"txid": txid, "vout": coins[0]["vout"]}], + [{self.wpk_rpc.getnewaddress(): 0.5}], 0, + {"add_inputs": False}, True, + ) + request = PSBT() + request.deserialize(funded["psbt"]) + self.assertEqual(len(request.inputs), 1) + request.inputs[0].sighash = hash_type + if version == 2: + request.convert_to_v2() + pubkey = ae.get_utxo(request, 0).scriptPubKey[2:] + entropy = (5 if hash_type is None else 6).to_bytes(32, "big") + request.inputs[0].unknown[ae.key(ae.HOST_COMMITMENT, pubkey)] = ae.host_commit(entropy) + for mapping in [request.unknown] + [item.unknown for item in request.inputs + request.outputs]: + mapping[bytes.fromhex("fc017800")] = b"original caller metadata" + unsigned = request.get_unsigned_tx().serialize_without_witness() + + first_result = self.do_command(self.dev_args + ["signtx", request.serialize()]) + self.assertNotIn("error", first_result, first_result) + self.assertFalse(first_result["signed"]) + first = PSBT() + first.deserialize(first_result["psbt"]) + expected = copy.deepcopy(request) + self.assertFalse(first.inputs[0].tap_key_sig) + nonce = first.inputs[0].unknown[ae.key(ae.SIGNER_NONCE, pubkey)] + self.assertEqual(len(nonce), 33) + expected.inputs[0].unknown[ae.key(ae.SIGNER_NONCE, pubkey)] = nonce + self.assertEqual(first.serialize(), expected.serialize()) + self.assertEqual(first.get_unsigned_tx().serialize_without_witness(), unsigned) + # Reconnecting between subprocess calls does not lose the device's commitment. + retry_result = self.do_command(self.dev_args + ["signtx", request.serialize()]) + self.assertNotIn("error", retry_result, retry_result) + retry = PSBT() + retry.deserialize(retry_result["psbt"]) + self.assertEqual(retry.inputs[0].unknown[ae.key(ae.SIGNER_NONCE, pubkey)], nonce) + first.inputs[0].unknown[ae.key(ae.HOST_ENTROPY, pubkey)] = entropy + + # Bypass HWI preflight here: the firmware itself must reject a wrong + # opening and a changed round-1 nonce rather than sign anyway. + for bad_entropy, bad_nonce in ((True, False), (False, True)): + bad = copy.deepcopy(first) + if bad_entropy: + bad.inputs[0].unknown[ae.key(ae.HOST_ENTROPY, pubkey)] = (7).to_bytes(32, "big") + if bad_nonce: + bad.inputs[0].unknown[ae.key(ae.SIGNER_NONCE, pubkey)] = point_to_bytes(point_mul(G, 7)) + client = get_client("coldcard", self.emulator.path, chain=Chain.TEST) + try: + client.device.check_mitm() + with self.assertRaises(Exception): + client._sign_tx_once(bad) + finally: + client.close() + + signed_result = self.do_command(self.dev_args + ["signtx", first.serialize()]) + self.assertNotIn("error", signed_result, signed_result) + signed = PSBT() + signed.deserialize(signed_result["psbt"]) + expected = copy.deepcopy(first) + for index, psbt_in in enumerate(signed.inputs): + expected.inputs[index].tap_key_sig = psbt_in.tap_key_sig + self.assertEqual(signed.serialize(), expected.serialize()) + self.assertEqual(signed.get_unsigned_tx().serialize_without_witness(), unsigned) + signature = signed.inputs[0].tap_key_sig + self.assertEqual(len(signature), 64 if hash_type in (None, 0) else 65) + self.assertTrue(ae.host_verify(pubkey, ae.signature_hash(request, 0, hash_type or 0), signature[:64], entropy, nonce)) + finalized = self.wrpc.finalizepsbt(signed.serialize()) + self.assertTrue(finalized["complete"]) + self.assertTrue(self.wrpc.testmempoolaccept([finalized["hex"]])[0]["allowed"]) + sent = self.wrpc.sendrawtransaction(finalized["hex"]) + self.wpk_rpc.generatetoaddress(1, self.wpk_rpc.getnewaddress()) + self.assertGreater(self.wrpc.gettransaction(sent)["confirmations"], 0) + + +# Ledger specific disabled command tests +def coldcard_test_suite(simulator, bitcoind, interface, is_edge=False, anti_exfil=False): + dev_emulator = ColdcardSimulator(simulator, is_edge, segregate=anti_exfil) + if anti_exfil: + if not is_edge: + raise ValueError("Coldcard anti-exfil tests require Edge firmware") + suite = DeviceTestCase.parameterize(TestColdcardAntiExfil, bitcoind, emulator=dev_emulator, interface=interface) + return unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite).wasSuccessful() signtx_cases = [ (["legacy"], [], False, False), diff --git a/test/test_device.py b/test/test_device.py index 4c09c548a..e66fa98e5 100644 --- a/test/test_device.py +++ b/test/test_device.py @@ -20,9 +20,13 @@ from hwilib.descriptor import AddChecksum, parse_descriptor, PubkeyProvider, RegisteredDescriptor from hwilib.key import ExtendedKey, KeyOriginInfo from hwilib.psbt import PSBT +from hwilib.tx import CTxOut +from hwilib import anti_exfil as ae # Class for emulator control class DeviceEmulator(): + supports_anti_exfil = False + def __init__(self): self.type = None self.path = None @@ -59,8 +63,9 @@ def stop(self): # Class for bitcoind control and RPC class Bitcoind(): - def __init__(self, bitcoind_path): + def __init__(self, bitcoind_path, extra_args=None): self.bitcoind_path = bitcoind_path + self.extra_args = extra_args or [] self.datadir = tempfile.mkdtemp() self.rpc = None self.bitcoind_proc = None @@ -76,7 +81,6 @@ def get_free_port(): s.close() return port - self.p2p_port = get_free_port() self.rpc_port = get_free_port() self.bitcoind_proc = subprocess.Popen( @@ -87,9 +91,9 @@ def get_free_port(): "-noprinttoconsole", "-fallbackfee=0.0002", "-keypool=1", - f"-port={self.p2p_port}", + "-listen=0", f"-rpcport={self.rpc_port}" - ] + ] + self.extra_args ) atexit.register(self.cleanup) @@ -608,6 +612,25 @@ def _test_signtx(self, input_types, multisig_types, external, op_return: bool): self.wrpc.sendrawtransaction(final_tx) # Test wrapper to avoid mixed-inputs signing for Ledger + def test_anti_exfil_unsupported(self): + if self.emulator.supports_anti_exfil: + self.skipTest("Interactive signing is exercised by this device's anti-exfil tests") + # A well-formed request must be refused by unsupported drivers, even + # when they would otherwise ignore proprietary PSBT fields. + pubkey = bytes.fromhex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798") + serialized = self.wrpc.createpsbt( + [{"txid": "00" * 32, "vout": 0}], + [{self.wpk_rpc.getnewaddress(): 0.5}], + ) + request = PSBT() + request.deserialize(serialized) + request.inputs[0].witness_utxo = CTxOut(100000000, b"\x51\x20" + pubkey) + request.inputs[0].unknown[ae.key(ae.HOST_COMMITMENT, pubkey)] = ae.host_commit((5).to_bytes(32, "big")) + response = self.do_command(self.dev_args + ["signtx", request.serialize()]) + self.assertEqual(response.get("code"), -9, response) + self.assertIn("does not support interactive Taproot anti-exfil", response.get("error", "")) + self.assertNotIn("psbt", response) + def test_signtx(self): for addrtypes, multisig_types, external, op_return in self.signtx_cases: with self.subTest(addrtypes=addrtypes, multisig_types=multisig_types, external=external, op_return=op_return): @@ -901,7 +924,9 @@ def test_sign_multiple_registered_descriptors(self): descriptors = [] registrations = [] - for account in range(2): + # Account 0 is registered by test_register_descriptor. Some devices + # reject registering that same policy again under a different name. + for account in (1, 2): descriptor, registration = self._register_descriptor(f"HWI_testing_{account}", account) descriptors.append(descriptor) registrations.append(registration) diff --git a/test/test_jade.py b/test/test_jade.py index 741892e80..1750114a3 100755 --- a/test/test_jade.py +++ b/test/test_jade.py @@ -2,6 +2,7 @@ import argparse import atexit +import copy import os import subprocess import logging @@ -9,6 +10,7 @@ import sys import time import unittest +from unittest import mock from test_device import ( Bitcoind, @@ -23,6 +25,13 @@ TestSignTx, ) from hwilib.devices.jadepy.jade import JadeAPI +from hwilib import anti_exfil as ae +from hwilib.commands import get_client, signtx +from hwilib.common import Chain +from hwilib.key import G, point_mul, point_to_bytes +from hwilib.psbt import PSBT, PartiallySignedInput, PartiallySignedOutput +from hwilib.tx import COutPoint, CTransaction, CTxIn, CTxOut +from hwilib.errors import HWWError, UnavailableActionError USE_SIMULATOR = True JADE_PATH = 'tcp:127.0.0.1:30121' if USE_SIMULATOR else None # None -> should search and find plugged unit @@ -49,7 +58,8 @@ def __init__(self, jade_qemu_emulator_path): self.supports_ms_display = False self.supports_xpub_ms_display = False self.supports_unsorted_ms = False - self.supports_taproot = False + self.supports_taproot = True + self.supports_anti_exfil = True self.strict_bip48 = False self.include_xpubs = False self.supports_device_multiple_multisig = True @@ -225,22 +235,171 @@ def test_get_signing_p2shwsh(self): result = self.do_command(self.dev_args + ['displayaddress', descriptor_param]) self.assertEqual(result['address'], '2NAXBEePa5ebo1zTDrtQ9C21QDkkamwczfQ', result) +class TestJadeAntiExfilCapability(DeviceTestCase): + def test_released_firmware_refuses_anti_exfil(self): + # A real device capability query, followed by a valid protocol request. + # No signing RPC may reach firmware that doesn't advertise support. + client = get_client("jade", self.emulator.path, chain=Chain.TEST) + try: + if client.can_sign_anti_exfil(): + self.skipTest("Firmware advertises the draft protocol") + pubkey = point_mul(G, 3)[0].to_bytes(32, "big") + transaction = CTransaction() + transaction.nVersion = 2 + transaction.vin = [CTxIn(COutPoint(1, 0), nSequence=0xfffffffd)] + transaction.vout = [CTxOut(90000, b"\x51\x20" + pubkey)] + request = PSBT(transaction) + request.inputs = [PartiallySignedInput(0)] + request.outputs = [PartiallySignedOutput(0)] + request.cache_unsigned_tx_pieces() + request.inputs[0].witness_utxo = CTxOut(100000, b"\x51\x20" + pubkey) + request.inputs[0].unknown[ae.key(ae.HOST_COMMITMENT, pubkey)] = ae.host_commit((5).to_bytes(32, "big")) + with mock.patch.object(client.jade, "sign_psbt", side_effect=AssertionError("Signing RPC must not be called")): + with self.assertRaises(UnavailableActionError): + signtx(client, request.serialize()) + with self.assertRaises(UnavailableActionError): + client.sign_tx(request) + finally: + client.close() + + +class TestJadeAntiExfil(DeviceTestCase): + """Real QEMU firmware signing; ordinary Jade firmware must fail capability checks.""" + + def setUp(self): + super().setUp() + self.setup_wallets() + + def test_taproot_anti_exfil(self): + descriptors = self.do_command(self.dev_args + ["getkeypool", "--addr-type", "tap", "0", "10"]) + self.assertIsInstance(descriptors, list, descriptors) + self.assertTrue(all(result["success"] for result in self.wrpc.importdescriptors(descriptors))) + + for psbt_version, hash_type in ((0, None), (0, 1), (2, None), (2, 1)): + with self.subTest(version=psbt_version, sighash=hash_type): + addresses = [self.wrpc.getnewaddress("", "bech32m") for _ in range(2)] + txid = self.wpk_rpc.sendmany("", {address: 1 for address in addresses}) + self.wpk_rpc.generatetoaddress(1, self.wpk_rpc.getnewaddress()) + coins = [coin for coin in self.wrpc.listunspent() if coin["txid"] == txid] + self.assertEqual(len(coins), 2) + funded = self.wrpc.walletcreatefundedpsbt( + [{"txid": txid, "vout": coin["vout"]} for coin in coins], + [{self.wpk_rpc.getnewaddress(): 0.5}], 0, + {"add_inputs": False}, True, + ) + request = PSBT() + request.deserialize(funded["psbt"]) + if psbt_version == 2: + request.convert_to_v2() + self.assertEqual(len(request.inputs), 2) + pubkeys, entropies = [], [] + for index, psbt_in in enumerate(request.inputs): + psbt_in.sighash = hash_type + pubkey = ae.get_utxo(request, index).scriptPubKey[2:] + entropy = (5 + index + 2 * (hash_type or 0)).to_bytes(32, "big") + psbt_in.unknown[ae.key(ae.HOST_COMMITMENT, pubkey)] = ae.host_commit(entropy) + pubkeys.append(pubkey) + entropies.append(entropy) + for mapping in [request.unknown] + [item.unknown for item in request.inputs + request.outputs]: + mapping[bytes.fromhex("fc017800")] = b"original caller metadata" + unsigned = request.get_unsigned_tx().serialize_without_witness() + + first_result = self.do_command(self.dev_args + ["signtx", request.serialize()]) + self.assertNotIn("error", first_result, first_result) + self.assertFalse(first_result["signed"]) + first = PSBT() + first.deserialize(first_result["psbt"]) + expected = copy.deepcopy(request) + nonces = [] + for index, pubkey in enumerate(pubkeys): + self.assertFalse(first.inputs[index].tap_key_sig) + nonce = first.inputs[index].unknown[ae.key(ae.SIGNER_NONCE, pubkey)] + self.assertEqual(len(nonce), 33) + nonces.append(nonce) + expected.inputs[index].unknown[ae.key(ae.SIGNER_NONCE, pubkey)] = nonce + self.assertEqual(first.serialize(), expected.serialize()) + self.assertEqual(first.get_unsigned_tx().serialize_without_witness(), unsigned) + self.assertEqual(first.version, request.version) + # Reconnecting cannot change the committed nonce for the same session. + retry_result = self.do_command(self.dev_args + ["signtx", request.serialize()]) + self.assertNotIn("error", retry_result, retry_result) + retry = PSBT() + retry.deserialize(retry_result["psbt"]) + for index, pubkey in enumerate(pubkeys): + self.assertEqual(retry.inputs[index].unknown[ae.key(ae.SIGNER_NONCE, pubkey)], nonces[index]) + first.inputs[index].unknown[ae.key(ae.HOST_ENTROPY, pubkey)] = entropies[index] + + # Bypass commands.signtx preflight: these errors must be caught by + # the actual firmware, before any signature is released. + for mutation in ("entropy", "nonce", "output-key", "existing-signature", "mixed-round"): + bad = copy.deepcopy(first) + if mutation == "entropy": + bad.inputs[0].unknown[ae.key(ae.HOST_ENTROPY, pubkeys[0])] = (11).to_bytes(32, "big") + elif mutation == "nonce": + bad.inputs[0].unknown[ae.key(ae.SIGNER_NONCE, pubkeys[0])] = point_to_bytes(point_mul(G, 7)) + elif mutation == "output-key": + value = bad.inputs[0].unknown.pop(ae.key(ae.HOST_COMMITMENT, pubkeys[0])) + bad.inputs[0].unknown[ae.key(ae.HOST_COMMITMENT, point_mul(G, 7)[0].to_bytes(32, "big"))] = value + elif mutation == "existing-signature": + bad.inputs[0].tap_key_sig = bytes(64) + else: + del bad.inputs[0].unknown[ae.key(ae.HOST_ENTROPY, pubkeys[0])] + del bad.inputs[0].unknown[ae.key(ae.SIGNER_NONCE, pubkeys[0])] + client = get_client("jade", self.emulator.path, chain=Chain.TEST) + try: + with self.assertRaises(HWWError): + client.sign_tx(bad) + finally: + client.close() + + signed_result = self.do_command(self.dev_args + ["signtx", first.serialize()]) + self.assertNotIn("error", signed_result, signed_result) + signed = PSBT() + signed.deserialize(signed_result["psbt"]) + expected = copy.deepcopy(first) + for index, psbt_in in enumerate(signed.inputs): + expected.inputs[index].tap_key_sig = psbt_in.tap_key_sig + self.assertEqual(signed.serialize(), expected.serialize()) + self.assertEqual(signed.get_unsigned_tx().serialize_without_witness(), unsigned) + self.assertEqual(signed.version, request.version) + for index, pubkey in enumerate(pubkeys): + signature = signed.inputs[index].tap_key_sig + self.assertEqual(len(signature), 64 if hash_type is None else 65) + self.assertTrue(ae.host_verify(pubkey, ae.signature_hash(request, index, hash_type or 0), + signature[:64], entropies[index], nonces[index])) + # Core v31 finalizes v0; verify v2 preservation before conversion. + if psbt_version == 2: + signed.convert_to_v0() + finalized = self.wrpc.finalizepsbt(signed.serialize()) + self.assertTrue(finalized["complete"]) + self.assertTrue(self.wrpc.testmempoolaccept([finalized["hex"]])[0]["allowed"]) + sent = self.wrpc.sendrawtransaction(finalized["hex"]) + self.wpk_rpc.generatetoaddress(1, self.wpk_rpc.getnewaddress()) + self.assertGreater(self.wrpc.gettransaction(sent)["confirmations"], 0) + + class TestJadeSignTx(TestSignTx): # disable big psbt as jade simulator can't handle it def test_big_tx(self): pass -def jade_test_suite(emulator, bitcoind, interface): +def jade_test_suite(emulator, bitcoind, interface, anti_exfil=False): dev_emulator = JadeEmulator(emulator) signtx_cases = [ (["legacy"], ["legacy"], True, True), (["segwit"], ["segwit"], True, True), - (["legacy", "segwit"], ["legacy", "segwit"], True, True), + (["legacy", "segwit", "tap"], ["legacy", "segwit"], True, True), + (["tap"], [], False, False), ] + if anti_exfil: + suite = DeviceTestCase.parameterize(TestJadeAntiExfil, bitcoind, emulator=dev_emulator, interface=interface) + return unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite).wasSuccessful() + # Generic Device tests suite = unittest.TestSuite() + suite.addTest(DeviceTestCase.parameterize(TestJadeAntiExfilCapability, bitcoind, emulator=dev_emulator, interface=interface)) suite.addTest(DeviceTestCase.parameterize(TestJadeDisabledCommands, bitcoind, emulator=dev_emulator, interface=interface)) suite.addTest(DeviceTestCase.parameterize(TestDeviceConnect, bitcoind, emulator=dev_emulator, interface=interface, detect_type="jade")) suite.addTest(DeviceTestCase.parameterize(TestJadeGetXpub, bitcoind, emulator=dev_emulator, interface=interface)) diff --git a/test/test_ledger.py b/test/test_ledger.py index 0d783cb44..f455a94ea 100755 --- a/test/test_ledger.py +++ b/test/test_ledger.py @@ -2,9 +2,11 @@ import argparse import atexit +import copy import os import subprocess import signal +import shlex import sys import time import unittest @@ -23,6 +25,11 @@ ) from hwilib._cli import process_commands +from hwilib import anti_exfil as ae +from hwilib.commands import get_client +from hwilib.common import Chain +from hwilib.key import G, point_mul, point_to_bytes +from hwilib.psbt import PSBT class LedgerEmulator(DeviceEmulator): def __init__(self, path, legacy=False): @@ -44,6 +51,7 @@ def __init__(self, path, legacy=False): self.supports_xpub_ms_display = False # Legacy does not multisig address display; tests not updated for new app self.supports_unsorted_ms = False # Legacy does not support unsorted multisig; tests not updated for new app self.supports_taproot = not legacy # Legacy does not support Taproot + self.supports_anti_exfil = not legacy self.strict_bip48 = True self.include_xpubs = True self.supports_device_multiple_multisig = True @@ -55,7 +63,7 @@ def start(self): super().start() automation_path = os.path.abspath("data/speculos-automation.json") app_path = f"./apps/btc-test{'-legacy' if self.legacy else ''}.elf" - os.environ["SPECULOS_APPNAME"] = "Bitcoin Test:1.6.6" if self.legacy else "Bitcoin Test:2.5.0" + os.environ["SPECULOS_APPNAME"] = "Bitcoin Test:1.6.6" if self.legacy else "Bitcoin Test:2.5.1" self.emulator_stderr = open('ledger-emulator.stderr', 'a') # Start the emulator @@ -112,6 +120,126 @@ def stop(self): self.emulator_stdout.close() atexit.unregister(self.stop) +class TestLedgerCoreAntiExfil(DeviceTestCase): + """Actual Core C++ host -> HWI subprocess -> Ledger firmware integration.""" + + def test_core_taproot_anti_exfil(self): + # A separate node makes the host's mandatory anti-exfil setting explicit. + # Its subprocess uses the same installed HWI environment as this harness. + hwi_path = os.path.join(os.path.dirname(sys.executable), "hwi") + signer = shlex.quote(hwi_path) + " --emulators" + node = Bitcoind.create(self.bitcoind.bitcoind_path, extra_args=["-signerantiexfil", "-signer=" + signer]) + try: + node.rpc.createwallet(wallet_name="core_anti_exfil", disable_private_keys=True, external_signer=True) + wallet = node.get_wallet_rpc("core_anti_exfil") + supply = node.get_wallet_rpc("supply") + address = wallet.getnewaddress("", "bech32m") + supply.sendtoaddress(address, 1) + supply.generatetoaddress(1, supply.getnewaddress()) + destination = supply.getnewaddress() + request = wallet.walletcreatefundedpsbt([], [{destination: 0.25}], 0, {}, True)["psbt"] + signed = wallet.walletprocesspsbt(request) + self.assertTrue(signed["complete"]) + psbt = PSBT() + psbt.deserialize(signed["psbt"]) + self.assertTrue(all(not any(field.startswith(ae.PREFIX) for field in item.unknown) for item in psbt.inputs)) + finalized = wallet.finalizepsbt(signed["psbt"]) + self.assertTrue(finalized["complete"]) + self.assertTrue(wallet.testmempoolaccept([finalized["hex"]])[0]["allowed"]) + + # The ordinary wallet send path also invokes both C++ anti-exfil rounds, + # then submits to the local mempool and broadcasts. + sent = wallet.send(outputs={destination: 0.25}) + self.assertTrue(sent["complete"]) + self.assertIn(sent["txid"], node.rpc.getrawmempool()) + supply.generatetoaddress(1, supply.getnewaddress()) + self.assertGreater(wallet.gettransaction(sent["txid"])["confirmations"], 0) + finally: + node.cleanup() + atexit.unregister(node.cleanup) + + +class TestLedgerAntiExfil(DeviceTestCase): + """Opt-in tests requiring a Ledger app built with the draft protocol.""" + + def setUp(self): + super().setUp() + self.setup_wallets() + + def test_taproot_anti_exfil(self): + descriptors = self.do_command(self.dev_args + ["getkeypool", "--addr-type", "tap", "0", "5"]) + self.assertIsInstance(descriptors, list, descriptors) + self.assertTrue(all(result["success"] for result in self.wrpc.importdescriptors(descriptors))) + + for hash_type in (None, 1): + with self.subTest(sighash=hash_type): + address = self.wrpc.getnewaddress("", "bech32m") + txid = self.wpk_rpc.sendtoaddress(address, 1) + self.wpk_rpc.generatetoaddress(1, self.wpk_rpc.getnewaddress()) + coins = [coin for coin in self.wrpc.listunspent() if coin["txid"] == txid] + self.assertEqual(len(coins), 1) + funded = self.wrpc.walletcreatefundedpsbt( + [{"txid": txid, "vout": coins[0]["vout"]}], + [{self.wpk_rpc.getnewaddress(): 0.5}], 0, + {"add_inputs": False}, True, + ) + request = PSBT() + request.deserialize(funded["psbt"]) + self.assertEqual(len(request.inputs), 1) + request.inputs[0].sighash = hash_type + pubkey = ae.get_utxo(request, 0).scriptPubKey[2:] + entropy = (5 if hash_type is None else 6).to_bytes(32, "big") + request.inputs[0].unknown[ae.key(ae.HOST_COMMITMENT, pubkey)] = ae.host_commit(entropy) + unsigned = request.get_unsigned_tx().serialize_without_witness() + + first_result = self.do_command(self.dev_args + ["signtx", request.serialize()]) + self.assertNotIn("error", first_result, first_result) + self.assertFalse(first_result["signed"]) + first = PSBT() + first.deserialize(first_result["psbt"]) + self.assertFalse(first.inputs[0].tap_key_sig) + nonce = first.inputs[0].unknown[ae.key(ae.SIGNER_NONCE, pubkey)] + self.assertEqual(len(nonce), 33) + self.assertEqual(first.get_unsigned_tx().serialize_without_witness(), unsigned) + # Reconnecting between subprocess calls does not lose the device's commitment. + retry_result = self.do_command(self.dev_args + ["signtx", request.serialize()]) + self.assertNotIn("error", retry_result, retry_result) + retry = PSBT() + retry.deserialize(retry_result["psbt"]) + self.assertEqual(retry.inputs[0].unknown[ae.key(ae.SIGNER_NONCE, pubkey)], nonce) + first.inputs[0].unknown[ae.key(ae.HOST_ENTROPY, pubkey)] = entropy + + # Bypass HWI preflight here: the firmware itself must reject a wrong + # opening and a changed round-1 nonce rather than sign anyway. + for bad_entropy, bad_nonce in ((True, False), (False, True)): + bad = copy.deepcopy(first) + if bad_entropy: + bad.inputs[0].unknown[ae.key(ae.HOST_ENTROPY, pubkey)] = (7).to_bytes(32, "big") + if bad_nonce: + bad.inputs[0].unknown[ae.key(ae.SIGNER_NONCE, pubkey)] = point_to_bytes(point_mul(G, 7)) + client = get_client("ledger", self.emulator.path, chain=Chain.TEST) + try: + with self.assertRaises(Exception): + client.sign_tx(bad) + finally: + client.close() + + signed_result = self.do_command(self.dev_args + ["signtx", first.serialize()]) + self.assertNotIn("error", signed_result, signed_result) + signed = PSBT() + signed.deserialize(signed_result["psbt"]) + self.assertEqual(signed.get_unsigned_tx().serialize_without_witness(), unsigned) + signature = signed.inputs[0].tap_key_sig + self.assertEqual(len(signature), 64 if hash_type is None else 65) + self.assertTrue(ae.host_verify(pubkey, ae.signature_hash(request, 0, hash_type or 0), signature[:64], entropy, nonce)) + finalized = self.wrpc.finalizepsbt(signed.serialize()) + self.assertTrue(finalized["complete"]) + self.assertTrue(self.wrpc.testmempoolaccept([finalized["hex"]])[0]["allowed"]) + sent = self.wrpc.sendrawtransaction(finalized["hex"]) + self.wpk_rpc.generatetoaddress(1, self.wpk_rpc.getnewaddress()) + self.assertGreater(self.wrpc.gettransaction(sent)["confirmations"], 0) + + # Ledger specific disabled command tests class TestLedgerDisabledCommands(DeviceTestCase): def test_pin(self): @@ -167,7 +295,7 @@ def test_getxpub(self): self.assertEqual(result['chaincode'], "1067f2a53975faf7ac265be505c1c50ef80a0dcbe1f53f50497c5618e8888dbd") self.assertEqual(result['pubkey'], "035879ca173a9c1b3f300ec587fb4cc6d54d618e30584e425c1b53b98828708f1d") -def ledger_test_suite(emulator, bitcoind, interface, legacy=False): +def ledger_test_suite(emulator, bitcoind, interface, legacy=False, anti_exfil=False, anti_exfil_core=False): dev_emulator = LedgerEmulator(emulator, legacy) signtx_cases = [ @@ -181,6 +309,14 @@ def ledger_test_suite(emulator, bitcoind, interface, legacy=False): (["legacy", "segwit", "tap"], ["legacy", "segwit"], True, legacy), ]) + if anti_exfil: + if legacy: + raise ValueError("Anti-exfil tests require the modern Ledger app") + suite = DeviceTestCase.parameterize(TestLedgerAntiExfil, bitcoind, emulator=dev_emulator, interface=interface) + if anti_exfil_core: + suite.addTest(DeviceTestCase.parameterize(TestLedgerCoreAntiExfil, bitcoind, emulator=dev_emulator, interface=interface)) + return unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite).wasSuccessful() + # Generic Device tests suite = unittest.TestSuite() suite.addTest(DeviceTestCase.parameterize(TestLedgerDisabledCommands, bitcoind, emulator=dev_emulator, interface=interface)) diff --git a/test/test_trezor.py b/test/test_trezor.py index b61c1f00a..32bce1236 100755 --- a/test/test_trezor.py +++ b/test/test_trezor.py @@ -1,6 +1,9 @@ #! /usr/bin/env python3 import argparse +import copy +from dataclasses import replace +from unittest.mock import patch import atexit import json import os @@ -15,6 +18,7 @@ from hwilib.devices.trezorlib.transport.udp import UdpTransport from hwilib.devices.trezorlib.debuglink import TrezorClientDebugLink, load_device_by_mnemonic from hwilib.devices.trezorlib import device, messages +from hwilib.devices.trezorlib.exceptions import TrezorFailure from test_device import ( Bitcoind, DeviceEmulator, @@ -29,6 +33,11 @@ from hwilib._cli import process_commands from hwilib.devices.trezor import TrezorClient +from hwilib import anti_exfil as ae +from hwilib.commands import get_client +from hwilib.common import Chain +from hwilib.key import G, point_mul, point_to_bytes +from hwilib.psbt import PSBT from types import MethodType @@ -41,7 +50,7 @@ def get_pin(self, code=None): return self.debuglink.read_pin_encoded() class TrezorEmulator(DeviceEmulator): - def __init__(self, path, model): + def __init__(self, path, model, anti_exfil=False): assert model in TREZOR_MODELS self.emulator_path = path self.emulator_proc = None @@ -60,6 +69,7 @@ def __init__(self, path, model): self.supports_xpub_ms_display = True self.supports_unsorted_ms = True self.supports_taproot = True + self.supports_anti_exfil = anti_exfil self.strict_bip48 = True self.include_xpubs = False self.supports_device_multiple_multisig = True @@ -95,6 +105,7 @@ def start(self): client.init_device() device.wipe(client) load_device_by_mnemonic(client=client, mnemonic='alcohol woman abuse must during monitor noble actual mixed trade anger aisle', pin='', passphrase_protection=False, label='test') # From Trezor device tests + self.supports_anti_exfil = messages.Capability.BitcoinAntiExfil in client.features.capabilities atexit.register(self.stop) return client @@ -421,12 +432,155 @@ def test_passphrase(self): else: self.fail("Did not enumerate device") -def trezor_test_suite(emulator, bitcoind, interface, model): +class TestTrezorAntiExfil(DeviceTestCase): + """Opt-in tests requiring Trezor firmware built with the draft protocol.""" + + def setUp(self): + super().setUp() + self.setup_wallets() + + def test_taproot_anti_exfil(self): + descriptors = self.do_command(self.dev_args + ["getkeypool", "--addr-type", "tap", "0", "5"]) + self.assertIsInstance(descriptors, list, descriptors) + self.assertTrue(all(result["success"] for result in self.wrpc.importdescriptors(descriptors))) + + for hash_type in (None, 1): + with self.subTest(sighash=hash_type): + address = self.wrpc.getnewaddress("", "bech32m") + txid = self.wpk_rpc.sendtoaddress(address, 1) + self.wpk_rpc.generatetoaddress(1, self.wpk_rpc.getnewaddress()) + coins = [coin for coin in self.wrpc.listunspent() if coin["txid"] == txid] + self.assertEqual(len(coins), 1) + funded = self.wrpc.walletcreatefundedpsbt( + [{"txid": txid, "vout": coins[0]["vout"]}], + [{self.wpk_rpc.getnewaddress(): 0.5}], 0, + {"add_inputs": False}, True, + ) + request = PSBT() + request.deserialize(funded["psbt"]) + self.assertEqual(len(request.inputs), 1) + request.inputs[0].sighash = hash_type + pubkey = ae.get_utxo(request, 0).scriptPubKey[2:] + entropy = (5 if hash_type is None else 6).to_bytes(32, "big") + request.inputs[0].unknown[ae.key(ae.HOST_COMMITMENT, pubkey)] = ae.host_commit(entropy) + unsigned = request.get_unsigned_tx().serialize_without_witness() + + first_result = self.do_command(self.dev_args + ["signtx", request.serialize()]) + self.assertNotIn("error", first_result, first_result) + self.assertFalse(first_result["signed"]) + first = PSBT() + first.deserialize(first_result["psbt"]) + self.assertFalse(first.inputs[0].tap_key_sig) + nonce = first.inputs[0].unknown[ae.key(ae.SIGNER_NONCE, pubkey)] + self.assertEqual(len(nonce), 33) + self.assertEqual(first.get_unsigned_tx().serialize_without_witness(), unsigned) + # Reconnecting between subprocess calls does not lose the device's commitment. + retry_result = self.do_command(self.dev_args + ["signtx", request.serialize()]) + self.assertNotIn("error", retry_result, retry_result) + retry = PSBT() + retry.deserialize(retry_result["psbt"]) + self.assertEqual(retry.inputs[0].unknown[ae.key(ae.SIGNER_NONCE, pubkey)], nonce) + first.inputs[0].unknown[ae.key(ae.HOST_ENTROPY, pubkey)] = entropy + + # Bypass HWI preflight here: the firmware itself must reject a wrong + # opening and a changed round-1 nonce rather than sign anyway. + for bad_entropy, bad_nonce in ((True, False), (False, True)): + bad = copy.deepcopy(first) + if bad_entropy: + bad.inputs[0].unknown[ae.key(ae.HOST_ENTROPY, pubkey)] = (7).to_bytes(32, "big") + if bad_nonce: + bad.inputs[0].unknown[ae.key(ae.SIGNER_NONCE, pubkey)] = point_to_bytes(point_mul(G, 7)) + # Keep the host's valid preflight result, but change the + # fields sent to the device to exercise firmware checks. + valid = ae.requests(first) + request_fields = valid[0] + forged = replace( + request_fields, + entropy=bad.inputs[0].unknown[ae.key(ae.HOST_ENTROPY, pubkey)], + signer_nonce=bad.inputs[0].unknown[ae.key(ae.SIGNER_NONCE, pubkey)], + ) + client = get_client("trezor", self.emulator.path, chain=Chain.TEST) + try: + with patch.object(ae, "requests", return_value={0: forged}): + with self.assertRaises(TrezorFailure): + client.sign_tx(bad) + finally: + client.close() + + signed_result = self.do_command(self.dev_args + ["signtx", first.serialize()]) + self.assertNotIn("error", signed_result, signed_result) + signed = PSBT() + signed.deserialize(signed_result["psbt"]) + self.assertEqual(signed.get_unsigned_tx().serialize_without_witness(), unsigned) + signature = signed.inputs[0].tap_key_sig + self.assertEqual(len(signature), 64 if hash_type is None else 65) + self.assertTrue(ae.host_verify(pubkey, ae.signature_hash(request, 0, hash_type or 0), signature[:64], entropy, nonce)) + finalized = self.wrpc.finalizepsbt(signed.serialize()) + self.assertTrue(finalized["complete"]) + self.assertTrue(self.wrpc.testmempoolaccept([finalized["hex"]])[0]["allowed"]) + sent = self.wrpc.sendrawtransaction(finalized["hex"]) + self.wpk_rpc.generatetoaddress(1, self.wpk_rpc.getnewaddress()) + self.assertGreater(self.wrpc.gettransaction(sent)["confirmations"], 0) + + def test_two_input_anti_exfil(self): + descriptors = self.do_command(self.dev_args + ["getkeypool", "--addr-type", "tap", "0", "5"]) + self.assertTrue(all(item["success"] for item in self.wrpc.importdescriptors(descriptors))) + addresses = [self.wrpc.getnewaddress("", "bech32m") for _ in range(2)] + txid = self.wpk_rpc.sendmany("", {address: 1 for address in addresses}) + self.wpk_rpc.generatetoaddress(1, self.wpk_rpc.getnewaddress()) + coins = [coin for coin in self.wrpc.listunspent() if coin["txid"] == txid] + self.assertEqual(len(coins), 2) + funded = self.wrpc.walletcreatefundedpsbt( + [{"txid": txid, "vout": coin["vout"]} for coin in coins], + [{self.wpk_rpc.getnewaddress(): 1.5}], 0, {"add_inputs": False}, True) + request = PSBT() + request.deserialize(funded["psbt"]) + pubkeys = [ae.get_utxo(request, i).scriptPubKey[2:] for i in range(2)] + entropies = [(10 + i).to_bytes(32, "big") for i in range(2)] + for i, psbt_in in enumerate(request.inputs): + psbt_in.sighash = i # DEFAULT and ALL in the same transaction. + psbt_in.unknown[ae.key(ae.HOST_COMMITMENT, pubkeys[i])] = ae.host_commit(entropies[i]) + result = self.do_command(self.dev_args + ["signtx", request.serialize()]) + self.assertNotIn("error", result, result) + self.assertFalse(result["signed"]) + first = PSBT() + first.deserialize(result["psbt"]) + nonces = [] + for i, psbt_in in enumerate(first.inputs): + self.assertFalse(psbt_in.tap_key_sig) + nonces.append(psbt_in.unknown[ae.key(ae.SIGNER_NONCE, pubkeys[i])]) + psbt_in.unknown[ae.key(ae.HOST_ENTROPY, pubkeys[i])] = entropies[i] + self.assertNotEqual(nonces[0], nonces[1]) + # Mixing valid receipts between inputs must fail inside the firmware. + mixed = copy.deepcopy(first) + for i in range(2): + mixed.inputs[i].unknown[ae.key(ae.SIGNER_NONCE, pubkeys[i])] = nonces[1 - i] + client = get_client("trezor", self.emulator.path, chain=Chain.TEST) + try: + with self.assertRaises(TrezorFailure): + client.sign_tx(mixed) + finally: + client.close() + result = self.do_command(self.dev_args + ["signtx", first.serialize()]) + self.assertNotIn("error", result, result) + self.assertTrue(result["signed"]) + signed = PSBT() + signed.deserialize(result["psbt"]) + for i, psbt_in in enumerate(signed.inputs): + self.assertEqual(len(psbt_in.tap_key_sig), 64 + i) + self.assertTrue(ae.host_verify(pubkeys[i], ae.signature_hash(request, i, i), + psbt_in.tap_key_sig[:64], entropies[i], nonces[i])) + finalized = self.wrpc.finalizepsbt(signed.serialize()) + self.assertTrue(finalized["complete"]) + self.assertTrue(self.wrpc.testmempoolaccept([finalized["hex"]])[0]["allowed"]) + + +def trezor_test_suite(emulator, bitcoind, interface, model, anti_exfil=False): assert model in TREZOR_MODELS # Redirect stderr to /dev/null as it's super spammy sys.stderr = open(os.devnull, 'w') - dev_emulator = TrezorEmulator(emulator, model) + dev_emulator = TrezorEmulator(emulator, model, anti_exfil) signtx_cases = [ (["legacy"], ["legacy"], False, True), @@ -438,6 +592,11 @@ def trezor_test_suite(emulator, bitcoind, interface, model): # Generic Device tests suite = unittest.TestSuite() + if anti_exfil: + suite.addTest(DeviceTestCase.parameterize(TestTrezorAntiExfil, bitcoind, emulator=dev_emulator, interface=interface)) + result = unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite) + sys.stderr = sys.__stderr__ + return result.wasSuccessful() suite.addTest(DeviceTestCase.parameterize(TestDeviceConnect, bitcoind, emulator=dev_emulator, interface=interface, detect_type="trezor")) suite.addTest(DeviceTestCase.parameterize(TestGetDescriptors, bitcoind, emulator=dev_emulator, interface=interface)) suite.addTest(DeviceTestCase.parameterize(TestGetKeypool, bitcoind, emulator=dev_emulator, interface=interface)) diff --git a/test/test_trezor_anti_exfil_transport.py b/test/test_trezor_anti_exfil_transport.py new file mode 100644 index 000000000..37a7d3f6a --- /dev/null +++ b/test/test_trezor_anti_exfil_transport.py @@ -0,0 +1,121 @@ +"""Unit tests for Trezor's nonce receipt wire transport.""" +from io import BytesIO +import unittest +from types import SimpleNamespace +from unittest.mock import patch +import test_anti_exfil as fixtures +from hwilib import anti_exfil as ae +from hwilib.common import Chain +from hwilib.devices.trezor import TrezorClient +from hwilib.errors import BadArgumentError, DeviceFailureError +from hwilib.key import KeyOriginInfo +from hwilib._base58 import get_xpub_fingerprint +from hwilib.devices.trezorlib import btc, messages, protobuf + + +class Client: + def __init__(self, receipt): + self.receipt = receipt + + def open(self): + pass + + def close(self): + pass + + def call(self, request): + return messages.TxRequest(request_type=messages.RequestType.TXFINISHED, + serialized=self.receipt) + + +class TestTrezorAntiExfilTransport(unittest.TestCase): + def setUp(self): + self.input = messages.TxInputType( + prev_hash=bytes(32), prev_index=0, + script_type=messages.InputScriptType.SPENDTAPROOT, + anti_exfil_host_commitment=bytes([1]) * 32, + ) + self.nonce = bytes([3]) + bytes([2]) * 32 + + def test_ordinary_input_has_no_anti_exfil_fields(self): + ordinary = messages.TxInputType(prev_hash=bytes(32), prev_index=0) + encoded = BytesIO() + protobuf.dump_message(encoded, ordinary) + decoded = protobuf.load_message(BytesIO(encoded.getvalue()), messages.TxInputType) + for name in ("anti_exfil_host_commitment", "anti_exfil_signer_nonce", + "anti_exfil_host_entropy", "anti_exfil_sighash"): + self.assertIsNone(getattr(ordinary, name)) + self.assertIsNone(getattr(decoded, name)) + + def test_wire_roundtrip(self): + self.input.anti_exfil_signer_nonce = self.nonce + self.input.anti_exfil_host_entropy = bytes([4]) * 32 + self.input.anti_exfil_sighash = 1 + encoded = BytesIO() + protobuf.dump_message(encoded, self.input) + decoded = protobuf.load_message(BytesIO(encoded.getvalue()), messages.TxInputType) + for name in ("anti_exfil_host_commitment", "anti_exfil_signer_nonce", + "anti_exfil_host_entropy", "anti_exfil_sighash"): + self.assertEqual(getattr(decoded, name), getattr(self.input, name)) + + def test_receipt_is_not_signature(self): + nonces = {} + client = Client(messages.TxRequestSerializedType(signature_index=0, + anti_exfil_nonce=self.nonce)) + signatures, transaction = btc.sign_tx(client, "Bitcoin", [self.input], [], + anti_exfil_nonces=nonces, serialize=False) + self.assertEqual(signatures, [None]) + self.assertEqual(transaction, b"") + self.assertEqual(nonces, {0: self.nonce}) + + def test_direct_driver_checks_signature_proof(self): + fixture = fixtures.TestAntiExfil() + fixture.setUp() + psbt = fixture.round_two_request() + xpub = "tpubDCknDegFqAdP4V2AhHhs635DPe8N1aTjfKE9m2UFbdej8zmeNbtqDzK59SxnsYSRSx5uS3AujbwgANUiAk4oHmDNUKoGGkWWUY6c48WgjEx" + psbt.inputs[0].tap_internal_key = fixture.pubkey + psbt.inputs[0].tap_bip32_paths[fixture.pubkey] = ([], KeyOriginInfo( + get_xpub_fingerprint(xpub), [0x80000056, 0x80000001, 0x80000000, 0, 0])) + request = ae.requests(psbt)[0] + client = TrezorClient.__new__(TrezorClient) + client.chain = Chain.TEST + client.coin_name = "Testnet" + client.client = object() + # A malicious firmware can return a valid signature whose nonce ignores + # the originally recorded host transcript. The direct library API must + # reject this too, without relying on commands.signtx's outer verifier. + signature = fixtures.sign(fixture.secret, request.message, (7).to_bytes(32, "big")) + self.assertTrue(ae.verify_signature(fixture.pubkey, request.message, signature)) + with patch.object(client, "_check_unlocked"), patch.object(client, "can_sign_anti_exfil", return_value=True): + with patch.object(btc, "get_public_node", return_value=SimpleNamespace(xpub=xpub)): + with patch.object(btc, "sign_tx", return_value=([signature], b"")): + with self.assertRaises(DeviceFailureError): + client.sign_tx(psbt) + self.assertFalse(psbt.inputs[0].tap_key_sig) + # Unowned protected targets must be rejected before the ordinary + # external-input fallback can ask the device for an unrelated signature. + psbt.inputs[0].tap_bip32_paths.clear() + with patch.object(client, "_check_unlocked"), patch.object(client, "can_sign_anti_exfil", return_value=True): + with patch.object(client, "_supports_external", return_value=True): + with patch.object(btc, "get_public_node", return_value=SimpleNamespace(xpub=xpub)): + with patch.object(btc, "sign_tx", return_value=([signature], b"")) as signer: + with self.assertRaises(BadArgumentError): + client.sign_tx(psbt) + signer.assert_not_called() + + def test_invalid_receipts(self): + for receipt in ( + messages.TxRequestSerializedType(signature_index=1, anti_exfil_nonce=self.nonce), + messages.TxRequestSerializedType(signature_index=0, anti_exfil_nonce=bytes(32)), + messages.TxRequestSerializedType(signature_index=0, signature=bytes(64)), + messages.TxRequestSerializedType(signature_index=0, signature=bytes(64), anti_exfil_nonce=self.nonce), + messages.TxRequestSerializedType(), + ): + with self.subTest(receipt=receipt): + with self.assertRaises(Exception): + btc.sign_tx(Client(receipt), "Bitcoin", [self.input], [], + anti_exfil_nonces={}, serialize=False) + + +if __name__ == "__main__": + unittest.main()