diff --git a/requirements.txt b/requirements.txt index 71130595f..db888dcda 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,14 @@ +# Runtime dependencies, pinned by version or by commit. +# +# NOT hash-locked, unlike l10n/requirements-l10n.txt. Upstream hash-locked this +# file in SeedSigner/seedsigner#1018, but the fork cannot follow yet: +# specter-card is a `git+` URL, and pip's hash-checking mode cannot verify a git +# checkout at all. TODO: republish specter-card as a commit-pinned archive, then +# hash-lock this file and tests/requirements.txt and collapse CI back to one +# `pip install` invocation. +# +# Pillow and qrcode are deliberately pinned differently from upstream; don't +# "resync" them without checking why. embit==0.8.0 Pillow>=10.4.0 pyzbar @ https://github.com/seedsigner/pyzbar/archive/c3c237821c6a20b17953efe59b90df0b514a1c03.zip diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 0ac2909df..f79031461 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -114,6 +114,38 @@ class RejectCode: TX_MODIFIABLE = "TX_MODIFIABLE" UNDISPLAYABLE_OUTPUT = "UNDISPLAYABLE_OUTPUT" + # An output scope claims this seed's fingerprint on a key the seed does not + # derive. This is not a psbt that merely fails to be ours. A fingerprint is + # coordinator-supplied metadata, so this is a psbt asserting that a key + # belongs to this seed when it does not. On an output that assertion is how a + # fake change output is dressed up as the user's own, so it is treated as an + # attack. + FORGED_OUTPUT_OWNERSHIP = "FORGED_OUTPUT_OWNERSHIP" + + # The same false claim, but on an input, where the threat picture inverts. A + # forged input claim has no path to losing funds: it cannot produce a + # signature (embit re-derives the real key and refuses on a mismatch), and it + # cannot alter the amounts, the fee, or how outputs are classified. The likely + # causes are instead a psbt assembled for a different wallet, a corrupted + # entry, or a collaborative spend that happens to include a key whose 4-byte + # fingerprint collides with ours (1 in 2^32 chance). + # + # The psbt still fails, deliberately, following embit's lead: sign_with raises + # on this same condition and abandons the entire signing pass, so tolerating + # the entry here would only defer the failure to a worse spot. Changing this + # behavior, if desired, should happen in embit first. Until then the trade-off + # is accepted: a collaborative-spend counterparty could grief such a + # transaction into unsignability. + FORGED_INPUT_OWNERSHIP = "FORGED_INPUT_OWNERSHIP" + + # The selected seed holds no key that could sign any input. Alone among these + # codes this is a mismatch rather than a refusal of the psbt: the usual cause + # is the user picking the wrong seed. It is raised so the flow can say so up + # front, instead of walking the user through reviewing and approving a + # transaction that would then produce no signatures. The view layer keeps the + # psbt and routes back to seed selection -- see REJECT_PRESENTATION. + SEED_CANNOT_SIGN = "SEED_CANNOT_SIGN" + class InvalidPSBTError(Exception): """ @@ -137,7 +169,8 @@ class PSBTParser(): cosigners for multisig), the amount coming in, what is being spent, what comes back as change, the fee, where the spend is going, and any OP_RETURN payload. - Constructing it with a seed parses immediately. + Constructing it with a seed parses immediately; see parse() for what that establishes + in what order and which psbts it turns away. The parse fully processes the psbt, validates what it can, then stores the organized results in the instance attributes (spend_amount, fee_amount, destination_addresses, @@ -239,6 +272,13 @@ def __init__( self.locktime_is_enforced: bool = False self.locktime: int = 0 + # Indexed alongside psbt.inputs / psbt.outputs. Each entry is the derivation path + # the seed genuinely owns in each scope or None where it owns nothing. Determined + # in _verify_claimed_derivation_paths. Left empty when there is no BIP32 tree to + # verify against (WIF / BIP38 signing) -- see can_verify_derivations. + self.verified_input_derivation_paths: List[List[int] | None] = [] + self.verified_output_derivation_paths: List[List[int] | None] = [] + if self.seed is not None or self.root is not None: self.parse() @@ -295,6 +335,47 @@ def _set_root(self): def parse(self): """ + Establishes, in order: + + 0. _validate_psbt_version / _check_tx_modifiable / _assert_v2_complete: the + psbt must be one whose bytes can only mean one transaction before any of its + claims are worth reading. See RejectCode. + + 1. _fill_missing_fingerprints: backfills all-zero fingerprints, but only for + scopes the seed provably derives. + + 2. _verify_claimed_derivation_paths: each input and output scope that claims to + be controlled by the seed is verified. Raises InvalidPSBTError with + RejectCode.FORGED_[INPUT|OUTPUT]_OWNERSHIP if a claimed scope fails + verification. + + 3. _reject_if_seed_cannot_sign: raises RejectCode.SEED_CANNOT_SIGN if none of + the inputs can be signed by the seed. A mismatch rather than an attack, + caught here so the flow can say so before showing a transaction. + + Steps 2 and 3 need a BIP32 tree to derive against, so both are skipped when + there is none -- WIF / BIP38 signing, or a seedless multisig pre-parse. See + can_verify_derivations. + + 4. _parse_inputs: every input must resolve to the same policy, otherwise + RejectCode.MIXED_INPUTS. Each input is also structurally validated here + (RejectCode.MISSING_UTXO, UNSUPPORTED_SIGHASH, and the rest). + + A policy is one of: + - single-sig: the script type alone. Says nothing about keys. + - multisig, cosigners resolved: script type, m-of-n, and the cosigner + xpubs that every key in the script was traced back to. + - multisig, cosigners unresolved: script type and m-of-n only. + _get_policy doesn't propagate cosigner errors, so two such policies match + without anything having tied them to the same keys. TODO: don't let a + policy with no cosigner information pass as a match. + + 5. _parse_outputs: works out which outputs come back to this seed. For + single-sig this proves the output script derives from the seed at the + claimed path. TODO: reject outputs at a path the user's wallet would never + scan. + + Optimization via child_key_derivation_cache: Parsing traverses a derivation path down to an individual address one level at a time, over and over, and where that traversal begins depends on the wallet. @@ -302,7 +383,7 @@ def parse(self): the PSBT claims is ours. Multisig instead traverses just the last two levels down from each cosigner's - account xpub — once per cosigner, on every INPUT and on every OUTPUT carrying the + account xpub, once per cosigner, on every INPUT and on every OUTPUT carrying the multisig script. Deriving each level costs a hash and an elliptic curve operation, and these @@ -325,11 +406,22 @@ def parse(self): if self.seed is not None and self.root is None: self._set_root() + # A derivable BIP32 root is what makes verification possible at all. Without + # one -- WIF/BIP38 signing, or a seedless multisig pre-parse -- no evidence can + # be gathered and none is expected. Established here rather than in + # _parse_inputs because the ownership scan below needs it first. + self.can_verify_derivations = self.root is not None and hasattr(self.root, "derive") + child_key_derivation_cache = {} # Try to fix missing fingerprints before parsing self._fill_missing_fingerprints(child_key_derivation_cache) + # Work out what this seed actually owns before anything below reads the psbt's + # claims about it. + self._verify_claimed_derivation_paths(child_key_derivation_cache) + self._reject_if_seed_cannot_sign() + rt = self._parse_inputs(child_key_derivation_cache) if rt == False: return False @@ -822,10 +914,8 @@ def _parse_inputs(self, child_key_derivation_cache: dict): self.num_inputs = len(self.psbt.inputs) self.verified_input_prefixes = set() self.verified_max_input_index = -1 - # A derivable root is what makes verification possible at all. Without - # one -- WIF/BIP38 signing, or a seedless multisig pre-parse -- no - # evidence can be gathered and none is expected. - self.can_verify_derivations = self.root is not None and hasattr(self.root, "derive") + # can_verify_derivations is established in parse(), before the ownership + # scan that also depends on it. for i, inp in enumerate(self.psbt.inputs): PSBTParser._validate_input(i, inp) @@ -840,11 +930,12 @@ def _parse_inputs(self, child_key_derivation_cache: dict): # absence -- is_reachable_derivation gets None rather than an empty # set in that case. if self.can_verify_derivations: - for public_key, derivation in self._scope_keyed_derivations(inp): + for public_key, derivation, is_taproot in self._scope_keyed_derivations(inp): if not derivation: continue if not self._verify_derivation( - inp, public_key, derivation, child_key_derivation_cache + inp, public_key, derivation, child_key_derivation_cache, + is_taproot=is_taproot, ): # A path we cannot re-derive, or one the utxo does not # commit to: a cosigner's, or a fabrication. Not evidence. @@ -927,10 +1018,14 @@ def _scope_derivations(scope: InputScope | OutputScope) -> list[list[int]]: @staticmethod def _scope_keyed_derivations(scope: InputScope | OutputScope) -> list[tuple]: - """Every claimed derivation paired with the pubkey it claims to produce.""" - pairs = [(pub, d.derivation) for pub, d in scope.bip32_derivations.items()] - pairs += [(pub, d.derivation) for pub, (_, d) in scope.taproot_bip32_derivations.items()] - return pairs + """ + Every claimed derivation paired with the pubkey it claims to produce, and + whether that claim is a taproot one. Taproot keys are stored x-only and so + have to be compared differently -- see seed_owns_pubkey. + """ + triples = [(pub, d.derivation, False) for pub, d in scope.bip32_derivations.items()] + triples += [(pub, d.derivation, True) for pub, (_, d) in scope.taproot_bip32_derivations.items()] + return triples @staticmethod @@ -980,7 +1075,8 @@ def _input_commits_to_key(inp: InputScope, derived_key) -> bool: def _verify_derivation(self, inp: InputScope, public_key, derivation: list[int], - child_key_derivation_cache: dict | None = None) -> bool: + child_key_derivation_cache: dict | None = None, + is_taproot: bool = False) -> bool: """ Whether this seed really does produce `public_key` at `derivation`, *and* whether the utxo being spent actually commits to that key. @@ -990,19 +1086,26 @@ def _verify_derivation(self, inp: InputScope, public_key, derivation: list[int], supply a self-consistent lie drawn from elsewhere in our own tree. Both halves are needed: re-deriving makes it a fact about this seed, and the script check makes it a fact about this utxo. + + The first half is seed_owns_pubkey, which compares x-only for taproot and + the full key for ecdsa. The second half is this file's own contribution + and has no equivalent upstream. """ - if self.root is None or not hasattr(self.root, "derive"): + if not self.can_verify_derivations: # WIF/BIP38 signing has no BIP32 tree to check against. return False try: + if not PSBTParser.seed_owns_pubkey( + self.root, derivation, public_key, child_key_derivation_cache, + is_taproot=is_taproot, root_path=self.root_path, + ): + return False derived = PSBTParser._derive_with_cache( self.root, derivation[len(self.root_path):], child_key_derivation_cache ) except Exception as e: logger.debug("Could not derive %s: %s", derivation, e) return False - if derived.key.xonly() != public_key.xonly(): - return False return PSBTParser._input_commits_to_key(inp, derived) @@ -1075,9 +1178,6 @@ def _parse_outputs(self, child_key_derivation_cache: dict): elif self.policy["type"] == "p2wpkh" and my_pubkey is not None: sc = script.p2wpkh(my_pubkey) - if sc.data == vout[i].script_pubkey.data: - is_change = True - elif "p2tr" in self.policy["type"]: my_pubkey = None # should have one or zero derivations for single-key addresses @@ -1088,9 +1188,6 @@ def _parse_outputs(self, child_key_derivation_cache: dict): my_pubkey = PSBTParser._derive_with_cache(self.root, der, child_key_derivation_cache) sc = script.p2tr(my_pubkey) - if sc.data == vout[i].script_pubkey.data: - is_change = True - if sc.data == vout[i].script_pubkey.data: is_change = True @@ -1355,6 +1452,12 @@ def _get_policy(scope, scriptpubkey, xpubs, child_key_derivation_cache: dict | N cosigners = PSBTParser._get_cosigners(pubkeys, scope.bip32_derivations, xpubs, child_key_derivation_cache) policy.update({"m": m, "n": n, "cosigners": cosigners}) except: + # TODO: stop swallowing everything here. This also catches bugs in the + # cosigner check itself, and cannot tell those apart from the psbt + # simply not supplying xpubs to check against, which is valid and must + # not be rejected outright. The fallback policy carries no cosigner + # information at all, and two of those compare equal on script type + # and m-of-n alone. Fix pending with the multisig verification work. policy.update({"m": m, "n": n}) return policy @@ -1400,7 +1503,7 @@ def _derive_with_cache(parent_key: bip32.HDKey, derivation_path: List[int], chil cache, so a later derivation running through that level picks it up instead of deriving it a second time. - Entries are keyed on (id(parent_key), derivation_path_so_far) — the path traversed + Entries are keyed on (id(parent_key), derivation_path_so_far), the path traversed down from that parent to reach this point. id() is the Python built-in for an object's identity; the parent belongs in the key because a multisig parse runs these same derivations below each cosigner's xpub in turn. @@ -1512,7 +1615,7 @@ def has_matching_input_fingerprint( else: return False - def check_fingerprint_match(public_key: PublicKey, derivation_path_obj: DerivationPath): + def check_fingerprint_match(public_key: PublicKey, derivation_path_obj: DerivationPath, is_taproot: bool): """Check fingerprint match with missing fingerprint fallback""" # If exact fingerprint match @@ -1525,27 +1628,207 @@ def check_fingerprint_match(public_key: PublicKey, derivation_path_obj: Derivati if fallback_root is None: fallback_root = bip32.HDKey.from_seed(seed.seed_bytes, version=NETWORKS[SettingsConstants.map_network_to_embit(network)]["xprv"]) try: - derived_key = fallback_root.derive(derivation_path_obj.derivation) - return derived_key.key.sec() == public_key.sec() # Public keys match + # fallback_root, not root: the caller may have passed no root at + # all, in which case the master key was just derived from the seed + # above. + return PSBTParser.seed_owns_pubkey(fallback_root, derivation_path_obj.derivation, public_key, child_key_derivation_cache=None, is_taproot=is_taproot) except Exception as e: logger.debug("Fingerprint fallback derive failed: %s", e, exc_info=True) return False - + # Check all derivations in all inputs for input in psbt.inputs: # Check regular BIP32 derivations for public_key, derivation_path_obj in input.bip32_derivations.items(): - if check_fingerprint_match(public_key, derivation_path_obj): + if check_fingerprint_match(public_key, derivation_path_obj, is_taproot=False): return True - + # Check Taproot derivations for public_key, (leaf_hashes, derivation_path_obj) in input.taproot_bip32_derivations.items(): - if check_fingerprint_match(public_key, derivation_path_obj): + if check_fingerprint_match(public_key, derivation_path_obj, is_taproot=True): return True return False + @staticmethod + def seed_owns_pubkey(root: bip32.HDKey, claimed_derivation_path: List[int], public_key: PublicKey, child_key_derivation_cache: dict | None, is_taproot: bool = False, root_path: List[int] | None = None) -> bool: + """ + Returns True if the signing seed (root) really does derive public_key at + claimed_derivation_path. + + This is the canonical ownership check. The fingerprint a psbt or a descriptor + carries alongside a key is metadata that whoever wrote the file chose, so it can + say anything. Ownership is established here and only here, by deriving the key + again from the seed and comparing the actual key material. + + claimed_derivation_path is always the psbt's full path, measured from the master + key. `root` need not be the master key: a smartcard exports an account-level xpub + and nothing below it, so root_path names where that xpub sits and the leading + levels are dropped before deriving. See PSBTParser.root_path. + """ + if root_path: + if list(claimed_derivation_path[:len(root_path)]) != list(root_path): + # The claim starts somewhere this root cannot reach, so this root + # derives nothing at that path and owns nothing there. + return False + claimed_derivation_path = claimed_derivation_path[len(root_path):] + + derived_public_key = PSBTParser._derive_with_cache(root, claimed_derivation_path, child_key_derivation_cache).get_public_key() + + if is_taproot: + # A psbt carries a taproot key as its bare 32-byte x coordinate, but embit + # rebuilds a full key from it by just assuming even parity. The key derived + # from the seed carries its real parity, so a naive full-key comparison + # succeeds only when that real parity happens to be even, wrongly rejecting + # roughly half of the keys this seed genuinely owns. Only the x coordinate is + # real information: compare x-only. + return derived_public_key.xonly() == public_key.xonly() + + # For ecdsa the parity byte IS part of the identity, so compare the full key. + # This is deliberately stricter than embit, whose sign_with compares x-only even + # for ecdsa. embit would sign a psbt whose entry names the parity-flipped twin of + # our real key. The flipped key is still one this seed does NOT derive, and the + # signature embit produces under it is one no standard finalizer can use. So this + # extra strictness only rejects transactions that could never actually complete. + return derived_public_key == public_key + + + @staticmethod + def _get_seed_derivation_path(scope: InputScope | OutputScope, root: bip32.HDKey, child_key_derivation_cache: dict, seed_fingerprint: bytes, root_path: List[int] | None = None) -> List[int] | None: + """ + Scans the derivation path(s) in the provided input or output scope to determine + which, if any, are provably derived from the signing seed (for multisig a path is + provided per key; if the seed is part of the multisig, one of the n paths will + match). Returns the verified derivation path (as a list of ints) or None. + + Every key in the scope that claims this seed's fingerprint is re-derived and + checked. A claim that does not hold up raises InvalidPSBTError with + RejectCode.FORGED_[OUTPUT|INPUT]_OWNERSHIP. This includes fingerprint collisions + (two different keys with the same 4-byte fingerprint): + * On the output side, a collision is considered an attack. + * On the input side it is merely disallowed because it is unsignable by embit. + + seed_fingerprint is passed in rather than read off `root`, because `root` is not + always the master key: with a smartcard it is an account-level xpub whose own + fingerprint is not the one the psbt names. See PSBTParser.master_fingerprint. + + One edge case: + * A multisig could use this seed in more than one cosigner slot, each + at its own derivation path. The scope then carries several entries that all + verify against this seed; we return the first but still check the rest. + + The path itself is still whatever the psbt supplied: it can be any length or + shape, since any path that derives from the seed will pass. Whether the path is + one the user's wallet would ever look at is a separate question, answered + elsewhere. + """ + verified_derivation_path = None + + def _check_claim(public_key: PublicKey, derivation_path_obj: DerivationPath, is_taproot: bool): + nonlocal verified_derivation_path + + if derivation_path_obj.fingerprint != seed_fingerprint: + # Claims to belong to some other key. Nothing to prove or disprove here. + return + + if not PSBTParser.seed_owns_pubkey(root, derivation_path_obj.derivation, public_key, child_key_derivation_cache, is_taproot=is_taproot, root_path=root_path): + code = (RejectCode.FORGED_INPUT_OWNERSHIP if isinstance(scope, InputScope) else RejectCode.FORGED_OUTPUT_OWNERSHIP) + raise InvalidPSBTError( + f"Key at {bip32.path_to_str(derivation_path_obj.derivation)} claims this seed's fingerprint but does not derive from it", + code=code, + ) + + # Store only the first verified path + if verified_derivation_path is None: + verified_derivation_path = derivation_path_obj.derivation + + # Note that both loops check EVERY claim + for public_key, derivation_path_obj in scope.bip32_derivations.items(): + _check_claim(public_key, derivation_path_obj, is_taproot=False) + + for public_key, (leaf_hashes, derivation_path_obj) in scope.taproot_bip32_derivations.items(): + # TODO: Support keys in taptree leaves + _check_claim(public_key, derivation_path_obj, is_taproot=True) + + return verified_derivation_path + + + def _verify_claimed_derivation_paths(self, child_key_derivation_cache: dict): + """ + Verifies every claimed derivation path that names this seed's fingerprint. The + result, stored in verified_[input|output]_derivation_paths, is either the verified + derivation path or None (the seed was not named) for each input/output scope. + + The coordinator-supplied fingerprints cannot be trusted as-is. We must derive and + verify the ownership of each one that claims to belong to this seed. + + Outputs are verified before inputs; a false claim on an output (e.g. fake-change + forgery) is likely an attack whereas a false claim on an input is merely + unsignable. + + Raises InvalidPSBTError with RejectCode.FORGED_[OUTPUT|INPUT]_OWNERSHIP on the + first false claim detected. + + Does nothing when there is no BIP32 tree to derive against -- WIF / BIP38 + signing, or a seedless multisig pre-parse. Both lists stay empty, which + _reject_if_seed_cannot_sign reads as "no evidence expected" rather than as + "no ownership found". + """ + if not self.can_verify_derivations: + return + + seed_fingerprint = self.master_fingerprint or self.root.my_fingerprint + + self.verified_output_derivation_paths = [ + PSBTParser._get_seed_derivation_path(out, self.root, child_key_derivation_cache, seed_fingerprint, self.root_path) + for out in self.psbt.outputs + ] + + self.verified_input_derivation_paths = [ + PSBTParser._get_seed_derivation_path(inp, self.root, child_key_derivation_cache, seed_fingerprint, self.root_path) + for inp in self.psbt.inputs + ] + + + def _reject_if_seed_cannot_sign(self): + """ + Rejects the psbt when none of its inputs rely on a key derived by this seed. + + We detect it here, early, so the psbt can be rejected without sending the user + through the full verification flow only for signing to fail at the end anyway. + + (embit's sign_with is marginally more permissive: it also signs an input whose + script names the master key directly, with no derivation. That runs against how HD + wallets are built. The master key is a derivation root, not a spending key, so no + standard wallet produces such a psbt. We deliberately ignore this case. + + Similarly, it's not worth the effort to verify that each key is included in its + input's script. A psbt that excludes a key in that way would be nonsensical but + harmless: the excluded key cannot spend the input, so nothing of this seed's is + at risk.) + + Skipped when there is no BIP32 tree to derive against, because then nothing was + verified and an empty result is not evidence of absence. WIF / BIP38 signing + matches its key against the input script in _parse_inputs instead. + """ + if not self.can_verify_derivations: + return + + # An input names a key at a derivation path and _verify_claimed_derivation_paths + # proved the seed derives it (single-sig: one such key; multisig: one per + # cosigner, ours among them). One verified input path is enough for the psbt to + # be signable. + if any(path is not None for path in self.verified_input_derivation_paths): + return + + # There's nothing for this seed to sign + raise InvalidPSBTError( + "None of the inputs in this transaction are controlled by this seed.", + code=RejectCode.SEED_CANNOT_SIGN, + ) + + def verify_multisig_output(self, descriptor: Descriptor, change_num: int) -> bool: change_data = self.get_change_data(change_num) i = change_data["output_index"] @@ -1578,32 +1861,31 @@ def _fill_scope(scope: InputScope | OutputScope): """Helper function to fill missing fingerprints in a scope (input/output)""" # Helper function to check and fix fingerprint - def _get_updated_fingerprint(public_key: PublicKey, derivation_path_obj: DerivationPath) -> DerivationPath | None: + def _get_updated_fingerprint(public_key: PublicKey, derivation_path_obj: DerivationPath, is_taproot: bool) -> DerivationPath | None: if derivation_path_obj.fingerprint != b"\x00\x00\x00\x00": return None - - # Derive the public key from the currently loaded seed using the derivation - # contained in the PSBT. If the derived public key exactly matches - # the PSBT-provided public key, we can be confident that this input/output - # is owned by the signing seed. In that case we populate the missing (zero) - # fingerprint with the signing seed's master fingerprint so downstream - # parsing/signing can treat it as owned by this seed. - derived_key = PSBTParser._derive_with_cache( - self.root, derivation_path_obj.derivation, child_key_derivation_cache) - if derived_key.key.sec() == public_key.sec(): - return DerivationPath(self.root.my_fingerprint, derivation_path_obj.derivation) + + # If the signing seed really derives the psbt-provided public key at the + # claimed derivation path, this input/output is owned by the signing seed. + # In that case we populate the missing (zero) fingerprint with the signing + # seed's master fingerprint so downstream parsing/signing can treat it as + # owned by this seed. + # root_path / master_fingerprint keep this correct when `root` is an + # account-level xpub from a smartcard rather than the master key. + if PSBTParser.seed_owns_pubkey(self.root, derivation_path_obj.derivation, public_key, child_key_derivation_cache, is_taproot=is_taproot, root_path=self.root_path): + return DerivationPath(self.master_fingerprint or self.root.my_fingerprint, derivation_path_obj.derivation) return None - + # Handle regular BIP32 derivations for public_key, derivation_path_obj in list(scope.bip32_derivations.items()): - new_derivation = _get_updated_fingerprint(public_key, derivation_path_obj) + new_derivation = _get_updated_fingerprint(public_key, derivation_path_obj, is_taproot=False) if new_derivation: scope.bip32_derivations[public_key] = new_derivation logger.debug(f"Filled missing fingerprint for pubkey {public_key.sec().hex()} derivation {bip32.path_to_str(derivation_path_obj.derivation)}") - - # Handle Taproot derivations + + # Handle Taproot derivations for public_key, (leaf_hashes, derivation_path_obj) in list(scope.taproot_bip32_derivations.items()): - new_derivation = _get_updated_fingerprint(public_key, derivation_path_obj) + new_derivation = _get_updated_fingerprint(public_key, derivation_path_obj, is_taproot=True) if new_derivation: scope.taproot_bip32_derivations[public_key] = (leaf_hashes, new_derivation) logger.debug(f"Filled missing fingerprint for pubkey {public_key.sec().hex()} derivation {bip32.path_to_str(derivation_path_obj.derivation)}") diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index a7a62bd48..851165fc1 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -2,7 +2,7 @@ from seedsigner.helpers.l10n import mark_for_translation as _mft from binascii import hexlify -from binascii import hexlify +from dataclasses import dataclass from embit import bip32 import logging @@ -10,7 +10,7 @@ from seedsigner.models.psbt_parser import InvalidPSBTError, PSBTParser, RejectCode, RiskWarning from seedsigner.models.settings import SettingsConstants -from seedsigner.gui.components import FontAwesomeIconConstants, SeedSignerIconConstants +from seedsigner.gui.components import FontAwesomeIconConstants, GUIConstants, SeedSignerIconConstants from seedsigner.gui.screens.screen import ( RET_CODE__BACK_BUTTON, ButtonListScreen, @@ -276,6 +276,15 @@ def ensure_microsd_seed_warning() -> bool: master_fingerprint=master_fp, network=network, ) + except InvalidPSBTError as e: + # A deliberate refusal. Card signing gets the same screens as + # seed signing -- see REJECT_PRESENTATION. + logger.info("Refusing psbt from %s: %s (%s)", card_label, e, e.code) + self.controller.psbt_parser = None + self.controller.psbt_sign_with_satochip = False + loading.stop() + loading_stopped = True + return refusal_destination(e) except Exception as e: logger.exception("Failed to parse PSBT with %s data", card_label) loading.stop() @@ -434,24 +443,201 @@ def run(self): self.controller.psbt_seed = key return Destination(PSBTOverviewView) -class PSBTOverviewView(View): - # Refusals that the user can legitimately act on, rather than simply having - # to reject the transaction. Appended to the technical reason. - # - # Budget: the warning screen's text box fits five lines at the body font, and - # TextArea renders past the bottom edge rather than raising, so an overlong - # message silently draws over the button. Reason + tip must stay within that - # for the longest realistic values AND a verbose translation. - REJECT_TIPS = { - # TRANSLATOR_NOTE: Points the user at the setting that controls this check - RejectCode.CHANGE_INDEX_TOO_FAR: _mft("See Change Gap Limit in Settings."), - } +@dataclass +class RejectPresentation: + """ + How one RejectCode is shown to the user, and where the flow goes afterwards. + + Every refusal used to render as the same generic "Invalid PSBT" warning carrying + the parser's technical message. That is still the default -- `screen` is None and + the parser's message is the body -- but a code that deserves its own severity, + headline, or exit route gets an entry here instead of a special case in the flow. + + * screen / title / headline / text / icon / color / button: what is drawn. `text` + of None means "use the parser's own message", which is right where the message + names a specific offending value and wrong where fixed prose reads better. + * tip: appended to the message, for refusals the user can actually act on. + * clear_psbt: whether the psbt itself is discarded. False only for + SEED_CANNOT_SIGN, which is a seed/psbt mismatch rather than a bad psbt. + * clear_history: whether the redirect INTO this screen wipes the back stack, so + BACK cannot walk into a half-parsed psbt. False only where the user is meant to + step back into the flow they came from. + * destination_name: which View to land on once the screen is dismissed. Named as a + string because the table sits above the Views it points at. + """ + screen: type = None + title: str = "Invalid PSBT" + headline: str = None + text: str = None + icon: str = None + color: str = None + button_label: str = "Done" + tip: str = None + clear_psbt: bool = True + clear_history: bool = True + destination_name: str = "MainMenuView" + + +# Keyed by RejectCode. Anything absent renders with RejectPresentation() defaults, so +# adding a code to the parser never leaves the flow without a screen. +# +# Budget: the warning screen's text box fits five lines at the body font, and TextArea +# renders past the bottom edge rather than raising, so an overlong message silently +# draws over the button. Message + tip must stay within that for the longest realistic +# values AND a verbose translation. tests/test_psbt_refusal_screens.py pins this. +REJECT_PRESENTATION = { + # TRANSLATOR_NOTE: Points the user at the setting that controls this check + RejectCode.CHANGE_INDEX_TOO_FAR: RejectPresentation(tip=_mft("See Change Gap Limit in Settings.")), + + RejectCode.FORGED_OUTPUT_OWNERSHIP: RejectPresentation( + screen=DireWarningScreen, + # TRANSLATOR_NOTE: Title of the screen shown when a psbt lies about owning an output + title=_mft("Suspicious Transaction"), + headline=_mft("Likely an Attack!"), + text=_mft("The transaction's change/self-transfer outputs are not going back to your wallet."), + button_label=_mft("Discard transaction"), + ), + + RejectCode.FORGED_INPUT_OWNERSHIP: RejectPresentation( + screen=WarningScreen, + # TRANSLATOR_NOTE: Title of the screen shown when a psbt misstates who owns an input + title=_mft("Transaction Problem"), + text=_mft("This transaction incorrectly claims that its input(s) belong to this seed."), + button_label=_mft("Discard transaction"), + ), + + RejectCode.SEED_CANNOT_SIGN: RejectPresentation( + # An informational mismatch, not a warning, so it uses the neutral info icon and + # color rather than WarningScreen's alarming yellow edges. + # TODO: give this its own InfoScreen (LargeIconStatusScreen with the INFO icon + # and color baked in) rather than customizing the base screen at each call site. + screen=LargeIconStatusScreen, + # TRANSLATOR_NOTE: Title of the screen shown when the chosen seed can't sign the psbt + title=_mft("Seed Can't Sign"), + text=_mft("None of the inputs in this transaction are controlled by this seed."), + icon=SeedSignerIconConstants.INFO, + color=GUIConstants.INFO_COLOR, + button_label=_mft("Select a different seed"), + # The user is choosing a different seed for this psbt, not starting over, so the + # psbt is kept and only the seed and its parser are cleared. + clear_psbt=False, + clear_history=False, + destination_name="PSBTSelectSeedView", + ), +} + + + +class PSBTRefusalView(View): + """ + Renders one refused psbt, per REJECT_PRESENTATION, and routes onward. + + Reached by redirect from PSBTOverviewView, so each refusal is a real View: it can be + screenshotted, its strings extracted for translation, and its routing asserted in a + flow test. Subclasses below fix `code` so the named cases can be referred to + directly. + """ + code: str = None + + def __init__(self, code: str = None, message: str = None): + super().__init__() + self.code = code if code is not None else self.code + self.message = message + self.presentation = REJECT_PRESENTATION.get(self.code, RejectPresentation()) + + + def run(self): + p = self.presentation + + if p.text is not None: + text = _(p.text) + else: + # The parser's own message, which names the offending value. + text = self.message or _("This transaction could not be verified.") + if p.tip: + # Single newline, not a blank line: the warning screen's text box fits + # about five lines and a blank one costs a whole line. + text += "\n" + _(p.tip) + + kwargs = dict( + title=_(p.title), + status_headline=_(p.headline) if p.headline else None, + text=text, + button_data=[ButtonOption(p.button_label)], + show_back_button=False, + ) + if p.icon: + kwargs["status_icon_name"] = p.icon + if p.color: + kwargs["status_color"] = p.color + + self.run_screen(p.screen or WarningScreen, **kwargs) + + if p.clear_psbt: + self.controller.psbt = None + self.controller.psbt_parser = None + self.controller.psbt_seed = None + # Whichever signer was selected, it isn't signing this psbt. + self.controller.psbt_sign_with_satochip = False + + # Named rather than referenced directly so the table can sit above the Views it + # points at. test_every_reject_code_has_a_reachable_destination resolves them all. + return Destination(globals()[p.destination_name], clear_history=True) + + + +class PSBTOutputOwnershipClaimFailedView(PSBTRefusalView): + """ + An output claims a key this seed does not derive -- how a fake change output is + dressed up as the user's own. Shows a dire warning and discards the psbt. + """ + code = RejectCode.FORGED_OUTPUT_OWNERSHIP + DISCARD = ButtonOption("Discard transaction") + + +class PSBTInputOwnershipClaimFailedView(PSBTRefusalView): + """ + An input claims a key this seed does not derive. Unsignable rather than dangerous, + so a plain warning; the psbt is still discarded. + """ + code = RejectCode.FORGED_INPUT_OWNERSHIP + DISCARD = ButtonOption("Discard transaction") + + + +class PSBTSeedCannotSignView(PSBTRefusalView): + """ + This seed can't sign any of the psbt's inputs. Routes back to seed selection, keeping + the psbt, so the user can pick another. + """ + code = RejectCode.SEED_CANNOT_SIGN + SELECT_DIFFERENT_SEED = ButtonOption("Select a different seed") + + +# The named subclasses above, keyed by the code each one fixes. A code without one is +# rendered by PSBTRefusalView itself; give a code its own subclass when it is worth +# naming in a flow test or a screenshot, and it lands here automatically. +REFUSAL_VIEWS = {cls.code: cls for cls in PSBTRefusalView.__subclasses__()} + + +def refusal_destination(error: InvalidPSBTError) -> Destination: + """Where a refused psbt goes: the View for its code, carrying its message.""" + presentation = REJECT_PRESENTATION.get(error.code, RejectPresentation()) + return Destination( + REFUSAL_VIEWS.get(error.code, PSBTRefusalView), + view_args=dict(code=error.code, message=str(error)), + # Set clear_history to disable returning via BACK button + clear_history=presentation.clear_history, + ) + + + +class PSBTOverviewView(View): def __init__(self): super().__init__() self.loading_screen = None - self.parse_error: InvalidPSBTError = None if not self.controller.psbt_parser or self.controller.psbt_parser.seed != self.controller.psbt_seed: # The PSBTParser takes a while to read the PSBT. Run the loading screen while @@ -470,41 +656,19 @@ def __init__(self): block_anchor=(_Controller.RELEASE_BLOCK_HEIGHT, _Controller.RELEASE_BLOCK_TIME), ) except InvalidPSBTError as e: - # A deliberate refusal, not a crash: the psbt is parseable but - # unsafe to present. run() turns this into a warning screen. - self.loading_screen.stop() - self.loading_screen = None + # A deliberate refusal, not a crash: the psbt is parseable but unsafe to + # present, or not this seed's to sign. Redirect to the View that renders + # this code -- see REJECT_PRESENTATION. logger.info("Refusing psbt: %s (%s)", e, e.code) - self.parse_error = e - except Exception as e: + self.set_redirect(refusal_destination(e)) + return + finally: self.loading_screen.stop() - raise e def run(self): from seedsigner.gui.screens.psbt_screens import PSBTOverviewScreen - if self.parse_error: - text = str(self.parse_error) - tip = self.REJECT_TIPS.get(self.parse_error.code) - if tip: - # Single newline, not a blank line: the warning screen's text box - # fits about five lines and a blank one costs a whole line. - text += "\n" + _(tip) - - self.run_screen( - WarningScreen, - title=_("Invalid PSBT"), - status_headline=None, - text=text, - button_data=[ButtonOption("Done")], - show_back_button=False, - ) - self.controller.psbt = None - self.controller.psbt_parser = None - self.controller.psbt_seed = None - return Destination(MainMenuView, clear_history=True) - psbt_parser = self.controller.psbt_parser change_data = psbt_parser.change_data @@ -529,10 +693,6 @@ def run(self): else: num_self_transfer_outputs += 1 - # Everything is set. Stop the loading screen - if self.loading_screen: - self.loading_screen.stop() - # Run the overview screen selected_menu_num = self.run_screen( PSBTOverviewScreen, @@ -982,10 +1142,14 @@ def run(self): from seedsigner.views.seed_views import LoadMultisigWalletDescriptorView self.controller.resume_main_flow = Controller.FLOW__PSBT return Destination(LoadMultisigWalletDescriptorView) - + class PSBTAddressVerificationFailedView(View): + """ + Reached when a change or self-transfer output fails address verification. Shows a dire + warning and discards the psbt to the main menu. + """ def __init__(self, is_change: bool = True, is_multisig: bool = False): super().__init__() self.is_change = is_change @@ -1009,8 +1173,9 @@ def run(self): show_back_button=False, ) - # We're done with this PSBT. Route back to MainMenuView which always - # clears all ephemeral data (except in-memory seeds). + # We're done with this PSBT. Route back to MainMenuView, which clears all ephemeral + # data (except in-memory seeds). + # Set clear_history to disable returning via BACK button. return Destination(MainMenuView, clear_history=True) diff --git a/tests/psbt_suite_util.py b/tests/psbt_suite_util.py index 11fe31364..c7b19a68a 100644 --- a/tests/psbt_suite_util.py +++ b/tests/psbt_suite_util.py @@ -78,6 +78,9 @@ class RejectCode: UNSUPPORTED_PSBT_VERSION = "UNSUPPORTED_PSBT_VERSION" TX_MODIFIABLE = "TX_MODIFIABLE" UNDISPLAYABLE_OUTPUT = "UNDISPLAYABLE_OUTPUT" + FORGED_OUTPUT_OWNERSHIP = "FORGED_OUTPUT_OWNERSHIP" + FORGED_INPUT_OWNERSHIP = "FORGED_INPUT_OWNERSHIP" + SEED_CANNOT_SIGN = "SEED_CANNOT_SIGN" class Advisory: diff --git a/tests/psbt_testing_util.py b/tests/psbt_testing_util.py index f47d49ecc..00ea93d28 100644 --- a/tests/psbt_testing_util.py +++ b/tests/psbt_testing_util.py @@ -1,8 +1,10 @@ from binascii import a2b_base64, unhexlify from io import BytesIO +from embit import bip32 +from embit.ec import PublicKey from embit.networks import NETWORKS -from embit.psbt import PSBT, OutputScope +from embit.psbt import PSBT, DerivationPath, InputScope, OutputScope from seedsigner.models.seed import Seed @@ -60,6 +62,13 @@ class PSBTTestData: MULTISIG_LEGACY_P2SH_CHANGE = "0100695221031ce6ddb7a26336264b132c1b45c3e631e8502bc155226d46fc38d73d57f9e4ff21031d9e6e094413dc3a508518f729af23a35b3943ca79bafbc55afab631595e5ccf2103c3a6cb2786d860aa1ccff81fae79c1a973bc8a79938af6ff3c75fc4f54333d7353ae220203c3a6cb2786d860aa1ccff81fae79c1a973bc8a79938af6ff3c75fc4f54333d73100fb882ff2d00008001000000000000002202031d9e6e094413dc3a508518f729af23a35b3943ca79bafbc55afab631595e5ccf1003cd0a2b2d00008001000000000000002202031ce6ddb7a26336264b132c1b45c3e631e8502bc155226d46fc38d73d57f9e4ff100f8890442d0000800100000000000000010308000ff20500000000010417a91402e6f3cb4a98d88fbedf0e43869ce9e1a01e8d9f8700" MULTISIG_LEGACY_P2SH_SELF_TRANSFER = "01006952210283a03b8fa4cce258e536514416f448cf20aca8ef42492413c149a329029adb4e210346b5d12c00554bce6920e60d647893db6555e0844b8583747bc0ca1ecaba3e1c2103bfc0f7151411ace2d2eef986efca7873dabdc0f6f1bbea7bd3c863be1f2e00de53ae220203bfc0f7151411ace2d2eef986efca7873dabdc0f6f1bbea7bd3c863be1f2e00de100fb882ff2d000080000000000100000022020346b5d12c00554bce6920e60d647893db6555e0844b8583747bc0ca1ecaba3e1c1003cd0a2b2d000080000000000100000022020283a03b8fa4cce258e536514416f448cf20aca8ef42492413c149a329029adb4e100f8890442d000080000000000100000001030890d0030000000000010417a914505efc1adc72f354e827da94b49dec46d80717068700" + # Fingerprint-collision pair: two unrelated seeds whose master fingerprints collide, + # for tests of the honest-collision case (a genuine foreign key that names our + # fingerprint without any forgery involved). Any two seeds collide with probability 1 + # in 2^32. + collision_seed_a = Seed("trend local ecology client torch face wink soup right craft nerve bread".split()) + collision_seed_b = Seed("oval stadium chimney tone deny catch idea gasp absorb short vibrant tribe".split()) + # External receive outputs recipient_seed = Seed("shove album flame dad equal cook spike cheap hollow exit great forest".split()) recipient_multisig_key_2 = Seed("grow curve arrive reflect alarm water black funny comfort match attend tired".split()) @@ -126,3 +135,46 @@ def create_output(output_hex: str, value: int = None) -> OutputScope: if value is not None: output.value = value return output + + +def root_for_seed(seed: Seed) -> bip32.HDKey: + """ + A seed's master key, built the way PSBTParser builds it. + + The network only picks the version bytes, and neither the fingerprint nor any of the + key material compared below depends on those, so the fixtures' regtest is used + throughout. + """ + return bip32.HDKey.from_seed(seed.seed_bytes, version=NETWORKS["regtest"]["xprv"]) + + +def foreign_public_key(derivation_path: str = "m/84h/1h/0h/0/0", seed: Seed = None) -> PublicKey: + """ + A genuine public key belonging to some seed other than the signing seed, for building + scopes that name a key the signing seed does not control. + """ + if seed is None: + seed = PSBTTestData.recipient_seed + return root_for_seed(seed).derive(derivation_path).get_public_key() + + +def claim_seed_owns_key(scope: InputScope | OutputScope, claimed_derivation_path: str, public_key: PublicKey, seed: Seed = None, is_taproot: bool = False): + """ + Writes a derivation into the scope claiming that seed owns public_key at + claimed_derivation_path. + + Building one of these needs no key material from the seed, because nothing in a psbt + ties a fingerprint to the key written beside it. The fingerprint is all it takes, and + that is published in every psbt the seed has ever been sent. So pass a public_key the + seed does not own and the result is a psbt asserting ownership that does not exist. + """ + if seed is None: + seed = PSBTTestData.seed + + derivation_path = DerivationPath( + root_for_seed(seed).my_fingerprint, bip32.parse_path(claimed_derivation_path)) + + if is_taproot: + scope.taproot_bip32_derivations[public_key] = ([], derivation_path) + else: + scope.bip32_derivations[public_key] = derivation_path diff --git a/tests/screenshot_generator/generator.py b/tests/screenshot_generator/generator.py index c32c125ee..586d9f12f 100644 --- a/tests/screenshot_generator/generator.py +++ b/tests/screenshot_generator/generator.py @@ -521,6 +521,9 @@ def mock_version_to_most_recent_release(): ScreenshotConfig(psbt_views.PSBTAddressVerificationFailedView, dict(is_change=False, is_multisig=False), screenshot_name="PSBTAddressVerificationFailedView_singlesig_selftransfer"), ScreenshotConfig(psbt_views.PSBTAddressVerificationFailedView, dict(is_change=True, is_multisig=True), screenshot_name="PSBTAddressVerificationFailedView_multisig_change"), ScreenshotConfig(psbt_views.PSBTAddressVerificationFailedView, dict(is_change=False, is_multisig=True), screenshot_name="PSBTAddressVerificationFailedView_multisig_selftransfer"), + ScreenshotConfig(psbt_views.PSBTOutputOwnershipClaimFailedView), + ScreenshotConfig(psbt_views.PSBTInputOwnershipClaimFailedView), + ScreenshotConfig(psbt_views.PSBTSeedCannotSignView), ScreenshotConfig(psbt_views.PSBTFinalizeView, mock_context_manager=mock_multisig_psbt_loaded), #ScreenshotConfig(PSBTSignedQRDisplayViewScreenshotConfig), ScreenshotConfig(psbt_views.PSBTSigningErrorView, mock_context_manager=mock_multisig_psbt_loaded), diff --git a/tests/test_flows_psbt.py b/tests/test_flows_psbt.py index 27b4312bf..e4b7296bf 100644 --- a/tests/test_flows_psbt.py +++ b/tests/test_flows_psbt.py @@ -1,10 +1,16 @@ -from base import BaseTest, FlowTest, FlowStep - +from binascii import a2b_base64 from unittest.mock import Mock +from embit.psbt import PSBT + +from base import BaseTest, FlowTest, FlowStep +from psbt_testing_util import (PSBTTestData, claim_seed_owns_key, create_output, + foreign_public_key) + from seedsigner.controller import Controller from seedsigner.views.view import MainMenuView from seedsigner.views import scan_views, seed_views, psbt_views +from seedsigner.models.seed import Seed from seedsigner.models.settings import SettingsConstants @@ -373,3 +379,86 @@ def test_descriptor_mismatch_clears_descriptor_and_prompts(self): assert follow_up_kwargs["button_data"][0] is follow_up_view.VERIFY_MULTISIG assert follow_up_kwargs["button_data"][1] is follow_up_view.SKIP_VERIFICATION assert follow_up_destination.View_cls.__name__ == "BackStackView" + + + +class TestPSBTOwnershipClaimRouting(FlowTest): + """ + A psbt carrying an ownership claim that does not hold up is rejected while it is being + parsed, before the user is shown anything about the transaction. These cover the + routing that turns that rejection into a warning screen instead of a crash. + """ + + def _load_psbt_for_signing(self, psbt: PSBT, seed: Seed = None): + """ + Stage the psbt in the Controller and load the signing seed into storage, as if + both had just been scanned. Each test's sequence then starts at seed selection; + the parse itself runs when PSBTOverviewView is instantiated. + """ + self.settings.set_value(SettingsConstants.SETTING__NETWORK, SettingsConstants.REGTEST) + self.controller.psbt = psbt + self.controller.storage.set_pending_seed(seed if seed is not None else PSBTTestData.seed) + self.controller.storage.finalize_pending_seed() + + + def _psbt_with_change(self): + psbt = PSBT.parse(a2b_base64(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_1_INPUT)) + psbt.outputs.append(create_output(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_CHANGE, 10_000)) + return psbt + + + def test_forged_output_claim_terminates_signing_flow(self): + """ + A forged ownership claim on an output is framed as a potential attack, so it + routes to a warning that aborts the signing flow. + """ + psbt = self._psbt_with_change() + claim_seed_owns_key(psbt.outputs[0], "m/84h/1h/0h/1/0", foreign_public_key()) + self._load_psbt_for_signing(psbt) + + self.run_sequence([ + FlowStep(psbt_views.PSBTSelectSeedView, screen_return_value=0), + FlowStep(psbt_views.PSBTOverviewView, is_redirect=True), + FlowStep(psbt_views.PSBTOutputOwnershipClaimFailedView, button_data_selection=psbt_views.PSBTOutputOwnershipClaimFailedView.DISCARD), + FlowStep(MainMenuView), + ]) + + + def test_forged_input_claim_terminates_signing_flow(self): + """ + A false claim on an input is framed as inconsistent data rather than as an attack, + but also routes to its own information screen that aborts the signing flow. + """ + psbt = self._psbt_with_change() + claim_seed_owns_key(psbt.inputs[0], "m/84h/1h/0h/0/0", foreign_public_key()) + self._load_psbt_for_signing(psbt) + + self.run_sequence([ + FlowStep(psbt_views.PSBTSelectSeedView, screen_return_value=0), + FlowStep(psbt_views.PSBTOverviewView, is_redirect=True), + FlowStep(psbt_views.PSBTInputOwnershipClaimFailedView, button_data_selection=psbt_views.PSBTInputOwnershipClaimFailedView.DISCARD), + FlowStep(MainMenuView), + ]) + + + def test_wrong_seed_routes_back_to_seed_selection_flow(self): + """ + The wrong seed for a psbt redirects before any transaction detail is rendered and + routes back to seed selection with the signing seed cleared so another can be + picked. + """ + self._load_psbt_for_signing(self._psbt_with_change(), seed=PSBTTestData.recipient_seed) + + self.run_sequence([ + FlowStep(psbt_views.PSBTSelectSeedView, screen_return_value=0), + FlowStep(psbt_views.PSBTOverviewView, is_redirect=True), + FlowStep(psbt_views.PSBTSeedCannotSignView, button_data_selection=psbt_views.PSBTSeedCannotSignView.SELECT_DIFFERENT_SEED), + FlowStep(psbt_views.PSBTSelectSeedView), + ]) + + assert self.controller.psbt_seed is None + assert self.controller.psbt_parser is None + + # The psbt itself is kept: the user is choosing a different seed for it, not + # starting over + assert self.controller.psbt is not None diff --git a/tests/test_flows_psbt_malicious.py b/tests/test_flows_psbt_malicious.py index b1736410c..ca6148adc 100644 --- a/tests/test_flows_psbt_malicious.py +++ b/tests/test_flows_psbt_malicious.py @@ -84,7 +84,10 @@ def test_mixed_input_types_is_refused_with_a_warning(self): """ self.run_sequence( self.scan_and_select_seed("XTRAS.MIXED_INPUT_TYPES") + [ - FlowStep(psbt_views.PSBTOverviewView, screen_return_value=0), + # The refusal redirects out of the overview before any transaction + # detail is rendered; PSBTRefusalView draws the screen. + FlowStep(psbt_views.PSBTOverviewView, is_redirect=True), + FlowStep(psbt_views.PSBTRefusalView, screen_return_value=0), FlowStep(MainMenuView), ] ) @@ -99,7 +102,10 @@ def test_non_sighash_all_psbt_is_refused_at_load(self): """ self.run_sequence( self.scan_and_select_seed("TX-08.SINGLE") + [ - FlowStep(psbt_views.PSBTOverviewView, screen_return_value=0), + # The refusal redirects out of the overview before any transaction + # detail is rendered; PSBTRefusalView draws the screen. + FlowStep(psbt_views.PSBTOverviewView, is_redirect=True), + FlowStep(psbt_views.PSBTRefusalView, screen_return_value=0), FlowStep(MainMenuView), ] ) @@ -116,7 +122,10 @@ def test_spliced_change_path_is_refused(self): """ self.run_sequence( self.scan_and_select_seed("TX-01") + [ - FlowStep(psbt_views.PSBTOverviewView, screen_return_value=0), + # The refusal redirects out of the overview before any transaction + # detail is rendered; PSBTRefusalView draws the screen. + FlowStep(psbt_views.PSBTOverviewView, is_redirect=True), + FlowStep(psbt_views.PSBTRefusalView, screen_return_value=0), FlowStep(MainMenuView), ] ) diff --git a/tests/test_flows_smartcard_hardware.py b/tests/test_flows_smartcard_hardware.py index f7e20cca4..191f42f50 100644 --- a/tests/test_flows_smartcard_hardware.py +++ b/tests/test_flows_smartcard_hardware.py @@ -162,6 +162,23 @@ def cap_dir(): return p +def _reinstall_blank(gp, cap_path, aid, **install_kwargs): + """ + Install `cap_path` onto a card carrying no prior copy of `aid`. + + install_capfile skips the load and install steps for a package that is + already on the card, so installing over a previous run leaves that run's PIN + and key material in place. Provisioning then short-circuits on setup_done, + the PIN this run expects never matches, and the seed import is refused with a + bare status word. Deleting first makes "install, initialise, test, uninstall" + mean what it says. + """ + _reauth_and_delete(gp, aid) + result = gp.install_capfile(str(cap_path), **install_kwargs) + gp.close() + return result + + def _reauth_and_delete(gp, aid): """Re-establish GP auth and remove an applet package, tolerating absence.""" try: @@ -554,3 +571,581 @@ def test_import_refuses_when_card_already_seeded(self): FlowStep(MainMenuView), ], ) + + + +# ====================================================================== +# PSBT signing against a live card +# ====================================================================== +# +# These cover the parser's *card* root mode, which no desktop test can reach. +# +# A seed-backed parse hands PSBTParser the master key: `root` is m, `root_path` +# is empty, and every derivation the psbt names is measured from that same +# point. A card never exports its master private key, so the flow exports an +# account-level xpub instead, and PSBTParser is given three things rather than +# one: `root` (the account key), `root_path` (where that key sits), and +# `master_fingerprint` (which the psbt's derivations actually name). Ownership +# is then established by stripping the root_path prefix and deriving the +# remainder -- see PSBTParser.seed_owns_pubkey. +# +# Each of those three has a plausible-looking wrong answer: comparing against +# the account key's own fingerprint instead of the master's, or deriving a full +# path from an account-level key. Both fail *closed* -- the card verifies +# nothing, so every psbt looks unsignable or every change output looks forged -- +# so the failure mode resembles a working refusal. Only a real card proves the +# difference. + +ACCOUNT_PATH = "m/84h/1h/0h" +INPUT_PATH = ACCOUNT_PATH + "/0/0" +CHANGE_PATH = ACCOUNT_PATH + "/1/0" + +# A seed that is not the card's, for building claims the card cannot honour. +FOREIGN_MNEMONIC = "shove album flame dad equal cook spike cheap hollow exit great forest".split() + + +def _regtest_root(mnemonic: list[str]): + from embit import bip32 + from embit.networks import NETWORKS + + return bip32.HDKey.from_seed( + Seed(mnemonic=mnemonic).seed_bytes, version=NETWORKS["regtest"]["xprv"] + ) + + +def build_signable_psbt(mnemonic: list[str]): + """ + A real, parseable 1-in/2-out native segwit psbt: spending to a stranger with + change coming back to `mnemonic`'s own wallet. + + `_build_psbt` in test_smartcard_hardware.py is deliberately a stub -- enough + for the signer helper, not enough for PSBTParser, which needs a transaction, + prevouts and amounts. This builds the real thing, so the parse under test is + the parse a user's psbt actually gets. + """ + from embit import bip32, script + from embit.psbt import PSBT, DerivationPath + from embit.transaction import Transaction, TransactionInput, TransactionOutput + + root = _regtest_root(mnemonic) + input_key = root.derive(INPUT_PATH) + change_key = root.derive(CHANGE_PATH) + stranger_key = _regtest_root(FOREIGN_MNEMONIC).derive("m/84h/1h/0h/0/7") + + tx = Transaction( + version=2, + vin=[TransactionInput(bytes.fromhex("11" * 32), 0)], + vout=[ + TransactionOutput(70_000, script.p2wpkh(stranger_key.to_public())), + TransactionOutput(29_000, script.p2wpkh(change_key.to_public())), + ], + locktime=0, + ) + + psbt = PSBT(tx) + psbt.inputs[0].witness_utxo = TransactionOutput( + 100_000, script.p2wpkh(input_key.to_public())) + psbt.inputs[0].bip32_derivations[input_key.to_public().key] = DerivationPath( + root.my_fingerprint, bip32.parse_path(INPUT_PATH)) + psbt.outputs[1].bip32_derivations[change_key.to_public().key] = DerivationPath( + root.my_fingerprint, bip32.parse_path(CHANGE_PATH)) + return psbt + + +def claim_ownership(scope, mnemonic: list[str], claimed_path: str, public_key): + """ + Write a derivation asserting that `mnemonic`'s seed owns `public_key` at + `claimed_path`. + + Forging one needs no key material at all: nothing in a psbt ties a + fingerprint to the key stored beside it, and the fingerprint is published in + every psbt that seed has ever been sent. Pass a key the seed does not own and + the result is a psbt asserting ownership that does not exist. + """ + from embit import bip32 + from embit.psbt import DerivationPath + + scope.bip32_derivations[public_key] = DerivationPath( + _regtest_root(mnemonic).my_fingerprint, bip32.parse_path(claimed_path)) + + +def foreign_public_key(path: str = "m/84h/1h/0h/0/0"): + """A genuine key belonging to a seed that is not the card's.""" + return _regtest_root(FOREIGN_MNEMONIC).derive(path).to_public().key + + +class CardPSBTSigningFlowTest(SmartcardFlowTest): + """ + Shared body for the card signing modes. Subclasses supply the applet + lifecycle, a connector, and which PSBTSelectSeedView button selects them. + """ + + CARD_BUTTON = None # a PSBTSelectSeedView ButtonOption; set by the subclass + + # Each concrete subclass carries its own `pytestmark = pytest.mark.order(N)`. + # + # pytest-order sorts globally rather than per class, and each applet lifecycle + # is a class-scoped fixture, so two classes sharing an order number interleave + # and one installs or deletes its applet out from under the other's tests. A + # distinct number per class keeps each class's install -> initialise -> tests + # -> uninstall contiguous, and tests within a class keep their definition + # order, which is the order they are written to run in. + # + # The number cannot be set here or derived per-test in this base: a marker + # applied in the base class body binds at definition time, so every subclass + # would inherit the same value and collide. + + # -- plumbing ------------------------------------------------------ + + def prime_for_psbt(self, psbt): + """ + Stage a psbt and put the controller in the state PSBTSelectSeedView + expects, on regtest so the card's testnet account path is the live one. + """ + from seedsigner.models.settings import SettingsConstants as SC + + self.prime_controller_for_card() + self.settings.set_value(SC.SETTING__NETWORK, SC.REGTEST) + self.controller.psbt = psbt + self.controller.psbt_parser = None + self.controller.psbt_seed = None + self.controller.psbt_sign_with_satochip = False + + def run_card_selection(self, psbt, expected_view): + """ + Drive PSBTSelectSeedView against the real card and stop where expected. + + The card is chosen by ButtonOption rather than by index: the menu is + built conditionally from settings, so a fixed number silently selects the + wrong signer as soon as an option above it appears or disappears. + """ + from seedsigner.views import psbt_views + + self.prime_for_psbt(psbt) + self.run_sequence([ + FlowStep(psbt_views.PSBTSelectSeedView, button_data_selection=self.CARD_BUTTON), + FlowStep(expected_view), + ]) + + def reconnect(self): + """ + Drop every open card session and start a new one. + + Running a flow hands the card to init_satochip, which builds its own + connector and parks it on the controller. That leaves this class's cached + connector holding a session the card has already torn down, and the next + direct call fails with a bare status word (0x9C23) that names nothing + about the real problem. So every direct card access starts over rather + than trusting a connector that a flow may have invalidated. + """ + parked = getattr(self.controller, "Satochip_Connector", None) + if parked is not None: + try: + parked.card_disconnect() + except Exception: + pass + self.controller.Satochip_Connector = None + self._disconnect() + return self._connect() + + def card_account_xpub(self) -> str: + return self.reconnect().card_bip32_get_xpub(ACCOUNT_PATH.replace("h", "'"), + "p2wpkh", False) + + def card_master_fingerprint(self) -> bytes: + from embit.bip32 import HDKey + + return HDKey.from_base58( + self.reconnect().card_bip32_get_xpub("", "p2wpkh", False)).my_fingerprint + + # -- tests --------------------------------------------------------- + + def test_card_holds_the_seed_these_tests_assume(self): + """ + Everything below compares the card against keys derived from + BIP39_MNEMONIC. If the card is carrying some other seed, those + comparisons fail for reasons that have nothing to do with the code under + test, so establish it once here and fail with a legible message. + """ + from embit.bip32 import HDKey + + expected = _regtest_root(BIP39_MNEMONIC).my_fingerprint + actual = self.card_master_fingerprint() + assert actual == expected, ( + "card master fingerprint %s does not match BIP39_MNEMONIC (%s); " + "the applet was not re-seeded" % (actual.hex(), expected.hex())) + + on_card = HDKey.from_base58(self.card_account_xpub()) + in_test = _regtest_root(BIP39_MNEMONIC).derive(ACCOUNT_PATH).to_public() + assert on_card.key.sec() == in_test.key.sec() + + def test_parse_runs_in_account_xpub_root_mode(self): + """ + The card hands the parser an account-level xpub, not a master key. The + three fields that make that work have to be set consistently, and the + ownership scan has to succeed against them. + + Asserting verified_input_derivation_paths is the point: an empty list + here is exactly what a wrong fingerprint or an unstripped derivation path + produces, and it is indistinguishable from "this card cannot sign" at + every layer above. + """ + from embit import bip32 + from seedsigner.views import psbt_views + + self.run_card_selection(build_signable_psbt(BIP39_MNEMONIC), + psbt_views.PSBTOverviewView) + + parser = self.controller.psbt_parser + assert parser is not None, "card selection did not build a parser" + assert self.controller.psbt_sign_with_satochip is True + + assert parser.seed is None, "card mode must not carry a Seed" + assert parser.root_path == bip32.parse_path(ACCOUNT_PATH) + assert parser.master_fingerprint == self.card_master_fingerprint() + assert parser.root.my_fingerprint != parser.master_fingerprint, ( + "root should be the account xpub, not the master key -- otherwise this " + "test proves nothing about the account-relative derivation") + assert parser.can_verify_derivations is True + + assert parser.verified_input_derivation_paths == [bip32.parse_path(INPUT_PATH)] + assert parser.verified_output_derivation_paths == [ + None, bip32.parse_path(CHANGE_PATH)] + + def test_card_parse_agrees_with_a_seed_parse(self): + """ + Same psbt, same wallet, two ways of reaching the keys. Every number the + user is shown, and every ownership verdict behind it, must come out the + same -- otherwise the account-relative derivation is subtly wrong in a + way no single-mode test would notice. + """ + from seedsigner.models.psbt_parser import PSBTParser + from seedsigner.models.settings import SettingsConstants as SC + from seedsigner.views import psbt_views + + self.run_card_selection(build_signable_psbt(BIP39_MNEMONIC), + psbt_views.PSBTOverviewView) + from_card = self.controller.psbt_parser + + from_seed = PSBTParser(build_signable_psbt(BIP39_MNEMONIC), + seed=Seed(mnemonic=BIP39_MNEMONIC), network=SC.REGTEST) + + assert from_card.verified_input_derivation_paths == from_seed.verified_input_derivation_paths + assert from_card.verified_output_derivation_paths == from_seed.verified_output_derivation_paths + assert from_card.change_data == from_seed.change_data + assert from_card.spend_amount == from_seed.spend_amount + assert from_card.change_amount == from_seed.change_amount + assert from_card.fee_amount == from_seed.fee_amount + assert from_card.destination_addresses == from_seed.destination_addresses + + def test_forged_change_claim_is_refused(self): + """ + The attack the ownership scan exists to stop, run against a real card: an + output claims the card's fingerprint on a key the card does not derive, + so a naive signer labels it "your change" while the funds leave the + wallet for good. + + This is the case that would silently regress if the card's account-level + root were fed to a master-relative ownership check. That refuses + everything, including this, so the regression still looks like a pass. + test_parse_runs_in_account_xpub_root_mode is what separates the two. + """ + from seedsigner.views import psbt_views + + psbt = build_signable_psbt(BIP39_MNEMONIC) + psbt.outputs[1].bip32_derivations.clear() + claim_ownership(psbt.outputs[1], BIP39_MNEMONIC, CHANGE_PATH, foreign_public_key()) + + self.run_card_selection(psbt, psbt_views.PSBTOutputOwnershipClaimFailedView) + + assert self.controller.psbt_parser is None + assert self.controller.psbt_sign_with_satochip is False + + def test_forged_input_claim_is_refused(self): + """ + The same false claim on an input. It cannot cost the user anything -- no + signature can come of it -- so it is reported as a problem with the + transaction rather than as an attack, but it still stops the flow. + """ + from seedsigner.views import psbt_views + + psbt = build_signable_psbt(BIP39_MNEMONIC) + claim_ownership(psbt.inputs[0], BIP39_MNEMONIC, INPUT_PATH, + foreign_public_key("m/84h/1h/0h/0/9")) + + self.run_card_selection(psbt, psbt_views.PSBTInputOwnershipClaimFailedView) + + assert self.controller.psbt_parser is None + + def test_psbt_for_another_wallet_cannot_be_signed(self): + """ + A psbt belonging to a different wallet must not verify against this card. + + Driven at the parser rather than through the menu, because the menu never + gets this far: PSBTSelectSeedView compares fingerprints first and sends + the user back to pick another signer. That earlier guard is also why + RejectCode.SEED_CANNOT_SIGN, which covers this case for a seed, is not + reachable through the card path -- but the parser must still be right + about it, since it is the layer that actually decides. + """ + import pytest as _pytest + from embit import bip32 + from embit.bip32 import HDKey + from seedsigner.models.psbt_parser import InvalidPSBTError, PSBTParser, RejectCode + from seedsigner.models.settings import SettingsConstants as SC + + with _pytest.raises(InvalidPSBTError) as excinfo: + PSBTParser( + build_signable_psbt(FOREIGN_MNEMONIC), + seed=None, + root=HDKey.from_base58(self.card_account_xpub()), + root_path=bip32.parse_path(ACCOUNT_PATH), + master_fingerprint=self.card_master_fingerprint(), + network=SC.REGTEST, + ) + assert excinfo.value.code == RejectCode.SEED_CANNOT_SIGN + + def test_verified_psbt_signs_on_the_card(self): + """ + End to end: parse in card mode, then let PSBTFinalizeView drive the real + applet, and check that the signature the card produced verifies against + the key the parser said the card owns. + + This closes the loop the tests above leave open. They prove the parser + believes the card owns the input; only a signature that the input's own + pubkey verifies proves it was right. + """ + from embit.ec import Signature + from seedsigner.models.psbt_parser import PSBTParser + from seedsigner.views import psbt_views + + psbt = build_signable_psbt(BIP39_MNEMONIC) + self.run_card_selection(psbt, psbt_views.PSBTOverviewView) + + input_pubkey = _regtest_root(BIP39_MNEMONIC).derive(INPUT_PATH).to_public().key + assert PSBTParser.sig_count(psbt) == 0 + + view = psbt_views.PSBTFinalizeView() + view.run_screen = MagicMock(return_value=0) # APPROVE_PSBT + view.run() + + assert PSBTParser.sig_count(psbt) >= 1, "the card produced no signature" + signature = psbt.inputs[0].partial_sigs.get(input_pubkey) + assert signature is not None, ( + "the card signed under a key other than the one the parser verified") + + # psbt.sighash resolves the script and value for the input itself; the + # trailing byte of the signature is the sighash flag, not DER. + assert input_pubkey.verify(Signature.parse(signature[:-1]), psbt.sighash(0)), ( + "the card's signature does not verify against the verified input key") + + +class TestSatochipPSBTSigningFlows(CardPSBTSigningFlowTest): + """Blank card -> install Satochip -> seed it -> sign a psbt through the UI.""" + + AID = "5361746F43686970" + CAP = "SatoChip-0.12-official.cap" + # Above TestSatochipImportSeedFlows' 1-2 so the two Satochip classes do not + # interleave their applet lifecycles. + pytestmark = pytest.mark.order(10) + + _connector = None + + @pytest.fixture(scope="class", autouse=True) + def applet(self, gp, cap_dir): + # install -> initialise -> tests -> uninstall. Preparation failures are + # raised, not skipped: the card is present, so a card that will not + # provision or seed is a real failure and every test below would + # otherwise fail somewhere less informative. + logger.info("Satochip install result: %s", + _reinstall_blank(gp, cap_dir / self.CAP, self.AID)) + self._initialise() + yield + self._disconnect() + _reauth_and_delete(gp, self.AID) + + @property + def CARD_BUTTON(self): + from seedsigner.views import psbt_views + return psbt_views.PSBTSelectSeedView.SATOCHIP + + # -- card lifecycle ------------------------------------------------ + # + # Deliberately not shared with TestSatochipImportSeedFlows: that class + # provisions a card to be left *unseeded* so its import flow has something to + # do, while this one needs a card already carrying BIP39_MNEMONIC. Same APDUs, + # opposite end states. + + def _connect(self): + from pysatochip.CardConnector import CardConnector + + if TestSatochipPSBTSigningFlows._connector is None: + connector = CardConnector(card_filter=["satochip"]) + connector.cardmonitor.deleteObserver(connector.cardobserver) + connector.cardservice.connection.connect() + connector.card_select() + (_, _, _, status) = connector.card_get_status() + if connector.needs_secure_channel: + connector.card_initiate_secure_channel() + if status.get("setup_done"): + connector.set_pin(0, list(CARD_PIN.encode("utf-8"))) + connector.card_verify_PIN() + time.sleep(0.3) + TestSatochipPSBTSigningFlows._connector = connector + return TestSatochipPSBTSigningFlows._connector + + def _disconnect(self): + if TestSatochipPSBTSigningFlows._connector is not None: + try: + TestSatochipPSBTSigningFlows._connector.card_disconnect() + except Exception: + pass + TestSatochipPSBTSigningFlows._connector = None + + def _initialise(self): + """ + Provision the applet and load the seed, on one session. See the Keycard + version for why setup and seeding must not be split across connectors. + """ + import os as _os + + connector = self._connect() + pin_list = list(CARD_PIN.encode("utf-8")) + + (_, _, _, status) = connector.card_get_status() + if not status.get("setup_done"): + connector.card_setup( + pin_tries0=5, ublk_tries0=1, + pin0=pin_list, ublk0=list(_os.urandom(16)), + pin_tries1=1, ublk_tries1=1, + pin1=[0x30] * 6, ublk1=[0x30] * 6, + memsize=0x4000, memsize2=0x0060, + create_object_ACL=0x01, create_key_ACL=0x01, create_pin_ACL=0x01, + ) + connector.set_pin(0, pin_list) + connector.card_verify_PIN() + + (_, _, _, status) = connector.card_get_status() + if not status.get("is_seeded"): + connector.card_bip32_import_seed(list(Seed(mnemonic=BIP39_MNEMONIC).seed_bytes)) + (_, _, _, status) = connector.card_get_status() + if not status.get("is_seeded"): + raise RuntimeError( + "Satochip accepted the seed import but reports no key: %s" % status) + + self._disconnect() + + +class TestKeycardPSBTSigningFlows(CardPSBTSigningFlowTest): + """Blank card -> install Keycard -> seed it -> sign a psbt through the UI.""" + + AID = "A0000008040001" + CAP = "Keycard_v3.2.cap" + PIN = "123456" + pytestmark = pytest.mark.order(20) + + _connector = None + + @pytest.fixture(scope="class", autouse=True) + def applet(self, gp, cap_dir): + try: + import keycard # noqa: F401 + except ImportError: + pytest.skip("keycard-py not installed (pip install keycard-py)") + + logger.info("Keycard install result: %s", + _reinstall_blank(gp, cap_dir / self.CAP, self.AID)) + self._initialise() + yield + self._disconnect() + _reauth_and_delete(gp, self.AID) + + @property + def CARD_BUTTON(self): + from seedsigner.views import psbt_views + return psbt_views.PSBTSelectSeedView.KEYCARD + + def prime_for_psbt(self, psbt): + from seedsigner.models.settings import SettingsConstants as SC + + super().prime_for_psbt(psbt) + # PSBTSelectSeedView offers each card only when its own support setting is + # on. Satochip's happens to default to enabled, Keycard's does not, so + # without this the menu has no Keycard button to select. + self.settings.set_value(SC.SETTING__KEYCARD_SUPPORT, SC.OPTION__ENABLED) + # The Keycard applet has its own PIN, and its own backend: init_satochip + # only prompts for a PIN when the controller has none cached, and picks + # the connector class from smartcard_backend_preference. + self.controller.Satochip_PIN = list(self.PIN.encode("utf-8")) + self.controller.smartcard_backend_preference = "keycard" + + # -- card lifecycle ------------------------------------------------ + + def _connect(self): + from seedsigner.helpers.keycard_connector import KeycardSatochipConnector + + if TestKeycardPSBTSigningFlows._connector is None: + connector = KeycardSatochipConnector.create(card_filter=["satochip"]) + connector.set_pin(0, list(self.PIN.encode("utf-8"))) + (_, _, _, status) = connector.card_get_status() + if status.get("setup_done"): + connector.card_verify_PIN() + TestKeycardPSBTSigningFlows._connector = connector + return TestKeycardPSBTSigningFlows._connector + + def _disconnect(self): + if TestKeycardPSBTSigningFlows._connector is not None: + try: + TestKeycardPSBTSigningFlows._connector.card_disconnect() + except Exception: + pass + TestKeycardPSBTSigningFlows._connector = None + + def _initialise(self): + """ + Provision the applet and load the seed, on one session. + + This is deliberately a single step. card_setup leaves the session that + ran it authenticated -- card_get_status returns the applet's full native + status -- and LOAD KEY is accepted there. A connector built afterwards + against the same, now set-up card comes back in a reduced state (status + answers with a four-field fallback rather than the native record) and the + applet refuses LOAD KEY with 0x6985. So the seed goes on while the card + is still talking to the session that set it up. + + The class fixture installs a blank applet first, so this always runs the + full path rather than resuming a half-initialised card. + """ + connector = self._connect() + pin_list = list(self.PIN.encode("utf-8")) + + (_, _, _, status) = connector.card_get_status() + if not status.get("setup_done"): + if connector.needs_secure_channel: + connector.card_initiate_secure_channel() + connector.card_setup( + pin_tries_0=5, ublk_tries_0=1, + pin_0=self.PIN, ublk_0=list(bytes(range(16))), + pin_tries_1=1, ublk_tries_1=1, + pin_1="654321", ublk_1=b"654321", + secmemsize=0x0000, memsize=0, + create_object_ACL=0x01, create_key_ACL=0x01, create_pin_ACL=0x01, + ) + connector.set_pin(0, pin_list) + + (_, _, _, status) = connector.card_get_status() + if not (status.get("key_initialized") or status.get("is_seeded")): + (_, sw1, sw2) = connector.card_bip32_import_seed( + list(Seed(mnemonic=BIP39_MNEMONIC).seed_bytes)) + # card_bip32_import_seed reports failure in its status word rather + # than by raising, so an unchecked call looks like a success and only + # shows up later as an unexplained 0x6985 on every derivation. + if (sw1, sw2) != (0x90, 0x00): + raise RuntimeError( + "Keycard refused the seed import: SW=%02X%02X" % (sw1, sw2)) + (_, _, _, status) = connector.card_get_status() + if not (status.get("key_initialized") or status.get("is_seeded")): + raise RuntimeError( + "Keycard accepted the seed import but reports no key: %s" % status) + + self._disconnect() diff --git a/tests/test_psbt_parser.py b/tests/test_psbt_parser.py index 76d1e70fb..ae508468a 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -4,16 +4,39 @@ from binascii import a2b_base64 from copy import deepcopy from unittest.mock import patch -from embit import bip32 +from embit import bip32, script +from embit.ec import PublicKey from embit.networks import NETWORKS from embit.psbt import PSBT, DerivationPath from embit.descriptor import Descriptor -from seedsigner.models.psbt_parser import PSBTParser +from seedsigner.models.psbt_parser import InvalidPSBTError, PSBTParser, RejectCode + + +def raises_reject(code): + """ + The fork folds upstream's PSBTVerificationError subclasses into one + InvalidPSBTError carrying a RejectCode, so an upstream `pytest.raises(SomeError)` + becomes a raises() plus a check on the code. See psbt_parser.RejectCode. + """ + import pytest + class _Ctx: + def __enter__(self): + self._raises = pytest.raises(InvalidPSBTError) + self.excinfo = self._raises.__enter__() + return self + def __exit__(self, *exc): + handled = self._raises.__exit__(*exc) + if handled: + assert self.excinfo.value.code == code, ( + f"expected {code}, got {self.excinfo.value.code}") + return handled + return _Ctx() from seedsigner.models.seed import Seed from seedsigner.models.settings_definition import SettingsConstants -from psbt_testing_util import PSBTTestData, create_output +from psbt_testing_util import (PSBTTestData, claim_seed_owns_key, create_output, + foreign_public_key, root_for_seed) @@ -209,15 +232,69 @@ def test_missing_fingerprint_handling(self): from binascii import hexlify fingerprint_hex = hexlify(derivation.fingerprint).decode() - # Check if this public key derives from the current seed + # Check if this public key derives from the current seed. A psbt + # carries a taproot key as its bare 32-byte x coordinate, and embit + # rebuilds a full key from it by just assuming even parity. The real + # derived key can be odd-parity, so a full-key compare would wrongly + # report a mismatch. Only the x coordinate is real data: compare + # x-only. derived_key = parser.root.derive(derivation.derivation) - if derived_key.key.sec() == pub.sec(): + if derived_key.xonly() == pub.xonly(): # This pubkey derives from current seed, should have current seed's fingerprint assert fingerprint_hex == seed_fingerprint, f"Expected {seed_fingerprint}, got {fingerprint_hex} for taproot pubkey that derives from current seed" else: # This pubkey doesn't derive from current seed, should remain 00000000 assert fingerprint_hex == "00000000" + # All of the above only proves the even-parity case. A psbt carries taproot keys + # as bare 32-byte x coordinates and embit rebuilds full keys from them by assuming + # even parity; that assumption happens to hold for the fixture's key at + # m/86h/1h/0h/0/0. Re-key the taproot input to a path whose key really derives + # with odd parity to prove the ownership fallback compares x-only rather than + # trusting embit's artificial parity. + root = root_for_seed(PSBTTestData.seed) + odd_parity_derivation_path = "m/86h/1h/0h/0/1" + odd_parity_public_key = root.derive(odd_parity_derivation_path).get_public_key() + assert odd_parity_public_key.sec()[0] == 0x03 # odd parity + + psbt = PSBT.parse(a2b_base64(PSBTTestData.SINGLE_SIG_TAPROOT_1_INPUT)) + taproot_input = psbt.inputs[0] + + # Present the key the way embit's psbt parsing yields it: rebuilt from just the + # x coordinate, carrying the assumed even parity (wrong for this key) + x_only_public_key = PublicKey.from_xonly(odd_parity_public_key.xonly()) + taproot_input.taproot_bip32_derivations.clear() + taproot_input.taproot_bip32_derivations[x_only_public_key] = ([], DerivationPath( + fingerprint=b"\x00\x00\x00\x00", + derivation=bip32.parse_path(odd_parity_derivation_path) + )) + taproot_input.taproot_internal_key = x_only_public_key + taproot_input.witness_utxo.script_pubkey = script.p2tr(x_only_public_key) + # Rewriting witness_utxo leaves any non_witness_utxo describing the original + # script, and _validate_input refuses a prevout described two inconsistent ways + # (the BIP-143 amount-binding shape). A segwit input carrying witness_utxo alone + # is legal and is what this fixture means. + taproot_input.non_witness_utxo = None + + # The zeroed-fingerprint fallback check must recognize this input as the seed's, + # even though embit's internal parity byte for the pubkey is wrong. Taproot + # pubkeys must be compared by their x-only representation. + assert PSBTParser.has_matching_input_fingerprint(psbt, PSBTTestData.seed, SettingsConstants.REGTEST) + + # Comparing x-only looks less strict than the full-key comparison used for + # non-taproot keys, but nothing is actually given up: a psbt never carries a + # parity byte for a taproot key, so the x coordinate is all the key material + # there is to compare. A completely wrong seed will still fail to match. + wrong_seed = Seed(["bacon"] * 24) + assert not PSBTParser.has_matching_input_fingerprint(psbt, wrong_seed, SettingsConstants.REGTEST) + + # Parsing should successfully fill the fingerprint and verify that the input + # belongs to the seed. + parser = PSBTParser(p=psbt, seed=PSBTTestData.seed, network=SettingsConstants.REGTEST) + (_, filled_derivation) = parser.psbt.inputs[0].taproot_bip32_derivations[x_only_public_key] + assert filled_derivation.fingerprint == parser.root.my_fingerprint + assert parser.verified_input_derivation_paths == [bip32.parse_path(odd_parity_derivation_path)] + def test_trim_and_sig_count(self): """ @@ -772,3 +849,421 @@ def build_psbt(case: tuple) -> PSBT: assert max(capped_sizes) == cap + +class TestPSBTParserSeedOwnership: + """ + The ownership scan: what the signing seed provably owns in a psbt, and the rejection + of any psbt whose ownership claims do not hold up. + """ + seed = PSBTTestData.seed + + def _root(self) -> bip32.HDKey: + return root_for_seed(self.seed) + + + def _psbt_with_change(self, input_base64: str = None, change_hex: str = None) -> PSBT: + """ + A base psbt plus its own change output. But no external recipient output is added, + so all paths are owned by the seed. + """ + if input_base64 is None: + input_base64 = PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_1_INPUT + if change_hex is None: + change_hex = PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_CHANGE + + psbt = PSBT.parse(a2b_base64(input_base64)) + psbt.outputs.append(create_output(change_hex, 10_000)) + return psbt + + + def _parse(self, psbt: PSBT) -> PSBTParser: + return PSBTParser(psbt, self.seed, network=SettingsConstants.REGTEST) + + + def test__seed_owns_pubkey__accepts_the_seeds_own_key(self): + """ + seed_owns_pubkey should confirm the simple base case that a pubkey directly + derived from the seed is owned by the seed. + """ + root = self._root() + derivation_path = bip32.parse_path("m/84h/1h/0h/0/0") + public_key = root.derive(derivation_path).get_public_key() + + assert PSBTParser.seed_owns_pubkey(root, derivation_path, public_key, child_key_derivation_cache=None) is True + + + def test__seed_owns_pubkey__rejects_a_key_the_seed_does_not_control(self): + """ + seed_owns_pubkey should reject a pubkey that the seed does not control. + """ + root = self._root() + derivation_path = bip32.parse_path("m/84h/1h/0h/0/0") + + assert PSBTParser.seed_owns_pubkey(root, derivation_path, foreign_public_key(), child_key_derivation_cache=None) is False + + + def test__seed_owns_pubkey__rejects_the_seeds_own_key_at_the_wrong_path(self): + """ + The path is as much a part of the claim as the key is. The seed owns this key, but + not at the path the claim names so it is still a false claim. + """ + root = self._root() + public_key = root.derive(bip32.parse_path("m/84h/1h/0h/0/0")).get_public_key() + + assert PSBTParser.seed_owns_pubkey(root, bip32.parse_path("m/84h/1h/0h/0/1"), public_key, child_key_derivation_cache=None) is False + + + def test__seed_owns_pubkey__compares_taproot_keys_without_parity(self): + """ + Taproot keys are x-only, so a key the seed genuinely owns routinely differs from + the derived key by the parity byte alone. Comparing the full key would read that + as a stranger's key and reject the seed's own output. + """ + root = self._root() + + # Address index 1 is the first whose derived key has odd parity, which is the + # case where a full comparison and an x-only comparison disagree. + derivation_path = bip32.parse_path("m/86h/1h/0h/0/1") + public_key = root.derive(derivation_path).get_public_key() + + # Sanity check: the key's first byte is its parity, 0x02 for even, 0x03 for odd + assert public_key.sec()[0] == 0x03 + + # The psbt carries the key x-only, so reconstruct what it would hold: the same x + # coordinate, with the EVEN-parity prefix. + as_written_in_psbt = PublicKey.parse(b"\x02" + public_key.xonly()) + + # Taproot is x-only so it ignores the now-even parity byte + assert PSBTParser.seed_owns_pubkey(root, derivation_path, as_written_in_psbt, child_key_derivation_cache=None, is_taproot=True) is True + + # Non-taproot compares the full key so it rejects the key with the wrong parity byte + assert PSBTParser.seed_owns_pubkey(root, derivation_path, as_written_in_psbt, child_key_derivation_cache=None) is False + + + def test__parse__populates_verified_derivation_paths(self): + """ + The scan writes one verified_*_derivation_paths entry per input and per output + (regardless of ownership; not-owned paths are recorded as None) in the psbt's own + order. + """ + # The psbt fixture has one input and one output, both of which are owned by the + # seed. + psbt = self._psbt_with_change() + psbt_parser = self._parse(psbt) + + assert len(psbt_parser.verified_input_derivation_paths) == len(psbt.inputs) + assert len(psbt_parser.verified_output_derivation_paths) == len(psbt.outputs) + + # Every recorded path is one the seed really does derive the scope's key at + for scopes, verified_derivation_paths in [ + (psbt.inputs, psbt_parser.verified_input_derivation_paths), + (psbt.outputs, psbt_parser.verified_output_derivation_paths), + ]: + for scope, verified_derivation_path in zip(scopes, verified_derivation_paths): + assert verified_derivation_path is not None + public_key = list(scope.bip32_derivations.keys())[0] + assert PSBTParser.seed_owns_pubkey(psbt_parser.root, verified_derivation_path, public_key, child_key_derivation_cache=None) is True + + + def test__parse__verified_derivation_paths_none_for_not_owned_output(self): + """ + An output paying someone else is not a failure; the seed simply owns nothing + there so the matching verified_output_derivation_paths should be None. + """ + psbt = self._psbt_with_change() + + # Add an external recipient at index 0 + psbt.outputs.insert(0, create_output(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_RECEIVE, 10_000)) + + psbt_parser = self._parse(psbt) + + assert psbt_parser.verified_output_derivation_paths[0] is None + assert psbt_parser.verified_output_derivation_paths[1] is not None + + + def test__parse__verified_derivation_paths_none_for_not_owned_input(self): + """ + A collaborative spend also includes an input belonging to another party, in two + shapes: a payjoin counterparty's input arrives finalized with no derivation info + at all (BIP-78 requires the sender to verify no keypaths appear anywhere), while + a coordinator managing every party's wallet writes each party's genuine + derivation entry. Neither is a failure; the seed simply owns nothing there. + """ + psbt = self._psbt_with_change() + + # The other party's input: their utxo, carrying no derivation info + foreign_input = deepcopy(psbt.inputs[0]) + foreign_input.bip32_derivations.clear() + foreign_input.witness_utxo.script_pubkey = script.p2wpkh(foreign_public_key()) + # See the note in test_missing_fingerprint_handling: the copied non_witness_utxo + # still describes our own script, which _validate_input reads as a prevout + # described two ways. A real payjoin input carries witness_utxo alone anyway. + foreign_input.non_witness_utxo = None + psbt.inputs.append(foreign_input) + + # The payjoin shape + psbt_parser = self._parse(psbt) + assert psbt_parser.verified_input_derivation_paths[0] is not None + assert psbt_parser.verified_input_derivation_paths[1] is None + + # The coordinated shape: the derivation entry is truthful, naming the other + # party's fingerprint and a key that party really controls. + claim_seed_owns_key(foreign_input, "m/84h/1h/0h/0/0", foreign_public_key(), seed=PSBTTestData.recipient_seed) + psbt_parser = self._parse(psbt) + assert psbt_parser.verified_input_derivation_paths[0] is not None + assert psbt_parser.verified_input_derivation_paths[1] is None + + + def test__parse__rejects_a_forged_claim_on_an_input(self): + """ + `parse` should raise RejectCode.FORGED_INPUT_OWNERSHIP when a psbt carries a false + claim that the seed owns an input that it does not actually control. + """ + psbt = self._psbt_with_change() + claim_seed_owns_key(psbt.inputs[0], "m/84h/1h/0h/0/0", foreign_public_key()) + + with raises_reject(RejectCode.FORGED_INPUT_OWNERSHIP): + self._parse(psbt) + + + def test__parse__rejects_a_forged_claim_on_an_output(self): + """ + `parse` should raise RejectCode.FORGED_OUTPUT_OWNERSHIP when a psbt carries a false + claim that the seed owns an output that it does not actually control. This is + the fake-change attack scenario that is more severe than a forged input claim. + """ + psbt = self._psbt_with_change() + claim_seed_owns_key(psbt.outputs[0], "m/84h/1h/0h/1/0", foreign_public_key()) + + # The output-scope error specifically: the dire, attack-framed rejection + with raises_reject(RejectCode.FORGED_OUTPUT_OWNERSHIP): + self._parse(psbt) + + + def test__parse__forged_output_claim_outranks_forged_input_claim(self): + """ + The scan stops at the first false claim, so scan order decides which error the + psbt is reported with. A false output claim is the fake-change forgery and must + be the one reported even when the same psbt also carries a false input claim -- + otherwise an attacker could plant a throwaway input claim just to be routed to + the milder input-scope warning. + """ + psbt = self._psbt_with_change() + claim_seed_owns_key(psbt.inputs[0], "m/84h/1h/0h/0/0", foreign_public_key()) + claim_seed_owns_key(psbt.outputs[0], "m/84h/1h/0h/1/0", foreign_public_key()) + + # The output error is the more severe issue + with raises_reject(RejectCode.FORGED_OUTPUT_OWNERSHIP): + self._parse(psbt) + + + def test__parse__rejects_a_forged_taproot_claim(self): + """ + A false taproot claim is rejected the same way as an ecdsa one: the input-scope + error on an input, the output-scope (attack) error on an output. Taproot claims + live in their own taproot_bip32_derivations dict, so the scan's coverage of that + dict is pinned on both scope types. + """ + psbt = self._psbt_with_change(PSBTTestData.SINGLE_SIG_TAPROOT_1_INPUT, PSBTTestData.SINGLE_SIG_TAPROOT_CHANGE) + claim_seed_owns_key(psbt.inputs[0], "m/86h/1h/0h/0/0", foreign_public_key(), is_taproot=True) + + with raises_reject(RejectCode.FORGED_INPUT_OWNERSHIP): + self._parse(psbt) + + # The same forgery on a taproot output gets the attack classification + psbt = self._psbt_with_change(PSBTTestData.SINGLE_SIG_TAPROOT_1_INPUT, PSBTTestData.SINGLE_SIG_TAPROOT_CHANGE) + claim_seed_owns_key(psbt.outputs[0], "m/86h/1h/0h/1/0", foreign_public_key(), is_taproot=True) + + with raises_reject(RejectCode.FORGED_OUTPUT_OWNERSHIP): + self._parse(psbt) + + + def test__parse__rejects_a_forged_claim_on_a_multisig_scope(self): + """ + Multisig scopes legitimately carry one derivation entry per cosigner, but a + forged claim naming this seed's fingerprint is rejected there exactly as in + single-sig: the input-scope error on an input, the attack-classified error on + an output. + """ + psbt = self._psbt_with_change(PSBTTestData.MULTISIG_NATIVE_SEGWIT_1_INPUT, PSBTTestData.MULTISIG_NATIVE_SEGWIT_CHANGE) + claim_seed_owns_key(psbt.inputs[0], "m/48h/1h/0h/2h/0/9", foreign_public_key()) + + with raises_reject(RejectCode.FORGED_INPUT_OWNERSHIP): + self._parse(psbt) + + # The same forgery on the multisig change output gets the attack classification + psbt = self._psbt_with_change(PSBTTestData.MULTISIG_NATIVE_SEGWIT_1_INPUT, PSBTTestData.MULTISIG_NATIVE_SEGWIT_CHANGE) + claim_seed_owns_key(psbt.outputs[0], "m/48h/1h/0h/2h/1/9", foreign_public_key()) + + with raises_reject(RejectCode.FORGED_OUTPUT_OWNERSHIP): + self._parse(psbt) + + + def test__parse__rejects_a_forged_claim_behind_a_genuine_one(self): + """ + A scope can hold more than one key. Finding the one the seed owns is not a reason + to stop looking. + + No honest coordinator writes extra derivation entries on a single-sig scope; this + shape arrives only from buggy or adversarial software. The scan copes with it + because the same scan serves multisig, where multi-entry scopes are the norm. + """ + psbt = self._psbt_with_change() + + # The scope's own genuine derivation stays exactly where it is... + assert len(psbt.inputs[0].bip32_derivations) == 1 + + # ...but add a false claim to the bip32_derivations dict + claim_seed_owns_key(psbt.inputs[0], "m/84h/1h/0h/0/9", foreign_public_key()) + assert len(psbt.inputs[0].bip32_derivations) == 2 + assert list(psbt.inputs[0].bip32_derivations.keys())[-1] == foreign_public_key() + + with raises_reject(RejectCode.FORGED_INPUT_OWNERSHIP): + self._parse(psbt) + + + def test__parse__accepts_a_key_belonging_to_someone_else(self): + """ + Only a claim on THIS seed's fingerprint is ever checked. A key openly belonging to + another wallet says nothing about this seed and must not reject the psbt. + + No honest coordinator writes extra derivation entries on a single-sig scope; this + shape arrives only from buggy or adversarial software. The scan copes with it + because the same scan serves multisig, where multi-entry scopes are the norm. + """ + psbt = self._psbt_with_change() + other_seed = PSBTTestData.recipient_seed + claim_seed_owns_key(psbt.inputs[0], "m/84h/1h/0h/0/0", foreign_public_key(), seed=other_seed) + + # Confirm the fixture really does carry someone else's fingerprint + claimed_fingerprint = psbt.inputs[0].bip32_derivations[foreign_public_key()].fingerprint + assert claimed_fingerprint == root_for_seed(other_seed).my_fingerprint + assert claimed_fingerprint != self._root().my_fingerprint + + psbt_parser = self._parse(psbt) + + # The seed still owns its own key in that input, via the scope's genuine + # derivation. + assert psbt_parser.verified_input_derivation_paths[0] is not None + + + def test_genuine_fingerprint_collision_is_rejected_like_a_forgery(self): + """ + 4-byte fingerprints collide. The fixture pair were brute-force generated so that + they share a master fingerprint with no forgery involved, so a foreign party's + honest derivation entry can name our fingerprint on a key we do not control. + + The parser cannot distinguish that from a forged claim -- they are byte-for-byte + the same situation -- and so it deliberately fails the psbt as an input-scope + inconsistency. + """ + foreign_root = root_for_seed(PSBTTestData.collision_seed_b) + + # The collision is real: same fingerprint, different key material + signing_root = root_for_seed(PSBTTestData.collision_seed_a) + assert foreign_root.my_fingerprint == signing_root.my_fingerprint + assert foreign_root.get_public_key() != signing_root.get_public_key() + + # The foreign party's own genuine entry on their own input: their true + # fingerprint beside their true key, no forgery anywhere + psbt = self._psbt_with_change() + foreign_derivation_path = bip32.parse_path("m/84h/1h/0h/0/0") + colliding_public_key = foreign_root.derive(foreign_derivation_path).get_public_key() + psbt.inputs[0].bip32_derivations[colliding_public_key] = DerivationPath(foreign_root.my_fingerprint, foreign_derivation_path) + + with raises_reject(RejectCode.FORGED_INPUT_OWNERSHIP): + PSBTParser(psbt, PSBTTestData.collision_seed_a, network=SettingsConstants.REGTEST) + + + def test_ownership_scan_derives_through_the_cache(self): + """ + Ownership verification does its own deriving and the later parse phases do theirs, + but all of it flows through one shared cache: across the whole parse, each unique + path level is derived exactly once, no matter how many scopes claim it or how many + phases revisit it. + + Note that even the initial pass benefits from the cache by skipping shared + levels that have already been derived. + """ + psbt = self._psbt_with_change() + + # Boost to 10 inputs from the same wallet, all sharing the one derivation path + for _ in range(9): + psbt.inputs.append(deepcopy(psbt.inputs[0])) + + # How deep does the derivation path go? + num_levels = len(list(psbt.inputs[0].bip32_derivations.values())[0].derivation) + + # Count every level actually derived over the course of the parse + num_derivations = 0 + uncounted_child = bip32.HDKey.child + def counting_child(self, index, hardened=False): + nonlocal num_derivations + num_derivations += 1 + return uncounted_child(self, index, hardened) + + with patch.object(bip32.HDKey, "child", counting_child): + psbt_parser = self._parse(psbt) + + # Sanity check: the scan really did run over all ten inputs and the change output + assert len(psbt_parser.verified_input_derivation_paths) == 10 + assert all(path is not None for path in psbt_parser.verified_input_derivation_paths) + assert psbt_parser.verified_output_derivation_paths[0] is not None + + # The inputs were cloned so they all use the same path with num_levels depth. The + # change output differs only in its last two levels. Verify that each of these + # levels was derived exactly once. + assert num_derivations == num_levels + 2 + + + def test__parse__rejects_a_seed_that_owns_no_input(self): + """ + The wrong seed for a psbt can produce no signature at all, so parsing raises + RejectCode.SEED_CANNOT_SIGN rather than letting the flow discover it after the user + has approved. + + And under the same wrong-seed conditions, embit will produce no signature anyway. + """ + psbt = self._psbt_with_change() + + # Intentionally use the wrong seed + with raises_reject(RejectCode.SEED_CANNOT_SIGN): + PSBTParser(psbt, PSBTTestData.recipient_seed, network=SettingsConstants.REGTEST) + + # Try to sign with the wrong seed anyway + root = root_for_seed(PSBTTestData.recipient_seed) + assert psbt.sign_with(root) == 0 + + + def test__parse__accepts_a_cosigner_seed_on_a_multisig(self): + """ + Each cosigner holding a key on the device signs the same psbt in turn, so a seed + that owns an input must pass whether or not it is the first one used. + """ + psbt = self._psbt_with_change(PSBTTestData.MULTISIG_NATIVE_SEGWIT_1_INPUT, PSBTTestData.MULTISIG_NATIVE_SEGWIT_CHANGE) + + psbt_parser = PSBTParser(psbt, PSBTTestData.seed, network=SettingsConstants.REGTEST) + assert any(path is not None for path in psbt_parser.verified_input_derivation_paths) + + psbt_parser = PSBTParser(psbt, PSBTTestData.multisig_key_2, network=SettingsConstants.REGTEST) + assert any(path is not None for path in psbt_parser.verified_input_derivation_paths) + + psbt_parser = PSBTParser(psbt, PSBTTestData.multisig_key_3, network=SettingsConstants.REGTEST) + assert any(path is not None for path in psbt_parser.verified_input_derivation_paths) + + + def test_a_psbt_with_no_utxos_is_rejected_rather_than_crashing(self): + """ + A psbt with no inputs is malformed and cannot be signed. `parse` should raise + RejectCode.SEED_CANNOT_SIGN. Note that diagnosing the malformation is not this check's + job. + """ + psbt = self._psbt_with_change() + for psbt_input in psbt.inputs: + psbt_input.witness_utxo = None + psbt_input.non_witness_utxo = None + psbt_input._utxo = None + psbt_input.bip32_derivations.clear() + + with raises_reject(RejectCode.SEED_CANNOT_SIGN): + self._parse(psbt) diff --git a/tests/test_psbt_refusal_screens.py b/tests/test_psbt_refusal_screens.py index 931d9e1d5..fa88b012d 100644 --- a/tests/test_psbt_refusal_screens.py +++ b/tests/test_psbt_refusal_screens.py @@ -16,7 +16,7 @@ from seedsigner.gui.screens.screen import ButtonOption, WarningScreen from seedsigner.models.psbt_parser import MAX_MONEY, PSBTParser -from seedsigner.views.psbt_views import PSBTOverviewView +from seedsigner.views.psbt_views import REJECT_PRESENTATION, RejectPresentation from psbt_suite_util import REJECT_PARSER_VECTORS, suite_seed, SUITE_NETWORK, load_psbt @@ -70,13 +70,13 @@ def stub_renderer(): yield -def measure(text: str) -> tuple[int, int, int]: - """Returns (box_height, line_count, text_height) for a WarningScreen body.""" - screen = WarningScreen( +def measure(text: str, screen_cls=None, headline=None, button_label="Done") -> tuple[int, int, int]: + """Returns (box_height, line_count, text_height) for a refusal screen body.""" + screen = (screen_cls or WarningScreen)( title="Invalid PSBT", - status_headline=None, + status_headline=headline, text=text, - button_data=[ButtonOption("Done")], + button_data=[ButtonOption(button_label)], show_back_button=False, ) text_area = [c for c in screen.components if c.__class__.__name__ == "TextArea"][-1] @@ -85,8 +85,8 @@ def measure(text: str) -> tuple[int, int, int]: return text_area.height, lines, height -def assert_fits(text: str, label: str): - box, lines, height = measure(text) +def assert_fits(text: str, label: str, screen_cls=None, headline=None, button_label="Done"): + box, lines, height = measure(text, screen_cls, headline, button_label) assert height <= box, ( f"{label}: {lines} lines, {height}px in a {box}px box — this renders over " f"the button. Shorten it.\n {text!r}" @@ -104,11 +104,16 @@ def test_real_refusal_message_fits(self, vector): with pytest.raises(InvalidPSBTError) as excinfo: PSBTParser(p=load_psbt(vector.name), seed=suite_seed(), network=SUITE_NETWORK) + presentation = REJECT_PRESENTATION.get(excinfo.value.code, RejectPresentation()) + assert presentation.text is None, ( + f"{vector.name}: this code now renders fixed prose, so the parser's own " + f"message is never shown; cover it in test_table_prose_fits instead.") + text = str(excinfo.value) - tip = PSBTOverviewView.REJECT_TIPS.get(excinfo.value.code) - if tip: - text += "\n" + tip - assert_fits(text, vector.name) + if presentation.tip: + text += "\n" + presentation.tip + assert_fits(text, vector.name, presentation.screen, + presentation.headline, presentation.button_label) def test_worst_case_values_fit(self): """ @@ -127,6 +132,31 @@ def test_worst_case_values_fit(self): for label, text in cases.items(): assert_fits(text, label) + def test_table_prose_fits(self): + """ + The entries that render fixed prose instead of the parser's message. These never + reach test_real_refusal_message_fits, and they use the dire and info screens, + whose headline and icon eat into the same 240x240 budget. + """ + for code, presentation in REJECT_PRESENTATION.items(): + if presentation.text is None: + continue + assert_fits(presentation.text, code, presentation.screen, + presentation.headline, presentation.button_label) + + + def test_every_reject_code_has_a_reachable_destination(self): + """ + A typo in destination_name would only surface when a user hit that refusal on + the device, so resolve every one of them here. + """ + from seedsigner.views import psbt_views + + for code, presentation in REJECT_PRESENTATION.items(): + assert hasattr(psbt_views, presentation.destination_name), ( + f"{code}: no View named {presentation.destination_name}") + + def test_gap_limit_tip_survives_a_verbose_translation(self): """ The one refusal that carries a tip is also the one with two numbers in diff --git a/tests/test_psbt_test_suite.py b/tests/test_psbt_test_suite.py index 2d41fb09d..2ffc6c1ef 100644 --- a/tests/test_psbt_test_suite.py +++ b/tests/test_psbt_test_suite.py @@ -294,14 +294,14 @@ class TestEvidenceCannotBeForged: gets its own test. """ - def _tx01_with(self, mutate): + def _tx01_with(self, mutate, expected_code=None): from psbt_suite_util import RejectCode psbt = load_psbt("TX-01") mutate(psbt) with pytest.raises(InvalidPSBTError) as excinfo: PSBTParser(p=psbt, seed=suite_seed(), network=SUITE_NETWORK) - assert excinfo.value.code == RejectCode.UNREACHABLE_CHANGE_PATH + assert excinfo.value.code == (expected_code or RejectCode.UNREACHABLE_CHANGE_PATH) def test_self_consistent_input_path_lie_is_rejected(self): """ @@ -331,13 +331,22 @@ def test_withholding_input_derivations_is_rejected(self): The cheaper attack: supply no input derivations at all, so no evidence can be gathered and a naive check has nothing to compare against. No evidence must not read as permission. + + The refusal now comes from the ownership scan rather than from the change + binding check, and says so: with every input derivation stripped, the seed + provably owns nothing on any input, which is what SEED_CANNOT_SIGN means. It + runs first, so it answers before the change path is ever examined. The + invariant this test exists to protect is unchanged -- the psbt is refused, + never displayed -- and the diagnosis is the more accurate of the two. """ + from psbt_suite_util import RejectCode + def strip(psbt): for inp in psbt.inputs: inp.bip32_derivations.clear() inp.taproot_bip32_derivations.clear() - self._tx01_with(strip) + self._tx01_with(strip, RejectCode.SEED_CANNOT_SIGN) def test_cosigner_derivations_are_not_treated_as_our_evidence(self): """