From c00a7f8601aec26d1053fbd7e01366ab7685425c Mon Sep 17 00:00:00 2001 From: kkdao <44775666+kkdao@users.noreply.github.com> Date: Sun, 20 Sep 2026 14:23:51 +0100 Subject: [PATCH 01/10] fix: read the account path this card holds The card flow took the account path from the first bip32 derivation of input 0. An input can legitimately carry no ECDSA derivation -- a taproot input, or one another wallet has already signed -- and next(iter({}.values())) then raised a bare StopIteration, which reaches the user as a crash rather than as a refusal. The first input that does carry one is not the answer either. A psbt may spend from several wallets, and another signer's path exports an account this card has no part in, which then rejects the input it could have signed. Ask the card for its master fingerprint first and read the account only from derivations naming it. No input naming that fingerprint means the card is not a signer here, which is a refusal, not a fallback. A zero fingerprint is still read when nothing names the card. A coordinator given only an xpub writes 00000000 for the master it was never told, and the parser already backfills it wherever the card's key derives the input; skipping it refused a psbt the card can sign. --- src/seedsigner/views/psbt_views.py | 89 ++++++++++-- tests/test_psbt_card_account_path.py | 201 +++++++++++++++++++++++++++ 2 files changed, 280 insertions(+), 10 deletions(-) create mode 100644 tests/test_psbt_card_account_path.py diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index 220aa37b9..57c37a6ee 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -27,6 +27,49 @@ +def account_path_for_inputs(psbt, master_fingerprint: bytes = None) -> list[int] | None: + """The hardened prefix of an input derivation, or None. + + Every input is considered, not just the first: an input can legitimately + carry no ECDSA bip32 derivation -- taproot, or one another wallet has + already finished -- and reading input 0 alone raised a bare StopIteration + that surfaced as a crash rather than a refusal. + + With `master_fingerprint`, only derivations claiming that key are read. A + psbt may spend from several wallets, and the account to export from a card + is the one that card's own fingerprint names: taking whichever input comes + first exports an account the card has nothing to do with, and then rejects + the input it could actually have signed. No input naming that fingerprint + means the card is not a signer here, which is a refusal, not a fallback. + + A zero fingerprint is the one exception, read only when no derivation names + the card: a coordinator given only an xpub writes 00000000 for the master + it was never told. It proves nothing on its own. The parser backfills it + only where the card's key derives the input, and the card's fingerprint is + checked after that. + """ + HARDENED_INDEX = 0x80000000 + MISSING_FINGERPRINT = b"\x00" * 4 + + def hardened_prefix(derivation): + account_path = [] + for idx in derivation: + if idx & HARDENED_INDEX: + account_path.append(idx) + else: + break + return account_path + + unnamed = None + for inp in getattr(psbt, "inputs", None) or []: + for deriv in inp.bip32_derivations.values(): + if master_fingerprint is None or deriv.fingerprint == master_fingerprint: + return hardened_prefix(deriv.derivation) + if unnamed is None and deriv.fingerprint == MISSING_FINGERPRINT: + unnamed = hardened_prefix(deriv.derivation) + return unnamed + + class PSBTSelectSeedView(View): SCAN_SEED = ButtonOption("Scan a seed", SeedSignerIconConstants.QRCODE) SATOCHIP = ButtonOption("Use Satochip card", SeedSignerIconConstants.FINGERPRINT) @@ -236,15 +279,43 @@ def ensure_microsd_seed_warning() -> bool: network = self.settings.get_value(SettingsConstants.SETTING__NETWORK) is_mainnet = network == SettingsConstants.MAINNET - first_der = next(iter(self.controller.psbt.inputs[0].bip32_derivations.values())).derivation - account_path = [] - HARDENED_INDEX = 0x80000000 - for idx in first_der: - if idx & HARDENED_INDEX: - account_path.append(idx) - else: - break + # Ask the card who it is before reading the psbt's account paths. A + # psbt may spend from several wallets, and only the derivations + # naming this card's fingerprint say which account it holds; the + # first input's path can belong to a wallet the card has no part in. + # The master key's xtype only picks version bytes, and a fingerprint + # does not depend on those. + try: + master_xpub = connector.card_bip32_get_xpub("", "standard", is_mainnet) + master_fp = HDKey.from_base58(master_xpub).my_fingerprint + except Exception as e: + logger.exception("Failed to export master xpub from %s card", card_label) + self.run_screen( + WarningScreen, + title="Failed", + status_headline=None, + text=str(e), + ) + return Destination(PSBTSelectSeedView, clear_history=True) + + account_path = account_path_for_inputs(self.controller.psbt, master_fp) + if account_path is None: + # No input names a key for this card to derive: a taproot-only + # psbt, one whose ECDSA inputs another wallet already finished, + # or simply a psbt this card is not a signer on. Say so rather + # than raising StopIteration out of a next(iter(...)) on the + # first input, or exporting some other wallet's account. + self.run_screen( + WarningScreen, + title=_("Cannot sign"), + status_icon_name=SeedSignerIconConstants.WARNING, + status_headline=None, + text=_("No input in this PSBT names a key this card can derive."), + ) + return Destination(PSBTSelectSeedView, clear_history=True) + + HARDENED_INDEX = 0x80000000 account_path_str = "m" for i in account_path: hardened = bool(i & HARDENED_INDEX) @@ -267,7 +338,6 @@ def ensure_microsd_seed_warning() -> bool: try: try: account_xpub = connector.card_bip32_get_xpub(account_path_str, xtype, is_mainnet) - master_xpub = connector.card_bip32_get_xpub("", xtype, is_mainnet) except Exception as e: logger.exception("Failed to export xpub from %s card", card_label) loading.stop() @@ -281,7 +351,6 @@ def ensure_microsd_seed_warning() -> bool: return Destination(PSBTSelectSeedView, clear_history=True) root_key = HDKey.from_base58(account_xpub) - master_fp = HDKey.from_base58(master_xpub).my_fingerprint try: self.controller.psbt_parser = PSBTParser( diff --git a/tests/test_psbt_card_account_path.py b/tests/test_psbt_card_account_path.py new file mode 100644 index 000000000..96a55c45c --- /dev/null +++ b/tests/test_psbt_card_account_path.py @@ -0,0 +1,201 @@ +# pylint: disable=missing-function-docstring +# Must import base before any seedsigner modules +from base import BaseTest + +from embit import bip32, script +from embit.psbt import DerivationPath, InputScope, PSBT +from embit.ec import PrivateKey +from embit.transaction import Transaction, TransactionInput, TransactionOutput + +from seedsigner.models.seed import Seed +from seedsigner.models.settings_definition import SettingsConstants +from seedsigner.views import psbt_views +from seedsigner.views.psbt_views import account_path_for_inputs + + +HARDENED = 0x80000000 +ACCOUNT = [84 + HARDENED, 0 + HARDENED, 0 + HARDENED, 0, 0] + + +def psbt_with(derivation_flags): + """A PSBT whose inputs carry a derivation only where flagged True.""" + psbt = PSBT() + psbt.inputs = [] + for i, has_derivation in enumerate(derivation_flags): + inp = InputScope() + if has_derivation: + pub = PrivateKey(bytes([i + 1]) * 32).get_public_key() + inp.bip32_derivations[pub] = DerivationPath(b"\x00" * 4, list(ACCOUNT)) + psbt.inputs.append(inp) + return psbt + + +class TestAccountPathFromInputs(BaseTest): + """The account path must come from an input that actually has one.""" + + def test_uses_the_first_input_with_a_derivation(self): + # Input 0 is bare -- a taproot input, or one another wallet finished + psbt = psbt_with([False, True]) + + assert account_path_for_inputs(psbt) == [84 + HARDENED, 0 + HARDENED, 0 + HARDENED] + + def test_plain_case_still_uses_input_zero(self): + psbt = psbt_with([True, True]) + + assert account_path_for_inputs(psbt) == [84 + HARDENED, 0 + HARDENED, 0 + HARDENED] + + def test_no_derivations_anywhere_is_none_not_an_exception(self): + psbt = psbt_with([False, False]) + + assert account_path_for_inputs(psbt) is None + + +class TestAccountPathBelongsToTheCard(BaseTest): + """ + A psbt can carry inputs from more than one wallet. The account to export + from the card is the one the *card's* fingerprint claims, not whichever + input happens to come first -- reading the wrong one exports an account + the card has no business in and then rejects the input it could have signed. + """ + + def _psbt_with_fingerprints(self, entries): + """entries: [(fingerprint, path)] -- one input each.""" + psbt = PSBT() + psbt.inputs = [] + for i, (fingerprint, path) in enumerate(entries): + inp = InputScope() + pub = PrivateKey(bytes([i + 1]) * 32).get_public_key() + inp.bip32_derivations[pub] = DerivationPath(fingerprint, list(path)) + psbt.inputs.append(inp) + return psbt + + def test_picks_the_input_matching_the_card_fingerprint(self): + stranger = [49 + HARDENED, 0 + HARDENED, 7 + HARDENED, 0, 0] + psbt = self._psbt_with_fingerprints([ + (b"\xaa" * 4, stranger), + (b"\xbb" * 4, ACCOUNT), + ]) + + path = account_path_for_inputs(psbt, master_fingerprint=b"\xbb" * 4) + + assert path == [84 + HARDENED, 0 + HARDENED, 0 + HARDENED] + + def test_a_card_named_by_no_input_gets_no_path(self): + psbt = self._psbt_with_fingerprints([(b"\xaa" * 4, ACCOUNT)]) + + assert account_path_for_inputs(psbt, master_fingerprint=b"\xbb" * 4) is None + + def test_a_blank_fingerprint_is_read_when_none_names_the_card(self): + """ + A coordinator given only an xpub writes 00000000 for the master it was + never told. The parser backfills that from the card's key if the key + derives it, so the account still has to be read from it. + """ + psbt = self._psbt_with_fingerprints([(b"\x00" * 4, ACCOUNT)]) + + path = account_path_for_inputs(psbt, master_fingerprint=b"\xbb" * 4) + + assert path == [84 + HARDENED, 0 + HARDENED, 0 + HARDENED] + + def test_the_cards_own_fingerprint_wins_over_a_blank_one(self): + blank = [49 + HARDENED, 0 + HARDENED, 7 + HARDENED, 0, 0] + psbt = self._psbt_with_fingerprints([ + (b"\x00" * 4, blank), + (b"\xbb" * 4, ACCOUNT), + ]) + + path = account_path_for_inputs(psbt, master_fingerprint=b"\xbb" * 4) + + assert path == [84 + HARDENED, 0 + HARDENED, 0 + HARDENED] + + +CARD_MNEMONIC = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about".split() +STRANGER_MNEMONIC = "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong".split() + + +class MockCard: + """Answers xpub requests the way a card holding `root` would, and keeps a list of them.""" + + def __init__(self, root): + self.root = root + self.exported = [] + + def card_bip32_get_xpub(self, path, xtype, is_mainnet): + self.exported.append(path) + key = self.root.derive(path) if path else self.root + return key.to_public().to_base58() + + +def spend_from(owners): + """A PSBT spending one p2wpkh coin per (root, path, fingerprint) in `owners`.""" + coins = [] + for i, (root, path, fingerprint) in enumerate(owners): + public_key = root.derive(path).get_public_key() + spk = script.p2wpkh(public_key) + prev = Transaction(vin=[TransactionInput(bytes([i + 1]) * 32, 0)], vout=[TransactionOutput(100_000, spk)]) + coins.append((prev, public_key, DerivationPath(fingerprint, bip32.parse_path(path)))) + + payee = script.p2wpkh(PrivateKey(b"\x07" * 32).get_public_key()) + tx = Transaction( + vin=[TransactionInput(prev.txid(), 0) for prev, _, _ in coins], + vout=[TransactionOutput(100_000 * len(coins) - 1_000, payee)], + ) + psbt = PSBT(tx) + for inp, (prev, public_key, derivation) in zip(psbt.inputs, coins): + inp.witness_utxo = prev.vout[0] + inp.bip32_derivations[public_key] = derivation + return psbt + + +class TestCardFlowReadsTheCardsAccount(BaseTest): + """ + What PSBTSelectSeedView asks the card for. The account it exports decides + which inputs the card can be shown to sign, so reading it from the wrong + derivation turns a psbt the card can sign into a refusal. + """ + + def choose_the_card(self, monkeypatch, card, psbt): + from seedsigner.helpers import seedkeeper_utils + + monkeypatch.setattr(seedkeeper_utils, "init_satochip", lambda *args, **kwargs: card) + self.controller.storage.seeds = [] + self.controller.psbt = psbt + + view = psbt_views.PSBTSelectSeedView() + warnings = [] + + def run_screen(screen_cls, **kwargs): + if screen_cls.__name__ == "ButtonListScreen": + return kwargs["button_data"].index(psbt_views.PSBTSelectSeedView.SATOCHIP) + warnings.append(kwargs.get("text")) + return 0 + + monkeypatch.setattr(view, "run_screen", run_screen) + return view.run(), warnings + + def test_another_wallets_input_first_does_not_pick_the_account(self, monkeypatch): + card_root = Seed(mnemonic=CARD_MNEMONIC).get_root(SettingsConstants.MAINNET) + stranger_root = Seed(mnemonic=STRANGER_MNEMONIC).get_root(SettingsConstants.MAINNET) + psbt = spend_from([ + (stranger_root, "m/84h/0h/5h/0/0", stranger_root.my_fingerprint), + (card_root, "m/84h/0h/0h/0/0", card_root.my_fingerprint), + ]) + card = MockCard(card_root) + + destination, warnings = self.choose_the_card(monkeypatch, card, psbt) + + assert warnings == [] + assert destination.View_cls is psbt_views.PSBTOverviewView + assert "m/84'/0'/0'" in card.exported + assert "m/84'/0'/5'" not in card.exported + assert self.controller.psbt_parser.root_path == bip32.parse_path("m/84h/0h/0h") + + def test_a_blank_fingerprint_on_the_cards_input_still_signs(self, monkeypatch): + card_root = Seed(mnemonic=CARD_MNEMONIC).get_root(SettingsConstants.MAINNET) + psbt = spend_from([(card_root, "m/84h/0h/0h/0/3", b"\x00" * 4)]) + + destination, warnings = self.choose_the_card(monkeypatch, MockCard(card_root), psbt) + + assert warnings == [] + assert destination.View_cls is psbt_views.PSBTOverviewView + assert self.controller.psbt_sign_with_satochip is True From ee9ad07f1b181b551e8fc393ec1f68ccbbf969fb Mon Sep 17 00:00:00 2001 From: kkdao <44775666+kkdao@users.noreply.github.com> Date: Sun, 20 Sep 2026 14:24:32 +0100 Subject: [PATCH 02/10] fix: raise the retry timeout from the used value "Retry (higher timeout)" computed the new timeout from the configured setting rather than from the timeout that had just expired, so every retry landed on the same value and pressing it twice changed nothing. The screen quoted the setting too, naming a timeout the user had already moved past. And the raised value was cleared only when signing produced no signatures, so a successful sign left it on the controller for the next PSBT to inherit. Track the used timeout, raise from it, quote it, and clear it whenever the flow ends. --- src/seedsigner/views/psbt_views.py | 55 ++++++++++++++--- tests/test_psbt_retry_timeout.py | 99 ++++++++++++++++++++++++++++++ 2 files changed, 144 insertions(+), 10 deletions(-) create mode 100644 tests/test_psbt_retry_timeout.py diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index 57c37a6ee..9e520d753 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -27,6 +27,34 @@ + +# How much a "Retry (higher timeout)" adds, in seconds. +RETRY_TIMEOUT_STEP = 0.75 + + +def signing_timeout(controller, configured_timeout: float) -> float: + """The timeout this signing attempt should use.""" + return getattr(controller, "_psbt_sign_retry_timeout", None) or configured_timeout + + +def bump_retry_timeout(controller, used_timeout: float) -> float: + """Raise the retry timeout above the value that just timed out. + + Raising it from the configured setting instead meant every retry landed on + the same value, so pressing "Retry (higher timeout)" a second time changed + nothing. + """ + new_timeout = used_timeout + RETRY_TIMEOUT_STEP + controller._psbt_sign_retry_timeout = new_timeout + return new_timeout + + +def clear_retry_timeout(controller) -> None: + """Forget the raised timeout, so the next PSBT starts from the setting.""" + if hasattr(controller, "_psbt_sign_retry_timeout"): + delattr(controller, "_psbt_sign_retry_timeout") + + def account_path_for_inputs(psbt, master_fingerprint: bytes = None) -> list[int] | None: """The hardened prefix of an input derivation, or None. @@ -1596,10 +1624,16 @@ def run(self): loading.start() try: sign_result = None + retry_timeout = None if self.controller.psbt_sign_with_satochip: is_keycard = getattr(connector, "is_keycard_backend", False) # Track retry state on the controller so we can increase timeout across retries - retry_timeout = getattr(self.controller, "_psbt_sign_retry_timeout", None) + configured_timeout = ( + self.settings.get_value(SettingsConstants.SETTING__KEYCARD_SIGN_TIMEOUT) + if is_keycard + else self.settings.get_value(SettingsConstants.SETTING__SATOCHIP_SIGN_TIMEOUT) + ) + retry_timeout = signing_timeout(self.controller, configured_timeout) if is_keycard: from seedsigner.helpers.keycard_signer import sign_psbt_with_keycard sign_result = sign_psbt_with_keycard(psbt, connector, timeout=retry_timeout) @@ -1654,18 +1688,17 @@ def run(self): "PSBTFinalizeView" if self.controller.psbt_sign_with_satochip else "PSBTSigningErrorView", ) # Clean up retry state regardless of path taken - if hasattr(self.controller, "_psbt_sign_retry_timeout"): - delattr(self.controller, "_psbt_sign_retry_timeout") + used_timeout = retry_timeout + clear_retry_timeout(self.controller) if self.controller.psbt_sign_with_satochip: # If a timeout occurred during signing, offer to retry with higher timeout if sign_result and sign_result.timed_out: is_keycard = getattr(connector, "is_keycard_backend", False) - current_timeout = ( - self.settings.get_value(SettingsConstants.SETTING__KEYCARD_SIGN_TIMEOUT) - if is_keycard - else self.settings.get_value(SettingsConstants.SETTING__SATOCHIP_SIGN_TIMEOUT) - ) + # The value that actually timed out, not the setting: after a + # retry those differ, and quoting the setting told the user a + # timeout they had already moved past. + current_timeout = used_timeout card_label = "Keycard" if is_keycard else "Satochip" selected = self.run_screen( @@ -1681,8 +1714,7 @@ def run(self): if selected == 0: # Increase timeout by one step and retry - new_timeout = current_timeout + 0.75 - self.controller._psbt_sign_retry_timeout = new_timeout + new_timeout = bump_retry_timeout(self.controller, current_timeout) logger.info( "PSBTFinalize: user chose to retry with timeout=%.2fs", new_timeout ) @@ -1694,6 +1726,9 @@ def run(self): logger.info("PSBTFinalize: signatures added; routing=PSBTSignedQRDisplayView") self.controller.psbt = trimmed_psbt self.controller.psbt_sign_with_satochip = False + # A raised timeout belonged to this psbt only; the next one starts from + # the configured setting again. + clear_retry_timeout(self.controller) return Destination(PSBTSignedQRDisplayView) diff --git a/tests/test_psbt_retry_timeout.py b/tests/test_psbt_retry_timeout.py new file mode 100644 index 000000000..a4b3e536e --- /dev/null +++ b/tests/test_psbt_retry_timeout.py @@ -0,0 +1,99 @@ +# pylint: disable=missing-function-docstring +from types import SimpleNamespace + +# Must import base before any seedsigner modules +from base import BaseTest + +from seedsigner.views.psbt_views import ( + RETRY_TIMEOUT_STEP, + bump_retry_timeout, + clear_retry_timeout, + signing_timeout, +) + + +class TestRetryTimeout(BaseTest): + """Each retry must raise the timeout that was actually used.""" + + def test_first_attempt_uses_the_setting(self): + controller = SimpleNamespace() + + assert signing_timeout(controller, 2.0) == 2.0 + + def test_a_retry_uses_the_raised_value(self): + controller = SimpleNamespace() + + used = signing_timeout(controller, 2.0) + bump_retry_timeout(controller, used) + assert signing_timeout(controller, 2.0) == 2.0 + RETRY_TIMEOUT_STEP + + def test_retries_keep_climbing(self): + controller = SimpleNamespace() + seen = [] + for _ in range(3): + used = signing_timeout(controller, 2.0) + seen.append(used) + bump_retry_timeout(controller, used) + + assert seen == [2.0, 2.0 + RETRY_TIMEOUT_STEP, 2.0 + 2 * RETRY_TIMEOUT_STEP] + + def test_a_finished_flow_starts_from_the_setting_again(self): + controller = SimpleNamespace() + bump_retry_timeout(controller, signing_timeout(controller, 2.0)) + + clear_retry_timeout(controller) + + assert signing_timeout(controller, 2.0) == 2.0 + + +class TestFinalizeRetriesClimb(BaseTest): + """ + The helpers above only help if PSBTFinalizeView uses them: each "Retry + (higher timeout)" has to hand the card more time than the attempt that + just expired, and the screen has to quote the timeout that expired. + """ + + def test_each_retry_gives_the_card_a_longer_timeout(self, monkeypatch): + from embit import script + from embit.ec import PrivateKey + from embit.psbt import PSBT + from embit.transaction import Transaction, TransactionInput, TransactionOutput + + from seedsigner.helpers import satochip_signer, seedkeeper_utils + from seedsigner.helpers.satochip_signer import SignResult + from seedsigner.models.settings import SettingsConstants + from seedsigner.views import psbt_views + + spk = script.p2wpkh(PrivateKey(b"\x01" * 32).get_public_key()) + prev = Transaction(vin=[TransactionInput(b"\x11" * 32, 0)], vout=[TransactionOutput(100_000, spk)]) + psbt = PSBT(Transaction(vin=[TransactionInput(prev.txid(), 0)], vout=[TransactionOutput(90_000, spk)])) + psbt.inputs[0].witness_utxo = prev.vout[0] + self.controller.psbt = psbt + self.controller.psbt_parser = None + self.controller.psbt_sign_with_satochip = True + + monkeypatch.setattr(seedkeeper_utils, "init_satochip", lambda *args, **kwargs: SimpleNamespace()) + timeouts = [] + + def card_that_times_out(psbt, connector, timeout=None): + timeouts.append(timeout) + return SignResult(signed_count=0, timed_out=True) + + monkeypatch.setattr(satochip_signer, "sign_psbt_with_satochip", card_that_times_out) + + quoted = [] + for _ in range(3): + view = psbt_views.PSBTFinalizeView() + + def run_screen(screen_cls, **kwargs): + if "text" in kwargs: + quoted.append(kwargs["text"]) + # Approve, then "Retry (higher timeout)" when it times out + return 0 + + monkeypatch.setattr(view, "run_screen", run_screen) + assert view.run().View_cls is psbt_views.PSBTFinalizeView + + setting = self.settings.get_value(SettingsConstants.SETTING__SATOCHIP_SIGN_TIMEOUT) + assert timeouts == [setting, setting + RETRY_TIMEOUT_STEP, setting + 2 * RETRY_TIMEOUT_STEP] + assert f"timed out at {timeouts[-1]}s" in quoted[-1] From b0b68ef89ee91ca93c4942721467a3ef61123c92 Mon Sep 17 00:00:00 2001 From: kkdao <44775666+kkdao@users.noreply.github.com> Date: Sun, 20 Sep 2026 14:24:42 +0100 Subject: [PATCH 03/10] fix: keep the card's key data for a parser rebuild PSBTOverviewView rebuilds the PSBTParser whenever the parser does not match psbt_seed, passing seed=psbt_seed. In the card flow that is None -- the card holds the key, not a seed -- so the rebuilt parser had no root to derive with: the review screens showed a transaction with no inputs, outputs or fee, and the flow failed further along. Loading a multisig descriptor is the ordinary way to reach that rebuild. Remember what the card's parser was built from and reuse it. The multisig card branch builds its parser with no key material on purpose, a multisig being reviewed against its descriptor rather than against one cosigner's xpub, so it records an empty dict and a rebuild reproduces that parser. Only an unset record -- a card flow whose key data is gone -- is refused, with a reason, instead of parsing blind. A parser built without key material does not parse on construction, so the rebuild has to finish the job. Unparsed it reports no inputs, no outputs and no fee, which is the same empty review by another route. That rebuild covers the card's multisig too, which the overview had a shortcut for: a dropped parser in any card flow was rebuilt seedless, as if every card signed a multisig. A single-sig card reaching it had its psbt parsed with no key, which raises rather than refuses. The shortcut goes, and both card flows rebuild from what they recorded. --- src/seedsigner/controller.py | 8 ++ src/seedsigner/models/psbt_parser.py | 6 ++ src/seedsigner/views/psbt_views.py | 59 +++++++++--- tests/test_flows_psbt.py | 3 + tests/test_psbt_overview_card_flow.py | 124 ++++++++++++++++++++++++++ 5 files changed, 187 insertions(+), 13 deletions(-) create mode 100644 tests/test_psbt_overview_card_flow.py diff --git a/src/seedsigner/controller.py b/src/seedsigner/controller.py index 0cd3f04ba..559c32ea2 100644 --- a/src/seedsigner/controller.py +++ b/src/seedsigner/controller.py @@ -291,6 +291,14 @@ def _load_block_anchor(cls): GPG_Admin_PIN = None javacard_keys: dict | None = None + # What the card flow's PSBTParser was built from (root, root_path, + # master_fingerprint). The card holds the key, so there is no seed to + # rebuild a parser from later. An empty dict means the parser was built + # without key material on purpose -- the multisig card flow, which reviews + # against a descriptor. None means no card flow is in progress. + psbt_card_keys: dict | None = None + + # Destination placeholder for when we need to jump out to a side flow but intend to # return navigation to the main flow (e.g. PSBT flow, load multisig descriptor, # then resume PSBT flow). diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 5e8f06b3e..ebc191509 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -367,6 +367,11 @@ def __init__( self.verified_input_derivation_paths: List[List[DerivationPath]] = [] self.verified_output_derivation_paths: List[List[DerivationPath]] = [] + # Whether a successful parse has run. Constructing without key material + # leaves every total at zero, which reads exactly like a transaction that + # moves nothing -- see PSBTOverviewView, which has to finish the job. + self.parsed: bool = False + if self.seed is not None or self.root is not None: self.parse() @@ -547,6 +552,7 @@ def parse(self): # Every total is known now, so settle this once rather than per view. self.is_high_fee = self.has_high_fee() + self.parsed = True return True diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index 9e520d753..bfe61ac25 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -303,6 +303,11 @@ def ensure_microsd_seed_warning() -> bool: self.controller.psbt_parser = parser self.controller.psbt_seed = None self.controller.psbt_sign_with_satochip = True + # Built with no key material on purpose: a multisig is reviewed + # against its descriptor, not against one cosigner's xpub. Say so + # rather than leaving it unset, so a later rebuild reproduces this + # parser instead of refusing for want of a card key. + self.controller.psbt_card_keys = {} return Destination(PSBTOverviewView) network = self.settings.get_value(SettingsConstants.SETTING__NETWORK) @@ -444,6 +449,15 @@ def ensure_microsd_seed_warning() -> bool: self.controller.psbt_seed = None self.controller.psbt_sign_with_satochip = True + # The card, not a seed, holds the key. Keep what the parser was built + # from: anything that rebuilds it later (loading a descriptor, for + # one) has no seed to fall back on and would otherwise build a parser + # with no root, which can answer nothing about the transaction. + self.controller.psbt_card_keys = dict( + root=root_key, + root_path=account_path, + master_fingerprint=master_fp, + ) return Destination(PSBTOverviewView) elif button_data[selected_menu_num] in [self.TYPE_12WORD, self.TYPE_15WORD, self.TYPE_18WORD, self.TYPE_21WORD, self.TYPE_24WORD]: @@ -824,19 +838,6 @@ def __init__(self): self.loading_screen = None - if (not self.controller.psbt_parser - and self.controller.psbt_seed is None - and self.controller.psbt_sign_with_satochip): - # Card multisig: the parser was dropped to re-read the psbt with a newly - # loaded descriptor (see MultisigWalletDescriptorView). There is no seed to - # hand the constructor, so it is parsed seedless, as it was the first time. - try: - self.controller.psbt_parser = seedless_multisig_parser(self.controller, self.settings) - except InvalidPSBTError as e: - logger.info("Refusing psbt: %s (%s)", e, e.code) - self.set_redirect(refusal_destination(e)) - return - if not self.controller.psbt_parser or self.controller.psbt_parser.seed != self.controller.psbt_seed: # The PSBTParser takes a while to read the PSBT. Run the loading screen while # we wait. @@ -844,6 +845,19 @@ def __init__(self): self.loading_screen = LoadingScreenThread(text=_("Parsing PSBT...")) self.loading_screen.start() + card_keys = getattr(self.controller, "psbt_card_keys", None) + if self.controller.psbt_sign_with_satochip and card_keys is None: + # Signing with a card but nothing to derive with: a parser built + # here would show an empty transaction and fail later. Refuse + # while the reason is still knowable. + self.loading_screen.stop() + self.loading_screen = None + self.set_redirect(refusal_destination(InvalidPSBTError( + "Card key data is no longer available for this transaction.", + code=RejectCode.SEED_CANNOT_SIGN, + ))) + return + try: from seedsigner.controller import Controller as _Controller self.controller.psbt_parser = PSBTParser( @@ -853,7 +867,15 @@ def __init__(self): reference_time=getattr(self.controller, "psbt_source_time", None), block_anchor=(_Controller.RELEASE_BLOCK_HEIGHT, _Controller.RELEASE_BLOCK_TIME), multisig_descriptor=self.controller.multisig_wallet_descriptor, + **(card_keys or {}), ) + if not self.controller.psbt_parser.parsed: + # A parser built without key material -- the card's multisig + # flow, reviewed against a descriptor -- does not parse on + # construction. Unparsed it reports no inputs, no outputs and + # no fee, which the review screens show as a transaction that + # moves nothing. + self.controller.psbt_parser.parse() except InvalidPSBTError as e: # A deliberate refusal, not a crash: the psbt is parseable but unsafe to # present, or not this seed's to sign. Redirect to the View that renders @@ -861,6 +883,17 @@ def __init__(self): logger.info("Refusing psbt: %s (%s)", e, e.code) self.set_redirect(refusal_destination(e)) return + except RuntimeError as e: + # parse() refuses a single-key psbt with no key to parse it with. + # Only the card's multisig flow gets here without key material, so + # this is a state that should not arise -- but it is a refusal + # either way, not a crash screen. + logger.info("Cannot parse psbt without a key: %s", e) + self.set_redirect(refusal_destination(InvalidPSBTError( + "No key is available to review this transaction.", + code=RejectCode.SEED_CANNOT_SIGN, + ))) + return finally: self.loading_screen.stop() diff --git a/tests/test_flows_psbt.py b/tests/test_flows_psbt.py index 1393d3fe5..ae1ec4f6e 100644 --- a/tests/test_flows_psbt.py +++ b/tests/test_flows_psbt.py @@ -424,6 +424,9 @@ def setup_method(self): self.controller.psbt = load_psbt("TX-21.ms_honest_change_no_xpubs") self.controller.psbt_seed = None self.controller.psbt_sign_with_satochip = True + # What PSBTSelectSeedView records for a card multisig: no key material, + # on purpose, so a rebuild parses against the descriptor alone. + self.controller.psbt_card_keys = {} self.settings.set_value(SettingsConstants.SETTING__NETWORK, SettingsConstants.MAINNET) def test_change_is_unidentified_without_a_descriptor(self): diff --git a/tests/test_psbt_overview_card_flow.py b/tests/test_psbt_overview_card_flow.py new file mode 100644 index 000000000..e20ac862c --- /dev/null +++ b/tests/test_psbt_overview_card_flow.py @@ -0,0 +1,124 @@ +# pylint: disable=missing-function-docstring +# Must import base before any seedsigner modules +from base import BaseTest + +from embit import bip32, script +from embit.psbt import PSBT, DerivationPath +from embit.transaction import Transaction, TransactionInput, TransactionOutput + +from seedsigner.controller import Controller +from seedsigner.models.seed import Seed +from seedsigner.models.settings_definition import SettingsConstants +from seedsigner.views import psbt_views + + +MNEMONIC = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about".split() +PATH = "m/84'/0'/0'/0/0" + + +def card_psbt(): + """A PSBT the card's key can sign, as the card flow would have built it.""" + seed = Seed(mnemonic=MNEMONIC) + root = seed.get_root(SettingsConstants.MAINNET) + child = root.derive(PATH) + spk = script.p2wpkh(child.key.get_public_key()) + prev = Transaction(vin=[TransactionInput(b"\x11" * 32, 0)], vout=[TransactionOutput(100000, spk)]) + tx = Transaction(vin=[TransactionInput(prev.txid(), 0)], vout=[TransactionOutput(90000, spk)]) + psbt = PSBT(tx) + psbt.inputs[0].witness_utxo = prev.vout[0] + psbt.inputs[0].bip32_derivations[child.key.get_public_key()] = DerivationPath( + root.my_fingerprint, bip32.parse_path(PATH) + ) + return psbt, root + + +class TestOverviewRebuildInTheCardFlow(BaseTest): + """Rebuilding the parser must not throw away the card's key material.""" + + def test_rebuild_uses_the_cards_root(self): + controller = Controller.get_instance() + psbt, root = card_psbt() + controller.psbt = psbt + controller.psbt_seed = None + controller.psbt_parser = None + controller.psbt_sign_with_satochip = True + controller.psbt_card_keys = dict( + root=root.derive("m/84'/0'/0'"), + root_path=bip32.parse_path("m/84'/0'/0'"), + master_fingerprint=root.my_fingerprint, + ) + + view = psbt_views.PSBTOverviewView() + + assert not view.has_redirect + parser = controller.psbt_parser + assert parser is not None + assert parser.root is not None + # The card can sign this input, so the parser must see it + assert parser.num_inputs == 1 + + def test_card_flow_without_card_keys_refuses_instead_of_parsing_blind(self): + controller = Controller.get_instance() + psbt, _root = card_psbt() + controller.psbt = psbt + controller.psbt_seed = None + controller.psbt_parser = None + controller.psbt_sign_with_satochip = True + controller.psbt_card_keys = None + + view = psbt_views.PSBTOverviewView() + + assert view.has_redirect + + def test_a_single_key_psbt_with_no_key_refuses_instead_of_crashing(self): + """ + Only the multisig card flow records an empty key set, so a single-key + psbt should never reach a parse with nothing to parse it with. If it + does, parse() raises rather than returning, and the user is owed a + refusal rather than a crash screen. + """ + controller = Controller.get_instance() + psbt, _root = card_psbt() + controller.psbt = psbt + controller.psbt_seed = None + controller.psbt_parser = None + controller.psbt_sign_with_satochip = True + controller.psbt_card_keys = {} + + view = psbt_views.PSBTOverviewView() + + assert view.has_redirect + +MULTISIG_PSBT_B64 = "cHNidP8BAIkCAAAAAc9dCSh2RcRPfHaT5bNVBpbg0jAekRLqOK+bpN/QA0jeAAAAAAD9////AtAHAAAAAAAAIlEg24shYsV3IRCzlgmMKjAsR4Ad9tX896z7zDAi5q0TU9H3CgAAAAAAACIAIByGQg/VP2aRID62ty40E64HYZeRRsKRGLt8J/76R6stQ04FAE8BBDWHzwSLLGdzgAAAAq3q6nR20JnHR+vKrBQdWxN9C7xU8zNX942mVF7AQpl2ArrdLwVlkGxaatQJ4wwkvypNBKbwOq9hXGLNlKi7rZWAFDUxzXUwAACAAQAAgAAAAIACAACATwEENYfPBHOCZmWAAAACmH6KTXIny0vueRgQFBq4M6oMuG8f1QM0I/RzKQ03bCgCHrF0fyUtV0+FD2N34u/woqb8MAt/o+7Ed58RddhY8zYUCUjSaDAAAIABAACAAAAAgAIAAIAAAQEriBMAAAAAAAAiACBY4WsjDgJXLj3VW222jU1tkIIhT26ce/2efH73BWGGBiICAqyfkrdUO662QBrdvJcSOZMFxniD7M1awm9U0Kb5XCm5RzBEAiAPkQTY84YjFFkpD6MI2cc5rJySqws5fsTQA/8XEZFpbAIgTNVykbEH4Z7bqyzhhy6lty0K8rtCUDCaHNv+47NNIWgBAQMEAQAAAAEFR1IhApL4XO+VE1pPYn5wnRFyJQKVSc9TX2dO6KIBH6jwvgPaIQKsn5K3VDuutkAa3byXEjmTBcZ4g+zNWsJvVNCm+VwpuVKuIgYCkvhc75UTWk9ifnCdEXIlApVJz1NfZ07oogEfqPC+A9ocNTHNdTAAAIABAACAAAAAgAIAAIAAAAAAAAAAACIGAqyfkrdUO662QBrdvJcSOZMFxniD7M1awm9U0Kb5XCm5HAlI0mgwAACAAQAAgAAAAIACAACAAAAAAAAAAAAAAAEBR1IhApYXaczuYbBM/A+EH639Ir2yIB4PxL46dK/I1V1O9aHgIQLa02HCI/+EP+9gGpxHskjYWFN5hZzXY7RRvwV4UF42ylKuIgIClhdpzO5hsEz8D4Qfrf0ivbIgHg/Evjp0r8jVXU71oeAcNTHNdTAAAIABAACAAAAAgAIAAIABAAAAAAAAACICAtrTYcIj/4Q/72AanEeySNhYU3mFnNdjtFG/BXhQXjbKHAlI0mgwAACAAQAAgAAAAIACAACAAQAAAAAAAAAA" + + +class TestMultisigCardRebuildIsParsed(BaseTest): + """ + The card's multisig flow builds its parser with no key material, and a + PSBTParser built that way does not parse on construction -- it is the one + case where the caller has to finish the job. Handed to the review screens + unparsed it reports no inputs, no outputs and no fee, which reads as a + transaction that moves nothing. + """ + + def test_the_rebuilt_multisig_parser_has_read_the_transaction(self): + from embit.psbt import PSBT as EmbitPSBT + + controller = Controller.get_instance() + controller.psbt = EmbitPSBT.from_string(MULTISIG_PSBT_B64) + controller.psbt_seed = None + controller.psbt_parser = None + controller.psbt_sign_with_satochip = True + # What the multisig card branch records: parsed against a descriptor, + # not against any one cosigner's key. + controller.psbt_card_keys = {} + + view = psbt_views.PSBTOverviewView() + + assert not view.has_redirect + parser = controller.psbt_parser + assert parser.num_inputs == 1 + assert parser.input_amount > 0 + assert parser.fee_amount > 0 + assert len(parser.destination_addresses) > 0 + assert parser.parsed is True From 259ea67ee0c1f7fbda46480fe05bad95fad2b3a3 Mon Sep 17 00:00:00 2001 From: kkdao <44775666+kkdao@users.noreply.github.com> Date: Sun, 20 Sep 2026 14:25:04 +0100 Subject: [PATCH 04/10] fix: leave card mode wherever a seed is stored Choosing "sign with card" sets psbt_sign_with_satochip, and nothing cleared it. Going BACK from the card flow and selecting a seed set psbt_seed but left the flag standing, so finalizing still routed to the card -- signing with a key the user had just navigated away from, or failing outright when no card was present. Every view that picks a signer stores it in psbt_seed: the stored-seed list, a scanned or typed seed, WIF and BIP38 keys and a Satodime slot among them. Clearing the flag in each of those views is a line the next one added will miss, so it is cleared where the seed lands, in the psbt_seed setter. Clearing the seed is not choosing one: the card flow sets psbt_seed to None on its way in and keeps its own state. The screenshot generator patched psbt_seed with patch.object. Where the instance holds no value of its own, patch.object undoes itself by deleting the attribute, and a property with no deleter refuses: the generator failed at its first psbt screen. It patches the field behind the property instead. --- src/seedsigner/controller.py | 31 ++++++++- src/seedsigner/views/psbt_views.py | 2 + tests/screenshot_generator/generator.py | 6 +- tests/test_psbt_select_seed_clears_card.py | 77 ++++++++++++++++++++++ 4 files changed, 113 insertions(+), 3 deletions(-) create mode 100644 tests/test_psbt_select_seed_clears_card.py diff --git a/src/seedsigner/controller.py b/src/seedsigner/controller.py index 559c32ea2..ad1c93c37 100644 --- a/src/seedsigner/controller.py +++ b/src/seedsigner/controller.py @@ -238,7 +238,10 @@ def _load_block_anchor(cls): # TODO: Refactor these flow-related attrs that survive across multiple Screens. # TODO: Should all in-memory flow-related attrs get wiped on MainMenuView? psbt: PSBT = None - psbt_seed: Seed = None + # Behind the psbt_seed property. Tests patch this field, not the + # property: patch.object undoes a property patch by deleting it, and + # a property with no deleter refuses. + _psbt_seed: Seed = None psbt_parser: PSBTParser = None psbt_sign_with_satochip: bool = False psbt_from_microsd: bool = False @@ -299,6 +302,32 @@ def _load_block_anchor(cls): psbt_card_keys: dict | None = None + @property + def psbt_seed(self) -> Seed: + return self._psbt_seed + + + @psbt_seed.setter + def psbt_seed(self, seed: Seed): + """ + Storing a seed to sign with ends any card flow that was in progress. + + Every view that picks a signer stores it here: the stored-seed list, a + scanned or typed seed, WIF and BIP38 keys and a Satodime slot among + them. Clearing the card flag in each of those views is a line the next + one added will miss -- and missing it signs with the card the user + navigated away from, or with a card that is no longer in the reader. + The flag has no meaning once a seed is chosen, so it is cleared where + the seed lands. + + Clearing the seed is not choosing one: the card flow itself sets + psbt_seed = None on its way in, and must keep its own state. + """ + self._psbt_seed = seed + if seed is not None: + self.psbt_sign_with_satochip = False + self.psbt_card_keys = None + # Destination placeholder for when we need to jump out to a side flow but intend to # return navigation to the main flow (e.g. PSBT flow, load multisig descriptor, # then resume PSBT flow). diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index bfe61ac25..598ba4045 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -216,6 +216,8 @@ def ensure_microsd_seed_warning() -> bool: # User selected one of the n seeds if not ensure_microsd_seed_warning(): return Destination(PSBTSelectSeedView) + # Storing the seed is what ends any card flow that was entered and + # backed out of -- see Controller.psbt_seed. self.controller.psbt_seed = seeds[selected_menu_num] return Destination(PSBTOverviewView) diff --git a/tests/screenshot_generator/generator.py b/tests/screenshot_generator/generator.py index a9e64bd14..cfb0caca6 100644 --- a/tests/screenshot_generator/generator.py +++ b/tests/screenshot_generator/generator.py @@ -321,7 +321,9 @@ def mock_load_psbt(base64_psbt: str, seed: Seed = seed_12b): decoder = DecodeQR() decoder.add_data(base64_psbt) with patch.object(controller, 'psbt', decoder.get_psbt()): - with patch.object(controller, 'psbt_seed', seed): + # psbt_seed is a property, which patch.object cannot undo; + # the field behind it can be patched and restored. + with patch.object(controller, '_psbt_seed', seed): with patch.object(controller, 'psbt_parser', PSBTParser(p=controller.psbt, seed=seed, multisig_descriptor=controller.multisig_wallet_descriptor)): yield @@ -384,7 +386,7 @@ def mock_address_verification_data_loaded(): @contextmanager def mock_controller_psbt_seed_empty(): # Have to ensure this is cleared out in order to get the seed selection screen - with patch.object(controller, 'psbt_seed', None): + with patch.object(controller, '_psbt_seed', None): yield diff --git a/tests/test_psbt_select_seed_clears_card.py b/tests/test_psbt_select_seed_clears_card.py new file mode 100644 index 000000000..4dec8561b --- /dev/null +++ b/tests/test_psbt_select_seed_clears_card.py @@ -0,0 +1,77 @@ +# pylint: disable=missing-function-docstring +# Must import base before any seedsigner modules +from base import BaseTest + +from embit import script +from embit.psbt import PSBT +from embit.transaction import Transaction, TransactionInput, TransactionOutput + +from seedsigner.controller import Controller +from seedsigner.models.seed import Seed +from seedsigner.views import psbt_views +from seedsigner.views.view import Destination + + +MNEMONIC = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about".split() + + +class TestChoosingASeedLeavesTheCardFlow(BaseTest): + """Backing out of card signing and picking a seed must sign with the seed.""" + + def test_selecting_a_seed_clears_the_card_flag(self, monkeypatch): + controller = Controller.get_instance() + seed = Seed(mnemonic=MNEMONIC) + from seedsigner.models.settings_definition import SettingsConstants + root = seed.get_root(SettingsConstants.MAINNET) + spk = script.p2wpkh(root.derive("m/84'/0'/0'/0/0").key.get_public_key()) + prev = Transaction(vin=[TransactionInput(b"\x11" * 32, 0)], vout=[TransactionOutput(100000, spk)]) + controller.psbt = PSBT(Transaction(vin=[TransactionInput(prev.txid(), 0)], + vout=[TransactionOutput(90000, spk)])) + controller.storage.seeds = [seed] + # The user went into the card flow first and came back + controller.psbt_sign_with_satochip = True + + view = psbt_views.PSBTSelectSeedView() + monkeypatch.setattr(view, "run_screen", lambda *a, **kw: 0, raising=False) + monkeypatch.setattr( + psbt_views.PSBTSelectSeedView, "ensure_microsd_seed_warning", + lambda self: True, raising=False, + ) + + destination = view.run() + + assert controller.psbt_seed is seed + assert controller.psbt_sign_with_satochip is False + assert isinstance(destination, Destination) + + +class TestAnySeedLeavesTheCardFlow(BaseTest): + """ + A seed can be chosen from many places -- the stored list, a scan, manual + entry, WIF and BIP38 keys, a Satodime slot -- and every one of them used + to leave card mode standing, so the flow signed with the card the user had + navigated away from. The flag is cleared where the seed is stored, which is + the one line all of them pass through. + """ + + def test_storing_any_seed_leaves_card_mode(self): + controller = Controller.get_instance() + controller.psbt_sign_with_satochip = True + controller.psbt_card_keys = {"root": object()} + + controller.psbt_seed = Seed(mnemonic=MNEMONIC) + + assert controller.psbt_sign_with_satochip is False + assert controller.psbt_card_keys is None + + def test_clearing_the_seed_does_not_disturb_card_mode(self): + """The card flow sets psbt_seed = None on its way in.""" + controller = Controller.get_instance() + controller.psbt_seed = None + controller.psbt_sign_with_satochip = True + controller.psbt_card_keys = {"root": object()} + + controller.psbt_seed = None + + assert controller.psbt_sign_with_satochip is True + assert controller.psbt_card_keys is not None From 67ae21fab76c3e300a828d96c76ec18ee6459b06 Mon Sep 17 00:00:00 2001 From: kkdao <44775666+kkdao@users.noreply.github.com> Date: Mon, 21 Sep 2026 17:07:17 +0100 Subject: [PATCH 05/10] fix: label change only when our key can spend it The parser proves a script-hash output is ours only for an m-of-n, by finding our key among its cosigners. A wallet whose script is anything else still reached that proof: its policy records the type alone, so any two such policies matched whatever their scripts said. The parse then crashed, rebuilding a scriptPubKey from a missing witness script or parsing a non-multisig script as an m-of-n, and a WIF signer took the output as change. Finding our key's bytes in the script would not settle it, because a key can sit in a script that cannot spend with it: OP_DROP OP_CHECKSIG pushes our key only to throw it away. So a script-hash policy with no m-of-n matches nothing, and the output is a payment. WIF and BIP38 signing has no tree to derive from, but it does hold one key, and that key either is a cosigner of the script or is not. Taking every multisig of the right shape as change hid an attacker's payment behind the change screen. Only a parser with no key material at all, the card's seedless pre-parse, has nothing to test with. --- src/seedsigner/models/psbt_parser.py | 20 +++- tests/test_psbt_script_hash_change.py | 154 ++++++++++++++++++++++++++ 2 files changed, 173 insertions(+), 1 deletion(-) create mode 100644 tests/test_psbt_script_hash_change.py diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index ebc191509..125385988 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -1533,7 +1533,15 @@ def _parse_outputs(self, child_key_derivation_cache: dict): # as well. Only a known-good descriptor can identify the # output as change; until then it is a payment, and # PSBTIdentifyChangeView offers to load one. - if (self.multisig_descriptor is not None + if self.root is not None and not PSBTParser._multisig_script_contains_key(multisig_script, self.root.get_public_key()): + # WIF / BIP38 has no tree, but it does hold one key, and + # that key either is a cosigner of this script or is + # not. Nothing has to be derived to answer it, so it is + # answered: a multisig this key cannot sign for is a + # payment, however standard its shape, and no + # descriptor is offered to call it change. + is_presumed_change = False + elif (self.multisig_descriptor is not None and self._descriptor_owns_output(self.multisig_descriptor, i)): is_presumed_change = True else: @@ -2065,11 +2073,21 @@ def _policy_shape_matches(policy_a: dict, policy_b: dict) -> bool: that output's cosigners fail to resolve, and the output then stops matching the inputs' policy. Shape comes from the scriptPubKey and the supplied script, and the caller proves ownership rather than assuming it. + + A script-hash policy with no m-of-n has no shape to compare: its script was not + supplied, or is not a multisig, and _get_policy recorded only the type. Two such + policies would match however different their scripts, and the caller can only + prove ownership of an m-of-n. A key's bytes appearing in the script is no proof: + ` OP_DROP OP_CHECKSIG` pushes our key only to throw it away. + So such a policy matches nothing, and the output is an external spend. """ for field in ("type", "m", "n"): if policy_a.get(field) != policy_b.get(field): return False + if policy_a.get("type") in ("p2wsh", "p2sh-p2wsh", "p2sh") and "m" not in policy_a: + return False + return True diff --git a/tests/test_psbt_script_hash_change.py b/tests/test_psbt_script_hash_change.py new file mode 100644 index 000000000..dfc05b317 --- /dev/null +++ b/tests/test_psbt_script_hash_change.py @@ -0,0 +1,154 @@ +# pylint: disable=missing-function-docstring +# Must import base before any seedsigner modules +from base import BaseTest + +from embit import bip32, script +from embit.ec import PrivateKey +from embit.networks import NETWORKS +from embit.psbt import PSBT, DerivationPath +from embit.transaction import Transaction, TransactionInput, TransactionOutput + +from psbt_testing_util import PSBTTestData, root_for_seed + +from seedsigner.models.psbt_parser import PSBTParser +from seedsigner.models.settings_definition import SettingsConstants +from seedsigner.models.wif import WIFKey + + +NETWORK = SettingsConstants.REGTEST +ACCOUNT = "m/48h/1h/0h/2h" +STRANGER = PrivateKey(bytes([77]) * 32).get_public_key() +OTHER = PrivateKey(bytes([99]) * 32).get_public_key() +WIF_KEY = PrivateKey(bytes([55]) * 32) + +PREVIOUS_TXID = bytes(range(32)) + + +def our_key(branch_index): + """This seed's key at branch_index under ACCOUNT, and the derivation naming it.""" + root = root_for_seed(PSBTTestData.seed) + path = f"{ACCOUNT}/{branch_index}" + public_key = root.derive(path).get_public_key() + return public_key, {public_key: DerivationPath(root.my_fingerprint, bip32.parse_path(path))} + + +def single_key_script(public_key): + """ OP_CHECKSIG: a script-hash wallet whose script is not an m-of-n.""" + return script.Script(b"\x21" + public_key.sec() + b"\xac") + + +def script_hash_psbt(input_script, input_derivations, output_script, + output_derivations=None, supply_output_script=True): + """ + One p2wsh input spending input_script, then 90,000 sats to the p2wsh of + output_script and a payment out. The output's witness script is supplied unless + supply_output_script is False. + """ + tx = Transaction( + vin=[TransactionInput(PREVIOUS_TXID, 0)], + vout=[ + TransactionOutput(90_000, script.p2wsh(output_script)), + TransactionOutput(9_500, script.p2wpkh(OTHER)), + ], + ) + psbt = PSBT(tx) + + psbt.inputs[0].witness_utxo = TransactionOutput(100_000, script.p2wsh(input_script)) + psbt.inputs[0].witness_script = input_script + psbt.inputs[0].bip32_derivations = input_derivations + + if supply_output_script: + psbt.outputs[0].witness_script = output_script + if output_derivations: + psbt.outputs[0].bip32_derivations = output_derivations + + return psbt + + +class TestScriptHashChange(BaseTest): + """ + A script-hash output is change only if its script is an m-of-n with our key among + the cosigners. A wallet whose script is anything else is one this parser cannot + reason about, so its outputs are payments rather than a crash. + """ + + def test_a_script_our_key_cannot_spend_is_not_change(self): + """ + Our key appearing in the script's bytes is not the same as our key being + able to spend it. ` OP_DROP OP_CHECKSIG` drops our + key on the stack and checks theirs, so only they can spend -- however + truthfully the psbt names our key on it. + """ + input_key, input_derivations = our_key("0/0") + change_key, change_derivations = our_key("1/0") + drop_script = script.Script( + b"\x21" + change_key.sec() + b"\x75" + b"\x21" + STRANGER.sec() + b"\xac" + ) + psbt = script_hash_psbt( + single_key_script(input_key), input_derivations, + drop_script, change_derivations, + ) + + parser = PSBTParser(psbt, seed=PSBTTestData.seed, network=NETWORK) + + assert parser.change_amount == 0 + assert parser.spend_amount == 99_500 + + def test_a_missing_witness_script_is_not_change_and_does_not_raise(self): + input_key, input_derivations = our_key("0/0") + change_key, change_derivations = our_key("1/0") + psbt = script_hash_psbt( + single_key_script(input_key), input_derivations, + single_key_script(change_key), change_derivations, + supply_output_script=False, + ) + + parser = PSBTParser(psbt, seed=PSBTTestData.seed, network=NETWORK) + + assert parser.change_amount == 0 + assert parser.spend_amount == 99_500 + + +class TestWIFMultisigChange(BaseTest): + """ + WIF and BIP38 signing has no BIP32 tree to derive from, but it does hold one key, + and that key either is a cosigner of an output's script or is not. + """ + + def _wif_psbt(self, output_keys): + cosigner_root = root_for_seed(PSBTTestData.multisig_key_2) + path = f"{ACCOUNT}/0/0" + cosigner_key = cosigner_root.derive(path).get_public_key() + input_script = script.multisig(2, [WIF_KEY.get_public_key(), cosigner_key]) + input_derivations = { + cosigner_key: DerivationPath(cosigner_root.my_fingerprint, bip32.parse_path(path)), + } + return script_hash_psbt(input_script, input_derivations, script.multisig(2, output_keys)) + + def _parse(self, psbt): + wif = WIFKey(WIF_KEY.wif(NETWORKS["regtest"])) + return PSBTParser(psbt, seed=wif, network=NETWORK) + + def test_a_wif_that_cannot_spend_the_multisig_is_not_change(self): + """ + Treating "no tree" as "no way to tell" labelled any multisig output of + the right shape as change, which hides an attacker's payment behind the + change screen. + """ + parser = self._parse(self._wif_psbt([STRANGER, OTHER])) + + assert parser.change_amount == 0 + assert parser.spend_amount == 99_500 + # Nor is a descriptor offered to call it change: no descriptor can make + # this key a cosigner. + assert parser.unidentified_change_outputs == [] + + def test_a_wif_that_is_a_cosigner_waits_for_a_descriptor(self): + """ + With no tree, a matching script is the coordinator's own claim, so the + output is a payment until a known descriptor identifies it as change. + """ + parser = self._parse(self._wif_psbt([WIF_KEY.get_public_key(), STRANGER])) + + assert parser.change_amount == 0 + assert parser.unidentified_change_outputs == [0] From 4fac5641c2bb599f014a659d4fd23f4d5050b9ae Mon Sep 17 00:00:00 2001 From: kkdao <44775666+kkdao@users.noreply.github.com> Date: Sun, 20 Sep 2026 14:25:17 +0100 Subject: [PATCH 06/10] fix: bind change to this seed's own derivation Change binding measured every derivation on the output, cosigners' included, against the account prefixes gathered from the inputs. Those prefixes only ever come from keys this seed owns, so a cosigner's path could never match one: a multisig whose members keep the wallet at different account indices -- m/48h/0h/0h/2h here, m/48h/0h/1h/2h there, routine across vendors -- had its change refused as outside the wallet, and the psbt could not be signed at all. Measure the path this seed was verified to own against the inputs, and hold every other path on the output to ours on the last two levels. A cosigner's account index says nothing about whether our wallet finds our change, but the branch and index do: a multisig address is built from all the cosigners at once, so one moved to 1/9999 while we sit at 1/0 gives an address no member's change scan will ever generate. The spliced and off-branch paths the check exists for are refused as before. --- src/seedsigner/models/psbt_parser.py | 51 ++++++++- tests/test_psbt_mixed_account_paths.py | 140 +++++++++++++++++++++++++ 2 files changed, 190 insertions(+), 1 deletion(-) create mode 100644 tests/test_psbt_mixed_account_paths.py diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 125385988..001889a21 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -1190,6 +1190,55 @@ def is_reachable_derivation(derivation: list[int], input_prefixes: set | None) - return True + def _change_derivations_to_check(self, index: int, out: OutputScope) -> list[list[int]]: + """ + The derivations on a change output that the binding checks apply to. + + Only this seed's own path decides whether our change is reachable: the + prefixes it is measured against were gathered from the inputs this seed + owns, and a cosigner's path was never a candidate to match them. A + multisig whose cosigners keep the wallet at different account indices -- + m/48h/0h/0h/2h here, m/48h/0h/1h/2h there, routine across vendors -- is + perfectly ordinary, and judging our change by their prefix refused it + outright, leaving the psbt unsignable. + + What a cosigner's path still has to do is agree with ours on the last two + levels. A multisig address is built from every cosigner's key at once, so + the wallet only reproduces it by scanning all of them at the same branch + and index; a cosigner moved to 1/9999 while we sit at 1/0 yields an + address that no member's change scan will ever generate, and the funds are + gone even though our own path reads as ordinary. The account prefix above + those two levels is each cosigner's own business -- that is the part this + fixes -- but the branch and index are shared or the output is unreachable. + + So this narrows what is checked, never what is required: our own path is + still measured against the inputs, and every other path on the output is + still held to ours. Where the seed's own path could not be established -- + no BIP32 tree, or no verified claim on this output -- every derivation is + checked against the inputs, exactly as before. + """ + derivations = self._scope_derivations(out) + if not (self.can_verify_derivations and index < len(self.verified_output_derivation_paths)): + return derivations + + seed_derivations = self.verified_output_derivation_paths[index] + if not seed_derivations: + return derivations + + # The seed may hold more than one key on the output. Every path on it, + # those included, is held to the branch and index of the first. + suffix = list(seed_derivations[0].derivation[-2:]) + for derivation in derivations: + if list(derivation[-2:]) != suffix: + raise InvalidPSBTError( + f"Change path {bip32.path_to_str(list(derivation))} does not " + f"share this wallet's change index.", + code=RejectCode.UNREACHABLE_CHANGE_PATH, + ) + + return [list(d.derivation) for d in seed_derivations] + + @staticmethod def _scope_derivations(scope: InputScope | OutputScope) -> list[list[int]]: """Every claimed bip32 derivation on a scope, taproot and non-taproot alike.""" @@ -1673,7 +1722,7 @@ def _parse_outputs(self, child_key_derivation_cache: dict): # output "your change" while the funds land somewhere the wallet # can never find them. Refuse rather than relabel -- a psbt that # tried to deceive the display should not be signed at all. - derivations = self._scope_derivations(out) + derivations = self._change_derivations_to_check(i, out) unreachable = [ d for d in derivations if not PSBTParser.is_reachable_derivation( diff --git a/tests/test_psbt_mixed_account_paths.py b/tests/test_psbt_mixed_account_paths.py new file mode 100644 index 000000000..2dca8e3fb --- /dev/null +++ b/tests/test_psbt_mixed_account_paths.py @@ -0,0 +1,140 @@ +# pylint: disable=missing-function-docstring +# Must import base before any seedsigner modules +from base import BaseTest + +import pytest + +from embit import bip32, script +from embit.networks import NETWORKS +from embit.psbt import PSBT, DerivationPath +from embit.transaction import Transaction, TransactionInput, TransactionOutput + +from psbt_testing_util import PSBTTestData, root_for_seed + +from seedsigner.models.psbt_parser import InvalidPSBTError, PSBTParser +from seedsigner.models.settings_definition import SettingsConstants + + +NETWORK = SettingsConstants.REGTEST +EMBIT_NETWORK = NETWORKS["regtest"] + +OUR_ACCOUNT = "m/48h/1h/0h/2h" +# A cosigner is free to keep the same wallet under a different account index. +# Mixed-vendor multisig setups do this routinely. +THEIR_ACCOUNT = "m/48h/1h/1h/2h" + +PREVIOUS_TXID = bytes(range(32)) + + +def _multisig_scope_keys(our_branch_index, their_branch_index): + """The 2-of-2 script for one branch/index, plus the derivations that describe it.""" + our_root = root_for_seed(PSBTTestData.seed) + their_root = root_for_seed(PSBTTestData.multisig_key_2) + + our_path = f"{OUR_ACCOUNT}/{our_branch_index}" + their_path = f"{THEIR_ACCOUNT}/{their_branch_index}" + our_key = our_root.derive(our_path).get_public_key() + their_key = their_root.derive(their_path).get_public_key() + + witness_script = script.multisig(2, [our_key, their_key]) + derivations = { + our_key: DerivationPath(our_root.my_fingerprint, bip32.parse_path(our_path)), + their_key: DerivationPath(their_root.my_fingerprint, bip32.parse_path(their_path)), + } + return witness_script, derivations + + +def mixed_account_psbt(change_branch_index="1/0", cosigner_branch_index=None): + """ + A 2-of-2 psbt whose two cosigners hold the wallet at different account paths. + + Everything else about it is ordinary: one input the wallet already owns, change + back to the same 2-of-2 on the change branch, and a payment out. + """ + input_script, input_derivations = _multisig_scope_keys("0/0", "0/0") + change_script, change_derivations = _multisig_scope_keys( + change_branch_index, cosigner_branch_index or change_branch_index + ) + + payment = script.p2wpkh( + root_for_seed(PSBTTestData.multisig_key_3).derive("m/84h/1h/0h/0/0").get_public_key() + ) + + tx = Transaction( + vin=[TransactionInput(PREVIOUS_TXID, 0)], + vout=[ + TransactionOutput(90_000, script.p2wsh(change_script)), + TransactionOutput(9_500, payment), + ], + ) + psbt = PSBT(tx) + + psbt.inputs[0].witness_utxo = TransactionOutput(100_000, script.p2wsh(input_script)) + psbt.inputs[0].witness_script = input_script + psbt.inputs[0].bip32_derivations = input_derivations + + psbt.outputs[0].witness_script = change_script + psbt.outputs[0].bip32_derivations = change_derivations + + # The global xpubs are what let the parser name the cosigners, without which + # change is withheld for a different reason entirely. + for seed, account in ((PSBTTestData.seed, OUR_ACCOUNT), + (PSBTTestData.multisig_key_2, THEIR_ACCOUNT)): + root = root_for_seed(seed) + psbt.xpubs[root.derive(account).to_public()] = DerivationPath( + root.my_fingerprint, bip32.parse_path(account) + ) + + return psbt + + +class TestMixedAccountPathsMultisig(BaseTest): + """ + Change binding measures a change path against the account prefixes the inputs + demonstrate. Those prefixes are gathered from the keys this seed owns, so a + cosigner keeping the wallet at a different account index has no bearing on + whether our own change is reachable. + """ + + def test_change_survives_a_cosigner_on_another_account(self): + parser = PSBTParser(mixed_account_psbt(), seed=PSBTTestData.seed, network=NETWORK) + + assert parser.change_amount == 90_000 + assert len(parser.change_data) == 1 + + def test_our_own_spliced_change_path_is_still_refused(self): + """ + The refusal this check exists for: our key moved off the branch any wallet + scans. Relaxing the cosigner case must not relax this one. + """ + with pytest.raises(InvalidPSBTError) as excinfo: + PSBTParser(mixed_account_psbt(change_branch_index="7/0"), + seed=PSBTTestData.seed, network=NETWORK) + + assert excinfo.value.code == "UNREACHABLE_CHANGE_PATH" + + +class TestCosignerBranchAndIndexMustAgree(BaseTest): + """ + A multisig address is built from every cosigner's key, so change is only + recoverable if all of them sit at the same branch and index. The account + prefix above that may differ; the last two levels may not. + """ + + def test_a_cosigner_on_another_index_is_refused(self): + # Our own path stays at 1/0; the cosigner's is moved to 1/9999, so the + # address is one no wallet's change scan will ever reproduce. + psbt = mixed_account_psbt(cosigner_branch_index="1/9999") + + with pytest.raises(InvalidPSBTError) as excinfo: + PSBTParser(psbt, seed=PSBTTestData.seed, network=NETWORK) + + assert excinfo.value.code == "UNREACHABLE_CHANGE_PATH" + + def test_a_cosigner_on_another_branch_is_refused(self): + psbt = mixed_account_psbt(cosigner_branch_index="0/0") + + with pytest.raises(InvalidPSBTError) as excinfo: + PSBTParser(psbt, seed=PSBTTestData.seed, network=NETWORK) + + assert excinfo.value.code == "UNREACHABLE_CHANGE_PATH" From 4172d351ad4ccf841d41428a7d04bade57990bd1 Mon Sep 17 00:00:00 2001 From: kkdao <44775666+kkdao@users.noreply.github.com> Date: Sun, 20 Sep 2026 14:25:57 +0100 Subject: [PATCH 07/10] fix: reset the psbt flow state in one place Start-up, Home and the inactivity wipe each cleared their own subset of the psbt signing flow's leftovers, so anything added later reached only some of them. Two things were reaching none: the card's account xpub, and the raised value behind "Retry (higher timeout)". Pressing Home after a card flow left both standing: the xpub of a card the user had walked away from stayed in memory past Home and the wipe, and the next psbt timed out on a value another transaction had set. Put the list in one method and call it from all three. A refusal keeps the psbt so another signer can be chosen, and clears both by hand. BACK from the approval screen keeps the review, and the card key data a rebuild of that review needs, so it clears only the raised timeout. --- src/seedsigner/controller.py | 43 +++++++++++++-------- src/seedsigner/views/psbt_views.py | 9 ++++- tests/test_controller.py | 4 ++ tests/test_psbt_flow_exits.py | 60 ++++++++++++++++++++++++++++++ tests/test_psbt_retry_timeout.py | 28 ++++++++++++++ 5 files changed, 128 insertions(+), 16 deletions(-) create mode 100644 tests/test_psbt_flow_exits.py diff --git a/src/seedsigner/controller.py b/src/seedsigner/controller.py index ad1c93c37..7ccb806e2 100644 --- a/src/seedsigner/controller.py +++ b/src/seedsigner/controller.py @@ -424,13 +424,7 @@ def configure_instance(cls): controller.battery_hat.start() # Store one working psbt in memory - controller.psbt = None - controller.psbt_parser = None - controller.psbt_sign_with_satochip = False - controller.psbt_from_microsd = False - controller.psbt_microsd_save_path = None - controller.psbt_microsd_seed_warning_shown = False - controller.psbt_source_time = None + controller.reset_psbt_flow_state() controller.sign_message_with_satochip = False # Configure the Renderer @@ -616,10 +610,7 @@ def run(self): # self.multisig_wallet_descriptor = None self.unverified_address = None self.address_explorer_data = None - self.psbt = None - self.psbt_parser = None - self.psbt_seed = None - self.psbt_sign_with_satochip = False + self.reset_psbt_flow_state() self.sign_message_with_satochip = False # Clear camera entropy data so it cannot be used to @@ -814,6 +805,31 @@ def activate_toast(self, toast_manager_thread: BaseToastOverlayManagerThread): self.toast_notification_thread.start() + def reset_psbt_flow_state(self): + """ + Drop everything the psbt signing flow accumulated. + + Home, the inactivity wipe and start-up each used to clear their own + subset of this list, so state added later reached only some of them: + the card's account xpub and the raised retry timeout both outlived + Home and the wipe. The xpub of a card the user had walked away from + stayed in memory, and the next psbt began with another transaction's + timeout. One list, called from all three. + """ + self.psbt = None + self.psbt_parser = None + self.psbt_seed = None + self.psbt_sign_with_satochip = False + self.psbt_card_keys = None + self.psbt_from_microsd = False + self.psbt_microsd_save_path = None + self.psbt_microsd_seed_warning_shown = False + self.psbt_source_time = None + # Set by the "Retry (higher timeout)" path in psbt_views. + if hasattr(self, "_psbt_sign_retry_timeout"): + del self._psbt_sign_retry_timeout + + def handle_wipe_timeout(self): from seedsigner.gui.toast import InfoToast from seedsigner.views import MainMenuView @@ -845,10 +861,7 @@ def handle_wipe_timeout(self): except Exception: logger.debug("Error clearing release-signing keys on auto-wipe", exc_info=True) - self.psbt = None - self.psbt_parser = None - self.psbt_seed = None - self.psbt_sign_with_satochip = False + self.reset_psbt_flow_state() self.sign_message_with_satochip = False self.multisig_wallet_descriptor = None self.unverified_address = None diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index 598ba4045..8cc6db728 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -762,8 +762,12 @@ def run(self): self.controller.psbt = None self.controller.psbt_parser = None self.controller.psbt_seed = None - # Whichever signer was selected, it isn't signing this psbt. + # Whichever signer was selected, it isn't signing this psbt: the card's + # account xpub and any raised retry timeout belong to an attempt that is + # over, and the next psbt must not inherit either. self.controller.psbt_sign_with_satochip = False + self.controller.psbt_card_keys = None + clear_retry_timeout(self.controller) # Named rather than referenced directly so the table can sit above the Views it # points at. test_every_reject_code_has_a_reachable_destination resolves them all. @@ -1630,6 +1634,9 @@ def run(self): ) if selected_menu_num == RET_CODE__BACK_BUTTON: + # This signing attempt is abandoned, so a timeout it raised is not + # owed to whatever is reviewed next. + clear_retry_timeout(self.controller) return Destination(BackStackView) sig_cnt = PSBTParser.sig_count(psbt) diff --git a/tests/test_controller.py b/tests/test_controller.py index c9a578f3b..59b950261 100644 --- a/tests/test_controller.py +++ b/tests/test_controller.py @@ -277,6 +277,9 @@ def wipe(self): "roll_data": "1234512345", "entropy_bytes": b"\x00\x01\x02\x03", } + # The card flow keeps the account xpub it built the parser from; that is + # wallet data and has no business outliving the wipe either. + controller.psbt_card_keys = {"root": object(), "root_path": [0], "master_fingerprint": b"\x00" * 4} toasts = [] import seedsigner.gui.toast as gui_toast monkeypatch.setattr(controller, "activate_toast", lambda toast: toasts.append(toast)) @@ -288,5 +291,6 @@ def wipe(self): assert controller.storage.seeds == [] assert controller.password_generator_entropy_cache is None assert controller.psbt_seed is None + assert controller.psbt_card_keys is None assert controller.auto_wiped is True assert len(toasts) == 1 diff --git a/tests/test_psbt_flow_exits.py b/tests/test_psbt_flow_exits.py new file mode 100644 index 000000000..939581eaa --- /dev/null +++ b/tests/test_psbt_flow_exits.py @@ -0,0 +1,60 @@ +# pylint: disable=missing-function-docstring +# Must import base before any seedsigner modules +from base import BaseTest + +from seedsigner.controller import Controller +from seedsigner.gui.screens.screen import RET_CODE__BACK_BUTTON +from seedsigner.views import psbt_views + + +class TestLeavingThePSBTFlow(BaseTest): + """ + Every way out of the signing flow has to drop what that psbt accumulated. + The card's account xpub and the raised retry timeout are the two that were + left behind: the next psbt then began with another transaction's timeout, + or holding an xpub for a card the user had walked away from. + """ + + def test_a_refusal_drops_the_card_state_and_the_retry_timeout(self, monkeypatch): + controller = Controller.get_instance() + controller.psbt_sign_with_satochip = True + controller.psbt_card_keys = {"root": object()} + psbt_views.bump_retry_timeout(controller, 5.0) + + view = psbt_views.PSBTRefusalView(code="UNREACHABLE_CHANGE_PATH", message="nope") + monkeypatch.setattr(view, "run_screen", lambda *a, **kw: 0) + + view.run() + + assert controller.psbt_sign_with_satochip is False + assert controller.psbt_card_keys is None + assert psbt_views.signing_timeout(controller, 2.0) == 2.0 + + def test_backing_out_of_finalize_drops_the_retry_timeout(self, monkeypatch): + """ + BACK from the approval screen abandons this signing attempt, so the + timeout it raised does not belong to whatever is reviewed next. The + card's key data stays: BACK returns to the review, and rebuilding the + review's parser needs it. + """ + from test_psbt_mixed_account_paths import NETWORK, mixed_account_psbt + from psbt_testing_util import PSBTTestData + from seedsigner.models.psbt_parser import PSBTParser + + controller = Controller.get_instance() + controller.psbt = mixed_account_psbt() + controller.psbt_parser = PSBTParser( + controller.psbt, seed=PSBTTestData.seed, network=NETWORK + ) + card_keys = {"root": object()} + controller.psbt_card_keys = card_keys + psbt_views.bump_retry_timeout(controller, 5.0) + + view = psbt_views.PSBTFinalizeView() + monkeypatch.setattr(view, "run_screen", lambda *a, **kw: RET_CODE__BACK_BUTTON) + + destination = view.run() + + assert destination.View_cls.__name__ == "BackStackView" + assert psbt_views.signing_timeout(controller, 2.0) == 2.0 + assert controller.psbt_card_keys is card_keys diff --git a/tests/test_psbt_retry_timeout.py b/tests/test_psbt_retry_timeout.py index a4b3e536e..b20d3ea29 100644 --- a/tests/test_psbt_retry_timeout.py +++ b/tests/test_psbt_retry_timeout.py @@ -97,3 +97,31 @@ def run_screen(screen_cls, **kwargs): setting = self.settings.get_value(SettingsConstants.SETTING__SATOCHIP_SIGN_TIMEOUT) assert timeouts == [setting, setting + RETRY_TIMEOUT_STEP, setting + 2 * RETRY_TIMEOUT_STEP] assert f"timed out at {timeouts[-1]}s" in quoted[-1] + + +class TestPSBTFlowStateIsResetTogether(BaseTest): + """ + The card's key data and the raised retry timeout are psbt-flow state, so + they belong with the rest of it. Leaving them behind meant the next psbt + started from another transaction's timeout, or with a card whose xpub the + user had walked away from -- and Home, the wipe and start-up each cleared + their own subset of the same list. + """ + + def test_resetting_the_flow_clears_the_card_keys_and_retry_timeout(self): + from seedsigner.controller import Controller + from seedsigner.views.psbt_views import bump_retry_timeout, signing_timeout + + controller = Controller.get_instance() + controller.psbt_sign_with_satochip = True + controller.psbt_card_keys = {"root": object()} + bump_retry_timeout(controller, 5.0) + + controller.reset_psbt_flow_state() + + assert controller.psbt is None + assert controller.psbt_parser is None + assert controller.psbt_seed is None + assert controller.psbt_sign_with_satochip is False + assert controller.psbt_card_keys is None + assert signing_timeout(controller, 2.0) == 2.0 From bcecb7a6b10a26202d80e8af37a7a3f11d1ef27d Mon Sep 17 00:00:00 2001 From: kkdao <44775666+kkdao@users.noreply.github.com> Date: Fri, 16 Oct 2026 08:55:26 +0200 Subject: [PATCH 08/10] fix: let a wrong multisig descriptor be replaced With no BIP32 tree to derive from (the card's multisig flow, WIF or BIP38 signing), only the descriptor the user loaded can identify a multisig output as change. Loading the wrong one is the ordinary way to reach the screen that says it identifies nothing, and that screen offered only "Continue": the right descriptor could not be loaded without abandoning the transaction. Offer to load one there too. Swapping in a descriptor that does not own the output empties the change list while change details is still being asked for change 0. Report that as the mismatch it is, rather than crash on the missing entry. --- src/seedsigner/views/psbt_views.py | 26 ++++- tests/test_psbt_refusal_screens.py | 45 +++++--- tests/test_rootless_multisig_change.py | 145 +++++++++++++++++++++++++ 3 files changed, 200 insertions(+), 16 deletions(-) create mode 100644 tests/test_rootless_multisig_change.py diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index 8cc6db728..d01a51cec 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -1012,7 +1012,10 @@ def run(self): if self.controller.multisig_wallet_descriptor: # TRANSLATOR_NOTE: A loaded multisig descriptor did not match an output that looked like change text = _("The loaded descriptor doesn't identify it. Shown as a payment.") - button_data = [self.CONTINUE] + # Loading the wrong descriptor is the ordinary way to arrive here, and + # offering only "Continue" left the right one unreachable: the user + # had to abandon the transaction to try again. + button_data = [self.LOAD_DESCRIPTOR, self.CONTINUE] else: # TRANSLATOR_NOTE: Multisig change can't be told apart from a payment without the wallet descriptor text = _("Load descriptor to identify change.") @@ -1308,6 +1311,27 @@ def run(self): } """ + if change_data is None: + # This output is no longer counted as change: the descriptor that + # identified it has been replaced by one that does not, which a + # rootless multisig parse depends on entirely. Reading on would crash + # on the missing dict. + if self.controller.multisig_wallet_descriptor: + self.controller.multisig_wallet_descriptor = None + self.run_screen( + WarningScreen, + title=_("Descriptor mismatch"), + status_icon_name=SeedSignerIconConstants.WARNING, + status_headline=_("Descriptor cleared"), + text=_( + "Loaded multisig wallet descriptor does not match this PSBT. " + "Load the correct descriptor or skip verification to continue." + ), + show_back_button=False, + button_data=[ButtonOption(_("OK"))], + ) + return Destination(PSBTOverviewView) + # The parser proved this derivation path belongs to this seed before recording # the output as change, so the view reads the verified path rather than the # coordinator's claimed fingerprint/derivation strings. diff --git a/tests/test_psbt_refusal_screens.py b/tests/test_psbt_refusal_screens.py index d276c6c10..97f37b890 100644 --- a/tests/test_psbt_refusal_screens.py +++ b/tests/test_psbt_refusal_screens.py @@ -301,21 +301,36 @@ def test_shipped_json_is_plausible(self): assert data["timestamp"] > 1_700_000_000 -class TestIdentifyChangeScreenFits: - """PSBTIdentifyChangeView's text shares the warning box with a headline and two buttons.""" - - @pytest.mark.parametrize("text,buttons", [ - ("Load descriptor to identify change.", ["Load descriptor", "Continue as payment"]), - ("The loaded descriptor doesn't identify it. Shown as a payment.", ["Continue"]), - ]) - def test_text_fits(self, text, buttons): - screen = WarningScreen( - status_headline="Change Not Identified", - text=text, - button_data=[ButtonOption(b) for b in buttons], - show_back_button=True, - ) +class TestIdentifyChangeScreenFits(base.BaseTest): + """ + PSBTIdentifyChangeView's text shares the warning box with a headline and its + buttons. Measured on the screen the view asks for, not on a copy of its + arguments: a copy kept measuring one button after the view offered two. + """ + + @pytest.mark.parametrize("descriptor_loaded", [False, True]) + def test_text_fits(self, descriptor_loaded): + from seedsigner.gui.screens.screen import RET_CODE__BACK_BUTTON + from seedsigner.views.psbt_views import PSBTIdentifyChangeView + + self.controller.psbt_parser = object() + self.controller.multisig_wallet_descriptor = object() if descriptor_loaded else None + + view = PSBTIdentifyChangeView() + requested = [] + + def run_screen(screen_cls, **kwargs): + requested.append((screen_cls, kwargs)) + return RET_CODE__BACK_BUTTON + + view.run_screen = run_screen + view.run() + + [(screen_cls, kwargs)] = requested + screen = screen_cls(**kwargs) text_area = [c for c in screen.components if c.__class__.__name__ == "TextArea"][-1] lines = len(text_area.text_lines) height = text_area.text_height_above_baseline * lines + text_area.line_spacing * (lines - 1) - assert height <= text_area.height, f"{lines} lines, {height}px in a {text_area.height}px box" + assert height <= text_area.height, ( + f"{lines} lines, {height}px in a {text_area.height}px box: {kwargs['text']!r}" + ) diff --git a/tests/test_rootless_multisig_change.py b/tests/test_rootless_multisig_change.py new file mode 100644 index 000000000..90afbd806 --- /dev/null +++ b/tests/test_rootless_multisig_change.py @@ -0,0 +1,145 @@ +# pylint: disable=missing-function-docstring +# Must import base before any seedsigner modules +from base import BaseTest, FlowStep, FlowTest + +from test_psbt_mixed_account_paths import NETWORK, mixed_account_psbt +from psbt_testing_util import PSBTTestData + +from seedsigner.models.psbt_parser import PSBTParser + + +class TestRootlessMultisigNeedsADescriptor(BaseTest): + """ + The card's multisig flow parses before any key is available, so nothing it + can check says an m-of-n output is ours: the script's shape matches the + inputs', and at most the psbt's own global xpub map -- which the psbt's + author wrote -- names its cosigners. Accepting that labels an attacker's + output as change, and in a 1-of-2 that output is one the attacker alone can + spend. Only a descriptor the user loaded can identify change here. + """ + + def test_global_xpubs_alone_do_not_make_an_output_change(self): + parser = PSBTParser(mixed_account_psbt(), network=NETWORK) + parser.parse() + + assert parser.change_amount == 0 + assert parser.change_data == [] + # Which is what puts the "Load descriptor" prompt in front of the user. + assert parser.unidentified_change_outputs == [0] + + def test_without_global_xpubs_an_output_is_not_change_either(self): + psbt = mixed_account_psbt() + psbt.xpubs.clear() + + parser = PSBTParser(psbt, network=NETWORK) + parser.parse() + + assert parser.change_amount == 0 + assert parser.unidentified_change_outputs == [0] + + def test_a_seed_still_identifies_its_own_change(self): + """The seeded path is untouched: it proves ownership by deriving.""" + parser = PSBTParser(mixed_account_psbt(), seed=PSBTTestData.seed, network=NETWORK) + + assert parser.change_amount == 90_000 + assert parser.unidentified_change_outputs == [] + + +class TestChangeDetailsWithoutChangeData(BaseTest): + """ + Swapping the loaded descriptor for one that does not own the output leaves + the change list empty while the view is still being asked for change 0. That + is a mismatch, not a crash. + """ + + def test_a_missing_change_entry_is_a_mismatch_not_a_crash(self, monkeypatch): + from seedsigner.controller import Controller + from seedsigner.views import psbt_views + + controller = Controller.get_instance() + controller.psbt = mixed_account_psbt() + controller.psbt_parser = PSBTParser(controller.psbt, network=NETWORK) + controller.psbt_parser.parse() + controller.multisig_wallet_descriptor = object() + + view = psbt_views.PSBTChangeDetailsView(change_address_num=0) + screens = [] + monkeypatch.setattr(view, "run_screen", lambda *a, **kw: screens.append(a) or 0) + + destination = view.run() + + assert controller.multisig_wallet_descriptor is None + assert destination.View_cls is psbt_views.PSBTOverviewView + assert len(screens) == 1 + + +class TestWrongDescriptorCanBeReplaced(BaseTest): + """ + Loading the wrong descriptor is the ordinary way to arrive at "change not + identified". Offering only "Continue" there left the right descriptor + unreachable: the only way back to it was to abandon the transaction. + """ + + def test_a_loaded_descriptor_that_identifies_nothing_still_offers_to_load_one(self, monkeypatch): + from seedsigner.controller import Controller + from seedsigner.views import psbt_views + + controller = Controller.get_instance() + controller.psbt = mixed_account_psbt() + controller.psbt_parser = PSBTParser(controller.psbt, network=NETWORK) + controller.psbt_parser.parse() + controller.multisig_wallet_descriptor = object() + + view = psbt_views.PSBTIdentifyChangeView() + captured = {} + + def fake_screen(*args, **kwargs): + captured.update(kwargs) + return 0 + + monkeypatch.setattr(view, "run_screen", fake_screen) + + destination = view.run() + + assert captured["button_data"][0] is psbt_views.PSBTIdentifyChangeView.LOAD_DESCRIPTOR + assert destination.View_cls.__name__ == "LoadMultisigWalletDescriptorView" + + +# The 2-of-2 wallet that MULTISIG_PSBT_B64 spends from, and whose change it pays. +MULTISIG_DESCRIPTOR = ( + "wsh(sortedmulti(2,[3531cd75/48h/1h/0h/2h]tpubDEvs8aQCFkexBPVGJoqctrxgK9zeFwejWUWsAn7fKeSbbSUQ8sW6BJHrkKpNGRXwAfk7UWZDKz6amomvE2bo7DzokRtH8gnfweyQZf2ufFz/{0,1}/*," + "[0948d268/48h/1h/0h/2h]tpubDEkn1ih27ZcgHeu4tLzDw5EceCBa8hYMhRoCP7QmfijsrxDgchvMEC8ukFncE9Y7qBCBozBzYjEz4ophQ2quGRZsbN2bTziJxpLeK7mHq4L/{0,1}/*))" +) + + +class TestCardMultisigReviewsWithTheLoadedDescriptor(FlowTest): + """ + A descriptor loaded earlier in the session survives Home, so the card's + multisig flow often starts with one in place. The review has to use it: a + parser built without it identifies no change, and the user was then told + that their own descriptor did not identify it. + """ + + def test_a_descriptor_loaded_before_the_card_identifies_change(self, monkeypatch): + from embit.descriptor import Descriptor + from embit.psbt import PSBT + + from seedsigner.helpers import seedkeeper_utils + from seedsigner.views import psbt_views + from test_psbt_overview_card_flow import MULTISIG_PSBT_B64 + + monkeypatch.setattr(seedkeeper_utils, "init_satochip", lambda *args, **kwargs: object()) + self.controller.storage.seeds = [] + self.controller.psbt = PSBT.from_string(MULTISIG_PSBT_B64) + self.controller.multisig_wallet_descriptor = Descriptor.from_string(MULTISIG_DESCRIPTOR) + + self.run_sequence([ + FlowStep(psbt_views.PSBTSelectSeedView, button_data_selection=psbt_views.PSBTSelectSeedView.SATOCHIP), + FlowStep(psbt_views.PSBTOverviewView, screen_return_value=0), + FlowStep(psbt_views.PSBTMathView), + ]) + + parser = self.controller.psbt_parser + assert self.controller.psbt_sign_with_satochip is True + assert parser.unidentified_change_outputs == [] + assert parser.change_amount == 2_807 From 92d5a280d2622126a08b3e614c03f0919ce9a386 Mon Sep 17 00:00:00 2001 From: kkdao <44775666+kkdao@users.noreply.github.com> Date: Mon, 21 Sep 2026 18:35:06 +0100 Subject: [PATCH 09/10] fix: show the change path the descriptor matched With no BIP32 tree to derive from, the change screen took its path from the first derivation the psbt lists on the output. The descriptor that admits the output skips every entry whose fingerprint names none of its keys, so an entry listed first for a key it never checked chose the title, path and index the user saw: "Your Change" at 1/0, while the funds went to receive index 50000. Show the path the descriptor matched, and hold the output to what a seeded parse asks once it finds our key there: no more entries than the script has keys, and every entry on that path's branch and index. --- src/seedsigner/models/psbt_parser.py | 111 ++++++++++++++++--------- tests/test_rootless_multisig_change.py | 106 ++++++++++++++++++++++- 2 files changed, 173 insertions(+), 44 deletions(-) diff --git a/src/seedsigner/models/psbt_parser.py b/src/seedsigner/models/psbt_parser.py index 001889a21..aa757a183 100644 --- a/src/seedsigner/models/psbt_parser.py +++ b/src/seedsigner/models/psbt_parser.py @@ -367,6 +367,12 @@ def __init__( self.verified_input_derivation_paths: List[List[DerivationPath]] = [] self.verified_output_derivation_paths: List[List[DerivationPath]] = [] + # With no BIP32 tree, the derivation the loaded descriptor matched on each + # output it identified as change, keyed by output index. It stands in for + # the seed's verified path: the change screen reads it, and every other + # entry on the output is held to it. See _parse_outputs. + self.descriptor_output_derivation_paths: dict[int, List[int]] = {} + # Whether a successful parse has run. Constructing without key material # leaves every total at zero, which reads exactly like a transaction that # moves nothing -- see PSBTOverviewView, which has to finish the job. @@ -1213,21 +1219,28 @@ def _change_derivations_to_check(self, index: int, out: OutputScope) -> list[lis So this narrows what is checked, never what is required: our own path is still measured against the inputs, and every other path on the output is - still held to ours. Where the seed's own path could not be established -- - no BIP32 tree, or no verified claim on this output -- every derivation is - checked against the inputs, exactly as before. + still held to ours. With no BIP32 tree, ours is the path the loaded + descriptor matched. Where neither could be established, every derivation + is checked against the inputs, exactly as before. """ derivations = self._scope_derivations(out) - if not (self.can_verify_derivations and index < len(self.verified_output_derivation_paths)): - return derivations - - seed_derivations = self.verified_output_derivation_paths[index] - if not seed_derivations: + if self.can_verify_derivations: + # Every path the seed owns on the output, one per key it holds there. + seed_paths = ( + self.verified_output_derivation_paths[index] + if index < len(self.verified_output_derivation_paths) + else [] + ) + own_derivations = [list(d.derivation) for d in seed_paths] + else: + matched = self.descriptor_output_derivation_paths.get(index) + own_derivations = [matched] if matched else [] + if not own_derivations: return derivations # The seed may hold more than one key on the output. Every path on it, # those included, is held to the branch and index of the first. - suffix = list(seed_derivations[0].derivation[-2:]) + suffix = list(own_derivations[0][-2:]) for derivation in derivations: if list(derivation[-2:]) != suffix: raise InvalidPSBTError( @@ -1236,7 +1249,7 @@ def _change_derivations_to_check(self, index: int, out: OutputScope) -> list[lis code=RejectCode.UNREACHABLE_CHANGE_PATH, ) - return [list(d.derivation) for d in seed_derivations] + return own_derivations @staticmethod @@ -1247,23 +1260,6 @@ def _scope_derivations(scope: InputScope | OutputScope) -> list[list[int]]: return derivations - @staticmethod - def _first_claimed_derivation_path(scope: InputScope | OutputScope) -> list[int] | None: - """ - The first coordinator-claimed derivation path on a scope, or None. - - Only used when there is no BIP32 tree to verify against (the seedless - multisig pre-parse), where the change_data has to carry some path for the - view to display and the descriptor check is what ultimately verifies the - output. - """ - for derivation_path_obj in scope.bip32_derivations.values(): - return list(derivation_path_obj.derivation) - for _leaf_hashes, derivation_path_obj in scope.taproot_bip32_derivations.values(): - return list(derivation_path_obj.derivation) - return None - - @staticmethod def _scope_keyed_derivations(scope: InputScope | OutputScope) -> list[tuple]: """ @@ -1590,11 +1586,31 @@ def _parse_outputs(self, child_key_derivation_cache: dict): # payment, however standard its shape, and no # descriptor is offered to call it change. is_presumed_change = False - elif (self.multisig_descriptor is not None - and self._descriptor_owns_output(self.multisig_descriptor, i)): - is_presumed_change = True else: - self.unidentified_change_outputs.append(i) + descriptor_paths = ( + self._descriptor_derivations(self.multisig_descriptor, i) + if self.multisig_descriptor is not None + else [] + ) + if not descriptor_paths: + self.unidentified_change_outputs.append(i) + else: + # The descriptor stands in for the seed, so the + # output answers to what a seeded parse asks once + # it finds our key: no more entries than the + # script has keys, and every entry on the branch + # and index of the path the descriptor matched + # (see _change_derivations_to_check). That path + # is also the one shown. The first entry listed + # may name none of the descriptor's keys, and so + # was never checked. + if len(out.bip32_derivations) > self.policy["n"]: + raise InvalidPSBTError( + f"Output {i} claims more keys than its script uses.", + code=RejectCode.SURPLUS_DERIVATIONS, + ) + self.descriptor_output_derivation_paths[i] = descriptor_paths[0] + is_presumed_change = True elif verified_derivation_paths == []: # No entry claimed this seed's fingerprint, but we already @@ -1784,12 +1800,11 @@ def _parse_outputs(self, child_key_derivation_cache: dict): # receive. addr = vout[i].script_pubkey.address(NETWORKS[SettingsConstants.map_network_to_embit(self.network)]) # With no BIP32 tree to verify against (the seedless multisig - # pre-parse), fall back to the coordinator's claimed path so the - # view has something to display; the descriptor check verifies it. + # flow, WIF/BIP38), the path the loaded descriptor matched. verified_path = ( self.verified_output_derivation_paths[i][0].derivation if self.can_verify_derivations - else PSBTParser._first_claimed_derivation_path(out) + else self.descriptor_output_derivation_paths.get(i) ) self.change_data.append({ "output_index": i, @@ -2902,16 +2917,30 @@ def verify_multisig_output(self, descriptor: Descriptor, change_num: int) -> boo def _descriptor_owns_output(self, descriptor: Descriptor, i: int) -> bool: """See verify_multisig_output; takes an output index rather than a change number.""" output = self.psbt.outputs[i] - script_pubkey = self.psbt.tx.vout[i].script_pubkey if not output.bip32_derivations: # Taproot descriptors carry their claims in the taproot map instead. return descriptor.owns(output) + return bool(self._descriptor_derivations(descriptor, i)) + + + def _descriptor_derivations(self, descriptor: Descriptor, i: int) -> list[list[int]]: + """ + The derivations on output i that the descriptor checked, or [] unless it owns + the output. + + Only entries naming one of the descriptor's keys are checked, and every one of + them has to hold up (see verify_multisig_output). An entry naming none of its + keys is skipped, and so is not returned: nothing vouches for its path. + """ + output = self.psbt.outputs[i] + script_pubkey = self.psbt.tx.vout[i].script_pubkey + if script_pubkey.script_type() != descriptor.scriptpubkey_type(): - return False + return [] - matched = False + matched = [] for public_key, derivation_path_obj in output.bip32_derivations.items(): res = descriptor.check_derivation(derivation_path_obj) if res is None: @@ -2919,16 +2948,16 @@ def _descriptor_owns_output(self, descriptor: Descriptor, i: int) -> bool: idx, branch_idx = res derived = descriptor.derive(idx, branch_index=branch_idx) if derived.script_pubkey().data != script_pubkey.data: - return False + return [] committed = derived.witness_script() or derived.redeem_script() if committed is not None: if committed.script_type() == "p2wpkh": # sh(wpkh): the script holds the key's hash, not the key. if script.p2wpkh(public_key).data != committed.data: - return False + return [] elif public_key.sec() not in committed.data: - return False - matched = True + return [] + matched.append(list(derivation_path_obj.derivation)) return matched diff --git a/tests/test_rootless_multisig_change.py b/tests/test_rootless_multisig_change.py index 90afbd806..12000c678 100644 --- a/tests/test_rootless_multisig_change.py +++ b/tests/test_rootless_multisig_change.py @@ -2,10 +2,17 @@ # Must import base before any seedsigner modules from base import BaseTest, FlowStep, FlowTest -from test_psbt_mixed_account_paths import NETWORK, mixed_account_psbt -from psbt_testing_util import PSBTTestData +import pytest -from seedsigner.models.psbt_parser import PSBTParser +from embit import bip32 +from embit.descriptor import Descriptor +from embit.ec import PrivateKey +from embit.psbt import DerivationPath + +from test_psbt_mixed_account_paths import NETWORK, OUR_ACCOUNT, THEIR_ACCOUNT, mixed_account_psbt +from psbt_testing_util import PSBTTestData, root_for_seed + +from seedsigner.models.psbt_parser import InvalidPSBTError, PSBTParser class TestRootlessMultisigNeedsADescriptor(BaseTest): @@ -143,3 +150,96 @@ def test_a_descriptor_loaded_before_the_card_identifies_change(self, monkeypatch assert self.controller.psbt_sign_with_satochip is True assert parser.unidentified_change_outputs == [] assert parser.change_amount == 2_807 + + + +def mixed_account_descriptor(): + """The known-good descriptor for mixed_account_psbt's 2-of-2.""" + keys = [] + for seed, account in ((PSBTTestData.seed, OUR_ACCOUNT), + (PSBTTestData.multisig_key_2, THEIR_ACCOUNT)): + root = root_for_seed(seed) + xpub = root.derive(account).to_public().to_base58() + keys.append(f"[{root.my_fingerprint.hex()}{account[1:]}]{xpub}/{{0,1}}/*") + return Descriptor.from_string(f"wsh(multi(2,{','.join(keys)}))") + + +class TestRootlessChangeShowsTheDescriptorsPath(BaseTest): + """ + With no BIP32 tree, the path on the change screen is all the user has to + judge a change output by: its branch picks "Your Change" or "Self-Transfer" + and its last level is the index shown. The descriptor skips any entry whose + fingerprint names none of its keys, so an entry listed first for a key it + never checked chose that path, and the index the user saw was not the one + the funds went to. + """ + + # Real change, but at receive index 50000: past any wallet's gap limit. + CHANGE_BRANCH_INDEX = "0/50000" + + @staticmethod + def with_decoy_first(psbt, path, replacing_the_cosigner=False): + """List an entry for a key the descriptor has never seen ahead of the real ones.""" + real = list(psbt.outputs[0].bip32_derivations.items()) + if replacing_the_cosigner: + real = real[:1] + decoy = PrivateKey(b"\x0d" * 32).get_public_key() + psbt.outputs[0].bip32_derivations = { + decoy: DerivationPath(bytes.fromhex("deadbeef"), bip32.parse_path(path)), + **dict(real), + } + return psbt + + def parse(self, psbt): + parser = PSBTParser(psbt, network=NETWORK, multisig_descriptor=mixed_account_descriptor()) + parser.parse() + return parser + + def test_the_path_shown_is_one_the_descriptor_matched(self): + # The decoy agrees on branch and index, so only its prefix is false. + psbt = self.with_decoy_first( + mixed_account_psbt(change_branch_index=self.CHANGE_BRANCH_INDEX), + f"m/84h/1h/0h/{self.CHANGE_BRANCH_INDEX}", + replacing_the_cosigner=True, + ) + + parser = self.parse(psbt) + + assert parser.change_amount == 90_000 + assert parser.change_data[0]["verified_derivation_path"] == bip32.parse_path( + f"{OUR_ACCOUNT}/{self.CHANGE_BRANCH_INDEX}" + ) + + def test_an_entry_beyond_the_scripts_keys_is_refused(self): + """The seeded parse's refusal: the script has two keys and three are listed.""" + psbt = self.with_decoy_first( + mixed_account_psbt(change_branch_index=self.CHANGE_BRANCH_INDEX), + f"{OUR_ACCOUNT}/1/0", + ) + + with pytest.raises(InvalidPSBTError) as excinfo: + self.parse(psbt) + + assert excinfo.value.code == "SURPLUS_DERIVATIONS" + + def test_an_entry_on_another_branch_and_index_is_refused(self): + """ + The seeded parse's other refusal: shown at 1/0, "Your Change" at index 0, + while the script pays receive index 50000. + """ + psbt = self.with_decoy_first( + mixed_account_psbt(change_branch_index=self.CHANGE_BRANCH_INDEX), + f"{OUR_ACCOUNT}/1/0", + replacing_the_cosigner=True, + ) + + with pytest.raises(InvalidPSBTError) as excinfo: + self.parse(psbt) + + assert excinfo.value.code == "UNREACHABLE_CHANGE_PATH" + + def test_honest_change_keeps_its_path(self): + parser = self.parse(mixed_account_psbt(change_branch_index="1/3")) + + assert parser.change_amount == 90_000 + assert parser.change_data[0]["verified_derivation_path"] == bip32.parse_path(f"{OUR_ACCOUNT}/1/3") From f13c7da84cd1c63352042ee7540a0602042860f8 Mon Sep 17 00:00:00 2001 From: kkdao <44775666+kkdao@users.noreply.github.com> Date: Mon, 21 Sep 2026 18:36:56 +0100 Subject: [PATCH 10/10] fix: build the card's parsers with the clock A psbt loaded from microSD is dated by its file, and the review uses that date to flag a locktime years in the future. The card's parsers, single-sig and multisig, are built in the signer menu and the overview keeps them, and they were built there without the clock. A lock nearly three years out that the seed flow warned about reached the approval screen unmentioned when a card signed the same psbt. Build every parser through one function that takes the network, the loaded descriptor and the clock from the controller and the settings, so the signer menu and the overview cannot pass different lists again. --- src/seedsigner/views/psbt_views.py | 42 +++++++++++++------- tests/test_psbt_card_account_path.py | 58 +++++++++++++++++++++++++++- 2 files changed, 83 insertions(+), 17 deletions(-) diff --git a/src/seedsigner/views/psbt_views.py b/src/seedsigner/views/psbt_views.py index d01a51cec..ccf67aab5 100644 --- a/src/seedsigner/views/psbt_views.py +++ b/src/seedsigner/views/psbt_views.py @@ -98,6 +98,28 @@ def hardened_prefix(derivation): return unnamed +def build_psbt_parser(controller, settings, **key_material) -> PSBTParser: + """The parser for the controller's psbt, given the key material to parse with. + + Everything else comes from the controller and the settings: the network, + the loaded multisig descriptor, and the clock the far-future locktime check + dates a psbt by. The card parsers are built in the signer menu and the + overview keeps them, and they were built there with the network alone: a + lock the seed flow warned about went unmentioned when a card signed. One + builder for every parse, so the argument lists cannot drift apart again. + """ + from seedsigner.controller import Controller + + return PSBTParser( + controller.psbt, + network=settings.get_value(SettingsConstants.SETTING__NETWORK), + reference_time=getattr(controller, "psbt_source_time", None), + block_anchor=(Controller.RELEASE_BLOCK_HEIGHT, Controller.RELEASE_BLOCK_TIME), + multisig_descriptor=controller.multisig_wallet_descriptor, + **key_material, + ) + + class PSBTSelectSeedView(View): SCAN_SEED = ButtonOption("Scan a seed", SeedSignerIconConstants.QRCODE) SATOCHIP = ButtonOption("Use Satochip card", SeedSignerIconConstants.FINGERPRINT) @@ -388,13 +410,12 @@ def ensure_microsd_seed_warning() -> bool: root_key = HDKey.from_base58(account_xpub) try: - self.controller.psbt_parser = PSBTParser( - self.controller.psbt, + self.controller.psbt_parser = build_psbt_parser( + self.controller, self.settings, seed=None, root=root_key, root_path=account_path, master_fingerprint=master_fp, - network=network, ) except InvalidPSBTError as e: # A deliberate refusal. Card signing gets the same screens as @@ -828,11 +849,7 @@ def seedless_multisig_parser(controller, settings) -> PSBTParser: the card holds the key, so there is no BIP32 tree here. Change can then only be identified by the loaded descriptor, if any. Raises InvalidPSBTError on refusal. """ - parser = PSBTParser( - controller.psbt, - network=settings.get_value(SettingsConstants.SETTING__NETWORK), - multisig_descriptor=controller.multisig_wallet_descriptor, - ) + parser = build_psbt_parser(controller, settings) parser.parse() return parser @@ -865,14 +882,9 @@ def __init__(self): return try: - from seedsigner.controller import Controller as _Controller - self.controller.psbt_parser = PSBTParser( - self.controller.psbt, + self.controller.psbt_parser = build_psbt_parser( + self.controller, self.settings, seed=self.controller.psbt_seed, - network=self.settings.get_value(SettingsConstants.SETTING__NETWORK), - reference_time=getattr(self.controller, "psbt_source_time", None), - block_anchor=(_Controller.RELEASE_BLOCK_HEIGHT, _Controller.RELEASE_BLOCK_TIME), - multisig_descriptor=self.controller.multisig_wallet_descriptor, **(card_keys or {}), ) if not self.controller.psbt_parser.parsed: diff --git a/tests/test_psbt_card_account_path.py b/tests/test_psbt_card_account_path.py index 96a55c45c..931cb09bb 100644 --- a/tests/test_psbt_card_account_path.py +++ b/tests/test_psbt_card_account_path.py @@ -126,7 +126,7 @@ def card_bip32_get_xpub(self, path, xtype, is_mainnet): return key.to_public().to_base58() -def spend_from(owners): +def spend_from(owners, locktime=0, sequence=0xFFFFFFFF): """A PSBT spending one p2wpkh coin per (root, path, fingerprint) in `owners`.""" coins = [] for i, (root, path, fingerprint) in enumerate(owners): @@ -137,8 +137,9 @@ def spend_from(owners): payee = script.p2wpkh(PrivateKey(b"\x07" * 32).get_public_key()) tx = Transaction( - vin=[TransactionInput(prev.txid(), 0) for prev, _, _ in coins], + vin=[TransactionInput(prev.txid(), 0, sequence=sequence) for prev, _, _ in coins], vout=[TransactionOutput(100_000 * len(coins) - 1_000, payee)], + locktime=locktime, ) psbt = PSBT(tx) for inp, (prev, public_key, derivation) in zip(psbt.inputs, coins): @@ -199,3 +200,56 @@ def test_a_blank_fingerprint_on_the_cards_input_still_signs(self, monkeypatch): assert warnings == [] assert destination.View_cls is psbt_views.PSBTOverviewView assert self.controller.psbt_sign_with_satochip is True + + +class TestCardParserKnowsTheClock(BaseTest): + """ + A psbt loaded from microSD is dated by its file, and the review uses that + date to flag a locktime years away. The card's parser is built in the + signer menu and the overview keeps it, so it needs the same clock the + overview would have given it: without it, a lock the seed flow warns about + went unmentioned when a card signed. + """ + + choose_the_card = TestCardFlowReadsTheCardsAccount.choose_the_card + + def test_a_far_future_locktime_is_flagged_for_the_card(self, monkeypatch): + from seedsigner.controller import Controller + from seedsigner.models.psbt_parser import RiskWarning + + card_root = Seed(mnemonic=CARD_MNEMONIC).get_root(SettingsConstants.MAINNET) + # About 2.9 years of blocks past the release anchor, in a file written then. + psbt = spend_from( + [(card_root, "m/84h/0h/0h/0/0", card_root.my_fingerprint)], + locktime=Controller.RELEASE_BLOCK_HEIGHT + 150_000, + sequence=0xFFFFFFFE, + ) + self.controller.psbt_source_time = Controller.RELEASE_BLOCK_TIME + + destination, warnings = self.choose_the_card(monkeypatch, MockCard(card_root), psbt) + assert warnings == [] + assert destination.View_cls is psbt_views.PSBTOverviewView + + psbt_views.PSBTOverviewView() + parser = self.controller.psbt_parser + + assert RiskWarning.LOCKTIME_FAR_FUTURE in parser.risk_warnings + assert psbt_views.post_overview_destination(parser).View_cls is psbt_views.PSBTRiskWarningView + + def test_a_far_future_locktime_is_flagged_for_a_card_multisig(self): + """The card's multisig parse has no key of its own, and needs the clock all the same.""" + from seedsigner.controller import Controller + from seedsigner.models.psbt_parser import RiskWarning + from seedsigner.models.settings import Settings + from test_psbt_mixed_account_paths import mixed_account_psbt + + psbt = mixed_account_psbt() + # embit rebuilds psbt.tx from these fields, so they are what to set. + psbt.locktime = Controller.RELEASE_BLOCK_HEIGHT + 150_000 + psbt.inputs[0].sequence = 0xFFFFFFFE + self.controller.psbt = psbt + self.controller.psbt_source_time = Controller.RELEASE_BLOCK_TIME + + parser = psbt_views.seedless_multisig_parser(self.controller, Settings.get_instance()) + + assert RiskWarning.LOCKTIME_FAR_FUTURE in parser.risk_warnings