Refuse mixed base paths on single sig segwit v0
What changed, and why it matters
This commit fixes a security flaw in SeedSigner, a small hardware wallet used to sign Bitcoin transactions. The bug could let a malicious transaction coordinator trick the device into accepting change money sent to a wallet path the user never monitors, potentially making funds appear lost. The fix refuses to sign certain single-signature SegWit v0 transactions when inputs come from different wallet paths and the full previous transaction data is missing. The commit message and code clearly describe the attack and the fix.
Treat this as a security fix. Review the new _evaluate_input_base_paths logic for completeness, ensure the UI correctly prevents signing in all code paths, and verify that the test coverage includes edge cases such as collaborative spends with foreign inputs and PSBTs where only some inputs provide non_witness_utxo.
Security signals we found
New security check explicitly described as preventing a malicious coordinator from anchoring change to an unmonitored derivation path
New exception class PSBTUnverifiableMixedInputBasePathsError with Warning-grade refusal
UI flow now redirects to a blocking warning screen instead of allowing signing
Tests added for both the refusal case and the allowed case with non_witness_utxo
Existing tests that spent from two base paths on p2wpkh were moved to taproot/legacy/multisig script types
Centralized base-path extraction into _get_base_path() to prevent inconsistent slicing
Evidence from the diff
The patch adds a new verification step, _evaluate_input_base_paths(), in PSBTParser. For single-sig SegWit v0 (p2wpkh and p2sh-p2wpkh) PSBTs, it now requires every input this seed signs to share the same base derivation path unless each input also provides a non_witness_utxo. The rationale is that SegWit v0 signatures commit only to their own input’s script and amount, so a coordinator can add its own UTXO but supply a fabricated witness_utxo claiming it belongs to one of the user’s keys. Because change validation trusts input base paths, that fake input could anchor change to an unmonitored derivation path. Taproot is exempt because signatures commit to all inputs; legacy inputs are exempt because they must supply non_witness_utxo; multisig is exempt because change is checked against the full cosigner set. A new exception, PSBTUnverifiableMixedInputBasePathsError, is raised as a Warning-grade refusal, and a corresponding UI view blocks the user from continuing. Tests are added and existing tests are adjusted to use non-vulnerable script types where mixed base paths are intended.
Changed components
src/seedsigner/models/psbt_parser.pysrc/seedsigner/views/psbt_views.pytests/test_psbt_parser.pytests/test_flows_psbt.pytests/screenshot_generator/generator.pyInspect captured patch +432 / −87
### src/seedsigner/models/psbt_parser.py
@@ -237,6 +237,21 @@ def __init__(self, derivation_path: List[int]):
self.derivation_path = derivation_path
+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
+
+
class PSBTSeedCannotSignError(PSBTVerificationError):
"""
The selected seed holds no key that could sign any input.
@@ -442,18 +457,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: 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.
+ 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
@@ -514,6 +533,8 @@ def parse(self):
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.
@@ -1814,14 +1835,27 @@ 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 verified_derivation_path.derivation[:-2] == base_path:
+ if PSBTParser._get_base_path(verified_derivation_path.derivation) == base_path:
matching_derivation_paths.append(verified_derivation_path)
return matching_derivation_paths
@@ -1842,9 +1876,9 @@ def _is_wallet_change_derivation_path(self, change_derivation_path: List[int]) -
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.
+ * 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".
@@ -1861,7 +1895,7 @@ def _is_wallet_change_derivation_path(self, change_derivation_path: List[int]) -
# Too short to hold both a branch and an address index
return False
- base_path = change_derivation_path[:-2]
+ base_path = PSBTParser._get_base_path(change_derivation_path)
branch = change_derivation_path[-2]
address_index = change_derivation_path[-1]
@@ -1894,7 +1928,7 @@ def _is_change_address_index_within_window(self, change_derivation_path: List[in
Expects a path that already passed the change path rules.
"""
- base_path = change_derivation_path[:-2]
+ base_path = PSBTParser._get_base_path(change_derivation_path)
address_index = change_derivation_path[-1]
smallest_input_address_index = None
@@ -1947,7 +1981,7 @@ def _evaluate_change_derivation_paths(self):
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
+ 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.
@@ -1974,6 +2008,101 @@ def _evaluate_change_derivation_paths(self):
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
@@ -9,7 +9,8 @@
PSBTMissingInputUtxoError, PSBTMixedDerivationPathTypesError, PSBTNegativeFeeError,
PSBTOutputOwnershipClaimError, PSBTOutputOwnershipContradictionError, PSBTParser,
PSBTSeedCannotSignError, PSBTSurplusDerivationPathsError,
- PSBTUnsupportedDerivationPathError, PSBTUnsupportedScriptPathError)
+ 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)
@@ -181,6 +182,10 @@ def __init__(self):
))
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.
@@ -961,6 +966,34 @@ def run(self):
+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/screenshot_generator/generator.py
@@ -481,6 +481,7 @@ def mock_version_to_most_recent_release():
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,4 +1,5 @@
from binascii import a2b_base64
+from copy import deepcopy
from embit import bip32, script
from embit.psbt import PSBT, DerivationPath
@@ -573,6 +574,35 @@ def test_unexpected_change_derivation_path_terminates_signing_flow(self):
])
+ 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
### tests/test_psbt_parser.py
@@ -19,7 +19,8 @@
PSBTMissingInputUtxoError, PSBTMixedDerivationPathTypesError, PSBTNegativeFeeError,
PSBTOutputOwnershipClaimError, PSBTOutputOwnershipContradictionError, PSBTParser,
PSBTSeedCannotSignError, PSBTSurplusDerivationPathsError,
- PSBTUnsupportedDerivationPathError, PSBTUnsupportedScriptPathError)
+ PSBTUnsupportedDerivationPathError, PSBTUnsupportedScriptPathError,
+ PSBTUnverifiableMixedInputBasePathsError)
from seedsigner.models.seed import Seed
from seedsigner.models.settings_definition import SettingsConstants
@@ -1241,6 +1242,86 @@ def _sibling_path(self, input_derivation_path: str, branch: int, address_index:
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)])
@@ -1625,7 +1706,7 @@ def test__parse__evaluates_change_before_reporting_a_held_output_finding(self):
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
+ path entry for our seed, a finding the parse holds. The parse should raise
PSBTChangeDerivationPathError rather than the held
PSBTSurplusDerivationPathsError.
"""
@@ -3623,7 +3704,7 @@ def test__parse__refuses_an_input_this_seed_can_sign_only_through_a_script_path(
class TestPSBTParserChangeDerivationPathRules(PSBTParserOwnershipTestBase):
"""
- Where change is allowed to come back to.
+ 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
@@ -3648,21 +3729,6 @@ class TestPSBTParserChangeDerivationPathRules(PSBTParserOwnershipTestBase):
] + 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
@@ -3733,43 +3799,6 @@ def test__parse__refuses_change_to_a_base_path_this_transaction_does_not_spend_f
assert exc_info.value.derivation_path == bip32.parse_path(change_at_extended_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
@@ -3880,8 +3909,8 @@ def test__parse__refuses_a_multisig_output_at_an_unscanned_path_with_or_without_
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:
+ 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"
@@ -4046,12 +4075,12 @@ def test__parse__leaves_hardened_input_indices_out_of_the_window(self):
"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
+ 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 coin, and a second coin of ours at a hardened "address_index" with
+ # 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])
@@ -4129,27 +4158,29 @@ def test__parse__measures_each_base_path_window_from_its_own_inputs(self):
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.
+ 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/84h/1h/7h wallet at the same
- "address_index" (m/84h/1h/7h/1/20000), it is within that wallet's window, so the
+ 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 coin, and a second coin of ours at a larger "address_index" in
+ # 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()
+ 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/84h/1h/7h/0/50000"
+ 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
- psbt = self._psbt_with_change()
+ # 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
@@ -4158,16 +4189,137 @@ def test__parse__measures_each_base_path_window_from_its_own_inputs(self):
bip32.parse_path(other_wallet_input_derivation_path),
]
- # Scenario 1: Change for the m/84h/1h/0h wallet
+ # 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/84h/1h/7h wallet
+ # 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.
@@ -4287,7 +4439,7 @@ def test__parse__a_foreign_input_cannot_anchor_change_to_an_unspent_base_path(se
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
+ 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.
"""Why this scored 69/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.