Merge pull request #995 from newtonick/psbt-verify
What changed, and why it matters
This commit fixes a security flaw in SeedSigner, a small offline Bitcoin signing device. Previously, when a user scanned a transaction to sign, the device added up the input amounts exactly as a malicious or compromised computer/coordinator app told it to. That meant the 'fee' shown on the device's screen could be a lie: the coordinator could quietly claim inputs were much smaller than they really are, making an enormous real fee look tiny. The fix makes the device independently verify each input's amount against the previous transaction data (the 'non-witness UTXO') before showing the fee. If the numbers don't check out, it refuses to proceed and warns the user with a 'Likely an Attack!' screen.
Treat this as a security fix and include it in the next release. Users should upgrade before signing any PSBTs produced by coordinators they do not fully trust. Wallet/coordinator compatibility should be checked, especially for legacy inputs that may now need to provide non_witness_utxo.
Security signals we found
Fixes a fee-display manipulation vulnerability where a compromised coordinator could understate input amounts to hide excessive real fees
Adds explicit verification of each input's amount against the prior transaction before totaling inputs
Raises dedicated security exceptions (PSBTInputAmountVerificationError, PSBTMissingInputUtxoError) and blocks the signing flow
References CVE-2020-14199 and BIP-143/BIP-341 sighash amount-commitment behavior in code comments
Includes comprehensive regression tests for tampered and missing input data across all supported script types
Evidence from the diff
The patch adds input-amount verification to PSBTParser._verify_input_amounts() before any fee is computed or displayed. It now requires a non_witness_utxo for legacy (p2pkh/p2sh) and unrecognized script types, whose sighashes do not commit to the input amount. For segwit/taproot inputs it allows witness_utxo-only PSBTs because BIP-143/BIP-341 sighashes commit the amount, but when both utxo forms are present it cross-checks value and script_pubkey. It calls embit’s InputScope.verify() to ensure the non_witness_utxo hashes to the claimed txid, and raises new PSBTInputAmountVerificationError or PSBTMissingInputUtxoError exceptions that the UI routes to dedicated warning screens. The old unverified input_amount field is replaced by verified_input_amount, and tests cover tampered non_witness_utxo, mismatched witness_utxo, missing utxo, out-of-range vout, and multi-input cases.
Changed components
src/seedsigner/models/psbt_parser.pysrc/seedsigner/views/psbt_views.pytests/test_psbt_parser.pytests/test_flows_psbt.pytests/test_decodepsbtqr.pytests/screenshot_generator/generator.pyInspect captured patch +508 / −34
### 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,28 @@ class PSBTOutputOwnershipContradictionError(PSBTVerificationError):
pass
+class PSBTInputAmountVerificationError(PSBTVerificationError):
+ """
+ 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
+
+
+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.
@@ -114,7 +136,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 +177,9 @@ 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.
+ UNCOMMITTED_AMOUNT_SCRIPT_TYPES = [None, "p2pkh", "p2sh"]
+
# Warn when the fee exceeds this percentage of what is being sent (outputs other than
# change). TODO: Possibly make this configurable via settings.
HIGH_FEES_WARNING_THRESHOLD = 25
@@ -171,7 +195,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 = []
@@ -237,7 +261,12 @@ 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: 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: 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.
@@ -251,7 +280,7 @@ def parse(self):
policy with no cosigner information pass as a match between inputs.
Outputs deliberately compare shape alone; see _is_change_candidate.
- 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
@@ -301,6 +330,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: each is verified before it is totaled
+ self._verify_input_amounts()
+
rt = self._parse_inputs(child_key_derivation_cache)
if rt == False:
return False
@@ -315,20 +347,89 @@ def parse(self):
return True
+ def _verify_input_amounts(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.
+ """
+ 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.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.
+ 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.
+ 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.
+ 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
+ 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:
- 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
+ script_pubkey = inp.script_pubkey
inp_policy = PSBTParser._get_policy(inp, script_pubkey, self.psbt.xpubs, child_key_derivation_cache)
if self.policy == None:
@@ -664,9 +765,8 @@ def sig_count(tx):
@staticmethod
- def _get_policy(scope, scriptpubkey, xpubs, child_key_derivation_cache: dict | None):
- """Parse scope and get policy"""
- # we don't know the policy yet, let's parse it
+ def _get_script_type(scope, scriptpubkey) -> str:
+ """Like script_type(), but tells nested segwit p2sh apart from legacy p2sh"""
script_type = scriptpubkey.script_type()
# p2sh can be either legacy multisig, or nested segwit multisig
# or nested segwit singlesig
@@ -678,6 +778,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
### src/seedsigner/views/psbt_views.py
@@ -1,6 +1,9 @@
+import logging
+
from gettext import gettext as _
-from seedsigner.models.psbt_parser import (PSBTInputOwnershipClaimError,
+from seedsigner.models.psbt_parser import (PSBTInputAmountVerificationError,
+ PSBTInputOwnershipClaimError, PSBTMissingInputUtxoError,
PSBTMixedDerivationPathTypesError, PSBTOutputOwnershipClaimError,
PSBTOutputOwnershipContradictionError, PSBTParser, PSBTSeedCannotSignError,
PSBTSurplusDerivationPathsError)
@@ -9,6 +12,8 @@
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 +140,17 @@ 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.
+ logger.error(f"PSBT input amount verification failed: {e}")
+ self.set_redirect(Destination(PSBTInputAmountVerificationFailedView, clear_history=True))
+ return
+
finally:
self.loading_screen.stop()
@@ -290,7 +306,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,
@@ -686,6 +702,58 @@ 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=_("Likely an Attack!"),
+ text=_("This transaction's input amounts cannot be verified, so its fee 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 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 is missing required data 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
### tests/screenshot_generator/generator.py
@@ -458,6 +458,8 @@ 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.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),
### 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
### tests/test_flows_psbt.py
@@ -61,6 +61,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.
@@ -320,6 +351,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
### tests/test_psbt_parser.py
@@ -10,8 +10,10 @@
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,
+from seedsigner.models.psbt_parser import (PSBTInputAmountVerificationError,
+ PSBTInputOwnershipClaimError, PSBTMissingInputUtxoError,
PSBTMixedDerivationPathTypesError, PSBTOutputOwnershipClaimError,
PSBTOutputOwnershipContradictionError, PSBTParser, PSBTSeedCannotSignError,
PSBTSurplusDerivationPathsError)
@@ -53,13 +55,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
@@ -72,13 +74,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
@@ -96,13 +98,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
@@ -122,13 +124,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
@@ -271,6 +273,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.
@@ -467,6 +476,224 @@ def test_parse_sets_is_high_fee(self):
+class TestPSBTInputAmountVerification:
+ """
+ A compromised coordinator can declare whatever input amounts it likes. Unless we check
+ them against each input's non_witness_utxo, the fee we display is whatever the
+ coordinator wants it to be.
+ """
+ seed = PSBTTestData.seed
+
+ # Fixtures that ship a witness_utxo alongside their non_witness_utxo
+ WITNESS_UTXO_INPUTS = [
+ PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_1_INPUT,
+ PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_1_INPUT,
+ PSBTTestData.SINGLE_SIG_TAPROOT_1_INPUT,
+ PSBTTestData.MULTISIG_NATIVE_SEGWIT_1_INPUT,
+ PSBTTestData.MULTISIG_NESTED_SEGWIT_1_INPUT,
+ ]
+
+ # Legacy sighashes commit no input amount, so these must always be verifiable
+ LEGACY_INPUTS = [
+ PSBTTestData.SINGLE_SIG_LEGACY_P2PKH_1_INPUT,
+ PSBTTestData.MULTISIG_LEGACY_P2SH_1_INPUT,
+ ]
+
+
+ def build_psbt(self, psbt_base64: str) -> PSBT:
+ """ Turn an input-only fixture into a complete psbt that spends to an external recipient """
+ psbt: PSBT = PSBT.parse(a2b_base64(psbt_base64))
+ input_amount = sum([inp.utxo.value for inp in psbt.inputs])
+ psbt.outputs.clear()
+ psbt.outputs.append(create_output(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_RECEIVE, input_amount - 5_000))
+ return psbt
+
+
+ @pytest.mark.parametrize("psbt_base64", PSBTTestData.ALL_INPUTS)
+ def test_untampered_psbts_verify(self, psbt_base64: str):
+ """
+ There is one test psbt per script type. Each one includes the previous transaction
+ (non_witness_utxo) for every input. With nothing missing, there's no excuse for any
+ input not to verify: parsing should mark every input is_verified and total their amounts.
+ """
+ psbt = self.build_psbt(psbt_base64)
+ assert all(inp.is_verified is False for inp in psbt.inputs) # not verified until we do it
+
+ psbt_parser = PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST)
+
+ assert all(inp.is_verified for inp in psbt.inputs)
+ assert psbt_parser.verified_input_amount == sum([inp.utxo.value for inp in psbt.inputs])
+
+
+ @pytest.mark.parametrize("psbt_base64", PSBTTestData.ALL_INPUTS)
+ def test_tampered_non_witness_utxo_raises(self, psbt_base64: str):
+ """
+ Should raise PSBTInputAmountVerificationError if the input's txid doesn't match its
+ non_witness_utxo. Covers every supported script type.
+ """
+ psbt = self.build_psbt(psbt_base64)
+
+ # Editing the non_witness_utxo changes the txid it hashes to, so it no longer matches
+ # the txid the input claims to spend.
+ psbt.inputs[0].non_witness_utxo.vout[0].value += 100_000
+
+ with pytest.raises(PSBTInputAmountVerificationError):
+ PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST)
+
+
+ @pytest.mark.parametrize("psbt_base64", WITNESS_UTXO_INPUTS)
+ def test_witness_utxo_value_disagreeing_with_non_witness_utxo_raises(self, psbt_base64: str):
+ """
+ The non_witness_utxo still hashes correctly here, so embit's verify() is satisfied.
+ But embit's PSBT.utxo()/fee() prefer witness_utxo, so an inflated witness_utxo would
+ still drive the fee we display. Must be caught by the cross-check.
+ """
+ psbt = self.build_psbt(psbt_base64)
+ psbt.inputs[0].witness_utxo.value += 100_000
+
+ # Confirm the premise: the non_witness_utxo is untouched and still verifies
+ assert psbt.inputs[0].verify() is True
+
+ with pytest.raises(PSBTInputAmountVerificationError):
+ PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST)
+
+
+ @pytest.mark.parametrize("psbt_base64", WITNESS_UTXO_INPUTS)
+ def test_witness_utxo_script_pubkey_disagreeing_with_non_witness_utxo_raises(self, psbt_base64: str):
+ """
+ The input has both utxo fields. Its non_witness_utxo matches the input's txid, and its
+ witness_utxo has the same amount but a different scriptPubKey. The two contradict, so
+ the parse should raise PSBTInputAmountVerificationError.
+ """
+ psbt = self.build_psbt(psbt_base64)
+ witness_utxo = psbt.inputs[0].witness_utxo
+ original_value = witness_utxo.value
+
+ # Same value, different scriptPubKey
+ witness_utxo.script_pubkey = Script(b"\x00\x14" + b"\x11" * 20)
+
+ # Confirm the premise: only the scriptPubKey moved, and the non_witness_utxo still verifies
+ prevout = psbt.inputs[0].non_witness_utxo.vout[psbt.inputs[0].vout]
+ assert witness_utxo.value == original_value
+ assert witness_utxo.script_pubkey.data != prevout.script_pubkey.data
+ assert psbt.inputs[0].verify() is True
+
+ with pytest.raises(PSBTInputAmountVerificationError):
+ PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST)
+
+
+ @pytest.mark.parametrize("psbt_base64", LEGACY_INPUTS)
+ def test_legacy_input_without_non_witness_utxo_raises(self, psbt_base64: str):
+ """
+ BIP-174 reserves witness_utxo for segwit inputs, so for a legacy input, a
+ well-formed psbt would only provide its non_witness_utxo. In this test we create
+ an unusual psbt that presents a legacy input and only a witness_utxo. In this case
+ we can't verify the input's amount or the fee we would display. The parse should
+ raise PSBTInputAmountVerificationError.
+ """
+ psbt = self.build_psbt(psbt_base64)
+ inp = psbt.inputs[0]
+ inp.witness_utxo = inp.non_witness_utxo.vout[inp.vout]
+ inp.witness_utxo.value += 100_000
+ inp.non_witness_utxo = None
+
+ with pytest.raises(PSBTInputAmountVerificationError):
+ PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST)
+
+
+ def test_unrecognized_script_type_without_non_witness_utxo_raises(self):
+ """
+ Covers the None entry in UNCOMMITTED_AMOUNT_SCRIPT_TYPES. embit's script_type() returns
+ None for any scriptPubKey it doesn't recognize, and an unknown script type gives us no
+ basis to assume its sighash commits the input amount. So an unprovable amount on an
+ unrecognized input has to be refused rather than trusted.
+ """
+ psbt = self.build_psbt(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_1_INPUT)
+ inp = psbt.inputs[0]
+
+ # Bare multisig: a real scriptPubKey form that embit doesn't recognize, since it only
+ # knows the p2sh- and p2wsh-wrapped forms.
+ OP_1 = b"\x51"
+ OP_PUSHBYTES_33 = b"\x21"
+ OP_CHECKMULTISIG = b"\xae"
+ pubkey = list(inp.bip32_derivations.keys())[0].sec()
+ inp.witness_utxo = inp.non_witness_utxo.vout[inp.vout]
+ inp.witness_utxo.script_pubkey = Script(OP_1 + OP_PUSHBYTES_33 + pubkey + OP_1 + OP_CHECKMULTISIG)
+ inp.non_witness_utxo = None
+
+ # Confirm the premise: this really is an unrecognized script type
+ assert inp.witness_utxo.script_pubkey.script_type() is None
+
+ with pytest.raises(PSBTInputAmountVerificationError):
+ PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST)
+
+
+ @pytest.mark.parametrize("psbt_base64", WITNESS_UTXO_INPUTS)
+ def test_segwit_input_without_non_witness_utxo_is_allowed(self, psbt_base64: str):
+ """
+ Coordinators routinely omit non_witness_utxo for segwit inputs. BIP143/BIP341 commit
+ the input amount to the sighash, so a lie there invalidates the signature rather than
+ burning funds. Rejecting these would break almost every normal signing.
+ """
+ psbt = self.build_psbt(psbt_base64)
+ psbt.inputs[0].non_witness_utxo = None
+
+ # Parses without raising an exception
+ psbt_parser = PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST)
+ assert psbt_parser.verified_input_amount == psbt.inputs[0].witness_utxo.value
+
+
+ @pytest.mark.parametrize("psbt_base64", PSBTTestData.ALL_INPUTS)
+ def test_input_with_no_utxo_data_raises(self, psbt_base64: str):
+ """
+ Nothing to verify against and nothing to sum; refuse rather than guess.
+ """
+ psbt = self.build_psbt(psbt_base64)
+ psbt.inputs[0].witness_utxo = None
+ psbt.inputs[0].non_witness_utxo = None
+
+ with pytest.raises(PSBTMissingInputUtxoError):
+ PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST)
+
+
+ def test_outpoint_index_past_end_of_non_witness_utxo_raises(self):
+ """
+ The input's vout points to an output index past the end of its non_witness_utxo's
+ output list. Basically, it's claiming to spend an output that doesn't exist. When
+ this happens, the parse should raise PSBTMissingInputUtxoError.
+ """
+ psbt = self.build_psbt(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_1_INPUT)
+ inp = psbt.inputs[0]
+
+ # Confirm the premise: the prev tx really is shorter than the index we then claim
+ assert inp.vout < len(inp.non_witness_utxo.vout)
+ inp.vout = len(inp.non_witness_utxo.vout)
+
+ with pytest.raises(PSBTMissingInputUtxoError):
+ PSBTParser(p=psbt, seed=self.seed, network=SettingsConstants.REGTEST)
+
+
+ def test_every_input_is_checked_not_just_the_first(self):
+ """
+ A tampered input shouldn't be able to hide behind a legit one. Tampering the second
+ input of a 2-input psbt must raise, and the error must name the input that failed.
+ """
+ psbt: PSBT = PSBT.parse(a2b_base64(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_2_INPUTS))
+ assert len(psbt.inputs) == 2
+
+ # Untampered, both inputs verify and their amounts are summed
+ psbt_parser = PSBTParser(p=psbt, seed=PSBTTestData.two_input_seed, network=SettingsConstants.REGTEST)
+ assert psbt_parser.num_inputs == 2
+ assert psbt_parser.verified_input_amount == 56_522_834 + 1_990_245_069
+
+ psbt.inputs[1].non_witness_utxo.vout[0].value += 100_000
+
+ with 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 """
@@ -671,7 +898,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
@@ -1103,10 +1330,18 @@ def test__parse__verified_derivation_paths_empty_for_not_owned_input(self):
"""
psbt = self._psbt_with_change()
- # The other party's input: their utxo, carrying no derivation info
+ # 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
@@ -2430,5 +2665,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
+ # 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)Why this scored 81/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.