Skip to content
82 changes: 66 additions & 16 deletions src/seedsigner/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -291,6 +294,40 @@ 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


@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).
Expand Down Expand Up @@ -387,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
Expand Down Expand Up @@ -579,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
Expand Down Expand Up @@ -777,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
Expand Down Expand Up @@ -808,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
Expand Down
166 changes: 134 additions & 32 deletions src/seedsigner/models/psbt_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,17 @@ 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.
self.parsed: bool = False

if self.seed is not None or self.root is not None:
self.parse()

Expand Down Expand Up @@ -547,6 +558,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


Expand Down Expand Up @@ -1184,6 +1196,62 @@ 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. 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 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(own_derivations[0][-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 own_derivations


@staticmethod
def _scope_derivations(scope: InputScope | OutputScope) -> list[list[int]]:
"""Every claimed bip32 derivation on a scope, taproot and non-taproot alike."""
Expand All @@ -1192,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]:
"""
Expand Down Expand Up @@ -1527,11 +1578,39 @@ 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
and self._descriptor_owns_output(self.multisig_descriptor, i)):
is_presumed_change = True
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
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
Expand Down Expand Up @@ -1659,7 +1738,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(
Expand Down Expand Up @@ -1721,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,
Expand Down Expand Up @@ -2059,11 +2137,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:
`<our key> OP_DROP <their key> 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


Expand Down Expand Up @@ -2829,33 +2917,47 @@ 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:
continue
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


Expand Down
Loading