Check change derivation paths against the inputs
What changed, and why it matters
This commit adds a safety check to SeedSigner that refuses to sign a Bitcoin transaction if the change output is being sent to a derivation path the user's wallet is unlikely to scan. Before this change, an attacker could trick a user into signing a transaction where the coins technically still belong to the user but are sent to an unusual path (for example, a different account, a non-standard branch, or a hardened address index), making them effectively lost or hard to recover. The update also warns the user if the change address index is unusually far ahead of the addresses being spent from. The commit includes new error screens, warnings, and extensive tests.
Review the new derivation-path rules for compatibility with your wallet's change and self-transfer patterns. Ensure the CHANGE_ADDRESS_INDEX_WINDOW of 10,000 is sufficient for active wallets, and consider whether the TODO about honest transfers to another owned wallet should be addressed in a follow-up. Run the new test suite to confirm no regressions in payjoin, coinjoin, or multisig flows.
Security signals we found
New attack-level exception PSBTChangeDerivationPathError for change sent to an unscanned derivation path
New warning WARNING__CHANGE_ADDRESS_INDEX_BEYOND_WINDOW for change address indices far past spent indices
New UI screen PSBTUnexpectedChangeDerivationPathView with DireWarningScreen and forced discard
Change details screen now marks distant address indices with a warning icon
Extensive new unit and flow tests covering single-sig, multisig, payjoin, coinjoin, and edge cases
Evidence from the diff
The patch introduces PSBTChangeDerivationPathError and a new _evaluate_change_derivation_paths() step in PSBTParser.parse(). After inputs and outputs are parsed, every output that pays the seed’s key is checked against the base path of a verified input: the path must be long enough, use only the receive (0) or change (1) branch, and use a non-hardened address index. Violations raise an attack-level exception and route to a new DireWarningScreen. Outputs with an address index more than CHANGE_ADDRESS_INDEX_WINDOW (10,000) past the largest matching input index are flagged (address_index_beyond_window) and shown as a warning, but signing can continue. The same rules apply to multisig outputs counted as spends due to cosigner mismatch. Held findings are now split into input and output groups so change evaluation runs before held output findings are raised.
Changed components
src/seedsigner/models/psbt_parser.pysrc/seedsigner/views/psbt_views.pysrc/seedsigner/gui/screens/psbt_screens.pytests/test_psbt_parser.pytests/test_flows_psbt.pytests/psbt_testing_util.pytests/screenshot_generator/generator.pyInspect captured patch +1285 / −50
### 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
@@ -214,6 +214,29 @@ class PSBTUnsupportedScriptPathError(PSBTVerificationError):
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
+
+
class PSBTSeedCannotSignError(PSBTVerificationError):
"""
The selected seed holds no key that could sign any input.
@@ -287,9 +310,14 @@ 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
+ # largest 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):
@@ -324,11 +352,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:
@@ -408,6 +442,12 @@ 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: rejects the psbt unless 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.
+
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
@@ -467,10 +507,17 @@ 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()
+
+ 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()
@@ -483,6 +530,11 @@ def parse(self):
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
@@ -615,7 +667,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
@@ -684,7 +736,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)
@@ -818,7 +870,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)
@@ -886,6 +938,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 = []
@@ -1086,6 +1139,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
@@ -1123,6 +1181,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
@@ -1746,7 +1805,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
@@ -1755,6 +1814,155 @@ def _reject_if_seed_cannot_sign(self):
raise PSBTSeedCannotSignError()
+ 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 verified_derivation_path.derivation[:-2] == 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 the base path that this transaction spends from.
+ * Note: certain scenarios can spend inputs with different base paths. All of
+ those inputs' base paths are considered valid, provided that we own 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 = change_derivation_path[:-2]
+ 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 largest non-hardened address index among the
+ inputs that match the output's base path.
+
+ Expects a path that already passed the change path rules.
+ """
+ base_path = change_derivation_path[:-2]
+ address_index = change_derivation_path[-1]
+
+ largest_input_address_index = 0
+ 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 input_address_index > largest_input_address_index:
+ largest_input_address_index = input_address_index
+
+ return address_index <= largest_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 a key of ours
+ 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)
+
+
@staticmethod
def is_change_branch(derivation_path: List[int]) -> bool:
"""
### src/seedsigner/views/psbt_views.py
@@ -2,14 +2,14 @@
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)
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)
@@ -173,6 +173,14 @@ 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 PSBTSeedCannotSignError:
# Not a suspicious psbt, just the wrong seed for it. Send the user back to
# pick another rather than clearing the flow.
@@ -209,6 +217,7 @@ def run(self):
'amount': 397621401,
'verified_derivation_path':
[2147483696, 2147483649, 2147483648, 2147483650, 1, 0],
+ 'address_index_beyond_window': False,
}, {},
]
"""
@@ -276,6 +285,20 @@ def run(self):
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}")
@@ -421,13 +444,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:
@@ -481,6 +503,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,6 +923,44 @@ 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 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=="
@@ -274,6 +277,77 @@ def set_input_locking_script(inp: InputScope, script_pubkey: Script):
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,11 +281,21 @@ 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]):
+ with patch.object(controller.psbt_parser, "warnings", [PSBTParser.WARNING__HIGH_FEE, PSBTParser.WARNING__NO_CHANGE, PSBTParser.WARNING__CHANGE_ADDRESS_INDEX_BEYOND_WINDOW]):
yield
@@ -448,11 +458,13 @@ def mock_version_to_most_recent_release():
ScreenshotConfig(psbt_views.PSBTOverviewView, mock_context_manager=mock_multisig_psbt_loaded),
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),
@@ -468,6 +480,7 @@ 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.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
@@ -6,10 +6,10 @@
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, PSBTParser
from seedsigner.models.seed import Seed
@@ -233,10 +233,11 @@ def _psbt_with_change(self):
class TestPSBTOwnershipClaimRouting(PSBTSigningFlowTest):
"""
- 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.
+ 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):
@@ -550,6 +551,28 @@ 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_wrong_seed_routes_back_to_seed_selection_flow(self):
"""
The wrong seed for a psbt redirects before any transaction detail is rendered and
@@ -599,6 +622,86 @@ class TestPSBTWarningRouting(PSBTSigningFlowTest):
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
### tests/test_psbt_parser.py
@@ -12,21 +12,21 @@
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)
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 +705,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 +865,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 +1204,43 @@ 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 _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 +1253,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 +1577,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 +1596,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 of ours, 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
@@ -3514,3 +3618,634 @@ 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):
+ """
+ Where change is allowed to 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 _add_own_input(self, psbt: PSBT, derivation_path: str):
+ """
+ Adds a second input owned by this seed, at derivation_path.
+
+ Built by copying the first input and repointing it to a p2wpkh at that path.
+ """
+ public_key = self._root().derive(derivation_path).get_public_key()
+ own_input = deepcopy(psbt.inputs[0])
+ own_input.bip32_derivations.clear()
+ set_input_locking_script(own_input, script.p2wpkh(public_key))
+
+ claim_seed_owns_key(own_input, derivation_path, public_key)
+ psbt.inputs.append(own_input)
+
+
+ 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 the input's base path with its last level
+ changed to 7h. The parse should refuse the change with
+ PSBTChangeDerivationPathError, naming the change's path.
+ """
+ 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)
+
+
+ def test__parse__accepts_change_to_any_base_path_this_transaction_spends_from(self):
+ """
+ Change may come back to the base path of any of our inputs.
+
+ The psbt spends from two of the seed's accounts, which have different base paths.
+ Change into either account should be accepted. Change into a third account should
+ be refused with PSBTChangeDerivationPathError.
+ """
+ # The fixture's input spends from the first account
+ fixture_input_derivation_path = self._input_derivation_path()
+ first_account = "/".join(fixture_input_derivation_path.split("/")[:-2])
+ second_account = "m/84h/1h/7h"
+ unrecognized_account = "m/84h/1h/3h"
+
+ psbt = self._psbt_with_change()
+ self._add_own_input(psbt, f"{second_account}/0/2")
+
+ # Both inputs are ours and both accounts are spent from
+ psbt_parser = self._parse(psbt)
+ assert self._verified_input_derivation_paths(psbt_parser) == [
+ bip32.parse_path(fixture_input_derivation_path),
+ bip32.parse_path(f"{second_account}/0/2"),
+ ]
+
+ repoint_change(psbt, f"{first_account}/1/0")
+ assert self._parse(psbt).change_amount == 10_000
+
+ repoint_change(psbt, f"{second_account}/1/0")
+ assert self._parse(psbt).change_amount == 10_000
+
+ # This unrecognized_account doesn't match the base path of any input, so it should
+ # be rejected.
+ repoint_change(psbt, f"{unrecognized_account}/1/0")
+ with pytest.raises(PSBTChangeDerivationPathError):
+ self._parse(psbt)
+
+
+ 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 a multisig output of ours 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_largest_input_index_for_the_base_path(self):
+ """
+ The change address index window is measured from the largest "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 = max(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 largest 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 coins of ours from one base path: the fixture's coin 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 coin, and a second coin of ours 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_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 coins of ours from different base paths: the fixture's coin at
+ m/84h/1h/0h/0/3 and a second at m/84h/1h/7h/0/50000. Change at m/84h/1h/0h/1/20000
+ is past the window of the m/84h/1h/0h wallet, so the parse should flag it, even
+ though the m/84h/1h/7h wallet's input is at a larger index.
+
+ However, if the change is instead sent to the m/84h/1h/7h wallet at the same
+ "address_index" (m/84h/1h/7h/1/20000), it is within that wallet's window, so the
+ parse should leave it unflagged.
+ """
+ # The fixture's coin, and a second coin of ours at a larger "address_index" in
+ # another wallet
+ fixture_input_derivation_path = self._input_derivation_path()
+ fixture_address_index = int(fixture_input_derivation_path.split("/")[-1])
+ other_wallet_input_derivation_path = "m/84h/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
+
+ psbt = self._psbt_with_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/84h/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/84h/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 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 an unused account of ours. 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 81/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.