From d0636cc52bbce9c56c43554ef881fd5f809a937c Mon Sep 17 00:00:00 2001 From: Nick Klockenga Date: Fri, 28 Aug 2026 21:52:51 -0400 Subject: [PATCH 01/48] Verify PSBT input amounts and discard unverifiable transactions PSBTParser summed each input's declared amount without ever checking it, so the fee shown on the overview and math screens was only a claim from the coordinator. _verify_input_amounts() now runs in parse() and raises PSBTInputAmountVerificationError when an input has no utxo data, when its outpoint index falls outside the non_witness_utxo it claims to spend, when that non_witness_utxo does not hash to the txid it claims to spend, when a legacy or unrecognized input supplies no non_witness_utxo, or when a witness_utxo disagrees with a verified non_witness_utxo. PSBTOverviewView catches it, clears the parser, and routes to a discard-only PSBTInputAmountVerificationFailedView (approach and placement from #977). The check runs after the ownership checks so a psbt this seed cannot sign is reported as a mismatch rather than as a suspicious transaction, and before _parse_inputs, where amounts are first summed. Segwit inputs carrying only a witness_utxo are still accepted, since BIP-143 commits the amount they sign and many coordinators never sends both utxo fields Co-Authored-By: 0kPN1 <55192256+0kPN1@users.noreply.github.com> --- src/seedsigner/models/psbt_parser.py | 123 ++++++++++-- src/seedsigner/views/psbt_views.py | 45 ++++- tests/screenshot_generator/generator.py | 1 + tests/test_flows_psbt.py | 75 ++++++- tests/test_psbt_parser.py | 257 +++++++++++++++++++++++- 5 files changed, 475 insertions(+), 26 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 441c1e1db9..75584393de 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -3,7 +3,7 @@ from embit import psbt, script, ec, bip32 from embit.descriptor import Descriptor from embit.networks import NETWORKS -from embit.psbt import PSBT, DerivationPath, InputScope, OutputScope +from embit.psbt import PSBT, DerivationPath, InputScope, OutputScope, PSBTError from embit.ec import PublicKey from io import BytesIO from typing import List @@ -103,6 +103,19 @@ class PSBTOutputOwnershipContradictionError(PSBTVerificationError): pass +class PSBTInputAmountVerificationError(PSBTVerificationError): + """ + An input's declared amount could not be verified, so the fee this device would display + cannot be trusted. See PSBTParser._verify_input_amounts(). + + Segwit inputs carrying only a witness_utxo are deliberately NOT rejected: there the + sighash commits the amount, so a lie invalidates the signature rather than burning + funds. _verify_input_amounts() covers why the residual risk (CVE-2020-14199) is accepted + rather than warned about. + """ + pass + + class PSBTSeedCannotSignError(PSBTVerificationError): """ The selected seed holds no key that could sign any input. @@ -114,7 +127,6 @@ class PSBTSeedCannotSignError(PSBTVerificationError): pass - class PSBTParser(): """ Reads a psbt on behalf of one seed and works out everything the signing flow shows the @@ -156,6 +168,10 @@ class PSBTParser(): # just stops getting cache hits once the cache is full. MAX_CACHED_DERIVATIONS = 1000 + # Input types whose sighash does NOT commit to the input amount. A lie about the + # input amount still allows a valid signature, so these inputs must supply a non_witness_utxo. + UNCOMMITTED_AMOUNT_SCRIPT_TYPES = [None, "p2pkh", "p2sh"] + def __init__(self, p: PSBT, seed: Seed, network: str = SettingsConstants.MAINNET): self.psbt: PSBT = p @@ -227,7 +243,13 @@ def parse(self): inputs can be signed by the seed. A mismatch rather than an attack, caught here so the flow can say so before showing a transaction. - 4. _parse_inputs: every input must resolve to the same policy otherwise a + 4. _verify_input_amounts: raises PSBTInputAmountVerificationError when an input's + claimed amount cannot be verified against a non_witness_utxo. Runs after the + ownership checks so a psbt this seed cannot sign is reported as a mismatch + rather than as a suspicious transaction, but before _parse_inputs, which is + where amounts are first summed. + + 5. _parse_inputs: every input must resolve to the same policy otherwise a RuntimeError is raised. TODO: make this a PSBTVerificationError subclass so the view can deliberately catch this scenario and route accordingly. @@ -241,7 +263,7 @@ def parse(self): policy with no cosigner information pass as a match between inputs. Outputs deliberately compare shape alone; see _policy_shape_matches. - 5. _parse_outputs: organizes the output data (amounts, destination_addresses, + 6. _parse_outputs: organizes the output data (amounts, destination_addresses, etc.) and verifies the ownership of the outputs that come back to this seed via: - single-sig: Rebuild the output script from the seed and match it against @@ -291,6 +313,9 @@ def parse(self): self._verify_claimed_derivation_paths(child_key_derivation_cache) self._reject_if_seed_cannot_sign() + # Single source of truth for input amounts; raises before any amount is summed + self._verify_input_amounts() + rt = self._parse_inputs(child_key_derivation_cache) if rt == False: return False @@ -302,6 +327,69 @@ def parse(self): return True + def _verify_input_amounts(self): + """ + Verify each input's declared amount before any of them is summed. Since seedsigner is + airgapped, we can't look up what an input is actually worth. We're relying on what the + coordinator declared. Unchecked, a compromised coordinator could declare false amounts + and have us display any fee it liked. See the miner fee attack described in embit's + InputScope.verify(). + + Despite the name, an input's non_witness_utxo is the *entire* transaction that created + the coin being spent, so we can hash it and confirm it produces the txid this input + claims to spend. A witness_utxo is just the one output, with no such proof. + + ignore_missing=True is required: coordinators legitimately and typically supply only + the witness_utxo for segwit inputs, where the sighash commits the input amount. A lie there + invalidates the signature instead of burning funds. Legacy sighashes commit no amount + at all, so legacy inputs must supply a non_witness_utxo. + + Known limitation: that sighash protection is not absolute. BIP-143 commits only the + amount of the input being signed, so a coordinator that gets us to sign the same + transaction twice can keep one valid signature per session/input and combine them into + a tx that burns the difference as miner fee (CVE-2020-14199). + + We accept that risk for segwit rather than warn about it, because the data needed to + close it isn't coming. Wallets generally provide non_witness_utxo *or* witness_utxo but + not both. This is mainly so psbts stay small for QR-based signers. Warning + on it would therefore fire on nearly every ordinary multi-input segwit spend and only + teach users to click through warnings. + """ + for i, inp in enumerate(self.psbt.inputs): + # Must precede any read of inp.utxo which dereferences + # non_witness_utxo.vout[inp.vout], so an out-of-range outpoint index raises + # IndexError rather than something the view can route on. embit's verify() + # only compares txids and never checks this. + if inp.non_witness_utxo and inp.vout >= len(inp.non_witness_utxo.vout): + raise PSBTInputAmountVerificationError( + f"Input {i}: outpoint index {inp.vout} is out of range of its non_witness_utxo") + + if inp.utxo is None: + raise PSBTInputAmountVerificationError(f"Input {i} has no utxo data") + + try: + verified = inp.verify(ignore_missing=True) + except PSBTError as e: + raise PSBTInputAmountVerificationError(f"Input {i}: {e}") + + if not verified: + # No non_witness_utxo supplied; only safe if the sighash commits the amount + script_type = PSBTParser._get_script_type(inp, inp.script_pubkey) + if script_type in PSBTParser.UNCOMMITTED_AMOUNT_SCRIPT_TYPES: + raise PSBTInputAmountVerificationError(f"Input {i}: {script_type} input has no non_witness_utxo to verify against") + continue + + # verify() hashes the non_witness_utxo but never looks at the witness_utxo that may + # sit alongside it. embit's PSBT.utxo()/fee() prefer witness_utxo, so a witness_utxo + # that disagrees would still be the value driving our fee. Coordinators that keep + # psbts small send one field or the other, never both, so this only fires on a + # malformed or deliberately crafted psbt. + if inp.witness_utxo and inp.non_witness_utxo: + prevout = inp.non_witness_utxo.vout[inp.vout] + if prevout.value != inp.witness_utxo.value or prevout.script_pubkey.data != inp.witness_utxo.script_pubkey.data: + raise PSBTInputAmountVerificationError(f"Input {i}: witness_utxo doesn't match verified non_witness_utxo") + + def _parse_inputs(self, child_key_derivation_cache: dict): """ Totals the input amounts and determines the wallet policy. Every input must @@ -310,12 +398,9 @@ def _parse_inputs(self, child_key_derivation_cache: dict): self.input_amount = 0 self.num_inputs = len(self.psbt.inputs) for inp in self.psbt.inputs: - 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 + # Amounts were verified in _verify_input_amounts() + self.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: @@ -649,9 +734,11 @@ 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: + """ + Disambiguate the scriptpubkey's type. Cheap: pattern-matches bytes and derives + nothing, so it's safe to call before an input's amounts have been verified. + """ script_type = scriptpubkey.script_type() # p2sh can be either legacy multisig, or nested segwit multisig # or nested segwit singlesig @@ -663,6 +750,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 @@ -1181,4 +1276,4 @@ def _get_updated_fingerprint(public_key: PublicKey, derivation_path_obj: Derivat _fill_scope(inp) for out in self.psbt.outputs: - _fill_scope(out) \ No newline at end of file + _fill_scope(out) diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index dba57fb434..000554c50e 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -1,14 +1,18 @@ +import logging + from gettext import gettext as _ -from seedsigner.models.psbt_parser import (PSBTInputOwnershipClaimError, - PSBTMixedDerivationPathTypesError, PSBTOutputOwnershipClaimError, - PSBTOutputOwnershipContradictionError, PSBTParser, PSBTSeedCannotSignError, - PSBTSurplusDerivationPathsError) +from seedsigner.models.psbt_parser import (PSBTInputAmountVerificationError, + PSBTInputOwnershipClaimError, PSBTMixedDerivationPathTypesError, + PSBTOutputOwnershipClaimError, PSBTOutputOwnershipContradictionError, PSBTParser, + PSBTSeedCannotSignError, PSBTSurplusDerivationPathsError) from seedsigner.models.settings import SettingsConstants from seedsigner.gui.components import FontAwesomeIconConstants, GUIConstants, SeedSignerIconConstants from seedsigner.gui.screens.screen import (RET_CODE__BACK_BUTTON, ButtonListScreen, ButtonOption, LargeIconStatusScreen, WarningScreen, DireWarningScreen, QRDisplayScreen) from seedsigner.views.view import BackStackView, MainMenuView, View, Destination +logger = logging.getLogger(__name__) + class PSBTSelectSeedView(View): @@ -135,6 +139,14 @@ def __init__(self): self.set_redirect(Destination(PSBTSeedCannotSignView)) return + except PSBTInputAmountVerificationError as e: + # The declared input amounts could not be verified, so the fee we would show is unproven + # Set clear_history to disable returning via BACK button. + logger.error(f"PSBT input amount verification failed: {e}") + self.controller.psbt_parser = None + self.set_redirect(Destination(PSBTInputAmountVerificationFailedView, clear_history=True)) + return + finally: self.loading_screen.stop() @@ -648,6 +660,31 @@ def run(self): +class PSBTInputAmountVerificationFailedView(View): + """ + Reached when an input's declared amount could not be verified (see + PSBTInputAmountVerificationError). Shows a dire warning and discards the psbt to the + main menu. + """ + DISCARD = ButtonOption("Discard transaction") + + def run(self): + self.run_screen( + DireWarningScreen, + title=_("Suspicious Transaction"), + status_headline=_("Input Amounts Unverified"), + text=_("The PSBT input amounts cannot be confirmed. The fee shown cannot be trusted."), + button_data=[self.DISCARD], + show_back_button=False, + ) + + # We're done with this PSBT. Route back to MainMenuView, which clears all ephemeral + # data (except in-memory seeds). + # Set clear_history to disable returning via BACK button. + return Destination(MainMenuView, clear_history=True) + + + class PSBTOpReturnView(View): """ Shows the OP_RETURN data diff --git a/tests/screenshot_generator/generator.py b/tests/screenshot_generator/generator.py index 5fa52a2ccd..e1edf58c38 100644 --- a/tests/screenshot_generator/generator.py +++ b/tests/screenshot_generator/generator.py @@ -457,6 +457,7 @@ def mock_version_to_most_recent_release(): ScreenshotConfig(psbt_views.PSBTOutputOwnershipClaimFailedView), ScreenshotConfig(psbt_views.PSBTInputOwnershipClaimFailedView), ScreenshotConfig(psbt_views.PSBTSeedCannotSignView), + ScreenshotConfig(psbt_views.PSBTInputAmountVerificationFailedView), ScreenshotConfig(psbt_views.PSBTFinalizeView, mock_context_manager=mock_multisig_psbt_loaded), #ScreenshotConfig(PSBTSignedQRDisplayViewScreenshotConfig), ScreenshotConfig(psbt_views.PSBTSigningErrorView, mock_context_manager=mock_multisig_psbt_loaded), diff --git a/tests/test_flows_psbt.py b/tests/test_flows_psbt.py index c21a3e0501..0e78b0590c 100644 --- a/tests/test_flows_psbt.py +++ b/tests/test_flows_psbt.py @@ -1,13 +1,15 @@ from binascii import a2b_base64 +from unittest.mock import Mock from embit import bip32, script from embit.psbt import PSBT, DerivationPath -from base import FlowTest, FlowStep +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 seedsigner.controller import Controller +from seedsigner.models.psbt_parser import PSBTParser from seedsigner.views.view import MainMenuView from seedsigner.views import scan_views, seed_views, psbt_views from seedsigner.models.seed import Seed @@ -61,6 +63,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. @@ -341,3 +374,43 @@ 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 + + + +class TestPSBTOverviewView(BaseTest): + """ + View-level tests for the parts of PSBTOverviewView that a FlowTest can't reach. + """ + + def test_stale_psbt_parser_is_cleared_on_input_verification_failure(self): + """ + The error handler nulls controller.psbt_parser so an unusable parser can't be left + behind for a later view to read a fee from. + + This is defensive: ScanView already nulls psbt_parser whenever it sets a new psbt + (scan_views.py), so no real flow reaches PSBTOverviewView with a stale parser in + place. That's precisely why this is tested here and not in a flow — the state has to + be constructed by hand, and asserting it inside a flow would only ever be checking + ScanView's cleanup rather than the handler's. + """ + self.settings.set_value(SettingsConstants.SETTING__NETWORK, SettingsConstants.REGTEST) + + psbt = PSBT.parse(a2b_base64(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_2_INPUTS)) + psbt.inputs[0].non_witness_utxo.vout[0].value += 100_000 + + self.controller.psbt = psbt + self.controller.psbt_seed = PSBTTestData.two_input_seed + + # Stand in for a parser left over from a previously-viewed psbt. Its seed differs from + # psbt_seed, so PSBTOverviewView will re-parse rather than reuse it. + self.controller.psbt_parser = Mock(spec=PSBTParser, seed=PSBTTestData.seed) + assert self.controller.psbt_parser.seed != self.controller.psbt_seed + + view = psbt_views.PSBTOverviewView() + + assert self.controller.psbt_parser is None + + # The view redirects away from the overview rather than rendering an unproven fee. + # Destination._run_view() honors this before run() is ever called. + assert view.has_redirect + assert view.get_redirect().View_cls is psbt_views.PSBTInputAmountVerificationFailedView diff --git a/tests/test_psbt_parser.py b/tests/test_psbt_parser.py index 4d28c2ff67..5abee9a0c6 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -9,11 +9,12 @@ 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 (PSBTInputOwnershipClaimError, - PSBTMixedDerivationPathTypesError, PSBTOutputOwnershipClaimError, - PSBTOutputOwnershipContradictionError, PSBTParser, PSBTSeedCannotSignError, - PSBTSurplusDerivationPathsError) +from seedsigner.models.psbt_parser import (PSBTInputAmountVerificationError, + PSBTInputOwnershipClaimError, PSBTMixedDerivationPathTypesError, + PSBTOutputOwnershipClaimError, PSBTOutputOwnershipContradictionError, PSBTParser, + PSBTSeedCannotSignError, PSBTSurplusDerivationPathsError) from seedsigner.models.seed import Seed from seedsigner.models.settings_definition import SettingsConstants @@ -253,6 +254,13 @@ def test_missing_fingerprint_handling(self): taproot_input.taproot_internal_key = x_only_public_key taproot_input.witness_utxo.script_pubkey = script.p2tr(x_only_public_key) + # 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. @@ -351,6 +359,230 @@ def test__is_change_branch__distinguishes_the_change_branch_from_the_receive_bra +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 + + + def parse(self, psbt: PSBT) -> PSBTParser: + return PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) + + + @pytest.mark.parametrize("psbt_base64", PSBTTestData.ALL_INPUTS) + def test_untampered_psbts_verify(self, psbt_base64: str): + """ + Every supported script type's fixture carries a verifiable non_witness_utxo. + + is_verified is the assertion that carries the weight here. It is only set by embit's + InputScope.verify(), so it is the one flag that distinguishes "we hashed the previous + tx ourselves" from "we took the coordinator's word for it". input_amount alone would + hold with or without _verify_input_amounts(), since _parse_inputs() sums inp.utxo.value + either way. + """ + psbt = self.build_psbt(psbt_base64) + assert all(inp.is_verified == False for inp in psbt.inputs) # not verified until we do it + + psbt_parser = self.parse(psbt) + + assert all(inp.is_verified for inp in psbt.inputs) + assert psbt_parser.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): + """ + Editing the non_witness_utxo changes the txid it hashes to, so it no longer matches + the txid the input claims to spend. + """ + psbt = self.build_psbt(psbt_base64) + psbt.inputs[0].non_witness_utxo.vout[0].value += 100_000 + + with pytest.raises(PSBTInputAmountVerificationError): + self.parse(psbt) + + + @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() == True + + with pytest.raises(PSBTInputAmountVerificationError): + self.parse(psbt) + + + @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 other half of the cross-check: same amount, different scriptPubKey. Nothing about + the fee changes, but InputScope.script_pubkey resolves to the witness_utxo's, which is + what _parse_inputs() hands to _get_policy(). A mismatched scriptPubKey therefore means + we'd report the wrong script type for a coin we never actually inspected. + """ + 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 + assert witness_utxo.value == original_value + assert psbt.inputs[0].verify() == True + + with pytest.raises(PSBTInputAmountVerificationError): + self.parse(psbt) + + + @pytest.mark.parametrize("psbt_base64", LEGACY_INPUTS) + def test_legacy_input_without_non_witness_utxo_raises(self, psbt_base64: str): + """ + The concrete fund-loss case: a legacy sighash commits no input amount, so an inflated + witness_utxo yields a *valid* signature on a transaction that burns the difference as + miner fee. With no non_witness_utxo to check against, we have to refuse. + """ + 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 + + with pytest.raises(PSBTInputAmountVerificationError): + self.parse(psbt) + + + 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. + pubkey = list(inp.bip32_derivations.keys())[0].sec() + inp.witness_utxo = inp.non_witness_utxo.vout[inp.vout] + inp.witness_utxo.script_pubkey = Script(b"\x51\x21" + pubkey + b"\x51\xae") + 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 + + with pytest.raises(PSBTInputAmountVerificationError): + self.parse(psbt) + + + @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 + + assert self.parse(psbt).input_amount == psbt.inputs[0].witness_utxo.value + + + def test_input_with_no_utxo_data_raises(self): + """ + Nothing to verify against and nothing to sum; refuse rather than guess. Without this + guard _get_policy() is handed a None script_pubkey and dies with an AttributeError + instead of an error the caller can route on. + + One fixture is enough: this is the first check in the loop, and once utxo is None the + input's script_pubkey is None too, so no script type can reach it differently. + """ + psbt = self.build_psbt(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_1_INPUT) + psbt.inputs[0].witness_utxo = None + psbt.inputs[0].non_witness_utxo = None + + with pytest.raises(PSBTInputAmountVerificationError): + self.parse(psbt) + + + def test_outpoint_index_past_end_of_non_witness_utxo_raises(self): + """ + embit's verify() only compares txids and never checks that vout indexes into the + non_witness_utxo it just hashed, so a genuine prev tx paired with an out-of-range + outpoint passes verification. Unguarded, the deref raises a bare IndexError that + escapes parse() and crashes the view instead of routing to a warning. + """ + 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) + + with pytest.raises(PSBTInputAmountVerificationError): + self.parse(psbt) + + + def test_every_input_is_checked_not_just_the_first(self): + """ + Every fixture above has a single input, so none of them can catch a check that stops + after input 0. Tampering the *second* input of a 2-input psbt must fail just as loudly, + and the error must name the input that actually failed. + + Tampering input 0 is deliberately not covered here; that is exactly what + test_tampered_non_witness_utxo_raises already does across all seven script types. + """ + 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.input_amount == 56_522_834 + 1_990_245_069 + + psbt.inputs[1].non_witness_utxo.vout[0].value += 100_000 + + with pytest.raises(PSBTInputAmountVerificationError, match="Input 1:"): + 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 """ @@ -963,9 +1195,12 @@ def test__parse__verified_derivation_paths_none_for_not_owned_input(self): """ psbt = self._psbt_with_change() - # The other party's input: their utxo, carrying no derivation info + # The other party's input: their utxo, carrying no derivation info. Witness-only, + # as a real payjoin counterparty's input is — the deepcopy's non_witness_utxo + # describes this seed's coin and would contradict the witness_utxo rewritten below. foreign_input = deepcopy(psbt.inputs[0]) foreign_input.bip32_derivations.clear() + foreign_input.non_witness_utxo = None foreign_input.witness_utxo.script_pubkey = script.p2wpkh(foreign_public_key()) psbt.inputs.append(foreign_input) @@ -2150,5 +2385,13 @@ def p2pk(public_key: PublicKey) -> script.Script: assert psbt.inputs[0].witness_utxo.script_pubkey.script_type() is None assert psbt.outputs[0].script_pubkey.script_type() is None - with pytest.raises(RuntimeError, match="Unsupported policy type"): - self._parse(psbt) + # An unrecognized script type with no non_witness_utxo to prove its amount is + # exactly what _verify_input_amounts() now refuses, and editing the + # non_witness_utxo to pay to this p2pk script is not an option either: that + # changes the txid it hashes to. So this psbt can no longer reach _parse_inputs on + # its own; see test_unrecognized_script_type_without_non_witness_utxo_raises for + # that rejection. The catch-all safety check is still worth asserting, so stub out + # the amount verification that now precedes it. + with patch.object(PSBTParser, "_verify_input_amounts"): + with pytest.raises(RuntimeError, match="Unsupported policy type"): + self._parse(psbt) From d30f349fafd7e5f08b915b0a9441c1a0e18391b9 Mon Sep 17 00:00:00 2001 From: newtonick Date: Tue, 22 Sep 2026 22:22:34 -0400 Subject: [PATCH 02/48] Escalate PSBTInputAmountVerificationFailedView headline to "Likely an Attack!" --- src/seedsigner/views/psbt_views.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index 000554c50e..e82f05d236 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -672,7 +672,7 @@ def run(self): self.run_screen( DireWarningScreen, title=_("Suspicious Transaction"), - status_headline=_("Input Amounts Unverified"), + status_headline=_("Likely an Attack!"), text=_("The PSBT input amounts cannot be confirmed. The fee shown cannot be trusted."), button_data=[self.DISCARD], show_back_button=False, From ba67bfdfbd16644f557a0c07baaa3808561f989e Mon Sep 17 00:00:00 2001 From: newtonick Date: Tue, 22 Sep 2026 22:36:28 -0400 Subject: [PATCH 03/48] Clarify comment on the non_witness_utxo outpoint bounds check --- src/seedsigner/models/psbt_parser.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 75584393de..57a33cd046 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -356,10 +356,9 @@ def _verify_input_amounts(self): teach users to click through warnings. """ for i, inp in enumerate(self.psbt.inputs): - # Must precede any read of inp.utxo which dereferences - # non_witness_utxo.vout[inp.vout], so an out-of-range outpoint index raises - # IndexError rather than something the view can route on. embit's verify() - # only compares txids and never checks this. + # Make sure inp.vout, the output this input claims to spend, actually exists in the + # non_witness_utxo. Otherwise the lookups below raise an IndexError instead of + # rejecting the psbt. if inp.non_witness_utxo and inp.vout >= len(inp.non_witness_utxo.vout): raise PSBTInputAmountVerificationError( f"Input {i}: outpoint index {inp.vout} is out of range of its non_witness_utxo") From cf18a0b9f2181afae9b7e2bc50aa394be8c42049 Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Thu, 24 Sep 2026 11:23:48 -0500 Subject: [PATCH 04/48] Admit bare p2sh outputs as nested single sig change A p2sh-p2wpkh output's scriptPubKey is a bare p2sh hash. BIP-174 leaves the redeem script optional on an output, and without it _get_policy types the output as plain p2sh, which does not match a p2sh-p2wpkh wallet policy. The output then never reaches the ownership check at all. Two things follow. The user's own change is displayed as a payment out to a stranger. And an output that keeps a genuine claim on this seed while repointing its scriptPubKey escapes the ownership-contradiction refusal by dropping one optional field. Nested single sig is the only script type whose identity depends on an optional field its proof does not read: the rebuild is p2sh(p2wpkh(K)) from our own seed at the claimed path and the inputs' policy, so the missing field is a discriminator rather than evidence. For p2sh-p2wsh the discriminator and the proof material are the same field, so its absence is genuine silence and correctly out of reach. _policy_shape_matches becomes _is_change_candidate, an instance method, since it now reads the inputs' policy and the output's verified derivation paths. Beside the unchanged shape comparison it admits a bare p2sh output under a p2sh-p2wpkh wallet that carries no m-of-n, supplies exactly one derivation path entry, and holds one verified claim on this seed. Everything below is unchanged: the rebuild decides, honest change is counted as change, and a repointed output raises PSBTOutputOwnershipContradictionError. The single-entry conditions are what keep that refusal safe. A genuine multisig output carries one derivation path entry per cosigner, so it never reaches the contradiction check by this route. The shape that would is a bare p2sh output withholding both scripts while annotating a single key of a multisig, and no surveyed coordinator emits one. Every coordinator but Bitcoin Core annotates only its own change output. Core annotates an output because a descriptor solved its script, so it holds all n key origins and writes them. --- src/seedsigner/models/psbt_parser.py | 49 +++++++++++++++++++--------- tests/test_psbt_parser.py | 43 ++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 15 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 2f62066d41..7c51f94a3e 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -249,7 +249,7 @@ def parse(self): _get_policy doesn't propagate cosigner errors, so two such policies match without anything having tied them to the same keys. TODO: don't let a policy with no cosigner information pass as a match between inputs. - Outputs deliberately compare shape alone; see _policy_shape_matches. + Outputs deliberately compare shape alone; see _is_change_candidate. 5. _parse_outputs: organizes the output data (amounts, destination_addresses, etc.) and verifies the ownership of the outputs that come back to this seed @@ -411,7 +411,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, self.verified_output_derivation_paths[i]): # Begin the extensive work to fully verify whether this output is indeed # change. @@ -708,23 +708,42 @@ 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, verified_derivation_paths: List[DerivationPath]) -> bool: """ - Compares two policies on the shape of the script they describe: the script type, - plus m-of-n for multisig. - - 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. + 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. + + Note: A multisig's input or output policy can also include the cosigners if + they're supplied in the global xpubs. But this function does not take the + cosigners into account; cosigner information, if provided, is evaluated later. """ + # The outlier: a single sig p2sh output when the inputs are p2sh-p2wpkh. + if ( + self.policy["type"] == "p2sh-p2wpkh" # Input policy criteria + and out_policy["type"] == "p2sh" # Output policy criteria + and "m" not in out_policy # Exclude multisig + and len(out.bip32_derivations) == 1 # Nested single sig pays just one key + and len(verified_derivation_paths) == 1 # And that one key must be ours + ): + return True + + # The usual test: the output's policy has the same shape as the inputs' policy. 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 diff --git a/tests/test_psbt_parser.py b/tests/test_psbt_parser.py index 588dc393e2..40b6ce248a 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -2062,6 +2062,49 @@ 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 pytest.raises(PSBTOutputOwnershipContradictionError): + self._parse(psbt) + + def test_get_cosigners_returns_a_sorted_list(self): """ Two multisig scripts can list the same wallet's keys in different orders, so the From f04675e4a3d8241a5c70a98123c4c322ca706a9f Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Tue, 29 Sep 2026 10:02:11 -0500 Subject: [PATCH 05/48] Narrow bare p2sh candidacy to what the rebuild cannot decide The nested single sig outlier in change candidacy also required the output's one derivation path entry to claim this seed's fingerprint. That kept an output paying our key under another seed's key and fingerprint out of the rebuild, so it was shown as a spend to the user's own address, while the same output with its redeem script present is refused as a contradiction. The rebuild derives our key at the entry's path whatever fingerprint it lists, so the outlier drops the condition and _is_change_candidate drops the verified derivation paths it read for it. The outlier also required exactly one derivation path entry. It only kept out bare p2sh outputs annotated with several keys while omitting their scripts, which no surveyed coordinator emits, and the single sig surplus check now refuses those. The m-of-n exclusion becomes a check that the output omits its redeem script. For an output parsed as plain p2sh the two admit the same outputs, since a supplied multisig redeem script is the only source of an m-of-n there, and the new check states what the outlier is for. New tests refuse an output that pays this seed but lists another key, and pin each of the three remaining conditions: a payment to another wallet of this seed, annotated with our key, stays a spend. --- src/seedsigner/models/psbt_parser.py | 14 +++--- tests/test_psbt_parser.py | 64 ++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 8 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 7c51f94a3e..16741a3d43 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -411,7 +411,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 self._is_change_candidate(out, out_policy, self.verified_output_derivation_paths[i]): + if self._is_change_candidate(out, out_policy): # Begin the extensive work to fully verify whether this output is indeed # change. @@ -708,7 +708,7 @@ def _get_policy(scope, scriptpubkey, xpubs, child_key_derivation_cache: dict | N return policy - def _is_change_candidate(self, out: OutputScope, out_policy: dict, verified_derivation_paths: List[DerivationPath]) -> bool: + def _is_change_candidate(self, out: OutputScope, out_policy: dict) -> bool: """ Determines whether an output is worth the full ownership check in _parse_outputs. @@ -732,15 +732,13 @@ def _is_change_candidate(self, out: OutputScope, out_policy: dict, verified_deri """ # The outlier: a single sig p2sh output when the inputs are p2sh-p2wpkh. if ( - self.policy["type"] == "p2sh-p2wpkh" # Input policy criteria - and out_policy["type"] == "p2sh" # Output policy criteria - and "m" not in out_policy # Exclude multisig - and len(out.bip32_derivations) == 1 # Nested single sig pays just one key - and len(verified_derivation_paths) == 1 # And that one key must be ours + 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 - # The usual test: the output's policy has the same shape as the inputs' policy. + # All other outputs must have the same policy shape as the inputs for field in ("type", "m", "n"): if out_policy.get(field) != self.policy.get(field): return False diff --git a/tests/test_psbt_parser.py b/tests/test_psbt_parser.py index 40b6ce248a..4bb9103adb 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -2105,6 +2105,70 @@ def test__parse__rejects_a_bare_p2sh_output_that_claims_this_seed_but_pays_someo 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) + + with pytest.raises(PSBTOutputOwnershipContradictionError): + 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 From f5cbc18a3c43bebea78aac5921e23686aef422c8 Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Wed, 30 Sep 2026 15:21:32 -0400 Subject: [PATCH 06/48] Restore why change candidacy ignores cosigners Renaming _policy_shape_matches to _is_change_candidate dropped the reason the candidacy test compares shape alone. Without it, adding the cosigners to the comparison reads as a harmless tightening. The old wording named a misannotated fingerprint as what breaks an output's cosigner resolution. Since #1032, _get_cosigners matches each key to a global xpub by derivation path alone and never reads the fingerprint, so the restored note names a misannotated derivation path instead. --- src/seedsigner/models/psbt_parser.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 16741a3d43..501c23ca93 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -728,7 +728,16 @@ def _is_change_candidate(self, out: OutputScope, out_policy: dict) -> bool: Note: A multisig's input or output policy can also include the cosigners if they're supplied in the global xpubs. But this function does not take the - cosigners into account; cosigner information, if provided, is evaluated later. + cosigners into account; comparing the cosigners here 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. + + Cosigner information, if provided, is evaluated later. """ # The outlier: a single sig p2sh output when the inputs are p2sh-p2wpkh. if ( From 5fc0ea624f9eb69af9ab3f05370c8f805772de64 Mon Sep 17 00:00:00 2001 From: newtonick Date: Sun, 4 Oct 2026 22:41:25 -0400 Subject: [PATCH 07/48] Reword PSBTInputAmountVerificationFailedView text based on feedback --- src/seedsigner/views/psbt_views.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index 97f184bec1..5857ae200e 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -711,7 +711,7 @@ def run(self): DireWarningScreen, title=_("Suspicious Transaction"), status_headline=_("Likely an Attack!"), - text=_("The PSBT input amounts cannot be confirmed. The fee shown cannot be trusted."), + text=_("This transaction's input amounts cannot be verified, so its fee cannot be trusted."), button_data=[self.DISCARD], show_back_button=False, ) From 457cef3299547a7433f9d2afd0f8e049499dbd88 Mon Sep 17 00:00:00 2001 From: newtonick Date: Sun, 4 Oct 2026 22:54:06 -0400 Subject: [PATCH 08/48] Trim input amount explanations duplicated outside _verify_input_amounts() --- src/seedsigner/models/psbt_parser.py | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 6e8fe76726..5e4ee01126 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -106,12 +106,7 @@ class PSBTOutputOwnershipContradictionError(PSBTVerificationError): class PSBTInputAmountVerificationError(PSBTVerificationError): """ An input's declared amount could not be verified, so the fee this device would display - cannot be trusted. See PSBTParser._verify_input_amounts(). - - Segwit inputs carrying only a witness_utxo are deliberately NOT rejected: there the - sighash commits the amount, so a lie invalidates the signature rather than burning - funds. _verify_input_amounts() covers why the residual risk (CVE-2020-14199) is accepted - rather than warned about. + cannot be trusted. """ pass @@ -168,8 +163,7 @@ class PSBTParser(): # just stops getting cache hits once the cache is full. MAX_CACHED_DERIVATIONS = 1000 - # Input types whose sighash does NOT commit to the input amount. A lie about the - # input amount still allows a valid signature, so these inputs must supply a non_witness_utxo. + # Input types whose sighash does NOT commit to the input amount. UNCOMMITTED_AMOUNT_SCRIPT_TYPES = [None, "p2pkh", "p2sh"] # Warn when the fee exceeds this percentage of what is being sent (outputs other than From 335c11af2bd6ca66adc1e43ab73d6238897a485c Mon Sep 17 00:00:00 2001 From: newtonick Date: Sun, 4 Oct 2026 23:52:15 -0400 Subject: [PATCH 09/48] Total verified_input_amount in _verify_input_amounts() --- src/seedsigner/models/psbt_parser.py | 29 ++++++++++++++------------- src/seedsigner/views/psbt_views.py | 2 +- tests/test_decodepsbtqr.py | 8 ++++---- tests/test_psbt_parser.py | 30 ++++++++++++++-------------- 4 files changed, 35 insertions(+), 34 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 5e4ee01126..71b8aee6e0 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -181,7 +181,7 @@ def __init__(self, p: PSBT, seed: Seed, network: str = SettingsConstants.MAINNET self.change_amount = 0 self.change_data = [] self.fee_amount = 0 - self.input_amount = 0 + self.verified_input_amount = 0 self.num_inputs = 0 self.destination_addresses = [] self.destination_amounts = [] @@ -246,11 +246,10 @@ def parse(self): inputs can be signed by the seed. A mismatch rather than an attack, caught here so the flow can say so before showing a transaction. - 4. _verify_input_amounts: raises PSBTInputAmountVerificationError when an input's - claimed amount cannot be verified against a non_witness_utxo. Runs after the - ownership checks so a psbt this seed cannot sign is reported as a mismatch - rather than as a suspicious transaction, but before _parse_inputs, which is - where amounts are first summed. + 4. _verify_input_amounts: verifies each input's claimed amount, then totals them + as verified_input_amount. Raises PSBTInputAmountVerificationError if an amount + cannot be verified. Runs after the ownership checks so a psbt this seed cannot + sign is reported as a mismatch rather than as a suspicious transaction. 5. _parse_inputs: every input must resolve to the same policy otherwise a RuntimeError is raised. TODO: make this a PSBTVerificationError subclass so @@ -316,7 +315,7 @@ def parse(self): self._verify_claimed_derivation_paths(child_key_derivation_cache) self._reject_if_seed_cannot_sign() - # Single source of truth for input amounts; raises before any amount is summed + # Single source of truth for input amounts: each is verified before it is totaled self._verify_input_amounts() rt = self._parse_inputs(child_key_derivation_cache) @@ -335,7 +334,7 @@ def parse(self): def _verify_input_amounts(self): """ - Verify each input's declared amount before any of them is summed. Since seedsigner is + Verify each input's declared amount before it is added to the total. Since seedsigner is airgapped, we can't look up what an input is actually worth. We're relying on what the coordinator declared. Unchecked, a compromised coordinator could declare false amounts and have us display any fee it liked. See the miner fee attack described in embit's @@ -361,6 +360,7 @@ def _verify_input_amounts(self): on it would therefore fire on nearly every ordinary multi-input segwit spend and only teach users to click through warnings. """ + verified_input_amount = 0 for i, inp in enumerate(self.psbt.inputs): # Make sure inp.vout, the output this input claims to spend, actually exists in the # non_witness_utxo. Otherwise the lookups below raise an IndexError instead of @@ -382,7 +382,6 @@ def _verify_input_amounts(self): script_type = PSBTParser._get_script_type(inp, inp.script_pubkey) if script_type in PSBTParser.UNCOMMITTED_AMOUNT_SCRIPT_TYPES: raise PSBTInputAmountVerificationError(f"Input {i}: {script_type} input has no non_witness_utxo to verify against") - continue # verify() hashes the non_witness_utxo but never looks at the witness_utxo that may # sit alongside it. embit's PSBT.utxo()/fee() prefer witness_utxo, so a witness_utxo @@ -394,17 +393,19 @@ def _verify_input_amounts(self): if prevout.value != inp.witness_utxo.value or prevout.script_pubkey.data != inp.witness_utxo.script_pubkey.data: raise PSBTInputAmountVerificationError(f"Input {i}: witness_utxo doesn't match verified non_witness_utxo") + verified_input_amount += inp.utxo.value + + # Only assigned once every input has passed, so a rejected psbt leaves no partial total + self.verified_input_amount = verified_input_amount + def _parse_inputs(self, child_key_derivation_cache: dict): """ - Totals the input amounts and determines the wallet policy. Every input must - resolve to the same policy, otherwise a RuntimeError is raised. + Determines the wallet policy. Every input must resolve to the same policy, + otherwise a RuntimeError is raised. """ - self.input_amount = 0 self.num_inputs = len(self.psbt.inputs) for inp in self.psbt.inputs: - # Amounts were verified in _verify_input_amounts() - self.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) diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index 5857ae200e..4ab55c2f67 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -302,7 +302,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, spend_amount=psbt_parser.spend_amount, num_recipients=psbt_parser.num_destinations, diff --git a/tests/test_decodepsbtqr.py b/tests/test_decodepsbtqr.py index 3c86b6a0de..119320b495 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_psbt_parser.py b/tests/test_psbt_parser.py index ea49764286..7dc217f3a3 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -54,13 +54,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 @@ -73,13 +73,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 @@ -97,13 +97,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 @@ -123,13 +123,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 @@ -519,9 +519,9 @@ def test_untampered_psbts_verify(self, psbt_base64: str): is_verified is the assertion that carries the weight here. It is only set by embit's InputScope.verify(), so it is the one flag that distinguishes "we hashed the previous - tx ourselves" from "we took the coordinator's word for it". input_amount alone would - hold with or without _verify_input_amounts(), since _parse_inputs() sums inp.utxo.value - either way. + tx ourselves" from "we took the coordinator's word for it". verified_input_amount + alone can't tell those apart: it is totaled the same way for a segwit input that was + accepted with no non_witness_utxo to hash. """ psbt = self.build_psbt(psbt_base64) assert all(inp.is_verified == False for inp in psbt.inputs) # not verified until we do it @@ -529,7 +529,7 @@ def test_untampered_psbts_verify(self, psbt_base64: str): psbt_parser = self.parse(psbt) assert all(inp.is_verified for inp in psbt.inputs) - assert psbt_parser.input_amount == sum([inp.utxo.value 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) @@ -636,7 +636,7 @@ def test_segwit_input_without_non_witness_utxo_is_allowed(self, psbt_base64: str psbt = self.build_psbt(psbt_base64) psbt.inputs[0].non_witness_utxo = None - assert self.parse(psbt).input_amount == psbt.inputs[0].witness_utxo.value + assert self.parse(psbt).verified_input_amount == psbt.inputs[0].witness_utxo.value def test_input_with_no_utxo_data_raises(self): @@ -689,7 +689,7 @@ def test_every_input_is_checked_not_just_the_first(self): # 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.input_amount == 56_522_834 + 1_990_245_069 + assert psbt_parser.verified_input_amount == 56_522_834 + 1_990_245_069 psbt.inputs[1].non_witness_utxo.vout[0].value += 100_000 @@ -903,7 +903,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 From 6605c68cadd9c2bf7288980b78795643f1756967 Mon Sep 17 00:00:00 2001 From: newtonick Date: Mon, 5 Oct 2026 17:11:15 -0400 Subject: [PATCH 10/48] Add PSBTMissingInputUtxoError for inputs with no utxo to verify --- src/seedsigner/models/psbt_parser.py | 22 ++++++++++---- src/seedsigner/views/psbt_views.py | 38 +++++++++++++++++++++++-- tests/screenshot_generator/generator.py | 1 + tests/test_flows_psbt.py | 24 ++++++++++++++++ tests/test_psbt_parser.py | 11 +++---- 5 files changed, 83 insertions(+), 13 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 71b8aee6e0..3461b4ae17 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -111,6 +111,15 @@ class PSBTInputAmountVerificationError(PSBTVerificationError): pass +class PSBTMissingInputUtxoError(PSBTVerificationError): + """ + An input is missing its utxo, which holds its amount. A psbt supplies the amount in + the witness_utxo or non_witness_utxo field, and without either there is no amount to + verify. This is a correctness problem rather than an attack. + """ + pass + + class PSBTSeedCannotSignError(PSBTVerificationError): """ The selected seed holds no key that could sign any input. @@ -247,9 +256,11 @@ def parse(self): here so the flow can say so before showing a transaction. 4. _verify_input_amounts: verifies each input's claimed amount, then totals them - as verified_input_amount. Raises PSBTInputAmountVerificationError if an amount - cannot be verified. Runs after the ownership checks so a psbt this seed cannot - sign is reported as a mismatch rather than as a suspicious transaction. + as verified_input_amount. Raises PSBTMissingInputUtxoError if an input is + missing the utxo that holds its amount, or PSBTInputAmountVerificationError + if an amount cannot be verified. Runs after the ownership checks so a psbt + this seed cannot sign is reported as a mismatch rather than as a suspicious + transaction. 5. _parse_inputs: every input must resolve to the same policy otherwise a RuntimeError is raised. TODO: make this a PSBTVerificationError subclass so @@ -366,11 +377,12 @@ def _verify_input_amounts(self): # non_witness_utxo. Otherwise the lookups below raise an IndexError instead of # rejecting the psbt. if inp.non_witness_utxo and inp.vout >= len(inp.non_witness_utxo.vout): - raise PSBTInputAmountVerificationError( + raise PSBTMissingInputUtxoError( f"Input {i}: outpoint index {inp.vout} is out of range of its non_witness_utxo") + # Without any utxo data there is no amount to verify or total if inp.utxo is None: - raise PSBTInputAmountVerificationError(f"Input {i} has no utxo data") + raise PSBTMissingInputUtxoError(f"Input {i} has no utxo data") try: verified = inp.verify(ignore_missing=True) diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index 4ab55c2f67..50e55a5214 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -3,9 +3,10 @@ from gettext import gettext as _ from seedsigner.models.psbt_parser import (PSBTInputAmountVerificationError, - PSBTInputOwnershipClaimError, PSBTMixedDerivationPathTypesError, - PSBTOutputOwnershipClaimError, PSBTOutputOwnershipContradictionError, PSBTParser, - PSBTSeedCannotSignError, PSBTSurplusDerivationPathsError) + PSBTInputOwnershipClaimError, PSBTMissingInputUtxoError, + PSBTMixedDerivationPathTypesError, PSBTOutputOwnershipClaimError, + PSBTOutputOwnershipContradictionError, PSBTParser, PSBTSeedCannotSignError, + PSBTSurplusDerivationPathsError) from seedsigner.models.settings import SettingsConstants from seedsigner.gui.components import FontAwesomeIconConstants, GUIConstants, SeedSignerIconConstants from seedsigner.gui.screens.screen import (RET_CODE__BACK_BUTTON, ButtonListScreen, ButtonOption, LargeIconStatusScreen, WarningScreen, DireWarningScreen, QRDisplayScreen) @@ -139,6 +140,10 @@ def __init__(self): self.set_redirect(Destination(PSBTSeedCannotSignView)) return + except PSBTMissingInputUtxoError: + self.set_redirect(Destination(PSBTMissingInputUtxoView, clear_history=True)) + return + except PSBTInputAmountVerificationError as e: # The declared input amounts could not be verified, so the fee we would show is unproven # Set clear_history to disable returning via BACK button. @@ -723,6 +728,33 @@ def run(self): +class PSBTMissingInputUtxoView(View): + """ + Reached when an input is missing the utxo it spends (see PSBTMissingInputUtxoError). + + We view this as a correctness problem rather than an attack. We do not allow the user + to continue, but only give this the "Warning" level. + """ + DISCARD = ButtonOption("Discard transaction") + + def run(self): + self.run_screen( + WarningScreen, + title=_("Transaction Problem"), + status_headline=None, + # TRANSLATOR_NOTE: The transaction/psbt has an error but does not seem to be malicious. + text=_("This transaction left out the amount for one of its inputs."), + button_data=[self.DISCARD], + show_back_button=False, + ) + + # We're done with this PSBT. Route back to MainMenuView, which clears all + # ephemeral data (except in-memory seeds). + # Set clear_history to disable returning via BACK button. + return Destination(MainMenuView, clear_history=True) + + + class PSBTOpReturnView(View): """ Shows the OP_RETURN data diff --git a/tests/screenshot_generator/generator.py b/tests/screenshot_generator/generator.py index e90bf1486a..8fcc56014d 100644 --- a/tests/screenshot_generator/generator.py +++ b/tests/screenshot_generator/generator.py @@ -459,6 +459,7 @@ def mock_version_to_most_recent_release(): ScreenshotConfig(psbt_views.PSBTInputOwnershipClaimFailedView), 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_flows_psbt.py b/tests/test_flows_psbt.py index 0e78b0590c..d078ec055f 100644 --- a/tests/test_flows_psbt.py +++ b/tests/test_flows_psbt.py @@ -353,6 +353,30 @@ 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_wrong_seed_routes_back_to_seed_selection_flow(self): """ The wrong seed for a psbt redirects before any transaction detail is rendered and diff --git a/tests/test_psbt_parser.py b/tests/test_psbt_parser.py index 7dc217f3a3..60bbb5679f 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -13,9 +13,10 @@ from embit.script import Script from seedsigner.models.psbt_parser import (PSBTInputAmountVerificationError, - PSBTInputOwnershipClaimError, PSBTMixedDerivationPathTypesError, - PSBTOutputOwnershipClaimError, PSBTOutputOwnershipContradictionError, PSBTParser, - PSBTSeedCannotSignError, PSBTSurplusDerivationPathsError) + PSBTInputOwnershipClaimError, PSBTMissingInputUtxoError, + PSBTMixedDerivationPathTypesError, PSBTOutputOwnershipClaimError, + PSBTOutputOwnershipContradictionError, PSBTParser, PSBTSeedCannotSignError, + PSBTSurplusDerivationPathsError) from seedsigner.models.seed import Seed from seedsigner.models.settings_definition import SettingsConstants @@ -652,7 +653,7 @@ def test_input_with_no_utxo_data_raises(self): psbt.inputs[0].witness_utxo = None psbt.inputs[0].non_witness_utxo = None - with pytest.raises(PSBTInputAmountVerificationError): + with pytest.raises(PSBTMissingInputUtxoError): self.parse(psbt) @@ -670,7 +671,7 @@ def test_outpoint_index_past_end_of_non_witness_utxo_raises(self): assert inp.vout < len(inp.non_witness_utxo.vout) inp.vout = len(inp.non_witness_utxo.vout) - with pytest.raises(PSBTInputAmountVerificationError): + with pytest.raises(PSBTMissingInputUtxoError): self.parse(psbt) From 5ca043c939f7ad0965d8107849add419e6c2add3 Mon Sep 17 00:00:00 2001 From: newtonick Date: Mon, 5 Oct 2026 17:17:44 -0400 Subject: [PATCH 11/48] Reword the _verify_input_amounts() docstring --- src/seedsigner/models/psbt_parser.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 3461b4ae17..b6344a34a2 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -345,7 +345,7 @@ def parse(self): def _verify_input_amounts(self): """ - Verify each input's declared amount before it is added to the total. Since seedsigner is + Verify each input's declared amount before it is added to the total. Since SeedSigner is airgapped, we can't look up what an input is actually worth. We're relying on what the coordinator declared. Unchecked, a compromised coordinator could declare false amounts and have us display any fee it liked. See the miner fee attack described in embit's @@ -355,21 +355,22 @@ def _verify_input_amounts(self): the coin being spent, so we can hash it and confirm it produces the txid this input claims to spend. A witness_utxo is just the one output, with no such proof. - ignore_missing=True is required: coordinators legitimately and typically supply only - the witness_utxo for segwit inputs, where the sighash commits the input amount. A lie there - invalidates the signature instead of burning funds. Legacy sighashes commit no amount - at all, so legacy inputs must supply a non_witness_utxo. + InputScope.verify() needs ignore_missing=True: coordinators legitimately and typically + supply only the witness_utxo for segwit and taproot inputs, where the sighash commits the + input amount. A lie there invalidates the signature instead of burning funds. Legacy + sighashes commit no amount at all, so legacy inputs must supply a non_witness_utxo. + Raises PSBTInputAmountVerificationError otherwise. Known limitation: that sighash protection is not absolute. BIP-143 commits only the amount of the input being signed, so a coordinator that gets us to sign the same transaction twice can keep one valid signature per session/input and combine them into - a tx that burns the difference as miner fee (CVE-2020-14199). + a tx that burns the difference as miner fee (CVE-2020-14199). Taproot is not affected: + BIP-341 commits the amount of every input. We accept that risk for segwit rather than warn about it, because the data needed to close it isn't coming. Wallets generally provide non_witness_utxo *or* witness_utxo but - not both. This is mainly so psbts stay small for QR-based signers. Warning - on it would therefore fire on nearly every ordinary multi-input segwit spend and only - teach users to click through warnings. + not both, likely to keep psbts small for QR-based signers. Warning on it would therefore + fire on nearly every ordinary multi-input segwit spend. """ verified_input_amount = 0 for i, inp in enumerate(self.psbt.inputs): From 22a4ed43676e0f36b79a8f5f6c927bd054d59429 Mon Sep 17 00:00:00 2001 From: newtonick Date: Mon, 5 Oct 2026 17:25:19 -0400 Subject: [PATCH 12/48] Simplify the outpoint bounds check comment --- src/seedsigner/models/psbt_parser.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index b6344a34a2..6fc28f9d24 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -374,9 +374,8 @@ def _verify_input_amounts(self): """ verified_input_amount = 0 for i, inp in enumerate(self.psbt.inputs): - # Make sure inp.vout, the output this input claims to spend, actually exists in the - # non_witness_utxo. Otherwise the lookups below raise an IndexError instead of - # rejecting the psbt. + # Make sure the output that this input claims to spend (inp.vout) actually exists + # in the non_witness_utxo. if inp.non_witness_utxo and inp.vout >= len(inp.non_witness_utxo.vout): raise PSBTMissingInputUtxoError( f"Input {i}: outpoint index {inp.vout} is out of range of its non_witness_utxo") From 274116675166354eacb84940d499846c83ff5cec Mon Sep 17 00:00:00 2001 From: newtonick Date: Mon, 5 Oct 2026 22:45:53 -0400 Subject: [PATCH 13/48] Clarify the comments around InputScope.verify() --- src/seedsigner/models/psbt_parser.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 6fc28f9d24..8d19ee53f0 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -385,21 +385,24 @@ def _verify_input_amounts(self): raise PSBTMissingInputUtxoError(f"Input {i} has no utxo data") try: + # ignore_missing=True: a missing non_witness_utxo returns False instead of raising verified = inp.verify(ignore_missing=True) except PSBTError as e: + # embit's verify() hashes the non_witness_utxo and raises PSBTError only when that + # hash isn't the txid this input spends: a wrong or altered previous transaction. raise PSBTInputAmountVerificationError(f"Input {i}: {e}") if not verified: - # No non_witness_utxo supplied; only safe if the sighash commits the amount + # embit's verify() with ignore_missing=True returns False only when the input has + # no non_witness_utxo. Raise if the sighash does not commit to the amount: without + # that commitment, the signature would still be valid for a false amount. script_type = PSBTParser._get_script_type(inp, inp.script_pubkey) if script_type in PSBTParser.UNCOMMITTED_AMOUNT_SCRIPT_TYPES: raise PSBTInputAmountVerificationError(f"Input {i}: {script_type} input has no non_witness_utxo to verify against") - # verify() hashes the non_witness_utxo but never looks at the witness_utxo that may - # sit alongside it. embit's PSBT.utxo()/fee() prefer witness_utxo, so a witness_utxo - # that disagrees would still be the value driving our fee. Coordinators that keep - # psbts small send one field or the other, never both, so this only fires on a - # malformed or deliberately crafted psbt. + # With both fields present, compare the witness_utxo to the output this input spends + # in the verified non_witness_utxo. embit's verify() does not compare the two, so + # reject the psbt if their amounts or scripts contradict. if inp.witness_utxo and inp.non_witness_utxo: prevout = inp.non_witness_utxo.vout[inp.vout] if prevout.value != inp.witness_utxo.value or prevout.script_pubkey.data != inp.witness_utxo.script_pubkey.data: From 00ee7714a6033da16f114b89b7d07b5f512b6277 Mon Sep 17 00:00:00 2001 From: newtonick Date: Fri, 16 Oct 2026 23:12:17 -0400 Subject: [PATCH 14/48] Restructure _verify_input_amounts() around non_witness_utxo and reword its comments --- src/seedsigner/models/psbt_parser.py | 75 ++++++++++++++-------------- 1 file changed, 38 insertions(+), 37 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 8d19ee53f0..1b1d9667f3 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -355,16 +355,17 @@ def _verify_input_amounts(self): the coin being spent, so we can hash it and confirm it produces the txid this input claims to spend. A witness_utxo is just the one output, with no such proof. - InputScope.verify() needs ignore_missing=True: coordinators legitimately and typically - supply only the witness_utxo for segwit and taproot inputs, where the sighash commits the - input amount. A lie there invalidates the signature instead of burning funds. Legacy - sighashes commit no amount at all, so legacy inputs must supply a non_witness_utxo. - Raises PSBTInputAmountVerificationError otherwise. + Coordinators typically only supply the witness_utxo for segwit and taproot inputs, where + the sighash commits the input amount. A lie there invalidates the signature instead + of burning funds. Legacy sighashes commit no amount at all, so legacy inputs must + supply a non_witness_utxo, otherwise a PSBTInputAmountVerificationError is raised. Known limitation: that sighash protection is not absolute. BIP-143 commits only the - amount of the input being signed, so a coordinator that gets us to sign the same - transaction twice can keep one valid signature per session/input and combine them into - a tx that burns the difference as miner fee (CVE-2020-14199). Taproot is not affected: + amount of the input being signed. A coordinator who tricks a user into signing the same + multi-input transaction more than once can understate different inputs in each round, + so every round shows a normal-looking fee. It then combines each input's signature from + a round where that input's amount was true, producing a valid transaction whose real + fee is far higher than any round showed (CVE-2020-14199). Taproot is not affected: BIP-341 commits the amount of every input. We accept that risk for segwit rather than warn about it, because the data needed to @@ -374,39 +375,39 @@ def _verify_input_amounts(self): """ verified_input_amount = 0 for i, inp in enumerate(self.psbt.inputs): - # Make sure the output that this input claims to spend (inp.vout) actually exists - # in the non_witness_utxo. - if inp.non_witness_utxo and inp.vout >= len(inp.non_witness_utxo.vout): - raise PSBTMissingInputUtxoError( - f"Input {i}: outpoint index {inp.vout} is out of range of its non_witness_utxo") - - # Without any utxo data there is no amount to verify or total - if inp.utxo is None: - raise PSBTMissingInputUtxoError(f"Input {i} has no utxo data") - - try: - # ignore_missing=True: a missing non_witness_utxo returns False instead of raising - verified = inp.verify(ignore_missing=True) - except PSBTError as e: - # embit's verify() hashes the non_witness_utxo and raises PSBTError only when that - # hash isn't the txid this input spends: a wrong or altered previous transaction. - raise PSBTInputAmountVerificationError(f"Input {i}: {e}") - - if not verified: - # embit's verify() with ignore_missing=True returns False only when the input has - # no non_witness_utxo. Raise if the sighash does not commit to the amount: without - # that commitment, the signature would still be valid for a false amount. + if inp.non_witness_utxo is None: + # Without any utxo data there is no amount to verify or total + if inp.witness_utxo is None: + raise PSBTMissingInputUtxoError(f"Input {i} has no utxo data") + + # Only a witness_utxo, so there is no previous transaction to hash. Raise if the + # sighash does not commit to the amount: without that commitment, the signature + # would still be valid for a false amount. script_type = PSBTParser._get_script_type(inp, inp.script_pubkey) if script_type in PSBTParser.UNCOMMITTED_AMOUNT_SCRIPT_TYPES: raise PSBTInputAmountVerificationError(f"Input {i}: {script_type} input has no non_witness_utxo to verify against") - # With both fields present, compare the witness_utxo to the output this input spends - # in the verified non_witness_utxo. embit's verify() does not compare the two, so - # reject the psbt if their amounts or scripts contradict. - if inp.witness_utxo and inp.non_witness_utxo: - prevout = inp.non_witness_utxo.vout[inp.vout] - if prevout.value != inp.witness_utxo.value or prevout.script_pubkey.data != inp.witness_utxo.script_pubkey.data: - raise PSBTInputAmountVerificationError(f"Input {i}: witness_utxo doesn't match verified non_witness_utxo") + else: + # Make sure inp.vout points to an output that exists in the non_witness_utxo + if inp.vout >= len(inp.non_witness_utxo.vout): + raise PSBTMissingInputUtxoError(f"Input {i}: outpoint index {inp.vout} is out of range of its non_witness_utxo") + + try: + inp.verify() + except PSBTError as e: + # verify() hashes the non_witness_utxo and raises if that hash doesn't match the + # txid this input references, so it isn't the transaction that created this coin. + # The amount the coordinator declared for this input can't be trusted, so we + # treat this as an attack. + raise PSBTInputAmountVerificationError(f"Input {i}: {e}") + + # With both non_witness_utxo and witness_utxo present, compare them. verify() only + # proved the non_witness_utxo, so the witness_utxo must match its output at inp.vout. + # Reject the psbt if their amounts or scripts contradict. + if inp.witness_utxo is not None: + prevout = inp.non_witness_utxo.vout[inp.vout] + if prevout.value != inp.witness_utxo.value or prevout.script_pubkey.data != inp.witness_utxo.script_pubkey.data: + raise PSBTInputAmountVerificationError(f"Input {i}: witness_utxo doesn't match verified non_witness_utxo") verified_input_amount += inp.utxo.value From 67e049ef0a06aec7d0b474a380e0ea26346bed4a Mon Sep 17 00:00:00 2001 From: newtonick Date: Fri, 16 Oct 2026 23:22:42 -0400 Subject: [PATCH 15/48] Remove the psbt_parser reset from the input verification failure handler --- src/seedsigner/views/psbt_views.py | 1 - tests/test_flows_psbt.py | 44 +----------------------------- 2 files changed, 1 insertion(+), 44 deletions(-) diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index 50e55a5214..c16c6c9f4a 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -148,7 +148,6 @@ def __init__(self): # The declared input amounts could not be verified, so the fee we would show is unproven # Set clear_history to disable returning via BACK button. logger.error(f"PSBT input amount verification failed: {e}") - self.controller.psbt_parser = None self.set_redirect(Destination(PSBTInputAmountVerificationFailedView, clear_history=True)) return diff --git a/tests/test_flows_psbt.py b/tests/test_flows_psbt.py index d078ec055f..61bf653800 100644 --- a/tests/test_flows_psbt.py +++ b/tests/test_flows_psbt.py @@ -1,15 +1,13 @@ from binascii import a2b_base64 -from unittest.mock import Mock from embit import bip32, script from embit.psbt import PSBT, DerivationPath -from base import BaseTest, FlowTest, FlowStep +from base import FlowTest, FlowStep from psbt_testing_util import (PSBTTestData, claim_seed_owns_key, create_output, foreign_public_key, root_for_seed) from seedsigner.controller import Controller -from seedsigner.models.psbt_parser import PSBTParser from seedsigner.views.view import MainMenuView from seedsigner.views import scan_views, seed_views, psbt_views from seedsigner.models.seed import Seed @@ -398,43 +396,3 @@ 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 - - - -class TestPSBTOverviewView(BaseTest): - """ - View-level tests for the parts of PSBTOverviewView that a FlowTest can't reach. - """ - - def test_stale_psbt_parser_is_cleared_on_input_verification_failure(self): - """ - The error handler nulls controller.psbt_parser so an unusable parser can't be left - behind for a later view to read a fee from. - - This is defensive: ScanView already nulls psbt_parser whenever it sets a new psbt - (scan_views.py), so no real flow reaches PSBTOverviewView with a stale parser in - place. That's precisely why this is tested here and not in a flow — the state has to - be constructed by hand, and asserting it inside a flow would only ever be checking - ScanView's cleanup rather than the handler's. - """ - self.settings.set_value(SettingsConstants.SETTING__NETWORK, SettingsConstants.REGTEST) - - psbt = PSBT.parse(a2b_base64(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_2_INPUTS)) - psbt.inputs[0].non_witness_utxo.vout[0].value += 100_000 - - self.controller.psbt = psbt - self.controller.psbt_seed = PSBTTestData.two_input_seed - - # Stand in for a parser left over from a previously-viewed psbt. Its seed differs from - # psbt_seed, so PSBTOverviewView will re-parse rather than reuse it. - self.controller.psbt_parser = Mock(spec=PSBTParser, seed=PSBTTestData.seed) - assert self.controller.psbt_parser.seed != self.controller.psbt_seed - - view = psbt_views.PSBTOverviewView() - - assert self.controller.psbt_parser is None - - # The view redirects away from the overview rather than rendering an unproven fee. - # Destination._run_view() honors this before run() is ever called. - assert view.has_redirect - assert view.get_redirect().View_cls is psbt_views.PSBTInputAmountVerificationFailedView From 5bfbe0b25a81698b73225bbea11def95b13c8207 Mon Sep 17 00:00:00 2001 From: newtonick Date: Fri, 16 Oct 2026 23:28:11 -0400 Subject: [PATCH 16/48] Reword PSBTMissingInputUtxoView text based on feedback --- src/seedsigner/views/psbt_views.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index c16c6c9f4a..567a0c55cd 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -742,7 +742,7 @@ def run(self): title=_("Transaction Problem"), status_headline=None, # TRANSLATOR_NOTE: The transaction/psbt has an error but does not seem to be malicious. - text=_("This transaction left out the amount for one of its inputs."), + text=_("This transaction is missing required data for one of its inputs."), button_data=[self.DISCARD], show_back_button=False, ) From efc92cac86e2d096eb22e4df624340afa4f064eb Mon Sep 17 00:00:00 2001 From: newtonick Date: Fri, 16 Oct 2026 23:41:54 -0400 Subject: [PATCH 17/48] Reword the PSBTInputAmountVerificationError, parse() and _get_script_type() docstrings --- src/seedsigner/models/psbt_parser.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 1b1d9667f3..c3cc2a1e41 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -105,8 +105,13 @@ class PSBTOutputOwnershipContradictionError(PSBTVerificationError): class PSBTInputAmountVerificationError(PSBTVerificationError): """ - An input's declared amount could not be verified, so the fee this device would display - cannot be trusted. + An input's declared amount is unproven or false, so the fee displayed cannot be trusted. + It's one of these: + * The input has no non_witness_utxo and its sighash doesn't commit to its amount. + * The input's non_witness_utxo doesn't hash to the txid the input references. + * The input's witness_utxo contradicts the verified non_witness_utxo. + + We treat any of these as an attack. """ pass @@ -258,9 +263,7 @@ def parse(self): 4. _verify_input_amounts: verifies each input's claimed amount, then totals them as verified_input_amount. Raises PSBTMissingInputUtxoError if an input is missing the utxo that holds its amount, or PSBTInputAmountVerificationError - if an amount cannot be verified. Runs after the ownership checks so a psbt - this seed cannot sign is reported as a mismatch rather than as a suspicious - transaction. + if an amount is unproven or false. 5. _parse_inputs: every input must resolve to the same policy otherwise a RuntimeError is raised. TODO: make this a PSBTVerificationError subclass so @@ -757,10 +760,7 @@ def sig_count(tx): @staticmethod def _get_script_type(scope, scriptpubkey) -> str: - """ - Disambiguate the scriptpubkey's type. Cheap: pattern-matches bytes and derives - nothing, so it's safe to call before an input's amounts have been verified. - """ + """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 From 9b608437a932e28d4d33f18e59c4926e86b06743 Mon Sep 17 00:00:00 2001 From: Nick Klockenga Date: Mon, 19 Oct 2026 22:09:21 -0400 Subject: [PATCH 18/48] Apply suggestion from @kdmukai Co-authored-by: kdmukai <934746+kdmukai@users.noreply.github.com> --- src/seedsigner/models/psbt_parser.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index c3cc2a1e41..7e71fbe7d4 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -396,12 +396,13 @@ def _verify_input_amounts(self): raise PSBTMissingInputUtxoError(f"Input {i}: outpoint index {inp.vout} is out of range of its non_witness_utxo") try: + # verify() checks that the provided non_witness_utxo matches the txid this + # input spends. inp.verify() except PSBTError as e: - # verify() hashes the non_witness_utxo and raises if that hash doesn't match the - # txid this input references, so it isn't the transaction that created this coin. - # The amount the coordinator declared for this input can't be trusted, so we - # treat this as an attack. + # The provided non_witness_utxo is not the transaction that created this coin. + # As a result, we cannot trust the psbt's claims about the amount this input spends. + # We treat this as an attack. raise PSBTInputAmountVerificationError(f"Input {i}: {e}") # With both non_witness_utxo and witness_utxo present, compare them. verify() only From 698ae384e0fa38df074513636bfb9d73bbb9500e Mon Sep 17 00:00:00 2001 From: Nick Klockenga Date: Mon, 19 Oct 2026 22:09:33 -0400 Subject: [PATCH 19/48] Apply suggestion from @kdmukai Co-authored-by: kdmukai <934746+kdmukai@users.noreply.github.com> --- src/seedsigner/models/psbt_parser.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 7e71fbe7d4..629fef0404 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -379,8 +379,9 @@ def _verify_input_amounts(self): verified_input_amount = 0 for i, inp in enumerate(self.psbt.inputs): if inp.non_witness_utxo is None: - # Without any utxo data there is no amount to verify or total if inp.witness_utxo is None: + # We have no utxo data at all. This PSBT is invalid: it tries to spend an + # input whose source coin/value is completely unknown and unverifiable. raise PSBTMissingInputUtxoError(f"Input {i} has no utxo data") # Only a witness_utxo, so there is no previous transaction to hash. Raise if the From 4dcdcfa8a54af616e54f27c7df140371cfca14f2 Mon Sep 17 00:00:00 2001 From: newtonick Date: Mon, 19 Oct 2026 22:17:01 -0400 Subject: [PATCH 20/48] Tidy the comments at the end of _verify_input_amounts() --- src/seedsigner/models/psbt_parser.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 629fef0404..24032c8d9c 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -408,12 +408,13 @@ def _verify_input_amounts(self): # With both non_witness_utxo and witness_utxo present, compare them. verify() only # proved the non_witness_utxo, so the witness_utxo must match its output at inp.vout. - # Reject the psbt if their amounts or scripts contradict. if inp.witness_utxo is not None: prevout = inp.non_witness_utxo.vout[inp.vout] if prevout.value != inp.witness_utxo.value or prevout.script_pubkey.data != inp.witness_utxo.script_pubkey.data: + # The amounts or scripts contradict. Reject the psbt. raise PSBTInputAmountVerificationError(f"Input {i}: witness_utxo doesn't match verified non_witness_utxo") + # Every check passed, so this input amount is verified verified_input_amount += inp.utxo.value # Only assigned once every input has passed, so a rejected psbt leaves no partial total From 34b881a36c6d68179fe78d97bcef3bcb88f3d126 Mon Sep 17 00:00:00 2001 From: Nick Klockenga Date: Mon, 19 Oct 2026 22:34:20 -0400 Subject: [PATCH 21/48] Apply suggestion from @kdmukai Co-authored-by: kdmukai <934746+kdmukai@users.noreply.github.com> --- tests/test_psbt_parser.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/test_psbt_parser.py b/tests/test_psbt_parser.py index 60bbb5679f..557fc7eb26 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -589,9 +589,11 @@ def test_witness_utxo_script_pubkey_disagreeing_with_non_witness_utxo_raises(sel @pytest.mark.parametrize("psbt_base64", LEGACY_INPUTS) def test_legacy_input_without_non_witness_utxo_raises(self, psbt_base64: str): """ - The concrete fund-loss case: a legacy sighash commits no input amount, so an inflated - witness_utxo yields a *valid* signature on a transaction that burns the difference as - miner fee. With no non_witness_utxo to check against, we have to refuse. + 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] From ec5113615ad734337696239ab9bd34945948f719 Mon Sep 17 00:00:00 2001 From: Nick Klockenga Date: Mon, 19 Oct 2026 22:35:06 -0400 Subject: [PATCH 22/48] Apply suggestion from @kdmukai Co-authored-by: kdmukai <934746+kdmukai@users.noreply.github.com> --- tests/test_psbt_parser.py | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/tests/test_psbt_parser.py b/tests/test_psbt_parser.py index 557fc7eb26..b1dc24515d 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -1314,14 +1314,19 @@ def test__parse__verified_derivation_paths_none_for_not_owned_input(self): """ psbt = self._psbt_with_change() - # The other party's input: their utxo, carrying no derivation info. Witness-only, - # as a real payjoin counterparty's input is — the deepcopy's non_witness_utxo - # describes this seed's coin and would contradict the witness_utxo rewritten below. - foreign_input = deepcopy(psbt.inputs[0]) - foreign_input.bip32_derivations.clear() - foreign_input.non_witness_utxo = None - foreign_input.witness_utxo.script_pubkey = script.p2wpkh(foreign_public_key()) - psbt.inputs.append(foreign_input) +# Build the other party's input, starting from a copy of our input: +foreign_input = deepcopy(psbt.inputs[0]) + +# A payjoin counterparty's input would not have derivation path info +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()) + +# We can't let this copy's original non_witness_utxo contradict the witness_utxo we just altered. +foreign_input.non_witness_utxo = None + +psbt.inputs.append(foreign_input) # The payjoin shape psbt_parser = self._parse(psbt) From d4acbf341246819f9881262d64886a35104b35d7 Mon Sep 17 00:00:00 2001 From: Nick Klockenga Date: Mon, 19 Oct 2026 22:36:44 -0400 Subject: [PATCH 23/48] Apply suggestion from @kdmukai Co-authored-by: kdmukai <934746+kdmukai@users.noreply.github.com> --- tests/test_psbt_parser.py | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/tests/test_psbt_parser.py b/tests/test_psbt_parser.py index b1dc24515d..fae25435ea 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -2509,13 +2509,11 @@ def p2pk(public_key: PublicKey) -> script.Script: assert psbt.inputs[0].witness_utxo.script_pubkey.script_type() is None assert psbt.outputs[0].script_pubkey.script_type() is None - # An unrecognized script type with no non_witness_utxo to prove its amount is - # exactly what _verify_input_amounts() now refuses, and editing the - # non_witness_utxo to pay to this p2pk script is not an option either: that - # changes the txid it hashes to. So this psbt can no longer reach _parse_inputs on - # its own; see test_unrecognized_script_type_without_non_witness_utxo_raises for - # that rejection. The catch-all safety check is still worth asserting, so stub out - # the amount verification that now precedes it. - with patch.object(PSBTParser, "_verify_input_amounts"): - with pytest.raises(RuntimeError, match="Unsupported policy type"): - self._parse(psbt) + # The parse verifies input amounts before the scriptPubKey rebuild, so give this + # p2pk coin a matching non_witness_utxo and point the input at its new txid. + inp = psbt.inputs[0] + inp.non_witness_utxo.vout[inp.vout].script_pubkey = inp.witness_utxo.script_pubkey + inp.txid = inp.non_witness_utxo.txid() + + with pytest.raises(RuntimeError, match="Unsupported policy type"): + self._parse(psbt) From ee853c39e73f099b92e4311b55fd98b870a95b79 Mon Sep 17 00:00:00 2001 From: newtonick Date: Mon, 19 Oct 2026 22:38:35 -0400 Subject: [PATCH 24/48] correct indentation --- tests/test_psbt_parser.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/tests/test_psbt_parser.py b/tests/test_psbt_parser.py index fae25435ea..ca047ac82b 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -1314,19 +1314,19 @@ def test__parse__verified_derivation_paths_none_for_not_owned_input(self): """ psbt = self._psbt_with_change() -# Build the other party's input, starting from a copy of our input: -foreign_input = deepcopy(psbt.inputs[0]) + # Build the other party's input, starting from a copy of our input: + foreign_input = deepcopy(psbt.inputs[0]) -# A payjoin counterparty's input would not have derivation path info -foreign_input.bip32_derivations.clear() + # A payjoin counterparty's input would not have derivation path info + 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()) + # Alter the input so it's owned by the other party + foreign_input.witness_utxo.script_pubkey = script.p2wpkh(foreign_public_key()) -# We can't let this copy's original non_witness_utxo contradict the witness_utxo we just altered. -foreign_input.non_witness_utxo = None + # We can't let this copy's original non_witness_utxo contradict the witness_utxo we just altered. + foreign_input.non_witness_utxo = None -psbt.inputs.append(foreign_input) + psbt.inputs.append(foreign_input) # The payjoin shape psbt_parser = self._parse(psbt) From a71b7b391c2624aabfea02ef6bd7b7c18ecdd6cc Mon Sep 17 00:00:00 2001 From: newtonick Date: Mon, 19 Oct 2026 22:44:00 -0400 Subject: [PATCH 25/48] Replace the parse() test helper with direct PSBTParser calls --- tests/test_psbt_parser.py | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/tests/test_psbt_parser.py b/tests/test_psbt_parser.py index ca047ac82b..a3c0ed36c7 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -509,10 +509,6 @@ def build_psbt(self, psbt_base64: str) -> PSBT: return psbt - def parse(self, psbt: PSBT) -> PSBTParser: - return PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) - - @pytest.mark.parametrize("psbt_base64", PSBTTestData.ALL_INPUTS) def test_untampered_psbts_verify(self, psbt_base64: str): """ @@ -527,7 +523,7 @@ def test_untampered_psbts_verify(self, psbt_base64: str): psbt = self.build_psbt(psbt_base64) assert all(inp.is_verified == False for inp in psbt.inputs) # not verified until we do it - psbt_parser = self.parse(psbt) + 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]) @@ -543,7 +539,7 @@ def test_tampered_non_witness_utxo_raises(self, psbt_base64: str): psbt.inputs[0].non_witness_utxo.vout[0].value += 100_000 with pytest.raises(PSBTInputAmountVerificationError): - self.parse(psbt) + PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) @pytest.mark.parametrize("psbt_base64", WITNESS_UTXO_INPUTS) @@ -560,7 +556,7 @@ def test_witness_utxo_value_disagreeing_with_non_witness_utxo_raises(self, psbt_ assert psbt.inputs[0].verify() == True with pytest.raises(PSBTInputAmountVerificationError): - self.parse(psbt) + PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) @pytest.mark.parametrize("psbt_base64", WITNESS_UTXO_INPUTS) @@ -583,7 +579,7 @@ def test_witness_utxo_script_pubkey_disagreeing_with_non_witness_utxo_raises(sel assert psbt.inputs[0].verify() == True with pytest.raises(PSBTInputAmountVerificationError): - self.parse(psbt) + PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) @pytest.mark.parametrize("psbt_base64", LEGACY_INPUTS) @@ -602,7 +598,7 @@ def test_legacy_input_without_non_witness_utxo_raises(self, psbt_base64: str): inp.non_witness_utxo = None with pytest.raises(PSBTInputAmountVerificationError): - self.parse(psbt) + PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) def test_unrecognized_script_type_without_non_witness_utxo_raises(self): @@ -626,7 +622,7 @@ def test_unrecognized_script_type_without_non_witness_utxo_raises(self): assert inp.witness_utxo.script_pubkey.script_type() is None with pytest.raises(PSBTInputAmountVerificationError): - self.parse(psbt) + PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) @pytest.mark.parametrize("psbt_base64", WITNESS_UTXO_INPUTS) @@ -639,7 +635,9 @@ def test_segwit_input_without_non_witness_utxo_is_allowed(self, psbt_base64: str psbt = self.build_psbt(psbt_base64) psbt.inputs[0].non_witness_utxo = None - assert self.parse(psbt).verified_input_amount == psbt.inputs[0].witness_utxo.value + # 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 def test_input_with_no_utxo_data_raises(self): @@ -656,7 +654,7 @@ def test_input_with_no_utxo_data_raises(self): psbt.inputs[0].non_witness_utxo = None with pytest.raises(PSBTMissingInputUtxoError): - self.parse(psbt) + PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) def test_outpoint_index_past_end_of_non_witness_utxo_raises(self): @@ -674,7 +672,7 @@ def test_outpoint_index_past_end_of_non_witness_utxo_raises(self): inp.vout = len(inp.non_witness_utxo.vout) with pytest.raises(PSBTMissingInputUtxoError): - self.parse(psbt) + PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) def test_every_input_is_checked_not_just_the_first(self): From 222bf3d551deafc1219db67960e004a452e8d366 Mon Sep 17 00:00:00 2001 From: newtonick Date: Mon, 19 Oct 2026 22:51:03 -0400 Subject: [PATCH 26/48] Tighten the input-amount test asserts and run the no-utxo test over every fixture --- tests/test_psbt_parser.py | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/tests/test_psbt_parser.py b/tests/test_psbt_parser.py index a3c0ed36c7..93551e1ceb 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -521,7 +521,7 @@ def test_untampered_psbts_verify(self, psbt_base64: str): accepted with no non_witness_utxo to hash. """ psbt = self.build_psbt(psbt_base64) - assert all(inp.is_verified == False for inp in psbt.inputs) # not verified until we do it + 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) @@ -553,7 +553,7 @@ def test_witness_utxo_value_disagreeing_with_non_witness_utxo_raises(self, psbt_ 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() == True + assert psbt.inputs[0].verify() is True with pytest.raises(PSBTInputAmountVerificationError): PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) @@ -575,8 +575,10 @@ def test_witness_utxo_script_pubkey_disagreeing_with_non_witness_utxo_raises(sel 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 psbt.inputs[0].verify() == True + assert witness_utxo.script_pubkey.data != prevout.script_pubkey.data + assert psbt.inputs[0].verify() is True with pytest.raises(PSBTInputAmountVerificationError): PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST) @@ -613,9 +615,12 @@ def test_unrecognized_script_type_without_non_witness_utxo_raises(self): # 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(b"\x51\x21" + pubkey + b"\x51\xae") + 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 @@ -640,16 +645,14 @@ def test_segwit_input_without_non_witness_utxo_is_allowed(self, psbt_base64: str assert psbt_parser.verified_input_amount == psbt.inputs[0].witness_utxo.value - def test_input_with_no_utxo_data_raises(self): + @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. Without this guard _get_policy() is handed a None script_pubkey and dies with an AttributeError instead of an error the caller can route on. - - One fixture is enough: this is the first check in the loop, and once utxo is None the - input's script_pubkey is None too, so no script type can reach it differently. """ - psbt = self.build_psbt(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_1_INPUT) + psbt = self.build_psbt(psbt_base64) psbt.inputs[0].witness_utxo = None psbt.inputs[0].non_witness_utxo = None From afb7305a2324ae14f2c785104ef37517464cea85 Mon Sep 17 00:00:00 2001 From: newtonick Date: Mon, 19 Oct 2026 23:14:38 -0400 Subject: [PATCH 27/48] Trim the input-amount verification test docstrings --- tests/test_psbt_parser.py | 43 ++++++++++++++++----------------------- 1 file changed, 17 insertions(+), 26 deletions(-) diff --git a/tests/test_psbt_parser.py b/tests/test_psbt_parser.py index 93551e1ceb..59f48b2389 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -512,13 +512,9 @@ def build_psbt(self, psbt_base64: str) -> PSBT: @pytest.mark.parametrize("psbt_base64", PSBTTestData.ALL_INPUTS) def test_untampered_psbts_verify(self, psbt_base64: str): """ - Every supported script type's fixture carries a verifiable non_witness_utxo. - - is_verified is the assertion that carries the weight here. It is only set by embit's - InputScope.verify(), so it is the one flag that distinguishes "we hashed the previous - tx ourselves" from "we took the coordinator's word for it". verified_input_amount - alone can't tell those apart: it is totaled the same way for a segwit input that was - accepted with no non_witness_utxo to hash. + 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 @@ -532,10 +528,13 @@ def test_untampered_psbts_verify(self, psbt_base64: str): @pytest.mark.parametrize("psbt_base64", PSBTTestData.ALL_INPUTS) def test_tampered_non_witness_utxo_raises(self, psbt_base64: str): """ - Editing the non_witness_utxo changes the txid it hashes to, so it no longer matches - the txid the input claims to spend. + 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 pytest.raises(PSBTInputAmountVerificationError): @@ -562,10 +561,9 @@ def test_witness_utxo_value_disagreeing_with_non_witness_utxo_raises(self, psbt_ @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 other half of the cross-check: same amount, different scriptPubKey. Nothing about - the fee changes, but InputScope.script_pubkey resolves to the witness_utxo's, which is - what _parse_inputs() hands to _get_policy(). A mismatched scriptPubKey therefore means - we'd report the wrong script type for a coin we never actually inspected. + 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 @@ -648,9 +646,7 @@ def test_segwit_input_without_non_witness_utxo_is_allowed(self, psbt_base64: str @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. Without this - guard _get_policy() is handed a None script_pubkey and dies with an AttributeError - instead of an error the caller can route on. + Nothing to verify against and nothing to sum; refuse rather than guess. """ psbt = self.build_psbt(psbt_base64) psbt.inputs[0].witness_utxo = None @@ -662,10 +658,9 @@ def test_input_with_no_utxo_data_raises(self, psbt_base64: str): def test_outpoint_index_past_end_of_non_witness_utxo_raises(self): """ - embit's verify() only compares txids and never checks that vout indexes into the - non_witness_utxo it just hashed, so a genuine prev tx paired with an out-of-range - outpoint passes verification. Unguarded, the deref raises a bare IndexError that - escapes parse() and crashes the view instead of routing to a warning. + 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] @@ -680,12 +675,8 @@ def test_outpoint_index_past_end_of_non_witness_utxo_raises(self): def test_every_input_is_checked_not_just_the_first(self): """ - Every fixture above has a single input, so none of them can catch a check that stops - after input 0. Tampering the *second* input of a 2-input psbt must fail just as loudly, - and the error must name the input that actually failed. - - Tampering input 0 is deliberately not covered here; that is exactly what - test_tampered_non_witness_utxo_raises already does across all seven script types. + 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 From 9b810ba963757d6d347d617e5dcb1f9a4b9c9932 Mon Sep 17 00:00:00 2001 From: okaybro <66475772+Chaitanya-Keyal@users.noreply.github.com> Date: Sat, 19 Sep 2026 03:40:32 +0530 Subject: [PATCH 28/48] Reject psbts whose outputs exceed their inputs embit computes the fee as inputs minus outputs and never looks at the sign of the result, so a psbt that spends more than it funds parses cleanly and reaches the review flow quoting a negative fee. Raise PSBTNegativeFeeError as soon as the fee is known and route it to its own warning. Malformed rather than hostile: no honest coordinator builds one and the network would refuse to relay it, so it gets a plain warning, not the attack framing. A zero fee is still accepted. --- src/seedsigner/models/psbt_parser.py | 25 ++++++++++++++++++- src/seedsigner/views/psbt_views.py | 32 ++++++++++++++++++++++++- tests/screenshot_generator/generator.py | 1 + tests/test_flows_psbt.py | 25 ++++++++++++++++--- tests/test_psbt_parser.py | 31 +++++++++++++++++++++++- 5 files changed, 108 insertions(+), 6 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index ec2a60eb74..f81c5925b9 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -136,6 +136,21 @@ class PSBTSeedCannotSignError(PSBTVerificationError): pass +class PSBTNegativeFeeError(PSBTVerificationError): + """ + The outputs spend more than the inputs bring in, so the fee is negative. + + Treated as malformed data rather than an attack. No honest coordinator builds one, + and a coordinator lying about its input amounts wants the fee it shows us to look + small, not impossible. Note that the amounts on both sides of that subtraction are + the coordinator's claims, so a negative result only establishes that the arithmetic + cannot be trusted, not which side of it is false. Either way nothing is signed here. + It is raised because the alternative is walking the user through a review that quotes + a negative fee. + """ + pass + + class PSBTParser(): """ Reads a psbt on behalf of one seed and works out everything the signing flow shows the @@ -288,7 +303,8 @@ def parse(self): - multisig: Match each of the seed's verified keys against the pubkeys in the script the output commits to. Every change_data entry after this point will carry a derivation path that - our seed provably owns. + our seed provably owns. Raises PSBTNegativeFeeError if the outputs spend more + than the inputs bring in. Optimization via child_key_derivation_cache: Parsing traverses a derivation path down to an individual address one level at a @@ -732,7 +748,14 @@ 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. A negative fee means the outputs claim more than the inputs fund, + # which no valid transaction can do. 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: + raise PSBTNegativeFeeError() + return True diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index 567a0c55cd..49e04b858e 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -4,7 +4,7 @@ from seedsigner.models.psbt_parser import (PSBTInputAmountVerificationError, PSBTInputOwnershipClaimError, PSBTMissingInputUtxoError, - PSBTMixedDerivationPathTypesError, PSBTOutputOwnershipClaimError, + PSBTMixedDerivationPathTypesError, PSBTNegativeFeeError, PSBTOutputOwnershipClaimError, PSBTOutputOwnershipContradictionError, PSBTParser, PSBTSeedCannotSignError, PSBTSurplusDerivationPathsError) from seedsigner.models.settings import SettingsConstants @@ -132,6 +132,10 @@ def __init__(self): self.set_redirect(Destination(PSBTOutputOwnershipContradictionView, clear_history=True)) return + except PSBTNegativeFeeError: + self.set_redirect(Destination(PSBTNegativeFeeView, clear_history=True)) + return + except PSBTSeedCannotSignError: # Not a suspicious psbt, just the wrong seed for it. Send the user back to # pick another rather than clearing the flow. @@ -668,6 +672,32 @@ def run(self): +class PSBTNegativeFeeView(View): + """ + Reached when a psbt's outputs spend more than its inputs bring in (see + PSBTNegativeFeeError). Malformed rather than hostile, so it shows a plain (not dire) + warning and discards the psbt to the main menu. + """ + DISCARD = ButtonOption("Discard transaction") + + def run(self): + self.run_screen( + WarningScreen, + title=_("Transaction Problem"), + status_headline=None, + # TRANSLATOR_NOTE: The transaction's outputs spend more than its inputs hold, which is impossible. + text=_("This transaction's outputs send more than its inputs provide."), + button_data=[self.DISCARD], + show_back_button=False, + ) + + # We're done with this PSBT. Route back to MainMenuView, which clears all ephemeral + # data (except in-memory seeds). + # Set clear_history to disable returning via BACK button. + return Destination(MainMenuView, clear_history=True) + + + class PSBTAddressVerificationFailedView(View): """ Reached from PSBTChangeDetailsView when a multisig change or self-transfer output diff --git a/tests/screenshot_generator/generator.py b/tests/screenshot_generator/generator.py index 8fcc56014d..c9a471103a 100644 --- a/tests/screenshot_generator/generator.py +++ b/tests/screenshot_generator/generator.py @@ -457,6 +457,7 @@ def mock_version_to_most_recent_release(): ScreenshotConfig(psbt_views.PSBTAddressVerificationFailedView, dict(is_change=False), 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), diff --git a/tests/test_flows_psbt.py b/tests/test_flows_psbt.py index 61bf653800..8a4375988e 100644 --- a/tests/test_flows_psbt.py +++ b/tests/test_flows_psbt.py @@ -208,9 +208,10 @@ def load_seed_into_decoder(view: scan_views.ScanView): class TestPSBTOwnershipClaimRouting(FlowTest): """ - A psbt whose own description of itself does not hold up 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. + 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): @@ -396,3 +397,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 f47f5e37b9..377d749f72 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -14,7 +14,7 @@ from seedsigner.models.psbt_parser import (PSBTInputAmountVerificationError, PSBTInputOwnershipClaimError, PSBTMissingInputUtxoError, - PSBTMixedDerivationPathTypesError, PSBTOutputOwnershipClaimError, + PSBTMixedDerivationPathTypesError, PSBTNegativeFeeError, PSBTOutputOwnershipClaimError, PSBTOutputOwnershipContradictionError, PSBTParser, PSBTSeedCannotSignError, PSBTSurplusDerivationPathsError) from seedsigner.models.seed import Seed @@ -2673,3 +2673,32 @@ def p2pk(public_key: PublicKey) -> script.Script: with pytest.raises(RuntimeError, match="Unsupported policy type"): 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 pytest.raises(PSBTNegativeFeeError): + 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 From fdcf21bbf3e02d139c85bd0dc395aa4db9eaffec Mon Sep 17 00:00:00 2001 From: okaybro <66475772+Chaitanya-Keyal@users.noreply.github.com> Date: Tue, 29 Sep 2026 22:08:05 +0530 Subject: [PATCH 29/48] style: restore the blank lines between the psbt parser tests --- tests/test_psbt_parser.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/test_psbt_parser.py b/tests/test_psbt_parser.py index 377d749f72..72bf11f936 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -2673,6 +2673,8 @@ def p2pk(public_key: PublicKey) -> script.Script: with pytest.raises(RuntimeError, match="Unsupported policy type"): 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` From bf5146e69b6a72977df85229fcb4e83b3e3f23bc Mon Sep 17 00:00:00 2001 From: okaybro <66475772+Chaitanya-Keyal@users.noreply.github.com> Date: Mon, 5 Oct 2026 00:28:11 +0530 Subject: [PATCH 30/48] Keep PSBTNegativeFeeError's docstring to what a caller needs The error's docstring argued about a lying coordinator's motives and why the error exists for the user. Like the other PSBTVerificationError subclasses, it now just states the problem and that it is not treated as an attack. The one part of the reasoning that matters, that both totals are the coordinator's own claims, moves to the check that raises it. --- src/seedsigner/models/psbt_parser.py | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index f81c5925b9..ef4ce10c81 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -140,13 +140,8 @@ class PSBTNegativeFeeError(PSBTVerificationError): """ The outputs spend more than the inputs bring in, so the fee is negative. - Treated as malformed data rather than an attack. No honest coordinator builds one, - and a coordinator lying about its input amounts wants the fee it shows us to look - small, not impossible. Note that the amounts on both sides of that subtraction are - the coordinator's claims, so a negative result only establishes that the arithmetic - cannot be trusted, not which side of it is false. Either way nothing is signed here. - It is raised because the alternative is walking the user through a review that quotes - a negative fee. + This is a malformed psbt rather than a proven deception, so we do not treat it as an + attack. """ pass @@ -750,8 +745,9 @@ def _parse_outputs(self, child_key_derivation_cache: dict): # embit computes the fee as inputs minus outputs and does not look at the sign of # the result. A negative fee means the outputs claim more than the inputs fund, - # which no valid transaction can do. Zero is left alone: it is a pointless - # transaction, but not a malformed one. + # which no valid transaction can do. Both totals are the coordinator's own claims, + # so this proves the psbt is malformed but not which side is false. 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: raise PSBTNegativeFeeError() From 9994a04e036aaa56a9bb420768ae1485f41809b3 Mon Sep 17 00:00:00 2001 From: okaybro <66475772+Chaitanya-Keyal@users.noreply.github.com> Date: Thu, 22 Oct 2026 02:15:47 +0530 Subject: [PATCH 31/48] Drop the negative fee comment's claim that both totals are unverified _verify_input_amounts() now checks every input's amount before the outputs are parsed, so the input total is no longer just the coordinator's claim. --- src/seedsigner/models/psbt_parser.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index ef4ce10c81..1d9fff42b8 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -744,10 +744,9 @@ def _parse_outputs(self, child_key_derivation_cache: dict): self.spend_amount += vout[i].value # embit computes the fee as inputs minus outputs and does not look at the sign of - # the result. A negative fee means the outputs claim more than the inputs fund, - # which no valid transaction can do. Both totals are the coordinator's own claims, - # so this proves the psbt is malformed but not which side is false. Zero is left - # alone: it is a pointless transaction, but not a malformed one. + # the result. A negative fee means the outputs spend more than the inputs hold, + # which no valid transaction can do. 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: raise PSBTNegativeFeeError() From 7ecc8d9925ec52596e8201a02a41337f151948d1 Mon Sep 17 00:00:00 2001 From: okaybro <66475772+Chaitanya-Keyal@users.noreply.github.com> Date: Sat, 19 Sep 2026 03:51:45 +0530 Subject: [PATCH 32/48] Parse the OP_RETURN push opcode instead of assuming OP_PUSHDATA1 The payload was read at a fixed 3-byte offset, which only holds when the script uses OP_PUSHDATA1. Opcodes 0x01-0x4b are themselves the byte count, and that is the minimal encoding Bitcoin Core emits, so every payload of 75 bytes or fewer lost its first byte: scriptPubKey 6a 28 "Chancellor on the brink of third bailout" parsed b'hancellor on the brink of third bailout' PSBTOpReturnView is a pre-signing review screen, so the user approved a transaction whose OP_RETURN content was displayed wrong. When the payload is not human-readable it renders as hex, where a one byte shift is invisible. Read the push opcode and slice to the declared length, in a static helper so the loop stays readable. OP_PUSHDATA2 and OP_PUSHDATA4 are handled too: Bitcoin Core v30 raised the default -datacarriersize to 100,000 bytes, and consensus never limited OP_RETURN data at all, so a payload past what OP_PUSHDATA1 can describe is no longer exotic. Several pushes after OP_RETURN are legal and are concatenated; the user is being shown the data the transaction commits to, and the push boundaries carry no consensus meaning. Anything that is not a data push, or a push that overruns the script, ends the walk and the remaining bytes are surfaced verbatim rather than dropped. Also reset op_return_data in _parse_outputs, which only ever set it in __init__, and compare the first byte by slice so an empty scriptPubKey does not raise IndexError. Fixes #963 Co-authored-by: ruipereira1 <159703278+ruipereira1@users.noreply.github.com> Co-authored-by: kwsantiago <44934418+kwsantiago@users.noreply.github.com> --- src/seedsigner/models/psbt_parser.py | 78 ++++++++++++++++++++++++++-- 1 file changed, 75 insertions(+), 3 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 1d9fff42b8..551af8cd14 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -15,7 +15,13 @@ 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 @@ -510,6 +516,7 @@ def _parse_outputs(self, child_key_derivation_cache: dict): self.fee_amount = 0 self.destination_addresses = [] self.destination_amounts = [] + self.op_return_data = None # Asking the PSBT for its transaction rebuilds that entire transaction from # scratch on every single request. The outputs are consulted a dozen times @@ -719,9 +726,9 @@ def _parse_outputs(self, child_key_derivation_cache: dict): # an omitted optional field is not a contradiction. raise PSBTOutputOwnershipContradictionError(f"Output claims this seed at {bip32.path_to_str(verified_derivation_paths[0].derivation)} but its committed script contradicts that") - if vout[i].script_pubkey.data[0] == OPCODES.OP_RETURN: - # The data is written as: OP_RETURN + OP_PUSHDATA1 + len(payload) + payload - self.op_return_data = vout[i].script_pubkey.data[3:] + script_data = vout[i].script_pubkey.data + if script_data[:1] == bytes([OPCODES.OP_RETURN]): + self.op_return_data = PSBTParser._parse_op_return_payload(script_data) elif is_presumed_change: # Remember that "change" in this function is ANY output coming back to our @@ -782,6 +789,71 @@ def sig_count(tx): return cnt + @staticmethod + 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. + + 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. + + Anything that is not a data push, and any push that claims more bytes than the + script actually carries, ends the walk and the remaining bytes are appended + verbatim, so no committed data is hidden from the review. 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 + else: + # Not a data push (OP_0, a numeric opcode, anything else). Surface the + # rest as-is rather than silently dropping it. + pushes.append(script_data[i:]) + break + + 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 + pushes.append(script_data[i:]) + break + 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 + pushes.append(script_data[data_start:]) + break + + pushes.append(script_data[data_start:data_end]) + i = data_end + + return b"".join(pushes) + + @staticmethod def _get_script_type(scope, scriptpubkey) -> str: """Like script_type(), but tells nested segwit p2sh apart from legacy p2sh""" From 89c5241ec670d2e5515153a12dd3d3ab61391969 Mon Sep 17 00:00:00 2001 From: okaybro <66475772+Chaitanya-Keyal@users.noreply.github.com> Date: Sat, 19 Sep 2026 03:52:02 +0530 Subject: [PATCH 33/48] Cover every OP_RETURN push encoding in the parser tests Every existing OP_RETURN vector hand-built OP_PUSHDATA1, which is exactly the one encoding the parser assumed, so the mis-slice never showed up. The regtest psbt behind test_parse_op_return_content carries 2b 6a 4c 28 43 68 61 6e ... and the screenshot generator concatenated OP_PUSHDATA1 by hand. Add fixture helpers that build an OP_RETURN scriptPubKey with the minimal push by default, and that can force a specific OP_PUSHDATA* so the non-minimal encodings a coordinator is free to produce are testable too. Note in the helper that the scriptPubKey and value have to be set on the OutputScope: PSBT.tx rebuilds the transaction from the scopes on every access, so assigning through psbt.tx.vout[i] is silently discarded and leaves a test asserting against the fixture it meant to replace. The new tests cover the direct-push/OP_PUSHDATA1 boundary at 75/76, OP_PUSHDATA2 and OP_PUSHDATA4, a non-minimal encoding, several pushes in one script, a bare OP_RETURN, an empty scriptPubKey, a truncated length field, an over-long declared length, and a leading opcode that is not a data push. Co-authored-by: ruipereira1 <159703278+ruipereira1@users.noreply.github.com> Co-authored-by: kwsantiago <44934418+kwsantiago@users.noreply.github.com> --- tests/psbt_testing_util.py | 69 ++++++++++++++++++++ tests/test_psbt_parser.py | 126 ++++++++++++++++++++++++++++++++++++- 2 files changed, 193 insertions(+), 2 deletions(-) diff --git a/tests/psbt_testing_util.py b/tests/psbt_testing_util.py index 85ebe82797..821fa725ef 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 @@ -254,3 +256,70 @@ 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, push_opcode: int = None) -> Script: + """ + Build an OP_RETURN scriptPubKey carrying `payload`. + + Defaults to the minimal push encoding, which is what 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. + + `push_opcode` forces a specific OP_PUSHDATA* instead, so a test can build the + non-minimal encodings that a coordinator is still free to produce. + """ + if push_opcode is None: + 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") + else: + length_size = {OPCODES.OP_PUSHDATA1: 1, OPCODES.OP_PUSHDATA2: 2, OPCODES.OP_PUSHDATA4: 4}[push_opcode] + push = bytes([push_opcode]) + len(payload).to_bytes(length_size, "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, change_amount: int = None, fee_amount: int = 5_000) -> 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. + + `change_amount` defaults to whatever is left of the input after the OP_RETURN values + and the fee, so the psbt balances. + """ + 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]) + + if change_amount is None: + change_amount = input_amount - op_return_amount - fee_amount + + 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/test_psbt_parser.py b/tests/test_psbt_parser.py index 72bf11f936..bee2bcce2f 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -12,7 +12,7 @@ from embit.descriptor import Descriptor from embit.script import Script -from seedsigner.models.psbt_parser import (PSBTInputAmountVerificationError, +from seedsigner.models.psbt_parser import (OPCODES, PSBTInputAmountVerificationError, PSBTInputOwnershipClaimError, PSBTMissingInputUtxoError, PSBTMixedDerivationPathTypesError, PSBTNegativeFeeError, PSBTOutputOwnershipClaimError, PSBTOutputOwnershipContradictionError, PSBTParser, PSBTSeedCannotSignError, @@ -21,7 +21,8 @@ from seedsigner.models.settings_definition import SettingsConstants from psbt_testing_util import (NUMS_INTERNAL_KEY, PSBTTestData, claim_seed_owns_key, - create_output, foreign_public_key, p2tr_with_script_tree, root_for_seed, tapleaf_hash) + create_op_return_output, create_op_return_psbt, create_output, foreign_public_key, + op_return_script, p2tr_with_script_tree, root_for_seed, tapleaf_hash) @@ -2704,3 +2705,124 @@ def test__parse__accepts_a_zero_fee(self): 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) + + 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"" + + # A push claiming more data than the script carries yields what is actually there, + # rather than raising or returning nothing + assert PSBTParser._parse_op_return_payload(op_return + bytes([10]) + b"abc") == b"abc" + + # A truncated OP_PUSHDATA2 length field, same rule + assert PSBTParser._parse_op_return_payload(op_return + bytes([OPCODES.OP_PUSHDATA2, 0x01])) == bytes([OPCODES.OP_PUSHDATA2, 0x01]) + + # A leading opcode that is not a data push. The remaining bytes are still surfaced; + # the user has to be able to see everything the transaction commits to. + assert PSBTParser._parse_op_return_payload(op_return + bytes([0x00, 0x51])) == bytes([0x00, 0x51]) + + + +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"" From 36fb9b35742f647dc9b607a79f47cb00b83e5394 Mon Sep 17 00:00:00 2001 From: okaybro <66475772+Chaitanya-Keyal@users.noreply.github.com> Date: Sat, 19 Sep 2026 03:52:02 +0530 Subject: [PATCH 34/48] Build the screenshot generator's OP_RETURN with a minimal push The generator concatenated OP_PUSHDATA1 unconditionally, so its 49-byte payload was encoded a way Bitcoin Core would never produce. Push directly at 75 bytes or fewer and via OP_PUSHDATA1 above that, matching the parser. The rendered screenshots are unchanged; the vector behind them is no longer wrong. Co-authored-by: kwsantiago <44934418+kwsantiago@users.noreply.github.com> --- tests/screenshot_generator/generator.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/tests/screenshot_generator/generator.py b/tests/screenshot_generator/generator.py index c9a471103a..3d70998e14 100644 --- a/tests/screenshot_generator/generator.py +++ b/tests/screenshot_generator/generator.py @@ -11,7 +11,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 @@ -83,11 +82,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 From 79e22d2de7527b1b5140c3bd3db94014f675dd38 Mon Sep 17 00:00:00 2001 From: okaybro <66475772+Chaitanya-Keyal@users.noreply.github.com> Date: Thu, 15 Oct 2026 17:57:02 +0530 Subject: [PATCH 35/48] Drop OP_RETURN test helper parameters that nothing passes `op_return_script`'s `push_opcode` and `create_op_return_psbt`'s `change_amount` and `fee_amount` were never used by any test. The non-minimal encoding cases build their bytes by hand and call `_parse_op_return_payload` directly. --- tests/psbt_testing_util.py | 41 ++++++++++++++------------------------ 1 file changed, 15 insertions(+), 26 deletions(-) diff --git a/tests/psbt_testing_util.py b/tests/psbt_testing_util.py index 821fa725ef..c215229b58 100644 --- a/tests/psbt_testing_util.py +++ b/tests/psbt_testing_util.py @@ -258,29 +258,20 @@ def claim_seed_owns_key(scope: InputScope | OutputScope, claimed_derivation_path scope.bip32_derivations[public_key] = derivation_path -def op_return_script(payload: bytes, push_opcode: int = None) -> Script: +def op_return_script(payload: bytes) -> Script: """ - Build an OP_RETURN scriptPubKey carrying `payload`. - - Defaults to the minimal push encoding, which is what 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. - - `push_opcode` forces a specific OP_PUSHDATA* instead, so a test can build the - non-minimal encodings that a coordinator is still free to produce. + 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 push_opcode is None: - 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") + 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: - length_size = {OPCODES.OP_PUSHDATA1: 1, OPCODES.OP_PUSHDATA2: 2, OPCODES.OP_PUSHDATA4: 4}[push_opcode] - push = bytes([push_opcode]) + len(payload).to_bytes(length_size, "little") + push = bytes([OPCODES.OP_PUSHDATA4]) + len(payload).to_bytes(4, "little") return Script(bytes([OPCODES.OP_RETURN]) + push + payload) @@ -303,20 +294,18 @@ def create_op_return_output(payload: bytes, value: int = 0, script_pubkey: Scrip return output -def create_op_return_psbt(op_return_outputs: list, change_amount: int = None, fee_amount: int = 5_000) -> PSBT: +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. - `change_amount` defaults to whatever is left of the input after the OP_RETURN values - and the fee, so the psbt balances. + 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]) - - if change_amount is None: - change_amount = input_amount - op_return_amount - fee_amount + 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)) From 6403723dcd10e18b4e0dfbc13f2a5a3e7fc2d08b Mon Sep 17 00:00:00 2001 From: okaybro <66475772+Chaitanya-Keyal@users.noreply.github.com> Date: Thu, 15 Oct 2026 17:59:35 +0530 Subject: [PATCH 36/48] Refuse an OP_RETURN that is not made of complete pushes Bitcoin Core treats an OP_RETURN output as nonstandard unless everything after the opcode is a push. The parser used to display whatever was left when a push ran past the end of the script, or when it met an opcode that is not a push. It now raises PSBTMalformedOpReturnError instead, and the user gets the same plain "Transaction Problem" warning used for other malformed psbts before discarding it. OP_0, OP_1NEGATE, OP_RESERVED, and OP_1 through OP_16 still count as pushes to Core, so they are kept and the walk carries on past them rather than stopping there. --- src/seedsigner/models/psbt_parser.py | 41 ++++++++++++------ src/seedsigner/views/psbt_views.py | 34 ++++++++++++++- tests/screenshot_generator/generator.py | 1 + tests/test_flows_psbt.py | 24 ++++++++++- tests/test_psbt_parser.py | 57 +++++++++++++++++++++---- 5 files changed, 132 insertions(+), 25 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 551af8cd14..3c4dc21522 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -22,6 +22,7 @@ class OPCODES: OP_PUSHDATA1 = 76 OP_PUSHDATA2 = 77 OP_PUSHDATA4 = 78 + OP_16 = 96 @@ -131,6 +132,17 @@ class PSBTMissingInputUtxoError(PSBTVerificationError): pass +class PSBTMalformedOpReturnError(PSBTVerificationError): + """ + An OP_RETURN output's script is not made of complete pushes: a push runs past the end + of the script, or an opcode is not a push at all. + + This is a malformed psbt rather than a proven deception, so we do not treat it as an + attack. + """ + pass + + class PSBTSeedCannotSignError(PSBTVerificationError): """ The selected seed holds no key that could sign any input. @@ -804,10 +816,12 @@ def _parse_op_return_payload(script_data: bytes) -> bytes: 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. - Anything that is not a data push, and any push that claims more bytes than the - script actually carries, ends the walk and the remaining bytes are appended - verbatim, so no committed data is hidden from the review. The caller gets raw - bytes and decides how to render them. + Bitcoin Core treats an OP_RETURN output as nonstandard unless everything after the + opcode is a push. Raises PSBTMalformedOpReturnError for a push that runs past the + end of the script or an opcode that is not a push. 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. The caller gets raw bytes and decides how to + render them. """ pushes = [] @@ -825,28 +839,29 @@ def _parse_op_return_payload(script_data: bytes) -> bytes: 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 else: - # Not a data push (OP_0, a numeric opcode, anything else). Surface the - # rest as-is rather than silently dropping it. - pushes.append(script_data[i:]) - break + # Not a push, so the script cannot be read as OP_RETURN data + raise PSBTMalformedOpReturnError(f"OP_RETURN script holds non-push opcode 0x{opcode:02x}") 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 - pushes.append(script_data[i:]) - break + # The length field itself is truncated, so the push size is unknown + raise PSBTMalformedOpReturnError("OP_RETURN push length field is truncated") 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 - pushes.append(script_data[data_start:]) - break + raise PSBTMalformedOpReturnError(f"OP_RETURN push declares {length} bytes but only {len(script_data) - data_start} remain") pushes.append(script_data[data_start:data_end]) i = data_end diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index 49e04b858e..6c14b98871 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -3,7 +3,7 @@ from gettext import gettext as _ from seedsigner.models.psbt_parser import (PSBTInputAmountVerificationError, - PSBTInputOwnershipClaimError, PSBTMissingInputUtxoError, + PSBTInputOwnershipClaimError, PSBTMalformedOpReturnError, PSBTMissingInputUtxoError, PSBTMixedDerivationPathTypesError, PSBTNegativeFeeError, PSBTOutputOwnershipClaimError, PSBTOutputOwnershipContradictionError, PSBTParser, PSBTSeedCannotSignError, PSBTSurplusDerivationPathsError) @@ -128,6 +128,10 @@ def __init__(self): self.set_redirect(Destination(PSBTMixedDerivationPathTypesView, clear_history=True)) return + except PSBTMalformedOpReturnError: + self.set_redirect(Destination(PSBTMalformedOpReturnView, clear_history=True)) + return + except PSBTOutputOwnershipContradictionError: self.set_redirect(Destination(PSBTOutputOwnershipContradictionView, clear_history=True)) return @@ -644,6 +648,34 @@ def run(self): +class PSBTMalformedOpReturnView(View): + """ + Reached when an OP_RETURN output's script is not made of complete pushes (see + PSBTMalformedOpReturnError). + + We view this as a malformed psbt and do not try to decide whether it is malicious. We + do not allow the user to continue, but only give this the "Warning" level. + """ + DISCARD = ButtonOption("Discard transaction") + + def run(self): + self.run_screen( + WarningScreen, + title=_("Transaction Problem"), + status_headline=None, + # TRANSLATOR_NOTE: The transaction/psbt has an error but does not seem to be malicious. + text=_("This transaction's OP_RETURN data is malformed."), + button_data=[self.DISCARD], + show_back_button=False, + ) + + # We're done with this PSBT. Route back to MainMenuView, which clears all + # ephemeral data (except in-memory seeds). + # Set clear_history to disable returning via BACK button. + return Destination(MainMenuView, clear_history=True) + + + class PSBTOutputOwnershipContradictionView(View): """ Reached when the psbt's account of who an output pays contradicts the script that diff --git a/tests/screenshot_generator/generator.py b/tests/screenshot_generator/generator.py index 3d70998e14..6ca4660d12 100644 --- a/tests/screenshot_generator/generator.py +++ b/tests/screenshot_generator/generator.py @@ -453,6 +453,7 @@ def mock_version_to_most_recent_release(): ScreenshotConfig(psbt_views.PSBTOpReturnView, screenshot_name="PSBTOpReturnView_raw_hex_data", mock_context_manager=mock_psbt_with_op_return_raw_bytes_loaded), ScreenshotConfig(psbt_views.PSBTSurplusDerivationPathsView), ScreenshotConfig(psbt_views.PSBTMixedDerivationPathTypesView), + ScreenshotConfig(psbt_views.PSBTMalformedOpReturnView), ScreenshotConfig(psbt_views.PSBTOutputOwnershipContradictionView), ScreenshotConfig(psbt_views.PSBTAddressVerificationFailedView, dict(is_change=True), screenshot_name="PSBTAddressVerificationFailedView_multisig_change"), ScreenshotConfig(psbt_views.PSBTAddressVerificationFailedView, dict(is_change=False), screenshot_name="PSBTAddressVerificationFailedView_multisig_selftransfer"), diff --git a/tests/test_flows_psbt.py b/tests/test_flows_psbt.py index 8a4375988e..786987be55 100644 --- a/tests/test_flows_psbt.py +++ b/tests/test_flows_psbt.py @@ -4,12 +4,13 @@ from embit.psbt import PSBT, DerivationPath from base import 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 @@ -376,6 +377,25 @@ def test_missing_input_utxo_terminates_signing_flow(self): ]) + 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_wrong_seed_routes_back_to_seed_selection_flow(self): """ The wrong seed for a psbt redirects before any transaction detail is rendered and diff --git a/tests/test_psbt_parser.py b/tests/test_psbt_parser.py index bee2bcce2f..5983f5f202 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -13,7 +13,7 @@ from embit.script import Script from seedsigner.models.psbt_parser import (OPCODES, PSBTInputAmountVerificationError, - PSBTInputOwnershipClaimError, PSBTMissingInputUtxoError, + PSBTInputOwnershipClaimError, PSBTMalformedOpReturnError, PSBTMissingInputUtxoError, PSBTMixedDerivationPathTypesError, PSBTNegativeFeeError, PSBTOutputOwnershipClaimError, PSBTOutputOwnershipContradictionError, PSBTParser, PSBTSeedCannotSignError, PSBTSurplusDerivationPathsError) @@ -2722,6 +2722,7 @@ def test_parse_op_return_payload_push_encodings(): # 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]) @@ -2762,16 +2763,54 @@ def test_parse_op_return_payload_push_encodings(): # An empty scriptPubKey must not index past the end assert PSBTParser._parse_op_return_payload(b"") == b"" - # A push claiming more data than the script carries yields what is actually there, - # rather than raising or returning nothing - assert PSBTParser._parse_op_return_payload(op_return + bytes([10]) + b"abc") == b"abc" + # 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]) - # A truncated OP_PUSHDATA2 length field, same rule - assert PSBTParser._parse_op_return_payload(op_return + bytes([OPCODES.OP_PUSHDATA2, 0x01])) == bytes([OPCODES.OP_PUSHDATA2, 0x01]) - # A leading opcode that is not a data push. The remaining bytes are still surfaced; - # the user has to be able to see everything the transaction commits to. - assert PSBTParser._parse_op_return_payload(op_return + bytes([0x00, 0x51])) == bytes([0x00, 0x51]) + +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 pytest.raises(PSBTMalformedOpReturnError): + 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 pytest.raises(PSBTMalformedOpReturnError): + PSBTParser(p=psbt, seed=PSBTTestData.seed, network=SettingsConstants.REGTEST) From 2b4c578c0a0a15286d9864ddbf8790a420bb00e4 Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Fri, 25 Sep 2026 14:22:20 -0500 Subject: [PATCH 37/48] Verify input scripts against the scriptPubKey they commit to BIP-174 asks a signer to hash an input's redeem or witness script against the scriptPubKey being spent. We read the wallet policy (m-of-n, cosigner keys) out of those scripts and never checked them, so a coordinator's own script decided which outputs we displayed as the user's change. _verify_input_scripts runs on every input before the policy is read, and each refusal has its own screen: - A missing script raises PSBTMissingInputScriptError, graded as a correctness problem. - A script that hashes to the wrong value raises PSBTInputScriptMismatchError, graded as an attack. It is the same contradiction between a supplied script and its scriptPubKey that PSBTOutputOwnershipContradictionError grades as an attack on outputs. - An extraneous script (a witness script on a legacy multisig input, a redeem script on a native segwit input) raises PSBTExtraneousInputScriptError, left ungraded. It is refused on every input type: there is no hash to check it against, and _get_policy decides a p2sh input is nested segwit from the mere presence of a witness script. Measured across the four p2sh and p2wsh fixtures: no signature over a wrong script was valid against the real coin, because embit builds the digest from the first supplied script (witness, then redeem, then scriptPubKey). Funds were never movable this way; what the check closes is the display. --- src/seedsigner/models/psbt_parser.py | 127 ++++++++++++++- src/seedsigner/views/psbt_views.py | 102 +++++++++++- tests/screenshot_generator/generator.py | 3 + tests/test_flows_psbt.py | 71 ++++++++ tests/test_psbt_parser.py | 207 +++++++++++++++++++++++- 5 files changed, 502 insertions(+), 8 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 3c4dc21522..8af82ccdb2 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -104,7 +104,6 @@ class PSBTOutputOwnershipContradictionError(PSBTVerificationError): output claims our key but commits to another key, or it commits to our key while claiming a different fingerprint in our place. - We treat any of these deceptions as an attack. """ pass @@ -143,6 +142,43 @@ class PSBTMalformedOpReturnError(PSBTVerificationError): pass +class PSBTMissingInputScriptError(PSBTVerificationError): + """ + An input is missing a required script. + + Required scripts: + * p2wsh: witness_script + * p2sh: redeem_script + * p2sh-p2wsh (nested segwit multisig): witness_script and redeem_script + + This is a correctness problem rather than an attack. + """ + pass + + +class PSBTInputScriptMismatchError(PSBTVerificationError): + """ + An input supplied a script that doesn't match what the input actually commits to. + + This sort of misleading script can lead the parser to an incorrect determination of + whether an output is our change. + + We treat this deception as an attack. + """ + pass + + +class PSBTExtraneousInputScriptError(PSBTVerificationError): + """ + An input commits to a specific script type but also supplies an extraneous script that + is not used by that script type (e.g. a redeem script is meaningless for native + segwit). + + We don't try to decide whether this is an attack or a mistake. + """ + pass + + class PSBTSeedCannotSignError(PSBTVerificationError): """ The selected seed holds no key that could sign any input. @@ -294,9 +330,13 @@ def parse(self): missing the utxo that holds its amount, or PSBTInputAmountVerificationError if an amount is unproven or false. - 5. _parse_inputs: every input must resolve to the same policy otherwise a - RuntimeError is raised. TODO: make this a PSBTVerificationError subclass so - the view can deliberately catch this scenario and route accordingly. + 5. _parse_inputs: an input must supply every script it commits to and no others. + A missing script raises PSBTMissingInputScriptError, a wrong one + PSBTInputScriptMismatchError, and an extra one + PSBTExtraneousInputScriptError. Every input must then resolve to the same + policy otherwise a RuntimeError is raised (TODO: replace the RuntimeError + with a PSBTVerificationError subclass so the View can deliberately catch this + scenario and route accordingly). A policy is one of: - single-sig: the script type alone. Says nothing about keys. @@ -460,6 +500,10 @@ def _parse_inputs(self, child_key_derivation_cache: dict): for inp in self.psbt.inputs: script_pubkey = inp.script_pubkey + # Verify the input's scripts and reject the psbt if verification fails + PSBTParser._verify_input_scripts(inp, script_pubkey) + + # Now we can safely use those scripts to determine this input's wallet policy inp_policy = PSBTParser._get_policy(inp, script_pubkey, self.psbt.xpubs, child_key_derivation_cache) if self.policy == None: self.policy = inp_policy @@ -468,6 +512,81 @@ def _parse_inputs(self, child_key_derivation_cache: dict): raise RuntimeError("Mixed inputs in the transaction") + @staticmethod + def _verify_input_scripts(inp: InputScope, script_pubkey: script.Script): + """ + Checks that an input supplies exactly the scripts it commits to. + + A p2sh or p2wsh scriptPubKey holds only a hash of the script the input spends + with. Per BIP-174, the psbt must supply that script. Missing scripts raise + PSBTMissingInputScriptError. + + We then rebuild what the input commits to and compare, as BIP-174 requires of a + signer: + p2wsh: p2wsh(witness_script) == scriptPubKey + p2sh: p2sh(redeem_script) == scriptPubKey + p2sh-p2wpkh: p2sh(redeem_script) == scriptPubKey + + Multisig nested segwit has TWO layers to check: + p2sh-p2wsh: p2sh(redeem_script) == scriptPubKey + p2wsh(witness_script) == redeem_script + + If any comparison required above fails, we raise PSBTInputScriptMismatchError. + + Each input commits to a specific script type. It should not include any extraneous + scripts that are not required by that script type (e.g. a witness_script on a p2sh + input). Such a script could distort the parser's understanding of the wallet being + spent from, which would affect its determination of whether an output is the + user's change. But it's also possible that a buggy coordinator just created an odd + psbt. Either way, we raise PSBTExtraneousInputScriptError for any extraneous + script. + """ + script_type = script_pubkey.script_type() + expects_redeem_script = False + expects_witness_script = False + + if script_type == "p2wsh": + expects_witness_script = True + + if inp.witness_script is None: + raise PSBTMissingInputScriptError("Input commits to a witness script it did not supply") + + # The scriptPubKey holds a hash of the witness script, so we rebuild the + # scriptPubKey from the supplied one and compare. + if script.p2wsh(inp.witness_script).data != script_pubkey.data: + raise PSBTInputScriptMismatchError("Input's witness script is not the one its scriptPubKey commits to") + + elif script_type == "p2sh": + expects_redeem_script = True + + if inp.redeem_script is None: + raise PSBTMissingInputScriptError("Input commits to a redeem script it did not supply") + + # The scriptPubKey holds a hash of the redeem script, so we rebuild the + # scriptPubKey from the supplied one and compare. For legacy p2sh multisig and + # p2sh-p2wpkh, the redeem script is the only layer. + if script.p2sh(inp.redeem_script).data != script_pubkey.data: + raise PSBTInputScriptMismatchError("Input's redeem script is not the one its scriptPubKey commits to") + + # Nested segwit: the redeem script is itself a commitment to a witness script, + # so p2sh-p2wsh has a second layer to check. + if inp.redeem_script.script_type() == "p2wsh": + expects_witness_script = True + + if inp.witness_script is None: + raise PSBTMissingInputScriptError("Nested segwit input commits to a witness script it did not supply") + + if script.p2wsh(inp.witness_script).data != inp.redeem_script.data: + raise PSBTInputScriptMismatchError("Nested segwit input's witness script is not the one its redeem script commits to") + + # Any script beyond the ones this input commits to is extraneous + if inp.redeem_script is not None and not expects_redeem_script: + raise PSBTExtraneousInputScriptError("Input supplied a redeem script its scriptPubKey does not commit to") + + if inp.witness_script is not None and not expects_witness_script: + raise PSBTExtraneousInputScriptError("Input supplied a witness script its scriptPubKey does not commit to") + + def _parse_outputs(self, child_key_derivation_cache: dict): """ Sorts each output into change coming back to this seed, an external spend, or diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index 6c14b98871..bf4efb7021 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -2,8 +2,10 @@ from gettext import gettext as _ -from seedsigner.models.psbt_parser import (PSBTInputAmountVerificationError, - PSBTInputOwnershipClaimError, PSBTMalformedOpReturnError, PSBTMissingInputUtxoError, +from seedsigner.models.psbt_parser import (PSBTExtraneousInputScriptError, + PSBTInputAmountVerificationError, PSBTInputOwnershipClaimError, + PSBTInputScriptMismatchError, PSBTMalformedOpReturnError, + PSBTMissingInputScriptError, PSBTMissingInputUtxoError, PSBTMixedDerivationPathTypesError, PSBTNegativeFeeError, PSBTOutputOwnershipClaimError, PSBTOutputOwnershipContradictionError, PSBTParser, PSBTSeedCannotSignError, PSBTSurplusDerivationPathsError) @@ -132,6 +134,18 @@ def __init__(self): self.set_redirect(Destination(PSBTMalformedOpReturnView, clear_history=True)) return + except PSBTMissingInputScriptError: + self.set_redirect(Destination(PSBTMissingInputScriptView, clear_history=True)) + return + + except PSBTInputScriptMismatchError: + self.set_redirect(Destination(PSBTInputScriptMismatchView, clear_history=True)) + return + + except PSBTExtraneousInputScriptError: + self.set_redirect(Destination(PSBTExtraneousInputScriptView, clear_history=True)) + return + except PSBTOutputOwnershipContradictionError: self.set_redirect(Destination(PSBTOutputOwnershipContradictionView, clear_history=True)) return @@ -730,6 +744,90 @@ def run(self): +class PSBTMissingInputScriptView(View): + """ + Reached when an input commits to a script that the psbt did not supply (see + PSBTMissingInputScriptError). + + We view this as a correctness problem rather than an attack. We do not allow the user + to continue, but only give this the "Warning" level. + """ + DISCARD = ButtonOption("Discard transaction") + + def run(self): + self.run_screen( + WarningScreen, + title=_("Transaction Problem"), + status_headline=None, + # TRANSLATOR_NOTE: The transaction/psbt has an error but does not seem to be malicious. + text=_("This transaction left out a script that one of its inputs needs."), + button_data=[self.DISCARD], + show_back_button=False, + ) + + # We're done with this PSBT. Route back to MainMenuView, which clears all + # ephemeral data (except in-memory seeds). + # Set clear_history to disable returning via BACK button. + return Destination(MainMenuView, clear_history=True) + + + +class PSBTInputScriptMismatchView(View): + """ + Reached when an input supplies a script that hashes to something other than what the + input commits to (see PSBTInputScriptMismatchError). + + We view this as an attack. We do not allow the user to continue and give this the + "Dire Warning" level. + """ + DISCARD = ButtonOption("Discard transaction") + + def run(self): + self.run_screen( + DireWarningScreen, + title=_("Suspicious Transaction"), + status_headline=_("Likely an Attack!"), + # TRANSLATOR_NOTE: The transaction/psbt contains a deception that we consider an attack. + text=_("This transaction supplied the wrong script for one of its inputs."), + button_data=[self.DISCARD], + show_back_button=False, + ) + + # We're done with this PSBT. Route back to MainMenuView, which clears all + # ephemeral data (except in-memory seeds). + # Set clear_history to disable returning via BACK button. + return Destination(MainMenuView, clear_history=True) + + + +class PSBTExtraneousInputScriptView(View): + """ + Reached when an input supplies a script beyond the ones its scriptPubKey commits to + (see PSBTExtraneousInputScriptError). + + We do not try to decide whether this is an attack or a mistake. We do not allow the + user to continue, but only give this the "Warning" level. + """ + DISCARD = ButtonOption("Discard transaction") + + def run(self): + self.run_screen( + WarningScreen, + title=_("Transaction Problem"), + status_headline=None, + # TRANSLATOR_NOTE: The transaction/psbt has an error but does not seem to be malicious. + text=_("This transaction supplied an extra script for one of its inputs."), + button_data=[self.DISCARD], + show_back_button=False, + ) + + # We're done with this PSBT. Route back to MainMenuView, which clears all + # ephemeral data (except in-memory seeds). + # Set clear_history to disable returning via BACK button. + return Destination(MainMenuView, clear_history=True) + + + class PSBTAddressVerificationFailedView(View): """ Reached from PSBTChangeDetailsView when a multisig change or self-transfer output diff --git a/tests/screenshot_generator/generator.py b/tests/screenshot_generator/generator.py index 6ca4660d12..4e2d310130 100644 --- a/tests/screenshot_generator/generator.py +++ b/tests/screenshot_generator/generator.py @@ -455,6 +455,9 @@ def mock_version_to_most_recent_release(): ScreenshotConfig(psbt_views.PSBTMixedDerivationPathTypesView), ScreenshotConfig(psbt_views.PSBTMalformedOpReturnView), ScreenshotConfig(psbt_views.PSBTOutputOwnershipContradictionView), + ScreenshotConfig(psbt_views.PSBTMissingInputScriptView), + ScreenshotConfig(psbt_views.PSBTInputScriptMismatchView), + ScreenshotConfig(psbt_views.PSBTExtraneousInputScriptView), ScreenshotConfig(psbt_views.PSBTAddressVerificationFailedView, dict(is_change=True), screenshot_name="PSBTAddressVerificationFailedView_multisig_change"), ScreenshotConfig(psbt_views.PSBTAddressVerificationFailedView, dict(is_change=False), screenshot_name="PSBTAddressVerificationFailedView_multisig_selftransfer"), ScreenshotConfig(psbt_views.PSBTOutputOwnershipClaimFailedView), diff --git a/tests/test_flows_psbt.py b/tests/test_flows_psbt.py index 786987be55..8fbc8a3aef 100644 --- a/tests/test_flows_psbt.py +++ b/tests/test_flows_psbt.py @@ -396,6 +396,77 @@ def test_malformed_op_return_terminates_signing_flow(self): ]) + 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 diff --git a/tests/test_psbt_parser.py b/tests/test_psbt_parser.py index 5983f5f202..154a0cbc22 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -12,8 +12,10 @@ from embit.descriptor import Descriptor from embit.script import Script -from seedsigner.models.psbt_parser import (OPCODES, PSBTInputAmountVerificationError, - PSBTInputOwnershipClaimError, PSBTMalformedOpReturnError, PSBTMissingInputUtxoError, +from seedsigner.models.psbt_parser import (OPCODES, PSBTExtraneousInputScriptError, + PSBTInputAmountVerificationError, PSBTInputOwnershipClaimError, + PSBTInputScriptMismatchError, PSBTMalformedOpReturnError, + PSBTMissingInputScriptError, PSBTMissingInputUtxoError, PSBTMixedDerivationPathTypesError, PSBTNegativeFeeError, PSBTOutputOwnershipClaimError, PSBTOutputOwnershipContradictionError, PSBTParser, PSBTSeedCannotSignError, PSBTSurplusDerivationPathsError) @@ -2865,3 +2867,204 @@ def test_parse_op_return_with_no_payload(): 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 _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 _add_foreign_nested_segwit_input(self, psbt: PSBT, derivation_path: str = "m/49h/1h/0h/0/0"): + """ + Adds another party's p2sh-p2wpkh input with no derivation paths, as in a payjoin: + their utxo, their key, and a redeem script built from their key. + + The supplied psbt's first input should carry both a witness_utxo and a + non_witness_utxo. + """ + # Start from a copy of our own input for its utxo fields + foreign_input = deepcopy(psbt.inputs[0]) + + # 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) + + # The parse verifies input amounts before the script checks, so give this coin a + # matching non_witness_utxo and point the input at its new txid. + foreign_input.non_witness_utxo.vout[foreign_input.vout].script_pubkey = foreign_input.witness_utxo.script_pubkey + foreign_input.txid = foreign_input.non_witness_utxo.txid() + + 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 pytest.raises(PSBTMissingInputScriptError): + 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 pytest.raises(PSBTMissingInputScriptError): + 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 pytest.raises(PSBTMissingInputScriptError): + 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 pytest.raises(PSBTMissingInputScriptError): + 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 pytest.raises(PSBTMissingInputScriptError): + 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 pytest.raises(PSBTInputScriptMismatchError): + 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 pytest.raises(PSBTInputScriptMismatchError): + 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 pytest.raises(PSBTInputScriptMismatchError): + 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 pytest.raises(PSBTInputScriptMismatchError): + 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 pytest.raises(PSBTInputScriptMismatchError): + 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 pytest.raises(PSBTExtraneousInputScriptError): + self._parse(psbt) + + # p2wpkh: add a redeem script + psbt = self._psbt_with_change() + psbt.inputs[0].redeem_script = arbitrary_script + with pytest.raises(PSBTExtraneousInputScriptError): + 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 pytest.raises(PSBTExtraneousInputScriptError): + self._parse(psbt) + + + def test__parse__checks_input_scripts_whoever_the_input_belongs_to(self): + """ + A collaborative spend, such as a payjoin, puts another party's input alongside the + user's. That input's scripts should be checked just as the user's are. Whose + input it is rests on the psbt's own claims, so no input is exempt from the script + checks. + + The psbt will be rejected if a script is missing (PSBTMissingInputScriptError) or + wrong (PSBTInputScriptMismatchError). + """ + 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 + foreign_input.redeem_script = None + with pytest.raises(PSBTMissingInputScriptError): + 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 pytest.raises(PSBTInputScriptMismatchError): + self._parse(psbt) From b4a56bc72ea0a839d310847036d4cef4ed3ea0de Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Mon, 28 Sep 2026 12:04:46 -0500 Subject: [PATCH 38/48] Correct the input script docstring's BIP-174 claim The _verify_input_scripts docstring said BIP-174 requires the psbt to supply an input's redeem or witness script. BIP-174 allows a psbt to be passed between roles before every script is known, with each Updater adding the scripts it knows. A signer still needs an input's script to produce a valid signature for that input. BIP-174's signer rules check a script once it is provided. The mismatch and extraneous checks enforce those rules. The docstring now also groups the checks by the inputs they cover. The missing and mismatch checks run only on p2sh and p2wsh inputs. The extraneous script check runs on every input. Docstring-only change. --- src/seedsigner/models/psbt_parser.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 8af82ccdb2..cbbe56a0c0 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -517,12 +517,10 @@ def _verify_input_scripts(inp: InputScope, script_pubkey: script.Script): """ Checks that an input supplies exactly the scripts it commits to. + **** For just p2sh or p2wsh inputs: **** A p2sh or p2wsh scriptPubKey holds only a hash of the script the input spends - with. Per BIP-174, the psbt must supply that script. Missing scripts raise - PSBTMissingInputScriptError. - - We then rebuild what the input commits to and compare, as BIP-174 requires of a - signer: + with. So we have to rebuild what the input commits to and compare our result + against the input's scriptPubKey: p2wsh: p2wsh(witness_script) == scriptPubKey p2sh: p2sh(redeem_script) == scriptPubKey p2sh-p2wpkh: p2sh(redeem_script) == scriptPubKey @@ -531,8 +529,11 @@ def _verify_input_scripts(inp: InputScope, script_pubkey: script.Script): p2sh-p2wsh: p2sh(redeem_script) == scriptPubKey p2wsh(witness_script) == redeem_script + If any required scripts are missing, raise PSBTMissingInputScriptError. + If any comparison required above fails, we raise PSBTInputScriptMismatchError. + **** For all script types: **** Each input commits to a specific script type. It should not include any extraneous scripts that are not required by that script type (e.g. a witness_script on a p2sh input). Such a script could distort the parser's understanding of the wallet being From aac8893d7bf85a9eec2406c3ece789dd930c7119 Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Mon, 28 Sep 2026 14:36:52 -0500 Subject: [PATCH 39/48] Document the payjoin gaps in input handling A payjoin receiver's input arrives finalized (BIP-78), and finalizing clears its redeem and witness script fields (BIP-174). So a nested segwit payjoin is refused as missing its input script; before input script verification it was refused as "Mixed inputs". Native segwit payjoins parse either way. Two TODOs mark what payjoins and other collaborative spends would need: - recover a finalized input's script from its final scriptSig or witness - read the wallet policy only from the user's own inputs The every-input test's docstrings now describe its fixture by the rule it tests rather than as a payjoin input. It is an unfinalized input that carries its redeem script, built to check that every input's scripts are verified whoever the psbt says the input belongs to. Comment-only change. --- src/seedsigner/models/psbt_parser.py | 9 +++++++++ tests/test_psbt_parser.py | 16 ++++++++++------ 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index cbbe56a0c0..1f4ad751bf 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -509,6 +509,10 @@ def _parse_inputs(self, child_key_derivation_cache: dict): 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 RuntimeError("Mixed inputs in the transaction") @@ -542,6 +546,11 @@ def _verify_input_scripts(inp: InputScope, script_pubkey: script.Script): psbt. Either way, we raise PSBTExtraneousInputScriptError for any extraneous script. """ + # 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 rejected here for + # missing its script. Recover the script from the final fields, verify it the same + # way, and read the policy from it. script_type = script_pubkey.script_type() expects_redeem_script = False expects_witness_script = False diff --git a/tests/test_psbt_parser.py b/tests/test_psbt_parser.py index 154a0cbc22..337ed8429d 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -2886,8 +2886,8 @@ def _foreign_multisig_script(self) -> script.Script: def _add_foreign_nested_segwit_input(self, psbt: PSBT, derivation_path: str = "m/49h/1h/0h/0/0"): """ - Adds another party's p2sh-p2wpkh input with no derivation paths, as in a payjoin: - their utxo, their key, and a redeem script built from their key. + 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. The supplied psbt's first input should carry both a witness_utxo and a non_witness_utxo. @@ -3041,13 +3041,17 @@ def test__parse__refuses_an_input_that_supplies_an_extra_script(self): def test__parse__checks_input_scripts_whoever_the_input_belongs_to(self): """ - A collaborative spend, such as a payjoin, puts another party's input alongside the - user's. That input's scripts should be checked just as the user's are. Whose - input it is rests on the psbt's own claims, so no input is exempt from the script - checks. + 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) From 0aea073112cb36344ba9c72937966b590776e1dc Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Wed, 30 Sep 2026 06:25:22 -0500 Subject: [PATCH 40/48] Fix two stale comments on the input script checks The comment above the _get_policy call in _parse_inputs said the input's scripts could now be used "safely". The check before it binds each script to the scriptPubKey the psbt supplies, and nothing in the parse authenticates that scriptPubKey yet, so the word claims more than the check establishes. The shared test base class described itself as the base for the two ownership test classes. The input script tests are a third subclass, and not an ownership test class. Comment-only change. --- src/seedsigner/models/psbt_parser.py | 2 +- tests/test_psbt_parser.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 1f4ad751bf..2e31a2605b 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -503,7 +503,7 @@ def _parse_inputs(self, child_key_derivation_cache: dict): # Verify the input's scripts and reject the psbt if verification fails PSBTParser._verify_input_scripts(inp, script_pubkey) - # Now we can safely use those scripts to determine this input's wallet policy + # Now we can use those scripts to determine this input's wallet policy inp_policy = PSBTParser._get_policy(inp, script_pubkey, self.psbt.xpubs, child_key_derivation_cache) if self.policy == None: self.policy = inp_policy diff --git a/tests/test_psbt_parser.py b/tests/test_psbt_parser.py index 337ed8429d..ca231bb745 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -1183,7 +1183,7 @@ def build_psbt(case: tuple) -> PSBT: class PSBTParserOwnershipTestBase: """ - Base class for the two ownership test classes below. Provides: + Base class for the test classes below. Provides: * the signing seed * a psbt made of nothing but that seed's own scopes * the parse call under test. From 4b93177771a036df389ad840f01a3ce2e158447a Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Fri, 16 Oct 2026 10:52:40 -0400 Subject: [PATCH 41/48] Move the foreign multisig test helper to the shared base class TestPSBTParserInputScripts carried a copy of _foreign_multisig_script identical to the one in TestPSBTParserOutputOwnership. Both classes now inherit it from PSBTParserOwnershipTestBase. The base class docstring listed the fixtures the class body defines. Adding this helper would have meant extending that list. It now names the tests the fixtures support: how PSBTParser verifies a psbt's claims about its inputs and outputs. That covers the input script tests too, which check an input's scripts whoever owns it. Test-only change. --- tests/test_psbt_parser.py | 21 +++++++-------------- 1 file changed, 7 insertions(+), 14 deletions(-) diff --git a/tests/test_psbt_parser.py b/tests/test_psbt_parser.py index ca231bb745..af8cfa5ed2 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -1183,10 +1183,8 @@ def build_psbt(case: tuple) -> PSBT: class PSBTParserOwnershipTestBase: """ - Base class for the test classes below. Provides: - * the signing seed - * a psbt made of nothing but that seed's own scopes - * the parse call under test. + Shared fixtures for tests of how PSBTParser verifies a psbt's claims about its inputs + and outputs. """ seed = PSBTTestData.seed @@ -1209,6 +1207,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() @@ -1623,11 +1626,6 @@ class TestPSBTParserOutputOwnership(PSBTParserOwnershipTestBase): 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 @@ -2879,11 +2877,6 @@ class TestPSBTParserInputScripts(PSBTParserOwnershipTestBase): the parser requiring that script, requiring it to be the right one, and refusing an extraneous one. """ - 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 _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 From 717a0e9ef990f6243152d42a5f3701edb225d61d Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Fri, 16 Oct 2026 11:01:37 -0400 Subject: [PATCH 42/48] Name the input script check in the _parse_inputs docstring The docstring now lists the method's two steps in the order they run: verifying each input's scripts and determining the wallet policy. Docstring-only change. --- src/seedsigner/models/psbt_parser.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 2e31a2605b..caf3ea79e9 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -493,8 +493,8 @@ def _verify_input_amounts(self): def _parse_inputs(self, child_key_derivation_cache: dict): """ - Determines the wallet policy. Every input must resolve to the same policy, - otherwise a RuntimeError is raised. + Verifies each input's scripts and determines the wallet policy. Every input must + resolve to the same policy, otherwise a RuntimeError is raised. """ self.num_inputs = len(self.psbt.inputs) for inp in self.psbt.inputs: From 85833cc857317a6ce336d8293d1c5f490eccd35c Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:04:19 -0500 Subject: [PATCH 43/48] Verify input scripts before reading the script type To decide whether an input's sighash commits its amount, the amount check reads the input's script type, and telling nested segwit from legacy p2sh reads the input's redeem and witness scripts. Those scripts were verified only later, in _parse_inputs. So a witness-only nested segwit input missing one of its scripts read as legacy p2sh and was refused with PSBTInputAmountVerificationError, graded as an attack, instead of PSBTMissingInputScriptError. The script check now runs inside the amount check's loop: after the checks on an input's previous transaction, so a forged one is still refused as an attack, and before the check that reads the scripts. The method is renamed _verify_input_amounts_and_scripts to match, and the per-type utxo requirements move to the comment on UNCOMMITTED_AMOUNT_SCRIPT_TYPES. The foreign nested segwit input in the every-input test now carries a witness_utxo alone, so its missing-redeem-script case takes the witness-only path. The test fails on the previous order. --- src/seedsigner/models/psbt_parser.py | 92 +++++++++++++++------------- tests/test_psbt_parser.py | 19 +++--- 2 files changed, 61 insertions(+), 50 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index caf3ea79e9..fef3f10255 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -241,7 +241,11 @@ class PSBTParser(): # just stops getting cache hits once the cache is full. MAX_CACHED_DERIVATIONS = 1000 - # Input types whose sighash does NOT commit to the input amount. + # Input types whose sighash does NOT commit to the input amount, so each must supply + # a non_witness_utxo: + # * "p2pkh" and "p2sh": legacy. "p2sh" here is legacy p2sh only; nested segwit + # (p2sh-p2wpkh and p2sh-p2wsh) is segwit, and its sighash commits the amount. + # * `None`: an unrecognized script type, held to the same rule as legacy. UNCOMMITTED_AMOUNT_SCRIPT_TYPES = [None, "p2pkh", "p2sh"] # Warn when the fee exceeds this percentage of what is being sent (outputs other than @@ -325,17 +329,18 @@ def parse(self): inputs can be signed by the seed. A mismatch rather than an attack, caught here so the flow can say so before showing a transaction. - 4. _verify_input_amounts: verifies each input's claimed amount, then totals them - as verified_input_amount. Raises PSBTMissingInputUtxoError if an input is - missing the utxo that holds its amount, or PSBTInputAmountVerificationError - if an amount is unproven or false. - - 5. _parse_inputs: an input must supply every script it commits to and no others. - A missing script raises PSBTMissingInputScriptError, a wrong one + 4. _verify_input_amounts_and_scripts: verifies each input's claimed amount, then + totals them as verified_input_amount. Raises PSBTMissingInputUtxoError if an + input is missing the utxo that holds its amount, or + PSBTInputAmountVerificationError if an amount is unproven or false. Each + input must also supply every script it commits to and no others. A missing + script raises PSBTMissingInputScriptError, a wrong one PSBTInputScriptMismatchError, and an extra one - PSBTExtraneousInputScriptError. Every input must then resolve to the same - policy otherwise a RuntimeError is raised (TODO: replace the RuntimeError - with a PSBTVerificationError subclass so the View can deliberately catch this + PSBTExtraneousInputScriptError. + + 5. _parse_inputs: every input must resolve to the same policy otherwise a + RuntimeError is raised (TODO: replace the RuntimeError with a + PSBTVerificationError subclass so the View can deliberately catch this scenario and route accordingly). A policy is one of: @@ -400,7 +405,7 @@ def parse(self): self._reject_if_seed_cannot_sign() # Single source of truth for input amounts: each is verified before it is totaled - self._verify_input_amounts() + self._verify_input_amounts_and_scripts() rt = self._parse_inputs(child_key_derivation_cache) if rt == False: @@ -416,22 +421,27 @@ def parse(self): return True - def _verify_input_amounts(self): + def _verify_input_amounts_and_scripts(self): """ - Verify each input's declared amount before it is added to the total. Since SeedSigner is - airgapped, we can't look up what an input is actually worth. We're relying on what the - coordinator declared. Unchecked, a compromised coordinator could declare false amounts - and have us display any fee it liked. See the miner fee attack described in embit's - InputScope.verify(). + Verifies each input's declared amount before it is added to the total. Also + verifies that the input supplies every script it commits to and no others. This + allows us to determine the input's script type; some types have specific utxo data + requirements for verifying the input's amount. + + Since SeedSigner is airgapped, we can't look up what an input is actually worth. + We're relying on what the coordinator declared. Unchecked, a compromised + coordinator could declare false amounts and have us display any fee it liked. See + the miner fee attack described in embit's InputScope.verify(). Despite the name, an input's non_witness_utxo is the *entire* transaction that created the coin being spent, so we can hash it and confirm it produces the txid this input claims to spend. A witness_utxo is just the one output, with no such proof. - Coordinators typically only supply the witness_utxo for segwit and taproot inputs, where - the sighash commits the input amount. A lie there invalidates the signature instead - of burning funds. Legacy sighashes commit no amount at all, so legacy inputs must - supply a non_witness_utxo, otherwise a PSBTInputAmountVerificationError is raised. + Coordinators typically only supply the witness_utxo for segwit and taproot inputs, + where the sighash commits the input amount. A lie there invalidates the signature + instead of burning funds. Legacy sighashes (p2pkh and p2sh) commit no amount at + all, so legacy inputs must supply a non_witness_utxo, otherwise a + PSBTInputAmountVerificationError is raised. Known limitation: that sighash protection is not absolute. BIP-143 commits only the amount of the input being signed. A coordinator who tricks a user into signing the same @@ -448,20 +458,12 @@ def _verify_input_amounts(self): """ verified_input_amount = 0 for i, inp in enumerate(self.psbt.inputs): - if inp.non_witness_utxo is None: - if inp.witness_utxo is None: - # We have no utxo data at all. This PSBT is invalid: it tries to spend an - # input whose source coin/value is completely unknown and unverifiable. - raise PSBTMissingInputUtxoError(f"Input {i} has no utxo data") - - # Only a witness_utxo, so there is no previous transaction to hash. Raise if the - # sighash does not commit to the amount: without that commitment, the signature - # would still be valid for a false amount. - script_type = PSBTParser._get_script_type(inp, inp.script_pubkey) - if script_type in PSBTParser.UNCOMMITTED_AMOUNT_SCRIPT_TYPES: - raise PSBTInputAmountVerificationError(f"Input {i}: {script_type} input has no non_witness_utxo to verify against") + if inp.non_witness_utxo is None and inp.witness_utxo is None: + # We have no utxo data at all. This PSBT is invalid: it tries to spend an + # input whose source coin/value is completely unknown and unverifiable. + raise PSBTMissingInputUtxoError(f"Input {i} has no utxo data") - else: + if inp.non_witness_utxo is not None: # Make sure inp.vout points to an output that exists in the non_witness_utxo if inp.vout >= len(inp.non_witness_utxo.vout): raise PSBTMissingInputUtxoError(f"Input {i}: outpoint index {inp.vout} is out of range of its non_witness_utxo") @@ -484,6 +486,18 @@ def _verify_input_amounts(self): # The amounts or scripts contradict. Reject the psbt. raise PSBTInputAmountVerificationError(f"Input {i}: witness_utxo doesn't match verified non_witness_utxo") + # The next check relies on being able to trust the input's scripts. So we must + # verify that the input supplies every script it commits to and no others. + PSBTParser._verify_input_scripts(inp, inp.script_pubkey) + + if inp.non_witness_utxo is None: + # Only a witness_utxo, so there is no previous transaction to hash. Raise if the + # sighash does not commit to the amount: without that commitment, the signature + # would still be valid for a false amount. + script_type = PSBTParser._get_script_type(inp, inp.script_pubkey) + if script_type in PSBTParser.UNCOMMITTED_AMOUNT_SCRIPT_TYPES: + raise PSBTInputAmountVerificationError(f"Input {i}: {script_type} input has no non_witness_utxo to verify against") + # Every check passed, so this input amount is verified verified_input_amount += inp.utxo.value @@ -493,17 +507,13 @@ def _verify_input_amounts(self): def _parse_inputs(self, child_key_derivation_cache: dict): """ - Verifies each input's scripts and determines the wallet policy. Every input must - resolve to the same policy, otherwise a RuntimeError is raised. + Determines the wallet policy. Every input must resolve to the same policy, + otherwise a RuntimeError is raised. """ self.num_inputs = len(self.psbt.inputs) for inp in self.psbt.inputs: script_pubkey = inp.script_pubkey - # Verify the input's scripts and reject the psbt if verification fails - PSBTParser._verify_input_scripts(inp, script_pubkey) - - # Now we can use those scripts to determine this input's wallet policy inp_policy = PSBTParser._get_policy(inp, script_pubkey, self.psbt.xpubs, child_key_derivation_cache) if self.policy == None: self.policy = inp_policy diff --git a/tests/test_psbt_parser.py b/tests/test_psbt_parser.py index af8cfa5ed2..88ac7464b7 100644 --- a/tests/test_psbt_parser.py +++ b/tests/test_psbt_parser.py @@ -2880,12 +2880,12 @@ class TestPSBTParserInputScripts(PSBTParserOwnershipTestBase): 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. + 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 both a witness_utxo and a - non_witness_utxo. + The supplied psbt's first input should carry a witness_utxo. """ - # Start from a copy of our own input for its utxo fields + # Start from a copy of our own input for its witness_utxo foreign_input = deepcopy(psbt.inputs[0]) # Strip the derivation paths so the input claims none of the user's keys @@ -2897,10 +2897,9 @@ def _add_foreign_nested_segwit_input(self, psbt: PSBT, derivation_path: str = "m foreign_input.redeem_script = script.p2wpkh(public_key) foreign_input.witness_utxo.script_pubkey = script.p2sh(foreign_input.redeem_script) - # The parse verifies input amounts before the script checks, so give this coin a - # matching non_witness_utxo and point the input at its new txid. - foreign_input.non_witness_utxo.vout[foreign_input.vout].script_pubkey = foreign_input.witness_utxo.script_pubkey - foreign_input.txid = foreign_input.non_witness_utxo.txid() + # 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 @@ -3055,7 +3054,9 @@ def test__parse__checks_input_scripts_whoever_the_input_belongs_to(self): assert psbt_parser.num_inputs == 2 assert psbt_parser.verified_input_derivation_paths[1] == [] - # Omit its redeem script + # 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 pytest.raises(PSBTMissingInputScriptError): self._parse(psbt) From bcd2610bf8cf37fe28ed1c845b0427c5413d7487 Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:04:19 -0500 Subject: [PATCH 44/48] Rewrap the amount check's comments at 90 columns The docstring and inline comments in _verify_input_amounts_and_scripts ran to 104 columns. They are now wrapped at 90, with no wording changes apart from a closing period on the two comments that now span two lines. Comment-only change. --- src/seedsigner/models/psbt_parser.py | 60 +++++++++++++++------------- 1 file changed, 33 insertions(+), 27 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index fef3f10255..4f182174d5 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -433,9 +433,10 @@ def _verify_input_amounts_and_scripts(self): coordinator could declare false amounts and have us display any fee it liked. See the miner fee attack described in embit's InputScope.verify(). - Despite the name, an input's non_witness_utxo is the *entire* transaction that created - the coin being spent, so we can hash it and confirm it produces the txid this input - claims to spend. A witness_utxo is just the one output, with no such proof. + Despite the name, an input's non_witness_utxo is the *entire* transaction that + created the coin being spent, so we can hash it and confirm it produces the txid + this input claims to spend. A witness_utxo is just the one output, with no such + proof. Coordinators typically only supply the witness_utxo for segwit and taproot inputs, where the sighash commits the input amount. A lie there invalidates the signature @@ -443,18 +444,20 @@ def _verify_input_amounts_and_scripts(self): all, so legacy inputs must supply a non_witness_utxo, otherwise a PSBTInputAmountVerificationError is raised. - Known limitation: that sighash protection is not absolute. BIP-143 commits only the - amount of the input being signed. A coordinator who tricks a user into signing the same - multi-input transaction more than once can understate different inputs in each round, - so every round shows a normal-looking fee. It then combines each input's signature from - a round where that input's amount was true, producing a valid transaction whose real - fee is far higher than any round showed (CVE-2020-14199). Taproot is not affected: - BIP-341 commits the amount of every input. - - We accept that risk for segwit rather than warn about it, because the data needed to - close it isn't coming. Wallets generally provide non_witness_utxo *or* witness_utxo but - not both, likely to keep psbts small for QR-based signers. Warning on it would therefore - fire on nearly every ordinary multi-input segwit spend. + Known limitation: that sighash protection is not absolute. BIP-143 commits only + the amount of the input being signed. A coordinator who tricks a user into signing + the same multi-input transaction more than once can understate different inputs in + each round, so every round shows a normal-looking fee. It then combines each + input's signature from a round where that input's amount was true, producing a + valid transaction whose real fee is far higher than any round showed + (CVE-2020-14199). Taproot is not affected: BIP-341 commits the amount of every + input. + + We accept that risk for segwit rather than warn about it, because the data needed + to close it isn't coming. Wallets generally provide non_witness_utxo *or* + witness_utxo but not both, likely to keep psbts small for QR-based signers. + Warning on it would therefore fire on nearly every ordinary multi-input segwit + spend. """ verified_input_amount = 0 for i, inp in enumerate(self.psbt.inputs): @@ -464,22 +467,24 @@ def _verify_input_amounts_and_scripts(self): raise PSBTMissingInputUtxoError(f"Input {i} has no utxo data") if inp.non_witness_utxo is not None: - # Make sure inp.vout points to an output that exists in the non_witness_utxo + # Make sure inp.vout points to an output that exists in the + # non_witness_utxo. if inp.vout >= len(inp.non_witness_utxo.vout): raise PSBTMissingInputUtxoError(f"Input {i}: outpoint index {inp.vout} is out of range of its non_witness_utxo") try: - # verify() checks that the provided non_witness_utxo matches the txid this - # input spends. + # verify() checks that the provided non_witness_utxo matches the txid + # this input spends. inp.verify() except PSBTError as e: - # The provided non_witness_utxo is not the transaction that created this coin. - # As a result, we cannot trust the psbt's claims about the amount this input spends. - # We treat this as an attack. + # The provided non_witness_utxo is not the transaction that created + # this coin. As a result, we cannot trust the psbt's claims about the + # amount this input spends. We treat this as an attack. raise PSBTInputAmountVerificationError(f"Input {i}: {e}") - # With both non_witness_utxo and witness_utxo present, compare them. verify() only - # proved the non_witness_utxo, so the witness_utxo must match its output at inp.vout. + # With both non_witness_utxo and witness_utxo present, compare them. + # verify() only proved the non_witness_utxo, so the witness_utxo must + # match its output at inp.vout. if inp.witness_utxo is not None: prevout = inp.non_witness_utxo.vout[inp.vout] if prevout.value != inp.witness_utxo.value or prevout.script_pubkey.data != inp.witness_utxo.script_pubkey.data: @@ -491,9 +496,9 @@ def _verify_input_amounts_and_scripts(self): PSBTParser._verify_input_scripts(inp, inp.script_pubkey) if inp.non_witness_utxo is None: - # Only a witness_utxo, so there is no previous transaction to hash. Raise if the - # sighash does not commit to the amount: without that commitment, the signature - # would still be valid for a false amount. + # Only a witness_utxo, so there is no previous transaction to hash. Raise + # if the sighash does not commit to the amount: without that commitment, + # the signature would still be valid for a false amount. script_type = PSBTParser._get_script_type(inp, inp.script_pubkey) if script_type in PSBTParser.UNCOMMITTED_AMOUNT_SCRIPT_TYPES: raise PSBTInputAmountVerificationError(f"Input {i}: {script_type} input has no non_witness_utxo to verify against") @@ -501,7 +506,8 @@ def _verify_input_amounts_and_scripts(self): # Every check passed, so this input amount is verified verified_input_amount += inp.utxo.value - # Only assigned once every input has passed, so a rejected psbt leaves no partial total + # Only assigned once every input has passed, so a rejected psbt leaves no partial + # total. self.verified_input_amount = verified_input_amount From dd2a2bea6dd7076be02694d51afe5d4568e7ae05 Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Sat, 24 Oct 2026 13:58:04 -0500 Subject: [PATCH 45/48] Move error names out of parse()'s step list parse()'s docstring is a high-level overview of the steps. _verify_input_amounts_and_scripts and _verify_input_scripts each end their docstring with a list of every error they raise, and name the errors only there. --- src/seedsigner/models/psbt_parser.py | 43 ++++++++++++++-------------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 4f182174d5..df2204d185 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -323,20 +323,14 @@ def parse(self): 2. _verify_claimed_derivation_paths: each input and output that claims to be controlled by the seed declares a derivation path that must be verified. - Raises an Input/Output OwnershipClaimError if a claim fails verification. - 3. _reject_if_seed_cannot_sign: raises PSBTSeedCannotSignError if none of the - inputs can be signed by the seed. A mismatch rather than an attack, caught - here so the flow can say so before showing a transaction. + 3. _reject_if_seed_cannot_sign: rejects the psbt if none of the inputs can be + signed by the seed. A mismatch rather than an attack, caught here so the flow + can say so before showing a transaction. 4. _verify_input_amounts_and_scripts: verifies each input's claimed amount, then - totals them as verified_input_amount. Raises PSBTMissingInputUtxoError if an - input is missing the utxo that holds its amount, or - PSBTInputAmountVerificationError if an amount is unproven or false. Each - input must also supply every script it commits to and no others. A missing - script raises PSBTMissingInputScriptError, a wrong one - PSBTInputScriptMismatchError, and an extra one - PSBTExtraneousInputScriptError. + totals them as verified_input_amount. Each input must also supply every + script it commits to and no others. 5. _parse_inputs: every input must resolve to the same policy otherwise a RuntimeError is raised (TODO: replace the RuntimeError with a @@ -361,8 +355,8 @@ def parse(self): - multisig: Match each of the seed's verified keys against the pubkeys in the script the output commits to. Every change_data entry after this point will carry a derivation path that - our seed provably owns. Raises PSBTNegativeFeeError if the outputs spend more - than the inputs bring in. + our seed provably owns. Also rejects a psbt whose outputs spend more than its + inputs bring in. Optimization via child_key_derivation_cache: Parsing traverses a derivation path down to an individual address one level at a @@ -441,8 +435,7 @@ def _verify_input_amounts_and_scripts(self): Coordinators typically only supply the witness_utxo for segwit and taproot inputs, where the sighash commits the input amount. A lie there invalidates the signature instead of burning funds. Legacy sighashes (p2pkh and p2sh) commit no amount at - all, so legacy inputs must supply a non_witness_utxo, otherwise a - PSBTInputAmountVerificationError is raised. + all, so legacy inputs must supply a non_witness_utxo. Known limitation: that sighash protection is not absolute. BIP-143 commits only the amount of the input being signed. A coordinator who tricks a user into signing @@ -458,6 +451,13 @@ def _verify_input_amounts_and_scripts(self): witness_utxo but not both, likely to keep psbts small for QR-based signers. Warning on it would therefore fire on nearly every ordinary multi-input segwit spend. + + Raises: + * PSBTMissingInputUtxoError: An input's utxo is missing. + * PSBTInputAmountVerificationError: An input's amount is unproven or false. + * PSBTMissingInputScriptError: An input is missing a script it commits to. + * PSBTInputScriptMismatchError: An input supplies the wrong script. + * PSBTExtraneousInputScriptError: An input supplies an extraneous script. """ verified_input_amount = 0 for i, inp in enumerate(self.psbt.inputs): @@ -549,18 +549,19 @@ def _verify_input_scripts(inp: InputScope, script_pubkey: script.Script): p2sh-p2wsh: p2sh(redeem_script) == scriptPubKey p2wsh(witness_script) == redeem_script - If any required scripts are missing, raise PSBTMissingInputScriptError. - - If any comparison required above fails, we raise PSBTInputScriptMismatchError. - **** For all script types: **** Each input commits to a specific script type. It should not include any extraneous scripts that are not required by that script type (e.g. a witness_script on a p2sh input). Such a script could distort the parser's understanding of the wallet being spent from, which would affect its determination of whether an output is the user's change. But it's also possible that a buggy coordinator just created an odd - psbt. Either way, we raise PSBTExtraneousInputScriptError for any extraneous - script. + psbt. Either way, we reject the psbt. + **** + + Raises: + * PSBTMissingInputScriptError: An input is missing a script it commits to. + * PSBTInputScriptMismatchError: An input supplies the wrong script. + * PSBTExtraneousInputScriptError: An input supplies an extraneous script. """ # 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 From c255bf5716656bef6d0ade523933e2158f3b8fd4 Mon Sep 17 00:00:00 2001 From: kdmukai <934746+kdmukai@users.noreply.github.com> Date: Wed, 28 Oct 2026 08:08:07 -0500 Subject: [PATCH 46/48] Enable Swahili --- src/seedsigner/models/settings_definition.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/seedsigner/models/settings_definition.py b/src/seedsigner/models/settings_definition.py index 52b31c8786..6b055f949a 100644 --- a/src/seedsigner/models/settings_definition.py +++ b/src/seedsigner/models/settings_definition.py @@ -101,6 +101,7 @@ class SettingsConstants: LOCALE__SLOVENIAN = "sl" LOCALE__SPANISH = "es" LOCALE__SWEDISH = "sv" + LOCALE__SWAHILI = "sw" LOCALE__TAGALOG = "tl" LOCALE__TAMIL = "ta" LOCALE__TELUGU = "te" @@ -139,6 +140,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)", From f58e943c9f5896293697e37e626eef5e0537cbbb Mon Sep 17 00:00:00 2001 From: 3rd Iteration Date: Sat, 31 Oct 2026 22:01:35 -0400 Subject: [PATCH 47/48] Add test vectors for the upstream input/OP_RETURN/nested-change merge 24 new corpus vectors, with _V2 twins where the trap is not version-specific. derive_followup_vectors.py derives each one from a vendored fixture with a single edit, and is deterministic: - OP_RETURN: a Runes runestone (OP_13), small-int pushes and a multi-push are negative controls that must be shown. A truncated push and a non-push opcode are refused as MALFORMED_OP_RETURN. - Input scripts: a stray redeem_script, a missing redeem_script or witness_script, a wrong redeem_script, and a wrong script on another party's input in a collaborative spend. - Change: nested segwit change without its redeem_script is counted as change. A redeem-less output that claims this seed but pays a stranger is refused as FORGED_OUTPUT_OWNERSHIP; before the merge it parsed as an ordinary payment. - A zero fee is accepted. Also asserts the exact payload shown for each push-only OP_RETURN vector, and records the vectors in PROVENANCE.md. Co-Authored-By: Claude Opus 5.5 --- tests/data/psbt_test_suite/PROVENANCE.md | 24 +++ ...nested_bare_p2sh_claims_us_pays_other.psbt | Bin 0 -> 333 bytes ...ted_bare_p2sh_claims_us_pays_other_V2.psbt | Bin 0 -> 367 bytes .../XTRAS.FOREIGN_INPUT_BAD_SCRIPT.psbt | Bin 0 -> 460 bytes .../XTRAS.MISSING_REDEEM_SCRIPT.psbt | Bin 0 -> 333 bytes .../XTRAS.MISSING_REDEEM_SCRIPT_V2.psbt | Bin 0 -> 367 bytes .../XTRAS.MISSING_WITNESS_SCRIPT.psbt | Bin 0 -> 738 bytes .../XTRAS.NESTED_CHANGE_NO_REDEEM.psbt | Bin 0 -> 333 bytes .../XTRAS.NESTED_CHANGE_NO_REDEEM_V2.psbt | Bin 0 -> 367 bytes .../XTRAS.OP_RETURN_MULTI_PUSH.psbt | Bin 0 -> 356 bytes .../XTRAS.OP_RETURN_MULTI_PUSH_V2.psbt | Bin 0 -> 395 bytes .../XTRAS.OP_RETURN_NON_PUSH.psbt | Bin 0 -> 347 bytes .../XTRAS.OP_RETURN_NON_PUSH_V2.psbt | Bin 0 -> 386 bytes .../XTRAS.OP_RETURN_RUNESTONE.psbt | Bin 0 -> 351 bytes .../XTRAS.OP_RETURN_RUNESTONE_V2.psbt | Bin 0 -> 390 bytes .../XTRAS.OP_RETURN_SMALLINT.psbt | Bin 0 -> 344 bytes .../XTRAS.OP_RETURN_SMALLINT_V2.psbt | Bin 0 -> 383 bytes .../XTRAS.OP_RETURN_TRUNCATED_PUSH.psbt | Bin 0 -> 346 bytes .../XTRAS.OP_RETURN_TRUNCATED_PUSH_V2.psbt | Bin 0 -> 385 bytes .../XTRAS.STRAY_REDEEM_SCRIPT.psbt | Bin 0 -> 333 bytes .../XTRAS.STRAY_REDEEM_SCRIPT_V2.psbt | Bin 0 -> 367 bytes .../XTRAS.WRONG_REDEEM_SCRIPT.psbt | Bin 0 -> 358 bytes .../XTRAS.WRONG_REDEEM_SCRIPT_V2.psbt | Bin 0 -> 392 bytes .../data/psbt_test_suite/XTRAS.ZERO_FEE.psbt | Bin 0 -> 329 bytes .../psbt_test_suite/XTRAS.ZERO_FEE_V2.psbt | Bin 0 -> 363 bytes .../derive_followup_vectors.py | 129 ++++++++++++++ tests/psbt_suite_util.py | 168 ++++++++++++++++++ tests/test_psbt_test_suite.py | 14 ++ 28 files changed, 335 insertions(+) create mode 100644 tests/data/psbt_test_suite/TX-21.nested_bare_p2sh_claims_us_pays_other.psbt create mode 100644 tests/data/psbt_test_suite/TX-21.nested_bare_p2sh_claims_us_pays_other_V2.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.FOREIGN_INPUT_BAD_SCRIPT.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.MISSING_REDEEM_SCRIPT.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.MISSING_REDEEM_SCRIPT_V2.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.MISSING_WITNESS_SCRIPT.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.NESTED_CHANGE_NO_REDEEM.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.NESTED_CHANGE_NO_REDEEM_V2.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.OP_RETURN_MULTI_PUSH.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.OP_RETURN_MULTI_PUSH_V2.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.OP_RETURN_NON_PUSH.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.OP_RETURN_NON_PUSH_V2.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.OP_RETURN_RUNESTONE.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.OP_RETURN_RUNESTONE_V2.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.OP_RETURN_SMALLINT.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.OP_RETURN_SMALLINT_V2.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.OP_RETURN_TRUNCATED_PUSH.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.OP_RETURN_TRUNCATED_PUSH_V2.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.STRAY_REDEEM_SCRIPT.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.STRAY_REDEEM_SCRIPT_V2.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.WRONG_REDEEM_SCRIPT.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.WRONG_REDEEM_SCRIPT_V2.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.ZERO_FEE.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.ZERO_FEE_V2.psbt create mode 100644 tests/data/psbt_test_suite/derive_followup_vectors.py diff --git a/tests/data/psbt_test_suite/PROVENANCE.md b/tests/data/psbt_test_suite/PROVENANCE.md index 360c48acaf..6db43bb1f6 100644 --- a/tests/data/psbt_test_suite/PROVENANCE.md +++ b/tests/data/psbt_test_suite/PROVENANCE.md @@ -92,3 +92,27 @@ 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). Unlike the vectors above, these are **not** +generated by psbt_faker. `derive_followup_vectors.py` (in this directory) derives each +one from a vendored fixture (`NORMAL-1_p2wpkh(_V2)`, `NORMAL-2_wrapped(_V2)` or +`TX-21.ms_honest_change_no_xpubs`) with a single edit, so the trap is the only +difference from a psbt that must sign cleanly. The script is deterministic: run it +from the repository root to regenerate the same bytes. The one foreign key it uses +comes from a fixed throwaway seed, which no corpus wallet derives. + +* 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`). +* 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 0000000000000000000000000000000000000000..9f66aab470aedf438eb3ad5fea7affe547139812 GIT binary patch literal 333 zcmXRYPAd7&$WYA0z`($`tX=LyAm>%bYv(HUX8CG6y?tr9drSC|+4t`sKe_Hhs~S)Z z1H*qHVES?A7f1(#_(~DSeaDuv9jaQo{yl%GMWM6-lgfv??MU+bQ?3{qh!#ry>FPKg z(!SVye!b}Cc932MMn(mOhhJGiOrSY32OrEzzPPS3s?gxU%uQX~vVH#R+8J5I7)0Vr z)t9qM^~PCk%9+C2D!2LEOX+kaHl{6%b5eE-yYDTUmGw)|r27WJ62(VvaTzi&Gyu&9V@4nY3>a~`n?Z?*Ny|xo$+D>Si-(^mH-_GbufBA2cYCtF Vv2?i7M}df}g)=bB1(^vp8vsq7eEk3b literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..cfeb01d3d58cbe82a7dc0cb977438793d2cbf509 GIT binary patch literal 367 zcmXRYPAd7&$i%|Lz`(%B%mO4C7+Dw@8Ce;b7=MFB85kKA7#@CQ1xbmo6p=ajU{>f)B|^IzA_$Rfrd5?`vmoK>nf&T3Q66xLR`&F5Z9rz^2BZDE{~vRl}F zZ_%u*UxFsxH@Kg?J}h#d`CG{Mw*8N`EZ2}IK6;DGkb$8AXg(M-0vRB{$fvNZUG765 z=T*mR=PLDP`D#18eQCLSOZbx6_wOG+x$Z-&8Y4f%#R4q|5hE3v6vb5?NlmJU0(LZ%;geu0c;5ML?c zxbN6fwnJ4**T3g4wJ4M}U{d*Tw;f6TQh!e~r;!dvfZ_*^#7{NTt^YG`ZwH&i$f&^Z z@GC3S9GQa;W+h)-R~c1k@L=YqE^gUA|8?z*EMg2I@ulj^S*3d8tTyFLVQrP$eD0-m zx)K}H7REU#yM^8N7R}1~C1}!pgZs(r!y@;YzlD5n+y7|Gat(>%qqn#W85kOX7JxA$ z$R-d#wRrC|E4P3EL#D|y*SeTjseTPiUHTnjad-TK_0s*%CN5msYxCt~%=u$|R!Izu zI6V!N0=o8F@xNs`+YAf#-0(`td6x6x?wwgiN=!^zPV!5ZMYUf%{6x7i^hSL3rK7vs Xll6_I!<9Y?L}V?Tf#F)PLqP-pD^RwA literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..e49e318ce1bb5b70e8177ada3e26713c02f31957 GIT binary patch literal 333 zcmXRYPAd7&$WYA0z`($`tX=LyAm>%bYv(HUX8CG6y?tr9drSC|+4t`sKe_Hhs~S)Z z1H*qHVES?A7f1(#_(~DSeaDuv9jaQo{yl%GMWM6-lgfv??MU*M`g@u=jdVBy6hCkz zeyW*n{hxVzJ4i1BBclSt!>_C$CeR$2gAZmUUtCuiRcP>F=B6%g**^bu?MiG+TNvl0 z>=t(4TQn={m!L`a4elqe4~yJq{uc7RZU3V!%QYm5kKW=kWMF6j8Ux0RKn55v;&dJZ zBZC-&$hYEu%W}3E7VNpf)B|^IzAl#KyFRaZbu^VfVd7v$B2(nsndbe)9UT$bIH-A>Z5fKiaZf zL!$WTEiOX_h6bQ9V9W?)fB++(!m@U`4}qLl9j~3M)SKn2?ezAg1!C21bxO=Iy-^xZuwK9`W`BwaIS18f(_J~XQ@_4hP$8tHHZD1P8b{8TgD`akpbb_M`(=z|yl literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..1c44867a1cc14a5a063078f70d38b38a3b869bff GIT binary patch literal 738 zcmXRYPAd7&$k55ez`(#5^=(aYL};e)MDeQXB^O^j`1xaASH_gN|5CVX|NG57>Ht*3 z!0;aknAWr~f;mbI3hJ&2Oa^E7-p^Gz>T~vo?A8F|XSq$h0lw3^PMvtax$+Z|(l61> z*QRqNAN&1I^uzvlSEsyAOF#2y_TqyoTVp~d?+Gjf8_CEJ2X@TbdtffZ`+X1^o%93= zfE>fOCPmW49U|?tfDhFeriy9z42I*(^ zkTGlR4vqI!RyhzV{pjW7-li^_00z;JSu>*d_U5nuCsTa%78f4|^1EVvk!GYY?1v&L?-xUC|yQVeUM!m0KHZy))3D)nn?SuF1~yrL~WA!X6ALsuF% ze^X@6b#ZPn746GEEMvQ7&z-xq&$tv*N=4dO?ipJ1Yt0Cp61+}{iJ(PTJqrvt22g-0 WF%fhIR?i~oC*(-1kp%bYv(HUX8CG6y?tr9drSC|+4t`sKe_Hhs~S)Z z1H*qHVES?A7f1(#_(~DSeaDuv9jaQo{yl%GMWM6-lgfv??MU*M`g@u=jdVBy6hCkz zeyW*n{hxVzJ4i1BBclSt!>_C$CeR$2gAZmUUtCuiRcP>F=B6%g**^bu?Tjp93?lKR z>dRTBdgH7%8i3}5F(Z%x28=k}&7j1@q~#>PWLZ@E#lugO8$)lzS6@21yFFRo VSUOzkqd-K~!WkImg3JV)4FH%(d@}$5 literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..a07aff6d0f326bee2a4fac406c6753ce75de698f GIT binary patch literal 367 zcmXRYPAd7&$i%|Lz`(%B%mO4C7+Dw@8Ce;b7=MFB85kKA7#@CQ1xbmo6p=ajU{>f)B|^IzA_$Rfrd5?`vmoK>nf&T3Q66xLR`&F5Z9rz^2BZDE{~vRl}F zZ_%u*UxFsxH@Kg?J}h#d`CG{Mw*8N`EZ2}IK6;DGkb$8AXg(M-0vRB{$fvNZUG765 z=T*mR=PLDP`D#18eQCLSOZbx6_wOG+x$Z-&8Y4f%#R4q`MIA~w>~&^+SdJv_6Dx zhW|jo{Nv6qkPZeh29dj_AJ2RFGw*ci>Daa>PUp~AEuO4urMQ|Jj27UtRObfd^?jFv8VFyp8Rb# z)8WbS8;{!UgXSo)F*60Lbo4pR+VS}Idie^blyHCBRxBu;o≶-j~? zLKqktfTn;kBai_GjEp#3%>b6c=3pfz=I5n<13%o~akedX{>L+m7Dk*;m47+?@5z5J T4_@B-a_Xyc4EsQKLF@zonHY#3 literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..60d59772dbea367d9140925ae5ededf2ea9ab938 GIT binary patch literal 395 zcmXRYPAd7&$i%|Lz`(%B%mO4C7+Dw@8Ce;b8GnOC85kMm86JLR1xbl9h}fCTh&`2m z_vCN0nGR2m-+0t+A2dgajhQJ}rK8Vj){e)w*UMKhrF74^AUE5wrS<49AL-fQ3=fw{ z6d%3C6~e&K05k=R8G#HCVB}Ny$H3m(wKBz~KHOexfA;dc{M=8gTOXV{ZR`F-`-Y>i z5+gsvT>>osfdJ?ppfi|7=D(YLd(zr72C6KGg5PM@_m^Z5|fgBm{L+10A50iSpWb4 literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..8907af7247911aef08927ba98b91be3ba894a053 GIT binary patch literal 347 zcmXRYPAd7&$k4>Zz`(%xkAc0nYh{W}eYm~Y{_N#>`MIA~w>~&^+SdJv_6Dx zhW|jo{Nv6qkPZeh29dj_AJ2RFGw*ci>Daa>PUpx4$1{r-Mx0NTe>wf{$$u{oUf%k0>Z@`L K`#^R<>;wQ3t%fTA literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..ac79fb8836b29a9155df01379994735f1d6b74bd GIT binary patch literal 386 zcmXRYPAd7&$i%|Lz`(%B%mO4C7+Dw@8Ce;b8GnOC85kMm86JLR1xbl9h}fCTh&`2m z_vCN0nGR2m-+0t+A2dgajhQJ}rK8Vj){e)w*UMKhrF74^AUE5wrS<49AL-fQ3=fw{ z6d%3C6~e&K05k=R8G#HCVB}Ny$H3m(wKBz~KHOexfA;dc{M=8gTOXV{ZR`F-`-Y>i z5+gsvT>>osfdJ?ppfi|7=D(YLd(zr72C`MIA~w>~&^+SdJv_6Dx zhW|jo{Nv6qkPZeh29dj_AJ2RFGw*ci>Daa>PUp;u^au@eAk?uC~C literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..2310a2cc4775bcbc07af3c99b0d0d51ac3c019ab GIT binary patch literal 390 zcmXRYPAd7&$i%|Lz`(%B%mO4C7+Dw@8Ce;b8GnOC85kMm86JLR1xbl9h}fCTh&`2m z_vCN0nGR2m-+0t+A2dgajhQJ}rK8Vj){e)w*UMKhrF74^AUE5wrS<49AL-fQ3=fw{ z6d%3C6~e&K05k=R8G#HCVB}Ny$H3m(wKBz~KHOexfA;dc{M=8gTOXV{ZR`F-`-Y>i z5+gsvT>>osfdJ?ppfi|7=D(YLd(zr72C`MIA~w>~&^+SdJv_6Dx zhW|jo{Nv6qkPZeh29dj_AJ2RFGw*ci>Daa>PUpG0(EjYsYFL35PY zn3;lAI{KVu?Rb29y?g~zO81-#ai z5+gsvT>>osfdJ?ppfi|7=D(YLd(zr72C`MIA~w>~&^+SdJv_6Dx zhW|jo{Nv6qkPZeh29dj_AJ2RFGw*ci>Daa>PUp_C$HqcZ%lNqt6^6#GfZ8p>4$?+SH+U%QInCPf`1X4F3Z|6qITz$+JGQhQ{pBM)JDlO+GKu1&x41$W7#e`4fH5PG z0S1hWINZtrmciysB_`(QrGEoI+~0AwEq4CLGm92RoKKa1IsNa+e=iSS-uiOtt8xtc JKz2dw1OS;zh1LK7 literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..08076f265250d9fb2cf35d1b88c52dc7a5116729 GIT binary patch literal 385 zcmXRYPAd7&$i%|Lz`(%B%mO4C7+Dw@8Ce;b8GnOC85kMm86JLR1xbl9h}fCTh&`2m z_vCN0nGR2m-+0t+A2dgajhQJ}rK8Vj){e)w*UMKhrF74^AUE5wrS<49AL-fQ3=fw{ z6d%3C6~e&K05k=R8G#HCVB}Ny$H3m(wKBz~KHOexfA;dc{M=8gTOXV{ZR`F-`-Y>i z5+gsvT>>osfdJ?ppfi|7=D(YLd(zr72C`MIA~w>~&^+SdJv_6Dx zhW|jo^yAJikPZeh29dj_AJ2RFGw*ci>Daa>PUpTh<#y}-DW~N}3 zjy|VZJ09O&FJHlw(mm&b+-%2|)}z0Cq-TdSJX|JGeDoGq2m?a{&?GQs1Tw&Ykr9Xc zfR+PgusKbMiTQcy-@p&|cbsjDo&WL7qJosx%U3X^bkDgUH`}qL_2@4j>Dl27 z50^<4AHBsD!obh~Gzp9ufea8}^+)t}pADlXE>;6Rh zhNG|&BR|A#0xbW50O%&5Q%bYv(HUX8CG6y?tr9drSC|+4t`sKe_Hhs~S)Z z1H*qHVES?A7f1(#_(~DSeaDuv9jaQo{yl%GMWM6-lgfv??MU*M`g@u=jdVBy6hCkz zeyW*n{hxVzJ4i1BBclSt!>_C$CeR$2gAZmUUtCuiRcP>F=B6%g**^bu?Tjp93?gS# zOxVl)bl)|6X}D<@+47d*XZ}7VHl{6%b5eE-yYDTUmGw)|r27WJ62(VvaTzi&Gyu&9V@4nY3>a~`n}Lx5XyLcwf6H>V85Zoh;gyo}Ea$`BJF|?G un3%Mjl;glD}5A*$XYl9!$Oc{U`qk5f{J|r literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..a0e496acedc983c1babb9b9c5197354d582d63b4 GIT binary patch literal 392 zcmXRYPAd7&$i%|Lz`(%B%mO4C7+Dw@8Ce;b7=MFB85kKA7#@CQ1xbmo6p=ajU{>f)B|^IzA_$Rfrdaz@33z1&atUBj1#n|6^cZyA2(?^9x9+QK*|Ww)^V z-lADqzXVOXZ*V_(eOTl^^S6-iZTlZ>S*{^beDoHVAp=7L(0njv1TsK?kxyY+yWEFB z&Z~~s&Qcq|8JRhL-1!CaB+z@f6an=Ez45L1-?E%-h6Q_Wc%|e#%lUBk&MYG( zCMGQ>`6bJu+Akh{qTCpIBfk35(cSII`o_}XN*@IxvKG$3@CMi}kbP)YU+V8^<}}jb T2vGdMk@%@*y7hnN?d=QzU3862 literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..e19f88db4e252f5bc2425b0a112f83b6f4a48740 GIT binary patch literal 329 zcmXRYPAd7&$WX|{z`(%xkAc0nYh{W}eYm~Y{_N#>`MIA~w>~&^+SdJv_6Dx zhW|jo^yAJikPZeh29dj_AJ2RFGw*ci>Daa>PUpjQM-N693?hpreKwh zKBrkb9^YOsU%`~pJ?DblY{!i z5+gsvT>>osfdJ?ppfi|7=D(YLd(zr72C6!t03@n}UjP6A literal 0 HcmV?d00001 diff --git a/tests/data/psbt_test_suite/derive_followup_vectors.py b/tests/data/psbt_test_suite/derive_followup_vectors.py new file mode 100644 index 0000000000..5f520546a5 --- /dev/null +++ b/tests/data/psbt_test_suite/derive_followup_vectors.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +""" +Derives the "Follow-up of 2026-10-31" vectors (see PROVENANCE.md) from vendored +psbt_faker fixtures. + +Each vector is a vendored NORMAL-* (or multisig negative control) fixture with one +surgical edit, so the trap is the only thing that differs from a psbt that must sign +cleanly. Run from the repository root: + + python tests/data/psbt_test_suite/derive_followup_vectors.py + +The output is deterministic; re-running rewrites the same bytes. +""" +import hashlib +import os + +from embit import bip32, script +from embit.psbt import PSBT, OutputScope + + +HERE = os.path.dirname(os.path.abspath(__file__)) + + +def load(name: str) -> PSBT: + with open(os.path.join(HERE, name + ".psbt"), "rb") as f: + return PSBT.parse(f.read()) + + +def write(name: str, psbt: PSBT): + with open(os.path.join(HERE, name + ".psbt"), "wb") as f: + f.write(psbt.serialize()) + + +def foreign_key(index: int): + """A key no corpus seed derives: a fixed throwaway root, mainnet BIP49 receive path.""" + root = bip32.HDKey.from_seed(hashlib.sha256(b"seedsigner-followup-2026-10-31-foreign").digest()) + return root.derive(f"m/49h/0h/0h/0/{index}").get_public_key() + + +def with_op_return(base: str, script_bytes: bytes) -> PSBT: + """Appends a zero-value OP_RETURN output with the given raw script. The fee is unchanged.""" + psbt = load(base) + out = OutputScope() + out.script_pubkey = script.Script(script_bytes) + out.value = 0 + psbt.outputs.append(out) + return psbt + + +RUNESTONE = bytes.fromhex("00c0a2331414010203") + +# (name, raw OP_RETURN script). Each gets a v0 and a _V2 twin. +OP_RETURN_VECTORS = [ + # Runes: OP_RETURN OP_13 . Push-only per Core's IsPushOnly. + ("XTRAS.OP_RETURN_RUNESTONE", b"\x6a\x5d" + bytes([len(RUNESTONE)]) + RUNESTONE), + # OP_0, OP_1NEGATE, OP_1, OP_16: pushes that carry no data bytes. + ("XTRAS.OP_RETURN_SMALLINT", b"\x6a\x00\x4f\x51\x60"), + # A direct push, an OP_PUSHDATA2 and an OP_PUSHDATA1, concatenated: "helloabcde". + ("XTRAS.OP_RETURN_MULTI_PUSH", b"\x6a\x05hello" + b"\x4d\x03\x00abc" + b"\x4c\x02de"), + # OP_PUSHDATA2 declaring 255 bytes, with 3 present. + ("XTRAS.OP_RETURN_TRUNCATED_PUSH", b"\x6a\x4d\xff\x00abc"), + # A valid push followed by OP_CHECKSIG. + ("XTRAS.OP_RETURN_NON_PUSH", b"\x6a\x05hello\xac"), +] + + +def main(): + for name, raw in OP_RETURN_VECTORS: + write(name, with_op_return("NORMAL-1_p2wpkh", raw)) + write(name + "_V2", with_op_return("NORMAL-1_p2wpkh_V2", raw)) + + for suffix in ("", "_V2"): + # Native segwit input carrying a redeem_script it does not commit to. + psbt = load("NORMAL-1_p2wpkh" + suffix) + psbt.inputs[0].redeem_script = script.Script(b"\x51") + write("XTRAS.STRAY_REDEEM_SCRIPT" + suffix, psbt) + + # Nested segwit input with its redeem_script left out. + psbt = load("NORMAL-2_wrapped" + suffix) + psbt.inputs[0].redeem_script = None + write("XTRAS.MISSING_REDEEM_SCRIPT" + suffix, psbt) + + # Nested segwit input whose redeem_script wraps a different key than the one its + # scriptPubKey commits to. + psbt = load("NORMAL-2_wrapped" + suffix) + psbt.inputs[0].redeem_script = script.p2wpkh(foreign_key(0)) + write("XTRAS.WRONG_REDEEM_SCRIPT" + suffix, psbt) + + # Genuine nested segwit change, minus its (BIP-174 optional) redeem_script. + psbt = load("NORMAL-2_wrapped" + suffix) + psbt.outputs[1].redeem_script = None + write("XTRAS.NESTED_CHANGE_NO_REDEEM" + suffix, psbt) + + # The same redeem-less change output, repointed at a stranger's key while it + # keeps this seed's derivation claim. + psbt = load("NORMAL-2_wrapped" + suffix) + psbt.outputs[1].redeem_script = None + psbt.outputs[1].script_pubkey = script.p2sh(script.p2wpkh(foreign_key(1))) + write("TX-21.nested_bare_p2sh_claims_us_pays_other" + suffix, psbt) + + # p2wsh multisig input with its witness_script left out. + psbt = load("TX-21.ms_honest_change_no_xpubs") + psbt.inputs[0].witness_script = None + write("XTRAS.MISSING_WITNESS_SCRIPT", psbt) + + # A collaborative spend: our nested segwit input plus another party's, whose + # redeem_script is not the one its scriptPubKey commits to. The other party's input + # claims none of our keys, but its scripts are checked all the same. + psbt = load("NORMAL-2_wrapped") + from copy import deepcopy + other = deepcopy(psbt.inputs[0]) + other.txid = hashlib.sha256(b"followup-foreign-outpoint").digest() + other.vout = 0 + other.bip32_derivations.clear() + other.non_witness_utxo = None + other.witness_utxo.script_pubkey = script.p2sh(script.p2wpkh(foreign_key(2))) + other.redeem_script = script.p2wpkh(foreign_key(3)) + psbt.inputs.append(other) + write("XTRAS.FOREIGN_INPUT_BAD_SCRIPT", psbt) + + # Zero fee: the change output absorbs the original 10,000 sat fee. + for suffix in ("", "_V2"): + psbt = load("NORMAL-1_p2wpkh" + suffix) + psbt.outputs[1].value += 10_000 + write("XTRAS.ZERO_FEE" + suffix, psbt) + + +if __name__ == "__main__": + main() diff --git a/tests/psbt_suite_util.py b/tests/psbt_suite_util.py index a7a81ffeea..2ec06ef4e5 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,171 @@ 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. Derived from the vendored + # fixtures by data/psbt_test_suite/derive_followup_vectors.py; 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.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/test_psbt_test_suite.py b/tests/test_psbt_test_suite.py index 9297bd20c7..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 From 8e479ef3db98a25d0e298c87de3edfb553dcbd44 Mon Sep 17 00:00:00 2001 From: 3rd Iteration Date: Sun, 1 Nov 2026 08:22:27 -0500 Subject: [PATCH 48/48] Vendor the follow-up vectors from psbt_faker; add nested multisig vectors psbt_faker now builds every 2026-10-31 follow-up vector itself: same ids, traps, amounts and verdicts as before. The 24 locally derived fixtures are replaced with its output, and derive_followup_vectors.py is removed, so the whole corpus again has one source. New: four nested segwit (p2sh-p2wsh) multisig vectors at m/48h/0h/0h/1h. XTRAS.MS_NESTED_HONEST is a negative control. XTRAS.MS_NESTED_WRONG_WITNESS_SCRIPT breaks only the inner layer (witness_script to redeem_script) and XTRAS.MS_NESTED_WRONG_REDEEM_SCRIPT only the outer one (redeem_script to scriptPubKey), so both layers must be checked. XTRAS.MS_NESTED_MISSING_WITNESS_SCRIPT is MISSING_INPUT_SCRIPT. dev already refused both layer swaps, so these are regression coverage. Co-Authored-By: Claude Opus 5.5 --- tests/data/psbt_test_suite/PROVENANCE.md | 23 ++-- ...nested_bare_p2sh_claims_us_pays_other.psbt | Bin 333 -> 340 bytes ...ted_bare_p2sh_claims_us_pays_other_V2.psbt | Bin 367 -> 367 bytes .../XTRAS.FOREIGN_INPUT_BAD_SCRIPT.psbt | Bin 460 -> 467 bytes .../XTRAS.MISSING_REDEEM_SCRIPT.psbt | Bin 333 -> 340 bytes .../XTRAS.MISSING_REDEEM_SCRIPT_V2.psbt | Bin 367 -> 367 bytes .../XTRAS.MISSING_WITNESS_SCRIPT.psbt | Bin 738 -> 1048 bytes .../XTRAS.MS_NESTED_HONEST.psbt | Bin 0 -> 1201 bytes ...TRAS.MS_NESTED_MISSING_WITNESS_SCRIPT.psbt | Bin 0 -> 1100 bytes .../XTRAS.MS_NESTED_WRONG_REDEEM_SCRIPT.psbt | Bin 0 -> 1208 bytes .../XTRAS.MS_NESTED_WRONG_WITNESS_SCRIPT.psbt | Bin 0 -> 1208 bytes .../XTRAS.NESTED_CHANGE_NO_REDEEM.psbt | Bin 333 -> 340 bytes .../XTRAS.NESTED_CHANGE_NO_REDEEM_V2.psbt | Bin 367 -> 367 bytes .../XTRAS.OP_RETURN_MULTI_PUSH.psbt | Bin 356 -> 363 bytes .../XTRAS.OP_RETURN_MULTI_PUSH_V2.psbt | Bin 395 -> 395 bytes .../XTRAS.OP_RETURN_NON_PUSH.psbt | Bin 347 -> 354 bytes .../XTRAS.OP_RETURN_NON_PUSH_V2.psbt | Bin 386 -> 386 bytes .../XTRAS.OP_RETURN_RUNESTONE.psbt | Bin 351 -> 358 bytes .../XTRAS.OP_RETURN_RUNESTONE_V2.psbt | Bin 390 -> 390 bytes .../XTRAS.OP_RETURN_SMALLINT.psbt | Bin 344 -> 351 bytes .../XTRAS.OP_RETURN_SMALLINT_V2.psbt | Bin 383 -> 383 bytes .../XTRAS.OP_RETURN_TRUNCATED_PUSH.psbt | Bin 346 -> 353 bytes .../XTRAS.OP_RETURN_TRUNCATED_PUSH_V2.psbt | Bin 385 -> 385 bytes .../XTRAS.STRAY_REDEEM_SCRIPT.psbt | Bin 333 -> 340 bytes .../XTRAS.STRAY_REDEEM_SCRIPT_V2.psbt | Bin 367 -> 367 bytes .../XTRAS.WRONG_REDEEM_SCRIPT.psbt | Bin 358 -> 365 bytes .../XTRAS.WRONG_REDEEM_SCRIPT_V2.psbt | Bin 392 -> 392 bytes .../data/psbt_test_suite/XTRAS.ZERO_FEE.psbt | Bin 329 -> 329 bytes .../psbt_test_suite/XTRAS.ZERO_FEE_V2.psbt | Bin 363 -> 363 bytes .../derive_followup_vectors.py | 129 ------------------ tests/psbt_suite_util.py | 37 ++++- 31 files changed, 50 insertions(+), 139 deletions(-) create mode 100644 tests/data/psbt_test_suite/XTRAS.MS_NESTED_HONEST.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.MS_NESTED_MISSING_WITNESS_SCRIPT.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.MS_NESTED_WRONG_REDEEM_SCRIPT.psbt create mode 100644 tests/data/psbt_test_suite/XTRAS.MS_NESTED_WRONG_WITNESS_SCRIPT.psbt delete mode 100644 tests/data/psbt_test_suite/derive_followup_vectors.py diff --git a/tests/data/psbt_test_suite/PROVENANCE.md b/tests/data/psbt_test_suite/PROVENANCE.md index 6db43bb1f6..072f1dd296 100644 --- a/tests/data/psbt_test_suite/PROVENANCE.md +++ b/tests/data/psbt_test_suite/PROVENANCE.md @@ -96,14 +96,13 @@ 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). Unlike the vectors above, these are **not** -generated by psbt_faker. `derive_followup_vectors.py` (in this directory) derives each -one from a vendored fixture (`NORMAL-1_p2wpkh(_V2)`, `NORMAL-2_wrapped(_V2)` or -`TX-21.ms_honest_change_no_xpubs`) with a single edit, so the trap is the only -difference from a psbt that must sign cleanly. The script is deterministic: run it -from the repository root to regenerate the same bytes. The one foreign key it uses -comes from a fixed throwaway seed, which no corpus wallet derives. +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 @@ -112,6 +111,14 @@ comes from a fixed throwaway seed, which no corpus wallet derives. `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. 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 index 9f66aab470aedf438eb3ad5fea7affe547139812..fd46db3cf476cf55f38dba78b7ddd3539ba87ff1 100644 GIT binary patch delta 95 zcmX@hbcJbxlTDf2ZMoEf4rPubVu8=a=6f+cU-hQ_$DLnH3_u{hQbcrF%97XTmowY_ gU|yxRSjV>XcU4_GNRIJ0%f#|#5p4P=^D){306B6c)Bpeg delta 88 zcmcb@be3s?ld0prV@uf%RV`irp1;(hP}+b=<-^_fA9sE+F#v)1N|F63R}2kA3#I;a bb({`qUu-_VUUYN&#JXk?Y#JwvGTH+Gw+bc= 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 index cfeb01d3d58cbe82a7dc0cb977438793d2cbf509..b83d351c131f53337a6a791f744ca3d8aa1f34ee 100644 GIT binary patch delta 107 zcmaFQ^qy(LC95*I+j6M|9m*U>!~&m-&G%w@zUoaoBa8S-5$rO|96#>-VqyS-$vlj9 hsvw1;%TkuSKEIsV?g#TKwZ%HNrN67{+8GfF836GNC~g1% delta 107 zcmaFQ^qy(LC98RRZv-y*b4~80kcEv=&#g?87`JQfjLaNA?)+k600Kr9@s%Q26;0-0 gv{OY>xIg8Jp@C?j)Ss@7(;@AP&F9yPZf<7)0G}-@OaK4? 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 index b253b981ac09553143ad1365e8554cb92c1feaa8..bc5c850795b41663533d0d5460035af53ed2f014 100644 GIT binary patch delta 172 zcmX@Ze3^NInO}xqbn34g!D8<2tF5}Sxn?LwtUmD5!9|`|_Oi;FwmAnGK;S|H_OBYJsufJld8YW`}8w|&0`UEv*vFdHPH-=xXhhg!WaPn>tjl^ delta 168 zcmcc2e1>^~nctb{YfIvnOj^wPX3NpHt89O5DQDk(>a4`3cFkGA(OWv~7(n1Z5HS6? z^NR_@5nn0dxbN6fwnJ4**T3g4wJ4M}U{d*Tw;d!uu|;9x>JE>+)2!SA0t}fZ&s^(b wUZwgqFm>toc19L429fUg2kWK#pG{o2wAbd#$(ZxU`mB-|7;%|7xtcKo05b_p%m4rY diff --git a/tests/data/psbt_test_suite/XTRAS.MISSING_REDEEM_SCRIPT.psbt b/tests/data/psbt_test_suite/XTRAS.MISSING_REDEEM_SCRIPT.psbt index e49e318ce1bb5b70e8177ada3e26713c02f31957..2d99d5ec6b1eebb9385078d19333a10ae39efc02 100644 GIT binary patch delta 61 ycmX@hbcJbxlgNr0OxYgq80MO^l?nWD-R|A5%cpV=b!D&7rgEv^xy8v8c_i$8AcE?kg)B1I=ZmR!-`!~BUmA2lQuPIV|^cI%^0|U^odJw_Tzy!olTNG!e@PKR) z)QJBpujjhsmfmJvol3b?wPnEub;s2#8Es^C6&?R(&Ky{ocR|F>Y2`*|?V0*DT5-y1 z7C&d~KbK?IfmTyy6PdIzF{4O(}bJRMs#->otO4VbR&fR+1R++f;?isy?y;-~r8AWY}MeLKK PlF@Bp{LQklHu2!mwz;= zh)-K3Qhf9lmjMF<&@c!Fy0!soiQ>!@9*`wl4k<{k__S~8_PIqSjm+u{ww86hbC>V* zy(ay}(&zBYFH9FDlJbge*j_iC4v!0R^gI<t9W*$pns8;p*5Gl-juXru(N;jrXg z;g6#rOD-@~H3pn${=uzp!?8nWnsUAJ`@FrId==w`-*H*xxz{r<-BegQx6Xy-#o3u< zNo!2r78EaUFmm4xevn3 z^0UL`nWp;kF?@gEw8wwujunionL&z7V$xqts!W?-uKT)TM%`AXKaTSPeJ?C+<4!y% z7*R6!t*jzb*^b4UypGc^$Xw5Bw@FQ!vq(3wblWBuMdsDK{~rBPt59U#r^pg}B4FcX zPu4Qsmkzcyg4H!mCvqq8@CZ!!kL=t38Elb=&`;2j zGT2fYOg}K5fFWwExo^snsrz2Jo<4hj2ZL-{f9qS1_VD%vIZN&`-(Ajc!pH~=QD!dr z+D}u0_bu2zG05R?|BID^Nv#PmJW%!$yyla$UYIUTEj7sTCHu%-SnZqj;lN(*j*! ih%ynh2&<34$pc6L^%HUi)(}P3Pr#8_V-%*JfdK%o!@1D_ literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..330280b571b830ca6af0b03903fb5950fbbec8dd GIT binary patch literal 1100 zcmXRYPAd7&$WX_`z`(#5%E4ZuG4Iyw7c18qsoI49ux~iFuQE;N)}~PA1?{=(mH^c- zF#HDsrZp{$V2=1ok?6Uvl&h|7|6gR-f7gD`mJYdn?K9e8@=6Q}Vz+(yKHJQyUvwcW z$9I+Arc>F!K4cxABH(If>+tAs`y!Az{){Xgo8(wzK1~;E0J>wH*01P2Cr`xa%zD3J z#eDTdkBW`=kFTk*xRL0S@_+xi0_NN$C$lSFtc^Jwn!P3E;aXNaDbxC|H=fQCUZ(6tRvOB83O@PI7Ya!5gP#ixB!x6dsyX=GMsu(hn~ox6Oe z?=|T+mOh7Heqp*Ok(5_#!}hxAba-5lqvxr>y48^{&u(y8-e7dhn?c-ML?b1D4TmM~ z3V$30S#p7?sxjb1^AB!)8;%`1)0FF#-{88TcxpgiqFV4;^ zOIl;{wxD=E7Kpxd4awcmbP&x z9u$lynfq2&2CLJ-)-x~w^_T5ftjX&*{esN(ymp(^q&bUp6HB*ka#3Vn&HL}sFSQC8 zY~c$@b|C%C`xIGXPXuhd?8#cD`_jR-MzFf3=|t`%9v*=SKk}I_O_jlx2w?hwVF&c3 zvF5%hOQ!C7<$C(;{T&RlY5lElJ=(+D7vwCt%Y1h^zX>B_W{@H?mwfG~DZ%>|?4KCq zaJc_S-N&Yl5C7($Ik|mLZpHoTzr2dft5P0c5_o#2-SO{)%QFwwvA+NJaCY8e_H{fz zPTYHc--8vXBEKg_^6Fuu$4a>_Ul%X5^VZY~3tVRH6{u0X(W_~JZtyxKCW01W^$|GA YfCNxKA!lF>QDprD9EmkXVfq;u0FelfVE_OC literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..17f4a8e71e4074a60a0f3acb6579a55816fb4f67 GIT binary patch literal 1208 zcmXRYPAd7&$WX_`z`(#5%E4ZuG4Iyw7c18qsoI49ux~iFuQE;N)}~PA1?{=(mH^c- zF#HDsrZp{$V2=1ok?6Uvl&h|7|6gR-f7gD`mJYdn?K9e8@=6Q}SxhchmaEF1Ua@7; zQEk?So6qcO*HlDs{@-NoB0A}KUJA$@e@2#$O>!(UpQej70Nt@p>sR!ilP6+yX1(9A zV!nE!N5#hb$Jf+Y+(`6E`M>{M0dww>li3w7*2WwT&EAsoa4oB_&Y2CIeYYl?U;fdg zB0g=ENb%8ITm}pbK*Jyy=-LLTC5kgsctDnHIiw)D;?usV+vgUUG%~9**jm>0&RxFK z_nPz@OP|9pzc5{tNXjd=VSC+lIy^4O(eqSb-Rj7fXE(SkZ!kLM%^+?rqLC87hQpF~ zg+GphEV;l`)fjN1`3JYY4aW|hY0CA=@ALL<@>Pr%e#d2%=U&gebW>sJ+&UMQ7iVXd zC9N@eTTr~bk>8Gs{aMiD&0g;r+C=P=qmt1rVf@Vk^cc{1hG1~Kt-S~4GQ8ghq0vcC zkN_y&7#(<-!IHpugs z2KStddo4%GZutr7zUtj_<=)24E1o@LWX%jzWD=A9YEos|{Bqsb6*KC#GW~I!7wCIo zX&ZOqLBWWUxo>3^naXx7*5q}ZenIAXUb{_d(ws%QiKW{%xhOKP=Kc5Rms*7)^FBqE z*b@O8FMG0<>ArNZtr4uQX*!WRiHApE!jF8WOH+f_DX|f>NCs;#fxXJW0Mt*&88X=7 z5|YG0`UyHx23vxI=?BIWFhq?t_f1(cb>A!3(`WDRV31AgZ++|09^SqnXUSdWyUY1a z7#TBz6q&i?Yd=j1-nU@?#2|;m{YUCPHf?v{s ze1_l7Sx4;en literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..7d4f87b8234630b42fa6452f27d141106af08ceb GIT binary patch literal 1208 zcmXRYPAd7&$WX_`z`(#5%E4ZuG4Iyw7c18qsoI49ux~iFuQE;N)}~PA1?{=(mH^c- zF#HDsrZp{$V2=1ok?6Uvl&h|7|6gR-f7gD`mJYdn?K9e8@=6Q}g*xieKQ85aFaEr+ z2vty7p996NqNOKY_FS6hsOmudY%fbTOIlG>;{+R4MxYj8N|&+G*SZCa9HxL z@W)Y*B^Q{g8Us!=|KQfQ;n<-wO}SqAecs+pzKZd}@3^e;-0PW_ZYnIDTj#>^;_S?_ zq%|gQ3yPOF^4oE-KMR_?+3P(+n}~gKR5H3HjK5ic9s?TB5DbpDwfDeWhWGm*G&<=C z5&*>;qXRE9SP~d-{Qs7m`u5K1G(; z69F49d$N}4zI3py5v;ChI*~hxheu$-k9?*}Q-jwju@SUL25T^Zy~@A<)KAD6GT7o0 zlEgv!2|7{+TY`h>2gVaHM2$7~O<6K^-z(SCXYcP|kWK4vee2O4-o7Ab$zA5V%lSKN9sN{ZG8AQ|IEqldvYu8SO4WzWL}l>_>#cWJME5t zCtRL+u#WZpzlXE)7PGJ8`Elaj`}-cOKo$8tF_Kpg8$DLab@{q@p`Ev;R#@ONYp+0! p;*DNS3v_`Y%0$p2tUdxK4aj{q7G<;t0Q1Zk+5i9m 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 index a07aff6d0f326bee2a4fac406c6753ce75de698f..dd00a5320da57328f2e4c5db86e5ad88ba8ae7e5 100644 GIT binary patch delta 86 zcmaFQ^qy(LC98h*`oG6sN*|da^z9bI#PkON{{)`2GqQ-U6u~aT%<<#SFD3>cn9Rdy OH#wA1l7|r?#sB~dSR=9k delta 107 zcmaFQ^qy(LC98RRZv-y*b4~80kcEv=&#g?87`JQfjLaNA?)+k600Kr9@s%Q26;0-0 gv{OY>c&WdqnbSyzBS7&3N8+cN>DK?5x3@C@0Fn4Af&c&j 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 index 9d6358f100aec8e53a441d661e91c1978eb33b1d..6a0484b20ce8a41c7d0134920de6ab3f8a114eb4 100644 GIT binary patch delta 74 zcmaFD^qOgclgy`xv!`C);;Vf-=e?-=3t?+_J;vT2cYZN30KsH_M)8TIa?FgsStj;p MieOVZnTIg~0OA!Nga7~l delta 64 zcmaFO^n_`GlgM4ukLSJonRmMMbZpxbr*r1s(#F>l!)zzcN)^W@#lXloF;0B4E~6a) D0#6*Tf004jHArk-q delta 135 zcmeBX?q;5_!-834{=3V-UfnX5xo% z7c^yaCj2yc75Ixkl|{V3`N4$VWs_z$GXTv3nF9ihEP`3A8L2rr`M%5yiAl*mOev`h E0A|TDs{jB1 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 index 8907af7247911aef08927ba98b91be3ba894a053..4b7c805d78d5c6d435cce146d210ff0e70fa84d2 100644 GIT binary patch delta 68 zcmcc3^oVJKlgNdjKBLTSCrwt*bxG*<;8-#Js%_20FcW6R-z*c`GR3h;GcYnvj1!+M H%V-Ax^W+l!%QYlOclo_#lXloF;0B43ZoqW D`%@ju 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 index ac79fb8836b29a9155df01379994735f1d6b74bd..738a9dcc7ce6adfae3a13916026cd6cc876507f0 100644 GIT binary patch delta 106 zcmZo-ZepIW!{S0vpHb$vlP0U@x+HXaaIBbq)wYI_MT|iNs{}L0k2}AZ7=U2nhw#Zk cj1tO>2q6YW7LF{|jMSW*{53#fkSZ_$0B{E(*8l(j delta 126 zcmZo-ZepIW!-834{=3V-UfnX5xo% vYcyqZCj2yc75Ixkl|{V3`N4$VWs_z$GXTv3nF9ihEF4*^8L2rr`D+*eoW?Mw diff --git a/tests/data/psbt_test_suite/XTRAS.OP_RETURN_RUNESTONE.psbt b/tests/data/psbt_test_suite/XTRAS.OP_RETURN_RUNESTONE.psbt index 97c0895c518719c4dc4d5e524fc477b0eb79db9d..bda9cf52335b90de0914bd75454b68c3a7765b67 100644 GIT binary patch delta 68 zcmcc5^o(hOlgO+^E$TJGEA$SfZ HWV8bSg8&!! delta 70 zcmaFHbf0O0lgwSykLSJonRmMMbZpxbr*r1s(#F?6?)+k60D{SajN%hZB_~cz6~U%# IG9P0E0El-WXaE2J 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 index 2310a2cc4775bcbc07af3c99b0d0d51ac3c019ab..37b868e904e4236ce1bbfb63f14774699eeb4897 100644 GIT binary patch delta 95 zcmZo;ZeyOX!(!H=7WEq86?%u#H%dw$*v8Ki+R4tyBE}$sRf3u0$DLnH3_vjPL-^z% UMhSLCh|uIhMiCw$8zcn=03T@_7ytkO delta 130 zcmZo;ZeyOX!-834{=3V-UfnX5xo% zdo*QpCj2yc75Ixkl|{V3`N4$VWs_z$GXTv3nF9ihEIe7UoD2sR8Hl!we_(rHW&dVqj#P7$-hikLv;Y7A delta 123 zcmey*^q*0van_`_y;C1004irFVg@3 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 index 7fdb8afe8fe60473db907914e6a8270806420cfd..882090fb36a059e5def2d9ca488b8402e21183b6 100644 GIT binary patch delta 68 zcmcb`^pI(SlSuR;i5mQiV9m@zZsZl!;B|RNEOE>#lXloF;0B4GNT;; D`i>pO 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 index 08076f265250d9fb2cf35d1b88c52dc7a5116729..6a3b9db1b73fa01b3459ef027f92d59373bc7fb0 100644 GIT binary patch delta 105 zcmZoV-UfnX5xo% uD>P+uCj2yc75Ixkl|{V3`N4$VWs_z$GXTv3nF9ihEbLjn{}~dKk{JMPUocMq diff --git a/tests/data/psbt_test_suite/XTRAS.STRAY_REDEEM_SCRIPT.psbt b/tests/data/psbt_test_suite/XTRAS.STRAY_REDEEM_SCRIPT.psbt index 15895b9cb84e8b4fa123c2993575661160c386c0..7102aaccaf9e3fe2d15bef9387fc17c9c2cd851a 100644 GIT binary patch delta 68 zcmX@hbcJbxlgP7ICncvS>VBJ9)bAv5jiozv3G4oeVam*mzgZ@h=89vJW?*ET7$-hi HfYBBJ{xTbE delta 65 zcmcb@be3s?lgwSykLSJonRmMMbZpxbr*r1s(#F?6?)+k60D?)3;uC9fMX)KE_%|E? D_Ld** 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 index ebc09b09bf3c174740c8f196e04e12d82f22e3ec..196d4a3d077a7080bf342d9998f28024709f86da 100644 GIT binary patch delta 103 zcmaFQ^qy(L9*bwMPD)Nu)crQIsNYHA8cTQT64w2UEMg2ISS6S_e%$%R!~g^nzl5uR fl+Bs&)8tj)FaA^(@dD=u6MC0Tn%T^VP{sfN=07O? delta 103 zcmaFQ^qy(L9t&oX`R``mp0xIiLG0%DODk{OnYi~NBQwX3JHMD1fPj%jj6npOnu%Y+ eRnU~pnefx(Rp2lFR2K09=LZvdmra`4%m4t)=`JS# diff --git a/tests/data/psbt_test_suite/XTRAS.WRONG_REDEEM_SCRIPT.psbt b/tests/data/psbt_test_suite/XTRAS.WRONG_REDEEM_SCRIPT.psbt index ffa3a174992fc7449a32aa41a86954bc206d20e4..01ebd67ede92d937dc6aeb56ec348e03a5567f4d 100644 GIT binary patch delta 86 zcmaFH^pJ*0 YXCF0f%F8`YJ&O-b+<{%&WIo0S0HCfW=l}o! delta 82 zcmaFM^o(hOlZfNKV@uf%RV`irp1;(hP}+b=<-^^HVX70GG)2y+n6Q`o>Aq|D(s0u* UvgIwq&-{H8_hZ*GS(GsX0QIgUdjJ3c 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 index a0e496acedc983c1babb9b9c5197354d582d63b4..823c182835782878a02274909b2d2c05e6984c1c 100644 GIT binary patch delta 110 zcmeBR?qHtaE%L(aa%b;PbITw*`>1JCUhZ+~S$t?>e6iIfBcrgl5toEdw{OZlB>g5) m_-VRmJ0pwuN)hZb%p5=N{904tdQ delta 107 zcmeBR?qHtaEpkT1guUEP_g%x6hMRVgEpHiq=I@&rUu-pR?~T9(f3C^B6tb`}>baF^ n661EQospU2$DLnH3_!rhBEC`ttD?y~jN$B1g_GkMWf>U&$c-zu diff --git a/tests/data/psbt_test_suite/XTRAS.ZERO_FEE.psbt b/tests/data/psbt_test_suite/XTRAS.ZERO_FEE.psbt index e19f88db4e252f5bc2425b0a112f83b6f4a48740..9bf5445d83cdaf4685254de7b45c8a2b7ac846ee 100644 GIT binary patch delta 75 zcmX@fbdqU;xl+T2UrY=@AjTl_Lhe^&?Rxc`yvSQ$oL5e&`Z`6h5GXw{vQ-?L6aypU L#5nQEJdCyg&O0DW delta 75 zcmX@fbdqU;xzdk2znB<+K#W1;uIb0~UjEEGU3xmU?TOPlb8l(mYYvv*6C+#2u}Lv7 NGER&WpUlH(3joVvAXoqZ diff --git a/tests/data/psbt_test_suite/XTRAS.ZERO_FEE_V2.psbt b/tests/data/psbt_test_suite/XTRAS.ZERO_FEE_V2.psbt index 87b0f8e835af762fc1b9c05cf21c1677070060b8..a23c6cdb3f5cbeb41b7d4e0e04ea733fb2704273 100644 GIT binary patch delta 83 zcmaFO^qOhH4vQCZzanebtLNlJ-umLaa#GdTDT0NJEMg2ISS6S_8b17DVgQ1PAHpXG LF-q_-B7_(KC$%8F delta 103 zcmaFO^qOhH4hv?H`R``mp0xIiLG0%DODk{OnYi~NBQwX3JHMD1fPj%jj6npOnu#C6 jRhT(ASbigv&6)7i PSBT: - with open(os.path.join(HERE, name + ".psbt"), "rb") as f: - return PSBT.parse(f.read()) - - -def write(name: str, psbt: PSBT): - with open(os.path.join(HERE, name + ".psbt"), "wb") as f: - f.write(psbt.serialize()) - - -def foreign_key(index: int): - """A key no corpus seed derives: a fixed throwaway root, mainnet BIP49 receive path.""" - root = bip32.HDKey.from_seed(hashlib.sha256(b"seedsigner-followup-2026-10-31-foreign").digest()) - return root.derive(f"m/49h/0h/0h/0/{index}").get_public_key() - - -def with_op_return(base: str, script_bytes: bytes) -> PSBT: - """Appends a zero-value OP_RETURN output with the given raw script. The fee is unchanged.""" - psbt = load(base) - out = OutputScope() - out.script_pubkey = script.Script(script_bytes) - out.value = 0 - psbt.outputs.append(out) - return psbt - - -RUNESTONE = bytes.fromhex("00c0a2331414010203") - -# (name, raw OP_RETURN script). Each gets a v0 and a _V2 twin. -OP_RETURN_VECTORS = [ - # Runes: OP_RETURN OP_13 . Push-only per Core's IsPushOnly. - ("XTRAS.OP_RETURN_RUNESTONE", b"\x6a\x5d" + bytes([len(RUNESTONE)]) + RUNESTONE), - # OP_0, OP_1NEGATE, OP_1, OP_16: pushes that carry no data bytes. - ("XTRAS.OP_RETURN_SMALLINT", b"\x6a\x00\x4f\x51\x60"), - # A direct push, an OP_PUSHDATA2 and an OP_PUSHDATA1, concatenated: "helloabcde". - ("XTRAS.OP_RETURN_MULTI_PUSH", b"\x6a\x05hello" + b"\x4d\x03\x00abc" + b"\x4c\x02de"), - # OP_PUSHDATA2 declaring 255 bytes, with 3 present. - ("XTRAS.OP_RETURN_TRUNCATED_PUSH", b"\x6a\x4d\xff\x00abc"), - # A valid push followed by OP_CHECKSIG. - ("XTRAS.OP_RETURN_NON_PUSH", b"\x6a\x05hello\xac"), -] - - -def main(): - for name, raw in OP_RETURN_VECTORS: - write(name, with_op_return("NORMAL-1_p2wpkh", raw)) - write(name + "_V2", with_op_return("NORMAL-1_p2wpkh_V2", raw)) - - for suffix in ("", "_V2"): - # Native segwit input carrying a redeem_script it does not commit to. - psbt = load("NORMAL-1_p2wpkh" + suffix) - psbt.inputs[0].redeem_script = script.Script(b"\x51") - write("XTRAS.STRAY_REDEEM_SCRIPT" + suffix, psbt) - - # Nested segwit input with its redeem_script left out. - psbt = load("NORMAL-2_wrapped" + suffix) - psbt.inputs[0].redeem_script = None - write("XTRAS.MISSING_REDEEM_SCRIPT" + suffix, psbt) - - # Nested segwit input whose redeem_script wraps a different key than the one its - # scriptPubKey commits to. - psbt = load("NORMAL-2_wrapped" + suffix) - psbt.inputs[0].redeem_script = script.p2wpkh(foreign_key(0)) - write("XTRAS.WRONG_REDEEM_SCRIPT" + suffix, psbt) - - # Genuine nested segwit change, minus its (BIP-174 optional) redeem_script. - psbt = load("NORMAL-2_wrapped" + suffix) - psbt.outputs[1].redeem_script = None - write("XTRAS.NESTED_CHANGE_NO_REDEEM" + suffix, psbt) - - # The same redeem-less change output, repointed at a stranger's key while it - # keeps this seed's derivation claim. - psbt = load("NORMAL-2_wrapped" + suffix) - psbt.outputs[1].redeem_script = None - psbt.outputs[1].script_pubkey = script.p2sh(script.p2wpkh(foreign_key(1))) - write("TX-21.nested_bare_p2sh_claims_us_pays_other" + suffix, psbt) - - # p2wsh multisig input with its witness_script left out. - psbt = load("TX-21.ms_honest_change_no_xpubs") - psbt.inputs[0].witness_script = None - write("XTRAS.MISSING_WITNESS_SCRIPT", psbt) - - # A collaborative spend: our nested segwit input plus another party's, whose - # redeem_script is not the one its scriptPubKey commits to. The other party's input - # claims none of our keys, but its scripts are checked all the same. - psbt = load("NORMAL-2_wrapped") - from copy import deepcopy - other = deepcopy(psbt.inputs[0]) - other.txid = hashlib.sha256(b"followup-foreign-outpoint").digest() - other.vout = 0 - other.bip32_derivations.clear() - other.non_witness_utxo = None - other.witness_utxo.script_pubkey = script.p2sh(script.p2wpkh(foreign_key(2))) - other.redeem_script = script.p2wpkh(foreign_key(3)) - psbt.inputs.append(other) - write("XTRAS.FOREIGN_INPUT_BAD_SCRIPT", psbt) - - # Zero fee: the change output absorbs the original 10,000 sat fee. - for suffix in ("", "_V2"): - psbt = load("NORMAL-1_p2wpkh" + suffix) - psbt.outputs[1].value += 10_000 - write("XTRAS.ZERO_FEE" + suffix, psbt) - - -if __name__ == "__main__": - main() diff --git a/tests/psbt_suite_util.py b/tests/psbt_suite_util.py index 2ec06ef4e5..145738dafe 100644 --- a/tests/psbt_suite_util.py +++ b/tests/psbt_suite_util.py @@ -1068,8 +1068,8 @@ def path(self) -> str: ), # ------------------------------------------- follow-up of 2026-10-31 - # Upstream #995/#1041/#1042/#1046/#1047 merge. Derived from the vendored - # fixtures by data/psbt_test_suite/derive_followup_vectors.py; see PROVENANCE.md. + # 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 " @@ -1190,6 +1190,39 @@ def path(self) -> str: 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) "