Merge pull request #1047 from kdmukai/2026_09_psbt_input_scripts
What changed, and why it matters
This commit adds security checks to SeedSigner, a small offline Bitcoin signing device. Before the change, a malicious or buggy wallet coordinator could give the device a transaction where an input's hidden script did not match the public address it claimed to spend from. That could trick the device into thinking a payment to an attacker's address was actually change coming back to the user. The patch now verifies that every input includes exactly the scripts it publicly commits to, and stops the signing flow with a warning if something is missing, wrong, or extra.
Treat this as a security fix and include it in the next release. Users building from source or running pre-release firmware should update to a revision that includes this merge. Wallet coordinators that create PSBTs for SeedSigner should ensure they supply only the scripts each input's scriptPubKey actually commits to.
Security signals we found
New validation logic compares supplied witness/redeem scripts against scriptPubKey hashes
New exception classes explicitly label script mismatch as an attack and missing/extraneous scripts as correctness problems
UI flow terminates signing before rendering transaction details when a script check fails
Tests demonstrate that a foreign witness_script or redeem_script is rejected even when the coin is owned by the user
Commit title and message are explicitly tagged [security]
Evidence from the diff
The merge adds input-script verification to PSBTParser._verify_input_amounts_and_scripts(). For each PSBT input it now checks: (1) p2wsh inputs include a witness_script whose hash matches the scriptPubKey; (2) p2sh inputs include a redeem_script whose hash matches the scriptPubKey; (3) nested p2sh-p2wsh inputs also match the witness_script against the redeem_script; (4) no extraneous redeem_script or witness_script is present for script types that do not use them. New exceptions (PSBTMissingInputScriptError, PSBTInputScriptMismatchError, PSBTExtraneousInputScriptError) are raised and routed to dedicated warning screens that discard the PSBT before any transaction detail is shown. Tests cover omission, mismatch, and extraneous-script cases for native segwit, legacy p2sh, p2sh-p2wpkh, and p2sh-p2wsh inputs, including inputs that do not belong to the user’s seed.
Changed components
src/seedsigner/models/psbt_parser.pysrc/seedsigner/views/psbt_views.pytests/test_psbt_parser.pytests/test_flows_psbt.pytests/screenshot_generator/generator.pyInspect captured patch +598 / −79
### 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.
@@ -205,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
@@ -283,20 +323,19 @@ 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: 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.
+ 4. _verify_input_amounts_and_scripts: verifies each input's claimed amount, then
+ 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: make this a PSBTVerificationError subclass so
- the view can deliberately catch this scenario and route accordingly.
+ 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.
@@ -316,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
@@ -360,7 +399,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:
@@ -376,78 +415,99 @@ 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().
-
- 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.
-
- 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.
+ 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 (p2pkh and p2sh) 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. 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.
+
+ 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):
- 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")
-
- else:
- # Make sure inp.vout points to an output that exists in the non_witness_utxo
+ 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")
+
+ 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")
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:
# 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
- # 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
@@ -465,9 +525,95 @@ 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")
+ @staticmethod
+ 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. 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
+
+ Multisig nested segwit has TWO layers to check:
+ p2sh-p2wsh: p2sh(redeem_script) == scriptPubKey
+ p2wsh(witness_script) == redeem_script
+
+ **** 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 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
+ # 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
+
+ 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
### 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
### 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),
### 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
### 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)
@@ -1181,10 +1183,8 @@ def build_psbt(case: tuple) -> PSBT:
class PSBTParserOwnershipTestBase:
"""
- Base class for the two ownership 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
@@ -1207,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()
@@ -1621,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
@@ -2865,3 +2865,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 _add_foreign_nested_segwit_input(self, psbt: PSBT, derivation_path: str = "m/49h/1h/0h/0/0"):
+ """
+ Adds a p2sh-p2wpkh input spending from another party's key with no derivation
+ paths specified. Its scriptPubKey and redeem script are both built from that key,
+ and its coin is described by a witness_utxo alone.
+
+ The supplied psbt's first input should carry a witness_utxo.
+ """
+ # Start from a copy of our own input for its witness_utxo
+ 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)
+
+ # Drop the copied non_witness_utxo, which describes our own coin and contradicts
+ # the witness_utxo altered above.
+ foreign_input.non_witness_utxo = None
+
+ psbt.inputs.append(foreign_input)
+ return foreign_input
+
+
+ def test__parse__refuses_an_input_that_omits_the_script_it_commits_to(self):
+ """
+ The psbt leaves out a script that an input commits to:
+ * p2wsh: witness_script
+ * legacy p2sh multisig: redeem_script
+ * p2sh-p2wpkh: redeem_script
+ * p2sh-p2wsh: witness_script or redeem_script
+
+ Each case should raise PSBTMissingInputScriptError.
+ """
+ # Each case first confirms that the fixture really does carry the script it is
+ # about to omit.
+
+ # p2wsh: omit the witness script
+ psbt = self._psbt_with_change(PSBTTestData.MULTISIG_NATIVE_SEGWIT_1_INPUT, PSBTTestData.MULTISIG_NATIVE_SEGWIT_CHANGE)
+ assert psbt.inputs[0].witness_script is not None
+ psbt.inputs[0].witness_script = None
+ with 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):
+ """
+ The parser verifies the scripts on every input, whoever the psbt says the input
+ belongs to. So an input with no derivation paths, claiming none of the user's
+ keys, gets the same script checks as the user's own input.
+
+ The psbt will be rejected if a script is missing (PSBTMissingInputScriptError) or
+ wrong (PSBTInputScriptMismatchError).
+
+ Note: despite setting up a collaborative spend, this test is not meant to mimic a
+ realistic payjoin transaction. Certain types of payjoin inputs (e.g. nested
+ segwit) require special handling to pass the input script checks. See the separate
+ payjoin TODO in the parser.
+ """
+ psbt = self._psbt_with_change(PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_1_INPUT, PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_CHANGE)
+ foreign_input = self._add_foreign_nested_segwit_input(psbt)
+
+ # The other party's input carries its correct redeem script and none of the
+ # user's keys.
+ psbt_parser = self._parse(psbt)
+ assert psbt_parser.num_inputs == 2
+ assert psbt_parser.verified_input_derivation_paths[1] == []
+
+ # Omit its redeem script. Its scriptPubKey alone then reads as legacy p2sh, which
+ # needs a non_witness_utxo to prove its amount. The parse should still report the
+ # missing script.
+ foreign_input.redeem_script = None
+ with 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)Why this scored 78/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.