Merge pull request #1073 from kdmukai/2026-10_psbt_change_path_rules
What changed, and why it matters
This commit adds security checks to SeedSigner, an offline Bitcoin signing device, to prevent malicious or buggy wallet software from tricking users into sending change to derivation paths their wallet will never scan. It now verifies that change outputs return to the same wallet (base derivation path) the transaction spends from, use only standard receive/change branches, and use non-hardened address indexes. It also blocks single-signature segwit v0 transactions that spend from multiple accounts unless each input includes the full previous transaction, because without that data a coordinator could fake an input's ownership to justify sending change to a hidden path. Change at an unusually far address index is now flagged with a warning instead of being silently accepted.
Users and downstream packagers should treat this as a security fix and update to the merged code. Reviewers should verify that the new derivation-path rules do not break legitimate multisig or self-transfer workflows in their coordinator software, and that the CHANGE_ADDRESS_INDEX_WINDOW threshold is appropriate for their wallet's gap limit and address lookahead settings.
Security signals we found
New fatal error class PSBTChangeDerivationPathError for non-standard change derivation paths
New fatal error class PSBTUnverifiableMixedInputBasePathsError for unverifiable mixed-base-path segwit v0 inputs
Change output base path must match a verified input base path
Change branch restricted to receive (0) or change (1)
Change address index must be non-hardened
Distant change address index flagged when >10,000 past smallest input index
Single-sig segwit v0 mixed base paths rejected unless all inputs provide non_witness_utxo
UI now shows dire warning for unsafe derivation path and warning for distant address
Evidence from the diff
The patch introduces two new fatal error classes in psbt_parser.py: PSBTChangeDerivationPathError and PSBTUnverifiableMixedInputBasePathsError. It adds _evaluate_change_derivation_paths() and _evaluate_input_base_paths() to the parse flow. The first rejects change outputs whose derivation path is too short, pays to a different base path than any verified input, uses a branch other than 0/1, or uses a hardened address index. It also flags outputs whose address index exceeds CHANGE_ADDRESS_INDEX_WINDOW (10,000) past the smallest input address index for the same base path. The second rejects single-sig segwit v0 PSBTs where the seed’s inputs span multiple base paths while any of them lacks non_witness_utxo. The UI layer replaces separate high-fee/no-change warning views with a unified PSBTWarningView, adds a dire warning for unexpected change paths, and shows a warning for distant change address indices.
Changed components
src/seedsigner/models/psbt_parser.pysrc/seedsigner/views/psbt_views.pysrc/seedsigner/gui/screens/psbt_screens.pytests/psbt_testing_util.pytests/test_psbt_parser.pytests/test_flows_psbt.pytests/screenshot_generator/generator.pyInspect captured patch +1863 / −139
### src/seedsigner/gui/screens/psbt_screens.py
@@ -676,6 +676,7 @@ class PSBTChangeDetailsScreen(ButtonListScreen):
is_change_derivation_path: bool = True
derivation_path_addr_index: int = 0
is_change_addr_verified: bool = False
+ is_address_index_beyond_window: bool = False
def __post_init__(self):
# Customize defaults
@@ -716,20 +717,60 @@ def __post_init__(self):
max_lines=1,
))
+ # Each status line below the address is an icon and a short message
+ status_lines = []
if self.is_change_addr_verified:
- # How much empty space is left between the bottom of the addr and the first button?
- available_y = self.buttons[0].screen_y - (self.components[-1].screen_y + self.components[-1].height)
-
- self.components.append(IconTextLine(
+ status_lines.append(dict(
icon_name=SeedSignerIconConstants.SUCCESS,
icon_color=GUIConstants.SUCCESS_COLOR,
value_text=_("Address verified!"),
+ ))
+
+ if self.is_address_index_beyond_window:
+ status_lines.append(dict(
+ icon_name=SeedSignerIconConstants.WARNING,
+ icon_color=GUIConstants.WARNING_COLOR,
+ # TRANSLATOR_NOTE: Variable is an address index such as "#20000". Calls out that this address is far beyond the addresses being spent.
+ value_text=_("Distant index {}").format(f"{index_num_symbol}{self.derivation_path_addr_index}"),
+ ))
+
+ if len(status_lines) == 1:
+ # How much empty space is left between the bottom of the addr and the first button?
+ status_line_top = self.components[-1].screen_y + self.components[-1].height
+ available_y = self.buttons[0].screen_y - status_line_top
+
+ self.components.append(IconTextLine(
+ **status_lines[0],
is_text_centered=True,
screen_x=GUIConstants.EDGE_PADDING,
- screen_y=self.components[-1].screen_y + self.components[-1].height,
+ screen_y=status_line_top,
height=available_y, # Let the component auto-center vertically
))
+ elif len(status_lines) > 1:
+ # Space the lines by what is actually drawn, so the visible gaps above,
+ # between, and below them are equal. The address's characters run past the
+ # bottom of its box, and each line's icon rises above the top of its own box.
+ address = self.components[-1]
+ address_bottom = address.screen_y
+ for ((text_x, text_y), text, font_color, font) in address.text_params:
+ address_bottom = max(address_bottom, address.screen_y + text_y + font.getbbox(text)[3])
+
+ sample_line = IconTextLine(**status_lines[0])
+ icon_offset = sample_line.icon.screen_y - sample_line.screen_y
+ icon_height = sample_line.icon.height
+ gap = int((self.buttons[0].screen_y - address_bottom - len(status_lines) * icon_height) / (len(status_lines) + 1))
+
+ icon_y = address_bottom + gap
+ for status_line in status_lines:
+ self.components.append(IconTextLine(
+ **status_line,
+ is_text_centered=True,
+ screen_x=GUIConstants.EDGE_PADDING,
+ screen_y=icon_y - icon_offset,
+ ))
+ icon_y += icon_height + gap
+
@dataclass
### src/seedsigner/models/psbt_parser.py
@@ -206,10 +206,46 @@ class PSBTUnsupportedDerivationPathError(PSBTVerificationError):
class PSBTUnsupportedScriptPathError(PSBTVerificationError):
"""
- This seed can sign an input only through a taproot script path spend, because the
- keys of ours that the input claims are keys in its script tree leaves.
+ An input only lets this seed sign through a taproot script path spend. Script path
+ spends are not yet supported.
+ """
+ pass
+
+
+class PSBTChangeDerivationPathError(PSBTVerificationError):
+ """
+ An output pays one of this seed's keys at a derivation path that the user's
+ coordinator software is unlikely to check. The coins still belong to the user's seed,
+ but their coordinator might never find them.
+
+ Derivation paths are assessed as:
+ * [base path] / change / address_index
+ * (note: embit refers to the "change" level as the "branch")
+
+ A change output is refused if its derivation path:
+ * is too short to hold both a "branch" and an "address_index",
+ * pays to a different wallet (base path) than the user's inputs being spent,
+ * specifies a "branch" other than receive or change (0 or 1),
+ * or specifies a hardened "address_index".
+
+ We treat this as an attack.
+ """
+ def __init__(self, derivation_path: List[int]):
+ super().__init__(f"Output pays this seed at {bip32.path_to_str(derivation_path)}, a path coordinator software is unlikely to check")
+ self.derivation_path = derivation_path
+
- Script path spends are not yet supported.
+class PSBTUnverifiableMixedInputBasePathsError(PSBTVerificationError):
+ """
+ The inputs of a single sig segwit v0 psbt that this seed signs are at different
+ base paths and non_witness_utxo data was not provided.
+
+ The change path rules require change to go back to the same wallet (base path) that
+ the inputs spend from. But if non_witness_utxo data is not provided, segwit v0 inputs
+ can't be verified as genuine when they come from different base paths.
+
+ Some advanced coordinators can create a legitimate psbt with mixed base paths and no
+ non_witness_utxo data, but we disallow it regardless.
"""
pass
@@ -287,6 +323,15 @@ class PSBTParser():
# change). TODO: Possibly make this configurable via settings.
HIGH_FEES_WARNING_THRESHOLD = 25
+ # The maximum difference allowed between a change output's address index and the
+ # smallest address index of the relevant inputs being spent.
+ CHANGE_ADDRESS_INDEX_WINDOW = 10_000
+
+ # The non-fatal findings that can be recorded in self.warnings
+ WARNING__HIGH_FEE = "high_fee"
+ WARNING__NO_CHANGE = "no_change"
+ WARNING__CHANGE_ADDRESS_INDEX_BEYOND_WINDOW = "change_address_index_beyond_window"
+
def __init__(self, p: PSBT, seed: Seed, network: str = SettingsConstants.MAINNET):
self.psbt: PSBT = p
@@ -309,6 +354,9 @@ def __init__(self, p: PSBT, seed: Seed, network: str = SettingsConstants.MAINNET
# re-walking the outputs.
self.is_high_fee: bool = False
+ # The psbt's non-fatal findings, as WARNING__* constants, most serious first
+ self.warnings: List[str] = []
+
# Contains one entry per input in psbt.inputs and per output in psbt.outputs. Each
# entry lists every derivation path the seed genuinely owns there, in the order
# the psbt lists them. On an input, the key at each listed path is also one the
@@ -317,11 +365,17 @@ def __init__(self, p: PSBT, seed: Seed, network: str = SettingsConstants.MAINNET
self.verified_input_derivation_paths: List[List[DerivationPath]] = []
self.verified_output_derivation_paths: List[List[DerivationPath]] = []
- # The findings held until the outputs have been read, in the order they were
- # found, and the index of each output that carries one.
- self.held_findings: List[PSBTVerificationError] = []
+ # The findings held until later in the parse, in the order they were found, and
+ # the index of each output that carries one.
+ self.held_input_findings: List[PSBTVerificationError] = []
+ self.held_output_findings: List[PSBTVerificationError] = []
self.held_output_indices: List[int] = []
+ # The verified derivation paths of multisig outputs that pay a multisig our seed
+ # is part of, but that we count as spends because their cosigners differ from the
+ # inputs' cosigners (or fail to resolve).
+ self.verified_cosigner_mismatch_output_derivation_paths: List[DerivationPath] = []
+
self.root = None
if self.seed is not None:
@@ -401,12 +455,22 @@ def parse(self):
our seed provably owns. Also rejects a psbt whose outputs spend more than its
inputs bring in.
+ 7. _evaluate_change_derivation_paths: verifies that every output coming back to
+ this seed uses what we consider a valid change derivation path. Also
+ identifies any change address indices that are far past the indices of the
+ spending wallet's inputs; they're flagged for the user to review.
+
+ 8. _evaluate_input_base_paths: verifies that a single sig segwit v0 psbt spends
+ from a single wallet, unless each of those inputs supplies a
+ non_witness_utxo. No-op for other script types.
+
Held findings:
The parse reports the most serious problem it finds. A finding we treat as an
attack stops the parse at the step that finds it, since nothing found later can
outrank it. Parsing may uncover other milder findings along the way. Those are
- held aside while the remaining checks run. A held finding is raised only if those
- remaining checks find nothing more serious.
+ held aside so that later checks can still find something more serious. Held
+ findings can only wait up to the point where they must be raised to prevent
+ subsequent checks from relying on the problematic data.
Optimization via child_key_derivation_cache:
Parsing traverses a derivation path down to an individual address one level at a
@@ -460,14 +524,36 @@ def parse(self):
if rt == False:
return False
- if self.held_findings:
+ if self.held_input_findings:
# The checks to this point did not raise any attack-level exceptions, but a
- # milder finding was held. The psbt is still rejected.
- raise self.held_findings[0]
+ # milder input finding was held and is grounds for rejecting the psbt.
+ raise self.held_input_findings[0]
+
+ self._evaluate_change_derivation_paths()
+
+ self._evaluate_input_base_paths()
+
+ if self.held_output_findings:
+ # A milder output finding that was held from earlier in the parse can now be
+ # raised, rejecting the psbt.
+ raise self.held_output_findings[0]
# Every total is known now, so settle this once rather than per view.
self.is_high_fee = self.has_high_fee()
+ # Record the non-fatal findings, most serious first
+ self.warnings = []
+ if self.is_high_fee:
+ self.warnings.append(PSBTParser.WARNING__HIGH_FEE)
+
+ if self.change_amount == 0:
+ self.warnings.append(PSBTParser.WARNING__NO_CHANGE)
+
+ for change_output in self.change_data:
+ if change_output["address_index_beyond_window"]:
+ self.warnings.append(PSBTParser.WARNING__CHANGE_ADDRESS_INDEX_BEYOND_WINDOW)
+ break
+
return True
@@ -588,7 +674,7 @@ def _parse_inputs(self, child_key_derivation_cache: dict):
path maps.
* PSBTUnsupportedDerivationPathError: An input claims one of our keys at a
derivation path too short for any wallet to use.
- * PSBTUnsupportedScriptPathError: This seed can sign an input only through a
+ * PSBTUnsupportedScriptPathError: An input only lets this seed sign through a
taproot script path spend.
"""
self.num_inputs = len(self.psbt.inputs)
@@ -600,7 +686,7 @@ def _parse_inputs(self, child_key_derivation_cache: dict):
except (PSBTInputOwnershipClaimError, PSBTMixedDerivationPathTypesError, PSBTUnsupportedDerivationPathError) as e:
# Held rather than raised, and this input is left with no verified
# derivation paths.
- self.held_findings.append(e)
+ self.held_input_findings.append(e)
verified_derivation_paths = []
script_pubkey = inp.script_pubkey
@@ -669,7 +755,7 @@ def _parse_inputs(self, child_key_derivation_cache: dict):
# None of our claims on this input passed. At least one of them is a key
# in a script tree leaf, so this seed could only sign the input through a
# script path spend. Held rather than raised.
- self.held_findings.append(PSBTUnsupportedScriptPathError("Input can only be signed through a taproot script path spend"))
+ self.held_input_findings.append(PSBTUnsupportedScriptPathError("Input can only be signed through a taproot script path spend"))
self.verified_input_derivation_paths.append(script_committed_derivation_paths)
@@ -803,7 +889,7 @@ def _hold_output_finding(self, output_index: int, finding: PSBTVerificationError
"""
Holds a finding along with the index of the output that carries it.
"""
- self.held_findings.append(finding)
+ self.held_output_findings.append(finding)
self.held_output_indices.append(output_index)
@@ -871,6 +957,7 @@ def _parse_outputs(self, child_key_derivation_cache: dict):
self.spend_amount = 0
self.change_amount = 0
self.change_data = []
+ self.verified_cosigner_mismatch_output_derivation_paths = []
self.fee_amount = 0
self.destination_addresses = []
self.destination_amounts = []
@@ -1071,6 +1158,11 @@ def _parse_outputs(self, child_key_derivation_cache: dict):
if input_cosigners is not None and input_cosigners != output_cosigners:
is_presumed_change = False
+ # The output still pays our key, so we record where
+ # that key is for the change path rules to check later
+ # in the parse.
+ self.verified_cosigner_mismatch_output_derivation_paths.append(verified_derivation_paths[0])
+
elif verified_derivation_paths != [] and self.policy["type"] != "p2tr":
# The psbt claims one of this seed's keys on this output, yet the
# output does NOT pay what that claim describes. We treat this
@@ -1108,6 +1200,7 @@ def _parse_outputs(self, child_key_derivation_cache: dict):
"address": addr,
"amount": vout[i].value,
"verified_derivation_path": self.verified_output_derivation_paths[i][0].derivation,
+ "address_index_beyond_window": False, # initial default; evaluated later
})
self.change_amount += vout[i].value
@@ -1731,7 +1824,7 @@ def _reject_if_seed_cannot_sign(self):
if len(verified_derivation_paths) > 0:
return
- if self.held_findings:
+ if self.held_input_findings or self.held_output_findings:
# The held finding is the one to report rather than "wrong seed". parse()
# raises it once the outputs have been read.
return
@@ -1740,6 +1833,274 @@ def _reject_if_seed_cannot_sign(self):
raise PSBTSeedCannotSignError()
+ @staticmethod
+ def _get_base_path(derivation_path: List[int]) -> List[int]:
+ """
+ Returns derivation_path's base path (its wallet): every level before the "branch"
+ and "address_index".
+
+ Several security checks on change outputs and inputs depend on the base path.
+ Extracting it is trivial, but each check needs a guarantee that it is extracted
+ correctly. So every check shares this one definition.
+ """
+ return derivation_path[:-2]
+
+
+ def _get_verified_input_derivation_paths_matching_base_path(self, base_path: List[int]) -> List[DerivationPath]:
+ """
+ Returns every verified input derivation path whose base path matches base_path.
+ """
+ matching_derivation_paths = []
+ for verified_derivation_paths in self.verified_input_derivation_paths:
+ for verified_derivation_path in verified_derivation_paths:
+ if PSBTParser._get_base_path(verified_derivation_path.derivation) == base_path:
+ matching_derivation_paths.append(verified_derivation_path)
+ return matching_derivation_paths
+
+
+ def _is_wallet_change_derivation_path(self, change_derivation_path: List[int]) -> bool:
+ """
+ Determines whether a change derivation path is standard enough for the user's
+ coordinator software to find the change output.
+
+ A typical single-sig derivation path consists of:
+ m / purpose' / coin_type' / account' / change / address_index
+
+ The levels before "change" are what we call the "base path". Regardless of the
+ structure of the full derivation path, we simplify our evaluation to:
+ [base path] / change / address_index
+
+ Note: embit refers to the "change" level as the "branch".
+
+ The derivation path must:
+ * be long enough to hold both a "branch" and an "address_index".
+ * match a base path that this transaction spends from.
+ * Note: a transaction can spend inputs from more than one base path. The
+ change output may match any of them.
+ * only use the non-hardened receive (0) or change (1) "branch".
+ * use a non-hardened "address_index".
+
+ Rationales:
+ * A coordinator should send change back to the same wallet that the coins are
+ being spent from. For our purposes, we define a wallet as its base path.
+ Therefore a change output going to a different base path is viewed as being sent
+ to a different wallet.
+
+ * We expect coordinator software to follow the derivation path standards that
+ define the valid "branch" and "address_index" values.
+ """
+ if len(change_derivation_path) < 2:
+ # Too short to hold both a branch and an address index
+ return False
+
+ base_path = PSBTParser._get_base_path(change_derivation_path)
+ branch = change_derivation_path[-2]
+ address_index = change_derivation_path[-1]
+
+ # The change has to come back to a base path the coins are leaving from
+ if not self._get_verified_input_derivation_paths_matching_base_path(base_path):
+ return False
+
+ # Coordinators scan only the non-hardened receive (0) and change (1) branches
+ if branch not in (0, 1):
+ return False
+
+ # A hardened address index cannot appear on the receive or change branch
+ if address_index >= bip32.HARDENED_INDEX:
+ return False
+
+ return True
+
+
+ def _is_change_address_index_within_window(self, change_derivation_path: List[int]) -> bool:
+ """
+ Determines whether a change output's address index is within
+ CHANGE_ADDRESS_INDEX_WINDOW of the smallest non-hardened address index among the
+ inputs that match the output's base path.
+
+ A malicious coordinator might attempt to add an input that would skew our
+ accounting of the address indices being spent. This would alter our range for the
+ change indices we would flag. But by constraining our rule to calculate the index
+ window from the smallest input index, we protect against deceptive large indices
+ skewing our safety check.
+
+ Expects a path that already passed the change path rules.
+ """
+ base_path = PSBTParser._get_base_path(change_derivation_path)
+ address_index = change_derivation_path[-1]
+
+ smallest_input_address_index = None
+ for derivation_path in self._get_verified_input_derivation_paths_matching_base_path(base_path):
+ input_address_index = derivation_path.derivation[-1]
+ if input_address_index < bip32.HARDENED_INDEX and (smallest_input_address_index is None or input_address_index < smallest_input_address_index):
+ smallest_input_address_index = input_address_index
+
+ if smallest_input_address_index is None:
+ # Edge case: every matching input is at a hardened address index. So
+ # measure from 0, which gives the narrowest window.
+ smallest_input_address_index = 0
+
+ return address_index <= smallest_input_address_index + PSBTParser.CHANGE_ADDRESS_INDEX_WINDOW
+
+
+ def _evaluate_change_derivation_paths(self):
+ """
+ Runs two checks on each change output's derivation path:
+ * Valid change derivation path: a path the user's coordinator software is
+ unlikely to check is refused and the parse stops.
+ * Address index window: an address index beyond the window is flagged on the
+ change output (address_index_beyond_window = True) and the parse continues. The
+ window is a guess, so the user decides: a coordinator spending an old, low-index
+ coin may legitimately have handed out change addresses far beyond that coin's
+ address index.
+
+ When the psbt spends inputs from multiple wallets (different base paths) owned by
+ this seed, each valid change output will pay back to a specific source wallet. The
+ output's address index window is only evaluated against its source wallet's input
+ indices.
+
+ The rules only measure change against our own inputs. In a collaborative spend
+ (payjoin, coinjoin), the other parties' inputs are ignored by these checks. Those
+ external wallets (base paths) are irrelevant here. Similarly, their inputs'
+ address indices do not factor into the index window check.
+
+ Raises:
+ * PSBTChangeDerivationPathError: An output pays this seed at a derivation path
+ the user's coordinator software is unlikely to check.
+
+ Edge case note:
+ Coordinators typically only annotate outputs that are coming back to the wallet
+ being spent from (e.g. change outputs). So even when a user transfers funds into a
+ different wallet that they also own, that output has no annotations (i.e. it
+ doesn't claim that it's owned by our seed); it's presented to us as an external
+ spend. The notable exception is Bitcoin Core, which can annotate an output
+ regardless of which wallet is being spent from. So a transfer to a different
+ wallet that our seed also controls (e.g. different "account" index) would still
+ claim our seed but the output's base path won't match any of our inputs' base
+ path(s). So this otherwise valid output is rejected.
+
+ TODO: Possibly add a separate output category for outputs paying one of our keys
+ in another wallet or another quorum, shown to the user with a warning to confirm
+ the transfer is intended. An honest transfer into another of the user's own
+ wallets would then get that warning rather than this refusal.
+
+ TODO: Possibly add a verified_ attribute that this step fills in, such as
+ verified_change_data, so the attribute's name records that each change output's
+ derivation path passed these checks.
+ """
+ # Check all single sig / multisig change outputs
+ for change_data in self.change_data:
+ change_derivation_path = change_data["verified_derivation_path"]
+
+ if not self._is_wallet_change_derivation_path(change_derivation_path):
+ raise PSBTChangeDerivationPathError(derivation_path=change_derivation_path)
+
+ if not self._is_change_address_index_within_window(change_derivation_path):
+ change_data["address_index_beyond_window"] = True
+
+ # Check the multisig outputs that pay our key but were counted as SPENDS
+ # because their cosigners differ from the inputs'. They must pass the same rules.
+ # (the address index window check only applies to change, already checked above)
+ for verified_derivation_path in self.verified_cosigner_mismatch_output_derivation_paths:
+ if not self._is_wallet_change_derivation_path(verified_derivation_path.derivation):
+ raise PSBTChangeDerivationPathError(derivation_path=verified_derivation_path.derivation)
+
+
+ def _evaluate_input_base_paths(self):
+ """
+ A check for single sig segwit v0 inputs that this seed signs. The inputs must
+ either:
+ * Only spend from a single wallet (every input this seed signs must be at the
+ same base path).
+ * Or each input must supply a non_witness_utxo.
+
+ Segwit v0 (any segwit type before taproot) has a combination of weaker guarantees
+ about its inputs that differentiate it from legacy inputs and taproot inputs:
+ * Versus legacy inputs:
+ * Legacy inputs must provide the full previous transaction (the
+ non_witness_utxo) that created the utxo being spent.
+ * A segwit v0 input may provide just a witness_utxo, which only describes a
+ utxo without the transaction context; without the non_witness_utxo, we
+ cannot verify that the coordinator has honestly described the input we're
+ being asked to spend.
+ * Versus taproot inputs:
+ * Each taproot signature commits to ALL inputs' details (scriptPubKeys and
+ amounts); any faked detail in one input would invalidate the other inputs'
+ signatures.
+ * But segwit v0 signatures commit to just their own input's details.
+
+ A consequence of segwit v0's weaker guarantees is that the coordinator can add one
+ of its own utxos but provide a faked witness_utxo that makes it look like the
+ input is owned by one of our keys. Our validation rules for change outputs rely on
+ the base paths of our inputs. So if we were to accept that faked input's base
+ path as being valid for our change, we could end up sending our change to a
+ derivation path that our wallet would never check.
+
+ But for a valid transaction, we do have at least one crucial guarantee we can
+ depend on that emerges from the following facts:
+ * The coordinator needs valid signatures on all of our genuine inputs in order
+ to spend them.
+ * Our signature on an input is valid only if that input is described correctly
+ (its real scriptPubKey and amount).
+
+ So in this scenario, while a malicious coordinator can try to add its own faked
+ inputs, it still has to describe our genuine inputs truthfully. Which means
+ that at least one of the supplied base paths is correct.
+
+ But if we're presented with segwit v0 inputs that have different base paths, how
+ are we to know which one is correct? Where should we allow our change to go? We
+ have no way to determine that, so the check here simply requires that all of our
+ inputs in a segwit v0 transaction have the same base path (outsiders' inputs in a
+ collaborative spend are irrelevant here).
+
+ However, an input that supplies a non_witness_utxo has already been verified
+ against the txid it spends. Faking it would mean making up its previous
+ transaction, which would leave the transaction we sign unable to confirm. So when
+ all of our inputs supply a non_witness_utxo, we allow our inputs to be at
+ different base paths.
+
+ Multisig is exempt because its change has its own checks, based on the full set of
+ cosigners.
+
+ Edge case note: some software allows users to build a psbt with inputs from
+ different wallets for the same seed by merging psbts by hand (Bitcoin Core's
+ joinpsbts, Electrum's "Join inputs/outputs"). Such psbts could present segwit v0
+ inputs with multiple base paths and no non_witness_utxo. They will be rejected
+ even though they were legitimately constructed.
+
+ Note: a Bitcoin Core wallet built from more than one of this seed's base paths
+ (e.g. different "account" derivation paths) can also spend from all of them in one
+ psbt. Core includes the non_witness_utxo on each segwit v0 input from its own
+ wallet, so its psbts pass this check.
+ """
+ # We're only concerned with single sig segwit v0 inputs; early exit for all
+ # others.
+ if self.policy["type"] not in ("p2wpkh", "p2sh-p2wpkh"):
+ return
+
+ input_base_paths = set()
+ has_witness_only_input = False
+ for i, verified_derivation_paths in enumerate(self.verified_input_derivation_paths):
+ if not verified_derivation_paths:
+ # Another party's input, in a collaborative spend for example
+ continue
+
+ # We know it's single sig; directly access its one derivation path
+ input_base_path = PSBTParser._get_base_path(verified_derivation_paths[0].derivation)
+
+ # The set needs a hashable type; convert the list to string
+ input_base_paths.add(bip32.path_to_str(input_base_path))
+
+ if self.psbt.inputs[i].non_witness_utxo is None:
+ # Only a witness_utxo, so this input's details could be faked
+ has_witness_only_input = True
+
+ if len(input_base_paths) > 1 and has_witness_only_input:
+ # Our inputs are at more than one base path and at least one input could be
+ # faked. By rule we reject the psbt.
+ raise PSBTUnverifiableMixedInputBasePathsError(f"Inputs are at {len(input_base_paths)} base paths and at least one has no non_witness_utxo")
+
+
@staticmethod
def is_change_branch(derivation_path: List[int]) -> bool:
"""
### src/seedsigner/views/psbt_views.py
@@ -2,14 +2,15 @@
from gettext import gettext as _
-from seedsigner.models.psbt_parser import (PSBTExtraneousInputScriptError,
- PSBTInputAmountVerificationError, PSBTInputOwnershipClaimError,
- PSBTInputOwnershipContradictionError, PSBTInputScriptMismatchError,
- PSBTMalformedOpReturnError, PSBTMissingInputScriptError, PSBTMissingInputUtxoError,
- PSBTMixedDerivationPathTypesError, PSBTNegativeFeeError, PSBTOutputOwnershipClaimError,
- PSBTOutputOwnershipContradictionError, PSBTParser, PSBTSeedCannotSignError,
- PSBTSurplusDerivationPathsError, PSBTUnsupportedDerivationPathError,
- PSBTUnsupportedScriptPathError)
+from seedsigner.models.psbt_parser import (PSBTChangeDerivationPathError,
+ PSBTExtraneousInputScriptError, PSBTInputAmountVerificationError,
+ PSBTInputOwnershipClaimError, PSBTInputOwnershipContradictionError,
+ PSBTInputScriptMismatchError, PSBTMalformedOpReturnError, PSBTMissingInputScriptError,
+ PSBTMissingInputUtxoError, PSBTMixedDerivationPathTypesError, PSBTNegativeFeeError,
+ PSBTOutputOwnershipClaimError, PSBTOutputOwnershipContradictionError, PSBTParser,
+ PSBTSeedCannotSignError, PSBTSurplusDerivationPathsError,
+ PSBTUnsupportedDerivationPathError, PSBTUnsupportedScriptPathError,
+ PSBTUnverifiableMixedInputBasePathsError)
from seedsigner.models.settings import SettingsConstants
from seedsigner.gui.components import FontAwesomeIconConstants, GUIConstants, SeedSignerIconConstants
from seedsigner.gui.screens.screen import (RET_CODE__BACK_BUTTON, ButtonListScreen, ButtonOption, LargeIconStatusScreen, WarningScreen, DireWarningScreen, QRDisplayScreen)
@@ -115,6 +116,12 @@ def __init__(self):
# Note that in almost every exception case, we set clear_history to disable
# returning via BACK button in the Destination.
+ #
+ # TODO: Most of these except clauses route to a View of their own whose only
+ # job is to show a WarningScreen or DireWarningScreen and discard the psbt.
+ # Replace them with a dict that maps each error type to its warning level and
+ # user-facing message, shown by one generic View (as PSBTWarningView does for
+ # the non-fatal warnings).
except PSBTInputOwnershipClaimError:
self.set_redirect(Destination(PSBTInputOwnershipClaimFailedView, clear_history=True))
return
@@ -167,6 +174,18 @@ def __init__(self):
self.set_redirect(Destination(PSBTNegativeFeeView, clear_history=True))
return
+ except PSBTChangeDerivationPathError as e:
+ self.set_redirect(Destination(
+ PSBTUnexpectedChangeDerivationPathView,
+ view_args=dict(derivation_path=e.derivation_path),
+ clear_history=True,
+ ))
+ return
+
+ except PSBTUnverifiableMixedInputBasePathsError:
+ self.set_redirect(Destination(PSBTUnverifiableMixedInputBasePathsView, clear_history=True))
+ return
+
except PSBTSeedCannotSignError:
# Not a suspicious psbt, just the wrong seed for it. Send the user back to
# pick another rather than clearing the flow.
@@ -203,6 +222,7 @@ def run(self):
'amount': 397621401,
'verified_derivation_path':
[2147483696, 2147483649, 2147483648, 2147483650, 1, 0],
+ 'address_index_beyond_window': False,
}, {},
]
"""
@@ -232,97 +252,80 @@ def run(self):
self.controller.psbt_seed = None
return Destination(BackStackView)
- # expecting p2sh (legacy multisig) and p2pkh to have no policy set
- # skip change warning and psbt math view
- if psbt_parser.policy == None:
- return Destination(PSBTUnsupportedScriptTypeWarningView)
-
- elif psbt_parser.is_high_fee:
- return Destination(PSBTHighFeeWarningView, view_args={"warning_threshold_percent": psbt_parser.HIGH_FEES_WARNING_THRESHOLD})
-
- elif psbt_parser.change_amount == 0:
- return Destination(PSBTNoChangeWarningView)
+ if len(psbt_parser.warnings) > 0:
+ return Destination(PSBTWarningView)
else:
return Destination(PSBTMathView)
-class PSBTUnsupportedScriptTypeWarningView(View):
- def run(self):
- selected_menu_num = self.run_screen(
- WarningScreen,
- status_headline=_("Unsupported Script Type!"),
- text=_("Transaction has unsupported input script type, please verify your change addresses."),
- button_data=[ButtonOption("Continue")],
- )
-
- if selected_menu_num == RET_CODE__BACK_BUTTON:
- return Destination(BackStackView)
-
- # Only one exit point
- # skip PSBTMathView
- return Destination(
- PSBTAddressDetailsView, view_args={"address_num": 0},
- skip_current_view=True, # Prevent going BACK to WarningViews
- )
+class PSBTWarningView(View):
+ """
+ Shows the psbt's warning at warning_index and then moves on to the next one. Once
+ every warning has been shown, redirects to PSBTMathView instead.
+ """
+ CONTINUE = ButtonOption("Continue")
+
+ def __init__(self, warning_index: int = 0):
+ super().__init__()
+ self.warning_index = warning_index
+ if warning_index >= len(self.controller.psbt_parser.warnings):
+ self.set_redirect(Destination(PSBTMathView))
+ return
-class PSBTNoChangeWarningView(View):
def run(self):
- selected_menu_num = self.run_screen(
- WarningScreen,
+ warning = self.controller.psbt_parser.warnings[self.warning_index]
+ if warning == PSBTParser.WARNING__HIGH_FEE:
+ Screen_cls = DireWarningScreen
+ status_headline = _("High Fee!")
+ # TRANSLATOR_NOTE: Variable is the percentage of the total output value (excluding change) that the fee exceeds. (e.g. "This transaction has a fee higher than 25% of the total output value (excluding change).")
+ text = _("This transaction has a fee higher than {}% of the total output value (excluding change).").format(PSBTParser.HIGH_FEES_WARNING_THRESHOLD)
+
+ elif warning == PSBTParser.WARNING__NO_CHANGE:
+ Screen_cls = WarningScreen
# TRANSLATOR_NOTE: User will receive no change back; the inputs to this transaction are fully spent
- status_headline=_("Full Spend!"),
- text=_("This transaction spends its entire input value. No change is coming back to your wallet."),
- button_data=[ButtonOption("Continue")],
+ status_headline = _("Full Spend!")
+ text = _("This transaction spends its entire input value. No change is coming back to your wallet.")
+
+ elif warning == PSBTParser.WARNING__CHANGE_ADDRESS_INDEX_BEYOND_WINDOW:
+ # Change or a self-transfer comes back to a derivation path this wallet does
+ # use, but at an address index further along than the coins being spent
+ # suggest it has reached.
+ #
+ # We warn and let the user continue rather than discarding the psbt. We are
+ # offline and cannot see how far the coordinator has handed out addresses, so
+ # the address index is the one change rule we can only guess at. An ordinary
+ # transaction from an active wallet can trip it.
+ Screen_cls = WarningScreen
+ # TRANSLATOR_NOTE: Warns that funds are coming back to the user's own wallet (as change or a self-transfer) at an address far beyond the ones this transaction spends from, which their wallet may not look far enough ahead to find.
+ status_headline = _("Distant Address")
+ text = _("Funds return to an address far beyond the ones being spent. Your wallet may not find them.")
+
+ else:
+ raise Exception(f"Unhandled psbt warning: {warning}")
+
+ selected_menu_num = self.run_screen(
+ Screen_cls,
+ status_headline=status_headline,
+ text=text,
+ button_data=[self.CONTINUE],
)
if selected_menu_num == RET_CODE__BACK_BUTTON:
return Destination(BackStackView)
# Only one exit point
return Destination(
- PSBTMathView,
+ PSBTWarningView,
+ view_args=dict(warning_index=self.warning_index + 1),
skip_current_view=True, # Prevent going BACK to WarningViews
)
-class PSBTHighFeeWarningView(View):
- def __init__(self, warning_threshold_percent: int):
- super().__init__()
-
- self.warning_threshold_percent = warning_threshold_percent
-
- def run(self):
- selected_menu_num = self.run_screen(
- DireWarningScreen,
- status_headline=_("High Fee!"),
- # TRANSLATOR_NOTE: Variable is the percentage of the total output value (excluding change) that the fee exceeds. (e.g. "This transaction has a fee higher than 25% of the total output value (excluding change).")
- text=_("This transaction has a fee higher than {}% of the total output value (excluding change).").format(self.warning_threshold_percent),
- button_data=[ButtonOption("Continue")],
- )
-
- if selected_menu_num == RET_CODE__BACK_BUTTON:
- return Destination(BackStackView)
-
- # PSBT may have high fee + no change
- if self.controller.psbt_parser.change_amount == 0:
- return Destination(
- PSBTNoChangeWarningView,
- skip_current_view=True, # Prevent going BACK to WarningViews
- )
-
- else:
- return Destination(
- PSBTMathView,
- skip_current_view=True, # Prevent going BACK to WarningViews
- )
-
-
-
class PSBTMathView(View):
"""
Follows the Overview pictogram. Shows:
@@ -446,13 +449,12 @@ def run(self):
'amount': 397621401,
'verified_derivation_path':
[2147483696, 2147483649, 2147483648, 2147483650, 1, 0],
+ 'address_index_beyond_window': False,
}
"""
seed_fingerprint = self.controller.psbt_seed.get_fingerprint(self.settings.get_value(SettingsConstants.SETTING__NETWORK))
verified_derivation_path = change_data.get("verified_derivation_path")
is_change_derivation_path = PSBTParser.is_change_branch(verified_derivation_path)
-
- # TODO: Refuse a path too short to carry a branch and an address index
derivation_path_addr_index = verified_derivation_path[-1]
if is_change_derivation_path:
@@ -506,6 +508,7 @@ def run(self):
is_change_derivation_path=is_change_derivation_path,
derivation_path_addr_index=derivation_path_addr_index,
is_change_addr_verified=is_change_addr_verified,
+ is_address_index_beyond_window=change_data["address_index_beyond_window"],
)
if selected_menu_num == RET_CODE__BACK_BUTTON:
@@ -900,7 +903,7 @@ def run(self):
class PSBTUnsupportedScriptPathView(View):
"""
- Reached when this seed can sign an input only through a taproot script path spend
+ Reached when an input only lets this seed sign through a taproot script path spend
(see PSBTUnsupportedScriptPathError).
Script path spends are not yet supported, so this seed cannot sign the input. We do
@@ -925,6 +928,72 @@ def run(self):
+class PSBTUnexpectedChangeDerivationPathView(View):
+ """
+ Reached when an output comes back to this seed at a derivation path the wallet this
+ transaction spends from does not use (see PSBTChangeDerivationPathError). Single sig
+ and multisig alike.
+
+ The coins still belong to the user's seed, but their coordinator software will never
+ scan that path to find them. We view this as an attack. We do not allow the user to
+ continue and give this the "Dire Warning" level. The path is displayed and named as a
+ derivation path, which gives the user a term to search for.
+ """
+ DISCARD = ButtonOption("Discard transaction")
+
+ def __init__(self, derivation_path: list[int]):
+ super().__init__()
+ self.derivation_path = derivation_path
+
+
+ def run(self):
+ from embit import bip32
+
+ self.run_screen(
+ DireWarningScreen,
+ title=_("Suspicious Transaction"),
+ status_headline=_("Unsafe Derivation Path"),
+ # TRANSLATOR_NOTE: Variable is a derivation path such as "m/84'/0'/0'/5/0", shown on its own line, where this transaction sends funds back to the user's seed. "Our" refers to SeedSigner.
+ text=_("{}\nfailed our safety checks.").format(bip32.path_to_str(self.derivation_path).replace("h", "'")),
+ button_data=[self.DISCARD],
+ show_back_button=False,
+ )
+
+ # We're done with this PSBT. Route back to MainMenuView, which clears all
+ # ephemeral data (except in-memory seeds).
+ # Set clear_history to disable returning via BACK button.
+ return Destination(MainMenuView, clear_history=True)
+
+
+
+class PSBTUnverifiableMixedInputBasePathsView(View):
+ """
+ Reached by single sig segwit v0 transactions when the inputs this seed signs are at
+ more than one base path and at least one input has no non_witness_utxo (the full
+ transaction that created its utxo). See PSBTUnverifiableMixedInputBasePathsError.
+
+ We do not allow the user to continue, but only give this the "Warning" level.
+ """
+ DISCARD = ButtonOption("Discard transaction")
+
+ def run(self):
+ self.run_screen(
+ WarningScreen,
+ title=_("Transaction Problem"),
+ status_headline=None,
+ # TRANSLATOR_NOTE: This transaction includes inputs from multiple wallets (accounts) controlled by this seed. This can be allowed for some script types, but not this one.
+ text=_("Inputs from multiple wallets: cannot complete verification for this script type."),
+ button_data=[self.DISCARD],
+ show_back_button=False,
+ )
+
+ # We're done with this PSBT. Route back to MainMenuView, which clears all
+ # ephemeral data (except in-memory seeds).
+ # Set clear_history to disable returning via BACK button.
+ return Destination(MainMenuView, clear_history=True)
+
+
+
class PSBTAddressVerificationFailedView(View):
"""
Reached from PSBTChangeDetailsView when a multisig change or self-transfer output
### tests/psbt_testing_util.py
@@ -8,7 +8,7 @@
from embit.psbt import PSBT, DerivationPath, InputScope, OutputScope
from embit.script import Script
-from seedsigner.models.psbt_parser import OPCODES
+from seedsigner.models.psbt_parser import OPCODES, PSBTParser
from seedsigner.models.seed import Seed
@@ -21,6 +21,9 @@ class PSBTTestData:
multisig_key_2 = Seed("better gown govern speak spawn vendor exercise item uncle odor sound cat".split())
multisig_key_3 = Seed("sign sword lift deer ocean insect web lazy sick pencil start select".split())
+ # The three cosigners of the multisig fixtures' 2-of-3
+ multisig_cosigner_seeds = [seed, multisig_key_2, multisig_key_3]
+
# Base psbts with various inputs for various wallet script types; outputs have been stripped
SINGLE_SIG_NATIVE_SEGWIT_1_INPUT = "cHNidP8BADMCAAAAAU4T/0aX9mmNZHyKh+0AHYY+EtdJxndMRra0gn4QPCZdAQAAAAD9////AHAAAABPAQQ1h88DV5lJlYAAAADURWu0eYGA/OFm4Wt3dUJ44H2DzgcPO6J+nF0t9lqMqgLDxbT8Qez0U3W7o1JwT1FQ4fWFAbcK5eJ3NDnETRryMhAPuIL/VAAAgAEAAIAAAACAAAEAiAIAAAAB1Tct22qlCW5iTOZDfXqVu6CKlwdTtrPhbPI7pcTQ/GUBAAAAFxYAFCPpAsYWUNJnTErOjkoChnQylGp6/f///wLNLhoeAQAAABYAFI4lU5EAZIlw/MpX6r3gh1zqazEOAOH1BQAAAAAWABRYjLo+w43NT+5rzgPCNuy79lZjDm4AAAABAR8A4fUFAAAAABYAFFiMuj7Djc1P7mvOA8I27Lv2VmMOAQMEAQAAACIGAvXbqnkmWDXPNEkHznP0l2VFFql2WpgX42yD3Z9fJY/3GA+4gv9UAACAAQAAgAAAAIAAAAAAAwAAAAA="
SINGLE_SIG_NESTED_SEGWIT_1_INPUT = "cHNidP8BADMCAAAAAdU3LdtqpQluYkzmQ316lbugipcHU7az4WzyO6XE0PxlAAAAAAD9////AHAAAABPAQQ1h88DIWg8n4AAAACkwPiG7M1QVnBPyAKQofuHpAZAXgXRNyJ15AYUNQRCFQIwD+a/8Dc8z2f/GXiC8z1fbvjC6VqIcciZQ51uU2tq9BAPuIL/MQAAgAEAAIAAAACAAAEAcwIAAAAB9EA7OurOd1aGyQJpQN+S0G+3IF31HO2UFAZnIpALsfQAAAAAAP3///8CAOH1BQAAAAAXqRQDW7vsMAXGa+tKARihpGq6ZwuDYYdxEBAkAQAAABepFGaYxdrjSngzRRSCeg3U/SKQOEfXhwAAAAABASAA4fUFAAAAABepFANbu+wwBcZr60oBGKGkarpnC4NhhwEDBAEAAAABBBYAFDriE9Kbby6bOWzXbXatODyyIRpcIgYDQD4mWFMSOO9mDOb+bwzEiaDf+1dWJICoG4BCig4K2awYD7iC/zEAAIABAACAAAAAgAAAAAAAAAAAAA=="
@@ -260,20 +263,90 @@ def claim_seed_owns_key(scope: InputScope | OutputScope, claimed_derivation_path
def set_input_locking_script(inp: InputScope, script_pubkey: Script):
"""
- Changes the locking script (the scriptPubKey) of the coin a segwit input spends.
+ Changes the locking script (the scriptPubKey) of the utxo a segwit input spends.
Lets a test make the input commit to a different script or key.
Edits the witness_utxo and drops the non_witness_utxo. The non_witness_utxo is the
previous transaction, which still pays the old scriptPubKey, so it would contradict
- the edit. Editing it to match is not an option either: that changes the txid it
- hashes to, so it would no longer be the transaction this input claims to spend. The
- witness_utxo alone describes a segwit input's coin, which is what a coordinator
- would normally send anyway.
+ the edit. Editing it to match would change its txid, and the input would then have
+ to point at the new txid. The witness_utxo alone describes a segwit input's utxo,
+ which is what a coordinator would normally send anyway.
"""
inp.witness_utxo.script_pubkey = script_pubkey
inp.non_witness_utxo = None
+def repoint_change(psbt: PSBT, derivation_path: str, seed: Seed = None):
+ """
+ Moves the psbt's change output to derivation_path, still paying seed. Lets a test
+ choose where the change comes back to, such as another base path or a distant address
+ index.
+
+ Rebuilds the script the output commits to and the entries describing it, keeping
+ whatever script type the output already had. Callers pass a psbt whose change output
+ comes first. A multisig output is rebuilt from the multisig fixtures' cosigners, so
+ seed applies to single sig only.
+ """
+ if seed is None:
+ seed = PSBTTestData.seed
+ out = psbt.outputs[0]
+
+ # Find the output's multisig script, if it has one. Nested single sig also carries
+ # a redeem_script, which is a p2wpkh.
+ multisig_script = out.witness_script or out.redeem_script
+ is_multisig = multisig_script is not None and multisig_script.script_type() != "p2wpkh"
+
+ # Drop the entries describing the old path
+ out.bip32_derivations.clear()
+ out.taproot_bip32_derivations.clear()
+
+ if is_multisig:
+ # Move every cosigner to the new path
+ cosigner_public_keys = []
+ for cosigner_seed in PSBTTestData.multisig_cosigner_seeds:
+ public_key = root_for_seed(cosigner_seed).derive(derivation_path).get_public_key()
+ cosigner_public_keys.append(public_key)
+ claim_seed_owns_key(out, derivation_path, public_key, seed=cosigner_seed)
+
+ # The fixtures are sortedmulti, so keep the keys in lexicographic order
+ cosigner_public_keys.sort(key=lambda public_key: public_key.sec())
+ multisig_script = script.multisig(2, cosigner_public_keys)
+
+ # Rebuild the scripts the output commits to, wrapped the same way as before
+ # (p2wsh, p2sh, or p2wsh nested in p2sh).
+ if out.witness_script is not None:
+ out.witness_script = multisig_script
+ inner_script = script.p2wsh(multisig_script)
+ else:
+ inner_script = multisig_script
+
+ if out.redeem_script is not None:
+ out.redeem_script = inner_script
+ out.script_pubkey = script.p2sh(inner_script)
+ else:
+ out.script_pubkey = inner_script
+
+ else:
+ # Rebuild the scriptPubKey (and a nested output's redeem_script) for our key
+ # at the new path, keeping the output's script type.
+ public_key = root_for_seed(seed).derive(derivation_path).get_public_key()
+ is_taproot = out.script_pubkey.script_type() == "p2tr"
+
+ if is_taproot:
+ policy_type = "p2tr"
+ elif out.redeem_script is not None:
+ policy_type = "p2sh-p2wpkh"
+ out.redeem_script = script.p2wpkh(public_key)
+ else:
+ policy_type = out.script_pubkey.script_type()
+
+ out.script_pubkey = PSBTParser._build_singlesig_script(policy_type, public_key)
+
+ # Describe the output's new path
+ claim_seed_owns_key(out, derivation_path, public_key, seed=seed, is_taproot=is_taproot)
+
+
+
def op_return_script(payload: bytes) -> Script:
"""
Build an OP_RETURN scriptPubKey carrying `payload`, using the minimal push encoding
### tests/screenshot_generator/generator.py
@@ -281,6 +281,24 @@ def mock_single_sig_psbt_loaded():
yield
+ @contextmanager
+ def mock_single_sig_psbt_with_distant_change_loaded():
+ with mock_single_sig_psbt_loaded():
+ # Show the change at a large address index, flagged as beyond the window
+ change_output = controller.psbt_parser.change_data[0]
+ change_output["verified_derivation_path"] = change_output["verified_derivation_path"][:-1] + [20000]
+ change_output["address_index_beyond_window"] = True
+ yield
+
+
+ @contextmanager
+ def mock_single_sig_psbt_with_every_warning_loaded():
+ with mock_single_sig_psbt_loaded():
+ # List every warning so each one can be shown by its index
+ with patch.object(controller.psbt_parser, "warnings", [PSBTParser.WARNING__HIGH_FEE, PSBTParser.WARNING__NO_CHANGE, PSBTParser.WARNING__CHANGE_ADDRESS_INDEX_BEYOND_WINDOW]):
+ yield
+
+
@contextmanager
def mock_multisig_psbt_loaded():
with mock_load_psbt(BASE64_MULTISIG_PSBT):
@@ -438,14 +456,15 @@ def mock_version_to_most_recent_release():
"PSBT Views": [
ScreenshotConfig(psbt_views.PSBTSelectSeedView, mock_context_manager=mock_controller_psbt_seed_empty),
ScreenshotConfig(psbt_views.PSBTOverviewView, mock_context_manager=mock_multisig_psbt_loaded),
- ScreenshotConfig(psbt_views.PSBTUnsupportedScriptTypeWarningView),
- ScreenshotConfig(psbt_views.PSBTNoChangeWarningView),
- ScreenshotConfig(psbt_views.PSBTHighFeeWarningView, dict(warning_threshold_percent=25)),
+ ScreenshotConfig(psbt_views.PSBTWarningView, dict(warning_index=0), screenshot_name="PSBTWarningView_high_fee", mock_context_manager=mock_single_sig_psbt_with_every_warning_loaded),
+ ScreenshotConfig(psbt_views.PSBTWarningView, dict(warning_index=1), screenshot_name="PSBTWarningView_no_change", mock_context_manager=mock_single_sig_psbt_with_every_warning_loaded),
+ ScreenshotConfig(psbt_views.PSBTWarningView, dict(warning_index=2), screenshot_name="PSBTWarningView_distant_address", mock_context_manager=mock_single_sig_psbt_with_every_warning_loaded),
ScreenshotConfig(psbt_views.PSBTMathView, mock_context_manager=mock_multisig_psbt_loaded),
ScreenshotConfig(psbt_views.PSBTAddressDetailsView, dict(address_num=0), mock_context_manager=mock_multisig_psbt_loaded),
ScreenshotConfig(psbt_views.PSBTChangeDetailsView, dict(change_address_num=0), screenshot_name="PSBTChangeDetailsView_single_sig_change_verified", mock_context_manager=mock_single_sig_psbt_loaded),
ScreenshotConfig(psbt_views.PSBTChangeDetailsView, dict(change_address_num=1), screenshot_name="PSBTChangeDetailsView_single_sig_self_transfer_verified", mock_context_manager=mock_single_sig_psbt_loaded),
+ ScreenshotConfig(psbt_views.PSBTChangeDetailsView, dict(change_address_num=0), screenshot_name="PSBTChangeDetailsView_single_sig_change_distant_index", mock_context_manager=mock_single_sig_psbt_with_distant_change_loaded),
ScreenshotConfig(psbt_views.PSBTChangeDetailsView, dict(change_address_num=0), screenshot_name="PSBTChangeDetailsView_multisig_unverified", mock_context_manager=mock_multisig_psbt_loaded),
ScreenshotConfig(psbt_views.PSBTChangeDetailsView, dict(change_address_num=0), screenshot_name="PSBTChangeDetailsView_multisig_verified", mock_context_manager=mock_multisig_psbt_and_descriptor_loaded),
ScreenshotConfig(psbt_views.PSBTOverviewView, screenshot_name="PSBTOverviewView_op_return", mock_context_manager=mock_psbt_with_op_return_loaded),
@@ -461,6 +480,8 @@ def mock_version_to_most_recent_release():
ScreenshotConfig(psbt_views.PSBTInputScriptMismatchView),
ScreenshotConfig(psbt_views.PSBTExtraneousInputScriptView),
ScreenshotConfig(psbt_views.PSBTUnsupportedScriptPathView),
+ ScreenshotConfig(psbt_views.PSBTUnexpectedChangeDerivationPathView, dict(derivation_path=embit.bip32.parse_path("m/84h/1h/5h/1/0"))),
+ ScreenshotConfig(psbt_views.PSBTUnverifiableMixedInputBasePathsView),
ScreenshotConfig(psbt_views.PSBTAddressVerificationFailedView, dict(is_change=True), screenshot_name="PSBTAddressVerificationFailedView_multisig_change"),
ScreenshotConfig(psbt_views.PSBTAddressVerificationFailedView, dict(is_change=False), screenshot_name="PSBTAddressVerificationFailedView_multisig_selftransfer"),
ScreenshotConfig(psbt_views.PSBTOutputOwnershipClaimFailedView),
### tests/test_flows_psbt.py
@@ -1,17 +1,18 @@
from binascii import a2b_base64
+from copy import deepcopy
from embit import bip32, script
from embit.psbt import PSBT, DerivationPath
from base import FlowTest, FlowStep
from psbt_testing_util import (NUMS_INTERNAL_KEY, PSBTTestData, claim_seed_owns_key,
create_op_return_output, create_output, foreign_public_key, p2tr_with_script_tree,
- root_for_seed, set_input_locking_script, tapleaf_hash)
+ repoint_change, root_for_seed, set_input_locking_script, tapleaf_hash)
from seedsigner.controller import Controller
-from seedsigner.views.view import MainMenuView
+from seedsigner.views.view import MainMenuView, View
from seedsigner.views import scan_views, seed_views, psbt_views
-from seedsigner.models.psbt_parser import OPCODES
+from seedsigner.models.psbt_parser import OPCODES, PSBTParser
from seedsigner.models.seed import Seed
from seedsigner.models.settings import SettingsConstants
@@ -208,14 +209,10 @@ def load_seed_into_decoder(view: scan_views.ScanView):
-class TestPSBTOwnershipClaimRouting(FlowTest):
+class PSBTSigningFlowTest(FlowTest):
"""
- A psbt whose own description of itself does not hold up, or whose arithmetic is
- impossible, is refused during parsing, before the user is shown anything about the
- transaction. These cover what the user meets when that happens: a warning screen that
- ends the flow, not a crash.
+ Shared helpers for flow tests that load a psbt and walk through the signing flow.
"""
-
def _load_psbt_for_signing(self, psbt: PSBT, seed: Seed = None):
"""
Stage the psbt in the Controller and load the signing seed into storage, as if
@@ -234,6 +231,16 @@ def _psbt_with_change(self):
return psbt
+
+class TestPSBTOwnershipClaimRouting(PSBTSigningFlowTest):
+ """
+ A psbt whose own description of itself does not hold up, whose arithmetic is
+ impossible, or whose change pays our key at a path the user's coordinator software is
+ unlikely to check is refused during parsing, before the user is shown anything about
+ the transaction. These cover what the user meets when that happens: a warning screen
+ that ends the flow, not a crash.
+ """
+
def test_forged_output_claim_terminates_signing_flow(self):
"""
A forged ownership claim on an output is framed as a potential attack, so it
@@ -491,8 +498,9 @@ def test_extraneous_input_script_terminates_signing_flow(self):
def test_input_ownership_contradiction_terminates_signing_flow(self):
"""
- The psbt adds a second claim of ours to the user's own input, at a path whose key
- the input's script does not use. That is framed as an attack.
+ The psbt claims that our input is also controlled by our key at a second
+ derivation path. The input's script uses a different key, so the claim is false.
+ That is framed as an attack.
The flow should stop at PSBTInputOwnershipContradictionView, before any
transaction detail is rendered.
@@ -545,6 +553,57 @@ def test_unsupported_script_path_terminates_signing_flow(self):
])
+ def test_unexpected_change_derivation_path_terminates_signing_flow(self):
+ """
+ The psbt pays change to our key on a branch that no coordinator software scans.
+ The coins stay the user's, but their coordinator software will never look there to
+ find them, so this is framed as an attack.
+
+ The flow should stop at PSBTUnexpectedChangeDerivationPathView, before any
+ transaction detail is rendered.
+ """
+ psbt = self._psbt_with_change()
+ repoint_change(psbt, "m/84h/1h/0h/2/0")
+
+ self._load_psbt_for_signing(psbt)
+
+ self.run_sequence([
+ FlowStep(psbt_views.PSBTSelectSeedView, screen_return_value=0),
+ FlowStep(psbt_views.PSBTOverviewView, is_redirect=True),
+ FlowStep(psbt_views.PSBTUnexpectedChangeDerivationPathView, button_data_selection=psbt_views.PSBTUnexpectedChangeDerivationPathView.DISCARD),
+ FlowStep(MainMenuView),
+ ])
+
+
+ def test_mixed_base_paths_terminate_signing_flow(self):
+ """
+ A single sig segwit v0 psbt spends utxos from two of the seed's accounts. The
+ added input only has a witness_utxo, so it can't be verified as genuine.
+
+ The flow should stop at PSBTUnverifiableMixedInputBasePathsView, before any
+ transaction detail is rendered.
+ """
+ psbt = self._psbt_with_change()
+
+ # One more of our utxos, from another account
+ second_account_derivation_path = "m/84h/1h/7h/0/2"
+ public_key = root_for_seed(PSBTTestData.seed).derive(second_account_derivation_path).get_public_key()
+ second_input = deepcopy(psbt.inputs[0])
+ second_input.bip32_derivations.clear()
+ set_input_locking_script(second_input, script.p2wpkh(public_key))
+ claim_seed_owns_key(second_input, second_account_derivation_path, public_key)
+ psbt.inputs.append(second_input)
+
+ self._load_psbt_for_signing(psbt)
+
+ self.run_sequence([
+ FlowStep(psbt_views.PSBTSelectSeedView, screen_return_value=0),
+ FlowStep(psbt_views.PSBTOverviewView, is_redirect=True),
+ FlowStep(psbt_views.PSBTUnverifiableMixedInputBasePathsView, button_data_selection=psbt_views.PSBTUnverifiableMixedInputBasePathsView.DISCARD),
+ FlowStep(MainMenuView),
+ ])
+
+
def test_wrong_seed_routes_back_to_seed_selection_flow(self):
"""
The wrong seed for a psbt redirects before any transaction detail is rendered and
@@ -584,3 +643,166 @@ def test_negative_fee_terminates_signing_flow(self):
FlowStep(psbt_views.PSBTNegativeFeeView, button_data_selection=psbt_views.PSBTNegativeFeeView.DISCARD),
FlowStep(MainMenuView),
])
+
+
+
+class TestPSBTWarningRouting(PSBTSigningFlowTest):
+ """
+ Some findings are worth a warning but leave the decision to the user. Each applicable
+ warning is shown in turn before the transaction details. The user can then continue
+ to sign. These cover each warning alone and in the sequences that can occur together.
+ """
+
+ def test_distant_change_index_warns_but_allows_signing(self):
+ """
+ The psbt pays change at an address index far past the one this transaction spends
+ from.
+
+ Unlike a change path refusal, the flow should show the distant address warning and
+ then let the user carry on to sign, with the transaction detail screens shown as
+ usual. The change details screen should be told the address index is distant.
+ """
+ psbt = self._psbt_with_change()
+
+ # The lone input's key is at index 3, so this is well past the window
+ repoint_change(psbt, "m/84h/1h/0h/1/20000")
+
+ self._load_psbt_for_signing(psbt)
+
+ change_details_screen_kwargs = {}
+
+ def capture_change_details_screen(view: psbt_views.PSBTChangeDetailsView):
+ """
+ Record what the change details View hands its Screen. run_sequence has already
+ mocked View.run_screen, so this wrapper records the arguments and then calls
+ that mock, leaving the sequence's own bookkeeping intact.
+ """
+ def wrapper(ScreenClass, **kwargs):
+ change_details_screen_kwargs.update(kwargs)
+ return View.run_screen(view, ScreenClass, **kwargs)
+ view.run_screen = wrapper
+
+ self.run_sequence([
+ FlowStep(psbt_views.PSBTSelectSeedView, screen_return_value=0),
+ FlowStep(psbt_views.PSBTOverviewView),
+ FlowStep(psbt_views.PSBTWarningView, button_data_selection=psbt_views.PSBTWarningView.CONTINUE),
+ FlowStep(psbt_views.PSBTWarningView, is_redirect=True),
+ FlowStep(psbt_views.PSBTMathView),
+ FlowStep(psbt_views.PSBTChangeDetailsView, before_run=capture_change_details_screen, button_data_selection=psbt_views.PSBTChangeDetailsView.NEXT),
+ FlowStep(psbt_views.PSBTFinalizeView, button_data_selection=psbt_views.PSBTFinalizeView.APPROVE_PSBT),
+ FlowStep(psbt_views.PSBTSignedQRDisplayView),
+ ])
+
+ # The output the warning was about is the one the parse flagged
+ assert self.controller.psbt_parser.warnings == [PSBTParser.WARNING__CHANGE_ADDRESS_INDEX_BEYOND_WINDOW]
+ assert self.controller.psbt_parser.change_data[0]["address_index_beyond_window"] is True
+
+ # The View passes that flag on to the change details screen
+ assert change_details_screen_kwargs["is_address_index_beyond_window"] is True
+
+
+ def test_high_fee_warning_continues_to_the_distant_change_index_warning(self):
+ """
+ The psbt pays a 50,000 sat recipient out of a 1 BTC input, so nearly all of the
+ input goes to the fee. Its change output also pays a key at an address index far
+ past the input's.
+
+ The user should see the high fee warning, then the distant change index warning,
+ and then the transaction details.
+ """
+ psbt = self._psbt_with_change()
+
+ # The lone input's key is at index 3, so this is well past the window
+ repoint_change(psbt, "m/84h/1h/0h/1/20000")
+ psbt.outputs.append(create_output(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_RECEIVE, 50_000))
+
+ self._load_psbt_for_signing(psbt)
+
+ self.run_sequence([
+ FlowStep(psbt_views.PSBTSelectSeedView, screen_return_value=0),
+ FlowStep(psbt_views.PSBTOverviewView),
+ FlowStep(psbt_views.PSBTWarningView, button_data_selection=psbt_views.PSBTWarningView.CONTINUE),
+ FlowStep(psbt_views.PSBTWarningView, button_data_selection=psbt_views.PSBTWarningView.CONTINUE),
+ FlowStep(psbt_views.PSBTWarningView, is_redirect=True),
+ FlowStep(psbt_views.PSBTMathView),
+ ])
+
+ assert self.controller.psbt_parser.warnings == [
+ PSBTParser.WARNING__HIGH_FEE,
+ PSBTParser.WARNING__CHANGE_ADDRESS_INDEX_BEYOND_WINDOW,
+ ]
+
+
+ def test_high_fee_warning_alone_continues_to_the_transaction_details(self):
+ """
+ The psbt pays a 50,000 sat recipient out of a 1 BTC input, with its change at an
+ ordinary address index, so nearly all of the input goes to the fee.
+
+ The user should see the high fee warning and then the transaction details.
+ """
+ psbt = self._psbt_with_change()
+ psbt.outputs.append(create_output(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_RECEIVE, 50_000))
+
+ self._load_psbt_for_signing(psbt)
+
+ self.run_sequence([
+ FlowStep(psbt_views.PSBTSelectSeedView, screen_return_value=0),
+ FlowStep(psbt_views.PSBTOverviewView),
+ FlowStep(psbt_views.PSBTWarningView, button_data_selection=psbt_views.PSBTWarningView.CONTINUE),
+ FlowStep(psbt_views.PSBTWarningView, is_redirect=True),
+ FlowStep(psbt_views.PSBTMathView),
+ ])
+
+ assert self.controller.psbt_parser.warnings == [PSBTParser.WARNING__HIGH_FEE]
+
+
+ def test_no_change_warning_alone_continues_to_the_transaction_details(self):
+ """
+ The psbt spends its whole 1 BTC input on a single recipient, apart from a 10,000
+ sat fee, so no change comes back.
+
+ The user should see the no change warning and then the transaction details.
+ """
+ psbt = PSBT.parse(a2b_base64(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_1_INPUT))
+ input_amount = psbt.inputs[0].utxo.value
+ psbt.outputs.append(create_output(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_RECEIVE, input_amount - 10_000))
+
+ self._load_psbt_for_signing(psbt)
+
+ self.run_sequence([
+ FlowStep(psbt_views.PSBTSelectSeedView, screen_return_value=0),
+ FlowStep(psbt_views.PSBTOverviewView),
+ FlowStep(psbt_views.PSBTWarningView, button_data_selection=psbt_views.PSBTWarningView.CONTINUE),
+ FlowStep(psbt_views.PSBTWarningView, is_redirect=True),
+ FlowStep(psbt_views.PSBTMathView),
+ ])
+
+ assert self.controller.psbt_parser.warnings == [PSBTParser.WARNING__NO_CHANGE]
+
+
+ def test_high_fee_warning_continues_to_the_no_change_warning(self):
+ """
+ The psbt pays a single 50,000 sat recipient out of a 1 BTC input and sends no
+ change back, so nearly all of the input goes to the fee.
+
+ The user should see the high fee warning, then the no change warning, and then the
+ transaction details.
+ """
+ psbt = PSBT.parse(a2b_base64(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_1_INPUT))
+ psbt.outputs.append(create_output(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_RECEIVE, 50_000))
+
+ self._load_psbt_for_signing(psbt)
+
+ self.run_sequence([
+ FlowStep(psbt_views.PSBTSelectSeedView, screen_return_value=0),
+ FlowStep(psbt_views.PSBTOverviewView),
+ FlowStep(psbt_views.PSBTWarningView, button_data_selection=psbt_views.PSBTWarningView.CONTINUE),
+ FlowStep(psbt_views.PSBTWarningView, button_data_selection=psbt_views.PSBTWarningView.CONTINUE),
+ FlowStep(psbt_views.PSBTWarningView, is_redirect=True),
+ FlowStep(psbt_views.PSBTMathView),
+ ])
+
+ assert self.controller.psbt_parser.warnings == [
+ PSBTParser.WARNING__HIGH_FEE,
+ PSBTParser.WARNING__NO_CHANGE,
+ ]
### tests/test_psbt_parser.py
@@ -12,21 +12,22 @@
from embit.descriptor import Descriptor
from embit.script import Script
-from seedsigner.models.psbt_parser import (OPCODES, PSBTExtraneousInputScriptError,
- PSBTInputAmountVerificationError, PSBTInputOwnershipClaimError,
- PSBTInputOwnershipContradictionError, PSBTInputScriptMismatchError,
- PSBTMalformedOpReturnError, PSBTMissingInputScriptError, PSBTMissingInputUtxoError,
- PSBTMixedDerivationPathTypesError, PSBTNegativeFeeError, PSBTOutputOwnershipClaimError,
- PSBTOutputOwnershipContradictionError, PSBTParser, PSBTSeedCannotSignError,
- PSBTSurplusDerivationPathsError, PSBTUnsupportedDerivationPathError,
- PSBTUnsupportedScriptPathError)
+from seedsigner.models.psbt_parser import (OPCODES, PSBTChangeDerivationPathError,
+ PSBTExtraneousInputScriptError, PSBTInputAmountVerificationError,
+ PSBTInputOwnershipClaimError, PSBTInputOwnershipContradictionError,
+ PSBTInputScriptMismatchError, PSBTMalformedOpReturnError, PSBTMissingInputScriptError,
+ PSBTMissingInputUtxoError, PSBTMixedDerivationPathTypesError, PSBTNegativeFeeError,
+ PSBTOutputOwnershipClaimError, PSBTOutputOwnershipContradictionError, PSBTParser,
+ PSBTSeedCannotSignError, PSBTSurplusDerivationPathsError,
+ PSBTUnsupportedDerivationPathError, PSBTUnsupportedScriptPathError,
+ PSBTUnverifiableMixedInputBasePathsError)
from seedsigner.models.seed import Seed
from seedsigner.models.settings_definition import SettingsConstants
from psbt_testing_util import (NUMS_INTERNAL_KEY, PSBTTestData, claim_seed_owns_key,
create_op_return_output, create_op_return_psbt, create_output, foreign_public_key,
- op_return_script, p2tr_with_script_tree, root_for_seed, set_input_locking_script,
- tapleaf_hash)
+ op_return_script, p2tr_with_script_tree, repoint_change, root_for_seed,
+ set_input_locking_script, tapleaf_hash)
@@ -705,7 +706,8 @@ def test_p2tr_change_detection():
'output_index': 0,
'address': 'bcrt1prz4g6saush37epdwhvwpu78td3q7yfz3xxz37axlx7udck6wracq3rwq30',
'amount': 2871443918,
- 'verified_derivation_path': bip32.parse_path('m/86h/1h/0h/1/1')}
+ 'verified_derivation_path': bip32.parse_path('m/86h/1h/0h/1/1'),
+ 'address_index_beyond_window': False}
]
assert pp.spend_amount == 319049328
assert pp.change_amount == 2871443918
@@ -864,7 +866,8 @@ def test_parse_op_return_content():
'output_index': 0,
'address': 'bcrt1qvwkhakqhz7m7kmz6332avatsmdy32m644g86vv',
'amount': 99992296,
- 'verified_derivation_path': bip32.parse_path("m/84h/1h/0h/0/2")}
+ 'verified_derivation_path': bip32.parse_path("m/84h/1h/0h/0/2"),
+ 'address_index_beyond_window': False}
]
assert psbt_parser.spend_amount == 0 # This is a self-spend; no value being spent, other than the tx fee
assert psbt_parser.change_amount == 99992296
@@ -1202,6 +1205,123 @@ def _psbt_with_change(self, input_base64: str = None, change_hex: str = None) ->
return psbt
+ def _input_derivation_path(self, input_base64: str = None) -> str:
+ """
+ Returns the derivation path the fixture's single input spends from, as recorded in
+ that input's derivation path entry for this seed. Defaults to the
+ SINGLE_SIG_NATIVE_SEGWIT_1_INPUT fixture.
+ """
+ if input_base64 is None:
+ input_base64 = PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_1_INPUT
+
+ inp = PSBT.parse(a2b_base64(input_base64)).inputs[0]
+
+ # Gather the input's entries
+ derivation_path_objs = list(inp.bip32_derivations.values())
+
+ # Taproot entries live in their own map, each paired with the leaf hashes its key
+ # appears in.
+ for leaf_hashes, derivation_path_obj in inp.taproot_bip32_derivations.values():
+ derivation_path_objs.append(derivation_path_obj)
+
+ # A multisig input has an entry for each cosigner, so pick out this seed's
+ for derivation_path_obj in derivation_path_objs:
+ if derivation_path_obj.fingerprint == self._root().my_fingerprint:
+ return bip32.path_to_str(derivation_path_obj.derivation)
+
+
+ def _sibling_path(self, input_derivation_path: str, branch: int, address_index: int) -> str:
+ """
+ Returns input_derivation_path with its "branch" and "address_index" replaced.
+
+ Those are always the last two indices of the derivation path, regardless of the
+ base path structure:
+ [base path] / "branch" / "address_index"
+ """
+ base_path_levels = input_derivation_path.split("/")[:-2]
+ return "/".join(base_path_levels + [str(branch), str(address_index)])
+
+
+ def _add_own_input(self, psbt: PSBT, derivation_path: str, include_non_witness_utxo: bool = False):
+ """
+ Adds a second input owned by this seed, at derivation_path, with the same script
+ type as the first input. Lets a test spend from a second base path.
+
+ Built by copying the first input and repointing it to our key at that path. A
+ multisig copy moves all of the fixtures' cosigners to that path.
+
+ By default the new segwit input will only have a witness_utxo. When
+ include_non_witness_utxo is set, the new input will also have a non_witness_utxo,
+ modified from the first input's non_witness_utxo.
+
+ Note: the new input's non_witness_utxo is a made-up previous transaction. The
+ parse can't tell it from a real one, so it serves its purpose for these tests.
+ """
+ own_input = deepcopy(psbt.inputs[0])
+ script_type = PSBTParser._get_script_type(own_input, own_input.script_pubkey)
+
+ # Drop the entries describing the old path
+ own_input.bip32_derivations.clear()
+ own_input.taproot_bip32_derivations.clear()
+
+ # Multisig input: build the new input from every cosigner's key
+ if script_type in ("p2wsh", "p2sh-p2wsh", "p2sh"):
+ cosigner_public_keys = []
+ for cosigner_seed in PSBTTestData.multisig_cosigner_seeds:
+ public_key = root_for_seed(cosigner_seed).derive(derivation_path).get_public_key()
+ cosigner_public_keys.append(public_key)
+ claim_seed_owns_key(own_input, derivation_path, public_key, seed=cosigner_seed)
+
+ # The fixtures are sortedmulti, so keep the keys in lexicographic order
+ cosigner_public_keys.sort(key=lambda public_key: public_key.sec())
+ multisig_script = script.multisig(2, cosigner_public_keys)
+
+ # Wrap the script the same way as the first input
+ if script_type == "p2wsh":
+ own_input.witness_script = multisig_script
+ locking_script = script.p2wsh(multisig_script)
+ elif script_type == "p2sh-p2wsh":
+ own_input.witness_script = multisig_script
+ own_input.redeem_script = script.p2wsh(multisig_script)
+ locking_script = script.p2sh(own_input.redeem_script)
+ else:
+ own_input.redeem_script = multisig_script
+ locking_script = script.p2sh(multisig_script)
+
+ # Single sig input
+ else:
+ # Our key alone, claimed under our fingerprint
+ public_key = self._root().derive(derivation_path).get_public_key()
+ is_taproot = script_type == "p2tr"
+ claim_seed_owns_key(own_input, derivation_path, public_key, is_taproot=is_taproot)
+
+ if is_taproot:
+ # Our key is the internal key of a key path spend
+ own_input.taproot_internal_key = PublicKey.from_xonly(public_key.xonly())
+ elif script_type == "p2sh-p2wpkh":
+ own_input.redeem_script = script.p2wpkh(public_key)
+
+ locking_script = PSBTParser._build_singlesig_script(script_type, public_key)
+
+ if script_type in ("p2pkh", "p2sh"):
+ # A legacy input describes its utxo by the previous transaction. So make that
+ # transaction pay the new script, then point the input at its new txid. The
+ # result is a made-up previous transaction.
+ own_input.non_witness_utxo.vout[own_input.vout].script_pubkey = locking_script
+ own_input.txid = own_input.non_witness_utxo.txid()
+ elif include_non_witness_utxo:
+ # A segwit input may also describe its utxo by the previous transaction. So
+ # make that transaction pay the new script, point the input at its new txid,
+ # and match the witness_utxo to it.
+ own_input.non_witness_utxo.vout[own_input.vout].script_pubkey = locking_script
+ own_input.txid = own_input.non_witness_utxo.txid()
+ own_input.witness_utxo.script_pubkey = locking_script
+ else:
+ set_input_locking_script(own_input, locking_script)
+
+ psbt.inputs.append(own_input)
+
+
def _foreign_multisig_script(self) -> script.Script:
"""A 2-of-3 built entirely from someone else's keys."""
return script.multisig(2, [foreign_public_key(f"m/48h/1h/0h/2h/0/{i}") for i in range(3)])
@@ -1214,6 +1334,19 @@ def _parse(self, psbt: PSBT) -> PSBTParser:
return PSBTParser(psbt, self.seed, network=SettingsConstants.REGTEST)
+ def _verified_input_derivation_paths(self, psbt_parser: PSBTParser) -> list[list[int]]:
+ """
+ Returns every derivation path the parse verified on the psbt's inputs, as one list
+ in input order. Each path is an index list, so it compares directly against
+ bip32.parse_path().
+ """
+ derivation_paths = []
+ for verified_derivation_paths in psbt_parser.verified_input_derivation_paths:
+ for verified_derivation_path in verified_derivation_paths:
+ derivation_paths.append(verified_derivation_path.derivation)
+ return derivation_paths
+
+
class TestPSBTParserSeedOwnership(PSBTParserOwnershipTestBase):
"""
@@ -1525,12 +1658,13 @@ def claim_a_stranger_on_the_change(psbt: PSBT):
self._parse(psbt)
- def test__parse__reports_the_first_held_finding(self):
+ def test__parse__reports_a_held_input_finding_before_a_held_output_finding(self):
"""
- The psbt carries two findings milder than an attack: a false claim on its input,
- found while the inputs are read, and a second derivation path entry on its change
- output, found later while the outputs are read. The parse should report the one
- it found first, PSBTInputOwnershipClaimError.
+ The parse reports a held input finding before a held output finding.
+
+ The psbt carries a false claim on its input and a second derivation path entry on
+ its change output. The parse holds both findings and should report the input's
+ finding, PSBTInputOwnershipClaimError.
"""
decoy_derivation_path = "m/84h/1h/0h/1/9"
decoy_public_key = self._root().derive(decoy_derivation_path).get_public_key()
@@ -1543,6 +1677,57 @@ def test__parse__reports_the_first_held_finding(self):
self._parse(psbt)
+ def test__parse__reports_a_held_input_finding_before_evaluating_change(self):
+ """
+ The parse reports a held input finding before it evaluates the change.
+
+ The psbt's only input carries a false claim in addition to its honest one. The
+ psbt also has an honest change output. The false claim makes the parse discard
+ every claim on the input, the honest one included.
+
+ The change rules measure each change output against our inputs. The only input
+ here has just been discarded. So the false claim is the one real problem with this
+ psbt. The parse should raise the held PSBTInputOwnershipClaimError first,
+ preventing any attempt to evaluate the change.
+ """
+ psbt = self._psbt_with_change()
+ claim_seed_owns_key(psbt.inputs[0], "m/84h/1h/0h/0/0", foreign_public_key())
+
+ with patch.object(PSBTParser, "_evaluate_change_derivation_paths") as evaluate_change_derivation_paths:
+ with pytest.raises(PSBTInputOwnershipClaimError):
+ self._parse(psbt)
+
+ evaluate_change_derivation_paths.assert_not_called()
+
+
+ def test__parse__evaluates_change_before_reporting_a_held_output_finding(self):
+ """
+ The parse evaluates the change before it reports a held output finding.
+
+ The psbt's change output pays our key on "branch" 2 of the input's base path,
+ which the change path rules refuse. A second output carries a surplus derivation
+ path entry for our seed, a finding the parse holds. The parse should raise
+ PSBTChangeDerivationPathError rather than the held
+ PSBTSurplusDerivationPathsError.
+ """
+ input_derivation_path = self._input_derivation_path()
+ change_derivation_path = self._sibling_path(input_derivation_path, branch=2, address_index=0)
+
+ psbt = self._psbt_with_change()
+ repoint_change(psbt, change_derivation_path)
+
+ # A second output claiming two of our keys
+ surplus_output = create_output(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_RECEIVE, 5_000)
+ first_derivation_path = self._sibling_path(input_derivation_path, branch=0, address_index=0)
+ second_derivation_path = self._sibling_path(input_derivation_path, branch=0, address_index=1)
+ claim_seed_owns_key(surplus_output, first_derivation_path, self._root().derive(first_derivation_path).get_public_key())
+ claim_seed_owns_key(surplus_output, second_derivation_path, self._root().derive(second_derivation_path).get_public_key())
+ psbt.outputs.append(surplus_output)
+
+ with pytest.raises(PSBTChangeDerivationPathError):
+ self._parse(psbt)
+
+
def test__parse__rejects_a_forged_taproot_claim(self):
"""
A false taproot claim is rejected the same way as an ecdsa one: the input-scope
@@ -3292,7 +3477,7 @@ class TestPSBTParserInputOwnership(PSBTParserOwnershipTestBase):
really derive a claimed key, but it's the script the input commits to that decides
which keys can spend it.
- These tests cover claims of ours that the committed script does not use. They also
+ These tests cover claims on our keys that the committed script does not use. They also
cover the taproot claims whose check needs the input's merkle root.
"""
def test__parse__refuses_a_true_claim_planted_on_another_partys_input(self):
@@ -3450,7 +3635,7 @@ def test__parse__drops_an_internal_key_claim_when_the_merkle_root_is_left_out(se
cannot rebuild the address, so the claim is neither confirmed nor contradicted.
The parse should drop the claim, leaving that input with no verified derivation
- paths. With another input of ours, the psbt should still parse.
+ paths. With another of our inputs, the psbt should still parse.
"""
internal_derivation_path = "m/86h/1h/0h/0/0"
internal_public_key = self._root().derive(internal_derivation_path).get_public_key()
@@ -3514,3 +3699,755 @@ def test__parse__refuses_an_input_this_seed_can_sign_only_through_a_script_path(
with pytest.raises(PSBTUnsupportedScriptPathError):
self._parse(psbt)
+
+
+
+class TestPSBTParserChangeDerivationPathRules(PSBTParserOwnershipTestBase):
+ """
+ The change path rules decide where change may come back to.
+
+ By the time these rules run, the parse has already proved that a change output pays
+ this seed at the path the psbt claims. What is left is whether that path is somewhere
+ the user's coordinator software would ever look. Violations of the change path rules
+ lead to rejecting the psbt outright. But failing the address index window check only
+ flags the output for the user to judge.
+
+ Most of these tests run on every supported single-sig and multisig script type.
+ """
+ # One fixture per supported script type: a psbt with a single input, and a change
+ # output that shares the input's base path.
+ MULTISIG_WALLETS = [
+ (PSBTTestData.MULTISIG_NATIVE_SEGWIT_1_INPUT, PSBTTestData.MULTISIG_NATIVE_SEGWIT_CHANGE),
+ (PSBTTestData.MULTISIG_NESTED_SEGWIT_1_INPUT, PSBTTestData.MULTISIG_NESTED_SEGWIT_CHANGE),
+ (PSBTTestData.MULTISIG_LEGACY_P2SH_1_INPUT, PSBTTestData.MULTISIG_LEGACY_P2SH_CHANGE),
+ ]
+ WALLETS = [
+ (PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_1_INPUT, PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_CHANGE),
+ (PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_1_INPUT, PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_CHANGE),
+ (PSBTTestData.SINGLE_SIG_TAPROOT_1_INPUT, PSBTTestData.SINGLE_SIG_TAPROOT_CHANGE),
+ (PSBTTestData.SINGLE_SIG_LEGACY_P2PKH_1_INPUT, PSBTTestData.SINGLE_SIG_LEGACY_P2PKH_CHANGE),
+ ] + MULTISIG_WALLETS
+
+
+ def _repoint_legacy_multisig_input(self, psbt: PSBT, derivation_path: str):
+ """
+ Moves the psbt's legacy p2sh multisig input to derivation_path, still owned by
+ this seed. Lets a test choose the base path the psbt spends from, such as one with
+ an extra "wallet" level.
+
+ Rebuilds its redeem script as the same 2-of-3 with every cosigner moved to the new
+ path, then edits the previous transaction to pay the new redeem script.
+ """
+ legacy_input = psbt.inputs[0]
+ legacy_input.bip32_derivations.clear()
+
+ # Each cosigner's key at the new path, claimed under that cosigner's fingerprint
+ cosigner_public_keys = []
+ for cosigner_seed in PSBTTestData.multisig_cosigner_seeds:
+ public_key = root_for_seed(cosigner_seed).derive(derivation_path).get_public_key()
+ cosigner_public_keys.append(public_key)
+ claim_seed_owns_key(legacy_input, derivation_path, public_key, seed=cosigner_seed)
+
+ # The fixtures are sortedmulti, so keep the keys in lexicographic order
+ cosigner_public_keys.sort(key=lambda public_key: public_key.sec())
+ legacy_input.redeem_script = script.multisig(2, cosigner_public_keys)
+
+ # Make the coin being spent pay the new redeem script
+ previous_output = legacy_input.non_witness_utxo.vout[legacy_input.vout]
+ previous_output.script_pubkey = script.p2sh(legacy_input.redeem_script)
+
+ # The input identifies its coin by the previous transaction's txid, which the edit
+ # above changed, so update the input to match.
+ legacy_input.txid = legacy_input.non_witness_utxo.txid()
+
+
+ def test__parse__refuses_change_to_a_base_path_this_transaction_does_not_spend_from(self):
+ """
+ Change may only come back to a base path that one of our inputs spends from.
+
+ The psbt pays change to our key at a different base path. Two variants are
+ tested:
+ * the input's base path with its last level changed.
+ * the input's base path with an extra level added to the end.
+
+ The parse should refuse each with a PSBTChangeDerivationPathError. The problematic
+ derivation path should be included in the exception object.
+ """
+ for input_base64, change_hex in self.WALLETS:
+ input_derivation_path = self._input_derivation_path(input_base64)
+
+ # The input's base path with its last level changed
+ base_path_levels = input_derivation_path.split("/")[:-2]
+ base_path_levels[-1] = "7h"
+ change_at_other_base_path = "/".join(base_path_levels + ["1", "0"])
+
+ psbt = self._psbt_with_change(input_base64, change_hex)
+ repoint_change(psbt, change_at_other_base_path)
+
+ with pytest.raises(PSBTChangeDerivationPathError) as exc_info:
+ self._parse(psbt)
+ assert exc_info.value.derivation_path == bip32.parse_path(change_at_other_base_path)
+
+ # The input's base path with an extra level added to the end
+ input_base_path_levels = input_derivation_path.split("/")[:-2]
+ change_at_extended_base_path = "/".join(input_base_path_levels + ["7", "1", "0"])
+
+ repoint_change(psbt, change_at_extended_base_path)
+
+ with pytest.raises(PSBTChangeDerivationPathError) as exc_info:
+ self._parse(psbt)
+ assert exc_info.value.derivation_path == bip32.parse_path(change_at_extended_base_path)
+
+
+ def test__parse__counts_a_non_hardened_wallet_level_as_part_of_the_base_path(self):
+ """
+ The base path is everything before the "branch" and the "address_index", which may
+ include a non-hardened "wallet" level such as:
+ m/45h/0h/0h/<wallet>/<branch>/<address_index>
+
+ Some multisig wallets add such a non-hardened level after each cosigner's account
+ xpub, one value per wallet, so new wallets can be created from account xpubs the
+ cosigners already exported (e.g. the Unchained collaborative custody vault
+ format). For the above example, the user would supply an xpub at m/45h/0h/0h with
+ new wallet keys being derived for them at "wallet" level indices.
+
+ The psbt spends from "wallet" 3. Change coming back to "wallet" 3 should be
+ accepted. Change sent to "wallet" 7 of the same account xpubs should be refused
+ with PSBTChangeDerivationPathError.
+ """
+ input_derivation_path = "m/45h/0h/0h/3/0/12"
+ change_derivation_path = "m/45h/0h/0h/3/1/4"
+ sibling_wallet_derivation_path = "m/45h/0h/0h/7/1/0"
+
+ psbt = self._psbt_with_change(PSBTTestData.MULTISIG_LEGACY_P2SH_1_INPUT, PSBTTestData.MULTISIG_LEGACY_P2SH_CHANGE)
+ self._repoint_legacy_multisig_input(psbt, input_derivation_path)
+
+ # The fixture's global xpubs are for its original m/45h base path, so drop them
+ # rather than leave stale ones in place.
+ psbt.xpubs.clear()
+
+ repoint_change(psbt, change_derivation_path)
+ psbt_parser = self._parse(psbt)
+ assert self._verified_input_derivation_paths(psbt_parser) == [bip32.parse_path(input_derivation_path)]
+ assert psbt_parser.change_amount == 10_000
+
+ # Different "wallet" index means the change is going to a different base path. So
+ # the psbt should now be rejected.
+ repoint_change(psbt, sibling_wallet_derivation_path)
+ with pytest.raises(PSBTChangeDerivationPathError) as exc_info:
+ self._parse(psbt)
+ assert exc_info.value.derivation_path == bip32.parse_path(sibling_wallet_derivation_path)
+
+
+ def test__parse__refuses_change_on_a_branch_no_coordinator_scans(self):
+ """
+ Change may only come back on the receive "branch" (0) or the change "branch" (1).
+
+ The psbt pays change to our key on "branch" 2 of the input's base path. The parse
+ should refuse it with PSBTChangeDerivationPathError.
+ """
+ for input_base64, change_hex in self.WALLETS:
+ input_derivation_path = self._input_derivation_path(input_base64)
+ change_derivation_path = self._sibling_path(input_derivation_path, branch=2, address_index=0)
+
+ psbt = self._psbt_with_change(input_base64, change_hex)
+ repoint_change(psbt, change_derivation_path)
+
+ with pytest.raises(PSBTChangeDerivationPathError) as exc_info:
+ self._parse(psbt)
+ assert exc_info.value.derivation_path == bip32.parse_path(change_derivation_path)
+
+
+ def test__parse__refuses_change_at_a_hardened_address_index(self):
+ """
+ Change may only come back at a non-hardened "address_index", on the change
+ "branch" and the receive "branch" alike.
+
+ The psbt pays our key at a hardened "address_index", first on the change "branch"
+ and then on the receive "branch". The parse should refuse both with
+ PSBTChangeDerivationPathError.
+ """
+ for input_base64, change_hex in self.WALLETS:
+ input_derivation_path = self._input_derivation_path(input_base64)
+ psbt = self._psbt_with_change(input_base64, change_hex)
+
+ # On the change "branch"
+ change_derivation_path = self._sibling_path(input_derivation_path, branch=1, address_index=bip32.HARDENED_INDEX)
+ repoint_change(psbt, change_derivation_path)
+ with pytest.raises(PSBTChangeDerivationPathError) as exc_info:
+ self._parse(psbt)
+ assert exc_info.value.derivation_path == bip32.parse_path(change_derivation_path)
+
+ # On the receive "branch", as a self-transfer
+ receive_derivation_path = self._sibling_path(input_derivation_path, branch=0, address_index=bip32.HARDENED_INDEX)
+ repoint_change(psbt, receive_derivation_path)
+ with pytest.raises(PSBTChangeDerivationPathError) as exc_info:
+ self._parse(psbt)
+ assert exc_info.value.derivation_path == bip32.parse_path(receive_derivation_path)
+
+
+ def test__parse__refuses_change_at_a_derivation_path_too_short_for_a_wallet(self):
+ """
+ Change may only come back at a derivation path long enough to hold both a
+ "branch" and an "address_index".
+
+ The psbt pays change to our key at the one-level derivation path m/5. The parse
+ should refuse it with PSBTChangeDerivationPathError.
+ """
+ change_derivation_path = "m/5"
+
+ psbt = self._psbt_with_change()
+ repoint_change(psbt, change_derivation_path)
+
+ with pytest.raises(PSBTChangeDerivationPathError) as exc_info:
+ self._parse(psbt)
+ assert exc_info.value.derivation_path == bip32.parse_path(change_derivation_path)
+
+
+ def test__parse__refuses_a_multisig_output_at_an_unscanned_path_with_or_without_global_xpubs(self):
+ """
+ A multisig output that pays our key must pass the change path rules, whether the
+ parse counts it as change or as a spend.
+
+ The psbt pays one of our multisig outputs at a derivation path that fails the
+ change path rules. Two failing paths are tested:
+ * a different base path
+ * a hardened "address_index"
+
+ The presence or absence of global xpubs can determine if multisig outputs are
+ considered change or spend.
+ * With the global xpubs:
+ * In either test scenario the output is counted as a spend because the parser
+ cannot match the output's cosigners with the global xpubs:
+ * At a different base path, the output's key paths don't start with any
+ global xpub's path.
+ * At a hardened "address_index", the key paths do start with the global
+ xpubs' path, but an xpub can only derive non-hardened levels.
+ * The one flaw in each failing path has two effects: the output becomes a
+ spend and it fails the change path rules.
+ * With the global xpubs removed: the output is presumed change; the parser has
+ no cosigners to compare with the inputs' cosigners.
+
+ The parser should reject all four scenarios (both change path failures, with and
+ without global xpubs) with PSBTChangeDerivationPathError.
+ """
+ for input_base64, change_hex in self.MULTISIG_WALLETS:
+ input_derivation_path = self._input_derivation_path(input_base64)
+
+ # The input's base path with its last level changed
+ base_path_levels = input_derivation_path.split("/")[:-2]
+ base_path_levels[-1] = "7h"
+ change_at_other_base_path = "/".join(base_path_levels + ["1", "0"])
+
+ hardened_index_path = self._sibling_path(input_derivation_path, branch=1, address_index=bip32.HARDENED_INDEX)
+
+ for change_derivation_path in (change_at_other_base_path, hardened_index_path):
+ psbt = self._psbt_with_change(input_base64, change_hex)
+ repoint_change(psbt, change_derivation_path)
+
+ # Sanity check the setup: the psbt supplies global xpubs, but they cannot
+ # resolve the output's cosigners.
+ out = psbt.outputs[0]
+ assert len(psbt.xpubs) == 3
+ assert "cosigners" not in PSBTParser._get_policy(out, out.script_pubkey, psbt.xpubs, None)
+
+ # Classified as an external spend to a different multisig, but our seed is
+ # one of the cosigners so the output is still put through the same
+ # change path checks that a change output would get.
+ with pytest.raises(PSBTChangeDerivationPathError) as exc_info:
+ self._parse(psbt)
+ assert exc_info.value.derivation_path == bip32.parse_path(change_derivation_path)
+
+ # Remove the global xpubs. The output will be presumed to be change. Its
+ # derivation path fails the same change path checks.
+ psbt.xpubs.clear()
+ with pytest.raises(PSBTChangeDerivationPathError) as exc_info:
+ self._parse(psbt)
+ assert exc_info.value.derivation_path == bip32.parse_path(change_derivation_path)
+
+
+ def test__parse__flags_rather_than_refuses_change_far_past_the_inputs_address_indices(self):
+ """
+ Change may come back at an "address_index" up to CHANGE_ADDRESS_INDEX_WINDOW past
+ the input's "address_index". Change past that is flagged for the user to decide
+ on, but still counted as change. The window applies the same way to a
+ self-transfer, which sends funds back to one of our receive addresses rather than
+ to the change "branch".
+ """
+ for input_base64, change_hex in self.WALLETS:
+ input_derivation_path = self._input_derivation_path(input_base64)
+ input_address_index = int(input_derivation_path.split("/")[-1])
+ last_index_within_window = input_address_index + PSBTParser.CHANGE_ADDRESS_INDEX_WINDOW
+ psbt = self._psbt_with_change(input_base64, change_hex)
+
+ # On the change "branch". Exactly CHANGE_ADDRESS_INDEX_WINDOW past the input's
+ # "address_index" is still within the acceptable range, so it is left
+ # unflagged.
+ repoint_change(psbt, self._sibling_path(input_derivation_path, branch=1, address_index=last_index_within_window))
+ psbt_parser = self._parse(psbt)
+ assert psbt_parser.change_amount == 10_000
+ assert psbt_parser.change_data[0]["address_index_beyond_window"] is False
+
+ # One index further is past the window: flagged, but still counted as change
+ repoint_change(psbt, self._sibling_path(input_derivation_path, branch=1, address_index=last_index_within_window + 1))
+ psbt_parser = self._parse(psbt)
+ assert psbt_parser.change_amount == 10_000
+ assert psbt_parser.change_data[0]["address_index_beyond_window"] is True
+
+ # And now a self-transfer that is within the window. Reminder: the parser
+ # treats self-transfers as "change" in its internal accounting.
+ repoint_change(psbt, self._sibling_path(input_derivation_path, branch=0, address_index=last_index_within_window))
+ psbt_parser = self._parse(psbt)
+ assert psbt_parser.change_amount == 10_000
+ assert psbt_parser.change_data[0]["address_index_beyond_window"] is False
+
+ # And a self-transfer that is beyond the window
+ repoint_change(psbt, self._sibling_path(input_derivation_path, branch=0, address_index=last_index_within_window + 1))
+ psbt_parser = self._parse(psbt)
+ assert psbt_parser.change_amount == 10_000
+ assert psbt_parser.change_data[0]["address_index_beyond_window"] is True
+
+
+ def test__parse__flags_each_distant_change_output_and_warns_once(self):
+ """
+ Each change output past the change address index window is flagged. The window
+ warning is recorded once, however many change outputs are flagged.
+
+ The psbt has two change outputs, both past the window measured from the input's
+ "address_index". The parse should flag both change outputs and record
+ WARNING__CHANGE_ADDRESS_INDEX_BEYOND_WINDOW once.
+ """
+ input_derivation_path = self._input_derivation_path()
+ input_address_index = int(input_derivation_path.split("/")[-1])
+ last_index_within_window = input_address_index + PSBTParser.CHANGE_ADDRESS_INDEX_WINDOW
+
+ # The first change output
+ psbt = self._psbt_with_change()
+ repoint_change(psbt, self._sibling_path(input_derivation_path, branch=1, address_index=last_index_within_window + 1))
+
+ # A second change output: a copy of the first, placed first so that
+ # repoint_change moves it.
+ psbt.outputs.insert(0, deepcopy(psbt.outputs[0]))
+ repoint_change(psbt, self._sibling_path(input_derivation_path, branch=1, address_index=last_index_within_window + 2))
+
+ psbt_parser = self._parse(psbt)
+ assert len(psbt_parser.change_data) == 2
+
+ # Both change outputs should be flagged
+ assert psbt_parser.change_data[0]["address_index_beyond_window"] is True
+ assert psbt_parser.change_data[1]["address_index_beyond_window"] is True
+
+ # But the warnings list should only record this warning type once
+ assert psbt_parser.warnings == [PSBTParser.WARNING__CHANGE_ADDRESS_INDEX_BEYOND_WINDOW]
+
+
+ def test__parse__measures_the_window_from_the_smallest_input_index_for_the_base_path(self):
+ """
+ The change address index window is measured from the smallest "address_index"
+ among our inputs that share the change output's base path, regardless of the
+ order the psbt lists the inputs in.
+ """
+ # This fixture spends inputs at [base path]/1/6 and [base path]/1/0, in that
+ # order. Verify that input order doesn't matter when determining the window.
+ fixture_input_address_indices = [6, 0]
+ last_index_within_window = min(fixture_input_address_indices) + PSBTParser.CHANGE_ADDRESS_INDEX_WINDOW
+
+ for input_address_indices in (fixture_input_address_indices, list(reversed(fixture_input_address_indices))):
+ psbt = PSBT.parse(a2b_base64(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_2_INPUTS))
+ if input_address_indices != fixture_input_address_indices:
+ psbt.inputs.reverse()
+ assert [list(inp.bip32_derivations.values())[0].derivation[-1] for inp in psbt.inputs] == input_address_indices
+
+ # Within the window, when measured from the smallest input index
+ repoint_change(psbt, f"m/84h/1h/0h/1/{last_index_within_window}", seed=PSBTTestData.two_input_seed)
+ psbt_parser = PSBTParser(psbt, PSBTTestData.two_input_seed, network=SettingsConstants.REGTEST)
+ assert psbt_parser.change_data[0]["address_index_beyond_window"] is False
+
+ # Beyond that window
+ repoint_change(psbt, f"m/84h/1h/0h/1/{last_index_within_window + 1}", seed=PSBTTestData.two_input_seed)
+ psbt_parser = PSBTParser(psbt, PSBTTestData.two_input_seed, network=SettingsConstants.REGTEST)
+ assert psbt_parser.change_data[0]["address_index_beyond_window"] is True
+
+
+ def test__parse__leaves_hardened_input_indices_out_of_the_window(self):
+ """
+ The change address index window is measured from our inputs' non-hardened
+ "address_index" values only, since change can only use a non-hardened
+ "address_index".
+
+ The psbt spends two of our utxos from one base path: the fixture's utxo at
+ "address_index" 3 and a second at the hardened "address_index" 5h. So the window
+ should be measured from index 3 alone. The change at index 20,000 is past that
+ window, so the parse should flag it.
+ """
+ # The fixture's utxo, and another of our utxos at a hardened "address_index" with
+ # the same base path
+ fixture_input_derivation_path = self._input_derivation_path()
+ fixture_address_index = int(fixture_input_derivation_path.split("/")[-1])
+ fixture_base_path = "/".join(fixture_input_derivation_path.split("/")[:-2])
+ hardened_input_derivation_path = f"{fixture_base_path}/0/5h"
+
+ beyond_window = 20_000
+ assert beyond_window > fixture_address_index + PSBTParser.CHANGE_ADDRESS_INDEX_WINDOW
+
+ # Sanity check: as a raw number, the hardened index 5h lies far past our window;
+ # if it was allowed to count towards the window, it would yield an enormous cutoff
+ # index.
+ hardened_address_index = bip32.HARDENED_INDEX + 5
+ assert hardened_address_index > fixture_address_index + PSBTParser.CHANGE_ADDRESS_INDEX_WINDOW
+
+ psbt = self._psbt_with_change()
+ self._add_own_input(psbt, hardened_input_derivation_path)
+ repoint_change(psbt, self._sibling_path(fixture_input_derivation_path, branch=1, address_index=beyond_window))
+
+ psbt_parser = self._parse(psbt)
+
+ # Both inputs are ours
+ assert self._verified_input_derivation_paths(psbt_parser) == [
+ bip32.parse_path(fixture_input_derivation_path),
+ bip32.parse_path(hardened_input_derivation_path),
+ ]
+
+ # The window uses the non-hardened input's index as its starting point and so the
+ # change is determined to be beyond the window; the hardened input's enormous
+ # index was not a factor.
+ assert psbt_parser.change_data[0]["address_index_beyond_window"] is True
+
+
+ def test__parse__measures_the_window_from_index_0_when_every_input_address_index_is_hardened(self):
+ """
+ The change address index window is measured from index 0 when all of our inputs
+ at the change's base path have a hardened "address_index".
+
+ The psbt spends one of our utxos, at the hardened "address_index" 5h. Two outcomes
+ are tested:
+ * Change at the last index in the window should be within the window.
+ * Change one index past the window should be flagged.
+ """
+ # Add one of our utxos at a hardened "address_index", then remove the fixture's
+ # input so that the hardened one is our only input
+ fixture_input_derivation_path = self._input_derivation_path()
+ fixture_base_path = "/".join(fixture_input_derivation_path.split("/")[:-2])
+ hardened_input_derivation_path = f"{fixture_base_path}/0/5h"
+
+ psbt = self._psbt_with_change()
+ self._add_own_input(psbt, hardened_input_derivation_path)
+ del psbt.inputs[0]
+
+ # Scenario 1: change at the last index in the window
+ last_index_in_window = PSBTParser.CHANGE_ADDRESS_INDEX_WINDOW
+ repoint_change(psbt, self._sibling_path(fixture_input_derivation_path, branch=1, address_index=last_index_in_window))
+ psbt_parser = self._parse(psbt)
+
+ # The hardened input is our only input
+ assert self._verified_input_derivation_paths(psbt_parser) == [
+ bip32.parse_path(hardened_input_derivation_path),
+ ]
+ assert psbt_parser.change_data[0]["address_index_beyond_window"] is False
+
+ # Scenario 2: change one index past the window
+ repoint_change(psbt, self._sibling_path(fixture_input_derivation_path, branch=1, address_index=last_index_in_window + 1))
+ assert self._parse(psbt).change_data[0]["address_index_beyond_window"] is True
+
+
+ def test__parse__measures_each_base_path_window_from_its_own_inputs(self):
+ """
+ Each base path is viewed as a separate wallet, so a change output going back to
+ that wallet will have the same base path. The address index window for that change
+ output should only be evaluated against the inputs from that same wallet; if
+ there's another input that has a different base path, it should not affect the
+ change output's address index window.
+
+ The psbt spends two of our utxos from different base paths: the fixture's utxo at
+ m/86h/1h/0h/0/0 and a second at m/86h/1h/7h/0/50000. Change at m/86h/1h/0h/1/20000
+ is past the window of the m/86h/1h/0h wallet, so the parse should flag it, even
+ though the m/86h/1h/7h wallet's input is at a larger index.
+
+ However, if the change is instead sent to the m/86h/1h/7h wallet at the same
+ "address_index" (m/86h/1h/7h/1/20000), it is within that wallet's window, so the
+ parse should leave it unflagged.
+ """
+ # The fixture's utxo, and one more of our utxos at a larger "address_index" in
+ # another wallet
+ fixture_input_derivation_path = self._input_derivation_path(PSBTTestData.SINGLE_SIG_TAPROOT_1_INPUT)
+ fixture_address_index = int(fixture_input_derivation_path.split("/")[-1])
+ other_wallet_input_derivation_path = "m/86h/1h/7h/0/50000"
+ other_wallet_address_index = int(other_wallet_input_derivation_path.split("/")[-1])
+
+ change_address_index = 20_000
+ assert change_address_index > fixture_address_index + PSBTParser.CHANGE_ADDRESS_INDEX_WINDOW
+ assert change_address_index <= other_wallet_address_index + PSBTParser.CHANGE_ADDRESS_INDEX_WINDOW
+
+ # Use the taproot fixture; our rules allow spending from multiple base paths from
+ # taproot inputs.
+ psbt = self._psbt_with_change(PSBTTestData.SINGLE_SIG_TAPROOT_1_INPUT, PSBTTestData.SINGLE_SIG_TAPROOT_CHANGE)
+ self._add_own_input(psbt, other_wallet_input_derivation_path)
+
+ # Both inputs are ours
+ assert self._verified_input_derivation_paths(self._parse(psbt)) == [
+ bip32.parse_path(fixture_input_derivation_path),
+ bip32.parse_path(other_wallet_input_derivation_path),
+ ]
+
+ # Scenario 1: Change for the m/86h/1h/0h wallet
+ repoint_change(psbt, self._sibling_path(fixture_input_derivation_path, branch=1, address_index=change_address_index))
+ assert self._parse(psbt).change_data[0]["address_index_beyond_window"] is True
+
+ # Scenario 2: Change for the m/86h/1h/7h wallet
+ repoint_change(psbt, self._sibling_path(other_wallet_input_derivation_path, branch=1, address_index=change_address_index))
+ assert self._parse(psbt).change_data[0]["address_index_beyond_window"] is False
+
+
+
+class TestPSBTParserInputBasePaths(PSBTParserOwnershipTestBase):
+ """
+ A single sig segwit v0 psbt must spend from a single wallet (one base path), unless
+ each of our inputs has a non_witness_utxo. A psbt of any other script type may spend
+ from more than one base path.
+ """
+ SEGWIT_V0_SINGLE_SIG_WALLETS = [
+ (PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_1_INPUT, PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_CHANGE),
+ (PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_1_INPUT, PSBTTestData.SINGLE_SIG_NESTED_SEGWIT_CHANGE),
+ ]
+ OTHER_SCRIPT_TYPE_WALLETS = [
+ (PSBTTestData.MULTISIG_NATIVE_SEGWIT_1_INPUT, PSBTTestData.MULTISIG_NATIVE_SEGWIT_CHANGE),
+ (PSBTTestData.MULTISIG_NESTED_SEGWIT_1_INPUT, PSBTTestData.MULTISIG_NESTED_SEGWIT_CHANGE),
+ (PSBTTestData.SINGLE_SIG_TAPROOT_1_INPUT, PSBTTestData.SINGLE_SIG_TAPROOT_CHANGE),
+ (PSBTTestData.SINGLE_SIG_LEGACY_P2PKH_1_INPUT, PSBTTestData.SINGLE_SIG_LEGACY_P2PKH_CHANGE),
+ (PSBTTestData.MULTISIG_LEGACY_P2SH_1_INPUT, PSBTTestData.MULTISIG_LEGACY_P2SH_CHANGE),
+ ]
+
+
+ def test__parse__refuses_segwit_v0_single_sig_mixed_base_paths(self):
+ """
+ All of our inputs on a single sig segwit v0 psbt must be at the same base path,
+ unless each one has a non_witness_utxo.
+
+ Each psbt spends from two of the seed's base paths: the fixture input's and that
+ base path with an extra level added to the end. The added input only has a
+ witness_utxo. Two outcomes are tested:
+ * Change into either base path should be refused with
+ PSBTUnverifiableMixedInputBasePathsError.
+ * Change into an unrecognized base path should be refused with
+ PSBTChangeDerivationPathError, which outranks
+ PSBTUnverifiableMixedInputBasePathsError.
+ """
+ for input_base64, change_hex in self.SEGWIT_V0_SINGLE_SIG_WALLETS:
+ # The fixture's input spends from the first base path
+ fixture_input_derivation_path = self._input_derivation_path(input_base64)
+ first_base_path = "/".join(fixture_input_derivation_path.split("/")[:-2])
+ second_base_path = f"{first_base_path}/7"
+ unrecognized_base_path = f"{first_base_path}/3"
+
+ psbt = self._psbt_with_change(input_base64, change_hex)
+ self._add_own_input(psbt, f"{second_base_path}/0/2")
+
+ repoint_change(psbt, f"{first_base_path}/1/0")
+ with pytest.raises(PSBTUnverifiableMixedInputBasePathsError):
+ self._parse(psbt)
+
+ repoint_change(psbt, f"{second_base_path}/1/0")
+ with pytest.raises(PSBTUnverifiableMixedInputBasePathsError):
+ self._parse(psbt)
+
+ # This unrecognized_base_path doesn't match the base path of any input, so it
+ # should be rejected as an attack.
+ repoint_change(psbt, f"{unrecognized_base_path}/1/0")
+ with pytest.raises(PSBTChangeDerivationPathError):
+ self._parse(psbt)
+
+
+ def test__parse__accepts_segwit_v0_single_sig_mixed_base_paths_with_non_witness_utxos(self):
+ """
+ Our inputs on a single sig segwit v0 psbt may be at different base paths when
+ each one has a non_witness_utxo.
+
+ Each psbt spends from two of the seed's base paths: the fixture input's and that
+ base path with an extra level added to the end. Both inputs have a
+ non_witness_utxo. Two outcomes are tested:
+ * Change into either base path should be accepted.
+ * Once the fixture input only has a witness_utxo, change should be refused with
+ PSBTUnverifiableMixedInputBasePathsError.
+ """
+ for input_base64, change_hex in self.SEGWIT_V0_SINGLE_SIG_WALLETS:
+ # The fixture's input spends from the first base path
+ fixture_input_derivation_path = self._input_derivation_path(input_base64)
+ first_base_path = "/".join(fixture_input_derivation_path.split("/")[:-2])
+ second_base_path = f"{first_base_path}/7"
+
+ psbt = self._psbt_with_change(input_base64, change_hex)
+ self._add_own_input(psbt, f"{second_base_path}/0/2", include_non_witness_utxo=True)
+
+ repoint_change(psbt, f"{first_base_path}/1/0")
+ assert self._parse(psbt).change_amount == 10_000
+
+ repoint_change(psbt, f"{second_base_path}/1/0")
+ assert self._parse(psbt).change_amount == 10_000
+
+ # Strip the fixture input down to its witness_utxo
+ psbt.inputs[0].non_witness_utxo = None
+ with pytest.raises(PSBTUnverifiableMixedInputBasePathsError):
+ self._parse(psbt)
+
+
+ def test__parse__accepts_mixed_base_paths_for_other_script_types(self):
+ """
+ Change may come back to the base path of any of our inputs on a multisig,
+ taproot, or legacy psbt.
+
+ Each psbt spends from two of the seed's base paths: the fixture input's and that
+ base path with an extra level added to the end. Change into either base path
+ should be accepted.
+ """
+ for input_base64, change_hex in self.OTHER_SCRIPT_TYPE_WALLETS:
+ # The fixture's input spends from the first base path
+ fixture_input_derivation_path = self._input_derivation_path(input_base64)
+ first_base_path = "/".join(fixture_input_derivation_path.split("/")[:-2])
+ second_base_path = f"{first_base_path}/7"
+
+ psbt = self._psbt_with_change(input_base64, change_hex)
+ self._add_own_input(psbt, f"{second_base_path}/0/2")
+
+ # The fixture's global xpubs resolve the first input's cosigners and not the
+ # second's. Drop them so both inputs share one wallet policy.
+ psbt.xpubs.clear()
+
+ repoint_change(psbt, f"{first_base_path}/1/0")
+ assert self._parse(psbt).change_amount == 10_000
+
+ repoint_change(psbt, f"{second_base_path}/1/0")
+ assert self._parse(psbt).change_amount == 10_000
+
+
+
+class TestPSBTParserCollaborativeSpends(PSBTParserOwnershipTestBase):
+ """
+ Payjoins and coinjoins put another party's inputs in the same transaction as ours.
+
+ The change path rules are measured against the inputs this seed spends with, so these
+ tests check two things:
+ * an honest collaborative spend still parses
+ * and the other parties' inputs cannot affect the base paths our own change may come
+ back to.
+ """
+ def _add_foreign_input(self, psbt: PSBT, derivation_path: str = "m/84h/1h/0h/0/0", annotated: bool = False):
+ """
+ Adds another party's input: their utxo, controlled by a key of their own seed.
+
+ Built by copying one of ours and repointing it, which is what keeps its script
+ type, and therefore the shared wallet policy, the same. A collaborative spend
+ mixing script types is refused before any of this by the mixed-inputs check.
+
+ By default the input carries no derivation path entries, as BIP-78 requires of a
+ payjoin. With annotated=True it also carries a derivation path entry for the other
+ party's key at derivation_path, under their seed's fingerprint.
+ """
+ foreign_input = deepcopy(psbt.inputs[0])
+ foreign_input.bip32_derivations.clear()
+ public_key = foreign_public_key(derivation_path)
+ set_input_locking_script(foreign_input, script.p2wpkh(public_key))
+
+ if annotated:
+ claim_seed_owns_key(foreign_input, derivation_path, public_key, seed=PSBTTestData.recipient_seed)
+
+ psbt.inputs.append(foreign_input)
+ return foreign_input
+
+
+ def test__parse__payjoin_parses_and_anchors_only_on_our_own_input(self):
+ """
+ A payjoin receiver's input only adds value to the transaction. The change path
+ rules measure only against our own input.
+
+ The psbt is a payjoin: the receiver adds one of their own coins as a second input,
+ with no derivation path entries, as BIP-78 requires. The parse should add that
+ coin's value to the total input value, count our change as usual, and verify only
+ our own input's derivation path.
+ """
+ our_input_amount = PSBT.parse(a2b_base64(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_1_INPUT)).inputs[0].utxo.value
+
+ psbt = self._psbt_with_change()
+ foreign_input = self._add_foreign_input(psbt)
+
+ psbt_parser = self._parse(psbt)
+
+ assert psbt_parser.num_inputs == 2
+ assert psbt_parser.verified_input_amount == our_input_amount + foreign_input.utxo.value
+ assert psbt_parser.change_amount == 10_000
+
+ # Should only have our one input's derivation path
+ assert self._verified_input_derivation_paths(psbt_parser) == [bip32.parse_path(self._input_derivation_path())]
+
+
+ def test__parse__coinjoin_parses_with_many_foreign_inputs_and_outputs(self):
+ """
+ The other participants' outputs in a coinjoin are ordinary payments out as far as
+ this seed is concerned.
+
+ The psbt is a coinjoin: several other participants' inputs and outputs in addition
+ to ours. The psbt should parse with our change intact and their outputs as spends.
+ """
+ psbt = self._psbt_with_change()
+ for i in range(3):
+ self._add_foreign_input(psbt, derivation_path=f"m/84h/1h/0h/0/{i}")
+ for i in range(3):
+ psbt.outputs.append(create_output(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_RECEIVE, 250_000))
+
+ psbt_parser = self._parse(psbt)
+
+ assert psbt_parser.num_inputs == 4
+ assert psbt_parser.num_change_outputs == 1
+ assert psbt_parser.num_destinations == 3
+ assert psbt_parser.spend_amount == 750_000
+
+ # Should only have our one input's derivation path
+ assert self._verified_input_derivation_paths(psbt_parser) == [bip32.parse_path(self._input_derivation_path())]
+
+
+ def test__parse__a_foreign_input_cannot_affect_the_change_index_window(self):
+ """
+ The change address index window is measured from the "address_index" values of
+ the inputs this seed spends with.
+
+ The psbt adds another party's input at a far larger "address_index" than ours,
+ with the same path shape; only the fingerprint tells their input from ours. Our
+ own input's key is at index 3, so the window ends at 10,003. Change placed past
+ our window should be flagged, even though it is within the other party's.
+ """
+ fixture_input_derivation_path = self._input_derivation_path()
+ fixture_address_index = int(fixture_input_derivation_path.split("/")[-1])
+
+ beyond_window = 20_000
+ assert beyond_window > fixture_address_index + PSBTParser.CHANGE_ADDRESS_INDEX_WINDOW
+
+ # The other party's input shares our input's path shape, at a far larger
+ # "address_index"
+ psbt = self._psbt_with_change()
+ foreign_input_derivation_path = self._sibling_path(fixture_input_derivation_path, branch=0, address_index=beyond_window * 2)
+ self._add_foreign_input(psbt, derivation_path=foreign_input_derivation_path, annotated=True)
+ repoint_change(psbt, self._sibling_path(fixture_input_derivation_path, branch=1, address_index=beyond_window))
+
+ psbt_parser = self._parse(psbt)
+
+ assert psbt_parser.change_data[0]["address_index_beyond_window"] is True
+
+
+ def test__parse__a_foreign_input_cannot_anchor_change_to_an_unspent_base_path(self):
+ """
+ Change may only come back to a base path that one of our own inputs spends from.
+ Another party's input is in THEIR wallet and carries their own fingerprint,
+ however its path is shaped.
+
+ A coinjoin participant's input lists a derivation path that starts with
+ m/84h/1h/7h, which is one of our unused accounts. The psbt points our change into
+ that same account. The parse should refuse the change with
+ PSBTChangeDerivationPathError.
+ """
+ unrecognized_account = "m/84h/1h/7h"
+
+ psbt = self._psbt_with_change()
+ self._add_foreign_input(psbt, derivation_path=f"{unrecognized_account}/0/0", annotated=True)
+ repoint_change(psbt, f"{unrecognized_account}/1/0")
+
+ with pytest.raises(PSBTChangeDerivationPathError):
+ self._parse(psbt)Why this scored 80/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.