Merge pull request #681 from Foundation-Devices/SFT-7377-harden-utxo-history
What changed, and why it matters
This commit hardens how Passport remembers past Bitcoin input amounts. Previously, the device could record an unverified amount from a rejected or malicious transaction, then later compare a real transaction against that poisoned value and wrongly reject it. The fix only saves amounts after a signature succeeds, rejects duplicate inputs earlier, and adds a user menu to clear the saved amounts. It is a defensive hardening patch rather than a remote exploit fix.
Treat as a security-relevant hardening fix. Review that no other code paths still call OutptValueCache.add or verify_amount in a way that records rejected PSBT data, and confirm the duplicate-input check covers all input iteration paths. Consider whether a CVE is warranted given the device could be tricked into rejecting legitimate user transactions.
Security signals we found
SegWit input amount cache could be poisoned by unapproved/rejected PSBTs
Duplicate prevouts accepted before signing could enable amount-cache confusion
Amount recording moved to post-success signature path
New user-facing cache-clear flow added
Unit tests explicitly model malicious coordinator scenarios
Evidence from the diff
The patch changes OutptValueCache behavior in history.py: verify_amount now only checks known values and never records new ones; a new record_amount is called only after successful signing. psbtObject.consider_inputs now detects duplicate prevouts before signing and raises FatalPSBTIssue. sign_psbt_task verifies SegWit amounts during signing and records them only after all signatures succeed, preventing partial-sign failures from persisting data. A new ClearUTXOCacheFlow lets users clear the cache from the advanced menu. Tests cover duplicate inputs, rejected PSBTs, abandoned reviews, forged keys, partial signing, and cache reset.
Changed components
history.py (OutptValueCache)psbt.py (consider_inputs)tasks/sign_psbt_task.pyflows/clear_utxo_cache_flow.pymenus.py (advanced menu)Inspect captured patch +378 / −20
### ports/stm32/boards/Passport/manifest.py
@@ -85,6 +85,7 @@
'flows/backup_common_flow.py',
'flows/backup_flow.py',
'flows/change_pin_flow.py',
+ 'flows/clear_utxo_cache_flow.py',
'flows/delete_account_flow.py',
'flows/delete_multisig_flow.py',
'flows/envoy_setup_flow.py',
### ports/stm32/boards/Passport/modules/flows/__init__.py
@@ -29,6 +29,7 @@
from .auto_backup_flow import *
from .backup_flow import *
from .change_pin_flow import *
+from .clear_utxo_cache_flow import *
from .delete_account_flow import *
from .delete_multisig_flow import *
from .erase_passport_flow import *
### ports/stm32/boards/Passport/modules/flows/clear_utxo_cache_flow.py
@@ -0,0 +1,26 @@
+# SPDX-FileCopyrightText: © 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+from flows import Flow
+
+
+class ClearUTXOCacheFlow(Flow):
+ def __init__(self):
+ super().__init__(initial_state=self.confirm)
+
+ async def confirm(self):
+ from history import OutptValueCache
+ from pages import LongQuestionPage, SuccessPage
+
+ result = await LongQuestionPage(
+ text='Clear saved input amounts?\n\n'
+ "Only use this if Passport rejected a transaction because an input amount didn't match.\n\n"
+ 'Passport will forget amounts from past signings, '
+ 'so check the amounts in a trusted wallet before you sign again.').show()
+ if not result:
+ self.set_result(False)
+ return
+
+ OutptValueCache.clear()
+ await SuccessPage(text='Saved input amounts cleared.').show()
+ self.set_result(True)
### ports/stm32/boards/Passport/modules/history.py
@@ -107,24 +107,30 @@ def fetch_amount(cls, prevout):
@classmethod
def verify_amount(cls, prevout, amount, in_idx):
- # check this input either:
- # - not been seen before, in which case, record it
- # - OR: the amount matches exactly, any previously-seend UTXO w/ same outpoint
+ # Check previously recorded amounts without trusting new PSBT data.
+ # New amounts are recorded only after successful signing. Deliberately
+ # forget amounts seen only in unsigned/rejected PSBTs: remembering them
+ # lets an untrusted coordinator poison later legitimate spends. This
+ # loses cross-attempt comparison until we sign; history remains a
+ # secondary check, not a replacement for non_witness_utxo verification.
# raises IncorrectUTXOAmount with details if it fails, which should abort any signing
exp = cls.fetch_amount(prevout)
- if exp is None:
- # new entry, add it
- cls.add(prevout, amount)
-
- elif exp != amount:
+ if exp is not None and exp != amount:
# Found the hacking we are looking for!
ch = chains.current_chain()
exp, units = ch.render_value(exp, True)
amount, _ = ch.render_value(amount, True)
raise IncorrectUTXOAmount(in_idx, "Expected %s but PSBT claims %s %s" % (
exp, amount, units))
+ return exp
+
+ @classmethod
+ def record_amount(cls, prevout, amount, in_idx):
+ # Only call for inputs whose ownership was verified and which we signed.
+ if cls.verify_amount(prevout, amount, in_idx) is None:
+ cls.add(prevout, amount)
@classmethod
def add(cls, prevout, amount):
### ports/stm32/boards/Passport/modules/menus.py
@@ -410,6 +410,7 @@ def developer_pubkey_menu():
def advanced_menu():
from flows import ViewSeedWordsFlow, ErasePassportFlow, ScvFlow, ShowSecurityWordsSettingFlow
+ from flows import ClearUTXOCacheFlow
return [
{'icon': 'ICON_SETTINGS', 'label': 'Security Words', 'flow': ShowSecurityWordsSettingFlow},
@@ -419,6 +420,7 @@ def advanced_menu():
{'icon': 'ICON_ONE_KEY', 'label': 'Developer Pubkey', 'submenu': developer_pubkey_menu,
'statusbar': {'title': 'DEV. PUBKEY'}},
{'icon': 'ICON_MICROSD', 'label': 'microSD', 'submenu': microsd_menu},
+ {'icon': 'ICON_ERASE', 'label': 'Clear Saved Input Amounts', 'flow': ClearUTXOCacheFlow},
{'icon': 'ICON_ERASE', 'label': 'Erase Passport', 'flow': ErasePassportFlow,
'is_visible': lambda: not has_temporary_seed()},
{'icon': 'ICON_SHIELD', 'label': 'Security Check', 'flow': ScvFlow,
### ports/stm32/boards/Passport/modules/psbt.py
@@ -1443,9 +1443,17 @@ def consider_inputs(self):
missing = 0
total_in = 0
witness_inputs_to_verify = []
+ prevouts = set()
for i, txi in self.input_iter():
gc.collect()
+ # Reject repeated spends before review/signing, regardless of
+ # ownership or amount. Otherwise post-sign recording can persist
+ # the first claimed amount before a conflicting duplicate fails.
+ prevout = (txi.prevout.hash, txi.prevout.n)
+ if prevout in prevouts:
+ raise FatalPSBTIssue('Duplicate input #%d' % i)
+ prevouts.add(prevout)
inp = self.inputs[i]
if inp.fully_signed:
self.presigned_inputs.add(i)
@@ -1485,14 +1493,14 @@ def consider_inputs(self):
del utxo
+ del prevouts
if witness_inputs_to_verify:
import stash
with stash.SensitiveValues() as sv:
for i in witness_inputs_to_verify:
self.inputs[i].get_signing_node(sv, self.my_xfp, i)
- # Only update the amount cache after all claimed owned inputs have
- # proved their signing keys, so rejected metadata cannot be recorded.
+ # Check known amounts without recording unapproved PSBT data.
for i, txi in self.input_iter():
inp = self.inputs[i]
if inp.is_segwit:
### ports/stm32/boards/Passport/modules/tasks/sign_psbt_task.py
@@ -18,6 +18,7 @@ async def sign_psbt_task(on_done, psbt):
import gc
from foundation import secp256k1
from taproot import taproot_sign_key
+ import history
try:
with stash.SensitiveValues() as sv:
@@ -54,6 +55,9 @@ async def sign_psbt_task(on_done, psbt):
if not txi.scriptSig:
raise AssertionError('No scriptsig?')
+ if inp.is_segwit:
+ history.verify_amount(txi.prevout, inp.amount, in_idx)
+
if not inp.is_segwit:
# Hash by serializing/blanking various subparts of the transaction
digest = psbt.make_txn_sighash(in_idx, txi, inp.sighash)
@@ -102,6 +106,13 @@ async def sign_psbt_task(on_done, psbt):
success.add(in_idx)
+ # No cache writes until every signature succeeds. The success set only
+ # includes inputs whose signing keys we derived and verified above.
+ for in_idx, txi in psbt.input_iter():
+ inp = psbt.inputs[in_idx]
+ if in_idx in success and inp.is_segwit:
+ history.OutptValueCache.record_amount(txi.prevout, inp.amount, in_idx)
+
# All went well, so just fall through and call on_done()
except FraudulentChangeOutput as e:
### ports/stm32/boards/Passport/modules/tests/test_unit.py
@@ -104,6 +104,10 @@ def test_psbt_fee(test):
assert test('psbt_fee.py') == b'OK'
+def test_psbt_history(test):
+ assert test('psbt_history.py') == b'OK'
+
+
def test_unchained(test):
assert test('unchained.py') == b'OK'
### ports/stm32/boards/Passport/modules/tests/unit/psbt_amounts.py
@@ -8,7 +8,7 @@
from exceptions import FatalPSBTIssue
from psbt import psbtObject
from public_constants import MAX_MONEY
-from serializations import CTxOut
+from serializations import COutPoint, CTxIn, CTxOut
P2WPKH_SCRIPT = b'\x00\x14' + (b'\x11' * 20)
@@ -22,14 +22,6 @@ def __init__(self, values):
self.total_value_out = None
-class MockPrevout:
- n = 0
-
-
-class MockTxIn:
- prevout = MockPrevout()
-
-
class MockInput:
def __init__(self, value):
self.value = value
@@ -61,7 +53,9 @@ def __init__(self, values):
def input_iter(self):
for idx in range(self.num_inputs):
- yield idx, MockTxIn()
+ txi = CTxIn()
+ txi.prevout = COutPoint(idx + 1, 0)
+ yield idx, txi
def read_outputs(values):
### ports/stm32/boards/Passport/modules/tests/unit/psbt_fee.py
@@ -77,6 +77,7 @@ def assert_raises(exc_type, callback):
class MockPrevout:
+ hash = 1
n = 0
### ports/stm32/boards/Passport/modules/tests/unit/psbt_history.py
@@ -0,0 +1,304 @@
+# SPDX-FileCopyrightText: © 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+import common
+import history
+import pages
+import stash
+import uasyncio as asyncio
+from uio import BytesIO
+from ustruct import pack
+from ubinascii import unhexlify
+
+from exceptions import FatalPSBTIssue, IncorrectUTXOAmount
+from flows import ClearUTXOCacheFlow, SignPsbtCommonFlow
+from history import OutptValueCache as Cache
+from psbt import psbtInputProxy, psbtObject
+from public_constants import PSBT_IN_BIP32_DERIVATION, PSBT_IN_WITNESS_UTXO
+from public_constants import PSBT_IN_TAP_BIP32_DERIVATION
+from serializations import COutPoint, CTxIn, CTxOut, hash160, ser_compact_size
+from taproot import output_script
+from tasks.sign_psbt_task import sign_psbt_task
+
+
+MY_XFP = 0x12345678
+PUBKEY = unhexlify('0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798')
+
+
+class MockSettings:
+ def get(self, key, default=None):
+ return default
+
+
+class MockFlashCache:
+ def __init__(self):
+ self.data = {}
+ self.writes = 0
+ self.saves = 0
+
+ def get(self, key):
+ return self.data.get(key)
+
+ def set(self, key, value):
+ self.writes += 1
+ self.data[key] = value[:]
+
+ def remove(self, key):
+ self.writes += 1
+ self.data.pop(key, None)
+
+ def save(self):
+ self.saves += 1
+
+
+class MockNode:
+ def public_key(self):
+ return PUBKEY
+
+ def private_key(self):
+ return b'\x00' * 31 + b'\x01'
+
+
+class MockSensitiveValues:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ pass
+
+ def derive_path(self, path, register=True):
+ assert path == 'm/0'
+ assert register
+ return MockNode()
+
+
+def field(kind, value, key=b''):
+ key = bytes([kind]) + key
+ return ser_compact_size(len(key)) + key + ser_compact_size(len(value)) + value
+
+
+def make_input(amount, owned=True, pubkey=PUBKEY, taproot=False):
+ script = output_script(pubkey[1:], None) if taproot else b'\x00\x14' + hash160(pubkey)
+ txout = CTxOut(amount, script)
+ data = field(PSBT_IN_WITNESS_UTXO, txout.serialize())
+ if owned:
+ if taproot:
+ data += field(PSBT_IN_TAP_BIP32_DERIVATION, b'\x00' + pack('<II', MY_XFP, 0), pubkey[1:])
+ else:
+ data += field(PSBT_IN_BIP32_DERIVATION, pack('<II', MY_XFP, 0), pubkey)
+ return psbtInputProxy(BytesIO(data + b'\x00'), 0)
+
+
+class TestPSBT:
+ def __init__(self, inputs, prevouts=None):
+ self.inputs = inputs
+ self.my_xfp = MY_XFP
+ self.total_value_in = None
+ self.fee_is_verified = True
+ self.presigned_inputs = set()
+ self.num_inputs = len(inputs)
+ self.prevouts = prevouts or [COutPoint(idx + 1, 0) for idx in range(self.num_inputs)]
+ self.warnings = []
+ self.fail_at = None
+ for idx, txi in self.input_iter():
+ inputs[idx].validate(idx, txi, MY_XFP)
+
+ def input_iter(self):
+ for idx in range(self.num_inputs):
+ txi = CTxIn()
+ txi.prevout = self.prevouts[idx]
+ yield idx, txi
+
+ def make_txn_segwit_sighash(self, idx, *_args):
+ if idx == self.fail_at:
+ raise AssertionError('Simulated signing failure')
+ return b'\x42' * 32
+
+ make_txn_taproot_sighash = make_txn_segwit_sighash
+
+
+def assert_raises(exc_type, callback):
+ try:
+ callback()
+ except exc_type:
+ return
+ raise AssertionError('Expected {}'.format(exc_type))
+
+
+async def sign(psbt, success=True):
+ results = []
+
+ async def on_done(message, error):
+ results.append((message, error))
+
+ await sign_psbt_task(on_done, psbt)
+ assert len(results) == 1
+ if success:
+ assert results[0] == (None, None), results
+ else:
+ assert results[0][1] is not None
+
+
+class MockQuestionPage:
+ approved = False
+
+ def __init__(self, text, **_kwargs):
+ self.text = text
+
+ async def show(self):
+ if self.text == 'Sign transaction?':
+ return False
+ if self.text == 'Cancel this transaction?':
+ return True
+ assert 'Clear saved input amounts?' in self.text
+ return self.approved
+
+
+class MockSuccessPage:
+ def __init__(self, text):
+ assert text == 'Saved input amounts cleared.'
+
+ async def show(self):
+ pass
+
+
+async def run_tests():
+ flash = MockFlashCache()
+ replacements = (
+ (common, 'settings', MockSettings()),
+ (history, 'flash_cache', flash),
+ (stash, 'SensitiveValues', MockSensitiveValues),
+ (stash, 'blank_object', lambda obj: None),
+ (pages, 'QuestionPage', MockQuestionPage),
+ (pages, 'LongQuestionPage', MockQuestionPage),
+ (pages, 'SuccessPage', MockSuccessPage),
+ )
+ originals = [(module, name, getattr(module, name)) for module, name, _ in replacements]
+ original_runtime = Cache.runtime_cache
+ original_loaded = Cache._cache_loaded
+ try:
+ for module, name, replacement in replacements:
+ setattr(module, name, replacement)
+ Cache.runtime_cache = []
+ Cache._cache_loaded = False
+ prevout = COutPoint(1, 0)
+
+ # Duplicate outpoints must fail before signing, even with matching amounts,
+ # unowned inputs, or a non-adjacent duplicate. No rejected amount may persist.
+ for amounts in ((9999, 1000), (1000, 1000), (9999, 2000, 1000)):
+ for owned in (True, False):
+ outpoints = [COutPoint(idx + 1, 0) for idx in range(len(amounts))]
+ outpoints[-1] = COutPoint(1, 0)
+ duplicate = TestPSBT([make_input(amount, owned=owned) for amount in amounts], outpoints)
+ try:
+ psbtObject.consider_inputs(duplicate)
+ except FatalPSBTIssue as exc:
+ assert str(exc) == 'Duplicate input #%d' % (len(amounts) - 1)
+ else:
+ raise AssertionError('Duplicate input accepted')
+ assert all(inp.added_sig is None for inp in duplicate.inputs)
+ assert flash.writes == 0
+ Cache.runtime_cache = []
+ Cache._cache_loaded = False
+ assert Cache.fetch_amount(prevout) is None
+
+ # Different output indexes in the same transaction are distinct outpoints.
+ distinct = TestPSBT([make_input(1000), make_input(2000)],
+ [COutPoint(1, 0), COutPoint(1, 1)])
+ psbtObject.consider_inputs(distinct)
+ assert distinct.total_value_in == 3000
+ assert flash.writes == 0
+
+ # The real input parser and cache must not trust a PSBT rejected by consider_keys.
+ malicious = TestPSBT([make_input(9999, owned=False)])
+ psbtObject.consider_inputs(malicious)
+ assert_raises(FatalPSBTIssue, lambda: psbtObject.consider_keys(malicious))
+ assert flash.writes == 0
+ assert Cache.fetch_amount(prevout) is None
+
+ # Even valid owned metadata does not authorize a write before approval/signing.
+ abandoned = TestPSBT([make_input(8888)])
+ psbtObject.consider_inputs(abandoned)
+ psbtObject.consider_keys(abandoned)
+ review = SignPsbtCommonFlow(0)
+ review.psbt = abandoned
+ review.goto(review.sign_transaction)
+ assert await review.run() is None
+ assert abandoned.inputs[0].added_sig is None
+ assert flash.writes == 0
+ assert Cache.fetch_amount(prevout) is None
+
+ forged = TestPSBT([make_input(7777, pubkey=b'\x03' + PUBKEY[1:])])
+ assert_raises(AssertionError, lambda: psbtObject.consider_inputs(forged))
+ assert flash.writes == 0
+
+ # A later failure must not record an earlier input whose signature succeeded.
+ failed = TestPSBT([make_input(1000), make_input(2000)])
+ psbtObject.consider_inputs(failed)
+ failed.fail_at = 1
+ await sign(failed, success=False)
+ assert failed.inputs[0].added_sig
+ assert flash.writes == 0
+
+ # Only newly signed owned inputs are recorded, including for a partial PSBT.
+ approved = TestPSBT([make_input(1000), make_input(2000, owned=False), make_input(3000)])
+ psbtObject.consider_inputs(approved)
+ approved.inputs[2].fully_signed = True
+ await sign(approved)
+ assert approved.inputs[0].added_sig
+ assert flash.writes == 1
+ assert Cache.fetch_amount(prevout) == 1000
+ assert Cache.fetch_amount(COutPoint(2, 0)) is None
+ assert Cache.fetch_amount(COutPoint(3, 0)) is None
+
+ # Re-signing the same amount must not duplicate entries or cause FIFO eviction.
+ repeated = TestPSBT([make_input(1000)])
+ psbtObject.consider_inputs(repeated)
+ await sign(repeated)
+ assert flash.writes == 1
+ assert len(Cache.runtime_cache) == 1
+
+ # Reload the saved representation and retain the SegWit fee-attack defense.
+ Cache.runtime_cache = []
+ Cache._cache_loaded = False
+ changed = TestPSBT([make_input(1001)])
+ assert_raises(IncorrectUTXOAmount, lambda: psbtObject.consider_inputs(changed))
+ await sign(changed, success=False)
+ assert changed.inputs[0].added_sig is None
+ assert flash.writes == 1
+ assert Cache.fetch_amount(prevout) == 1000
+
+ # Cancelling reset preserves protection; confirming removes memory and saved data.
+ assert await ClearUTXOCacheFlow().run() is False
+ assert Cache.fetch_amount(prevout) == 1000
+ assert flash.writes == 1
+ MockQuestionPage.approved = True
+ assert await ClearUTXOCacheFlow().run() is True
+ assert flash.saves == 1
+ assert Cache.KEY not in flash.data
+ assert Cache.runtime_cache == []
+ Cache._cache_loaded = False
+ assert Cache.fetch_amount(prevout) is None
+
+ recovered = TestPSBT([make_input(1001)])
+ psbtObject.consider_inputs(recovered)
+ await sign(recovered)
+ assert Cache.fetch_amount(prevout) == 1001
+
+ # Taproot signatures use the same recording boundary as ECDSA signatures.
+ Cache.clear()
+ taproot = TestPSBT([make_input(4000, taproot=True)])
+ psbtObject.consider_inputs(taproot)
+ assert Cache.fetch_amount(prevout) is None
+ await sign(taproot)
+ assert taproot.inputs[0].tap_key_sig
+ assert Cache.fetch_amount(prevout) == 4000
+ return_value.write(b'OK')
+ finally:
+ for module, name, original in originals:
+ setattr(module, name, original)
+ Cache.runtime_cache = original_runtime
+ Cache._cache_loaded = original_loaded
+
+
+asyncio.run(run_tests())Why this scored 64/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.