Skip to content

Verify PSBT input amounts against the previous transaction - #977

Closed
0kPN1 wants to merge 1 commit into
SeedSigner:devfrom
0kPN1:verify-psbt-input-amounts
Closed

0kPN1 wants to merge 1 commit into
SeedSigner:devfrom
0kPN1:verify-psbt-input-amounts

Conversation

@0kPN1

@0kPN1 0kPN1 commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Description

Problem or Issue being addressed

PSBTParser reads each input's amount straight out of the PSBT and never checks it (psbt_parser.py#L97-L106):

if inp.witness_utxo:
    self.input_amount += inp.witness_utxo.value
elif inp.non_witness_utxo:
    self.input_amount += inp.utxo.value

witness_utxo / non_witness_utxo are supplied by whoever built the PSBT. Nothing in src/ calls PSBT.verify() or InputScope.verify() — grep -rn "non_witness_utxo" src/ returns the single hit above. The input total, and therefore the fee on PSBTMathScreen, is an unverified claim from the coordinator.

embit provides InputScope.verify() for exactly this, and its docstring is explicit about why:

Verifies the hash of previous transaction provided in non_witness_utxo. We must verify on a hardware wallet even on segwit transactions to avoid miner fee attack described here: https://blog.trezor.io/details-of-firmware-updates-for-trezor-one-version-1-9-1-and-trezor-model-t-version-2-3-1-1eba8f60f2dd

The "even on segwit" part is the non-obvious bit. BIP-143 commits only to the amount of the input currently being signed, so segwit is not inherently safe once a transaction has two or more inputs: an attacker can collect one valid signature per signing session by being truthful about exactly one input each time, then combine the sessions.

Solution

A bare psbt.verify() is too strict — it defaults to ignore_missing=False and raises for any input carrying no previous transaction, and BIP-174 permits a segwit input to supply only witness_utxo. That would reject PSBTs from coordinators that omit it.

So _verify_input_amounts() splits the two cases:

  • previous tx present but its txid does not match the outpoint → raise (this is the actual attack signature)
  • no previous tx at all → record in unverified_input_nums, so the UI can warn rather than refuse

has_unverified_input_amounts is exposed for a follow-up warning screen. This PR changes no UI, to keep it reviewable.

No extra memory cost: PSBT.parse() already defaults to CompressMode.KEEP_ALL, so the previous transaction is retained in RAM today and simply never used. The added work is one SHA256d per input over data already in memory. (CompressMode.PARTIAL keeps only the needed txout plus _txhash if memory ever matters — the check handles that case too.)

Additional Information

Compatibility. All seven bundled test PSBTs already carry the previous transaction and verify cleanly, so no currently-supported flow regresses:

fixture with previous tx verify()
SINGLE_SIG_NATIVE_SEGWIT_1_INPUT 1/1 pass
SINGLE_SIG_NESTED_SEGWIT_1_INPUT 1/1 pass
SINGLE_SIG_TAPROOT_1_INPUT 1/1 pass
SINGLE_SIG_LEGACY_P2PKH_1_INPUT 1/1 pass
MULTISIG_NATIVE_SEGWIT_1_INPUT 1/1 pass
MULTISIG_NESTED_SEGWIT_1_INPUT 1/1 pass
MULTISIG_LEGACY_P2SH_1_INPUT 1/1 pass

Overlapping PRs. #965 and #966 touch the same region of psbt_parser.py. This PR is independent of both and inserts its call in parse() rather than inside _parse_inputs(), but it will need a trivial rebase depending on merge order — happy to do that whenever suits.

Not hands-on tested. Verified via the unit test suite only; I have not run this on a Pi or the emulator. Since the change is confined to parsing and adds no screen, I did not want to claim hardware validation I did not do. Grateful if a reviewer with a device can confirm a normal signing flow is unaffected.

Exception type. I used RuntimeError to match the existing "Mixed inputs in the transaction" raise in the same file. A dedicated exception routed to a DireWarningScreen may fit the codebase better — happy to change it.

Screenshots

N/A — no new or modified screens. The parser exposes has_unverified_input_amounts but nothing renders it yet.


This pull request is categorized as a:

  • New feature
  • Bug fix
  • Code refactor
  • Documentation
  • Other

Checklist

I ran pytest locally

  • All tests passed before submitting the PR
  • I couldn't run the tests
  • N/A

191 passed (translations submodule initialised and catalogs compiled).


I included screenshots of any new or modified screens

Should be part of the PR description above.

  • Yes
  • No
  • N/A

I added or updated tests

Any new or altered functionality should be covered in a unit test. Any new or updated sequences require FlowTests.

  • Yes
  • No, I'm a fool
  • N/A

Three cases in tests/test_psbt_parser.py: every bundled PSBT verifies; a forged previous tx is rejected; a witness_utxo-only input is flagged but not rejected. No flow sequences changed, so no FlowTests.


I tested this PR hands-on on the following platform(s):

None — unit tests only, as noted above.


I have reviewed these notes:

  • Keep your changes limited in scope.
  • If you uncover other issues or improvements along the way, ideally submit those as a separate PR.
  • The more complicated the PR, the harder it is to review, test, and merge.
  • We appreciate your efforts, but we're a small team of volunteers so PR review can be a very slow process.
  • Please only "@" mention a contributor if their input is truly needed to enable further progress.
  • I understand

Scope kept to the parser; the warning screen is deliberately left for a follow-up.


🤖 Generated with Claude Code

`PSBTParser` took each input's declared amount straight from `witness_utxo` /
`non_witness_utxo` and never checked it. Those fields are supplied by whoever
built the PSBT, so the input total -- and therefore the fee shown on the
review screens -- was an unverified claim.

embit provides `InputScope.verify()` for exactly this: it re-hashes the
supplied previous transaction and compares it to the outpoint's txid. Its
docstring cites the 2020 miner-fee attack and notes that a hardware wallet
must do this check "even on segwit transactions", because BIP-143 commits
only to the amount of the input currently being signed -- with two or more
inputs an attacker can collect one valid signature per signing session by
being truthful about exactly one input each time.

`psbt.verify()` on its own is too strict: it raises for any input lacking a
previous tx, and BIP-174 permits a segwit input to carry only `witness_utxo`.
So this splits the two cases:

  * previous tx present but its txid does not match the outpoint -> reject
  * no previous tx at all -> record in `unverified_input_nums` so the UI can
    warn, rather than refusing PSBTs from coordinators that omit it

`has_unverified_input_amounts` is exposed for a follow-up warning screen; this
commit deliberately changes no UI.

All seven bundled test PSBTs (native segwit, nested segwit, taproot, legacy
p2pkh, and the three multisig variants) already carry the previous
transaction and verify cleanly, so no currently-supported flow regresses.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@0kPN1

0kPN1 commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

Cross-referencing #973, which I only found after opening this PR.

@vinovod reported on 2026-08-02 that they had independently identified and reproduced three issues in the PSBT review/signing flow on 0.8.7 and dev, and asked for a private security contact before publishing reproduction details. One of the three areas listed there for triage — "previous-transaction verification before fee review/signing" — sounds like it may cover the same ground as this PR, though I have no way to tell from the summary alone whether the underlying defect is the same one.

I reached this independently and had not seen #973 when I opened this PR; I searched the tracker only afterwards, which was the wrong order. To whatever extent the two overlap, @vinovod reported first.

newtonick added a commit to newtonick/seedsigner that referenced this pull request Aug 20, 2026
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() before any
amount is summed and raises InputAmountVerificationError when an input
has no utxo data, when its 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, and PSBTOverviewView catches it, clears the parser,
and routes to a discard-only PSBTInputVerificationFailedView (approach
and placement from SeedSigner#977). Segwit inputs carrying only a witness_utxo are
still accepted, since BIP-143 commits the amount they sign and Sparrow
never sends both utxo fields

Co-Authored-By: 0kPN1 <55192256+0kPN1@users.noreply.github.com>
newtonick added a commit to newtonick/seedsigner that referenced this pull request Aug 29, 2026
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 SeedSigner#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 Sparrow never sends both utxo fields

Co-Authored-By: 0kPN1 <55192256+0kPN1@users.noreply.github.com>
3rdIteration added a commit to 3rdIteration/seedsigner that referenced this pull request Sep 18, 2026
…ia descriptor

From a review of open upstream SeedSigner PRs and their discussions:

- Previous-tx proof (upstream SeedSigner#995/SeedSigner#977): a non_witness_utxo must hash to the
  txid its input spends (UTXO_MISMATCH), and a legacy p2sh input may not rely
  on a witness_utxo alone (INVALID_WITNESS_UTXO). Legacy signatures commit to
  no amount, so either lie hides fee in a single signing.
- Multisig change without global xpubs (review thread on upstream SeedSigner#1032): a
  change-shaped m-of-n containing our key is not provably this wallet's. It is
  now a payment unless a loaded descriptor identifies it; the new
  PSBTIdentifyChangeView offers "Load descriptor to identify change", and
  returning with a descriptor re-reads the psbt. verify_multisig_output's
  per-entry check is shared as _descriptor_owns_output.
- OP_RETURN payload read from its push opcode (SeedSigner#965/SeedSigner#1003): direct pushes lost
  their first byte on screen.
- INCONSISTENT_FINGERPRINTS (SeedSigner#1040): a global xpub whose fingerprint disagrees
  with the keys it derives.
- Untrusted-QR crashes (SeedSigner#967/SeedSigner#968/SeedSigner#970/SeedSigner#971): SeedQR checksum and whole-payload
  detection, signmessage bounds, parse_derivation_path on short/48h paths, and
  a UR2 seq_len bound.

New psbt_faker vectors cover each (PREV_TX_TXID_MISMATCH, LEGACY_P2SH_WITNESS_ONLY,
OP_RETURN_DIRECT_PUSH, TX-24.xpub_fingerprint_mismatch, TX-21.ms_foreign_quorum*,
TX-21.ms_honest_change_no_xpubs). TX-20 and XTRAS.MIXED_INPUT_TYPES are
re-vendored after generator fixes; TX-20 is no longer vacuous.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
3rdIteration added a commit to 3rdIteration/seedsigner that referenced this pull request Sep 18, 2026
* test+fix: resync psbt_faker corpus and close the gaps it exposes

Re-vendor the regenerated psbt_faker corpus (97 vectors, fixed BIP-371
taproot encoding) and cover every vector in psbt_suite_util.

Parser fixes for vectors that previously parsed:
- FORGED_OUTPUT_OWNERSHIP also when a genuine key of ours annotates an
  output whose script does not pay it (TX-21.claims_us_pays_other,
  TX-21.ms_repointed_*, TX-22.ms_decoy_*).
- MISLABELED_OUTPUT_OWNERSHIP: an output paying our key but attributed to
  a foreign fingerprint (TX-21.pays_us_claims_other, taproot_claims_other,
  ms_fp_relabeled).
- SURPLUS_DERIVATIONS / MIXED_DERIVATION_MAPS for contradictory claims
  (TX-22.surplus_paths, taproot_surplus_internal_key, mixed_path_maps*).
- SCRIPT_TIMELOCK warning for CLTV/CSV in an output's committed script
  (TX-20.cltv_time).
- verify_multisig_output checks every derivation entry instead of embit's
  first-match Descriptor.owns (decoy-last used to verify as ours).

TX-20.cltv_height/csv_relative are vacuous upstream (scriptPubKey is still
p2wpkh) and marked so.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test: stop flow tests hanging when collected after the refusal-screen tests

tests/test_psbt_refusal_screens.py imported the GUI before tests/base.py
installed its renderer and hardware-button doubles. Any flow test collected
after it then ran against the real, never-configured Renderer (every View and
the error View raise, so the Controller loops forever) or against real buttons
(real-screen flows wait for a key press forever). The full suite only passed
because alphabetical order puts the flow tests first.

The refusal-screen test now imports base first, and base.py also rebinds
seedsigner.gui.Renderer when the package was already imported by some other
module collected earlier.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix: port upstream PSBT/QR hardening; identify multisig change only via descriptor

From a review of open upstream SeedSigner PRs and their discussions:

- Previous-tx proof (upstream SeedSigner#995/SeedSigner#977): a non_witness_utxo must hash to the
  txid its input spends (UTXO_MISMATCH), and a legacy p2sh input may not rely
  on a witness_utxo alone (INVALID_WITNESS_UTXO). Legacy signatures commit to
  no amount, so either lie hides fee in a single signing.
- Multisig change without global xpubs (review thread on upstream SeedSigner#1032): a
  change-shaped m-of-n containing our key is not provably this wallet's. It is
  now a payment unless a loaded descriptor identifies it; the new
  PSBTIdentifyChangeView offers "Load descriptor to identify change", and
  returning with a descriptor re-reads the psbt. verify_multisig_output's
  per-entry check is shared as _descriptor_owns_output.
- OP_RETURN payload read from its push opcode (SeedSigner#965/SeedSigner#1003): direct pushes lost
  their first byte on screen.
- INCONSISTENT_FINGERPRINTS (SeedSigner#1040): a global xpub whose fingerprint disagrees
  with the keys it derives.
- Untrusted-QR crashes (SeedSigner#967/SeedSigner#968/SeedSigner#970/SeedSigner#971): SeedQR checksum and whole-payload
  detection, signmessage bounds, parse_derivation_path on short/48h paths, and
  a UR2 seq_len bound.

New psbt_faker vectors cover each (PREV_TX_TXID_MISMATCH, LEGACY_P2SH_WITNESS_ONLY,
OP_RETURN_DIRECT_PUSH, TX-24.xpub_fingerprint_mismatch, TX-21.ms_foreign_quorum*,
TX-21.ms_honest_change_no_xpubs). TX-20 and XTRAS.MIXED_INPUT_TYPES are
re-vendored after generator fixes; TX-20 is no longer vacuous.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(screenshots): give the multisig PSBT global xpubs; add PSBTIdentifyChangeView

The screenshot generator's multisig PSBT carries no PSBT_GLOBAL_XPUB, so since
multisig change is only identified through global xpubs or a loaded descriptor,
it had no change output and the PSBTChangeDetailsView_multisig_* screenshots
crashed (get_change_data returned None), failing CI's "Generate screenshots".

- The multisig screenshots now use a copy of that PSBT with global xpubs taken
  from its own wallet descriptor, like a coordinator that includes them.
- The parser is built with the loaded descriptor, and the descriptor is loaded
  before the PSBT, so the "verified" screenshot parses the way the device would.
- New screenshots for PSBTIdentifyChangeView (no descriptor / descriptor loaded),
  from the original xpub-less PSBT.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
newtonick added a commit that referenced this pull request Oct 20, 2026
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>
@newtonick

Copy link
Copy Markdown
Collaborator

Replaced with #995, thank you for this contribution. Still plan to give credit for the release.

@newtonick newtonick closed this Oct 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants