Check input claims against the committed script
What changed, and why it matters
This commit hardens SeedSigner's PSBT parsing so that the device no longer trusts a transaction's claim that one of your keys controls an input. Before this change, a malicious or buggy wallet coordinator could attach one of your real public keys to an input that actually belongs to someone else, making the device think it was signing its own money when it was not. The fix rebuilds each input's spending script from the claimed key and compares it to the script the input commits to on the blockchain. If they do not match, the device now stops with a 'Likely an Attack!' warning instead of continuing. It also adds handling for newer Taproot script-path spends that SeedSigner does not yet support.
Treat this as a security hardening fix and include it in the next release. Users should upgrade to a version containing this commit before signing PSBTs from coordinators they do not fully trust. Wallet coordinators that construct PSBTs for SeedSigner should ensure all input bip32/taproot derivation claims correspond to keys actually present in the input's committed spending script, and should supply taproot_merkle_root when relevant.
Security signals we found
Fixes a trust boundary violation where key ownership was assumed from derivation alone
Adds explicit anti-spoofing check against committed scriptPubKey
Adds new attack-class exception: PSBTInputOwnershipContradictionError
Adds unsupported-feature exception for taproot script-path spends: PSBTUnsupportedScriptPathError
UI routes to DireWarningScreen for ownership contradiction
Extensive adversarial test cases added for planted true claims, decoy multisig claims, and taproot edge cases
Evidence from the diff
The patch adds input-script verification to PSBT parsing. Previously, _parse_inputs only re-derived keys to prove the seed owned them; now it also checks that each claimed key is actually used by the input’s committed scriptPubKey. A new _input_spends_with_key helper rebuilds the expected script for single-sig (p2pkh, p2wpkh, p2sh-p2wpkh), multisig (p2wsh, p2sh-p2wsh, p2sh), and taproot key-path spends, comparing against the input’s script_pubkey. Taproot uses the supplied merkle root (or empty) to tweak the internal key the same way embit signs. If a claimed key is not in the committed script, the parser raises PSBTInputOwnershipContradictionError and the UI shows a DireWarningScreen. If the seed could sign only via a taproot script-path leaf, it raises PSBTUnsupportedScriptPathError. Tests cover planted true claims on foreign inputs, decoy entries on multisig inputs, dual-cosigner slots, key-path taproot with and without merkle roots, and script-path-only inputs.
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 +540 / −22
### src/seedsigner/models/psbt_parser.py
@@ -109,6 +109,17 @@ class PSBTOutputOwnershipContradictionError(PSBTVerificationError):
pass
+class PSBTInputOwnershipContradictionError(PSBTVerificationError):
+ """
+ The psbt's account of which keys control an input contradicts the script that input
+ commits to. It claims one of this seed's keys on the input. Our seed really does
+ derive that key, but the committed script does not use it.
+
+ We treat this deception as an attack.
+ """
+ pass
+
+
class PSBTInputAmountVerificationError(PSBTVerificationError):
"""
An input's declared amount is unproven or false, so the fee displayed cannot be trusted.
@@ -179,6 +190,16 @@ class PSBTExtraneousInputScriptError(PSBTVerificationError):
pass
+class PSBTUnsupportedScriptPathError(PSBTVerificationError):
+ """
+ This seed can sign an input only through a taproot script path spend, because the
+ keys of ours that the input claims are keys in its script tree leaves.
+
+ Script path spends are not yet supported.
+ """
+ pass
+
+
class PSBTSeedCannotSignError(PSBTVerificationError):
"""
The selected seed holds no key that could sign any input.
@@ -276,8 +297,10 @@ def __init__(self, p: PSBT, seed: Seed, network: str = SettingsConstants.MAINNET
# Contains one entry per input in psbt.inputs and per output in psbt.outputs. Each
# entry lists every derivation path the seed genuinely owns there, in the order
- # the psbt lists them. An input or output that does not claim any of our keys
- # gets an empty list, as does an input carrying a held finding (see parse()).
+ # the psbt lists them. On an input, the key at each listed path is also one the
+ # input's committed script spends with. An input or output that does not claim
+ # any of our keys gets an empty list, as does an input carrying a held finding
+ # (see parse()).
self.verified_input_derivation_paths: List[List[DerivationPath]] = []
self.verified_output_derivation_paths: List[List[DerivationPath]] = []
@@ -334,9 +357,10 @@ def parse(self):
script it commits to and no others.
4. _parse_inputs: determines which inputs this seed can sign, and the wallet
- policy. An input's claims on this seed are verified. Every input must resolve
- to the same policy otherwise a RuntimeError is raised (TODO: replace the
- RuntimeError with a PSBTVerificationError subclass so the View can
+ policy. An input's claims on this seed are verified. Each verified claim must
+ also be a key that the input's committed script uses. Every input must
+ resolve to the same policy otherwise a RuntimeError is raised (TODO: replace
+ the RuntimeError with a PSBTVerificationError subclass so the View can
deliberately catch this scenario and route accordingly).
A policy is one of:
@@ -374,6 +398,7 @@ def parse(self):
* a false claim on an input.
* an input or output with entries in both derivation path maps.
* an output claiming more derivation path entries than it can use.
+ * an input that this seed can sign only through a taproot script path spend.
Optimization via child_key_derivation_cache:
Parsing traverses a derivation path down to an individual address one level at a
@@ -538,6 +563,14 @@ def _parse_inputs(self, child_key_derivation_cache: dict):
Verifies each input's claims on this seed and determines the wallet policy.
Perceived attacks are raised immediately. Milder errors are held (see parse()).
Every input must resolve to the same policy, otherwise a RuntimeError is raised.
+
+ First we re-derive each key the input claims for our seed, which confirms that the
+ key is ours. But the script an input commits to is what decides who can spend it;
+ the coordinator could attach our key to an input that someone else owns. So we
+ then confirm that the committed script does indeed use our key.
+
+ We need to be certain which inputs are ours because they determine what a valid
+ change output should look like.
"""
self.num_inputs = len(self.psbt.inputs)
self.verified_input_derivation_paths = []
@@ -564,7 +597,62 @@ def _parse_inputs(self, child_key_derivation_cache: dict):
# which is allowed by BIP-174 and BIP-78.
raise RuntimeError("Mixed inputs in the transaction")
- self.verified_input_derivation_paths.append(verified_derivation_paths)
+ # Now check each verified claim against the input's committed script. We read
+ # the entries from the input's own maps so that each taproot entry's leaf
+ # hashes come with it.
+ script_committed_derivation_paths = []
+ has_leaf_key_claim = False
+
+ for public_key, derivation_path_obj in inp.bip32_derivations.items():
+ if derivation_path_obj not in verified_derivation_paths:
+ # We check only the claims on our seed that verified above
+ continue
+
+ seed_public_key = PSBTParser._derive_with_cache_via_derivation_path(self.root, derivation_path_obj, child_key_derivation_cache).get_public_key()
+ if not PSBTParser._input_spends_with_key(inp, inp_policy, script_pubkey, seed_public_key):
+ # The psbt said this input is controlled by our key at that path, but
+ # the input's committed script does not use that key. We treat this
+ # deception as an attack.
+ raise PSBTInputOwnershipContradictionError(f"Input claims this seed at {bip32.path_to_str(derivation_path_obj.derivation)} but its committed script does not use that key")
+
+ script_committed_derivation_paths.append(derivation_path_obj)
+
+ for public_key, (leaf_hashes, derivation_path_obj) in inp.taproot_bip32_derivations.items():
+ if derivation_path_obj not in verified_derivation_paths:
+ # We check only the claims on our seed that verified above
+ continue
+
+ seed_public_key = PSBTParser._derive_with_cache_via_derivation_path(self.root, derivation_path_obj, child_key_derivation_cache).get_public_key()
+ if PSBTParser._input_spends_with_key(inp, inp_policy, script_pubkey, seed_public_key):
+ script_committed_derivation_paths.append(derivation_path_obj)
+
+ elif leaf_hashes:
+ # This entry lists the script tree leaves its key appears in. Signing
+ # with a key in a leaf takes a script path spend, which we do not
+ # support yet, so this entry is dropped.
+ has_leaf_key_claim = True
+
+ elif inp_policy["type"] == "p2tr" and inp.taproot_merkle_root is None:
+ # The psbt claims our key as this input's internal key. The input may
+ # commit to that key tweaked by a script tree, but the psbt did not
+ # supply the tree's merkle root, so we cannot rebuild the tweak. An
+ # omitted optional field is not a contradiction, so this entry is
+ # dropped.
+ pass
+
+ else:
+ # The psbt said this input is controlled by our key at that path, but
+ # the input's committed script does not use that key. We treat this
+ # deception as an attack.
+ raise PSBTInputOwnershipContradictionError(f"Input claims this seed at {bip32.path_to_str(derivation_path_obj.derivation)} but its committed script does not use that key")
+
+ if script_committed_derivation_paths == [] and has_leaf_key_claim:
+ # 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 (see parse()).
+ self.held_findings.append(PSBTUnsupportedScriptPathError("Input can only be signed through a taproot script path spend"))
+
+ self.verified_input_derivation_paths.append(script_committed_derivation_paths)
@staticmethod
@@ -649,6 +737,49 @@ def _verify_input_scripts(inp: InputScope, script_pubkey: script.Script):
raise PSBTExtraneousInputScriptError("Input supplied a witness script its scriptPubKey does not commit to")
+ @staticmethod
+ def _input_spends_with_key(inp: InputScope, inp_policy: dict, script_pubkey: script.Script, public_key: PublicKey) -> bool:
+ """
+ Answers whether public_key is one of the keys that the input actually spends
+ with.
+
+ Single sig: rebuild the scriptPubKey from the key and compare it to the input's
+ committed scriptPubKey.
+
+ Taproot: a key path spend uses the internal key tweaked by the input's merkle root
+ (an empty one when the psbt supplies none). That is the same tweak embit signs
+ with, so we rebuild the scriptPubKey from the key tweaked that way. A key in a
+ script tree leaf rebuilds some other scriptPubKey, so it gets False here.
+
+ Multisig: look for the key among the pubkeys in the supplied script.
+ _verify_input_scripts has already tied that script to the scriptPubKey, directly
+ for p2wsh and legacy p2sh, and through the redeem script for nested segwit. So its
+ pubkeys are the ones the input really spends with.
+ """
+ policy_type = inp_policy["type"]
+
+ if policy_type == "p2tr":
+ tweaked_public_key = public_key.taproot_tweak(inp.taproot_merkle_root or b"")
+ OP_1 = b"\x51" # segwit version byte
+ OP_PUSHBYTES_32 = b"\x20"
+ return OP_1 + OP_PUSHBYTES_32 + tweaked_public_key.xonly() == script_pubkey.data
+
+ if policy_type in ("p2pkh", "p2sh-p2wpkh", "p2wpkh"):
+ return PSBTParser._build_singlesig_script(policy_type, public_key).data == script_pubkey.data
+
+ if policy_type in ("p2wsh", "p2sh-p2wsh"):
+ multisig_script = inp.witness_script
+ elif policy_type == "p2sh":
+ multisig_script = inp.redeem_script
+ else:
+ # Safety catch-all: any new script types will need explicit handling
+ # above. Note that embit reports unrecognized script types as `None`,
+ # which is also caught here.
+ raise RuntimeError(f"Unsupported policy type: {policy_type}")
+
+ return PSBTParser._multisig_script_contains_key(multisig_script, public_key)
+
+
def _hold_output_finding(self, output_index: int, finding: PSBTVerificationError):
"""
Holds a finding on an output until the outputs have been read (see parse()), and
@@ -1543,16 +1674,12 @@ def _reject_if_seed_cannot_sign(self):
(embit's sign_with is marginally more permissive: it also signs an input whose
script names the master key directly, with no derivation. That runs against how HD
wallets are built. The master key is a derivation root, not a spending key, so no
- standard wallet produces such a psbt. We deliberately ignore this case.
-
- Similarly, it's not worth the effort to verify that each key is included in its
- input's script. A psbt that excludes a key in that way would be nonsensical but
- harmless: the excluded key cannot spend the input, so nothing of this seed's is
- at risk.)
+ standard wallet produces such a psbt. We deliberately ignore this case.)
"""
# An input claims a key at a derivation path. _parse_inputs proved that the seed
- # derives that key (single-sig: one such key; multisig: one per cosigner, ours
- # among them). One verified input path is enough for the psbt to be signable.
+ # derives that key and that the input's committed script uses it (single-sig: one
+ # such key; multisig: one per cosigner, ours among them). One verified input path
+ # is enough for the psbt to be signable.
for verified_derivation_paths in self.verified_input_derivation_paths:
if len(verified_derivation_paths) > 0:
return
### src/seedsigner/views/psbt_views.py
@@ -4,11 +4,11 @@
from seedsigner.models.psbt_parser import (PSBTExtraneousInputScriptError,
PSBTInputAmountVerificationError, PSBTInputOwnershipClaimError,
- PSBTInputScriptMismatchError, PSBTMalformedOpReturnError,
- PSBTMissingInputScriptError, PSBTMissingInputUtxoError,
+ PSBTInputOwnershipContradictionError, PSBTInputScriptMismatchError,
+ PSBTMalformedOpReturnError, PSBTMissingInputScriptError, PSBTMissingInputUtxoError,
PSBTMixedDerivationPathTypesError, PSBTNegativeFeeError, PSBTOutputOwnershipClaimError,
PSBTOutputOwnershipContradictionError, PSBTParser, PSBTSeedCannotSignError,
- PSBTSurplusDerivationPathsError)
+ PSBTSurplusDerivationPathsError, 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)
@@ -150,6 +150,14 @@ def __init__(self):
self.set_redirect(Destination(PSBTOutputOwnershipContradictionView, clear_history=True))
return
+ except PSBTInputOwnershipContradictionError:
+ self.set_redirect(Destination(PSBTInputOwnershipContradictionView, clear_history=True))
+ return
+
+ except PSBTUnsupportedScriptPathError:
+ self.set_redirect(Destination(PSBTUnsupportedScriptPathView, clear_history=True))
+ return
+
except PSBTNegativeFeeError:
self.set_redirect(Destination(PSBTNegativeFeeView, clear_history=True))
return
@@ -718,6 +726,34 @@ def run(self):
+class PSBTInputOwnershipContradictionView(View):
+ """
+ Reached when the psbt claims one of this seed's keys on an input whose committed
+ script does not use that key (see PSBTInputOwnershipContradictionError).
+
+ We view this as an attack. We do not allow the user to continue and give this the
+ "Dire Warning" level.
+ """
+ DISCARD = ButtonOption("Discard transaction")
+
+ def run(self):
+ self.run_screen(
+ DireWarningScreen,
+ title=_("Suspicious Transaction"),
+ status_headline=_("Likely an Attack!"),
+ # TRANSLATOR_NOTE: The transaction/psbt contains a deception that we consider an attack.
+ text=_("This transaction misrepresents which keys own an input."),
+ 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 PSBTNegativeFeeView(View):
"""
Reached when a psbt's outputs spend more than its inputs bring in (see
@@ -828,6 +864,33 @@ def run(self):
+class PSBTUnsupportedScriptPathView(View):
+ """
+ Reached when this seed can sign an input only through a taproot script path spend
+ (see PSBTUnsupportedScriptPathError).
+
+ Script path spends are not yet supported, so this seed cannot sign the input. 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=_("Not Yet Implemented"),
+ status_headline=None,
+ text=_("This transaction needs a taproot script path signature."),
+ 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
@@ -455,9 +455,11 @@ def mock_version_to_most_recent_release():
ScreenshotConfig(psbt_views.PSBTMixedDerivationPathTypesView),
ScreenshotConfig(psbt_views.PSBTMalformedOpReturnView),
ScreenshotConfig(psbt_views.PSBTOutputOwnershipContradictionView),
+ ScreenshotConfig(psbt_views.PSBTInputOwnershipContradictionView),
ScreenshotConfig(psbt_views.PSBTMissingInputScriptView),
ScreenshotConfig(psbt_views.PSBTInputScriptMismatchView),
ScreenshotConfig(psbt_views.PSBTExtraneousInputScriptView),
+ ScreenshotConfig(psbt_views.PSBTUnsupportedScriptPathView),
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
@@ -4,8 +4,9 @@
from embit.psbt import PSBT, DerivationPath
from base import FlowTest, FlowStep
-from psbt_testing_util import (PSBTTestData, claim_seed_owns_key, create_op_return_output,
- create_output, foreign_public_key, root_for_seed)
+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, tapleaf_hash)
from seedsigner.controller import Controller
from seedsigner.views.view import MainMenuView
@@ -467,6 +468,65 @@ def test_extraneous_input_script_terminates_signing_flow(self):
])
+ def test_input_ownership_contradiction_terminates_signing_flow(self):
+ """
+ The psbt adds a second claim of ours to the user's own input, at a path whose key
+ the input's script does not use. That is framed as an attack.
+
+ The flow should stop at PSBTInputOwnershipContradictionView, before any
+ transaction detail is rendered.
+ """
+ decoy_derivation_path = "m/84h/1h/0h/0/9"
+ decoy_public_key = root_for_seed(PSBTTestData.seed).derive(decoy_derivation_path).get_public_key()
+
+ psbt = self._psbt_with_change()
+ claim_seed_owns_key(psbt.inputs[0], decoy_derivation_path, decoy_public_key)
+
+ 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.PSBTInputOwnershipContradictionView, button_data_selection=psbt_views.PSBTInputOwnershipContradictionView.DISCARD),
+ FlowStep(MainMenuView),
+ ])
+
+
+ def test_unsupported_script_path_terminates_signing_flow(self):
+ """
+ The psbt's only input has our key in its taproot script tree's one leaf, behind
+ an unspendable internal key. This seed can sign it only through a script path
+ spend, which is not yet supported.
+
+ The flow should stop at PSBTUnsupportedScriptPathView, before any transaction
+ detail is rendered.
+ """
+ leaf_derivation_path = "m/86h/1h/0h/0/0"
+ leaf_public_key = root_for_seed(PSBTTestData.seed).derive(leaf_derivation_path).get_public_key()
+ merkle_root = tapleaf_hash(leaf_public_key)
+
+ psbt = PSBT.parse(a2b_base64(PSBTTestData.SINGLE_SIG_TAPROOT_1_INPUT))
+ psbt.outputs.append(create_output(PSBTTestData.SINGLE_SIG_TAPROOT_CHANGE, 10_000))
+
+ inp = psbt.inputs[0]
+ inp.witness_utxo.script_pubkey = p2tr_with_script_tree(NUMS_INTERNAL_KEY, merkle_root)
+ # Drop the non_witness_utxo, which describes the original coin and contradicts
+ # the witness_utxo altered above.
+ inp.non_witness_utxo = None
+ inp.taproot_merkle_root = merkle_root
+ inp.taproot_bip32_derivations.clear()
+ claim_seed_owns_key(inp, leaf_derivation_path, leaf_public_key, is_taproot=True, leaf_hashes=[merkle_root])
+
+ 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.PSBTUnsupportedScriptPathView, button_data_selection=psbt_views.PSBTUnsupportedScriptPathView.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
@@ -14,11 +14,11 @@
from seedsigner.models.psbt_parser import (OPCODES, PSBTExtraneousInputScriptError,
PSBTInputAmountVerificationError, PSBTInputOwnershipClaimError,
- PSBTInputScriptMismatchError, PSBTMalformedOpReturnError,
- PSBTMissingInputScriptError, PSBTMissingInputUtxoError,
+ PSBTInputOwnershipContradictionError, PSBTInputScriptMismatchError,
+ PSBTMalformedOpReturnError, PSBTMissingInputScriptError, PSBTMissingInputUtxoError,
PSBTMixedDerivationPathTypesError, PSBTNegativeFeeError, PSBTOutputOwnershipClaimError,
PSBTOutputOwnershipContradictionError, PSBTParser, PSBTSeedCannotSignError,
- PSBTSurplusDerivationPathsError)
+ PSBTSurplusDerivationPathsError, PSBTUnsupportedScriptPathError)
from seedsigner.models.seed import Seed
from seedsigner.models.settings_definition import SettingsConstants
@@ -1415,6 +1415,7 @@ def test__parse__held_findings_wait_for_an_output_contradiction(self):
PSBTOutputOwnershipContradictionError:
* p2wpkh input: a throwaway false claim
* p2wpkh input: entries in both derivation path maps
+ * p2tr input: our only key in a script tree leaf
* p2wpkh output: entries in both derivation path maps
* p2wpkh output: more derivation path entries than it can use
* p2tr output: more than one internal key claim
@@ -1464,6 +1465,22 @@ def claim_a_stranger_on_the_change(psbt: PSBT):
with pytest.raises(PSBTOutputOwnershipContradictionError):
self._parse(psbt)
+ # p2tr input: our only key in a script tree leaf
+ leaf_derivation_path = "m/86h/1h/0h/0/0"
+ leaf_public_key = self._root().derive(leaf_derivation_path).get_public_key()
+ merkle_root = tapleaf_hash(leaf_public_key)
+ psbt = self._psbt_with_change(PSBTTestData.SINGLE_SIG_TAPROOT_1_INPUT, PSBTTestData.SINGLE_SIG_TAPROOT_CHANGE)
+ psbt.inputs[0].witness_utxo.script_pubkey = p2tr_with_script_tree(NUMS_INTERNAL_KEY, merkle_root)
+ # Drop the non_witness_utxo, which describes the original coin and contradicts
+ # the witness_utxo altered above.
+ psbt.inputs[0].non_witness_utxo = None
+ psbt.inputs[0].taproot_merkle_root = merkle_root
+ psbt.inputs[0].taproot_bip32_derivations.clear()
+ claim_seed_owns_key(psbt.inputs[0], leaf_derivation_path, leaf_public_key, is_taproot=True, leaf_hashes=[merkle_root])
+ claim_a_stranger_on_the_change(psbt)
+ with pytest.raises(PSBTOutputOwnershipContradictionError):
+ self._parse(psbt)
+
# p2wpkh output: entries in both derivation path maps
psbt = self._psbt_with_change()
other_output = create_output(PSBTTestData.SINGLE_SIG_NATIVE_SEGWIT_CHANGE, 10_000)
@@ -2779,6 +2796,9 @@ def test__parse__refuses_an_unsupported_script_type(self):
the output's policy shape would match the input's (`None` == `None`) and so the
parse would consider it as possible change. Rather than continue, we expect the
catch-all safety check to spot the unsupported script type and raise RuntimeError.
+
+ Both the input's script check and the output's rebuild carry that catch-all; the
+ input's is the one reached first.
"""
root = self._root()
@@ -3197,3 +3217,249 @@ def test__parse__checks_input_scripts_whoever_the_input_belongs_to(self):
foreign_input.redeem_script = script.p2wpkh(foreign_public_key("m/49h/1h/0h/0/1"))
with pytest.raises(PSBTInputScriptMismatchError):
self._parse(psbt)
+
+
+
+class TestPSBTParserInputOwnership(PSBTParserOwnershipTestBase):
+ """
+ A psbt annotates its inputs with claims about which keys control them. Our seed may
+ really derive a claimed key, but it's the script the input commits to that decides
+ which keys can spend it.
+
+ These tests cover claims of ours that the committed script does not use. They also
+ cover the taproot claims whose check needs the input's merkle root.
+ """
+ def test__parse__refuses_a_true_claim_planted_on_another_partys_input(self):
+ """
+ A coordinator that holds our account xpub can derive our keys itself. So it can
+ write a TRUE claim (our fingerprint along with a key our seed really derives) onto
+ another party's input, which our key has no part in.
+
+ The claim verifies, because it is true. But the input's committed script does not
+ use that key, so the parse should refuse the psbt with
+ PSBTInputOwnershipContradictionError.
+ """
+ planted_derivation_path = "m/84h/1h/7h/0/0"
+ planted_public_key = self._root().derive(planted_derivation_path).get_public_key()
+
+ psbt = self._psbt_with_change()
+
+ # Another party's input: a copy of ours, repointed at their key and carrying no
+ # derivation path entries
+ foreign_input = deepcopy(psbt.inputs[0])
+ foreign_input.bip32_derivations.clear()
+ foreign_input.witness_utxo.script_pubkey = script.p2wpkh(foreign_public_key())
+ # Drop the copied non_witness_utxo, which describes our own coin and contradicts
+ # the witness_utxo altered above.
+ foreign_input.non_witness_utxo = None
+ psbt.inputs.append(foreign_input)
+
+ # With no claim on it, the other party's input is simply not ours
+ psbt_parser = self._parse(psbt)
+ assert psbt_parser.verified_input_derivation_paths[1] == []
+
+ # Plant the true claim
+ claim_seed_owns_key(foreign_input, planted_derivation_path, planted_public_key)
+
+ with pytest.raises(PSBTInputOwnershipContradictionError):
+ self._parse(psbt)
+
+
+ def test__parse__refuses_a_decoy_entry_on_a_multisig_input(self):
+ """
+ The psbt adds a decoy entry to the user's own multisig input, along with the
+ seed's real cosigner entry. The decoy claims a key our seed does own, at a path
+ whose key the input's script has no use for.
+
+ The real entry is still in place, but the decoy is a claim the committed script
+ contradicts. So the parse should refuse the psbt with
+ PSBTInputOwnershipContradictionError.
+ """
+ decoy_derivation_path = "m/48h/1h/0h/2h/0/500"
+ decoy_public_key = self._root().derive(decoy_derivation_path).get_public_key()
+
+ psbt = self._psbt_with_change(PSBTTestData.MULTISIG_NATIVE_SEGWIT_1_INPUT, PSBTTestData.MULTISIG_NATIVE_SEGWIT_CHANGE)
+ claim_seed_owns_key(psbt.inputs[0], decoy_derivation_path, decoy_public_key)
+
+ with pytest.raises(PSBTInputOwnershipContradictionError):
+ self._parse(psbt)
+
+
+ def test__parse__keeps_both_keys_of_a_seed_holding_two_cosigner_slots(self):
+ """
+ A multisig can use one seed in two of its cosigner slots, each at its own
+ derivation path. It is a poor wallet, since that seed can spend alone, but it is
+ a valid one.
+
+ The user's 2-of-3 input is rebuilt with this seed in two slots plus one
+ stranger's key. Both of our keys are in the input's committed script, so the
+ parse should keep both derivation paths.
+ """
+ slot_a_derivation_path = "m/48h/1h/0h/2h/0/0"
+ slot_b_derivation_path = "m/48h/1h/1h/2h/0/0"
+
+ psbt = self._psbt_with_change(PSBTTestData.MULTISIG_NATIVE_SEGWIT_1_INPUT, PSBTTestData.MULTISIG_NATIVE_SEGWIT_CHANGE)
+ inp = psbt.inputs[0]
+ inp.bip32_derivations.clear()
+
+ # Our two keys, each claimed under our fingerprint
+ cosigner_public_keys = []
+ for derivation_path in (slot_a_derivation_path, slot_b_derivation_path):
+ public_key = self._root().derive(derivation_path).get_public_key()
+ cosigner_public_keys.append(public_key)
+ claim_seed_owns_key(inp, derivation_path, public_key)
+
+ # The stranger's key, claimed under their fingerprint
+ stranger_public_key = foreign_public_key("m/48h/1h/0h/2h/0/0")
+ cosigner_public_keys.append(stranger_public_key)
+ claim_seed_owns_key(inp, "m/48h/1h/0h/2h/0/0", stranger_public_key, seed=PSBTTestData.recipient_seed)
+
+ # Rebuild the input's script and the scriptPubKey that commits to it
+ inp.witness_script = script.multisig(2, cosigner_public_keys)
+ inp.witness_utxo.script_pubkey = script.p2wsh(inp.witness_script)
+ # Drop the non_witness_utxo, which describes the original coin and contradicts
+ # the witness_utxo altered above.
+ inp.non_witness_utxo = None
+
+ # embit signs with both of our keys
+ assert deepcopy(psbt).sign_with(self._root()) == 2
+
+ psbt_parser = self._parse(psbt)
+ assert [entry.derivation for entry in psbt_parser.verified_input_derivation_paths[0]] == [
+ bip32.parse_path(slot_a_derivation_path),
+ bip32.parse_path(slot_b_derivation_path),
+ ]
+
+
+ def test__parse__keeps_a_key_path_spend_from_an_address_built_over_a_script_tree(self):
+ """
+ A taproot address can commit to its internal key tweaked by a script tree's
+ merkle root and still be spent through the key path. The psbt supplies that
+ merkle root on the input, so the parse should rebuild the address from our
+ internal key and keep its derivation path.
+
+ BIP-371 also lets an input list the keys in its script tree leaves. With a key of
+ ours listed in the tree's leaf as well, the parse should still keep just the
+ internal key's derivation path.
+ """
+ internal_derivation_path = "m/86h/1h/0h/0/0"
+ internal_public_key = self._root().derive(internal_derivation_path).get_public_key()
+
+ # A script tree of one leaf, holding another of our keys. A one-leaf tree's
+ # merkle root is that leaf's hash.
+ leaf_derivation_path = "m/86h/1h/0h/0/1"
+ leaf_public_key = self._root().derive(leaf_derivation_path).get_public_key()
+ merkle_root = tapleaf_hash(leaf_public_key)
+
+ psbt = self._psbt_with_change(PSBTTestData.SINGLE_SIG_TAPROOT_1_INPUT, PSBTTestData.SINGLE_SIG_TAPROOT_CHANGE)
+ inp = psbt.inputs[0]
+ inp.witness_utxo.script_pubkey = p2tr_with_script_tree(internal_public_key, merkle_root)
+ # Drop the non_witness_utxo, which describes the original coin and contradicts
+ # the witness_utxo altered above.
+ inp.non_witness_utxo = None
+ inp.taproot_merkle_root = merkle_root
+
+ # embit signs this input through its key path
+ assert deepcopy(psbt).sign_with(self._root()) == 1
+
+ psbt_parser = self._parse(psbt)
+ assert [entry.derivation for entry in psbt_parser.verified_input_derivation_paths[0]] == [bip32.parse_path(internal_derivation_path)]
+
+ # List our key in the leaf as well
+ claim_seed_owns_key(inp, leaf_derivation_path, leaf_public_key, is_taproot=True, leaf_hashes=[merkle_root])
+
+ psbt_parser = self._parse(psbt)
+ assert [entry.derivation for entry in psbt_parser.verified_input_derivation_paths[0]] == [bip32.parse_path(internal_derivation_path)]
+
+
+ def test__parse__refuses_an_internal_key_claim_that_its_merkle_root_contradicts(self):
+ """
+ The input's address commits to our internal key with no script tree, but the psbt
+ supplies a merkle root for it anyway. Our key tweaked by that merkle root is not
+ the key the input commits to. The psbt has supplied everything that check needs,
+ so the parse should refuse the psbt with PSBTInputOwnershipContradictionError.
+ """
+ psbt = self._psbt_with_change(PSBTTestData.SINGLE_SIG_TAPROOT_1_INPUT, PSBTTestData.SINGLE_SIG_TAPROOT_CHANGE)
+ psbt.inputs[0].taproot_merkle_root = tapleaf_hash(foreign_public_key())
+
+ with pytest.raises(PSBTInputOwnershipContradictionError):
+ self._parse(psbt)
+
+
+ def test__parse__drops_an_internal_key_claim_when_the_merkle_root_is_left_out(self):
+ """
+ The input's address commits to our internal key tweaked by a script tree, but the
+ psbt leaves out the input's merkle root, which is an optional field. Without it we
+ cannot rebuild the address, so the claim is neither confirmed nor contradicted.
+
+ The parse should drop the claim and treat that input as not ours. With another
+ input of ours, the psbt should still parse.
+ """
+ internal_derivation_path = "m/86h/1h/0h/0/0"
+ internal_public_key = self._root().derive(internal_derivation_path).get_public_key()
+ merkle_root = tapleaf_hash(foreign_public_key())
+
+ psbt = self._psbt_with_change(PSBTTestData.SINGLE_SIG_TAPROOT_1_INPUT, PSBTTestData.SINGLE_SIG_TAPROOT_CHANGE)
+
+ # A second input: a copy of ours, at an address built over the script tree, with
+ # no merkle root supplied
+ script_tree_input = deepcopy(psbt.inputs[0])
+ script_tree_input.witness_utxo.script_pubkey = p2tr_with_script_tree(internal_public_key, merkle_root)
+ # Drop the copied non_witness_utxo, which describes our own coin and contradicts
+ # the witness_utxo altered above.
+ script_tree_input.non_witness_utxo = None
+ assert script_tree_input.taproot_merkle_root is None
+ psbt.inputs.append(script_tree_input)
+
+ psbt_parser = self._parse(psbt)
+ assert [entry.derivation for entry in psbt_parser.verified_input_derivation_paths[0]] == [bip32.parse_path(internal_derivation_path)]
+ assert psbt_parser.verified_input_derivation_paths[1] == []
+
+
+ def test__parse__refuses_a_taproot_map_claim_on_a_non_taproot_input(self):
+ """
+ The psbt claims one of our keys in the taproot map of the user's own p2wpkh
+ input, at a path whose key the input's script does not use. Only a taproot
+ input commits to a key tweaked by a merkle root, so a missing merkle root
+ explains nothing here. The parse should refuse the psbt with
+ PSBTInputOwnershipContradictionError, as it would the same claim in the
+ non-taproot map.
+ """
+ claimed_derivation_path = "m/86h/1h/0h/0/9"
+ claimed_public_key = self._root().derive(claimed_derivation_path).get_public_key()
+
+ # Our claim is the input's only entry, written into the taproot map
+ psbt = self._psbt_with_change()
+ psbt.inputs[0].bip32_derivations.clear()
+ claim_seed_owns_key(psbt.inputs[0], claimed_derivation_path, claimed_public_key, is_taproot=True)
+ assert psbt.inputs[0].taproot_merkle_root is None
+
+ with pytest.raises(PSBTInputOwnershipContradictionError):
+ self._parse(psbt)
+
+
+ def test__parse__refuses_an_input_this_seed_can_sign_only_through_a_script_path(self):
+ """
+ The input's address is built for script path spends only. Its internal key is the
+ provably unspendable NUMS point. Our key is in its script tree's one leaf.
+ Script path spends are not yet supported, so the parse should refuse the psbt with
+ PSBTUnsupportedScriptPathError.
+ """
+ leaf_derivation_path = "m/86h/1h/0h/0/0"
+ leaf_public_key = self._root().derive(leaf_derivation_path).get_public_key()
+ merkle_root = tapleaf_hash(leaf_public_key)
+
+ psbt = self._psbt_with_change(PSBTTestData.SINGLE_SIG_TAPROOT_1_INPUT, PSBTTestData.SINGLE_SIG_TAPROOT_CHANGE)
+ inp = psbt.inputs[0]
+ inp.witness_utxo.script_pubkey = p2tr_with_script_tree(NUMS_INTERNAL_KEY, merkle_root)
+ # Drop the non_witness_utxo, which describes the original coin and contradicts
+ # the witness_utxo altered above.
+ inp.non_witness_utxo = None
+ inp.taproot_merkle_root = merkle_root
+
+ # Our key is now claimed only as the key in the leaf
+ inp.taproot_bip32_derivations.clear()
+ claim_seed_owns_key(inp, leaf_derivation_path, leaf_public_key, is_taproot=True, leaf_hashes=[merkle_root])
+
+ with pytest.raises(PSBTUnsupportedScriptPathError):
+ self._parse(psbt)Why this scored 78/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.