diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 3956cfd18c..a97d8f6e9a 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -20,9 +20,14 @@ class OPCODES: OP_RETURN = 106 + + # Opcodes 0x01-0x4b are themselves the number of bytes to push, so 75 is the largest + # payload a direct push can carry. + OP_PUSHDATA_MAX_DIRECT = 75 OP_PUSHDATA1 = 76 OP_PUSHDATA2 = 77 OP_PUSHDATA4 = 78 + OP_16 = 96 OP_CHECKLOCKTIMEVERIFY = 177 OP_CHECKSEQUENCEVERIFY = 178 @@ -33,7 +38,7 @@ class OPCODES: # Outputs below this are uneconomic to spend and are flagged for review. DUST_THRESHOLD = 546 -# Fee at or above input_amount * HIGH_FEE_NUMERATOR / HIGH_FEE_DENOMINATOR is flagged. +# Fee at or above verified_input_amount * HIGH_FEE_NUMERATOR / HIGH_FEE_DENOMINATOR is flagged. HIGH_FEE_NUMERATOR = 1 HIGH_FEE_DENOMINATOR = 10 @@ -132,6 +137,24 @@ class RejectCode: EXTRANEOUS_WITNESS_SCRIPT = "EXTRANEOUS_WITNESS_SCRIPT" UTXO_MISMATCH = "UTXO_MISMATCH" SCRIPT_HASH_MISMATCH = "SCRIPT_HASH_MISMATCH" + + # An input commits to a redeem or witness script (p2sh, p2wsh, or both for + # nested segwit multisig) that the psbt did not supply. Unlike a script that + # hashes to the wrong thing, an omission deceives no one, so it is graded as a + # malformed psbt rather than an attack. Upstream's PSBTMissingInputScriptError. + MISSING_INPUT_SCRIPT = "MISSING_INPUT_SCRIPT" + + # A redeem_script on an input whose scriptPubKey is not p2sh: it hashes to + # nothing the input commits to, and could only distort how the parser reads + # the wallet being spent from. Upstream's PSBTExtraneousInputScriptError, as + # is EXTRANEOUS_WITNESS_SCRIPT. + EXTRANEOUS_REDEEM_SCRIPT = "EXTRANEOUS_REDEEM_SCRIPT" + + # An OP_RETURN output whose script is not made of complete pushes: a push that + # runs past the end of the script, or an opcode that is not a push at all. + # Bitcoin Core treats such an output as nonstandard, and no display of its data + # would be faithful. Upstream's PSBTMalformedOpReturnError. + MALFORMED_OP_RETURN = "MALFORMED_OP_RETURN" UNREACHABLE_CHANGE_PATH = "UNREACHABLE_CHANGE_PATH" NONZERO_OP_RETURN = "NONZERO_OP_RETURN" UNSUPPORTED_SIGHASH = "UNSUPPORTED_SIGHASH" @@ -334,7 +357,9 @@ def __init__( self.change_amount = 0 self.change_data = [] self.fee_amount = 0 - self.input_amount = 0 + # Only ever the total of inputs that passed _validate_input. Upstream's name; + # input_amount is kept as an alias for the fork's callers. + self.verified_input_amount = 0 self.num_inputs = 0 self.verified_input_prefixes: set = set() self.verified_max_input_index: int = -1 @@ -451,6 +476,12 @@ def num_destinations(self): return len(self.destination_addresses) + @property + def input_amount(self) -> int: + """Alias for verified_input_amount.""" + return self.verified_input_amount + + @property def op_return_data(self) -> bytes | None: """The first OP_RETURN payload, or None. See op_return_payloads for all of them.""" @@ -498,7 +529,11 @@ def parse(self): 4. _parse_inputs: every input must resolve to the same policy, otherwise RejectCode.MIXED_INPUTS. Each input is also structurally validated here - (RejectCode.MISSING_UTXO, UNSUPPORTED_SIGHASH, and the rest). + (RejectCode.MISSING_UTXO, UNSUPPORTED_SIGHASH, and the rest): its declared + amount must be proven (a non_witness_utxo that hashes to its txid) or + committed to by its sighash, and it must supply exactly the redeem/witness + scripts its scriptPubKey commits to. Only then is it totaled into + verified_input_amount. A policy is one of: - single-sig: the script type alone. Says nothing about keys. @@ -1033,6 +1068,8 @@ def _validate_input(index: int, inp: InputScope): f"Input {index} spends an output its previous tx does not have.", code=RejectCode.UTXO_MISMATCH, ) + # Proven above; let embit record it too (InputScope.is_verified). + inp.verify() if witness_utxo is not None and non_witness_utxo is not None: # Both forms supplied: they must describe the same prevout. This is @@ -1083,12 +1120,23 @@ def _validate_input(index: int, inp: InputScope): code=RejectCode.INVALID_WITNESS_UTXO, ) + # Every input must supply exactly the scripts its scriptPubKey commits to: a + # p2sh or p2wsh scriptPubKey holds only a hash, so the supplied script is + # rebuilt into it and compared, and any script beyond those is refused. A + # misleading script could otherwise distort how the parser reads the wallet + # being spent from, and so which outputs it treats as change. + # + # TODO: Support finalized inputs, such as a payjoin receiver's input. + # Finalizing an input clears its script fields and leaves the script only in + # its final scriptSig or witness, so a finalized p2sh or p2wsh input is + # refused here for missing its script. Recover the script from the final + # fields, verify it the same way, and read the policy from it. effective_type = script_type if script_type == "p2sh": if inp.redeem_script is None: raise InvalidPSBTError( f"Input {index} is p2sh with no redeem_script.", - code=RejectCode.SCRIPT_HASH_MISMATCH, + code=RejectCode.MISSING_INPUT_SCRIPT, ) if script.p2sh(inp.redeem_script).data != script_pubkey.data: raise InvalidPSBTError( @@ -1109,7 +1157,7 @@ def _validate_input(index: int, inp: InputScope): if inp.witness_script is None: raise InvalidPSBTError( f"Input {index} is p2wsh with no witness_script.", - code=RejectCode.SCRIPT_HASH_MISMATCH, + code=RejectCode.MISSING_INPUT_SCRIPT, ) expected = inp.redeem_script if script_type == "p2sh" else script_pubkey if script.p2wsh(inp.witness_script).data != expected.data: @@ -1125,9 +1173,23 @@ def _validate_input(index: int, inp: InputScope): code=RejectCode.EXTRANEOUS_WITNESS_SCRIPT, ) + if inp.redeem_script is not None and script_type != "p2sh": + # Likewise a redeem_script on anything but a p2sh input (e.g. one on a + # native segwit input) commits to nothing. + raise InvalidPSBTError( + f"Input {index} has a stray redeem_script.", + code=RejectCode.EXTRANEOUS_REDEEM_SCRIPT, + ) + def _parse_inputs(self, child_key_derivation_cache: dict): - self.input_amount = 0 + """ + Validates every input (see _validate_input), totals their now-verified amounts + as verified_input_amount, and determines the wallet policy. Every input must + resolve to the same policy, otherwise RejectCode.MIXED_INPUTS. + """ + self.verified_input_amount = 0 + verified_input_amount = 0 self.num_inputs = len(self.psbt.inputs) self.verified_input_prefixes = set() self.verified_max_input_index = -1 @@ -1179,18 +1241,20 @@ def _parse_inputs(self, child_key_derivation_cache: dict): derivation[-1] & 0x7FFFFFFF, ) - if inp.witness_utxo: - self.input_amount += inp.witness_utxo.value - script_pubkey = inp.witness_utxo.script_pubkey - elif inp.non_witness_utxo: - self.input_amount += inp.utxo.value - script_pubkey = inp.script_pubkey + # _validate_input proved the utxo (or refused the psbt), and that a + # witness_utxo supplied alongside a non_witness_utxo agrees with it. + verified_input_amount += inp.utxo.value + script_pubkey = inp.script_pubkey inp_policy = PSBTParser._get_policy(inp, script_pubkey, self.psbt.xpubs, child_key_derivation_cache) if self.policy == None: self.policy = inp_policy else: if self.policy != inp_policy: + # TODO: Read the policy only from the user's own inputs. Requiring + # every input to share one policy rejects a collaborative spend whose + # other party spends from a different script type or multisig wallet, + # which is allowed by BIP-174 and BIP-78. raise InvalidPSBTError( "Mixed inputs in the transaction", code=RejectCode.MIXED_INPUTS, @@ -1198,12 +1262,16 @@ def _parse_inputs(self, child_key_derivation_cache: dict): # Each input was range-checked on its own; together they can still claim # more than can exist. - if self.input_amount > MAX_MONEY: + if verified_input_amount > MAX_MONEY: raise InvalidPSBTError( - f"Inputs total {self.input_amount} sats, more than can exist.", + f"Inputs total {verified_input_amount} sats, more than can exist.", code=RejectCode.AMOUNT_OUT_OF_RANGE, ) + # Only assigned once every input has passed, so a rejected psbt leaves no + # partial total. + self.verified_input_amount = verified_input_amount + @staticmethod def is_reachable_derivation(derivation: list[int], input_prefixes: set | None) -> bool: """ @@ -1473,7 +1541,7 @@ def _parse_outputs(self, child_key_derivation_cache: dict): # Is this output change? If this output's policy is superficially similar to # the spending wallet's policy (e.g. they're both 2-of-3 p2wsh), then it's a # candidate for being change. - if PSBTParser._policy_shape_matches(out_policy, self.policy): + if self._is_change_candidate(out, out_policy): # Begin the extensive work to fully verify whether this output is indeed # change. @@ -1788,15 +1856,10 @@ def _parse_outputs(self, child_key_derivation_cache: dict): ) if vout[i].script_pubkey.data[0] == OPCODES.OP_RETURN: - payload = PSBTParser._op_return_payload(vout[i].script_pubkey.data) - if payload is None: - # Shown as whatever its pushes happen to yield, it would not be - # what the output carries. Standard OP_RETURNs are push-only. - raise InvalidPSBTError( - f"Output {i} OP_RETURN data is malformed.", - code=RejectCode.UNDISPLAYABLE_OUTPUT, - ) - self.op_return_payloads.append(payload) + # Raises RejectCode.MALFORMED_OP_RETURN unless the script is push-only + self.op_return_payloads.append( + PSBTParser._parse_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 @@ -1857,6 +1920,9 @@ def _parse_outputs(self, child_key_derivation_cache: dict): self.destination_amounts.append(vout[i].value) self.spend_amount += vout[i].value + # embit computes the fee as inputs minus outputs and does not look at the sign of + # the result. Zero is left alone: it is a pointless transaction, but not a + # malformed one. self.fee_amount = self.psbt.fee() if self.fee_amount < 0: @@ -1869,9 +1935,9 @@ def _parse_outputs(self, child_key_derivation_cache: dict): ) accounted = self.spend_amount + self.change_amount + self.op_return_amount + self.fee_amount - if accounted != self.input_amount: + if accounted != self.verified_input_amount: raise InvalidPSBTError( - f"Amounts do not add up: {accounted} vs {self.input_amount} in.", + f"Amounts do not add up: {accounted} vs {self.verified_input_amount} in.", code=RejectCode.AMOUNT_OUT_OF_RANGE, ) @@ -1900,8 +1966,8 @@ def _collect_risk_warnings(self): Flag the things a user would want to know before approving, none of which make the transaction invalid. """ - if self.input_amount > 0 and ( - self.fee_amount * HIGH_FEE_DENOMINATOR >= self.input_amount * HIGH_FEE_NUMERATOR + if self.verified_input_amount > 0 and ( + self.fee_amount * HIGH_FEE_DENOMINATOR >= self.verified_input_amount * HIGH_FEE_NUMERATOR ): self.risk_warnings.add(RiskWarning.HIGH_FEE) @@ -2026,42 +2092,83 @@ def _script_has_timelock(sc) -> bool: @staticmethod - def _op_return_payload(data: bytes) -> bytes | None: - """ - The data an OP_RETURN script carries: everything its pushes push, in order. - None if anything after the OP_RETURN is not a complete data push -- a push - that runs past the end of the script, or a non-push opcode -- since no - display of it would be faithful. - - 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. - """ - body = data[1:] - payload = b"" - pos = 0 - while pos < len(body): - op = body[pos] - pos += 1 - if op == 0x00: - # OP_0: an empty push. + def _parse_op_return_payload(script_data: bytes) -> bytes: + """ + Extracts the data an OP_RETURN output carries, for every way the script can push + it. + + Script pushes data with a variable-width opcode: opcodes 0x01 through 0x4b are + themselves the byte count, while OP_PUSHDATA1, 2, and 4 are followed by a 1, 2, + or 4 byte little-endian length. Bitcoin Core emits the minimal encoding, so a + payload of 75 bytes or fewer arrives as a direct push. (Slicing at a fixed + offset, as this used to, dropped the first byte of every short payload.) + + A script may hold more than one push after OP_RETURN. That is unusual but legal, + and the pushes are concatenated here rather than returned separately, since where + the encoder chose to break the data into pushes carries no consensus meaning. + + Bitcoin Core treats an OP_RETURN output as nonstandard unless everything after the + opcode is a push (IsPushOnly: any opcode up to OP_16). Raises InvalidPSBTError + with RejectCode.MALFORMED_OP_RETURN for a push that runs past the end of the + script or an opcode that is not a push, since no display of it would be faithful. + OP_0, OP_1NEGATE, OP_RESERVED, and OP_1 through OP_16 carry no data bytes but + Core still counts them as pushes, so their opcode bytes are kept as-is. Runes, for + one, opens every runestone with OP_13. The caller gets raw bytes and decides how + to render them. + """ + pushes = [] + + # Start after the OP_RETURN opcode itself + i = 1 + while i < len(script_data): + opcode = script_data[i] + + if 1 <= opcode <= OPCODES.OP_PUSHDATA_MAX_DIRECT: + # The opcode is itself the length; no separate length field follows + length_size = 0 + elif opcode == OPCODES.OP_PUSHDATA1: + length_size = 1 + elif opcode == OPCODES.OP_PUSHDATA2: + length_size = 2 + elif opcode == OPCODES.OP_PUSHDATA4: + length_size = 4 + elif opcode <= OPCODES.OP_16: + # No data bytes follow; keep the opcode byte itself so it is shown + pushes.append(script_data[i:i + 1]) + i += 1 continue - if op <= 0x4B: - length = op - elif op in (OPCODES.OP_PUSHDATA1, OPCODES.OP_PUSHDATA2, OPCODES.OP_PUSHDATA4): - width = {OPCODES.OP_PUSHDATA1: 1, OPCODES.OP_PUSHDATA2: 2, - OPCODES.OP_PUSHDATA4: 4}[op] - if pos + width > len(body): - return None - length = int.from_bytes(body[pos:pos + width], "little") - pos += width else: - return None - if pos + length > len(body): - return None - payload += body[pos:pos + length] - pos += length - return payload + # Not a push, so the script cannot be read as OP_RETURN data + raise InvalidPSBTError( + f"OP_RETURN script holds non-push opcode 0x{opcode:02x}", + code=RejectCode.MALFORMED_OP_RETURN, + ) + + if length_size == 0: + length = opcode + else: + length_end = i + 1 + length_size + if length_end > len(script_data): + # The length field itself is truncated, so the push size is unknown + raise InvalidPSBTError( + "OP_RETURN push length field is truncated", + code=RejectCode.MALFORMED_OP_RETURN, + ) + length = int.from_bytes(script_data[i + 1:length_end], "little") + + data_start = i + 1 + length_size + data_end = data_start + length + if data_end > len(script_data): + # The push claims more data than the script carries + raise InvalidPSBTError( + f"OP_RETURN push declares {length} bytes but only {len(script_data) - data_start} remain", + code=RejectCode.MALFORMED_OP_RETURN, + ) + + pushes.append(script_data[data_start:data_end]) + i = data_end + + return b"".join(pushes) @staticmethod @@ -2093,9 +2200,8 @@ def sig_count(tx): @staticmethod - def _get_policy(scope, scriptpubkey, xpubs, child_key_derivation_cache: dict | None): - """Parse scope and get policy""" - # we don't know the policy yet, let's parse it + def _get_script_type(scope, scriptpubkey) -> str: + """Like script_type(), but tells nested segwit p2sh apart from legacy p2sh""" script_type = scriptpubkey.script_type() # p2sh can be either legacy multisig, or nested segwit multisig # or nested segwit singlesig @@ -2107,6 +2213,14 @@ def _get_policy(scope, scriptpubkey, xpubs, child_key_derivation_cache: dict | N and scope.redeem_script.script_type() == "p2wpkh" ): script_type = "p2sh-p2wpkh" + return script_type + + + @staticmethod + def _get_policy(scope, scriptpubkey, xpubs, child_key_derivation_cache: dict | None): + """Parse scope and get policy""" + # we don't know the policy yet, let's parse it + script_type = PSBTParser._get_script_type(scope, scriptpubkey) policy = {"type": script_type} # expected multisig @@ -2147,23 +2261,49 @@ def _get_policy(scope, scriptpubkey, xpubs, child_key_derivation_cache: dict | N return policy - @staticmethod - def _policy_shape_matches(policy_a: dict, policy_b: dict) -> bool: + def _is_change_candidate(self, out: OutputScope, out_policy: dict) -> bool: """ - Compares two policies on the shape of the script they describe: the script type, - plus m-of-n for multisig. + Determines whether an output is worth the full ownership check in _parse_outputs. + + Returns True if the output's policy has the same "shape" as the inputs' policy: + the script type, plus m-of-n for multisig. + + One outlier: Nested single sig (p2sh-p2wpkh). Its scriptPubKey is a p2sh hash of + its redeem script, but per BIP-174 the redeem script itself is optional. + When it is omitted, the output is superficially indistinguishable from plain p2sh. + If the inputs are p2sh-p2wpkh, then such an output would fail the policy + comparison test (p2sh != p2sh-p2wpkh) when it may have actually been possible to + verify it as our change. + + So instead, when a p2sh output could be our own nested single sig change we let it + through and leave it to the rebuild process to verify if the output really is our + change. - A policy can also carry the cosigners resolved from the coordinator's global - xpubs. Those are never authoritative here, and comparing them would let a psbt - decide which of its own outputs get verified: one misannotated fingerprint makes - that output's cosigners fail to resolve, and the output then stops matching the - inputs' policy. Shape comes from the scriptPubKey and the supplied script, and the - caller proves ownership rather than assuming it. + Note: A multisig's input or output policy can also include the cosigners if + they're supplied in the global xpubs. Those are never authoritative here, and + comparing them would let a psbt decide which of its own outputs get verified: + * One misannotated derivation path would make that output's cosigners fail + to resolve. + * The output's missing cosigners would mean that it would not match the inputs' + cosigners. + * End result: the output would not be considered a change candidate and would + not go through the same scrutiny that change candidates do. + + Shape comes from the scriptPubKey and the supplied script, and the caller proves + ownership rather than assuming it. """ + # The outlier: a single sig p2sh output when the inputs are p2sh-p2wpkh. + if ( + self.policy["type"] == "p2sh-p2wpkh" # Input is nested single sig + and out_policy["type"] == "p2sh" # Output parses as plain p2sh + and out.redeem_script is None # Output omits its redeem script + ): + return True + + # All other outputs must have the same policy shape as the inputs for field in ("type", "m", "n"): - if policy_a.get(field) != policy_b.get(field): + if out_policy.get(field) != self.policy.get(field): return False - return True @@ -2755,12 +2895,8 @@ def _verify_claim_shapes(self): 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" - ) + script_type = PSBTParser._get_script_type(scope, script_pubkey) + is_single_key = script_type in ("p2pkh", "p2wpkh", "p2sh-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( diff --git a/src/seedsigner/models/settings_definition.py b/src/seedsigner/models/settings_definition.py index 9b058e0a35..300a3022b6 100644 --- a/src/seedsigner/models/settings_definition.py +++ b/src/seedsigner/models/settings_definition.py @@ -116,6 +116,7 @@ class SettingsConstants: LOCALE__SLOVENIAN = "sl" LOCALE__SPANISH = "es" LOCALE__SWEDISH = "sv" + LOCALE__SWAHILI = "sw" LOCALE__TAGALOG = "tl" LOCALE__TAMIL = "ta" LOCALE__TELUGU = "te" @@ -154,6 +155,7 @@ class SettingsConstants: LOCALE__PERSIAN: "(beta) فارسی (Persian)", LOCALE__POLISH: "(beta) Polski", LOCALE__PORTUGUESE_BR: "(beta) Português (Brasil)", + LOCALE__SWAHILI: "(beta) Kiswahili (Swahili)", LOCALE__THAI: "(beta) ไทย (Thai)", LOCALE__VIETNAMESE: "(beta) Tiếng Việt (Vietnamese)", diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index e14900e5e2..ec63ceb331 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -578,6 +578,85 @@ class RejectPresentation: button_label=_mft("Discard transaction"), ), + # The declared input amounts are unproven or false: a previous tx that doesn't hash + # to the txid it claims, a witness_utxo that contradicts it, or a legacy input with + # only a witness_utxo, whose amount no legacy signature commits to. Any of them lets + # the coordinator show whatever fee it likes. Upstream's + # PSBTInputAmountVerificationFailedView. + RejectCode.UTXO_MISMATCH: RejectPresentation( + screen=DireWarningScreen, + title=_mft("Suspicious Transaction"), + headline=_mft("Likely an Attack!"), + text=_mft("This transaction's input amounts cannot be verified, so its fee cannot be trusted."), + button_label=_mft("Discard transaction"), + ), + + RejectCode.INVALID_WITNESS_UTXO: RejectPresentation( + screen=DireWarningScreen, + title=_mft("Suspicious Transaction"), + headline=_mft("Likely an Attack!"), + text=_mft("This transaction's input amounts cannot be verified, so its fee cannot be trusted."), + button_label=_mft("Discard transaction"), + ), + + RejectCode.SCRIPT_HASH_MISMATCH: RejectPresentation( + screen=DireWarningScreen, + title=_mft("Suspicious Transaction"), + headline=_mft("Likely an Attack!"), + # TRANSLATOR_NOTE: The transaction/psbt contains a deception that we consider an attack. + text=_mft("This transaction supplied the wrong script for one of its inputs."), + button_label=_mft("Discard transaction"), + ), + + # The rest are malformed psbts rather than proven deceptions: refused, but only at + # the "Warning" level. + RejectCode.MISSING_UTXO: RejectPresentation( + screen=WarningScreen, + title=_mft("Transaction Problem"), + # TRANSLATOR_NOTE: The transaction/psbt has an error but does not seem to be malicious. + text=_mft("This transaction is missing required data for one of its inputs."), + button_label=_mft("Discard transaction"), + ), + + RejectCode.MISSING_INPUT_SCRIPT: RejectPresentation( + screen=WarningScreen, + title=_mft("Transaction Problem"), + # TRANSLATOR_NOTE: The transaction/psbt has an error but does not seem to be malicious. + text=_mft("This transaction left out a script that one of its inputs needs."), + button_label=_mft("Discard transaction"), + ), + + RejectCode.EXTRANEOUS_REDEEM_SCRIPT: RejectPresentation( + screen=WarningScreen, + title=_mft("Transaction Problem"), + # TRANSLATOR_NOTE: The transaction/psbt has an error but does not seem to be malicious. + text=_mft("This transaction supplied an extra script for one of its inputs."), + button_label=_mft("Discard transaction"), + ), + + RejectCode.EXTRANEOUS_WITNESS_SCRIPT: RejectPresentation( + screen=WarningScreen, + title=_mft("Transaction Problem"), + text=_mft("This transaction supplied an extra script for one of its inputs."), + button_label=_mft("Discard transaction"), + ), + + RejectCode.NEGATIVE_FEE: RejectPresentation( + screen=WarningScreen, + title=_mft("Transaction Problem"), + # TRANSLATOR_NOTE: The transaction's outputs spend more than its inputs hold, which is impossible. + text=_mft("This transaction's outputs send more than its inputs provide."), + button_label=_mft("Discard transaction"), + ), + + RejectCode.MALFORMED_OP_RETURN: RejectPresentation( + screen=WarningScreen, + title=_mft("Transaction Problem"), + # TRANSLATOR_NOTE: The transaction/psbt has an error but does not seem to be malicious. + text=_mft("This transaction's OP_RETURN data is malformed."), + button_label=_mft("Discard transaction"), + ), + RejectCode.SEED_CANNOT_SIGN: RejectPresentation( # An informational mismatch, not a warning, so it uses the neutral info icon and # color rather than WarningScreen's alarming yellow edges. @@ -611,6 +690,10 @@ class PSBTRefusalView(View): """ code: str = None + # Further codes a named subclass also stands for. Each is still drawn from its own + # REJECT_PRESENTATION entry; this only decides which View class it routes to. + also_codes: tuple = () + def __init__(self, code: str = None, message: str = None): super().__init__() self.code = code if code is not None else self.code @@ -687,10 +770,73 @@ class PSBTSeedCannotSignView(PSBTRefusalView): SELECT_DIFFERENT_SEED = ButtonOption("Select a different seed") +class PSBTInputAmountVerificationFailedView(PSBTRefusalView): + """ + An input's declared amount is unproven or false, so the fee cannot be trusted. Shows + a dire warning and discards the psbt. + """ + code = RejectCode.UTXO_MISMATCH + also_codes = (RejectCode.INVALID_WITNESS_UTXO,) + DISCARD = ButtonOption("Discard transaction") + + + +class PSBTMissingInputUtxoView(PSBTRefusalView): + """An input is missing the utxo it spends. Malformed rather than hostile.""" + code = RejectCode.MISSING_UTXO + DISCARD = ButtonOption("Discard transaction") + + + +class PSBTMissingInputScriptView(PSBTRefusalView): + """An input commits to a script the psbt did not supply. Malformed rather than hostile.""" + code = RejectCode.MISSING_INPUT_SCRIPT + DISCARD = ButtonOption("Discard transaction") + + + +class PSBTInputScriptMismatchView(PSBTRefusalView): + """ + An input supplies a script other than the one its scriptPubKey commits to. Treated + as an attack: a dire warning, and the psbt is discarded. + """ + code = RejectCode.SCRIPT_HASH_MISMATCH + DISCARD = ButtonOption("Discard transaction") + + + +class PSBTExtraneousInputScriptView(PSBTRefusalView): + """ + An input supplies a redeem or witness script its scriptPubKey doesn't commit to. Not + graded as an attack or a mistake. + """ + code = RejectCode.EXTRANEOUS_REDEEM_SCRIPT + also_codes = (RejectCode.EXTRANEOUS_WITNESS_SCRIPT,) + DISCARD = ButtonOption("Discard transaction") + + + +class PSBTNegativeFeeView(PSBTRefusalView): + """The outputs spend more than the inputs bring in. Malformed rather than hostile.""" + code = RejectCode.NEGATIVE_FEE + DISCARD = ButtonOption("Discard transaction") + + + +class PSBTMalformedOpReturnView(PSBTRefusalView): + """An OP_RETURN script is not made of complete pushes. Malformed rather than hostile.""" + code = RejectCode.MALFORMED_OP_RETURN + DISCARD = ButtonOption("Discard transaction") + + # The named subclasses above, keyed by the code each one fixes. A code without one is # rendered by PSBTRefusalView itself; give a code its own subclass when it is worth # naming in a flow test or a screenshot, and it lands here automatically. -REFUSAL_VIEWS = {cls.code: cls for cls in PSBTRefusalView.__subclasses__()} +REFUSAL_VIEWS = { + code: cls + for cls in PSBTRefusalView.__subclasses__() + for code in (cls.code, *cls.also_codes) +} def refusal_destination(error: InvalidPSBTError) -> Destination: @@ -1158,7 +1304,7 @@ def run(self): selected_menu_num = self.run_screen( PSBTMathScreen, - input_amount=psbt_parser.input_amount, + input_amount=psbt_parser.verified_input_amount, num_inputs=psbt_parser.num_inputs, # An OP_RETURN carrying value is value leaving the wallet with no # recipient. Counting it as spend is what makes diff --git a/tests/data/psbt_test_suite/PROVENANCE.md b/tests/data/psbt_test_suite/PROVENANCE.md index 360c48acaf..072f1dd296 100644 --- a/tests/data/psbt_test_suite/PROVENANCE.md +++ b/tests/data/psbt_test_suite/PROVENANCE.md @@ -92,3 +92,34 @@ Without a `non_witness_utxo`, an offline signer cannot tell those bytes from an honest v2 spend. Signing it is safe: the input is segwit v0, and BIP-143 commits the signature to the `witness_utxo` amount and script, so the signature is invalid for any outpoint that does not hold exactly that. + +## Follow-up of 2026-10-31 + +Vectors for the merge of upstream SeedSigner #995 (input amounts), #1041 (negative +fee), #1042 (OP_RETURN push opcodes), #1046 (nested single sig change without a +redeem_script) and #1047 (input scripts), plus nested segwit multisig input +scripts. They are generated by the local psbt_faker's new 2026-10-31 builders and +vendored with `psbt_test_suite/generate.py --keep-existing`, which adds new tests +without regenerating the shipped ones. Each builder runs with the RNG seeded from its +test id, so its bytes are reproducible. Single sig wrapped vectors use the seed's +BIP49 account (`m/49h/0h/0h`). + +* OP_RETURN: `XTRAS.OP_RETURN_RUNESTONE`, `_SMALLINT` and `_MULTI_PUSH` are negative + controls (push-only, so they must be shown). `_TRUNCATED_PUSH` and `_NON_PUSH` are + refused as `MALFORMED_OP_RETURN`. Every one has a `_V2` twin. +* Input scripts: `XTRAS.STRAY_REDEEM_SCRIPT` (`EXTRANEOUS_REDEEM_SCRIPT`), + `XTRAS.MISSING_REDEEM_SCRIPT` and `XTRAS.MISSING_WITNESS_SCRIPT` + (`MISSING_INPUT_SCRIPT`), `XTRAS.WRONG_REDEEM_SCRIPT` and + `XTRAS.FOREIGN_INPUT_BAD_SCRIPT` (`SCRIPT_HASH_MISMATCH`). +* Nested segwit multisig: `XTRAS.MS_NESTED_*` use the corpus's three seeds as a + 2-of-3 P2SH-P2WSH wallet at `m/48h/0h/0h/1h`, the second wallet in psbt_faker's + multisig section. `_HONEST` is the negative control. `_WRONG_WITNESS_SCRIPT` breaks + only the inner layer (witness_script to redeem_script) and `_WRONG_REDEEM_SCRIPT` + only the outer one (redeem_script to scriptPubKey), so a signer must check both. + `_MISSING_WITNESS_SCRIPT` is malformed. Building these needed a psbt_faker fix: + `fake_ms_txn` used to set a nested input's redeem_script to the multisig itself and + omitted the redeem_script on nested change. +* Change: `XTRAS.NESTED_CHANGE_NO_REDEEM` (negative control, counted as change) and + `TX-21.nested_bare_p2sh_claims_us_pays_other` (`FORGED_OUTPUT_OWNERSHIP`). Before + the merge, the second one parsed as an ordinary payment. +* Fee: `XTRAS.ZERO_FEE` is a negative control. Zero is pointless but not malformed. diff --git a/tests/data/psbt_test_suite/TX-21.nested_bare_p2sh_claims_us_pays_other.psbt b/tests/data/psbt_test_suite/TX-21.nested_bare_p2sh_claims_us_pays_other.psbt new file mode 100644 index 0000000000..fd46db3cf4 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-21.nested_bare_p2sh_claims_us_pays_other.psbt differ diff --git a/tests/data/psbt_test_suite/TX-21.nested_bare_p2sh_claims_us_pays_other_V2.psbt b/tests/data/psbt_test_suite/TX-21.nested_bare_p2sh_claims_us_pays_other_V2.psbt new file mode 100644 index 0000000000..b83d351c13 Binary files /dev/null and b/tests/data/psbt_test_suite/TX-21.nested_bare_p2sh_claims_us_pays_other_V2.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.FOREIGN_INPUT_BAD_SCRIPT.psbt b/tests/data/psbt_test_suite/XTRAS.FOREIGN_INPUT_BAD_SCRIPT.psbt new file mode 100644 index 0000000000..bc5c850795 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.FOREIGN_INPUT_BAD_SCRIPT.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.MISSING_REDEEM_SCRIPT.psbt b/tests/data/psbt_test_suite/XTRAS.MISSING_REDEEM_SCRIPT.psbt new file mode 100644 index 0000000000..2d99d5ec6b Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.MISSING_REDEEM_SCRIPT.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.MISSING_REDEEM_SCRIPT_V2.psbt b/tests/data/psbt_test_suite/XTRAS.MISSING_REDEEM_SCRIPT_V2.psbt new file mode 100644 index 0000000000..b06bcfc24a Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.MISSING_REDEEM_SCRIPT_V2.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.MISSING_WITNESS_SCRIPT.psbt b/tests/data/psbt_test_suite/XTRAS.MISSING_WITNESS_SCRIPT.psbt new file mode 100644 index 0000000000..0eb48c4bb9 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.MISSING_WITNESS_SCRIPT.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.MS_NESTED_HONEST.psbt b/tests/data/psbt_test_suite/XTRAS.MS_NESTED_HONEST.psbt new file mode 100644 index 0000000000..414d23ea04 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.MS_NESTED_HONEST.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.MS_NESTED_MISSING_WITNESS_SCRIPT.psbt b/tests/data/psbt_test_suite/XTRAS.MS_NESTED_MISSING_WITNESS_SCRIPT.psbt new file mode 100644 index 0000000000..330280b571 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.MS_NESTED_MISSING_WITNESS_SCRIPT.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.MS_NESTED_WRONG_REDEEM_SCRIPT.psbt b/tests/data/psbt_test_suite/XTRAS.MS_NESTED_WRONG_REDEEM_SCRIPT.psbt new file mode 100644 index 0000000000..17f4a8e71e Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.MS_NESTED_WRONG_REDEEM_SCRIPT.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.MS_NESTED_WRONG_WITNESS_SCRIPT.psbt b/tests/data/psbt_test_suite/XTRAS.MS_NESTED_WRONG_WITNESS_SCRIPT.psbt new file mode 100644 index 0000000000..7d4f87b823 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.MS_NESTED_WRONG_WITNESS_SCRIPT.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.NESTED_CHANGE_NO_REDEEM.psbt b/tests/data/psbt_test_suite/XTRAS.NESTED_CHANGE_NO_REDEEM.psbt new file mode 100644 index 0000000000..586982ae54 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.NESTED_CHANGE_NO_REDEEM.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.NESTED_CHANGE_NO_REDEEM_V2.psbt b/tests/data/psbt_test_suite/XTRAS.NESTED_CHANGE_NO_REDEEM_V2.psbt new file mode 100644 index 0000000000..dd00a5320d Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.NESTED_CHANGE_NO_REDEEM_V2.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.OP_RETURN_MULTI_PUSH.psbt b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_MULTI_PUSH.psbt new file mode 100644 index 0000000000..6a0484b20c Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_MULTI_PUSH.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.OP_RETURN_MULTI_PUSH_V2.psbt b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_MULTI_PUSH_V2.psbt new file mode 100644 index 0000000000..c8ae463750 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_MULTI_PUSH_V2.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.OP_RETURN_NON_PUSH.psbt b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_NON_PUSH.psbt new file mode 100644 index 0000000000..4b7c805d78 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_NON_PUSH.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.OP_RETURN_NON_PUSH_V2.psbt b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_NON_PUSH_V2.psbt new file mode 100644 index 0000000000..738a9dcc7c Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_NON_PUSH_V2.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.OP_RETURN_RUNESTONE.psbt b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_RUNESTONE.psbt new file mode 100644 index 0000000000..bda9cf5233 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_RUNESTONE.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.OP_RETURN_RUNESTONE_V2.psbt b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_RUNESTONE_V2.psbt new file mode 100644 index 0000000000..37b868e904 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_RUNESTONE_V2.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.OP_RETURN_SMALLINT.psbt b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_SMALLINT.psbt new file mode 100644 index 0000000000..409b394d85 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_SMALLINT.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.OP_RETURN_SMALLINT_V2.psbt b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_SMALLINT_V2.psbt new file mode 100644 index 0000000000..01cf50c0a0 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_SMALLINT_V2.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.OP_RETURN_TRUNCATED_PUSH.psbt b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_TRUNCATED_PUSH.psbt new file mode 100644 index 0000000000..882090fb36 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_TRUNCATED_PUSH.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.OP_RETURN_TRUNCATED_PUSH_V2.psbt b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_TRUNCATED_PUSH_V2.psbt new file mode 100644 index 0000000000..6a3b9db1b7 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_TRUNCATED_PUSH_V2.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.STRAY_REDEEM_SCRIPT.psbt b/tests/data/psbt_test_suite/XTRAS.STRAY_REDEEM_SCRIPT.psbt new file mode 100644 index 0000000000..7102aaccaf Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.STRAY_REDEEM_SCRIPT.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.STRAY_REDEEM_SCRIPT_V2.psbt b/tests/data/psbt_test_suite/XTRAS.STRAY_REDEEM_SCRIPT_V2.psbt new file mode 100644 index 0000000000..196d4a3d07 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.STRAY_REDEEM_SCRIPT_V2.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.WRONG_REDEEM_SCRIPT.psbt b/tests/data/psbt_test_suite/XTRAS.WRONG_REDEEM_SCRIPT.psbt new file mode 100644 index 0000000000..01ebd67ede Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.WRONG_REDEEM_SCRIPT.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.WRONG_REDEEM_SCRIPT_V2.psbt b/tests/data/psbt_test_suite/XTRAS.WRONG_REDEEM_SCRIPT_V2.psbt new file mode 100644 index 0000000000..823c182835 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.WRONG_REDEEM_SCRIPT_V2.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.ZERO_FEE.psbt b/tests/data/psbt_test_suite/XTRAS.ZERO_FEE.psbt new file mode 100644 index 0000000000..9bf5445d83 Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.ZERO_FEE.psbt differ diff --git a/tests/data/psbt_test_suite/XTRAS.ZERO_FEE_V2.psbt b/tests/data/psbt_test_suite/XTRAS.ZERO_FEE_V2.psbt new file mode 100644 index 0000000000..a23c6cdb3f Binary files /dev/null and b/tests/data/psbt_test_suite/XTRAS.ZERO_FEE_V2.psbt differ diff --git a/tests/psbt_suite_util.py b/tests/psbt_suite_util.py index a7a81ffeea..145738dafe 100644 --- a/tests/psbt_suite_util.py +++ b/tests/psbt_suite_util.py @@ -76,6 +76,9 @@ class RejectCode: EXTRANEOUS_WITNESS_SCRIPT = "EXTRANEOUS_WITNESS_SCRIPT" UTXO_MISMATCH = "UTXO_MISMATCH" SCRIPT_HASH_MISMATCH = "SCRIPT_HASH_MISMATCH" + MISSING_INPUT_SCRIPT = "MISSING_INPUT_SCRIPT" + EXTRANEOUS_REDEEM_SCRIPT = "EXTRANEOUS_REDEEM_SCRIPT" + MALFORMED_OP_RETURN = "MALFORMED_OP_RETURN" UNREACHABLE_CHANGE_PATH = "UNREACHABLE_CHANGE_PATH" NONZERO_OP_RETURN = "NONZERO_OP_RETURN" UNSUPPORTED_SIGHASH = "UNSUPPORTED_SIGHASH" @@ -1063,6 +1066,204 @@ def path(self) -> str: Expect.REJECT_FRAMING, reject_code=RejectCode.WRONG_VERSION_FIELD, ), + + # ------------------------------------------- follow-up of 2026-10-31 + # Upstream #995/#1041/#1042/#1046/#1047 merge, plus nested segwit multisig input + # scripts. Generated by psbt_faker; see PROVENANCE.md. + Vector( + "XTRAS.OP_RETURN_RUNESTONE", "display", + "Negative control: a Runes runestone, OP_RETURN OP_13 . OP_13 is " + "push-only per Bitcoin Core's IsPushOnly, so the output is standard and must " + "be shown, OP_13 byte included.", + Expect.PARSES, + input_amount=100_000_000, output_amount=99_990_000, num_outputs=3, owned_outputs=1, + ), + Vector( + "XTRAS.OP_RETURN_RUNESTONE_V2", "display", + "BIP-370 twin of XTRAS.OP_RETURN_RUNESTONE.", + Expect.PARSES, + input_amount=100_000_000, output_amount=99_990_000, num_outputs=3, owned_outputs=1, + ), + Vector( + "XTRAS.OP_RETURN_SMALLINT", "display", + "Negative control: OP_RETURN followed by OP_0, OP_1NEGATE, OP_1 and OP_16, " + "pushes that carry no data bytes. Shown as their opcode bytes.", + Expect.PARSES, + input_amount=100_000_000, output_amount=99_990_000, num_outputs=3, owned_outputs=1, + ), + Vector( + "XTRAS.OP_RETURN_SMALLINT_V2", "display", + "BIP-370 twin of XTRAS.OP_RETURN_SMALLINT.", + Expect.PARSES, + input_amount=100_000_000, output_amount=99_990_000, num_outputs=3, owned_outputs=1, + ), + Vector( + "XTRAS.OP_RETURN_MULTI_PUSH", "display", + "Negative control: a direct push, an OP_PUSHDATA2 and an OP_PUSHDATA1 in one " + "OP_RETURN. Their data is shown concatenated.", + Expect.PARSES, + input_amount=100_000_000, output_amount=99_990_000, num_outputs=3, owned_outputs=1, + ), + Vector( + "XTRAS.OP_RETURN_MULTI_PUSH_V2", "display", + "BIP-370 twin of XTRAS.OP_RETURN_MULTI_PUSH.", + Expect.PARSES, + input_amount=100_000_000, output_amount=99_990_000, num_outputs=3, owned_outputs=1, + ), + Vector( + "XTRAS.OP_RETURN_TRUNCATED_PUSH", "display", + "An OP_RETURN whose OP_PUSHDATA2 declares 255 bytes but carries 3. Any " + "display of it would show data the output does not carry.", + Expect.REJECT_PARSER, + input_amount=100_000_000, output_amount=99_990_000, num_outputs=3, reject_code=RejectCode.MALFORMED_OP_RETURN, + ), + Vector( + "XTRAS.OP_RETURN_TRUNCATED_PUSH_V2", "display", + "BIP-370 twin of XTRAS.OP_RETURN_TRUNCATED_PUSH.", + Expect.REJECT_PARSER, + input_amount=100_000_000, output_amount=99_990_000, num_outputs=3, reject_code=RejectCode.MALFORMED_OP_RETURN, + ), + Vector( + "XTRAS.OP_RETURN_NON_PUSH", "display", + "An OP_RETURN whose data push is followed by OP_CHECKSIG: not push-only, so " + "nonstandard and not readable as data.", + Expect.REJECT_PARSER, + input_amount=100_000_000, output_amount=99_990_000, num_outputs=3, reject_code=RejectCode.MALFORMED_OP_RETURN, + ), + Vector( + "XTRAS.OP_RETURN_NON_PUSH_V2", "display", + "BIP-370 twin of XTRAS.OP_RETURN_NON_PUSH.", + Expect.REJECT_PARSER, + input_amount=100_000_000, output_amount=99_990_000, num_outputs=3, reject_code=RejectCode.MALFORMED_OP_RETURN, + ), + Vector( + "XTRAS.STRAY_REDEEM_SCRIPT", "extras", + "A native segwit input carrying a redeem_script its scriptPubKey does not " + "commit to. It could only distort how the spending wallet is read.", + Expect.REJECT_PARSER, + input_amount=100_000_000, output_amount=99_990_000, num_outputs=2, reject_code=RejectCode.EXTRANEOUS_REDEEM_SCRIPT, + ), + Vector( + "XTRAS.STRAY_REDEEM_SCRIPT_V2", "extras", + "BIP-370 twin of XTRAS.STRAY_REDEEM_SCRIPT.", + Expect.REJECT_PARSER, + input_amount=100_000_000, output_amount=99_990_000, num_outputs=2, reject_code=RejectCode.EXTRANEOUS_REDEEM_SCRIPT, + ), + Vector( + "XTRAS.MISSING_REDEEM_SCRIPT", "extras", + "A nested segwit input with its redeem_script left out. Malformed rather than " + "deceptive.", + Expect.REJECT_PARSER, + input_amount=100_000_000, output_amount=99_990_000, num_outputs=2, reject_code=RejectCode.MISSING_INPUT_SCRIPT, + ), + Vector( + "XTRAS.MISSING_REDEEM_SCRIPT_V2", "extras", + "BIP-370 twin of XTRAS.MISSING_REDEEM_SCRIPT.", + Expect.REJECT_PARSER, + input_amount=100_000_000, output_amount=99_990_000, num_outputs=2, reject_code=RejectCode.MISSING_INPUT_SCRIPT, + ), + Vector( + "XTRAS.WRONG_REDEEM_SCRIPT", "extras", + "A nested segwit input whose redeem_script wraps a stranger's key, not the " + "one its scriptPubKey commits to.", + Expect.REJECT_PARSER, + input_amount=100_000_000, output_amount=99_990_000, num_outputs=2, reject_code=RejectCode.SCRIPT_HASH_MISMATCH, + ), + Vector( + "XTRAS.WRONG_REDEEM_SCRIPT_V2", "extras", + "BIP-370 twin of XTRAS.WRONG_REDEEM_SCRIPT.", + Expect.REJECT_PARSER, + input_amount=100_000_000, output_amount=99_990_000, num_outputs=2, reject_code=RejectCode.SCRIPT_HASH_MISMATCH, + ), + Vector( + "XTRAS.MISSING_WITNESS_SCRIPT", "multisig", + "A p2wsh multisig input with its witness_script left out. Malformed rather " + "than deceptive.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, reject_code=RejectCode.MISSING_INPUT_SCRIPT, + ), + Vector( + "XTRAS.FOREIGN_INPUT_BAD_SCRIPT", "extras", + "A collaborative spend: our nested segwit input plus another party's, whose " + "redeem_script is not the one its scriptPubKey commits to. Inputs that claim " + "none of our keys are checked all the same.", + Expect.REJECT_PARSER, + num_outputs=2, reject_code=RejectCode.SCRIPT_HASH_MISMATCH, + ), + Vector( + "XTRAS.MS_NESTED_HONEST", "multisig", + "Negative control: an honest 2-of-3 p2sh-p2wsh spend at m/48h/0h/0h/1h with " + "both script layers supplied, and change back to the same wallet.", + Expect.PARSES, + input_amount=200_000, output_amount=199_000, num_outputs=2, owned_outputs=1, + ), + Vector( + "XTRAS.MS_NESTED_WRONG_WITNESS_SCRIPT", "multisig", + "A p2sh-p2wsh input whose redeem_script still hashes to the scriptPubKey but " + "whose witness_script is a 1-of-3 of the same keys: only the inner layer is " + "wrong.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.SCRIPT_HASH_MISMATCH, + ), + Vector( + "XTRAS.MS_NESTED_WRONG_REDEEM_SCRIPT", "multisig", + "A p2sh-p2wsh input whose redeem_script and witness_script were swapped, " + "consistently, for a 1-of-3: they agree with each other, but not with the " + "scriptPubKey.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.SCRIPT_HASH_MISMATCH, + ), + Vector( + "XTRAS.MS_NESTED_MISSING_WITNESS_SCRIPT", "multisig", + "A p2sh-p2wsh input with its redeem_script but no witness_script. Malformed " + "rather than deceptive.", + Expect.REJECT_PARSER, + input_amount=200_000, output_amount=199_000, num_outputs=2, + reject_code=RejectCode.MISSING_INPUT_SCRIPT, + ), + Vector( + "XTRAS.NESTED_CHANGE_NO_REDEEM", "binding", + "Negative control: genuine nested segwit change with its (BIP-174 optional) " + "redeem_script omitted. It reads as plain p2sh, but rebuilding it from the " + "seed proves it is change.", + Expect.PARSES, + input_amount=100_000_000, output_amount=99_990_000, num_outputs=2, owned_outputs=1, + ), + Vector( + "XTRAS.NESTED_CHANGE_NO_REDEEM_V2", "binding", + "BIP-370 twin of XTRAS.NESTED_CHANGE_NO_REDEEM.", + Expect.PARSES, + input_amount=100_000_000, output_amount=99_990_000, num_outputs=2, owned_outputs=1, + ), + Vector( + "TX-21.nested_bare_p2sh_claims_us_pays_other", "ownership", + "A redeem-less p2sh output that keeps this seed's derivation claim but pays a " + "stranger's nested segwit key. Without the redeem_script nothing short of " + "rebuilding it exposes the lie.", + Expect.REJECT_PARSER, + input_amount=100_000_000, output_amount=99_990_000, num_outputs=2, reject_code=RejectCode.FORGED_OUTPUT_OWNERSHIP, + ), + Vector( + "TX-21.nested_bare_p2sh_claims_us_pays_other_V2", "ownership", + "BIP-370 twin of TX-21.nested_bare_p2sh_claims_us_pays_other.", + Expect.REJECT_PARSER, + input_amount=100_000_000, output_amount=99_990_000, num_outputs=2, reject_code=RejectCode.FORGED_OUTPUT_OWNERSHIP, + ), + Vector( + "XTRAS.ZERO_FEE", "extras", + "Negative control: a zero fee. Pointless, but not malformed, so it is not " + "refused.", + Expect.PARSES, + input_amount=100_000_000, output_amount=100_000_000, num_outputs=2, owned_outputs=1, + ), + Vector( + "XTRAS.ZERO_FEE_V2", "extras", + "BIP-370 twin of XTRAS.ZERO_FEE.", + Expect.PARSES, + input_amount=100_000_000, output_amount=100_000_000, num_outputs=2, owned_outputs=1, + ), ] VECTORS_BY_NAME = {v.name: v for v in VECTORS} diff --git a/tests/psbt_testing_util.py b/tests/psbt_testing_util.py index 3fc47c011c..25f4ec9e83 100644 --- a/tests/psbt_testing_util.py +++ b/tests/psbt_testing_util.py @@ -6,7 +6,9 @@ from embit.hashes import tagged_hash from embit.networks import NETWORKS from embit.psbt import PSBT, DerivationPath, InputScope, OutputScope +from embit.script import Script +from seedsigner.models.psbt_parser import OPCODES from seedsigner.models.seed import Seed @@ -277,3 +279,59 @@ def claim_seed_owns_key(scope: InputScope | OutputScope, claimed_derivation_path scope.taproot_bip32_derivations[public_key] = (leaf_hashes or [], derivation_path) else: scope.bip32_derivations[public_key] = derivation_path + + +def op_return_script(payload: bytes) -> Script: + """ + Build an OP_RETURN scriptPubKey carrying `payload`, using the minimal push encoding + that Bitcoin Core emits: a direct push for 75 bytes or fewer, OP_PUSHDATA1 up to 255, + OP_PUSHDATA2 up to 65535, and OP_PUSHDATA4 above that. + """ + if len(payload) <= OPCODES.OP_PUSHDATA_MAX_DIRECT: + push = bytes([len(payload)]) + elif len(payload) <= 0xff: + push = bytes([OPCODES.OP_PUSHDATA1, len(payload)]) + elif len(payload) <= 0xffff: + push = bytes([OPCODES.OP_PUSHDATA2]) + len(payload).to_bytes(2, "little") + else: + push = bytes([OPCODES.OP_PUSHDATA4]) + len(payload).to_bytes(4, "little") + + return Script(bytes([OPCODES.OP_RETURN]) + push + payload) + + +def create_op_return_output(payload: bytes, value: int = 0, script_pubkey: Script = None) -> OutputScope: + """ + Create an OP_RETURN OutputScope that can be appended to a PSBT's `outputs`. + + Pass `script_pubkey` to supply a hand-built script (a bare OP_RETURN, several pushes, + a deliberately malformed one); otherwise `payload` is wrapped in a minimal push. + + Note that the scriptPubKey and value have to be set on the OutputScope. `PSBT.tx` + rebuilds the whole transaction from the scopes on every access and `OutputScope.vout` + rebuilds its TransactionOutput, so assigning through `psbt.tx.vout[i]` is silently + discarded and would leave a test asserting against the fixture it meant to replace. + """ + output = OutputScope() + output.script_pubkey = script_pubkey if script_pubkey is not None else op_return_script(payload) + output.value = value + return output + + +def create_op_return_psbt(op_return_outputs: list) -> PSBT: + """ + A single-sig native segwit psbt with one change output and the given OP_RETURN + OutputScopes (see `create_op_return_output`) appended after it, in order. + + The change output gets whatever is left of the input after the OP_RETURN values and a + 5,000 sat fee. + """ + psbt = PSBT.parse(a2b_base64(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_1_INPUT)) + input_amount = sum([inp.utxo.value for inp in psbt.inputs]) + op_return_amount = sum([output.value for output in op_return_outputs]) + change_amount = input_amount - op_return_amount - 5_000 + + psbt.outputs.clear() + psbt.outputs.append(create_output(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_CHANGE, change_amount)) + for output in op_return_outputs: + psbt.outputs.append(output) + return psbt diff --git a/tests/screenshot_generator/generator.py b/tests/screenshot_generator/generator.py index b0c19d45de..3da43710e3 100644 --- a/tests/screenshot_generator/generator.py +++ b/tests/screenshot_generator/generator.py @@ -12,7 +12,6 @@ from PIL import ImageFont from unittest.mock import Mock, patch, MagicMock -from embit import compact from embit.psbt import PSBT, OutputScope from embit.script import Script @@ -93,11 +92,13 @@ def test_generate_all(locale, target_locale): seed_12b = Seed(mnemonic=mnemonic_12b, wordlist_language_code=SettingsConstants.WORDLIST_LANGUAGE__ENGLISH) def add_op_return_to_psbt(psbt: PSBT, raw_payload_data: bytes): - data = (compact.to_bytes(OPCODES.OP_RETURN) + - compact.to_bytes(OPCODES.OP_PUSHDATA1) + - compact.to_bytes(len(raw_payload_data)) + - raw_payload_data) - script = Script(data) + # Push the payload the way Bitcoin Core does: directly for 75 bytes or fewer, via + # OP_PUSHDATA1 above that. + if len(raw_payload_data) <= OPCODES.OP_PUSHDATA_MAX_DIRECT: + push = bytes([len(raw_payload_data)]) + else: + push = bytes([OPCODES.OP_PUSHDATA1, len(raw_payload_data)]) + script = Script(bytes([OPCODES.OP_RETURN]) + push + raw_payload_data) output = OutputScope() output.script_pubkey = script output.value = 0 @@ -744,13 +745,20 @@ def mock_provision_warnings(): ScreenshotConfig(psbt_views.PSBTOverviewView, screenshot_name="PSBTOverviewView_op_return", mock_context_manager=mock_psbt_with_op_return_loaded), ScreenshotConfig(psbt_views.PSBTOpReturnView, screenshot_name="PSBTOpReturnView_text", mock_context_manager=mock_psbt_with_op_return_loaded), ScreenshotConfig(psbt_views.PSBTOpReturnView, screenshot_name="PSBTOpReturnView_raw_hex_data", mock_context_manager=mock_psbt_with_op_return_raw_bytes_loaded), + ScreenshotConfig(psbt_views.PSBTMalformedOpReturnView), + ScreenshotConfig(psbt_views.PSBTMissingInputScriptView), + ScreenshotConfig(psbt_views.PSBTInputScriptMismatchView), + ScreenshotConfig(psbt_views.PSBTExtraneousInputScriptView), ScreenshotConfig(psbt_views.PSBTAddressVerificationFailedView, dict(is_change=True, is_multisig=False), screenshot_name="PSBTAddressVerificationFailedView_singlesig_change"), ScreenshotConfig(psbt_views.PSBTAddressVerificationFailedView, dict(is_change=False, is_multisig=False), screenshot_name="PSBTAddressVerificationFailedView_singlesig_selftransfer"), ScreenshotConfig(psbt_views.PSBTAddressVerificationFailedView, dict(is_change=True, is_multisig=True), screenshot_name="PSBTAddressVerificationFailedView_multisig_change"), ScreenshotConfig(psbt_views.PSBTAddressVerificationFailedView, dict(is_change=False, is_multisig=True), screenshot_name="PSBTAddressVerificationFailedView_multisig_selftransfer"), ScreenshotConfig(psbt_views.PSBTOutputOwnershipClaimFailedView), ScreenshotConfig(psbt_views.PSBTInputOwnershipClaimFailedView), + ScreenshotConfig(psbt_views.PSBTNegativeFeeView), ScreenshotConfig(psbt_views.PSBTSeedCannotSignView), + ScreenshotConfig(psbt_views.PSBTInputAmountVerificationFailedView), + ScreenshotConfig(psbt_views.PSBTMissingInputUtxoView), ScreenshotConfig(psbt_views.PSBTFinalizeView, mock_context_manager=mock_multisig_psbt_loaded), #ScreenshotConfig(PSBTSignedQRDisplayViewScreenshotConfig), ScreenshotConfig(psbt_views.PSBTSigningErrorView, mock_context_manager=mock_multisig_psbt_loaded), diff --git a/tests/test_decodepsbtqr.py b/tests/test_decodepsbtqr.py index 862328c024..163a84e807 100644 --- a/tests/test_decodepsbtqr.py +++ b/tests/test_decodepsbtqr.py @@ -144,7 +144,7 @@ def test_base64_2_input_p2wsh(): assert tx.inputs[1].witness_utxo.value == 10000000 # input amount 2 in psbt - assert pp.input_amount == 20000000 + assert pp.verified_input_amount == 20000000 assert (pp.spend_amount + pp.change_amount + pp.fee_amount) == 20000000 @@ -169,7 +169,7 @@ def test_base64_1_input_p2sh_p2wsh(): assert tx.inputs[0].witness_utxo.value == 100000000 # input amount 1 in psbt - assert pp.input_amount == 100000000 + assert pp.verified_input_amount == 100000000 assert (pp.spend_amount + pp.change_amount + pp.fee_amount) == 100000000 @@ -201,7 +201,7 @@ def test_specter_multisig_animated_qr(): mnemonic = "zone zone zone zone zone abandon ability able abandon ability able abstract".split() pp = PSBTParser(p=tx, seed=Seed(mnemonic), network=SettingsConstants.TESTNET) - assert pp.input_amount == 1052818 + assert pp.verified_input_amount == 1052818 assert pp.change_amount == 0 @@ -239,7 +239,7 @@ def test_specter_multisig_animated_qr(): mnemonic2 = "able bacon cable able bacon cable abandon abandon abandon abandon abandon access".split() pp2 = PSBTParser(p=tx2, seed=Seed(mnemonic2), network=SettingsConstants.TESTNET) - assert pp2.input_amount == 1052818 + assert pp2.verified_input_amount == 1052818 assert pp2.change_amount == 0 diff --git a/tests/test_flows_psbt.py b/tests/test_flows_psbt.py index 1393d3fe51..2223d82b94 100644 --- a/tests/test_flows_psbt.py +++ b/tests/test_flows_psbt.py @@ -5,12 +5,13 @@ from embit.psbt import PSBT, DerivationPath from base import BaseTest, FlowTest, FlowStep -from psbt_testing_util import (PSBTTestData, claim_seed_owns_key, create_output, - foreign_public_key, root_for_seed) +from psbt_testing_util import (PSBTTestData, claim_seed_owns_key, create_op_return_output, + create_output, foreign_public_key, root_for_seed) from seedsigner.controller import Controller from seedsigner.views.view import MainMenuView from seedsigner.views import scan_views, seed_views, psbt_views +from seedsigner.models.psbt_parser import OPCODES from seedsigner.models.seed import Seed from seedsigner.models.settings import SettingsConstants @@ -79,6 +80,37 @@ def load_seed_into_decoder(view: scan_views.ScanView): assert self.controller.psbt_seed is self.controller.storage.seeds[0] + def test_tampered_input_amounts_routes_to_input_verification_failed(self): + """ + A psbt whose non_witness_utxo doesn't verify can declare any input amounts it + likes, which means it can display any fee it likes. It should be discarded + outright with no option to proceed. + """ + def load_tampered_psbt_into_decoder(view: scan_views.ScanView): + # Editing the non_witness_utxo changes the txid it hashes to, so it no longer + # matches the txid the input claims to spend. + psbt = PSBT.parse(a2b_base64(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_2_INPUTS)) + psbt.inputs[0].non_witness_utxo.vout[0].value += 100_000 + view.decoder.add_data(str(psbt)) + + def load_seed_into_decoder(view: scan_views.ScanView): + view.decoder.add_data("080115060387063104071857067618681125136207731354") + + self.run_sequence([ + FlowStep(MainMenuView, button_data_selection=MainMenuView.SCAN), + FlowStep(scan_views.ScanView, before_run=load_tampered_psbt_into_decoder), + FlowStep(psbt_views.PSBTSelectSeedView, button_data_selection=psbt_views.PSBTSelectSeedView.SCAN_SEED), + FlowStep(scan_views.ScanSeedQRView, before_run=load_seed_into_decoder), + FlowStep(seed_views.SeedFinalizeView, button_data_selection=seed_views.SeedFinalizeView.FINALIZE), + FlowStep(seed_views.SeedOptionsView, is_redirect=True), + + # Parsing fails, so the overview never renders; it redirects straight to the warning + FlowStep(psbt_views.PSBTOverviewView, is_redirect=True), + FlowStep(psbt_views.PSBTInputAmountVerificationFailedView), + FlowStep(MainMenuView), + ]) + + def test_scan_psbt_first_then_load_electrum_seed(self): """ Should be able to load an Electrum mnemonic after first loading in a psbt. @@ -511,9 +543,10 @@ def test_descriptor_mismatch_clears_descriptor_and_prompts(self): class TestPSBTOwnershipClaimRouting(FlowTest): """ - A psbt carrying an ownership claim that does not hold up is rejected while it is being - parsed, before the user is shown anything about the transaction. These cover the - routing that turns that rejection into a warning screen instead of a crash. + A psbt whose own description of itself does not hold up, or whose arithmetic is + impossible, is refused during parsing, before the user is shown anything about the + transaction. These cover what the user meets when that happens: a warning screen that + ends the flow, not a crash. """ def _load_psbt_for_signing(self, psbt: PSBT, seed: Seed = None): @@ -663,6 +696,120 @@ def test_mixed_derivation_path_types_terminate_signing_flow(self): ]) + def test_missing_input_utxo_terminates_signing_flow(self): + """ + An input that carries no utxo data gives us no amount to verify, so parsing + refuses the psbt. + + It ends the flow at its own warning before any transaction detail is rendered. + """ + psbt = PSBT.parse(a2b_base64(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_2_INPUTS)) + + # Input 0 is left intact, so the seed can still sign and the parse gets as far as + # the amount check. + psbt.inputs[1].witness_utxo = None + psbt.inputs[1].non_witness_utxo = None + + self._load_psbt_for_signing(psbt, seed=PSBTTestData.two_input_seed) + + self.run_sequence([ + FlowStep(psbt_views.PSBTSelectSeedView, screen_return_value=0), + FlowStep(psbt_views.PSBTOverviewView, is_redirect=True), + FlowStep(psbt_views.PSBTMissingInputUtxoView, button_data_selection=psbt_views.PSBTMissingInputUtxoView.DISCARD), + FlowStep(MainMenuView), + ]) + + + def test_malformed_op_return_terminates_signing_flow(self): + """ + An OP_RETURN push that claims more bytes than its script carries is malformed + rather than hostile, but it is still refused during the parse and routes to a + warning that aborts the signing flow. + """ + psbt = self._psbt_with_change() + truncated_push = script.Script(bytes([OPCODES.OP_RETURN, 10]) + b"abc") + psbt.outputs.append(create_op_return_output(b"", script_pubkey=truncated_push)) + self._load_psbt_for_signing(psbt) + + self.run_sequence([ + FlowStep(psbt_views.PSBTSelectSeedView, screen_return_value=0), + FlowStep(psbt_views.PSBTOverviewView, is_redirect=True), + FlowStep(psbt_views.PSBTMalformedOpReturnView, button_data_selection=psbt_views.PSBTMalformedOpReturnView.DISCARD), + FlowStep(MainMenuView), + ]) + + + def test_missing_input_script_terminates_signing_flow(self): + """ + The psbt leaves out the witness script that a p2wsh input commits to. + + The flow should stop at PSBTMissingInputScriptView, before any transaction detail + is rendered. + """ + psbt = PSBT.parse(a2b_base64(PSBTTestData.MULTISIG_NATIVE_SEGWIT_1_INPUT)) + psbt.outputs.append(create_output(PSBTTestData.MULTISIG_NATIVE_SEGWIT_CHANGE, 10_000)) + psbt.inputs[0].witness_script = None + + self._load_psbt_for_signing(psbt) + + self.run_sequence([ + FlowStep(psbt_views.PSBTSelectSeedView, screen_return_value=0), + FlowStep(psbt_views.PSBTOverviewView, is_redirect=True), + FlowStep(psbt_views.PSBTMissingInputScriptView, button_data_selection=psbt_views.PSBTMissingInputScriptView.DISCARD), + FlowStep(MainMenuView), + ]) + + + def test_input_script_mismatch_terminates_signing_flow(self): + """ + The psbt replaces a p2wsh input's witness script with a stranger's. The coin + really is the user's, but the supplied script hashes to something other than what + the input's scriptPubKey commits to. + + The flow should stop at PSBTInputScriptMismatchView, before any transaction detail + is rendered. + """ + psbt = PSBT.parse(a2b_base64(PSBTTestData.MULTISIG_NATIVE_SEGWIT_1_INPUT)) + psbt.outputs.append(create_output(PSBTTestData.MULTISIG_NATIVE_SEGWIT_CHANGE, 10_000)) + foreign_multisig_keys = [foreign_public_key(f"m/48h/1h/0h/2h/0/{i}") for i in range(3)] + psbt.inputs[0].witness_script = script.multisig(2, foreign_multisig_keys) + + self._load_psbt_for_signing(psbt) + + self.run_sequence([ + FlowStep(psbt_views.PSBTSelectSeedView, screen_return_value=0), + FlowStep(psbt_views.PSBTOverviewView, is_redirect=True), + FlowStep(psbt_views.PSBTInputScriptMismatchView, button_data_selection=psbt_views.PSBTInputScriptMismatchView.DISCARD), + FlowStep(MainMenuView), + ]) + + + def test_extraneous_input_script_terminates_signing_flow(self): + """ + The psbt adds a witness script to a legacy multisig input, in addition to the + input's own redeem script. The coin really is the user's and the redeem script + still hashes to the scriptPubKey, but a legacy p2sh multisig input should never + have a witness script. + + The flow should stop at PSBTExtraneousInputScriptView, before any transaction + detail is rendered. + """ + psbt = PSBT.parse(a2b_base64(PSBTTestData.MULTISIG_LEGACY_P2SH_1_INPUT)) + psbt.outputs.append(create_output(PSBTTestData.MULTISIG_LEGACY_P2SH_CHANGE, 10_000)) + + # The extraneous script's content is irrelevant, so an arbitrary script will do + psbt.inputs[0].witness_script = script.Script(b"\x51") # OP_TRUE + + self._load_psbt_for_signing(psbt) + + self.run_sequence([ + FlowStep(psbt_views.PSBTSelectSeedView, screen_return_value=0), + FlowStep(psbt_views.PSBTOverviewView, is_redirect=True), + FlowStep(psbt_views.PSBTExtraneousInputScriptView, button_data_selection=psbt_views.PSBTExtraneousInputScriptView.DISCARD), + FlowStep(MainMenuView), + ]) + + def test_wrong_seed_routes_back_to_seed_selection_flow(self): """ The wrong seed for a psbt redirects before any transaction detail is rendered and @@ -684,3 +831,21 @@ def test_wrong_seed_routes_back_to_seed_selection_flow(self): # The psbt itself is kept: the user is choosing a different seed for it, not # starting over assert self.controller.psbt is not None + + + def test_negative_fee_terminates_signing_flow(self): + """ + A psbt whose outputs spend more than its inputs bring in is malformed rather than + hostile, but it is still rejected during the parse and routes to a warning that + aborts the signing flow. + """ + psbt = self._psbt_with_change() + psbt.outputs[0].value = sum(inp.utxo.value for inp in psbt.inputs) + 1 + self._load_psbt_for_signing(psbt) + + self.run_sequence([ + FlowStep(psbt_views.PSBTSelectSeedView, screen_return_value=0), + FlowStep(psbt_views.PSBTOverviewView, is_redirect=True), + FlowStep(psbt_views.PSBTNegativeFeeView, button_data_selection=psbt_views.PSBTNegativeFeeView.DISCARD), + FlowStep(MainMenuView), + ]) diff --git a/tests/test_psbt_parser.py b/tests/test_psbt_parser.py index 98d37b781b..c2057a4c37 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -10,8 +10,9 @@ from embit.networks import NETWORKS from embit.psbt import PSBT, DerivationPath, OutputScope from embit.descriptor import Descriptor +from embit.script import Script -from seedsigner.models.psbt_parser import InvalidPSBTError, PSBTParser, RejectCode +from seedsigner.models.psbt_parser import OPCODES, InvalidPSBTError, PSBTParser, RejectCode def raises_reject(code): @@ -37,8 +38,9 @@ def __exit__(self, *exc): from seedsigner.models.settings_definition import SettingsConstants from psbt_testing_util import (NUMS_INTERNAL_KEY, PSBTTestData, claim_seed_owns_key, - create_output, foreign_output, foreign_public_key, input_at_new_outpoint, - p2tr_with_script_tree, root_for_seed, tapleaf_hash) + create_op_return_output, create_op_return_psbt, create_output, foreign_output, + foreign_public_key, input_at_new_outpoint, op_return_script, p2tr_with_script_tree, + root_for_seed, tapleaf_hash) @@ -72,13 +74,13 @@ def run_basic_test(self, psbt_base64: str, change_data: str, self_transfer_data: assert len(psbt.outputs) == 2 psbt_parser = PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) assert psbt_parser.num_inputs == len(psbt.inputs) - assert psbt_parser.input_amount == input_amount + assert psbt_parser.verified_input_amount == input_amount assert psbt_parser.num_destinations == 1 assert psbt_parser.num_change_outputs == 1 assert psbt_parser.spend_amount == recipient_amount assert psbt_parser.change_amount == input_amount - recipient_amount - fee_amount assert psbt_parser.fee_amount == fee_amount - assert psbt_parser.input_amount == psbt_parser.spend_amount + psbt_parser.change_amount + psbt_parser.fee_amount + assert psbt_parser.verified_input_amount == psbt_parser.spend_amount + psbt_parser.change_amount + psbt_parser.fee_amount # No self-transfer here, so all change is true change assert psbt_parser.get_total_output_value() == psbt_parser.spend_amount @@ -91,13 +93,13 @@ def run_basic_test(self, psbt_base64: str, change_data: str, self_transfer_data: assert len(psbt.outputs) == 1 psbt_parser = PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) assert psbt_parser.num_inputs == len(psbt.inputs) - assert psbt_parser.input_amount == input_amount + assert psbt_parser.verified_input_amount == input_amount assert psbt_parser.num_destinations == 0 # No external recipients == no destinations assert psbt_parser.num_change_outputs == 1 # PSBTParser considers self-transfers == change assert psbt_parser.spend_amount == 0 # No external recipients == nothing spent (ignores fee) assert psbt_parser.change_amount == input_amount - fee_amount # PSBTParser considers self-transfers == change assert psbt_parser.fee_amount == fee_amount - assert psbt_parser.input_amount == psbt_parser.spend_amount + psbt_parser.change_amount + psbt_parser.fee_amount + assert psbt_parser.verified_input_amount == psbt_parser.spend_amount + psbt_parser.change_amount + psbt_parser.fee_amount # Only self-transfer, and no "true" change, so `change_amount` is included in total output # Both calls should return the same value @@ -115,13 +117,13 @@ def run_basic_test(self, psbt_base64: str, change_data: str, self_transfer_data: assert len(psbt.outputs) == 1 psbt_parser = PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) assert psbt_parser.num_inputs == len(psbt.inputs) - assert psbt_parser.input_amount == input_amount + assert psbt_parser.verified_input_amount == input_amount assert psbt_parser.num_destinations == 1 assert psbt_parser.num_change_outputs == 0 assert psbt_parser.spend_amount == recipient_amount assert psbt_parser.change_amount == 0 assert psbt_parser.fee_amount == fee_amount - assert psbt_parser.input_amount == psbt_parser.spend_amount + psbt_parser.change_amount + psbt_parser.fee_amount + assert psbt_parser.verified_input_amount == psbt_parser.spend_amount + psbt_parser.change_amount + psbt_parser.fee_amount # No self-transfer here, so all change is true change assert psbt_parser.get_total_output_value() == psbt_parser.spend_amount @@ -141,13 +143,13 @@ def run_basic_test(self, psbt_base64: str, change_data: str, self_transfer_data: assert len(psbt.outputs) == len(PSBTTestData.ALL_EXTERNAL_OUTPUTS) + 1 psbt_parser = PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) assert psbt_parser.num_inputs == len(psbt.inputs) - assert psbt_parser.input_amount == input_amount + assert psbt_parser.verified_input_amount == input_amount assert psbt_parser.num_destinations == len(PSBTTestData.ALL_EXTERNAL_OUTPUTS) assert psbt_parser.num_change_outputs == 1 assert psbt_parser.spend_amount == input_amount - change_amount - fee_amount assert psbt_parser.change_amount == change_amount assert psbt_parser.fee_amount == fee_amount - assert psbt_parser.input_amount == psbt_parser.spend_amount + psbt_parser.change_amount + psbt_parser.fee_amount + assert psbt_parser.verified_input_amount == psbt_parser.spend_amount + psbt_parser.change_amount + psbt_parser.fee_amount # No self-transfer here, so all change is true change assert psbt_parser.get_total_output_value() == psbt_parser.spend_amount @@ -299,6 +301,13 @@ def test_missing_fingerprint_handling(self): # is legal and is what this fixture means. taproot_input.non_witness_utxo = None + # Re-keying the input invalidates the non_witness_utxo, which still pays to the + # original script. Editing it to match is not an option either: that changes the + # txid it hashes to, so it would no longer be the tx this input claims to spend. + # Drop it. Taproot is segwit, so a witness-only input is what a coordinator would + # normally send anyway. + taproot_input.non_witness_utxo = None + # The zeroed-fingerprint fallback check must recognize this input as the seed's, # even though embit's internal parity byte for the pubkey is wrong. Taproot # pubkeys must be compared by their x-only representation. @@ -520,6 +529,232 @@ def test_parse_sets_is_high_fee(self): +class TestPSBTInputAmountVerification: + """ + A compromised coordinator can declare whatever input amounts it likes. Unless we check + them against each input's non_witness_utxo, the fee we display is whatever the + coordinator wants it to be. + """ + seed = PSBTTestData.seed + + # Fixtures that ship a witness_utxo alongside their non_witness_utxo + WITNESS_UTXO_INPUTS = [ + PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_1_INPUT, + PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_1_INPUT, + PSBTTestData.SINGLE_SIG_TAPROOT_1_INPUT, + PSBTTestData.MULTISIG_NATIVE_SEGWIT_1_INPUT, + PSBTTestData.MULTISIG_NESTED_SEGWIT_1_INPUT, + ] + + # Legacy sighashes commit no input amount, so these must always be verifiable + LEGACY_INPUTS = [ + PSBTTestData.SINGLE_SIG_LEGACY_P2PKH_1_INPUT, + PSBTTestData.MULTISIG_LEGACY_P2SH_1_INPUT, + ] + + + def build_psbt(self, psbt_base64: str) -> PSBT: + """ Turn an input-only fixture into a complete psbt that spends to an external recipient """ + psbt: PSBT = PSBT.parse(a2b_base64(psbt_base64)) + input_amount = sum([inp.utxo.value for inp in psbt.inputs]) + psbt.outputs.clear() + psbt.outputs.append(create_output(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_RECEIVE, input_amount - 5_000)) + return psbt + + + @pytest.mark.parametrize("psbt_base64", PSBTTestData.ALL_INPUTS) + def test_untampered_psbts_verify(self, psbt_base64: str): + """ + There is one test psbt per script type. Each one includes the previous transaction + (non_witness_utxo) for every input. With nothing missing, there's no excuse for any + input not to verify: parsing should mark every input is_verified and total their amounts. + """ + psbt = self.build_psbt(psbt_base64) + assert all(inp.is_verified is False for inp in psbt.inputs) # not verified until we do it + + psbt_parser = PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) + + assert all(inp.is_verified for inp in psbt.inputs) + assert psbt_parser.verified_input_amount == sum([inp.utxo.value for inp in psbt.inputs]) + + + @pytest.mark.parametrize("psbt_base64", PSBTTestData.ALL_INPUTS) + def test_tampered_non_witness_utxo_raises(self, psbt_base64: str): + """ + Should raise PSBTInputAmountVerificationError if the input's txid doesn't match its + non_witness_utxo. Covers every supported script type. + """ + psbt = self.build_psbt(psbt_base64) + + # Editing the non_witness_utxo changes the txid it hashes to, so it no longer matches + # the txid the input claims to spend. + psbt.inputs[0].non_witness_utxo.vout[0].value += 100_000 + + with raises_reject(RejectCode.UTXO_MISMATCH): + PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) + + + @pytest.mark.parametrize("psbt_base64", WITNESS_UTXO_INPUTS) + def test_witness_utxo_value_disagreeing_with_non_witness_utxo_raises(self, psbt_base64: str): + """ + The non_witness_utxo still hashes correctly here, so embit's verify() is satisfied. + But embit's PSBT.utxo()/fee() prefer witness_utxo, so an inflated witness_utxo would + still drive the fee we display. Must be caught by the cross-check. + """ + psbt = self.build_psbt(psbt_base64) + psbt.inputs[0].witness_utxo.value += 100_000 + + # Confirm the premise: the non_witness_utxo is untouched and still verifies + assert psbt.inputs[0].verify() is True + + with raises_reject(RejectCode.UTXO_MISMATCH): + PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) + + + @pytest.mark.parametrize("psbt_base64", WITNESS_UTXO_INPUTS) + def test_witness_utxo_script_pubkey_disagreeing_with_non_witness_utxo_raises(self, psbt_base64: str): + """ + The input has both utxo fields. Its non_witness_utxo matches the input's txid, and its + witness_utxo has the same amount but a different scriptPubKey. The two contradict, so + the parse should raise PSBTInputAmountVerificationError. + """ + psbt = self.build_psbt(psbt_base64) + witness_utxo = psbt.inputs[0].witness_utxo + original_value = witness_utxo.value + + # Same value, different scriptPubKey + witness_utxo.script_pubkey = Script(b"\x00\x14" + b"\x11" * 20) + + # Confirm the premise: only the scriptPubKey moved, and the non_witness_utxo still verifies + prevout = psbt.inputs[0].non_witness_utxo.vout[psbt.inputs[0].vout] + assert witness_utxo.value == original_value + assert witness_utxo.script_pubkey.data != prevout.script_pubkey.data + assert psbt.inputs[0].verify() is True + + with raises_reject(RejectCode.UTXO_MISMATCH): + PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) + + + @pytest.mark.parametrize("psbt_base64", LEGACY_INPUTS) + def test_legacy_input_without_non_witness_utxo_raises(self, psbt_base64: str): + """ + BIP-174 reserves witness_utxo for segwit inputs, so for a legacy input, a + well-formed psbt would only provide its non_witness_utxo. In this test we create + an unusual psbt that presents a legacy input and only a witness_utxo. In this case + we can't verify the input's amount or the fee we would display. The parse should + raise PSBTInputAmountVerificationError. + """ + psbt = self.build_psbt(psbt_base64) + inp = psbt.inputs[0] + inp.witness_utxo = inp.non_witness_utxo.vout[inp.vout] + inp.witness_utxo.value += 100_000 + inp.non_witness_utxo = None + + # The fork refuses this as INVALID_WITNESS_UTXO (a witness_utxo describing an + # input whose sighash commits to no amount); upstream raises + # PSBTInputAmountVerificationError. + with raises_reject(RejectCode.INVALID_WITNESS_UTXO): + PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) + + + def test_unrecognized_script_type_without_non_witness_utxo_raises(self): + """ + Covers the None entry in UNCOMMITTED_AMOUNT_SCRIPT_TYPES. embit's script_type() returns + None for any scriptPubKey it doesn't recognize, and an unknown script type gives us no + basis to assume its sighash commits the input amount. So an unprovable amount on an + unrecognized input has to be refused rather than trusted. + """ + psbt = self.build_psbt(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_1_INPUT) + inp = psbt.inputs[0] + + # Bare multisig: a real scriptPubKey form that embit doesn't recognize, since it only + # knows the p2sh- and p2wsh-wrapped forms. + OP_1 = b"\x51" + OP_PUSHBYTES_33 = b"\x21" + OP_CHECKMULTISIG = b"\xae" + pubkey = list(inp.bip32_derivations.keys())[0].sec() + inp.witness_utxo = inp.non_witness_utxo.vout[inp.vout] + inp.witness_utxo.script_pubkey = Script(OP_1 + OP_PUSHBYTES_33 + pubkey + OP_1 + OP_CHECKMULTISIG) + inp.non_witness_utxo = None + + # Confirm the premise: this really is an unrecognized script type + assert inp.witness_utxo.script_pubkey.script_type() is None + + # The fork refuses this as INVALID_WITNESS_UTXO (a witness_utxo describing an + # input whose sighash commits to no amount); upstream raises + # PSBTInputAmountVerificationError. + with raises_reject(RejectCode.INVALID_WITNESS_UTXO): + PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) + + + @pytest.mark.parametrize("psbt_base64", WITNESS_UTXO_INPUTS) + def test_segwit_input_without_non_witness_utxo_is_allowed(self, psbt_base64: str): + """ + Coordinators routinely omit non_witness_utxo for segwit inputs. BIP143/BIP341 commit + the input amount to the sighash, so a lie there invalidates the signature rather than + burning funds. Rejecting these would break almost every normal signing. + """ + psbt = self.build_psbt(psbt_base64) + psbt.inputs[0].non_witness_utxo = None + + # Parses without raising an exception + psbt_parser = PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) + assert psbt_parser.verified_input_amount == psbt.inputs[0].witness_utxo.value + + + @pytest.mark.parametrize("psbt_base64", PSBTTestData.ALL_INPUTS) + def test_input_with_no_utxo_data_raises(self, psbt_base64: str): + """ + Nothing to verify against and nothing to sum; refuse rather than guess. + """ + psbt = self.build_psbt(psbt_base64) + psbt.inputs[0].witness_utxo = None + psbt.inputs[0].non_witness_utxo = None + + with raises_reject(RejectCode.MISSING_UTXO): + PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) + + + def test_outpoint_index_past_end_of_non_witness_utxo_raises(self): + """ + The input's vout points to an output index past the end of its non_witness_utxo's + output list. Basically, it's claiming to spend an output that doesn't exist. When + this happens, the parse should raise PSBTMissingInputUtxoError. + """ + psbt = self.build_psbt(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_1_INPUT) + inp = psbt.inputs[0] + + # Confirm the premise: the prev tx really is shorter than the index we then claim + assert inp.vout < len(inp.non_witness_utxo.vout) + inp.vout = len(inp.non_witness_utxo.vout) + + # The fork grades a previous tx that lacks the spent output as UTXO_MISMATCH; + # upstream raises PSBTMissingInputUtxoError. + with raises_reject(RejectCode.UTXO_MISMATCH): + PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) + + + def test_every_input_is_checked_not_just_the_first(self): + """ + A tampered input shouldn't be able to hide behind a legit one. Tampering the second + input of a 2-input psbt must raise, and the error must name the input that failed. + """ + psbt: PSBT = PSBT.parse(a2b_base64(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_2_INPUTS)) + assert len(psbt.inputs) == 2 + + # Untampered, both inputs verify and their amounts are summed + psbt_parser = PSBTParser(p=psbt, seed=PSBTTestData.two_input_seed, network=SettingsConstants.REGTEST) + assert psbt_parser.num_inputs == 2 + assert psbt_parser.verified_input_amount == 56_522_834 + 1_990_245_069 + + psbt.inputs[1].non_witness_utxo.vout[0].value += 100_000 + + with raises_reject(RejectCode.UTXO_MISMATCH): + PSBTParser(p=psbt, seed=PSBTTestData.two_input_seed, network=SettingsConstants.REGTEST) + + + + # TODO: Refactor all tests to be in the TestPSBTParser class(?) def test_p2tr_change_detection(): """ Should successfully detect change in a p2tr to p2tr psbt spend @@ -745,7 +980,7 @@ def assert_same_parse_result(self, parser_a: PSBTParser, parser_b: PSBTParser): psbt is compared too, not just the parser's own attributes. """ assert parser_a.policy == parser_b.policy - assert parser_a.input_amount == parser_b.input_amount + assert parser_a.verified_input_amount == parser_b.verified_input_amount assert parser_a.spend_amount == parser_b.spend_amount assert parser_a.change_amount == parser_b.change_amount assert parser_a.fee_amount == parser_b.fee_amount @@ -1027,10 +1262,10 @@ def build_psbt(case: tuple) -> PSBT: -class TestPSBTParserSeedOwnership: +class PSBTParserOwnershipTestBase: """ - The ownership scan: what the signing seed provably owns in a psbt, and the rejection - of any psbt whose ownership claims do not hold up. + Shared fixtures for tests of how PSBTParser verifies a psbt's claims about its inputs + and outputs. """ seed = PSBTTestData.seed @@ -1053,6 +1288,11 @@ def _psbt_with_change(self, input_base64: str = None, change_hex: str = None) -> return psbt + def _foreign_multisig_script(self) -> script.Script: + """A 2-of-3 built entirely from someone else's keys.""" + return script.multisig(2, [foreign_public_key(f"m/48h/1h/0h/2h/0/{i}") for i in range(3)]) + + def _parse(self, psbt: PSBT) -> PSBTParser: # TODO: Rename this helper. "parse" does not convey that a new PSBTParser instance # is being created and it creates confusion in tests that also call PSBT.parse() @@ -1060,6 +1300,13 @@ def _parse(self, psbt: PSBT) -> PSBTParser: return PSBTParser(psbt, self.seed, network=SettingsConstants.REGTEST) + + +class TestPSBTParserSeedOwnership(PSBTParserOwnershipTestBase): + """ + The ownership scan: what the signing seed provably owns in a psbt, and the rejection + of any psbt whose ownership claims do not hold up. + """ def test__seed_owns_pubkey__accepts_the_seeds_own_key(self): """ seed_owns_pubkey should confirm the simple base case that a pubkey directly @@ -1174,6 +1421,8 @@ def test__parse__verified_derivation_paths_empty_for_not_owned_input(self): # The other party's input: their utxo, carrying no derivation info foreign_input = input_at_new_outpoint(psbt.inputs[0], 0) foreign_input.bip32_derivations.clear() + + # Alter the input so it's owned by the other party foreign_input.witness_utxo.script_pubkey = script.p2wpkh(foreign_public_key()) # See the note in test_missing_fingerprint_handling: the copied non_witness_utxo # still describes our own script, which _validate_input reads as a prevout @@ -1460,7 +1709,7 @@ def test__is_change_branch__distinguishes_the_change_branch_from_the_receive_bra # TODO: Refactor all tests to be in the TestPSBTParser class(?) -class TestPSBTParserOutputOwnership(TestPSBTParserSeedOwnership): +class TestPSBTParserOutputOwnership(PSBTParserOwnershipTestBase): """ A psbt annotates its outputs with claims about which keys own them by providing derivation path entries for each key. @@ -1470,11 +1719,6 @@ class TestPSBTParserOutputOwnership(TestPSBTParserSeedOwnership): These tests cover invalid claims as well as the ways that the claims and the script can disagree and how PSBTParser handles such discrepancies. """ - def _foreign_multisig_script(self) -> script.Script: - """A 2-of-3 built entirely from someone else's keys.""" - return script.multisig(2, [foreign_public_key(f"m/48h/1h/0h/2h/0/{i}") for i in range(3)]) - - def _rebuild_around_foreign_keys(self, out: OutputScope): """ Replace a multisig output's script to pay to a different quorum made entirely of @@ -2147,6 +2391,115 @@ def test__parse__rejects_a_multisig_output_whose_supplied_script_is_not_its_own( self._parse(psbt) + def test__parse__counts_nested_single_sig_change_without_its_redeem_script_as_change(self): + """ + A legitimate nested single sig (p2sh-p2wpkh) change output can omit its redeem + script (BIP-174 makes it optional) while still claiming (via bip32_derivations) + that a key owned by our seed will receive the change. + + But the parser's proof of ownership check does not care about the missing redeem + script: the parser rebuilds p2sh(p2wpkh(K)) from the seed's own key at the claimed + path regardless. So the output should still be verifiable as change. + """ + psbt = self._psbt_with_change(PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_1_INPUT, PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_CHANGE) + + # The output claims a single key and our seed really does derive it there. + assert len(psbt.outputs[0].bip32_derivations) == 1 + public_key, derivation_path = list(psbt.outputs[0].bip32_derivations.items())[0] + assert PSBTParser.seed_owns_pubkey(self._root(), derivation_path.derivation, public_key, child_key_derivation_cache=None) is True + + psbt.outputs[0].redeem_script = None + + psbt_parser = self._parse(psbt) + assert psbt_parser.change_amount == 10_000 + assert psbt_parser.spend_amount == 0 + + + def test__parse__rejects_a_bare_p2sh_output_that_claims_this_seed_but_pays_someone_else(self): + """ + Variation on the prior test: the redeem script is still omitted but this time the + psbt repoints its output at a stranger's p2sh-p2wpkh. Crucially, the output keeps + its claim on this seed, making this an attempt at deception (if there was no claim + on the output, it would simply be a typical external spend output). + + When the parser rebuilds p2sh(p2wpkh(K)), the resulting scriptPubKey will not + match what the output commits to. The psbt should be refused with + PSBTOutputOwnershipContradictionError. + """ + psbt = self._psbt_with_change(PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_1_INPUT, PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_CHANGE) + psbt.outputs[0].redeem_script = None + psbt.outputs[0].script_pubkey = script.p2sh(script.p2wpkh(foreign_public_key())) + + with raises_reject(RejectCode.FORGED_OUTPUT_OWNERSHIP): + self._parse(psbt) + + + def test__parse__rejects_a_bare_p2sh_output_that_pays_this_seed_but_lists_another_key(self): + """ + Another variation: the redeem script is omitted and the output still pays our key, + but its one derivation path entry lists another seed's key and fingerprint at the + same path. + + The parser rebuilds p2sh(p2wpkh(K)) from our own key at that path and ignores the + fingerprint the entry lists. The result based on our key matches what the output + commits to, so it actually is our output even though the psbt claimed that it paid + to a different key. The psbt should be refused with + PSBTOutputOwnershipContradictionError. + """ + psbt = self._psbt_with_change(PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_1_INPUT, PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_CHANGE) + psbt.outputs[0].redeem_script = None + + # Swap the output's entry for another seed's key at the same path. The + # scriptPubKey still pays our key there. + derivation_path = list(psbt.outputs[0].bip32_derivations.values())[0] + path = bip32.path_to_str(derivation_path.derivation) + psbt.outputs[0].bip32_derivations.clear() + claim_seed_owns_key(psbt.outputs[0], path, foreign_public_key(path), seed=PSBTTestData.recipient_seed) + + # The fork's code for an output that pays this seed while naming another + # wallet's fingerprint; upstream raises PSBTOutputOwnershipContradictionError. + with raises_reject(RejectCode.MISLABELED_OUTPUT_OWNERSHIP): + self._parse(psbt) + + + def test__parse__counts_a_payment_to_another_wallet_of_this_seed_as_a_spend(self): + """ + A psbt can pay another wallet of this seed, such as its native segwit account or a + multisig it belongs to, and annotate that output with our key. Each case below is + such a payment. Each should parse and be counted as a spend. + + The parser makes an exception for nested single sig change that omits its redeem + script. An output must meet three criteria to qualify for the exception: + * inputs: the inputs are nested single sig + * output type: the output is parsed as plain p2sh + * redeem script: the output omits its redeem script + + These outputs should be categorized as external spends if any of the three + criteria are not met. Each scenario in this test sets up one criterion to fail + while the other two are met. + """ + # Fails the inputs condition: a native segwit input instead of nested single sig + psbt = self._psbt_with_change(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_1_INPUT, PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_CHANGE) + psbt.outputs[0].redeem_script = None + psbt_parser = self._parse(psbt) + assert psbt_parser.change_amount == 0 + assert psbt_parser.spend_amount == 10_000 + + # Fails the output type condition: p2wpkh is not parsed as a plain p2sh output + psbt = self._psbt_with_change(PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_1_INPUT, PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_CHANGE) + psbt_parser = self._parse(psbt) + assert psbt_parser.change_amount == 0 + assert psbt_parser.spend_amount == 10_000 + + # Fails the redeem script condition: legacy multisig is parsed as plain p2sh even + # when it supplies its redeem script. + psbt = self._psbt_with_change(PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_1_INPUT, PSBTTestData.MULTISIG_LEGACY_P2SH_CHANGE) + assert psbt.outputs[0].redeem_script is not None + psbt_parser = self._parse(psbt) + assert psbt_parser.change_amount == 0 + assert psbt_parser.spend_amount == 10_000 + + def test_get_cosigners_returns_a_sorted_list(self): """ Two multisig scripts can list the same wallet's keys in different orders, so the @@ -2420,3 +2773,396 @@ def p2pk(public_key: PublicKey) -> script.Script: with raises_reject(RejectCode.UNDISPLAYABLE_OUTPUT): self._parse(psbt) + + + def test__parse__rejects_outputs_that_exceed_inputs(self): + """ + Outputs that spend more than the inputs bring in produce a negative fee. `parse` + should raise PSBTNegativeFeeError rather than carry that impossible figure into + the review screens. + + Note that `psbt.tx` is rebuilt from the output scopes on every access, so the + amount has to be changed on the scope itself. + """ + psbt = self._psbt_with_change() + input_total = sum(inp.utxo.value for inp in psbt.inputs) + + # One satoshi more than the inputs fund, i.e. the smallest negative fee there is + psbt.outputs[0].value = input_total + 1 + + with raises_reject(RejectCode.NEGATIVE_FEE): + self._parse(psbt) + + + def test__parse__accepts_a_zero_fee(self): + """ + A transaction that pays no fee is pointless but not malformed (and can still be + relayed as part of a package), so only a strictly negative fee is rejected. This + pins the boundary the check is written against. + """ + psbt = self._psbt_with_change() + psbt.outputs[0].value = sum(inp.utxo.value for inp in psbt.inputs) + + assert self._parse(psbt).fee_amount == 0 + + + +def test_parse_op_return_payload_push_encodings(): + """ + Should extract the payload whichever push opcode carries it. + + Opcodes 0x01-0x4b are themselves the byte count; OP_PUSHDATA1, 2, and 4 are + followed by a 1, 2, or 4 byte little-endian length. Bitcoin Core emits the + minimal encoding, so a payload of 75 bytes or fewer arrives as a direct push and + the push opcode has to be read rather than assumed. 75/76 is the boundary between + the two. + """ + # Pin the constants: every assertion below is written in terms of them, so a typo + # in one would otherwise make this test agree with the bug it is meant to catch. + assert (OPCODES.OP_RETURN, OPCODES.OP_PUSHDATA_MAX_DIRECT) == (0x6a, 0x4b) + assert (OPCODES.OP_PUSHDATA1, OPCODES.OP_PUSHDATA2, OPCODES.OP_PUSHDATA4) == (0x4c, 0x4d, 0x4e) + assert OPCODES.OP_16 == 0x60 + + op_return = bytes([OPCODES.OP_RETURN]) + + # Direct push: the encoding Bitcoin Core produces for payloads up to 75 bytes + for length in [1, 2, 40, OPCODES.OP_PUSHDATA_MAX_DIRECT]: + payload = b"A" * length + assert PSBTParser._parse_op_return_payload(op_return + bytes([length]) + payload) == payload + + # OP_PUSHDATA1 carries a 1-byte length; 76 is the first payload that needs it + for length in [76, 80, 0xff]: + payload = b"B" * length + script_data = op_return + bytes([OPCODES.OP_PUSHDATA1, length]) + payload + assert PSBTParser._parse_op_return_payload(script_data) == payload + + # OP_PUSHDATA2 carries a 2-byte length. Now that Bitcoin Core v30 defaults + # `-datacarriersize` to 100,000 bytes this is an ordinary encoding, not an exotic one. + payload = b"C" * 300 + script_data = op_return + bytes([OPCODES.OP_PUSHDATA2]) + len(payload).to_bytes(2, "little") + payload + assert PSBTParser._parse_op_return_payload(script_data) == payload + + # OP_PUSHDATA4 carries a 4-byte length + payload = b"D" * 300 + script_data = op_return + bytes([OPCODES.OP_PUSHDATA4]) + len(payload).to_bytes(4, "little") + payload + assert PSBTParser._parse_op_return_payload(script_data) == payload + + # A non-minimal encoding is unusual but a coordinator is free to produce one + payload = b"E" * 10 + script_data = op_return + bytes([OPCODES.OP_PUSHDATA2]) + len(payload).to_bytes(2, "little") + payload + assert PSBTParser._parse_op_return_payload(script_data) == payload + + # Several pushes in one script are legal; they are concatenated + script_data = op_return + bytes([4]) + b"data" + bytes([4]) + b"more" + assert PSBTParser._parse_op_return_payload(script_data) == b"datamore" + + # Bare OP_RETURN, nothing pushed + assert PSBTParser._parse_op_return_payload(op_return) == b"" + + # An empty scriptPubKey must not index past the end + assert PSBTParser._parse_op_return_payload(b"") == b"" + + # OP_0 through OP_16 carry no data bytes but still count as pushes. Their opcode bytes + # are kept, and the walk carries on past them. + assert PSBTParser._parse_op_return_payload(op_return + bytes([0x00, 0x51])) == bytes([0x00, 0x51]) + assert PSBTParser._parse_op_return_payload(op_return + bytes([0x4f, 0x50])) == bytes([0x4f, 0x50]) + assert PSBTParser._parse_op_return_payload(op_return + bytes([0x00, 4]) + b"data") == b"\x00data" + assert PSBTParser._parse_op_return_payload(op_return + bytes([OPCODES.OP_16])) == bytes([OPCODES.OP_16]) + + + +def test_parse_op_return_payload_rejects_malformed_scripts(): + """ + Should raise PSBTMalformedOpReturnError when the script after OP_RETURN is not made + of complete pushes, which Bitcoin Core treats as nonstandard. + """ + op_return = bytes([OPCODES.OP_RETURN]) + + malformed_scripts = [ + # A direct push claiming more data than the script carries + op_return + bytes([10]) + b"abc", + + # An OP_PUSHDATA1 push claiming more data than the script carries + op_return + bytes([OPCODES.OP_PUSHDATA1, 80]) + b"abc", + + # OP_PUSHDATA1 with no length byte at all + op_return + bytes([OPCODES.OP_PUSHDATA1]), + + # A truncated OP_PUSHDATA2 length field + op_return + bytes([OPCODES.OP_PUSHDATA2, 0x01]), + + # A truncated OP_PUSHDATA4 length field + op_return + bytes([OPCODES.OP_PUSHDATA4, 0x01, 0x00, 0x00]), + + # The first opcode past OP_16 is not a push, and neither is anything above it + op_return + bytes([OPCODES.OP_16 + 1]), + op_return + bytes([0xff]), + + # A non-push opcode after a valid push; the whole script is checked + op_return + bytes([4]) + b"data" + bytes([0xac]), + ] + for script_data in malformed_scripts: + with raises_reject(RejectCode.MALFORMED_OP_RETURN): + PSBTParser._parse_op_return_payload(script_data) + + # The parser refuses the whole psbt, rather than parsing the rest of it + truncated_push = script.Script(op_return + bytes([10]) + b"abc") + psbt = create_op_return_psbt([create_op_return_output(b"", script_pubkey=truncated_push)]) + with raises_reject(RejectCode.MALFORMED_OP_RETURN): + PSBTParser(p=psbt, seed=PSBTTestData.seed, network=SettingsConstants.REGTEST) + + + +def test_parse_op_return_content_direct_push(): + """ + Should parse an OP_RETURN whose payload uses a direct push. + + This is the canonical encoding: `bitcoin-tx outdata=` and any Bitcoin Core + wallet produce it for payloads of 75 bytes or fewer. + """ + message = "Chancellor on the brink of third bailout".encode() + assert len(message) <= OPCODES.OP_PUSHDATA_MAX_DIRECT + + script_pubkey = op_return_script(message) + assert script_pubkey.data[:2] == bytes([OPCODES.OP_RETURN, len(message)]) + + psbt = create_op_return_psbt([create_op_return_output(message)]) + psbt_parser = PSBTParser(p=psbt, seed=PSBTTestData.seed, network=SettingsConstants.REGTEST) + + assert psbt_parser.op_return_data == message + + + +def test_parse_op_return_content_pushdata2(): + """ + Should parse an OP_RETURN payload large enough to require OP_PUSHDATA2. + + Bitcoin Core v30 raised the default `-datacarriersize` to 100,000 bytes, so + payloads past the 255 bytes OP_PUSHDATA1 can describe now arrive from honest + coordinators. Consensus has never limited OP_RETURN data at all, so no payload + size can be assumed either way. + """ + message = b"F" * 300 + + script_pubkey = op_return_script(message) + assert script_pubkey.data[:2] == bytes([OPCODES.OP_RETURN, OPCODES.OP_PUSHDATA2]) + + psbt = create_op_return_psbt([create_op_return_output(message)]) + psbt_parser = PSBTParser(p=psbt, seed=PSBTTestData.seed, network=SettingsConstants.REGTEST) + + assert psbt_parser.op_return_data == message + + + +def test_parse_op_return_with_no_payload(): + """ + A bare OP_RETURN output carries no data and must parse to empty, not crash. + """ + psbt = create_op_return_psbt([ + create_op_return_output(b"", script_pubkey=script.Script(bytes([OPCODES.OP_RETURN]))) + ]) + psbt_parser = PSBTParser(p=psbt, seed=PSBTTestData.seed, network=SettingsConstants.REGTEST) + + assert psbt_parser.op_return_data == b"" + + + +class TestPSBTParserInputScripts(PSBTParserOwnershipTestBase): + """ + Tests that an input supplies exactly the scripts it commits to. + + A p2sh or p2wsh input's scriptPubKey holds only a hash of the script it spends with, + so the psbt has to supply that script for anything to be checked. These tests cover + the parser requiring that script, requiring it to be the right one, and refusing an + extraneous one. + """ + def _add_foreign_nested_segwit_input(self, psbt: PSBT, derivation_path: str = "m/49h/1h/0h/0/0"): + """ + Adds a p2sh-p2wpkh input spending from another party's key with no derivation + paths specified. Its scriptPubKey and redeem script are both built from that key, + and its coin is described by a witness_utxo alone. + + The supplied psbt's first input should carry a witness_utxo. + """ + # Start from a copy of our own input for its witness_utxo, at an outpoint of its + # own (the fork refuses a transaction that spends one outpoint twice) + foreign_input = input_at_new_outpoint(psbt.inputs[0], len(psbt.inputs)) + + # Strip the derivation paths so the input claims none of the user's keys + foreign_input.bip32_derivations.clear() + + # Give it the other party's key: a redeem script built from that key and a + # scriptPubKey that commits to that redeem script. + public_key = foreign_public_key(derivation_path) + foreign_input.redeem_script = script.p2wpkh(public_key) + foreign_input.witness_utxo.script_pubkey = script.p2sh(foreign_input.redeem_script) + + # Drop the copied non_witness_utxo, which describes our own coin and contradicts + # the witness_utxo altered above. + foreign_input.non_witness_utxo = None + + psbt.inputs.append(foreign_input) + return foreign_input + + + def test__parse__refuses_an_input_that_omits_the_script_it_commits_to(self): + """ + The psbt leaves out a script that an input commits to: + * p2wsh: witness_script + * legacy p2sh multisig: redeem_script + * p2sh-p2wpkh: redeem_script + * p2sh-p2wsh: witness_script or redeem_script + + Each case should raise PSBTMissingInputScriptError. + """ + # Each case first confirms that the fixture really does carry the script it is + # about to omit. + + # p2wsh: omit the witness script + psbt = self._psbt_with_change(PSBTTestData.MULTISIG_NATIVE_SEGWIT_1_INPUT, PSBTTestData.MULTISIG_NATIVE_SEGWIT_CHANGE) + assert psbt.inputs[0].witness_script is not None + psbt.inputs[0].witness_script = None + with raises_reject(RejectCode.MISSING_INPUT_SCRIPT): + self._parse(psbt) + + # legacy p2sh multisig: omit the redeem script + psbt = self._psbt_with_change(PSBTTestData.MULTISIG_LEGACY_P2SH_1_INPUT, PSBTTestData.MULTISIG_LEGACY_P2SH_CHANGE) + assert psbt.inputs[0].redeem_script is not None + psbt.inputs[0].redeem_script = None + with raises_reject(RejectCode.MISSING_INPUT_SCRIPT): + self._parse(psbt) + + # p2sh-p2wpkh: omit the redeem script + psbt = self._psbt_with_change(PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_1_INPUT, PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_CHANGE) + assert psbt.inputs[0].redeem_script is not None + psbt.inputs[0].redeem_script = None + with raises_reject(RejectCode.MISSING_INPUT_SCRIPT): + self._parse(psbt) + + # p2sh-p2wsh: omit the witness script + psbt = self._psbt_with_change(PSBTTestData.MULTISIG_NESTED_SEGWIT_1_INPUT, PSBTTestData.MULTISIG_NESTED_SEGWIT_CHANGE) + assert psbt.inputs[0].witness_script is not None + psbt.inputs[0].witness_script = None + with raises_reject(RejectCode.MISSING_INPUT_SCRIPT): + self._parse(psbt) + + # p2sh-p2wsh: omit the redeem script + psbt = self._psbt_with_change(PSBTTestData.MULTISIG_NESTED_SEGWIT_1_INPUT, PSBTTestData.MULTISIG_NESTED_SEGWIT_CHANGE) + assert psbt.inputs[0].redeem_script is not None + psbt.inputs[0].redeem_script = None + with raises_reject(RejectCode.MISSING_INPUT_SCRIPT): + self._parse(psbt) + + + def test__parse__refuses_an_input_that_supplies_the_wrong_script(self): + """ + The psbt replaces one of an input's own scripts with a stranger's. A script that + hashes to the wrong value should raise PSBTInputScriptMismatchError, at each layer + of each script type that has one. + """ + foreign_script = self._foreign_multisig_script() + + # p2wsh: the witness script is the only layer + psbt = self._psbt_with_change(PSBTTestData.MULTISIG_NATIVE_SEGWIT_1_INPUT, PSBTTestData.MULTISIG_NATIVE_SEGWIT_CHANGE) + psbt.inputs[0].witness_script = foreign_script + with raises_reject(RejectCode.SCRIPT_HASH_MISMATCH): + self._parse(psbt) + + # legacy p2sh multisig: the redeem script is the only layer + psbt = self._psbt_with_change(PSBTTestData.MULTISIG_LEGACY_P2SH_1_INPUT, PSBTTestData.MULTISIG_LEGACY_P2SH_CHANGE) + psbt.inputs[0].redeem_script = foreign_script + with raises_reject(RejectCode.SCRIPT_HASH_MISMATCH): + self._parse(psbt) + + # p2sh-p2wpkh: a redeem script built from someone else's key + psbt = self._psbt_with_change(PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_1_INPUT, PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_CHANGE) + psbt.inputs[0].redeem_script = script.p2wpkh(foreign_public_key()) + with raises_reject(RejectCode.SCRIPT_HASH_MISMATCH): + self._parse(psbt) + + # p2sh-p2wsh, inner layer: the genuine redeem script, but a witness script other + # than the one it commits to + psbt = self._psbt_with_change(PSBTTestData.MULTISIG_NESTED_SEGWIT_1_INPUT, PSBTTestData.MULTISIG_NESTED_SEGWIT_CHANGE) + psbt.inputs[0].witness_script = foreign_script + with raises_reject(RejectCode.SCRIPT_HASH_MISMATCH): + self._parse(psbt) + + # p2sh-p2wsh, outer layer: a redeem script other than the one the scriptPubKey + # commits to + psbt = self._psbt_with_change(PSBTTestData.MULTISIG_NESTED_SEGWIT_1_INPUT, PSBTTestData.MULTISIG_NESTED_SEGWIT_CHANGE) + psbt.inputs[0].redeem_script = script.p2wsh(foreign_script) + with raises_reject(RejectCode.SCRIPT_HASH_MISMATCH): + self._parse(psbt) + + + def test__parse__refuses_an_input_that_supplies_an_extra_script(self): + """ + The psbt adds an extraneous script that is nonsensical to include for the input's + script type: + * legacy p2sh multisig: should never have a witness_script + * p2wpkh: should never have a redeem_script + * p2sh-p2wpkh: should never have a witness_script + + The input's required script(s) must pass validation in order to reach the + extraneous script check, so those required scripts are preserved in their correct + form here. + + By rule, an extraneous script should raise PSBTExtraneousInputScriptError. + """ + # The extraneous script's content is irrelevant, so an arbitrary script will do + arbitrary_script = script.Script(b"\x51") # OP_TRUE + + # legacy p2sh multisig: add a witness script + psbt = self._psbt_with_change(PSBTTestData.MULTISIG_LEGACY_P2SH_1_INPUT, PSBTTestData.MULTISIG_LEGACY_P2SH_CHANGE) + psbt.inputs[0].witness_script = arbitrary_script + with raises_reject(RejectCode.EXTRANEOUS_WITNESS_SCRIPT): + self._parse(psbt) + + # p2wpkh: add a redeem script + psbt = self._psbt_with_change() + psbt.inputs[0].redeem_script = arbitrary_script + with raises_reject(RejectCode.EXTRANEOUS_REDEEM_SCRIPT): + self._parse(psbt) + + # p2sh-p2wpkh: add a witness script + psbt = self._psbt_with_change(PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_1_INPUT, PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_CHANGE) + psbt.inputs[0].witness_script = arbitrary_script + with raises_reject(RejectCode.EXTRANEOUS_WITNESS_SCRIPT): + self._parse(psbt) + + + def test__parse__checks_input_scripts_whoever_the_input_belongs_to(self): + """ + The parser verifies the scripts on every input, whoever the psbt says the input + belongs to. So an input with no derivation paths, claiming none of the user's + keys, gets the same script checks as the user's own input. + + The psbt will be rejected if a script is missing (PSBTMissingInputScriptError) or + wrong (PSBTInputScriptMismatchError). + + Note: despite setting up a collaborative spend, this test is not meant to mimic a + realistic payjoin transaction. Certain types of payjoin inputs (e.g. nested + segwit) require special handling to pass the input script checks. See the separate + payjoin TODO in the parser. + """ + psbt = self._psbt_with_change(PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_1_INPUT, PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_CHANGE) + foreign_input = self._add_foreign_nested_segwit_input(psbt) + + # The other party's input carries its correct redeem script and none of the + # user's keys. + psbt_parser = self._parse(psbt) + assert psbt_parser.num_inputs == 2 + assert psbt_parser.verified_input_derivation_paths[1] == [] + + # Omit its redeem script. Its scriptPubKey alone then reads as legacy p2sh, which + # needs a non_witness_utxo to prove its amount. The parse should still report the + # missing script. + foreign_input.redeem_script = None + with raises_reject(RejectCode.MISSING_INPUT_SCRIPT): + self._parse(psbt) + + # With a redeem script built from the other party's key at the next address + # (index 1), rather than the index 0 key that the scriptPubKey commits to. + foreign_input.redeem_script = script.p2wpkh(foreign_public_key("m/49h/1h/0h/0/1")) + with raises_reject(RejectCode.SCRIPT_HASH_MISMATCH): + self._parse(psbt) diff --git a/tests/test_psbt_test_suite.py b/tests/test_psbt_test_suite.py index 1f654d3168..1dc29a7426 100644 --- a/tests/test_psbt_test_suite.py +++ b/tests/test_psbt_test_suite.py @@ -1057,6 +1057,20 @@ class TestOpReturnPayload: def test_direct_push_is_shown_exactly(self, name): assert parse_vector(VECTORS_BY_NAME[name]).op_return_data == self.MSG + @pytest.mark.parametrize("name,expected", [ + # OP_13 is kept as its opcode byte, ahead of the runestone's push + ("XTRAS.OP_RETURN_RUNESTONE", b"\x5d" + bytes.fromhex("00c0a2331414010203")), + ("XTRAS.OP_RETURN_RUNESTONE_V2", b"\x5d" + bytes.fromhex("00c0a2331414010203")), + # OP_0, OP_1NEGATE, OP_1, OP_16 + ("XTRAS.OP_RETURN_SMALLINT", b"\x00\x4f\x51\x60"), + ("XTRAS.OP_RETURN_SMALLINT_V2", b"\x00\x4f\x51\x60"), + ("XTRAS.OP_RETURN_MULTI_PUSH", b"helloabcde"), + ("XTRAS.OP_RETURN_MULTI_PUSH_V2", b"helloabcde"), + ]) + def test_push_only_payload_is_shown_exactly(self, name, expected): + """Anything Core's IsPushOnly accepts is shown, not refused.""" + assert parse_vector(VECTORS_BY_NAME[name]).op_return_data == expected + @pytest.mark.parametrize("script,expected", [ (b"j(" + MSG, MSG), # direct push (<= 75 bytes) (b"jLP" + b"x" * 80, b"x" * 80), # OP_PUSHDATA1 @@ -1064,11 +1078,18 @@ def test_direct_push_is_shown_exactly(self, name): (b"j", b""), # bare OP_RETURN (b"j\x03ab", None), # truncated push: refused, not partly shown (b"j\x4c", None), # OP_PUSHDATA1 with no length byte - (b"j\x51", None), # a non-push opcode - (b"j\x00\x02hi", b"hi"), # OP_0 is an empty push + (b"j\xac", None), # a non-push opcode (OP_CHECKSIG) + (b"j\x00\x02hi", b"\x00hi"), # OP_0 counts as a push; its byte is kept + (b"j\x51", b"\x51"), # OP_1: push-only per Core's IsPushOnly + (b"j\x5d\x03abc", b"\x5dabc"), # Runes: OP_RETURN OP_13 ]) def test_payload_parsing(self, script, expected): - assert PSBTParser._op_return_payload(script) == expected + if expected is None: + with pytest.raises(InvalidPSBTError) as excinfo: + PSBTParser._parse_op_return_payload(script) + assert excinfo.value.code == RejectCode.MALFORMED_OP_RETURN + else: + assert PSBTParser._parse_op_return_payload(script) == expected def test_malformed_payload_is_refused(self): """A push that runs past the end would be shown as data the output doesn't carry.""" @@ -1079,7 +1100,7 @@ def test_malformed_payload_is_refused(self): with pytest.raises(InvalidPSBTError) as excinfo: PSBTParser(p=psbt, seed=suite_seed(), network=SUITE_NETWORK, max_fee_rate=SUITE_MAX_FEE_RATE) - assert excinfo.value.code == RejectCode.UNDISPLAYABLE_OUTPUT + assert excinfo.value.code == RejectCode.MALFORMED_OP_RETURN def test_every_op_return_is_shown(self): """Each OP_RETURN's payload is kept, in output order -- not just the last one."""