diff --git a/src/seedsigner/helpers/embit_utils.py b/src/seedsigner/helpers/embit_utils.py index 0eea39faf..e43c4c441 100644 --- a/src/seedsigner/helpers/embit_utils.py +++ b/src/seedsigner/helpers/embit_utils.py @@ -235,9 +235,15 @@ def parse_derivation_path(derivation_path: str) -> dict: sections = derivation_path.split("/") - if sections[1] == "48h": - # So far this helper is only meant for single sig message signing - raise Exception("Not implemented") + # The path can come verbatim from an untrusted signmessage QR. A path too short + # to name a purpose and coin type, or a multisig (48h) one -- this helper is + # only meant for single sig -- is reported as an unclean match, which callers + # already turn into "not supported", rather than raised as a System Error. + if len(sections) < 3 or sections[1] == "48h": + return dict( + script_type=None, network=None, is_change=None, index=None, + wallet_derivation_path=None, clean_match=False, + ) lookups = { "script_types": { diff --git a/src/seedsigner/helpers/ur2/fountain_decoder.py b/src/seedsigner/helpers/ur2/fountain_decoder.py index 9e8dcdf34..268830cae 100644 --- a/src/seedsigner/helpers/ur2/fountain_decoder.py +++ b/src/seedsigner/helpers/ur2/fountain_decoder.py @@ -8,6 +8,16 @@ from .fountain_utils import choose_fragments, contains, is_strict_subset, set_difference from .utils import join_lists, join_bytes, crc32_int, xor_with, take_first +# A part's seq_len comes straight off a scanned QR; the UR parser only rejects values +# below 1 or above 2**64. validate_part() builds a set that size and choose_fragments() +# runs a shuffle quadratic in it, so one frame could exhaust memory or hang a Pi Zero +# for hours. The shuffle is part of the fountain code and can't be changed without +# breaking interoperability, so the count is bounded instead. 10,000 fragments is far +# beyond any real message (100 KB even at a 10-byte fragment). Same bound as upstream +# SeedSigner #970. +MAX_SEQ_LEN = 10000 + + class InvalidPart(Exception): pass @@ -268,6 +278,10 @@ def process_mixed_part(self, p): self.mixed_parts[p2.indexes] = p2 def validate_part(self, p): + # Reject implausible part counts before allocating anything sized by them + if p.seq_len < 1 or p.seq_len > MAX_SEQ_LEN: + return False + # If this is the first part we've seen if self.expected_part_indexes == None: # Record the things that all the other parts we see will have to match to be valid. diff --git a/src/seedsigner/models/decode_qr.py b/src/seedsigner/models/decode_qr.py index 6e3ebb7a7..10a79839f 100644 --- a/src/seedsigner/models/decode_qr.py +++ b/src/seedsigner/models/decode_qr.py @@ -717,7 +717,9 @@ def detect_segment_type(s, wordlist_language_code=None): return QRType.WALLET__GENERIC # Seed - if re.search(r'\d{48,96}', s): + # The whole payload, not merely a digit run inside something else (a + # SettingsQR with a long number in it is not a seed). + if re.fullmatch(r'(?:\d{4}){12,24}', s.strip()): return QRType.SEED__SEEDQR # Bitcoin Address @@ -1218,7 +1220,13 @@ def add(self, segment, qr_type=QRType.SEED__SEEDQR): if len(self.seed_phrase) > 0: if not self.has_valid_word_count(): return DecodeQRStatus.INVALID - self.seed_type = "bip39" + # Hand-transcribed SeedQRs are exactly where a wrong digit is + # expected, and the checksum is what catches it. Unchecked, the + # bad mnemonic only failed later, as a System Error. + seed_type = self._classify_mnemonic(self.seed_phrase) + if seed_type is None: + return DecodeQRStatus.INVALID + self.seed_type = seed_type self.complete = True self.collected_segments = 1 return DecodeQRStatus.COMPLETE @@ -1249,23 +1257,10 @@ def add(self, segment, qr_type=QRType.SEED__SEEDQR): if not self.has_valid_word_count(): return DecodeQRStatus.INVALID - is_valid_bip39 = False - try: - Seed(seed_phrase_list, passphrase="", wordlist_language_code=self.wordlist_language_code) - is_valid_bip39 = True - except Exception: - is_valid_bip39 = False - - is_valid_aezeed = len(seed_phrase_list) == 24 and aezeed_has_valid_checksum(seed_phrase_list, self.word_to_index) - - if is_valid_aezeed and is_valid_bip39: - self.seed_type = "ambiguous" - elif is_valid_aezeed: - self.seed_type = "aezeed" - elif is_valid_bip39: - self.seed_type = "bip39" - else: + seed_type = self._classify_mnemonic(seed_phrase_list) + if seed_type is None: return DecodeQRStatus.INVALID + self.seed_type = seed_type self.seed_phrase = seed_phrase_list self.complete = True @@ -1312,6 +1307,29 @@ def get_seed_type(self): return self.seed_type return None + def _classify_mnemonic(self, words: list) -> str | None: + """ + "bip39", "aezeed", or "ambiguous" (both checksums pass) for a mnemonic whose + checksum holds; None when neither does. + """ + is_valid_bip39 = False + try: + Seed(words, passphrase="", wordlist_language_code=self.wordlist_language_code) + is_valid_bip39 = True + except Exception: + is_valid_bip39 = False + + is_valid_aezeed = len(words) == 24 and aezeed_has_valid_checksum(words, self.word_to_index) + + if is_valid_aezeed and is_valid_bip39: + return "ambiguous" + elif is_valid_aezeed: + return "aezeed" + elif is_valid_bip39: + return "bip39" + return None + + def has_valid_word_count(self): return len(self.seed_phrase) in (12, 15, 18, 21, 24) @@ -1440,10 +1458,14 @@ def add(self, segment, qr_type=QRType.SIGN_MESSAGE): signmessage {derivation_path} ascii:{message} """ - parts = segment.split() + # Split off the header only: the message itself may contain spaces or + # another "ascii:". A malformed payload is INVALID, never an IndexError -- + # this decoder runs inside the camera loop, where an exception is a crash. + parts = segment.split(maxsplit=2) + if len(parts) < 3 or ":" not in parts[2]: + return DecodeQRStatus.INVALID self.derivation_path = parts[1].replace("h", "'") - fmt = parts[2].split(":")[0] - self.message = segment.split(f"{fmt}:")[1] + fmt, self.message = parts[2].split(":", 1) # TODO: support formats other than ascii? if fmt != "ascii": diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 9f35c6a0d..c50f70888 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -21,6 +21,10 @@ class OPCODES: OP_RETURN = 106 OP_PUSHDATA1 = 76 + OP_PUSHDATA2 = 77 + OP_PUSHDATA4 = 78 + OP_CHECKLOCKTIMEVERIFY = 177 + OP_CHECKSEQUENCEVERIFY = 178 # Consensus ceiling on any single amount, in sats. @@ -78,6 +82,14 @@ class RiskWarning: FUTURE_LOCKTIME = "FUTURE_LOCKTIME" LOCKTIME_FAR_FUTURE = "LOCKTIME_FAR_FUTURE" RELATIVE_TIMELOCK = "RELATIVE_TIMELOCK" + + # An output's own script contains OP_CHECKLOCKTIMEVERIFY or + # OP_CHECKSEQUENCEVERIFY. Unlike the two locktime warnings above, which + # delay *this* transaction, this locks the funds the output receives: + # consensus rejects any spend of them until the condition is met. The + # address alone never shows it. + SCRIPT_TIMELOCK = "SCRIPT_TIMELOCK" + RBF = "RBF" # Recorded, but not worth interrupting the user for. Opt-in RBF is the @@ -120,6 +132,10 @@ class RejectCode: # 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. + # + # Also raised for the mirror image: the claimed key really is ours, but the + # output's script pays someone else. Proving the key is only half the claim; + # the other half is that this output is locked to it. FORGED_OUTPUT_OWNERSHIP = "FORGED_OUTPUT_OWNERSHIP" # The same false claim, but on an input, where the threat picture inverts. A @@ -138,6 +154,26 @@ class RejectCode: # transaction into unsignability. FORGED_INPUT_OWNERSHIP = "FORGED_INPUT_OWNERSHIP" + # A single-key output carries more than one derivation claim. One key can + # only sit at one path, so the extras are either malformed or there to make + # a checker that reads only the first entry pass over a false one. + SURPLUS_DERIVATIONS = "SURPLUS_DERIVATIONS" + + # A scope declares both ecdsa and taproot derivations for this seed. No + # wallet produces this; it exists to confuse which key form is checked. + MIXED_DERIVATION_MAPS = "MIXED_DERIVATION_MAPS" + + # An output pays a key this seed derives, but the psbt attributes that key to + # another wallet's fingerprint. No funds are lost -- the output really is ours -- + # but the psbt misdescribes its own outputs, and one that lies about ownership in + # this direction cannot be trusted about anything else. + MISLABELED_OUTPUT_OWNERSHIP = "MISLABELED_OUTPUT_OWNERSHIP" + + # A key's derivation entry and the global xpub that derives it name different + # master fingerprints. Both are the coordinator's claims about the same key, so + # one of them is wrong; nothing says which, so it is not graded as an attack. + INCONSISTENT_FINGERPRINTS = "INCONSISTENT_FINGERPRINTS" + # 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 @@ -223,6 +259,7 @@ def __init__( reference_time: int | None = None, max_fee_rate: float | None = None, block_anchor: tuple[int, int] | None = None, + multisig_descriptor: Descriptor | None = None, ): self.psbt: PSBT = p self.seed = seed @@ -237,6 +274,16 @@ def __init__( self.reference_time = reference_time self.block_anchor = block_anchor + # A user-loaded, known-good multisig descriptor. Without one, multisig change + # can only be identified when the psbt's global xpubs tie every cosigner key + # back to the inputs' wallet; see _parse_outputs. + self.multisig_descriptor = multisig_descriptor + + # Output indexes that look like multisig change (same script shape, our key + # among the cosigners) but that nothing could tie to the inputs' wallet. They + # are presented as payments until a descriptor identifies them. + self.unidentified_change_outputs: list[int] = [] + self.change_index_lookahead = ( change_index_lookahead if change_index_lookahead is not None @@ -347,7 +394,10 @@ def parse(self): 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. + verification. The claims that survive are then checked for shape + (_verify_claim_shapes: SURPLUS_DERIVATIONS, MIXED_DERIVATION_MAPS) and, + on outputs, against the script they sit on + (_verify_output_claims_match_scripts: FORGED_OUTPUT_OWNERSHIP). 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, @@ -420,6 +470,9 @@ def parse(self): # 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._verify_claim_shapes() + self._verify_output_claims_match_scripts() + self._reject_mislabeled_outputs(child_key_derivation_cache) self._reject_if_seed_cannot_sign() rt = self._parse_inputs(child_key_derivation_cache) @@ -433,6 +486,10 @@ def parse(self): if rt == False: return False + # Last, so that a more serious finding about this seed's own keys is the + # one reported. + self._reject_inconsistent_fingerprints(child_key_derivation_cache) + return True @@ -825,6 +882,24 @@ def _validate_input(index: int, inp: InputScope): code=RejectCode.MISSING_UTXO, ) + if non_witness_utxo is not None: + # non_witness_utxo is the whole previous transaction, so unlike + # witness_utxo it can be proven: it has to hash to the txid this input + # spends. A legacy signature commits to no amount at all, so an altered + # previous tx is enough to understate an input and hide the difference + # in the fee, in a single signing. (embit's InputScope.verify does the + # same hash, but raises bare exceptions and skips inputs without one.) + if non_witness_utxo.txid() != inp.txid: + raise InvalidPSBTError( + f"Input {index} previous tx does not match the txid it spends.", + code=RejectCode.UTXO_MISMATCH, + ) + if inp.vout is None or not 0 <= inp.vout < len(non_witness_utxo.vout): + raise InvalidPSBTError( + f"Input {index} spends an output its previous tx does not have.", + code=RejectCode.UTXO_MISMATCH, + ) + if witness_utxo is not None and non_witness_utxo is not None: # Both forms supplied: they must describe the same prevout. This is # the BIP-143 amount-binding attack -- a lowered witness_utxo value @@ -887,6 +962,14 @@ def _validate_input(index: int, inp: InputScope): code=RejectCode.SCRIPT_HASH_MISMATCH, ) effective_type = inp.redeem_script.script_type() + if non_witness_utxo is None and effective_type not in ("p2wpkh", "p2wsh"): + # A p2sh that wraps no witness program is legacy (e.g. bare p2sh + # multisig): its signature commits to no amount, so a witness_utxo + # alone is an unprovable claim about it. + raise InvalidPSBTError( + f"Input {index} is legacy p2sh with no previous tx.", + code=RejectCode.INVALID_WITNESS_UTXO, + ) if effective_type == "p2wsh": if inp.witness_script is None: @@ -1191,6 +1274,17 @@ def _parse_outputs(self, child_key_derivation_cache: dict): if sc.data == vout[i].script_pubkey.data: is_change = True + if is_change and self.is_multisig and "cosigners" not in self.policy: + # The script is a well-formed m-of-n that contains our key, but with no + # global xpubs nothing ties its other keys to the inputs' wallet. A + # different wallet that shares our key -- the same m-of-n with one + # cosigner swapped for an attacker's -- looks identical. Labelling it + # change would hide it from review, so it stays a payment unless a + # known-good descriptor identifies it. + if self.multisig_descriptor is None or not self._descriptor_owns_output(self.multisig_descriptor, i): + is_change = False + self.unidentified_change_outputs.append(i) + if is_change: # The seed can derive this scriptPubKey, but the path is not one # any wallet will scan for. There is no honest reason to build @@ -1233,8 +1327,7 @@ def _parse_outputs(self, child_key_derivation_cache: dict): ) if vout[i].script_pubkey.data[0] == OPCODES.OP_RETURN: - # The data is written as: OP_RETURN + OP_PUSHDATA1 + len(payload) + payload - self.op_return_data = vout[i].script_pubkey.data[3:] + self.op_return_data = PSBTParser._op_return_payload(vout[i].script_pubkey.data) # Bitcoin Core v30 relaxed OP_RETURN standardness, so the amount # cannot be assumed to be zero. An OP_RETURN is provably @@ -1380,6 +1473,79 @@ def _collect_risk_warnings(self): self.risk_warnings.add(RiskWarning.RELATIVE_TIMELOCK) break + # CLTV / CSV inside an output's own script. Only a script the psbt + # supplies *and* that hashes to the scriptPubKey is read; anything else + # says nothing about what the output is really locked by. + vout = self.psbt.tx.vout + for i, out in enumerate(self.psbt.outputs): + committed = PSBTParser._committed_output_script(out, vout[i].script_pubkey) + if committed is not None and PSBTParser._script_has_timelock(committed): + self.risk_warnings.add(RiskWarning.SCRIPT_TIMELOCK) + break + + + @staticmethod + def _committed_output_script(out: OutputScope, script_pubkey): + """The supplied witness or redeem script this output is provably locked by, if any.""" + if out.witness_script is not None: + wsh = script.p2wsh(out.witness_script).data + if wsh == script_pubkey.data or script.p2sh(script.Script(wsh)).data == script_pubkey.data: + return out.witness_script + if out.redeem_script is not None and script.p2sh(out.redeem_script).data == script_pubkey.data: + return out.redeem_script + return None + + + @staticmethod + def _script_ops(data: bytes): + """ + Yields (opcode, pushed_bytes) for each operation in a script; pushed_bytes is + None for anything that is not a push. A push that runs past the end of the + script yields what is there and stops. + """ + pos = 0 + while pos < len(data): + op = data[pos] + pos += 1 + if 0x01 <= op <= 0x4b: + length = op + elif op == OPCODES.OP_PUSHDATA1: + length, pos = int.from_bytes(data[pos:pos + 1], "little"), pos + 1 + elif op == OPCODES.OP_PUSHDATA2: + length, pos = int.from_bytes(data[pos:pos + 2], "little"), pos + 2 + elif op == OPCODES.OP_PUSHDATA4: + length, pos = int.from_bytes(data[pos:pos + 4], "little"), pos + 4 + else: + yield op, None + continue + yield op, data[pos:pos + length] + pos += length + + + @staticmethod + def _script_has_timelock(sc) -> bool: + """ + Whether a script runs OP_CHECKLOCKTIMEVERIFY or OP_CHECKSEQUENCEVERIFY. + Walks the opcodes rather than searching the bytes, so a push that happens + to contain 0xb1 or 0xb2 is not mistaken for one. + """ + return any( + op in (OPCODES.OP_CHECKLOCKTIMEVERIFY, OPCODES.OP_CHECKSEQUENCEVERIFY) + for op, _pushed in PSBTParser._script_ops(sc.data) + ) + + + @staticmethod + def _op_return_payload(data: bytes) -> bytes: + """ + The data an OP_RETURN script carries: everything its pushes push, in order. + + Payloads of 75 bytes or fewer are pushed directly (OP_RETURN ), + which is how Bitcoin Core writes them; OP_PUSHDATA1 is only for longer ones. + Slicing at a fixed offset dropped the first byte of every short payload. + """ + return b"".join(pushed for _op, pushed in PSBTParser._script_ops(data[1:]) if pushed is not None) + @staticmethod @@ -1848,6 +2014,210 @@ def _verify_claimed_derivation_paths(self, child_key_derivation_cache: dict): ] + def _seed_claims(self, scope: InputScope | OutputScope) -> tuple[list, list]: + """ + The (ecdsa, taproot) claims in a scope that name this seed's fingerprint. + Taproot entries are (pubkey, leaf_hashes). + """ + seed_fingerprint = self.master_fingerprint or self.root.my_fingerprint + ecdsa = [pub for pub, d in scope.bip32_derivations.items() + if d.fingerprint == seed_fingerprint] + taproot = [(pub, leaf_hashes) for pub, (leaf_hashes, d) in scope.taproot_bip32_derivations.items() + if d.fingerprint == seed_fingerprint] + return ecdsa, taproot + + + def _verify_claim_shapes(self): + """ + Refuses claims that are each individually true but could not all be true + of one honest wallet's scope. + + Runs after _verify_claimed_derivation_paths, so every claim here already + re-derives from the seed; a claim that does not is reported as forged + rather than as mis-shaped. + + * MIXED_DERIVATION_MAPS: a scope naming this seed in both the ecdsa and + the taproot derivation maps. A script is one or the other. + * SURPLUS_DERIVATIONS: a single-key output naming this seed more than + once. Only one of those keys can be the one the script pays, so the + rest are decoys for a checker that reads only the first entry. + """ + if not self.can_verify_derivations: + return + + vout = self.psbt.tx.vout + scopes = [(out, vout[i].script_pubkey) for i, out in enumerate(self.psbt.outputs)] + scopes += [(inp, None) for inp in self.psbt.inputs] + + for scope, script_pubkey in scopes: + ecdsa, taproot = self._seed_claims(scope) + if ecdsa and taproot: + raise InvalidPSBTError( + "A transaction entry names this seed as both an ecdsa and a taproot key.", + code=RejectCode.MIXED_DERIVATION_MAPS, + ) + + if script_pubkey is None: + continue + + script_type = script_pubkey.script_type() + is_single_key = script_type in ("p2pkh", "p2wpkh") or ( + script_type == "p2sh" + and scope.redeem_script is not None + and scope.redeem_script.script_type() == "p2wpkh" + ) + key_path_claims = [pub for pub, leaf_hashes in taproot if not leaf_hashes] + if (is_single_key and len(ecdsa) > 1) or (script_type == "p2tr" and len(key_path_claims) > 1): + raise InvalidPSBTError( + "A single-key output names more than one of this seed's keys.", + code=RejectCode.SURPLUS_DERIVATIONS, + ) + + + @staticmethod + def _output_commits_to_key(out: OutputScope, script_pubkey, public_key) -> bool | None: + """ + Whether an output's scriptPubKey is locked to `public_key`. None when the + psbt does not carry enough to tell (a script-hash output with no script + supplied), which is left to the rest of the parse to judge. + + The output-side counterpart of _input_commits_to_key. + """ + sec = public_key.sec() + script_type = script_pubkey.script_type() + + if script_type == "p2wpkh": + return script.p2wpkh(public_key).data == script_pubkey.data + if script_type == "p2pkh": + return script.p2pkh(public_key).data == script_pubkey.data + if script_type == "p2wsh": + if out.witness_script is None: + return None + return (script.p2wsh(out.witness_script).data == script_pubkey.data + and sec in out.witness_script.data) + if script_type == "p2sh": + if script.p2sh(script.p2wpkh(public_key)).data == script_pubkey.data: + return True + redeem = out.redeem_script + if redeem is None: + return None + if script.p2sh(redeem).data != script_pubkey.data: + return False + if redeem.script_type() == "p2wsh": + witness = out.witness_script + return (witness is not None + and script.p2wsh(witness).data == redeem.data + and sec in witness.data) + if redeem.script_type() == "p2wpkh": + # Wraps a single key, and the check above showed it isn't this one. + return False + return sec in redeem.data + return None + + + def _verify_output_claims_match_scripts(self): + """ + Refuses an output whose derivation names one of this seed's keys when the + output's script is not locked to that key. + + _verify_claimed_derivation_paths proves the key is ours. That is only half + of an ownership claim: a psbt can annotate a stranger's output with a + genuine key and path of ours, and the key check alone passes it. Such an + output is not labelled change (the script comparison in _parse_outputs + fails), so it would be shown as an ordinary payment with no hint that the + psbt tried to pass it off as ours. + + Taproot claims are not checked here. A key-path claim can still sit under + a script tree this parser does not reconstruct, so a mismatch is not proof + of a lie; such outputs are simply never labelled change. + """ + if not self.can_verify_derivations: + return + + vout = self.psbt.tx.vout + for i, out in enumerate(self.psbt.outputs): + ecdsa, _taproot = self._seed_claims(out) + for public_key in ecdsa: + if PSBTParser._output_commits_to_key(out, vout[i].script_pubkey, public_key) is False: + raise InvalidPSBTError( + f"Output {i} is annotated with one of this seed's keys, " + f"but its script pays a different key.", + code=RejectCode.FORGED_OUTPUT_OWNERSHIP, + ) + + + def _reject_mislabeled_outputs(self, child_key_derivation_cache: dict): + """ + Refuses an output whose derivation names a foreign fingerprint on a key this + seed actually derives at that path. + + The mirror image of FORGED_OUTPUT_OWNERSHIP: there the psbt claims a key of + someone else's is ours; here it claims a key of ours is someone else's. The + second costs nothing directly, but it is still the psbt misdescribing who owns + its outputs, and ownership is decided by re-derivation in both directions. + + All-zero fingerprints were already filled in by _fill_missing_fingerprints, so + an xpub imported without its fingerprint (issue #359) does not land here. + """ + if not self.can_verify_derivations: + return + + seed_fingerprint = self.master_fingerprint or self.root.my_fingerprint + for i, out in enumerate(self.psbt.outputs): + claims = [(pub, d, False) for pub, d in out.bip32_derivations.items()] + claims += [(pub, d, True) for pub, (_, d) in out.taproot_bip32_derivations.items()] + for public_key, derivation_path_obj, is_taproot in claims: + if derivation_path_obj.fingerprint == seed_fingerprint: + continue + try: + ours = 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, + ) + except Exception as e: + # e.g. a hardened step below an account-level xpub root + logger.debug("Could not derive %s: %s", derivation_path_obj.derivation, e) + ours = False + if ours: + raise InvalidPSBTError( + f"Output {i} pays this seed but is labelled as another wallet's.", + code=RejectCode.MISLABELED_OUTPUT_OWNERSHIP, + ) + + + def _reject_inconsistent_fingerprints(self, child_key_derivation_cache: dict): + """ + Refuses a psbt where a key's derivation entry and the global xpub that derives + that key name different master fingerprints. + + Keys are matched to xpubs by derivation, not by fingerprint, so a mislabel + changes nothing downstream -- but it is a self-contradictory psbt, which is + refused like the others. All-zero fingerprints are skipped on either side: + coordinators write 00000000 for a fingerprint they do not know. + """ + zero = bytes(4) + for scope in list(self.psbt.inputs) + list(self.psbt.outputs): + for public_key, derivation_path_obj in scope.bip32_derivations.items(): + if derivation_path_obj.fingerprint == zero: + continue + path = derivation_path_obj.derivation + for xpub, origin in self.psbt.xpubs.items(): + if origin.fingerprint == zero or origin.fingerprint == derivation_path_obj.fingerprint: + continue + if len(path) < 2 or list(origin.derivation) != list(path[:-2]): + continue + try: + derived = PSBTParser._derive_with_cache(xpub, path[-2:], child_key_derivation_cache) + except Exception: + continue + if derived.key == public_key: + raise InvalidPSBTError( + "A key's fingerprint disagrees with the xpub that derives it.", + code=RejectCode.INCONSISTENT_FINGERPRINTS, + ) + + def _reject_if_seed_cannot_sign(self): """ Rejects the psbt when none of its inputs rely on a key derived by this seed. @@ -1887,12 +2257,49 @@ def _reject_if_seed_cannot_sign(self): def verify_multisig_output(self, descriptor: Descriptor, change_num: int) -> bool: - change_data = self.get_change_data(change_num) - i = change_data["output_index"] + """ + Whether a change output really is the known-good descriptor's. + + embit's Descriptor.owns stops at the first derivation that names one of the + descriptor's keys. A psbt listing a genuine entry first and a decoy after it + therefore passes, while the same entries in the other order fail. Here + every entry that names a descriptor key has to derive this output's script, + and has to be one of the keys that script actually contains. + """ + return self._descriptor_owns_output(descriptor, self.get_change_data(change_num)["output_index"]) + + + def _descriptor_owns_output(self, descriptor: Descriptor, i: int) -> bool: + """See verify_multisig_output; takes an output index rather than a change number.""" output = self.psbt.outputs[i] - is_owner = descriptor.owns(output) - # print(f"{self.psbt.tx.vout[i].script_pubkey.address()} | {output.value} | {is_owner}") - return is_owner + script_pubkey = self.psbt.tx.vout[i].script_pubkey + + if not output.bip32_derivations: + # Taproot descriptors carry their claims in the taproot map instead. + return descriptor.owns(output) + + if script_pubkey.script_type() != descriptor.scriptpubkey_type(): + return False + + matched = False + for public_key, derivation_path_obj in output.bip32_derivations.items(): + res = descriptor.check_derivation(derivation_path_obj) + if res is None: + continue + idx, branch_idx = res + derived = descriptor.derive(idx, branch_index=branch_idx) + if derived.script_pubkey().data != script_pubkey.data: + return False + committed = derived.witness_script() or derived.redeem_script() + if committed is not None: + if committed.script_type() == "p2wpkh": + # sh(wpkh): the script holds the key's hash, not the key. + if script.p2wpkh(public_key).data != committed.data: + return False + elif public_key.sec() not in committed.data: + return False + matched = True + return matched def _fill_missing_fingerprints(self, child_key_derivation_cache: dict): diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index 341b1e0f0..a5335cab6 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -511,6 +511,42 @@ class RejectPresentation: button_label=_mft("Discard transaction"), ), + # Both are ownership claims that could not all be honest at once: several of + # this seed's keys on a single-key output, or the same seed named as both an + # ecdsa and a taproot key. Same threat as a forged output. + RejectCode.SURPLUS_DERIVATIONS: RejectPresentation( + screen=DireWarningScreen, + title=_mft("Suspicious Transaction"), + headline=_mft("Likely an Attack!"), + # TRANSLATOR_NOTE: A psbt's claims about which keys belong to this seed contradict each other + text=_mft("This transaction makes contradictory claims about which keys are yours."), + button_label=_mft("Discard transaction"), + ), + + RejectCode.MIXED_DERIVATION_MAPS: RejectPresentation( + screen=DireWarningScreen, + title=_mft("Suspicious Transaction"), + headline=_mft("Likely an Attack!"), + text=_mft("This transaction makes contradictory claims about which keys are yours."), + button_label=_mft("Discard transaction"), + ), + + RejectCode.MISLABELED_OUTPUT_OWNERSHIP: RejectPresentation( + screen=WarningScreen, + title=_mft("Transaction Problem"), + # TRANSLATOR_NOTE: A psbt labels an output that really pays this seed as another wallet's + text=_mft("An output that pays this seed is labelled as another wallet's. The transaction misdescribes itself."), + button_label=_mft("Discard transaction"), + ), + + RejectCode.INCONSISTENT_FINGERPRINTS: RejectPresentation( + screen=WarningScreen, + title=_mft("Transaction Problem"), + # TRANSLATOR_NOTE: Two records in the psbt disagree about which wallet a key comes from + text=_mft("This transaction's records disagree about which wallet a key comes from."), + 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 @@ -667,6 +703,7 @@ def __init__(self): network=self.settings.get_value(SettingsConstants.SETTING__NETWORK), reference_time=getattr(self.controller, "psbt_source_time", None), block_anchor=(_Controller.RELEASE_BLOCK_HEIGHT, _Controller.RELEASE_BLOCK_TIME), + multisig_descriptor=self.controller.multisig_wallet_descriptor, ) except InvalidPSBTError as e: # A deliberate refusal, not a crash: the psbt is parseable but unsafe to @@ -723,19 +760,76 @@ def run(self): self.controller.psbt_seed = None return Destination(BackStackView) - if psbt_parser.risk_warnings - RiskWarning.INFORMATIONAL: - return Destination(PSBTRiskWarningView) + if psbt_parser.unidentified_change_outputs: + return Destination(PSBTIdentifyChangeView) - # expecting p2sh (legacy multisig) and p2pkh to have no policy set - # skip change warning and psbt math view - if psbt_parser.policy == None: - return Destination(PSBTUnsupportedScriptTypeWarningView) - - elif psbt_parser.change_amount == 0: - return Destination(PSBTNoChangeWarningView) + return post_overview_destination(psbt_parser) + + + +def post_overview_destination(psbt_parser: PSBTParser, skip_current_view: bool = False) -> Destination: + """Where review continues once the overview (and any interstitial after it) is done.""" + if psbt_parser.risk_warnings - RiskWarning.INFORMATIONAL: + return Destination(PSBTRiskWarningView, skip_current_view=skip_current_view) + + # expecting p2sh (legacy multisig) and p2pkh to have no policy set + # skip change warning and psbt math view + if psbt_parser.policy == None: + return Destination(PSBTUnsupportedScriptTypeWarningView, skip_current_view=skip_current_view) + elif psbt_parser.change_amount == 0: + return Destination(PSBTNoChangeWarningView, skip_current_view=skip_current_view) + + else: + return Destination(PSBTMathView, skip_current_view=skip_current_view) + + + +class PSBTIdentifyChangeView(View): + """ + Some output looks like this multisig wallet's change, but the psbt carries no global + xpubs to tie its other cosigner keys to the inputs' wallet. A different wallet that + shares our key would look the same, so PSBTParser shows it as a payment. Only the + wallet's descriptor can identify it as change. + """ + LOAD_DESCRIPTOR = ButtonOption("Load descriptor") + # TRANSLATOR_NOTE: Review the unidentified output as a payment, without loading a descriptor + CONTINUE_AS_PAYMENT = ButtonOption("Continue as payment") + CONTINUE = ButtonOption("Continue") + + def run(self): + psbt_parser: PSBTParser = self.controller.psbt_parser + if not psbt_parser: + # Should not be able to get here + return Destination(MainMenuView) + + if self.controller.multisig_wallet_descriptor: + # TRANSLATOR_NOTE: A loaded multisig descriptor did not match an output that looked like change + text = _("The loaded descriptor doesn't identify it. Shown as a payment.") + button_data = [self.CONTINUE] else: - return Destination(PSBTMathView) + # TRANSLATOR_NOTE: Multisig change can't be told apart from a payment without the wallet descriptor + text = _("Load descriptor to identify change.") + button_data = [self.LOAD_DESCRIPTOR, self.CONTINUE_AS_PAYMENT] + + selected_menu_num = self.run_screen( + WarningScreen, + # TRANSLATOR_NOTE: Headline when multisig change cannot be identified + status_headline=_("Change Not Identified"), + text=text, + button_data=button_data, + ) + + if selected_menu_num == RET_CODE__BACK_BUTTON: + return Destination(BackStackView) + + if button_data[selected_menu_num] == self.LOAD_DESCRIPTOR: + from seedsigner.controller import Controller + from seedsigner.views.seed_views import LoadMultisigWalletDescriptorView + self.controller.resume_main_flow = Controller.FLOW__PSBT + return Destination(LoadMultisigWalletDescriptorView) + + return post_overview_destination(psbt_parser, skip_current_view=True) @@ -758,6 +852,9 @@ class PSBTRiskWarningView(View): # TRANSLATOR_NOTE: BIP-68 relative timelock; the delay runs from when the # input confirmed, so no fixed date can be shown. RiskWarning.RELATIVE_TIMELOCK: _mft("An input is time-locked and cannot be spent yet."), + # TRANSLATOR_NOTE: An output's script (CLTV/CSV) locks the funds it + # receives, so whoever gets them cannot spend them until later. + RiskWarning.SCRIPT_TIMELOCK: _mft("An output is time-locked by its script; those funds cannot be spent until later."), RiskWarning.RBF: _mft("This transaction is marked replaceable (RBF)."), } diff --git a/src/seedsigner/views/seed_views.py b/src/seedsigner/views/seed_views.py index 7ced83b45..1874d8bd3 100644 --- a/src/seedsigner/views/seed_views.py +++ b/src/seedsigner/views/seed_views.py @@ -4813,9 +4813,17 @@ def run(self): return Destination(BackStackView) elif button_data[selected_menu_num] == self.RETURN: + self.controller.resume_main_flow = None + psbt_parser = self.controller.psbt_parser + if psbt_parser and psbt_parser.unidentified_change_outputs: + # The descriptor decides which outputs are change, so the psbt has to be + # read again with it; the review restarts from the overview. + from seedsigner.views.psbt_views import PSBTOverviewView + self.controller.psbt_parser = None + return Destination(PSBTOverviewView, skip_current_view=True) + # Jump straight back to PSBT change verification from seedsigner.views.psbt_views import PSBTChangeDetailsView - self.controller.resume_main_flow = None return Destination(PSBTChangeDetailsView, view_args=dict(change_address_num=0)) elif button_data[selected_menu_num].button_label.startswith(_(self.VERIFY_ADDR.button_label)): diff --git a/tests/base.py b/tests/base.py index 0834cdbf8..6a76edba3 100644 --- a/tests/base.py +++ b/tests/base.py @@ -19,6 +19,14 @@ _renderer_module.Renderer.get_instance.return_value.canvas_width = 240 _renderer_module.Renderer.get_instance.return_value.canvas_height = 240 sys.modules['seedsigner.gui.renderer'] = _renderer_module +# Views resolve the renderer as `from seedsigner.gui import Renderer`, i.e. through +# the package attribute, not sys.modules. If a test module collected before this +# one already imported seedsigner.gui (tests/test_psbt_refusal_screens.py does), +# that attribute is still the real, never-configured Renderer: every View -- and +# the error View the Controller falls back to -- raises "Must call +# Renderer.configure_instance() first", and the Controller loops on it forever. +if 'seedsigner.gui' in sys.modules: + sys.modules['seedsigner.gui'].Renderer = _renderer_module.Renderer sys.modules['seedsigner.gui.screens.screensaver'] = MagicMock() sys.modules['seedsigner.gui.toast'] = MagicMock() sys.modules['seedsigner.hardware.buttons'] = MagicMock() diff --git a/tests/data/psbt_test_suite/NORMAL-1_p2wpkh.psbt b/tests/data/psbt_test_suite/NORMAL-1_p2wpkh.psbt index 3b3cf3f21..9716924c9 100644 Binary files a/tests/data/psbt_test_suite/NORMAL-1_p2wpkh.psbt and b/tests/data/psbt_test_suite/NORMAL-1_p2wpkh.psbt differ diff --git a/tests/data/psbt_test_suite/NORMAL-1_p2wpkh_V2.psbt b/tests/data/psbt_test_suite/NORMAL-1_p2wpkh_V2.psbt index e27f5783b..52ae9092d 100644 Binary files a/tests/data/psbt_test_suite/NORMAL-1_p2wpkh_V2.psbt and b/tests/data/psbt_test_suite/NORMAL-1_p2wpkh_V2.psbt differ diff --git a/tests/data/psbt_test_suite/NORMAL-2_wrapped.psbt b/tests/data/psbt_test_suite/NORMAL-2_wrapped.psbt index 50b443e3b..6de123fe5 100644 Binary files a/tests/data/psbt_test_suite/NORMAL-2_wrapped.psbt and b/tests/data/psbt_test_suite/NORMAL-2_wrapped.psbt differ diff --git a/tests/data/psbt_test_suite/NORMAL-2_wrapped_V2.psbt b/tests/data/psbt_test_suite/NORMAL-2_wrapped_V2.psbt index 9782ee6f7..2dcebf2bc 100644 Binary files a/tests/data/psbt_test_suite/NORMAL-2_wrapped_V2.psbt and b/tests/data/psbt_test_suite/NORMAL-2_wrapped_V2.psbt differ diff --git a/tests/data/psbt_test_suite/NORMAL-3_legacy.psbt b/tests/data/psbt_test_suite/NORMAL-3_legacy.psbt index c2fa63f14..e68a754e2 100644 Binary files a/tests/data/psbt_test_suite/NORMAL-3_legacy.psbt and b/tests/data/psbt_test_suite/NORMAL-3_legacy.psbt differ diff --git a/tests/data/psbt_test_suite/NORMAL-3_legacy_V2.psbt b/tests/data/psbt_test_suite/NORMAL-3_legacy_V2.psbt index d169714fe..b5c14ae8b 100644 Binary files a/tests/data/psbt_test_suite/NORMAL-3_legacy_V2.psbt and b/tests/data/psbt_test_suite/NORMAL-3_legacy_V2.psbt differ diff --git a/tests/data/psbt_test_suite/NORMAL-4_multi_input.psbt b/tests/data/psbt_test_suite/NORMAL-4_multi_input.psbt index b9ba0f0e0..8d0e88a8f 100644 Binary files a/tests/data/psbt_test_suite/NORMAL-4_multi_input.psbt and b/tests/data/psbt_test_suite/NORMAL-4_multi_input.psbt differ diff --git a/tests/data/psbt_test_suite/NORMAL-4_multi_input_V2.psbt b/tests/data/psbt_test_suite/NORMAL-4_multi_input_V2.psbt index 72ada1820..3e3a2c34f 100644 Binary files a/tests/data/psbt_test_suite/NORMAL-4_multi_input_V2.psbt and b/tests/data/psbt_test_suite/NORMAL-4_multi_input_V2.psbt differ diff --git a/tests/data/psbt_test_suite/PROVENANCE.md b/tests/data/psbt_test_suite/PROVENANCE.md index 002c1d71b..f11d78d9f 100644 --- a/tests/data/psbt_test_suite/PROVENANCE.md +++ b/tests/data/psbt_test_suite/PROVENANCE.md @@ -30,6 +30,39 @@ meaning a coordinator may still add or remove inputs and outputs *after* we sign That voids the review, so it is refused (`RejectCode.TX_MODIFIABLE`) rather than merely warned about. A missing or zero `TX_MODIFIABLE` means final and is accepted. +## Resync of 2026-09-17 + +Re-vendored from the regenerated corpus (97 vectors). That regeneration fixed +the BIP-371 taproot derivation encoding, so TX-09.* and TX-11.v1_bech32 now +parse in embit, and it made TX-10, TX-14.cross_net and +XTRAS.NETWORK_HRP_MISMATCH real traps rather than vacuous ones. It added the +TX-19/20/21/22/23 families and the structural XTRAS vectors (missing utxo, +unsupported version, undisplayable outputs, witness/non-witness mismatch). + +Local deviations from upstream: + +* `XTRAS.LOCKTIME_FUTURE.psbt` is kept though upstream dropped it (superseded by + TX-19.timestamp_future); TestTimelocks mutates it. +* The TX-20 vectors were re-vendored on 2026-09-18 after two generator fixes + (P2WSH was built as a p2wpkh-shaped hash160, and OP_CLTV/OP_CSV had the wrong + opcode values); all three now carry a committed CLTV/CSV script. +* Only three vectors are refused by embit itself: TX-04, TX-13.duplicate and + XTRAS.TRUNCATED_PSBT. + +## Follow-up of 2026-09-18 + +Vectors added for the fixes brought over from the upstream SeedSigner PR review +(#995/#977, #965/#1003, #1040, and the #1032 review thread), generated with the +local psbt_faker: XTRAS.PREV_TX_TXID_MISMATCH(_V2), XTRAS.LEGACY_P2SH_WITNESS_ONLY, +XTRAS.OP_RETURN_DIRECT_PUSH(_V2), TX-24.xpub_fingerprint_mismatch, +TX-21.ms_foreign_quorum, TX-21.ms_foreign_quorum_no_xpubs and +TX-21.ms_honest_change_no_xpubs. XTRAS.MIXED_INPUT_TYPES was re-vendored too: its +legacy input used to spend its previous tx by a placeholder txid. + +The multisig vectors (TX-04/05, TX-13.*, TX-21.ms_*, TX-22.ms_*) are built +against the suite's 2-of-3 `wsh(sortedmulti)` wallet at `m/48h/0h/0h/2h`; see +`MULTISIG_DESCRIPTOR` in `tests/psbt_suite_util.py`. + `XTRAS.HUGE_WITNESS_STACK.psbt` is deliberately **not** vendored: the original is 1.5 MB of incompressible witness data. `psbt_suite_util.build_huge_witness_psbt()` synthesizes an equivalent at test time. diff --git a/tests/data/psbt_test_suite/TX-01.psbt b/tests/data/psbt_test_suite/TX-01.psbt index cf2bbb013..7c0ceebd5 100644 Binary files a/tests/data/psbt_test_suite/TX-01.psbt and b/tests/data/psbt_test_suite/TX-01.psbt differ diff --git a/tests/data/psbt_test_suite/TX-02.psbt b/tests/data/psbt_test_suite/TX-02.psbt index edb0e28c1..864fcd2e3 100644 Binary files a/tests/data/psbt_test_suite/TX-02.psbt and b/tests/data/psbt_test_suite/TX-02.psbt differ diff --git a/tests/data/psbt_test_suite/TX-03.bare.psbt b/tests/data/psbt_test_suite/TX-03.bare.psbt index e610db86b..0c9ece108 100644 Binary files a/tests/data/psbt_test_suite/TX-03.bare.psbt and b/tests/data/psbt_test_suite/TX-03.bare.psbt differ diff --git a/tests/data/psbt_test_suite/TX-03.fee_inflate.psbt b/tests/data/psbt_test_suite/TX-03.fee_inflate.psbt index e9040e8f2..8e36f4da5 100644 Binary files a/tests/data/psbt_test_suite/TX-03.fee_inflate.psbt and b/tests/data/psbt_test_suite/TX-03.fee_inflate.psbt differ diff --git a/tests/data/psbt_test_suite/TX-03.fee_inflate_V2.psbt b/tests/data/psbt_test_suite/TX-03.fee_inflate_V2.psbt index 11caee28d..71858e84e 100644 Binary files a/tests/data/psbt_test_suite/TX-03.fee_inflate_V2.psbt and b/tests/data/psbt_test_suite/TX-03.fee_inflate_V2.psbt differ diff --git a/tests/data/psbt_test_suite/TX-04.psbt b/tests/data/psbt_test_suite/TX-04.psbt new file mode 100644 index 000000000..41860b662 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-04.psbt differ diff --git a/tests/data/psbt_test_suite/TX-05.psbt b/tests/data/psbt_test_suite/TX-05.psbt new file mode 100644 index 000000000..ee2db8ca4 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-05.psbt differ diff --git a/tests/data/psbt_test_suite/TX-06.branch127.psbt b/tests/data/psbt_test_suite/TX-06.branch127.psbt index 1f71d4367..9887aa157 100644 Binary files a/tests/data/psbt_test_suite/TX-06.branch127.psbt and b/tests/data/psbt_test_suite/TX-06.branch127.psbt differ diff --git a/tests/data/psbt_test_suite/TX-06.depth6.psbt b/tests/data/psbt_test_suite/TX-06.depth6.psbt index d0155d754..82ebad6de 100644 Binary files a/tests/data/psbt_test_suite/TX-06.depth6.psbt and b/tests/data/psbt_test_suite/TX-06.depth6.psbt differ diff --git a/tests/data/psbt_test_suite/TX-08.ANYONECANPAY.psbt b/tests/data/psbt_test_suite/TX-08.ANYONECANPAY.psbt index 1ac18d047..080bf9c37 100644 Binary files a/tests/data/psbt_test_suite/TX-08.ANYONECANPAY.psbt and b/tests/data/psbt_test_suite/TX-08.ANYONECANPAY.psbt differ diff --git a/tests/data/psbt_test_suite/TX-08.NONE.psbt b/tests/data/psbt_test_suite/TX-08.NONE.psbt index c97cc8763..ee69a035f 100644 Binary files a/tests/data/psbt_test_suite/TX-08.NONE.psbt and b/tests/data/psbt_test_suite/TX-08.NONE.psbt differ diff --git a/tests/data/psbt_test_suite/TX-08.NONE_ACP.psbt b/tests/data/psbt_test_suite/TX-08.NONE_ACP.psbt index 2b0b4d868..354288616 100644 Binary files a/tests/data/psbt_test_suite/TX-08.NONE_ACP.psbt and b/tests/data/psbt_test_suite/TX-08.NONE_ACP.psbt differ diff --git a/tests/data/psbt_test_suite/TX-08.SINGLE.psbt b/tests/data/psbt_test_suite/TX-08.SINGLE.psbt index f81814402..2e1ff9b42 100644 Binary files a/tests/data/psbt_test_suite/TX-08.SINGLE.psbt and b/tests/data/psbt_test_suite/TX-08.SINGLE.psbt differ diff --git a/tests/data/psbt_test_suite/TX-08.SINGLE_ACP.psbt b/tests/data/psbt_test_suite/TX-08.SINGLE_ACP.psbt index 85fc3f508..cd67f7b59 100644 Binary files a/tests/data/psbt_test_suite/TX-08.SINGLE_ACP.psbt and b/tests/data/psbt_test_suite/TX-08.SINGLE_ACP.psbt differ diff --git a/tests/data/psbt_test_suite/TX-09.attacker_internal_key.psbt b/tests/data/psbt_test_suite/TX-09.attacker_internal_key.psbt index 5b8cee38a..fa4eca3ef 100644 Binary files a/tests/data/psbt_test_suite/TX-09.attacker_internal_key.psbt and b/tests/data/psbt_test_suite/TX-09.attacker_internal_key.psbt differ diff --git a/tests/data/psbt_test_suite/TX-09.hidden_taptree.psbt b/tests/data/psbt_test_suite/TX-09.hidden_taptree.psbt index fc12c4ae3..c999240ba 100644 Binary files a/tests/data/psbt_test_suite/TX-09.hidden_taptree.psbt and b/tests/data/psbt_test_suite/TX-09.hidden_taptree.psbt differ diff --git a/tests/data/psbt_test_suite/TX-10.psbt b/tests/data/psbt_test_suite/TX-10.psbt index 08c05f406..dbe76134a 100644 Binary files a/tests/data/psbt_test_suite/TX-10.psbt and b/tests/data/psbt_test_suite/TX-10.psbt differ diff --git a/tests/data/psbt_test_suite/TX-11.v0_bech32m.psbt b/tests/data/psbt_test_suite/TX-11.v0_bech32m.psbt index e927d1c56..d5023ae52 100644 Binary files a/tests/data/psbt_test_suite/TX-11.v0_bech32m.psbt and b/tests/data/psbt_test_suite/TX-11.v0_bech32m.psbt differ diff --git a/tests/data/psbt_test_suite/TX-11.v1_bech32.psbt b/tests/data/psbt_test_suite/TX-11.v1_bech32.psbt index 01490fe95..797306d73 100644 Binary files a/tests/data/psbt_test_suite/TX-11.v1_bech32.psbt and b/tests/data/psbt_test_suite/TX-11.v1_bech32.psbt differ diff --git a/tests/data/psbt_test_suite/TX-12.psbt b/tests/data/psbt_test_suite/TX-12.psbt index c826b1807..7b86f296e 100644 Binary files a/tests/data/psbt_test_suite/TX-12.psbt and b/tests/data/psbt_test_suite/TX-12.psbt differ diff --git a/tests/data/psbt_test_suite/TX-13.duplicate.psbt b/tests/data/psbt_test_suite/TX-13.duplicate.psbt new file mode 100644 index 000000000..3c263801d Binary files /dev/null and b/tests/data/psbt_test_suite/TX-13.duplicate.psbt differ diff --git a/tests/data/psbt_test_suite/TX-13.reorder.psbt b/tests/data/psbt_test_suite/TX-13.reorder.psbt new file mode 100644 index 000000000..487f0ac36 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-13.reorder.psbt differ diff --git a/tests/data/psbt_test_suite/TX-13.substitute.psbt b/tests/data/psbt_test_suite/TX-13.substitute.psbt new file mode 100644 index 000000000..81ea47848 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-13.substitute.psbt differ diff --git a/tests/data/psbt_test_suite/TX-13.threshold.psbt b/tests/data/psbt_test_suite/TX-13.threshold.psbt new file mode 100644 index 000000000..a644aa9df Binary files /dev/null and b/tests/data/psbt_test_suite/TX-13.threshold.psbt differ diff --git a/tests/data/psbt_test_suite/TX-14.cross_net.psbt b/tests/data/psbt_test_suite/TX-14.cross_net.psbt index 3b98fc3cd..d0beff080 100644 Binary files a/tests/data/psbt_test_suite/TX-14.cross_net.psbt and b/tests/data/psbt_test_suite/TX-14.cross_net.psbt differ diff --git a/tests/data/psbt_test_suite/TX-15.mismatch.psbt b/tests/data/psbt_test_suite/TX-15.mismatch.psbt index 25655880b..c3304dbce 100644 Binary files a/tests/data/psbt_test_suite/TX-15.mismatch.psbt and b/tests/data/psbt_test_suite/TX-15.mismatch.psbt differ diff --git a/tests/data/psbt_test_suite/TX-16.foreign_fingerprint.psbt b/tests/data/psbt_test_suite/TX-16.foreign_fingerprint.psbt index fcf7938fa..555d73318 100644 Binary files a/tests/data/psbt_test_suite/TX-16.foreign_fingerprint.psbt and b/tests/data/psbt_test_suite/TX-16.foreign_fingerprint.psbt differ diff --git a/tests/data/psbt_test_suite/TX-16.global_xpub_injected.psbt b/tests/data/psbt_test_suite/TX-16.global_xpub_injected.psbt index 5d2fbfa07..3caee6af5 100644 Binary files a/tests/data/psbt_test_suite/TX-16.global_xpub_injected.psbt and b/tests/data/psbt_test_suite/TX-16.global_xpub_injected.psbt differ diff --git a/tests/data/psbt_test_suite/TX-16.unknown_field.psbt b/tests/data/psbt_test_suite/TX-16.unknown_field.psbt index ff765d18b..6f66d87cc 100644 Binary files a/tests/data/psbt_test_suite/TX-16.unknown_field.psbt and b/tests/data/psbt_test_suite/TX-16.unknown_field.psbt differ diff --git a/tests/data/psbt_test_suite/TX-17.psbt b/tests/data/psbt_test_suite/TX-17.psbt index b4c4366b5..e113b3bb9 100644 Binary files a/tests/data/psbt_test_suite/TX-17.psbt and b/tests/data/psbt_test_suite/TX-17.psbt differ diff --git a/tests/data/psbt_test_suite/TX-18.psbt b/tests/data/psbt_test_suite/TX-18.psbt index d3f05c947..ee11fb53a 100644 Binary files a/tests/data/psbt_test_suite/TX-18.psbt and b/tests/data/psbt_test_suite/TX-18.psbt differ diff --git a/tests/data/psbt_test_suite/TX-19.height_far.psbt b/tests/data/psbt_test_suite/TX-19.height_far.psbt new file mode 100644 index 000000000..981c027b9 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-19.height_far.psbt differ diff --git a/tests/data/psbt_test_suite/TX-19.height_far_V2.psbt b/tests/data/psbt_test_suite/TX-19.height_far_V2.psbt index 0500ab572..902bbd611 100644 Binary files a/tests/data/psbt_test_suite/TX-19.height_far_V2.psbt and b/tests/data/psbt_test_suite/TX-19.height_far_V2.psbt differ diff --git a/tests/data/psbt_test_suite/TX-19.height_near.psbt b/tests/data/psbt_test_suite/TX-19.height_near.psbt new file mode 100644 index 000000000..9f2f89c4c Binary files /dev/null and b/tests/data/psbt_test_suite/TX-19.height_near.psbt differ diff --git a/tests/data/psbt_test_suite/TX-19.inert.psbt b/tests/data/psbt_test_suite/TX-19.inert.psbt new file mode 100644 index 000000000..87aa35546 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-19.inert.psbt differ diff --git a/tests/data/psbt_test_suite/TX-19.relative_blocks.psbt b/tests/data/psbt_test_suite/TX-19.relative_blocks.psbt new file mode 100644 index 000000000..8082194d7 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-19.relative_blocks.psbt differ diff --git a/tests/data/psbt_test_suite/TX-19.relative_rbf_masquerade.psbt b/tests/data/psbt_test_suite/TX-19.relative_rbf_masquerade.psbt new file mode 100644 index 000000000..3613cce65 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-19.relative_rbf_masquerade.psbt differ diff --git a/tests/data/psbt_test_suite/TX-19.relative_time.psbt b/tests/data/psbt_test_suite/TX-19.relative_time.psbt new file mode 100644 index 000000000..aca1f1aa1 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-19.relative_time.psbt differ diff --git a/tests/data/psbt_test_suite/TX-19.relative_time_V2.psbt b/tests/data/psbt_test_suite/TX-19.relative_time_V2.psbt index 067c48867..c86cd2855 100644 Binary files a/tests/data/psbt_test_suite/TX-19.relative_time_V2.psbt and b/tests/data/psbt_test_suite/TX-19.relative_time_V2.psbt differ diff --git a/tests/data/psbt_test_suite/TX-19.timestamp_future.psbt b/tests/data/psbt_test_suite/TX-19.timestamp_future.psbt new file mode 100644 index 000000000..43127b877 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-19.timestamp_future.psbt differ diff --git a/tests/data/psbt_test_suite/TX-20.cltv_height.psbt b/tests/data/psbt_test_suite/TX-20.cltv_height.psbt new file mode 100644 index 000000000..28e73c724 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-20.cltv_height.psbt differ diff --git a/tests/data/psbt_test_suite/TX-20.cltv_time.psbt b/tests/data/psbt_test_suite/TX-20.cltv_time.psbt new file mode 100644 index 000000000..258b8d7c7 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-20.cltv_time.psbt differ diff --git a/tests/data/psbt_test_suite/TX-20.csv_relative.psbt b/tests/data/psbt_test_suite/TX-20.csv_relative.psbt new file mode 100644 index 000000000..963bb18a7 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-20.csv_relative.psbt differ diff --git a/tests/data/psbt_test_suite/TX-21.claims_us_pays_other.psbt b/tests/data/psbt_test_suite/TX-21.claims_us_pays_other.psbt new file mode 100644 index 000000000..63ba6c0a3 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-21.claims_us_pays_other.psbt differ diff --git a/tests/data/psbt_test_suite/TX-21.claims_us_pays_other_V2.psbt b/tests/data/psbt_test_suite/TX-21.claims_us_pays_other_V2.psbt new file mode 100644 index 000000000..1b3d5cccc Binary files /dev/null and b/tests/data/psbt_test_suite/TX-21.claims_us_pays_other_V2.psbt differ diff --git a/tests/data/psbt_test_suite/TX-21.honest_foreign_annotated_spend.psbt b/tests/data/psbt_test_suite/TX-21.honest_foreign_annotated_spend.psbt new file mode 100644 index 000000000..74fcc6260 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-21.honest_foreign_annotated_spend.psbt differ diff --git a/tests/data/psbt_test_suite/TX-21.ms_foreign_quorum.psbt b/tests/data/psbt_test_suite/TX-21.ms_foreign_quorum.psbt new file mode 100644 index 000000000..05d51a2ff Binary files /dev/null and b/tests/data/psbt_test_suite/TX-21.ms_foreign_quorum.psbt differ diff --git a/tests/data/psbt_test_suite/TX-21.ms_foreign_quorum_no_xpubs.psbt b/tests/data/psbt_test_suite/TX-21.ms_foreign_quorum_no_xpubs.psbt new file mode 100644 index 000000000..932d8c4ac Binary files /dev/null and b/tests/data/psbt_test_suite/TX-21.ms_foreign_quorum_no_xpubs.psbt differ diff --git a/tests/data/psbt_test_suite/TX-21.ms_fp_relabeled.psbt b/tests/data/psbt_test_suite/TX-21.ms_fp_relabeled.psbt new file mode 100644 index 000000000..1d9e9719a Binary files /dev/null and b/tests/data/psbt_test_suite/TX-21.ms_fp_relabeled.psbt differ diff --git a/tests/data/psbt_test_suite/TX-21.ms_honest_change_no_xpubs.psbt b/tests/data/psbt_test_suite/TX-21.ms_honest_change_no_xpubs.psbt new file mode 100644 index 000000000..dcbdf720a Binary files /dev/null and b/tests/data/psbt_test_suite/TX-21.ms_honest_change_no_xpubs.psbt differ diff --git a/tests/data/psbt_test_suite/TX-21.ms_repointed_keys.psbt b/tests/data/psbt_test_suite/TX-21.ms_repointed_keys.psbt new file mode 100644 index 000000000..3add96057 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-21.ms_repointed_keys.psbt differ diff --git a/tests/data/psbt_test_suite/TX-21.ms_repointed_spk.psbt b/tests/data/psbt_test_suite/TX-21.ms_repointed_spk.psbt new file mode 100644 index 000000000..9106498a4 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-21.ms_repointed_spk.psbt differ diff --git a/tests/data/psbt_test_suite/TX-21.pays_us_claims_other.psbt b/tests/data/psbt_test_suite/TX-21.pays_us_claims_other.psbt new file mode 100644 index 000000000..caf107dd2 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-21.pays_us_claims_other.psbt differ diff --git a/tests/data/psbt_test_suite/TX-21.pays_us_claims_other_V2.psbt b/tests/data/psbt_test_suite/TX-21.pays_us_claims_other_V2.psbt new file mode 100644 index 000000000..fc63ad12a Binary files /dev/null and b/tests/data/psbt_test_suite/TX-21.pays_us_claims_other_V2.psbt differ diff --git a/tests/data/psbt_test_suite/TX-21.taproot_claims_other.psbt b/tests/data/psbt_test_suite/TX-21.taproot_claims_other.psbt new file mode 100644 index 000000000..fc3f81685 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-21.taproot_claims_other.psbt differ diff --git a/tests/data/psbt_test_suite/TX-22.mixed_path_maps.psbt b/tests/data/psbt_test_suite/TX-22.mixed_path_maps.psbt new file mode 100644 index 000000000..822ced0e8 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-22.mixed_path_maps.psbt differ diff --git a/tests/data/psbt_test_suite/TX-22.mixed_path_maps_input.psbt b/tests/data/psbt_test_suite/TX-22.mixed_path_maps_input.psbt new file mode 100644 index 000000000..77704a0e4 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-22.mixed_path_maps_input.psbt differ diff --git a/tests/data/psbt_test_suite/TX-22.ms_decoy_first.psbt b/tests/data/psbt_test_suite/TX-22.ms_decoy_first.psbt new file mode 100644 index 000000000..b709b5add Binary files /dev/null and b/tests/data/psbt_test_suite/TX-22.ms_decoy_first.psbt differ diff --git a/tests/data/psbt_test_suite/TX-22.ms_decoy_last.psbt b/tests/data/psbt_test_suite/TX-22.ms_decoy_last.psbt new file mode 100644 index 000000000..973004eb4 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-22.ms_decoy_last.psbt differ diff --git a/tests/data/psbt_test_suite/TX-22.surplus_paths.psbt b/tests/data/psbt_test_suite/TX-22.surplus_paths.psbt new file mode 100644 index 000000000..e27f0f32e Binary files /dev/null and b/tests/data/psbt_test_suite/TX-22.surplus_paths.psbt differ diff --git a/tests/data/psbt_test_suite/TX-22.taproot_surplus_internal_key.psbt b/tests/data/psbt_test_suite/TX-22.taproot_surplus_internal_key.psbt new file mode 100644 index 000000000..8e5070a55 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-22.taproot_surplus_internal_key.psbt differ diff --git a/tests/data/psbt_test_suite/TX-23.forged_input_claim.psbt b/tests/data/psbt_test_suite/TX-23.forged_input_claim.psbt new file mode 100644 index 000000000..133071ff8 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-23.forged_input_claim.psbt differ diff --git a/tests/data/psbt_test_suite/TX-23.forged_input_claim_V2.psbt b/tests/data/psbt_test_suite/TX-23.forged_input_claim_V2.psbt new file mode 100644 index 000000000..f1aebca55 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-23.forged_input_claim_V2.psbt differ diff --git a/tests/data/psbt_test_suite/TX-23.forged_output_claim.psbt b/tests/data/psbt_test_suite/TX-23.forged_output_claim.psbt new file mode 100644 index 000000000..e3bddab5a Binary files /dev/null and b/tests/data/psbt_test_suite/TX-23.forged_output_claim.psbt differ diff --git a/tests/data/psbt_test_suite/TX-23.forged_output_claim_V2.psbt b/tests/data/psbt_test_suite/TX-23.forged_output_claim_V2.psbt new file mode 100644 index 000000000..c75c7f55e Binary files /dev/null and b/tests/data/psbt_test_suite/TX-23.forged_output_claim_V2.psbt differ diff --git a/tests/data/psbt_test_suite/TX-23.forged_taproot_claim.psbt b/tests/data/psbt_test_suite/TX-23.forged_taproot_claim.psbt new file mode 100644 index 000000000..ec9c964f0 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-23.forged_taproot_claim.psbt differ diff --git a/tests/data/psbt_test_suite/TX-24.xpub_fingerprint_mismatch.psbt b/tests/data/psbt_test_suite/TX-24.xpub_fingerprint_mismatch.psbt new file mode 100644 index 000000000..39e56cc57 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-24.xpub_fingerprint_mismatch.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.ANYONE_CAN_SPEND_OUTPUT.psbt b/tests/data/psbt_test_suite/XTRAS.ANYONE_CAN_SPEND_OUTPUT.psbt new file mode 100644 index 000000000..efe1168ff Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.ANYONE_CAN_SPEND_OUTPUT.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.ANYONE_CAN_SPEND_OUTPUT_V2.psbt b/tests/data/psbt_test_suite/XTRAS.ANYONE_CAN_SPEND_OUTPUT_V2.psbt new file mode 100644 index 000000000..c991bbd28 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.ANYONE_CAN_SPEND_OUTPUT_V2.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.BARE_MULTISIG_OUTPUT.psbt b/tests/data/psbt_test_suite/XTRAS.BARE_MULTISIG_OUTPUT.psbt new file mode 100644 index 000000000..7d73c04bd Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.BARE_MULTISIG_OUTPUT.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.BARE_MULTISIG_OUTPUT_V2.psbt b/tests/data/psbt_test_suite/XTRAS.BARE_MULTISIG_OUTPUT_V2.psbt new file mode 100644 index 000000000..1afa322c5 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.BARE_MULTISIG_OUTPUT_V2.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.DUST_OUTPUT.psbt b/tests/data/psbt_test_suite/XTRAS.DUST_OUTPUT.psbt index e26bed1b0..8eaa7cb6a 100644 Binary files a/tests/data/psbt_test_suite/XTRAS.DUST_OUTPUT.psbt and b/tests/data/psbt_test_suite/XTRAS.DUST_OUTPUT.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.HUGE_FEE.psbt b/tests/data/psbt_test_suite/XTRAS.HUGE_FEE.psbt index 3d3bfc712..2e1546fb1 100644 Binary files a/tests/data/psbt_test_suite/XTRAS.HUGE_FEE.psbt and b/tests/data/psbt_test_suite/XTRAS.HUGE_FEE.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.HUGE_FEE_V2.psbt b/tests/data/psbt_test_suite/XTRAS.HUGE_FEE_V2.psbt index b333b1a75..61f363914 100644 Binary files a/tests/data/psbt_test_suite/XTRAS.HUGE_FEE_V2.psbt and b/tests/data/psbt_test_suite/XTRAS.HUGE_FEE_V2.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.LEGACY_P2SH_WITNESS_ONLY.psbt b/tests/data/psbt_test_suite/XTRAS.LEGACY_P2SH_WITNESS_ONLY.psbt new file mode 100644 index 000000000..68e7a672d Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.LEGACY_P2SH_WITNESS_ONLY.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.MISMATCHED_WITNESS_SCRIPT.psbt b/tests/data/psbt_test_suite/XTRAS.MISMATCHED_WITNESS_SCRIPT.psbt index 4f29f144e..a3ed3e34f 100644 Binary files a/tests/data/psbt_test_suite/XTRAS.MISMATCHED_WITNESS_SCRIPT.psbt and b/tests/data/psbt_test_suite/XTRAS.MISMATCHED_WITNESS_SCRIPT.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.MISSING_UTXO.psbt b/tests/data/psbt_test_suite/XTRAS.MISSING_UTXO.psbt new file mode 100644 index 000000000..02bd32413 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.MISSING_UTXO.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.MISSING_UTXO_V2.psbt b/tests/data/psbt_test_suite/XTRAS.MISSING_UTXO_V2.psbt new file mode 100644 index 000000000..5df30e100 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.MISSING_UTXO_V2.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.MIXED_INPUT_TYPES.psbt b/tests/data/psbt_test_suite/XTRAS.MIXED_INPUT_TYPES.psbt index c36499da2..1e12cf5aa 100644 Binary files a/tests/data/psbt_test_suite/XTRAS.MIXED_INPUT_TYPES.psbt and b/tests/data/psbt_test_suite/XTRAS.MIXED_INPUT_TYPES.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.NEGATIVE_AMOUNT.psbt b/tests/data/psbt_test_suite/XTRAS.NEGATIVE_AMOUNT.psbt index 340308a7f..1ea790a2d 100644 Binary files a/tests/data/psbt_test_suite/XTRAS.NEGATIVE_AMOUNT.psbt and b/tests/data/psbt_test_suite/XTRAS.NEGATIVE_AMOUNT.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.NEGATIVE_FEE.psbt b/tests/data/psbt_test_suite/XTRAS.NEGATIVE_FEE.psbt index 16c9d431e..4f30fb08b 100644 Binary files a/tests/data/psbt_test_suite/XTRAS.NEGATIVE_FEE.psbt and b/tests/data/psbt_test_suite/XTRAS.NEGATIVE_FEE.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.NEGATIVE_FEE_V2.psbt b/tests/data/psbt_test_suite/XTRAS.NEGATIVE_FEE_V2.psbt index b976a40c9..3fc1b4514 100644 Binary files a/tests/data/psbt_test_suite/XTRAS.NEGATIVE_FEE_V2.psbt and b/tests/data/psbt_test_suite/XTRAS.NEGATIVE_FEE_V2.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.NETWORK_HRP_MISMATCH.psbt b/tests/data/psbt_test_suite/XTRAS.NETWORK_HRP_MISMATCH.psbt index 8d84aa029..85bb73dcc 100644 Binary files a/tests/data/psbt_test_suite/XTRAS.NETWORK_HRP_MISMATCH.psbt and b/tests/data/psbt_test_suite/XTRAS.NETWORK_HRP_MISMATCH.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.OP_RETURN_BURN.psbt b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_BURN.psbt index f019d965f..5d8f862cc 100644 Binary files a/tests/data/psbt_test_suite/XTRAS.OP_RETURN_BURN.psbt and b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_BURN.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.OP_RETURN_BURN_V2.psbt b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_BURN_V2.psbt index ed9391f03..a5e0298fd 100644 Binary files a/tests/data/psbt_test_suite/XTRAS.OP_RETURN_BURN_V2.psbt and b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_BURN_V2.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.OP_RETURN_DIRECT_PUSH.psbt b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_DIRECT_PUSH.psbt new file mode 100644 index 000000000..5890c6718 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_DIRECT_PUSH.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.OP_RETURN_DIRECT_PUSH_V2.psbt b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_DIRECT_PUSH_V2.psbt new file mode 100644 index 000000000..0c956208a Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_DIRECT_PUSH_V2.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.PREV_TX_TXID_MISMATCH.psbt b/tests/data/psbt_test_suite/XTRAS.PREV_TX_TXID_MISMATCH.psbt new file mode 100644 index 000000000..3ab263d47 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.PREV_TX_TXID_MISMATCH.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.PREV_TX_TXID_MISMATCH_V2.psbt b/tests/data/psbt_test_suite/XTRAS.PREV_TX_TXID_MISMATCH_V2.psbt new file mode 100644 index 000000000..de7d7347e Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.PREV_TX_TXID_MISMATCH_V2.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.RBF_SIGNAL.psbt b/tests/data/psbt_test_suite/XTRAS.RBF_SIGNAL.psbt index aef2353af..9e5e458ae 100644 Binary files a/tests/data/psbt_test_suite/XTRAS.RBF_SIGNAL.psbt and b/tests/data/psbt_test_suite/XTRAS.RBF_SIGNAL.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.TRUNCATED_PSBT.psbt b/tests/data/psbt_test_suite/XTRAS.TRUNCATED_PSBT.psbt index d238404f3..f09a34783 100644 Binary files a/tests/data/psbt_test_suite/XTRAS.TRUNCATED_PSBT.psbt and b/tests/data/psbt_test_suite/XTRAS.TRUNCATED_PSBT.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.UNSUPPORTED_PSBT_VERSION.psbt b/tests/data/psbt_test_suite/XTRAS.UNSUPPORTED_PSBT_VERSION.psbt new file mode 100644 index 000000000..9c50c1e7b Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.UNSUPPORTED_PSBT_VERSION.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.UNSUPPORTED_PSBT_VERSION_V2.psbt b/tests/data/psbt_test_suite/XTRAS.UNSUPPORTED_PSBT_VERSION_V2.psbt new file mode 100644 index 000000000..b6f5bc738 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.UNSUPPORTED_PSBT_VERSION_V2.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.V2_MISSING_PREVOUT.psbt b/tests/data/psbt_test_suite/XTRAS.V2_MISSING_PREVOUT.psbt new file mode 100644 index 000000000..889e7b582 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.V2_MISSING_PREVOUT.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.WITNESS_NONWITNESS_MISMATCH.psbt b/tests/data/psbt_test_suite/XTRAS.WITNESS_NONWITNESS_MISMATCH.psbt new file mode 100644 index 000000000..04238b39a Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.WITNESS_NONWITNESS_MISMATCH.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.WITNESS_UTXO_MISMATCH.psbt b/tests/data/psbt_test_suite/XTRAS.WITNESS_UTXO_MISMATCH.psbt index 1a14c37e5..7f18e6d5d 100644 Binary files a/tests/data/psbt_test_suite/XTRAS.WITNESS_UTXO_MISMATCH.psbt and b/tests/data/psbt_test_suite/XTRAS.WITNESS_UTXO_MISMATCH.psbt differ diff --git a/tests/psbt_suite_util.py b/tests/psbt_suite_util.py index c7b19a68a..b4cc94887 100644 --- a/tests/psbt_suite_util.py +++ b/tests/psbt_suite_util.py @@ -81,6 +81,10 @@ class RejectCode: FORGED_OUTPUT_OWNERSHIP = "FORGED_OUTPUT_OWNERSHIP" FORGED_INPUT_OWNERSHIP = "FORGED_INPUT_OWNERSHIP" SEED_CANNOT_SIGN = "SEED_CANNOT_SIGN" + SURPLUS_DERIVATIONS = "SURPLUS_DERIVATIONS" + MISLABELED_OUTPUT_OWNERSHIP = "MISLABELED_OUTPUT_OWNERSHIP" + INCONSISTENT_FINGERPRINTS = "INCONSISTENT_FINGERPRINTS" + MIXED_DERIVATION_MAPS = "MIXED_DERIVATION_MAPS" class Advisory: @@ -94,6 +98,7 @@ class Advisory: DUST_OUTPUT = "DUST_OUTPUT" FUTURE_LOCKTIME = "FUTURE_LOCKTIME" RELATIVE_TIMELOCK = "RELATIVE_TIMELOCK" + SCRIPT_TIMELOCK = "SCRIPT_TIMELOCK" LOCKTIME_FAR_FUTURE = "LOCKTIME_FAR_FUTURE" RBF = "RBF" @@ -250,16 +255,21 @@ def path(self) -> str: ), Vector( "TX-14.cross_net", "binding", - "Mainnet chain params with testnet-labeled derivation.", - Expect.PARSES, - input_amount=200_000, output_amount=199_000, num_outputs=2, owned_outputs=1, - vacuous=True, # shipped derivation is m/84h/0h/0h — mainnet coin type, nothing crossed + "Mainnet transaction whose input derivation is relabelled to coin type 1h " + "(testnet) while the change stays at 0h. The input key is really our 0h key, " + "so the 1h claim is false -- refused as forged rather than by a network rule.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.FORGED_INPUT_OWNERSHIP, ), Vector( "TX-16.foreign_fingerprint", "binding", - "Output bip32_derivation with a foreign master fingerprint and an " - "unparseable pubkey.", - Expect.REJECT_EMBIT, + "Output bip32_derivation with a foreign master fingerprint. A foreign " + "fingerprint only means 'not claimed as ours': the output is shown as an " + "external payment, and ownership of the real change is still decided by " + "re-derivation.", + Expect.PARSES, + input_amount=200_000, output_amount=199_000, num_outputs=2, owned_outputs=1, ), Vector( "TX-16.global_xpub_injected", "binding", @@ -277,13 +287,16 @@ def path(self) -> str: ), Vector( "TX-09.attacker_internal_key", "binding", - "p2tr change with an attacker-supplied internal key.", - Expect.REJECT_EMBIT, + "p2tr change with an attacker-supplied internal key. Must not be labelled " + "change: the output key cannot be rebuilt from anything this seed derives.", + Expect.PARSES, + input_amount=200_000, output_amount=199_000, num_outputs=2, owned_outputs=0, ), Vector( "TX-09.hidden_taptree", "binding", - "p2tr change with an unverifiable taptree leaf.", - Expect.REJECT_EMBIT, + "p2tr change with an unverifiable taptree leaf. Must not be labelled change.", + Expect.PARSES, + input_amount=200_000, output_amount=199_000, num_outputs=2, owned_outputs=0, ), # ------------------------------------------------------------------ crypto @@ -339,11 +352,11 @@ def path(self) -> str: ), Vector( "TX-10", "coverage", - "Destination address ground to collide on the first 6 + last 6 characters " - "with the change address, defeating truncated verification.", + "Destination copies the first program bytes of the change output, so both " + "addresses share the HRP and leading characters and differ in the middle. " + "A display-layer trap: only full-address rendering catches it.", Expect.PARSES, input_amount=200_000, output_amount=199_000, num_outputs=2, owned_outputs=1, - vacuous=True, # the shipped outputs share no visible prefix or suffix ), Vector( "TX-15.mismatch", "coverage", @@ -357,16 +370,18 @@ def path(self) -> str: # --------------------------------------------------------------- catalogue Vector( "TX-11.v0_bech32m", "catalogue", - "v0 witness program encoded with bech32m.", + "A wrong-variant (bech32m) address string for a v0 output planted in a " + "non-standard global field. Display addresses must be re-derived from the " + "scriptPubKey, never read from the psbt.", Expect.PARSES, input_amount=200_000, output_amount=199_000, num_outputs=2, owned_outputs=1, - vacuous=True, # a PSBT carries scriptPubKey bytes; the address encoding is display-layer ), Vector( "TX-11.v1_bech32", "catalogue", - "v1+ witness program encoded with bech32 instead of bech32m.", - Expect.REJECT_EMBIT, - vacuous=True, + "The v1/taproot counterpart: a bech32 (not bech32m) address string planted " + "in a non-standard global field.", + Expect.PARSES, + input_amount=200_000, output_amount=199_000, num_outputs=2, owned_outputs=0, ), # ------------------------------------------------------------------ extras @@ -402,7 +417,9 @@ def path(self) -> str: "must carry a witness program.", Expect.REJECT_PARSER, input_amount=200_000, output_amount=199_000, num_outputs=2, - vacuous=True, # no non_witness_utxo ships, so the real cross-check is untested here + # No non_witness_utxo ships, so the real cross-check is left to + # XTRAS.WITNESS_NONWITNESS_MISMATCH. + vacuous=True, reject_code=RejectCode.INVALID_WITNESS_UTXO, ), Vector( @@ -427,6 +444,8 @@ def path(self) -> str: advisories=frozenset({Advisory.DUST_OUTPUT, Advisory.HIGH_FEE, Advisory.HIGH_FEE_RATE}), ), Vector( + # Dropped upstream in favour of TX-19.timestamp_future; kept as a local + # fixture because TestTimelocks mutates it. "XTRAS.LOCKTIME_FUTURE", "extras", "nLocktime 2,000,000,000 — a unix timestamp in 2033.", Expect.PARSES, @@ -442,10 +461,13 @@ def path(self) -> str: ), Vector( "XTRAS.NETWORK_HRP_MISMATCH", "extras", - "Output address HRP does not match the active network.", - Expect.PARSES, - input_amount=200_000, output_amount=199_000, num_outputs=2, owned_outputs=1, - vacuous=True, # the shipped output is an ordinary mainnet bc1q address + "Two inputs claiming different networks: input 0 at coin type 0h, input 1 " + "relabelled to 1h. scriptPubKeys carry no network, so the coin type is the " + "only cross-network signal -- and input 1's key is really our 0h key, so the " + "claim is false.", + Expect.REJECT_PARSER, + input_amount=400_000, output_amount=399_000, num_outputs=2, + reject_code=RejectCode.FORGED_INPUT_OWNERSHIP, ), Vector( "XTRAS.TRUNCATED_PSBT", "parser", @@ -535,6 +557,418 @@ def path(self) -> str: Expect.PARSES, input_amount=100_000, output_amount=99_000, num_outputs=2, owned_outputs=1, ), + + # ------------------------------------------------------ structural (XTRAS) + Vector( + "XTRAS.MISSING_UTXO", "extras", + "The sole input carries neither witness_utxo nor non_witness_utxo: no " + "amount, no script, nothing to sign against.", + Expect.REJECT_PARSER, + reject_code=RejectCode.MISSING_UTXO, + ), + Vector( + "XTRAS.MISSING_UTXO_V2", "extras", + "BIP-370 twin of XTRAS.MISSING_UTXO: a v2 input naming its prevout but " + "carrying no utxo.", + Expect.REJECT_PARSER, + reject_code=RejectCode.MISSING_UTXO, + ), + Vector( + "XTRAS.V2_MISSING_PREVOUT", "extras", + "A v2 input with a witness_utxo but no previous_txid / output_index. " + "BIP-370 requires the outpoint; without it there is no transaction to sign.", + Expect.REJECT_PARSER, + reject_code=RejectCode.MISSING_UTXO, + ), + Vector( + "XTRAS.UNSUPPORTED_PSBT_VERSION", "extras", + "A v0 psbt declaring PSBT_GLOBAL_VERSION 1, which BIP-370 reserves.", + Expect.REJECT_PARSER, + reject_code=RejectCode.UNSUPPORTED_PSBT_VERSION, + ), + Vector( + "XTRAS.UNSUPPORTED_PSBT_VERSION_V2", "extras", + "A structurally complete v2 psbt declaring version 3, which is undefined.", + Expect.REJECT_PARSER, + reject_code=RejectCode.UNSUPPORTED_PSBT_VERSION, + ), + Vector( + "XTRAS.ANYONE_CAN_SPEND_OUTPUT", "extras", + "The spend output pays witness version 2: no address form, and " + "anyone-can-spend until a soft fork defines it.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.UNDISPLAYABLE_OUTPUT, + ), + Vector( + "XTRAS.ANYONE_CAN_SPEND_OUTPUT_V2", "extras", + "BIP-370 twin of XTRAS.ANYONE_CAN_SPEND_OUTPUT.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.UNDISPLAYABLE_OUTPUT, + ), + Vector( + "XTRAS.BARE_MULTISIG_OUTPUT", "extras", + "The spend output is a bare 2-of-2 multisig script, which has no address " + "and so cannot be reviewed.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.UNDISPLAYABLE_OUTPUT, + ), + Vector( + "XTRAS.BARE_MULTISIG_OUTPUT_V2", "extras", + "BIP-370 twin of XTRAS.BARE_MULTISIG_OUTPUT.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.UNDISPLAYABLE_OUTPUT, + ), + Vector( + "XTRAS.WITNESS_NONWITNESS_MISMATCH", "extras", + "An input ships both utxo forms and they disagree (100,000 vs 200,000 sats, " + "different scripts) -- the BIP-143 amount-binding attack.", + Expect.REJECT_PARSER, + num_outputs=2, + reject_code=RejectCode.UTXO_MISMATCH, + ), + + # --------------------------------------------------------------- timelocks + Vector( + "TX-19.timestamp_future", "extras", + "nLocktime 2,000,000,000 (~2033) with a non-final input: unconfirmable until then.", + Expect.PARSES, + input_amount=100_000, output_amount=99_000, num_outputs=2, owned_outputs=1, + advisories=frozenset({Advisory.FUTURE_LOCKTIME}), + ), + Vector( + "TX-19.height_far", "extras", + "Block-height nLockTime ~4 years out. With no block anchor it parses as an " + "ordinary spend, like its v2 twin.", + Expect.PARSES, + input_amount=100_000, output_amount=99_000, num_outputs=2, owned_outputs=1, + ), + Vector( + "TX-19.height_near", "extras", + "Negative control: nLockTime at the chain tip (anti-fee-sniping). Normal; " + "must not warn.", + Expect.PARSES, + input_amount=100_000, output_amount=99_000, num_outputs=2, owned_outputs=1, + ), + Vector( + "TX-19.inert", "extras", + "Negative control: far-future nLockTime with every input final, so the " + "locktime is not enforced. Must not warn.", + Expect.PARSES, + input_amount=100_000, output_amount=99_000, num_outputs=2, owned_outputs=1, + ), + Vector( + "TX-19.relative_blocks", "extras", + "BIP-68 block-based relative timelock (0x0000ffff, ~15 months).", + Expect.PARSES, + input_amount=100_000, output_amount=99_000, num_outputs=2, owned_outputs=1, + advisories=frozenset({Advisory.RBF, Advisory.RELATIVE_TIMELOCK}), + ), + Vector( + "TX-19.relative_time", "extras", + "BIP-68 time-based relative timelock (512-second units, ~24 days).", + Expect.PARSES, + input_amount=100_000, output_amount=99_000, num_outputs=2, owned_outputs=1, + advisories=frozenset({Advisory.RBF, Advisory.RELATIVE_TIMELOCK}), + ), + Vector( + "TX-19.relative_rbf_masquerade", "extras", + "Same bytes as relative_blocks, presented as mere RBF. 'Replaceable' alone " + "would hide a ~15-month hold.", + Expect.PARSES, + input_amount=100_000, output_amount=99_000, num_outputs=2, owned_outputs=1, + advisories=frozenset({Advisory.RBF, Advisory.RELATIVE_TIMELOCK}), + ), + Vector( + "TX-20.cltv_time", "coverage", + "A P2SH output whose redeem script is CLTV-locked until ~2033. Consensus " + "rejects any earlier spend of those funds; the address alone hides it.", + Expect.PARSES, + input_amount=100_000, output_amount=99_000, num_outputs=2, owned_outputs=1, + advisories=frozenset({Advisory.SCRIPT_TIMELOCK}), + ), + Vector( + "TX-20.cltv_height", "coverage", + "A P2WSH output whose witness script is CLTV-locked at a block height ~2 " + "years out.", + Expect.PARSES, + input_amount=100_000, output_amount=99_000, num_outputs=2, owned_outputs=1, + advisories=frozenset({Advisory.SCRIPT_TIMELOCK}), + ), + Vector( + "TX-20.csv_relative", "coverage", + "A P2WSH output whose witness script is CSV-locked (144 blocks after it " + "confirms). Unlike TX-19 the hold lives in the output's own script.", + Expect.PARSES, + input_amount=100_000, output_amount=99_000, num_outputs=2, owned_outputs=1, + advisories=frozenset({Advisory.SCRIPT_TIMELOCK}), + ), + + # --------------------------------------------------------------- ownership + Vector( + "TX-21.claims_us_pays_other", "ownership", + "Change annotated with one of our genuine keys and paths, but the script " + "pays a stranger. The key re-derives; the output is not locked to it.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.FORGED_OUTPUT_OWNERSHIP, + ), + Vector( + "TX-21.claims_us_pays_other_V2", "ownership", + "BIP-370 twin of TX-21.claims_us_pays_other.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.FORGED_OUTPUT_OWNERSHIP, + ), + Vector( + "TX-21.pays_us_claims_other", "ownership", + "Change pays our key but is annotated with a foreign fingerprint. The " + "funds are ours, but the psbt misdescribes who owns its outputs, which is " + "refused just like the opposite lie.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.MISLABELED_OUTPUT_OWNERSHIP, + ), + Vector( + "TX-21.pays_us_claims_other_V2", "ownership", + "BIP-370 twin of TX-21.pays_us_claims_other.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.MISLABELED_OUTPUT_OWNERSHIP, + ), + Vector( + "TX-21.taproot_claims_other", "ownership", + "P2TR change paying our internal key but claiming a foreign fingerprint.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.MISLABELED_OUTPUT_OWNERSHIP, + ), + Vector( + "TX-22.surplus_paths", "ownership", + "A single-sig output naming two of our keys. Only one can be the key the " + "script pays; the other is a decoy for a first-entry-only checker.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.SURPLUS_DERIVATIONS, + ), + Vector( + "TX-22.taproot_surplus_internal_key", "ownership", + "A P2TR output claiming two internal keys; a taproot output has one.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.SURPLUS_DERIVATIONS, + ), + Vector( + "TX-22.mixed_path_maps", "ownership", + "An output scope naming us in both the ecdsa and taproot derivation maps.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.MIXED_DERIVATION_MAPS, + ), + Vector( + "TX-22.mixed_path_maps_input", "ownership", + "The input-side variant of TX-22.mixed_path_maps.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.MIXED_DERIVATION_MAPS, + ), + Vector( + "TX-23.forged_output_claim", "ownership", + "Change claims our fingerprint at a plausible change path, on a key we do " + "not derive.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.FORGED_OUTPUT_OWNERSHIP, + ), + Vector( + "TX-23.forged_output_claim_V2", "ownership", + "BIP-370 twin of TX-23.forged_output_claim.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.FORGED_OUTPUT_OWNERSHIP, + ), + Vector( + "TX-23.forged_taproot_claim", "ownership", + "P2TR change claiming our fingerprint on an internal key we do not derive.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.FORGED_OUTPUT_OWNERSHIP, + ), + Vector( + "TX-23.forged_input_claim", "ownership", + "An extra input derivation naming our fingerprint on a foreign key, " + "alongside the genuine one.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.FORGED_INPUT_OWNERSHIP, + ), + Vector( + "TX-23.forged_input_claim_V2", "ownership", + "BIP-370 twin of TX-23.forged_input_claim.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.FORGED_INPUT_OWNERSHIP, + ), + + # ---------------------------------------------------------------- multisig + # Built against the suite's 2-of-3 wallet (MULTISIG_DESCRIPTOR). Parsed with + # the seed alone, as the flow does before a descriptor is loaded; the + # descriptor checks are in TestMultisigPolicy. + Vector( + "TX-04", "multisig", + "Mixed input script types in a multisig flow, carrying an invalid pubkey.", + Expect.REJECT_EMBIT, + ), + Vector( + "TX-13.duplicate", "multisig", + "Duplicated cosigner key: nominally 2-of-3, effectively 2-of-2.", + Expect.REJECT_EMBIT, + ), + Vector( + "TX-13.substitute", "multisig", + "One cosigner key swapped for an attacker's; ours is gone from the inputs.", + Expect.REJECT_PARSER, + input_amount=100_000, output_amount=99_000, num_outputs=2, + reject_code=RejectCode.SEED_CANNOT_SIGN, + ), + Vector( + "TX-13.threshold", "multisig", + "Change script reduced to 1-of-3. Only a registered descriptor can tell.", + Expect.PARSES, + input_amount=100_000, output_amount=99_000, num_outputs=2, owned_outputs=1, + ), + Vector( + "TX-13.reorder", "multisig", + "Cosigner keys reordered, which breaks sortedmulti. Only a registered " + "descriptor can tell.", + Expect.PARSES, + input_amount=100_000, output_amount=99_000, num_outputs=2, owned_outputs=1, + ), + Vector( + "TX-05", "multisig", + "Multisig change built from attacker-only xpubs. Must not be labelled change.", + Expect.PARSES, + input_amount=200_000, output_amount=199_000, num_outputs=2, owned_outputs=0, + ), + Vector( + "TX-21.honest_foreign_annotated_spend", "multisig", + "Negative control: an honest payment to a stranger's M-of-N, fully " + "annotated with their keys. An external payment, not an attack.", + Expect.PARSES, + input_amount=200_000, output_amount=199_000, num_outputs=2, owned_outputs=0, + ), + Vector( + "TX-21.ms_fp_relabeled", "multisig", + "Genuine multisig change with our cosigner entry relabelled to a foreign " + "fingerprint: our key, attributed to another wallet.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.MISLABELED_OUTPUT_OWNERSHIP, + ), + Vector( + "TX-21.ms_repointed_keys", "multisig", + "Change witness script swapped for a stranger's M-of-N while our " + "derivation entry stays: the script no longer contains our key.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.FORGED_OUTPUT_OWNERSHIP, + ), + Vector( + "TX-21.ms_repointed_spk", "multisig", + "Change scriptPubKey repointed while the supplied witness script stays " + "ours: the script no longer hashes to the output.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.FORGED_OUTPUT_OWNERSHIP, + ), + Vector( + "TX-22.ms_decoy_first", "multisig", + "Genuine multisig change with a decoy entry of ours listed first.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.FORGED_OUTPUT_OWNERSHIP, + ), + Vector( + "TX-22.ms_decoy_last", "multisig", + "The same decoy listed last, which a first-match check never reaches.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.FORGED_OUTPUT_OWNERSHIP, + ), + + # ------------------------------------------ upstream-review follow-ups + Vector( + "XTRAS.PREV_TX_TXID_MISMATCH", "extras", + "Legacy input really spends 1,000,000 sats, but its previous tx was edited " + "to claim 201,000: the screen would show a 1,000-sat fee for an 800,000-sat " + "one. A legacy signature commits to no amount; only the previous tx's hash " + "catches it.", + Expect.REJECT_PARSER, + num_outputs=2, + reject_code=RejectCode.UTXO_MISMATCH, + ), + Vector( + "XTRAS.PREV_TX_TXID_MISMATCH_V2", "extras", + "BIP-370 twin of XTRAS.PREV_TX_TXID_MISMATCH.", + Expect.REJECT_PARSER, + num_outputs=2, + reject_code=RejectCode.UTXO_MISMATCH, + ), + Vector( + "XTRAS.OP_RETURN_DIRECT_PUSH", "extras", + "Negative control: a zero-value OP_RETURN whose 40-byte payload is pushed " + "directly, as Bitcoin Core writes it. Must be shown byte-for-byte.", + Expect.PARSES, + input_amount=200_000, output_amount=199_000, num_outputs=3, owned_outputs=1, + ), + Vector( + "XTRAS.OP_RETURN_DIRECT_PUSH_V2", "extras", + "BIP-370 twin of XTRAS.OP_RETURN_DIRECT_PUSH.", + Expect.PARSES, + input_amount=200_000, output_amount=199_000, num_outputs=3, owned_outputs=1, + ), + Vector( + "XTRAS.LEGACY_P2SH_WITNESS_ONLY", "multisig", + "Legacy P2SH multisig input described only by a witness_utxo: an amount a " + "legacy signature never commits to, with no previous tx to prove it.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.INVALID_WITNESS_UTXO, + ), + Vector( + "TX-24.xpub_fingerprint_mismatch", "multisig", + "One cosigner's global xpub relabelled to a foreign fingerprint while its " + "derivation entries keep the real one: the psbt contradicts itself.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.INCONSISTENT_FINGERPRINTS, + ), + Vector( + "TX-21.ms_foreign_quorum", "multisig", + "Change paid to a different 2-of-3 that still contains our key (one " + "cosigner swapped for a stranger's). The global xpubs do not derive the " + "stranger, so it is a payment.", + Expect.PARSES, + input_amount=200_000, output_amount=199_000, num_outputs=2, owned_outputs=0, + ), + Vector( + "TX-21.ms_foreign_quorum_no_xpubs", "multisig", + "The same foreign 2-of-3 with the global xpubs withheld. Nothing ties its " + "keys to the inputs' wallet, so it stays a payment -- even once a " + "descriptor is loaded, since that descriptor does not own it.", + Expect.PARSES, + input_amount=200_000, output_amount=199_000, num_outputs=2, owned_outputs=0, + ), + Vector( + "TX-21.ms_honest_change_no_xpubs", "multisig", + "Negative control: genuine multisig change from a coordinator that omits " + "global xpubs. A payment until the descriptor identifies it as change.", + Expect.PARSES, + input_amount=200_000, output_amount=199_000, num_outputs=2, owned_outputs=0, + ), ] VECTORS_BY_NAME = {v.name: v for v in VECTORS} @@ -545,6 +979,18 @@ def path(self) -> str: NORMAL_VECTORS = [v for v in VECTORS if v.category == "normal"] +MULTISIG_VECTORS = [v for v in VECTORS if v.category == "multisig"] + +# The suite's 2-of-3 wallet, from psbt_test_suite/test_vectors.json ("multisig"). +# The corpus seed is the 73c5da0a cosigner. +MULTISIG_DESCRIPTOR = ( + "wsh(sortedmulti(2," + "[73c5da0a/48h/0h/0h/2h]xpub6DkFAXWQ2dHxq2vatrt9qyA3bXYU4ToWQwCHbf5XB2mSTexcHZCeKS1VZYcPoBd5X8yVcbXFHJR9R8UCVpt82VX1VhR28mCyxUFL4r6KFrf/<0;1>/*," + "[28645006/48h/0h/0h/2h]xpub6DnEBNkSJKBYQmsbhS1sP9cNdtU5c9PLFGCjTJmxicxc13WB8zNNGQazabQpyFAGW5bV9tMko4uBxDxjUKL6dSAcx1tEbgEHtgSqyRsekh6/<0;1>/*," + "[3f635a63/48h/0h/0h/2h]xpub6FHZCoNb3tg3o1GAJQxSwgFNF8mLRtTk2GgkF7n5rwzoxBhUEdFWa8cyZRHqytAzKZWsKz8627cQEMCCfR5GDSv6yXegqirpgDUX41Pxybr/<0;1>/*" + "))" +) + # Vectors whose sighash flag is anything other than SIGHASH_ALL; signing must be # refused outright rather than producing a partial signature. NON_SIGHASH_ALL_VECTORS = [v for v in VECTORS if v.category == "crypto"] diff --git a/tests/screenshot_generator/generator.py b/tests/screenshot_generator/generator.py index 586d9f12f..b7d609ee5 100644 --- a/tests/screenshot_generator/generator.py +++ b/tests/screenshot_generator/generator.py @@ -124,6 +124,18 @@ def add_op_return_to_psbt(psbt: PSBT, raw_payload_data: bytes): MULTISIG_WALLET_DESCRIPTOR = """wsh(sortedmulti(1,[22bde1a9/48h/1h/0h/2h]tpubDFfsBrmpj226ZYiRszYi2qK6iGvh2vkkghfGB2YiRUVY4rqqedHCFEgw12FwDkm7rUoVtq9wLTKc6BN2sxswvQeQgp7m8st4FP8WtP8go76/{0,1}/*,[73c5da0a/48h/1h/0h/2h]tpubDFH9dgzveyD8zTbPUFuLrGmCydNvxehyNdUXKJAQN8x4aZ4j6UZqGfnqFrD4NqyaTVGKbvEW54tsvPTK2UoSbCC1PJY8iCNiwTL3RWZEheQ/{0,1}/*))#3jhtf6yx""" +# A coordinator that includes PSBT_GLOBAL_XPUB, which is what lets PSBTParser tie the +# multisig change's cosigner keys to the inputs' wallet. Without them the change stays +# a payment until a descriptor identifies it (see PSBTIdentifyChangeView). +def add_global_xpubs(base64_psbt: str, descriptor_str: str) -> str: + from embit.psbt import DerivationPath + psbt = PSBT.from_base64(base64_psbt) + for key in embit.descriptor.Descriptor.from_string(descriptor_str).keys: + psbt.xpubs[key.key] = DerivationPath(key.origin.fingerprint, key.origin.derivation) + return psbt.to_string() + +BASE64_MULTISIG_PSBT_WITH_XPUBS = add_global_xpubs(BASE64_MULTISIG_PSBT, MULTISIG_WALLET_DESCRIPTOR) + # Grab the most recent release version info for the "release build" splash screenshots. (latest_release_version_name, latest_release_version_timestamp) = VersionUtils._fetch_latest_seedsigner_release_tag() if not latest_release_version_name or not latest_release_version_timestamp: @@ -291,7 +303,7 @@ def mock_load_psbt(base64_psbt: str, seed: Seed = seed_12b): decoder.add_data(base64_psbt) with patch.object(controller, 'psbt', decoder.get_psbt()): with patch.object(controller, 'psbt_seed', seed): - with patch.object(controller, 'psbt_parser', PSBTParser(p=controller.psbt, seed=seed)): + with patch.object(controller, 'psbt_parser', PSBTParser(p=controller.psbt, seed=seed, multisig_descriptor=controller.multisig_wallet_descriptor)): yield @@ -303,6 +315,12 @@ def mock_single_sig_psbt_loaded(): @contextmanager def mock_multisig_psbt_loaded(): + with mock_load_psbt(BASE64_MULTISIG_PSBT_WITH_XPUBS): + yield + + + @contextmanager + def mock_multisig_psbt_without_xpubs_loaded(): with mock_load_psbt(BASE64_MULTISIG_PSBT): yield @@ -315,8 +333,16 @@ def mock_multisig_wallet_descriptor_loaded(): @contextmanager def mock_multisig_psbt_and_descriptor_loaded(): - with mock_multisig_psbt_loaded(): - with mock_multisig_wallet_descriptor_loaded(): + # Descriptor first: the parser is built with whatever descriptor is loaded. + with mock_multisig_wallet_descriptor_loaded(): + with mock_multisig_psbt_loaded(): + yield + + + @contextmanager + def mock_multisig_psbt_without_xpubs_and_descriptor_loaded(): + with mock_multisig_wallet_descriptor_loaded(): + with mock_multisig_psbt_without_xpubs_loaded(): yield @@ -507,6 +533,8 @@ def mock_version_to_most_recent_release(): ScreenshotConfig(psbt_views.PSBTUnsupportedScriptTypeWarningView), ScreenshotConfig(psbt_views.PSBTNoChangeWarningView), ScreenshotConfig(psbt_views.PSBTRiskWarningView, mock_context_manager=mock_psbt_with_risk_warnings_loaded), + ScreenshotConfig(psbt_views.PSBTIdentifyChangeView, screenshot_name="PSBTIdentifyChangeView_no_descriptor", mock_context_manager=mock_multisig_psbt_without_xpubs_loaded), + ScreenshotConfig(psbt_views.PSBTIdentifyChangeView, screenshot_name="PSBTIdentifyChangeView_descriptor_mismatch", mock_context_manager=mock_multisig_psbt_without_xpubs_and_descriptor_loaded), ScreenshotConfig(psbt_views.PSBTMathView, mock_context_manager=mock_multisig_psbt_loaded), ScreenshotConfig(psbt_views.PSBTAddressDetailsView, dict(address_num=0), mock_context_manager=mock_multisig_psbt_loaded), diff --git a/tests/test_flows_psbt_malicious.py b/tests/test_flows_psbt_malicious.py index ca6148adc..7e3277ffd 100644 --- a/tests/test_flows_psbt_malicious.py +++ b/tests/test_flows_psbt_malicious.py @@ -132,7 +132,7 @@ def test_spliced_change_path_is_refused(self): def test_unparseable_psbt_is_rejected_at_scan(self): """ - TX-16.foreign_fingerprint carries a pubkey embit cannot parse. Delivered + TX-04 carries a pubkey embit cannot parse. Delivered as UR2 (how a real scan arrives), `DecodeQR.is_psbt` is True but `get_psbt()` returns None. ScanView must refuse it there, rather than routing on with `controller.psbt = None` — which PSBTSelectSeedView @@ -142,6 +142,82 @@ def test_unparseable_psbt_is_rejected_at_scan(self): self.run_sequence([ FlowStep(MainMenuView, button_data_selection=MainMenuView.SCAN), FlowStep(scan_views.ScanView, - before_run=self.load_psbt_as_ur2("TX-16.foreign_fingerprint")), + before_run=self.load_psbt_as_ur2("TX-04")), FlowStep(MainMenuView), ]) + + + def test_unidentified_multisig_change_is_a_payment_until_identified(self): + """ + With no global xpubs, genuine multisig change looks exactly like a different + wallet that shares our key (TX-21.ms_foreign_quorum_no_xpubs). Without the + descriptor it is shown as a payment, and the user is told a descriptor would + identify it. Continuing without one reviews it as the full spend it appears to be. + """ + def assert_unidentified(view): + assert view.controller.psbt_parser.unidentified_change_outputs == [0] + assert view.controller.psbt_parser.num_change_outputs == 0 + + self.run_sequence( + self.scan_and_select_seed("TX-21.ms_honest_change_no_xpubs") + [ + FlowStep(psbt_views.PSBTOverviewView, screen_return_value=0), + FlowStep(psbt_views.PSBTIdentifyChangeView, before_run=assert_unidentified, + button_data_selection=psbt_views.PSBTIdentifyChangeView.CONTINUE_AS_PAYMENT), + FlowStep(psbt_views.PSBTNoChangeWarningView), + ] + ) + + def test_loading_the_descriptor_identifies_the_change(self): + """"Load descriptor" goes to the descriptor loader, resuming the psbt flow.""" + from seedsigner.controller import Controller + from seedsigner.views.seed_views import LoadMultisigWalletDescriptorView + + def assert_resumes(view): + assert view.controller.resume_main_flow == Controller.FLOW__PSBT + + self.run_sequence( + self.scan_and_select_seed("TX-21.ms_honest_change_no_xpubs") + [ + FlowStep(psbt_views.PSBTOverviewView, screen_return_value=0), + FlowStep(psbt_views.PSBTIdentifyChangeView, + button_data_selection=psbt_views.PSBTIdentifyChangeView.LOAD_DESCRIPTOR), + FlowStep(LoadMultisigWalletDescriptorView, before_run=assert_resumes), + ] + ) + + def test_returning_with_a_descriptor_re_reads_the_psbt(self): + """ + Once a descriptor is loaded, "Return to transaction" discards the parse that + couldn't identify the change and restarts review, now with the change shown as + change. (Starts at MultisigWalletDescriptorView, as after a descriptor scan.) + """ + from embit.descriptor import Descriptor + + from seedsigner.controller import Controller + from seedsigner.models.psbt_parser import PSBTParser + from seedsigner.views.seed_views import MultisigWalletDescriptorView + + from psbt_suite_util import MULTISIG_DESCRIPTOR, SUITE_NETWORK, load_psbt + + seed = self.controller.storage.seeds[0] + psbt = load_psbt("TX-21.ms_honest_change_no_xpubs") + self.controller.psbt = psbt + self.controller.psbt_seed = seed + self.controller.psbt_parser = PSBTParser(psbt, seed=seed, network=SUITE_NETWORK) + assert self.controller.psbt_parser.unidentified_change_outputs == [0] + self.controller.multisig_wallet_descriptor = Descriptor.from_string(MULTISIG_DESCRIPTOR) + self.controller.resume_main_flow = Controller.FLOW__PSBT + # On a device the descriptor screen is on the back stack when RETURN skips it. + from seedsigner.views.view import Destination + self.controller.back_stack.append(Destination(MultisigWalletDescriptorView)) + + def assert_identified(view): + parser = view.controller.psbt_parser + assert parser.unidentified_change_outputs == [] + assert parser.num_change_outputs == 1 + + self.run_sequence([ + FlowStep(MultisigWalletDescriptorView, + button_data_selection=MultisigWalletDescriptorView.RETURN), + FlowStep(psbt_views.PSBTOverviewView, screen_return_value=0), + FlowStep(psbt_views.PSBTMathView, before_run=assert_identified), + ]) diff --git a/tests/test_psbt_refusal_screens.py b/tests/test_psbt_refusal_screens.py index fa88b012d..d276c6c10 100644 --- a/tests/test_psbt_refusal_screens.py +++ b/tests/test_psbt_refusal_screens.py @@ -6,6 +6,12 @@ reason produces a visually broken screen that nothing else catches. These tests measure the real layout and fail if a message no longer fits. """ +# Before any seedsigner import: base installs the test doubles for the renderer +# and the hardware buttons. Importing the GUI first bound the real ones for every +# module collected after this file, so the flow tests that followed it hung -- on +# an unconfigured Renderer, or on real buttons waiting for a key press. +import base # noqa: F401 + import threading from unittest.mock import patch @@ -105,9 +111,8 @@ def test_real_refusal_message_fits(self, vector): 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.") + if presentation.text is not None: + pytest.skip(f"{excinfo.value.code} renders fixed prose; see test_table_prose_fits") text = str(excinfo.value) if presentation.tip: @@ -294,3 +299,23 @@ def test_shipped_json_is_plausible(self): data = json.loads(path.read_text(encoding="utf-8")) assert data["height"] > 900_000 assert data["timestamp"] > 1_700_000_000 + + +class TestIdentifyChangeScreenFits: + """PSBTIdentifyChangeView's text shares the warning box with a headline and two buttons.""" + + @pytest.mark.parametrize("text,buttons", [ + ("Load descriptor to identify change.", ["Load descriptor", "Continue as payment"]), + ("The loaded descriptor doesn't identify it. Shown as a payment.", ["Continue"]), + ]) + def test_text_fits(self, text, buttons): + screen = WarningScreen( + status_headline="Change Not Identified", + text=text, + button_data=[ButtonOption(b) for b in buttons], + show_back_button=True, + ) + text_area = [c for c in screen.components if c.__class__.__name__ == "TextArea"][-1] + lines = len(text_area.text_lines) + height = text_area.text_height_above_baseline * lines + text_area.line_spacing * (lines - 1) + assert height <= text_area.height, f"{lines} lines, {height}px in a {text_area.height}px box" diff --git a/tests/test_psbt_test_suite.py b/tests/test_psbt_test_suite.py index 2ffc6c1ef..45b14381a 100644 --- a/tests/test_psbt_test_suite.py +++ b/tests/test_psbt_test_suite.py @@ -851,3 +851,249 @@ def test_it_warns_rather_than_refuses(self): network=SUITE_NETWORK, max_fee_rate=1) assert parser.fee_amount > 0 # parsed fine, was not refused assert RiskWarning.HIGH_FEE_RATE not in RiskWarning.INFORMATIONAL # but interrupts + + +class TestOutputClaimsMatchScripts: + """ + Re-deriving a claimed key proves it is ours. It does not prove the output + pays it: a psbt can annotate a stranger's output with a genuine key and path + of ours (TX-21.claims_us_pays_other). Both halves have to hold. + """ + + def _with_other_genuine_key(self, name: str): + """The fixture's change output, re-annotated with a different key of ours.""" + from embit.psbt import DerivationPath + + psbt = load_psbt(name) + root = suite_seed().get_root(SUITE_NETWORK) + for out in psbt.outputs: + for pub, der in list(out.bip32_derivations.items()): + path = list(der.derivation[:-1]) + [der.derivation[-1] + 7] + del out.bip32_derivations[pub] + out.bip32_derivations[root.derive(path).key] = DerivationPath(der.fingerprint, path) + return psbt + + @pytest.mark.parametrize("name", ["NORMAL-1_p2wpkh", "NORMAL-2_wrapped", "NORMAL-3_legacy", + "NORMAL-1_p2wpkh_V2"]) + def test_genuine_key_on_a_script_that_does_not_pay_it_is_refused(self, name): + with pytest.raises(InvalidPSBTError) as excinfo: + PSBTParser(p=self._with_other_genuine_key(name), seed=suite_seed(), network=SUITE_NETWORK) + assert excinfo.value.code == RejectCode.FORGED_OUTPUT_OWNERSHIP + + def test_a_bogus_script_on_a_foreign_output_is_not_a_claim(self): + """NORMAL-2's destination carries a redeem script that hashes to nothing; it names no key of ours.""" + parser = PSBTParser(p=load_psbt("NORMAL-2_wrapped"), seed=suite_seed(), network=SUITE_NETWORK) + assert parser.num_change_outputs == 1 + + +class TestMultisigPolicy: + """ + The multisig vectors against the suite's registered 2-of-3 wallet. Without a + descriptor the parser can only tell whether this seed's key is in a script; + whether the script is the *wallet's* is the descriptor's job. + """ + + @staticmethod + def _descriptor(): + from embit.descriptor import Descriptor + from psbt_suite_util import MULTISIG_DESCRIPTOR + return Descriptor.from_string(MULTISIG_DESCRIPTOR) + + @staticmethod + def _honest_change(): + """TX-22.ms_decoy_first with its decoy removed: genuine multisig change.""" + psbt = load_psbt("TX-22.ms_decoy_first") + out = psbt.outputs[0] + decoys = [pub for pub in out.bip32_derivations if pub.sec() not in out.witness_script.data] + assert len(decoys) == 1 + decoy = (decoys[0], out.bip32_derivations.pop(decoys[0])) + return psbt, decoy + + @pytest.mark.parametrize("name", ["TX-13.threshold", "TX-13.reorder"]) + def test_tampered_change_is_not_the_wallets(self, name): + parser = parse_vector(VECTORS_BY_NAME[name]) + assert parser.num_change_outputs == 1 + assert parser.verify_multisig_output(self._descriptor(), 0) is False + + def test_genuine_change_is_the_wallets(self): + psbt, _decoy = self._honest_change() + parser = PSBTParser(p=psbt, seed=suite_seed(), network=SUITE_NETWORK) + assert parser.num_change_outputs == 1 + assert parser.verify_multisig_output(self._descriptor(), 0) is True + + @pytest.mark.parametrize("position", ["first", "last"]) + def test_a_decoy_fails_in_either_position(self, position): + """ + embit's Descriptor.owns stops at the first matching entry, so a decoy listed + after a genuine one used to pass. Checked here on an already-parsed psbt, + because the parser itself now refuses the decoy before it gets this far. + """ + from collections import OrderedDict + + psbt, (decoy_pub, decoy_der) = self._honest_change() + parser = PSBTParser(p=psbt, seed=suite_seed(), network=SUITE_NETWORK) + + out = parser.psbt.outputs[parser.get_change_data(0)["output_index"]] + entries = list(out.bip32_derivations.items()) + entries = [(decoy_pub, decoy_der)] + entries if position == "first" else entries + [(decoy_pub, decoy_der)] + out.bip32_derivations = OrderedDict(entries) + + assert parser.verify_multisig_output(self._descriptor(), 0) is False + + +class TestScriptTimelock: + """CLTV / CSV inside an output's own script lock the funds, not the transaction.""" + + def test_committed_cltv_script_is_flagged(self): + assert Advisory.SCRIPT_TIMELOCK in parse_vector(VECTORS_BY_NAME["TX-20.cltv_time"]).risk_warnings + + def test_uncommitted_script_is_ignored(self): + """A CLTV script the output does not commit to says nothing about the output.""" + from embit.psbt import PSBT + from embit.script import Script + + psbt = load_psbt("NORMAL-1_p2wpkh") + external = next(i for i, out in enumerate(psbt.outputs) if not out.bip32_derivations) + # <1,005,000> OP_CHECKLOCKTIMEVERIFY OP_DROP, attached to a p2wpkh output + psbt.outputs[external].witness_script = Script(bytes.fromhex("03c8550fb175")) + parser = PSBTParser(p=PSBT.parse(psbt.serialize()), seed=suite_seed(), network=SUITE_NETWORK) + assert Advisory.SCRIPT_TIMELOCK not in parser.risk_warnings + + def test_push_data_is_not_mistaken_for_an_opcode(self): + from embit.script import Script + # OP_DROP: the bytes are pushed as data, never executed. + assert PSBTParser._script_has_timelock(Script(bytes([0x03, 0xB1, 0xB2, 0xB1, 0x75]))) is False + # <0x0100> OP_CHECKSEQUENCEVERIFY + assert PSBTParser._script_has_timelock(Script(bytes([0x02, 0x00, 0x01, 0xB2]))) is True + + def test_it_interrupts_rather_than_being_informational(self): + from seedsigner.models.psbt_parser import RiskWarning + from seedsigner.views.psbt_views import PSBTRiskWarningView + assert RiskWarning.SCRIPT_TIMELOCK not in RiskWarning.INFORMATIONAL + assert RiskWarning.SCRIPT_TIMELOCK in PSBTRiskWarningView.RISK_TEXT + + +class TestPreviousTxProof: + """ + A non_witness_utxo is the whole previous transaction, so it can be proven: it + must hash to the txid the input spends. Legacy signatures commit to no amount, + so this hash is the only thing standing between a lying amount and the fee. + """ + + def test_altered_previous_tx_is_refused(self): + """XTRAS.PREV_TX_TXID_MISMATCH would otherwise show a 1,000-sat fee for an 800,000-sat one.""" + with pytest.raises(InvalidPSBTError) as excinfo: + parse_vector(VECTORS_BY_NAME["XTRAS.PREV_TX_TXID_MISMATCH"]) + assert excinfo.value.code == RejectCode.UTXO_MISMATCH + + def test_editing_a_normal_legacy_prev_tx_is_caught(self): + psbt = load_psbt("NORMAL-3_legacy") + inp = psbt.inputs[0] + inp.non_witness_utxo.vout[inp.vout].value -= 1 + with pytest.raises(InvalidPSBTError) as excinfo: + PSBTParser(p=psbt, seed=suite_seed(), network=SUITE_NETWORK) + assert excinfo.value.code == RejectCode.UTXO_MISMATCH + + def test_spending_an_output_the_prev_tx_lacks_is_refused(self): + """A vout past the end of the previous tx used to escape as an IndexError.""" + from embit.psbt import PSBT + + psbt = load_psbt("NORMAL-3_legacy") + psbt.tx.vin[0].vout = 99 + psbt = PSBT.parse(psbt.serialize()) + psbt.inputs[0].vout = 99 + with pytest.raises(InvalidPSBTError) as excinfo: + PSBTParser(p=psbt, seed=suite_seed(), network=SUITE_NETWORK) + assert excinfo.value.code == RejectCode.UTXO_MISMATCH + + def test_honest_legacy_prev_tx_still_parses(self): + parser = parse_vector(VECTORS_BY_NAME["NORMAL-3_legacy"]) + assert parser.input_amount == 100_000_000 + + +class TestOpReturnPayload: + """The payload is read from its push opcode, never sliced at a fixed offset.""" + + MSG = b"Chancellor on the brink of third bailout" + + @pytest.mark.parametrize("name", ["XTRAS.OP_RETURN_DIRECT_PUSH", "XTRAS.OP_RETURN_DIRECT_PUSH_V2"]) + def test_direct_push_is_shown_exactly(self, name): + assert parse_vector(VECTORS_BY_NAME[name]).op_return_data == self.MSG + + @pytest.mark.parametrize("script,expected", [ + (b"j(" + MSG, MSG), # direct push (<= 75 bytes) + (b"jLP" + b"x" * 80, b"x" * 80), # OP_PUSHDATA1 + (b"jM," + b"y" * 300, b"y" * 300), # OP_PUSHDATA2 + (b"j", b""), # bare OP_RETURN + (b"jab", b"ab"), # truncated push: what is there + ]) + def test_payload_parsing(self, script, expected): + assert PSBTParser._op_return_payload(script) == expected + + +class TestFingerprintConsistency: + """A key's derivation entry and the global xpub deriving it must name the same master.""" + + def test_relabelled_global_xpub_is_refused(self): + with pytest.raises(InvalidPSBTError) as excinfo: + parse_vector(VECTORS_BY_NAME["TX-24.xpub_fingerprint_mismatch"]) + assert excinfo.value.code == RejectCode.INCONSISTENT_FINGERPRINTS + + def test_unknown_fingerprint_is_not_a_contradiction(self): + """Coordinators write 00000000 for a fingerprint they do not know.""" + from embit.psbt import DerivationPath + + psbt = load_psbt("TX-24.xpub_fingerprint_mismatch") + for xpub, origin in list(psbt.xpubs.items()): + if origin.fingerprint == bytes.fromhex("deadbeef"): + psbt.xpubs[xpub] = DerivationPath(bytes(4), origin.derivation) + # Refused only for a contradiction; an unknown fingerprint just leaves that + # cosigner unresolved, so the change waits on a descriptor to be identified. + parser = PSBTParser(p=psbt, seed=suite_seed(), network=SUITE_NETWORK) + assert parser.num_change_outputs + len(parser.unidentified_change_outputs) == 1 + + +class TestUnidentifiedMultisigChange: + """ + Without global xpubs, nothing in a psbt ties a multisig change script's other keys + to the inputs' wallet, so our key being in it proves nothing. Such outputs are + payments until a known-good descriptor identifies them. + """ + + @staticmethod + def _descriptor(): + from embit.descriptor import Descriptor + from psbt_suite_util import MULTISIG_DESCRIPTOR + return Descriptor.from_string(MULTISIG_DESCRIPTOR) + + def _parse(self, name, **kw): + return PSBTParser(p=load_psbt(name), seed=suite_seed(), network=SUITE_NETWORK, **kw) + + def test_honest_change_without_xpubs_is_unidentified(self): + parser = self._parse("TX-21.ms_honest_change_no_xpubs") + assert parser.num_change_outputs == 0 + assert parser.unidentified_change_outputs == [0] + assert parser.spend_amount == 199_000 + + def test_the_descriptor_identifies_it(self): + parser = self._parse("TX-21.ms_honest_change_no_xpubs", multisig_descriptor=self._descriptor()) + assert parser.num_change_outputs == 1 + assert parser.unidentified_change_outputs == [] + + def test_a_foreign_quorum_is_never_identified(self): + """Loading the real wallet's descriptor must not turn the foreign 2-of-3 into change.""" + parser = self._parse("TX-21.ms_foreign_quorum_no_xpubs", multisig_descriptor=self._descriptor()) + assert parser.num_change_outputs == 0 + assert parser.unidentified_change_outputs == [0] + + def test_with_xpubs_the_foreign_quorum_is_a_plain_payment(self): + parser = self._parse("TX-21.ms_foreign_quorum") + assert parser.num_change_outputs == 0 + assert parser.unidentified_change_outputs == [] + + def test_change_with_xpubs_needs_no_descriptor(self): + """Global xpubs resolve every cosigner, so identification doesn't wait on a descriptor.""" + psbt, _decoy = TestMultisigPolicy._honest_change() + parser = PSBTParser(p=psbt, seed=suite_seed(), network=SUITE_NETWORK) + assert parser.num_change_outputs == 1 + assert parser.unidentified_change_outputs == [] diff --git a/tests/test_untrusted_qr_hardening.py b/tests/test_untrusted_qr_hardening.py new file mode 100644 index 000000000..36a2b84fb --- /dev/null +++ b/tests/test_untrusted_qr_hardening.py @@ -0,0 +1,91 @@ +""" +Scanned QR payloads are untrusted input. Each of these used to escape as an +uncaught exception -- the System Error screen, or in the UR2 case a device that +appears frozen -- instead of being turned away as an invalid QR. Mirrors fixes +proposed upstream (SeedSigner #967, #968, #970, #971). +""" +import time + +import pytest + +from seedsigner.helpers import embit_utils +from seedsigner.models.decode_qr import DecodeQR, DecodeQRStatus +from seedsigner.models.qr_type import QRType +from seedsigner.models.settings_definition import SettingsConstants + + +def decode(data: str): + decoder = DecodeQR(wordlist_language_code=SettingsConstants.WORDLIST_LANGUAGE__ENGLISH) + return decoder, decoder.add_data(data) + + +class TestSignMessageQr: + + @pytest.mark.parametrize("payload", [ + "signmessage", + "signmessage m/84h/0h/0h/0/0", + "signmessage m/84h/0h/0h/0/0 nocolon", + ]) + def test_malformed_payload_is_invalid_not_a_crash(self, payload): + _decoder, status = decode(payload) + assert status == DecodeQRStatus.INVALID + + def test_message_keeps_spaces_and_a_second_format_marker(self): + decoder, status = decode("signmessage m/84h/0h/0h/0/0 ascii:hello world ascii:again") + assert status == DecodeQRStatus.COMPLETE + assert decoder.get_qr_data()["message"] == "hello world ascii:again" + + +class TestStandardSeedQr: + + def test_bad_checksum_is_invalid(self): + """'abandon' x12 is twelve valid words with an invalid checksum.""" + _decoder, status = decode("0000" * 12) + assert status == DecodeQRStatus.INVALID + + def test_valid_seedqr_still_decodes(self): + """'abandon' x11 + 'about' (word 3) is the canonical valid 12-word mnemonic.""" + decoder, status = decode("0000" * 11 + "0003") + assert status == DecodeQRStatus.COMPLETE + assert decoder.get_seed_phrase()[-1] == "about" + + def test_a_digit_run_inside_other_data_is_not_a_seedqr(self): + assert DecodeQR.detect_segment_type("settings::v1 " + "1" * 48) != QRType.SEED__SEEDQR + + def test_whole_payload_seedqr_is_detected(self): + assert DecodeQR.detect_segment_type("0000" * 11 + "0003") == QRType.SEED__SEEDQR + + +class TestParseDerivationPath: + + @pytest.mark.parametrize("path", ["", "m", "x", "m/", "m/84h", "m/48h/0h/0h/2h/0/0"]) + def test_unparseable_path_is_an_unclean_match(self, path): + assert embit_utils.parse_derivation_path(path)["clean_match"] is False + + def test_standard_path_still_parses(self): + details = embit_utils.parse_derivation_path("m/84h/0h/0h/0/5") + assert details["clean_match"] is True + assert details["index"] == 5 + + +class TestUR2SeqLenBound: + + @staticmethod + def _part(seq_num, seq_len): + from seedsigner.helpers.ur2.fountain_encoder import Part + return Part(seq_num=seq_num, seq_len=seq_len, message_len=32, checksum=0, data=b"\x00" * 32) + + def test_implausible_part_count_is_rejected_quickly(self): + from seedsigner.helpers.ur2.fountain_decoder import FountainDecoder, MAX_SEQ_LEN + + decoder = FountainDecoder() + started = time.monotonic() + assert decoder.receive_part(self._part(seq_num=MAX_SEQ_LEN * 10, seq_len=MAX_SEQ_LEN * 10)) is False + assert time.monotonic() - started < 1 + assert decoder.expected_part_indexes is None + + def test_plausible_part_count_is_accepted(self): + from seedsigner.helpers.ur2.fountain_decoder import FountainDecoder + + decoder = FountainDecoder() + assert decoder.validate_part(self._part(seq_num=1, seq_len=10)) is True